@calltelemetry/fmix 2.7.18 → 2.7.19

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 +1987 -225
  2. package/package.json +3 -3
package/bin/fmix CHANGED
@@ -3,8 +3,8 @@
3
3
  # See docs/designs/2026-07-30-fmix-session-cache-v2.md for the v2 contract.
4
4
  #
5
5
  # Usage:
6
- # ./fmix test [--worktree <path>] [--session <id>] [--isolate] [--cache-base <N.N.N-stable>] [--unit] -- <mix test args>
7
- # ./fmix coverage --worktree <path> [--session <id>] --base <git-ref> -- <test paths>
6
+ # ./fmix test [--worktree <path>] [--session <id>] [--isolate] [--cache-base <N.N.N-stable>] [--no-auto-setup] [--unit] -- <mix test args>
7
+ # ./fmix coverage --worktree <path> [--session <id>] [--no-auto-setup] --base <git-ref> -- <test paths>
8
8
  # ./fmix task [--worktree <path>] [--session <id>] [--database <name>] [--mix-env <env>] [--allow-run] -- <mix task> [args]
9
9
  # ./fmix format [--worktree <path>] [--session <id>] [--mix-env <env>] [--dot-formatter <path>] [--check] -- <files...>
10
10
  # ./fmix setup [--worktree <path>] [--session <id>] [--rebuild-db|--cold-db|--from-zero]
@@ -27,7 +27,7 @@ set -uo pipefail
27
27
  # ---------------------------------------------------------------------------
28
28
  # Constants & config
29
29
  # ---------------------------------------------------------------------------
30
- FMIX_VERSION="2.7.18"
30
+ FMIX_VERSION="2.7.19"
31
31
  FMIX_HOME="${FMIX_HOME:-${HOME}/.ct-fmix}"
32
32
  FMIX_OS="$(uname -s)"
33
33
  FMIX_ARCH="$(uname -m)"
@@ -96,6 +96,10 @@ FMIX_DEPENDENCY_ARTIFACT_TTL_DAYS="${FMIX_DEPENDENCY_ARTIFACT_TTL_DAYS-}"
96
96
  FMIX_DEPENDENCY_ARTIFACT_TTL_HOURS="${FMIX_DEPENDENCY_ARTIFACT_TTL_HOURS-}"
97
97
  FMIX_TEMPLATE_TTL_HOURS="${FMIX_TEMPLATE_TTL_HOURS-}"
98
98
  FMIX_ARTIFACT_TTL_DEFAULT_HOURS="4"
99
+ # Auto-expire batch bound for one preparation pass: pending retirement
100
+ # journals first, then fresh candidates, at most this many operations total.
101
+ FMIX_AUTO_EXPIRE_MAX_DEFAULT="3"
102
+ FMIX_AUTO_EXPIRE_MAX_LIMIT="10"
99
103
  FMIX_MIGRATION_DELTA_LIMIT="${FMIX_MIGRATION_DELTA_LIMIT:-50}"
100
104
  FMIX_COMPILE_HEARTBEAT="${FMIX_COMPILE_HEARTBEAT:-30}"
101
105
  FMIX_COMPILE_TIMEOUT="${FMIX_COMPILE_TIMEOUT:-900}"
@@ -122,6 +126,15 @@ FMIX_STRUCTURE_LOAD_HEARTBEAT="${FMIX_STRUCTURE_LOAD_HEARTBEAT:-30}"
122
126
  FMIX_HELD_LOCK_NAMES=()
123
127
  FMIX_HELD_LOCK_KEEPER_PIDS=()
124
128
  FMIX_HELD_LOCK_TOKENS=()
129
+ # Parallel to FMIX_HELD_LOCK_NAMES: "exclusive" (default) or "shared" (read).
130
+ FMIX_HELD_LOCK_MODES=()
131
+ # Parallel to FMIX_HELD_LOCK_NAMES: 1 when this process published the
132
+ # directory-shaped legacy metadata record, 0 for a shared joiner that left
133
+ # the publisher's record untouched.
134
+ FMIX_HELD_LOCK_PUBLISHED=()
135
+ # Set by fmix_lock_mutate_gate when it escalated a shared hold and the caller
136
+ # must re-verify its warm decision before mutating (retry-once protocol).
137
+ FMIX_LOCK_GATE_RETRY=""
125
138
  FMIX_LAST_LOCK_KEEPER_PID=""
126
139
  FMIX_LOCK_STOP_PROBE_PIDS=()
127
140
  FMIX_PENDING_LOCK_KEEPER_PID=""
@@ -143,8 +156,26 @@ DB_HOST="${FMIX_DB_HOST:-localhost}"
143
156
  DB_PORT="${FMIX_DB_PORT:-5432}"
144
157
  DB_USER="${FMIX_DB_USER:-calltelemetry}"
145
158
  DB_PASSWORD="${FMIX_DB_PASSWORD:-calltelemetry_dev_password}"
146
- NATS_HOST="${FMIX_NATS_HOST:-localhost}"
147
159
  NATS_PORT="${FMIX_NATS_PORT:-4222}"
160
+ FMIX_TAILNET_NATS_HOST="${FMIX_TAILNET_NATS_HOST:-nats-dev}"
161
+
162
+ fmix_resolve_nats_host() {
163
+ if [[ "${FMIX_NATS_HOST+set}" == "set" ]]; then
164
+ printf '%s\n' "$FMIX_NATS_HOST"
165
+ return 0
166
+ fi
167
+ if [[ "${GITHUB_ACTIONS:-}" == "true" || "${CI:-}" == "true" || "${FMIX_DISABLE_TAILNET_NATS:-}" == "1" ]]; then
168
+ printf '%s\n' "localhost"
169
+ return 0
170
+ fi
171
+ if nc -z -w 1 "$FMIX_TAILNET_NATS_HOST" "$NATS_PORT" >/dev/null 2>&1; then
172
+ printf '%s\n' "$FMIX_TAILNET_NATS_HOST"
173
+ return 0
174
+ fi
175
+ printf '%s\n' "localhost"
176
+ return 0
177
+ }
178
+ NATS_HOST="$(fmix_resolve_nats_host)"
148
179
 
149
180
  # Fixed dev constant SECRET_KEY_BASE (64 hex chars — only used in test env)
150
181
  SECRET_KEY_BASE="${FMIX_SECRET_KEY_BASE:-dev0000000000000000000000000000000000000000000000000000000000000001}"
@@ -366,6 +397,29 @@ fmix_stat_mtime() {
366
397
  fi
367
398
  }
368
399
 
400
+ fmix_stat_device() {
401
+ # Device id containing a path. Portable BSD/GNU.
402
+ local f="$1"
403
+ if [[ "$FMIX_OS" == "Darwin" ]]; then
404
+ stat -f '%d' "$f"
405
+ else
406
+ stat -c '%d' "$f"
407
+ fi
408
+ }
409
+
410
+ fmix_stat_identity() {
411
+ # Identity stamp for lock-free CAS reads: the retirement engine's
412
+ # identity() audit fields (device, inode, uid, mode, mtime, ctime) as one
413
+ # comparable line. Fails on a missing or non-regular path.
414
+ local f="$1"
415
+ [[ -f "$f" && ! -L "$f" ]] || return 1
416
+ if [[ "$FMIX_OS" == "Darwin" ]]; then
417
+ stat -f '%d:%i:%u:%Lp:%m:%c' "$f"
418
+ else
419
+ stat -c '%d:%i:%u:%a:%Y:%Z' "$f"
420
+ fi
421
+ }
422
+
369
423
  fmix_cow_clone() {
370
424
  # CoW clone source_dir → dest_dir (dest must NOT exist).
371
425
  # Returns 0 on success, non-zero on failure.
@@ -735,6 +789,13 @@ fmix_hash_string() {
735
789
  }
736
790
 
737
791
  fmix_hash_files() {
792
+ if [[ -n "${FMIX_STAT_HASH_CACHE:-}" ]] && (( $# > 0 )); then
793
+ local fmix_cached_hash_output=""
794
+ if fmix_cached_hash_output="$(fmix_stat_hash_files_cached "$@")"; then
795
+ printf '%s\n' "$fmix_cached_hash_output"
796
+ return 0
797
+ fi
798
+ fi
738
799
  if command -v shasum >/dev/null 2>&1; then
739
800
  shasum -a 256 -- "$@"
740
801
  elif command -v sha256sum >/dev/null 2>&1; then
@@ -745,6 +806,192 @@ fmix_hash_files() {
745
806
  fi
746
807
  }
747
808
 
809
+ # --- Stat-validated content-hash cache (warm admission) ---------------------
810
+ # A cache line records path -> dev,ino,mtime_ns,ctime_ns,size -> sha256. A
811
+ # recorded digest is reused only when the whole stat tuple is unchanged;
812
+ # ctime cannot be preserved by userspace, so every write is re-hashed even
813
+ # when mtime and size are restored. The cache is an accelerator only: any
814
+ # anomaly (odd names, symlinks, special files, stat/read errors, a corrupt
815
+ # cache) falls back to the real full-hash path for the affected call, and the
816
+ # dirty/ignored/dependency guards deliberately keep hashing live content.
817
+ fmix_stat_hash_cache_path() {
818
+ local worktree="$1"
819
+ printf '%s.statcache\n' "$(fmix_compile_stamp_file "$worktree")"
820
+ }
821
+
822
+ fmix_stat_hash_cache_use() {
823
+ local worktree="${1:-}" cache
824
+ [[ -n "$worktree" ]] || return 1
825
+ cache="$(fmix_stat_hash_cache_path "$worktree")" || return 1
826
+ mkdir -p "$(dirname "$cache")" || return 1
827
+ if [[ -n "${FMIX_STAT_HASH_CACHE:-}" ]]; then
828
+ FMIX_STAT_HASH_CACHE_REFCOUNT=$(( ${FMIX_STAT_HASH_CACHE_REFCOUNT:-0} + 1 ))
829
+ return 0
830
+ fi
831
+ FMIX_STAT_HASH_CACHE="$cache"
832
+ FMIX_STAT_HASH_CACHE_REFCOUNT=1
833
+ export FMIX_STAT_HASH_CACHE
834
+ return 0
835
+ }
836
+
837
+ fmix_stat_hash_cache_done() {
838
+ local fmix_cache_count="${FMIX_STAT_HASH_CACHE_REFCOUNT:-1}"
839
+ fmix_cache_count=$(( fmix_cache_count - 1 ))
840
+ if (( fmix_cache_count > 0 )); then
841
+ FMIX_STAT_HASH_CACHE_REFCOUNT="$fmix_cache_count"
842
+ return 0
843
+ fi
844
+ unset FMIX_STAT_HASH_CACHE FMIX_STAT_HASH_CACHE_REFCOUNT
845
+ return 0
846
+ }
847
+
848
+ fmix_stat_hash_cache_seed() {
849
+ # Replace the active cache with a decoded stat manifest (base64 + zlib of
850
+ # the TSV cache format). Empty or undecodable input fails without touching
851
+ # the cache; the caller then runs the ordinary full-hash path. Old stamps
852
+ # without the field are an ordinary miss here, never an error.
853
+ local fmix_manifest="${1:-}" py_bin cache tmp rc
854
+ [[ -n "${FMIX_STAT_HASH_CACHE:-}" ]] || return 1
855
+ [[ -n "$fmix_manifest" ]] || return 1
856
+ cache="$FMIX_STAT_HASH_CACHE"
857
+ tmp="$(mktemp)" || return 1
858
+ printf '%s' "$fmix_manifest" >"$tmp"
859
+ py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
860
+ "$py_bin" - "$tmp" "$cache" <<'PY'
861
+ import base64, os, sys, zlib
862
+
863
+ source, target = sys.argv[1], sys.argv[2]
864
+ try:
865
+ with open(source, "rb") as handle:
866
+ data = handle.read()
867
+ raw = zlib.decompress(base64.b64decode(data))
868
+ except Exception:
869
+ raise SystemExit(1)
870
+ if not raw or b"\0" in raw:
871
+ raise SystemExit(1)
872
+ tmp = target + ".seed.%d" % os.getpid()
873
+ try:
874
+ with open(tmp, "wb") as handle:
875
+ handle.write(raw)
876
+ os.replace(tmp, target)
877
+ except OSError:
878
+ try:
879
+ os.unlink(tmp)
880
+ except OSError:
881
+ pass
882
+ raise SystemExit(1)
883
+ PY
884
+ rc=$?
885
+ rm -f "$tmp"
886
+ (( rc == 0 )) || return 1
887
+ return 0
888
+ }
889
+
890
+ fmix_stat_hash_cache_dump() {
891
+ # Serialize the active cache as the stamp's stat manifest payload.
892
+ local py_bin
893
+ [[ -n "${FMIX_STAT_HASH_CACHE:-}" && -f "$FMIX_STAT_HASH_CACHE" ]] || return 0
894
+ py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
895
+ "$py_bin" - "$FMIX_STAT_HASH_CACHE" <<'PY'
896
+ import base64, sys, zlib
897
+
898
+ try:
899
+ with open(sys.argv[1], "rb") as handle:
900
+ raw = handle.read()
901
+ except OSError:
902
+ raise SystemExit(0)
903
+ if not raw:
904
+ raise SystemExit(0)
905
+ sys.stdout.write(base64.b64encode(zlib.compress(raw, 6)).decode("ascii"))
906
+ PY
907
+ }
908
+
909
+ fmix_stat_hash_files_cached() {
910
+ # Cached fmix_hash_files: byte-identical digest lines (matching the text
911
+ # output of shasum/sha256sum) with recorded digests reused for stat-tuple
912
+ # matches and only drifted entries read from disk. Exits non-zero without
913
+ # printing anything so the caller can fall back to the real hash tools.
914
+ local py_bin
915
+ py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
916
+ "$py_bin" - "$FMIX_STAT_HASH_CACHE" "$@" <<'PY'
917
+ import hashlib, os, stat, sys
918
+
919
+ cache_path = sys.argv[1]
920
+ names = sys.argv[2:]
921
+
922
+ for name in names:
923
+ if "\n" in name or "\\" in name or "\0" in name:
924
+ raise SystemExit(42)
925
+
926
+ entries = {}
927
+ try:
928
+ if os.path.isfile(cache_path):
929
+ with open(cache_path, "r", encoding="utf-8", errors="surrogateescape") as handle:
930
+ for line in handle:
931
+ parts = line.rstrip("\n").split("\t")
932
+ if len(parts) == 7:
933
+ entries[parts[0]] = parts[1:]
934
+ except OSError:
935
+ raise SystemExit(43)
936
+
937
+
938
+ def hash_file(path):
939
+ digest = hashlib.sha256()
940
+ with open(path, "rb") as source:
941
+ while True:
942
+ chunk = source.read(1024 * 1024)
943
+ if not chunk:
944
+ break
945
+ digest.update(chunk)
946
+ return digest.hexdigest()
947
+
948
+
949
+ lines = []
950
+ fresh = {}
951
+ for name in names:
952
+ try:
953
+ key = os.path.normpath(os.path.abspath(name))
954
+ st = os.lstat(name)
955
+ if stat.S_ISLNK(st.st_mode) or not stat.S_ISREG(st.st_mode):
956
+ raise SystemExit(42)
957
+ tup = (
958
+ str(st.st_dev),
959
+ str(st.st_ino),
960
+ str(st.st_mtime_ns),
961
+ str(st.st_ctime_ns),
962
+ str(st.st_size),
963
+ )
964
+ cached = entries.get(key)
965
+ if cached is not None and tuple(cached[:5]) == tup and len(cached[5]) == 64:
966
+ digest = cached[5]
967
+ else:
968
+ digest = hash_file(name)
969
+ fresh[key] = tup + (digest,)
970
+ except SystemExit:
971
+ raise
972
+ except OSError:
973
+ raise SystemExit(42)
974
+ lines.append(digest + " " + name)
975
+
976
+ if fresh:
977
+ entries.update(fresh)
978
+ tmp = cache_path + ".tmp.%d" % os.getpid()
979
+ try:
980
+ with open(tmp, "w", encoding="utf-8", errors="surrogateescape") as handle:
981
+ for key in sorted(entries):
982
+ handle.write("\t".join([key] + list(entries[key])) + "\n")
983
+ os.replace(tmp, cache_path)
984
+ except OSError:
985
+ try:
986
+ os.unlink(tmp)
987
+ except OSError:
988
+ pass
989
+ raise SystemExit(43)
990
+
991
+ sys.stdout.write("".join(line + "\n" for line in lines))
992
+ PY
993
+ }
994
+
748
995
  fmix_hash_file_batches() {
749
996
  local file
750
997
  local -a batch=()
@@ -760,12 +1007,39 @@ fmix_hash_file_batches() {
760
1007
  fi
761
1008
  }
762
1009
 
1010
+ fmix_hash_paired_lines() {
1011
+ # Print "<prefix>:<rel>:<digest-line>" for each (rel, abs) pair while
1012
+ # batching the content hashes into as few hash processes as possible.
1013
+ # Output is byte-identical to interleaved printf + fmix_hash_files calls.
1014
+ local prefix="$1" line index=0 hash_out
1015
+ shift
1016
+ local -a pair_rels=() pair_abses=()
1017
+ while (( $# >= 2 )); do
1018
+ pair_rels+=("$1")
1019
+ pair_abses+=("$2")
1020
+ shift 2
1021
+ done
1022
+ (( ${#pair_abses[@]} > 0 )) || return 0
1023
+ hash_out="$(mktemp)" || return 1
1024
+ if ! fmix_hash_file_batches "${pair_abses[@]}" >"$hash_out"; then
1025
+ rm -f "$hash_out"
1026
+ return 1
1027
+ fi
1028
+ while IFS= read -r line; do
1029
+ printf '%s:%s:%s\n' "$prefix" "${pair_rels[$index]}" "$line"
1030
+ index=$((index + 1))
1031
+ done <"$hash_out"
1032
+ rm -f "$hash_out"
1033
+ return 0
1034
+ }
1035
+
763
1036
  fmix_hash_tracked_compile_inputs() {
764
1037
  local root="$1" tracked_file="$2" py_bin
765
1038
  py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
766
1039
  "$py_bin" - "$root" "$tracked_file" <<'PY'
767
1040
  import hashlib
768
1041
  import os
1042
+ import stat as stat_module
769
1043
  import sys
770
1044
 
771
1045
 
@@ -774,6 +1048,24 @@ tracked_file = sys.argv[2]
774
1048
  output = sys.stdout.buffer
775
1049
  error_output = sys.stderr.buffer
776
1050
 
1051
+ # Stat-validated digest reuse: recorded entries are used only when the full
1052
+ # stat tuple (including ctime) still matches; anomalies simply hash fresh.
1053
+ stat_cache_path = os.environ.get("FMIX_STAT_HASH_CACHE", "")
1054
+ stat_cache_entries = {}
1055
+ stat_cache_usable = bool(stat_cache_path)
1056
+ if stat_cache_usable:
1057
+ try:
1058
+ with open(stat_cache_path, "r", encoding="utf-8", errors="surrogateescape") as handle:
1059
+ for line in handle:
1060
+ parts = line.rstrip("\n").split("\t")
1061
+ if len(parts) == 7:
1062
+ stat_cache_entries[parts[0]] = parts[1:]
1063
+ except FileNotFoundError:
1064
+ pass
1065
+ except OSError:
1066
+ stat_cache_usable = False
1067
+ stat_cache_fresh = {}
1068
+
777
1069
 
778
1070
  def iter_nul_records(stream):
779
1071
  pending = bytearray()
@@ -816,6 +1108,31 @@ def hash_file(path):
816
1108
  return digest.hexdigest().encode("ascii")
817
1109
 
818
1110
 
1111
+ def cached_hash_file(path):
1112
+ if not stat_cache_usable:
1113
+ return hash_file(path)
1114
+ try:
1115
+ key = os.path.normpath(os.path.abspath(os.fsdecode(path)))
1116
+ st = os.lstat(path)
1117
+ except OSError:
1118
+ return hash_file(path)
1119
+ if stat_module.S_ISLNK(st.st_mode) or not stat_module.S_ISREG(st.st_mode):
1120
+ return hash_file(path)
1121
+ tup = (
1122
+ str(st.st_dev),
1123
+ str(st.st_ino),
1124
+ str(st.st_mtime_ns),
1125
+ str(st.st_ctime_ns),
1126
+ str(st.st_size),
1127
+ )
1128
+ cached = stat_cache_entries.get(key)
1129
+ if cached is not None and tuple(cached[:5]) == tup and len(cached[5]) == 64:
1130
+ return cached[5].encode("ascii")
1131
+ digest = hash_file(path)
1132
+ stat_cache_fresh[key] = tup + (digest.decode("ascii"),)
1133
+ return digest
1134
+
1135
+
819
1136
  try:
820
1137
  with open(tracked_file, "rb") as records:
821
1138
  for entry in iter_nul_records(records):
@@ -839,7 +1156,7 @@ try:
839
1156
  raise SystemExit(1)
840
1157
  if os.path.isfile(candidate):
841
1158
  try:
842
- digest = hash_file(candidate)
1159
+ digest = cached_hash_file(candidate)
843
1160
  except OSError:
844
1161
  output.flush()
845
1162
  report_error(b"Could not hash compiler input: " + candidate)
@@ -851,6 +1168,20 @@ try:
851
1168
  except OSError:
852
1169
  report_error(b"Could not read tracked compiler input records")
853
1170
  raise SystemExit(1)
1171
+
1172
+ if stat_cache_usable and stat_cache_fresh:
1173
+ stat_cache_entries.update(stat_cache_fresh)
1174
+ stat_cache_tmp = stat_cache_path + ".tmp.%d" % os.getpid()
1175
+ try:
1176
+ with open(stat_cache_tmp, "w", encoding="utf-8", errors="surrogateescape") as handle:
1177
+ for key in sorted(stat_cache_entries):
1178
+ handle.write("\t".join([key] + list(stat_cache_entries[key])) + "\n")
1179
+ os.replace(stat_cache_tmp, stat_cache_path)
1180
+ except OSError:
1181
+ try:
1182
+ os.unlink(stat_cache_tmp)
1183
+ except OSError:
1184
+ pass
854
1185
  PY
855
1186
  }
856
1187
 
@@ -2111,6 +2442,12 @@ fmix_session_meta_file() {
2111
2442
  fmix_create_or_touch_meta_json() {
2112
2443
  local worktree="$1" meta created lockfile_hash app_name ttl_days ttl_hours tmp
2113
2444
  meta="$(fmix_session_meta_file)" || return 1
2445
+ if [[ ! -f "$meta" ]] && fmix_lock_any_shared_held; then
2446
+ # Creating the session metadata record is a shared-state mutation.
2447
+ # Refreshing an existing record is timestamp-only access accounting
2448
+ # (see docs/fmix.md) and stays under the shared hold.
2449
+ fmix_lock_escalate_exclusive "session meta creation" || return 70
2450
+ fi
2114
2451
 
2115
2452
  ttl_days="$(fmix_effective_session_ttl_days)"
2116
2453
  ttl_hours="$(fmix_effective_session_ttl_hours)"
@@ -2616,16 +2953,36 @@ fmix_activate_session() {
2616
2953
  session_root="$FMIX_HOME/sessions/v1/$host_hash/$session_hash/$worktree_hash"
2617
2954
  session_lock="session-$session_hash"
2618
2955
 
2956
+ # Shared (read) activation is used only when the session overlay is already
2957
+ # warm (root + meta + priv bridge present). Creation and session housekeeping
2958
+ # are mutations and always run under the exclusive lease.
2959
+ local activation_mode="exclusive"
2960
+ if fmix_session_lock_split_enabled \
2961
+ && fmix_activation_probe_readonly "$session_root" "$real"; then
2962
+ activation_mode="shared"
2963
+ fi
2619
2964
  fmix_lock_acquire "$session_lock" "$FMIX_WORKTREE_LOCK_TIMEOUT" \
2620
- "session activation" || {
2965
+ "session activation" 0 "$activation_mode" || {
2621
2966
  activation_rc=$?
2622
2967
  fmix_clear_active_session
2623
2968
  return "$activation_rc"
2624
2969
  }
2970
+ if [[ "$activation_mode" == "shared" ]]; then
2971
+ # Re-verify the warm activation conditions under the lease: the overlay
2972
+ # may have been created or removed while the lock was acquired.
2973
+ if ! fmix_activation_probe_readonly "$session_root" "$real"; then
2974
+ fmix_lock_escalate_exclusive "session root creation" || {
2975
+ activation_rc=$?
2976
+ fmix_clear_active_session
2977
+ return "$activation_rc"
2978
+ }
2979
+ activation_mode="exclusive"
2980
+ fi
2981
+ fi
2625
2982
  if [[ -e "$session_root" || -L "$session_root" ]]; then
2626
2983
  session_root_preexisting=1
2627
2984
  fi
2628
- if (( activation_rc == 0 )); then
2985
+ if (( activation_rc == 0 )) && [[ "$activation_mode" == "exclusive" ]]; then
2629
2986
  if created_session_root="$(fmix_create_session_root \
2630
2987
  "$host_hash" "$session_hash" "$worktree_hash")"; then
2631
2988
  session_root="$created_session_root"
@@ -2633,7 +2990,7 @@ fmix_activate_session() {
2633
2990
  activation_rc=1
2634
2991
  fi
2635
2992
  fi
2636
- if (( activation_rc == 0 )); then
2993
+ if (( activation_rc == 0 )) && [[ "$activation_mode" == "exclusive" ]]; then
2637
2994
  local housekeeping_rc=0
2638
2995
  fmix_purge_expired_sessions 1 || housekeeping_rc=$?
2639
2996
  if fmix_lock_failure_is_fatal "$housekeeping_rc"; then
@@ -2642,7 +2999,7 @@ fmix_activate_session() {
2642
2999
  fmix_warn "Session housekeeping is degraded; activation will continue without destructive cleanup."
2643
3000
  fi
2644
3001
  fi
2645
- if (( activation_rc == 0 )); then
3002
+ if (( activation_rc == 0 )) && [[ "$activation_mode" == "exclusive" ]]; then
2646
3003
  chmod 0700 "$FMIX_HOME" "$FMIX_HOME/sessions" "$FMIX_HOME/sessions/v1" \
2647
3004
  "$FMIX_HOME/sessions/v1/$host_hash" \
2648
3005
  "$FMIX_HOME/sessions/v1/$host_hash/$session_hash" "$session_root" \
@@ -2673,7 +3030,13 @@ fmix_activate_session() {
2673
3030
  fmix_error "Session priv bridge path is occupied by non-symlink state: $priv_link"
2674
3031
  activation_rc=1
2675
3032
  elif (( activation_rc == 0 )); then
2676
- ln -s "$expected_priv" "$priv_link" || activation_rc=1
3033
+ if fmix_lock_any_shared_held; then
3034
+ fmix_lock_escalate_exclusive "session priv bridge creation" \
3035
+ || activation_rc=70
3036
+ fi
3037
+ if (( activation_rc == 0 )); then
3038
+ ln -s "$expected_priv" "$priv_link" || activation_rc=1
3039
+ fi
2677
3040
  fi
2678
3041
 
2679
3042
  if (( activation_rc == 0 )) && ! fmix_write_session_meta "$real"; then
@@ -3320,7 +3683,7 @@ fmix_with_reused_artifact_lease() {
3320
3683
  }
3321
3684
  fmix_artifact_v2_prepare_directory() {
3322
3685
  local rel="${1:-}" py_bin
3323
- [[ "$rel" == artifacts/v2/templates || "$rel" == quarantine/artifacts-v2/templates || "$rel" == quarantine/artifacts-v2/dependencies || "$rel" == artifact-access/v2/templates || "$rel" =~ ^artifacts/v2/dependencies/[0-9a-f]{64}$ || "$rel" =~ ^artifact-access/v2/dependencies/[0-9a-f]{64}$ ]] || return 1
3686
+ [[ "$rel" == artifacts/v2/templates || "$rel" == quarantine/artifacts-v2/templates || "$rel" == quarantine/artifacts-v2/dependencies || "$rel" == quarantine/artifacts-v2/app-compiles || "$rel" == artifact-access/v2/templates || "$rel" =~ ^artifacts/v2/dependencies/[0-9a-f]{64}$ || "$rel" =~ ^artifact-access/v2/dependencies/[0-9a-f]{64}$ || "$rel" =~ ^artifacts/v2/app-compiles/[0-9a-f]{64}$ || "$rel" =~ ^artifact-access/v2/app-compiles/[0-9a-f]{64}$ ]] || return 1
3324
3687
  py_bin="$(fmix_python_bin)" || return 1
3325
3688
  "$py_bin" -I -B - "$FMIX_HOME" "$rel" <<'PY'
3326
3689
  import os,stat,sys
@@ -3345,32 +3708,48 @@ fmix_dependency_artifact_v2_dir() {
3345
3708
  [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
3346
3709
  printf '%s/artifacts/v2/dependencies/%s/%s\n' "$FMIX_HOME" "$lane" "$exact"
3347
3710
  }
3711
+ fmix_app_compile_artifact_v2_dir() {
3712
+ # The app-compile pool is v2-only: exact keys are content-exact compile
3713
+ # fingerprints (fmix_compute_compile_fingerprint) and lanes are dependency
3714
+ # lane fingerprints (fmix_dependency_lane_fingerprint).
3715
+ local lane="${1:-}" exact="${2:-}"
3716
+ [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
3717
+ printf '%s/artifacts/v2/app-compiles/%s/%s\n' "$FMIX_HOME" "$lane" "$exact"
3718
+ }
3348
3719
  fmix_dependency_artifact_legacy_dir() {
3349
3720
  local lane="${1:-}" exact="${2:-}"
3350
3721
  [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
3351
3722
  printf '%s/dependency-artifacts/v1/%s/%s\n' "$FMIX_HOME" "$lane" "$exact"
3352
3723
  }
3353
3724
  fmix_dependency_artifact_dir() {
3354
- local lane="${1:-}" exact="${2:-}" v2
3725
+ local lane="${1:-}" exact="${2:-}" kind="${3:-dependency}" v2
3355
3726
  [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
3727
+ [[ "$kind" == "dependency" || "$kind" == "app" ]] || return 1
3728
+ if [[ "$kind" == "app" ]]; then
3729
+ fmix_app_compile_artifact_v2_dir "$lane" "$exact"
3730
+ return $?
3731
+ fi
3356
3732
  v2="$(fmix_dependency_artifact_v2_dir "$lane" "$exact")" || return 1
3357
3733
  if [[ -e "$v2" || -L "$v2" ]]; then printf '%s\n' "$v2"
3358
3734
  else fmix_dependency_artifact_legacy_dir "$lane" "$exact"; fi
3359
3735
  }
3360
3736
 
3361
3737
  fmix_touch_dependency_artifact_access() {
3738
+ # Access timestamps live outside the CAS and land via one atomic
3739
+ # mktemp+mv, so a lease is never acquired just to refresh one. When the
3740
+ # caller already holds the exact artifact lease, keep the fail-closed
3741
+ # keeper check (a dead keeper is corrupt hold state) and write through
3742
+ # the same atomic path.
3362
3743
  local lane="${1:-}" exact="${2:-}" lock_name index
3363
3744
  [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
3364
3745
  lock_name="dependency-artifact-${lane:0:16}-${exact:0:16}"
3365
3746
  if index="$(fmix_lock_find_index "$lock_name")"; then
3366
3747
  kill -0 "${FMIX_HELD_LOCK_KEEPER_PIDS[$index]}" 2>/dev/null || return 1
3367
- _fmix_touch_dependency_artifact_access_locked "$lane" "$exact"
3368
- else
3369
- fmix_with_artifact_lease "$lock_name" _fmix_touch_dependency_artifact_access_locked "$lane" "$exact"
3370
3748
  fi
3749
+ _fmix_touch_dependency_artifact_access_write "$lane" "$exact"
3371
3750
  }
3372
3751
 
3373
- _fmix_touch_dependency_artifact_access_locked() {
3752
+ _fmix_touch_dependency_artifact_access_write() {
3374
3753
  local lane="${1:-}" exact="${2:-}" root access tmp artifact
3375
3754
  [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
3376
3755
  artifact="$FMIX_HOME/artifacts/v2/dependencies/$lane/$exact"
@@ -3388,6 +3767,37 @@ _fmix_touch_dependency_artifact_access_locked() {
3388
3767
  mv "$tmp" "$access" || { rm -f "$tmp"; return 1; }
3389
3768
  }
3390
3769
 
3770
+ fmix_touch_app_compile_artifact_access() {
3771
+ local lane="${1:-}" exact="${2:-}" lock_name index
3772
+ [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
3773
+ lock_name="app-compile-${lane:0:16}-${exact:0:16}"
3774
+ if index="$(fmix_lock_find_index "$lock_name")"; then
3775
+ kill -0 "${FMIX_HELD_LOCK_KEEPER_PIDS[$index]}" 2>/dev/null || return 1
3776
+ _fmix_touch_app_compile_artifact_access_locked "$lane" "$exact"
3777
+ else
3778
+ fmix_with_artifact_lease "$lock_name" _fmix_touch_app_compile_artifact_access_locked "$lane" "$exact"
3779
+ fi
3780
+ }
3781
+
3782
+ _fmix_touch_app_compile_artifact_access_locked() {
3783
+ # Mutable access timestamps stay outside the immutable CAS, mirroring the
3784
+ # dependency pool's outside-CAS access pattern.
3785
+ local lane="${1:-}" exact="${2:-}" root access tmp artifact
3786
+ [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
3787
+ artifact="$FMIX_HOME/artifacts/v2/app-compiles/$lane/$exact"
3788
+ if [[ -e "$artifact" || -L "$artifact" ]]; then
3789
+ fmix_artifact_v2_managed_entrypoint || return 1
3790
+ root="$FMIX_HOME/artifact-access/v2/app-compiles/$lane"
3791
+ fmix_artifact_v2_prepare_directory "artifact-access/v2/app-compiles/$lane" || return 1
3792
+ else
3793
+ return 1
3794
+ fi
3795
+ access="$root/$exact"
3796
+ tmp="$(mktemp "${access}.tmp.XXXXXX")" || return 1
3797
+ printf '%s\n' "$(fmix_now)" >"$tmp" || { rm -f "$tmp"; return 1; }
3798
+ mv "$tmp" "$access" || { rm -f "$tmp"; return 1; }
3799
+ }
3800
+
3391
3801
  fmix_dependency_artifact_manifest_digest() {
3392
3802
  local root="${1:-}" output="${2:-}" py_bin tmp digest
3393
3803
  (( $# == 1 || $# == 2 )) || return 1
@@ -3436,6 +3846,59 @@ PY
3436
3846
  printf '%s\n' "$digest"
3437
3847
  }
3438
3848
 
3849
+ fmix_app_compile_artifact_manifest_digest() {
3850
+ # fmix_dependency_artifact_manifest_digest-equivalent digest for the
3851
+ # application-only transport. Rows cover every node below _build (never
3852
+ # _build itself), and the payload is strictly link-free like dependency
3853
+ # children: the Mix app priv link is materialized at publication
3854
+ # (fmix_template_materialize_app_priv) so a shared generation never
3855
+ # retains a host/worktree-bound link.
3856
+ local root="${1:-}" output="${2:-}" py_bin tmp digest
3857
+ (( $# == 1 || $# == 2 )) || return 1
3858
+ [[ -d "$root/_build/test/lib" ]] || return 1
3859
+ py_bin="$(fmix_python_bin)"
3860
+ tmp="${output:-$(mktemp)}" || return 1
3861
+ if ! "$py_bin" - "$root" >"$tmp" <<'PY'
3862
+ import hashlib
3863
+ import os
3864
+ import sys
3865
+
3866
+ root = os.path.realpath(sys.argv[1])
3867
+ start = os.path.join(root, "_build")
3868
+ if not os.path.isdir(start) or os.path.islink(start):
3869
+ raise SystemExit(1)
3870
+ for current, dirs, files in os.walk(start, topdown=True, followlinks=False):
3871
+ dirs.sort()
3872
+ files.sort()
3873
+ for name in list(dirs) + files:
3874
+ path = os.path.join(current, name)
3875
+ rel = os.path.relpath(path, root)
3876
+ info = os.lstat(path)
3877
+ if os.path.islink(path):
3878
+ raise SystemExit(1)
3879
+ if os.path.isdir(path):
3880
+ print(f"D\t{rel}\t-")
3881
+ elif os.path.isfile(path):
3882
+ value = hashlib.sha256()
3883
+ with open(path, "rb") as handle:
3884
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
3885
+ value.update(chunk)
3886
+ print(f"F\t{rel}\t{info.st_size}\t{value.hexdigest()}")
3887
+ else:
3888
+ raise SystemExit(1)
3889
+ PY
3890
+ then
3891
+ [[ -n "$output" ]] || rm -f "$tmp"
3892
+ return 1
3893
+ fi
3894
+ digest="$(fmix_hash_stdin <"$tmp")" || {
3895
+ [[ -n "$output" ]] || rm -f "$tmp"
3896
+ return 1
3897
+ }
3898
+ [[ -n "$output" ]] || rm -f "$tmp"
3899
+ printf '%s\n' "$digest"
3900
+ }
3901
+
3439
3902
  fmix_dependency_artifact_meta_matches() {
3440
3903
  local artifact="${1:-}" expected_lane="${2:-}" expected_exact="${3:-}"
3441
3904
  local py_bin validation_output
@@ -3594,63 +4057,279 @@ fmix_dependency_artifact_quarantine() {
3594
4057
  return 1
3595
4058
  }
3596
4059
 
3597
- fmix_stable_seed_parse_meta() {
3598
- local seed_dir="${1:-}" meta
3599
- meta="$seed_dir/meta.json"
3600
- [[ -f "$meta" && -r "$meta" ]] || return 1
3601
- awk '
3602
- function reject() { bad = 1 }
3603
- {
3604
- line = $0
3605
- sub(/^[[:space:]]+/, "", line)
3606
- sub(/[[:space:]]+$/, "", line)
3607
- if (line == "") next
3608
- if (!opened) {
3609
- if (line != "{") reject()
3610
- opened = 1
3611
- next
3612
- }
3613
- if (closed) {
3614
- reject()
3615
- next
3616
- }
3617
- if (line == "}") {
3618
- closed = 1
3619
- next
3620
- }
3621
- has_comma = (line ~ /,$/)
3622
- if (has_comma) sub(/,$/, "", line)
3623
- if (line !~ /^"[^"]+"[[:space:]]*:[[:space:]]*"[^"]*"$/) {
3624
- reject()
3625
- next
3626
- }
3627
- text = line
3628
- sub(/^"/, "", text)
3629
- quote = index(text, "\"")
3630
- key = substr(text, 1, quote - 1)
3631
- text = substr(text, quote + 1)
3632
- sub(/^[[:space:]]*:[[:space:]]*"/, "", text)
3633
- sub(/"$/, "", text)
3634
- value = text
3635
- if (value !~ /^[A-Za-z0-9._\/-]+$/) reject()
3636
- if (key != "schema" && key != "base_ref" && key != "producer_ref" \
3637
- && key != "producer_sha" && key != "compatibility") reject()
3638
- count[key]++
3639
- values[key] = value
3640
- members++
3641
- comma[members] = has_comma
3642
- }
3643
- END {
3644
- if (!opened || !closed || bad || members != 5) exit 1
3645
- for (i = 1; i < members; i++) if (!comma[i]) exit 1
3646
- if (comma[members]) exit 1
3647
- if (count["schema"] != 1 || count["base_ref"] != 1 \
3648
- || count["producer_ref"] != 1 || count["producer_sha"] != 1 \
3649
- || count["compatibility"] != 1) exit 1
3650
- printf "%s\t%s\t%s\t%s\t%s\n", values["schema"], values["base_ref"], \
3651
- values["producer_ref"], values["producer_sha"], values["compatibility"]
3652
- }
3653
- ' "$meta"
4060
+ fmix_app_compile_payload_is_safe() {
4061
+ # A shared application payload is strictly link-free and contains only
4062
+ # ordinary files and directories, exactly like dependency children. The
4063
+ # Mix app priv link is materialized at publication
4064
+ # (fmix_template_materialize_app_priv) before this gate runs; any other
4065
+ # link or special file is refused.
4066
+ local app_dir="${1:-}" py_bin
4067
+ (( $# == 1 )) || return 1
4068
+ [[ -d "$app_dir" && ! -L "$app_dir" ]] || return 1
4069
+ py_bin="$(fmix_python_bin)" || return 1
4070
+ "$py_bin" - "$app_dir" <<'PY'
4071
+ import os
4072
+ import stat
4073
+ import sys
4074
+
4075
+ root = os.path.realpath(sys.argv[1])
4076
+ if os.path.islink(sys.argv[1]):
4077
+ raise SystemExit(1)
4078
+ for current, dirs, files in os.walk(root, topdown=True, followlinks=False):
4079
+ for name in list(dirs) + files:
4080
+ path = os.path.join(current, name)
4081
+ info = os.lstat(path)
4082
+ if stat.S_ISLNK(info.st_mode):
4083
+ raise SystemExit(1)
4084
+ if not (stat.S_ISDIR(info.st_mode) or stat.S_ISREG(info.st_mode)):
4085
+ raise SystemExit(1)
4086
+ PY
4087
+ }
4088
+
4089
+ fmix_app_compile_artifact_meta_matches() {
4090
+ local artifact="${1:-}" expected_lane="${2:-}" expected_exact="${3:-}"
4091
+ local py_bin producer_runner_sha
4092
+ (( $# == 3 )) || return 1
4093
+ [[ "$artifact" == "$FMIX_HOME/artifacts/v2/app-compiles/"* ]] || return 1
4094
+ py_bin="$(fmix_python_bin)"
4095
+ if ! "$py_bin" - "$artifact/meta.json" "$expected_lane" "$expected_exact" <<'PY'
4096
+ import json
4097
+ import re
4098
+ import sys
4099
+
4100
+ def strict_object(pairs):
4101
+ result = {}
4102
+ for key, value in pairs:
4103
+ if key in result:
4104
+ raise ValueError("duplicate key")
4105
+ result[key] = value
4106
+ return result
4107
+
4108
+ path, lane, exact = sys.argv[1:]
4109
+ try:
4110
+ with open(path, encoding="utf-8") as handle:
4111
+ data = json.load(handle, object_pairs_hook=strict_object)
4112
+ except (OSError, ValueError, json.JSONDecodeError):
4113
+ raise SystemExit(1)
4114
+
4115
+ required = {
4116
+ "schema", "lane", "compile_fingerprint", "producer_sha",
4117
+ "source_clean", "manifest_sha256", "built_at",
4118
+ "producer_runner_sha256", "consumer_protocol",
4119
+ }
4120
+ if set(data) != required:
4121
+ raise SystemExit(1)
4122
+ if data["schema"] != "2" or data["lane"] != lane:
4123
+ raise SystemExit(1)
4124
+ if data["compile_fingerprint"] != exact:
4125
+ raise SystemExit(1)
4126
+ if not re.fullmatch(r"[0-9a-f]{40}", data["producer_sha"]):
4127
+ raise SystemExit(1)
4128
+ if data["source_clean"] not in ("true", "false"):
4129
+ raise SystemExit(1)
4130
+ if not re.fullmatch(r"[0-9a-f]{64}", data["manifest_sha256"]):
4131
+ raise SystemExit(1)
4132
+ if not isinstance(data["built_at"], str) or not data["built_at"]:
4133
+ raise SystemExit(1)
4134
+ if (not re.fullmatch(r"[0-9a-f]{64}", data["producer_runner_sha256"])
4135
+ or data["consumer_protocol"] != "fmix-native-artifacts.v2"):
4136
+ raise SystemExit(1)
4137
+ PY
4138
+ then
4139
+ return 1
4140
+ fi
4141
+ producer_runner_sha="$(fmix_read_state "$artifact/meta.json" producer_runner_sha256)" \
4142
+ || return 1
4143
+ fmix_artifact_v2_producer_runner_is_known "$producer_runner_sha"
4144
+ }
4145
+
4146
+ fmix_app_compile_artifact_is_complete() {
4147
+ local artifact="${1:-}" lane="${2:-}" exact="${3:-}" allow_writable="${4:-0}"
4148
+ local expected recorded unexpected writable
4149
+ (( $# == 3 || $# == 4 )) || return 1
4150
+ [[ "$allow_writable" == "0" || "$allow_writable" == "1" ]] || return 1
4151
+ [[ -d "$artifact" && ! -L "$artifact" ]] || return 1
4152
+ [[ -f "$artifact/meta.json" && ! -L "$artifact/meta.json" ]] || return 1
4153
+ [[ -f "$artifact/manifest.tsv" && ! -L "$artifact/manifest.tsv" ]] || return 1
4154
+ [[ -f "$artifact/manifest.sha256" && ! -L "$artifact/manifest.sha256" ]] || return 1
4155
+ unexpected="$(find "$artifact" -mindepth 1 -maxdepth 1 \
4156
+ ! -name _build ! -name meta.json \
4157
+ ! -name manifest.tsv ! -name manifest.sha256 -print -quit 2>/dev/null)" \
4158
+ || return 1
4159
+ [[ -z "$unexpected" ]] || return 1
4160
+ unexpected="$(find "$artifact/_build" -mindepth 1 -maxdepth 1 \
4161
+ ! -name test -print -quit 2>/dev/null)" || return 1
4162
+ [[ -z "$unexpected" ]] || return 1
4163
+ unexpected="$(find "$artifact/_build/test" -mindepth 1 -maxdepth 1 \
4164
+ ! -name lib -print -quit 2>/dev/null)" || return 1
4165
+ [[ -z "$unexpected" ]] || return 1
4166
+ unexpected="$(find "$artifact/_build/test/lib" -mindepth 1 -maxdepth 1 \
4167
+ ! -name cdrcisco -print -quit 2>/dev/null)" || return 1
4168
+ [[ -z "$unexpected" ]] || return 1
4169
+ fmix_app_compile_payload_is_safe "$artifact/_build/test/lib/cdrcisco" || return 1
4170
+ fmix_app_compile_artifact_meta_matches "$artifact" "$lane" "$exact" || return 1
4171
+ IFS= read -r expected <"$artifact/manifest.sha256"
4172
+ recorded="$(fmix_read_state "$artifact/meta.json" manifest_sha256)"
4173
+ [[ "$expected" =~ ^[0-9a-f]{64}$ && "$recorded" == "$expected" ]] || return 1
4174
+ if [[ "$allow_writable" == "0" ]]; then
4175
+ writable="$(find "$artifact" -perm -u+w -print -quit 2>/dev/null)" || return 1
4176
+ [[ -z "$writable" ]] || return 1
4177
+ fi
4178
+ }
4179
+
4180
+ fmix_app_compile_artifact_verify_full_unleased() {
4181
+ local artifact="${1:-}" lane="${2:-}" exact="${3:-}" expected actual
4182
+ fmix_app_compile_artifact_is_complete "$artifact" "$lane" "$exact" || return 1
4183
+ IFS= read -r expected <"$artifact/manifest.sha256"
4184
+ actual="$(fmix_app_compile_artifact_manifest_digest "$artifact")" || return 1
4185
+ [[ "$actual" == "$expected" ]]
4186
+ }
4187
+
4188
+ fmix_app_compile_artifact_verify_full() {
4189
+ local artifact="${1:-}" lane="${2:-}" exact="${3:-}" lock_name index
4190
+ (( $# == 3 )) || return 1
4191
+ [[ "$artifact" == "$FMIX_HOME/artifacts/v2/app-compiles/"* ]] || return 1
4192
+ fmix_artifact_v2_managed_entrypoint || return 1
4193
+ lock_name="app-compile-${lane:0:16}-${exact:0:16}"
4194
+ if index="$(fmix_lock_find_index "$lock_name")"; then
4195
+ kill -0 "${FMIX_HELD_LOCK_KEEPER_PIDS[$index]}" 2>/dev/null || return 1
4196
+ fmix_app_compile_artifact_verify_full_unleased "$@"
4197
+ else
4198
+ fmix_with_artifact_lease "$lock_name" fmix_app_compile_artifact_verify_full_unleased "$@"
4199
+ fi
4200
+ }
4201
+
4202
+ fmix_app_compile_artifact_quick_ready() {
4203
+ # O(1) maintenance probe for a publisher that already completed a full
4204
+ # immutable verification. Consumers never use this shortcut: exact
4205
+ # installation still verifies the complete manifest first.
4206
+ local artifact="${1:-}" lane="${2:-}" exact="${3:-}" producer_runner_sha
4207
+ (( $# == 3 )) || return 1
4208
+ [[ -d "$artifact" && ! -L "$artifact" && ! -w "$artifact" ]] || return 1
4209
+ [[ -d "$artifact/_build/test/lib" \
4210
+ && ! -L "$artifact/_build" \
4211
+ && ! -L "$artifact/_build/test" \
4212
+ && ! -L "$artifact/_build/test/lib" ]] || return 1
4213
+ [[ "$artifact" == "$FMIX_HOME/artifacts/v2/app-compiles/"* ]] || return 1
4214
+ fmix_artifact_v2_managed_entrypoint || return 1
4215
+ producer_runner_sha="$(fmix_read_state "$artifact/meta.json" producer_runner_sha256)" \
4216
+ || return 1
4217
+ fmix_artifact_v2_producer_runner_is_known "$producer_runner_sha" || return 1
4218
+ [[ -f "$artifact/meta.json" && ! -L "$artifact/meta.json" ]] || return 1
4219
+ [[ -f "$artifact/manifest.tsv" && ! -L "$artifact/manifest.tsv" ]] || return 1
4220
+ [[ -f "$artifact/manifest.sha256" && ! -L "$artifact/manifest.sha256" ]] || return 1
4221
+ fmix_app_compile_artifact_verify_full "$artifact" "$lane" "$exact"
4222
+ }
4223
+
4224
+ fmix_app_compile_artifact_path_is_owned() {
4225
+ # Every generation ancestor must belong to this home's lease namespace.
4226
+ local py_bin
4227
+ py_bin="$(fmix_python_bin)" || return 1
4228
+ "$py_bin" -I -B - "$FMIX_HOME" "$1" <<'PY'
4229
+ import os, re, stat, sys
4230
+ home, artifact = sys.argv[1:]
4231
+ fd = None
4232
+ try:
4233
+ if os.path.realpath(home) != home:
4234
+ raise ValueError()
4235
+ if artifact.startswith(home + "/artifacts/v2/app-compiles/"):
4236
+ suffix = artifact[len(home + "/artifacts/v2/app-compiles/"):]
4237
+ components = ("artifacts", "v2", "app-compiles", *suffix.split("/"))
4238
+ else:
4239
+ raise ValueError()
4240
+ if not re.fullmatch(r"[0-9a-f]{64}/[0-9a-f]{64}", suffix):
4241
+ raise ValueError()
4242
+ flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
4243
+ fd = os.open(home, flags)
4244
+ device = os.fstat(fd).st_dev
4245
+ if os.fstat(fd).st_uid != os.getuid():
4246
+ raise ValueError()
4247
+ for component in components:
4248
+ child = os.open(component, flags, dir_fd=fd)
4249
+ os.close(fd)
4250
+ fd = child
4251
+ info = os.fstat(fd)
4252
+ if info.st_uid != os.getuid() or info.st_dev != device or not stat.S_ISDIR(info.st_mode):
4253
+ raise ValueError()
4254
+ except (OSError, ValueError):
4255
+ raise SystemExit(1)
4256
+ finally:
4257
+ if fd is not None:
4258
+ os.close(fd)
4259
+ PY
4260
+ }
4261
+
4262
+ fmix_app_compile_artifact_quarantine() {
4263
+ local artifact="${1:-}" reason="${2:-invalid app compile artifact}" destination
4264
+ [[ "$artifact" == "$FMIX_HOME/artifacts/v2/app-compiles/"* ]] || return 1
4265
+ [[ -e "$artifact" || -L "$artifact" ]] || return 0
4266
+ destination="$FMIX_HOME/quarantine/artifacts-v2/app-compiles/$(basename "$(dirname "$artifact")")-$(basename "$artifact").$(fmix_epoch).$$.${RANDOM}"
4267
+ fmix_app_compile_artifact_path_is_owned "$artifact" || return 1
4268
+ fmix_artifact_v2_prepare_directory "quarantine/artifacts-v2/app-compiles" || return 1
4269
+ if mv "$artifact" "$destination"; then
4270
+ fmix_warn "Quarantined app compile artifact ($reason): $destination"
4271
+ return 0
4272
+ fi
4273
+ return 1
4274
+ }
4275
+
4276
+ fmix_stable_seed_parse_meta() {
4277
+ local seed_dir="${1:-}" meta
4278
+ meta="$seed_dir/meta.json"
4279
+ [[ -f "$meta" && -r "$meta" ]] || return 1
4280
+ awk '
4281
+ function reject() { bad = 1 }
4282
+ {
4283
+ line = $0
4284
+ sub(/^[[:space:]]+/, "", line)
4285
+ sub(/[[:space:]]+$/, "", line)
4286
+ if (line == "") next
4287
+ if (!opened) {
4288
+ if (line != "{") reject()
4289
+ opened = 1
4290
+ next
4291
+ }
4292
+ if (closed) {
4293
+ reject()
4294
+ next
4295
+ }
4296
+ if (line == "}") {
4297
+ closed = 1
4298
+ next
4299
+ }
4300
+ has_comma = (line ~ /,$/)
4301
+ if (has_comma) sub(/,$/, "", line)
4302
+ if (line !~ /^"[^"]+"[[:space:]]*:[[:space:]]*"[^"]*"$/) {
4303
+ reject()
4304
+ next
4305
+ }
4306
+ text = line
4307
+ sub(/^"/, "", text)
4308
+ quote = index(text, "\"")
4309
+ key = substr(text, 1, quote - 1)
4310
+ text = substr(text, quote + 1)
4311
+ sub(/^[[:space:]]*:[[:space:]]*"/, "", text)
4312
+ sub(/"$/, "", text)
4313
+ value = text
4314
+ if (value !~ /^[A-Za-z0-9._\/-]+$/) reject()
4315
+ if (key != "schema" && key != "base_ref" && key != "producer_ref" \
4316
+ && key != "producer_sha" && key != "compatibility") reject()
4317
+ count[key]++
4318
+ values[key] = value
4319
+ members++
4320
+ comma[members] = has_comma
4321
+ }
4322
+ END {
4323
+ if (!opened || !closed || bad || members != 5) exit 1
4324
+ for (i = 1; i < members; i++) if (!comma[i]) exit 1
4325
+ if (comma[members]) exit 1
4326
+ if (count["schema"] != 1 || count["base_ref"] != 1 \
4327
+ || count["producer_ref"] != 1 || count["producer_sha"] != 1 \
4328
+ || count["compatibility"] != 1) exit 1
4329
+ printf "%s\t%s\t%s\t%s\t%s\n", values["schema"], values["base_ref"], \
4330
+ values["producer_ref"], values["producer_sha"], values["compatibility"]
4331
+ }
4332
+ ' "$meta"
3654
4333
  }
3655
4334
 
3656
4335
  fmix_stable_seed_read_meta() {
@@ -4885,7 +5564,7 @@ _fmix_dependency_install_interrupt() {
4885
5564
  fmix_effective_artifact_ttl_hours() {
4886
5565
  local pool="${1:-}" value legacy
4887
5566
  case "$pool" in
4888
- dependency)
5567
+ dependency|app)
4889
5568
  value="${FMIX_DEPENDENCY_ARTIFACT_TTL_HOURS-}"
4890
5569
  legacy="${FMIX_DEPENDENCY_ARTIFACT_TTL_DAYS-}"
4891
5570
  if [[ -z "$value" && -n "$legacy" ]]; then
@@ -4909,6 +5588,29 @@ fmix_effective_artifact_ttl_hours() {
4909
5588
  printf '%s\n' "$(( 10#$value ))"
4910
5589
  }
4911
5590
 
5591
+ fmix_auto_expire_batch_limit() {
5592
+ # FMIX_AUTO_EXPIRE_MAX bounds one auto-expire pass (default 3, bounded
5593
+ # 1-10): at most this many retirement operations run per pass, pending
5594
+ # journals first (forward-only), then the oldest fresh candidates.
5595
+ # Invalid values fall back to the default; out-of-range clamps to bounds.
5596
+ local value="${FMIX_AUTO_EXPIRE_MAX:-}"
5597
+ [[ -n "$value" ]] || { printf '%s\n' "$FMIX_AUTO_EXPIRE_MAX_DEFAULT"; return 0; }
5598
+ if [[ ! "$value" =~ ^[0-9]+$ ]] || (( ${#value} > 4 )); then
5599
+ fmix_warn "FMIX_AUTO_EXPIRE_MAX='$value' must be an integer; using $FMIX_AUTO_EXPIRE_MAX_DEFAULT."
5600
+ printf '%s\n' "$FMIX_AUTO_EXPIRE_MAX_DEFAULT"
5601
+ return 0
5602
+ fi
5603
+ if (( 10#$value < 1 )); then
5604
+ fmix_warn "FMIX_AUTO_EXPIRE_MAX='$value' is below 1; using 1."
5605
+ printf '1\n'
5606
+ elif (( 10#$value > FMIX_AUTO_EXPIRE_MAX_LIMIT )); then
5607
+ fmix_warn "FMIX_AUTO_EXPIRE_MAX='$value' exceeds $FMIX_AUTO_EXPIRE_MAX_LIMIT; using $FMIX_AUTO_EXPIRE_MAX_LIMIT."
5608
+ printf '%s\n' "$FMIX_AUTO_EXPIRE_MAX_LIMIT"
5609
+ else
5610
+ printf '%s\n' "$(( 10#$value ))"
5611
+ fi
5612
+ }
5613
+
4912
5614
  fmix_with_artifact_lease() {
4913
5615
  # Readers use the publisher's existing kernel/mixed-version lease for the
4914
5616
  # entire verification, copy and access refresh. Never nest or steal leases.
@@ -5175,76 +5877,440 @@ _fmix_install_dependency_artifact_locked() {
5175
5877
  mv "$retired/dependency-stamp.json" "$dep_stamp" || rollback_failed=1
5176
5878
  else rollback_failed=1; fi
5177
5879
  fi
5178
- if (( had_compile_stamp != 0 )); then
5179
- if [[ ! -e "$compile_stamp" && ! -L "$compile_stamp" ]]; then
5180
- mv "$retired/compile-stamp.json" "$compile_stamp" || rollback_failed=1
5181
- else rollback_failed=1; fi
5880
+ if (( had_compile_stamp != 0 )); then
5881
+ if [[ ! -e "$compile_stamp" && ! -L "$compile_stamp" ]]; then
5882
+ mv "$retired/compile-stamp.json" "$compile_stamp" || rollback_failed=1
5883
+ else rollback_failed=1; fi
5884
+ fi
5885
+ trap - INT TERM HUP
5886
+ [[ -n "$saved_trap_int" ]] && eval "$saved_trap_int"
5887
+ [[ -n "$saved_trap_term" ]] && eval "$saved_trap_term"
5888
+ [[ -n "$saved_trap_hup" ]] && eval "$saved_trap_hup"
5889
+ if (( rollback_failed != 0 )); then
5890
+ fmix_error "Dependency replacement rollback incomplete; preserving recovery inputs: $stage"
5891
+ return 2
5892
+ fi
5893
+ rm -rf "$stage" || fmix_warn "Owned dependency staging remains: $stage"
5894
+ (( dependency_install_interrupted == 0 )) \
5895
+ || return "$dependency_install_interrupt_rc"
5896
+ return 1
5897
+ fi
5898
+ rm -rf "$stage" 2>/dev/null || \
5899
+ fmix_warn "Dependency install succeeded, but retired staging remains: $stage"
5900
+ trap - INT TERM HUP
5901
+ [[ -n "$saved_trap_int" ]] && eval "$saved_trap_int"
5902
+ [[ -n "$saved_trap_term" ]] && eval "$saved_trap_term"
5903
+ [[ -n "$saved_trap_hup" ]] && eval "$saved_trap_hup"
5904
+ (( dependency_install_interrupted == 0 )) \
5905
+ || return "$dependency_install_interrupt_rc"
5906
+ fmix_touch_dependency_artifact_access "$lane" "$artifact_exact" || return 1
5907
+ return 0
5908
+ }
5909
+
5910
+ fmix_prepare_dependency_artifacts() {
5911
+ local worktree="${1:-}" exact lane artifact reconciler reconciler_exact install_rc
5912
+ (( $# == 1 )) || return 1
5913
+ exact="$(fmix_compute_dependency_fingerprint "$worktree")" || return 1
5914
+ if fmix_dependency_stamp_matches "$worktree" "$exact"; then
5915
+ return 0
5916
+ fi
5917
+ lane="$(fmix_dependency_lane_fingerprint "$worktree")" || return 1
5918
+ artifact="$(fmix_dependency_artifact_dir "$lane" "$exact")" || return 1
5919
+ if [[ -e "$artifact" || -L "$artifact" ]]; then
5920
+ if fmix_install_dependency_artifact "$worktree" "$artifact" 1; then
5921
+ fmix_info "Exact dependency artifact hit — skipping dependency resolution and compilation."
5922
+ return 0
5923
+ else
5924
+ install_rc=$?
5925
+ case "$install_rc" in 2|129|130|143) return "$install_rc" ;; esac
5926
+ fmix_lock_failure_is_fatal "$install_rc" && return 70
5927
+ [[ "${FMIX_ARTIFACT_LEASE_RELEASE_FAILED:-0}" == "0" ]] || return "$install_rc"
5928
+ # Consumers must not quarantine a generation on an unlocked probe:
5929
+ # a concurrent publisher may have replaced it. The leased producer
5930
+ # handles corrupt entries before publishing their replacement.
5931
+ fmix_warn "Exact dependency artifact failed verification; rebuilding under its publisher lease."
5932
+ fi
5933
+ fi
5934
+ if reconciler="$(fmix_find_dependency_reconciler \
5935
+ "$worktree" "$lane" "$exact" 2>/dev/null)"; then
5936
+ reconciler_exact="$(basename "$reconciler")"
5937
+ if fmix_install_dependency_artifact "$worktree" "$reconciler" 0; then
5938
+ fmix_info "Seeded dependency reconciliation from the closest proven ancestor."
5939
+ fmix_info "This is builder input, not an exact cache hit; Mix must publish the new fingerprint."
5940
+ return 0
5941
+ else
5942
+ install_rc=$?
5943
+ case "$install_rc" in 2|129|130|143) return "$install_rc" ;; esac
5944
+ fmix_lock_failure_is_fatal "$install_rc" && return 70
5945
+ [[ "${FMIX_ARTIFACT_LEASE_RELEASE_FAILED:-0}" == "0" ]] || return "$install_rc"
5946
+ fi
5947
+ fmix_warn "Ancestor dependency seed was unusable; continuing with a cold dependency build."
5948
+ fi
5949
+ return 0
5950
+ }
5951
+
5952
+ # ---------------------------------------------------------------------------
5953
+ # Local app-compile CAS — shared compiled application layer
5954
+ # (artifacts/v2/app-compiles/<lane>/<exact>). Reuses the dependency store's
5955
+ # lease, manifest-digest, quarantine, and outside-CAS access conventions.
5956
+ # ---------------------------------------------------------------------------
5957
+
5958
+ fmix_publish_app_compile_artifact() {
5959
+ local worktree="${1:-}" expected="${2:-}" lane
5960
+ (( $# == 2 )) || return 1
5961
+ [[ "$expected" =~ ^[0-9a-f]{64}$ ]] || return 1
5962
+ [[ "${FMIX_APP_CAS:-1}" != "0" ]] || return 1
5963
+ lane="$(fmix_dependency_lane_fingerprint "$worktree")" || return 1
5964
+ [[ "$lane" =~ ^[0-9a-f]{64}$ ]] || return 1
5965
+ fmix_with_artifact_lease "app-compile-${lane:0:16}-${expected:0:16}" \
5966
+ _fmix_publish_app_compile_artifact_locked "$@"
5967
+ }
5968
+
5969
+ _fmix_publish_app_compile_artifact_locked() {
5970
+ # Publish only after the active compile stamp proves the exact key. This
5971
+ # cache is automatic and commit-agnostic; producer_sha is selection
5972
+ # metadata, never part of exact-hit validity. Callers treat every
5973
+ # non-signal failure as a best-effort hold, never a run failure.
5974
+ local worktree="${1:-}" expected_exact="${2:-}" real lane artifact app_source
5975
+ local build_root producer_sha source_clean source_status manifest_sha runner_sha
5976
+ local tmp writable current_exact current_lane
5977
+ (( $# == 2 )) || return 1
5978
+ [[ "$expected_exact" =~ ^[0-9a-f]{64}$ ]] || return 1
5979
+ real="$(fmix_realpath "$worktree")" || return 1
5980
+ current_exact="$(fmix_compute_compile_fingerprint "$real")" || return 1
5981
+ [[ "$current_exact" == "$expected_exact" ]] || return 1
5982
+ fmix_compile_stamp_matches "$real" "$expected_exact" || return 1
5983
+ lane="$(fmix_dependency_lane_fingerprint "$real")" || return 1
5984
+ artifact="$(fmix_app_compile_artifact_v2_dir "$lane" "$expected_exact")" || return 1
5985
+ if fmix_app_compile_artifact_verify_full "$artifact" "$lane" "$expected_exact"; then
5986
+ fmix_artifact_v2_managed_entrypoint || return 3
5987
+ fmix_touch_app_compile_artifact_access "$lane" "$expected_exact" \
5988
+ >/dev/null 2>&1 || return $?
5989
+ return 0
5990
+ fi
5991
+ build_root="$(fmix_compile_build_root "$real")" || return 1
5992
+ app_source="$build_root/test/lib/cdrcisco"
5993
+ [[ -d "$app_source" && ! -L "$app_source" ]] || return 1
5994
+ [[ -d "$app_source/.mix" && -d "$app_source/ebin" ]] || return 1
5995
+ [[ -n "$(find "$app_source/ebin" -maxdepth 1 -type f -name '*.beam' \
5996
+ -print -quit 2>/dev/null)" ]] || return 1
5997
+ fmix_session_normalize_links "$real" || return 1
5998
+ if ! fmix_optional_cache_has_headroom "$app_source"; then
5999
+ fmix_warn "Optional app-compile publication held by disk pressure or incomplete capacity observation; preserving and reusing the proven session."
6000
+ return 3
6001
+ fi
6002
+ if [[ -e "$artifact" || -L "$artifact" ]]; then
6003
+ fmix_app_compile_artifact_quarantine "$artifact" \
6004
+ "failed exact integrity verification" || return 1
6005
+ fi
6006
+ producer_sha="$(git -C "$real" rev-parse --verify 'HEAD^{commit}' 2>/dev/null)" \
6007
+ || producer_sha=""
6008
+ [[ "$producer_sha" =~ ^[0-9a-f]{40}$ ]] || return 1
6009
+ if ! fmix_artifact_v2_managed_entrypoint; then
6010
+ fmix_warn "Optional app-compile publication held because the managed runner handoff is unproven; keeping the current session."
6011
+ return 3
6012
+ fi
6013
+ runner_sha="$(fmix_hash_stdin <"$(fmix_realpath "${BASH_SOURCE[0]}")")" || return 1
6014
+ source_status="$(git -C "$real" status --porcelain --untracked-files=all 2>/dev/null)" \
6015
+ || return 1
6016
+ if [[ -z "$source_status" ]]; then
6017
+ source_clean=true
6018
+ else
6019
+ source_clean=false
6020
+ fi
6021
+
6022
+ fmix_artifact_v2_prepare_directory "artifacts/v2/app-compiles/$lane" || return 1
6023
+ tmp="${artifact}.tmp-$$-${RANDOM}"
6024
+ if [[ -e "$tmp" || -L "$tmp" ]] || ! mkdir "$tmp"; then
6025
+ return 1
6026
+ fi
6027
+ if ! mkdir -p "$tmp/_build/test/lib" \
6028
+ || ! fmix_cow_clone "$app_source" "$tmp/_build/test/lib/cdrcisco" 2>/dev/null; then
6029
+ rm -rf "$tmp" 2>/dev/null || true
6030
+ return 1
6031
+ fi
6032
+ # A shared generation must never retain the host/worktree-bound Mix priv
6033
+ # link; materialize it exactly like the template publisher does.
6034
+ if ! fmix_template_materialize_app_priv "$tmp" "$real" "$build_root"; then
6035
+ rm -rf "$tmp" 2>/dev/null || true
6036
+ return 1
6037
+ fi
6038
+ if ! fmix_app_compile_payload_is_safe "$tmp/_build/test/lib/cdrcisco"; then
6039
+ rm -rf "$tmp" 2>/dev/null || true
6040
+ return 1
6041
+ fi
6042
+ manifest_sha="$(fmix_app_compile_artifact_manifest_digest \
6043
+ "$tmp" "$tmp/manifest.tsv")" || {
6044
+ rm -rf "$tmp" 2>/dev/null || true
6045
+ return 1
6046
+ }
6047
+ printf '%s\n' "$manifest_sha" >"$tmp/manifest.sha256" || {
6048
+ rm -rf "$tmp" 2>/dev/null || true
6049
+ return 1
6050
+ }
6051
+ if ! cat >"$tmp/meta.json" <<EOF
6052
+ {
6053
+ "schema": "2",
6054
+ "lane": "$lane",
6055
+ "compile_fingerprint": "$expected_exact",
6056
+ "producer_sha": "$producer_sha",
6057
+ "source_clean": "$source_clean",
6058
+ "manifest_sha256": "$manifest_sha",
6059
+ "built_at": "$(fmix_now)",
6060
+ "producer_runner_sha256": "$runner_sha",
6061
+ "consumer_protocol": "fmix-native-artifacts.v2"
6062
+ }
6063
+ EOF
6064
+ then
6065
+ rm -rf "$tmp" 2>/dev/null || true
6066
+ return 1
6067
+ fi
6068
+ current_exact="$(fmix_compute_compile_fingerprint "$real")" || current_exact=""
6069
+ current_lane="$(fmix_dependency_lane_fingerprint "$real")" || current_lane=""
6070
+ if [[ "$current_exact" != "$expected_exact" || "$current_lane" != "$lane" ]] \
6071
+ || ! fmix_compile_stamp_matches "$real" "$expected_exact" \
6072
+ || ! fmix_app_compile_artifact_is_complete \
6073
+ "$tmp" "$lane" "$expected_exact" 1; then
6074
+ rm -rf "$tmp" 2>/dev/null || true
6075
+ return 1
6076
+ fi
6077
+ chmod -R a-w "$tmp" || {
6078
+ rm -rf "$tmp" 2>/dev/null || true
6079
+ return 1
6080
+ }
6081
+ chmod u+w "$tmp" || {
6082
+ rm -rf "$tmp" 2>/dev/null || true
6083
+ return 1
6084
+ }
6085
+ writable="$(find "$tmp" -mindepth 1 -perm -u+w -print -quit 2>/dev/null)" \
6086
+ || writable=invalid
6087
+ if ! fmix_artifact_v2_managed_entrypoint; then
6088
+ rm -rf "$tmp" 2>/dev/null || true
6089
+ fmix_warn "Optional app-compile publication held after launcher handoff changed; keeping the current session."
6090
+ return 3
6091
+ fi
6092
+ if [[ -n "$writable" || -e "$artifact" || -L "$artifact" ]] \
6093
+ || ! mv "$tmp" "$artifact"; then
6094
+ rm -rf "$tmp" 2>/dev/null || true
6095
+ return 1
6096
+ fi
6097
+ chmod a-w "$artifact" || {
6098
+ fmix_app_compile_artifact_quarantine "$artifact" \
6099
+ "could not seal exact publication" >/dev/null 2>&1 || true
6100
+ return 1
6101
+ }
6102
+ if ! fmix_app_compile_artifact_verify_full \
6103
+ "$artifact" "$lane" "$expected_exact"; then
6104
+ fmix_app_compile_artifact_quarantine "$artifact" \
6105
+ "post-publication verification failed" >/dev/null 2>&1 || true
6106
+ return 1
6107
+ fi
6108
+ fmix_touch_app_compile_artifact_access "$lane" "$expected_exact" \
6109
+ >/dev/null 2>&1 || return $?
6110
+ fmix_info "Published immutable exact app compile artifact."
6111
+ return 0
6112
+ }
6113
+
6114
+ fmix_install_app_compile_artifact() {
6115
+ local artifact="${2:-}" lane exact
6116
+ (( $# == 3 )) || return 1
6117
+ [[ "${FMIX_APP_CAS:-1}" != "0" ]] || return 1
6118
+ lane="$(basename "$(dirname "$artifact")")"
6119
+ exact="$(basename "$artifact")"
6120
+ [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
6121
+ [[ "$artifact" == "$FMIX_HOME/artifacts/v2/app-compiles/$lane/$exact" ]] || return 1
6122
+ fmix_app_compile_artifact_path_is_owned "$artifact" || return 1
6123
+ fmix_with_artifact_lease "app-compile-${lane:0:16}-${exact:0:16}" \
6124
+ _fmix_install_app_compile_artifact_locked "$@"
6125
+ }
6126
+
6127
+ _fmix_app_compile_install_interrupt() {
6128
+ app_compile_install_interrupted=1
6129
+ app_compile_install_interrupt_rc="${1:-130}"
6130
+ }
6131
+
6132
+ _fmix_install_app_compile_artifact_locked() {
6133
+ # Install into mutable session staging, bind fresh provenance to this
6134
+ # worktree's path/build_root (the same binding fmix_donor_rebind_staged_stamps
6135
+ # performs for donor stamps), and re-run fmix_compile_stamp_matches to
6136
+ # prove admission before committing. ANY verification failure rolls the
6137
+ # transaction back so the caller falls through to the normal bounded
6138
+ # compile — never a forced full rebuild.
6139
+ local worktree="${1:-}" artifact="${2:-}" exact="${3:-}"
6140
+ local real build_root target_lib target stage retired artifact_lane
6141
+ local compile_stamp staged_manifest
6142
+ local had_target=0 had_compile_stamp=0 installed=0 recorded=0 ok=0 rollback_failed=0
6143
+ local switch_failed=0
6144
+ local app_compile_install_interrupted=0 app_compile_install_interrupt_rc=0
6145
+ local saved_trap_int saved_trap_term saved_trap_hup
6146
+ (( $# == 3 )) || return 1
6147
+ [[ "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
6148
+ fmix_app_compile_artifact_path_is_owned "$artifact" || return 1
6149
+ fmix_artifact_v2_managed_entrypoint || return 3
6150
+ real="$(fmix_realpath "$worktree")" || return 1
6151
+ build_root="$(fmix_compile_build_root "$real")" || return 1
6152
+ artifact_lane="$(basename "$(dirname "$artifact")")"
6153
+ fmix_app_compile_artifact_verify_full "$artifact" "$artifact_lane" "$exact" || return 1
6154
+
6155
+ target_lib="$build_root/test/lib"
6156
+ target="$target_lib/cdrcisco"
6157
+ mkdir -p "$target_lib" || return 1
6158
+ [[ ! -L "$build_root" && ! -L "$build_root/test" \
6159
+ && ! -L "$target_lib" ]] || return 1
6160
+
6161
+ stage="$(mktemp -d "$target_lib/.app-compile-install.XXXXXX")" || return 1
6162
+ retired="$stage/retired"
6163
+ if ! mkdir -p "$stage/new/_build/test/lib" "$retired"; then
6164
+ rm -rf "$stage" 2>/dev/null || true
6165
+ return 1
6166
+ fi
6167
+ if ! fmix_cow_clone "$artifact/_build/test/lib/cdrcisco" \
6168
+ "$stage/new/_build/test/lib/cdrcisco"; then
6169
+ rm -rf "$stage" 2>/dev/null || true
6170
+ return 1
6171
+ fi
6172
+ # The donor clone's manifest freshness rule: cloned Mix manifests must
6173
+ # never look stale to an incremental compile.
6174
+ find "$stage/new" -type f -name 'compile.*' -exec touch {} + 2>/dev/null || true
6175
+ # Prove the staged transport before touching any live path.
6176
+ staged_manifest="$(fmix_app_compile_artifact_manifest_digest \
6177
+ "$stage/new" "$stage/new/manifest.tsv")" || {
6178
+ rm -rf "$stage" 2>/dev/null || true
6179
+ return 1
6180
+ }
6181
+ if [[ "$staged_manifest" != "$(fmix_read_state "$artifact/meta.json" manifest_sha256)" ]]; then
6182
+ rm -rf "$stage" 2>/dev/null || true
6183
+ return 1
6184
+ fi
6185
+ chmod -R u+w "$stage/new/_build/test/lib" || {
6186
+ rm -rf "$stage" 2>/dev/null || true
6187
+ return 1
6188
+ }
6189
+ if ! fmix_app_compile_artifact_verify_full \
6190
+ "$artifact" "$artifact_lane" "$exact"; then
6191
+ rm -rf "$stage" 2>/dev/null || true
6192
+ return 1
6193
+ fi
6194
+
6195
+ compile_stamp="$(fmix_compile_stamp_file "$real")"
6196
+ saved_trap_int="$(trap -p INT)"
6197
+ saved_trap_term="$(trap -p TERM)"
6198
+ saved_trap_hup="$(trap -p HUP)"
6199
+ trap '_fmix_app_compile_install_interrupt 130' INT
6200
+ trap '_fmix_app_compile_install_interrupt 143' TERM
6201
+ trap '_fmix_app_compile_install_interrupt 129' HUP
6202
+ if [[ -e "$target" || -L "$target" ]]; then
6203
+ if mv "$target" "$retired/cdrcisco"; then
6204
+ had_target=1
6205
+ else
6206
+ switch_failed=1
6207
+ fi
6208
+ fi
6209
+ if (( switch_failed == 0 && app_compile_install_interrupted == 0 )); then
6210
+ if mv "$stage/new/_build/test/lib/cdrcisco" "$target"; then
6211
+ installed=1
6212
+ else
6213
+ switch_failed=1
6214
+ fi
6215
+ fi
6216
+ if (( installed == 1 && switch_failed == 0 && app_compile_install_interrupted == 0 )); then
6217
+ if [[ -f "$compile_stamp" ]]; then
6218
+ if mv "$compile_stamp" "$retired/compile-stamp.json"; then
6219
+ had_compile_stamp=1
6220
+ else
6221
+ switch_failed=1
6222
+ fi
6223
+ fi
6224
+ fi
6225
+ if (( installed == 1 && switch_failed == 0 && app_compile_install_interrupted == 0 )); then
6226
+ if fmix_write_compile_stamp "$real" "$exact"; then
6227
+ recorded=1
6228
+ else
6229
+ switch_failed=1
5182
6230
  fi
6231
+ fi
6232
+ if (( recorded == 1 && switch_failed == 0 && app_compile_install_interrupted == 0 )) \
6233
+ && fmix_compile_stamp_matches "$real" "$exact"; then
6234
+ ok=1
6235
+ fi
6236
+
6237
+ if (( ok == 1 && switch_failed == 0 && app_compile_install_interrupted == 0 )); then
6238
+ rm -rf "$stage" 2>/dev/null || \
6239
+ fmix_warn "App compile install succeeded, but retired staging remains: $stage"
5183
6240
  trap - INT TERM HUP
5184
6241
  [[ -n "$saved_trap_int" ]] && eval "$saved_trap_int"
5185
6242
  [[ -n "$saved_trap_term" ]] && eval "$saved_trap_term"
5186
6243
  [[ -n "$saved_trap_hup" ]] && eval "$saved_trap_hup"
5187
- if (( rollback_failed != 0 )); then
5188
- fmix_error "Dependency replacement rollback incomplete; preserving recovery inputs: $stage"
5189
- return 2
6244
+ fmix_touch_app_compile_artifact_access "$artifact_lane" "$exact" || return 1
6245
+ return 0
6246
+ fi
6247
+
6248
+ # Roll back: never leave a half-installed application layer behind.
6249
+ if (( installed == 1 )); then
6250
+ if [[ -e "$target" || -L "$target" ]]; then
6251
+ chmod -R u+w "$target" 2>/dev/null || true
6252
+ rm -rf "$target" || rollback_failed=1
5190
6253
  fi
5191
- rm -rf "$stage" || fmix_warn "Owned dependency staging remains: $stage"
5192
- (( dependency_install_interrupted == 0 )) \
5193
- || return "$dependency_install_interrupt_rc"
5194
- return 1
5195
6254
  fi
5196
- rm -rf "$stage" 2>/dev/null || \
5197
- fmix_warn "Dependency install succeeded, but retired staging remains: $stage"
6255
+ if (( recorded == 1 )); then
6256
+ rm -f "$compile_stamp" || rollback_failed=1
6257
+ fi
6258
+ if (( had_compile_stamp == 1 )); then
6259
+ if [[ ! -e "$compile_stamp" && ! -L "$compile_stamp" ]]; then
6260
+ mv "$retired/compile-stamp.json" "$compile_stamp" || rollback_failed=1
6261
+ else rollback_failed=1; fi
6262
+ fi
6263
+ if (( had_target == 1 )); then
6264
+ if [[ ! -e "$target" && ! -L "$target" ]]; then
6265
+ mv "$retired/cdrcisco" "$target" || rollback_failed=1
6266
+ else rollback_failed=1; fi
6267
+ fi
5198
6268
  trap - INT TERM HUP
5199
6269
  [[ -n "$saved_trap_int" ]] && eval "$saved_trap_int"
5200
6270
  [[ -n "$saved_trap_term" ]] && eval "$saved_trap_term"
5201
6271
  [[ -n "$saved_trap_hup" ]] && eval "$saved_trap_hup"
5202
- (( dependency_install_interrupted == 0 )) \
5203
- || return "$dependency_install_interrupt_rc"
5204
- fmix_touch_dependency_artifact_access "$lane" "$artifact_exact" || return 1
5205
- return 0
6272
+ if (( rollback_failed != 0 )); then
6273
+ fmix_error "App compile replacement rollback incomplete; preserving recovery inputs: $stage"
6274
+ return 2
6275
+ fi
6276
+ rm -rf "$stage" 2>/dev/null || \
6277
+ fmix_warn "Owned app compile staging remains: $stage"
6278
+ if (( app_compile_install_interrupted != 0 )); then
6279
+ return "$app_compile_install_interrupt_rc"
6280
+ fi
6281
+ return 1
5206
6282
  }
5207
6283
 
5208
- fmix_prepare_dependency_artifacts() {
5209
- local worktree="${1:-}" exact lane artifact reconciler reconciler_exact install_rc
5210
- (( $# == 1 )) || return 1
5211
- exact="$(fmix_compute_dependency_fingerprint "$worktree")" || return 1
5212
- if fmix_dependency_stamp_matches "$worktree" "$exact"; then
5213
- return 0
5214
- fi
6284
+
6285
+ fmix_try_install_app_compile_artifact() {
6286
+ # Consumer gate for the local app-compile CAS. Returns 0 only after the
6287
+ # payload installed AND the recorded stamps prove admission. Every
6288
+ # verification outcome is a miss: the caller falls through to the normal
6289
+ # bounded compile (never a forced full rebuild).
6290
+ local worktree="${1:-}" fingerprint="${2:-}" lane artifact install_rc
6291
+ (( $# >= 2 )) || return 1
6292
+ [[ "${FMIX_APP_CAS:-1}" != "0" ]] || return 1
6293
+ [[ "$fingerprint" =~ ^[0-9a-f]{64}$ ]] || return 1
5215
6294
  lane="$(fmix_dependency_lane_fingerprint "$worktree")" || return 1
5216
- artifact="$(fmix_dependency_artifact_dir "$lane" "$exact")" || return 1
5217
- if [[ -e "$artifact" || -L "$artifact" ]]; then
5218
- if fmix_install_dependency_artifact "$worktree" "$artifact" 1; then
5219
- fmix_info "Exact dependency artifact hit — skipping dependency resolution and compilation."
5220
- return 0
5221
- else
5222
- install_rc=$?
5223
- case "$install_rc" in 2|129|130|143) return "$install_rc" ;; esac
5224
- fmix_lock_failure_is_fatal "$install_rc" && return 70
5225
- [[ "${FMIX_ARTIFACT_LEASE_RELEASE_FAILED:-0}" == "0" ]] || return "$install_rc"
5226
- # Consumers must not quarantine a generation on an unlocked probe:
5227
- # a concurrent publisher may have replaced it. The leased producer
5228
- # handles corrupt entries before publishing their replacement.
5229
- fmix_warn "Exact dependency artifact failed verification; rebuilding under its publisher lease."
5230
- fi
6295
+ [[ "$lane" =~ ^[0-9a-f]{64}$ ]] || return 1
6296
+ artifact="$(fmix_dependency_artifact_dir "$lane" "$fingerprint" app)" || return 1
6297
+ if [[ ! -e "$artifact" && ! -L "$artifact" ]]; then
6298
+ return 1
5231
6299
  fi
5232
- if reconciler="$(fmix_find_dependency_reconciler \
5233
- "$worktree" "$lane" "$exact" 2>/dev/null)"; then
5234
- reconciler_exact="$(basename "$reconciler")"
5235
- if fmix_install_dependency_artifact "$worktree" "$reconciler" 0; then
5236
- fmix_info "Seeded dependency reconciliation from the closest proven ancestor."
5237
- fmix_info "This is builder input, not an exact cache hit; Mix must publish the new fingerprint."
5238
- return 0
5239
- else
5240
- install_rc=$?
5241
- case "$install_rc" in 2|129|130|143) return "$install_rc" ;; esac
5242
- fmix_lock_failure_is_fatal "$install_rc" && return 70
5243
- [[ "${FMIX_ARTIFACT_LEASE_RELEASE_FAILED:-0}" == "0" ]] || return "$install_rc"
5244
- fi
5245
- fmix_warn "Ancestor dependency seed was unusable; continuing with a cold dependency build."
6300
+ if fmix_install_app_compile_artifact "$worktree" "$artifact" "$fingerprint"; then
6301
+ fmix_info "App compile artifact payload installed; stamps prove admission."
6302
+ return 0
6303
+ else
6304
+ install_rc=$?
6305
+ case "$install_rc" in 2|129|130|143) return "$install_rc" ;; esac
6306
+ fmix_lock_failure_is_fatal "$install_rc" && return 70
6307
+ [[ "${FMIX_ARTIFACT_LEASE_RELEASE_FAILED:-0}" == "0" ]] || return "$install_rc"
6308
+ # Consumers must not quarantine a generation on an unlocked probe: a
6309
+ # concurrent publisher may have replaced it. The leased producer
6310
+ # handles corrupt entries before publishing their replacement.
6311
+ fmix_warn "Exact app compile artifact failed verification; compiling locally."
5246
6312
  fi
5247
- return 0
6313
+ return 1
5248
6314
  }
5249
6315
 
5250
6316
  # ---------------------------------------------------------------------------
@@ -6133,6 +7199,7 @@ fmix_lock_acquire() {
6133
7199
  local lock_name="${1:-}" timeout="${2:-$FMIX_LOCK_TIMEOUT}"
6134
7200
  local diagnostic_name="${3:-${1:-}}" lock_dir kernel_file deadline
6135
7201
  local passive="${4:-0}" metadata_file metadata_document
7202
+ local mode="${5:-exclusive}"
6136
7203
  local keeper_pid token owner_start holder_pid holder_start recorded_start
6137
7204
  local lock_mtime lock_age grace printed_wait=0 index py_bin
6138
7205
  local publication_identity publication_snapshot current_snapshot rollback_keeper_pid rollback_rc rollback_stop_at
@@ -6145,6 +7212,14 @@ fmix_lock_acquire() {
6145
7212
  fmix_error "Invalid passive FMix lock mode."
6146
7213
  return 1
6147
7214
  }
7215
+ [[ "$mode" == "exclusive" || "$mode" == "shared" ]] || {
7216
+ fmix_error "Invalid FMix lock lease mode: '${mode:-empty}'."
7217
+ return 1
7218
+ }
7219
+ if [[ "$mode" == "shared" && "$passive" == "1" ]]; then
7220
+ fmix_error "Passive artifact leases are always exclusive; shared read leases are not passive."
7221
+ return 1
7222
+ fi
6148
7223
  if [[ -n "$FMIX_PENDING_LOCK_KEEPER_PID" ]]; then
6149
7224
  printf '{"error":"lock_keeper_cleanup_pending"}\n' >&2
6150
7225
  return 70
@@ -6171,7 +7246,7 @@ fmix_lock_acquire() {
6171
7246
  local remaining=$(( deadline - $(fmix_epoch) ))
6172
7247
  (( remaining >= 0 )) || remaining=0
6173
7248
  local keeper_rc=0
6174
- fmix_lock_keeper_start "$kernel_file" exclusive "$remaining" \
7249
+ fmix_lock_keeper_start "$kernel_file" "$mode" "$remaining" \
6175
7250
  "$diagnostic_name" "$lock_name" || keeper_rc=$?
6176
7251
  if (( keeper_rc != 0 )); then
6177
7252
  (( keeper_rc == 1 )) || return "$keeper_rc"
@@ -6220,6 +7295,22 @@ fmix_lock_acquire() {
6220
7295
  return 1
6221
7296
  }
6222
7297
  else
7298
+ if [[ "$mode" == "shared" ]] \
7299
+ && fmix_lock_owner_declares_shared "$lock_dir"; then
7300
+ # A live shared publisher owns the legacy record. Join it:
7301
+ # the kernel LOCK_SH lease already arbitrates against every
7302
+ # exclusive contender, and the publisher retires the record.
7303
+ token="$(
7304
+ printf '%s:%s:%s:%s\n' "$$" "$RANDOM" "$(fmix_epoch)" "$lock_name" \
7305
+ | fmix_hash_stdin | cut -c1-24
7306
+ )"
7307
+ FMIX_HELD_LOCK_NAMES+=("$lock_name")
7308
+ FMIX_HELD_LOCK_KEEPER_PIDS+=("$keeper_pid")
7309
+ FMIX_HELD_LOCK_TOKENS+=("$token")
7310
+ FMIX_HELD_LOCK_MODES+=("shared")
7311
+ FMIX_HELD_LOCK_PUBLISHED+=(0)
7312
+ return 0
7313
+ fi
6223
7314
  if (( printed_wait == 0 )); then
6224
7315
  fmix_info "Waiting for mixed-version lock '$diagnostic_name' (pid=$holder_pid) …"
6225
7316
  printed_wait=1
@@ -6268,6 +7359,7 @@ fmix_lock_acquire() {
6268
7359
  token=$token
6269
7360
  pid=$$
6270
7361
  start=$owner_start
7362
+ mode=$mode
6271
7363
  session=${FMIX_ACTIVE_SESSION_HASH:-none}
6272
7364
  command=${FMIX_INTERNAL_RUN_MODE:-${1:-fmix}}
6273
7365
  EOF
@@ -6331,6 +7423,7 @@ EOF
6331
7423
  {
6332
7424
  "lock_name": $(fmix_json_escape "$lock_name"),
6333
7425
  "pid": $$,
7426
+ "mode": $(fmix_json_escape "$mode"),
6334
7427
  "start_time": $(fmix_json_escape "$(fmix_now)"),
6335
7428
  "purpose": $(fmix_json_escape "$diagnostic_name"),
6336
7429
  "worktree": $(fmix_json_escape "${FMIX_ACTIVE_WORKTREE:-}")
@@ -6350,12 +7443,15 @@ EOF
6350
7443
  FMIX_HELD_LOCK_NAMES+=("$lock_name")
6351
7444
  FMIX_HELD_LOCK_KEEPER_PIDS+=("$keeper_pid")
6352
7445
  FMIX_HELD_LOCK_TOKENS+=("$token")
7446
+ FMIX_HELD_LOCK_MODES+=("$mode")
7447
+ FMIX_HELD_LOCK_PUBLISHED+=(1)
6353
7448
  return 0
6354
7449
  done
6355
7450
  }
6356
7451
 
6357
7452
  fmix_lock_release() {
6358
7453
  local lock_name="${1:-}" index keeper_pid token lock_dir recorded_token destination
7454
+ local published
6359
7455
  [[ -n "$lock_name" ]] || {
6360
7456
  fmix_error "fmix_lock_release called with empty lock name — refusing."
6361
7457
  return 1
@@ -6370,6 +7466,7 @@ fmix_lock_release() {
6370
7466
  }
6371
7467
  keeper_pid="${FMIX_HELD_LOCK_KEEPER_PIDS[$index]}"
6372
7468
  token="${FMIX_HELD_LOCK_TOKENS[$index]}"
7469
+ published="${FMIX_HELD_LOCK_PUBLISHED[$index]:-1}"
6373
7470
  lock_dir="$FMIX_HOME/locks/$lock_name"
6374
7471
  # A failed stop retains the indexed owner and all metadata for recovery.
6375
7472
  # Retirement can yield: recheck the token/pid afterwards, never remove a
@@ -6378,6 +7475,13 @@ fmix_lock_release() {
6378
7475
  FMIX_HELD_LOCK_NAMES[$index]=""
6379
7476
  FMIX_HELD_LOCK_KEEPER_PIDS[$index]=""
6380
7477
  FMIX_HELD_LOCK_TOKENS[$index]=""
7478
+ FMIX_HELD_LOCK_MODES[$index]=""
7479
+ FMIX_HELD_LOCK_PUBLISHED[$index]=""
7480
+ if [[ "$published" != "1" ]]; then
7481
+ # Joined shared read lease: the publishing holder owns the legacy
7482
+ # metadata record and retires it. Our kernel lease is already released.
7483
+ return 0
7484
+ fi
6381
7485
  recorded_token="$(sed -n 's/^token=//p' "$lock_dir/owner" 2>/dev/null | head -1)"
6382
7486
  if [[ "$recorded_token" != "$token" ]] \
6383
7487
  || [[ "$(cat "$lock_dir/pid" 2>/dev/null || true)" != "$$" ]]; then
@@ -6403,6 +7507,68 @@ fmix_lock_failure_is_fatal() {
6403
7507
  (( ${1:-0} == 70 )) || [[ -n "$FMIX_PENDING_LOCK_KEEPER_PID" ]]
6404
7508
  }
6405
7509
 
7510
+ fmix_session_lock_split_enabled() {
7511
+ # Kill switch for the shared/exclusive session-lock split. Default ON;
7512
+ # FMIX_SESSION_LOCK_SPLIT=0 forces every acquisition back to the legacy
7513
+ # exclusive-only behaviour (required for mixed-version FMIX_HOME safety).
7514
+ case "${FMIX_SESSION_LOCK_SPLIT:-1}" in
7515
+ 0|false|FALSE|no|NO|off|OFF) return 1 ;;
7516
+ *) return 0 ;;
7517
+ esac
7518
+ }
7519
+
7520
+ fmix_lock_owner_declares_shared() {
7521
+ local lock_dir="${1:-}" owner_mode=""
7522
+ [[ -d "$lock_dir" && -f "$lock_dir/owner" ]] || return 1
7523
+ owner_mode="$(sed -n 's/^mode=//p' "$lock_dir/owner" 2>/dev/null | head -1)"
7524
+ [[ "$owner_mode" == "shared" ]]
7525
+ }
7526
+
7527
+ fmix_lock_any_shared_held() {
7528
+ local i
7529
+ for (( i = 0; i < ${#FMIX_HELD_LOCK_NAMES[@]}; i++ )); do
7530
+ [[ -n "${FMIX_HELD_LOCK_NAMES[$i]:-}" ]] || continue
7531
+ [[ "${FMIX_HELD_LOCK_MODES[$i]:-}" == "shared" ]] && return 0
7532
+ done
7533
+ return 1
7534
+ }
7535
+
7536
+ fmix_lock_escalate_exclusive() {
7537
+ # Clean mid-run escalation: release every shared (read) hold, re-acquire
7538
+ # the same lock names exclusively, then let the caller re-verify its warm
7539
+ # conditions before mutating. Never mutate under a shared hold.
7540
+ local reason="${1:-shared-state mutation}" index name acquire_rc
7541
+ for (( index = 0; index < ${#FMIX_HELD_LOCK_NAMES[@]}; index++ )); do
7542
+ [[ -n "${FMIX_HELD_LOCK_NAMES[$index]:-}" ]] || continue
7543
+ [[ "${FMIX_HELD_LOCK_MODES[$index]:-}" == "shared" ]] || continue
7544
+ name="${FMIX_HELD_LOCK_NAMES[$index]}"
7545
+ fmix_info "Escalating session lock '$name' to exclusive ($reason)."
7546
+ fmix_lock_release "$name" || return 70
7547
+ acquire_rc=0
7548
+ fmix_lock_acquire "$name" "$FMIX_WORKTREE_LOCK_TIMEOUT" \
7549
+ "escalated: $reason" 0 exclusive || acquire_rc=$?
7550
+ if (( acquire_rc != 0 )); then
7551
+ (( acquire_rc == 1 )) || return 70
7552
+ fmix_error "Could not escalate lock '$name' to exclusive for: $reason"
7553
+ return 70
7554
+ fi
7555
+ done
7556
+ return 0
7557
+ }
7558
+
7559
+ fmix_lock_mutate_gate() {
7560
+ # Called immediately before any shared-state mutation. A shared hold must
7561
+ # escalate first and re-verify; return 200 tells the calling wrapper to
7562
+ # re-run its (cheap) warm decision under the new exclusive hold. An
7563
+ # exclusive (or absent) hold passes straight through.
7564
+ local reason="${1:-shared-state mutation}" escalate_rc=0
7565
+ fmix_lock_any_shared_held || return 0
7566
+ fmix_lock_escalate_exclusive "$reason" || escalate_rc=$?
7567
+ (( escalate_rc == 0 )) || return "$escalate_rc"
7568
+ FMIX_LOCK_GATE_RETRY=1
7569
+ return 200
7570
+ }
7571
+
6406
7572
  fmix_lock_release_optional() {
6407
7573
  # Housekeeping may tolerate retired metadata warnings, never a pending
6408
7574
  # live owner. Do not clear handles or retry retirement here.
@@ -7167,11 +8333,30 @@ fmix_template_make_readonly() {
7167
8333
  }
7168
8334
 
7169
8335
  fmix_template_quarantine() {
7170
- local path="$1" reason="$2" destination
8336
+ # Reader-observable CAS mutation: move the exact tree into the
8337
+ # pre-computed unique quarantine destination with ONE atomic mv — a
8338
+ # single rename into the final name, no intermediate name, no copy — so
8339
+ # a concurrent lock-free reader sees complete-old or ENOENT -> ordinary
8340
+ # miss, never a torn read. Same-filesystem rename is enforced before any
8341
+ # mutation: a cross-device source fails closed instead of letting mv
8342
+ # fall back to a recursive copy. Darwin refuses a cross-parent rename of
8343
+ # a directory whose own owner-write bit is clear (see
8344
+ # fmix_template_make_readonly), so the move root alone is re-enabled for
8345
+ # owner-write immediately before the rename; the sealed contents are
8346
+ # never touched and staging roots are already owner-writable.
8347
+ local path="$1" reason="$2" quarantine_root destination source_device quarantine_device
7171
8348
  [[ "$path" == "$FMIX_HOME/artifacts/v2/templates/"* ]] || return 1
7172
8349
  [[ -e "$path" || -L "$path" ]] || return 0
7173
- destination="$FMIX_HOME/quarantine/artifacts-v2/templates/$(basename "$path").$(fmix_epoch).$$.${RANDOM}"
8350
+ quarantine_root="$FMIX_HOME/quarantine/artifacts-v2/templates"
8351
+ destination="$quarantine_root/$(basename "$path").$(fmix_epoch).$$.${RANDOM}"
7174
8352
  fmix_artifact_v2_prepare_directory "quarantine/artifacts-v2/templates" || return 1
8353
+ [[ ! -e "$destination" && ! -L "$destination" ]] || return 1
8354
+ source_device="$(fmix_stat_device "$path")" || return 1
8355
+ quarantine_device="$(fmix_stat_device "$quarantine_root")" || return 1
8356
+ [[ "$source_device" == "$quarantine_device" ]] || return 1
8357
+ if [[ "$FMIX_OS" == "Darwin" && -d "$path" && ! -L "$path" ]]; then
8358
+ chmod u+w "$path" || return 1
8359
+ fi
7175
8360
  if mv "$path" "$destination"; then
7176
8361
  fmix_warn "Quarantined template state ($reason): $destination"
7177
8362
  return 0
@@ -7217,16 +8402,44 @@ fmix_template_is_complete_unleased() {
7217
8402
  [[ -z "$writable" ]]
7218
8403
  }
7219
8404
 
7220
- fmix_template_is_complete() {
8405
+ fmix_template_cas_read_identity() {
8406
+ # meta.json + manifest.sha256 identity snapshot for lock-free v2 reads
8407
+ # (see the retirement engine's identity() audit fields). A mid-read
8408
+ # quarantine rename or replacement publication changes it; missing
8409
+ # metadata fails closed as an ordinary miss.
7221
8410
  local key="${1:-}" tdir
7222
8411
  [[ "$key" =~ ^[0-9a-f]{16}$ ]] || return 1
7223
8412
  tdir="$(fmix_template_dir "$key")" || return 1
8413
+ fmix_stat_identity "$tdir/meta.json" || return 1
8414
+ fmix_stat_identity "$tdir/manifest.sha256" || return 1
8415
+ }
8416
+
8417
+ fmix_template_is_complete() {
8418
+ local key="${1:-}" tdir attempt before after outcome
8419
+ [[ "$key" =~ ^[0-9a-f]{16}$ ]] || return 1
8420
+ tdir="$(fmix_template_dir "$key")" || return 1
7224
8421
  if [[ "$tdir" != "$FMIX_HOME/artifacts/v2/templates/"* ]]; then
7225
8422
  fmix_template_is_complete_unleased "$key"
7226
8423
  return $?
7227
8424
  fi
7228
8425
  fmix_artifact_v2_managed_entrypoint || return 1
7229
- fmix_with_reused_artifact_lease "build-$key" fmix_template_is_complete_unleased "$key"
8426
+ # Lock-free CAS read. The published tree is immutable and this check
8427
+ # never promotes or writes CAS contents, so the exclusive build-<key>
8428
+ # lease is not taken: warm reads must not queue behind a producer's
8429
+ # minutes-long build lease. After validation, re-stat the meta.json /
8430
+ # manifest.sha256 identities to detect a mid-read quarantine rename or
8431
+ # replacement publication and retry once on identity change. An
8432
+ # identity that still moves on the retry fails closed as a miss.
8433
+ for attempt in 1 2; do
8434
+ before="$(fmix_template_cas_read_identity "$key")" || return 1
8435
+ outcome=1
8436
+ fmix_template_is_complete_unleased "$key" && outcome=0
8437
+ after="$(fmix_template_cas_read_identity "$key")" || after="missing"
8438
+ if [[ "$before" == "$after" ]]; then
8439
+ return "$outcome"
8440
+ fi
8441
+ done
8442
+ return 1
7230
8443
  }
7231
8444
 
7232
8445
  fmix_template_verify_full_unleased() {
@@ -8819,6 +10032,8 @@ _fmix_ensure_artifacts_impl() {
8819
10032
  fi
8820
10033
  else
8821
10034
  fmix_info "Template key mismatch (recorded=$recorded_key, current=$template_key)."
10035
+ fmix_lock_mutate_gate \
10036
+ "artifact adoption under template key $template_key" || return $?
8822
10037
  if fmix_adopt_compatible_worktree_artifacts \
8823
10038
  "$worktree" "$recorded_key" "$template_key"; then
8824
10039
  fmix_write_artifact_state "$worktree" "$template_key" || return 1
@@ -8863,6 +10078,9 @@ _fmix_ensure_artifacts_impl() {
8863
10078
  FMIX_LAST_ARTIFACTS_OUTCOME="missing_template"
8864
10079
  return 1
8865
10080
  fi
10081
+ # Everything past this point mutates shared artifact state (donor fetch,
10082
+ # template build, or clone). A shared hold must escalate first.
10083
+ fmix_lock_mutate_gate "artifact clone, donor fetch, or template build" || return $?
8866
10084
  # Prefer a warm peer session for the same worktree+template over a cold
8867
10085
  # template clone (avoids ~4700-file recompile when isolate/new session).
8868
10086
  # A contended donor can be skipped, but the retry window is deliberately
@@ -8929,6 +10147,9 @@ _fmix_ensure_artifacts_impl() {
8929
10147
  }
8930
10148
 
8931
10149
  fmix_auto_expire_artifacts() {
10150
+ # Shared (read) holds never mutate the shared artifact-retirement indexes.
10151
+ # Exclusive runs and explicit `fmix gc` cover this housekeeping.
10152
+ fmix_lock_any_shared_held && return 0
8932
10153
  [[ "${FMIX_ARTIFACT_AUTO_EXPIRE:-1}" == "1" ]] || return 0
8933
10154
  case "${cmd:-${FMIX_INTERNAL_RUN_MODE:-}}" in
8934
10155
  test|coverage|setup|task|format) ;;
@@ -8938,9 +10159,103 @@ fmix_auto_expire_artifacts() {
8938
10159
  return 0
8939
10160
  }
8940
10161
 
10162
+ fmix_run_probe_readonly() {
10163
+ # Pre-lock proof that the whole run is provably read-only w.r.t. shared
10164
+ # state (conditions a+b+c of the session-lock shared mode; condition d is
10165
+ # the caller's run-mode gate). STRICTLY read-only: any miss, ambiguity, or
10166
+ # probe error returns nonzero so the caller takes the exclusive lock.
10167
+ # (a) fmix_ensure_artifacts resolves warm: session_hit (recorded template
10168
+ # key + app manifest) or adopt_stamps (exact dependency/compile
10169
+ # stamps) — no clone, no template build, no donor fetch.
10170
+ # (b) compile is a stamp quick-hit (no deps.get, no mix compile).
10171
+ # (c) the scratch DB exists and is migration-current via an unexpired
10172
+ # schema-ready stamp (no CREATE/DROP, no migrate, no partitions).
10173
+ local worktree="$1" template_key="$2" db_name="$3"
10174
+ [[ -n "$FMIX_ACTIVE_SESSION_HASH" && -n "$FMIX_ACTIVE_SESSION_ROOT" ]] || return 1
10175
+ [[ "$template_key" =~ ^[0-9a-f]{16}$ ]] || return 1
10176
+
10177
+ # (a) artifacts warm without mutation.
10178
+ local state_file artifact_state_file recorded_key="" deps_root build_root
10179
+ state_file="$(fmix_worktree_state_file "$worktree")" || return 1
10180
+ artifact_state_file="$(fmix_artifact_state_file "$worktree")" || return 1
10181
+ if [[ -f "$artifact_state_file" ]]; then
10182
+ recorded_key="$(fmix_read_state "$artifact_state_file" "template_key")"
10183
+ elif [[ -f "$state_file" ]]; then
10184
+ recorded_key="$(fmix_read_state "$state_file" "template_key")"
10185
+ fi
10186
+ deps_root="$(fmix_session_deps_root "$worktree")" || return 1
10187
+ build_root="$(fmix_compile_build_root "$worktree")" || return 1
10188
+ [[ -d "$deps_root" && -d "$build_root" ]] || return 1
10189
+ if [[ -n "$recorded_key" ]]; then
10190
+ # session_hit: exact recorded key + intact overlay.
10191
+ [[ "$recorded_key" == "$template_key" ]] || return 1
10192
+ fmix_session_has_app_manifest "$worktree" "$build_root" || return 1
10193
+ else
10194
+ # adopt_stamps: only exact stamps may prove an unrecorded overlay.
10195
+ fmix_template_is_complete "$template_key" || return 1
10196
+ local dependency_fingerprint compile_fingerprint
10197
+ dependency_fingerprint="$(
10198
+ fmix_compute_dependency_fingerprint "$worktree" 2>/dev/null
10199
+ )" || return 1
10200
+ compile_fingerprint="$(
10201
+ fmix_compute_compile_fingerprint "$worktree" 2>/dev/null
10202
+ )" || return 1
10203
+ [[ -n "$dependency_fingerprint" && -n "$compile_fingerprint" ]] || return 1
10204
+ fmix_dependency_stamp_matches "$worktree" "$dependency_fingerprint" || return 1
10205
+ fmix_compile_stamp_matches "$worktree" "$compile_fingerprint" || return 1
10206
+ fi
10207
+
10208
+ # (b) compile is a stamp quick-hit (read-only admission).
10209
+ fmix_try_compile_stamp_quick_hit "$worktree" || return 1
10210
+
10211
+ # (c) scratch DB exists and is migration-current (no CREATE/DROP).
10212
+ fmix_db_exists "$db_name" || return 1
10213
+ fmix_schema_ready_stamp_warm_ro "$worktree" "$db_name" || return 1
10214
+ fmix_validate_db_integrity "$db_name" || return 1
10215
+ return 0
10216
+ }
10217
+
10218
+ fmix_activation_probe_readonly() {
10219
+ # Warm session activation is provably read-only: the session root, its
10220
+ # metadata record, and the priv bridge already exist and are correct.
10221
+ # Anything missing requires creation (an exclusive mutation).
10222
+ local session_root="$1" real="$2"
10223
+ [[ -n "$session_root" && -d "$session_root" && ! -L "$session_root" ]] || return 1
10224
+ [[ -f "$session_root/meta.json" && ! -L "$session_root/meta.json" ]] || return 1
10225
+ [[ -L "$session_root/priv" ]] || return 1
10226
+ [[ "$(readlink "$session_root/priv" 2>/dev/null)" == "$real/priv" ]] || return 1
10227
+ return 0
10228
+ }
10229
+
10230
+ fmix_publish_run_worktree_state() {
10231
+ # Shared-hold state publication contract (condition d): a run may publish
10232
+ # only provenance it just verified read-only. Identical provenance is a
10233
+ # timestamp-only refresh and stays under the shared hold; a publication
10234
+ # that would CREATE or CHANGE recorded provenance escalates to exclusive
10235
+ # first and then writes under the new hold.
10236
+ local worktree="$1" template_key="$2" db_name="$3" mig_stamp="$4"
10237
+ local schema_key="${5:-}" base_id="${6:-}" source_key="${7:-}"
10238
+ local state_file
10239
+ if fmix_lock_any_shared_held; then
10240
+ state_file="$(fmix_worktree_state_file "$worktree")" || return 1
10241
+ if [[ ! -f "$state_file" ]] || [[ "$(fmix_read_state "$state_file" template_key)" != "$template_key" ]] || [[ "$(fmix_read_state "$state_file" db_name)" != "$db_name" ]] || [[ "$(fmix_read_state "$state_file" last_migration_stamp)" != "$mig_stamp" ]] || [[ "$(fmix_read_state "$state_file" db_schema_key)" != "$schema_key" ]] || [[ "$(fmix_read_state "$state_file" db_base_id)" != "$base_id" ]] || [[ "$(fmix_read_state "$state_file" db_source_schema_key)" != "$source_key" ]]; then
10242
+ fmix_lock_escalate_exclusive "worktree state provenance publication" || return 70
10243
+ fi
10244
+ fi
10245
+ fmix_write_worktree_state "$worktree" "$template_key" "$db_name" "$mig_stamp" "$(fmix_now)" "$schema_key" "$base_id" "$source_key"
10246
+ }
10247
+
8941
10248
  fmix_ensure_artifacts() {
8942
10249
  local rc=0
8943
10250
  _fmix_ensure_artifacts_impl "$@" || rc=$?
10251
+ if (( rc == 200 )) && [[ "${FMIX_LOCK_GATE_RETRY:-}" == "1" ]]; then
10252
+ # A mutation gate escalated a shared hold mid-decision. Re-verify the
10253
+ # warm conditions once under the new exclusive hold: they may have
10254
+ # changed while the lease was upgraded, and only then mutate.
10255
+ FMIX_LOCK_GATE_RETRY=""
10256
+ rc=0
10257
+ _fmix_ensure_artifacts_impl "$@" || rc=$?
10258
+ fi
8944
10259
  (( rc == 0 )) || return "$rc"
8945
10260
  fmix_auto_expire_artifacts
8946
10261
  }
@@ -10240,6 +11555,19 @@ fmix_load_structure() {
10240
11555
  }
10241
11556
 
10242
11557
  fmix_ensure_db() {
11558
+ local rc=0
11559
+ _fmix_ensure_db_impl "$@" || rc=$?
11560
+ if (( rc == 200 )) && [[ "${FMIX_LOCK_GATE_RETRY:-}" == "1" ]]; then
11561
+ # Escalated before a scratch-DB mutation: re-verify existence and
11562
+ # provenance once under the new exclusive hold before CREATE/DROP.
11563
+ FMIX_LOCK_GATE_RETRY=""
11564
+ rc=0
11565
+ _fmix_ensure_db_impl "$@" || rc=$?
11566
+ fi
11567
+ return "$rc"
11568
+ }
11569
+
11570
+ _fmix_ensure_db_impl() {
10243
11571
  # Only this admission's actual bounded cold migration failure is primary
10244
11572
  # across its caller's retirement. Metadata/clone failures are not Mix.
10245
11573
  FMIX_LAST_DB_MAINTENANCE_MIX_FAILURE=0
@@ -10305,6 +11633,7 @@ fmix_ensure_db() {
10305
11633
  # no-ops. The operator asked for a fresh database: drop it.
10306
11634
  fmix_warn "Explicit rebuild requested; replacing otherwise-valid scratch DB $db_name."
10307
11635
  valid=0
11636
+ fmix_lock_mutate_gate "scratch DB rebuild (DROP)" || return $?
10308
11637
  fmix_drop_db "$db_name" || return $?
10309
11638
  fi
10310
11639
  if (( valid == 1 )); then
@@ -10322,10 +11651,13 @@ fmix_ensure_db() {
10322
11651
  return 1
10323
11652
  fi
10324
11653
  fmix_warn "Explicit setup is replacing unverified scratch DB $db_name."
11654
+ fmix_lock_mutate_gate "scratch DB replacement (DROP)" || return $?
10325
11655
  fmix_drop_db "$db_name" || return $?
10326
11656
  fi
10327
11657
  fi
10328
11658
 
11659
+ # Scratch-DB creation (clone/cold bootstrap) mutates shared state.
11660
+ fmix_lock_mutate_gate "scratch DB creation" || return $?
10329
11661
  t0="$(fmix_epoch)"
10330
11662
  selection=""
10331
11663
  if [[ "$allow_structure_build" == "1" || "$force_from_zero" == "1" ]]; then
@@ -10485,6 +11817,9 @@ fmix_run_migration_bounded() {
10485
11817
  MEESEEKS_HTML5EVER_BUILD=0 \
10486
11818
  LOCAL_NATS="$NATS_HOST" \
10487
11819
  NATS_PORT="$NATS_PORT" \
11820
+ NATS_HOST="$NATS_HOST" \
11821
+ CT_NATS_HOST="$NATS_HOST" \
11822
+ NATS_URL="nats://${NATS_HOST}:${NATS_PORT}" \
10488
11823
  POSTHOG_BACKEND_ENABLED="${POSTHOG_BACKEND_ENABLED:-false}" \
10489
11824
  POSTHOG_BROWSER_ENABLED="${POSTHOG_BROWSER_ENABLED:-false}" \
10490
11825
  mix ecto.migrate --no-compile
@@ -10547,6 +11882,35 @@ EOF
10547
11882
  mv "$tmp" "$stamp" || { rm -f "$tmp"; return 1; }
10548
11883
  }
10549
11884
 
11885
+ fmix_schema_ready_stamp_warm_ro() {
11886
+ # Strictly read-only twin of fmix_schema_ready_stamp_matches: same
11887
+ # admission, but never removes an expired stamp. Shared (read) holds and
11888
+ # the pre-lock read-only probe must not mutate; stamp expiry cleanup stays
11889
+ # in the exclusive path.
11890
+ local worktree="$1" db_name="$2" stamp mig_stamp schema_key
11891
+ local recorded_db recorded_mig recorded_schema recorded_epoch ttl age now
11892
+ stamp="$(fmix_schema_ready_stamp_file "$worktree")"
11893
+ [[ -f "$stamp" ]] || return 1
11894
+ recorded_db="$(fmix_read_state "$stamp" db_name)"
11895
+ recorded_mig="$(fmix_read_state "$stamp" migration_stamp)"
11896
+ recorded_schema="$(fmix_read_state "$stamp" schema_key)"
11897
+ recorded_epoch="$(fmix_read_state "$stamp" ready_epoch)"
11898
+ ttl="$(fmix_read_state "$stamp" ttl_s)"
11899
+ [[ "$ttl" =~ ^[0-9]+$ ]] || ttl="$(fmix_schema_ready_ttl_seconds)"
11900
+ [[ "$recorded_epoch" =~ ^[0-9]+$ ]] || return 1
11901
+ now="$(fmix_epoch)"
11902
+ age=$(( now - recorded_epoch ))
11903
+ (( age >= 0 && age < ttl )) || return 1
11904
+ [[ "$recorded_db" == "$db_name" ]] || return 1
11905
+ mig_stamp="$(fmix_migration_stamp "$worktree")" || return 1
11906
+ [[ "$recorded_mig" == "$mig_stamp" ]] || return 1
11907
+ schema_key="${FMIX_ACTIVE_DB_SCHEMA_KEY:-}"
11908
+ if [[ -n "$schema_key" && -n "$recorded_schema" ]]; then
11909
+ [[ "$recorded_schema" == "$schema_key" ]] || return 1
11910
+ fi
11911
+ return 0
11912
+ }
11913
+
10550
11914
  fmix_schema_ready_stamp_matches() {
10551
11915
  local worktree="$1" db_name="$2" stamp mig_stamp schema_key
10552
11916
  local recorded_db recorded_mig recorded_schema recorded_epoch ttl age now
@@ -10581,9 +11945,36 @@ fmix_schema_ready_stamp_matches() {
10581
11945
  }
10582
11946
 
10583
11947
  fmix_ensure_migrations() {
11948
+ local rc=0
11949
+ _fmix_ensure_migrations_impl "$@" || rc=$?
11950
+ if (( rc == 200 )) && [[ "${FMIX_LOCK_GATE_RETRY:-}" == "1" ]]; then
11951
+ # Escalated before schema work: re-verify the warm schema state once
11952
+ # under the new exclusive hold before migrating or writing stamps.
11953
+ FMIX_LOCK_GATE_RETRY=""
11954
+ rc=0
11955
+ _fmix_ensure_migrations_impl "$@" || rc=$?
11956
+ fi
11957
+ return "$rc"
11958
+ }
11959
+
11960
+ _fmix_ensure_migrations_impl() {
10584
11961
  local worktree="$1" db_name="$2" state_file="$3"
10585
11962
  fmix_prepend_toolchain_paths
10586
11963
 
11964
+ if fmix_lock_any_shared_held; then
11965
+ # Shared holds admit only the strictly read-only warm path. The stock
11966
+ # warm check auto-expires stale stamps (a mutation), so probe without
11967
+ # side effects; any miss escalates instead of scanning/writing under a
11968
+ # shared lease.
11969
+ if fmix_schema_ready_stamp_warm_ro "$worktree" "$db_name" \
11970
+ && fmix_validate_db_integrity "$db_name"; then
11971
+ fmix_info "Schema ready stamp hit (TTL $(fmix_schema_ready_ttl_seconds)s) — skipping migration ledger scan."
11972
+ return 0
11973
+ fi
11974
+ fmix_lock_mutate_gate \
11975
+ "migration ledger scan, migration delta, or schema-ready stamp" || return $?
11976
+ fi
11977
+
10587
11978
  # Warm path: prior success stamp matching migration files + db name skips
10588
11979
  # repeated ledger scans (was ~2 full psql + file walks per run).
10589
11980
  if fmix_schema_ready_stamp_matches "$worktree" "$db_name"; then
@@ -10710,6 +12101,9 @@ fmix_ensure_partitions() {
10710
12101
  MEESEEKS_HTML5EVER_BUILD=0 \
10711
12102
  LOCAL_NATS="$NATS_HOST" \
10712
12103
  NATS_PORT="$NATS_PORT" \
12104
+ NATS_HOST="$NATS_HOST" \
12105
+ CT_NATS_HOST="$NATS_HOST" \
12106
+ NATS_URL="nats://${NATS_HOST}:${NATS_PORT}" \
10713
12107
  POSTHOG_BACKEND_ENABLED="${POSTHOG_BACKEND_ENABLED:-false}" \
10714
12108
  POSTHOG_BROWSER_ENABLED="${POSTHOG_BROWSER_ENABLED:-false}" \
10715
12109
  env -u DB_HOST_IPV4 mix cdrcisco.bootstrap_partitions
@@ -10842,6 +12236,7 @@ fmix_hash_compile_paths() {
10842
12236
  rm -f "$untracked_file"
10843
12237
  return 1
10844
12238
  fi
12239
+ local -a untracked_pairs=()
10845
12240
  while IFS= read -r -d '' path; do
10846
12241
  case "$path" in
10847
12242
  _build|_build/*|deps|deps/*) continue ;;
@@ -10852,11 +12247,11 @@ fmix_hash_compile_paths() {
10852
12247
  return 1
10853
12248
  fi
10854
12249
  [[ -f "$root/$path" ]] || continue
10855
- printf 'untracked:%s:' "$path"
10856
- fmix_hash_files "$root/$path" \
10857
- || { rm -f "$untracked_file"; return 1; }
12250
+ untracked_pairs+=("$path" "$root/$path")
10858
12251
  done <"$untracked_file"
10859
12252
  rm -f "$untracked_file"
12253
+ fmix_hash_paired_lines "untracked" \
12254
+ "${untracked_pairs[@]+"${untracked_pairs[@]}"}" || return 1
10860
12255
  return 0
10861
12256
  fi
10862
12257
 
@@ -10869,10 +12264,12 @@ fmix_hash_compile_paths() {
10869
12264
  fmix_hash_files "$root/$path"
10870
12265
  elif [[ -d "$root/$path" ]]; then
10871
12266
  fmix_reject_nested_source_symlinks "$root/$path" || return 1
12267
+ local -a dir_pairs=()
10872
12268
  while IFS= read -r file; do
10873
- printf 'file:%s:' "${file#"$root/"}"
10874
- fmix_hash_files "$file"
12269
+ dir_pairs+=("${file#"$root/"}" "$file")
10875
12270
  done < <(find "$root/$path" -type f -print 2>/dev/null | LC_ALL=C sort)
12271
+ fmix_hash_paired_lines "file" \
12272
+ "${dir_pairs[@]+"${dir_pairs[@]}"}" || return 1
10876
12273
  else
10877
12274
  printf 'missing:%s\n' "$path"
10878
12275
  fi
@@ -10906,6 +12303,7 @@ fmix_ignored_compile_inputs_hash() {
10906
12303
  return 1
10907
12304
  fi
10908
12305
  rc=0
12306
+ local -a ignored_pairs=()
10909
12307
  {
10910
12308
  printf 'fmix-ignored-compile-inputs-v1\n'
10911
12309
  while IFS= read -r -d '' path; do
@@ -10915,12 +12313,10 @@ fmix_ignored_compile_inputs_hash() {
10915
12313
  ;;
10916
12314
  esac
10917
12315
  [[ -f "$real/$path" ]] || continue
10918
- printf 'ignored:%s:' "$path"
10919
- if ! fmix_hash_files "$real/$path"; then
10920
- rc=1
10921
- break
10922
- fi
12316
+ ignored_pairs+=("$path" "$real/$path")
10923
12317
  done <"$ignored_file"
12318
+ fmix_hash_paired_lines "ignored" \
12319
+ "${ignored_pairs[@]+"${ignored_pairs[@]}"}" || rc=1
10924
12320
  } >"$manifest"
10925
12321
  rm -f "$ignored_file"
10926
12322
  if (( rc != 0 )); then
@@ -11127,6 +12523,11 @@ fmix_invalidate_dependency_stamp() {
11127
12523
 
11128
12524
  fmix_invalidate_rejected_stamps() {
11129
12525
  local worktree="${1:-}" rc=0
12526
+ # Stamp removal mutates the shared session overlay. Failure paths call this
12527
+ # without retrying, so escalate directly and proceed under exclusive.
12528
+ if fmix_lock_any_shared_held; then
12529
+ fmix_lock_escalate_exclusive "rejected-stamp invalidation" || return 70
12530
+ fi
11130
12531
  fmix_invalidate_compile_stamp "$worktree" || rc=1
11131
12532
  fmix_invalidate_dependency_stamp "$worktree" || rc=1
11132
12533
  return "$rc"
@@ -11141,6 +12542,23 @@ fmix_require_stable_source() {
11141
12542
  || fmix_invalidate_rejected_stamps "$worktree"
11142
12543
  return 1
11143
12544
  }
12545
+ # Cheap stat-manifest pass first: per-file digests recorded at capture are
12546
+ # reused for stat-unchanged entries, so this revalidation re-reads nothing
12547
+ # while the snapshot is untouched. The verdict is still the captured
12548
+ # identity: any drift (or manifest anomaly) falls back to a full uncached
12549
+ # recompute before the fail-closed decision, so a source mutation between
12550
+ # capture and stamp publication can never pass as a warm hit.
12551
+ current=""
12552
+ if fmix_stat_hash_cache_use "$worktree"; then
12553
+ current="$(fmix_source_stability_identity \
12554
+ "$worktree" \
12555
+ "${FMIX_SOURCE_STABILITY_SELECTED_ARGS[@]+"${FMIX_SOURCE_STABILITY_SELECTED_ARGS[@]}"}")" \
12556
+ || current=""
12557
+ fmix_stat_hash_cache_done
12558
+ fi
12559
+ if [[ -n "$current" && "$current" == "$FMIX_SOURCE_STABILITY_IDENTITY" ]]; then
12560
+ return 0
12561
+ fi
11144
12562
  current="$(fmix_source_stability_identity \
11145
12563
  "$worktree" \
11146
12564
  "${FMIX_SOURCE_STABILITY_SELECTED_ARGS[@]+"${FMIX_SOURCE_STABILITY_SELECTED_ARGS[@]}"}")" \
@@ -11428,10 +12846,13 @@ fmix_compile_environment() {
11428
12846
  fmix_emit_environment_fingerprint MEESEEKS_HTML5EVER_BUILD 0
11429
12847
  fmix_emit_environment_fingerprint LOCAL_NATS "$NATS_HOST"
11430
12848
  fmix_emit_environment_fingerprint NATS_PORT "$NATS_PORT"
12849
+ fmix_emit_environment_fingerprint NATS_HOST "$NATS_HOST"
12850
+ fmix_emit_environment_fingerprint CT_NATS_HOST "$NATS_HOST"
12851
+ fmix_emit_environment_fingerprint NATS_URL "nats://${NATS_HOST}:${NATS_PORT}"
11431
12852
  printf '%s\n' "${compiler_vars[@]}" "$discovered" \
11432
12853
  | sed '/^$/d' | LC_ALL=C sort -u | while IFS= read -r name; do
11433
12854
  case "$name" in
11434
- MIX_ENV|DB_HOSTNAME|DB_PORT|DB_USER|DB_PASSWORD|SECRET_KEY_BASE|WORKER_NODE|ADMIN_NODE|ONPREM|MEESEEKS_HTML5EVER_BUILD|LOCAL_NATS|NATS_PORT)
12855
+ MIX_ENV|DB_HOSTNAME|DB_PORT|DB_USER|DB_PASSWORD|SECRET_KEY_BASE|WORKER_NODE|ADMIN_NODE|ONPREM|MEESEEKS_HTML5EVER_BUILD|LOCAL_NATS|NATS_PORT|NATS_HOST|CT_NATS_HOST|NATS_URL)
11435
12856
  # Effective fmix values were emitted above; ignore ambient copies.
11436
12857
  ;;
11437
12858
  MIX_BUILD_PATH|MIX_DEPS_PATH)
@@ -11808,7 +13229,7 @@ from pathlib import Path
11808
13229
 
11809
13230
  root = Path(sys.argv[1])
11810
13231
  h = hashlib.sha256()
11811
- h.update(b"fmix-compile-quick-guard-v1\n")
13232
+ h.update(b"fmix-compile-quick-guard-v2\n")
11812
13233
 
11813
13234
  def add_file(rel: str) -> None:
11814
13235
  p = root / rel
@@ -11828,9 +13249,12 @@ for rel in (
11828
13249
  ):
11829
13250
  add_file(rel)
11830
13251
 
11831
- # Newest mtime under compile roots — detects leaf edits without full content hash.
11832
- max_mtime = 0.0
11833
- file_count = 0
13252
+ # Per-file stat manifest (path -> dev,ino,mtime_ns,size) under compile roots.
13253
+ # Replaces the old single max-mtime: adds, removes, replaces, and leaf edits
13254
+ # all change the folded record set, while an unchanged stat tuple proves no
13255
+ # re-hash is needed. Sorted for cross-process determinism; a stat anomaly is
13256
+ # folded in as its own marker so it can never masquerade as stability.
13257
+ stat_records = []
11834
13258
  for rel in (
11835
13259
  "lib",
11836
13260
  "test/support",
@@ -11844,10 +13268,10 @@ for rel in (
11844
13268
  continue
11845
13269
  if base.is_file():
11846
13270
  try:
11847
- max_mtime = max(max_mtime, base.stat().st_mtime)
11848
- file_count += 1
13271
+ st = base.stat()
13272
+ stat_records.append(f"{rel}\0{st.st_dev},{st.st_ino},{st.st_mtime_ns},{st.st_size}\n")
11849
13273
  except OSError:
11850
- pass
13274
+ stat_records.append(f"{rel}\0stat-error\n")
11851
13275
  continue
11852
13276
  for dirpath, dirnames, filenames in os.walk(base):
11853
13277
  # Skip heavy/irrelevant trees
@@ -11855,15 +13279,16 @@ for rel in (
11855
13279
  for name in filenames:
11856
13280
  if not name.endswith((".ex", ".exs", ".heex", ".eex", ".leex", ".erl", ".hrl", ".c", ".h", ".rs", ".toml")):
11857
13281
  continue
13282
+ full = os.path.join(dirpath, name)
13283
+ rel_path = os.path.relpath(full, root)
11858
13284
  try:
11859
- st = os.stat(os.path.join(dirpath, name))
13285
+ st = os.stat(full)
13286
+ stat_records.append(f"{rel_path}\0{st.st_dev},{st.st_ino},{st.st_mtime_ns},{st.st_size}\n")
11860
13287
  except OSError:
11861
- continue
11862
- max_mtime = max(max_mtime, st.st_mtime)
11863
- file_count += 1
13288
+ stat_records.append(f"{rel_path}\0stat-error\n")
11864
13289
 
11865
- h.update(f"max_mtime={max_mtime:.6f}\n".encode())
11866
- h.update(f"file_count={file_count}\n".encode())
13290
+ for stat_record in sorted(stat_records):
13291
+ h.update(stat_record.encode())
11867
13292
  # Top-level deps dir signature (count + names + mtimes) — cheap vs full source_guard.
11868
13293
  deps = root # MIX_DEPS_PATH may be external; prefer env
11869
13294
  deps_path = os.environ.get("MIX_DEPS_PATH") or str(root / "deps")
@@ -11970,10 +13395,12 @@ fmix_compute_dirty_hash() {
11970
13395
  printf '%s\n' "$status"
11971
13396
  cat "$diff_file" || exit 1
11972
13397
  cat "$staged_file" || exit 1
13398
+ local -a untracked_pairs=()
11973
13399
  for file in "${untracked[@]+"${untracked[@]}"}"; do
11974
- printf 'untracked:%s:' "$file"
11975
- fmix_hash_files "$real/$file" || exit 1
13400
+ untracked_pairs+=("$file" "$real/$file")
11976
13401
  done
13402
+ fmix_hash_paired_lines "untracked" \
13403
+ "${untracked_pairs[@]+"${untracked_pairs[@]}"}" || exit 1
11977
13404
  ) >"$manifest"
11978
13405
  rc=$?
11979
13406
  rm -f "$untracked_file" "$diff_file" "$staged_file"
@@ -12003,6 +13430,7 @@ fmix_write_compile_stamp() {
12003
13430
  _fmix_write_compile_stamp_locked() {
12004
13431
  local worktree="$1" fingerprint="$2" real build_root guard dependency_guard stamp tmp quick_guard template_key
12005
13432
  local template_key tree_hash env_hash dirty_hash ignored_compile_hash source_stability_identity
13433
+ local stat_manifest
12006
13434
  real="$(fmix_realpath "$worktree")"
12007
13435
  build_root="$(fmix_compile_build_root "$real")"
12008
13436
  guard="$(fmix_compile_manifest_guard "$real")" || return 1
@@ -12019,6 +13447,7 @@ _fmix_write_compile_stamp_locked() {
12019
13447
  ignored_compile_hash="$(fmix_ignored_compile_inputs_hash "$real" 2>/dev/null)" \
12020
13448
  || return 1
12021
13449
  source_stability_identity="${FMIX_SOURCE_STABILITY_COMPILE_IDENTITY:-}"
13450
+ stat_manifest="$(fmix_stat_hash_cache_dump 2>/dev/null)" || stat_manifest=""
12022
13451
  stamp="$(fmix_compile_stamp_file "$real")"
12023
13452
  mkdir -p "$(dirname "$stamp")"
12024
13453
  tmp="$(mktemp "${stamp}.tmp.XXXXXX")" || return 1
@@ -12036,7 +13465,10 @@ _fmix_write_compile_stamp_locked() {
12036
13465
  "manifest_guard": $(fmix_json_escape "$guard"),
12037
13466
  "dependency_source_guard": $(fmix_json_escape "$dependency_guard"),
12038
13467
  "quick_guard": $(fmix_json_escape "$quick_guard"),
13468
+ "stat_manifest": $(fmix_json_escape "$stat_manifest"),
12039
13469
  "source_stability_identity": $(fmix_json_escape "$source_stability_identity"),
13470
+ "source_stability_run_identity": $(fmix_json_escape "${FMIX_SOURCE_STABILITY_IDENTITY:-}"),
13471
+ "source_stability_args_hash": $(fmix_json_escape "${FMIX_SOURCE_STABILITY_ARGS_HASH:-}"),
12040
13472
  "compiled_at": $(fmix_json_escape "$(fmix_now)")
12041
13473
  }
12042
13474
  EOF
@@ -12101,7 +13533,22 @@ fmix_try_compile_stamp_quick_hit() {
12101
13533
  || return 1
12102
13534
  # Git's status/index stat cache and the mtime quick guard are only early
12103
13535
  # rejectors. Admission is content-exact for the bounded compiler inputs.
12104
- current_fingerprint="$(fmix_compute_compile_fingerprint "$real")" || return 1
13536
+ # The recorded per-file stat manifest is an early rejector too: entries
13537
+ # whose stat tuple is unchanged reuse their recorded digest and only drift
13538
+ # is content-hashed. Any manifest anomaly (missing field on old stamps,
13539
+ # undecodable payload, stat/read errors) falls back to the full-hash path
13540
+ # below, so admission can never become weaker than a full recompute.
13541
+ current_fingerprint=""
13542
+ if fmix_stat_hash_cache_use "$real"; then
13543
+ if fmix_stat_hash_cache_seed "$(fmix_read_state "$stamp" stat_manifest)"; then
13544
+ current_fingerprint="$(fmix_compute_compile_fingerprint "$real")" \
13545
+ || current_fingerprint=""
13546
+ fi
13547
+ fmix_stat_hash_cache_done
13548
+ fi
13549
+ if [[ -z "$current_fingerprint" ]]; then
13550
+ current_fingerprint="$(fmix_compute_compile_fingerprint "$real")" || return 1
13551
+ fi
12105
13552
  [[ "$recorded_fingerprint" == "$current_fingerprint" ]] || return 1
12106
13553
  current_dependency_guard="$(fmix_dependency_source_guard "$real")" || return 1
12107
13554
  [[ "$recorded_dependency_guard" == "$current_dependency_guard" ]] || return 1
@@ -12736,6 +14183,9 @@ _fmix_run_compile() {
12736
14183
  MEESEEKS_HTML5EVER_BUILD=0 \
12737
14184
  LOCAL_NATS="$NATS_HOST" \
12738
14185
  NATS_PORT="$NATS_PORT" \
14186
+ NATS_HOST="$NATS_HOST" \
14187
+ CT_NATS_HOST="$NATS_HOST" \
14188
+ NATS_URL="nats://${NATS_HOST}:${NATS_PORT}" \
12739
14189
  POSTHOG_BACKEND_ENABLED="${POSTHOG_BACKEND_ENABLED:-false}" \
12740
14190
  POSTHOG_BROWSER_ENABLED="${POSTHOG_BROWSER_ENABLED:-false}" \
12741
14191
  mix compile $extra 2>&1
@@ -13021,6 +14471,19 @@ fmix_run_deps_get() {
13021
14471
  }
13022
14472
 
13023
14473
  fmix_ensure_compile() {
14474
+ local rc=0
14475
+ _fmix_ensure_compile_impl "$@" || rc=$?
14476
+ if (( rc == 200 )) && [[ "${FMIX_LOCK_GATE_RETRY:-}" == "1" ]]; then
14477
+ # Escalated mid-decision: re-verify the warm stamp state once under the
14478
+ # new exclusive hold before resolving dependencies or compiling.
14479
+ FMIX_LOCK_GATE_RETRY=""
14480
+ rc=0
14481
+ _fmix_ensure_compile_impl "$@" || rc=$?
14482
+ fi
14483
+ return "$rc"
14484
+ }
14485
+
14486
+ _fmix_ensure_compile_impl() {
13024
14487
  local worktree="$1" db_name="$2" compile_mode="${3:-incremental}"
13025
14488
  fmix_prepend_toolchain_paths
13026
14489
  FMIX_LAST_COMPILE_OUTCOME=""
@@ -13051,6 +14514,9 @@ fmix_ensure_compile() {
13051
14514
  FMIX_LAST_COMPILE_OUTCOME="stamp_hit_quick"
13052
14515
  return 0
13053
14516
  fi
14517
+ # Only the stamp quick-hit is provably read-only. Stamp writes, deps.get,
14518
+ # and compilation mutate the shared session overlay.
14519
+ fmix_lock_mutate_gate "dependency resolution or compilation" || return $?
13054
14520
 
13055
14521
  # The content/config stamp is authoritative for this exact realpath and
13056
14522
  # includes mix.lock, toolchain, compiler config, path deps, and Mix
@@ -13127,6 +14593,25 @@ fmix_ensure_compile() {
13127
14593
  return 0
13128
14594
  fi
13129
14595
 
14596
+ # Local app-compile CAS consumer: a content-exact shared application layer
14597
+ # can replace this compile outright. Any miss, corrupt generation, or
14598
+ # proof failure is discarded and falls through to the normal bounded
14599
+ # compile below — never a forced full rebuild. Opt out with FMIX_APP_CAS=0.
14600
+ local app_cas_rc=0
14601
+ if [[ "${FMIX_APP_CAS:-1}" != "0" && -n "$fingerprint" ]] \
14602
+ && fmix_try_install_app_compile_artifact "$worktree" "$fingerprint"; then
14603
+ fmix_info "Exact app compile artifact hit — skipping mix compile."
14604
+ FMIX_LAST_COMPILE_OUTCOME="app_cas_hit"
14605
+ return 0
14606
+ else
14607
+ app_cas_rc=$?
14608
+ case "$app_cas_rc" in
14609
+ 2|70|129|130|143)
14610
+ FMIX_LAST_COMPILE_OUTCOME="error"
14611
+ return "$app_cas_rc" ;;
14612
+ esac
14613
+ fi
14614
+
13130
14615
  fmix_info "Compiling app (incremental) …"
13131
14616
  local stamp_file log_file t0 t1 rc
13132
14617
  stamp_file="$(fmix_compile_stamp_file "$worktree")"
@@ -13203,19 +14688,41 @@ fmix_ensure_compile() {
13203
14688
  return 1
13204
14689
  fi
13205
14690
 
14691
+ # Stamp provenance: per-file digests recorded during this content hash are
14692
+ # persisted as the stamp's stat manifest so the next warm admission can
14693
+ # re-stat and content-hash only drift. Reuse is stat-validated (ctime
14694
+ # keyed), so anything mutated earlier in this run is re-hashed here, and
14695
+ # the requirement checks still fail closed on any source change.
14696
+ fmix_stat_hash_cache_use "$worktree" || true
13206
14697
  fingerprint="$(fmix_compute_compile_fingerprint "$worktree")" || fingerprint=""
13207
14698
  if [[ -z "$fingerprint" ]] \
13208
14699
  || ! fmix_require_stable_source "$worktree" "compile stamp construction" 1 \
13209
14700
  || ! fmix_write_compile_stamp "$worktree" "$fingerprint"; then
14701
+ fmix_stat_hash_cache_done
13210
14702
  fmix_invalidate_rejected_stamps "$worktree"
13211
14703
  fmix_error "Compile succeeded, but final content/config provenance could not be recorded."
13212
14704
  FMIX_LAST_COMPILE_OUTCOME="error"
13213
14705
  return 1
13214
14706
  fi
13215
14707
  if ! fmix_require_stable_source "$worktree" "compile stamp publication" 1; then
14708
+ fmix_stat_hash_cache_done
13216
14709
  FMIX_LAST_COMPILE_OUTCOME="error"
13217
14710
  return 1
13218
14711
  fi
14712
+ # Local app-compile CAS producer: best-effort publication of the proven
14713
+ # application layer for future worktrees. Ordinary publication failures
14714
+ # warn and never fail the run; interrupted/fatal outcomes still surface.
14715
+ local app_publish_rc=0
14716
+ if [[ "${FMIX_APP_CAS:-1}" != "0" ]]; then
14717
+ fmix_publish_app_compile_artifact "$worktree" "$fingerprint" \
14718
+ || app_publish_rc=$?
14719
+ case "$app_publish_rc" in
14720
+ 0) ;;
14721
+ 2|70|129|130|143) return "$app_publish_rc" ;;
14722
+ *) fmix_warn "Optional app compile artifact publication failed; keeping the proven session." ;;
14723
+ esac
14724
+ fi
14725
+ fmix_stat_hash_cache_done
13219
14726
  return 0
13220
14727
  }
13221
14728
 
@@ -13540,6 +15047,50 @@ cmd_setup() {
13540
15047
  fmix_warn "Could not backfill the exact dependency artifact during setup."
13541
15048
  fi
13542
15049
  fi
15050
+ # Explicit setup is also the maintenance/backfill lane for the local
15051
+ # app-compile CAS. Publication remains best-effort: the session's proven
15052
+ # application layer is authoritative on failure.
15053
+ local setup_app_fingerprint setup_app_lane setup_app_artifact
15054
+ local setup_app_publication_rc=0
15055
+ if [[ "${FMIX_APP_CAS:-1}" != "0" ]]; then
15056
+ setup_app_fingerprint="$(fmix_compute_compile_fingerprint \
15057
+ "$real_worktree" 2>/dev/null)" || setup_app_fingerprint=""
15058
+ if [[ -n "$setup_app_fingerprint" ]] \
15059
+ && fmix_compile_stamp_matches "$real_worktree" "$setup_app_fingerprint"; then
15060
+ setup_app_lane="$(fmix_dependency_lane_fingerprint \
15061
+ "$real_worktree" 2>/dev/null)" || setup_app_lane=""
15062
+ setup_app_artifact="$(fmix_dependency_artifact_dir \
15063
+ "$setup_app_lane" "$setup_app_fingerprint" app 2>/dev/null)" \
15064
+ || setup_app_artifact=""
15065
+ if [[ -n "$setup_app_artifact" ]] \
15066
+ && fmix_app_compile_artifact_quick_ready \
15067
+ "$setup_app_artifact" "$setup_app_lane" "$setup_app_fingerprint"; then
15068
+ fmix_touch_app_compile_artifact_access \
15069
+ "$setup_app_lane" "$setup_app_fingerprint" \
15070
+ >/dev/null 2>&1 || setup_app_publication_rc=$?
15071
+ else
15072
+ fmix_publish_app_compile_artifact \
15073
+ "$real_worktree" "$setup_app_fingerprint" \
15074
+ || setup_app_publication_rc=$?
15075
+ fi
15076
+ if (( setup_app_publication_rc != 0 )); then
15077
+ if fmix_lock_failure_is_fatal "$setup_app_publication_rc"; then
15078
+ fmix_command_lock_finish "$lock_name" "$setup_app_publication_rc"
15079
+ return $?
15080
+ fi
15081
+ case "$setup_app_publication_rc" in
15082
+ 2|129|130|143)
15083
+ fmix_command_lock_finish "$lock_name" "$setup_app_publication_rc"
15084
+ return $? ;;
15085
+ esac
15086
+ if [[ "${FMIX_ARTIFACT_LEASE_RELEASE_FAILED:-0}" != "0" ]]; then
15087
+ fmix_command_lock_finish "$lock_name" "$setup_app_publication_rc"
15088
+ return $?
15089
+ fi
15090
+ fmix_warn "Could not backfill the exact app compile artifact during setup."
15091
+ fi
15092
+ fi
15093
+ fi
13543
15094
  fmix_ensure_db "$real_worktree" "$db_name" "$rebuild_existing" "$allow_structure_build" 1 "$force_from_zero" || {
13544
15095
  local operation_rc=$?
13545
15096
  fmix_command_lock_finish "$lock_name" "$operation_rc" "$FMIX_LAST_DB_MAINTENANCE_MIX_FAILURE"
@@ -13665,6 +15216,10 @@ fmix_ensure_chromium() {
13665
15216
  # (quotes, backslashes, $) can't break or inject into the wrapper script.
13666
15217
  safe_chrome="${chrome//\'/\'\\\'\'}"
13667
15218
  if [[ ! -x "$shim" ]] || ! grep -qF "exec '$safe_chrome'" "$shim" 2>/dev/null; then
15219
+ # Installing the shim writes shared FMIX_HOME state; escalate first.
15220
+ if fmix_lock_any_shared_held; then
15221
+ fmix_lock_escalate_exclusive "Chromium shim installation" || return 1
15222
+ fi
13668
15223
  printf '#!/bin/sh\nexec '\''%s'\'' "$@"\n' "$safe_chrome" >"$shim" || return 1
13669
15224
  chmod +x "$shim" || return 1
13670
15225
  fi
@@ -13889,7 +15444,7 @@ cmd_test() {
13889
15444
  --) found_sep=1; shift; break ;;
13890
15445
  *)
13891
15446
  if [[ "$run_mode" == "coverage" ]]; then
13892
- fmix_error "Unknown option: $1. Usage: fmix coverage [--worktree <path>] [--cache-base <N.N.N-stable>] --base <git-ref> [--source <lib/**/*.ex>] [--threshold 80] -- <test paths>"
15447
+ fmix_error "Unknown option: $1. Usage: fmix coverage [--worktree <path>] [--cache-base <N.N.N-stable>] [--no-auto-setup] --base <git-ref> [--source <lib/**/*.ex>] [--threshold 80] -- <test paths>"
13893
15448
  else
13894
15449
  fmix_error "Unknown option: $1. Usage: fmix test [--worktree <path>] [--cache-base <N.N.N-stable>] [--unit] -- <mix test args>"
13895
15450
  fi
@@ -13934,7 +15489,7 @@ cmd_test() {
13934
15489
  done
13935
15490
  fi
13936
15491
  local coverage_source
13937
- for coverage_source in "${coverage_sources[@]}"; do
15492
+ for coverage_source in ${coverage_sources[@]+"${coverage_sources[@]}"}; do
13938
15493
  if [[ "$coverage_source" != lib/*.ex ]]; then
13939
15494
  fmix_error "--source must name a lib/**/*.ex file: $coverage_source"
13940
15495
  return 2
@@ -14029,11 +15584,28 @@ cmd_test() {
14029
15584
  fmix_run_telemetry_phase "preflight"
14030
15585
  fmix_emit_phase_change "preflight" "completed"
14031
15586
 
14032
- # Per-worktree lock (serializes concurrent runs in same worktree)
14033
- local lock_name
15587
+ # Per-worktree lock (serializes concurrent runs in same worktree).
15588
+ # Shared (read) mode is used ONLY when the whole run is provably read-only
15589
+ # w.r.t. shared state: (a) artifacts resolve warm without mutation, (b)
15590
+ # compile is a stamp quick-hit, (c) the scratch DB exists and is
15591
+ # migration-current, and (d) this run mode writes no receipts/stamps that
15592
+ # mutate shared indexes (test-lane receipts are per-worktree; see
15593
+ # docs/fmix.md). Any uncertainty falls back to the exclusive lock, and a
15594
+ # shared run that discovers a mutation escalates cleanly before mutating.
15595
+ local lock_name lock_mode="exclusive"
14034
15596
  lock_name="$(fmix_execution_lock_name "$real_worktree")"
15597
+ if fmix_session_lock_split_enabled \
15598
+ && [[ "$run_mode" == "test" ]] \
15599
+ && [[ -z "$cache_base" ]] \
15600
+ && fmix_run_probe_readonly "$real_worktree" "$template_key" "$db_name"; then
15601
+ lock_mode="shared"
15602
+ fmix_info "Session lock: shared (provably read-only warm run)."
15603
+ else
15604
+ fmix_info "Session lock: exclusive."
15605
+ fi
14035
15606
  fmix_emit_phase_change "lock" "started"
14036
- fmix_lock_acquire "$lock_name" "$FMIX_WORKTREE_LOCK_TIMEOUT" || {
15607
+ fmix_lock_acquire "$lock_name" "$FMIX_WORKTREE_LOCK_TIMEOUT" \
15608
+ "test run" 0 "$lock_mode" || {
14037
15609
  local lock_rc=$?
14038
15610
  fmix_emit_phase_change "lock" "failed"
14039
15611
  fmix_run_telemetry_finish "$lock_rc"
@@ -14049,11 +15621,26 @@ cmd_test() {
14049
15621
  local FMIX_SOURCE_STABILITY_REQUIRED=1
14050
15622
  local FMIX_SOURCE_STABILITY_IDENTITY=""
14051
15623
  local FMIX_SOURCE_STABILITY_COMPILE_IDENTITY=""
15624
+ local FMIX_SOURCE_STABILITY_ARGS_HASH=""
14052
15625
  local -a FMIX_SOURCE_STABILITY_SELECTED_ARGS=("${mix_args[@]+"${mix_args[@]}"}")
15626
+ FMIX_SOURCE_STABILITY_ARGS_HASH="$(printf '%s\0' "${FMIX_SOURCE_STABILITY_SELECTED_ARGS[@]+"${FMIX_SOURCE_STABILITY_SELECTED_ARGS[@]}"}" | fmix_hash_stdin)" \
15627
+ || FMIX_SOURCE_STABILITY_ARGS_HASH=""
15628
+ # Stat-validated capture: per-file digests persisted in the compile stamp
15629
+ # (bound to these exact selected args) are reused for stat-unchanged
15630
+ # entries; drift is content-hashed fresh. The identity itself is persisted
15631
+ # in the next compile stamp, and every fmix_require_stable_source
15632
+ # checkpoint revalidates it through the same stat manifest.
15633
+ fmix_stat_hash_cache_use "$real_worktree" || true
15634
+ if [[ -n "$FMIX_SOURCE_STABILITY_ARGS_HASH" ]] \
15635
+ && [[ "$(fmix_read_state "$(fmix_compile_stamp_file "$real_worktree")" source_stability_args_hash 2>/dev/null)" == "$FMIX_SOURCE_STABILITY_ARGS_HASH" ]]; then
15636
+ fmix_stat_hash_cache_seed "$(fmix_read_state "$(fmix_compile_stamp_file "$real_worktree")" stat_manifest 2>/dev/null)" \
15637
+ || true
15638
+ fi
14053
15639
  FMIX_SOURCE_STABILITY_IDENTITY="$(fmix_source_stability_identity \
14054
15640
  "$real_worktree" \
14055
15641
  "${FMIX_SOURCE_STABILITY_SELECTED_ARGS[@]+"${FMIX_SOURCE_STABILITY_SELECTED_ARGS[@]}"}")" \
14056
15642
  || {
15643
+ fmix_stat_hash_cache_done
14057
15644
  fmix_error "Could not capture a source-stability identity after acquiring the worktree lock."
14058
15645
  fmix_invalidate_rejected_stamps "$real_worktree"
14059
15646
  local source_rc=1
@@ -14064,6 +15651,7 @@ cmd_test() {
14064
15651
  FMIX_SOURCE_STABILITY_COMPILE_IDENTITY="$(
14065
15652
  fmix_source_stability_compile_identity "$real_worktree"
14066
15653
  )" || {
15654
+ fmix_stat_hash_cache_done
14067
15655
  fmix_error "Could not capture compile-source identity after acquiring the worktree lock."
14068
15656
  fmix_invalidate_rejected_stamps "$real_worktree"
14069
15657
  local source_rc=1
@@ -14071,6 +15659,7 @@ cmd_test() {
14071
15659
  fmix_run_telemetry_finish "$source_rc"
14072
15660
  return "$source_rc"
14073
15661
  }
15662
+ fmix_stat_hash_cache_done
14074
15663
  if ! fmix_require_stable_source "$real_worktree" "source identity capture" 1; then
14075
15664
  local source_rc=1
14076
15665
  fmix_command_lock_finish "$lock_name" "$source_rc" || source_rc=$?
@@ -14201,7 +15790,7 @@ cmd_test() {
14201
15790
  local mig_stamp schema_key
14202
15791
  schema_key="$FMIX_ACTIVE_DB_SCHEMA_KEY"
14203
15792
  mig_stamp="$(fmix_migration_stamp "$real_worktree")"
14204
- fmix_write_worktree_state "$real_worktree" "$template_key" "$db_name" "$mig_stamp" "$(fmix_now)" "$schema_key" "$FMIX_ACTIVE_DB_BASE_ID" "$FMIX_ACTIVE_DB_SOURCE_KEY" || {
15793
+ fmix_publish_run_worktree_state "$real_worktree" "$template_key" "$db_name" "$mig_stamp" "$schema_key" "$FMIX_ACTIVE_DB_BASE_ID" "$FMIX_ACTIVE_DB_SOURCE_KEY" || {
14205
15794
  local operation_rc=$?
14206
15795
  fmix_command_lock_finish "$lock_name" "$operation_rc" || operation_rc=$?
14207
15796
  fmix_run_telemetry_finish "$operation_rc"
@@ -14301,6 +15890,9 @@ cmd_test() {
14301
15890
  DB_TEST_POOL_SIZE=30
14302
15891
  LOCAL_NATS="$NATS_HOST"
14303
15892
  NATS_PORT="$NATS_PORT"
15893
+ NATS_HOST="$NATS_HOST"
15894
+ CT_NATS_HOST="$NATS_HOST"
15895
+ NATS_URL="nats://${NATS_HOST}:${NATS_PORT}"
14304
15896
  WORKER_NODE=TRUE
14305
15897
  ADMIN_NODE=TRUE
14306
15898
  ONPREM=TRUE
@@ -14369,7 +15961,7 @@ end
14369
15961
  '
14370
15962
  local -a coverage_source_args=()
14371
15963
  local coverage_source
14372
- for coverage_source in "${coverage_sources[@]}"; do
15964
+ for coverage_source in ${coverage_sources[@]+"${coverage_sources[@]}"}; do
14373
15965
  coverage_source_args+=(--source "$coverage_source")
14374
15966
  done
14375
15967
  exec env "${common_env[@]}" \
@@ -14963,6 +16555,9 @@ cmd_task() {
14963
16555
  DB_NAME="$task_db_name" \
14964
16556
  LOCAL_NATS="$NATS_HOST" \
14965
16557
  NATS_PORT="$NATS_PORT" \
16558
+ NATS_HOST="$NATS_HOST" \
16559
+ CT_NATS_HOST="$NATS_HOST" \
16560
+ NATS_URL="nats://${NATS_HOST}:${NATS_PORT}" \
14966
16561
  WORKER_NODE=TRUE \
14967
16562
  ADMIN_NODE=TRUE \
14968
16563
  ONPREM=TRUE \
@@ -15196,6 +16791,13 @@ fmix_infra_host_is_local() {
15196
16791
  esac
15197
16792
  }
15198
16793
 
16794
+ fmix_nats_host_is_local() {
16795
+ case "$NATS_HOST" in
16796
+ localhost|127.0.0.1|::1) return 0 ;;
16797
+ *) return 1 ;;
16798
+ esac
16799
+ }
16800
+
15199
16801
  fmix_write_ensure_compose() {
15200
16802
  local dir="$FMIX_HOME/infra"
15201
16803
  mkdir -p "$dir" || return 1
@@ -15260,7 +16862,11 @@ YAML
15260
16862
 
15261
16863
  fmix_start_existing_ct_infra() {
15262
16864
  local name started=0
15263
- for name in "${FMIX_INFRA_PROJECT}-postgres-1" "${FMIX_INFRA_PROJECT}-nats-1"; do
16865
+ local -a targets=("${FMIX_INFRA_PROJECT}-postgres-1")
16866
+ if fmix_nats_host_is_local; then
16867
+ targets+=("${FMIX_INFRA_PROJECT}-nats-1")
16868
+ fi
16869
+ for name in "${targets[@]}"; do
15264
16870
  if docker inspect "$name" >/dev/null 2>&1; then
15265
16871
  docker start "$name" >/dev/null 2>&1 || true
15266
16872
  started=1
@@ -15271,7 +16877,11 @@ fmix_start_existing_ct_infra() {
15271
16877
 
15272
16878
  fmix_compose_up_ensure() {
15273
16879
  fmix_write_ensure_compose || return 1
15274
- docker compose -p "$FMIX_INFRA_PROJECT" -f "$FMIX_HOME/infra/compose-ensure.yml" up -d postgres nats
16880
+ local -a services=(postgres)
16881
+ if fmix_nats_host_is_local; then
16882
+ services+=(nats)
16883
+ fi
16884
+ docker compose -p "$FMIX_INFRA_PROJECT" -f "$FMIX_HOME/infra/compose-ensure.yml" up -d "${services[@]}"
15275
16885
  }
15276
16886
 
15277
16887
  fmix_wait_infra() {
@@ -15282,6 +16892,9 @@ fmix_wait_infra() {
15282
16892
  if fmix_infra_ready; then
15283
16893
  return 0
15284
16894
  fi
16895
+ if ! fmix_nats_host_is_local && fmix_infra_postgres_ready && ! fmix_infra_nats_ready; then
16896
+ return 1
16897
+ fi
15285
16898
  sleep 1
15286
16899
  done
15287
16900
  return 1
@@ -15389,6 +17002,11 @@ fmix_ensure_infra() {
15389
17002
  return 0
15390
17003
  fi
15391
17004
 
17005
+ if ! fmix_nats_host_is_local && fmix_infra_postgres_ready && ! fmix_infra_nats_ready; then
17006
+ fmix_error "Remote/Tailnet NATS $NATS_HOST:$NATS_PORT is not reachable. Check Tailscale connectivity or set FMIX_NATS_HOST=localhost."
17007
+ return 1
17008
+ fi
17009
+
15392
17010
  if [[ "$FMIX_ENSURE" != "1" ]]; then
15393
17011
  fmix_error "Postgres/NATS not ready at $DB_HOST:$DB_PORT / $NATS_HOST:$NATS_PORT (FMIX_ENSURE=0)."
15394
17012
  return 1
@@ -15426,20 +17044,40 @@ fmix_ensure_infra_locked() {
15426
17044
  echo " [OK] infra ready postgres $DB_HOST:$DB_PORT nats $NATS_HOST:$NATS_PORT"
15427
17045
  return 0
15428
17046
  fi
17047
+ if ! fmix_nats_host_is_local && fmix_infra_postgres_ready && ! fmix_infra_nats_ready; then
17048
+ fmix_error "Remote/Tailnet NATS $NATS_HOST:$NATS_PORT is not reachable. Check Tailscale connectivity or set FMIX_NATS_HOST=localhost."
17049
+ return 1
17050
+ fi
15429
17051
  fmix_infra_has_headroom || return 75
15430
- echo " starting shared $FMIX_INFRA_PROJECT (postgres + nats)..."
17052
+ if fmix_nats_host_is_local; then
17053
+ echo " starting shared $FMIX_INFRA_PROJECT (postgres + nats)..."
17054
+ else
17055
+ echo " starting shared $FMIX_INFRA_PROJECT (postgres)..."
17056
+ fi
15431
17057
  fmix_start_existing_ct_infra || true
15432
17058
  if fmix_wait_infra; then
15433
17059
  echo " [OK] infra ready postgres $DB_HOST:$DB_PORT nats $NATS_HOST:$NATS_PORT"
15434
17060
  return 0
15435
17061
  fi
17062
+ if ! fmix_nats_host_is_local && fmix_infra_postgres_ready && ! fmix_infra_nats_ready; then
17063
+ fmix_error "Remote/Tailnet NATS $NATS_HOST:$NATS_PORT is not reachable. Check Tailscale connectivity or set FMIX_NATS_HOST=localhost."
17064
+ return 1
17065
+ fi
15436
17066
  # Another producer may allocate while existing services are warming.
15437
17067
  fmix_infra_has_headroom || return 75
15438
17068
  if ! fmix_compose_up_ensure; then
15439
- fmix_error "docker compose could not start $FMIX_INFRA_PROJECT postgres/nats"
17069
+ if fmix_nats_host_is_local; then
17070
+ fmix_error "docker compose could not start $FMIX_INFRA_PROJECT postgres/nats"
17071
+ else
17072
+ fmix_error "docker compose could not start $FMIX_INFRA_PROJECT postgres"
17073
+ fi
15440
17074
  return 1
15441
17075
  fi
15442
17076
  if ! fmix_wait_infra; then
17077
+ if ! fmix_nats_host_is_local && fmix_infra_postgres_ready && ! fmix_infra_nats_ready; then
17078
+ fmix_error "Remote/Tailnet NATS $NATS_HOST:$NATS_PORT is not reachable. Check Tailscale connectivity or set FMIX_NATS_HOST=localhost."
17079
+ return 1
17080
+ fi
15443
17081
  fmix_error "Shared infra did not become ready within ${FMIX_ENSURE_TIMEOUT}s at $DB_HOST:$DB_PORT / $NATS_HOST:$NATS_PORT"
15444
17082
  return 1
15445
17083
  fi
@@ -15577,9 +17215,17 @@ cmd_doctor() {
15577
17215
 
15578
17216
  # NATS TCP
15579
17217
  if nc -z "$NATS_HOST" "$NATS_PORT" 2>/dev/null; then
15580
- echo " [OK] NATS TCP $NATS_HOST:$NATS_PORT"
17218
+ if ! fmix_nats_host_is_local; then
17219
+ echo " [OK] nats: $NATS_HOST:$NATS_PORT (remote/tailnet)"
17220
+ else
17221
+ echo " [OK] NATS TCP $NATS_HOST:$NATS_PORT"
17222
+ fi
15581
17223
  else
15582
- echo " [WARN] NATS not reachable at $NATS_HOST:$NATS_PORT — run: ./infra.sh up (some tests may fail)"
17224
+ if ! fmix_nats_host_is_local; then
17225
+ echo " [WARN] NATS not reachable at $NATS_HOST:$NATS_PORT (remote/tailnet) — check Tailscale connectivity or set FMIX_NATS_HOST=localhost"
17226
+ else
17227
+ echo " [WARN] NATS not reachable at $NATS_HOST:$NATS_PORT — run: ./infra.sh up (some tests may fail)"
17228
+ fi
15583
17229
  fi
15584
17230
 
15585
17231
  # Headless Chromium for ChromicPDF-backed reporting suites (API-1184).
@@ -16518,7 +18164,7 @@ cmd_gc_artifact_retirement() {
16518
18164
  [[ -n "$mode" ]] || return 2
16519
18165
  case "$mode" in
16520
18166
  adopt|plan|pin)
16521
- [[ "$artifact_id" =~ ^(template|template-v2):[0-9a-f]{16}$|^(dependency|dependency-v2):[0-9a-f]{64}/[0-9a-f]{64}$ ]] || return 2 ;;
18167
+ [[ "$artifact_id" =~ ^(template|template-v2):[0-9a-f]{16}$|^(dependency|dependency-v2|app-compile-v2):[0-9a-f]{64}/[0-9a-f]{64}$ ]] || return 2 ;;
16522
18168
  retire-plan|resume)
16523
18169
  [[ "$pin_id" =~ ^[0-9a-f]{64}$ ]] || return 2 ;;
16524
18170
  unpin) [[ "$pin_id" =~ ^[0-9a-f]{32}$ ]] || return 2 ;;
@@ -16531,7 +18177,8 @@ cmd_gc_artifact_retirement() {
16531
18177
  fi
16532
18178
  if [[ "$mode" == "auto-expire" || "$mode" == "unpin" \
16533
18179
  || "$mode" == "retire-plan" || "$mode" == "resume" \
16534
- || "$artifact_id" == template-v2:* || "$artifact_id" == dependency-v2:* ]]; then
18180
+ || "$artifact_id" == template-v2:* || "$artifact_id" == dependency-v2:* \
18181
+ || "$artifact_id" == app-compile-v2:* ]]; then
16535
18182
  local handoff_reason
16536
18183
  handoff_reason="$(fmix_artifact_v2_managed_entrypoint 2>&1)" || {
16537
18184
  case "$handoff_reason" in
@@ -16545,12 +18192,13 @@ cmd_gc_artifact_retirement() {
16545
18192
  fmix_prepare_command_home || return 1
16546
18193
  dependency_ttl="$(fmix_effective_artifact_ttl_hours dependency)" || return 2
16547
18194
  template_ttl="$(fmix_effective_artifact_ttl_hours template)" || return 2
18195
+ auto_expire_max="$(fmix_auto_expire_batch_limit)"
16548
18196
  py_bin="$(fmix_python_bin)" || return 1
16549
18197
  runner="$(fmix_realpath "${BASH_SOURCE[0]}")" || return 1
16550
- "$py_bin" -I -B - "$FMIX_HOME" "$runner" "$0" "$$" "$mode" "$artifact_id" "$consumer" "$pin_id" "$dependency_ttl" "$template_ttl" <<'PY'
18198
+ "$py_bin" -I -B - "$FMIX_HOME" "$runner" "$0" "$$" "$mode" "$artifact_id" "$consumer" "$pin_id" "$dependency_ttl" "$template_ttl" "$auto_expire_max" <<'PY'
16551
18199
  import contextlib, ctypes, datetime, hashlib, json, os, re, select, stat, subprocess, sys, time
16552
18200
 
16553
- home, runner, entrypoint, entrypoint_pid, mode, artifact_id, consumer, object_id, dep_ttl, template_ttl = sys.argv[1:]
18201
+ home, runner, entrypoint, entrypoint_pid, mode, artifact_id, consumer, object_id, dep_ttl, template_ttl, auto_expire_max = sys.argv[1:]
16554
18202
  home = os.path.abspath(home)
16555
18203
  entrypoint = os.path.abspath(entrypoint)
16556
18204
  entrypoint_pid = int(entrypoint_pid)
@@ -16584,6 +18232,9 @@ def bounded_names(fd):
16584
18232
  def fail(reason, status=2):
16585
18233
  print(json.dumps({"schema":"fmix-artifact-retirement.v2","status":"held","reason":reason},sort_keys=True))
16586
18234
  raise SystemExit(status)
18235
+ if not re.fullmatch(r"[0-9]{1,4}", auto_expire_max) or not 1 <= int(auto_expire_max) <= 10:
18236
+ fail("invalid_auto_expire_batch_limit")
18237
+ auto_expire_max = int(auto_expire_max)
16587
18238
  def canonical(value):
16588
18239
  return json.dumps(value,sort_keys=True,separators=(",",":"),ensure_ascii=True).encode()
16589
18240
  def identity(st):
@@ -16830,10 +18481,13 @@ def read_json(rel):
16830
18481
  return strict_load(raw),raw,identity_value
16831
18482
  def artifact_id_for(row):
16832
18483
  pool=row["pool"]
16833
- prefix="template-v2" if pool=="template-v2" else "template" if pool=="template" else "dependency-v2" if pool=="dependency-v2" else "dependency"
18484
+ prefix=("template-v2" if pool=="template-v2" else "template" if pool=="template"
18485
+ else "app-compile-v2" if pool=="app-compile-v2"
18486
+ else "dependency-v2" if pool=="dependency-v2" else "dependency")
16834
18487
  return prefix+":"+row["key"] if pool.startswith("template") else prefix+":"+row["lane"]+"/"+row["key"]
16835
18488
  def parse_artifact_id(value):
16836
18489
  for prefix,pool in (("template-v2","template-v2"),("template","template"),
18490
+ ("app-compile-v2","app-compile-v2"),
16837
18491
  ("dependency-v2","dependency-v2"),("dependency","dependency")):
16838
18492
  if pool.startswith("template"):
16839
18493
  match=re.fullmatch(prefix+r":([0-9a-f]{16})",value or "")
@@ -16842,13 +18496,15 @@ def parse_artifact_id(value):
16842
18496
  match=re.fullmatch(prefix+r":([0-9a-f]{64})/([0-9a-f]{64})",value or "")
16843
18497
  if match: return pool,match.group(1),match.group(2)
16844
18498
  raise ValueError("invalid artifact identifier")
16845
- def pool_kind(pool): return "template" if pool.startswith("template") else "dependency"
18499
+ def pool_kind(pool):
18500
+ return "template" if pool.startswith("template") else "app" if pool.startswith("app") else "dependency"
16846
18501
  def pool_v2(pool): return pool.endswith("-v2")
16847
18502
  def cache_rel(pool,lane,key):
16848
18503
  if pool=="template": return "templates/"+key
16849
18504
  if pool=="template-v2": return "artifacts/v2/templates/"+key
16850
18505
  if pool=="dependency": return "dependency-artifacts/v1/"+lane+"/"+key
16851
18506
  if pool=="dependency-v2": return "artifacts/v2/dependencies/"+lane+"/"+key
18507
+ if pool=="app-compile-v2": return "artifacts/v2/app-compiles/"+lane+"/"+key
16852
18508
  raise ValueError("unknown artifact pool")
16853
18509
  def candidate_row(report,artifact_id):
16854
18510
  pool,lane,key=parse_artifact_id(artifact_id)
@@ -16864,7 +18520,7 @@ def candidate_row(report,artifact_id):
16864
18520
  or not all(isinstance(v,str) for v in row["references"]) or type(row.get("references_truncated")) is not bool):
16865
18521
  raise ValueError("candidate inventory schema incomplete")
16866
18522
  if pool_kind(pool)=="template" and row["lane"] is not None: raise ValueError("template lane schema")
16867
- if pool_kind(pool)=="dependency" and not hexkey(row["lane"],64): raise ValueError("dependency lane schema")
18523
+ if pool_kind(pool)!="template" and not hexkey(row["lane"],64): raise ValueError("dependency lane schema")
16868
18524
  expected=home+"/"+cache_rel(pool,lane,key)
16869
18525
  if row.get("path")!=expected: raise ValueError("candidate path identity mismatch")
16870
18526
  if pool_v2(pool): require_managed_handoff()
@@ -16886,7 +18542,10 @@ def candidate_holds(report,row):
16886
18542
  if row.get("status")!="held": holds.add("unexpected_inventory_state")
16887
18543
  if holds: raise ValueError(",".join(sorted(holds)))
16888
18544
  def lock_name(pool,lane,key):
16889
- return "build-"+key if pool_kind(pool)=="template" else "dependency-artifact-"+lane[:16]+"-"+key[:16]
18545
+ kind=pool_kind(pool)
18546
+ if kind=="template": return "build-"+key
18547
+ if kind=="app": return "app-compile-"+lane[:16]+"-"+key[:16]
18548
+ return "dependency-artifact-"+lane[:16]+"-"+key[:16]
16890
18549
  LEASE_PROVIDER = """source "$FMIX_RETIREMENT_PROVIDER_RUNNER" || exit 70
16891
18550
  lock_name="$1"
16892
18551
  fmix_lock_acquire "$lock_name" 0 "artifact retirement" 1 || exit $?
@@ -16970,14 +18629,19 @@ def read_meta(row):
16970
18629
  if sha(raw)!=row.get("metadata_sha256"): raise ValueError("metadata digest changed")
16971
18630
  meta=strict_load(raw)
16972
18631
  dep_v1={"schema","lane","dependency_fingerprint","producer_sha","source_clean","manifest_sha256","built_at"}
18632
+ app_v1={"schema","lane","compile_fingerprint","producer_sha","source_clean","manifest_sha256","built_at"}
16973
18633
  template_v1={"schema","status","template_key","manifest_sha256","built_at","toolchain","source_commit"}
16974
- expected=(dep_v1 if kind=="dependency" else template_v1)
18634
+ expected=(app_v1 if kind=="app" else dep_v1 if kind=="dependency" else template_v1)
16975
18635
  if v2: expected=expected|{"producer_runner_sha256","consumer_protocol"}
16976
18636
  if not isinstance(meta,dict) or set(meta)!=expected or meta.get("schema")!=("2" if v2 else "1"):
16977
18637
  raise ValueError("metadata schema")
16978
18638
  if kind=="template" and (meta["status"]!="complete" or meta["template_key"]!=key
16979
18639
  or not meta["toolchain"] or not re.fullmatch(r"[0-9a-f]{7,40}",meta["source_commit"])):
16980
18640
  raise ValueError("template identity")
18641
+ if kind=="app" and (meta["lane"]!=lane or meta["compile_fingerprint"]!=key
18642
+ or not re.fullmatch(r"[0-9a-f]{40}",meta["producer_sha"])
18643
+ or meta["source_clean"] not in ("true","false")):
18644
+ raise ValueError("app compile identity")
16981
18645
  if kind=="dependency" and (meta["lane"]!=lane or meta["dependency_fingerprint"]!=key
16982
18646
  or not re.fullmatch(r"[0-9a-f]{40}",meta["producer_sha"])
16983
18647
  or meta["source_clean"] not in ("true","false")):
@@ -16996,6 +18660,7 @@ def read_meta(row):
16996
18660
  def last_access(row,pool,lane,key,built):
16997
18661
  if pool_v2(pool):
16998
18662
  rel=("artifact-access/v2/templates/"+key if pool_kind(pool)=="template"
18663
+ else "artifact-access/v2/app-compiles/"+lane+"/"+key if pool_kind(pool)=="app"
16999
18664
  else "artifact-access/v2/dependencies/"+lane+"/"+key)
17000
18665
  else:
17001
18666
  rel=("template-access/"+key if pool_kind(pool)=="template"
@@ -17055,18 +18720,27 @@ def verify_tree(row,base_rel=None,allow_owner_write=False):
17055
18720
  os.close(rootfd_cache); raise ValueError("candidate identity incomplete or changed")
17056
18721
  try:
17057
18722
  names=bounded_names(rootfd_cache)
17058
- if names!=["_build","deps","manifest.sha256","manifest.tsv","meta.json"]:
18723
+ expected_names=(["_build","manifest.sha256","manifest.tsv","meta.json"] if kind=="app"
18724
+ else ["_build","deps","manifest.sha256","manifest.tsv","meta.json"])
18725
+ if names!=expected_names:
17059
18726
  raise ValueError("unexpected cache contents")
17060
18727
  meta_raw,meta_id=read_file(base_rel+"/meta.json",1024*1024)
17061
18728
  meta=strict_load(meta_raw)
18729
+ app_fields={"schema","lane","compile_fingerprint","producer_sha","source_clean","manifest_sha256","built_at"}
17062
18730
  dep_fields={"schema","lane","dependency_fingerprint","producer_sha","source_clean","manifest_sha256","built_at"}
17063
18731
  template_fields={"schema","status","template_key","manifest_sha256","built_at","toolchain","source_commit"}
17064
18732
  if v2:
18733
+ app_fields|={"producer_runner_sha256","consumer_protocol"}
17065
18734
  dep_fields|={"producer_runner_sha256","consumer_protocol"}
17066
18735
  template_fields|={"producer_runner_sha256","consumer_protocol"}
17067
- expected_fields=dep_fields if kind=="dependency" else template_fields
18736
+ expected_fields=(app_fields if kind=="app"
18737
+ else dep_fields if kind=="dependency" else template_fields)
17068
18738
  if not isinstance(meta,dict) or set(meta)!=expected_fields or meta.get("schema")!=("2" if v2 else "1"):
17069
18739
  raise ValueError("metadata schema")
18740
+ if kind=="app" and (meta["lane"]!=lane or meta["compile_fingerprint"]!=key
18741
+ or not re.fullmatch(r"[0-9a-f]{40}",meta["producer_sha"])
18742
+ or meta["source_clean"] not in ("true","false")):
18743
+ raise ValueError("app compile metadata identity")
17070
18744
  if kind=="dependency" and (meta["lane"]!=lane or meta["dependency_fingerprint"]!=key
17071
18745
  or not re.fullmatch(r"[0-9a-f]{40}",meta["producer_sha"])
17072
18746
  or meta["source_clean"] not in ("true","false")):
@@ -17094,7 +18768,8 @@ def verify_tree(row,base_rel=None,allow_owner_write=False):
17094
18768
  parts=line.split("\t")
17095
18769
  if len(parts)<3: raise ValueError("manifest row")
17096
18770
  kind,path=parts[:2]; safe_parts(path)
17097
- if path.split("/")[0] not in ("deps","_build") or path in records:
18771
+ if (path.split("/")[0] not in (("_build",) if kind=="app" else ("deps","_build"))
18772
+ or path in records):
17098
18773
  raise ValueError("manifest path")
17099
18774
  if kind=="D" and parts==["D",path,"-"]: pass
17100
18775
  elif kind=="F" and len(parts)==4 and parts[2].isdigit() and re.fullmatch(r"[0-9a-f]{64}",parts[3]): pass
@@ -17145,7 +18820,7 @@ def verify_tree(row,base_rel=None,allow_owner_write=False):
17145
18820
  if identity(before)!=identity(os.fstat(filefd)): raise ValueError("payload changed while hashing")
17146
18821
  finally: os.close(filefd)
17147
18822
  else: raise ValueError("special payload")
17148
- for top in ("deps","_build"):
18823
+ for top in (("_build",) if kind=="app" else ("deps","_build")):
17149
18824
  topfd=os.open(top,dir_flags,dir_fd=rootfd_cache)
17150
18825
  try:
17151
18826
  topst=os.fstat(topfd)
@@ -17238,7 +18913,7 @@ def access_baseline(row,pool,lane,key,proof):
17238
18913
  adopted=datetime.datetime.fromisoformat(adoption["adopted_at"].replace("Z","+00:00")) if adoption else now
17239
18914
  return max(built,access,adopted),adoption
17240
18915
  def ttl_hours(pool):
17241
- return int(dep_ttl if pool_kind(pool)=="dependency" else template_ttl)
18916
+ return int(dep_ttl if pool_kind(pool) in ("dependency","app") else template_ttl)
17242
18917
  def make_owned_directories_writable(base_rel,snapshot):
17243
18918
  changes=[]
17244
18919
  for rel in sorted([""]+snapshot["directories"],key=lambda value:value.count("/")):
@@ -17339,6 +19014,10 @@ def remove_verified_tree(base_rel,snapshot,delete=True):
17339
19014
  if root is not None: os.close(root)
17340
19015
  os.close(parent)
17341
19016
  def policy_sha(execution_mode):
19017
+ # Frozen policy digest: plan/journal validation recomputes it live, so its
19018
+ # content must never change or in-flight journals lose forward-only
19019
+ # resume. The FMIX_AUTO_EXPIRE_MAX batch bound is per-pass scheduling and
19020
+ # deliberately not part of this per-artifact policy identity.
17342
19021
  return sha(canonical({"schema":"fmix-artifact-retirement-policy.v2",
17343
19022
  "dependency_ttl_hours":int(dep_ttl),"template_ttl_hours":int(template_ttl),
17344
19023
  "max_candidates_per_preparation":1,"max_work_seconds":45,
@@ -17459,7 +19138,8 @@ def snapshots_match(before,after,phase="rename"):
17459
19138
  if path not in directories and old.get("ctime_ns")!=new.get("ctime_ns"):
17460
19139
  raise ValueError("unexpected file metadata change")
17461
19140
  def late_references(report,pool,lane,key):
17462
- field="template_key" if pool_kind(pool)=="template" else "dependency_fingerprint"
19141
+ field=("template_key" if pool_kind(pool)=="template"
19142
+ else "fingerprint" if pool_kind(pool)=="app" else "dependency_fingerprint")
17463
19143
  for observation in report.get("observations",[]):
17464
19144
  refs=observation.get("references",{})
17465
19145
  if refs.get(field)==key: raise ValueError("late_native_workspace_reference")
@@ -17837,40 +19517,82 @@ def mode_operation():
17837
19517
  journal=load_journal(object_id)
17838
19518
  return run_locked(journal["artifact_id"],lambda:finish_journal(load_journal(object_id)))
17839
19519
  raise ValueError("unsupported_retirement_mode")
19520
+ def auto_expire_summary(results,error=None):
19521
+ # One JSON result per pass. A single completed operation keeps its exact
19522
+ # historical shape (its keys surface at the top level) so consumers read
19523
+ # it unchanged; multi-operation passes carry a results list and an
19524
+ # aggregate status.
19525
+ if not results:
19526
+ if error is not None: return {"status":"skipped","reason":str(error)}
19527
+ return {"status":"skipped","reason":"no_unreferenced_nonfallback_candidate"}
19528
+ if error is not None:
19529
+ return {"status":"skipped","reason":str(error),"results":results}
19530
+ statuses={item.get("status") for item in results}
19531
+ if statuses<={"retired","already_retired"}: status="retired"
19532
+ elif "held" in statuses: status="held"
19533
+ else: status="adopted_waiting_ttl"
19534
+ summary={"status":status,"results":results}
19535
+ if len(results)==1:
19536
+ summary.update({key:value for key,value in results[0].items()
19537
+ if key not in ("schema","results")})
19538
+ return summary
17840
19539
  def auto_expire_one():
17841
- # One v2 cache attempt per preparation; legacy/global uncertainty stays held.
19540
+ # Batched auto-expire: one preparation pass runs at most
19541
+ # FMIX_AUTO_EXPIRE_MAX retirement operations (default 3, bounded 1-10) —
19542
+ # pending journals first (forward-only resume, never restarted), then the
19543
+ # oldest fresh candidates; legacy/global uncertainty stays held. The
19544
+ # per-artifact lease is held only for each artifact's destructive
19545
+ # rename->graveyard + rmtree phase, never across the batch or the shared
19546
+ # audit. Any failing step halts the pass fail-closed; completed work stays
19547
+ # journaled and resumes forward-only on a later pass.
17842
19548
  require_managed_handoff()
19549
+ results=[]
17843
19550
  try:
19551
+ budget=auto_expire_max
17844
19552
  journals=list_names(RETIRE_ROOT+"/journals")
17845
19553
  for name in journals:
19554
+ if budget<=0: break
17846
19555
  match=re.fullmatch(r"([0-9a-f]{64})\.json",name)
17847
19556
  if not match: raise ValueError("unknown_retirement_journal_layout")
17848
19557
  journal=load_journal(match.group(1))
17849
19558
  if journal.get("state") in ("intent","quarantined","permissions_pending","deleting"):
17850
- return run_locked(journal["artifact_id"],lambda:finish_journal(load_journal(match.group(1))))
17851
- report,runner_sha=run_audit()
17852
- protected,broken,unknown_template=fallbacks(report)
17853
- candidates=[]
17854
- for row in report.get("entries",[]):
17855
- if row.get("reference_count") or row.get("references_truncated"): continue
17856
- artifact_id=artifact_id_for(row)
17857
- if not pool_v2(row["pool"]): continue
17858
- try: candidate_holds(report,row)
17859
- except Exception: continue
17860
- if artifact_id in protected or (pool_kind(row["pool"])=="template" and unknown_template) or row.get("lane") in broken: continue
17861
- try:
17862
- meta,built=read_meta(row)
17863
- access=last_access(row,row["pool"],row.get("lane"),row["key"],built)
17864
- except Exception: continue
17865
- candidates.append((access,artifact_id))
17866
- if not candidates: return {"status":"skipped","reason":"no_unreferenced_nonfallback_candidate"}
17867
- _,artifact_id=min(candidates)
17868
- return run_locked(artifact_id,lambda:auto_candidate_locked(artifact_id))
19559
+ results.append(run_locked(journal["artifact_id"],
19560
+ lambda:finish_journal(load_journal(match.group(1)))))
19561
+ budget-=1
19562
+ if budget>0:
19563
+ report,runner_sha=run_audit()
19564
+ protected,broken,unknown_template=fallbacks(report)
19565
+ candidates=[]
19566
+ for row in report.get("entries",[]):
19567
+ if row.get("reference_count") or row.get("references_truncated"): continue
19568
+ artifact_id=artifact_id_for(row)
19569
+ if not pool_v2(row["pool"]): continue
19570
+ try: candidate_holds(report,row)
19571
+ except Exception: continue
19572
+ if artifact_id in protected or (pool_kind(row["pool"])=="template" and unknown_template) or row.get("lane") in broken: continue
19573
+ try:
19574
+ meta,built=read_meta(row)
19575
+ access=last_access(row,row["pool"],row.get("lane"),row["key"],built)
19576
+ except Exception: continue
19577
+ candidates.append((access,artifact_id))
19578
+ for access,artifact_id in sorted(candidates):
19579
+ if budget<=0: break
19580
+ results.append(run_locked(artifact_id,lambda:auto_candidate_locked(artifact_id)))
19581
+ budget-=1
17869
19582
  except Exception as exc:
17870
- return {"status":"skipped","reason":str(exc)}
19583
+ return auto_expire_summary(results,exc)
19584
+ return auto_expire_summary(results)
17871
19585
  def auto_candidate_locked(artifact_id):
17872
19586
  report,runner_sha,row,pool,lane,key,rel,proof,protected=fresh_proof(artifact_id)
17873
- plan=create_plan(artifact_id,report,row,proof,runner_sha,protected,*fallbacks(report)[1:],"automatic")
19587
+ try:
19588
+ plan=create_plan(artifact_id,report,row,proof,runner_sha,protected,*fallbacks(report)[1:],"automatic")
19589
+ except ValueError as exc:
19590
+ # A candidate that has not yet aged past its idle TTL is an expected
19591
+ # per-artifact deferral (same waiting status a first sighting gets),
19592
+ # not a step failure: the batch keeps moving. Every other failure
19593
+ # stays fail-closed and halts the pass.
19594
+ if str(exc)!="idle_ttl_not_elapsed": raise
19595
+ return {"status":"adopted_waiting_ttl","artifact_id":artifact_id}
17874
19596
  if plan is None: return {"status":"adopted_waiting_ttl","artifact_id":artifact_id}
17875
19597
  return execute_plan_locked(plan["plan_id"])
17876
19598
  try:
@@ -18058,6 +19780,10 @@ def reference(rel, kind):
18058
19780
  if not hexkey(d[field], width):
18059
19781
  raise ValueError("reference identity")
18060
19782
  refs[field] = d[field]
19783
+ # Compile stamps also carry the app-compile pool's exact key. Extract
19784
+ # it tolerantly so legacy/garbage stamps keep their existing holds.
19785
+ if "fingerprint" in d and hexkey(d["fingerprint"], 64):
19786
+ refs["fingerprint"] = d["fingerprint"]
18061
19787
  row.update(status="observed", references=refs,
18062
19788
  declared_source_path_sha256=sha(source.encode()))
18063
19789
  except (OSError, ValueError, UnicodeError):
@@ -18134,6 +19860,7 @@ def known_retirement_quarantine(rel,pool,lane=None):
18134
19860
  aid=plan.get("artifact_id","")
18135
19861
  if pool=="template-v2" and re.fullmatch(r"template-v2:[0-9a-f]{16}",aid): source="artifacts/v2/templates/"+aid.split(":")[1]
18136
19862
  elif pool=="dependency-v2" and re.fullmatch(r"dependency-v2:[0-9a-f]{64}/[0-9a-f]{64}",aid): source="artifacts/v2/dependencies/"+aid.split(":")[1]
19863
+ elif pool=="app-compile-v2" and re.fullmatch(r"app-compile-v2:[0-9a-f]{64}/[0-9a-f]{64}",aid): source="artifacts/v2/app-compiles/"+aid.split(":")[1]
18137
19864
  else: return False
18138
19865
  parent=source.rsplit("/",1)[0]
18139
19866
  if journal.get("home")!=home or journal.get("uid_scope")!=os.getuid() or journal.get("artifact_id")!=aid or journal.get("source_rel")!=source or journal.get("quarantine_rel")!=rel or rel!=parent+"/.fmix-retire-"+plan_id: return False
@@ -18201,22 +19928,32 @@ def inventory(row, allow_owner_write=False):
18201
19928
  if not stat.S_ISDIR(before.st_mode) or (before.st_mode & 0o222 and not
18202
19929
  (allow_owner_write and before.st_mode & 0o200 and not before.st_mode & 0o022)):
18203
19930
  raise ValueError("unsafe cache root")
18204
- if set(children(rel)) != {"deps", "_build", "meta.json", "manifest.tsv", "manifest.sha256"}:
19931
+ app = pool.startswith("app")
19932
+ dependency_pool = pool.startswith("dependency")
19933
+ expected_contents = ({"_build", "meta.json", "manifest.tsv", "manifest.sha256"}
19934
+ if app else
19935
+ {"deps", "_build", "meta.json", "manifest.tsv", "manifest.sha256"})
19936
+ if set(children(rel)) != expected_contents:
18205
19937
  raise ValueError("unexpected cache contents")
18206
- for child in ("deps", "_build", "_build/test", "_build/test/lib"):
19938
+ for child in (("_build", "_build/test", "_build/test/lib") if app else
19939
+ ("deps", "_build", "_build/test", "_build/test/lib")):
18207
19940
  if not stat.S_ISDIR(info(rel + "/" + child).st_mode):
18208
19941
  raise ValueError("missing cache directory")
18209
- if pool.startswith("dependency") and (children(rel + "/_build") != ["test"]
18210
- or children(rel + "/_build/test") != ["lib"]):
19942
+ if (dependency_pool or app) and (children(rel + "/_build") != ["test"]
19943
+ or children(rel + "/_build/test") != ["lib"]):
18211
19944
  raise ValueError("unexpected build environment")
19945
+ if app and children(rel + "/_build/test/lib") != ["cdrcisco"]:
19946
+ raise ValueError("unexpected app payload")
18212
19947
  raw, _ = read(rel + "/meta.json")
18213
19948
  row["metadata_sha256"] = sha(raw)
18214
19949
  d = decode(raw)
18215
19950
  dependency = pool.startswith("dependency")
18216
19951
  v2 = pool.endswith("-v2")
18217
- fields = (("schema lane dependency_fingerprint producer_sha source_clean manifest_sha256 built_at producer_runner_sha256 consumer_protocol"
19952
+ fields = (("schema lane compile_fingerprint producer_sha source_clean manifest_sha256 built_at producer_runner_sha256 consumer_protocol"
19953
+ if app else
19954
+ "schema lane dependency_fingerprint producer_sha source_clean manifest_sha256 built_at producer_runner_sha256 consumer_protocol"
18218
19955
  if v2 else "schema lane dependency_fingerprint producer_sha source_clean manifest_sha256 built_at")
18219
- if dependency else
19956
+ if (dependency or app) else
18220
19957
  ("schema status template_key manifest_sha256 built_at toolchain source_commit producer_runner_sha256 consumer_protocol"
18221
19958
  if v2 else "schema status template_key manifest_sha256 built_at toolchain source_commit"))
18222
19959
  if not isinstance(d, dict) or set(d) != set(fields.split()) or any(
@@ -18232,7 +19969,12 @@ def inventory(row, allow_owner_write=False):
18232
19969
  if (sha(producer_runner) != d["producer_runner_sha256"] or producer_id["mode"]&0o222
18233
19970
  or not producer_id["mode"]&0o111):
18234
19971
  raise ValueError("producer runner identity")
18235
- if dependency:
19972
+ if app:
19973
+ if (d["lane"] != lane or d["compile_fingerprint"] != key
19974
+ or not hexkey(d["producer_sha"], 40)
19975
+ or d["source_clean"] not in ("true", "false")):
19976
+ raise ValueError("app compile identity")
19977
+ elif dependency:
18236
19978
  if (d["lane"] != lane or d["dependency_fingerprint"] != key
18237
19979
  or not hexkey(d["producer_sha"], 40)
18238
19980
  or d["source_clean"] not in ("true", "false")):
@@ -18295,7 +20037,8 @@ try:
18295
20037
  for pool, base, width in (("template", "templates", 16),
18296
20038
  ("dependency", "dependency-artifacts/v1", 64),
18297
20039
  ("template-v2", "artifacts/v2/templates", 16),
18298
- ("dependency-v2", "artifacts/v2/dependencies", 64)):
20040
+ ("dependency-v2", "artifacts/v2/dependencies", 64),
20041
+ ("app-compile-v2", "artifacts/v2/app-compiles", 64)):
18299
20042
  try:
18300
20043
  for name in children(base):
18301
20044
  if not hexkey(name, width):
@@ -18333,7 +20076,9 @@ for observation in observations:
18333
20076
  for field, key in observation.get("references", {}).items():
18334
20077
  index.setdefault((field, key), []).append(observation["path"])
18335
20078
  for row in entries:
18336
- field = "template_key" if row["pool"].startswith("template") else "dependency_fingerprint"
20079
+ field = ("template_key" if row["pool"].startswith("template")
20080
+ else "fingerprint" if row["pool"].startswith("app")
20081
+ else "dependency_fingerprint")
18337
20082
  references = index.get((field, row["key"]), [])
18338
20083
  row["reference_count"] = len(references)
18339
20084
  row["references"] = references[:16]
@@ -23173,10 +24918,14 @@ fmix test — run ExUnit targets inside a provisioned session DB.
23173
24918
 
23174
24919
  Usage:
23175
24920
  fmix test [--worktree <path>] [--session <id>] [--isolate]
23176
- [--cache-base <N.N.N-stable>] [--event-fd <fd>] [--unit]
23177
- -- <mix test args>
24921
+ [--cache-base <N.N.N-stable>] [--event-fd <fd>] [--no-auto-setup]
24922
+ [--unit] -- <mix test args>
23178
24923
 
23179
24924
  Notes:
24925
+ - A missing artifact template is auto-bootstrapped by delegating to
24926
+ fmix setup, then the artifacts step retries. Opt out with --no-auto-setup
24927
+ or FMIX_NO_AUTO_SETUP=1 to fail fast instead. Missing DB snapshots still
24928
+ require an explicit fmix setup --cold-db.
23180
24929
  - One worktree → one warm overlay (SUPER-HOT): pass --session only with a
23181
24930
  stable name plus --isolate for true parallel Mix on one checkout.
23182
24931
  - Slow DB startup = local snapshot recovery (see fmix status / fmix timing).
@@ -23194,13 +24943,15 @@ VERB
23194
24943
  fmix coverage — targeted diff-coverage gate (ADR 0054).
23195
24944
 
23196
24945
  Usage:
23197
- fmix coverage --worktree <path> [--session <id>] --base <git-ref>
23198
- [--source <lib/**/*.ex>]... [--threshold 80]
24946
+ fmix coverage --worktree <path> [--session <id>] [--no-auto-setup]
24947
+ --base <git-ref> [--source <lib/**/*.ex>]... [--threshold 80]
23199
24948
  -- <test paths>
23200
24949
 
23201
24950
  Notes:
23202
24951
  --base is REQUIRED: it defines the changed-module set. --source scopes
23203
24952
  cover-compilation to explicit modules (default: every changed lib module).
24953
+ A missing artifact template is auto-bootstrapped via fmix setup like the
24954
+ test lane; opt out with --no-auto-setup or FMIX_NO_AUTO_SETUP=1.
23204
24955
  Cannot gate staged-but-uncommitted changes — the bootstrap diffs the
23205
24956
  committed base...HEAD range. For staged gates use:
23206
24957
  fmix task -- cdrcisco.diff_coverage --staged --staged-diff <patch>
@@ -23409,7 +25160,7 @@ fmix — fast native Elixir test runner for cisco-cdr
23409
25160
 
23410
25161
  Usage:
23411
25162
  ./fmix test [--worktree <path>] [--session <id>] [--no-auto-setup] [--cache-base <N.N.N-stable>] [--event-fd <fd>] [--unit] -- <mix test args>
23412
- ./fmix coverage [--worktree <path>] [--session <id>] --base <git-ref> [--source <lib/**/*.ex>] [--threshold 80] -- <test paths>
25163
+ ./fmix coverage [--worktree <path>] [--session <id>] [--no-auto-setup] --base <git-ref> [--source <lib/**/*.ex>] [--threshold 80] -- <test paths>
23413
25164
  ./fmix task [--worktree <path>] [--session <id>] [--database <name>] [--mix-env <env>] [--allow-run] -- <mix task> [args]
23414
25165
  ./fmix format [--worktree <path>] [--session <id>] [--mix-env <env>] [--dot-formatter <path>] [--check] -- <files...>
23415
25166
  ./fmix setup [--worktree <path>] [--session <id>] [--rebuild-db|--cold-db|--from-zero]
@@ -23465,15 +25216,23 @@ Operational notes:
23465
25216
  fmix status exits 1 when session metadata discovery is incomplete, while
23466
25217
  still printing the remaining read-only diagnostic sections.
23467
25218
  Stable seeds are dependency-only; fmix test still validates app artifacts locally.
25219
+ Template cache reads are lock-free (no build lease); only producers,
25220
+ publication, quarantine, and retirement mutate the CAS under a lease.
23468
25221
 
23469
25222
  Environment overrides:
23470
25223
  FMIX_HOME State directory (default: ~/.ct-fmix)
23471
25224
  FMIX_SESSION_ID Stable logical session identity (or pass --session)
23472
25225
  FMIX_ISOLATE Set to 1 with a stable session name for parallel Mix
25226
+ FMIX_NO_AUTO_SETUP Set to 1 to stop test/coverage lanes from auto-running
25227
+ fmix setup on a missing artifact template (same effect
25228
+ as --no-auto-setup)
23473
25229
  FMIX_FORCE_SESSION Set to 1 to allow ephemeral session ids (cold path)
23474
25230
  FMIX_THREAD_SESSIONS Set to 1 to restore CODEX_THREAD_ID session binding
23475
25231
  FMIX_HOT_PATH_BUDGET_S hot_path overhead budget seconds excl mix_test (default: 25)
23476
25232
  FMIX_SCHEMA_READY_TTL_S Schema-ready stamp TTL; auto-expire ledger skip (default: 300)
25233
+ FMIX_AUTO_EXPIRE_MAX Artifact auto-expire retirement operations per
25234
+ preparation pass (default: 3; bounded 1-10; invalid
25235
+ values fall back to the default)
23477
25236
  OBAN_LICENSE_KEY Oban Pro license key override (or from ~/.config/calltelemetry/fmix.env / Doppler)
23478
25237
  FMIX_SESSION_TTL_HOURS Inactive-session auto-purge and GC threshold (default: 4)
23479
25238
  FMIX_SESSION_TTL_DAYS Legacy compatibility override, converted to hours when FMIX_SESSION_TTL_HOURS is unset
@@ -23488,12 +25247,15 @@ Environment overrides:
23488
25247
  FMIX_DB_PORT Postgres port (default: 5432)
23489
25248
  FMIX_DB_USER Postgres user (default: calltelemetry)
23490
25249
  FMIX_DB_PASSWORD Postgres password (default: calltelemetry_dev_password)
23491
- FMIX_NATS_HOST NATS host (default: localhost)
25250
+ FMIX_NATS_HOST NATS host (default: nats-dev if reachable on Tailnet, else localhost)
25251
+ FMIX_TAILNET_NATS_HOST Tailnet NATS host to probe (default: nats-dev)
25252
+ FMIX_DISABLE_TAILNET_NATS Set to 1 to skip Tailnet probing (default: 1 on CI)
23492
25253
  FMIX_NATS_PORT NATS port (default: 4222)
23493
25254
  FMIX_COPY_MODE Set to 'full' to disable CoW clone
23494
25255
  FMIX_LOCK_TIMEOUT Lock wait timeout in seconds (default: 900)
23495
25256
  FMIX_LOCK_INIT_GRACE Grace before reclaiming a pid-less lock (default: 5)
23496
25257
  FMIX_WORKTREE_LOCK_TIMEOUT Same-worktree run wait cap in seconds (default: 360)
25258
+ FMIX_SESSION_LOCK_SPLIT 0 forces exclusive-only session locks (default: 1)
23497
25259
  FMIX_HOST_TEST_LOCK Set to 0 only to bypass CREATE/DROP serialization
23498
25260
  FMIX_HOST_LOCK_TIMEOUT Host database-DDL lock wait cap in seconds (default: 60)
23499
25261
  FMIX_DB_CREATE_ADMISSION Set to 0 only to bypass DB pressure admission