@calltelemetry/fmix 2.7.19 → 2.7.20

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 +2698 -138
  2. package/package.json +3 -3
package/bin/fmix CHANGED
@@ -3,7 +3,7 @@
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>] [--no-auto-setup] [--unit] -- <mix test args>
6
+ # ./fmix test [--worktree <path>] [--session <id>] [--isolate] [--cache-base <N.N.N-stable>] [--no-auto-setup] [--unit] [--profile-boot] [--profile-fixtures] -- <mix test args>
7
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...>
@@ -20,6 +20,7 @@
20
20
  # ./fmix self-test
21
21
  # ./fmix verify-push [--worktree <path>] [--cooldown-minutes <N>] [--require-receipt]
22
22
  # ./fmix hook install [--worktree <path>]
23
+ # ./fmix runner <submit|status|logs|cancel|list|receipt|install-hooks|gc-worktree>
23
24
  #
24
25
 
25
26
  set -uo pipefail
@@ -27,7 +28,7 @@ set -uo pipefail
27
28
  # ---------------------------------------------------------------------------
28
29
  # Constants & config
29
30
  # ---------------------------------------------------------------------------
30
- FMIX_VERSION="2.7.19"
31
+ FMIX_VERSION="2.7.20"
31
32
  FMIX_HOME="${FMIX_HOME:-${HOME}/.ct-fmix}"
32
33
  FMIX_OS="$(uname -s)"
33
34
  FMIX_ARCH="$(uname -m)"
@@ -103,7 +104,12 @@ FMIX_AUTO_EXPIRE_MAX_LIMIT="10"
103
104
  FMIX_MIGRATION_DELTA_LIMIT="${FMIX_MIGRATION_DELTA_LIMIT:-50}"
104
105
  FMIX_COMPILE_HEARTBEAT="${FMIX_COMPILE_HEARTBEAT:-30}"
105
106
  FMIX_COMPILE_TIMEOUT="${FMIX_COMPILE_TIMEOUT:-900}"
106
- FMIX_SETUP_COMPILE_TIMEOUT="${FMIX_SETUP_COMPILE_TIMEOUT:-900}"
107
+ # An explicit setup is a deliberate cold build. Its no-output stall budget
108
+ # cancels only a compiler that has stopped producing output; the absolute
109
+ # ceiling is a last-resort bound against a wedged process, not a progress
110
+ # estimate. The 900s normal-compile cap never applies to setup.
111
+ FMIX_SETUP_COMPILE_TIMEOUT="${FMIX_SETUP_COMPILE_TIMEOUT:-7200}"
112
+ FMIX_SETUP_COMPILE_STALL_TIMEOUT="${FMIX_SETUP_COMPILE_STALL_TIMEOUT:-600}"
107
113
  FMIX_DEPS_HEARTBEAT="${FMIX_DEPS_HEARTBEAT:-15}"
108
114
  FMIX_DEPS_STALL_TIMEOUT="${FMIX_DEPS_STALL_TIMEOUT:-120}"
109
115
  FMIX_DEPS_TIMEOUT="${FMIX_DEPS_TIMEOUT:-600}"
@@ -357,7 +363,7 @@ fmix_timing_help_requested() {
357
363
  fmix_readonly_entrypoint() {
358
364
  local arg
359
365
  case "${1:-}" in
360
- ""|help|--help|-h|version|--version) return 0 ;;
366
+ ""|help|--help|-h|version|--version|analyze) return 0 ;;
361
367
  timing)
362
368
  shift
363
369
  fmix_timing_help_requested "$@"
@@ -556,6 +562,71 @@ fmix_heal_toolchain_stale_nifs() {
556
562
  return 0
557
563
  }
558
564
 
565
+ fmix_native_deps_missing_so() {
566
+ # Read-only. Print (one per line) every elixir_make dependency that ships
567
+ # c_src + a Makefile but has no built NIF (.so/.dylib/.dll) anywhere under
568
+ # its priv/. Such a dep leaves `on_load` failing at runtime (for example
569
+ # "module Sippet.Parser is not available") while Mix still believes the dep
570
+ # is compiled. Deps already proven to build no priv library carry a
571
+ # .fmix-no-native-so sentinel and are skipped so a false positive costs
572
+ # one rebuild attempt, not one per run.
573
+ local deps_root="${1:-}" dep_dir
574
+ [[ -d "$deps_root" ]] || return 0
575
+ for dep_dir in "$deps_root"/*/; do
576
+ dep_dir="${dep_dir%/}"
577
+ [[ -d "$dep_dir/c_src" ]] || continue
578
+ [[ -f "$dep_dir/Makefile" || -f "$dep_dir/c_src/Makefile" ]] || continue
579
+ [[ -f "$dep_dir/mix.exs" ]] && grep -q elixir_make "$dep_dir/mix.exs" 2>/dev/null \
580
+ || continue
581
+ [[ -e "$dep_dir/.fmix-no-native-so" ]] && continue
582
+ if [[ -d "$dep_dir/priv" ]] \
583
+ && [[ -n "$(find -L "$dep_dir/priv" \( -name '*.so' -o -name '*.dylib' -o -name '*.dll' \) \
584
+ -print -quit 2>/dev/null)" ]]; then
585
+ continue
586
+ fi
587
+ basename "$dep_dir"
588
+ done
589
+ }
590
+
591
+ fmix_repair_missing_native_deps() {
592
+ # Post-install / post-heal verification: every native dep must have its NIF.
593
+ # fmix_heal_toolchain_stale_nifs deletes .so/.o/c_build but Mix does not
594
+ # re-run a dependency it already considers compiled, and donor clones /
595
+ # dependency artifacts can carry a purged tree. Force `mix deps.compile
596
+ # <dep> --force` for exactly the deps that lack their priv library; make
597
+ # then rebuilds them because the objects are gone. Best-effort: failures
598
+ # warn and the normal compile/test path surfaces the real error.
599
+ local worktree="${1:-}" deps_root dep
600
+ local -a missing=() build_env=()
601
+ [[ -n "$worktree" ]] || return 0
602
+ deps_root="$(fmix_session_deps_root "$worktree")" || return 0
603
+ [[ -d "$deps_root" ]] || return 0
604
+ while IFS= read -r dep; do
605
+ [[ -n "$dep" ]] && missing+=("$dep")
606
+ done < <(fmix_native_deps_missing_so "$deps_root")
607
+ (( ${#missing[@]} > 0 )) || return 0
608
+
609
+ fmix_warn "Native dependencies missing their NIF library: ${missing[*]}; rebuilding with mix deps.compile --force."
610
+ [[ -n "${MIX_BUILD_PATH:-}" ]] && build_env+=("MIX_BUILD_PATH=$MIX_BUILD_PATH")
611
+ [[ -n "${MIX_DEPS_PATH:-}" ]] && build_env+=("MIX_DEPS_PATH=$MIX_DEPS_PATH")
612
+ if ! (
613
+ cd "$worktree" || exit 1
614
+ exec env \
615
+ "${build_env[@]+"${build_env[@]}"}" \
616
+ MIX_ENV=test \
617
+ MEESEEKS_HTML5EVER_BUILD=0 \
618
+ mix deps.compile "${missing[@]}" --force
619
+ ); then
620
+ fmix_warn "mix deps.compile --force failed for: ${missing[*]}"
621
+ fi
622
+ while IFS= read -r dep; do
623
+ [[ -n "$dep" ]] || continue
624
+ fmix_warn "Dependency $dep still has no priv NIF library after rebuild; assuming it builds none."
625
+ : >"$deps_root/$dep/.fmix-no-native-so" 2>/dev/null || true
626
+ done < <(fmix_native_deps_missing_so "$deps_root")
627
+ return 0
628
+ }
629
+
559
630
  fmix_psql() {
560
631
  # Portable psql: prefer local binary, fall back to docker exec
561
632
  # Sets PGPASSWORD for the call.
@@ -1193,6 +1264,27 @@ fmix_epoch() {
1193
1264
  date +%s
1194
1265
  }
1195
1266
 
1267
+ # Wall-clock milliseconds for boundaries that must line up with in-VM
1268
+ # System.os_time(:millisecond) marks; whole seconds cannot split mix_test.
1269
+ fmix_epoch_ms() {
1270
+ if [[ -n "${EPOCHREALTIME:-}" ]]; then
1271
+ local t="${EPOCHREALTIME/[.,]/}"
1272
+ printf '%s\n' "${t:0:${#t}-3}"
1273
+ else
1274
+ python3 -c 'import time; print(int(time.time() * 1000))'
1275
+ fi
1276
+ }
1277
+
1278
+ # Record the runner side of the boot timeline next to the harness artifacts.
1279
+ # Analysis joins these with the VM's boot_timeline.json marks; absent outside
1280
+ # FMIX_RUN_ID executions.
1281
+ fmix_write_mix_boundaries() {
1282
+ local live="${FMIX_RUN_ARTIFACT_DIR:-}/live"
1283
+ [[ -n "${FMIX_RUN_ARTIFACT_DIR:-}" && -d "$live" && ! -L "$live" ]] || return 0
1284
+ printf '{"schema":"fmix-mix-boundaries.v1","clock":"os_time_ms","guard_pre_started_at":%s,"spawned_at":%s,"exited_at":%s,"guard_post_finished_at":%s,"boot_profile":%s,"fixture_profile":%s}\n' \
1285
+ "$1" "$2" "$3" "$4" "$5" "$6" > "$live/mix_boundaries.json" 2>/dev/null || true
1286
+ }
1287
+
1196
1288
  fmix_run_id_is_valid() {
1197
1289
  local run_id="${1:-}"
1198
1290
  [[ "$run_id" =~ ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ ]]
@@ -3652,6 +3744,17 @@ try:
3652
3744
  finally: os.close(fd)
3653
3745
  PY
3654
3746
  }
3747
+ fmix_managed_publication_gate() {
3748
+ # Shared-cache publication requires the managed install (fmix install).
3749
+ # An npm/mise-linked runner is refused. Report the validator's reason and
3750
+ # the remediation, so the hold is never misattributed to disk capacity.
3751
+ local reason
3752
+ reason="$(fmix_artifact_v2_managed_entrypoint 2>&1)" && return 0
3753
+ fmix_warn "Shared ${1:-artifact} publication is held: managed launcher check failed (${reason:-unknown})."
3754
+ fmix_warn "Run 'fmix install' and invoke fmix as \$HOME/.local/bin/fmix so shared templates and dependency artifacts can publish."
3755
+ return 1
3756
+ }
3757
+
3655
3758
  fmix_artifact_v2_producer_runner_is_known() {
3656
3759
  local digest="${1:-}" py_bin
3657
3760
  [[ "$digest" =~ ^[0-9a-f]{64}$ ]] || return 1
@@ -3768,18 +3871,21 @@ _fmix_touch_dependency_artifact_access_write() {
3768
3871
  }
3769
3872
 
3770
3873
  fmix_touch_app_compile_artifact_access() {
3874
+ # Access timestamps live outside the CAS and land via one atomic
3875
+ # mktemp+mv, so a lease is never acquired just to refresh one. When the
3876
+ # caller already holds the exact artifact lease, keep the fail-closed
3877
+ # keeper check (a dead keeper is corrupt hold state) and write through
3878
+ # the same atomic path.
3771
3879
  local lane="${1:-}" exact="${2:-}" lock_name index
3772
3880
  [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
3773
3881
  lock_name="app-compile-${lane:0:16}-${exact:0:16}"
3774
3882
  if index="$(fmix_lock_find_index "$lock_name")"; then
3775
3883
  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
3884
  fi
3885
+ _fmix_touch_app_compile_artifact_access_write "$lane" "$exact"
3780
3886
  }
3781
3887
 
3782
- _fmix_touch_app_compile_artifact_access_locked() {
3888
+ _fmix_touch_app_compile_artifact_access_write() {
3783
3889
  # Mutable access timestamps stay outside the immutable CAS, mirroring the
3784
3890
  # dependency pool's outside-CAS access pattern.
3785
3891
  local lane="${1:-}" exact="${2:-}" root access tmp artifact
@@ -4014,7 +4120,7 @@ fmix_dependency_artifact_is_complete() {
4014
4120
  recorded="$(fmix_read_state "$artifact/meta.json" manifest_sha256)"
4015
4121
  [[ "$expected" =~ ^[0-9a-f]{64}$ && "$recorded" == "$expected" ]] || return 1
4016
4122
  if [[ "$allow_writable" == "0" ]]; then
4017
- writable="$(find "$artifact" -perm -u+w -print -quit 2>/dev/null)" || return 1
4123
+ writable="$(find "$artifact" ! -type l -perm -u+w -print -quit 2>/dev/null)" || return 1
4018
4124
  [[ -z "$writable" ]] || return 1
4019
4125
  fi
4020
4126
  }
@@ -4027,8 +4133,20 @@ fmix_dependency_artifact_verify_full_unleased() {
4027
4133
  [[ "$actual" == "$expected" ]]
4028
4134
  }
4029
4135
 
4136
+ fmix_dependency_artifact_cas_read_identity() {
4137
+ # meta.json + manifest.sha256 identity snapshot for lock-free v2 reads
4138
+ # (see the retirement engine's identity() audit fields). A mid-read
4139
+ # quarantine rename or replacement publication changes it; missing
4140
+ # metadata fails closed as an ordinary miss.
4141
+ local artifact="${1:-}"
4142
+ [[ "$artifact" == "$FMIX_HOME/artifacts/v2/dependencies/"* ]] || return 1
4143
+ fmix_stat_identity "$artifact/meta.json" || return 1
4144
+ fmix_stat_identity "$artifact/manifest.sha256" || return 1
4145
+ }
4146
+
4030
4147
  fmix_dependency_artifact_verify_full() {
4031
4148
  local artifact="${1:-}" lane="${2:-}" exact="${3:-}" lock_name index
4149
+ local attempt before after outcome
4032
4150
  if [[ "$artifact" != "$FMIX_HOME/artifacts/v2/dependencies/"* ]]; then
4033
4151
  fmix_dependency_artifact_verify_full_unleased "$@"
4034
4152
  return $?
@@ -4036,20 +4154,58 @@ fmix_dependency_artifact_verify_full() {
4036
4154
  fmix_artifact_v2_managed_entrypoint || return 1
4037
4155
  lock_name="dependency-artifact-${lane:0:16}-${exact:0:16}"
4038
4156
  if index="$(fmix_lock_find_index "$lock_name")"; then
4157
+ # A mutation pipeline (install/publish/quarantine) already holds the
4158
+ # exact artifact lease: keep the serialized verify.
4039
4159
  kill -0 "${FMIX_HELD_LOCK_KEEPER_PIDS[$index]}" 2>/dev/null || return 1
4040
4160
  fmix_dependency_artifact_verify_full_unleased "$@"
4041
- else
4042
- fmix_with_artifact_lease "$lock_name" fmix_dependency_artifact_verify_full_unleased "$@"
4161
+ return $?
4043
4162
  fi
4163
+ # Lock-free CAS read. The published tree is immutable and this read never
4164
+ # promotes or writes CAS contents, so the exact artifact lease is not
4165
+ # taken: pure readers must not queue behind a publisher's lease. After
4166
+ # validation, re-stat the meta.json / manifest.sha256 identities to
4167
+ # detect a mid-read quarantine rename or replacement publication and
4168
+ # retry once on identity change. An identity that still moves on the
4169
+ # retry fails closed as a miss.
4170
+ for attempt in 1 2; do
4171
+ before="$(fmix_dependency_artifact_cas_read_identity "$artifact")" || return 1
4172
+ outcome=1
4173
+ fmix_dependency_artifact_verify_full_unleased "$@" && outcome=0
4174
+ after="$(fmix_dependency_artifact_cas_read_identity "$artifact")" || after="missing"
4175
+ if [[ "$before" == "$after" ]]; then
4176
+ return "$outcome"
4177
+ fi
4178
+ done
4179
+ return 1
4044
4180
  }
4045
4181
 
4046
4182
  fmix_dependency_artifact_quarantine() {
4047
- local artifact="${1:-}" reason="${2:-invalid dependency artifact}" destination
4183
+ # Reader-observable CAS mutation: move the exact artifact into the
4184
+ # pre-computed unique quarantine destination with ONE atomic mv — a
4185
+ # single rename into the final name, no intermediate name, no copy — so
4186
+ # a concurrent lock-free reader sees complete-old or ENOENT -> ordinary
4187
+ # miss, never a torn read. Same-filesystem rename is enforced before any
4188
+ # mutation: a cross-device source fails closed instead of letting mv
4189
+ # fall back to a recursive copy. Darwin refuses a cross-parent rename of
4190
+ # a directory whose own owner-write bit is clear (see
4191
+ # fmix_template_make_readonly), so the move root alone is re-enabled for
4192
+ # owner-write immediately before the rename; the sealed contents are
4193
+ # never touched.
4194
+ local artifact="${1:-}" reason="${2:-invalid dependency artifact}"
4195
+ local destination quarantine_root source_device quarantine_device
4048
4196
  [[ "$artifact" == "$FMIX_HOME/artifacts/v2/dependencies/"* ]] || return 1
4049
4197
  [[ -e "$artifact" || -L "$artifact" ]] || return 0
4050
- destination="$FMIX_HOME/quarantine/artifacts-v2/dependencies/$(basename "$(dirname "$artifact")")-$(basename "$artifact").$(fmix_epoch).$$.${RANDOM}"
4051
4198
  fmix_dependency_artifact_path_is_owned "$artifact" || return 1
4199
+ quarantine_root="$FMIX_HOME/quarantine/artifacts-v2/dependencies"
4200
+ destination="$quarantine_root/$(basename "$(dirname "$artifact")")-$(basename "$artifact").$(fmix_epoch).$$.${RANDOM}"
4052
4201
  fmix_artifact_v2_prepare_directory "quarantine/artifacts-v2/dependencies" || return 1
4202
+ [[ ! -e "$destination" && ! -L "$destination" ]] || return 1
4203
+ source_device="$(fmix_stat_device "$artifact")" || return 1
4204
+ quarantine_device="$(fmix_stat_device "$quarantine_root")" || return 1
4205
+ [[ "$source_device" == "$quarantine_device" ]] || return 1
4206
+ if [[ "$FMIX_OS" == "Darwin" && -d "$artifact" && ! -L "$artifact" ]]; then
4207
+ chmod u+w "$artifact" || return 1
4208
+ fi
4053
4209
  if mv "$artifact" "$destination"; then
4054
4210
  fmix_warn "Quarantined dependency artifact ($reason): $destination"
4055
4211
  return 0
@@ -4172,7 +4328,7 @@ fmix_app_compile_artifact_is_complete() {
4172
4328
  recorded="$(fmix_read_state "$artifact/meta.json" manifest_sha256)"
4173
4329
  [[ "$expected" =~ ^[0-9a-f]{64}$ && "$recorded" == "$expected" ]] || return 1
4174
4330
  if [[ "$allow_writable" == "0" ]]; then
4175
- writable="$(find "$artifact" -perm -u+w -print -quit 2>/dev/null)" || return 1
4331
+ writable="$(find "$artifact" ! -type l -perm -u+w -print -quit 2>/dev/null)" || return 1
4176
4332
  [[ -z "$writable" ]] || return 1
4177
4333
  fi
4178
4334
  }
@@ -4185,18 +4341,48 @@ fmix_app_compile_artifact_verify_full_unleased() {
4185
4341
  [[ "$actual" == "$expected" ]]
4186
4342
  }
4187
4343
 
4344
+ fmix_app_compile_artifact_cas_read_identity() {
4345
+ # meta.json + manifest.sha256 identity snapshot for lock-free v2 reads
4346
+ # (see the retirement engine's identity() audit fields). A mid-read
4347
+ # quarantine rename or replacement publication changes it; missing
4348
+ # metadata fails closed as an ordinary miss.
4349
+ local artifact="${1:-}"
4350
+ [[ "$artifact" == "$FMIX_HOME/artifacts/v2/app-compiles/"* ]] || return 1
4351
+ fmix_stat_identity "$artifact/meta.json" || return 1
4352
+ fmix_stat_identity "$artifact/manifest.sha256" || return 1
4353
+ }
4354
+
4188
4355
  fmix_app_compile_artifact_verify_full() {
4189
4356
  local artifact="${1:-}" lane="${2:-}" exact="${3:-}" lock_name index
4357
+ local attempt before after outcome
4190
4358
  (( $# == 3 )) || return 1
4191
4359
  [[ "$artifact" == "$FMIX_HOME/artifacts/v2/app-compiles/"* ]] || return 1
4192
4360
  fmix_artifact_v2_managed_entrypoint || return 1
4193
4361
  lock_name="app-compile-${lane:0:16}-${exact:0:16}"
4194
4362
  if index="$(fmix_lock_find_index "$lock_name")"; then
4363
+ # A mutation pipeline (install/publish/quarantine) already holds the
4364
+ # exact artifact lease: keep the serialized verify.
4195
4365
  kill -0 "${FMIX_HELD_LOCK_KEEPER_PIDS[$index]}" 2>/dev/null || return 1
4196
4366
  fmix_app_compile_artifact_verify_full_unleased "$@"
4197
- else
4198
- fmix_with_artifact_lease "$lock_name" fmix_app_compile_artifact_verify_full_unleased "$@"
4367
+ return $?
4199
4368
  fi
4369
+ # Lock-free CAS read. The published tree is immutable and this read never
4370
+ # promotes or writes CAS contents, so the exact artifact lease is not
4371
+ # taken: pure readers must not queue behind a publisher's lease. After
4372
+ # validation, re-stat the meta.json / manifest.sha256 identities to
4373
+ # detect a mid-read quarantine rename or replacement publication and
4374
+ # retry once on identity change. An identity that still moves on the
4375
+ # retry fails closed as a miss.
4376
+ for attempt in 1 2; do
4377
+ before="$(fmix_app_compile_artifact_cas_read_identity "$artifact")" || return 1
4378
+ outcome=1
4379
+ fmix_app_compile_artifact_verify_full_unleased "$@" && outcome=0
4380
+ after="$(fmix_app_compile_artifact_cas_read_identity "$artifact")" || after="missing"
4381
+ if [[ "$before" == "$after" ]]; then
4382
+ return "$outcome"
4383
+ fi
4384
+ done
4385
+ return 1
4200
4386
  }
4201
4387
 
4202
4388
  fmix_app_compile_artifact_quick_ready() {
@@ -4260,12 +4446,32 @@ PY
4260
4446
  }
4261
4447
 
4262
4448
  fmix_app_compile_artifact_quarantine() {
4263
- local artifact="${1:-}" reason="${2:-invalid app compile artifact}" destination
4449
+ # Reader-observable CAS mutation: move the exact artifact into the
4450
+ # pre-computed unique quarantine destination with ONE atomic mv — a
4451
+ # single rename into the final name, no intermediate name, no copy — so
4452
+ # a concurrent lock-free reader sees complete-old or ENOENT -> ordinary
4453
+ # miss, never a torn read. Same-filesystem rename is enforced before any
4454
+ # mutation: a cross-device source fails closed instead of letting mv
4455
+ # fall back to a recursive copy. Darwin refuses a cross-parent rename of
4456
+ # a directory whose own owner-write bit is clear (see
4457
+ # fmix_template_make_readonly), so the move root alone is re-enabled for
4458
+ # owner-write immediately before the rename; the sealed contents are
4459
+ # never touched.
4460
+ local artifact="${1:-}" reason="${2:-invalid app compile artifact}"
4461
+ local destination quarantine_root source_device quarantine_device
4264
4462
  [[ "$artifact" == "$FMIX_HOME/artifacts/v2/app-compiles/"* ]] || return 1
4265
4463
  [[ -e "$artifact" || -L "$artifact" ]] || return 0
4266
- destination="$FMIX_HOME/quarantine/artifacts-v2/app-compiles/$(basename "$(dirname "$artifact")")-$(basename "$artifact").$(fmix_epoch).$$.${RANDOM}"
4267
4464
  fmix_app_compile_artifact_path_is_owned "$artifact" || return 1
4465
+ quarantine_root="$FMIX_HOME/quarantine/artifacts-v2/app-compiles"
4466
+ destination="$quarantine_root/$(basename "$(dirname "$artifact")")-$(basename "$artifact").$(fmix_epoch).$$.${RANDOM}"
4268
4467
  fmix_artifact_v2_prepare_directory "quarantine/artifacts-v2/app-compiles" || return 1
4468
+ [[ ! -e "$destination" && ! -L "$destination" ]] || return 1
4469
+ source_device="$(fmix_stat_device "$artifact")" || return 1
4470
+ quarantine_device="$(fmix_stat_device "$quarantine_root")" || return 1
4471
+ [[ "$source_device" == "$quarantine_device" ]] || return 1
4472
+ if [[ "$FMIX_OS" == "Darwin" && -d "$artifact" && ! -L "$artifact" ]]; then
4473
+ chmod u+w "$artifact" || return 1
4474
+ fi
4269
4475
  if mv "$artifact" "$destination"; then
4270
4476
  fmix_warn "Quarantined app compile artifact ($reason): $destination"
4271
4477
  return 0
@@ -5281,7 +5487,11 @@ try:
5281
5487
  # transport occurrence (not unique inodes or allocated source blocks),
5282
5488
  # including repeated link targets. Cycles/drift/unknown types hold.
5283
5489
  import time
5284
- deadline = time.monotonic() + 5
5490
+ # Network filesystems (NFS-backed shared FMIX_HOME) need far more than a
5491
+ # workstation-local 5s to stat-walk a compiled artifact tree; a timeout
5492
+ # here fail-closes as "incomplete capacity observation" and holds every
5493
+ # optional publication. Bound the walk generously and still fail closed.
5494
+ deadline = time.monotonic() + 300
5285
5495
  remaining = 200000
5286
5496
  total = 0
5287
5497
  def identity(info):
@@ -5476,7 +5686,7 @@ EOF
5476
5686
  rm -rf "$tmp" 2>/dev/null || true
5477
5687
  return 1
5478
5688
  }
5479
- writable="$(find "$tmp" -mindepth 1 -perm -u+w -print -quit 2>/dev/null)" \
5689
+ writable="$(find "$tmp" -mindepth 1 ! -type l -perm -u+w -print -quit 2>/dev/null)" \
5480
5690
  || writable=invalid
5481
5691
  if ! fmix_artifact_v2_managed_entrypoint; then
5482
5692
  rm -rf "$tmp" 2>/dev/null || true
@@ -5542,10 +5752,12 @@ fmix_find_dependency_reconciler() {
5542
5752
  candidate_exact="$(basename "$candidate")"
5543
5753
  [[ "$candidate_exact" =~ ^[0-9a-f]{64}$ && "$candidate_exact" != "$exact" ]] \
5544
5754
  || continue
5545
- distance="$(fmix_with_reused_artifact_lease \
5546
- "dependency-artifact-${lane:0:16}-${candidate_exact:0:16}" \
5547
- fmix_dependency_reconciler_distance "$candidate" "$worktree" \
5548
- "$lane" "$exact" "$head")" || continue
5755
+ # Reconciler selection is a pure read audit over candidate
5756
+ # generations: verification runs lock-free (see
5757
+ # fmix_dependency_artifact_verify_full) and never takes a
5758
+ # candidate's artifact lease.
5759
+ distance="$(fmix_dependency_reconciler_distance \
5760
+ "$candidate" "$worktree" "$lane" "$exact" "$head")" || continue
5549
5761
  if [[ -z "$selected_distance" || "$distance" -lt "$selected_distance" ]]; then
5550
5762
  selected="$candidate"
5551
5763
  selected_distance="$distance"
@@ -6006,7 +6218,7 @@ _fmix_publish_app_compile_artifact_locked() {
6006
6218
  producer_sha="$(git -C "$real" rev-parse --verify 'HEAD^{commit}' 2>/dev/null)" \
6007
6219
  || producer_sha=""
6008
6220
  [[ "$producer_sha" =~ ^[0-9a-f]{40}$ ]] || return 1
6009
- if ! fmix_artifact_v2_managed_entrypoint; then
6221
+ if ! fmix_managed_publication_gate app-compile; then
6010
6222
  fmix_warn "Optional app-compile publication held because the managed runner handoff is unproven; keeping the current session."
6011
6223
  return 3
6012
6224
  fi
@@ -6082,7 +6294,7 @@ EOF
6082
6294
  rm -rf "$tmp" 2>/dev/null || true
6083
6295
  return 1
6084
6296
  }
6085
- writable="$(find "$tmp" -mindepth 1 -perm -u+w -print -quit 2>/dev/null)" \
6297
+ writable="$(find "$tmp" -mindepth 1 ! -type l -perm -u+w -print -quit 2>/dev/null)" \
6086
6298
  || writable=invalid
6087
6299
  if ! fmix_artifact_v2_managed_entrypoint; then
6088
6300
  rm -rf "$tmp" 2>/dev/null || true
@@ -6242,6 +6454,8 @@ _fmix_install_app_compile_artifact_locked() {
6242
6454
  [[ -n "$saved_trap_term" ]] && eval "$saved_trap_term"
6243
6455
  [[ -n "$saved_trap_hup" ]] && eval "$saved_trap_hup"
6244
6456
  fmix_touch_app_compile_artifact_access "$artifact_lane" "$exact" || return 1
6457
+ fmix_session_relink_app_priv "$build_root" \
6458
+ || fmix_warn "Could not relink the application priv to this checkout: $target/priv"
6245
6459
  return 0
6246
6460
  fi
6247
6461
 
@@ -6609,6 +6823,11 @@ fmix_template_access_file() {
6609
6823
  }
6610
6824
 
6611
6825
  fmix_update_template_last_used() {
6826
+ # Access timestamps live outside the CAS and land via one atomic
6827
+ # mktemp+mv, so a lease is never acquired just to refresh one. When the
6828
+ # caller already holds the exact build lease, keep the fail-closed
6829
+ # keeper check (a dead keeper is corrupt hold state) and write through
6830
+ # the same atomic path.
6612
6831
  local key="${1:-}" lock_name index
6613
6832
  [[ "$key" =~ ^[0-9a-f]{16}$ ]] || return 1
6614
6833
  # A pressure-held producer kept a proven session, not a cache generation.
@@ -6620,13 +6839,11 @@ fmix_update_template_last_used() {
6620
6839
  lock_name="build-$key"
6621
6840
  if index="$(fmix_lock_find_index "$lock_name")"; then
6622
6841
  kill -0 "${FMIX_HELD_LOCK_KEEPER_PIDS[$index]}" 2>/dev/null || return 1
6623
- _fmix_update_template_last_used_locked "$key"
6624
- else
6625
- fmix_with_artifact_lease "$lock_name" _fmix_update_template_last_used_locked "$key"
6626
6842
  fi
6843
+ _fmix_update_template_last_used_write "$key"
6627
6844
  }
6628
6845
 
6629
- _fmix_update_template_last_used_locked() {
6846
+ _fmix_update_template_last_used_write() {
6630
6847
  # Templates are immutable. Mutable access accounting lives beside the CAS,
6631
6848
  # never inside it, so concurrent readers cannot alter a published tree.
6632
6849
  local key="$1" access tmp v2
@@ -6641,7 +6858,7 @@ _fmix_update_template_last_used_locked() {
6641
6858
  else
6642
6859
  mkdir -p "$(dirname "$access")" || return 1
6643
6860
  fi
6644
- tmp="${access}.tmp-$$-${RANDOM}"
6861
+ tmp="$(mktemp "${access}.tmp.XXXXXX")" || return 1
6645
6862
  printf '%s\n' "$(fmix_now)" >"$tmp" || { rm -f "$tmp"; return 1; }
6646
6863
  mv "$tmp" "$access" || { rm -f "$tmp"; return 1; }
6647
6864
  }
@@ -7259,6 +7476,44 @@ fmix_lock_acquire() {
7259
7476
  # Retirement is passive: do not interpret or repair legacy lock state.
7260
7477
  # Refuse preexisting metadata while holding the kernel lease, then release only our keeper.
7261
7478
  if [[ "$passive" == "1" && ( -e "$lock_dir" || -L "$lock_dir" || -e "$metadata_file" || -L "$metadata_file" ) ]]; then
7479
+ # Cross-pod shared homes: our keeper already holds the kernel lease,
7480
+ # so a preexisting record can only belong to a DEAD holder. When the
7481
+ # death is provable (recorded pid gone, or pid+start pair reused --
7482
+ # the exact conditions the active path quarantines on), quarantine
7483
+ # the dead record -- never rewrite it -- and retry the acquisition.
7484
+ # Unprovable records are still refused; passive holders never
7485
+ # interpret live state.
7486
+ local passive_dead=0 passive_pid passive_recorded_start passive_live_start
7487
+ if [[ -d "$lock_dir" && ! -L "$lock_dir" ]]; then
7488
+ passive_pid="$(cat "$lock_dir/pid" 2>/dev/null || true)"
7489
+ passive_recorded_start="$(sed -n 's/^start=//p' "$lock_dir/owner" 2>/dev/null | head -1)"
7490
+ passive_live_start=""
7491
+ [[ "$passive_pid" =~ ^[0-9]+$ ]] \
7492
+ && passive_live_start="$(fmix_lock_process_start "$passive_pid")"
7493
+ if [[ "$passive_pid" =~ ^[0-9]+$ ]] \
7494
+ && { [[ -z "$passive_live_start" ]] \
7495
+ || { [[ -n "$passive_recorded_start" ]] \
7496
+ && [[ "$passive_recorded_start" != "$passive_live_start" ]]; }; }; then
7497
+ passive_dead=1
7498
+ fi
7499
+ elif [[ -e "$metadata_file" && ! -L "$metadata_file" ]]; then
7500
+ passive_pid="$(sed -n 's/.*"pid"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "$metadata_file" | head -1)"
7501
+ if [[ "$passive_pid" =~ ^[0-9]+$ ]] && ! kill -0 "$passive_pid" 2>/dev/null; then
7502
+ passive_dead=1
7503
+ fi
7504
+ fi
7505
+ if (( passive_dead == 1 )); then
7506
+ fmix_lock_quarantine_metadata "$lock_name" "$lock_dir" \
7507
+ "dead holder record observed with kernel lease free" || true
7508
+ if [[ -e "$metadata_file" && ! -L "$metadata_file" ]]; then
7509
+ mv "$metadata_file" \
7510
+ "$FMIX_HOME/lock-metadata/stale/${lock_name}.$(fmix_epoch).$$.${RANDOM}.json" \
7511
+ 2>/dev/null || true
7512
+ fi
7513
+ fmix_lock_keeper_retire "$keeper_pid" || return 70
7514
+ sleep 0.05
7515
+ continue
7516
+ fi
7262
7517
  fmix_lock_keeper_retire "$keeper_pid" || return 70
7263
7518
  fmix_error "Passive artifact lease held by preexisting lock metadata."
7264
7519
  return 1
@@ -8318,6 +8573,21 @@ fmix_template_materialize_app_priv() {
8318
8573
  fmix_cow_clone "$resolved" "$staged_link"
8319
8574
  }
8320
8575
 
8576
+ fmix_session_relink_app_priv() {
8577
+ # Templates and the app compile CAS carry a materialized copy of the
8578
+ # application priv (fmix_template_materialize_app_priv). Installed as-is,
8579
+ # that copy is the publisher's priv, not this checkout's, and it lives on
8580
+ # FMIX_HOME (NFS on runners: ~125x slower to walk than the worktree).
8581
+ # Restore Mix's own relative link, which resolves through the session priv
8582
+ # bridge to the active checkout.
8583
+ local build_root="$1" app_priv
8584
+ app_priv="$build_root/test/lib/cdrcisco/priv"
8585
+ [[ -L "$app_priv" || ! -d "$app_priv" ]] && return 0
8586
+ fmix_guard_path "$app_priv" || return 1
8587
+ rm -rf "$app_priv" || return 1
8588
+ ln -s ../../../../priv "$app_priv"
8589
+ }
8590
+
8321
8591
  fmix_template_make_readonly() {
8322
8592
  local root="$1" writable
8323
8593
  [[ "$root" == "$FMIX_HOME/templates/"*.tmp-* \
@@ -8327,7 +8597,7 @@ fmix_template_make_readonly() {
8327
8597
  # Leave only the staging root writable for the atomic rename. Consumers
8328
8598
  # reject the destination until the publisher clears that final bit.
8329
8599
  chmod u+w "$root" || return 1
8330
- writable="$(find "$root" -mindepth 1 -perm -u+w -print -quit 2>/dev/null)" \
8600
+ writable="$(find "$root" -mindepth 1 ! -type l -perm -u+w -print -quit 2>/dev/null)" \
8331
8601
  || return 1
8332
8602
  [[ -z "$writable" ]]
8333
8603
  }
@@ -8397,7 +8667,7 @@ fmix_template_is_complete_unleased() {
8397
8667
  [[ "$recorded_key" == "$key" ]] || return 1
8398
8668
  [[ "$recorded_sha" =~ ^[0-9a-f]{64}$ && "$recorded_sha" == "$manifest_sha" ]] \
8399
8669
  || return 1
8400
- writable="$(find "$tdir" -maxdepth 1 -perm -u+w -print -quit 2>/dev/null)" \
8670
+ writable="$(find "$tdir" -maxdepth 1 ! -type l -perm -u+w -print -quit 2>/dev/null)" \
8401
8671
  || return 1
8402
8672
  [[ -z "$writable" ]]
8403
8673
  }
@@ -8485,7 +8755,7 @@ PY
8485
8755
  actual="$(fmix_hash_stdin <"$actual_tmp")"
8486
8756
  rm -f "$actual_tmp"
8487
8757
  [[ "$actual" == "$expected" ]] || return 1
8488
- writable="$(find "$tdir" -perm -u+w -print -quit 2>/dev/null)" || return 1
8758
+ writable="$(find "$tdir" ! -type l -perm -u+w -print -quit 2>/dev/null)" || return 1
8489
8759
  [[ -z "$writable" ]]
8490
8760
  }
8491
8761
 
@@ -8633,7 +8903,8 @@ fmix_surface_log_tail() {
8633
8903
 
8634
8904
  fmix_retain_session_on_template_pressure() {
8635
8905
  local key="$1" tmp_dir="$2" lock_name="$3"
8636
- fmix_warn "Optional template publication held by disk pressure or incomplete capacity observation; keeping the proven writable session."
8906
+ local cause="${4:-disk pressure or incomplete capacity observation}"
8907
+ fmix_warn "Optional template publication held by ${cause}; keeping the proven writable session."
8637
8908
  # This producer's staging is still empty. Never recursively erase an
8638
8909
  # unexpected payload or a recovery stage to manufacture a successful skip.
8639
8910
  if ! rmdir "$tmp_dir"; then
@@ -8846,8 +9117,9 @@ fmix_build_template() {
8846
9117
 
8847
9118
  # Missing managed handoff is an optional publication hold, not a cold-build
8848
9119
  # failure. Retain the exact writable session and publish no shared generation.
8849
- if ! fmix_artifact_v2_managed_entrypoint; then
8850
- fmix_retain_session_on_template_pressure "$key" "$tmp_dir" "$lock_name"
9120
+ if ! fmix_managed_publication_gate template; then
9121
+ fmix_retain_session_on_template_pressure "$key" "$tmp_dir" "$lock_name" \
9122
+ "managed launcher handoff unproven"
8851
9123
  return $?
8852
9124
  fi
8853
9125
 
@@ -9759,6 +10031,8 @@ fmix_clone_donor_to_session() {
9759
10031
  return "$donor_install_interrupt_rc"
9760
10032
  fi
9761
10033
 
10034
+ fmix_session_relink_app_priv "$build_root" \
10035
+ || fmix_warn "Could not relink the application priv to this checkout: $build_root/test/lib/cdrcisco/priv"
9762
10036
  fmix_check_known_nif_caches "$worktree" 2>/dev/null || true
9763
10037
  fmix_info "Warm donor cloned into session."
9764
10038
  return 0
@@ -13494,6 +13768,10 @@ fmix_try_compile_stamp_quick_hit() {
13494
13768
  build_root="$(fmix_compile_build_root "$real")" || return 1
13495
13769
  stamp="$(fmix_compile_stamp_file "$real")"
13496
13770
  [[ -f "$stamp" ]] || return 1
13771
+ # A deps tree missing a native dep's NIF is never a quick hit; the slower
13772
+ # (mutating) path repairs it.
13773
+ [[ -z "$(fmix_native_deps_missing_so "$(fmix_session_deps_root "$real")")" ]] \
13774
+ || return 1
13497
13775
  recorded_path="$(fmix_read_state "$stamp" path)"
13498
13776
  recorded_build="$(fmix_read_state "$stamp" build_root)"
13499
13777
  recorded_quick="$(fmix_read_state "$stamp" quick_guard)"
@@ -14088,17 +14366,26 @@ fmix_run_compile_streamed() {
14088
14366
  # when Mix is CPU-bound without producing lines. Preserve compiler failures;
14089
14367
  # a successful compile is not green if its owned permit cannot be released.
14090
14368
  local worktree="$1" db_name="$2" extra="$3" log_file="$4"
14091
- local timeout_override="${5:-}"
14092
- local heartbeat timeout pid shown=0 lines now started last_output rc sem_rc=0 cleanup_rc=0
14369
+ local timeout_override="${5:-}" stall_override="${6:-}"
14370
+ local heartbeat timeout stall=0 pid shown=0 lines now started last_output last_progress rc sem_rc=0 cleanup_rc=0
14371
+ local cancel_reason
14093
14372
  heartbeat="$(fmix_uint_or_default "$FMIX_COMPILE_HEARTBEAT" 30 FMIX_COMPILE_HEARTBEAT)"
14094
14373
  if [[ -n "$timeout_override" ]]; then
14095
14374
  timeout="$(fmix_positive_uint_or_default "$timeout_override" 900 FMIX_SETUP_COMPILE_TIMEOUT)"
14096
14375
  else
14097
14376
  timeout="$(fmix_positive_uint_or_default "$FMIX_COMPILE_TIMEOUT" 900 FMIX_COMPILE_TIMEOUT)"
14098
14377
  fi
14378
+ # A stall budget (0 = disabled) cancels only when the compiler has produced
14379
+ # no new log output for that long. Heartbeats do not count as progress.
14380
+ if [[ -n "$stall_override" ]]; then
14381
+ stall="$(fmix_positive_uint_or_default "$stall_override" 600 FMIX_SETUP_COMPILE_STALL_TIMEOUT)"
14382
+ fi
14099
14383
 
14100
- # Acquire host compilation semaphore permit (Patch 2)
14384
+ # Split this consecutive phase boundary so host contention is not
14385
+ # mistaken for compiler execution. Existing exit/permit semantics stay put.
14386
+ fmix_run_telemetry_phase "compile_preparation"
14101
14387
  fmix_compile_semaphore_acquire "$worktree" || sem_rc=$?
14388
+ fmix_run_telemetry_phase "compile_permit_wait"
14102
14389
  if (( sem_rc != 0 )); then
14103
14390
  if (( sem_rc == 75 )); then
14104
14391
  return 75
@@ -14113,11 +14400,33 @@ fmix_run_compile_streamed() {
14113
14400
  pid=$!
14114
14401
  started="$(fmix_epoch)"
14115
14402
  last_output="$started"
14403
+ last_progress="$started"
14116
14404
 
14117
14405
  while kill -0 "$pid" 2>/dev/null; do
14118
14406
  now="$(fmix_epoch)"
14407
+ cancel_reason=""
14119
14408
  if (( timeout > 0 && now - started >= timeout )); then
14120
- fmix_error "Compile exceeded ${timeout}s; cancelling instead of holding the fmix lane. Log: $log_file"
14409
+ cancel_reason="Compile exceeded ${timeout}s; cancelling instead of holding the fmix lane."
14410
+ fi
14411
+ if [[ -z "$cancel_reason" ]]; then
14412
+ lines="$(wc -l <"$log_file" | tr -d ' ')"
14413
+ if (( lines > shown )); then
14414
+ sed -n "$(( shown + 1 )),${lines}p" "$log_file" >&2
14415
+ shown="$lines"
14416
+ last_output="$(fmix_epoch)"
14417
+ last_progress="$last_output"
14418
+ else
14419
+ if (( heartbeat > 0 && now - last_output >= heartbeat )); then
14420
+ fmix_info "Compile still running ($(( now - last_output ))s without output, pid=$pid). Log: $log_file"
14421
+ last_output="$now"
14422
+ fi
14423
+ if (( stall > 0 && now - last_progress >= stall )); then
14424
+ cancel_reason="Compile produced no new output for ${stall}s (no-output stall budget); cancelling."
14425
+ fi
14426
+ fi
14427
+ fi
14428
+ if [[ -n "$cancel_reason" ]]; then
14429
+ fmix_error "$cancel_reason Log: $log_file"
14121
14430
  fmix_kill_process_tree "$pid"
14122
14431
  sleep 1
14123
14432
  kill -KILL "$pid" 2>/dev/null || true
@@ -14128,17 +14437,6 @@ fmix_run_compile_streamed() {
14128
14437
  fi
14129
14438
  return 124
14130
14439
  fi
14131
- lines="$(wc -l <"$log_file" | tr -d ' ')"
14132
- if (( lines > shown )); then
14133
- sed -n "$(( shown + 1 )),${lines}p" "$log_file" >&2
14134
- shown="$lines"
14135
- last_output="$(fmix_epoch)"
14136
- else
14137
- if (( heartbeat > 0 && now - last_output >= heartbeat )); then
14138
- fmix_info "Compile still running ($(( now - last_output ))s without output, pid=$pid). Log: $log_file"
14139
- last_output="$now"
14140
- fi
14141
- fi
14142
14440
  sleep 2
14143
14441
  done
14144
14442
  rc=0
@@ -14163,6 +14461,9 @@ _fmix_run_compile() {
14163
14461
  _fmix_deps_root="$(fmix_session_deps_root "$worktree")"
14164
14462
  fmix_heal_cmake_nif_caches "$_fmix_deps_root"
14165
14463
  fmix_heal_toolchain_stale_nifs "$_fmix_deps_root"
14464
+ # The heal above purges .so files, but Mix will not recompile deps it
14465
+ # already considers built; rebuild the purged native deps explicitly.
14466
+ fmix_repair_missing_native_deps "$worktree"
14166
14467
  local -a build_env=()
14167
14468
  [[ -n "${MIX_BUILD_PATH:-}" ]] && build_env+=("MIX_BUILD_PATH=$MIX_BUILD_PATH")
14168
14469
  [[ -n "${MIX_DEPS_PATH:-}" ]] && build_env+=("MIX_DEPS_PATH=$MIX_DEPS_PATH")
@@ -14381,6 +14682,18 @@ fmix_remove_ephemeral_oban_repo() {
14381
14682
  HEX_HOME="$FMIX_HEX_HOME" mix hex.repo remove oban >/dev/null 2>&1 || true
14382
14683
  }
14383
14684
 
14685
+ # Ensures the Hex package manager is installed for this FMIX_HOME. deps.get is
14686
+ # normally what installs it, but a dependency stamp hit skips deps.get entirely;
14687
+ # compiling then fails closed with "Could not find an SCM for dependency" on any
14688
+ # fresh MIX_HOME (new pod, node replacement, or a session cloned without it).
14689
+ fmix_ensure_hex() {
14690
+ local worktree="$1"
14691
+ (
14692
+ cd "$worktree" || exit 1
14693
+ HEX_HOME="$FMIX_HEX_HOME" mix local.hex --force --if-missing
14694
+ ) >/dev/null 2>&1
14695
+ }
14696
+
14384
14697
  _fmix_run_deps_get() {
14385
14698
  local worktree="$1"
14386
14699
  local -a build_env=()
@@ -14393,6 +14706,7 @@ _fmix_run_deps_get() {
14393
14706
  env \
14394
14707
  "${build_env[@]+"${build_env[@]}"}" \
14395
14708
  HEX_HOME="$FMIX_HEX_HOME" \
14709
+ HEX_HTTP_TIMEOUT=300 \
14396
14710
  MIX_ENV=test mix deps.get
14397
14711
  )
14398
14712
  }
@@ -14517,6 +14831,10 @@ _fmix_ensure_compile_impl() {
14517
14831
  # Only the stamp quick-hit is provably read-only. Stamp writes, deps.get,
14518
14832
  # and compilation mutate the shared session overlay.
14519
14833
  fmix_lock_mutate_gate "dependency resolution or compilation" || return $?
14834
+ # Donor clones, dependency artifacts and stamp hits can all carry a deps/
14835
+ # tree whose NIF .so was purged (the quick-hit above refuses such a tree).
14836
+ # Verify and rebuild before any stamp or CAS admission can bless it.
14837
+ fmix_repair_missing_native_deps "$worktree"
14520
14838
 
14521
14839
  # The content/config stamp is authoritative for this exact realpath and
14522
14840
  # includes mix.lock, toolchain, compiler config, path deps, and Mix
@@ -14570,12 +14888,23 @@ _fmix_ensure_compile_impl() {
14570
14888
  fmix_info "Dependency stamp hit — skipping deps.get for source-only compile."
14571
14889
  else
14572
14890
  fmix_info "Dependency stamp miss; resolving dependencies once …"
14573
- fmix_run_deps_get "$worktree" || {
14574
- local deps_rc=$?
14891
+ # Transient registry/CDN stalls (e.g. the Hex tarball fetcher's internal
14892
+ # 120s await timing out against hex.pm) are retryable; only unresolvable
14893
+ # dependencies are fatal.
14894
+ local deps_rc=0 deps_attempt
14895
+ for deps_attempt in 1 2 3; do
14896
+ fmix_run_deps_get "$worktree" && { deps_rc=0; break; }
14897
+ deps_rc=$?
14898
+ if (( deps_attempt < 3 )); then
14899
+ fmix_warn "mix deps.get attempt ${deps_attempt} failed (rc=${deps_rc}); retrying in 15s …"
14900
+ sleep 15
14901
+ fi
14902
+ done
14903
+ if (( deps_rc != 0 )); then
14575
14904
  fmix_error "mix deps.get failed; refusing to compile against unresolved dependencies."
14576
14905
  FMIX_LAST_COMPILE_OUTCOME="error"
14577
14906
  return "$deps_rc"
14578
- }
14907
+ fi
14579
14908
  dependency_fingerprint="$(fmix_compute_dependency_fingerprint "$worktree")" \
14580
14909
  || dependency_fingerprint=""
14581
14910
  if [[ -n "$dependency_fingerprint" ]]; then
@@ -14620,16 +14949,18 @@ _fmix_ensure_compile_impl() {
14620
14949
  FMIX_LAST_COMPILE_LOG="$log_file"
14621
14950
  mkdir -p "$(dirname "$log_file")"
14622
14951
  t0=$(fmix_epoch)
14623
- local compile_timeout=""
14952
+ local compile_timeout="" compile_stall=""
14624
14953
  if [[ "$compile_mode" == "setup" ]]; then
14625
- compile_timeout="$FMIX_SETUP_COMPILE_TIMEOUT"
14626
- fmix_info "Explicit setup compile budget: ${compile_timeout}s."
14954
+ compile_timeout="$(fmix_positive_uint_or_default "$FMIX_SETUP_COMPILE_TIMEOUT" 7200 FMIX_SETUP_COMPILE_TIMEOUT)"
14955
+ compile_stall="$(fmix_positive_uint_or_default "$FMIX_SETUP_COMPILE_STALL_TIMEOUT" 600 FMIX_SETUP_COMPILE_STALL_TIMEOUT)"
14956
+ fmix_info "Explicit setup compile: cancel after ${compile_stall}s without compiler output (ceiling ${compile_timeout}s)."
14627
14957
  fi
14628
14958
  if ! fmix_require_stable_source "$worktree" "compile start" 1; then
14629
14959
  FMIX_LAST_COMPILE_OUTCOME="error"
14630
14960
  return 1
14631
14961
  fi
14632
- fmix_run_compile_streamed "$worktree" "$db_name" "" "$log_file" "$compile_timeout"
14962
+ fmix_ensure_hex "$worktree" || fmix_warn "Hex bootstrap failed; compile may fail to resolve dependency SCMs."
14963
+ fmix_run_compile_streamed "$worktree" "$db_name" "" "$log_file" "$compile_timeout" "$compile_stall"
14633
14964
  rc=$?
14634
14965
  t1=$(fmix_epoch)
14635
14966
  FMIX_LAST_COMPILE_SECONDS=$(( t1 - t0 ))
@@ -14641,7 +14972,7 @@ _fmix_ensure_compile_impl() {
14641
14972
  local elapsed_compile=$(( t1 - t0 ))
14642
14973
  FMIX_LAST_COMPILE_OUTCOME="error"
14643
14974
  if (( rc == 124 )); then
14644
- fmix_error "mix compile exceeded the hard wall-clock budget (${elapsed_compile}s)."
14975
+ fmix_error "mix compile was cancelled after ${elapsed_compile}s (no-output stall budget or setup ceiling; see the compile log)."
14645
14976
  else
14646
14977
  fmix_error "Incremental mix compile failed (${elapsed_compile}s); no automatic full recompile was started."
14647
14978
  fi
@@ -14975,6 +15306,11 @@ cmd_setup() {
14975
15306
  fmix_info "Worktree: $real_worktree"
14976
15307
  fmix_info "Session root: $FMIX_ACTIVE_SESSION_ROOT"
14977
15308
  fmix_info "Template key: $template_key"
15309
+ # Surface an unmanaged launcher before a long cold compile, not after it.
15310
+ # The publication hold itself is non-fatal; this is advisory only.
15311
+ if ! fmix_artifact_v2_managed_entrypoint >/dev/null 2>&1; then
15312
+ fmix_warn "This fmix launcher is not the managed install. The cold compile will run, but shared template and dependency artifacts will not publish from it (run 'fmix install', then use \$HOME/.local/bin/fmix)."
15313
+ fi
14978
15314
  fmix_info "DB name: $db_name"
14979
15315
 
14980
15316
  fmix_preflight "$real_worktree" || return $?
@@ -15350,7 +15686,7 @@ cmd_test() {
15350
15686
  # lifecycle) that only surface in CI's --no-start lane. Use --unit before
15351
15687
  # pushing any test that the unit lane will select (test/**/unit/** files
15352
15688
  # that don't `use` a DB-capable case).
15353
- local unit_mode=0
15689
+ local unit_mode=0 profile_boot=0 profile_fixtures=0
15354
15690
  local isolate_mode=0
15355
15691
  local auto_setup=1
15356
15692
  if [[ "${FMIX_NO_AUTO_SETUP:-0}" == "1" ]]; then
@@ -15441,12 +15777,20 @@ cmd_test() {
15441
15777
  unit_mode=1
15442
15778
  shift
15443
15779
  ;;
15780
+ --profile-boot|--profile-fixtures)
15781
+ if [[ "$run_mode" == "coverage" ]]; then
15782
+ fmix_error "$1 is not supported by 'fmix coverage'."
15783
+ return 2
15784
+ fi
15785
+ [[ "$1" == "--profile-boot" ]] && profile_boot=1 || profile_fixtures=1
15786
+ shift
15787
+ ;;
15444
15788
  --) found_sep=1; shift; break ;;
15445
15789
  *)
15446
15790
  if [[ "$run_mode" == "coverage" ]]; then
15447
15791
  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>"
15448
15792
  else
15449
- fmix_error "Unknown option: $1. Usage: fmix test [--worktree <path>] [--cache-base <N.N.N-stable>] [--unit] -- <mix test args>"
15793
+ fmix_error "Unknown option: $1. Usage: fmix test [--worktree <path>] [--cache-base <N.N.N-stable>] [--unit] [--profile-boot] [--profile-fixtures] -- <mix test args>"
15450
15794
  fi
15451
15795
  return 1
15452
15796
  ;;
@@ -15860,6 +16204,11 @@ cmd_test() {
15860
16204
  # the CI lane on top of `--no-start`.
15861
16205
  local -a profile_env=()
15862
16206
  (( unit_mode == 1 )) && profile_env=("CT_TEST_PROFILE=unit")
16207
+ # Opt-in TestProf-style hooks implemented by the cisco-cdr harness.
16208
+ (( profile_boot == 1 )) && profile_env+=("CT_TEST_BOOT_PROFILE=1")
16209
+ (( profile_fixtures == 1 )) && profile_env+=("CT_TEST_FIXTURE_PROF=1")
16210
+ local mix_guard_pre_ms mix_spawn_ms mix_exit_ms
16211
+ mix_guard_pre_ms="$(fmix_epoch_ms)"
15863
16212
 
15864
16213
  local -a build_env=()
15865
16214
  [[ -n "${MIX_BUILD_PATH:-}" ]] && build_env+=("MIX_BUILD_PATH=$MIX_BUILD_PATH")
@@ -15875,6 +16224,7 @@ cmd_test() {
15875
16224
 
15876
16225
  fmix_emit_phase_change "mix_test" "started"
15877
16226
  local test_rc=0
16227
+ mix_spawn_ms="$(fmix_epoch_ms)"
15878
16228
  (
15879
16229
  cd "$real_worktree" || exit 1
15880
16230
  local -a common_env=(
@@ -15909,6 +16259,7 @@ cmd_test() {
15909
16259
  local pass_session_id="${FMIX_SESSION_ID:-${session_arg:-${FMIX_ACTIVE_SESSION_HASH:-}}}"
15910
16260
  [[ -n "$pass_session_id" ]] && common_env+=("FMIX_SESSION_ID=$pass_session_id")
15911
16261
  [[ -n "${FMIX_RUN_ID:-}" ]] && common_env+=("FMIX_RUN_ID=$FMIX_RUN_ID")
16262
+ common_env+=("FMIX_MIX_SPAWN_AT_MS=$mix_spawn_ms")
15912
16263
  if [[ "$run_mode" == "coverage" ]]; then
15913
16264
  local coverage_targets="${mix_args[*]}"
15914
16265
  local coverage_bootstrap
@@ -15977,12 +16328,15 @@ end
15977
16328
  fi
15978
16329
  )
15979
16330
  test_rc=$?
16331
+ mix_exit_ms="$(fmix_epoch_ms)"
15980
16332
 
15981
16333
  local source_stable_after_mix=1
15982
16334
  if ! fmix_require_stable_source "$real_worktree" "Mix execution"; then
15983
16335
  source_stable_after_mix=0
15984
16336
  test_rc=1
15985
16337
  fi
16338
+ fmix_write_mix_boundaries "$mix_guard_pre_ms" "$mix_spawn_ms" "$mix_exit_ms" "$(fmix_epoch_ms)" \
16339
+ "$( (( profile_boot == 1 )) && echo true || echo false)" "$( (( profile_fixtures == 1 )) && echo true || echo false)"
15986
16340
 
15987
16341
  t1=$(fmix_epoch)
15988
16342
  local test_duration_ms=$(( (t1 - t0) * 1000 ))
@@ -16426,80 +16780,939 @@ cmd_hook() {
16426
16780
  }
16427
16781
 
16428
16782
  # ---------------------------------------------------------------------------
16429
- # cmd: fmix task
16783
+ # cmd: fmix runner — distributed runner CLI (portal Worker + orchestrator REST)
16430
16784
  # ---------------------------------------------------------------------------
16785
+ # The CLI speaks plain REST against the portal base URL (FMIX_RUNNER_URL); the
16786
+ # portal Worker signs the inner HMAC envelope for orchestrator hops itself.
16787
+ # Auth is the Cloudflare Access service-token pair sent as
16788
+ # CF-Access-Client-Id / CF-Access-Client-Secret headers (mcp-launch env
16789
+ # convention), with FMIX_RUNNER_TOKEN as a bearer fallback.
16790
+
16791
+ FMIX_RUNNER_URL_DEFAULT="https://mcp.calltelemetry.com/fmix-runner"
16792
+ FMIX_RUNNER_HOOK_MARKER="# managed-by: fmix runner/hooks"
16793
+
16794
+ fmix_runner_base_url() {
16795
+ local url="${FMIX_RUNNER_URL:-$FMIX_RUNNER_URL_DEFAULT}"
16796
+ printf '%s\n' "${url%/}"
16797
+ }
16798
+
16799
+ fmix_runner_resolve_auth() {
16800
+ FMIX_RUNNER_AUTH_ID=""
16801
+ FMIX_RUNNER_AUTH_SECRET=""
16802
+ FMIX_RUNNER_AUTH_BEARER="${FMIX_RUNNER_TOKEN:-}"
16803
+ if [[ -n "${CF_ACCESS_CLIENT_ID:-}" && -n "${CF_ACCESS_CLIENT_SECRET:-}" ]]; then
16804
+ FMIX_RUNNER_AUTH_ID="$CF_ACCESS_CLIENT_ID"
16805
+ FMIX_RUNNER_AUTH_SECRET="$CF_ACCESS_CLIENT_SECRET"
16806
+ return 0
16807
+ fi
16808
+ local user_name id_val secret_val
16809
+ user_name="${USER:-$(id -un 2>/dev/null || printf '')}"
16810
+ if [[ -n "$user_name" ]]; then
16811
+ id_val="$(printenv "MCP_ACCESS_CLIENT_ID_${user_name}" 2>/dev/null || true)"
16812
+ secret_val="$(printenv "MCP_ACCESS_CLIENT_SECRET_${user_name}" 2>/dev/null || true)"
16813
+ if [[ -n "$id_val" && -n "$secret_val" ]]; then
16814
+ FMIX_RUNNER_AUTH_ID="$id_val"
16815
+ FMIX_RUNNER_AUTH_SECRET="$secret_val"
16816
+ return 0
16817
+ fi
16818
+ fi
16819
+ if [[ -n "$FMIX_RUNNER_AUTH_BEARER" ]]; then
16820
+ return 0
16821
+ fi
16822
+ fmix_error "fmix runner: missing portal credentials (no request sent)."
16823
+ fmix_error "Set CF_ACCESS_CLIENT_ID and CF_ACCESS_CLIENT_SECRET (Cloudflare Access service token),"
16824
+ fmix_error "or the per-user pair MCP_ACCESS_CLIENT_ID_${user_name:-<USER>} / MCP_ACCESS_CLIENT_SECRET_${user_name:-<USER>},"
16825
+ fmix_error "or FMIX_RUNNER_TOKEN as a bearer token."
16826
+ return 1
16827
+ }
16431
16828
 
16432
- cmd_task() {
16433
- # Run a non-test Mix task against the same exact pinned runtime and
16434
- # session-local incremental deps/_build state as fmix setup/test. This is
16435
- # the supported path for generators and developer tasks that may introduce
16436
- # new dependencies; it never uses Docker, Depot, GHCR, or a prebuilt deps
16437
- # image.
16438
- local worktree_arg="auto"
16439
- local session_arg=""
16440
- local database_arg=""
16441
- local mix_env_arg="test"
16442
- local allow_run=0
16443
- local found_sep=0
16444
- local -a mix_args=()
16829
+ fmix_runner_http_ok() {
16830
+ case "${FMIX_RUNNER_HTTP_STATUS:-}" in
16831
+ 2*) return 0 ;;
16832
+ esac
16833
+ return 1
16834
+ }
16835
+
16836
+ fmix_runner_request() {
16837
+ # fmix_runner_request <METHOD> <path> [<json-body>]
16838
+ # Lands the response body in FMIX_RUNNER_HTTP_BODY and the HTTP status in
16839
+ # FMIX_RUNNER_HTTP_STATUS (globals: callers must NOT run this in a
16840
+ # command substitution). Curl transport failures return 1 (no status).
16841
+ local method="$1" path="$2" body="${3:-}"
16842
+ FMIX_RUNNER_HTTP_STATUS=""
16843
+ FMIX_RUNNER_HTTP_BODY=""
16844
+ local url resp_file http_code curl_rc
16845
+ url="$(fmix_runner_base_url)$path"
16846
+ resp_file="$(mktemp "${TMPDIR:-/tmp}/fmix-runner.XXXXXX")" || {
16847
+ fmix_error "fmix runner: could not allocate a response file."
16848
+ return 1
16849
+ }
16850
+ local -a curl_args=()
16851
+ curl_args=(-sS --connect-timeout "${FMIX_RUNNER_CONNECT_TIMEOUT_S:-5}" --max-time "${FMIX_RUNNER_TIMEOUT_S:-60}")
16852
+ curl_args+=(-X "$method" -H "Accept: application/json")
16853
+ if [[ -n "$FMIX_RUNNER_AUTH_ID" ]]; then
16854
+ curl_args+=(-H "CF-Access-Client-Id: ${FMIX_RUNNER_AUTH_ID}")
16855
+ curl_args+=(-H "CF-Access-Client-Secret: ${FMIX_RUNNER_AUTH_SECRET}")
16856
+ fi
16857
+ if [[ -n "$FMIX_RUNNER_AUTH_BEARER" ]]; then
16858
+ curl_args+=(-H "Authorization: Bearer ${FMIX_RUNNER_AUTH_BEARER}")
16859
+ fi
16860
+ if [[ -n "$body" ]]; then
16861
+ curl_args+=(-H "Content-Type: application/json")
16862
+ curl_args+=(--data-binary "$body")
16863
+ fi
16864
+ curl_args+=(-o "$resp_file" -w '%{http_code}')
16865
+ http_code="$(curl "${curl_args[@]+"${curl_args[@]}"}" "$url")"
16866
+ curl_rc=$?
16867
+ if (( curl_rc != 0 )); then
16868
+ rm -f "$resp_file"
16869
+ fmix_error "fmix runner: transport failure calling $url (curl exit $curl_rc)."
16870
+ return 1
16871
+ fi
16872
+ FMIX_RUNNER_HTTP_STATUS="$http_code"
16873
+ if [[ -s "$resp_file" ]]; then
16874
+ FMIX_RUNNER_HTTP_BODY="$(cat "$resp_file")"
16875
+ fi
16876
+ rm -f "$resp_file"
16877
+ return 0
16878
+ }
16879
+
16880
+ fmix_runner_reply_ok() {
16881
+ # fmix_runner_reply_ok <context> <body> — shared non-2xx error path.
16882
+ local context="$1" body="${2:-}"
16883
+ if fmix_runner_http_ok; then
16884
+ return 0
16885
+ fi
16886
+ fmix_error "fmix runner: $context failed (HTTP ${FMIX_RUNNER_HTTP_STATUS:-000})."
16887
+ if [[ -n "$body" ]]; then
16888
+ fmix_error "$body"
16889
+ fi
16890
+ return 1
16891
+ }
16892
+
16893
+ fmix_runner_json_field() {
16894
+ # fmix_runner_json_field <field> — reads a JSON object on stdin and prints
16895
+ # one top-level field (empty output when absent or unparseable). Nested
16896
+ # values print as compact JSON.
16897
+ local field="$1" py_bin
16898
+ py_bin="$(fmix_python_bin 2>/dev/null || printf 'python3')"
16899
+ "$py_bin" -c '
16900
+ import json, sys
16901
+ try:
16902
+ data = json.load(sys.stdin)
16903
+ except Exception:
16904
+ sys.exit(1)
16905
+ value = data.get(sys.argv[1], "") if isinstance(data, dict) else ""
16906
+ if isinstance(value, (dict, list)):
16907
+ print(json.dumps(value, separators=(",", ":")))
16908
+ elif value is None or value == "":
16909
+ sys.exit(0)
16910
+ elif isinstance(value, bool):
16911
+ print("true" if value else "false")
16912
+ else:
16913
+ print(value)
16914
+ ' "$field"
16915
+ }
16916
+
16917
+ fmix_runner_require_job_id() {
16918
+ local job_id="${1:-}"
16919
+ if [[ -z "$job_id" ]]; then
16920
+ fmix_error "fmix runner: missing <job-id>."
16921
+ return 1
16922
+ fi
16923
+ if [[ ! "$job_id" =~ ^[A-Za-z0-9._-]{1,128}$ ]]; then
16924
+ fmix_error "fmix runner: job id '$job_id' must match [A-Za-z0-9._-]{1,128}."
16925
+ return 1
16926
+ fi
16927
+ printf '%s\n' "$job_id"
16928
+ }
16929
+
16930
+ fmix_runner_worktree_name() {
16931
+ # Named runner worktree = basename of the resolved local checkout.
16932
+ basename "$1"
16933
+ }
16934
+
16935
+ fmix_runner_submit_body() {
16936
+ # fmix_runner_submit_body <repo> <worktree-name> <ref> <command> [args...]
16937
+ local repo="$1" worktree_name="$2" ref="$3" command="$4"
16938
+ shift 4
16939
+ local args_json="" a
16940
+ for a in "$@"; do
16941
+ args_json="${args_json}${args_json:+,}$(fmix_json_escape "$a")"
16942
+ done
16943
+ printf '{"repo": %s, "worktree": %s, "ref": %s, "rebase": "none", "command": %s, "args": [%s], "mode": "ephemeral"}\n' \
16944
+ "$(fmix_json_escape "$repo")" \
16945
+ "$(fmix_json_escape "$worktree_name")" \
16946
+ "$(fmix_json_escape "$ref")" \
16947
+ "$(fmix_json_escape "$command")" \
16948
+ "$args_json"
16949
+ }
16950
+
16951
+ cmd_runner_submit() {
16952
+ local worktree_arg="auto" ref_arg="" saw_sep=0
16445
16953
  while (( $# > 0 )); do
16446
16954
  case "$1" in
16447
- --worktree)
16448
- [[ $# -ge 2 ]] || { fmix_error "--worktree requires a path argument."; return 2; }
16449
- worktree_arg="$2"
16450
- shift 2
16451
- ;;
16955
+ --worktree) [[ $# -ge 2 ]] || { fmix_error "--worktree requires a path argument."; return 2; }; worktree_arg="$2"; shift 2 ;;
16452
16956
  --worktree=*) worktree_arg="${1#--worktree=}"; shift ;;
16453
- --session)
16454
- [[ $# -ge 2 ]] || { fmix_error "--session requires an identifier."; return 2; }
16455
- session_arg="$2"
16456
- shift 2
16457
- ;;
16458
- --session=*) session_arg="${1#--session=}"; shift ;;
16459
- --database)
16460
- [[ $# -ge 2 ]] || { fmix_error "--database requires a database name."; return 2; }
16461
- database_arg="$2"
16462
- shift 2
16463
- ;;
16464
- --database=*) database_arg="${1#--database=}"; shift ;;
16465
- --mix-env)
16466
- [[ $# -ge 2 ]] || { fmix_error "--mix-env requires an environment name."; return 2; }
16467
- mix_env_arg="$2"
16468
- shift 2
16469
- ;;
16470
- --mix-env=*) mix_env_arg="${1#--mix-env=}"; shift ;;
16471
- --allow-run) allow_run=1; shift ;;
16472
- --) found_sep=1; shift; break ;;
16473
- *)
16474
- fmix_error "Unknown option: $1. Usage: fmix task [--worktree <path>] [--database <name>] [--mix-env <env>] [--allow-run] -- <mix task> [args]"
16475
- return 2
16476
- ;;
16957
+ --ref) [[ $# -ge 2 ]] || { fmix_error "--ref requires a ref argument."; return 2; }; ref_arg="$2"; shift 2 ;;
16958
+ --ref=*) ref_arg="${1#--ref=}"; shift ;;
16959
+ --) shift; saw_sep=1; break ;;
16960
+ *) fmix_error "Unknown option: $1. Usage: fmix runner submit [--worktree <path>] [--ref <ref>] -- <test|coverage|task> [args]"; return 1 ;;
16477
16961
  esac
16478
16962
  done
16479
- (( found_sep == 1 )) || {
16480
- fmix_error "'fmix task' requires -- before the Mix task."
16481
- return 2
16482
- }
16483
- mix_args=("$@")
16484
- (( ${#mix_args[@]} > 0 )) || {
16485
- fmix_error "'fmix task' requires a Mix task after --."
16486
- return 2
16487
- }
16488
- case "${mix_args[0]}" in
16489
- test|test.*)
16490
- fmix_error "Use 'fmix test' for ExUnit tasks so database and test-lane isolation remain enforced."
16491
- return 2
16492
- ;;
16493
- do|cmd)
16494
- fmix_error "'fmix task' runs one repository Mix task; nested execution via '${mix_args[0]}' is not allowed."
16495
- fmix_error "Use 'fmix test' for ExUnit, or invoke the intended non-test task directly."
16496
- return 2
16497
- ;;
16498
- run)
16499
- if (( allow_run == 0 )); then
16500
- fmix_error "'mix run' requires explicit --allow-run because it executes repository code outside a named Mix task."
16501
- return 2
16502
- fi
16963
+ if (( saw_sep == 0 )); then
16964
+ fmix_error "fmix runner submit requires '--': fmix runner submit [--worktree <path>] [--ref <ref>] -- <test|coverage|task> [args]"
16965
+ return 1
16966
+ fi
16967
+ if [[ $# -lt 1 ]]; then
16968
+ fmix_error "fmix runner submit needs a command after '--' (test, coverage, or task)."
16969
+ return 1
16970
+ fi
16971
+ local command="$1"
16972
+ shift
16973
+ case "$command" in
16974
+ test|coverage|task) ;;
16975
+ *) fmix_error "fmix runner submit command must be test, coverage, or task (got '$command')."; return 1 ;;
16976
+ esac
16977
+ local -a args=("$@")
16978
+
16979
+ local worktree
16980
+ if [[ "$worktree_arg" != "auto" ]]; then
16981
+ worktree="$(fmix_find_worktree "$worktree_arg" readonly 2>/dev/null || fmix_realpath "$worktree_arg")"
16982
+ else
16983
+ worktree="$(fmix_find_worktree auto readonly 2>/dev/null || git rev-parse --show-toplevel 2>/dev/null || pwd -P)"
16984
+ fi
16985
+ local real_worktree
16986
+ real_worktree="$(fmix_realpath "$worktree")"
16987
+ local origin_url repo
16988
+ origin_url="$(git -C "$real_worktree" remote get-url origin 2>/dev/null || true)"
16989
+ if [[ -z "$origin_url" ]]; then
16990
+ fmix_error "fmix runner submit: no 'origin' remote in $real_worktree; cannot derive owner/name."
16991
+ return 1
16992
+ fi
16993
+ # Same owner/name normalisation the runner pre-push hook uses.
16994
+ repo="$(printf '%s' "$origin_url" | sed -E -e 's#^.*github\.com[:/]##' -e 's#\.git$##' -e 's#/$##')"
16995
+ local worktree_name
16996
+ worktree_name="$(fmix_runner_worktree_name "$real_worktree")"
16997
+ local ref="$ref_arg"
16998
+ if [[ -z "$ref" ]]; then
16999
+ ref="$(git -C "$real_worktree" rev-parse HEAD 2>/dev/null || true)"
17000
+ if [[ -z "$ref" ]]; then
17001
+ fmix_error "fmix runner submit: could not resolve HEAD in $real_worktree (pass --ref <ref>)."
17002
+ return 1
17003
+ fi
17004
+ fi
17005
+
17006
+ local body
17007
+ body="$(fmix_runner_submit_body "$repo" "$worktree_name" "$ref" "$command" ${args[@]+"${args[@]}"})"
17008
+ fmix_runner_resolve_auth || return 1
17009
+ local resp job_id state
17010
+ fmix_runner_request POST "/jobs" "$body" || return 1
17011
+ resp="$FMIX_RUNNER_HTTP_BODY"
17012
+ fmix_runner_reply_ok "submit" "$resp" || return 1
17013
+ job_id="$(printf '%s' "$resp" | fmix_runner_json_field job_id 2>/dev/null || true)"
17014
+ if [[ -z "$job_id" ]]; then
17015
+ fmix_error "fmix runner: submit response carried no job_id:"
17016
+ fmix_error "$resp"
17017
+ return 1
17018
+ fi
17019
+ state="$(printf '%s' "$resp" | fmix_runner_json_field state 2>/dev/null || true)"
17020
+ fmix_info "Runner job accepted: $job_id (state=${state:-unknown}, repo=$repo, ref=$ref)"
17021
+ printf '%s\n' "$job_id"
17022
+ return 0
17023
+ }
17024
+
17025
+ cmd_runner_status() {
17026
+ if [[ $# -gt 1 ]]; then
17027
+ fmix_error "Usage: fmix runner status <job-id>"
17028
+ return 1
17029
+ fi
17030
+ local job_id
17031
+ job_id="$(fmix_runner_require_job_id "${1:-}")" || return 1
17032
+ fmix_runner_resolve_auth || return 1
17033
+ local resp state
17034
+ fmix_runner_request GET "/jobs/$job_id" || return 1
17035
+ resp="$FMIX_RUNNER_HTTP_BODY"
17036
+ fmix_runner_reply_ok "status $job_id" "$resp" || return 1
17037
+ state="$(printf '%s' "$resp" | fmix_runner_json_field state 2>/dev/null || true)"
17038
+ if [[ -n "$state" ]]; then
17039
+ fmix_info "Job $job_id state: $state"
17040
+ fi
17041
+ printf '%s\n' "$resp"
17042
+ }
17043
+
17044
+ cmd_runner_logs() {
17045
+ local job_id="" tail_n="" query=""
17046
+ while (( $# > 0 )); do
17047
+ case "$1" in
17048
+ --tail) [[ $# -ge 2 ]] || { fmix_error "--tail requires a line count."; return 2; }; tail_n="$2"; shift 2 ;;
17049
+ --tail=*) tail_n="${1#--tail=}"; shift ;;
17050
+ -*) fmix_error "Unknown option: $1. Usage: fmix runner logs <job-id> [--tail N]"; return 1 ;;
17051
+ *) if [[ -z "$job_id" ]]; then job_id="$1"; shift; else fmix_error "Unexpected argument: $1. Usage: fmix runner logs <job-id> [--tail N]"; return 1; fi ;;
17052
+ esac
17053
+ done
17054
+ job_id="$(fmix_runner_require_job_id "$job_id")" || return 1
17055
+ if [[ -n "$tail_n" ]]; then
17056
+ if [[ ! "$tail_n" =~ ^[1-9][0-9]*$ ]] || (( 10#$tail_n > 10000 )); then
17057
+ fmix_error "fmix runner logs --tail must be an integer in [1, 10000]."
17058
+ return 1
17059
+ fi
17060
+ query="?tail=$tail_n"
17061
+ fi
17062
+ fmix_runner_resolve_auth || return 1
17063
+ local resp
17064
+ fmix_runner_request GET "/jobs/$job_id/logs$query" || return 1
17065
+ resp="$FMIX_RUNNER_HTTP_BODY"
17066
+ fmix_runner_reply_ok "logs $job_id" "$resp" || return 1
17067
+ if [[ -n "$tail_n" ]]; then
17068
+ printf '%s\n' "$resp" | tail -n "$tail_n"
17069
+ else
17070
+ printf '%s\n' "$resp"
17071
+ fi
17072
+ }
17073
+
17074
+ cmd_runner_cancel() {
17075
+ if [[ $# -gt 1 ]]; then
17076
+ fmix_error "Usage: fmix runner cancel <job-id>"
17077
+ return 1
17078
+ fi
17079
+ local job_id
17080
+ job_id="$(fmix_runner_require_job_id "${1:-}")" || return 1
17081
+ fmix_runner_resolve_auth || return 1
17082
+ local resp
17083
+ fmix_runner_request DELETE "/jobs/$job_id" || return 1
17084
+ resp="$FMIX_RUNNER_HTTP_BODY"
17085
+ fmix_runner_reply_ok "cancel $job_id" "$resp" || return 1
17086
+ printf '%s\n' "$resp"
17087
+ }
17088
+
17089
+ cmd_runner_list() {
17090
+ local worktree_filter="" state_filter="" query=""
17091
+ while (( $# > 0 )); do
17092
+ case "$1" in
17093
+ --worktree) [[ $# -ge 2 ]] || { fmix_error "--worktree requires a name argument."; return 2; }; worktree_filter="$2"; shift 2 ;;
17094
+ --worktree=*) worktree_filter="${1#--worktree=}"; shift ;;
17095
+ --state) [[ $# -ge 2 ]] || { fmix_error "--state requires a state argument."; return 2; }; state_filter="$2"; shift 2 ;;
17096
+ --state=*) state_filter="${1#--state=}"; shift ;;
17097
+ *) fmix_error "Unknown option: $1. Usage: fmix runner list [--worktree <name>] [--state <state>]"; return 1 ;;
17098
+ esac
17099
+ done
17100
+ if [[ -n "$worktree_filter" ]]; then
17101
+ if [[ ! "$worktree_filter" =~ ^[A-Za-z0-9._/:-]{1,256}$ ]]; then
17102
+ fmix_error "fmix runner list: invalid --worktree name '$worktree_filter'."
17103
+ return 1
17104
+ fi
17105
+ query="?worktree=$worktree_filter"
17106
+ fi
17107
+ if [[ -n "$state_filter" ]]; then
17108
+ if [[ ! "$state_filter" =~ ^[A-Za-z0-9_-]{1,64}$ ]]; then
17109
+ fmix_error "fmix runner list: invalid --state '$state_filter'."
17110
+ return 1
17111
+ fi
17112
+ if [[ -n "$query" ]]; then
17113
+ query="$query&state=$state_filter"
17114
+ else
17115
+ query="?state=$state_filter"
17116
+ fi
17117
+ fi
17118
+ fmix_runner_resolve_auth || return 1
17119
+ local resp
17120
+ fmix_runner_request GET "/jobs$query" || return 1
17121
+ resp="$FMIX_RUNNER_HTTP_BODY"
17122
+ fmix_runner_reply_ok "list" "$resp" || return 1
17123
+ printf '%s\n' "$resp"
17124
+ }
17125
+
17126
+ fmix_runner_verify_receipt() {
17127
+ # fmix_runner_verify_receipt <receipt-json> <pubkey-file>
17128
+ # Offline Ed25519 verification of the receipt_v1 envelope: the signature
17129
+ # covers the canonical JSON (sorted keys, Go json.Marshal string escaping)
17130
+ # of every field except signature. Uses `openssl pkeyutl -rawin` when the
17131
+ # local openssl supports it, else an embedded python3 verifier. Fail-closed:
17132
+ # missing capability, unreadable key, or any mismatch is a hard failure.
17133
+ local receipt_json="$1" pubkey_path="$2"
17134
+ local py_bin tmp_dir prep_rc verify_rc=1
17135
+ py_bin="$(fmix_python_bin 2>/dev/null || printf 'python3')"
17136
+ if ! command -v "$py_bin" >/dev/null 2>&1; then
17137
+ fmix_error "fmix runner: python3 is required for receipt verification."
17138
+ return 1
17139
+ fi
17140
+ tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/fmix-receipt.XXXXXX")" || {
17141
+ fmix_error "fmix runner: could not allocate a verification directory."
17142
+ return 1
17143
+ }
17144
+ printf '%s' "$receipt_json" > "$tmp_dir/receipt.json"
17145
+ "$py_bin" - "$tmp_dir" "$pubkey_path" <<'FMIX_RECEIPT_PREPARE_PY'
17146
+ import base64, binascii, json, os, sys
17147
+
17148
+
17149
+ def fail(msg):
17150
+ sys.stderr.write(" [fmix ERROR] fmix runner receipt: " + msg + "\n")
17151
+ raise SystemExit(1)
17152
+
17153
+
17154
+ def go_string(value):
17155
+ # Mirror Go encoding/json string output: UTF-8 kept, HTML characters
17156
+ # always escaped, standard short escapes for control characters.
17157
+ out = json.dumps(value, ensure_ascii=False)
17158
+ for src, dst in (
17159
+ ("&", "\\u0026"),
17160
+ ("<", "\\u003c"),
17161
+ (">", "\\u003e"),
17162
+ ("\u2028", "\\u2028"),
17163
+ ("\u2029", "\\u2029"),
17164
+ ):
17165
+ out = out.replace(src, dst)
17166
+ return out
17167
+
17168
+
17169
+ def canonical(node):
17170
+ if isinstance(node, dict):
17171
+ parts = []
17172
+ for key in sorted(node):
17173
+ parts.append(go_string(key) + ":" + canonical(node[key]))
17174
+ return "{" + ",".join(parts) + "}"
17175
+ if isinstance(node, list):
17176
+ return "[" + ",".join(canonical(item) for item in node) + "]"
17177
+ if node is None:
17178
+ return "null"
17179
+ if isinstance(node, bool):
17180
+ return "true" if node else "false"
17181
+ if isinstance(node, (int, float)):
17182
+ return json.dumps(node)
17183
+ return go_string(node)
17184
+
17185
+
17186
+ def decode_32_key(raw):
17187
+ text = raw.strip()
17188
+ if b"-----BEGIN" in text:
17189
+ lines = [line for line in text.splitlines() if b"-----" not in line]
17190
+ try:
17191
+ der = base64.b64decode(b"".join(lines))
17192
+ except (binascii.Error, ValueError):
17193
+ fail("could not decode public key PEM")
17194
+ prefix = bytes.fromhex("302a300506032b6570032100")
17195
+ if len(der) != 44 or not der.startswith(prefix):
17196
+ fail("public key PEM is not an Ed25519 SPKI key")
17197
+ return der[12:]
17198
+ try:
17199
+ text.decode("ascii")
17200
+ except UnicodeDecodeError:
17201
+ fail("public key must be Ed25519 SPKI PEM, base64, or hex")
17202
+ candidates = []
17203
+ try:
17204
+ candidates.append(binascii.unhexlify(text))
17205
+ except (binascii.Error, ValueError):
17206
+ pass
17207
+ for decoder in (
17208
+ lambda s: base64.b64decode(s, validate=True),
17209
+ lambda s: base64.b64decode(s + b"=" * (-len(s) % 4)),
17210
+ ):
17211
+ try:
17212
+ candidates.append(decoder(text))
17213
+ except (binascii.Error, ValueError):
17214
+ pass
17215
+ for candidate in candidates:
17216
+ if len(candidate) == 32:
17217
+ return candidate
17218
+ fail("public key must decode to 32 raw Ed25519 bytes (base64 or hex) or an SPKI PEM")
17219
+
17220
+
17221
+ def decode_sig(value):
17222
+ try:
17223
+ raw = value.encode("ascii")
17224
+ except UnicodeDecodeError:
17225
+ fail("signature is not base64")
17226
+ candidates = []
17227
+ for decoder in (
17228
+ lambda s: base64.b64decode(s, validate=True),
17229
+ lambda s: base64.b64decode(s + b"=" * (-len(s) % 4)),
17230
+ ):
17231
+ try:
17232
+ candidates.append(decoder(raw))
17233
+ except (binascii.Error, ValueError):
17234
+ pass
17235
+ for candidate in candidates:
17236
+ if len(candidate) == 64:
17237
+ return candidate
17238
+ fail("signature is not 64-byte base64 Ed25519 material")
17239
+
17240
+
17241
+ out_dir = sys.argv[1]
17242
+ pubkey_path = sys.argv[2]
17243
+ try:
17244
+ with open(os.path.join(out_dir, "receipt.json"), encoding="utf-8") as handle:
17245
+ receipt = json.load(handle)
17246
+ except (OSError, ValueError):
17247
+ fail("receipt is not valid JSON")
17248
+ if not isinstance(receipt, dict):
17249
+ fail("receipt must be a JSON object")
17250
+ signature = receipt.get("signature", "")
17251
+ if not isinstance(signature, str) or not signature:
17252
+ fail("receipt is unsigned (missing signature)")
17253
+ view = dict(receipt)
17254
+ del view["signature"]
17255
+ with open(os.path.join(out_dir, "canon.bin"), "wb") as handle:
17256
+ handle.write(canonical(view).encode("utf-8"))
17257
+ with open(os.path.join(out_dir, "sig.bin"), "wb") as handle:
17258
+ handle.write(decode_sig(signature))
17259
+ try:
17260
+ with open(pubkey_path, "rb") as handle:
17261
+ pub_raw = handle.read()
17262
+ except OSError:
17263
+ fail("could not read public key " + pubkey_path)
17264
+ key = decode_32_key(pub_raw)
17265
+ with open(os.path.join(out_dir, "pub.bin"), "wb") as handle:
17266
+ handle.write(key)
17267
+ prefix = bytes.fromhex("302a300506032b6570032100")
17268
+ pem_text = (
17269
+ "-----BEGIN PUBLIC KEY-----\n"
17270
+ + base64.encodebytes(prefix + key).decode("ascii")
17271
+ + "-----END PUBLIC KEY-----\n"
17272
+ )
17273
+ with open(os.path.join(out_dir, "pub.pem"), "w", encoding="ascii") as handle:
17274
+ handle.write(pem_text)
17275
+ FMIX_RECEIPT_PREPARE_PY
17276
+ prep_rc=$?
17277
+ if (( prep_rc != 0 )); then
17278
+ rm -rf "$tmp_dir"
17279
+ return 1
17280
+ fi
17281
+ if command -v openssl >/dev/null 2>&1 && openssl pkeyutl -help 2>&1 | grep -q -- '-rawin'; then
17282
+ if openssl pkeyutl -verify -pubin -inkey "$tmp_dir/pub.pem" -rawin -in "$tmp_dir/canon.bin" -sigfile "$tmp_dir/sig.bin" >/dev/null 2>&1; then
17283
+ verify_rc=0
17284
+ fi
17285
+ else
17286
+ "$py_bin" - "$tmp_dir" <<'FMIX_RECEIPT_ED25519_PY'
17287
+ # Pure-python Ed25519 verify (RFC 8032), used only when the local openssl
17288
+ # cannot do `pkeyutl -rawin`. Reads canon.bin / sig.bin / pub.bin from argv[1].
17289
+ import hashlib, os, sys
17290
+
17291
+ p = 2 ** 255 - 19
17292
+ d = (-121665 * pow(121666, p - 2, p)) % p
17293
+ q = 2 ** 252 + 27742317777372353535851937790883648493
17294
+
17295
+
17296
+ def inv(x):
17297
+ return pow(x, p - 2, p)
17298
+
17299
+
17300
+ def xrecover(y):
17301
+ xx = (y * y - 1) * inv(d * y * y + 1)
17302
+ x = pow(xx, (p + 3) // 8, p)
17303
+ if (x * x - xx) % p != 0:
17304
+ x = (x * pow(2, (p - 1) // 4, p)) % p
17305
+ if x % 2 != 0:
17306
+ x = p - x
17307
+ return x
17308
+
17309
+
17310
+ By = 4 * inv(5)
17311
+ Bx = xrecover(By)
17312
+ B = (Bx % p, By % p, 1, (Bx * By) % p)
17313
+
17314
+
17315
+ def edwards_add(P, Q):
17316
+ x1, y1, z1, t1 = P
17317
+ x2, y2, z2, t2 = Q
17318
+ a = ((y1 - x1) * (y2 - x2)) % p
17319
+ b = ((y1 + x1) * (y2 + x2)) % p
17320
+ c = (2 * t1 * t2 * d) % p
17321
+ dd = (2 * z1 * z2) % p
17322
+ e = b - a
17323
+ f = dd - c
17324
+ g = dd + c
17325
+ h = b + a
17326
+ return ((e * f) % p, (g * h) % p, (f * g) % p, (e * h) % p)
17327
+
17328
+
17329
+ def scalarmult(P, e):
17330
+ Q = (0, 1, 1, 0)
17331
+ while e > 0:
17332
+ if e & 1:
17333
+ Q = edwards_add(Q, P)
17334
+ P = edwards_add(P, P)
17335
+ e >>= 1
17336
+ return Q
17337
+
17338
+
17339
+ def encodepoint(P):
17340
+ x, y, z, t = P
17341
+ zi = inv(z)
17342
+ x = x * zi % p
17343
+ y = y * zi % p
17344
+ bits = [(y >> i) & 1 for i in range(255)] + [x & 1]
17345
+ return bytes(sum(bits[i * 8 + j] << j for j in range(8)) for i in range(32))
17346
+
17347
+
17348
+ def decodeint(s):
17349
+ return int.from_bytes(s, "little")
17350
+
17351
+
17352
+ def decodepoint(s):
17353
+ y = decodeint(s)
17354
+ sign = (y >> 255) & 1
17355
+ y &= (1 << 255) - 1
17356
+ if y >= p:
17357
+ raise ValueError("non-canonical point encoding")
17358
+ x = xrecover(y)
17359
+ if x & 1 != sign:
17360
+ x = p - x
17361
+ return (x, y, 1, (x * y) % p)
17362
+
17363
+
17364
+ out_dir = sys.argv[1]
17365
+ pub = open(os.path.join(out_dir, "pub.bin"), "rb").read()
17366
+ sig = open(os.path.join(out_dir, "sig.bin"), "rb").read()
17367
+ msg = open(os.path.join(out_dir, "canon.bin"), "rb").read()
17368
+ if len(pub) != 32 or len(sig) != 64:
17369
+ sys.exit(1)
17370
+ try:
17371
+ A = decodepoint(pub)
17372
+ R = decodepoint(sig[:32])
17373
+ except Exception:
17374
+ sys.exit(1)
17375
+ S = decodeint(sig[32:])
17376
+ if S >= q:
17377
+ sys.exit(1)
17378
+ h = decodeint(hashlib.sha512(sig[:32] + pub + msg).digest()) % q
17379
+ left = encodepoint(scalarmult(B, S))
17380
+ right = encodepoint(edwards_add(R, scalarmult(A, h)))
17381
+ sys.exit(0 if left == right else 1)
17382
+ FMIX_RECEIPT_ED25519_PY
17383
+ verify_rc=$?
17384
+ fi
17385
+ rm -rf "$tmp_dir"
17386
+ return "$verify_rc"
17387
+ }
17388
+
17389
+ cmd_runner_receipt() {
17390
+ local job_id="" verify=0 pubkey="${FMIX_RUNNER_PUBKEY:-}" verify_rc=0
17391
+ while (( $# > 0 )); do
17392
+ case "$1" in
17393
+ --verify) verify=1; shift ;;
17394
+ --pubkey) [[ $# -ge 2 ]] || { fmix_error "--pubkey requires a path argument."; return 2; }; pubkey="$2"; shift 2 ;;
17395
+ --pubkey=*) pubkey="${1#--pubkey=}"; shift ;;
17396
+ -*) fmix_error "Unknown option: $1. Usage: fmix runner receipt <job-id> [--verify [--pubkey <path>]]"; return 1 ;;
17397
+ *) if [[ -z "$job_id" ]]; then job_id="$1"; shift; else fmix_error "Unexpected argument: $1. Usage: fmix runner receipt <job-id> [--verify [--pubkey <path>]]"; return 1; fi ;;
17398
+ esac
17399
+ done
17400
+ job_id="$(fmix_runner_require_job_id "$job_id")" || return 1
17401
+ fmix_runner_resolve_auth || return 1
17402
+ local resp
17403
+ fmix_runner_request GET "/jobs/$job_id/receipt" || return 1
17404
+ resp="$FMIX_RUNNER_HTTP_BODY"
17405
+ fmix_runner_reply_ok "receipt $job_id" "$resp" || return 1
17406
+ if (( verify == 1 )); then
17407
+ if [[ -z "$pubkey" ]]; then
17408
+ fmix_error "fmix runner: receipt --verify needs an Ed25519 public key (--pubkey <path> or FMIX_RUNNER_PUBKEY)."
17409
+ return 1
17410
+ fi
17411
+ if [[ ! -f "$pubkey" ]]; then
17412
+ fmix_error "fmix runner: receipt public key '$pubkey' not found."
17413
+ return 1
17414
+ fi
17415
+ if ! fmix_runner_verify_receipt "$resp" "$pubkey"; then
17416
+ fmix_error "fmix runner: receipt $job_id signature verification FAILED."
17417
+ verify_rc=1
17418
+ else
17419
+ fmix_info "Receipt $job_id signature verified (ed25519)."
17420
+ fi
17421
+ fi
17422
+ printf '%s\n' "$resp"
17423
+ return "$verify_rc"
17424
+ }
17425
+
17426
+ cmd_runner_gc_worktree() {
17427
+ if [[ $# -gt 1 ]]; then
17428
+ fmix_error "Usage: fmix runner gc-worktree <worktree>"
17429
+ return 1
17430
+ fi
17431
+ local worktree_name="${1:-}"
17432
+ if [[ -z "$worktree_name" ]]; then
17433
+ fmix_error "Usage: fmix runner gc-worktree <worktree>"
17434
+ return 1
17435
+ fi
17436
+ if [[ ! "$worktree_name" =~ ^[A-Za-z0-9._/:-]{1,256}$ ]]; then
17437
+ fmix_error "fmix runner gc-worktree: invalid worktree name '$worktree_name' (want [A-Za-z0-9._/:-]{1,256})."
17438
+ return 1
17439
+ fi
17440
+ local body
17441
+ body="{\"worktree\": $(fmix_json_escape "$worktree_name")}"
17442
+ fmix_runner_resolve_auth || return 1
17443
+ local resp
17444
+ fmix_runner_request POST "/worktrees/gc" "$body" || return 1
17445
+ resp="$FMIX_RUNNER_HTTP_BODY"
17446
+ fmix_runner_reply_ok "gc-worktree $worktree_name" "$resp" || return 1
17447
+ printf '%s\n' "$resp"
17448
+ }
17449
+
17450
+ fmix_runner_write_pre_push_hook() {
17451
+ # Minimal fmix runner pre-push hook body (used when runner/hooks/ is not
17452
+ # vendored next to this script). Same hard contract as runner/hooks/pre-push:
17453
+ # NEVER blocks or fails a push; every path exits 0.
17454
+ cat <<'FMIX_HOOK_EOF'
17455
+ #!/usr/bin/env bash
17456
+ # managed-by: fmix runner/hooks
17457
+ # Minimal fmix runner pre-push hook (installed by `fmix runner install-hooks`).
17458
+ # Fires the runner's ahead-of-webhook trigger lane BEFORE refs are remote
17459
+ # visible. HARD CONTRACT: never blocks or fails a push; every path exits 0.
17460
+ #
17461
+ # Config (env first, then git config):
17462
+ # FMIX_RUNNER_HOOK_URL portal hook endpoint; defaults to
17463
+ # ${FMIX_RUNNER_URL%/}/hooks/git when FMIX_RUNNER_URL is set
17464
+ # FMIX_RUNNER_TOKEN bearer token (fmix.runnerToken)
17465
+ # FMIX_RUNNER_LANE lane params (fmix.lane; default "mix test --seed 0")
17466
+ # FMIX_RUNNER_SECRET optional HMAC secret (fmix.runnerSecret)
17467
+
17468
+ HOOK_URL="${FMIX_RUNNER_HOOK_URL:-}"
17469
+ TOKEN="${FMIX_RUNNER_TOKEN:-}"
17470
+ LANE="${FMIX_RUNNER_LANE:-}"
17471
+ SECRET="${FMIX_RUNNER_SECRET:-}"
17472
+ [ -n "$TOKEN" ] || TOKEN="$(git config --get fmix.runnerToken 2>/dev/null || true)"
17473
+ [ -n "$LANE" ] || LANE="$(git config --get fmix.lane 2>/dev/null || true)"
17474
+ LANE="${LANE:-mix test --seed 0}"
17475
+ [ -n "$SECRET" ] || SECRET="$(git config --get fmix.runnerSecret 2>/dev/null || true)"
17476
+ if [ -z "$HOOK_URL" ] && [ -n "${FMIX_RUNNER_URL:-}" ]; then
17477
+ HOOK_URL="${FMIX_RUNNER_URL%/}/hooks/git"
17478
+ fi
17479
+ [ -n "$HOOK_URL" ] || exit 0
17480
+
17481
+ ORIGIN_URL="$(git remote get-url origin 2>/dev/null || true)"
17482
+ [ -n "$ORIGIN_URL" ] || exit 0
17483
+ REPO="$(printf '%s' "$ORIGIN_URL" | sed -E \
17484
+ -e 's#^.*github\.com[:/]##' \
17485
+ -e 's#\.git$##' \
17486
+ -e 's#/$##')"
17487
+ ZERO_SHA="0000000000000000000000000000000000000000"
17488
+
17489
+ fire() {
17490
+ head_sha="$1"
17491
+ remote_ref="$2"
17492
+ nonce="$$-$(date +%s)-${RANDOM}"
17493
+ ts="$(date +%s)"
17494
+ lane_esc="$(printf '%s' "$LANE" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g')"
17495
+ body="{\"repo\":\"$REPO\",\"head_sha\":\"$head_sha\",\"remote_ref\":\"$remote_ref\",\"awaiting_ref\":true,\"lane\":\"$lane_esc\"}"
17496
+ curl_args=(-sS --connect-timeout 2 --max-time 3 -H "Content-Type: application/json")
17497
+ if [ -n "$TOKEN" ]; then
17498
+ curl_args+=(-H "Authorization: Bearer ${TOKEN}")
17499
+ fi
17500
+ if [ -n "$SECRET" ] && command -v openssl >/dev/null 2>&1; then
17501
+ sig="$(printf 'v1:%s:%s:%s' "$ts" "$nonce" "$body" \
17502
+ | openssl dgst -sha256 -hmac "$SECRET" 2>/dev/null | awk '{print $NF}')"
17503
+ if [ -n "$sig" ]; then
17504
+ curl_args+=(-H "X-Fmix-Runner-Timestamp: ${ts}")
17505
+ curl_args+=(-H "X-Fmix-Runner-Nonce: ${nonce}")
17506
+ curl_args+=(-H "X-Fmix-Runner-Signature: sha256=${sig}")
17507
+ fi
17508
+ fi
17509
+ ( curl "${curl_args[@]}" -d "$body" "$HOOK_URL" >/dev/null 2>&1 ) &
17510
+ }
17511
+
17512
+ seen_refs=""
17513
+ while read -r local_ref local_sha remote_ref; do
17514
+ [ -z "$local_ref" ] && continue
17515
+ [ "$local_sha" = "$ZERO_SHA" ] && continue
17516
+ case "$seen_refs" in
17517
+ *"|$remote_ref|"*) continue ;;
17518
+ esac
17519
+ seen_refs="$seen_refs|$remote_ref|"
17520
+ fire "$local_sha" "$remote_ref"
17521
+ done
17522
+ exit 0
17523
+ FMIX_HOOK_EOF
17524
+ }
17525
+
17526
+ cmd_runner_install_hooks() {
17527
+ local worktree_arg="auto" legacy=0 force=0
17528
+ while (( $# > 0 )); do
17529
+ case "$1" in
17530
+ --worktree) [[ $# -ge 2 ]] || { fmix_error "--worktree requires a path argument."; return 2; }; worktree_arg="$2"; shift 2 ;;
17531
+ --worktree=*) worktree_arg="${1#--worktree=}"; shift ;;
17532
+ --legacy) legacy=1; shift ;;
17533
+ --force) force=1; shift ;;
17534
+ *) fmix_error "Unknown option: $1. Usage: fmix runner install-hooks [--worktree <path>] [--legacy] [--force]"; return 1 ;;
17535
+ esac
17536
+ done
17537
+ local worktree
17538
+ if [[ "$worktree_arg" != "auto" ]]; then
17539
+ worktree="$(fmix_find_worktree "$worktree_arg" readonly 2>/dev/null || fmix_realpath "$worktree_arg")"
17540
+ else
17541
+ worktree="$(fmix_find_worktree auto readonly 2>/dev/null || git rev-parse --show-toplevel 2>/dev/null || pwd -P)"
17542
+ fi
17543
+ local real_worktree
17544
+ real_worktree="$(fmix_realpath "$worktree")"
17545
+ # A repo checkout carries runner/hooks/install-hooks.sh next to this
17546
+ # script; delegate to it so dev installs match the shipped hooks exactly.
17547
+ local self_dir installer=""
17548
+ self_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
17549
+ if [[ -f "$self_dir/runner/hooks/install-hooks.sh" ]]; then
17550
+ installer="$self_dir/runner/hooks/install-hooks.sh"
17551
+ fi
17552
+ local -a inst_args=()
17553
+ if (( legacy == 1 )); then
17554
+ inst_args+=(--legacy)
17555
+ fi
17556
+ if (( force == 1 )); then
17557
+ inst_args+=(--force)
17558
+ fi
17559
+ if [[ -n "$installer" ]]; then
17560
+ fmix_info "fmix runner install-hooks: delegating to $installer"
17561
+ ( cd "$real_worktree" && bash "$installer" ${inst_args[@]+"${inst_args[@]}"} )
17562
+ return $?
17563
+ fi
17564
+
17565
+ # Minimal inline install (idempotent): pre-push into .githooks/ +
17566
+ # core.hooksPath, or straight into .git/hooks with --legacy. A foreign
17567
+ # (unmarked) hook is never clobbered without --force.
17568
+ local repo_root git_dir
17569
+ repo_root="$(git -C "$real_worktree" rev-parse --show-toplevel 2>/dev/null || true)"
17570
+ git_dir="$(fmix_git_dir "$real_worktree" 2>/dev/null || true)"
17571
+ if [[ -z "$repo_root" || -z "$git_dir" ]]; then
17572
+ fmix_warn "fmix runner install-hooks: not inside a git repository — nothing installed"
17573
+ return 0
17574
+ fi
17575
+ local target_dir mode="path"
17576
+ if (( legacy == 1 )); then
17577
+ target_dir="$git_dir/hooks"
17578
+ mode="legacy"
17579
+ else
17580
+ target_dir="$repo_root/.githooks"
17581
+ fi
17582
+ mkdir -p "$target_dir" || return 1
17583
+ local src_tmp dst installed=0 unchanged=0 refused=0
17584
+ src_tmp="$(mktemp "${TMPDIR:-/tmp}/fmix-pre-push.XXXXXX")" || return 1
17585
+ fmix_runner_write_pre_push_hook > "$src_tmp"
17586
+ dst="$target_dir/pre-push"
17587
+ if [[ -f "$dst" ]]; then
17588
+ if cmp -s "$src_tmp" "$dst"; then
17589
+ unchanged=1
17590
+ elif ! grep -q "$FMIX_RUNNER_HOOK_MARKER" "$dst" 2>/dev/null && (( force == 0 )); then
17591
+ fmix_warn "fmix runner install-hooks: REFUSING to overwrite foreign hook $dst (use --force)"
17592
+ refused=1
17593
+ elif cp "$src_tmp" "$dst" && chmod 755 "$dst"; then
17594
+ installed=1
17595
+ else
17596
+ fmix_warn "fmix runner install-hooks: could not install $dst"
17597
+ fi
17598
+ elif cp "$src_tmp" "$dst" && chmod 755 "$dst"; then
17599
+ installed=1
17600
+ else
17601
+ fmix_warn "fmix runner install-hooks: could not install $dst"
17602
+ fi
17603
+ rm -f "$src_tmp"
17604
+ if (( legacy == 0 )); then
17605
+ local current
17606
+ current="$(git -C "$real_worktree" config --get core.hooksPath 2>/dev/null || true)"
17607
+ if [[ "$current" != ".githooks" ]]; then
17608
+ if git -C "$real_worktree" config core.hooksPath .githooks; then
17609
+ fmix_info "fmix runner install-hooks: core.hooksPath -> .githooks"
17610
+ fi
17611
+ fi
17612
+ fi
17613
+ fmix_info "fmix runner install-hooks: complete (installed=$installed unchanged=$unchanged refused=$refused mode=$mode)"
17614
+ return 0
17615
+ }
17616
+
17617
+ cmd_runner() {
17618
+ local subcmd="${1:-}"
17619
+ shift || true
17620
+ case "$subcmd" in
17621
+ submit) cmd_runner_submit "$@" ;;
17622
+ status) cmd_runner_status "$@" ;;
17623
+ logs) cmd_runner_logs "$@" ;;
17624
+ cancel) cmd_runner_cancel "$@" ;;
17625
+ list) cmd_runner_list "$@" ;;
17626
+ receipt) cmd_runner_receipt "$@" ;;
17627
+ install-hooks) cmd_runner_install_hooks "$@" ;;
17628
+ gc-worktree) cmd_runner_gc_worktree "$@" ;;
17629
+ ""|help|--help|-h)
17630
+ fmix_verb_help runner
17631
+ ;;
17632
+ *)
17633
+ fmix_error "Unknown runner subcommand: '${subcmd:-empty}'."
17634
+ fmix_error "Valid runner subcommands: submit, status, logs, cancel, list, receipt, install-hooks, gc-worktree"
17635
+ fmix_error "Run 'fmix help runner' for focused usage."
17636
+ return 1
17637
+ ;;
17638
+ esac
17639
+ }
17640
+
17641
+ # ---------------------------------------------------------------------------
17642
+ # cmd: fmix task
17643
+ # ---------------------------------------------------------------------------
17644
+
17645
+ cmd_task() {
17646
+ # Run a non-test Mix task against the same exact pinned runtime and
17647
+ # session-local incremental deps/_build state as fmix setup/test. This is
17648
+ # the supported path for generators and developer tasks that may introduce
17649
+ # new dependencies; it never uses Docker, Depot, GHCR, or a prebuilt deps
17650
+ # image.
17651
+ local worktree_arg="auto"
17652
+ local session_arg=""
17653
+ local database_arg=""
17654
+ local mix_env_arg="test"
17655
+ local allow_run=0
17656
+ local found_sep=0
17657
+ local -a mix_args=()
17658
+ while (( $# > 0 )); do
17659
+ case "$1" in
17660
+ --worktree)
17661
+ [[ $# -ge 2 ]] || { fmix_error "--worktree requires a path argument."; return 2; }
17662
+ worktree_arg="$2"
17663
+ shift 2
17664
+ ;;
17665
+ --worktree=*) worktree_arg="${1#--worktree=}"; shift ;;
17666
+ --session)
17667
+ [[ $# -ge 2 ]] || { fmix_error "--session requires an identifier."; return 2; }
17668
+ session_arg="$2"
17669
+ shift 2
17670
+ ;;
17671
+ --session=*) session_arg="${1#--session=}"; shift ;;
17672
+ --database)
17673
+ [[ $# -ge 2 ]] || { fmix_error "--database requires a database name."; return 2; }
17674
+ database_arg="$2"
17675
+ shift 2
17676
+ ;;
17677
+ --database=*) database_arg="${1#--database=}"; shift ;;
17678
+ --mix-env)
17679
+ [[ $# -ge 2 ]] || { fmix_error "--mix-env requires an environment name."; return 2; }
17680
+ mix_env_arg="$2"
17681
+ shift 2
17682
+ ;;
17683
+ --mix-env=*) mix_env_arg="${1#--mix-env=}"; shift ;;
17684
+ --allow-run) allow_run=1; shift ;;
17685
+ --) found_sep=1; shift; break ;;
17686
+ *)
17687
+ fmix_error "Unknown option: $1. Usage: fmix task [--worktree <path>] [--database <name>] [--mix-env <env>] [--allow-run] -- <mix task> [args]"
17688
+ return 2
17689
+ ;;
17690
+ esac
17691
+ done
17692
+ (( found_sep == 1 )) || {
17693
+ fmix_error "'fmix task' requires -- before the Mix task."
17694
+ return 2
17695
+ }
17696
+ mix_args=("$@")
17697
+ (( ${#mix_args[@]} > 0 )) || {
17698
+ fmix_error "'fmix task' requires a Mix task after --."
17699
+ return 2
17700
+ }
17701
+ case "${mix_args[0]}" in
17702
+ test|test.*)
17703
+ fmix_error "Use 'fmix test' for ExUnit tasks so database and test-lane isolation remain enforced."
17704
+ return 2
17705
+ ;;
17706
+ do|cmd)
17707
+ fmix_error "'fmix task' runs one repository Mix task; nested execution via '${mix_args[0]}' is not allowed."
17708
+ fmix_error "Use 'fmix test' for ExUnit, or invoke the intended non-test task directly."
17709
+ return 2
17710
+ ;;
17711
+ run)
17712
+ if (( allow_run == 0 )); then
17713
+ fmix_error "'mix run' requires explicit --allow-run because it executes repository code outside a named Mix task."
17714
+ return 2
17715
+ fi
16503
17716
  ;;
16504
17717
  esac
16505
17718
 
@@ -17030,7 +18243,7 @@ fmix_ensure_infra() {
17030
18243
  # Coalesce concurrent callers after an engine reset. The native lease is
17031
18244
  # held through readiness and admission; never force another owner's lock.
17032
18245
  local lock_name="infra-ensure" startup_rc=0
17033
- fmix_lock_acquire "$lock_name" "$FMIX_ENSURE_TIMEOUT" "shared infrastructure startup" || return 1
18246
+ fmix_lock_acquire "$lock_name" "$FMIX_ENSURE_TIMEOUT" "shared infrastructure startup" || return $?
17034
18247
  fmix_ensure_infra_locked || startup_rc=$?
17035
18248
  if ! fmix_lock_release "$lock_name"; then
17036
18249
  fmix_error "Infrastructure startup lease release failed."
@@ -20590,6 +21803,48 @@ cmd_self_test() {
20590
21803
  && st_pass "fmix_hash_stdin: sha256 of 'hello' → ${h:0:16}…" \
20591
21804
  || st_fail "fmix_hash_stdin failed or wrong length: '${h:-empty}'"
20592
21805
 
21806
+ # Native dep NIF verification: the toolchain heal purges .so files and Mix
21807
+ # will not rebuild deps it thinks are compiled, so a missing priv library
21808
+ # must be detected and rebuilt via a forced mix deps.compile.
21809
+ local nif_wt nif_stub nif_missing nif_old_path
21810
+ nif_wt="$(mktemp -d)"
21811
+ nif_wt="$(fmix_realpath "$nif_wt")"
21812
+ nif_stub="$(mktemp -d)"
21813
+ mkdir -p "$nif_wt/deps/sippet/c_src" "$nif_wt/deps/sippet/priv" \
21814
+ "$nif_wt/deps/pure_elixir" "$nif_wt/deps/has_so/c_src" "$nif_wt/deps/has_so/priv"
21815
+ printf 'compilers: [:elixir_make]\n' >"$nif_wt/deps/sippet/mix.exs"
21816
+ : >"$nif_wt/deps/sippet/Makefile"
21817
+ printf 'compilers: [:elixir_make]\n' >"$nif_wt/deps/has_so/mix.exs"
21818
+ : >"$nif_wt/deps/has_so/Makefile"
21819
+ : >"$nif_wt/deps/has_so/priv/has_so.so"
21820
+ nif_missing="$(fmix_native_deps_missing_so "$nif_wt/deps")"
21821
+ if [[ "$nif_missing" == "sippet" ]]; then
21822
+ # Fake `mix` that "rebuilds" the NIF for the requested deps.
21823
+ cat >"$nif_stub/mix" <<'NIFSTUB'
21824
+ #!/bin/sh
21825
+ [ "$1" = "deps.compile" ] || exit 1
21826
+ shift
21827
+ for dep in "$@"; do
21828
+ case "$dep" in --*) continue ;; esac
21829
+ : >"$MIX_DEPS_PATH/$dep/priv/$dep.so"
21830
+ done
21831
+ NIFSTUB
21832
+ chmod +x "$nif_stub/mix"
21833
+ nif_old_path="$PATH"
21834
+ PATH="$nif_stub:$PATH"
21835
+ MIX_DEPS_PATH="$nif_wt/deps" fmix_repair_missing_native_deps "$nif_wt" >/dev/null 2>&1
21836
+ PATH="$nif_old_path"
21837
+ if [[ -f "$nif_wt/deps/sippet/priv/sippet.so" \
21838
+ && -z "$(fmix_native_deps_missing_so "$nif_wt/deps")" ]]; then
21839
+ st_pass "native dep verify: purged sippet NIF detected and rebuilt via mix deps.compile"
21840
+ else
21841
+ st_fail "native dep verify: sippet NIF was not rebuilt"
21842
+ fi
21843
+ else
21844
+ st_fail "native dep verify: expected only 'sippet' missing, got '$nif_missing'"
21845
+ fi
21846
+ rm -rf "$nif_wt" "$nif_stub"
21847
+
20593
21848
  # Worktree discovery is consumed through command substitution. Any
20594
21849
  # initialization diagnostics must stay on stderr so they cannot become
20595
21850
  # part of the resolved path.
@@ -21178,6 +22433,18 @@ cmd_self_test() {
21178
22433
  else
21179
22434
  st_fail "template publication retained or rejected the exact app priv link"
21180
22435
  fi
22436
+ cas_relink="$FMIX_HOME/sessions/relink-self-test-$$"
22437
+ mkdir -p "$cas_relink/_build/test/lib/cdrcisco/priv"
22438
+ printf 'publisher priv\n' >"$cas_relink/_build/test/lib/cdrcisco/priv/stale.txt"
22439
+ if fmix_session_relink_app_priv "$cas_relink/_build" \
22440
+ && [[ -L "$cas_relink/_build/test/lib/cdrcisco/priv" ]] \
22441
+ && [[ "$(readlink "$cas_relink/_build/test/lib/cdrcisco/priv")" == "../../../../priv" ]] \
22442
+ && fmix_session_relink_app_priv "$cas_relink/_build"; then
22443
+ st_pass "installed sessions relink the materialized app priv to the checkout"
22444
+ else
22445
+ st_fail "installed session kept a materialized app priv copy"
22446
+ fi
22447
+ rm -rf "$cas_relink"
21181
22448
  rm -rf "$cas_source"
21182
22449
  FMIX_HOME="$cas_saved_home"
21183
22450
  chmod -R u+w "$cas_home" 2>/dev/null || true
@@ -24903,6 +26170,237 @@ cmd_install() {
24903
26170
  return 0
24904
26171
  }
24905
26172
 
26173
+ # ---------------------------------------------------------------------------
26174
+ # Automatic upgrade-on-invocation (fail-open; never touches the command)
26175
+ #
26176
+ # Every eligible fmix invocation makes one cheap, read-only TTL check before
26177
+ # command dispatch; when an attempt is due it runs detached and finishes after
26178
+ # the command returns. The attempt probes the published fmix-vX.Y.Z release on
26179
+ # calltelemetry/fmix for a newer version and, when found, verifies and installs
26180
+ # it through the existing content-addressed runtime path (fmix_install_snapshot).
26181
+ # The new runtime is picked up by the NEXT invocation: the running process
26182
+ # always finishes on its own snapshot and nothing is ever exec'd mid-run.
26183
+ #
26184
+ # Fail-open contract: every failure mode — no network, no curl, rate limiting,
26185
+ # partial download, digest mismatch, parse error, install refusal — ends the
26186
+ # attempt silently with success status. An upgrade attempt can never change
26187
+ # the invoking command's exit code, output contract, or artifacts.
26188
+ #
26189
+ # Skip conditions (documented in fmix_usage and docs/fmix.md):
26190
+ # - FMIX_NO_AUTO_UPGRADE=1 (explicit opt-out)
26191
+ # - CI / GITHUB_ACTIONS (pinned environments must not mutate mid-job)
26192
+ # - observability worker re-entry (FMIX_OBSERVABILITY_WORKER=1)
26193
+ # - self-test, doctor, install, cache (measurement, diagnosis, explicit
26194
+ # install, and inspection verbs describe the running snapshot exactly)
26195
+ # - help/version identity probes and every other read-only entrypoint
26196
+ # (fmix_readonly_entrypoint: includes gc --artifacts-only)
26197
+ # - anything that is not an installed runtime: a source checkout (./fmix)
26198
+ # or a sourced test copy is an intentional development context and never
26199
+ # self-upgrades
26200
+ # TTY state is deliberately NOT a skip condition: fmix's primary invokers are
26201
+ # headless agents and the attempt is fully detached and silent; the unsafe
26202
+ # non-interactive environments are CI, which is skipped above.
26203
+ # ---------------------------------------------------------------------------
26204
+
26205
+ fmix_auto_upgrade_stamp_file() {
26206
+ printf '%s/auto-upgrade.stamp\n' "${FMIX_HOME:-${HOME:-}/.ct-fmix}"
26207
+ }
26208
+
26209
+ fmix_auto_upgrade_ttl_seconds() {
26210
+ # Silent fallback (no fmix_warn): the auto-upgrade path must never add
26211
+ # output to the invoking command.
26212
+ local ttl="${FMIX_AUTO_UPGRADE_TTL_S:-3600}"
26213
+ [[ "$ttl" =~ ^[0-9]+$ ]] || ttl=3600
26214
+ printf '%s\n' "$ttl"
26215
+ }
26216
+
26217
+ fmix_auto_upgrade_stamp_due() {
26218
+ # Pure read: the attempt is due unless a stamp records one within the TTL.
26219
+ local stamp epoch now ttl age
26220
+ stamp="$(fmix_auto_upgrade_stamp_file)" || return 0
26221
+ [[ -f "$stamp" ]] || return 0
26222
+ IFS= read -r epoch < "$stamp" || return 0
26223
+ [[ "$epoch" =~ ^[0-9]+$ ]] || return 0
26224
+ now="$(fmix_epoch)"
26225
+ [[ "$now" =~ ^[0-9]+$ ]] || return 0
26226
+ ttl="$(fmix_auto_upgrade_ttl_seconds)"
26227
+ age=$(( now - epoch ))
26228
+ (( age >= 0 && age < ttl )) && return 1
26229
+ return 0
26230
+ }
26231
+
26232
+ fmix_auto_upgrade_installed_runtime() {
26233
+ # Auto-upgrade keeps an *installed* runtime current. A source checkout or
26234
+ # a sourced test copy is a development context: it must never spawn an
26235
+ # upgrade that could repoint the stable launcher underneath its operator.
26236
+ local self home runtime_dir install_dir
26237
+ self="$(fmix_realpath "${BASH_SOURCE[0]}" 2>/dev/null || printf '%s' "${BASH_SOURCE[0]}")"
26238
+ home="${FMIX_HOME:-${HOME:-}/.ct-fmix}"
26239
+ home="$(fmix_realpath "$home" 2>/dev/null || printf '%s' "$home")"
26240
+ runtime_dir="$home/runtime"
26241
+ case "$self" in
26242
+ "$runtime_dir"/fmix-*) return 0 ;;
26243
+ esac
26244
+ install_dir="${FMIX_INSTALL_DIR:-${HOME:-}/.local/bin}"
26245
+ [[ "$self" == "$(fmix_realpath "$install_dir/fmix" 2>/dev/null || printf '')" ]] && return 0
26246
+ return 1
26247
+ }
26248
+
26249
+ fmix_auto_upgrade_eligible() {
26250
+ local cmd="$1"
26251
+ shift
26252
+ [[ "${FMIX_NO_AUTO_UPGRADE:-0}" == "1" ]] && return 1
26253
+ [[ -n "${CI:-}" || -n "${GITHUB_ACTIONS:-}" ]] && return 1
26254
+ [[ "${FMIX_OBSERVABILITY_WORKER:-0}" == "1" ]] && return 1
26255
+ case "$cmd" in
26256
+ self-test|doctor|install|cache) return 1 ;;
26257
+ esac
26258
+ fmix_readonly_entrypoint "$cmd" "$@" && return 1
26259
+ fmix_auto_upgrade_installed_runtime || return 1
26260
+ return 0
26261
+ }
26262
+
26263
+ fmix_auto_upgrade_version_newer() {
26264
+ # Strict X.Y.Z comparison: succeeds only when $1 is newer than $2.
26265
+ local newer="$1" older="$2"
26266
+ [[ "$newer" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || return 1
26267
+ [[ "$older" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || return 1
26268
+ local n_major n_minor n_patch o_major o_minor o_patch
26269
+ IFS=. read -r n_major n_minor n_patch <<<"$newer"
26270
+ IFS=. read -r o_major o_minor o_patch <<<"$older"
26271
+ if (( 10#$n_major != 10#$o_major )); then
26272
+ (( 10#$n_major > 10#$o_major )) && return 0
26273
+ return 1
26274
+ fi
26275
+ if (( 10#$n_minor != 10#$o_minor )); then
26276
+ (( 10#$n_minor > 10#$o_minor )) && return 0
26277
+ return 1
26278
+ fi
26279
+ (( 10#$n_patch > 10#$o_patch )) && return 0
26280
+ return 1
26281
+ }
26282
+
26283
+ fmix_auto_upgrade_parse_latest_tag() {
26284
+ # Extracts X.Y.Z from a GitHub Releases API "tag_name":"fmix-vX.Y.Z" field.
26285
+ # sed on purpose — no JSON tool dependency — and a malformed or ambiguous
26286
+ # payload simply yields no version, which fails the attempt open.
26287
+ local json="$1" tag count
26288
+ count="$(printf '%s' "$json" | grep -o '"tag_name"' | wc -l | tr -d ' ')"
26289
+ [[ "$count" == "1" ]] || return 1
26290
+ tag="$(printf '%s' "$json" \
26291
+ | sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"fmix-v\([0-9]\{1,\}\.[0-9]\{1,\}\.[0-9]\{1,\}\)".*/\1/p')"
26292
+ [[ "$tag" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || return 1
26293
+ printf '%s\n' "$tag"
26294
+ }
26295
+
26296
+ fmix_auto_upgrade_latest_version() {
26297
+ # Version source: the published fmix-vX.Y.Z release identity on
26298
+ # calltelemetry/fmix (release.yml publishes tag + GitHub release). Bounded
26299
+ # timeouts so a dead network retires the detached attempt, not the host.
26300
+ local json
26301
+ command -v curl >/dev/null 2>&1 || return 1
26302
+ json="$(curl -fsSL --connect-timeout 5 --max-time 30 \
26303
+ -H 'Accept: application/vnd.github+json' \
26304
+ 'https://api.github.com/repos/calltelemetry/fmix/releases/latest' 2>/dev/null)" || return 1
26305
+ fmix_auto_upgrade_parse_latest_tag "$json"
26306
+ }
26307
+
26308
+ fmix_auto_upgrade_fetch_release() {
26309
+ # Downloads the fmix-v<V> release assets and verifies the full chain before
26310
+ # anything can be installed: tarball digest against the published .sha256,
26311
+ # runner digest against fmix.runnerSha256 in the published package
26312
+ # manifest, and the runner's own FMIX_VERSION line against the tag.
26313
+ local version="$1" out="$2"
26314
+ [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || return 1
26315
+ [[ -n "$out" && -d "$out" ]] || return 1
26316
+ command -v curl >/dev/null 2>&1 || return 1
26317
+ command -v tar >/dev/null 2>&1 || return 1
26318
+ local base="https://github.com/calltelemetry/fmix/releases/download/fmix-v${version}"
26319
+ curl -fsSL --connect-timeout 5 --max-time 60 \
26320
+ -o "$out/fmix.tar.gz.sha256" "$base/fmix-${version}.tar.gz.sha256" || return 1
26321
+ curl -fsSL --connect-timeout 5 --max-time 300 \
26322
+ -o "$out/fmix.tar.gz" "$base/fmix-${version}.tar.gz" || return 1
26323
+ curl -fsSL --connect-timeout 5 --max-time 60 \
26324
+ -o "$out/package.json" "$base/fmix-${version}.package.json" || return 1
26325
+ local want_tar have_tar manifest_sha have_runner declared
26326
+ want_tar="$(awk 'NR == 1 {print $1}' "$out/fmix.tar.gz.sha256")"
26327
+ [[ "$want_tar" =~ ^[0-9a-f]{64}$ ]] || return 1
26328
+ have_tar="$(fmix_hash_stdin < "$out/fmix.tar.gz")" || return 1
26329
+ [[ "$have_tar" == "$want_tar" ]] || return 1
26330
+ tar -xzf "$out/fmix.tar.gz" -C "$out" || return 1
26331
+ [[ -f "$out/fmix" && ! -L "$out/fmix" ]] || return 1
26332
+ manifest_sha="$(sed -n 's/.*"runnerSha256"[[:space:]]*:[[:space:]]*"\([0-9a-f]\{64\}\)".*/\1/p' "$out/package.json")"
26333
+ [[ "$manifest_sha" =~ ^[0-9a-f]{64}$ ]] || return 1
26334
+ have_runner="$(fmix_hash_stdin < "$out/fmix")" || return 1
26335
+ [[ "$have_runner" == "$manifest_sha" ]] || return 1
26336
+ declared="$(awk -F'"' '/^FMIX_VERSION=/{print $2; exit}' "$out/fmix")"
26337
+ [[ "$declared" == "$version" ]] || return 1
26338
+ return 0
26339
+ }
26340
+
26341
+ fmix_auto_upgrade_claim_stamp() {
26342
+ # Records the attempt start time so at most one attempt runs per TTL
26343
+ # window regardless of its outcome. The stamp is written before any
26344
+ # network work: a failed probe is not retried until the TTL expires.
26345
+ local home="${FMIX_HOME:-${HOME:-}/.ct-fmix}" stamp tmp now
26346
+ stamp="$home/auto-upgrade.stamp"
26347
+ mkdir -p "$home" 2>/dev/null || return 1
26348
+ fmix_auto_upgrade_stamp_due || return 1
26349
+ now="$(fmix_epoch)"
26350
+ [[ "$now" =~ ^[0-9]+$ ]] || return 1
26351
+ tmp="$stamp.tmp.$$"
26352
+ printf '%s\n' "$now" > "$tmp" 2>/dev/null || return 1
26353
+ mv -f "$tmp" "$stamp" 2>/dev/null || { rm -f "$tmp" 2>/dev/null; return 1; }
26354
+ return 0
26355
+ }
26356
+
26357
+ fmix_auto_upgrade_run() {
26358
+ # Real attempt body. "Success" means "nothing needed or nothing happened":
26359
+ # every exit path returns 0 so even a synchronous caller cannot observe an
26360
+ # upgrade failure in its own status.
26361
+ local latest tmp target
26362
+ fmix_auto_upgrade_claim_stamp || return 0
26363
+ latest="$(fmix_auto_upgrade_latest_version)" || return 0
26364
+ fmix_auto_upgrade_version_newer "$latest" "$FMIX_VERSION" || return 0
26365
+ tmp="$(mktemp -d "${TMPDIR:-/tmp}/fmix-auto-upgrade.XXXXXX")" || return 0
26366
+ target="${FMIX_INSTALL_DIR:-${HOME:-}/.local/bin}"
26367
+ if fmix_auto_upgrade_fetch_release "$latest" "$tmp" \
26368
+ && fmix_install_snapshot "$tmp/fmix" "$target" >/dev/null; then
26369
+ :
26370
+ fi
26371
+ rm -rf "$tmp"
26372
+ return 0
26373
+ }
26374
+
26375
+ fmix_auto_upgrade_attempt() {
26376
+ # Fail-open, silent boundary: the attempt always reports success and never
26377
+ # writes to the invoking command's output streams.
26378
+ fmix_auto_upgrade_run >/dev/null 2>&1 </dev/null || true
26379
+ return 0
26380
+ }
26381
+
26382
+ fmix_auto_upgrade_spawn() {
26383
+ # Detached background job: returns immediately and completes after the
26384
+ # command has finished. Redirected to /dev/null on every stream so it can
26385
+ # never touch the command's output contract, and immune to hangup so an
26386
+ # exiting shell does not kill the attempt mid-install.
26387
+ (
26388
+ trap '' HUP
26389
+ fmix_auto_upgrade_attempt
26390
+ ) >/dev/null 2>&1 </dev/null &
26391
+ return 0
26392
+ }
26393
+
26394
+ fmix_maybe_auto_upgrade() {
26395
+ # Hook for main: cheap read-only gate, then a detached attempt. Always
26396
+ # returns 0 and never prints — an upgrade attempt must never change the
26397
+ # invoking command's exit code, output contract, or artifacts.
26398
+ fmix_auto_upgrade_eligible "$@" || return 0
26399
+ fmix_auto_upgrade_stamp_due || return 0
26400
+ fmix_auto_upgrade_spawn
26401
+ return 0
26402
+ }
26403
+
24906
26404
  # ---------------------------------------------------------------------------
24907
26405
  # Main dispatch
24908
26406
  # ---------------------------------------------------------------------------
@@ -24919,7 +26417,7 @@ fmix test — run ExUnit targets inside a provisioned session DB.
24919
26417
  Usage:
24920
26418
  fmix test [--worktree <path>] [--session <id>] [--isolate]
24921
26419
  [--cache-base <N.N.N-stable>] [--event-fd <fd>] [--no-auto-setup]
24922
- [--unit] -- <mix test args>
26420
+ [--unit] [--profile-boot] [--profile-fixtures] -- <mix test args>
24923
26421
 
24924
26422
  Notes:
24925
26423
  - A missing artifact template is auto-bootstrapped by delegating to
@@ -25074,6 +26572,9 @@ Example:
25074
26572
  fmix status
25075
26573
  VERB
25076
26574
  ;;
26575
+ analyze)
26576
+ cmd_analyze --help
26577
+ ;;
25077
26578
  timing)
25078
26579
  cat <<'VERB'
25079
26580
  fmix timing — phase timings + session fragmentation report.
@@ -25145,10 +26646,59 @@ Usage:
25145
26646
 
25146
26647
  Notes:
25147
26648
  Installs a git pre-push hook invoking fmix verify-push.
26649
+ VERB
26650
+ ;;
26651
+ runner)
26652
+ cat <<'VERB'
26653
+ fmix runner — CLI surface for the distributed runner (submit, poll, receipts).
26654
+
26655
+ Usage:
26656
+ fmix runner submit [--worktree <path>] [--ref <ref>] -- <test|coverage|task> [args]
26657
+ fmix runner status <job-id>
26658
+ fmix runner logs <job-id> [--tail N]
26659
+ fmix runner cancel <job-id>
26660
+ fmix runner list [--worktree <name>] [--state <state>]
26661
+ fmix runner receipt <job-id> [--verify [--pubkey <path>]]
26662
+ fmix runner install-hooks [--worktree <path>] [--legacy] [--force]
26663
+ fmix runner gc-worktree <worktree>
26664
+
26665
+ Notes:
26666
+ - Transport is REST against the runner portal base URL (FMIX_RUNNER_URL);
26667
+ the portal signs the inner HMAC envelope for orchestrator hops itself.
26668
+ - Auth: Cloudflare Access service-token headers from
26669
+ CF_ACCESS_CLIENT_ID / CF_ACCESS_CLIENT_SECRET, falling back to the
26670
+ per-user pair MCP_ACCESS_CLIENT_ID_${USER} / MCP_ACCESS_CLIENT_SECRET_${USER},
26671
+ then FMIX_RUNNER_TOKEN as a bearer token. Missing credentials fail
26672
+ before any request is sent.
26673
+ - submit resolves the worktree (default: current git worktree), the repo
26674
+ from the origin remote (owner/name), and the ref (default: HEAD SHA);
26675
+ everything after `--` is the lane command plus its pass-through args.
26676
+ - receipt --verify checks the Ed25519 signature offline against the
26677
+ canonical JSON signing view; the key comes from --pubkey or
26678
+ FMIX_RUNNER_PUBKEY and verification is fail-closed (openssl pkeyutl,
26679
+ python3 fallback).
26680
+ - install-hooks wires the runner pre-push hook (core.hooksPath .githooks by
26681
+ default, .git/hooks with --legacy); it is idempotent and never clobbers a
26682
+ foreign hook without --force.
26683
+
26684
+ Examples:
26685
+ fmix runner submit --worktree . -- test
26686
+ fmix runner submit --worktree ./cisco-cdr --ref origin/main -- test test/cdrcisco/sip/replaces_test.exs
26687
+ fmix runner status job-7f3k2
26688
+ fmix runner logs job-7f3k2 --tail 200
26689
+ fmix runner receipt job-7f3k2 --verify --pubkey ~/.config/calltelemetry/fmix-runner.pub
26690
+ fmix runner install-hooks
26691
+ fmix runner gc-worktree cisco-cdr
26692
+
26693
+ Environment:
26694
+ FMIX_RUNNER_URL Portal base URL (default: https://mcp.calltelemetry.com/fmix-runner)
26695
+ FMIX_RUNNER_TOKEN Bearer token fallback (also used by the pre-push hook)
26696
+ FMIX_RUNNER_PUBKEY Ed25519 receipt public key for `receipt --verify`
26697
+ CF_ACCESS_CLIENT_ID / CF_ACCESS_CLIENT_SECRET Cloudflare Access service token
25148
26698
  VERB
25149
26699
  ;;
25150
26700
  *)
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"
26701
+ fmix_error "No focused help for '$verb'. Valid commands: test, coverage, task, format, setup, seed publish, cache explain, cache verify, ensure, doctor, status, timing, analyze, gc, install, self-test, verify-push, hook, runner, version, help"
25152
26702
  return 1
25153
26703
  ;;
25154
26704
  esac
@@ -25159,7 +26709,7 @@ fmix_usage() {
25159
26709
  fmix — fast native Elixir test runner for cisco-cdr
25160
26710
 
25161
26711
  Usage:
25162
- ./fmix test [--worktree <path>] [--session <id>] [--no-auto-setup] [--cache-base <N.N.N-stable>] [--event-fd <fd>] [--unit] -- <mix test args>
26712
+ ./fmix test [--worktree <path>] [--session <id>] [--no-auto-setup] [--cache-base <N.N.N-stable>] [--event-fd <fd>] [--unit] [--profile-boot] [--profile-fixtures] -- <mix test args>
25163
26713
  ./fmix coverage [--worktree <path>] [--session <id>] [--no-auto-setup] --base <git-ref> [--source <lib/**/*.ex>] [--threshold 80] -- <test paths>
25164
26714
  ./fmix task [--worktree <path>] [--session <id>] [--database <name>] [--mix-env <env>] [--allow-run] -- <mix task> [args]
25165
26715
  ./fmix format [--worktree <path>] [--session <id>] [--mix-env <env>] [--dot-formatter <path>] [--check] -- <files...>
@@ -25169,10 +26719,17 @@ Usage:
25169
26719
  ./fmix cache verify [--key <16-hex-template-key>]
25170
26720
  ./fmix verify-push [--worktree <path>] [--cooldown-minutes <N>] [--require-receipt]
25171
26721
  ./fmix hook install [--worktree <path>]
26722
+ ./fmix runner submit [--worktree <path>] [--ref <ref>] -- <test|coverage|task> [args]
26723
+ ./fmix runner <status|logs|cancel|receipt> <job-id> # logs --tail N; receipt --verify
26724
+ ./fmix runner list [--worktree <name>] [--state <state>]
26725
+ ./fmix runner install-hooks [--worktree <path>] [--legacy] [--force]
26726
+ ./fmix runner gc-worktree <worktree>
25172
26727
  ./fmix ensure
25173
26728
  ./fmix doctor
25174
26729
  ./fmix status
25175
26730
  ./fmix timing [--limit N] [--worktree <path>] # phase timings + session fragmentation
26731
+ ./fmix analyze report --run <UUID> --output <new-dir>
26732
+ ./fmix analyze hotspots --run <UUID> [--limit 20] # ranked JSON, no test execution
25176
26733
  ./fmix gc --artifacts-only [--json] # bounded read-only inventory; no eviction
25177
26734
  ./fmix gc [--reap|--consolidate] [--worktree <path>] [--yes]
25178
26735
  ./fmix install # immutable snapshot + atomic PATH link (~/.local/bin)
@@ -25197,6 +26754,9 @@ Examples:
25197
26754
  ./fmix gc
25198
26755
  ./fmix gc --consolidate --yes
25199
26756
  ./fmix gc --reap --yes
26757
+ ./fmix runner submit --worktree . -- test
26758
+ ./fmix runner logs job-7f3k2 --tail 200
26759
+ ./fmix runner install-hooks # pre-push hook install for the runner lane
25200
26760
 
25201
26761
  Operational notes:
25202
26762
  SUPER-HOT contract (2.2.0+): one worktree → one warm overlay by default.
@@ -25226,6 +26786,9 @@ Environment overrides:
25226
26786
  FMIX_NO_AUTO_SETUP Set to 1 to stop test/coverage lanes from auto-running
25227
26787
  fmix setup on a missing artifact template (same effect
25228
26788
  as --no-auto-setup)
26789
+ FMIX_NO_AUTO_UPGRADE Set to 1 to disable automatic upgrade-on-invocation
26790
+ FMIX_AUTO_UPGRADE_TTL_S Minimum seconds between background upgrade attempts
26791
+ (default: 3600; invalid values silently fall back to 3600)
25229
26792
  FMIX_FORCE_SESSION Set to 1 to allow ephemeral session ids (cold path)
25230
26793
  FMIX_THREAD_SESSIONS Set to 1 to restore CODEX_THREAD_ID session binding
25231
26794
  FMIX_HOT_PATH_BUDGET_S hot_path overhead budget seconds excl mix_test (default: 25)
@@ -25266,11 +26829,17 @@ Environment overrides:
25266
26829
  FMIX_MIGRATION_DELTA_LIMIT Maximum migrations applied from a selected base (default: 50)
25267
26830
  FMIX_COMPILE_HEARTBEAT Silent compile heartbeat seconds (default: 30; 0 disables)
25268
26831
  FMIX_COMPILE_TIMEOUT Per-attempt compile cap in seconds (default: 900)
25269
- FMIX_SETUP_COMPILE_TIMEOUT Explicit setup compile cap in seconds (default: 900)
26832
+ FMIX_SETUP_COMPILE_TIMEOUT Explicit setup compile absolute ceiling in seconds (default: 7200)
26833
+ FMIX_SETUP_COMPILE_STALL_TIMEOUT Explicit setup no-output stall budget in seconds (default: 600)
25270
26834
  FMIX_TIMING Set to 1 to print per-phase timing lines during a run
25271
26835
  FMIX_MIGRATION_TIMEOUT Migration delta cap in seconds (default: 120)
25272
26836
  FMIX_STRUCTURE_LOAD_TIMEOUT explicit cold structure.sql replay cap in seconds (default: 120)
25273
26837
  FMIX_STRUCTURE_LOAD_HEARTBEAT structure.sql replay heartbeat seconds (default: 30)
26838
+ FMIX_RUNNER_URL Distributed runner portal base URL (default: https://mcp.calltelemetry.com/fmix-runner)
26839
+ FMIX_RUNNER_TOKEN Bearer token for runner portal/hook endpoints (per-dev, revocable)
26840
+ FMIX_RUNNER_PUBKEY Ed25519 receipt public key for 'fmix runner receipt --verify'
26841
+ CF_ACCESS_CLIENT_ID / CF_ACCESS_CLIENT_SECRET Cloudflare Access service token for the runner portal
26842
+ (per-user fallback: MCP_ACCESS_CLIENT_ID_${USER} / MCP_ACCESS_CLIENT_SECRET_${USER})
25274
26843
  FMIX_INSTALL_DIR Target dir for 'fmix install' (default: ~/.local/bin)
25275
26844
  USAGE
25276
26845
  }
@@ -26065,6 +27634,11 @@ if worker_pid == 0:
26065
27634
  "CT_TEST_RUN_LIVE_DIR": artifact_live_run_dir,
26066
27635
  "CT_TEST_STATS_DIR": artifact_stats_dir,
26067
27636
  "CT_TEST_STATS_FILE": os.path.join(artifact_stats_dir, "stats.json"),
27637
+ "CT_TEST_STATS_PATH": os.path.join(artifact_stats_dir, "stats.json"),
27638
+ "CT_TEST_CURRENT_PATH": os.path.join(artifact_live_dir, "current.json"),
27639
+ "CT_TEST_EVENTS_PATH": os.path.join(artifact_live_dir, "events.ndjson"),
27640
+ "CT_TEST_VM_EVENTS_PATH": os.path.join(artifact_live_dir, "vm_events.ndjson"),
27641
+ "CT_TEST_VM_STATS_PATH": os.path.join(artifact_stats_dir, "vm_stats.json"),
26068
27642
  })
26069
27643
  signal.pthread_sigmask(signal.SIG_SETMASK, startup_signal_mask)
26070
27644
  os.execve("/bin/bash", ["/bin/bash", RUNNER, "--fmix-observability-worker"] + ARGS, worker_env)
@@ -27426,6 +29000,983 @@ fmix_observability_validate_worker_capability() {
27426
29000
  exec 7<&-
27427
29001
  }
27428
29002
 
29003
+ # Offline analysis stays inside the self-contained distributed runner. It never
29004
+ # initializes FMIX_HOME, resolves credentials, starts Mix, or changes run truth.
29005
+ cmd_analyze() {
29006
+ local py_bin
29007
+ py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
29008
+ "$py_bin" - "$@" <<'FMIX_ANALYZE_PY'
29009
+ import argparse
29010
+ import base64
29011
+ from collections import Counter, defaultdict
29012
+ import hashlib
29013
+ import html
29014
+ import json
29015
+ import math
29016
+ import os
29017
+ from pathlib import Path
29018
+ import re
29019
+ import stat
29020
+ import sys
29021
+
29022
+ MAX_BYTES = 256 * 1024 * 1024
29023
+ MAX_LINE = 256 * 1024
29024
+ MAX_EVENTS = 400000
29025
+ STATES = ('passed', 'failed', 'skipped', 'excluded', 'invalid')
29026
+ TAGS = {'unit', 'integration', 'benchmark', 'benchmark_heavy', 'heavy_benchmark',
29027
+ 'performance', 'stress_test', 'slow', 'e2e', 'feature_e2e', 'uat',
29028
+ 'external', 'manual_only', 'nightly_only', 'fmix_domain', 'fmix_level',
29029
+ 'fmix_purpose', 'fmix_services', 'report_registry', 'regression', 'story',
29030
+ 'requires_org', 'nats_required', 'nats_integration', 'timescaledb'}
29031
+
29032
+
29033
+ def strict_json(value):
29034
+ def invalid(_):
29035
+ raise ValueError('non-finite JSON number')
29036
+ return json.loads(value, parse_constant=invalid)
29037
+
29038
+
29039
+ def number(value):
29040
+ return value if type(value) in (int, float) and math.isfinite(value) and value >= 0 else None
29041
+
29042
+
29043
+ def text(value, limit=500):
29044
+ return value[:limit] if isinstance(value, str) else ''
29045
+
29046
+
29047
+ def safe_file(root, relative, optional=False):
29048
+ path = root
29049
+ for part in Path(relative).parts:
29050
+ path = path / part
29051
+ if path.is_symlink():
29052
+ raise ValueError('symlinked input: ' + relative)
29053
+ if optional and not path.exists():
29054
+ return None
29055
+ fd = os.open(path, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0))
29056
+ info = os.fstat(fd)
29057
+ if not stat.S_ISREG(info.st_mode) or info.st_size > MAX_BYTES:
29058
+ os.close(fd)
29059
+ raise ValueError('input is not a bounded regular file: ' + relative)
29060
+ return os.fdopen(fd, encoding='utf-8')
29061
+
29062
+
29063
+ def read_object(root, relative, optional=False):
29064
+ stream = safe_file(root, relative, optional)
29065
+ if stream is None:
29066
+ return None
29067
+ with stream:
29068
+ value = strict_json(stream.read(MAX_BYTES + 1))
29069
+ if not isinstance(value, dict):
29070
+ raise ValueError('expected JSON object: ' + relative)
29071
+ return value
29072
+
29073
+
29074
+ def records(root, relative, issues, optional=False):
29075
+ stream = safe_file(root, relative, optional)
29076
+ if stream is None:
29077
+ issues.append('missing ' + relative)
29078
+ return
29079
+ size = 0
29080
+ with stream:
29081
+ for index in range(MAX_EVENTS):
29082
+ line = stream.readline(MAX_LINE + 1)
29083
+ if not line:
29084
+ return
29085
+ size += len(line.encode('utf-8'))
29086
+ if len(line) > MAX_LINE or size > MAX_BYTES:
29087
+ issues.append('input limit reached: ' + relative)
29088
+ return
29089
+ try:
29090
+ item = strict_json(line)
29091
+ if not isinstance(item, dict):
29092
+ raise ValueError('record is not an object')
29093
+ yield item
29094
+ except (ValueError, TypeError):
29095
+ issues.append('invalid JSON record in ' + relative + ':' + str(index + 1))
29096
+ issues.append('event limit reached: ' + relative)
29097
+
29098
+
29099
+ def source_view(source):
29100
+ source = source if isinstance(source, dict) else {}
29101
+ result = {}
29102
+ for key in ('commit_sha', 'tree_sha'):
29103
+ value = source.get(key)
29104
+ result[key] = value if isinstance(value, str) and re.fullmatch('[0-9a-f]{40}', value) else None
29105
+ result['dirty'] = source.get('dirty') if type(source.get('dirty')) is bool else None
29106
+ for key in ('elixir', 'otp', 'profile', 'partition'):
29107
+ result[key] = text(source.get(key), 80)
29108
+ return result
29109
+
29110
+
29111
+ def classify(ref, tags, observed, queries):
29112
+ parts = ref['file'].split('/')
29113
+ domain = tags.get('fmix_domain')
29114
+ domain_basis = 'explicit tag'
29115
+ if not isinstance(domain, str):
29116
+ domain = parts[2] if len(parts) > 2 and parts[1] == 'cdrcisco' else (parts[1] if len(parts) > 1 else 'unknown')
29117
+ domain_basis = 'directory inference'
29118
+ level = tags.get('fmix_level')
29119
+ basis = 'explicit tag'
29120
+ if not isinstance(level, str):
29121
+ if observed and queries and queries > 0:
29122
+ level, basis = 'integration', 'observed SQL'
29123
+ elif tags.get('unit') is True:
29124
+ level = 'unit'
29125
+ elif tags.get('integration') is True:
29126
+ level = 'integration'
29127
+ elif '/unit/' in ref['file']:
29128
+ level, basis = 'unit', 'directory inference'
29129
+ elif '/integration/' in ref['file']:
29130
+ level, basis = 'integration', 'directory inference'
29131
+ else:
29132
+ level, basis = 'unknown', 'not classified'
29133
+ purpose = tags.get('fmix_purpose')
29134
+ if not isinstance(purpose, str):
29135
+ purpose = 'performance' if any(tags.get(t) is True for t in ('benchmark', 'benchmark_heavy', 'heavy_benchmark', 'performance')) else 'unclassified'
29136
+ return {'domain': domain, 'domain_basis': domain_basis, 'level': level,
29137
+ 'level_basis': basis, 'purpose': purpose}
29138
+
29139
+
29140
+ def measured_sections(raw, observed):
29141
+ if not observed or not isinstance(raw, list):
29142
+ return []
29143
+ result = []
29144
+ for row in raw[:256]:
29145
+ if not isinstance(row, dict):
29146
+ continue
29147
+ name, us = row.get('section'), number(row.get('time_us'))
29148
+ if isinstance(name, str) and re.fullmatch(r'[A-Za-z0-9_.:-]{1,100}', name) and us is not None:
29149
+ result.append({'section': name, 'duration_ms': us / 1000, 'inclusive': True})
29150
+ return result
29151
+
29152
+
29153
+ def operation_view(raw, sequence):
29154
+ if not isinstance(raw, dict) or raw.get('name') != 'report_registry.load':
29155
+ return None
29156
+ duration = number(raw.get('duration_ms'))
29157
+ if duration is None or raw.get('scope') != 'run' or raw.get('status') not in ('ok', 'error'):
29158
+ return None
29159
+ initiator = raw.get('initiator')
29160
+ initiator = ({key: text(initiator.get(key)) for key in ('module', 'name')}
29161
+ if isinstance(initiator, dict) else None)
29162
+ return {'name': raw['name'], 'scope': 'run', 'duration_ms': duration,
29163
+ 'status': raw['status'], 'event_sequence': sequence,
29164
+ 'trigger': raw.get('trigger') if raw.get('trigger') in ('first_use', 'refresh', 'manual_reload') else 'unknown',
29165
+ 'report_count': number(raw.get('report_count')), 'initiator': initiator}
29166
+
29167
+
29168
+ def focused_files(rows):
29169
+ files = sorted({t['file'] for t in rows if re.fullmatch(r'test/[A-Za-z0-9_./-]+\.exs', t['file'])
29170
+ and '..' not in Path(t['file']).parts})
29171
+ return {'mode': 'focused_fmix', 'test_files': files[:50], 'test_files_truncated': len(files) > 50}
29172
+
29173
+
29174
+ SQL_KINDS = ('select', 'insert', 'update', 'delete', 'ddl', 'transaction', 'other')
29175
+ SIGNAL_SECTIONS = ('sql_breakdown', 'logs', 'oban', 'http', 'beam')
29176
+ LOG_LEVELS = ('debug', 'info', 'notice', 'warning', 'error', 'total')
29177
+
29178
+
29179
+ def count_time(raw):
29180
+ if not isinstance(raw, dict) or type(raw.get('count')) is not int or raw['count'] < 0:
29181
+ return None
29182
+ ms = number(raw.get('time_ms'))
29183
+ return {'count': raw['count'], 'time_ms': ms} if ms is not None else None
29184
+
29185
+
29186
+ def counts(raw, keys):
29187
+ if not isinstance(raw, dict) or not all(type(raw.get(k)) is int and raw[k] >= 0 for k in keys):
29188
+ return None
29189
+ return {k: raw[k] for k in keys}
29190
+
29191
+
29192
+ def signals_view(raw):
29193
+ """Strict ct-test-signals.v1 view. Unobserved or malformed sections stay absent, never zero."""
29194
+ if raw is None:
29195
+ return None, False
29196
+ if not isinstance(raw, dict) or raw.get('schema') != 'ct-test-signals.v1' or not isinstance(raw.get('observed'), dict):
29197
+ return None, True
29198
+ observed = {key: raw['observed'].get(key) is True for key in SIGNAL_SECTIONS}
29199
+ view, malformed = {'observed': observed}, False
29200
+ sql = raw.get('sql')
29201
+ if observed['sql_breakdown'] and isinstance(sql, dict):
29202
+ kinds = sql.get('by_kind') if isinstance(sql.get('by_kind'), dict) else {}
29203
+ repos = sql.get('by_repo') if isinstance(sql.get('by_repo'), dict) else {}
29204
+ sources = sql.get('top_sources') if isinstance(sql.get('top_sources'), list) else []
29205
+ view['sql'] = {
29206
+ 'by_kind': {k: v for k in SQL_KINDS if (v := count_time(kinds.get(k)))},
29207
+ 'by_repo': {k: v for k, item in list(repos.items())[:16]
29208
+ if re.fullmatch('[a-z0-9_]{1,64}', k) and (v := count_time(item))},
29209
+ 'top_sources': [{'source': s['source'], **v} for s in sources[:10]
29210
+ if isinstance(s, dict) and isinstance(s.get('source'), str)
29211
+ and re.fullmatch(r'[A-Za-z0-9_.()]{1,64}', s['source']) and (v := count_time(s))]}
29212
+ elif observed['sql_breakdown']:
29213
+ observed['sql_breakdown'], malformed = False, True
29214
+ sections = [('logs', LOG_LEVELS, ()), ('oban', ('jobs', 'failures'), ('time_ms',)), ('http', ('requests',), ('time_ms',))]
29215
+ for key, ints, floats in sections:
29216
+ if not observed[key]:
29217
+ continue
29218
+ value = counts(raw.get(key), ints)
29219
+ if value is not None and all(number((raw.get(key) or {}).get(f)) is not None for f in floats):
29220
+ view[key] = value | {f: number(raw[key][f]) for f in floats}
29221
+ else:
29222
+ observed[key], malformed = False, True
29223
+ beam = raw.get('beam')
29224
+ if observed['beam']:
29225
+ valid = (isinstance(beam, dict) and beam.get('scope') == 'sync_exclusive'
29226
+ and all(type(beam.get(k)) is int for k in ('reductions', 'process_delta', 'memory_delta_bytes', 'gc_runs'))
29227
+ and beam['reductions'] >= 0 and beam['gc_runs'] >= 0)
29228
+ if valid:
29229
+ view['beam'] = {k: beam[k] for k in ('scope', 'reductions', 'process_delta', 'memory_delta_bytes', 'gc_runs')}
29230
+ else:
29231
+ observed['beam'], malformed = False, True
29232
+ return view, malformed
29233
+
29234
+
29235
+ def signals_summary(tests, started, malformed):
29236
+ raw = (started or {}).get('signals_collector')
29237
+ collector = None
29238
+ if isinstance(raw, dict):
29239
+ handlers = raw.get('handlers') if isinstance(raw.get('handlers'), list) else []
29240
+ collector = {'schema': text(raw.get('schema'), 40), 'logger_level': text(raw.get('logger_level'), 20),
29241
+ 'handlers': sorted({h for h in handlers if isinstance(h, str) and re.fullmatch('[a-z_]{1,40}', h)})}
29242
+ executed = [t for t in tests if t['status'] in ('passed', 'failed')]
29243
+ present = [t for t in executed if t['signals']]
29244
+ return {'collector': collector, 'executed_tests': len(executed), 'tests_with_signals': len(present),
29245
+ 'observed_tests': {key: sum(1 for t in present if t['signals']['observed'][key]) for key in SIGNAL_SECTIONS},
29246
+ 'malformed_records': malformed,
29247
+ 'note': 'Signals are attributed through test process lineage. Work in processes outside that lineage, and HTTP clients without telemetry, are not counted. BEAM deltas are recorded only for sync tests.'}
29248
+
29249
+
29250
+ BOOT_MARKS = ('vm_started', 'mix_task_entered', 'apps_started', 'helper_started', 'helper_finished',
29251
+ 'suite_started', 'suite_finished', 'at_exit')
29252
+ MFA = re.compile(r'[A-Za-z0-9_.?!]{1,160}/[0-9]{1,3}')
29253
+
29254
+
29255
+ def epoch_ms(value):
29256
+ return value if type(value) is int and 10 ** 12 <= value < 10 ** 14 else None
29257
+
29258
+
29259
+ def boot_view(root, startup, issues):
29260
+ """Join runner and VM wall-clock marks into consecutive measured boot segments."""
29261
+ runner = read_object(root, 'artifacts/live/mix_boundaries.json', optional=True)
29262
+ vm = read_object(root, 'artifacts/live/boot_timeline.json', optional=True)
29263
+ if runner is not None and runner.get('schema') != 'fmix-mix-boundaries.v1':
29264
+ issues.append('unknown mix boundary schema')
29265
+ runner = None
29266
+ if vm is not None and vm.get('schema') != 'ct-test-boot.v1':
29267
+ issues.append('unknown boot timeline schema')
29268
+ vm = None
29269
+ if runner is None and vm is None:
29270
+ return None
29271
+ runner = runner or {}
29272
+ raw_marks = vm.get('marks') if vm and isinstance(vm.get('marks'), dict) else {}
29273
+ marks = {'guard_pre_started': epoch_ms(runner.get('guard_pre_started_at')), 'spawned': epoch_ms(runner.get('spawned_at'))}
29274
+ marks.update({key: epoch_ms(raw_marks.get(key)) for key in BOOT_MARKS})
29275
+ marks.update({'exited': epoch_ms(runner.get('exited_at')), 'guard_post_finished': epoch_ms(runner.get('guard_post_finished_at'))})
29276
+ present = [(k, v) for k, v in marks.items() if v is not None]
29277
+ if any(b[1] < a[1] for a, b in zip(present, present[1:])):
29278
+ issues.append('boot timeline marks are out of order; segments omitted')
29279
+ present = []
29280
+ labels = {'spawned': 'Source check before Mix', 'vm_started': 'BEAM VM start',
29281
+ 'mix_task_entered': 'Mix boot (load paths, config)',
29282
+ 'apps_started': 'Application start (profiled)',
29283
+ 'helper_started': 'Before test helper (Mix app.start)' if marks['apps_started'] is None else 'Before test helper',
29284
+ 'helper_finished': 'Test helper', 'suite_started': 'Test file loading',
29285
+ 'suite_finished': 'ExUnit run', 'at_exit': 'Suite teardown and exit hooks',
29286
+ 'exited': 'VM shutdown', 'guard_post_finished': 'Source check after Mix'}
29287
+ # Without --profile-boot the apps_started mark is expected to be absent; any
29288
+ # other gap merges neighbors under a name that lists every covered interval.
29289
+ order = [k for k in marks if k != 'apps_started' or marks[k] is not None]
29290
+ segments = []
29291
+ for a, b in zip(present, present[1:]):
29292
+ covered = order[order.index(a[0]) + 1:order.index(b[0]) + 1]
29293
+ segments.append({'name': labels[b[0]] if len(covered) == 1 else 'Merged (missing marks): ' + ' + '.join(labels[k] for k in covered),
29294
+ 'from': a[0], 'to': b[0], 'start_ms': a[1] - present[0][1], 'duration_ms': b[1] - a[1],
29295
+ 'merged': len(covered) > 1, 'tests': covered == ['suite_finished']})
29296
+ window = present[-1][1] - present[0][1] if present else None
29297
+
29298
+ def ranked(rows, fields):
29299
+ out = []
29300
+ for row in rows if isinstance(rows, list) else []:
29301
+ if not isinstance(row, dict) or number(row.get('duration_ms')) is None:
29302
+ continue
29303
+ item = {f: text(row.get(f), 160) for f in fields}
29304
+ if all(item.values()):
29305
+ out.append(item | {'duration_ms': number(row['duration_ms'])})
29306
+ return sorted(out, key=lambda r: -r['duration_ms'])[:50]
29307
+
29308
+ return {'clock': 'os_time_ms', 'boot_profile': bool(vm and vm.get('boot_profile') is True),
29309
+ 'runner_marks': runner != {}, 'vm_marks': vm is not None, 'marks': marks, 'segments': segments,
29310
+ 'window_ms': window, 'helper_phases': startup,
29311
+ 'apps': ranked(vm.get('apps') if vm else None, ('app',)),
29312
+ 'children': ranked(vm.get('children') if vm else None, ('supervisor', 'child')),
29313
+ 'note': 'Segments are consecutive wall-clock intervals between recorded marks on one host clock. A missing mark merges its neighbors; nothing is estimated.'}
29314
+
29315
+
29316
+ def fixture_view(root, issues):
29317
+ raw = read_object(root, 'artifacts/live/fixture_prof.json', optional=True)
29318
+ if raw is None:
29319
+ return None
29320
+ if raw.get('schema') != 'ct-test-fixture-prof.v1' or not isinstance(raw.get('functions'), list):
29321
+ issues.append('unknown or malformed fixture profile')
29322
+ return None
29323
+ rows = []
29324
+ for row in raw['functions'][:200]:
29325
+ if (isinstance(row, dict) and isinstance(row.get('mfa'), str) and MFA.fullmatch(row['mfa'])
29326
+ and type(row.get('calls')) is int and row['calls'] >= 0 and number(row.get('inclusive_ms')) is not None):
29327
+ rows.append({'mfa': row['mfa'], 'calls': row['calls'], 'inclusive_ms': number(row['inclusive_ms']),
29328
+ 'max_ms': number(row.get('max_ms'))})
29329
+ return {'method': text(raw.get('method'), 60), 'truncated': raw.get('truncated') is True,
29330
+ 'modules': number(raw.get('modules')), 'functions': sorted(rows, key=lambda r: -r['inclusive_ms'])[:100],
29331
+ 'note': 'Inclusive time: nested fixture calls are counted in both the caller and the callee, so rows must not be summed.'}
29332
+
29333
+
29334
+ def tag_profile(tests):
29335
+ rows = defaultdict(lambda: {'tests': 0, 'work_ms': 0})
29336
+ for t in tests:
29337
+ if t['status'] not in ('passed', 'failed'):
29338
+ continue
29339
+ keys = [k for k, v in t['tags'].items() if v is True]
29340
+ keys += [k + '=' + v for k, v in t['tags'].items() if isinstance(v, str)]
29341
+ keys += ['level=' + t['classification']['level'], 'async' if t['async'] else 'sync']
29342
+ for key in keys:
29343
+ rows[key]['tests'] += 1
29344
+ rows[key]['work_ms'] += t['total_time_ms'] or 0
29345
+ return sorted(({'tag': k, **v} for k, v in rows.items()), key=lambda r: -r['work_ms'])[:60]
29346
+
29347
+
29348
+ def rank_hotspots(data):
29349
+ if not data['completeness']['complete']:
29350
+ return []
29351
+ tests = [t for t in data['tests'] if t['status'] in ('passed', 'failed')]
29352
+ rows = []
29353
+
29354
+ def add(rule, scope, key, title, cost, affected, recommendation, retain, confidence='observed_cost', evidence=None):
29355
+ facts = {'run_id': data['run_id'], 'source_commit': data['source']['commit_sha'],
29356
+ 'sample_count': 1, 'affected_tests': len(affected),
29357
+ 'test_ids': sorted({t['id'] for t in affected})[:100]}
29358
+ facts.update(evidence or {})
29359
+ rows.append({'id': hashlib.sha256((rule + '\0' + key).encode()).hexdigest(),
29360
+ 'rule_id': rule, 'scope': scope, 'scope_key': key, 'title': title,
29361
+ 'observed_cost_ms': cost, 'estimated_savings_ms': None,
29362
+ 'cost_additive': False, 'confidence': confidence,
29363
+ 'recommendation': recommendation, 'retain': retain,
29364
+ 'verification': focused_files(affected), 'evidence': facts})
29365
+
29366
+ timing = data['timing']
29367
+ prep = timing.get('runner_preparation_ms')
29368
+ execution_ms = timing.get('exunit_run_ms')
29369
+ if prep is not None and prep >= 1000:
29370
+ phases = timing['phases_seconds']
29371
+ components = sorted(((k, v) for k, v in phases.items() if k != 'mix_test' and v is not None), key=lambda x: -x[1])
29372
+ add('runner_preparation', 'run', 'runner_preparation',
29373
+ 'Runner preparation dominates this selection' if execution_ms is not None and prep >= execution_ms else 'Runner preparation has measured cost', prep, tests,
29374
+ 'Measure the largest preparation substeps through the normal installed runner before changing cache or lock policy.',
29375
+ 'Source identity, database provenance, locking and cache verification',
29376
+ evidence={'comparison_available': execution_ms is not None, 'exunit_run_ms': execution_ms,
29377
+ 'components_seconds': dict(components), 'compile_seconds': timing['compile']['seconds'],
29378
+ 'compile_files': timing['compile']['file_count'],
29379
+ 'permit_wait_seconds': phases.get('compile_permit_wait'),
29380
+ 'compile_timing_note': 'compiler invocation timing can include permit wait; phase boundaries are consecutive', 'cost_scope': 'runner preparation envelope'})
29381
+ startup = timing['startup_phases']
29382
+ envelope = startup.get('test_helper_pre_exunit_total', {}).get('duration_ms')
29383
+ if envelope is not None and envelope >= 100:
29384
+ add('helper_startup', 'run', 'test_helper_pre_exunit_total', 'Helper startup is a shared cost', envelope, tests,
29385
+ 'Check which selected test requirements need the largest startup phases; verify a narrower profile on the same selection.',
29386
+ 'Required services, partitions, migrations and integration behavior',
29387
+ evidence={'components': {k: v for k, v in startup.items() if k != 'test_helper_pre_exunit_total'},
29388
+ 'cost_scope': 'helper envelope; child phases are included'})
29389
+
29390
+ measured_first = defaultdict(float)
29391
+ if data['operation_evidence']['complete']:
29392
+ operations = defaultdict(list)
29393
+ for op in data['operations']:
29394
+ operations[op['name']].append(op)
29395
+ for name, spans in operations.items():
29396
+ modules = {s['initiator']['module'] for s in spans if s['initiator'] and s['initiator']['module']}
29397
+ for span in spans:
29398
+ if span['initiator'] and span['trigger'] == 'first_use':
29399
+ measured_first[(span['initiator']['module'], span['initiator']['name'])] += span['duration_ms']
29400
+ affected = [t for t in tests if t['module'] in modules] or tests
29401
+ add('shared_initialization', 'operation', name, 'Shared registry loading was measured',
29402
+ sum(s['duration_ms'] for s in spans), affected,
29403
+ 'Profile discovery and definition loading; preserve an explicit cold-load contract when reusing initialized state.',
29404
+ 'Registry contents, refresh/restart behavior and metadata contracts', 'measured_operation',
29405
+ {'operations': spans, 'occurrences': len(spans), 'cost_scope': 'shared operation; overlaps triggering test time'})
29406
+
29407
+ modules = defaultdict(list)
29408
+ for t in tests:
29409
+ modules[t['module']].append(t)
29410
+ for module, members in modules.items():
29411
+ if len(members) < 3:
29412
+ continue
29413
+ ordered = sorted(members, key=lambda t: t.get('start_sequence') or t['event_sequence'])
29414
+ first, rest = ordered[0], ordered[1:]
29415
+ total = sum(t['total_time_ms'] or 0 for t in members)
29416
+ others = sorted(t['total_time_ms'] or 0 for t in rest)
29417
+ median = others[len(others) // 2]
29418
+ cost = first['total_time_ms'] or 0
29419
+ if cost > 0 and measured_first[(module, first['name'])] >= cost * .5:
29420
+ continue
29421
+ if cost >= 50 and cost >= 5 * max(median, 0.001) and cost >= total * .5:
29422
+ add('first_use_concentration', 'module', module, 'First observed test dominates its module', cost, members,
29423
+ 'Add a shared-load span and vary test order to check whether the cost follows the first lookup; do not remove the triggering test.',
29424
+ 'Cold-start behavior and the triggering test assertions', 'hypothesis',
29425
+ {'first_test_id': first['id'], 'module_work_ms': total, 'other_median_ms': median,
29426
+ 'order_basis': 'test start event' if first.get('start_sequence') else 'first result observed',
29427
+ 'cost_scope': 'first test duration; shared-load contribution not yet attributed'})
29428
+
29429
+ fixtures = defaultdict(list)
29430
+ for t in tests:
29431
+ if t['setup_time_ms'] is None:
29432
+ continue
29433
+ aggregates = [s['section'] for s in t['setup_sections'] if s['section'].endswith('.setup')]
29434
+ key = aggregates[0] if len(aggregates) == 1 else 'observed_setup:' + t['module']
29435
+ fixtures[key].append(t)
29436
+ for name, members in fixtures.items():
29437
+ heavy = [t for t in members if (t['setup_percent'] or 0) >= 50]
29438
+ cost = sum(t['setup_time_ms'] for t in members)
29439
+ if len(heavy) >= 3 and cost >= 10:
29440
+ sections = defaultdict(float)
29441
+ for t in members:
29442
+ for section in t['setup_sections']:
29443
+ if section['section'] != name:
29444
+ sections[section['section']] += section['duration_ms']
29445
+ add('repeated_setup', 'fixture', name, 'Repeated fixture cost hides below per-test thresholds', cost, members,
29446
+ 'Inspect the setup-heavy subset for a focused case/fixture; use the breakdown to target common sandbox or service work.',
29447
+ 'Database isolation, cleanup and each test public behavior',
29448
+ evidence={'setup_heavy_tests': len(heavy), 'setup_heavy_work_ms': sum(t['total_time_ms'] or 0 for t in heavy),
29449
+ 'setup_heavy_setup_ms': sum(t['setup_time_ms'] for t in heavy),
29450
+ 'nested_sections_ms': dict(sorted(sections.items(), key=lambda x: -x[1])[:20]),
29451
+ 'cost_scope': 'observed setup aggregate; nested sections are not added'})
29452
+
29453
+ conflicts = defaultdict(list)
29454
+ query_heavy = defaultdict(list)
29455
+ for t in tests:
29456
+ if t['db_observed'] and (t['db_query_count'] or 0) > 0:
29457
+ if '/unit/' in t['file'] or t['tags'].get('unit') is True or t['classification']['level'] == 'unit':
29458
+ conflicts[t['file']].append(t)
29459
+ if (t['db_query_count'] or 0) >= 50:
29460
+ query_heavy[t['file']].append(t)
29461
+ for file, members in conflicts.items():
29462
+ declared = sorted({t['tags']['fmix_level'] if isinstance(t['tags'].get('fmix_level'), str) else 'unspecified' for t in members})
29463
+ action = ('The tests already declare integration; align the unit directory or acknowledge its legacy mapping.'
29464
+ if declared == ['integration'] else 'Review the unit classification against observed persistence work.')
29465
+ add('classification_conflict', 'file', file, 'Unit naming and observed persistence disagree', None, members,
29466
+ action + ' This is a classification recommendation, not a measured speedup.',
29467
+ 'Real persistence and tenant-scoping checks', 'classification',
29468
+ {'declared_levels': declared, 'queries': sum(t['db_query_count'] for t in members), 'cost_scope': 'classification only'})
29469
+ for file, members in query_heavy.items():
29470
+ add('sql_concentration', 'file', file, 'Attributed SQL work is concentrated',
29471
+ (sum(t['db_query_time_ms'] + t['db_queue_time_ms'] for t in members)
29472
+ if all(t['db_query_time_ms'] is not None and t['db_queue_time_ms'] is not None for t in members) else None), members,
29473
+ 'Separate fixture SQL, repeated lookups and pool waiting before proposing query or concurrency changes.',
29474
+ 'Persistence and transaction semantics',
29475
+ evidence={'queries': sum(t['db_query_count'] for t in members), 'cost_scope': 'attributed SQL execution plus queue time; overlaps test duration'})
29476
+ boot = data.get('boot') or {}
29477
+ for segment in boot.get('segments', []):
29478
+ # The helper interval is already ranked from its own measured phases.
29479
+ if not segment['tests'] and segment['to'] != 'helper_finished' and segment['duration_ms'] >= 2000:
29480
+ add('boot_segment', 'run', segment['to'], segment['name'] + ' is a measured startup cost', segment['duration_ms'], tests,
29481
+ 'Inspect this interval first. Rerun with fmix test --profile-boot to split application and supervisor-child start time.',
29482
+ 'Services and processes the selected tests actually exercise',
29483
+ evidence={'from_mark': segment['from'], 'to_mark': segment['to'], 'cost_scope': 'consecutive wall-clock interval'})
29484
+ for row in boot.get('apps', [])[:10]:
29485
+ if row['duration_ms'] >= 500:
29486
+ add('app_start', 'application', row['app'], 'Application start is slow', row['duration_ms'], tests,
29487
+ 'Check whether selected tests need this application; start it lazily or stub it in the test profile.',
29488
+ 'Behavior of tests that use this application', evidence={'cost_scope': 'Application.ensure_started duration'})
29489
+ for row in boot.get('children', [])[:15]:
29490
+ if row['duration_ms'] >= 500:
29491
+ add('child_start', 'supervisor_child', row['supervisor'] + ' > ' + row['child'], 'Supervisor child start is slow',
29492
+ row['duration_ms'], tests,
29493
+ 'Defer this child (handle_continue, lazy connect) or exclude it from the test supervision tree.',
29494
+ 'Behavior of tests that use this process', evidence={'cost_scope': 'supervisor child start call duration'})
29495
+ for row in (data.get('fixtures') or {}).get('functions', [])[:15]:
29496
+ if row['inclusive_ms'] >= 200:
29497
+ add('fixture_cost', 'fixture_function', row['mfa'], 'Fixture or helper function is expensive', row['inclusive_ms'], tests,
29498
+ 'Cache it in setup_all, build structs instead of inserting, or trim the records it creates.',
29499
+ 'Data shape that dependent tests assert on', 'observed_cost',
29500
+ {'calls': row['calls'], 'max_ms': row['max_ms'], 'cost_scope': 'inclusive call time; nested fixtures overlap'})
29501
+ write_only = defaultdict(list)
29502
+ for t in tests:
29503
+ kinds = (t.get('signals') or {}).get('sql', {}).get('by_kind')
29504
+ if kinds and 'insert' in kinds and not {'select', 'update', 'delete'} & set(kinds):
29505
+ write_only[t['file']].append(t)
29506
+ for file, members in write_only.items():
29507
+ if len(members) >= 3:
29508
+ add('insert_without_read', 'file', file, 'Tests persist rows they never read back', None, members,
29509
+ 'Check whether these tests need the database. Building structs or using in-memory params avoids inserts the test never queries.',
29510
+ 'Persistence assertions and constraint checks', 'hypothesis',
29511
+ {'inserts': sum(t['signals']['sql']['by_kind']['insert']['count'] for t in members), 'cost_scope': 'classification only'})
29512
+ ddl, noisy, http, leaks, perf = (defaultdict(list) for _ in range(5))
29513
+ for t in tests:
29514
+ if t['classification']['purpose'] == 'performance':
29515
+ perf[t['file']].append(t)
29516
+ s = t.get('signals')
29517
+ if not s:
29518
+ continue
29519
+ if 'ddl' in s.get('sql', {}).get('by_kind', {}):
29520
+ ddl[t['file']].append(t)
29521
+ logs = s.get('logs')
29522
+ if logs and t['status'] == 'passed' and (logs['error'] > 0 or logs['total'] >= 50):
29523
+ noisy[t['file']].append(t)
29524
+ if s.get('http', {}).get('requests', 0) > 0:
29525
+ http[t['file']].append(t)
29526
+ if s.get('beam', {}).get('process_delta', 0) >= 10:
29527
+ leaks[t['file']].append(t)
29528
+ for file, members in ddl.items():
29529
+ statements = [t['signals']['sql']['by_kind']['ddl'] for t in members]
29530
+ add('ddl_in_tests', 'file', file, 'Tests issue schema statements (DDL)', sum(s['time_ms'] for s in statements), members,
29531
+ 'Move schema work into the template database or a once-per-run helper. DDL inside tests takes locks and defeats sandbox reuse.',
29532
+ 'Behavior that genuinely depends on schema changes, such as migration tests',
29533
+ evidence={'ddl_statements': sum(s['count'] for s in statements), 'cost_scope': 'attributed DDL execution time; overlaps test duration'})
29534
+ for file, members in perf.items():
29535
+ add('performance_in_selection', 'file', file, 'Benchmark or performance tests ran in this selection',
29536
+ sum(t['total_time_ms'] or 0 for t in members), members,
29537
+ 'Confirm these belong in an explicit performance lane (tag exclusion) rather than routine runs; keep thresholds that guard real regressions.',
29538
+ 'Regression thresholds with a documented owner', 'classification',
29539
+ {'tags': sorted({k for t in members for k, v in t['tags'].items() if v is True}), 'cost_scope': 'test duration of performance-purpose tests'})
29540
+ for file, members in http.items():
29541
+ add('http_in_tests', 'file', file, 'Tests make telemetry-visible HTTP calls',
29542
+ sum(t['signals']['http']['time_ms'] for t in members), members,
29543
+ 'Confirm each call targets a local stub. Replace live network calls with an adapter, Mox, or a recorded stub.',
29544
+ 'Contract coverage against recorded or stubbed responses',
29545
+ evidence={'requests': sum(t['signals']['http']['requests'] for t in members), 'cost_scope': 'attributed HTTP request time; overlaps test duration'})
29546
+ for file, members in noisy.items():
29547
+ add('log_noise', 'file', file, 'Passing tests emit error or high-volume logs', None, members,
29548
+ 'Assert expected logs with capture_log and quiet incidental logging. Error logs in passing tests hide real failures.',
29549
+ 'Assertions on logged behavior', 'classification',
29550
+ {'error_logs': sum(t['signals']['logs']['error'] for t in members),
29551
+ 'warning_logs': sum(t['signals']['logs']['warning'] for t in members),
29552
+ 'total_logs': sum(t['signals']['logs']['total'] for t in members), 'cost_scope': 'classification only'})
29553
+ for file, members in leaks.items():
29554
+ add('process_leak', 'file', file, 'Sync tests leave processes running', None, members,
29555
+ 'Start test processes with start_supervised! or stop them in on_exit. Leaked processes skew later tests.',
29556
+ 'Process lifecycle behavior under test', 'classification',
29557
+ {'max_process_delta': max(t['signals']['beam']['process_delta'] for t in members), 'cost_scope': 'classification only'})
29558
+ rows.sort(key=lambda r: (r['observed_cost_ms'] is None, -(r['observed_cost_ms'] or 0), r['rule_id'], r['scope_key']))
29559
+ for i, row in enumerate(rows):
29560
+ row['rank'] = i + 1
29561
+ return rows
29562
+
29563
+
29564
+ def analyze(root):
29565
+ issues = []
29566
+ snapshot = read_object(root, 'snapshot.json')
29567
+ run_id = text(snapshot.get('runId'), 80)
29568
+ if snapshot.get('version') != 'fmix-session.v1' or not re.fullmatch('[0-9a-fA-F-]{36}', run_id):
29569
+ raise ValueError('missing valid FMix snapshot identity')
29570
+ if snapshot.get('state') not in ('completed', 'failed', 'cancelled', 'abandoned'):
29571
+ issues.append('runner is not terminal')
29572
+ tests, identities, active_tests = [], set(), set()
29573
+ starts, operations, operation_issues = {}, [], []
29574
+ malformed_signals = 0
29575
+ boot_issues = []
29576
+ started = finished = None
29577
+ source = source_view(None)
29578
+ sequence = 0
29579
+ inputs = ['snapshot.json', 'artifacts/live/events.ndjson']
29580
+ for event in records(root, inputs[1], issues, optional=True):
29581
+ if event.get('run_id') != run_id:
29582
+ issues.append('mismatched run identity in test events')
29583
+ continue
29584
+ if event.get('schema') != 'ct-test-event.v2':
29585
+ issues.append('legacy or unknown event schema')
29586
+ seq = event.get('sequence')
29587
+ if type(seq) is not int or seq != sequence + 1:
29588
+ issues.append('duplicate or missing event sequence')
29589
+ if type(seq) is int:
29590
+ sequence = seq
29591
+ kind = event.get('event')
29592
+ if kind == 'test_started':
29593
+ ref = event.get('test', {})
29594
+ if not isinstance(ref, dict) or not ref.get('module') or not ref.get('name'):
29595
+ issues.append('missing started test identity')
29596
+ else:
29597
+ identity = text(ref.get('module')) + '\0' + text(ref.get('name'))
29598
+ if identity in active_tests or identity in identities:
29599
+ issues.append('duplicate test start')
29600
+ active_tests.add(identity)
29601
+ starts[identity] = seq if type(seq) is int else None
29602
+ elif kind == 'max_failures_reached':
29603
+ issues.append('max failures reached; selection did not finish')
29604
+ elif kind == 'suite_started':
29605
+ if started is not None:
29606
+ issues.append('duplicate suite start')
29607
+ started = event
29608
+ source = source_view(event.get('source'))
29609
+ elif kind == 'suite_finished':
29610
+ if finished is not None:
29611
+ issues.append('duplicate suite terminal')
29612
+ finished = event
29613
+ elif kind == 'operation_finished':
29614
+ op = operation_view(event.get('operation'), seq)
29615
+ if op is None or len(operations) >= 1024 or finished is not None:
29616
+ operation_issues.append('invalid, late or over-limit operation record')
29617
+ else:
29618
+ operations.append(op)
29619
+ elif kind == 'test_finished':
29620
+ if finished is not None:
29621
+ issues.append('test result after suite terminal')
29622
+ ref = event.get('test')
29623
+ if not isinstance(ref, dict):
29624
+ issues.append('missing test identity')
29625
+ continue
29626
+ ref = {key: text(ref.get(key)) for key in ('module', 'name', 'file')} | {
29627
+ 'line': number(ref.get('line')), 'async': event['test'].get('async') is True}
29628
+ if not ref['module'] or not ref['name']:
29629
+ issues.append('missing test identity')
29630
+ continue
29631
+ identity = ref['module'] + '\0' + ref['name']
29632
+ if identity in identities:
29633
+ issues.append('duplicate test result')
29634
+ continue
29635
+ identities.add(identity)
29636
+ active_tests.discard(identity)
29637
+ status = event.get('status')
29638
+ if status not in STATES:
29639
+ status = 'unknown'
29640
+ issues.append('test outcome is not explicit')
29641
+ total = number(event.get('total_time_ms'))
29642
+ if total is None:
29643
+ issues.append('missing or invalid test duration')
29644
+ raw_tags = event['test'].get('tags', {})
29645
+ tags = {key: value for key, value in raw_tags.items()
29646
+ if key in TAGS and (type(value) is bool or (key in ("fmix_domain", "fmix_level", "fmix_purpose") and isinstance(value, str) and len(value) <= 128))} if isinstance(raw_tags, dict) else {}
29647
+ observed = event.get('db_observed') is True
29648
+ queries = number(event.get('db_query_count')) if observed else None
29649
+ setup = number(event.get('setup_time_ms')) if event.get('setup_observed') is True else None
29650
+ signals, malformed = signals_view(event.get('signals'))
29651
+ malformed_signals += malformed
29652
+ item = {**ref, 'id': hashlib.sha256(identity.encode()).hexdigest(), 'status': status,
29653
+ 'tags': tags, 'total_time_ms': total, 'setup_time_ms': setup,
29654
+ 'cleanup_time_ms': number(event.get('cleanup_time_ms')) if event.get('cleanup_observed') is True else None,
29655
+ 'setup_percent': (100 * setup / total) if setup is not None and total else None,
29656
+ 'db_observed': observed, 'db_query_count': queries,
29657
+ 'db_query_time_ms': number(event.get('db_query_time_ms')) if observed else None,
29658
+ 'db_queue_time_ms': number(event.get('db_queue_time_ms')) if observed else None,
29659
+ 'classification': classify(ref, tags, observed, queries),
29660
+ 'event_sequence': seq if type(seq) is int else 0, 'start_sequence': starts.get(identity),
29661
+ 'setup_observed': event.get('setup_observed') is True,
29662
+ 'cleanup_observed': event.get('cleanup_observed') is True,
29663
+ 'setup_sections': measured_sections(event.get('setup_sections'), event.get('setup_observed') is True),
29664
+ 'cleanup_sections': measured_sections(event.get('cleanup_sections'), event.get('cleanup_observed') is True),
29665
+ 'signals': signals}
29666
+ tests.append(item)
29667
+ if active_tests:
29668
+ issues.append('started tests without terminal outcomes: ' + str(len(active_tests)))
29669
+ if started is None:
29670
+ issues.append('missing suite start')
29671
+ if finished is None:
29672
+ issues.append('missing suite terminal')
29673
+ if not source['commit_sha'] or not source['tree_sha'] or source['dirty'] is None:
29674
+ issues.append('source identity unavailable')
29675
+ counts = dict(Counter(t['status'] for t in tests))
29676
+ expected = finished.get('counts') if finished else None
29677
+ if not isinstance(expected, dict):
29678
+ issues.append('missing suite counts')
29679
+ elif expected.get('tests') != len(tests) or any(expected.get(key) != counts.get(status, 0) for key, status in [('failures', 'failed'), ('invalid', 'invalid'), ('skipped', 'skipped'), ('excluded', 'excluded')]):
29680
+ issues.append('suite counts do not reconcile with result events')
29681
+ executed = [t for t in tests if t['status'] in ('passed', 'failed')]
29682
+ groups = defaultdict(lambda: {'count': 0, 'executed': 0, 'test_work_ms': 0, 'observed_setup_ms': 0})
29683
+ candidates = []
29684
+ for t in tests:
29685
+ group = groups[t['classification']['domain']]
29686
+ group['count'] += 1
29687
+ if t['status'] not in ('passed', 'failed'):
29688
+ continue
29689
+ group['executed'] += 1
29690
+ group['test_work_ms'] += t['total_time_ms'] or 0
29691
+ group['observed_setup_ms'] += t['setup_time_ms'] or 0
29692
+ resource_issues = []
29693
+ samples = []
29694
+ for row in records(root, 'metrics.jsonl', resource_issues, optional=True):
29695
+ if row.get('runId') != run_id or row.get('version') != 'fmix-metric.v1':
29696
+ resource_issues.append('resource identity or schema mismatch')
29697
+ continue
29698
+ samples.append({'at': text(row.get('timestamp'), 80), 'cpu_percent': number(row.get('processCpuPercent')),
29699
+ 'rss_bytes': number(row.get('processRssBytes'))})
29700
+ raw_resources = snapshot.get('resources', {})
29701
+ resources = {'scope': 'runner_process_tree', 'samples': samples, 'issues': sorted(set(resource_issues)),
29702
+ 'note': 'CPU/RSS include concurrent runner descendants. They are not per-test CPU, allocated memory, or external PostgreSQL CPU.'}
29703
+ if isinstance(raw_resources, dict):
29704
+ for key in ('processCpuPercent', 'processRssBytes'):
29705
+ val = raw_resources.get(key, {})
29706
+ resources[key] = {metric: number(val.get(metric)) for metric in ('p50', 'p95', 'max')} if isinstance(val, dict) else {}
29707
+ resources['sampleCount'] = number(raw_resources.get('sampleCount'))
29708
+ resources['truncated'] = raw_resources.get('truncated') is True
29709
+ vm = read_object(root, 'artifacts/stats/vm_stats.json', optional=True)
29710
+ resources['beam_peak_memory_bytes'] = number((((vm or {}).get('peak') or {}).get('memory') or {}).get('total'))
29711
+ exunit_times = (finished or {}).get('exunit_times_us', {})
29712
+ exunit_times = exunit_times if isinstance(exunit_times, dict) else {}
29713
+ exunit_ms = {key: number(exunit_times.get(key)) / 1000 if number(exunit_times.get(key)) is not None else None for key in ('run', 'load', 'async')}
29714
+ raw_startup = (started or {}).get('startup_phases', {})
29715
+ startup = {key: {'duration_ms': number(value.get('duration_ms')), 'status': text(value.get('status'), 20)}
29716
+ for key, value in raw_startup.items() if re.fullmatch('[a-zA-Z0-9_-]{1,80}', key) and isinstance(value, dict)} if isinstance(raw_startup, dict) else {}
29717
+ raw_phases = snapshot.get('phases', {})
29718
+ phases = {k: number(v) for k, v in raw_phases.items() if re.fullmatch('[a-zA-Z0-9_-]{1,64}', k)} if isinstance(raw_phases, dict) else {}
29719
+ compile_info = snapshot.get('compile', {})
29720
+ compile_info = compile_info if isinstance(compile_info, dict) else {}
29721
+ op_count = (finished or {}).get('operations_count')
29722
+ op_dropped = (finished or {}).get('operations_dropped')
29723
+ op_pending = (finished or {}).get('operations_pending')
29724
+ if operations and (type(op_count) is not int or op_count != len(operations)):
29725
+ operation_issues.append('operation count does not reconcile')
29726
+ if op_count is not None and (type(op_count) is not int or op_count != len(operations)):
29727
+ operation_issues.append('operation count does not reconcile')
29728
+ if op_count is not None and (type(op_dropped) is not int or op_dropped != 0):
29729
+ operation_issues.append('operation capture was truncated or unqualified')
29730
+ if op_count is not None and (type(op_pending) is not int or op_pending != 0):
29731
+ operation_issues.append('operation starts remain unfinished or are unqualified')
29732
+ cache = snapshot.get('cache', {})
29733
+ prep_seconds = number(cache.get('overheadSeconds')) if isinstance(cache, dict) else None
29734
+ data = {'schema': 'fmix-analysis.v1', 'run_id': run_id, 'source': source,
29735
+ 'runner': {'state': text(snapshot.get('state'), 40), 'exit_code': snapshot.get('exitCode') if type(snapshot.get('exitCode')) is int else None},
29736
+ 'completeness': {'complete': not issues, 'issues': sorted(set(issues)), 'scope': 'test results: one run, one shard, one attempt'},
29737
+ 'counts': counts, 'timing': {'runner_elapsed_ms': (number(snapshot.get('durationSeconds')) or 0) * 1000,
29738
+ 'suite_elapsed_ms': number((finished or {}).get('elapsed_ms')),
29739
+ 'collector_elapsed_ms': number((finished or {}).get('elapsed_ms')),
29740
+ 'runner_preparation_ms': prep_seconds * 1000 if prep_seconds is not None else None,
29741
+ 'exunit_run_ms': exunit_ms['run'], 'exunit_load_ms': exunit_ms['load'], 'exunit_async_ms': exunit_ms['async'],
29742
+ 'startup_phases': startup,
29743
+ 'compile': {'outcome': text(compile_info.get('outcome'), 60), 'file_count': number(compile_info.get('fileCount')), 'seconds': number(compile_info.get('seconds'))},
29744
+ 'test_work_ms': sum(t['total_time_ms'] or 0 for t in executed),
29745
+ 'phases_seconds': phases},
29746
+ 'domains': [{'domain': key, **value} for key, value in sorted(groups.items(), key=lambda x: -x[1]['test_work_ms'])],
29747
+ 'tests': sorted(tests, key=lambda t: -(t['total_time_ms'] or 0)),
29748
+ 'candidates': candidates, 'resources': resources,
29749
+ 'signals': signals_summary(tests, started, malformed_signals),
29750
+ 'boot': boot_view(root, startup, boot_issues), 'fixtures': fixture_view(root, boot_issues),
29751
+ 'tag_profile': tag_profile(tests), 'profile_issues': boot_issues,
29752
+ 'operations': operations, 'operation_evidence': {'available': op_count is not None, 'complete': not operation_issues and type(op_count) is int and op_count == len(operations) and op_dropped == 0 and op_pending == 0, 'issues': sorted(set(operation_issues))},
29753
+ 'limitations': ['Single-run observations, not historical regression or flakiness estimates.',
29754
+ 'Unobserved setup and SQL remain unknown. Inferred classifications need review.',
29755
+ 'Concurrent test work cannot be summed into elapsed time. No savings are claimed.',
29756
+ 'Execution receipts and test exit status remain the authority for passing.']}
29757
+ data['hotspots'] = rank_hotspots(data)
29758
+ data['ranking_basis'] = 'Observed per-selection cost, descending; overlapping scopes are not additive. Savings and frequency are unmeasured.'
29759
+ data['candidates'] = [{'test_id': row['evidence']['test_ids'][0] if row['evidence']['test_ids'] else None,
29760
+ 'file': row['verification']['test_files'][0] if row['verification']['test_files'] else '',
29761
+ 'name': row['title'], 'action': row['recommendation'],
29762
+ 'observed_time_ms': row['observed_cost_ms'], 'savings_ms': None,
29763
+ 'confidence': row['confidence']} for row in data['hotspots']]
29764
+ return data
29765
+
29766
+
29767
+
29768
+ REPORT_ASSETS = {
29769
+ 'echarts.min.js': ('https://cdn.jsdelivr.net/npm/echarts@6.1.0/dist/echarts.min.js',
29770
+ 'sha384-C2iskrW/uPW46KzOjrvJIQo4YkV8lkD+QS0CrDN18IIPIpT/g2USu8bTP3nvmIAD'),
29771
+ 'pico.min.css': ('https://cdn.jsdelivr.net/npm/@picocss/pico@2.1.1/css/pico.min.css',
29772
+ 'sha384-L1dWfspMTHU/ApYnFiMz2QID/PlP1xCW9visvBdbEkOLkSSWsP6ZJWhPw6apiXxU'),
29773
+ }
29774
+
29775
+
29776
+ def vendored_assets(directory):
29777
+ """Read pinned report assets for offline viewing; every byte must match its SRI pin."""
29778
+ assets = {}
29779
+ for name, (_, sri) in REPORT_ASSETS.items():
29780
+ path = directory / name
29781
+ if path.is_symlink() or not path.is_file():
29782
+ raise ValueError('vendor directory is missing ' + name)
29783
+ content = path.read_bytes()
29784
+ if 'sha384-' + base64.b64encode(hashlib.sha384(content).digest()).decode() != sri:
29785
+ raise ValueError(name + ' does not match its pinned integrity hash')
29786
+ assets[name] = content
29787
+ return assets
29788
+
29789
+
29790
+ def render(data):
29791
+ # Pico CSS styles light/dark from the viewer's scheme; Apache ECharts draws charts. Both load from
29792
+ # pinned, SRI-checked CDN URLs with an assets/ fallback, and every table renders without them.
29793
+ encoded = json.dumps(data, ensure_ascii=True, allow_nan=False).replace('<', '\\u003c').replace('>', '\\u003e').replace('&', '\\u0026')
29794
+ page = '''<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light dark"><title>FMix test analysis</title>
29795
+ +<link rel="stylesheet" href="PICO_URL" integrity="PICO_SRI" crossorigin="anonymous" onerror="this.onerror=null;this.removeAttribute('integrity');this.href='assets/pico.min.css'">
29796
+ +<script src="ECHARTS_URL" integrity="ECHARTS_SRI" crossorigin="anonymous" defer></script>
29797
+ +<style>
29798
+ +:root{color-scheme:light dark;--series-1:#2a78d6;--series-2:#eb6834;--series-3:#1baf7a;--series-4:#eda100;--series-5:#e87ba4;--series-6:#008300;--series-7:#6250d6;--neutral:#8b8f96;--grid:#e2e5e9}
29799
+ +@media (prefers-color-scheme:dark){:root:where(:not([data-theme=light])){--series-1:#3987e5;--series-2:#d95926;--series-3:#199e70;--series-4:#c98500;--series-5:#d55181;--series-6:#008300;--series-7:#9085e9;--neutral:#7a7f88;--grid:#2d323a}}
29800
+ +:root[data-theme=dark]{--series-1:#3987e5;--series-2:#d95926;--series-3:#199e70;--series-4:#c98500;--series-5:#d55181;--series-6:#008300;--series-7:#9085e9;--neutral:#7a7f88;--grid:#2d323a}
29801
+ +html,body{background-color:var(--pico-background-color,Canvas);color:var(--pico-color,CanvasText)}
29802
+ +main.container{max-width:1240px;padding-top:1rem}
29803
+ +.topbar{display:flex;justify-content:space-between;align-items:flex-start;gap:1rem;flex-wrap:wrap}.topbar label{width:11rem;margin:0}
29804
+ +.tiles{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:1rem;margin-bottom:1rem}.tiles article{margin:0;padding:1rem}
29805
+ +.tile-value{font-size:1.7rem;font-weight:650;line-height:1.15;font-variant-numeric:tabular-nums}
29806
+ +.chart{width:100%;height:340px}.chart.tall{height:520px}
29807
+ +.grid2{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:1rem}.grid2>article{margin:0;min-width:0}@media(max-width:860px){.grid2{grid-template-columns:1fr}}
29808
+ +article h3{font-size:1rem;margin-bottom:.5rem}
29809
+ +.legend{display:flex;gap:1rem;flex-wrap:wrap;font-size:.85rem;margin:.25rem 0 .5rem}.legend i{display:inline-block;width:.75rem;height:.75rem;border-radius:3px;margin-right:.35rem;vertical-align:-1px}
29810
+ +.tablewrap{max-height:520px;overflow:auto}.tablewrap thead th{position:sticky;top:0;background-color:var(--pico-background-color);z-index:1}
29811
+ +td.num,th.num{text-align:right;white-space:nowrap;font-variant-numeric:tabular-nums}
29812
+ +table{font-size:.85rem}code{font-size:.75rem;overflow-wrap:break-word}.tablewrap table{min-width:640px}.tablewrap td:first-child{min-width:16rem}
29813
+ +.muted{color:var(--pico-muted-color)}.small{font-size:.85rem}
29814
+ +.fallback{display:flex;align-items:center;justify-content:center;height:100%;text-align:center;color:var(--pico-muted-color);border:1px dashed var(--pico-muted-border-color);border-radius:var(--pico-border-radius);padding:1rem}
29815
+ +.chip{display:inline-block;padding:.1rem .5rem;border:1px solid var(--pico-muted-border-color);border-radius:999px;font-size:.75rem;margin-right:.35rem}
29816
+ +.controls{display:grid;grid-template-columns:2fr 1fr 1fr 1fr;gap:.75rem}@media(max-width:860px){.controls{grid-template-columns:1fr 1fr}}
29817
+ +.hotspot header{display:flex;justify-content:space-between;gap:1rem;flex-wrap:wrap}.hotspot p{margin-bottom:.4rem}
29818
+ +</style></head><body><main class="container">
29819
+ +<div class="topbar"><hgroup><h1>FMix test analysis</h1><p id="identity" class="small"></p></hgroup><label>Theme<select id="theme" aria-label="Theme"><option value="">Match system</option><option value="light">Light</option><option value="dark">Dark</option></select></label></div>
29820
+ +<p id="status"></p><div id="issues"></div>
29821
+ +<section><h2>Where the time went</h2><p id="time-story"></p><div id="tiles" class="tiles"></div><article><div id="chart-time" class="chart" role="img" aria-label="Runner time by phase"></div><p class="muted small" id="time-note"></p></article><div class="grid2" id="boot-detail"><article><h3>Application start</h3><div id="chart-apps" class="chart" role="img" aria-label="Application start durations"></div></article><article><h3>Slowest supervisor children</h3><div id="chart-children" class="chart" role="img" aria-label="Supervisor child start durations"></div></article></div><p class="muted small" id="boot-note"></p></section><section><h2>Fixtures and tags</h2><div class="grid2"><article><h3>Most expensive fixture functions</h3><div id="chart-fixtures" class="chart" role="img" aria-label="Fixture function inclusive time"></div><p class="muted small" id="fixture-note"></p></article><article><h3>Test work by tag</h3><div id="chart-tags" class="chart" role="img" aria-label="Test work by tag"></div><p class="muted small">A test counts under every tag it carries, so bars overlap and must not be summed.</p></article></div></section>
29822
+ +<section><h2>Hot spots by domain</h2><p class="muted small">Tile area is test time. Domain, then file, then test. Click a tile to drill in. Color shows the test level.</p><div class="legend" id="level-legend"></div><article><div id="chart-treemap" class="chart tall" role="img" aria-label="Test time treemap"></div></article>
29823
+ +<div class="grid2"><article><h3>Test work by domain</h3><div class="legend level-legend"></div><div id="chart-domains" class="chart" role="img" aria-label="Test work by domain"></div></article><article><h3>Test time vs SQL queries</h3><div class="legend level-legend"></div><div id="chart-scatter" class="chart" role="img" aria-label="Test time versus SQL queries"></div><p class="muted small" id="scatter-note"></p></article></div></section>
29824
+ +<section><h2>Per-test signals</h2><p id="signals-note" class="small"></p>
29825
+ +<div class="grid2"><article><h3>SQL time by statement kind</h3><div class="legend" id="kind-legend"></div><div id="chart-sqlkind" class="chart" role="img" aria-label="SQL time by statement kind and domain"></div></article><article><h3>Top tables by SQL time</h3><div id="chart-sources" class="chart" role="img" aria-label="Top tables by SQL time"></div><p class="muted small">Summed from each test's ten heaviest sources, so these are lower bounds.</p></article>
29826
+ +<article><h3>Log volume by file</h3><div id="chart-logs" class="chart" role="img" aria-label="Log events by file"></div></article><article><h3>Side effects by file</h3><div class="tablewrap" style="max-height:340px"><table class="striped"><thead><tr><th>File</th><th class="num">DDL</th><th class="num">Error logs</th><th class="num">Oban jobs</th><th class="num">HTTP</th><th class="num">Leaked procs</th></tr></thead><tbody id="effects"></tbody></table></div></article></div></section>
29827
+ +<section><h2>Runner resources</h2><div class="grid2"><article><h3>CPU · runner process tree</h3><div id="chart-cpu" class="chart" role="img" aria-label="CPU percent over time"></div></article><article><h3>RSS · runner process tree</h3><div id="chart-rss" class="chart" role="img" aria-label="Resident memory over time"></div></article></div><p id="resource-note" class="muted small"></p></section>
29828
+ +<section><h2>Ranked hotspots</h2><p id="ranking-note" class="muted small"></p><div id="hotspots"></div></section>
29829
+ +<section><h2>Test explorer</h2><div class="controls"><input id="search" type="search" aria-label="Search tests" placeholder="Filter by name, file, domain or tag"><select id="outcome" aria-label="Outcome"><option value="">All outcomes</option><option>passed</option><option>failed</option><option>invalid</option><option>skipped</option><option>excluded</option><option>unknown</option></select><select id="level" aria-label="Level"><option value="">All levels</option><option>unit</option><option>integration</option><option value="other">other</option></select><select id="sort" aria-label="Sort metric"><option value="time">Test time</option><option value="setup">Observed setup</option><option value="sql">SQL count</option><option value="sqlms">SQL time</option><option value="logs">Log events</option><option value="reductions">Reductions (sync)</option></select></div><p id="shown" class="muted small"></p>
29830
+ +<div class="tablewrap"><table class="striped"><thead><tr><th>Test / classification</th><th>Outcome</th><th class="num">Time ms</th><th class="num">Setup ms</th><th class="num">SQL</th><th class="num">SQL ms</th><th class="num">Logs</th><th class="num">Reductions</th></tr></thead><tbody id="tests"></tbody></table></div></section>
29831
+ +<details><summary>Phase timing details</summary><pre id="phases" class="small"></pre></details>
29832
+ +<section><h2>Interpretation limits</h2><ul id="limits" class="muted small"></ul></section>
29833
+ +</main><script>
29834
+ +const d=REPORT_DATA;const $=s=>document.querySelector(s);
29835
+ +const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
29836
+ +const n=v=>v==null?'unknown':Number(v).toLocaleString(undefined,{maximumFractionDigits:2});
29837
+ +const ms=v=>v==null?'unknown':v>=1000?n(v/1000)+' s':n(v)+' ms';
29838
+ +const bytes=v=>v==null?'unknown':v>=1073741824?n(v/1073741824)+' GiB':v>=1048576?n(v/1048576)+' MiB':n(v/1024)+' KiB';
29839
+ +const css=k=>getComputedStyle(document.documentElement).getPropertyValue(k).trim();
29840
+ +const LEVELS=[['unit','Unit','--series-1'],['integration','Integration','--series-2'],['other','Other / unknown','--neutral']];
29841
+ +const KINDS=['select','insert','update','delete','ddl','transaction','other'];
29842
+ +const levelOf=t=>t.classification.level==='unit'||t.classification.level==='integration'?t.classification.level:'other';
29843
+ +const levelColor=l=>css(LEVELS.find(x=>x[0]===l)[2]);
29844
+ +const ran=d.tests.filter(t=>t.status==='passed'||t.status==='failed');
29845
+ +const sig=t=>t.signals||null;
29846
+ +const fold=(rows,key,limit,label)=>{const s=[...rows].sort((a,b)=>b[key]-a[key]);if(s.length<=limit)return s;const rest=s.slice(limit-1);const o={name:label+' ('+rest.length+')',other:true};for(const r of rest)for(const k in r)if(typeof r[k]==='number')o[k]=(o[k]||0)+r[k];return s.slice(0,limit-1).concat([o])};
29847
+ +// Text and tables render first; charts are a progressive layer.
29848
+ +$('#identity').textContent=`Run ${d.run_id} · source ${d.source.commit_sha||'unknown'} · ${d.source.dirty===true?'dirty worktree':d.source.dirty===false?'clean worktree':'cleanliness unknown'} · Elixir ${d.source.elixir||'?'} / OTP ${d.source.otp||'?'}`;
29849
+ +$('#status').innerHTML=`<span class="chip">Evidence ${d.completeness.complete?'complete':'INCOMPLETE'}</span><span class="chip">Runner ${esc(d.runner.state)} · exit ${esc(d.runner.exit_code)}</span><span class="chip">${esc(d.completeness.scope)}</span>`;
29850
+ +$('#issues').innerHTML=(d.completeness.issues.length?'<article><strong>Evidence gaps</strong><ul>'+d.completeness.issues.map(i=>'<li>'+esc(i)+'</li>').join('')+'</ul></article>':'')+(d.operation_evidence.issues.length?'<p class="muted small">Operation evidence incomplete: '+d.operation_evidence.issues.map(esc).join('; ')+'</p>':'');
29851
+ +const T=d.timing,helper=T.startup_phases?.test_helper_pre_exunit_total?.duration_ms??null;
29852
+ +const share=T.runner_elapsed_ms&&T.exunit_run_ms!=null?100*T.exunit_run_ms/T.runner_elapsed_ms:null;
29853
+ +const BOOT=d.boot&&d.boot.segments&&d.boot.segments.length?d.boot:null;
29854
+ +$('#time-story').textContent=share==null?'ExUnit run time was not recorded, so the overhead share is unknown.':`Tests ran for ${ms(T.exunit_run_ms)} of ${ms(T.runner_elapsed_ms)} runner time (${n(share)}%). Everything else is preparation and startup.`;
29855
+ +$('#tiles').innerHTML=[['Results',n(d.tests.length)],['Runner elapsed',ms(T.runner_elapsed_ms)],['ExUnit run',ms(T.exunit_run_ms)],['Cumulative test work',ms(T.test_work_ms)],['Overhead share',share==null?'unknown':n(100-share)+'%']].map(([k,v])=>`<article><div class="tile-value">${esc(v)}</div><small class="muted">${esc(k)}</small></article>`).join('');
29856
+ +$('#time-note').textContent=BOOT?`Measured boot timeline across ${ms(BOOT.window_ms)} (${BOOT.runner_marks?'runner':'no runner'} and ${BOOT.vm_marks?'VM':'no VM'} marks). ${BOOT.note}`:'No boot timeline in this run, so mix test is one block: runner phases are whole seconds, and anything not measured inside the VM shows as unattributed.';
29857
+ +$('#boot-note').textContent=BOOT&&BOOT.boot_profile?'Application and supervisor-child starts come from fmix test --profile-boot. Child times include their own children.':'Run fmix test --profile-boot to split application start into per-application and per-supervisor-child durations.';
29858
+ +$('#fixture-note').textContent=d.fixtures?d.fixtures.note+(d.fixtures.truncated?' The function list was truncated.':''):'Run fmix test --profile-fixtures to record calls and inclusive time for fixture and helper functions.';
29859
+ +if(d.profile_issues&&d.profile_issues.length)$('#issues').innerHTML+='<p class="muted small">Profile data issues: '+d.profile_issues.map(esc).join('; ')+'</p>';
29860
+ +const legendHtml=items=>items.map(([label,color])=>`<span><i style="background:${color}"></i>${esc(label)}</span>`).join('');
29861
+ +function legends(){document.querySelectorAll('#level-legend,.level-legend').forEach(el=>el.innerHTML=legendHtml(LEVELS.map(l=>[l[1],css(l[2])])));$('#kind-legend').innerHTML=legendHtml(KINDS.map((k,i)=>[k,css('--series-'+(i+1))]))}
29862
+ +const S=d.signals||{observed_tests:{},tests_with_signals:0,executed_tests:ran.length};
29863
+ +const obs=S.observed_tests||{};
29864
+ +$('#signals-note').innerHTML=S.tests_with_signals?`Signals were recorded for ${n(S.tests_with_signals)} of ${n(S.executed_tests)} executed tests. Coverage by collector: SQL ${n(obs.sql_breakdown||0)} · logs ${n(obs.logs||0)} · Oban ${n(obs.oban||0)} · HTTP ${n(obs.http||0)} · BEAM (sync tests) ${n(obs.beam||0)}.${S.collector?.logger_level?' Logger level: '+esc(S.collector.logger_level)+'; lower-level events are not counted.':''} <span class="muted">${esc(S.note||'')}</span>`:'<strong>No per-test signals in this run.</strong> <span class="muted">The collector (Cdrcisco.Test.TestSignals) was not attached, so SQL kinds, logs, Oban, HTTP and BEAM data are unknown, not zero.</span>';
29865
+ +const byFile={};for(const t of ran){const s=sig(t);if(!s)continue;const f=byFile[t.file]||(byFile[t.file]={file:t.file,ddl:0,error:0,logs:0,warning:0,oban:0,http:0,leak:0});f.ddl+=s.sql?.by_kind?.ddl?.count||0;if(s.logs){f.error+=s.logs.error;f.logs+=s.logs.total;f.warning+=s.logs.warning}f.oban+=s.oban?.jobs||0;f.http+=s.http?.requests||0;f.leak=Math.max(f.leak,s.beam?.process_delta||0)}
29866
+ +const effects=Object.values(byFile).filter(f=>f.ddl||f.error||f.oban||f.http||f.leak>0).sort((a,b)=>b.ddl-a.ddl||b.http-a.http||b.error-a.error||b.oban-a.oban).slice(0,100);
29867
+ +$('#effects').innerHTML=effects.length?effects.map(f=>`<tr><td><code>${esc(f.file)}</code></td><td class="num">${n(f.ddl)}</td><td class="num">${n(f.error)}</td><td class="num">${n(f.oban)}</td><td class="num">${n(f.http)}</td><td class="num">${n(f.leak)}</td></tr>`).join(''):`<tr><td colspan="6" class="muted">${S.tests_with_signals?'No DDL, error logs, Oban jobs, HTTP calls or leaked processes were observed.':'Not observed.'}</td></tr>`;
29868
+ +$('#resource-note').textContent=[d.resources.note,...d.resources.issues].join(' ');
29869
+ +$('#ranking-note').textContent=d.ranking_basis;
29870
+ +$('#hotspots').innerHTML=d.hotspots.length?d.hotspots.slice(0,30).map(c=>`<article class="hotspot"><header><strong>#${c.rank} ${esc(c.title)}</strong><span><span class="chip">${esc(c.scope)}</span><span class="chip">${esc(c.confidence)}</span><span class="chip">${c.observed_cost_ms==null?'classification only':ms(c.observed_cost_ms)}</span></span></header><p><code>${esc(c.scope_key)}</code></p><p>${esc(c.recommendation)}</p><p class="muted small">Keep: ${esc(c.retain)} · ${n(c.evidence.affected_tests)} affected tests</p><details><summary class="small">Evidence and focused verification</summary><pre class="small">${esc(JSON.stringify({files:c.verification.test_files,evidence:Object.fromEntries(Object.entries(c.evidence).filter(([k])=>k!=='test_ids'))},null,2))}</pre></details></article>`).join(''):'<p class="muted">No hotspot crossed a ranking threshold.</p>';
29871
+ +const metric={time:t=>t.total_time_ms,setup:t=>t.setup_time_ms,sql:t=>t.db_query_count,sqlms:t=>t.db_query_time_ms,logs:t=>sig(t)?.logs?.total,reductions:t=>sig(t)?.beam?.reductions};
29872
+ +function draw(){const term=$('#search').value.toLowerCase(),state=$('#outcome').value,level=$('#level').value,key=metric[$('#sort').value];const rows=d.tests.filter(t=>(!state||t.status===state)&&(!level||levelOf(t)===level)&&JSON.stringify([t.name,t.file,t.classification,t.tags]).toLowerCase().includes(term)).sort((a,b)=>(key(b)??-1)-(key(a)??-1));$('#shown').textContent=`${n(rows.length)} matching results; showing the first ${Math.min(200,rows.length)}. Full results are in report.json.`;$('#tests').innerHTML=rows.slice(0,200).map(t=>{const s=sig(t);return `<tr><td>${esc(t.name)}<br><code>${esc(t.file)}:${esc(t.line)}</code><br><small class="muted">${esc(t.classification.domain)} · ${esc(t.classification.level)} (${esc(t.classification.level_basis)}) · ${esc(t.classification.purpose)}${Object.keys(t.tags).length?' · '+esc(Object.keys(t.tags).join(', ')):''}</small></td><td>${esc(t.status)}</td><td class="num">${n(t.total_time_ms)}</td><td class="num">${n(t.setup_time_ms)}</td><td class="num">${n(t.db_query_count)}</td><td class="num">${n(t.db_query_time_ms)}</td><td class="num">${s?.logs?n(s.logs.total):'unknown'}</td><td class="num">${s?.beam?n(s.beam.reductions):'n/a'}</td></tr>`}).join('')}
29873
+ +['search','outcome','level','sort'].forEach(id=>document.getElementById(id).addEventListener('input',draw));draw();
29874
+ +$('#phases').textContent=JSON.stringify({runner_seconds:T.phases_seconds,compile:T.compile,helper_startup:T.startup_phases,exunit_run_ms:T.exunit_run_ms,exunit_load_ms:T.exunit_load_ms,collector_elapsed_ms:T.collector_elapsed_ms},null,2);
29875
+ +$('#limits').innerHTML=d.limitations.map(x=>'<li>'+esc(x)+'</li>').join('');
29876
+ +// Chart layer: Apache ECharts, styled from Pico tokens and a validated categorical palette.
29877
+ +const charts={};
29878
+ +function base(){const ink=css('--pico-color')||'CanvasText',muted=css('--pico-muted-color')||'GrayText',grid=css('--grid'),surface=css('--pico-background-color')||'Canvas',card=css('--pico-card-background-color')||surface;return{ink,muted,grid,surface,axis:{axisLine:{lineStyle:{color:grid}},axisTick:{show:false},axisLabel:{color:muted,fontSize:11},splitLine:{lineStyle:{color:grid}},nameTextStyle:{color:muted}},tooltip:{backgroundColor:card,borderColor:grid,textStyle:{color:ink,fontSize:12},confine:true,extraCssText:'box-shadow:none'},text:{color:ink,fontFamily:'inherit'}}}
29879
+ +const bar=(b,color)=>({color,borderRadius:[0,4,4,0],borderColor:b.surface,borderWidth:1});
29880
+ +function specs(){const b=base(),o=[];
29881
+ +let rows=[];if(BOOT){let off=0;for(const[k,v]of Object.entries(T.phases_seconds||{}))if(k!=='mix_test'&&v!=null){rows.push({name:'runner: '+k,v:v*1000,start:off,tests:false});off+=v*1000}for(const g of BOOT.segments)rows.push({name:g.name,v:g.duration_ms,start:g.start_ms+off,tests:g.tests});rows=rows.reverse()}else{for(const[k,v]of Object.entries(T.phases_seconds||{}))if(k!=='mix_test'&&v!=null)rows.push({name:'runner: '+k,v:v*1000,tests:false});const mt=T.phases_seconds?.mix_test!=null?T.phases_seconds.mix_test*1000:null;if(helper!=null)rows.push({name:'test helper startup',v:helper,tests:false});if(T.exunit_run_ms!=null)rows.push({name:'ExUnit run (the tests)',v:T.exunit_run_ms,tests:true});if(mt!=null){const rest=mt-(helper||0)-(T.exunit_run_ms||0);if(rest>0)rows.push({name:'mix test: unattributed',v:rest,tests:false})}rows.sort((a,b2)=>a.v-b2.v)}
29882
+ +document.getElementById('chart-time').style.height=Math.max(240,rows.length*26+50)+'px';
29883
+ +o.push(['chart-time',rows.length,{textStyle:b.text,grid:{left:8,right:70,top:8,bottom:24,containLabel:true},tooltip:{...b.tooltip,trigger:'item',formatter:p=>p.seriesIndex===0?'':esc(p.name)+'<br>'+ms(p.value)+(BOOT?'<br>starts at +'+ms(rows[p.dataIndex].start):'')},xAxis:{type:'value',...b.axis,axisLabel:{...b.axis.axisLabel,formatter:v=>ms(v)}},yAxis:{type:'category',data:rows.map(r=>r.name),...b.axis,splitLine:{show:false},axisLabel:{color:b.ink,fontSize:12}},series:[{type:'bar',stack:'t',silent:true,itemStyle:{color:'transparent'},data:rows.map(r=>BOOT?r.start:0)},{type:'bar',stack:'t',barMaxWidth:22,data:rows.map(r=>({value:r.v,itemStyle:bar(b,r.tests?css('--series-1'):css('--neutral'))})),label:{show:true,position:'right',color:b.muted,formatter:p=>ms(p.value)}}]}]);
29884
+ +const domains={};for(const t of ran){const dm=t.classification.domain||'unknown';const files=domains[dm]||(domains[dm]={});(files[t.file]||(files[t.file]=[])).push(t)}
29885
+ +const tree=Object.entries(domains).map(([dm,files])=>({name:dm,children:Object.entries(files).map(([file,tests])=>{const lv={};for(const t of tests)lv[levelOf(t)]=(lv[levelOf(t)]||0)+(t.total_time_ms||0);const dom=Object.entries(lv).sort((a,b2)=>b2[1]-a[1])[0][0];const leaves=tests.filter(t=>(t.total_time_ms||0)>0).sort((a,b2)=>b2.total_time_ms-a.total_time_ms);const shown=leaves.slice(0,40).map(t=>({name:t.name,value:t.total_time_ms,itemStyle:{color:levelColor(levelOf(t))},meta:t.file+':'+t.line+' · '+t.classification.level}));const rest=leaves.slice(40);if(rest.length)shown.push({name:rest.length+' more tests',value:rest.reduce((s,t)=>s+t.total_time_ms,0),itemStyle:{color:css('--neutral')}});return{name:file.split('/').slice(-2).join('/'),children:shown,itemStyle:{color:levelColor(dom)},meta:file+' · '+tests.length+' tests'}}).filter(f=>f.children.length)})).filter(x=>x.children.length);
29886
+ +o.push(['chart-treemap',tree.length,{textStyle:b.text,tooltip:{...b.tooltip,formatter:p=>`<strong>${esc(p.name)}</strong><br>${ms(p.value)}${p.data.meta?'<br><span style="opacity:.75">'+esc(p.data.meta)+'</span>':''}`},series:[{type:'treemap',data:tree,roam:false,nodeClick:'zoomToNode',leafDepth:2,width:'100%',height:'88%',top:0,breadcrumb:{show:true,bottom:0,itemStyle:{color:b.surface,borderColor:b.grid,textStyle:{color:b.ink}}},label:{show:true,color:'#fff',fontSize:11,overflow:'truncate'},upperLabel:{show:true,height:22,color:b.ink},levels:[{itemStyle:{borderColor:b.surface,borderWidth:2,gapWidth:2},upperLabel:{show:false}},{itemStyle:{borderColor:b.grid,borderWidth:4,gapWidth:2},upperLabel:{show:true,backgroundColor:'transparent'}},{itemStyle:{borderColor:b.surface,borderWidth:1,gapWidth:1}},{itemStyle:{borderColor:b.surface,borderWidth:1,gapWidth:1}}]}]}]);
29887
+ +const dl=Object.entries(domains).map(([dm,files])=>{const r={name:dm,unit:0,integration:0,other:0};for(const ts of Object.values(files))for(const t of ts)r[levelOf(t)]+=t.total_time_ms||0;r.total=r.unit+r.integration+r.other;return r});const dr=fold(dl,'total',15,'Other domains').reverse();
29888
+ +o.push(['chart-domains',dr.length,{textStyle:b.text,grid:{left:8,right:16,top:8,bottom:24,containLabel:true},tooltip:{...b.tooltip,trigger:'axis',axisPointer:{type:'shadow'},valueFormatter:v=>ms(v)},xAxis:{type:'value',...b.axis,axisLabel:{...b.axis.axisLabel,formatter:v=>ms(v)}},yAxis:{type:'category',data:dr.map(r=>r.name),...b.axis,splitLine:{show:false},axisLabel:{color:b.ink}},series:LEVELS.map(([k,label,c])=>({name:label,type:'bar',stack:'w',barMaxWidth:22,data:dr.map(r=>r[k]),itemStyle:{color:css(c),borderColor:b.surface,borderWidth:1}}))}]);
29889
+ +const pts=ran.filter(t=>t.db_observed&&t.total_time_ms!=null);$('#scatter-note').textContent=`${n(pts.length)} of ${n(ran.length)} executed tests had SQL observed. Time uses a log scale.`;
29890
+ +o.push(['chart-scatter',pts.length,{textStyle:b.text,grid:{left:8,right:16,top:16,bottom:28,containLabel:true},tooltip:{...b.tooltip,trigger:'item',formatter:p=>`<strong>${esc(p.data.t.name)}</strong><br>${esc(p.data.t.file)}<br>${ms(p.data.t.total_time_ms)} · ${n(p.data.t.db_query_count)} queries`},xAxis:{type:'log',name:'test time (ms)',nameLocation:'middle',nameGap:24,...b.axis,min:v=>Math.max(0.01,v.min)},yAxis:{type:'value',name:'SQL queries',...b.axis},series:LEVELS.map(([k,label,c])=>({name:label,type:'scatter',symbolSize:8,large:pts.length>3000,itemStyle:{color:css(c),opacity:.75,borderColor:b.surface,borderWidth:1},data:pts.filter(t=>levelOf(t)===k).map(t=>({value:[Math.max(0.01,t.total_time_ms),t.db_query_count],t}))}))}]);
29891
+ +const kd={};for(const t of ran){const s=sig(t);if(!s?.sql)continue;const dm=t.classification.domain;const r=kd[dm]||(kd[dm]={name:dm,total:0});for(const[k,v]of Object.entries(s.sql.by_kind)){r[k]=(r[k]||0)+v.time_ms;r.total+=v.time_ms}}const kr=fold(Object.values(kd),'total',12,'Other domains').reverse();
29892
+ +o.push(['chart-sqlkind',kr.length,{textStyle:b.text,grid:{left:8,right:16,top:8,bottom:24,containLabel:true},tooltip:{...b.tooltip,trigger:'axis',axisPointer:{type:'shadow'},valueFormatter:v=>ms(v)},xAxis:{type:'value',...b.axis,axisLabel:{...b.axis.axisLabel,formatter:v=>ms(v)}},yAxis:{type:'category',data:kr.map(r=>r.name),...b.axis,splitLine:{show:false},axisLabel:{color:b.ink}},series:KINDS.map((k,i)=>({name:k,type:'bar',stack:'k',barMaxWidth:22,data:kr.map(r=>r[k]||0),itemStyle:{color:css('--series-'+(i+1)),borderColor:b.surface,borderWidth:1}}))}]);
29893
+ +const src={};for(const t of ran)for(const s of sig(t)?.sql?.top_sources||[]){const r=src[s.source]||(src[s.source]={name:s.source,time:0,count:0});r.time+=s.time_ms;r.count+=s.count}const sr=Object.values(src).sort((a,b2)=>b2.time-a.time).slice(0,15).reverse();
29894
+ +o.push(['chart-sources',sr.length,{textStyle:b.text,grid:{left:8,right:60,top:8,bottom:24,containLabel:true},tooltip:{...b.tooltip,trigger:'item',formatter:p=>`<strong>${esc(p.name)}</strong><br>${ms(p.value)} · ${n(sr[p.dataIndex].count)} queries`},xAxis:{type:'value',...b.axis,axisLabel:{...b.axis.axisLabel,formatter:v=>ms(v)}},yAxis:{type:'category',data:sr.map(r=>r.name),...b.axis,splitLine:{show:false},axisLabel:{color:b.ink}},series:[{type:'bar',barMaxWidth:18,data:sr.map(r=>r.time),itemStyle:bar(b,css('--series-1')),label:{show:true,position:'right',color:b.muted,formatter:p=>ms(p.value)}}]}]);
29895
+ +const lr=Object.values(byFile).filter(f=>f.logs>0).sort((a,b2)=>b2.logs-a.logs).slice(0,15).reverse();
29896
+ +o.push(['chart-logs',lr.length,{textStyle:b.text,grid:{left:8,right:50,top:8,bottom:24,containLabel:true},tooltip:{...b.tooltip,trigger:'item',formatter:p=>{const f=lr[p.dataIndex];return `<strong>${esc(f.file)}</strong><br>${n(f.logs)} events · ${n(f.error)} error · ${n(f.warning)} warning`}},xAxis:{type:'value',...b.axis},yAxis:{type:'category',data:lr.map(f=>f.file.split('/').slice(-1)[0]),...b.axis,splitLine:{show:false},axisLabel:{color:b.ink}},series:[{type:'bar',barMaxWidth:18,data:lr.map(f=>f.logs),itemStyle:bar(b,css('--series-1')),label:{show:true,position:'right',color:b.muted}}]}]);
29897
+ +const line=(key,fmt,title)=>{const s=d.resources.samples.filter(x=>x[key]!=null&&x.at);return[s.length,{textStyle:b.text,grid:{left:8,right:16,top:16,bottom:24,containLabel:true},tooltip:{...b.tooltip,trigger:'axis',axisPointer:{type:'line',lineStyle:{color:b.muted}},valueFormatter:fmt},xAxis:{type:'time',...b.axis,splitLine:{show:false}},yAxis:{type:'value',...b.axis,axisLabel:{...b.axis.axisLabel,formatter:fmt}},series:[{name:title,type:'line',showSymbol:false,lineStyle:{width:2,color:css('--series-1')},itemStyle:{color:css('--series-1')},areaStyle:{color:css('--series-1'),opacity:.12},data:s.map(x=>[x.at,x[key]])}]}]};
29898
+ +o.push(['chart-cpu',...line('cpu_percent',v=>n(v)+'%','CPU')]);o.push(['chart-rss',...line('rss_bytes',bytes,'RSS')]);
29899
+ +const hbar=(id,rows,label,val,fmt,tip)=>o.push([id,rows.length,{textStyle:b.text,grid:{left:8,right:70,top:8,bottom:24,containLabel:true},tooltip:{...b.tooltip,trigger:'item',formatter:p=>tip(rows[rows.length-1-p.dataIndex])},xAxis:{type:'value',...b.axis,axisLabel:{...b.axis.axisLabel,formatter:fmt}},yAxis:{type:'category',data:rows.map(label).reverse(),...b.axis,splitLine:{show:false},axisLabel:{color:b.ink,width:220,overflow:'truncate'}},series:[{type:'bar',barMaxWidth:18,data:rows.map(val).reverse(),itemStyle:bar(b,css('--series-1')),label:{show:true,position:'right',color:b.muted,formatter:p=>fmt(p.value)}}]}]);
29900
+ +const apps=(d.boot?.apps||[]).slice(0,15),kids=(d.boot?.children||[]).slice(0,15);
29901
+ +hbar('chart-apps',apps,r=>r.app,r=>r.duration_ms,ms,r=>`<strong>${esc(r.app)}</strong><br>${ms(r.duration_ms)}`);
29902
+ +hbar('chart-children',kids,r=>r.child.split('.').slice(-2).join('.'),r=>r.duration_ms,ms,r=>`<strong>${esc(r.child)}</strong><br>under ${esc(r.supervisor)}<br>${ms(r.duration_ms)}`);
29903
+ +const fx=(d.fixtures?.functions||[]).slice(0,15);
29904
+ +hbar('chart-fixtures',fx,r=>r.mfa.split('.').slice(-2).join('.'),r=>r.inclusive_ms,ms,r=>`<strong>${esc(r.mfa)}</strong><br>${ms(r.inclusive_ms)} inclusive · ${n(r.calls)} calls · max ${ms(r.max_ms)}`);
29905
+ +const tg=(d.tag_profile||[]).slice(0,15);
29906
+ +hbar('chart-tags',tg,r=>r.tag,r=>r.work_ms,ms,r=>`<strong>${esc(r.tag)}</strong><br>${ms(r.work_ms)} · ${n(r.tests)} tests`);
29907
+ +return o}
29908
+ +function fallback(id,msg){const el=document.getElementById(id);if(charts[id]){charts[id].dispose();delete charts[id]}el.innerHTML=`<div class="fallback">${esc(msg)}</div>`}
29909
+ +function render(){legends();if(!window.echarts){for(const id of ['chart-time','chart-treemap','chart-domains','chart-scatter','chart-sqlkind','chart-sources','chart-logs','chart-cpu','chart-rss','chart-apps','chart-children','chart-fixtures','chart-tags'])fallback(id,'Chart library unavailable (offline?). The tables on this page and report.json hold the same data.');return}for(const[id,count,opt]of specs()){if(!count){fallback(id,'Not observed in this run.');continue}const el=document.getElementById(id);if(!charts[id]){el.innerHTML='';charts[id]=echarts.init(el,null,{renderer:'canvas'})}charts[id].setOption(opt,true)}}
29910
+ +function boot(){if(window.echarts)return render();const s=document.createElement('script');s.src='assets/echarts.min.js';s.onload=render;s.onerror=render;document.head.appendChild(s)}
29911
+ +const theme=$('#theme');try{theme.value=localStorage.getItem('fmix-theme')||''}catch(e){}
29912
+ +const applyTheme=()=>{if(theme.value)document.documentElement.dataset.theme=theme.value;else delete document.documentElement.dataset.theme;try{localStorage.setItem('fmix-theme',theme.value)}catch(e){}};applyTheme();legends();
29913
+ +theme.addEventListener('input',()=>{applyTheme();render()});matchMedia('(prefers-color-scheme: dark)').addEventListener('change',()=>render());
29914
+ +window.addEventListener('resize',()=>Object.values(charts).forEach(c=>c.resize()));
29915
+ +if(document.readyState==='complete')boot();else window.addEventListener('load',boot);
29916
+ +</script></body></html>'''
29917
+ page = page.replace('\n+', '\n')
29918
+ for placeholder, name in (('PICO', 'pico.min.css'), ('ECHARTS', 'echarts.min.js')):
29919
+ page = page.replace(placeholder + '_URL', REPORT_ASSETS[name][0]).replace(placeholder + '_SRI', REPORT_ASSETS[name][1])
29920
+ return page.replace('REPORT_DATA', encoded)
29921
+
29922
+
29923
+ def main():
29924
+ parser = argparse.ArgumentParser(prog='fmix analyze', description='Generate an offline single-run test report. Does not run tests.')
29925
+ parser.add_argument('command', choices=['report', 'hotspots'])
29926
+ group = parser.add_mutually_exclusive_group(required=True)
29927
+ group.add_argument('--run')
29928
+ group.add_argument('--run-dir', type=Path)
29929
+ parser.add_argument('--output', type=Path, help='New output directory; existing paths are never overwritten')
29930
+ parser.add_argument('--limit', type=int, default=20, help='Hotspot JSON result limit (1-100)')
29931
+ parser.add_argument('--vendor-dir', type=Path, help='Directory with pinned echarts.min.js and pico.min.css; verified copies go to <output>/assets for offline viewing')
29932
+ args = parser.parse_args()
29933
+ if not 1 <= args.limit <= 100:
29934
+ parser.error('--limit must be between 1 and 100')
29935
+ if args.command == 'report' and not args.output:
29936
+ parser.error('report requires --output')
29937
+ if args.command == 'hotspots' and args.output:
29938
+ parser.error('hotspots writes JSON to stdout; omit --output')
29939
+ if args.vendor_dir and args.command != 'report':
29940
+ parser.error('--vendor-dir applies only to report')
29941
+ if args.run and not re.fullmatch('[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}', args.run):
29942
+ parser.error('--run must be a UUID')
29943
+ root = args.run_dir or Path(os.environ.get('FMIX_HOME', str(Path.home() / '.ct-fmix'))) / 'telemetry/runs' / args.run
29944
+ if root.is_symlink():
29945
+ raise ValueError('run directory must not be a symlink')
29946
+ root = root.resolve(strict=True)
29947
+ if args.output and (args.output.exists() or args.output.is_symlink()):
29948
+ raise ValueError('output already exists; choose a new directory')
29949
+ assets = vendored_assets(args.vendor_dir) if args.vendor_dir else {}
29950
+ data = analyze(root)
29951
+ if args.command == 'hotspots':
29952
+ print(json.dumps({'schema': 'fmix-hotspots.v1', 'run_id': data['run_id'], 'source': data['source'],
29953
+ 'completeness': data['completeness'], 'operation_evidence': data['operation_evidence'],
29954
+ 'runner': data['runner'], 'counts': data['counts'], 'limitations': data['limitations'],
29955
+ 'ranking_basis': data['ranking_basis'], 'total_items': len(data['hotspots']),
29956
+ 'truncated': len(data['hotspots']) > args.limit, 'items': data['hotspots'][:args.limit]}, allow_nan=False))
29957
+ return 0 if data['completeness']['complete'] else 2
29958
+ args.output.mkdir(mode=0o700, parents=True, exist_ok=False)
29959
+ for name, content in [('report.json', json.dumps(data, indent=2, allow_nan=False) + '\n'), ('index.html', render(data))]:
29960
+ fd = os.open(args.output / name, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
29961
+ with os.fdopen(fd, 'w') as stream:
29962
+ stream.write(content)
29963
+ if assets:
29964
+ (args.output / 'assets').mkdir(mode=0o700)
29965
+ for name, content in assets.items():
29966
+ fd = os.open(args.output / 'assets' / name, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
29967
+ with os.fdopen(fd, 'wb') as stream:
29968
+ stream.write(content)
29969
+ print(json.dumps({'report': str(args.output / 'index.html'), 'results': len(data['tests']), 'complete': data['completeness']['complete']}))
29970
+ return 0 if data['completeness']['complete'] else 2
29971
+
29972
+ try:
29973
+ sys.exit(main())
29974
+ except (OSError, ValueError, TypeError, KeyError) as error:
29975
+ print('fmix analyze: ' + str(error), file=sys.stderr)
29976
+ sys.exit(2)
29977
+ FMIX_ANALYZE_PY
29978
+ }
29979
+
27429
29980
  main() {
27430
29981
  if (( $# == 0 )); then
27431
29982
  fmix_usage
@@ -27434,6 +29985,14 @@ main() {
27434
29985
 
27435
29986
  local cmd="$1"
27436
29987
  shift
29988
+ if [[ "$cmd" == "analyze" ]]; then
29989
+ cmd_analyze "$@"
29990
+ return $?
29991
+ fi
29992
+ # Automatic upgrade-on-invocation: cheap read-only TTL gate before any
29993
+ # command dispatch; the check/install runs detached and can never affect
29994
+ # this command's exit code, output contract, or artifacts.
29995
+ fmix_maybe_auto_upgrade "$cmd" "$@" || true
27437
29996
  if [[ "$cmd" == "timing" ]] && fmix_timing_help_requested "$@"; then
27438
29997
  cmd_timing "$@"
27439
29998
  return $?
@@ -27475,7 +30034,7 @@ main() {
27475
30034
  return 0
27476
30035
  fi
27477
30036
  ;;
27478
- verify-push|hook)
30037
+ verify-push|hook|runner)
27479
30038
  if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
27480
30039
  fmix_verb_help "$cmd"
27481
30040
  return 0
@@ -27493,7 +30052,7 @@ main() {
27493
30052
 
27494
30053
  if [[ "$cmd" == "cache" ]]; then
27495
30054
  fmix_prepare_home_readonly || return 1
27496
- elif [[ "$cmd" != "test" && "$cmd" != "coverage" && "$cmd" != "verify-push" && "$cmd" != "hook" ]]; then
30055
+ elif [[ "$cmd" != "test" && "$cmd" != "coverage" && "$cmd" != "verify-push" && "$cmd" != "hook" && "$cmd" != "runner" ]]; then
27497
30056
  fmix_prepare_command_home || return 1
27498
30057
  fi
27499
30058
 
@@ -27504,7 +30063,7 @@ main() {
27504
30063
  return 0
27505
30064
  fi
27506
30065
  ;;
27507
- verify-push|hook)
30066
+ verify-push|hook|runner)
27508
30067
  if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
27509
30068
  fmix_verb_help "$cmd"
27510
30069
  return 0
@@ -27529,9 +30088,10 @@ main() {
27529
30088
  self-test) cmd_self_test "$@" ;;
27530
30089
  verify-push) cmd_verify_push "$@" ;;
27531
30090
  hook) cmd_hook "$@" ;;
30091
+ runner) cmd_runner "$@" ;;
27532
30092
  *)
27533
30093
  fmix_error "Unknown command: $cmd"
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"
30094
+ fmix_error "Valid commands: test, coverage, task, format, setup, seed publish, cache explain, cache verify, ensure, doctor, status, timing, analyze, gc, install, self-test, verify-push, hook, runner, version, help"
27535
30095
  fmix_error "Run 'fmix --help' for the full manual or 'fmix help <command>' for focused usage."
27536
30096
  return 1
27537
30097
  ;;