@calltelemetry/fmix 2.7.17 → 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 +2538 -269
  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]
@@ -18,6 +18,8 @@
18
18
  # ./fmix gc [--reap] [--yes]
19
19
  # ./fmix gc --artifacts-only [--json] # bounded read-only inventory; no eviction
20
20
  # ./fmix self-test
21
+ # ./fmix verify-push [--worktree <path>] [--cooldown-minutes <N>] [--require-receipt]
22
+ # ./fmix hook install [--worktree <path>]
21
23
  #
22
24
 
23
25
  set -uo pipefail
@@ -25,7 +27,7 @@ set -uo pipefail
25
27
  # ---------------------------------------------------------------------------
26
28
  # Constants & config
27
29
  # ---------------------------------------------------------------------------
28
- FMIX_VERSION="2.7.17"
30
+ FMIX_VERSION="2.7.19"
29
31
  FMIX_HOME="${FMIX_HOME:-${HOME}/.ct-fmix}"
30
32
  FMIX_OS="$(uname -s)"
31
33
  FMIX_ARCH="$(uname -m)"
@@ -94,6 +96,10 @@ FMIX_DEPENDENCY_ARTIFACT_TTL_DAYS="${FMIX_DEPENDENCY_ARTIFACT_TTL_DAYS-}"
94
96
  FMIX_DEPENDENCY_ARTIFACT_TTL_HOURS="${FMIX_DEPENDENCY_ARTIFACT_TTL_HOURS-}"
95
97
  FMIX_TEMPLATE_TTL_HOURS="${FMIX_TEMPLATE_TTL_HOURS-}"
96
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"
97
103
  FMIX_MIGRATION_DELTA_LIMIT="${FMIX_MIGRATION_DELTA_LIMIT:-50}"
98
104
  FMIX_COMPILE_HEARTBEAT="${FMIX_COMPILE_HEARTBEAT:-30}"
99
105
  FMIX_COMPILE_TIMEOUT="${FMIX_COMPILE_TIMEOUT:-900}"
@@ -120,6 +126,15 @@ FMIX_STRUCTURE_LOAD_HEARTBEAT="${FMIX_STRUCTURE_LOAD_HEARTBEAT:-30}"
120
126
  FMIX_HELD_LOCK_NAMES=()
121
127
  FMIX_HELD_LOCK_KEEPER_PIDS=()
122
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=""
123
138
  FMIX_LAST_LOCK_KEEPER_PID=""
124
139
  FMIX_LOCK_STOP_PROBE_PIDS=()
125
140
  FMIX_PENDING_LOCK_KEEPER_PID=""
@@ -141,8 +156,26 @@ DB_HOST="${FMIX_DB_HOST:-localhost}"
141
156
  DB_PORT="${FMIX_DB_PORT:-5432}"
142
157
  DB_USER="${FMIX_DB_USER:-calltelemetry}"
143
158
  DB_PASSWORD="${FMIX_DB_PASSWORD:-calltelemetry_dev_password}"
144
- NATS_HOST="${FMIX_NATS_HOST:-localhost}"
145
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)"
146
179
 
147
180
  # Fixed dev constant SECRET_KEY_BASE (64 hex chars — only used in test env)
148
181
  SECRET_KEY_BASE="${FMIX_SECRET_KEY_BASE:-dev0000000000000000000000000000000000000000000000000000000000000001}"
@@ -339,6 +372,9 @@ fmix_readonly_entrypoint() {
339
372
  test|coverage|task|format|setup|seed|cache|ensure|doctor|status|timing|gc|install|self-test)
340
373
  [[ "${2:-}" == "--help" || "${2:-}" == "-h" ]] && return 0
341
374
  ;;
375
+ verify-push|hook)
376
+ [[ "${2:-}" == "--help" || "${2:-}" == "-h" ]] && return 0
377
+ ;;
342
378
  esac
343
379
  return 1
344
380
  }
@@ -361,6 +397,29 @@ fmix_stat_mtime() {
361
397
  fi
362
398
  }
363
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
+
364
423
  fmix_cow_clone() {
365
424
  # CoW clone source_dir → dest_dir (dest must NOT exist).
366
425
  # Returns 0 on success, non-zero on failure.
@@ -730,6 +789,13 @@ fmix_hash_string() {
730
789
  }
731
790
 
732
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
733
799
  if command -v shasum >/dev/null 2>&1; then
734
800
  shasum -a 256 -- "$@"
735
801
  elif command -v sha256sum >/dev/null 2>&1; then
@@ -740,6 +806,192 @@ fmix_hash_files() {
740
806
  fi
741
807
  }
742
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
+
743
995
  fmix_hash_file_batches() {
744
996
  local file
745
997
  local -a batch=()
@@ -755,12 +1007,39 @@ fmix_hash_file_batches() {
755
1007
  fi
756
1008
  }
757
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
+
758
1036
  fmix_hash_tracked_compile_inputs() {
759
1037
  local root="$1" tracked_file="$2" py_bin
760
1038
  py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
761
1039
  "$py_bin" - "$root" "$tracked_file" <<'PY'
762
1040
  import hashlib
763
1041
  import os
1042
+ import stat as stat_module
764
1043
  import sys
765
1044
 
766
1045
 
@@ -769,6 +1048,24 @@ tracked_file = sys.argv[2]
769
1048
  output = sys.stdout.buffer
770
1049
  error_output = sys.stderr.buffer
771
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
+
772
1069
 
773
1070
  def iter_nul_records(stream):
774
1071
  pending = bytearray()
@@ -811,6 +1108,31 @@ def hash_file(path):
811
1108
  return digest.hexdigest().encode("ascii")
812
1109
 
813
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
+
814
1136
  try:
815
1137
  with open(tracked_file, "rb") as records:
816
1138
  for entry in iter_nul_records(records):
@@ -834,7 +1156,7 @@ try:
834
1156
  raise SystemExit(1)
835
1157
  if os.path.isfile(candidate):
836
1158
  try:
837
- digest = hash_file(candidate)
1159
+ digest = cached_hash_file(candidate)
838
1160
  except OSError:
839
1161
  output.flush()
840
1162
  report_error(b"Could not hash compiler input: " + candidate)
@@ -846,6 +1168,20 @@ try:
846
1168
  except OSError:
847
1169
  report_error(b"Could not read tracked compiler input records")
848
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
849
1185
  PY
850
1186
  }
851
1187
 
@@ -2106,6 +2442,12 @@ fmix_session_meta_file() {
2106
2442
  fmix_create_or_touch_meta_json() {
2107
2443
  local worktree="$1" meta created lockfile_hash app_name ttl_days ttl_hours tmp
2108
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
2109
2451
 
2110
2452
  ttl_days="$(fmix_effective_session_ttl_days)"
2111
2453
  ttl_hours="$(fmix_effective_session_ttl_hours)"
@@ -2611,16 +2953,36 @@ fmix_activate_session() {
2611
2953
  session_root="$FMIX_HOME/sessions/v1/$host_hash/$session_hash/$worktree_hash"
2612
2954
  session_lock="session-$session_hash"
2613
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
2614
2964
  fmix_lock_acquire "$session_lock" "$FMIX_WORKTREE_LOCK_TIMEOUT" \
2615
- "session activation" || {
2965
+ "session activation" 0 "$activation_mode" || {
2616
2966
  activation_rc=$?
2617
2967
  fmix_clear_active_session
2618
2968
  return "$activation_rc"
2619
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
2620
2982
  if [[ -e "$session_root" || -L "$session_root" ]]; then
2621
2983
  session_root_preexisting=1
2622
2984
  fi
2623
- if (( activation_rc == 0 )); then
2985
+ if (( activation_rc == 0 )) && [[ "$activation_mode" == "exclusive" ]]; then
2624
2986
  if created_session_root="$(fmix_create_session_root \
2625
2987
  "$host_hash" "$session_hash" "$worktree_hash")"; then
2626
2988
  session_root="$created_session_root"
@@ -2628,7 +2990,7 @@ fmix_activate_session() {
2628
2990
  activation_rc=1
2629
2991
  fi
2630
2992
  fi
2631
- if (( activation_rc == 0 )); then
2993
+ if (( activation_rc == 0 )) && [[ "$activation_mode" == "exclusive" ]]; then
2632
2994
  local housekeeping_rc=0
2633
2995
  fmix_purge_expired_sessions 1 || housekeeping_rc=$?
2634
2996
  if fmix_lock_failure_is_fatal "$housekeeping_rc"; then
@@ -2637,7 +2999,7 @@ fmix_activate_session() {
2637
2999
  fmix_warn "Session housekeeping is degraded; activation will continue without destructive cleanup."
2638
3000
  fi
2639
3001
  fi
2640
- if (( activation_rc == 0 )); then
3002
+ if (( activation_rc == 0 )) && [[ "$activation_mode" == "exclusive" ]]; then
2641
3003
  chmod 0700 "$FMIX_HOME" "$FMIX_HOME/sessions" "$FMIX_HOME/sessions/v1" \
2642
3004
  "$FMIX_HOME/sessions/v1/$host_hash" \
2643
3005
  "$FMIX_HOME/sessions/v1/$host_hash/$session_hash" "$session_root" \
@@ -2668,7 +3030,13 @@ fmix_activate_session() {
2668
3030
  fmix_error "Session priv bridge path is occupied by non-symlink state: $priv_link"
2669
3031
  activation_rc=1
2670
3032
  elif (( activation_rc == 0 )); then
2671
- 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
2672
3040
  fi
2673
3041
 
2674
3042
  if (( activation_rc == 0 )) && ! fmix_write_session_meta "$real"; then
@@ -3315,7 +3683,7 @@ fmix_with_reused_artifact_lease() {
3315
3683
  }
3316
3684
  fmix_artifact_v2_prepare_directory() {
3317
3685
  local rel="${1:-}" py_bin
3318
- [[ "$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
3319
3687
  py_bin="$(fmix_python_bin)" || return 1
3320
3688
  "$py_bin" -I -B - "$FMIX_HOME" "$rel" <<'PY'
3321
3689
  import os,stat,sys
@@ -3340,32 +3708,48 @@ fmix_dependency_artifact_v2_dir() {
3340
3708
  [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
3341
3709
  printf '%s/artifacts/v2/dependencies/%s/%s\n' "$FMIX_HOME" "$lane" "$exact"
3342
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
+ }
3343
3719
  fmix_dependency_artifact_legacy_dir() {
3344
3720
  local lane="${1:-}" exact="${2:-}"
3345
3721
  [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
3346
3722
  printf '%s/dependency-artifacts/v1/%s/%s\n' "$FMIX_HOME" "$lane" "$exact"
3347
3723
  }
3348
3724
  fmix_dependency_artifact_dir() {
3349
- local lane="${1:-}" exact="${2:-}" v2
3725
+ local lane="${1:-}" exact="${2:-}" kind="${3:-dependency}" v2
3350
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
3351
3732
  v2="$(fmix_dependency_artifact_v2_dir "$lane" "$exact")" || return 1
3352
3733
  if [[ -e "$v2" || -L "$v2" ]]; then printf '%s\n' "$v2"
3353
3734
  else fmix_dependency_artifact_legacy_dir "$lane" "$exact"; fi
3354
3735
  }
3355
3736
 
3356
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.
3357
3743
  local lane="${1:-}" exact="${2:-}" lock_name index
3358
3744
  [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
3359
3745
  lock_name="dependency-artifact-${lane:0:16}-${exact:0:16}"
3360
3746
  if index="$(fmix_lock_find_index "$lock_name")"; then
3361
3747
  kill -0 "${FMIX_HELD_LOCK_KEEPER_PIDS[$index]}" 2>/dev/null || return 1
3362
- _fmix_touch_dependency_artifact_access_locked "$lane" "$exact"
3363
- else
3364
- fmix_with_artifact_lease "$lock_name" _fmix_touch_dependency_artifact_access_locked "$lane" "$exact"
3365
3748
  fi
3749
+ _fmix_touch_dependency_artifact_access_write "$lane" "$exact"
3366
3750
  }
3367
3751
 
3368
- _fmix_touch_dependency_artifact_access_locked() {
3752
+ _fmix_touch_dependency_artifact_access_write() {
3369
3753
  local lane="${1:-}" exact="${2:-}" root access tmp artifact
3370
3754
  [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
3371
3755
  artifact="$FMIX_HOME/artifacts/v2/dependencies/$lane/$exact"
@@ -3383,6 +3767,37 @@ _fmix_touch_dependency_artifact_access_locked() {
3383
3767
  mv "$tmp" "$access" || { rm -f "$tmp"; return 1; }
3384
3768
  }
3385
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
+
3386
3801
  fmix_dependency_artifact_manifest_digest() {
3387
3802
  local root="${1:-}" output="${2:-}" py_bin tmp digest
3388
3803
  (( $# == 1 || $# == 2 )) || return 1
@@ -3431,6 +3846,59 @@ PY
3431
3846
  printf '%s\n' "$digest"
3432
3847
  }
3433
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
+
3434
3902
  fmix_dependency_artifact_meta_matches() {
3435
3903
  local artifact="${1:-}" expected_lane="${2:-}" expected_exact="${3:-}"
3436
3904
  local py_bin validation_output
@@ -3589,69 +4057,285 @@ fmix_dependency_artifact_quarantine() {
3589
4057
  return 1
3590
4058
  }
3591
4059
 
3592
- fmix_stable_seed_parse_meta() {
3593
- local seed_dir="${1:-}" meta
3594
- meta="$seed_dir/meta.json"
3595
- [[ -f "$meta" && -r "$meta" ]] || return 1
3596
- awk '
3597
- function reject() { bad = 1 }
3598
- {
3599
- line = $0
3600
- sub(/^[[:space:]]+/, "", line)
3601
- sub(/[[:space:]]+$/, "", line)
3602
- if (line == "") next
3603
- if (!opened) {
3604
- if (line != "{") reject()
3605
- opened = 1
3606
- next
3607
- }
3608
- if (closed) {
3609
- reject()
3610
- next
3611
- }
3612
- if (line == "}") {
3613
- closed = 1
3614
- next
3615
- }
3616
- has_comma = (line ~ /,$/)
3617
- if (has_comma) sub(/,$/, "", line)
3618
- if (line !~ /^"[^"]+"[[:space:]]*:[[:space:]]*"[^"]*"$/) {
3619
- reject()
3620
- next
3621
- }
3622
- text = line
3623
- sub(/^"/, "", text)
3624
- quote = index(text, "\"")
3625
- key = substr(text, 1, quote - 1)
3626
- text = substr(text, quote + 1)
3627
- sub(/^[[:space:]]*:[[:space:]]*"/, "", text)
3628
- sub(/"$/, "", text)
3629
- value = text
3630
- if (value !~ /^[A-Za-z0-9._\/-]+$/) reject()
3631
- if (key != "schema" && key != "base_ref" && key != "producer_ref" \
3632
- && key != "producer_sha" && key != "compatibility") reject()
3633
- count[key]++
3634
- values[key] = value
3635
- members++
3636
- comma[members] = has_comma
3637
- }
3638
- END {
3639
- if (!opened || !closed || bad || members != 5) exit 1
3640
- for (i = 1; i < members; i++) if (!comma[i]) exit 1
3641
- if (comma[members]) exit 1
3642
- if (count["schema"] != 1 || count["base_ref"] != 1 \
3643
- || count["producer_ref"] != 1 || count["producer_sha"] != 1 \
3644
- || count["compatibility"] != 1) exit 1
3645
- printf "%s\t%s\t%s\t%s\t%s\n", values["schema"], values["base_ref"], \
3646
- values["producer_ref"], values["producer_sha"], values["compatibility"]
3647
- }
3648
- ' "$meta"
3649
- }
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
3650
4074
 
3651
- fmix_stable_seed_read_meta() {
3652
- local seed_dir="${1:-}" field="${2:-}" parsed
3653
- local schema base_ref producer_ref producer_sha compatibility extra
3654
- case "$field" in
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"
4333
+ }
4334
+
4335
+ fmix_stable_seed_read_meta() {
4336
+ local seed_dir="${1:-}" field="${2:-}" parsed
4337
+ local schema base_ref producer_ref producer_sha compatibility extra
4338
+ case "$field" in
3655
4339
  schema|base_ref|producer_ref|producer_sha|compatibility) ;;
3656
4340
  *) return 1 ;;
3657
4341
  esac
@@ -4880,7 +5564,7 @@ _fmix_dependency_install_interrupt() {
4880
5564
  fmix_effective_artifact_ttl_hours() {
4881
5565
  local pool="${1:-}" value legacy
4882
5566
  case "$pool" in
4883
- dependency)
5567
+ dependency|app)
4884
5568
  value="${FMIX_DEPENDENCY_ARTIFACT_TTL_HOURS-}"
4885
5569
  legacy="${FMIX_DEPENDENCY_ARTIFACT_TTL_DAYS-}"
4886
5570
  if [[ -z "$value" && -n "$legacy" ]]; then
@@ -4904,6 +5588,29 @@ fmix_effective_artifact_ttl_hours() {
4904
5588
  printf '%s\n' "$(( 10#$value ))"
4905
5589
  }
4906
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
+
4907
5614
  fmix_with_artifact_lease() {
4908
5615
  # Readers use the publisher's existing kernel/mixed-version lease for the
4909
5616
  # entire verification, copy and access refresh. Never nest or steal leases.
@@ -5141,105 +5848,469 @@ _fmix_install_dependency_artifact_locked() {
5141
5848
  fi
5142
5849
  fi
5143
5850
 
5144
- if (( ok == 0 || dependency_install_interrupted != 0 )); then
5145
- [[ ! -e "$retired/deps" && ! -L "$retired/deps" ]] || had_deps=1
5146
- [[ ! -e "$retired/lib" && ! -L "$retired/lib" ]] || had_lib=1
5147
- [[ ! -e "$retired/dependency-stamp.json" && ! -L "$retired/dependency-stamp.json" ]] || had_dep_stamp=1
5148
- [[ ! -e "$retired/compile-stamp.json" && ! -L "$retired/compile-stamp.json" ]] || had_compile_stamp=1
5149
- if (( attempted_deps != 0 )) && [[ ! -e "$stage/new/deps" && ! -L "$stage/new/deps" \
5150
- && ( -e "$deps_root" || -L "$deps_root" ) ]]; then installed_deps=1; fi
5151
- if (( attempted_lib != 0 )) && [[ ! -e "$stage/new/_build/test/lib" && ! -L "$stage/new/_build/test/lib" \
5152
- && ( -e "$target_lib" || -L "$target_lib" ) ]]; then installed_lib=1; fi
5153
- (( installed_deps == 0 )) || rm -rf "$deps_root" || rollback_failed=1
5154
- (( installed_lib == 0 )) || rm -rf "$target_lib" || rollback_failed=1
5155
- if (( had_deps != 0 )); then
5156
- if [[ ! -e "$deps_root" && ! -L "$deps_root" ]]; then
5157
- mv "$retired/deps" "$deps_root" || rollback_failed=1
5158
- else rollback_failed=1; fi
5159
- fi
5160
- if (( had_lib != 0 )); then
5161
- if [[ ! -e "$target_lib" && ! -L "$target_lib" ]]; then
5162
- mv "$retired/lib" "$target_lib" || rollback_failed=1
5163
- else rollback_failed=1; fi
5851
+ if (( ok == 0 || dependency_install_interrupted != 0 )); then
5852
+ [[ ! -e "$retired/deps" && ! -L "$retired/deps" ]] || had_deps=1
5853
+ [[ ! -e "$retired/lib" && ! -L "$retired/lib" ]] || had_lib=1
5854
+ [[ ! -e "$retired/dependency-stamp.json" && ! -L "$retired/dependency-stamp.json" ]] || had_dep_stamp=1
5855
+ [[ ! -e "$retired/compile-stamp.json" && ! -L "$retired/compile-stamp.json" ]] || had_compile_stamp=1
5856
+ if (( attempted_deps != 0 )) && [[ ! -e "$stage/new/deps" && ! -L "$stage/new/deps" \
5857
+ && ( -e "$deps_root" || -L "$deps_root" ) ]]; then installed_deps=1; fi
5858
+ if (( attempted_lib != 0 )) && [[ ! -e "$stage/new/_build/test/lib" && ! -L "$stage/new/_build/test/lib" \
5859
+ && ( -e "$target_lib" || -L "$target_lib" ) ]]; then installed_lib=1; fi
5860
+ (( installed_deps == 0 )) || rm -rf "$deps_root" || rollback_failed=1
5861
+ (( installed_lib == 0 )) || rm -rf "$target_lib" || rollback_failed=1
5862
+ if (( had_deps != 0 )); then
5863
+ if [[ ! -e "$deps_root" && ! -L "$deps_root" ]]; then
5864
+ mv "$retired/deps" "$deps_root" || rollback_failed=1
5865
+ else rollback_failed=1; fi
5866
+ fi
5867
+ if (( had_lib != 0 )); then
5868
+ if [[ ! -e "$target_lib" && ! -L "$target_lib" ]]; then
5869
+ mv "$retired/lib" "$target_lib" || rollback_failed=1
5870
+ else rollback_failed=1; fi
5871
+ fi
5872
+ if (( stamp_attempted != 0 || had_dep_stamp != 0 )); then
5873
+ rm -f "$dep_stamp" || rollback_failed=1
5874
+ fi
5875
+ if (( had_dep_stamp != 0 )); then
5876
+ if [[ ! -e "$dep_stamp" && ! -L "$dep_stamp" ]]; then
5877
+ mv "$retired/dependency-stamp.json" "$dep_stamp" || rollback_failed=1
5878
+ else rollback_failed=1; fi
5879
+ 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
5164
6207
  fi
5165
- if (( stamp_attempted != 0 || had_dep_stamp != 0 )); then
5166
- rm -f "$dep_stamp" || rollback_failed=1
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
5167
6214
  fi
5168
- if (( had_dep_stamp != 0 )); then
5169
- if [[ ! -e "$dep_stamp" && ! -L "$dep_stamp" ]]; then
5170
- mv "$retired/dependency-stamp.json" "$dep_stamp" || rollback_failed=1
5171
- else rollback_failed=1; 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
5172
6223
  fi
5173
- if (( had_compile_stamp != 0 )); then
5174
- if [[ ! -e "$compile_stamp" && ! -L "$compile_stamp" ]]; then
5175
- mv "$retired/compile-stamp.json" "$compile_stamp" || rollback_failed=1
5176
- else rollback_failed=1; 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
5177
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"
5178
6240
  trap - INT TERM HUP
5179
6241
  [[ -n "$saved_trap_int" ]] && eval "$saved_trap_int"
5180
6242
  [[ -n "$saved_trap_term" ]] && eval "$saved_trap_term"
5181
6243
  [[ -n "$saved_trap_hup" ]] && eval "$saved_trap_hup"
5182
- if (( rollback_failed != 0 )); then
5183
- fmix_error "Dependency replacement rollback incomplete; preserving recovery inputs: $stage"
5184
- 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
5185
6253
  fi
5186
- rm -rf "$stage" || fmix_warn "Owned dependency staging remains: $stage"
5187
- (( dependency_install_interrupted == 0 )) \
5188
- || return "$dependency_install_interrupt_rc"
5189
- return 1
5190
6254
  fi
5191
- rm -rf "$stage" 2>/dev/null || \
5192
- 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
5193
6268
  trap - INT TERM HUP
5194
6269
  [[ -n "$saved_trap_int" ]] && eval "$saved_trap_int"
5195
6270
  [[ -n "$saved_trap_term" ]] && eval "$saved_trap_term"
5196
6271
  [[ -n "$saved_trap_hup" ]] && eval "$saved_trap_hup"
5197
- (( dependency_install_interrupted == 0 )) \
5198
- || return "$dependency_install_interrupt_rc"
5199
- fmix_touch_dependency_artifact_access "$lane" "$artifact_exact" || return 1
5200
- 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
5201
6282
  }
5202
6283
 
5203
- fmix_prepare_dependency_artifacts() {
5204
- local worktree="${1:-}" exact lane artifact reconciler reconciler_exact install_rc
5205
- (( $# == 1 )) || return 1
5206
- exact="$(fmix_compute_dependency_fingerprint "$worktree")" || return 1
5207
- if fmix_dependency_stamp_matches "$worktree" "$exact"; then
5208
- return 0
5209
- 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
5210
6294
  lane="$(fmix_dependency_lane_fingerprint "$worktree")" || return 1
5211
- artifact="$(fmix_dependency_artifact_dir "$lane" "$exact")" || return 1
5212
- if [[ -e "$artifact" || -L "$artifact" ]]; then
5213
- if fmix_install_dependency_artifact "$worktree" "$artifact" 1; then
5214
- fmix_info "Exact dependency artifact hit — skipping dependency resolution and compilation."
5215
- return 0
5216
- else
5217
- install_rc=$?
5218
- case "$install_rc" in 2|129|130|143) return "$install_rc" ;; esac
5219
- fmix_lock_failure_is_fatal "$install_rc" && return 70
5220
- [[ "${FMIX_ARTIFACT_LEASE_RELEASE_FAILED:-0}" == "0" ]] || return "$install_rc"
5221
- # Consumers must not quarantine a generation on an unlocked probe:
5222
- # a concurrent publisher may have replaced it. The leased producer
5223
- # handles corrupt entries before publishing their replacement.
5224
- fmix_warn "Exact dependency artifact failed verification; rebuilding under its publisher lease."
5225
- 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
5226
6299
  fi
5227
- if reconciler="$(fmix_find_dependency_reconciler \
5228
- "$worktree" "$lane" "$exact" 2>/dev/null)"; then
5229
- reconciler_exact="$(basename "$reconciler")"
5230
- if fmix_install_dependency_artifact "$worktree" "$reconciler" 0; then
5231
- fmix_info "Seeded dependency reconciliation from the closest proven ancestor."
5232
- fmix_info "This is builder input, not an exact cache hit; Mix must publish the new fingerprint."
5233
- return 0
5234
- else
5235
- install_rc=$?
5236
- case "$install_rc" in 2|129|130|143) return "$install_rc" ;; esac
5237
- fmix_lock_failure_is_fatal "$install_rc" && return 70
5238
- [[ "${FMIX_ARTIFACT_LEASE_RELEASE_FAILED:-0}" == "0" ]] || return "$install_rc"
5239
- fi
5240
- 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."
5241
6312
  fi
5242
- return 0
6313
+ return 1
5243
6314
  }
5244
6315
 
5245
6316
  # ---------------------------------------------------------------------------
@@ -6128,6 +7199,7 @@ fmix_lock_acquire() {
6128
7199
  local lock_name="${1:-}" timeout="${2:-$FMIX_LOCK_TIMEOUT}"
6129
7200
  local diagnostic_name="${3:-${1:-}}" lock_dir kernel_file deadline
6130
7201
  local passive="${4:-0}" metadata_file metadata_document
7202
+ local mode="${5:-exclusive}"
6131
7203
  local keeper_pid token owner_start holder_pid holder_start recorded_start
6132
7204
  local lock_mtime lock_age grace printed_wait=0 index py_bin
6133
7205
  local publication_identity publication_snapshot current_snapshot rollback_keeper_pid rollback_rc rollback_stop_at
@@ -6140,6 +7212,14 @@ fmix_lock_acquire() {
6140
7212
  fmix_error "Invalid passive FMix lock mode."
6141
7213
  return 1
6142
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
6143
7223
  if [[ -n "$FMIX_PENDING_LOCK_KEEPER_PID" ]]; then
6144
7224
  printf '{"error":"lock_keeper_cleanup_pending"}\n' >&2
6145
7225
  return 70
@@ -6166,7 +7246,7 @@ fmix_lock_acquire() {
6166
7246
  local remaining=$(( deadline - $(fmix_epoch) ))
6167
7247
  (( remaining >= 0 )) || remaining=0
6168
7248
  local keeper_rc=0
6169
- fmix_lock_keeper_start "$kernel_file" exclusive "$remaining" \
7249
+ fmix_lock_keeper_start "$kernel_file" "$mode" "$remaining" \
6170
7250
  "$diagnostic_name" "$lock_name" || keeper_rc=$?
6171
7251
  if (( keeper_rc != 0 )); then
6172
7252
  (( keeper_rc == 1 )) || return "$keeper_rc"
@@ -6215,6 +7295,22 @@ fmix_lock_acquire() {
6215
7295
  return 1
6216
7296
  }
6217
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
6218
7314
  if (( printed_wait == 0 )); then
6219
7315
  fmix_info "Waiting for mixed-version lock '$diagnostic_name' (pid=$holder_pid) …"
6220
7316
  printed_wait=1
@@ -6263,6 +7359,7 @@ fmix_lock_acquire() {
6263
7359
  token=$token
6264
7360
  pid=$$
6265
7361
  start=$owner_start
7362
+ mode=$mode
6266
7363
  session=${FMIX_ACTIVE_SESSION_HASH:-none}
6267
7364
  command=${FMIX_INTERNAL_RUN_MODE:-${1:-fmix}}
6268
7365
  EOF
@@ -6326,6 +7423,7 @@ EOF
6326
7423
  {
6327
7424
  "lock_name": $(fmix_json_escape "$lock_name"),
6328
7425
  "pid": $$,
7426
+ "mode": $(fmix_json_escape "$mode"),
6329
7427
  "start_time": $(fmix_json_escape "$(fmix_now)"),
6330
7428
  "purpose": $(fmix_json_escape "$diagnostic_name"),
6331
7429
  "worktree": $(fmix_json_escape "${FMIX_ACTIVE_WORKTREE:-}")
@@ -6345,12 +7443,15 @@ EOF
6345
7443
  FMIX_HELD_LOCK_NAMES+=("$lock_name")
6346
7444
  FMIX_HELD_LOCK_KEEPER_PIDS+=("$keeper_pid")
6347
7445
  FMIX_HELD_LOCK_TOKENS+=("$token")
7446
+ FMIX_HELD_LOCK_MODES+=("$mode")
7447
+ FMIX_HELD_LOCK_PUBLISHED+=(1)
6348
7448
  return 0
6349
7449
  done
6350
7450
  }
6351
7451
 
6352
7452
  fmix_lock_release() {
6353
7453
  local lock_name="${1:-}" index keeper_pid token lock_dir recorded_token destination
7454
+ local published
6354
7455
  [[ -n "$lock_name" ]] || {
6355
7456
  fmix_error "fmix_lock_release called with empty lock name — refusing."
6356
7457
  return 1
@@ -6365,6 +7466,7 @@ fmix_lock_release() {
6365
7466
  }
6366
7467
  keeper_pid="${FMIX_HELD_LOCK_KEEPER_PIDS[$index]}"
6367
7468
  token="${FMIX_HELD_LOCK_TOKENS[$index]}"
7469
+ published="${FMIX_HELD_LOCK_PUBLISHED[$index]:-1}"
6368
7470
  lock_dir="$FMIX_HOME/locks/$lock_name"
6369
7471
  # A failed stop retains the indexed owner and all metadata for recovery.
6370
7472
  # Retirement can yield: recheck the token/pid afterwards, never remove a
@@ -6373,6 +7475,13 @@ fmix_lock_release() {
6373
7475
  FMIX_HELD_LOCK_NAMES[$index]=""
6374
7476
  FMIX_HELD_LOCK_KEEPER_PIDS[$index]=""
6375
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
6376
7485
  recorded_token="$(sed -n 's/^token=//p' "$lock_dir/owner" 2>/dev/null | head -1)"
6377
7486
  if [[ "$recorded_token" != "$token" ]] \
6378
7487
  || [[ "$(cat "$lock_dir/pid" 2>/dev/null || true)" != "$$" ]]; then
@@ -6398,6 +7507,68 @@ fmix_lock_failure_is_fatal() {
6398
7507
  (( ${1:-0} == 70 )) || [[ -n "$FMIX_PENDING_LOCK_KEEPER_PID" ]]
6399
7508
  }
6400
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
+
6401
7572
  fmix_lock_release_optional() {
6402
7573
  # Housekeeping may tolerate retired metadata warnings, never a pending
6403
7574
  # live owner. Do not clear handles or retry retirement here.
@@ -7162,11 +8333,30 @@ fmix_template_make_readonly() {
7162
8333
  }
7163
8334
 
7164
8335
  fmix_template_quarantine() {
7165
- 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
7166
8348
  [[ "$path" == "$FMIX_HOME/artifacts/v2/templates/"* ]] || return 1
7167
8349
  [[ -e "$path" || -L "$path" ]] || return 0
7168
- 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}"
7169
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
7170
8360
  if mv "$path" "$destination"; then
7171
8361
  fmix_warn "Quarantined template state ($reason): $destination"
7172
8362
  return 0
@@ -7212,16 +8402,44 @@ fmix_template_is_complete_unleased() {
7212
8402
  [[ -z "$writable" ]]
7213
8403
  }
7214
8404
 
7215
- 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.
7216
8410
  local key="${1:-}" tdir
7217
8411
  [[ "$key" =~ ^[0-9a-f]{16}$ ]] || return 1
7218
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
7219
8421
  if [[ "$tdir" != "$FMIX_HOME/artifacts/v2/templates/"* ]]; then
7220
8422
  fmix_template_is_complete_unleased "$key"
7221
8423
  return $?
7222
8424
  fi
7223
8425
  fmix_artifact_v2_managed_entrypoint || return 1
7224
- 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
7225
8443
  }
7226
8444
 
7227
8445
  fmix_template_verify_full_unleased() {
@@ -8814,6 +10032,8 @@ _fmix_ensure_artifacts_impl() {
8814
10032
  fi
8815
10033
  else
8816
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 $?
8817
10037
  if fmix_adopt_compatible_worktree_artifacts \
8818
10038
  "$worktree" "$recorded_key" "$template_key"; then
8819
10039
  fmix_write_artifact_state "$worktree" "$template_key" || return 1
@@ -8847,12 +10067,20 @@ _fmix_ensure_artifacts_impl() {
8847
10067
  # Need to clone from template. A normal test lane may use an existing cache
8848
10068
  # but must never launch a cold dependency/app build.
8849
10069
  if ! fmix_template_is_complete "$template_key" && [[ "$allow_template_build" != "1" ]]; then
10070
+ if [[ "${FMIX_AUTO_SETUP:-0}" == "1" ]]; then
10071
+ FMIX_LAST_ARTIFACTS_OUTCOME="missing_template"
10072
+ return 1
10073
+ fi
8850
10074
  fmix_error "Artifact template $template_key is missing."
8851
10075
  fmix_error "Refusing a cold dependency/app build in a test lane."
8852
10076
  fmix_error "Build it explicitly with: ./fmix setup --worktree $worktree"
10077
+ fmix_error "DO NOT push untested code to remote CI; run 'fmix setup --worktree $worktree' locally (takes ~30s)."
8853
10078
  FMIX_LAST_ARTIFACTS_OUTCOME="missing_template"
8854
10079
  return 1
8855
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 $?
8856
10084
  # Prefer a warm peer session for the same worktree+template over a cold
8857
10085
  # template clone (avoids ~4700-file recompile when isolate/new session).
8858
10086
  # A contended donor can be skipped, but the retry window is deliberately
@@ -8919,6 +10147,9 @@ _fmix_ensure_artifacts_impl() {
8919
10147
  }
8920
10148
 
8921
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
8922
10153
  [[ "${FMIX_ARTIFACT_AUTO_EXPIRE:-1}" == "1" ]] || return 0
8923
10154
  case "${cmd:-${FMIX_INTERNAL_RUN_MODE:-}}" in
8924
10155
  test|coverage|setup|task|format) ;;
@@ -8928,9 +10159,103 @@ fmix_auto_expire_artifacts() {
8928
10159
  return 0
8929
10160
  }
8930
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
+
8931
10248
  fmix_ensure_artifacts() {
8932
10249
  local rc=0
8933
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
8934
10259
  (( rc == 0 )) || return "$rc"
8935
10260
  fmix_auto_expire_artifacts
8936
10261
  }
@@ -10230,6 +11555,19 @@ fmix_load_structure() {
10230
11555
  }
10231
11556
 
10232
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() {
10233
11571
  # Only this admission's actual bounded cold migration failure is primary
10234
11572
  # across its caller's retirement. Metadata/clone failures are not Mix.
10235
11573
  FMIX_LAST_DB_MAINTENANCE_MIX_FAILURE=0
@@ -10295,6 +11633,7 @@ fmix_ensure_db() {
10295
11633
  # no-ops. The operator asked for a fresh database: drop it.
10296
11634
  fmix_warn "Explicit rebuild requested; replacing otherwise-valid scratch DB $db_name."
10297
11635
  valid=0
11636
+ fmix_lock_mutate_gate "scratch DB rebuild (DROP)" || return $?
10298
11637
  fmix_drop_db "$db_name" || return $?
10299
11638
  fi
10300
11639
  if (( valid == 1 )); then
@@ -10312,10 +11651,13 @@ fmix_ensure_db() {
10312
11651
  return 1
10313
11652
  fi
10314
11653
  fmix_warn "Explicit setup is replacing unverified scratch DB $db_name."
11654
+ fmix_lock_mutate_gate "scratch DB replacement (DROP)" || return $?
10315
11655
  fmix_drop_db "$db_name" || return $?
10316
11656
  fi
10317
11657
  fi
10318
11658
 
11659
+ # Scratch-DB creation (clone/cold bootstrap) mutates shared state.
11660
+ fmix_lock_mutate_gate "scratch DB creation" || return $?
10319
11661
  t0="$(fmix_epoch)"
10320
11662
  selection=""
10321
11663
  if [[ "$allow_structure_build" == "1" || "$force_from_zero" == "1" ]]; then
@@ -10475,6 +11817,9 @@ fmix_run_migration_bounded() {
10475
11817
  MEESEEKS_HTML5EVER_BUILD=0 \
10476
11818
  LOCAL_NATS="$NATS_HOST" \
10477
11819
  NATS_PORT="$NATS_PORT" \
11820
+ NATS_HOST="$NATS_HOST" \
11821
+ CT_NATS_HOST="$NATS_HOST" \
11822
+ NATS_URL="nats://${NATS_HOST}:${NATS_PORT}" \
10478
11823
  POSTHOG_BACKEND_ENABLED="${POSTHOG_BACKEND_ENABLED:-false}" \
10479
11824
  POSTHOG_BROWSER_ENABLED="${POSTHOG_BROWSER_ENABLED:-false}" \
10480
11825
  mix ecto.migrate --no-compile
@@ -10537,6 +11882,35 @@ EOF
10537
11882
  mv "$tmp" "$stamp" || { rm -f "$tmp"; return 1; }
10538
11883
  }
10539
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
+
10540
11914
  fmix_schema_ready_stamp_matches() {
10541
11915
  local worktree="$1" db_name="$2" stamp mig_stamp schema_key
10542
11916
  local recorded_db recorded_mig recorded_schema recorded_epoch ttl age now
@@ -10571,9 +11945,36 @@ fmix_schema_ready_stamp_matches() {
10571
11945
  }
10572
11946
 
10573
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() {
10574
11961
  local worktree="$1" db_name="$2" state_file="$3"
10575
11962
  fmix_prepend_toolchain_paths
10576
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
+
10577
11978
  # Warm path: prior success stamp matching migration files + db name skips
10578
11979
  # repeated ledger scans (was ~2 full psql + file walks per run).
10579
11980
  if fmix_schema_ready_stamp_matches "$worktree" "$db_name"; then
@@ -10700,6 +12101,9 @@ fmix_ensure_partitions() {
10700
12101
  MEESEEKS_HTML5EVER_BUILD=0 \
10701
12102
  LOCAL_NATS="$NATS_HOST" \
10702
12103
  NATS_PORT="$NATS_PORT" \
12104
+ NATS_HOST="$NATS_HOST" \
12105
+ CT_NATS_HOST="$NATS_HOST" \
12106
+ NATS_URL="nats://${NATS_HOST}:${NATS_PORT}" \
10703
12107
  POSTHOG_BACKEND_ENABLED="${POSTHOG_BACKEND_ENABLED:-false}" \
10704
12108
  POSTHOG_BROWSER_ENABLED="${POSTHOG_BROWSER_ENABLED:-false}" \
10705
12109
  env -u DB_HOST_IPV4 mix cdrcisco.bootstrap_partitions
@@ -10832,6 +12236,7 @@ fmix_hash_compile_paths() {
10832
12236
  rm -f "$untracked_file"
10833
12237
  return 1
10834
12238
  fi
12239
+ local -a untracked_pairs=()
10835
12240
  while IFS= read -r -d '' path; do
10836
12241
  case "$path" in
10837
12242
  _build|_build/*|deps|deps/*) continue ;;
@@ -10842,11 +12247,11 @@ fmix_hash_compile_paths() {
10842
12247
  return 1
10843
12248
  fi
10844
12249
  [[ -f "$root/$path" ]] || continue
10845
- printf 'untracked:%s:' "$path"
10846
- fmix_hash_files "$root/$path" \
10847
- || { rm -f "$untracked_file"; return 1; }
12250
+ untracked_pairs+=("$path" "$root/$path")
10848
12251
  done <"$untracked_file"
10849
12252
  rm -f "$untracked_file"
12253
+ fmix_hash_paired_lines "untracked" \
12254
+ "${untracked_pairs[@]+"${untracked_pairs[@]}"}" || return 1
10850
12255
  return 0
10851
12256
  fi
10852
12257
 
@@ -10859,10 +12264,12 @@ fmix_hash_compile_paths() {
10859
12264
  fmix_hash_files "$root/$path"
10860
12265
  elif [[ -d "$root/$path" ]]; then
10861
12266
  fmix_reject_nested_source_symlinks "$root/$path" || return 1
12267
+ local -a dir_pairs=()
10862
12268
  while IFS= read -r file; do
10863
- printf 'file:%s:' "${file#"$root/"}"
10864
- fmix_hash_files "$file"
12269
+ dir_pairs+=("${file#"$root/"}" "$file")
10865
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
10866
12273
  else
10867
12274
  printf 'missing:%s\n' "$path"
10868
12275
  fi
@@ -10896,6 +12303,7 @@ fmix_ignored_compile_inputs_hash() {
10896
12303
  return 1
10897
12304
  fi
10898
12305
  rc=0
12306
+ local -a ignored_pairs=()
10899
12307
  {
10900
12308
  printf 'fmix-ignored-compile-inputs-v1\n'
10901
12309
  while IFS= read -r -d '' path; do
@@ -10905,12 +12313,10 @@ fmix_ignored_compile_inputs_hash() {
10905
12313
  ;;
10906
12314
  esac
10907
12315
  [[ -f "$real/$path" ]] || continue
10908
- printf 'ignored:%s:' "$path"
10909
- if ! fmix_hash_files "$real/$path"; then
10910
- rc=1
10911
- break
10912
- fi
12316
+ ignored_pairs+=("$path" "$real/$path")
10913
12317
  done <"$ignored_file"
12318
+ fmix_hash_paired_lines "ignored" \
12319
+ "${ignored_pairs[@]+"${ignored_pairs[@]}"}" || rc=1
10914
12320
  } >"$manifest"
10915
12321
  rm -f "$ignored_file"
10916
12322
  if (( rc != 0 )); then
@@ -11117,6 +12523,11 @@ fmix_invalidate_dependency_stamp() {
11117
12523
 
11118
12524
  fmix_invalidate_rejected_stamps() {
11119
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
11120
12531
  fmix_invalidate_compile_stamp "$worktree" || rc=1
11121
12532
  fmix_invalidate_dependency_stamp "$worktree" || rc=1
11122
12533
  return "$rc"
@@ -11131,6 +12542,23 @@ fmix_require_stable_source() {
11131
12542
  || fmix_invalidate_rejected_stamps "$worktree"
11132
12543
  return 1
11133
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
11134
12562
  current="$(fmix_source_stability_identity \
11135
12563
  "$worktree" \
11136
12564
  "${FMIX_SOURCE_STABILITY_SELECTED_ARGS[@]+"${FMIX_SOURCE_STABILITY_SELECTED_ARGS[@]}"}")" \
@@ -11418,10 +12846,13 @@ fmix_compile_environment() {
11418
12846
  fmix_emit_environment_fingerprint MEESEEKS_HTML5EVER_BUILD 0
11419
12847
  fmix_emit_environment_fingerprint LOCAL_NATS "$NATS_HOST"
11420
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}"
11421
12852
  printf '%s\n' "${compiler_vars[@]}" "$discovered" \
11422
12853
  | sed '/^$/d' | LC_ALL=C sort -u | while IFS= read -r name; do
11423
12854
  case "$name" in
11424
- 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)
11425
12856
  # Effective fmix values were emitted above; ignore ambient copies.
11426
12857
  ;;
11427
12858
  MIX_BUILD_PATH|MIX_DEPS_PATH)
@@ -11798,7 +13229,7 @@ from pathlib import Path
11798
13229
 
11799
13230
  root = Path(sys.argv[1])
11800
13231
  h = hashlib.sha256()
11801
- h.update(b"fmix-compile-quick-guard-v1\n")
13232
+ h.update(b"fmix-compile-quick-guard-v2\n")
11802
13233
 
11803
13234
  def add_file(rel: str) -> None:
11804
13235
  p = root / rel
@@ -11818,9 +13249,12 @@ for rel in (
11818
13249
  ):
11819
13250
  add_file(rel)
11820
13251
 
11821
- # Newest mtime under compile roots — detects leaf edits without full content hash.
11822
- max_mtime = 0.0
11823
- 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 = []
11824
13258
  for rel in (
11825
13259
  "lib",
11826
13260
  "test/support",
@@ -11834,10 +13268,10 @@ for rel in (
11834
13268
  continue
11835
13269
  if base.is_file():
11836
13270
  try:
11837
- max_mtime = max(max_mtime, base.stat().st_mtime)
11838
- 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")
11839
13273
  except OSError:
11840
- pass
13274
+ stat_records.append(f"{rel}\0stat-error\n")
11841
13275
  continue
11842
13276
  for dirpath, dirnames, filenames in os.walk(base):
11843
13277
  # Skip heavy/irrelevant trees
@@ -11845,15 +13279,16 @@ for rel in (
11845
13279
  for name in filenames:
11846
13280
  if not name.endswith((".ex", ".exs", ".heex", ".eex", ".leex", ".erl", ".hrl", ".c", ".h", ".rs", ".toml")):
11847
13281
  continue
13282
+ full = os.path.join(dirpath, name)
13283
+ rel_path = os.path.relpath(full, root)
11848
13284
  try:
11849
- 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")
11850
13287
  except OSError:
11851
- continue
11852
- max_mtime = max(max_mtime, st.st_mtime)
11853
- file_count += 1
13288
+ stat_records.append(f"{rel_path}\0stat-error\n")
11854
13289
 
11855
- h.update(f"max_mtime={max_mtime:.6f}\n".encode())
11856
- h.update(f"file_count={file_count}\n".encode())
13290
+ for stat_record in sorted(stat_records):
13291
+ h.update(stat_record.encode())
11857
13292
  # Top-level deps dir signature (count + names + mtimes) — cheap vs full source_guard.
11858
13293
  deps = root # MIX_DEPS_PATH may be external; prefer env
11859
13294
  deps_path = os.environ.get("MIX_DEPS_PATH") or str(root / "deps")
@@ -11960,10 +13395,12 @@ fmix_compute_dirty_hash() {
11960
13395
  printf '%s\n' "$status"
11961
13396
  cat "$diff_file" || exit 1
11962
13397
  cat "$staged_file" || exit 1
13398
+ local -a untracked_pairs=()
11963
13399
  for file in "${untracked[@]+"${untracked[@]}"}"; do
11964
- printf 'untracked:%s:' "$file"
11965
- fmix_hash_files "$real/$file" || exit 1
13400
+ untracked_pairs+=("$file" "$real/$file")
11966
13401
  done
13402
+ fmix_hash_paired_lines "untracked" \
13403
+ "${untracked_pairs[@]+"${untracked_pairs[@]}"}" || exit 1
11967
13404
  ) >"$manifest"
11968
13405
  rc=$?
11969
13406
  rm -f "$untracked_file" "$diff_file" "$staged_file"
@@ -11993,6 +13430,7 @@ fmix_write_compile_stamp() {
11993
13430
  _fmix_write_compile_stamp_locked() {
11994
13431
  local worktree="$1" fingerprint="$2" real build_root guard dependency_guard stamp tmp quick_guard template_key
11995
13432
  local template_key tree_hash env_hash dirty_hash ignored_compile_hash source_stability_identity
13433
+ local stat_manifest
11996
13434
  real="$(fmix_realpath "$worktree")"
11997
13435
  build_root="$(fmix_compile_build_root "$real")"
11998
13436
  guard="$(fmix_compile_manifest_guard "$real")" || return 1
@@ -12009,6 +13447,7 @@ _fmix_write_compile_stamp_locked() {
12009
13447
  ignored_compile_hash="$(fmix_ignored_compile_inputs_hash "$real" 2>/dev/null)" \
12010
13448
  || return 1
12011
13449
  source_stability_identity="${FMIX_SOURCE_STABILITY_COMPILE_IDENTITY:-}"
13450
+ stat_manifest="$(fmix_stat_hash_cache_dump 2>/dev/null)" || stat_manifest=""
12012
13451
  stamp="$(fmix_compile_stamp_file "$real")"
12013
13452
  mkdir -p "$(dirname "$stamp")"
12014
13453
  tmp="$(mktemp "${stamp}.tmp.XXXXXX")" || return 1
@@ -12026,7 +13465,10 @@ _fmix_write_compile_stamp_locked() {
12026
13465
  "manifest_guard": $(fmix_json_escape "$guard"),
12027
13466
  "dependency_source_guard": $(fmix_json_escape "$dependency_guard"),
12028
13467
  "quick_guard": $(fmix_json_escape "$quick_guard"),
13468
+ "stat_manifest": $(fmix_json_escape "$stat_manifest"),
12029
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:-}"),
12030
13472
  "compiled_at": $(fmix_json_escape "$(fmix_now)")
12031
13473
  }
12032
13474
  EOF
@@ -12091,7 +13533,22 @@ fmix_try_compile_stamp_quick_hit() {
12091
13533
  || return 1
12092
13534
  # Git's status/index stat cache and the mtime quick guard are only early
12093
13535
  # rejectors. Admission is content-exact for the bounded compiler inputs.
12094
- 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
12095
13552
  [[ "$recorded_fingerprint" == "$current_fingerprint" ]] || return 1
12096
13553
  current_dependency_guard="$(fmix_dependency_source_guard "$real")" || return 1
12097
13554
  [[ "$recorded_dependency_guard" == "$current_dependency_guard" ]] || return 1
@@ -12726,6 +14183,9 @@ _fmix_run_compile() {
12726
14183
  MEESEEKS_HTML5EVER_BUILD=0 \
12727
14184
  LOCAL_NATS="$NATS_HOST" \
12728
14185
  NATS_PORT="$NATS_PORT" \
14186
+ NATS_HOST="$NATS_HOST" \
14187
+ CT_NATS_HOST="$NATS_HOST" \
14188
+ NATS_URL="nats://${NATS_HOST}:${NATS_PORT}" \
12729
14189
  POSTHOG_BACKEND_ENABLED="${POSTHOG_BACKEND_ENABLED:-false}" \
12730
14190
  POSTHOG_BROWSER_ENABLED="${POSTHOG_BROWSER_ENABLED:-false}" \
12731
14191
  mix compile $extra 2>&1
@@ -13011,6 +14471,19 @@ fmix_run_deps_get() {
13011
14471
  }
13012
14472
 
13013
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() {
13014
14487
  local worktree="$1" db_name="$2" compile_mode="${3:-incremental}"
13015
14488
  fmix_prepend_toolchain_paths
13016
14489
  FMIX_LAST_COMPILE_OUTCOME=""
@@ -13041,6 +14514,9 @@ fmix_ensure_compile() {
13041
14514
  FMIX_LAST_COMPILE_OUTCOME="stamp_hit_quick"
13042
14515
  return 0
13043
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 $?
13044
14520
 
13045
14521
  # The content/config stamp is authoritative for this exact realpath and
13046
14522
  # includes mix.lock, toolchain, compiler config, path deps, and Mix
@@ -13117,6 +14593,25 @@ fmix_ensure_compile() {
13117
14593
  return 0
13118
14594
  fi
13119
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
+
13120
14615
  fmix_info "Compiling app (incremental) …"
13121
14616
  local stamp_file log_file t0 t1 rc
13122
14617
  stamp_file="$(fmix_compile_stamp_file "$worktree")"
@@ -13193,19 +14688,41 @@ fmix_ensure_compile() {
13193
14688
  return 1
13194
14689
  fi
13195
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
13196
14697
  fingerprint="$(fmix_compute_compile_fingerprint "$worktree")" || fingerprint=""
13197
14698
  if [[ -z "$fingerprint" ]] \
13198
14699
  || ! fmix_require_stable_source "$worktree" "compile stamp construction" 1 \
13199
14700
  || ! fmix_write_compile_stamp "$worktree" "$fingerprint"; then
14701
+ fmix_stat_hash_cache_done
13200
14702
  fmix_invalidate_rejected_stamps "$worktree"
13201
14703
  fmix_error "Compile succeeded, but final content/config provenance could not be recorded."
13202
14704
  FMIX_LAST_COMPILE_OUTCOME="error"
13203
14705
  return 1
13204
14706
  fi
13205
14707
  if ! fmix_require_stable_source "$worktree" "compile stamp publication" 1; then
14708
+ fmix_stat_hash_cache_done
13206
14709
  FMIX_LAST_COMPILE_OUTCOME="error"
13207
14710
  return 1
13208
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
13209
14726
  return 0
13210
14727
  }
13211
14728
 
@@ -13527,7 +15044,51 @@ cmd_setup() {
13527
15044
  fmix_command_lock_finish "$lock_name" "$setup_publication_rc"
13528
15045
  return $?
13529
15046
  fi
13530
- fmix_warn "Could not backfill the exact dependency artifact during setup."
15047
+ fmix_warn "Could not backfill the exact dependency artifact during setup."
15048
+ fi
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
13531
15092
  fi
13532
15093
  fi
13533
15094
  fmix_ensure_db "$real_worktree" "$db_name" "$rebuild_existing" "$allow_structure_build" 1 "$force_from_zero" || {
@@ -13655,6 +15216,10 @@ fmix_ensure_chromium() {
13655
15216
  # (quotes, backslashes, $) can't break or inject into the wrapper script.
13656
15217
  safe_chrome="${chrome//\'/\'\\\'\'}"
13657
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
13658
15223
  printf '#!/bin/sh\nexec '\''%s'\'' "$@"\n' "$safe_chrome" >"$shim" || return 1
13659
15224
  chmod +x "$shim" || return 1
13660
15225
  fi
@@ -13787,9 +15352,17 @@ cmd_test() {
13787
15352
  # that don't `use` a DB-capable case).
13788
15353
  local unit_mode=0
13789
15354
  local isolate_mode=0
15355
+ local auto_setup=1
15356
+ if [[ "${FMIX_NO_AUTO_SETUP:-0}" == "1" ]]; then
15357
+ auto_setup=0
15358
+ fi
13790
15359
 
13791
15360
  while (( $# > 0 )); do
13792
15361
  case "$1" in
15362
+ --no-auto-setup)
15363
+ auto_setup=0
15364
+ shift
15365
+ ;;
13793
15366
  --worktree) [[ $# -ge 2 ]] || { fmix_error "--worktree requires a path argument."; return 2; }; worktree_arg="$2"; shift 2 ;;
13794
15367
  --worktree=*) worktree_arg="${1#--worktree=}"; shift ;;
13795
15368
  --cache-base) [[ $# -ge 2 ]] || { fmix_error "--cache-base requires a stable branch."; return 2; }; cache_base="$2"; shift 2 ;;
@@ -13871,7 +15444,7 @@ cmd_test() {
13871
15444
  --) found_sep=1; shift; break ;;
13872
15445
  *)
13873
15446
  if [[ "$run_mode" == "coverage" ]]; then
13874
- 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>"
13875
15448
  else
13876
15449
  fmix_error "Unknown option: $1. Usage: fmix test [--worktree <path>] [--cache-base <N.N.N-stable>] [--unit] -- <mix test args>"
13877
15450
  fi
@@ -13916,7 +15489,7 @@ cmd_test() {
13916
15489
  done
13917
15490
  fi
13918
15491
  local coverage_source
13919
- for coverage_source in "${coverage_sources[@]}"; do
15492
+ for coverage_source in ${coverage_sources[@]+"${coverage_sources[@]}"}; do
13920
15493
  if [[ "$coverage_source" != lib/*.ex ]]; then
13921
15494
  fmix_error "--source must name a lib/**/*.ex file: $coverage_source"
13922
15495
  return 2
@@ -14011,11 +15584,28 @@ cmd_test() {
14011
15584
  fmix_run_telemetry_phase "preflight"
14012
15585
  fmix_emit_phase_change "preflight" "completed"
14013
15586
 
14014
- # Per-worktree lock (serializes concurrent runs in same worktree)
14015
- 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"
14016
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
14017
15606
  fmix_emit_phase_change "lock" "started"
14018
- 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" || {
14019
15609
  local lock_rc=$?
14020
15610
  fmix_emit_phase_change "lock" "failed"
14021
15611
  fmix_run_telemetry_finish "$lock_rc"
@@ -14031,11 +15621,26 @@ cmd_test() {
14031
15621
  local FMIX_SOURCE_STABILITY_REQUIRED=1
14032
15622
  local FMIX_SOURCE_STABILITY_IDENTITY=""
14033
15623
  local FMIX_SOURCE_STABILITY_COMPILE_IDENTITY=""
15624
+ local FMIX_SOURCE_STABILITY_ARGS_HASH=""
14034
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
14035
15639
  FMIX_SOURCE_STABILITY_IDENTITY="$(fmix_source_stability_identity \
14036
15640
  "$real_worktree" \
14037
15641
  "${FMIX_SOURCE_STABILITY_SELECTED_ARGS[@]+"${FMIX_SOURCE_STABILITY_SELECTED_ARGS[@]}"}")" \
14038
15642
  || {
15643
+ fmix_stat_hash_cache_done
14039
15644
  fmix_error "Could not capture a source-stability identity after acquiring the worktree lock."
14040
15645
  fmix_invalidate_rejected_stamps "$real_worktree"
14041
15646
  local source_rc=1
@@ -14046,6 +15651,7 @@ cmd_test() {
14046
15651
  FMIX_SOURCE_STABILITY_COMPILE_IDENTITY="$(
14047
15652
  fmix_source_stability_compile_identity "$real_worktree"
14048
15653
  )" || {
15654
+ fmix_stat_hash_cache_done
14049
15655
  fmix_error "Could not capture compile-source identity after acquiring the worktree lock."
14050
15656
  fmix_invalidate_rejected_stamps "$real_worktree"
14051
15657
  local source_rc=1
@@ -14053,6 +15659,7 @@ cmd_test() {
14053
15659
  fmix_run_telemetry_finish "$source_rc"
14054
15660
  return "$source_rc"
14055
15661
  }
15662
+ fmix_stat_hash_cache_done
14056
15663
  if ! fmix_require_stable_source "$real_worktree" "source identity capture" 1; then
14057
15664
  local source_rc=1
14058
15665
  fmix_command_lock_finish "$lock_name" "$source_rc" || source_rc=$?
@@ -14085,14 +15692,50 @@ cmd_test() {
14085
15692
  fi
14086
15693
  fi
14087
15694
  if (( stable_seed_restored == 0 )); then
14088
- fmix_ensure_artifacts "$real_worktree" "$template_key" 0 || {
14089
- local operation_rc=$?
14090
- fmix_command_lock_finish "$lock_name" "$operation_rc" || operation_rc=$?
14091
- FMIX_LAST_ARTIFACTS_OUTCOME="${FMIX_LAST_ARTIFACTS_OUTCOME:-error}"
14092
- fmix_emit_phase_change "artifacts" "failed"
14093
- fmix_run_telemetry_finish "$operation_rc"
14094
- return "$operation_rc"
14095
- }
15695
+ local artifacts_rc=0
15696
+ FMIX_AUTO_SETUP="$auto_setup" fmix_ensure_artifacts "$real_worktree" "$template_key" 0 || artifacts_rc=$?
15697
+ if (( artifacts_rc != 0 )); then
15698
+ if [[ "$FMIX_LAST_ARTIFACTS_OUTCOME" == "missing_template" && "$auto_setup" == "1" ]]; then
15699
+ fmix_info "Artifact template $template_key is missing. Auto-bootstrapping setup (--worktree $real_worktree)..."
15700
+ fmix_command_lock_finish "$lock_name" 0 || true
15701
+ local setup_rc=0
15702
+ local -a auto_setup_cmd=(cmd_setup --worktree "$real_worktree")
15703
+ [[ -n "$session_arg" ]] && auto_setup_cmd+=(--session "$session_arg")
15704
+ "${auto_setup_cmd[@]}" || setup_rc=$?
15705
+ if (( setup_rc != 0 )); then
15706
+ fmix_error "Auto-setup failed (exit $setup_rc)."
15707
+ fmix_error "DO NOT push untested code to remote CI; run 'fmix setup --worktree $real_worktree' locally (takes ~30s)."
15708
+ fmix_emit_phase_change "artifacts" "failed"
15709
+ fmix_run_telemetry_finish "$setup_rc"
15710
+ fmix_write_test_receipt "$real_worktree" "$setup_rc" "$session_arg" "${mix_args[*]:-}"
15711
+ return "$setup_rc"
15712
+ fi
15713
+ fmix_lock_acquire "$lock_name" "$FMIX_WORKTREE_LOCK_TIMEOUT" || {
15714
+ local re_lock_rc=$?
15715
+ fmix_emit_phase_change "artifacts" "failed"
15716
+ fmix_run_telemetry_finish "$re_lock_rc"
15717
+ fmix_write_test_receipt "$real_worktree" "$re_lock_rc" "$session_arg" "${mix_args[*]:-}"
15718
+ return "$re_lock_rc"
15719
+ }
15720
+ FMIX_AUTO_SETUP=0 fmix_ensure_artifacts "$real_worktree" "$template_key" 0 || {
15721
+ local operation_rc=$?
15722
+ fmix_command_lock_finish "$lock_name" "$operation_rc" || operation_rc=$?
15723
+ FMIX_LAST_ARTIFACTS_OUTCOME="${FMIX_LAST_ARTIFACTS_OUTCOME:-error}"
15724
+ fmix_emit_phase_change "artifacts" "failed"
15725
+ fmix_run_telemetry_finish "$operation_rc"
15726
+ fmix_write_test_receipt "$real_worktree" "$operation_rc" "$session_arg" "${mix_args[*]:-}"
15727
+ return "$operation_rc"
15728
+ }
15729
+ else
15730
+ local operation_rc="$artifacts_rc"
15731
+ fmix_command_lock_finish "$lock_name" "$operation_rc" || operation_rc=$?
15732
+ FMIX_LAST_ARTIFACTS_OUTCOME="${FMIX_LAST_ARTIFACTS_OUTCOME:-error}"
15733
+ fmix_emit_phase_change "artifacts" "failed"
15734
+ fmix_run_telemetry_finish "$operation_rc"
15735
+ fmix_write_test_receipt "$real_worktree" "$operation_rc" "$session_arg" "${mix_args[*]:-}"
15736
+ return "$operation_rc"
15737
+ fi
15738
+ fi
14096
15739
  FMIX_LAST_ARTIFACTS_OUTCOME="${FMIX_LAST_ARTIFACTS_OUTCOME:-ready}"
14097
15740
  fi
14098
15741
  fmix_run_telemetry_phase "artifacts"
@@ -14106,6 +15749,7 @@ cmd_test() {
14106
15749
  fmix_command_lock_finish "$lock_name" "$compile_rc" 1 || compile_rc=$?
14107
15750
  fmix_emit_phase_change "compile" "failed"
14108
15751
  fmix_run_telemetry_finish "$compile_rc"
15752
+ fmix_write_test_receipt "$real_worktree" "$compile_rc" "$session_arg" "${mix_args[*]:-}"
14109
15753
  return "$compile_rc"
14110
15754
  fi
14111
15755
  if ! fmix_require_stable_source "$real_worktree" "compilation" 1; then
@@ -14113,6 +15757,7 @@ cmd_test() {
14113
15757
  fmix_command_lock_finish "$lock_name" "$source_rc" || source_rc=$?
14114
15758
  fmix_emit_phase_change "compile" "failed"
14115
15759
  fmix_run_telemetry_finish "$source_rc"
15760
+ fmix_write_test_receipt "$real_worktree" "$source_rc" "$session_arg" "${mix_args[*]:-}"
14116
15761
  return "$source_rc"
14117
15762
  fi
14118
15763
  fmix_run_telemetry_phase "compile"
@@ -14145,7 +15790,7 @@ cmd_test() {
14145
15790
  local mig_stamp schema_key
14146
15791
  schema_key="$FMIX_ACTIVE_DB_SCHEMA_KEY"
14147
15792
  mig_stamp="$(fmix_migration_stamp "$real_worktree")"
14148
- 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" || {
14149
15794
  local operation_rc=$?
14150
15795
  fmix_command_lock_finish "$lock_name" "$operation_rc" || operation_rc=$?
14151
15796
  fmix_run_telemetry_finish "$operation_rc"
@@ -14245,6 +15890,9 @@ cmd_test() {
14245
15890
  DB_TEST_POOL_SIZE=30
14246
15891
  LOCAL_NATS="$NATS_HOST"
14247
15892
  NATS_PORT="$NATS_PORT"
15893
+ NATS_HOST="$NATS_HOST"
15894
+ CT_NATS_HOST="$NATS_HOST"
15895
+ NATS_URL="nats://${NATS_HOST}:${NATS_PORT}"
14248
15896
  WORKER_NODE=TRUE
14249
15897
  ADMIN_NODE=TRUE
14250
15898
  ONPREM=TRUE
@@ -14313,7 +15961,7 @@ end
14313
15961
  '
14314
15962
  local -a coverage_source_args=()
14315
15963
  local coverage_source
14316
- for coverage_source in "${coverage_sources[@]}"; do
15964
+ for coverage_source in ${coverage_sources[@]+"${coverage_sources[@]}"}; do
14317
15965
  coverage_source_args+=(--source "$coverage_source")
14318
15966
  done
14319
15967
  exec env "${common_env[@]}" \
@@ -14360,6 +16008,7 @@ end
14360
16008
  else
14361
16009
  fmix_info "Test run completed in $(( t1 - t0 ))s (rc=$test_rc)."
14362
16010
  fi
16011
+ fmix_write_test_receipt "$real_worktree" "$test_rc" "$session_arg" "${mix_args[*]:-}"
14363
16012
  fmix_run_telemetry_finish "$test_rc"
14364
16013
  return $test_rc
14365
16014
  }
@@ -14368,6 +16017,414 @@ cmd_coverage() {
14368
16017
  FMIX_INTERNAL_RUN_MODE=coverage cmd_test "$@"
14369
16018
  }
14370
16019
 
16020
+ # ---------------------------------------------------------------------------
16021
+ # Pre-Push Circuit Breaker & Proof-of-Test Receipt
16022
+ # ---------------------------------------------------------------------------
16023
+
16024
+ fmix_git_dir() {
16025
+ local wt="$1"
16026
+ local gd
16027
+ gd="$(git -C "$wt" rev-parse --path-format=absolute --git-dir 2>/dev/null)" || {
16028
+ gd="$(git -C "$wt" rev-parse --git-dir 2>/dev/null)" || return 1
16029
+ gd="$(cd "$wt" && cd "$gd" && pwd -P)" || return 1
16030
+ }
16031
+ printf '%s\n' "$gd"
16032
+ }
16033
+
16034
+ fmix_compute_code_tree_hash() {
16035
+ local wt="$1"
16036
+ local py_bin
16037
+ py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
16038
+ "$py_bin" - "$wt" <<'PY'
16039
+ import hashlib, os, subprocess, sys
16040
+ from pathlib import Path
16041
+
16042
+ root = Path(sys.argv[1]).resolve()
16043
+ tree = {}
16044
+ prefixes = ("lib", "test", "priv", "config", "mix.exs", "mix.lock")
16045
+
16046
+ # 1. Committed blobs from HEAD
16047
+ res = subprocess.run(
16048
+ ["git", "-C", str(root), "-c", "core.quotepath=false", "ls-tree", "-r", "HEAD", "--", *prefixes],
16049
+ capture_output=True, text=True, check=False
16050
+ )
16051
+ if res.returncode == 0:
16052
+ for line in res.stdout.splitlines():
16053
+ if not line:
16054
+ continue
16055
+ parts = line.split(None, 3)
16056
+ if len(parts) >= 4 and parts[1] == "blob":
16057
+ tree[parts[3]] = parts[2]
16058
+
16059
+ # 2. Status changes (modified, added, untracked, deleted)
16060
+ res = subprocess.run(
16061
+ ["git", "-C", str(root), "-c", "core.quotepath=false", "status", "--porcelain", "-uall", "--", *prefixes],
16062
+ capture_output=True, text=True, check=False
16063
+ )
16064
+ if res.returncode == 0:
16065
+ for line in res.stdout.splitlines():
16066
+ if not line:
16067
+ continue
16068
+ rpath = line[3:].strip()
16069
+ if " -> " in rpath:
16070
+ old_p, new_p = rpath.split(" -> ", 1)
16071
+ tree.pop(old_p.strip(), None)
16072
+ rpath = new_p.strip()
16073
+ fpath = root / rpath
16074
+ if fpath.is_file() and not fpath.is_symlink():
16075
+ try:
16076
+ data = fpath.read_bytes()
16077
+ sha = hashlib.sha1(f"blob {len(data)}\0".encode("utf-8") + data).hexdigest()
16078
+ tree[rpath] = sha
16079
+ except OSError:
16080
+ tree.pop(rpath, None)
16081
+ else:
16082
+ tree.pop(rpath, None)
16083
+
16084
+ manifest = "\n".join(f"{p}\t{tree[p]}" for p in sorted(tree.keys())) + "\n"
16085
+ print(hashlib.sha256(manifest.encode("utf-8")).hexdigest())
16086
+ PY
16087
+ }
16088
+
16089
+ fmix_write_test_receipt() {
16090
+ local wt="$1" rc="${2:-0}" session="${3:-}" test_args="${4:-}"
16091
+ local git_dir
16092
+ git_dir="$(fmix_git_dir "$wt" 2>/dev/null)" || return 0
16093
+ [[ -d "$git_dir" ]] || return 0
16094
+
16095
+ local code_tree_hash
16096
+ code_tree_hash="$(fmix_compute_code_tree_hash "$wt" 2>/dev/null)" || code_tree_hash=""
16097
+ [[ -n "$code_tree_hash" ]] || return 0
16098
+
16099
+ local head_sha
16100
+ head_sha="$(git -C "$wt" rev-parse HEAD 2>/dev/null || echo "0000000000000000000000000000000000000000")"
16101
+ local now
16102
+ now="$(fmix_epoch)"
16103
+ local passed="false"
16104
+ (( rc == 0 )) && passed="true"
16105
+
16106
+ local receipt_file="$git_dir/ct-fmix-receipt.json"
16107
+ local tmp_file
16108
+ tmp_file="$(mktemp "${TMPDIR:-/tmp}/ct-fmix-receipt.XXXXXX")" || return 0
16109
+
16110
+ local py_bin
16111
+ py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
16112
+ "$py_bin" - "$tmp_file" "$passed" "$rc" "$now" "$head_sha" "$code_tree_hash" "$session" "$test_args" <<'PY'
16113
+ import json, sys
16114
+ tmp_file, passed, rc, ts, head, code_hash, session, args = sys.argv[1:9]
16115
+ doc = {
16116
+ "schema_version": 1,
16117
+ "passed": passed == "true",
16118
+ "rc": int(rc),
16119
+ "ts_epoch": int(ts),
16120
+ "head_sha": head,
16121
+ "code_tree_hash": code_hash,
16122
+ "session": session,
16123
+ "test_args": args
16124
+ }
16125
+ with open(tmp_file, "w", encoding="utf-8") as f:
16126
+ json.dump(doc, f, indent=2)
16127
+ f.write("\n")
16128
+ PY
16129
+ mv -f "$tmp_file" "$receipt_file" 2>/dev/null || rm -f "$tmp_file"
16130
+ fmix_info "Proof-of-test receipt recorded at $receipt_file (passed=$passed, code_tree_hash=$code_tree_hash)"
16131
+ }
16132
+
16133
+ fmix_record_push_ledger() {
16134
+ local wt="$1" git_dir="$2"
16135
+ local ledger_file="$git_dir/ct-push-ledger.tsv"
16136
+ local branch
16137
+ branch="$(git -C "$wt" rev-parse --abbrev-ref HEAD 2>/dev/null || echo "HEAD")"
16138
+ local now
16139
+ now="$(fmix_epoch)"
16140
+ local receipt_file="$git_dir/ct-fmix-receipt.json"
16141
+ local receipt_epoch=0
16142
+ if [[ -f "$receipt_file" ]]; then
16143
+ receipt_epoch="$(grep -o '"ts_epoch":[[:space:]]*[0-9]*' "$receipt_file" 2>/dev/null | awk -F: '{print $2}' | tr -d ' ')"
16144
+ fi
16145
+ receipt_epoch="${receipt_epoch:-0}"
16146
+ printf '%s\t%s\t%s\t%s\n' "$now" "$branch" "pass" "$receipt_epoch" >> "$ledger_file"
16147
+ }
16148
+
16149
+ cmd_verify_push() {
16150
+ local worktree_arg="auto"
16151
+ local cooldown_minutes=30
16152
+ local require_receipt=0
16153
+
16154
+ while (( $# > 0 )); do
16155
+ case "$1" in
16156
+ --worktree)
16157
+ [[ $# -ge 2 ]] || { fmix_error "--worktree requires a path argument."; return 2; }
16158
+ worktree_arg="$2"
16159
+ shift 2
16160
+ ;;
16161
+ --worktree=*)
16162
+ worktree_arg="${1#--worktree=}"
16163
+ shift
16164
+ ;;
16165
+ --cooldown-minutes)
16166
+ [[ $# -ge 2 ]] || { fmix_error "--cooldown-minutes requires an integer."; return 2; }
16167
+ cooldown_minutes="$2"
16168
+ shift 2
16169
+ ;;
16170
+ --cooldown-minutes=*)
16171
+ cooldown_minutes="${1#--cooldown-minutes=}"
16172
+ shift
16173
+ ;;
16174
+ --require-receipt)
16175
+ require_receipt=1
16176
+ shift
16177
+ ;;
16178
+ --help|-h)
16179
+ fmix_verb_help "verify-push"
16180
+ return 0
16181
+ ;;
16182
+ *)
16183
+ # Git pre-push hook passes remote name and url as positional arguments; ignore them
16184
+ shift
16185
+ ;;
16186
+ esac
16187
+ done
16188
+
16189
+ # 1. Human Escape Hatch
16190
+ if [[ "${CT_HUMAN:-0}" == "1" || "${FMIX_BYPASS_PUSH_GATE:-0}" == "1" ]]; then
16191
+ fmix_info "[fmix verify-push] Push allowed: human bypass active (CT_HUMAN=1 or FMIX_BYPASS_PUSH_GATE=1)."
16192
+ return 0
16193
+ fi
16194
+
16195
+ local worktree=""
16196
+ if [[ "$worktree_arg" != "auto" ]]; then
16197
+ worktree="$(fmix_find_worktree "$worktree_arg" 2>/dev/null || fmix_realpath "$worktree_arg")"
16198
+ else
16199
+ worktree="$(fmix_find_worktree auto 2>/dev/null || git rev-parse --show-toplevel 2>/dev/null || pwd -P)"
16200
+ fi
16201
+ local real_worktree
16202
+ real_worktree="$(fmix_realpath "$worktree")"
16203
+
16204
+ if ! git -C "$real_worktree" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
16205
+ fmix_error "Path is not inside a git worktree: $real_worktree"
16206
+ return 1
16207
+ fi
16208
+
16209
+ local git_dir
16210
+ git_dir="$(fmix_git_dir "$real_worktree")" || {
16211
+ fmix_error "Could not resolve git directory for $real_worktree"
16212
+ return 1
16213
+ }
16214
+
16215
+ # 2. Docs / Workflow-Only Fast Pass
16216
+ local base_ref=""
16217
+ if git -C "$real_worktree" rev-parse --verify "@{upstream}" >/dev/null 2>&1; then
16218
+ base_ref="@{upstream}"
16219
+ else
16220
+ local candidate
16221
+ for candidate in origin/0.8.8-stable origin/0.8.7-stable origin/0.8.6-stable origin/main main; do
16222
+ if git -C "$real_worktree" rev-parse --verify "$candidate" >/dev/null 2>&1; then
16223
+ base_ref="$candidate"
16224
+ break
16225
+ fi
16226
+ done
16227
+ fi
16228
+
16229
+ if [[ -n "$base_ref" ]]; then
16230
+ local diff_files
16231
+ diff_files="$(git -C "$real_worktree" diff --name-only "$base_ref"...HEAD 2>/dev/null || true)"
16232
+ if [[ -n "$diff_files" ]]; then
16233
+ local elixir_code_touched=0
16234
+ local f
16235
+ while IFS= read -r f; do
16236
+ [[ -z "$f" ]] && continue
16237
+ case "$f" in
16238
+ lib/*|test/*|priv/*|mix.exs|mix.lock|config/*)
16239
+ elixir_code_touched=1
16240
+ break
16241
+ ;;
16242
+ esac
16243
+ done <<< "$diff_files"
16244
+ if (( elixir_code_touched == 0 )); then
16245
+ fmix_info "[fmix verify-push] Push allowed: only non-Elixir files modified (docs/workflows)."
16246
+ return 0
16247
+ fi
16248
+ fi
16249
+ fi
16250
+
16251
+ # 3. Draft PR Fast Pass (unless --require-receipt is explicitly specified)
16252
+ local pr_status=""
16253
+ if (( require_receipt == 0 )); then
16254
+ local py_bin
16255
+ py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
16256
+ pr_status="$("$py_bin" - "$real_worktree" <<'PY'
16257
+ import json, subprocess, sys
16258
+
16259
+ wt = sys.argv[1]
16260
+ try:
16261
+ res = subprocess.run(
16262
+ ["gh", "pr", "view", "--json", "isDraft,state"],
16263
+ cwd=wt,
16264
+ capture_output=True,
16265
+ text=True,
16266
+ timeout=4.0
16267
+ )
16268
+ if res.returncode != 0:
16269
+ # No open PR found or gh error
16270
+ print("no_open_pr")
16271
+ sys.exit(0)
16272
+ data = json.loads(res.stdout)
16273
+ if data.get("state") != "OPEN":
16274
+ print("no_open_pr")
16275
+ elif data.get("isDraft") is True:
16276
+ print("draft_pr")
16277
+ else:
16278
+ print("non_draft_pr")
16279
+ except subprocess.TimeoutExpired:
16280
+ print("timeout")
16281
+ except Exception:
16282
+ print("error")
16283
+ PY
16284
+ )"
16285
+ case "$pr_status" in
16286
+ no_open_pr|draft_pr|timeout|error)
16287
+ fmix_info "[fmix verify-push] Push allowed: no open ready PR ($pr_status). Encouraging Draft-First PR workflow."
16288
+ fmix_record_push_ledger "$real_worktree" "$git_dir"
16289
+ return 0
16290
+ ;;
16291
+ esac
16292
+ fi
16293
+
16294
+ # 4. Proof-of-Local-Test Gate (Open Non-Draft PR or --require-receipt)
16295
+ local receipt_file="$git_dir/ct-fmix-receipt.json"
16296
+ local current_code_tree_hash
16297
+ current_code_tree_hash="$(fmix_compute_code_tree_hash "$real_worktree" 2>/dev/null)" || current_code_tree_hash=""
16298
+
16299
+ local receipt_valid=0
16300
+ local receipt_passed=0
16301
+ local receipt_hash=""
16302
+ local receipt_epoch=0
16303
+
16304
+ if [[ -f "$receipt_file" ]]; then
16305
+ local py_bin
16306
+ py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
16307
+ local receipt_info
16308
+ receipt_info="$("$py_bin" - "$receipt_file" <<'PY'
16309
+ import json, sys
16310
+ try:
16311
+ with open(sys.argv[1], "r", encoding="utf-8") as f:
16312
+ d = json.load(f)
16313
+ passed = "1" if d.get("passed") is True else "0"
16314
+ h = str(d.get("code_tree_hash", ""))
16315
+ ts = str(d.get("ts_epoch", 0))
16316
+ print(f"{passed}\t{h}\t{ts}")
16317
+ except Exception:
16318
+ print("0\t\t0")
16319
+ PY
16320
+ )"
16321
+ IFS=$'\t' read -r receipt_passed receipt_hash receipt_epoch <<< "$receipt_info"
16322
+ if [[ "$receipt_passed" == "1" && "$receipt_hash" == "$current_code_tree_hash" && -n "$current_code_tree_hash" ]]; then
16323
+ receipt_valid=1
16324
+ fi
16325
+ fi
16326
+
16327
+ if (( receipt_valid == 0 )); then
16328
+ fmix_error "[fmix CIRCUIT BREAKER] Refusing push to open non-draft PR without a passing local fmix test receipt for the current code state. Run 'fmix test -- <test_files>' locally first, OR convert the PR to draft ('gh pr ready --undo') before pushing WIP commits."
16329
+ return 1
16330
+ fi
16331
+
16332
+ # 5. 30-Minute Push Rate-Limiter (<git-dir>/ct-push-ledger.tsv)
16333
+ local ledger_file="$git_dir/ct-push-ledger.tsv"
16334
+ local branch
16335
+ branch="$(git -C "$real_worktree" rev-parse --abbrev-ref HEAD 2>/dev/null || echo "HEAD")"
16336
+ local now
16337
+ now="$(fmix_epoch)"
16338
+ local window_seconds=$(( cooldown_minutes * 60 ))
16339
+ local cutoff=$(( now - window_seconds ))
16340
+
16341
+ local recent_pushes=0
16342
+ local last_push_epoch=0
16343
+
16344
+ if [[ -f "$ledger_file" ]]; then
16345
+ while IFS=$'\t' read -r p_ts p_branch p_hash p_rec_ts; do
16346
+ [[ -z "$p_ts" || "$p_branch" != "$branch" ]] && continue
16347
+ if (( p_ts >= cutoff )); then
16348
+ recent_pushes=$(( recent_pushes + 1 ))
16349
+ fi
16350
+ if (( p_ts > last_push_epoch )); then
16351
+ last_push_epoch="$p_ts"
16352
+ fi
16353
+ done < "$ledger_file"
16354
+ fi
16355
+
16356
+ if (( recent_pushes >= 2 && receipt_epoch <= last_push_epoch )); then
16357
+ fmix_error "[fmix CIRCUIT BREAKER] Push rate limit exceeded: $recent_pushes pushes in the last ${cooldown_minutes}m without a new passing test receipt recorded since the last push ($last_push_epoch). Run 'fmix test' locally before pushing again."
16358
+ return 1
16359
+ fi
16360
+
16361
+ printf '%s\t%s\t%s\t%s\n' "$now" "$branch" "$current_code_tree_hash" "$receipt_epoch" >> "$ledger_file"
16362
+ fmix_info "[fmix verify-push] Push verified and allowed."
16363
+ return 0
16364
+ }
16365
+
16366
+ cmd_hook_install() {
16367
+ local worktree_arg="auto"
16368
+ while (( $# > 0 )); do
16369
+ case "$1" in
16370
+ --worktree) [[ $# -ge 2 ]] || { fmix_error "--worktree requires a path argument."; return 2; }; worktree_arg="$2"; shift 2 ;;
16371
+ --worktree=*) worktree_arg="${1#--worktree=}"; shift ;;
16372
+ *) fmix_error "Unknown option: $1. Usage: fmix hook install [--worktree <path>]"; return 1 ;;
16373
+ esac
16374
+ done
16375
+ local worktree=""
16376
+ if [[ "$worktree_arg" != "auto" ]]; then
16377
+ worktree="$(fmix_find_worktree "$worktree_arg" 2>/dev/null || fmix_realpath "$worktree_arg")"
16378
+ else
16379
+ worktree="$(fmix_find_worktree auto 2>/dev/null || git rev-parse --show-toplevel 2>/dev/null || pwd -P)"
16380
+ fi
16381
+ local real_worktree
16382
+ real_worktree="$(fmix_realpath "$worktree")"
16383
+ if ! git -C "$real_worktree" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
16384
+ fmix_error "Path is not inside a git worktree: $real_worktree"
16385
+ return 1
16386
+ fi
16387
+ local git_dir
16388
+ git_dir="$(fmix_git_dir "$real_worktree")" || {
16389
+ fmix_error "Could not resolve git directory for $real_worktree"
16390
+ return 1
16391
+ }
16392
+ local hooks_dir="$git_dir/hooks"
16393
+ mkdir -p "$hooks_dir" || return 1
16394
+ local hook_file="$hooks_dir/pre-push"
16395
+ if [[ -f "$hook_file" ]]; then
16396
+ if grep -q "fmix verify-push" "$hook_file"; then
16397
+ fmix_info "fmix pre-push hook already installed in $hook_file"
16398
+ return 0
16399
+ fi
16400
+ printf '\n# fmix pre-push circuit breaker\nfmix verify-push --worktree "$PWD" "$@"\n' >> "$hook_file"
16401
+ else
16402
+ cat > "$hook_file" <<'EOF'
16403
+ #!/usr/bin/env bash
16404
+ # Installed by fmix hook install
16405
+ set -e
16406
+ fmix verify-push --worktree "$PWD" "$@"
16407
+ EOF
16408
+ chmod +x "$hook_file"
16409
+ fi
16410
+ fmix_info "Installed pre-push hook in $hook_file"
16411
+ return 0
16412
+ }
16413
+
16414
+ cmd_hook() {
16415
+ local subcmd="${1:-}"
16416
+ shift || true
16417
+ case "$subcmd" in
16418
+ install)
16419
+ cmd_hook_install "$@"
16420
+ ;;
16421
+ *)
16422
+ fmix_error "Unknown hook subcommand: '${subcmd:-empty}'. Usage: fmix hook install [--worktree <path>]"
16423
+ return 1
16424
+ ;;
16425
+ esac
16426
+ }
16427
+
14371
16428
  # ---------------------------------------------------------------------------
14372
16429
  # cmd: fmix task
14373
16430
  # ---------------------------------------------------------------------------
@@ -14498,6 +16555,9 @@ cmd_task() {
14498
16555
  DB_NAME="$task_db_name" \
14499
16556
  LOCAL_NATS="$NATS_HOST" \
14500
16557
  NATS_PORT="$NATS_PORT" \
16558
+ NATS_HOST="$NATS_HOST" \
16559
+ CT_NATS_HOST="$NATS_HOST" \
16560
+ NATS_URL="nats://${NATS_HOST}:${NATS_PORT}" \
14501
16561
  WORKER_NODE=TRUE \
14502
16562
  ADMIN_NODE=TRUE \
14503
16563
  ONPREM=TRUE \
@@ -14731,6 +16791,13 @@ fmix_infra_host_is_local() {
14731
16791
  esac
14732
16792
  }
14733
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
+
14734
16801
  fmix_write_ensure_compose() {
14735
16802
  local dir="$FMIX_HOME/infra"
14736
16803
  mkdir -p "$dir" || return 1
@@ -14795,7 +16862,11 @@ YAML
14795
16862
 
14796
16863
  fmix_start_existing_ct_infra() {
14797
16864
  local name started=0
14798
- 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
14799
16870
  if docker inspect "$name" >/dev/null 2>&1; then
14800
16871
  docker start "$name" >/dev/null 2>&1 || true
14801
16872
  started=1
@@ -14806,7 +16877,11 @@ fmix_start_existing_ct_infra() {
14806
16877
 
14807
16878
  fmix_compose_up_ensure() {
14808
16879
  fmix_write_ensure_compose || return 1
14809
- 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[@]}"
14810
16885
  }
14811
16886
 
14812
16887
  fmix_wait_infra() {
@@ -14817,6 +16892,9 @@ fmix_wait_infra() {
14817
16892
  if fmix_infra_ready; then
14818
16893
  return 0
14819
16894
  fi
16895
+ if ! fmix_nats_host_is_local && fmix_infra_postgres_ready && ! fmix_infra_nats_ready; then
16896
+ return 1
16897
+ fi
14820
16898
  sleep 1
14821
16899
  done
14822
16900
  return 1
@@ -14924,6 +17002,11 @@ fmix_ensure_infra() {
14924
17002
  return 0
14925
17003
  fi
14926
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
+
14927
17010
  if [[ "$FMIX_ENSURE" != "1" ]]; then
14928
17011
  fmix_error "Postgres/NATS not ready at $DB_HOST:$DB_PORT / $NATS_HOST:$NATS_PORT (FMIX_ENSURE=0)."
14929
17012
  return 1
@@ -14961,20 +17044,40 @@ fmix_ensure_infra_locked() {
14961
17044
  echo " [OK] infra ready postgres $DB_HOST:$DB_PORT nats $NATS_HOST:$NATS_PORT"
14962
17045
  return 0
14963
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
14964
17051
  fmix_infra_has_headroom || return 75
14965
- 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
14966
17057
  fmix_start_existing_ct_infra || true
14967
17058
  if fmix_wait_infra; then
14968
17059
  echo " [OK] infra ready postgres $DB_HOST:$DB_PORT nats $NATS_HOST:$NATS_PORT"
14969
17060
  return 0
14970
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
14971
17066
  # Another producer may allocate while existing services are warming.
14972
17067
  fmix_infra_has_headroom || return 75
14973
17068
  if ! fmix_compose_up_ensure; then
14974
- 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
14975
17074
  return 1
14976
17075
  fi
14977
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
14978
17081
  fmix_error "Shared infra did not become ready within ${FMIX_ENSURE_TIMEOUT}s at $DB_HOST:$DB_PORT / $NATS_HOST:$NATS_PORT"
14979
17082
  return 1
14980
17083
  fi
@@ -15112,9 +17215,17 @@ cmd_doctor() {
15112
17215
 
15113
17216
  # NATS TCP
15114
17217
  if nc -z "$NATS_HOST" "$NATS_PORT" 2>/dev/null; then
15115
- 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
15116
17223
  else
15117
- 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
15118
17229
  fi
15119
17230
 
15120
17231
  # Headless Chromium for ChromicPDF-backed reporting suites (API-1184).
@@ -16053,7 +18164,7 @@ cmd_gc_artifact_retirement() {
16053
18164
  [[ -n "$mode" ]] || return 2
16054
18165
  case "$mode" in
16055
18166
  adopt|plan|pin)
16056
- [[ "$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 ;;
16057
18168
  retire-plan|resume)
16058
18169
  [[ "$pin_id" =~ ^[0-9a-f]{64}$ ]] || return 2 ;;
16059
18170
  unpin) [[ "$pin_id" =~ ^[0-9a-f]{32}$ ]] || return 2 ;;
@@ -16066,7 +18177,8 @@ cmd_gc_artifact_retirement() {
16066
18177
  fi
16067
18178
  if [[ "$mode" == "auto-expire" || "$mode" == "unpin" \
16068
18179
  || "$mode" == "retire-plan" || "$mode" == "resume" \
16069
- || "$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
16070
18182
  local handoff_reason
16071
18183
  handoff_reason="$(fmix_artifact_v2_managed_entrypoint 2>&1)" || {
16072
18184
  case "$handoff_reason" in
@@ -16080,12 +18192,13 @@ cmd_gc_artifact_retirement() {
16080
18192
  fmix_prepare_command_home || return 1
16081
18193
  dependency_ttl="$(fmix_effective_artifact_ttl_hours dependency)" || return 2
16082
18194
  template_ttl="$(fmix_effective_artifact_ttl_hours template)" || return 2
18195
+ auto_expire_max="$(fmix_auto_expire_batch_limit)"
16083
18196
  py_bin="$(fmix_python_bin)" || return 1
16084
18197
  runner="$(fmix_realpath "${BASH_SOURCE[0]}")" || return 1
16085
- "$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'
16086
18199
  import contextlib, ctypes, datetime, hashlib, json, os, re, select, stat, subprocess, sys, time
16087
18200
 
16088
- 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:]
16089
18202
  home = os.path.abspath(home)
16090
18203
  entrypoint = os.path.abspath(entrypoint)
16091
18204
  entrypoint_pid = int(entrypoint_pid)
@@ -16119,6 +18232,9 @@ def bounded_names(fd):
16119
18232
  def fail(reason, status=2):
16120
18233
  print(json.dumps({"schema":"fmix-artifact-retirement.v2","status":"held","reason":reason},sort_keys=True))
16121
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)
16122
18238
  def canonical(value):
16123
18239
  return json.dumps(value,sort_keys=True,separators=(",",":"),ensure_ascii=True).encode()
16124
18240
  def identity(st):
@@ -16365,10 +18481,13 @@ def read_json(rel):
16365
18481
  return strict_load(raw),raw,identity_value
16366
18482
  def artifact_id_for(row):
16367
18483
  pool=row["pool"]
16368
- 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")
16369
18487
  return prefix+":"+row["key"] if pool.startswith("template") else prefix+":"+row["lane"]+"/"+row["key"]
16370
18488
  def parse_artifact_id(value):
16371
18489
  for prefix,pool in (("template-v2","template-v2"),("template","template"),
18490
+ ("app-compile-v2","app-compile-v2"),
16372
18491
  ("dependency-v2","dependency-v2"),("dependency","dependency")):
16373
18492
  if pool.startswith("template"):
16374
18493
  match=re.fullmatch(prefix+r":([0-9a-f]{16})",value or "")
@@ -16377,13 +18496,15 @@ def parse_artifact_id(value):
16377
18496
  match=re.fullmatch(prefix+r":([0-9a-f]{64})/([0-9a-f]{64})",value or "")
16378
18497
  if match: return pool,match.group(1),match.group(2)
16379
18498
  raise ValueError("invalid artifact identifier")
16380
- 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"
16381
18501
  def pool_v2(pool): return pool.endswith("-v2")
16382
18502
  def cache_rel(pool,lane,key):
16383
18503
  if pool=="template": return "templates/"+key
16384
18504
  if pool=="template-v2": return "artifacts/v2/templates/"+key
16385
18505
  if pool=="dependency": return "dependency-artifacts/v1/"+lane+"/"+key
16386
18506
  if pool=="dependency-v2": return "artifacts/v2/dependencies/"+lane+"/"+key
18507
+ if pool=="app-compile-v2": return "artifacts/v2/app-compiles/"+lane+"/"+key
16387
18508
  raise ValueError("unknown artifact pool")
16388
18509
  def candidate_row(report,artifact_id):
16389
18510
  pool,lane,key=parse_artifact_id(artifact_id)
@@ -16399,7 +18520,7 @@ def candidate_row(report,artifact_id):
16399
18520
  or not all(isinstance(v,str) for v in row["references"]) or type(row.get("references_truncated")) is not bool):
16400
18521
  raise ValueError("candidate inventory schema incomplete")
16401
18522
  if pool_kind(pool)=="template" and row["lane"] is not None: raise ValueError("template lane schema")
16402
- 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")
16403
18524
  expected=home+"/"+cache_rel(pool,lane,key)
16404
18525
  if row.get("path")!=expected: raise ValueError("candidate path identity mismatch")
16405
18526
  if pool_v2(pool): require_managed_handoff()
@@ -16421,7 +18542,10 @@ def candidate_holds(report,row):
16421
18542
  if row.get("status")!="held": holds.add("unexpected_inventory_state")
16422
18543
  if holds: raise ValueError(",".join(sorted(holds)))
16423
18544
  def lock_name(pool,lane,key):
16424
- 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]
16425
18549
  LEASE_PROVIDER = """source "$FMIX_RETIREMENT_PROVIDER_RUNNER" || exit 70
16426
18550
  lock_name="$1"
16427
18551
  fmix_lock_acquire "$lock_name" 0 "artifact retirement" 1 || exit $?
@@ -16505,14 +18629,19 @@ def read_meta(row):
16505
18629
  if sha(raw)!=row.get("metadata_sha256"): raise ValueError("metadata digest changed")
16506
18630
  meta=strict_load(raw)
16507
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"}
16508
18633
  template_v1={"schema","status","template_key","manifest_sha256","built_at","toolchain","source_commit"}
16509
- 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)
16510
18635
  if v2: expected=expected|{"producer_runner_sha256","consumer_protocol"}
16511
18636
  if not isinstance(meta,dict) or set(meta)!=expected or meta.get("schema")!=("2" if v2 else "1"):
16512
18637
  raise ValueError("metadata schema")
16513
18638
  if kind=="template" and (meta["status"]!="complete" or meta["template_key"]!=key
16514
18639
  or not meta["toolchain"] or not re.fullmatch(r"[0-9a-f]{7,40}",meta["source_commit"])):
16515
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")
16516
18645
  if kind=="dependency" and (meta["lane"]!=lane or meta["dependency_fingerprint"]!=key
16517
18646
  or not re.fullmatch(r"[0-9a-f]{40}",meta["producer_sha"])
16518
18647
  or meta["source_clean"] not in ("true","false")):
@@ -16531,6 +18660,7 @@ def read_meta(row):
16531
18660
  def last_access(row,pool,lane,key,built):
16532
18661
  if pool_v2(pool):
16533
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"
16534
18664
  else "artifact-access/v2/dependencies/"+lane+"/"+key)
16535
18665
  else:
16536
18666
  rel=("template-access/"+key if pool_kind(pool)=="template"
@@ -16590,18 +18720,27 @@ def verify_tree(row,base_rel=None,allow_owner_write=False):
16590
18720
  os.close(rootfd_cache); raise ValueError("candidate identity incomplete or changed")
16591
18721
  try:
16592
18722
  names=bounded_names(rootfd_cache)
16593
- 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:
16594
18726
  raise ValueError("unexpected cache contents")
16595
18727
  meta_raw,meta_id=read_file(base_rel+"/meta.json",1024*1024)
16596
18728
  meta=strict_load(meta_raw)
18729
+ app_fields={"schema","lane","compile_fingerprint","producer_sha","source_clean","manifest_sha256","built_at"}
16597
18730
  dep_fields={"schema","lane","dependency_fingerprint","producer_sha","source_clean","manifest_sha256","built_at"}
16598
18731
  template_fields={"schema","status","template_key","manifest_sha256","built_at","toolchain","source_commit"}
16599
18732
  if v2:
18733
+ app_fields|={"producer_runner_sha256","consumer_protocol"}
16600
18734
  dep_fields|={"producer_runner_sha256","consumer_protocol"}
16601
18735
  template_fields|={"producer_runner_sha256","consumer_protocol"}
16602
- 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)
16603
18738
  if not isinstance(meta,dict) or set(meta)!=expected_fields or meta.get("schema")!=("2" if v2 else "1"):
16604
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")
16605
18744
  if kind=="dependency" and (meta["lane"]!=lane or meta["dependency_fingerprint"]!=key
16606
18745
  or not re.fullmatch(r"[0-9a-f]{40}",meta["producer_sha"])
16607
18746
  or meta["source_clean"] not in ("true","false")):
@@ -16629,7 +18768,8 @@ def verify_tree(row,base_rel=None,allow_owner_write=False):
16629
18768
  parts=line.split("\t")
16630
18769
  if len(parts)<3: raise ValueError("manifest row")
16631
18770
  kind,path=parts[:2]; safe_parts(path)
16632
- 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):
16633
18773
  raise ValueError("manifest path")
16634
18774
  if kind=="D" and parts==["D",path,"-"]: pass
16635
18775
  elif kind=="F" and len(parts)==4 and parts[2].isdigit() and re.fullmatch(r"[0-9a-f]{64}",parts[3]): pass
@@ -16680,7 +18820,7 @@ def verify_tree(row,base_rel=None,allow_owner_write=False):
16680
18820
  if identity(before)!=identity(os.fstat(filefd)): raise ValueError("payload changed while hashing")
16681
18821
  finally: os.close(filefd)
16682
18822
  else: raise ValueError("special payload")
16683
- for top in ("deps","_build"):
18823
+ for top in (("_build",) if kind=="app" else ("deps","_build")):
16684
18824
  topfd=os.open(top,dir_flags,dir_fd=rootfd_cache)
16685
18825
  try:
16686
18826
  topst=os.fstat(topfd)
@@ -16773,7 +18913,7 @@ def access_baseline(row,pool,lane,key,proof):
16773
18913
  adopted=datetime.datetime.fromisoformat(adoption["adopted_at"].replace("Z","+00:00")) if adoption else now
16774
18914
  return max(built,access,adopted),adoption
16775
18915
  def ttl_hours(pool):
16776
- 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)
16777
18917
  def make_owned_directories_writable(base_rel,snapshot):
16778
18918
  changes=[]
16779
18919
  for rel in sorted([""]+snapshot["directories"],key=lambda value:value.count("/")):
@@ -16874,6 +19014,10 @@ def remove_verified_tree(base_rel,snapshot,delete=True):
16874
19014
  if root is not None: os.close(root)
16875
19015
  os.close(parent)
16876
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.
16877
19021
  return sha(canonical({"schema":"fmix-artifact-retirement-policy.v2",
16878
19022
  "dependency_ttl_hours":int(dep_ttl),"template_ttl_hours":int(template_ttl),
16879
19023
  "max_candidates_per_preparation":1,"max_work_seconds":45,
@@ -16994,7 +19138,8 @@ def snapshots_match(before,after,phase="rename"):
16994
19138
  if path not in directories and old.get("ctime_ns")!=new.get("ctime_ns"):
16995
19139
  raise ValueError("unexpected file metadata change")
16996
19140
  def late_references(report,pool,lane,key):
16997
- 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")
16998
19143
  for observation in report.get("observations",[]):
16999
19144
  refs=observation.get("references",{})
17000
19145
  if refs.get(field)==key: raise ValueError("late_native_workspace_reference")
@@ -17372,40 +19517,82 @@ def mode_operation():
17372
19517
  journal=load_journal(object_id)
17373
19518
  return run_locked(journal["artifact_id"],lambda:finish_journal(load_journal(object_id)))
17374
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
17375
19539
  def auto_expire_one():
17376
- # 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.
17377
19548
  require_managed_handoff()
19549
+ results=[]
17378
19550
  try:
19551
+ budget=auto_expire_max
17379
19552
  journals=list_names(RETIRE_ROOT+"/journals")
17380
19553
  for name in journals:
19554
+ if budget<=0: break
17381
19555
  match=re.fullmatch(r"([0-9a-f]{64})\.json",name)
17382
19556
  if not match: raise ValueError("unknown_retirement_journal_layout")
17383
19557
  journal=load_journal(match.group(1))
17384
19558
  if journal.get("state") in ("intent","quarantined","permissions_pending","deleting"):
17385
- return run_locked(journal["artifact_id"],lambda:finish_journal(load_journal(match.group(1))))
17386
- report,runner_sha=run_audit()
17387
- protected,broken,unknown_template=fallbacks(report)
17388
- candidates=[]
17389
- for row in report.get("entries",[]):
17390
- if row.get("reference_count") or row.get("references_truncated"): continue
17391
- artifact_id=artifact_id_for(row)
17392
- if not pool_v2(row["pool"]): continue
17393
- try: candidate_holds(report,row)
17394
- except Exception: continue
17395
- if artifact_id in protected or (pool_kind(row["pool"])=="template" and unknown_template) or row.get("lane") in broken: continue
17396
- try:
17397
- meta,built=read_meta(row)
17398
- access=last_access(row,row["pool"],row.get("lane"),row["key"],built)
17399
- except Exception: continue
17400
- candidates.append((access,artifact_id))
17401
- if not candidates: return {"status":"skipped","reason":"no_unreferenced_nonfallback_candidate"}
17402
- _,artifact_id=min(candidates)
17403
- 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
17404
19582
  except Exception as exc:
17405
- return {"status":"skipped","reason":str(exc)}
19583
+ return auto_expire_summary(results,exc)
19584
+ return auto_expire_summary(results)
17406
19585
  def auto_candidate_locked(artifact_id):
17407
19586
  report,runner_sha,row,pool,lane,key,rel,proof,protected=fresh_proof(artifact_id)
17408
- 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}
17409
19596
  if plan is None: return {"status":"adopted_waiting_ttl","artifact_id":artifact_id}
17410
19597
  return execute_plan_locked(plan["plan_id"])
17411
19598
  try:
@@ -17593,6 +19780,10 @@ def reference(rel, kind):
17593
19780
  if not hexkey(d[field], width):
17594
19781
  raise ValueError("reference identity")
17595
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"]
17596
19787
  row.update(status="observed", references=refs,
17597
19788
  declared_source_path_sha256=sha(source.encode()))
17598
19789
  except (OSError, ValueError, UnicodeError):
@@ -17669,6 +19860,7 @@ def known_retirement_quarantine(rel,pool,lane=None):
17669
19860
  aid=plan.get("artifact_id","")
17670
19861
  if pool=="template-v2" and re.fullmatch(r"template-v2:[0-9a-f]{16}",aid): source="artifacts/v2/templates/"+aid.split(":")[1]
17671
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]
17672
19864
  else: return False
17673
19865
  parent=source.rsplit("/",1)[0]
17674
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
@@ -17736,22 +19928,32 @@ def inventory(row, allow_owner_write=False):
17736
19928
  if not stat.S_ISDIR(before.st_mode) or (before.st_mode & 0o222 and not
17737
19929
  (allow_owner_write and before.st_mode & 0o200 and not before.st_mode & 0o022)):
17738
19930
  raise ValueError("unsafe cache root")
17739
- 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:
17740
19937
  raise ValueError("unexpected cache contents")
17741
- 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")):
17742
19940
  if not stat.S_ISDIR(info(rel + "/" + child).st_mode):
17743
19941
  raise ValueError("missing cache directory")
17744
- if pool.startswith("dependency") and (children(rel + "/_build") != ["test"]
17745
- or children(rel + "/_build/test") != ["lib"]):
19942
+ if (dependency_pool or app) and (children(rel + "/_build") != ["test"]
19943
+ or children(rel + "/_build/test") != ["lib"]):
17746
19944
  raise ValueError("unexpected build environment")
19945
+ if app and children(rel + "/_build/test/lib") != ["cdrcisco"]:
19946
+ raise ValueError("unexpected app payload")
17747
19947
  raw, _ = read(rel + "/meta.json")
17748
19948
  row["metadata_sha256"] = sha(raw)
17749
19949
  d = decode(raw)
17750
19950
  dependency = pool.startswith("dependency")
17751
19951
  v2 = pool.endswith("-v2")
17752
- 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"
17753
19955
  if v2 else "schema lane dependency_fingerprint producer_sha source_clean manifest_sha256 built_at")
17754
- if dependency else
19956
+ if (dependency or app) else
17755
19957
  ("schema status template_key manifest_sha256 built_at toolchain source_commit producer_runner_sha256 consumer_protocol"
17756
19958
  if v2 else "schema status template_key manifest_sha256 built_at toolchain source_commit"))
17757
19959
  if not isinstance(d, dict) or set(d) != set(fields.split()) or any(
@@ -17767,7 +19969,12 @@ def inventory(row, allow_owner_write=False):
17767
19969
  if (sha(producer_runner) != d["producer_runner_sha256"] or producer_id["mode"]&0o222
17768
19970
  or not producer_id["mode"]&0o111):
17769
19971
  raise ValueError("producer runner identity")
17770
- 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:
17771
19978
  if (d["lane"] != lane or d["dependency_fingerprint"] != key
17772
19979
  or not hexkey(d["producer_sha"], 40)
17773
19980
  or d["source_clean"] not in ("true", "false")):
@@ -17830,7 +20037,8 @@ try:
17830
20037
  for pool, base, width in (("template", "templates", 16),
17831
20038
  ("dependency", "dependency-artifacts/v1", 64),
17832
20039
  ("template-v2", "artifacts/v2/templates", 16),
17833
- ("dependency-v2", "artifacts/v2/dependencies", 64)):
20040
+ ("dependency-v2", "artifacts/v2/dependencies", 64),
20041
+ ("app-compile-v2", "artifacts/v2/app-compiles", 64)):
17834
20042
  try:
17835
20043
  for name in children(base):
17836
20044
  if not hexkey(name, width):
@@ -17868,7 +20076,9 @@ for observation in observations:
17868
20076
  for field, key in observation.get("references", {}).items():
17869
20077
  index.setdefault((field, key), []).append(observation["path"])
17870
20078
  for row in entries:
17871
- 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")
17872
20082
  references = index.get((field, row["key"]), [])
17873
20083
  row["reference_count"] = len(references)
17874
20084
  row["references"] = references[:16]
@@ -22708,10 +24918,14 @@ fmix test — run ExUnit targets inside a provisioned session DB.
22708
24918
 
22709
24919
  Usage:
22710
24920
  fmix test [--worktree <path>] [--session <id>] [--isolate]
22711
- [--cache-base <N.N.N-stable>] [--event-fd <fd>] [--unit]
22712
- -- <mix test args>
24921
+ [--cache-base <N.N.N-stable>] [--event-fd <fd>] [--no-auto-setup]
24922
+ [--unit] -- <mix test args>
22713
24923
 
22714
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.
22715
24929
  - One worktree → one warm overlay (SUPER-HOT): pass --session only with a
22716
24930
  stable name plus --isolate for true parallel Mix on one checkout.
22717
24931
  - Slow DB startup = local snapshot recovery (see fmix status / fmix timing).
@@ -22729,13 +24943,15 @@ VERB
22729
24943
  fmix coverage — targeted diff-coverage gate (ADR 0054).
22730
24944
 
22731
24945
  Usage:
22732
- fmix coverage --worktree <path> [--session <id>] --base <git-ref>
22733
- [--source <lib/**/*.ex>]... [--threshold 80]
24946
+ fmix coverage --worktree <path> [--session <id>] [--no-auto-setup]
24947
+ --base <git-ref> [--source <lib/**/*.ex>]... [--threshold 80]
22734
24948
  -- <test paths>
22735
24949
 
22736
24950
  Notes:
22737
24951
  --base is REQUIRED: it defines the changed-module set. --source scopes
22738
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.
22739
24955
  Cannot gate staged-but-uncommitted changes — the bootstrap diffs the
22740
24956
  committed base...HEAD range. For staged gates use:
22741
24957
  fmix task -- cdrcisco.diff_coverage --staged --staged-diff <patch>
@@ -22903,10 +25119,36 @@ fmix self-test — run the runner's internal correctness suite.
22903
25119
 
22904
25120
  Example:
22905
25121
  fmix self-test
25122
+ VERB
25123
+ ;;
25124
+ verify-push)
25125
+ cat <<'VERB'
25126
+ fmix verify-push — pre-push circuit breaker enforcing local test proof and push rate-limiting.
25127
+
25128
+ Usage:
25129
+ fmix verify-push [--worktree <path>] [--cooldown-minutes <N>] [--require-receipt]
25130
+
25131
+ Notes:
25132
+ - Bypassed if CT_HUMAN=1 or FMIX_BYPASS_PUSH_GATE=1.
25133
+ - Bypassed for docs/workflow-only diffs (no Elixir files modified).
25134
+ - Bypassed for draft PRs or branches without an open PR.
25135
+ - Enforces ct-fmix-receipt.json match for open non-draft PRs.
25136
+ - Limits push frequency to max 2 pushes per cooldown window without a new passing test receipt.
25137
+ VERB
25138
+ ;;
25139
+ hook)
25140
+ cat <<'VERB'
25141
+ fmix hook — manage git hooks for fmix.
25142
+
25143
+ Usage:
25144
+ fmix hook install [--worktree <path>]
25145
+
25146
+ Notes:
25147
+ Installs a git pre-push hook invoking fmix verify-push.
22906
25148
  VERB
22907
25149
  ;;
22908
25150
  *)
22909
- fmix_error "No focused help for '$verb'. Valid commands: test, coverage, task, format, setup, seed publish, cache explain, cache verify, ensure, doctor, status, timing, gc, install, self-test, version, help"
25151
+ fmix_error "No focused help for '$verb'. Valid commands: test, coverage, task, format, setup, seed publish, cache explain, cache verify, ensure, doctor, status, timing, gc, install, self-test, verify-push, hook, version, help"
22910
25152
  return 1
22911
25153
  ;;
22912
25154
  esac
@@ -22917,14 +25159,16 @@ fmix_usage() {
22917
25159
  fmix — fast native Elixir test runner for cisco-cdr
22918
25160
 
22919
25161
  Usage:
22920
- ./fmix test [--worktree <path>] [--session <id>] [--cache-base <N.N.N-stable>] [--event-fd <fd>] [--unit] -- <mix test args>
22921
- ./fmix coverage [--worktree <path>] [--session <id>] --base <git-ref> [--source <lib/**/*.ex>] [--threshold 80] -- <test paths>
25162
+ ./fmix test [--worktree <path>] [--session <id>] [--no-auto-setup] [--cache-base <N.N.N-stable>] [--event-fd <fd>] [--unit] -- <mix test args>
25163
+ ./fmix coverage [--worktree <path>] [--session <id>] [--no-auto-setup] --base <git-ref> [--source <lib/**/*.ex>] [--threshold 80] -- <test paths>
22922
25164
  ./fmix task [--worktree <path>] [--session <id>] [--database <name>] [--mix-env <env>] [--allow-run] -- <mix task> [args]
22923
25165
  ./fmix format [--worktree <path>] [--session <id>] [--mix-env <env>] [--dot-formatter <path>] [--check] -- <files...>
22924
25166
  ./fmix setup [--worktree <path>] [--session <id>] [--rebuild-db|--cold-db|--from-zero]
22925
25167
  ./fmix seed publish --worktree <path> [--session <id>] --cache-base <N.N.N-stable>
22926
25168
  ./fmix cache explain --worktree <path> --cache-base <N.N.N-stable>
22927
25169
  ./fmix cache verify [--key <16-hex-template-key>]
25170
+ ./fmix verify-push [--worktree <path>] [--cooldown-minutes <N>] [--require-receipt]
25171
+ ./fmix hook install [--worktree <path>]
22928
25172
  ./fmix ensure
22929
25173
  ./fmix doctor
22930
25174
  ./fmix status
@@ -22972,15 +25216,23 @@ Operational notes:
22972
25216
  fmix status exits 1 when session metadata discovery is incomplete, while
22973
25217
  still printing the remaining read-only diagnostic sections.
22974
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.
22975
25221
 
22976
25222
  Environment overrides:
22977
25223
  FMIX_HOME State directory (default: ~/.ct-fmix)
22978
25224
  FMIX_SESSION_ID Stable logical session identity (or pass --session)
22979
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)
22980
25229
  FMIX_FORCE_SESSION Set to 1 to allow ephemeral session ids (cold path)
22981
25230
  FMIX_THREAD_SESSIONS Set to 1 to restore CODEX_THREAD_ID session binding
22982
25231
  FMIX_HOT_PATH_BUDGET_S hot_path overhead budget seconds excl mix_test (default: 25)
22983
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)
22984
25236
  OBAN_LICENSE_KEY Oban Pro license key override (or from ~/.config/calltelemetry/fmix.env / Doppler)
22985
25237
  FMIX_SESSION_TTL_HOURS Inactive-session auto-purge and GC threshold (default: 4)
22986
25238
  FMIX_SESSION_TTL_DAYS Legacy compatibility override, converted to hours when FMIX_SESSION_TTL_HOURS is unset
@@ -22995,12 +25247,15 @@ Environment overrides:
22995
25247
  FMIX_DB_PORT Postgres port (default: 5432)
22996
25248
  FMIX_DB_USER Postgres user (default: calltelemetry)
22997
25249
  FMIX_DB_PASSWORD Postgres password (default: calltelemetry_dev_password)
22998
- 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)
22999
25253
  FMIX_NATS_PORT NATS port (default: 4222)
23000
25254
  FMIX_COPY_MODE Set to 'full' to disable CoW clone
23001
25255
  FMIX_LOCK_TIMEOUT Lock wait timeout in seconds (default: 900)
23002
25256
  FMIX_LOCK_INIT_GRACE Grace before reclaiming a pid-less lock (default: 5)
23003
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)
23004
25259
  FMIX_HOST_TEST_LOCK Set to 0 only to bypass CREATE/DROP serialization
23005
25260
  FMIX_HOST_LOCK_TIMEOUT Host database-DDL lock wait cap in seconds (default: 60)
23006
25261
  FMIX_DB_CREATE_ADMISSION Set to 0 only to bypass DB pressure admission
@@ -25220,6 +27475,12 @@ main() {
25220
27475
  return 0
25221
27476
  fi
25222
27477
  ;;
27478
+ verify-push|hook)
27479
+ if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
27480
+ fmix_verb_help "$cmd"
27481
+ return 0
27482
+ fi
27483
+ ;;
25223
27484
  esac
25224
27485
  if [[ "$cmd" == "gc" ]] && fmix_readonly_entrypoint gc "$@"; then
25225
27486
  if fmix_gc_artifact_retirement_requested "$@"; then
@@ -25232,7 +27493,7 @@ main() {
25232
27493
 
25233
27494
  if [[ "$cmd" == "cache" ]]; then
25234
27495
  fmix_prepare_home_readonly || return 1
25235
- elif [[ "$cmd" != "test" && "$cmd" != "coverage" ]]; then
27496
+ elif [[ "$cmd" != "test" && "$cmd" != "coverage" && "$cmd" != "verify-push" && "$cmd" != "hook" ]]; then
25236
27497
  fmix_prepare_command_home || return 1
25237
27498
  fi
25238
27499
 
@@ -25243,6 +27504,12 @@ main() {
25243
27504
  return 0
25244
27505
  fi
25245
27506
  ;;
27507
+ verify-push|hook)
27508
+ if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
27509
+ fmix_verb_help "$cmd"
27510
+ return 0
27511
+ fi
27512
+ ;;
25246
27513
  esac
25247
27514
 
25248
27515
  case "$cmd" in
@@ -25260,9 +27527,11 @@ main() {
25260
27527
  gc) cmd_gc "$@" ;;
25261
27528
  install) cmd_install "$@" ;;
25262
27529
  self-test) cmd_self_test "$@" ;;
27530
+ verify-push) cmd_verify_push "$@" ;;
27531
+ hook) cmd_hook "$@" ;;
25263
27532
  *)
25264
27533
  fmix_error "Unknown command: $cmd"
25265
- fmix_error "Valid commands: test, coverage, task, format, setup, seed publish, cache explain, cache verify, ensure, doctor, status, timing, gc, install, self-test, version, help"
27534
+ fmix_error "Valid commands: test, coverage, task, format, setup, seed publish, cache explain, cache verify, ensure, doctor, status, timing, gc, install, self-test, verify-push, hook, version, help"
25266
27535
  fmix_error "Run 'fmix --help' for the full manual or 'fmix help <command>' for focused usage."
25267
27536
  return 1
25268
27537
  ;;