@calltelemetry/fmix 2.7.8 → 2.7.10

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 +977 -80
  2. package/package.json +3 -3
package/bin/fmix CHANGED
@@ -24,7 +24,7 @@ set -uo pipefail
24
24
  # ---------------------------------------------------------------------------
25
25
  # Constants & config
26
26
  # ---------------------------------------------------------------------------
27
- FMIX_VERSION="2.7.8"
27
+ FMIX_VERSION="2.7.10"
28
28
  FMIX_HOME="${FMIX_HOME:-${HOME}/.ct-fmix}"
29
29
  FMIX_OS="$(uname -s)"
30
30
  FMIX_ARCH="$(uname -m)"
@@ -175,6 +175,14 @@ fmix_prepare_home() {
175
175
  export FMIX_HOME
176
176
  }
177
177
 
178
+ fmix_prepare_command_home() {
179
+ fmix_prepare_home || return 1
180
+ mkdir -p "$FMIX_HOME"/{templates,template-access,dependency-artifacts,dependency-artifact-access,sessions,worktrees,db-index,compile-stamps,dependency-stamps,locks,lock-kernel,lock-metadata,logs,quarantine} \
181
+ || return 1
182
+ fmix_prepare_session_state_root || return 1
183
+ chmod 0700 "$FMIX_HOME" 2>/dev/null || true
184
+ }
185
+
178
186
  fmix_prepare_home_readonly() {
179
187
  # Cache explain/verify are read-only. Canonicalize an existing home so the
180
188
  # same path-safety comparisons apply through aliases, but never create a
@@ -546,18 +554,43 @@ fmix_resolved_toolchain_identity() {
546
554
  }
547
555
  done
548
556
 
549
- actual_otp_major="$(
550
- cd "$worktree" &&
551
- erl -noshell -eval 'io:format("~s", [erlang:system_info(otp_release)]), halt().' 2>/dev/null
552
- )" || actual_otp_major=""
553
- otp_root="$(
554
- cd "$worktree" &&
555
- erl -noshell -eval 'io:format("~s", [code:root_dir()]), halt().' 2>/dev/null
556
- )" || otp_root=""
557
- actual_erts="$(
557
+ # ONE erl spawn, not three. Each BEAM start is a full VM boot; measured on a
558
+ # loaded host at 1.5s / 1.8s / 0.7s here, and this function runs on every
559
+ # compile-fingerprint computation, i.e. every warm fmix invocation.
560
+ #
561
+ # Fields are NEWLINE-separated, one per line. `code:root_dir()` is an
562
+ # operator-controlled filesystem path, so any PRINTABLE delimiter could occur
563
+ # inside it: a path containing a literal `|` would truncate otp_root, make
564
+ # OTP_VERSION unreadable, and produce a spurious mismatch refusal. A newline
565
+ # cannot appear in a path, so the probe is read as a stream instead of split
566
+ # on a character.
567
+ local erl_probe
568
+ erl_probe="$(
558
569
  cd "$worktree" &&
559
- erl -noshell -eval 'io:format("~s", [erlang:system_info(version)]), halt().' 2>/dev/null
560
- )" || actual_erts=""
570
+ erl -noshell -eval 'io:format("~s~n~s~n~s~n", [erlang:system_info(otp_release), code:root_dir(), erlang:system_info(version)]), halt().' 2>/dev/null
571
+ )" || erl_probe=""
572
+ actual_otp_major=""
573
+ otp_root=""
574
+ actual_erts=""
575
+ if [[ -n "$erl_probe" ]]; then
576
+ local -a erl_fields=()
577
+ while IFS= read -r erl_field; do
578
+ erl_fields+=("$erl_field")
579
+ done <<< "$erl_probe"
580
+ if (( ${#erl_fields[@]} >= 3 )); then
581
+ actual_otp_major="${erl_fields[0]}"
582
+ otp_root="${erl_fields[1]}"
583
+ actual_erts="${erl_fields[2]}"
584
+ fi
585
+ fi
586
+ # A probe that did not yield three non-empty fields means the VM could not be
587
+ # queried; fail the identity rather than compiling against an unverified
588
+ # toolchain.
589
+ if [[ -z "$actual_otp_major" || -z "$otp_root" || -z "$actual_erts" ]]; then
590
+ actual_otp_major=""
591
+ otp_root=""
592
+ actual_erts=""
593
+ fi
561
594
  otp_version_file="$otp_root/releases/$actual_otp_major/OTP_VERSION"
562
595
  if [[ -r "$otp_version_file" ]]; then
563
596
  actual_otp="$(tr -d '[:space:]' <"$otp_version_file")"
@@ -1678,7 +1711,7 @@ fmix_run_telemetry_finish() {
1678
1711
  case "${FMIX_LAST_COMPILE_OUTCOME:-}" in
1679
1712
  stamp_hit|stamp_hit_repaired|stamp_hit_after_deps|stamp_hit_quick|noop_compile)
1680
1713
  case "${FMIX_LAST_ARTIFACTS_OUTCOME:-}" in
1681
- session_hit|adopt_stamps|adopt_compatible|dependency_reconcile|ready|stable_seed|donor_clone)
1714
+ session_hit|adopt_stamps|adopt_compatible|adopt_migration_delta|dependency_reconcile|ready|stable_seed|donor_clone)
1682
1715
  cache_hot="yes"
1683
1716
  ;;
1684
1717
  esac
@@ -1688,7 +1721,8 @@ fmix_run_telemetry_finish() {
1688
1721
  # proven application build and lets Mix compile only the affected
1689
1722
  # dependency/app delta. That is still a cache hit; a near-full
1690
1723
  # compile is classified separately as full_recompile.
1691
- [[ "${FMIX_LAST_ARTIFACTS_OUTCOME:-}" == "dependency_reconcile" ]] \
1724
+ [[ "${FMIX_LAST_ARTIFACTS_OUTCOME:-}" == "dependency_reconcile" \
1725
+ || "${FMIX_LAST_ARTIFACTS_OUTCOME:-}" == "adopt_migration_delta" ]] \
1692
1726
  && cache_hot="yes"
1693
1727
  ;;
1694
1728
  esac
@@ -2663,7 +2697,7 @@ fmix_guard_stale_build() {
2663
2697
  fmix_error "SAFETY: refusing to delete '$path' — expected _build.fmix-stale.* pattern."
2664
2698
  return 1
2665
2699
  fi
2666
- if [[ ! -f "$parent/mix.exs" ]] || ! grep -q 'app: :cdrcisco' "$parent/mix.exs" 2>/dev/null; then
2700
+ if ! fmix_worktree_has_cisco_cdr_app "$parent"; then
2667
2701
  fmix_error "SAFETY: refusing to delete '$path' — parent is not a cisco-cdr checkout."
2668
2702
  return 1
2669
2703
  fi
@@ -2680,7 +2714,7 @@ fmix_guard_worktree_subdir() {
2680
2714
  fmix_error "SAFETY: refusing to rm '$path' — expected path ending in /deps or /_build."
2681
2715
  return 1
2682
2716
  fi
2683
- if [[ ! -f "$parent/mix.exs" ]] || ! grep -q 'app: :cdrcisco' "$parent/mix.exs" 2>/dev/null; then
2717
+ if ! fmix_worktree_has_cisco_cdr_app "$parent"; then
2684
2718
  fmix_error "SAFETY: refusing to rm '$path' — parent '$parent' is not a cisco-cdr checkout."
2685
2719
  return 1
2686
2720
  fi
@@ -2689,12 +2723,64 @@ fmix_guard_worktree_subdir() {
2689
2723
 
2690
2724
  # ---------------------------------------------------------------------------
2691
2725
  # Template key computation
2692
- # Template key (v4) = first 16 hex of sha256 over:
2726
+ # Template key (v5) = first 16 hex of sha256 over:
2693
2727
  # resolved BEAM ABI + dependency declarations/resolution + local dependency
2694
- # source inputs + uname -sm.
2728
+ # source inputs + a digest of priv/repo/migrations (names and contents) +
2729
+ # uname -sm.
2695
2730
  # ---------------------------------------------------------------------------
2696
2731
 
2732
+ fmix_migrations_digest() {
2733
+ # API-3576: a shared template that outlives a migration change is stale in
2734
+ # a way "0 pending migrations" can never reveal, because Ecto compares
2735
+ # versions, not contents. A migration edited in place (or a migration whose
2736
+ # body delegates to code that changed beside it) keeps its version while the
2737
+ # schema it produces moves on. Hashing every migration's relative name and
2738
+ # content makes any such change a new key, so the old template is simply
2739
+ # never selected. Emits a deterministic, path-relative manifest on stdout.
2740
+ local worktree="$1" dir listing file
2741
+ local -a files=()
2742
+ dir="$worktree/priv/repo/migrations"
2743
+ if [[ ! -d "$dir" ]]; then
2744
+ printf 'migrations:none\n'
2745
+ return 0
2746
+ fi
2747
+ listing="$(mktemp)" || return 1
2748
+ if ! find "$dir" -type f -print 2>/dev/null | LC_ALL=C sort >"$listing"; then
2749
+ rm -f "$listing"
2750
+ return 1
2751
+ fi
2752
+ while IFS= read -r file; do
2753
+ files+=("$file")
2754
+ done <"$listing"
2755
+ rm -f "$listing"
2756
+ printf 'migrations:v1\n'
2757
+ (( ${#files[@]} > 0 )) || return 0
2758
+ # Batched hashing keeps this to a handful of processes even for the
2759
+ # ~1000 migrations of a mature repository. Paths are made relative so the
2760
+ # digest does not depend on where the worktree lives.
2761
+ fmix_hash_file_batches "${files[@]}" | awk -v prefix="$dir/" '
2762
+ {
2763
+ digest = $1
2764
+ $1 = ""
2765
+ sub(/^ +/, "")
2766
+ if (index($0, prefix) == 1) $0 = substr($0, length(prefix) + 1)
2767
+ printf "migration:%s\t%s\n", $0, digest
2768
+ }' | LC_ALL=C sort
2769
+ [[ "${PIPESTATUS[0]}" == "0" && "${PIPESTATUS[1]}" == "0" ]]
2770
+ }
2771
+
2697
2772
  fmix_compute_template_key() {
2773
+ fmix_template_key_manifest_hash "$1" fmix-template-key-v5 1
2774
+ }
2775
+
2776
+ # FMix <= 2.7.9 addressed templates and stamped sessions with the v4 key, which
2777
+ # had no migrations digest. Kept only so artifact adoption can prove a session
2778
+ # stamped under v4 still describes the exact same non-migration inputs.
2779
+ fmix_compute_legacy_template_key_v4() {
2780
+ fmix_template_key_manifest_hash "$1" fmix-template-key-v4 0
2781
+ }
2782
+
2783
+ fmix_template_key_manifest_hash() {
2698
2784
  # The template caches compiled dependencies and an application baseline.
2699
2785
  # mix.lock alone is insufficient: path dependencies and dependency options
2700
2786
  # can change in mix.exs without producing a lockfile delta.
@@ -2708,7 +2794,7 @@ fmix_compute_template_key() {
2708
2794
  # and recompiles config-dependent APP modules after the post-clone
2709
2795
  # `mix compile`. Database selection uses the separate migration-content
2710
2796
  # manifest below and never includes wall-clock dates.
2711
- local worktree="$1"
2797
+ local worktree="$1" key_tag="$2" with_migrations="$3"
2712
2798
  local key toolchain_identity manifest rc
2713
2799
  toolchain_identity="${FMIX_TOOLCHAIN_IDENTITY:-}"
2714
2800
  if [[ -z "$toolchain_identity" ]]; then
@@ -2716,7 +2802,7 @@ fmix_compute_template_key() {
2716
2802
  fi
2717
2803
  manifest="$(mktemp)" || return 1
2718
2804
  (
2719
- printf 'fmix-template-key-v4\n'
2805
+ printf '%s\n' "$key_tag"
2720
2806
  printf 'os_arch=%s %s\n' "$FMIX_OS" "$FMIX_ARCH"
2721
2807
  printf '%s\n' "$toolchain_identity"
2722
2808
  for f in .tool-versions mix.exs mix.lock; do
@@ -2735,6 +2821,9 @@ fmix_compute_template_key() {
2735
2821
  fi
2736
2822
  done
2737
2823
  fmix_stable_seed_path_dependency_manifests "$worktree" || return 1
2824
+ if [[ "$with_migrations" == "1" ]]; then
2825
+ fmix_migrations_digest "$worktree" || return 1
2826
+ fi
2738
2827
  ) >"$manifest"
2739
2828
  rc=$?
2740
2829
  if (( rc != 0 )); then
@@ -3299,6 +3388,91 @@ fmix_stable_seed_source_tree_is_safe() {
3299
3388
  return 0
3300
3389
  }
3301
3390
 
3391
+ fmix_relativize_session_links() {
3392
+ # Rewrite ABSOLUTE symlinks that point back INSIDE this fmix session
3393
+ # directory into equivalent relative links. Usage:
3394
+ # fmix_relativize_session_links <session_root> <tree_root>...
3395
+ #
3396
+ # A dependency's own build can create an absolute link entirely inside the
3397
+ # session: rebar3 links deps/otel_http/_build/prod/plugins/rebar3_ex_doc to
3398
+ # the matching default/plugins directory using the session's absolute path.
3399
+ # That link is neither an escape nor host-bound state -- it is the session's
3400
+ # own content -- yet the absolute-link guards (template manifest, stable-seed
3401
+ # and dependency-artifact publication) rejected it, so `fmix setup` failed
3402
+ # and operators hand-edited the session to get past it.
3403
+ #
3404
+ # Relativizing preserves the link's exact meaning, so what the guards see is
3405
+ # what the absolute form already resolved to; nothing is weakened:
3406
+ # * only links whose normalized absolute target lies inside <session_root>
3407
+ # are rewritten; a link to anywhere else stays absolute and is still
3408
+ # rejected by the guards;
3409
+ # * a tree_root that is itself a symlink, or that resolves outside the
3410
+ # session, is never touched or traversed (a real symlinked _build/deps
3411
+ # ancestor is still rejected downstream);
3412
+ # * links are never followed while walking.
3413
+ local session_root="${1:-}"
3414
+ shift || true
3415
+ [[ -n "$session_root" && -d "$session_root" && ! -L "$session_root" ]] || return 0
3416
+ (( $# > 0 )) || return 0
3417
+ local py_bin
3418
+ py_bin="$(fmix_python_bin)" || return 1
3419
+ "$py_bin" - "$session_root" "$@" <<'PY'
3420
+ import os
3421
+ import sys
3422
+
3423
+ given = os.path.normpath(sys.argv[1])
3424
+ real = os.path.realpath(given)
3425
+ prefixes = {given, real}
3426
+
3427
+
3428
+ def inside(path):
3429
+ return any(path == p or path.startswith(p + os.sep) for p in prefixes)
3430
+
3431
+
3432
+ def to_real(path):
3433
+ for p in sorted(prefixes, key=len, reverse=True):
3434
+ if path == p or path.startswith(p + os.sep):
3435
+ return real + path[len(p):]
3436
+ return path
3437
+
3438
+
3439
+ for top in sys.argv[2:]:
3440
+ top = os.path.normpath(top)
3441
+ if os.path.islink(top) or not os.path.isdir(top):
3442
+ continue
3443
+ if not inside(os.path.realpath(top)):
3444
+ continue
3445
+ for current, dirs, files in os.walk(top, topdown=True, followlinks=False):
3446
+ for name in list(dirs) + files:
3447
+ path = os.path.join(current, name)
3448
+ if not os.path.islink(path):
3449
+ continue
3450
+ target = os.readlink(path)
3451
+ if not os.path.isabs(target):
3452
+ continue
3453
+ normalized = os.path.normpath(target)
3454
+ if not inside(normalized):
3455
+ continue
3456
+ relative = os.path.relpath(
3457
+ to_real(normalized), os.path.realpath(os.path.dirname(path))
3458
+ )
3459
+ staged = f"{path}.fmix-relink-{os.getpid()}"
3460
+ os.symlink(relative, staged)
3461
+ os.replace(staged, path)
3462
+ PY
3463
+ }
3464
+
3465
+ fmix_session_normalize_links() {
3466
+ # Relativize the session's own absolute links before any guard inspects it.
3467
+ # No-op outside an fmix session (an arbitrary worktree's deps/_build is
3468
+ # never rewritten).
3469
+ local worktree="${1:-}" deps_root build_root
3470
+ [[ -n "${FMIX_ACTIVE_SESSION_ROOT:-}" ]] || return 0
3471
+ deps_root="$(fmix_session_deps_root "$worktree")" || return 0
3472
+ build_root="$(fmix_compile_build_root "$worktree")" || return 0
3473
+ fmix_relativize_session_links "$FMIX_ACTIVE_SESSION_ROOT" "$deps_root" "$build_root"
3474
+ }
3475
+
3302
3476
  fmix_stable_seed_artifacts_are_safe() {
3303
3477
  # Validate the exact dependency transport roots without following links.
3304
3478
  # allow_app=1 is only for a publisher source, where the real cdrcisco build
@@ -3908,6 +4082,7 @@ _fmix_seed_publish_locked() {
3908
4082
  return 1
3909
4083
  fi
3910
4084
 
4085
+ fmix_session_normalize_links "$real" || return 1
3911
4086
  build_lib="$(fmix_compile_build_root "$real")/test/lib"
3912
4087
  if ! fmix_stable_seed_artifacts_are_safe \
3913
4088
  "$(fmix_session_deps_root "$real")" "$build_lib" 1 "$real" \
@@ -4106,6 +4281,10 @@ fmix_publish_dependency_artifact() {
4106
4281
  }
4107
4282
  fi
4108
4283
 
4284
+ fmix_session_normalize_links "$real" || {
4285
+ fmix_lock_release "$lock_name"
4286
+ return 1
4287
+ }
4109
4288
  deps_root="$(fmix_session_deps_root "$real")" || {
4110
4289
  fmix_lock_release "$lock_name"
4111
4290
  return 1
@@ -4565,16 +4744,24 @@ fmix_artifact_state_file() {
4565
4744
 
4566
4745
  fmix_write_artifact_state() {
4567
4746
  local worktree="$1" template_key="$2" real state tmp
4747
+ local base_key=""
4568
4748
  [[ "$template_key" =~ ^[0-9a-f]{16}$ ]] || return 1
4569
4749
  real="$(fmix_realpath "$worktree")" || return 1
4570
4750
  state="$(fmix_artifact_state_file "$real")" || return 1
4571
4751
  mkdir -p "$(dirname "$state")" || return 1
4572
4752
  tmp="$(mktemp "${state}.tmp.XXXXXX")" || return 1
4753
+ # The template key minus the migrations digest. A later migration-only key
4754
+ # change is recognised by this staying equal (see
4755
+ # fmix_adopt_migration_only_key_change); empty when it cannot be computed,
4756
+ # which simply disables that adoption.
4757
+ base_key="$(fmix_compute_legacy_template_key_v4 "$real" 2>/dev/null)" || base_key=""
4758
+ [[ "$base_key" =~ ^[0-9a-f]{16}$ ]] || base_key=""
4573
4759
  if ! cat >"$tmp" <<EOF
4574
4760
  {
4575
4761
  "schema": "fmix-artifacts-v1",
4576
4762
  "path": $(fmix_json_escape "$real"),
4577
4763
  "template_key": $(fmix_json_escape "$template_key"),
4764
+ "template_base_key": $(fmix_json_escape "$base_key"),
4578
4765
  "verified_at": $(fmix_json_escape "$(fmix_now)")
4579
4766
  }
4580
4767
  EOF
@@ -5151,6 +5338,7 @@ fmix_host_test_lock_enabled() {
5151
5338
 
5152
5339
  fmix_ensure_worktree_submodules() {
5153
5340
  local target_dir="$1"
5341
+ local selected_gitlink="${2:-}"
5154
5342
 
5155
5343
  # Find top-level repo if inside a Git tree
5156
5344
  local top_repo
@@ -5160,7 +5348,11 @@ fmix_ensure_worktree_submodules() {
5160
5348
  if [[ ! -f "$target_dir/mix.exs" ]]; then
5161
5349
  if [[ -f "$top_repo/.gitmodules" ]]; then
5162
5350
  fmix_info "Detected uninitialized submodules in $top_repo. Initializing..." >&2
5163
- git -C "$top_repo" submodule update --init --recursive >&2 || true
5351
+ if [[ -n "$selected_gitlink" ]]; then
5352
+ git -C "$top_repo" submodule update --init --recursive -- ":(top,literal)$selected_gitlink" >&2 || true
5353
+ else
5354
+ git -C "$top_repo" submodule update --init --recursive >&2 || true
5355
+ fi
5164
5356
  fi
5165
5357
  fi
5166
5358
 
@@ -5178,17 +5370,290 @@ fmix_ensure_worktree_submodules() {
5178
5370
  fi
5179
5371
  }
5180
5372
 
5373
+ fmix_worktree_has_cisco_cdr_app() {
5374
+ [[ -f "$1/mix.exs" ]] || return 1
5375
+
5376
+ # A bounded static recognizer, not an Elixir interpreter. Require one
5377
+ # literal module, a direct use Mix.Project and its literal project list.
5378
+ # Python is isolated from site/PYTHONPATH and cannot create bytecode; no
5379
+ # project code, helper, toolchain, home or session preparation runs here.
5380
+ python3 -I -S -B - "$1/mix.exs" <<'PY' 2>/dev/null
5381
+ import re
5382
+ import sys
5383
+
5384
+
5385
+ class Refuse(Exception):
5386
+ pass
5387
+
5388
+
5389
+ def require(condition):
5390
+ if not condition:
5391
+ raise Refuse()
5392
+
5393
+
5394
+ def literal_end(source, start):
5395
+ quote = source[start]
5396
+ delimiter = quote * (3 if source.startswith(quote * 3, start) else 1)
5397
+ i = start + len(delimiter)
5398
+ while i < len(source):
5399
+ if source[i] == "\\":
5400
+ i += 2
5401
+ elif source.startswith("#{", i):
5402
+ # Canonical project strings interpolate simple names/calls.
5403
+ # Nested/quoted interpolation is outside this static subset.
5404
+ end = source.find("}", i + 2)
5405
+ require(end != -1 and re.fullmatch(r"[A-Za-z0-9_.&!?()\[\] +*/=-]+", source[i + 2:end]))
5406
+ i = end + 1
5407
+ elif source.startswith(delimiter, i):
5408
+ return i + len(delimiter)
5409
+ else:
5410
+ i += 1
5411
+ raise Refuse()
5412
+
5413
+
5414
+ def tokenize(source):
5415
+ tokens = []
5416
+ identifier = re.compile(r"[A-Za-z_][A-Za-z0-9_]*[!?]?")
5417
+ i = 0
5418
+ while i < len(source):
5419
+ start = i
5420
+ c = source[i]
5421
+ if c.isspace():
5422
+ i += 1
5423
+ continue
5424
+ if c == "#":
5425
+ end = source.find("\n", i)
5426
+ i = len(source) if end == -1 else end
5427
+ continue
5428
+ if c in "\"'":
5429
+ i = literal_end(source, i)
5430
+ value = "<literal>"
5431
+ elif c == "~":
5432
+ # Only canonical plain ASCII wordlists are supported. All other
5433
+ # sigils (including unused ~S decoys) refuse the whole candidate.
5434
+ require(source[i + 1:i + 2] in ("w", "W"))
5435
+ opener = source[i + 2:i + 3]
5436
+ closer = {"(": ")", "[": "]", "{": "}", "<": ">", "/": "/", "|": "|",
5437
+ "\"": "\"", "'": "'"}.get(opener)
5438
+ require(closer is not None)
5439
+ end = source.find(closer, i + 3)
5440
+ require(end != -1 and re.fullmatch(r"[A-Za-z0-9_\s]*", source[i + 3:end]))
5441
+ i = end + 1
5442
+ modifier_start = i
5443
+ while i < len(source) and source[i] in "acs":
5444
+ i += 1
5445
+ require(source[modifier_start:i] in ("", "a", "c", "s"))
5446
+ require(i == len(source) or not (source[i].isalnum() or source[i] == "_"))
5447
+ value = "<literal>"
5448
+ else:
5449
+ word = identifier.match(source, i)
5450
+ require(c != "?") # Character literals are outside this subset.
5451
+ value = word.group() if word else c
5452
+ i += len(value)
5453
+ tokens.append((value, start, i))
5454
+ require(len(tokens) <= 65_536)
5455
+ return tokens
5456
+
5457
+
5458
+ def recognizes(source):
5459
+ tokens = tokenize(source)
5460
+ words = [token[0] for token in tokens]
5461
+ require(len(words) >= 7 and words[0] == "defmodule")
5462
+
5463
+ def codeword(i, word):
5464
+ return (words[i] == word and (i == 0 or words[i - 1] not in (":", "."))
5465
+ and (i + 1 == len(words) or words[i + 1] != ":"))
5466
+
5467
+ # Never let a helper module or quoted/metaprogrammed definition become
5468
+ # authority. Even otherwise-valid multi-module mix.exs files fail closed.
5469
+ require(sum(codeword(i, "defmodule") for i in range(len(words))) == 1)
5470
+ require(not any(codeword(i, word) for i in range(len(words))
5471
+ for word in ("quote", "unquote", "unquote_splicing")))
5472
+ # Do not infer ownership through aliases or imported macros. This also
5473
+ # excludes qualified Kernel.alias/import; literal atoms/keyword keys do
5474
+ # not change lexical resolution and remain opaque field values.
5475
+ require(not any(word in ("alias", "import")
5476
+ and (i == 0 or words[i - 1] != ":")
5477
+ and (i + 1 == len(words) or words[i + 1] != ":")
5478
+ for i, word in enumerate(words)))
5479
+ projects = [i for i, word in enumerate(words[:-1])
5480
+ if word in ("def", "defp") and codeword(i, word) and words[i + 1] == "project"]
5481
+ require(len(projects) == 1)
5482
+
5483
+ i = 1
5484
+ module = []
5485
+ while i < len(words) and words[i] != "do":
5486
+ module.append(words[i])
5487
+ i += 1
5488
+ require(module and len(module) % 2 == 1
5489
+ and all(value == "." if index % 2 else re.fullmatch(r"[A-Z][A-Za-z0-9_]*", value)
5490
+ for index, value in enumerate(module)))
5491
+ require(i < len(words) and codeword(i, "do"))
5492
+ module_do = i
5493
+ i += 1
5494
+ blocks = ["module"]
5495
+ delimiters = []
5496
+ closing = {"]": "[", ")": "(", "}": "{"}
5497
+ uses = 0
5498
+ project_ok = False
5499
+ functions_seen = False
5500
+
5501
+ def statement_start(index):
5502
+ return (index - 1 == module_do or words[index - 1] == ";"
5503
+ or "\n" in source[tokens[index - 1][2]:tokens[index][1]])
5504
+
5505
+ def project_list(index):
5506
+ if words[index:index + 2] == ["(", ")"]:
5507
+ index += 2
5508
+ inline = words[index:index + 3] == [",", "do", ":"]
5509
+ require(inline or words[index:index + 1] == ["do"])
5510
+ index += 3 if inline else 1
5511
+ require(words[index:index + 1] == ["["])
5512
+ depth = ["["]
5513
+ entries = []
5514
+ entry = []
5515
+ index += 1
5516
+ while index < len(words) and depth:
5517
+ word = words[index]
5518
+ if word in ("[", "(", "{"):
5519
+ depth.append(word)
5520
+ elif word in closing:
5521
+ require(depth[-1] == closing[word])
5522
+ depth.pop()
5523
+ if not depth:
5524
+ break
5525
+ # Control blocks or spliced lists are not literal keyword fields.
5526
+ require(not any(codeword(index, key) for key in ("do", "fn", "end")))
5527
+ if word == "," and len(depth) == 1:
5528
+ entries.append(entry)
5529
+ entry = []
5530
+ else:
5531
+ entry.append(word)
5532
+ index += 1
5533
+ require(not depth)
5534
+ if entry:
5535
+ entries.append(entry)
5536
+ require(entries and all(len(field) >= 3 and field[1] == ":"
5537
+ and re.fullmatch(r"[a-z_][A-Za-z0-9_]*[!?]?", field[0])
5538
+ for field in entries))
5539
+ require([field[2:] for field in entries if field[0] == "app"] == [[":", "cdrcisco"]])
5540
+ index += 1
5541
+ require(index < len(words))
5542
+ if inline:
5543
+ require(words[index] in (";", "end")
5544
+ or (statement_start(index) and words[index] in ("def", "defp", "@")))
5545
+ else:
5546
+ require(codeword(index, "end"))
5547
+ index += 1
5548
+ return index
5549
+
5550
+ while i < len(words):
5551
+ word = words[i]
5552
+ if codeword(i, "use"):
5553
+ require(blocks == ["module"] and not delimiters and not functions_seen
5554
+ and statement_start(i) and words[i + 1:i + 4] == ["Mix", ".", "Project"])
5555
+ uses += 1
5556
+ require(uses == 1)
5557
+ i += 4
5558
+ require(i < len(words) and (words[i] in (";", "end") or statement_start(i))
5559
+ and words[i] not in (",", "."))
5560
+ continue
5561
+ if word in ("def", "defp") and codeword(i, word):
5562
+ functions_seen = True
5563
+ if i == projects[0]:
5564
+ require(word == "def" and blocks == ["module"] and not delimiters
5565
+ and uses == 1 and statement_start(i))
5566
+ i = project_list(i + 2)
5567
+ project_ok = True
5568
+ continue
5569
+ if word in ("[", "(", "{"):
5570
+ delimiters.append(word)
5571
+ elif word in closing:
5572
+ require(delimiters and delimiters.pop() == closing[word])
5573
+ elif codeword(i, "do") or codeword(i, "fn"):
5574
+ blocks.append("block")
5575
+ elif codeword(i, "end"):
5576
+ require(blocks)
5577
+ blocks.pop()
5578
+ if not blocks:
5579
+ require(not delimiters and all(value == ";" for value in words[i + 1:]))
5580
+ return uses == 1 and project_ok
5581
+ i += 1
5582
+ return False
5583
+
5584
+
5585
+ try:
5586
+ with open(sys.argv[1], "rb") as handle:
5587
+ raw = handle.read(1_048_577)
5588
+ require(len(raw) <= 1_048_576)
5589
+ source = raw.decode("utf-8")
5590
+ sys.exit(0 if recognizes(source) else 1)
5591
+ except (OSError, UnicodeError, Refuse, IndexError):
5592
+ sys.exit(1)
5593
+ PY
5594
+ }
5595
+
5596
+ fmix_worktree_is_cold_submodule() {
5597
+ # A missing mix.exs is not a checkout identity. Admit the one cold
5598
+ # exception only when Git registers this exact directory as an
5599
+ # uninitialized Gitlink and .gitmodules names the cisco-cdr source.
5600
+ [[ -d "$1" && ! -e "$1/mix.exs" ]] || return 1
5601
+ local target top relative entry key registered_path url status
5602
+ target="$(fmix_realpath "$1")" || return 1
5603
+ top="$(git -C "$target" rev-parse --show-toplevel 2>/dev/null)" || return 1
5604
+ top="$(fmix_realpath "$top")" || return 1
5605
+ [[ "$target" == "$top/"* && -f "$top/.gitmodules" ]] || return 1
5606
+ relative="${target#"$top/"}"
5607
+ entry="$(git -C "$top" ls-files --stage -- "$relative" 2>/dev/null)" || return 1
5608
+ [[ "$entry" != *$'\n'* && "$entry" =~ ^160000\ [0-9a-f]{40}\ 0$'\t' ]] || return 1
5609
+ [[ "${entry#*$'\t'}" == "$relative" ]] || return 1
5610
+
5611
+ while IFS= read -r key; do
5612
+ registered_path="$(git -C "$top" config --file .gitmodules --get "$key" 2>/dev/null)" || continue
5613
+ [[ "$registered_path" == "$relative" ]] || continue
5614
+ url="$(git -C "$top" config --file .gitmodules --get "${key%.path}.url" 2>/dev/null)" || return 1
5615
+ case "$url" in
5616
+ https://github.com/calltelemetry/cisco-cdr|https://github.com/calltelemetry/cisco-cdr.git|git@github.com:calltelemetry/cisco-cdr|git@github.com:calltelemetry/cisco-cdr.git|ssh://git@github.com/calltelemetry/cisco-cdr|ssh://git@github.com/calltelemetry/cisco-cdr.git) ;;
5617
+ *) return 1 ;;
5618
+ esac
5619
+ status="$(git -C "$top" submodule status -- "$relative" 2>/dev/null)" || return 1
5620
+ [[ "$status" == -[0-9a-f]* ]] || return 1
5621
+ printf '%s\n' "$relative"
5622
+ return 0
5623
+ done < <(git -C "$top" config --file .gitmodules --name-only --get-regexp '^submodule\..*\.path$' 2>/dev/null)
5624
+ return 1
5625
+ }
5626
+
5181
5627
  fmix_find_worktree() {
5182
5628
  local path="$1"
5629
+ # Admission needs a verified candidate without initializing submodules.
5630
+ # The default resolution still initializes and verifies the checkout.
5631
+ local resolution_mode="${2:-initialize}"
5183
5632
  local search_from
5633
+ local cold_relative
5184
5634
 
5185
5635
  if [[ "$path" == "auto" ]]; then
5186
5636
  search_from="$(pwd)"
5187
5637
  # Walk up looking for mix.exs with app: :cdrcisco
5188
5638
  local dir="$search_from"
5189
5639
  while true; do
5190
- if [[ -f "$dir/mix.exs" ]] && grep -q 'app: :cdrcisco' "$dir/mix.exs" 2>/dev/null; then
5191
- fmix_ensure_worktree_submodules "$dir"
5640
+ cold_relative=""
5641
+ if fmix_worktree_has_cisco_cdr_app "$dir"; then
5642
+ :
5643
+ elif cold_relative="$(fmix_worktree_is_cold_submodule "$dir")"; then
5644
+ :
5645
+ else
5646
+ cold_relative=""
5647
+ fi
5648
+ if fmix_worktree_has_cisco_cdr_app "$dir" || [[ -n "$cold_relative" ]]; then
5649
+ if [[ "$resolution_mode" != "readonly" ]]; then
5650
+ if [[ -n "$cold_relative" ]]; then
5651
+ fmix_ensure_worktree_submodules "$dir" "$cold_relative"
5652
+ else
5653
+ fmix_ensure_worktree_submodules "$dir"
5654
+ fi
5655
+ fmix_worktree_has_cisco_cdr_app "$dir" || return 1
5656
+ fi
5192
5657
  printf '%s\n' "$dir"
5193
5658
  return 0
5194
5659
  fi
@@ -5202,10 +5667,29 @@ fmix_find_worktree() {
5202
5667
 
5203
5668
  # If not found walking up, check if CWD has a cisco-cdr subdirectory
5204
5669
  if [[ -d "$search_from/cisco-cdr" ]]; then
5205
- fmix_ensure_worktree_submodules "$search_from/cisco-cdr"
5206
- if [[ -f "$search_from/cisco-cdr/mix.exs" ]] && grep -q 'app: :cdrcisco' "$search_from/cisco-cdr/mix.exs" 2>/dev/null; then
5207
- printf '%s\n' "$search_from/cisco-cdr"
5208
- return 0
5670
+ if [[ "$resolution_mode" == "readonly" ]]; then
5671
+ cold_relative=""
5672
+ if ! fmix_worktree_has_cisco_cdr_app "$search_from/cisco-cdr"; then
5673
+ cold_relative="$(fmix_worktree_is_cold_submodule "$search_from/cisco-cdr")" || cold_relative=""
5674
+ fi
5675
+ if fmix_worktree_has_cisco_cdr_app "$search_from/cisco-cdr" || [[ -n "$cold_relative" ]]; then
5676
+ printf '%s\n' "$search_from/cisco-cdr"
5677
+ return 0
5678
+ fi
5679
+ else
5680
+ cold_relative=""
5681
+ if ! fmix_worktree_has_cisco_cdr_app "$search_from/cisco-cdr"; then
5682
+ cold_relative="$(fmix_worktree_is_cold_submodule "$search_from/cisco-cdr")" || cold_relative=""
5683
+ fi
5684
+ if [[ -n "$cold_relative" ]]; then
5685
+ fmix_ensure_worktree_submodules "$search_from/cisco-cdr" "$cold_relative"
5686
+ elif fmix_worktree_has_cisco_cdr_app "$search_from/cisco-cdr"; then
5687
+ fmix_ensure_worktree_submodules "$search_from/cisco-cdr"
5688
+ fi
5689
+ if fmix_worktree_has_cisco_cdr_app "$search_from/cisco-cdr"; then
5690
+ printf '%s\n' "$search_from/cisco-cdr"
5691
+ return 0
5692
+ fi
5209
5693
  fi
5210
5694
  fi
5211
5695
 
@@ -5223,9 +5707,30 @@ fmix_find_worktree() {
5223
5707
  resolved_dir="$resolved_dir/cisco-cdr"
5224
5708
  fi
5225
5709
 
5226
- fmix_ensure_worktree_submodules "$resolved_dir"
5710
+ cold_relative=""
5711
+ if ! fmix_worktree_has_cisco_cdr_app "$resolved_dir"; then
5712
+ cold_relative="$(fmix_worktree_is_cold_submodule "$resolved_dir")" || cold_relative=""
5713
+ fi
5714
+
5715
+ if [[ "$resolution_mode" == "readonly" ]]; then
5716
+ if ! fmix_worktree_has_cisco_cdr_app "$resolved_dir" && [[ -z "$cold_relative" ]]; then
5717
+ fmix_error "'$path' is not a cisco-cdr checkout (mix.exs missing or app: :cdrcisco not found; no recognized uninitialized cisco-cdr Gitlink)."
5718
+ return 1
5719
+ fi
5720
+ printf '%s\n' "$resolved_dir"
5721
+ return 0
5722
+ fi
5723
+ if [[ -n "$cold_relative" ]]; then
5724
+ fmix_ensure_worktree_submodules "$resolved_dir" "$cold_relative"
5725
+ elif fmix_worktree_has_cisco_cdr_app "$resolved_dir"; then
5726
+ fmix_ensure_worktree_submodules "$resolved_dir"
5727
+ else
5728
+ fmix_error "'$path' is not a cisco-cdr checkout (not inside a cisco-cdr checkout, mix.exs missing or app: :cdrcisco not found)."
5729
+ fmix_error "fmix v1 only supports cisco-cdr worktrees."
5730
+ return 1
5731
+ fi
5227
5732
 
5228
- if [[ ! -f "$resolved_dir/mix.exs" ]] || ! grep -q 'app: :cdrcisco' "$resolved_dir/mix.exs" 2>/dev/null; then
5733
+ if ! fmix_worktree_has_cisco_cdr_app "$resolved_dir"; then
5229
5734
  fmix_error "'$path' is not a cisco-cdr checkout (not inside a cisco-cdr checkout, mix.exs missing or app: :cdrcisco not found)."
5230
5735
  fmix_error "fmix v1 only supports cisco-cdr worktrees."
5231
5736
  return 1
@@ -5952,6 +6457,16 @@ fmix_build_template() {
5952
6457
  fmix_warn "Exact dependency artifact publication failed; the full template remains authoritative."
5953
6458
  fi
5954
6459
 
6460
+ # The session's own absolute links (e.g. a dependency build's plugin link)
6461
+ # become relative before staging, so the manifest guard below judges them
6462
+ # as the contained links they are.
6463
+ if ! fmix_session_normalize_links "$worktree" >>"$log_file" 2>&1; then
6464
+ fmix_error "Could not normalize session-internal symlinks. See log: $log_file"
6465
+ fmix_template_quarantine "$tmp_dir" "session link normalization failed" >/dev/null 2>&1 || true
6466
+ fmix_lock_release "$lock_name"
6467
+ return 1
6468
+ fi
6469
+
5955
6470
  fmix_info "Cloning proven session artifacts into immutable staging …"
5956
6471
  if ! fmix_cow_clone "$deps_root" "$tmp_dir/deps" >>"$log_file" 2>&1 \
5957
6472
  || ! fmix_cow_clone "$build_root" "$tmp_dir/_build" >>"$log_file" 2>&1; then
@@ -6143,7 +6658,7 @@ fmix_clone_donor_to_session() {
6143
6658
  local donor_keeper_pid
6144
6659
  [[ -f "$donor/meta.json" ]] || return 1
6145
6660
  if ! fmix_lock_keeper_start "$donor/meta.json" shared 0 \
6146
- "donor session clone" "donor-$(fmix_hash_text "$donor" | cut -c1-16)"; then
6661
+ "donor session clone" "donor-$(fmix_hash_string "$donor" | cut -c1-16)"; then
6147
6662
  fmix_warn "Could not acquire shared lock on donor session $donor."
6148
6663
  return 1
6149
6664
  fi
@@ -6308,6 +6823,27 @@ fmix_clone_template_to_worktree() {
6308
6823
  # Ensure session artifacts (deps/ + _build/) are ready and template-matched
6309
6824
  # ---------------------------------------------------------------------------
6310
6825
 
6826
+ # REL-1244: is the application itself compiled into this session overlay?
6827
+ #
6828
+ # A matching template key proves deps and toolchain agree; it does NOT prove the
6829
+ # app was compiled. An overlay from a compile that was killed by
6830
+ # FMIX_COMPILE_TIMEOUT still has deps/ and _build/ and cdrcisco.app, but no .beam
6831
+ # files and no .mix/compile.elixir. Accepting that as a session hit makes every
6832
+ # later `mix compile` rebuild the whole DAG from nothing.
6833
+ #
6834
+ # Extracted as a function so a compatibility test can call the SHIPPED logic
6835
+ # rather than replaying a copy of it.
6836
+ fmix_session_has_app_manifest() {
6837
+ local worktree="$1" build_root="$2"
6838
+ local app_name="cdrcisco" found_app=""
6839
+ if [[ -f "$worktree/mix.exs" ]]; then
6840
+ found_app="$(grep -o 'app:[[:space:]]*:[a-zA-Z0-9_]*' "$worktree/mix.exs" 2>/dev/null | head -1 | sed 's/.*:\([a-zA-Z0-9_]*\)/\1/')"
6841
+ [[ -n "$found_app" ]] && app_name="$found_app"
6842
+ fi
6843
+ [[ -f "$build_root/lib/$app_name/.mix/compile.elixir" ]] \
6844
+ || [[ -f "$build_root/lib/$app_name/.mix/compile.elixir_scm" ]]
6845
+ }
6846
+
6311
6847
  fmix_ensure_artifacts() {
6312
6848
  local worktree="$1" template_key="$2" allow_template_build="${3:-0}"
6313
6849
  local state_file artifact_state_file
@@ -6329,6 +6865,36 @@ fmix_ensure_artifacts() {
6329
6865
  [[ -d "$deps_root" ]] && has_deps=1
6330
6866
  [[ -d "$build_root" ]] && has_build=1
6331
6867
 
6868
+ # REL-1244: a matching template key is NOT proof that this session was ever
6869
+ # compiled. The key is derived from mix.lock plus the toolchain, so two
6870
+ # worktrees sharing a lockfile share a key -- and a session that inherited an
6871
+ # interrupted overlay still matches it.
6872
+ #
6873
+ # has_deps/has_build only tested that the DIRECTORIES exist. In the failure this
6874
+ # guards, the session had deps/ and _build/ present and cdrcisco.app present,
6875
+ # but ZERO .beam files and no .mix/compile.elixir for the app, because a prior
6876
+ # compile was killed by FMIX_COMPILE_TIMEOUT before it wrote a manifest. FMix
6877
+ # reported session_hit and returned success, so every subsequent `mix compile`
6878
+ # rebuilt the whole DAG from nothing (measured: 5252 files, 513s) and the
6879
+ # pre-push hook -- which runs that compile -- blew its own budget and reported
6880
+ # a compile failure that was really an unrecoverable cold rebuild.
6881
+ #
6882
+ # The clone path below touches every compile.* manifest after copying, and that
6883
+ # touch is precisely what makes a cloned session incremental. The early-return
6884
+ # path skipped that repair. Require the app compile manifest to be present
6885
+ # before accepting a session hit; otherwise fall through so the template is
6886
+ # re-cloned and the manifests are synchronized.
6887
+ #
6888
+ # Scoped deliberately to the SAME-KEY fast path. The other branches have their
6889
+ # own proofs (exact stamps, or fmix_adopt_compatible_worktree_artifacts) and a
6890
+ # key change must still be able to adopt a compatible overlay; gating the whole
6891
+ # block on the manifest broke "template storage-key changes adopt current
6892
+ # worktree stamps without cloning".
6893
+ local has_app_manifest=0
6894
+ if fmix_session_has_app_manifest "$worktree" "$build_root"; then
6895
+ has_app_manifest=1
6896
+ fi
6897
+
6332
6898
  if (( has_deps == 1 && has_build == 1 )); then
6333
6899
  if [[ -z "$recorded_key" ]]; then
6334
6900
  if [[ "$allow_template_build" != "1" ]]; then
@@ -6355,12 +6921,16 @@ fmix_ensure_artifacts() {
6355
6921
  fi
6356
6922
  fmix_info "Session artifact state is absent; exact stamps must prove it before publication."
6357
6923
  elif [[ "$recorded_key" == "$template_key" ]]; then
6358
- [[ -f "$artifact_state_file" ]] \
6359
- || fmix_write_artifact_state "$worktree" "$template_key" \
6360
- || return 1
6361
- fmix_info "Session artifacts match template key $template_key — skipping clone."
6362
- FMIX_LAST_ARTIFACTS_OUTCOME="session_hit"
6363
- return 0
6924
+ if (( has_app_manifest == 0 )); then
6925
+ fmix_warn "Session artifacts match template key $template_key but the app compile manifest is missing (interrupted or partial overlay); repairing from the template."
6926
+ else
6927
+ [[ -f "$artifact_state_file" ]] \
6928
+ || fmix_write_artifact_state "$worktree" "$template_key" \
6929
+ || return 1
6930
+ fmix_info "Session artifacts match template key $template_key — skipping clone."
6931
+ FMIX_LAST_ARTIFACTS_OUTCOME="session_hit"
6932
+ return 0
6933
+ fi
6364
6934
  else
6365
6935
  fmix_info "Template key mismatch (recorded=$recorded_key, current=$template_key)."
6366
6936
  if fmix_adopt_compatible_worktree_artifacts \
@@ -6370,6 +6940,14 @@ fmix_ensure_artifacts() {
6370
6940
  FMIX_LAST_ARTIFACTS_OUTCOME="adopt_compatible"
6371
6941
  return 0
6372
6942
  fi
6943
+ if (( has_app_manifest == 1 )) \
6944
+ && fmix_adopt_migration_only_key_change \
6945
+ "$worktree" "$recorded_key" "$template_key"; then
6946
+ fmix_write_artifact_state "$worktree" "$template_key" || return 1
6947
+ fmix_info "Only the migrations digest changed under template key $template_key — keeping the session build for incremental compile."
6948
+ FMIX_LAST_ARTIFACTS_OUTCOME="adopt_migration_delta"
6949
+ return 0
6950
+ fi
6373
6951
  if fmix_reconcile_same_toolchain_dependency_change \
6374
6952
  "$worktree" "$recorded_key" "$template_key"; then
6375
6953
  fmix_info "Dependency change adopted under template key $template_key — preserving the app cache for incremental compile."
@@ -7269,6 +7847,16 @@ fmix_publish_hot_base() {
7269
7847
  lock="db-publish-${key}"
7270
7848
  fmix_lock_acquire "$lock" "$FMIX_LOCK_TIMEOUT" || return 1
7271
7849
 
7850
+ if fmix_snapshot_ready "$target" && [[ "${FMIX_REPUBLISH_HOT_BASE:-0}" == "1" ]]; then
7851
+ # API-3576: an explicit cold rebuild just produced a verified-current
7852
+ # scratch. The base already published under this key is exactly the
7853
+ # artifact the operator is repairing, so replace it rather than keep
7854
+ # trusting it.
7855
+ fmix_warn "Replacing published hot base $target with the freshly rebuilt database."
7856
+ fmix_drop_db "$target" || { fmix_lock_release "$lock"; return 1; }
7857
+ rm -rf "$(fmix_db_index_dir "$key")" 2>/dev/null || true
7858
+ fi
7859
+
7272
7860
  if fmix_snapshot_ready "$target"; then
7273
7861
  if ! fmix_base_record_ready "$key"; then
7274
7862
  fmix_info "Hot base $target exists; publishing its missing metadata index."
@@ -7347,12 +7935,17 @@ fmix_migrate_from_zero() {
7347
7935
  # those objects) — but wherever the extension IS available, this lane is
7348
7936
  # unconditionally MORE faithful than the snapshot path can ever be by
7349
7937
  # construction, not just "no worse".
7350
- local worktree="$1" db_name="$2" key target lock timeout t0 t1
7938
+ #
7939
+ # API-3576: the optional third argument "1" (replace) skips both reuse
7940
+ # checks and replaces any published base for this key with the freshly
7941
+ # migrated result. Explicit --cold-db/--from-zero pass it: reusing a
7942
+ # published base is exactly what a rebuild is meant to avoid.
7943
+ local worktree="$1" db_name="$2" replace="${3:-0}" key target lock timeout t0 t1
7351
7944
  fmix_guard_db_name "$db_name" || return 1
7352
7945
  key="$(fmix_schema_key "$worktree")" || return 1
7353
7946
  target="$(fmix_hot_base_name "$key")" || return 1
7354
7947
 
7355
- if fmix_snapshot_ready "$target" && fmix_base_record_ready "$key"; then
7948
+ if [[ "$replace" != "1" ]] && fmix_snapshot_ready "$target" && fmix_base_record_ready "$key"; then
7356
7949
  fmix_info "Hot base $target already published for schema $key — cloning instead of migrating from zero."
7357
7950
  fmix_create_database "$db_name" "$target" || return 1
7358
7951
  return 0
@@ -7363,7 +7956,7 @@ fmix_migrate_from_zero() {
7363
7956
 
7364
7957
  # Double-checked: another host process may have published this exact
7365
7958
  # schema's hot base while we waited for the lock.
7366
- if fmix_snapshot_ready "$target" && fmix_base_record_ready "$key"; then
7959
+ if [[ "$replace" != "1" ]] && fmix_snapshot_ready "$target" && fmix_base_record_ready "$key"; then
7367
7960
  fmix_lock_release "$lock"
7368
7961
  fmix_info "Hot base $target was published while waiting on the lock — cloning."
7369
7962
  fmix_create_database "$db_name" "$target" || return 1
@@ -7399,7 +7992,7 @@ fmix_migrate_from_zero() {
7399
7992
 
7400
7993
  fmix_info "Publishing hot DB base $target from freshly from-zero-migrated $db_name …"
7401
7994
  if fmix_db_exists "$target"; then
7402
- fmix_warn "Removing incomplete hot base $target before a clean publication."
7995
+ fmix_warn "Removing incomplete or superseded hot base $target before a clean publication."
7403
7996
  fmix_drop_db "$target" || { fmix_lock_release "$lock"; return 1; }
7404
7997
  fi
7405
7998
  if ! fmix_create_database "$target" "$db_name" scratch-publish; then
@@ -7574,6 +8167,16 @@ fmix_ensure_db() {
7574
8167
  fmix_error "Scratch DB $db_name provenance is not a content-valid prefix of this branch."
7575
8168
  fi
7576
8169
  fi
8170
+ if (( valid == 1 )) && [[ "$rebuild_existing" == "1" ]]; then
8171
+ # API-3576: an explicit rebuild must rebuild. A scratch DB whose
8172
+ # recorded schema key still matches reports "0 pending migrations"
8173
+ # forever, even when the schema under that ledger is stale, so
8174
+ # reusing it here made --rebuild-db/--cold-db/--from-zero silent
8175
+ # no-ops. The operator asked for a fresh database: drop it.
8176
+ fmix_warn "Explicit rebuild requested; replacing otherwise-valid scratch DB $db_name."
8177
+ valid=0
8178
+ fmix_drop_db "$db_name" || return 1
8179
+ fi
7577
8180
  if (( valid == 1 )); then
7578
8181
  # The scratch will be asserted/migrated to the current manifest
7579
8182
  # before state publication. Preserve its source separately.
@@ -7582,18 +8185,29 @@ fmix_ensure_db() {
7582
8185
  FMIX_ACTIVE_DB_BASE_ID="$stored_base"
7583
8186
  return 0
7584
8187
  fi
7585
- if [[ "$rebuild_existing" != "1" ]]; then
7586
- fmix_error "Refusing to drop or reuse an unverified scratch DB in a normal lane."
7587
- fmix_error "After confirming no live owner: ./fmix setup --rebuild-db --worktree $worktree"
7588
- return 1
8188
+ if fmix_db_exists "$db_name"; then
8189
+ if [[ "$rebuild_existing" != "1" ]]; then
8190
+ fmix_error "Refusing to drop or reuse an unverified scratch DB in a normal lane."
8191
+ fmix_error "After confirming no live owner: ./fmix setup --rebuild-db --worktree $worktree"
8192
+ return 1
8193
+ fi
8194
+ fmix_warn "Explicit setup is replacing unverified scratch DB $db_name."
8195
+ fmix_drop_db "$db_name" || return 1
7589
8196
  fi
7590
- fmix_warn "Explicit setup is replacing unverified scratch DB $db_name."
7591
- fmix_drop_db "$db_name" || return 1
7592
8197
  fi
7593
8198
 
7594
- fmix_info "Selecting one content-indexed DB base for $db_name …"
7595
8199
  t0="$(fmix_epoch)"
7596
- selection="$(fmix_select_indexed_base "$worktree")" || selection=""
8200
+ selection=""
8201
+ if [[ "$allow_structure_build" == "1" ]]; then
8202
+ # API-3576: --cold-db and --from-zero exist to build the schema again.
8203
+ # Selecting a published hot base first re-cloned the very base that was
8204
+ # stale, so these lanes could never repair it. Skip selection; the
8205
+ # rebuilt scratch is republished over the stale base (see setup).
8206
+ fmix_info "Explicit cold rebuild: bypassing published hot bases for $db_name."
8207
+ else
8208
+ fmix_info "Selecting one content-indexed DB base for $db_name …"
8209
+ selection="$(fmix_select_indexed_base "$worktree")" || selection=""
8210
+ fi
7597
8211
  if [[ -n "$selection" ]]; then
7598
8212
  IFS=$'\t' read -r base base_key delta <<<"$selection"
7599
8213
  fmix_guard_template_db_name "$base" || return 1
@@ -7622,7 +8236,7 @@ fmix_ensure_db() {
7622
8236
  else
7623
8237
  fmix_warn "No indexed hot base exists and structure.sql is unusable for cold bootstrap; migrating from zero."
7624
8238
  fi
7625
- fmix_migrate_from_zero "$worktree" "$db_name" || return 1
8239
+ fmix_migrate_from_zero "$worktree" "$db_name" 1 || return 1
7626
8240
  FMIX_ACTIVE_DB_SCHEMA_KEY="$current_key"
7627
8241
  FMIX_ACTIVE_DB_SOURCE_KEY="$current_key"
7628
8242
  FMIX_ACTIVE_DB_BASE_ID="migrate-from-zero"
@@ -7730,6 +8344,8 @@ fmix_run_migration_bounded() {
7730
8344
  MEESEEKS_HTML5EVER_BUILD=0 \
7731
8345
  LOCAL_NATS="$NATS_HOST" \
7732
8346
  NATS_PORT="$NATS_PORT" \
8347
+ POSTHOG_BACKEND_ENABLED="${POSTHOG_BACKEND_ENABLED:-false}" \
8348
+ POSTHOG_BROWSER_ENABLED="${POSTHOG_BROWSER_ENABLED:-false}" \
7733
8349
  mix ecto.migrate --no-compile
7734
8350
  ) >"$log_file" 2>&1 &
7735
8351
  pid=$!
@@ -7952,6 +8568,8 @@ fmix_ensure_partitions() {
7952
8568
  MEESEEKS_HTML5EVER_BUILD=0 \
7953
8569
  LOCAL_NATS="$NATS_HOST" \
7954
8570
  NATS_PORT="$NATS_PORT" \
8571
+ POSTHOG_BACKEND_ENABLED="${POSTHOG_BACKEND_ENABLED:-false}" \
8572
+ POSTHOG_BROWSER_ENABLED="${POSTHOG_BROWSER_ENABLED:-false}" \
7955
8573
  env -u DB_HOST_IPV4 mix cdrcisco.bootstrap_partitions
7956
8574
  ) || {
7957
8575
  fmix_error "cdrcisco.bootstrap_partitions failed on $db_name."
@@ -9384,7 +10002,10 @@ fmix_compile_stamp_matches() {
9384
10002
  recorded_ignored_compile_hash="$(fmix_read_state "$stamp" ignored_compile_hash)"
9385
10003
 
9386
10004
  local current_template_key current_tree_hash current_env_hash current_dirty_hash
9387
- current_template_key="$(fmix_compute_template_key "$real" 2>/dev/null || echo "")"
10005
+ # The override lets artifact adoption prove a v4-stamped session against
10006
+ # the key it was actually stamped with (see
10007
+ # fmix_adopt_compatible_worktree_artifacts).
10008
+ current_template_key="${FMIX_COMPILE_STAMP_KEY_OVERRIDE:-$(fmix_compute_template_key "$real" 2>/dev/null || echo "")}"
9388
10009
  current_tree_hash="$(fmix_get_git_tree_hash "$real")" || return 1
9389
10010
  current_env_hash="$(fmix_compute_compile_env_hash "$real" 2>/dev/null || echo "")"
9390
10011
  current_dirty_hash="$(fmix_compute_dirty_hash "$real" 2>/dev/null)" \
@@ -9635,6 +10256,40 @@ fmix_reconcile_same_toolchain_dependency_change() {
9635
10256
  return 0
9636
10257
  }
9637
10258
 
10259
+ fmix_adopt_migration_only_key_change() {
10260
+ # API-3576: the template key now includes a migrations digest, so landing a
10261
+ # migration changes the key. Nothing the template caches (compiled deps and
10262
+ # the app baseline) depends on migrations, so a session whose recorded base
10263
+ # key (everything but the digest) still equals the current one keeps its
10264
+ # artifacts and only its storage key advances; Mix recompiles any changed
10265
+ # sources incrementally exactly as it did when migrations were not keyed.
10266
+ #
10267
+ # Deliberately does NOT adopt a v4-stamped session (see
10268
+ # fmix_adopt_compatible_worktree_artifacts, which also re-records stamps):
10269
+ # this path leaves stamps to the incremental compile that a changed tree
10270
+ # forces, so it requires proof that the tree actually changed.
10271
+ local worktree="$1" recorded_key="$2" template_key="$3"
10272
+ local real state_file artifact_state_file key_state_file recorded_base current_base
10273
+ local compile_stamp recorded_tree current_tree
10274
+ real="$(fmix_realpath "$worktree")" || return 1
10275
+ state_file="$(fmix_worktree_state_file "$real")"
10276
+ artifact_state_file="$(fmix_artifact_state_file "$real")"
10277
+ [[ -f "$artifact_state_file" ]] || return 1
10278
+ key_state_file="$artifact_state_file"
10279
+ [[ "$(fmix_read_state "$key_state_file" path)" == "$real" ]] || return 1
10280
+ recorded_base="$(fmix_read_state "$key_state_file" template_base_key)"
10281
+ [[ "$recorded_base" =~ ^[0-9a-f]{16}$ ]] || return 1
10282
+ current_base="$(fmix_compute_legacy_template_key_v4 "$real" 2>/dev/null)" || return 1
10283
+ [[ "$recorded_base" == "$current_base" ]] || return 1
10284
+ compile_stamp="$(fmix_compile_stamp_file "$real")"
10285
+ [[ -f "$compile_stamp" ]] || return 1
10286
+ recorded_tree="$(fmix_read_state "$compile_stamp" git_tree_hash)"
10287
+ current_tree="$(fmix_get_git_tree_hash "$real")" || return 1
10288
+ [[ -n "$recorded_tree" && "$recorded_tree" != "unknown" \
10289
+ && "$current_tree" != "unknown" && "$recorded_tree" != "$current_tree" ]] || return 1
10290
+ fmix_update_worktree_template_key "$real" "$recorded_key" "$template_key"
10291
+ }
10292
+
9638
10293
  fmix_adopt_compatible_worktree_artifacts() {
9639
10294
  local worktree="$1" recorded_key="$2" template_key="$3"
9640
10295
  local real state_file artifact_state_file key_state_file
@@ -9661,6 +10316,17 @@ fmix_adopt_compatible_worktree_artifacts() {
9661
10316
  if fmix_dependency_stamp_matches "$real" "$dependency_fingerprint" \
9662
10317
  && fmix_compile_stamp_matches "$real" "$compile_fingerprint"; then
9663
10318
  mode="current"
10319
+ elif legacy_key="$(fmix_compute_legacy_template_key_v4 "$real" 2>/dev/null)" \
10320
+ && [[ "$recorded_key" == "$legacy_key" ]] \
10321
+ && fmix_dependency_stamp_matches "$real" "$dependency_fingerprint" \
10322
+ && FMIX_COMPILE_STAMP_KEY_OVERRIDE="$legacy_key" \
10323
+ fmix_compile_stamp_matches "$real" "$compile_fingerprint"; then
10324
+ # API-3576: v5 added the migrations digest to the key, so every session
10325
+ # stamped by FMix <= 2.7.9 reads as a key mismatch even though nothing
10326
+ # it compiled changed. The recorded v4 key equals the v4 key of these
10327
+ # exact inputs and every stamp matches under it, so only the storage key
10328
+ # moves; stamps are re-recorded under v5 below.
10329
+ mode="v4"
9664
10330
  else
9665
10331
  legacy_key="$(fmix_compute_legacy_template_key_v2 "$real")" || return 1
9666
10332
  [[ "$recorded_key" == "$legacy_key" ]] || return 1
@@ -9677,7 +10343,7 @@ fmix_adopt_compatible_worktree_artifacts() {
9677
10343
  return 1
9678
10344
  fi
9679
10345
 
9680
- if [[ "$mode" == "legacy" ]]; then
10346
+ if [[ "$mode" == "legacy" || "$mode" == "v4" ]]; then
9681
10347
  if ! fmix_write_dependency_stamp "$real" "$dependency_fingerprint" \
9682
10348
  || ! fmix_write_compile_stamp "$real" "$compile_fingerprint"; then
9683
10349
  cp "$migration_dir/dependency.json" "$dependency_stamp" || true
@@ -9881,6 +10547,8 @@ _fmix_run_compile() {
9881
10547
  MEESEEKS_HTML5EVER_BUILD=0 \
9882
10548
  LOCAL_NATS="$NATS_HOST" \
9883
10549
  NATS_PORT="$NATS_PORT" \
10550
+ POSTHOG_BACKEND_ENABLED="${POSTHOG_BACKEND_ENABLED:-false}" \
10551
+ POSTHOG_BROWSER_ENABLED="${POSTHOG_BROWSER_ENABLED:-false}" \
9884
10552
  mix compile $extra 2>&1
9885
10553
  )
9886
10554
  }
@@ -10650,7 +11318,17 @@ cmd_setup() {
10650
11318
 
10651
11319
  local mig_stamp schema_key published_base
10652
11320
  schema_key="$FMIX_ACTIVE_DB_SCHEMA_KEY"
10653
- published_base="$(fmix_publish_hot_base "$real_worktree" "$db_name" "$schema_key")" || {
11321
+ # API-3576: --cold-db/--from-zero rebuilt the schema from scratch, so the
11322
+ # result must replace (not merely coexist with) any published base for this key.
11323
+ published_base="$(
11324
+ if [[ "$allow_structure_build" == "1" && "${FMIX_ACTIVE_DB_BASE_ID:-}" != "migrate-from-zero" ]]; then
11325
+ FMIX_REPUBLISH_HOT_BASE=1
11326
+ else
11327
+ FMIX_REPUBLISH_HOT_BASE=0
11328
+ fi
11329
+ export FMIX_REPUBLISH_HOT_BASE
11330
+ fmix_publish_hot_base "$real_worktree" "$db_name" "$schema_key"
11331
+ )" || {
10654
11332
  fmix_lock_release "$lock_name"
10655
11333
  return 1
10656
11334
  }
@@ -10744,6 +11422,107 @@ fmix_ensure_chromium() {
10744
11422
  # cmd: fmix test
10745
11423
  # ---------------------------------------------------------------------------
10746
11424
 
11425
+ fmix_validate_test_targets() {
11426
+ # Mix silently drops nonexistent selections when another file runs. Admit
11427
+ # every positional path before home/session/setup effects, without treating
11428
+ # Mix option values (tags, regexes, formatters, numbers) as file selections.
11429
+ local worktree="$1"
11430
+ shift
11431
+ local selection option boolean_name target prefix remaining part resolved
11432
+ local positional_only=0 takes_value=0
11433
+ while (( $# > 0 )); do
11434
+ selection="$1"
11435
+ shift
11436
+ if (( positional_only == 0 )); then
11437
+ takes_value=0
11438
+ option="${selection%%=*}"
11439
+ case "$option" in
11440
+ --)
11441
+ if [[ "$selection" == "--" ]]; then
11442
+ positional_only=1
11443
+ continue
11444
+ fi
11445
+ fmix_error "Unsupported or ambiguous Mix test option: $option. Target admission supports documented mix test options only; use -- before a literal positional selection."
11446
+ return 2
11447
+ ;;
11448
+ --include|--exclude|--only|--formatter|--name-pattern|--export-coverage|--profile-require|--max-cases|--max-failures|--max-requires|--seed|--timeout|--slowest|--slowest-modules|--partitions|--exit-status|--repeat-until-failure)
11449
+ takes_value=1
11450
+ ;;
11451
+ --*)
11452
+ boolean_name="${option#--}"
11453
+ boolean_name="${boolean_name#no-}"
11454
+ case "$boolean_name" in
11455
+ all-warnings|breakpoints|force|color|cover|trace|compile|start|raise|deps-check|archives-check|elixir-version-check|failed|stale|listen-on-stdin|preload-modules|warnings-as-errors|dry-run)
11456
+ continue
11457
+ ;;
11458
+ *)
11459
+ fmix_error "Unsupported or ambiguous Mix test option: $option. Target admission supports documented mix test options only; use -- before a literal positional selection."
11460
+ return 2
11461
+ ;;
11462
+ esac
11463
+ ;;
11464
+ -*)
11465
+ # Mix's only short aliases are -b (boolean) and -n
11466
+ # (regex). A cluster ending in -n also consumes a value;
11467
+ # a numeric suffix is an attached value, as in -n2pattern.
11468
+ if [[ "$option" =~ ^-b*n$ ]]; then
11469
+ takes_value=1
11470
+ elif [[ "$option" =~ ^-b+$ || "$option" =~ ^-b*n[0-9][^-_]*$ ]]; then
11471
+ continue
11472
+ elif [[ "$selection" != "-" && "$selection" != "- "* \
11473
+ && ! ( "$selection" =~ ^-[0-9] && "$selection" != *=* ) ]]; then
11474
+ fmix_error "Unsupported or ambiguous Mix test option: $option. Target admission supports documented mix test options only; use -- before a literal positional selection."
11475
+ return 2
11476
+ fi
11477
+ ;;
11478
+ esac
11479
+ if (( takes_value == 1 )); then
11480
+ [[ "$selection" == "$option" ]] || continue
11481
+ # Match OptionParser: another switch is not a value, but a
11482
+ # negative number, lone '-' or '- ' prefix can be one. Refuse
11483
+ # unknown arity before effects; leave value/type validation to
11484
+ # Mix rather than implementing another full option parser.
11485
+ if (( $# > 0 )) && { [[ "$1" != -* || "$1" == "-" || "$1" == "- "* ]] \
11486
+ || [[ "$1" =~ ^-[0-9] ]]; }; then
11487
+ shift
11488
+ else
11489
+ fmix_error "Mix test option requires a value: $option."
11490
+ return 2
11491
+ fi
11492
+ continue
11493
+ fi
11494
+ fi
11495
+ if [[ -z "$selection" ]]; then
11496
+ fmix_error "Invalid test target: empty positional selection."
11497
+ return 2
11498
+ fi
11499
+ # ExUnit treats the first positive numeric colon component as the
11500
+ # location boundary (including multiple lines and +/leading-zero forms).
11501
+ # Colons before that boundary remain part of the filename.
11502
+ target="$selection"
11503
+ prefix="${selection%%:*}"
11504
+ remaining="$selection"
11505
+ while [[ "$remaining" == *:* ]]; do
11506
+ remaining="${remaining#*:}"
11507
+ part="${remaining%%:*}"
11508
+ if [[ "$part" =~ ^[+]?0*[1-9][0-9]*$ ]]; then
11509
+ target="$prefix"
11510
+ break
11511
+ fi
11512
+ prefix="$prefix:$part"
11513
+ done
11514
+ case "$target" in
11515
+ /*) resolved="$target" ;;
11516
+ *) resolved="$worktree/$target" ;;
11517
+ esac
11518
+ if [[ -z "$target" || ! -f "$resolved" && ! -d "$resolved" ]]; then
11519
+ fmix_error "Missing or non-regular test target: $selection (resolved path: $resolved)."
11520
+ return 2
11521
+ fi
11522
+ done
11523
+ return 0
11524
+ }
11525
+
10747
11526
  cmd_test() {
10748
11527
  local run_mode="${FMIX_INTERNAL_RUN_MODE:-test}"
10749
11528
  local worktree_arg="auto"
@@ -10914,6 +11693,15 @@ cmd_test() {
10914
11693
  fi
10915
11694
  fi
10916
11695
 
11696
+ local worktree real_worktree
11697
+ worktree="$(fmix_find_worktree "$worktree_arg" readonly)" || return 1
11698
+ real_worktree="$(fmix_realpath "$worktree")" || return 1
11699
+ if (( mix_args_present == 1 )); then
11700
+ fmix_validate_test_targets "$real_worktree" "${mix_args[@]}" || return $?
11701
+ fi
11702
+
11703
+ # main defers all mutable test/coverage preparation until admission passes.
11704
+ fmix_prepare_command_home || return 1
10917
11705
  fmix_run_telemetry_begin "$run_mode"
10918
11706
 
10919
11707
  if (( isolate_mode == 1 )); then
@@ -10926,13 +11714,12 @@ cmd_test() {
10926
11714
  fi
10927
11715
  fi
10928
11716
 
10929
- local worktree
10930
- worktree="$(fmix_find_worktree "$worktree_arg")" || {
11717
+ # Initialize/verify this same candidate only after target admission. This
11718
+ # retains cold submodule bootstrap and the normal no-target default.
11719
+ worktree="$(fmix_find_worktree "$real_worktree")" || {
10931
11720
  fmix_run_telemetry_finish 1
10932
11721
  return 1
10933
11722
  }
10934
- local real_worktree
10935
- real_worktree="$(fmix_realpath "$worktree")"
10936
11723
  fmix_activate_toolchain "$real_worktree" || {
10937
11724
  fmix_run_telemetry_finish 1
10938
11725
  return 1
@@ -11208,6 +11995,8 @@ cmd_test() {
11208
11995
  SECRET_KEY_BASE="$SECRET_KEY_BASE"
11209
11996
  MEESEEKS_HTML5EVER_BUILD=0
11210
11997
  CT_SKIP_MIGRATION_TIMING=1
11998
+ POSTHOG_BACKEND_ENABLED="${POSTHOG_BACKEND_ENABLED:-false}"
11999
+ POSTHOG_BROWSER_ENABLED="${POSTHOG_BROWSER_ENABLED:-false}"
11211
12000
  )
11212
12001
  [[ -n "$event_fd" ]] && common_env+=("FMIX_EVENT_FD=$event_fd")
11213
12002
  # The child must observe the same run and session identity that
@@ -11453,6 +12242,8 @@ cmd_task() {
11453
12242
  ONPREM=TRUE \
11454
12243
  SECRET_KEY_BASE="$SECRET_KEY_BASE" \
11455
12244
  MEESEEKS_HTML5EVER_BUILD=0 \
12245
+ POSTHOG_BACKEND_ENABLED="${POSTHOG_BACKEND_ENABLED:-false}" \
12246
+ POSTHOG_BROWSER_ENABLED="${POSTHOG_BROWSER_ENABLED:-false}" \
11456
12247
  mix "${mix_args[@]}"
11457
12248
  ) || task_rc=$?
11458
12249
 
@@ -12113,8 +12904,105 @@ cmd_doctor() {
12113
12904
  # cmd: fmix status
12114
12905
  # ---------------------------------------------------------------------------
12115
12906
 
12907
+ # REL-1244: report a tree size WITHOUT stat()ing every file.
12908
+ #
12909
+ # fmix status and fmix doctor called `du -sh` on the artifact trees. On this host
12910
+ # the store is 1,682,684 files (753,820 templates + 928,864 dependency
12911
+ # artifacts, ~42 GB apparent). `du -sh` stats every one: measured at 40.9s for
12912
+ # templates and 63.5s for dependency-artifacts, i.e. ~104s of the 162s that
12913
+ # `fmix status` takes - all of it to print a size label nobody parses.
12914
+ #
12915
+ # Sizes are now read from a small cache beside each tree and refreshed at most
12916
+ # once per TTL. An uncached read returns "?" rather than blocking: a status
12917
+ # command must never be the slowest thing in a push.
12918
+ FMIX_TREE_SIZE_TTL="${FMIX_TREE_SIZE_TTL:-604800}" # 7 days
12919
+
12920
+ fmix_tree_size_cached() {
12921
+ local dir="$1" label="${2:-$(basename "$1")}"
12922
+ [[ -d "$dir" ]] || { printf '?\n'; return 0; }
12923
+ local cache="$FMIX_HOME/tree-sizes/${label}.json"
12924
+ local now recorded value
12925
+ now="$(date +%s)"
12926
+ if [[ -f "$cache" ]]; then
12927
+ recorded="$(fmix_read_state "$cache" recorded_at 2>/dev/null)"
12928
+ value="$(fmix_read_state "$cache" size 2>/dev/null)"
12929
+ # TTL is ENFORCED, not merely recorded. A cache entry without a usable
12930
+ # timestamp is treated as expired rather than trusted: an unenforced TTL
12931
+ # would report a size that a prune or a template rebuild has since
12932
+ # invalidated, and nothing would ever correct it.
12933
+ # A timestamp in the FUTURE is also invalid: `now - recorded` would be
12934
+ # negative and read as "very fresh". Clock skew or a hand-edited cache must
12935
+ # not be able to pin a stale size indefinitely.
12936
+ if [[ -n "$value" && "$recorded" =~ ^[0-9]+$ ]] \
12937
+ && (( recorded <= now )) \
12938
+ && (( now - recorded < FMIX_TREE_SIZE_TTL )); then
12939
+ printf '%s\n' "$value"
12940
+ return 0
12941
+ fi
12942
+ fi
12943
+ # No usable cached value: report unknown rather than walking 1.68M files here.
12944
+ # `fmix status --refresh-sizes` populates it explicitly.
12945
+ printf '?\n'
12946
+ return 0
12947
+ }
12948
+
12949
+ # Explicit, bounded refresh of the cached tree sizes.
12950
+ #
12951
+ # Labels MUST match what fmix_tree_size_cached is called with, or the cache is
12952
+ # written under keys nothing reads and every status stays "?". Templates are
12953
+ # cached per template key because the reader iterates per template.
12954
+ # Atomic: write beside the target and rename, so a concurrent reader never sees a
12955
+ # truncated file and two concurrent refreshes cannot interleave.
12956
+ fmix_tree_size_write() {
12957
+ local cache="$1" now="$2" size="$3" tmp
12958
+ tmp="${cache}.tmp-$$"
12959
+ if printf '{"recorded_at": %s, "size": "%s"}\n' "$now" "$size" > "$tmp" 2>/dev/null; then
12960
+ mv -f "$tmp" "$cache" 2>/dev/null || rm -f "$tmp" 2>/dev/null
12961
+ else
12962
+ rm -f "$tmp" 2>/dev/null
12963
+ fi
12964
+ }
12965
+
12966
+ fmix_tree_size_refresh() {
12967
+ local dirs_root="$FMIX_HOME/templates" key size now
12968
+ mkdir -p "$FMIX_HOME/tree-sizes" 2>/dev/null || true
12969
+ now="$(date +%s)"
12970
+ # Keys written this run; anything else in the cache refers to a tree that no
12971
+ # longer exists and is pruned below, so the cache cannot grow without bound
12972
+ # across prune/rebuild cycles.
12973
+ local -a live_keys=()
12974
+ if [[ -d "$dirs_root" ]]; then
12975
+ for dir in "$dirs_root"/*/; do
12976
+ [[ -d "$dir" ]] || continue
12977
+ key="$(basename "$dir")"
12978
+ size="$(du -sh "$dir" 2>/dev/null | awk '{print $1}')" || size="?"
12979
+ fmix_tree_size_write "$FMIX_HOME/tree-sizes/template_${key}.json" "$now" "$size"
12980
+ live_keys+=("template_${key}.json")
12981
+ printf '%s %s\n' "$size" "$dir"
12982
+ done
12983
+ fi
12984
+ local dep_root="$FMIX_HOME/dependency-artifacts/v1"
12985
+ if [[ -d "$dep_root" ]]; then
12986
+ size="$(du -sh "$dep_root" 2>/dev/null | awk '{print $1}')" || size="?"
12987
+ fmix_tree_size_write "$FMIX_HOME/tree-sizes/dependency_artifacts_v1.json" "$now" "$size"
12988
+ live_keys+=("dependency_artifacts_v1.json")
12989
+ printf '%s %s\n' "$size" "$dep_root"
12990
+ fi
12991
+ local existing base keep lk
12992
+ shopt -s nullglob
12993
+ for existing in "$FMIX_HOME/tree-sizes"/*.json; do
12994
+ base="$(basename "$existing")"
12995
+ keep=0
12996
+ for lk in "${live_keys[@]+"${live_keys[@]}"}"; do
12997
+ [[ "$base" == "$lk" ]] && { keep=1; break; }
12998
+ done
12999
+ (( keep == 0 )) && rm -f "$existing" 2>/dev/null
13000
+ done
13001
+ shopt -u nullglob
13002
+ }
13003
+
12116
13004
  cmd_status() {
12117
- local scoped_run_id="" scoped_json=0
13005
+ local scoped_run_id="" scoped_json=0 refresh_sizes=0
12118
13006
  while (( $# > 0 )); do
12119
13007
  case "$1" in
12120
13008
  --run-id)
@@ -12124,9 +13012,13 @@ cmd_status() {
12124
13012
  ;;
12125
13013
  --run-id=*) scoped_run_id="${1#--run-id=}"; shift ;;
12126
13014
  --json) scoped_json=1; shift ;;
12127
- *) fmix_error "Unknown status option: $1. Usage: fmix status [--run-id <uuid> --json]"; return 2 ;;
13015
+ --refresh-sizes) refresh_sizes=1; shift ;;
13016
+ *) fmix_error "Unknown status option: $1. Usage: fmix status [--run-id <uuid> --json] [--refresh-sizes]"; return 2 ;;
12128
13017
  esac
12129
13018
  done
13019
+ # NOTE: the refresh runs further down, AFTER --run-id validation. It walks every
13020
+ # artifact tree (~90s), so doing it before validation would spend that cost on an
13021
+ # invocation that is about to exit 2 with a usage error.
12130
13022
  if [[ -n "$scoped_run_id" ]]; then
12131
13023
  if ! fmix_run_id_is_valid "$scoped_run_id"; then
12132
13024
  fmix_error "Invalid FMix run ID: $scoped_run_id"
@@ -12209,6 +13101,13 @@ PY
12209
13101
  echo ""
12210
13102
 
12211
13103
  # Templates
13104
+ # Explicit, bounded: walks the artifact trees ONCE and records the result.
13105
+ # Normal status never does this; it reads the cached figure. Ordered after all
13106
+ # argument validation so a rejected invocation never pays for the walk.
13107
+ if (( refresh_sizes == 1 )); then
13108
+ fmix_tree_size_refresh >/dev/null
13109
+ fi
13110
+
12212
13111
  echo "--- Templates ($FMIX_HOME/templates/) ---"
12213
13112
  if [[ -d "$FMIX_HOME/templates" ]]; then
12214
13113
  local any_templates=0
@@ -12226,7 +13125,7 @@ PY
12226
13125
  built_at="$(fmix_read_template_meta "$key" "built_at")"
12227
13126
  last_used="$(fmix_read_template_last_used "$key")"
12228
13127
  local size=""
12229
- size="$(du -sh "$tdir" 2>/dev/null | awk '{print $1}')" || true
13128
+ size="$(fmix_tree_size_cached "$tdir" "template_${key}")"
12230
13129
  printf " %s status=%-10s built=%s last_used=%s size=%s\n" \
12231
13130
  "$key" "$status" "$built_at" "$last_used" "$size"
12232
13131
  done
@@ -12241,8 +13140,7 @@ PY
12241
13140
  if [[ -d "$FMIX_HOME/dependency-artifacts/v1" ]]; then
12242
13141
  dependency_artifact_count="$(find "$FMIX_HOME/dependency-artifacts/v1" \
12243
13142
  -mindepth 2 -maxdepth 2 -type d 2>/dev/null | wc -l | tr -d ' ')"
12244
- dependency_artifact_bytes="$(du -sh "$FMIX_HOME/dependency-artifacts/v1" \
12245
- 2>/dev/null | awk '{print $1}')" || dependency_artifact_bytes="?"
13143
+ dependency_artifact_bytes="$(fmix_tree_size_cached "$FMIX_HOME/dependency-artifacts/v1" "dependency_artifacts_v1")"
12246
13144
  printf ' generations=%s size=%s ttl=%sd\n' \
12247
13145
  "${dependency_artifact_count:-0}" "${dependency_artifact_bytes:-0}" \
12248
13146
  "$FMIX_DEPENDENCY_ARTIFACT_TTL_DAYS"
@@ -13259,15 +14157,22 @@ cmd_self_test() {
13259
14157
  # Also cover a top-level cisco-cdr submodule that has not materialized its
13260
14158
  # mix.exs yet. The mocked update creates the checkout while keeping every
13261
14159
  # initialization diagnostic off command-substitution stdout.
13262
- local submodule_parent top_level_wt top_level_stderr top_level_stdout
14160
+ local submodule_parent top_level_wt top_level_stderr top_level_stdout top_level_fixture_sha
13263
14161
  submodule_parent="$(mktemp -d)"
13264
14162
  submodule_parent="$(fmix_realpath "$submodule_parent")"
13265
14163
  top_level_wt="$submodule_parent/cisco-cdr"
13266
14164
  top_level_stderr="$(mktemp)"
13267
14165
  git init -q "$submodule_parent"
13268
14166
  mkdir -p "$top_level_wt"
13269
- printf '[submodule "cisco-cdr"]\n\tpath = cisco-cdr\n\turl = https://example.invalid/cisco-cdr.git\n' \
14167
+ printf '[submodule "cisco-cdr"]\n\tpath = cisco-cdr\n\turl = https://github.com/calltelemetry/cisco-cdr.git\n' \
13270
14168
  >"$submodule_parent/.gitmodules"
14169
+ git -C "$submodule_parent" -c user.name=fmix-self-test \
14170
+ -c user.email=fmix-self-test@example.invalid -c commit.gpgsign=false \
14171
+ commit --allow-empty -qm 'owned cold Gitlink fixture'
14172
+ top_level_fixture_sha="$(git -C "$submodule_parent" rev-parse HEAD)"
14173
+ git -C "$submodule_parent" add .gitmodules
14174
+ git -C "$submodule_parent" update-index --add --cacheinfo \
14175
+ "160000,$top_level_fixture_sha,cisco-cdr"
13271
14176
  if top_level_stdout="$({
13272
14177
  git() {
13273
14178
  if [[ " $* " == *" submodule update --init --recursive "* ]]; then
@@ -17618,9 +18523,9 @@ Usage:
17618
18523
  [--rebuild-db|--cold-db|--from-zero]
17619
18524
 
17620
18525
  Notes:
17621
- --rebuild-db reuse snapshots only; never replays structure.sql
17622
- --cold-db explicit one-time schema cache build
17623
- --from-zero full migration chain from an empty DB (structure.sql stale)
18526
+ --rebuild-db drop and re-clone the scratch DB from a published base; never replays structure.sql
18527
+ --cold-db rebuild from structure.sql, ignoring published bases, and replace the published base
18528
+ --from-zero full migration chain from an empty DB, replacing the published base (structure.sql stale)
17624
18529
 
17625
18530
  Example:
17626
18531
  fmix setup --worktree ./cisco-cdr
@@ -17754,9 +18659,9 @@ Examples:
17754
18659
  ./fmix task --worktree ./cisco-cdr -- openapi.gen --format all
17755
18660
  ./fmix task --worktree ./cisco-cdr --database ct_dev --mix-env dev -- ecto.migrate
17756
18661
  ./fmix setup --worktree ./cisco-cdr
17757
- ./fmix setup --rebuild-db --worktree ./cisco-cdr # reuse snapshots only; never replays structure.sql
17758
- ./fmix setup --cold-db --worktree ./cisco-cdr # explicit one-time schema cache build
17759
- ./fmix setup --from-zero --worktree ./cisco-cdr # full migration chain from an empty DB; structure.sql unusable/stale
18662
+ ./fmix setup --rebuild-db --worktree ./cisco-cdr # drop and re-clone the scratch DB from a published base; never replays structure.sql
18663
+ ./fmix setup --cold-db --worktree ./cisco-cdr # rebuild from structure.sql, ignoring and replacing the published base
18664
+ ./fmix setup --from-zero --worktree ./cisco-cdr # full migration chain from an empty DB, replacing the published base; structure.sql unusable/stale
17760
18665
  ./fmix seed publish --worktree ./cisco-cdr --cache-base 0.8.7-stable
17761
18666
  ./fmix cache explain --worktree ./cisco-cdr --cache-base 0.8.7-stable
17762
18667
  ./fmix doctor
@@ -19978,11 +20883,7 @@ fmix_observability_validate_worker_capability() {
19978
20883
 
19979
20884
  main() {
19980
20885
  if (( $# == 0 )); then
19981
- fmix_prepare_home || return 1
19982
- mkdir -p "$FMIX_HOME"/{templates,template-access,dependency-artifacts,dependency-artifact-access,sessions,worktrees,db-index,compile-stamps,dependency-stamps,locks,lock-kernel,lock-metadata,logs,quarantine} \
19983
- || return 1
19984
- fmix_prepare_session_state_root || return 1
19985
- chmod 0700 "$FMIX_HOME" 2>/dev/null || true
20886
+ fmix_prepare_command_home || return 1
19986
20887
  fmix_usage
19987
20888
  return 0
19988
20889
  fi
@@ -20021,12 +20922,8 @@ main() {
20021
20922
 
20022
20923
  if [[ "$cmd" == "cache" ]]; then
20023
20924
  fmix_prepare_home_readonly || return 1
20024
- else
20025
- fmix_prepare_home || return 1
20026
- mkdir -p "$FMIX_HOME"/{templates,template-access,dependency-artifacts,dependency-artifact-access,sessions,worktrees,db-index,compile-stamps,dependency-stamps,locks,lock-kernel,lock-metadata,logs,quarantine} \
20027
- || return 1
20028
- fmix_prepare_session_state_root || return 1
20029
- chmod 0700 "$FMIX_HOME" 2>/dev/null || true
20925
+ elif [[ "$cmd" != "test" && "$cmd" != "coverage" ]]; then
20926
+ fmix_prepare_command_home || return 1
20030
20927
  fi
20031
20928
 
20032
20929
  case "$cmd" in