@calltelemetry/fmix 2.7.12 → 2.7.13

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 +3095 -382
  2. package/package.json +3 -3
package/bin/fmix CHANGED
@@ -16,6 +16,7 @@
16
16
  # ./fmix status
17
17
  # ./fmix timing [--limit N] [--worktree <path>]
18
18
  # ./fmix gc [--reap] [--yes]
19
+ # ./fmix gc --artifacts-only [--json] # bounded read-only inventory; no eviction
19
20
  # ./fmix self-test
20
21
  #
21
22
 
@@ -24,7 +25,7 @@ set -uo pipefail
24
25
  # ---------------------------------------------------------------------------
25
26
  # Constants & config
26
27
  # ---------------------------------------------------------------------------
27
- FMIX_VERSION="2.7.12"
28
+ FMIX_VERSION="2.7.13"
28
29
  FMIX_HOME="${FMIX_HOME:-${HOME}/.ct-fmix}"
29
30
  FMIX_OS="$(uname -s)"
30
31
  FMIX_ARCH="$(uname -m)"
@@ -86,7 +87,13 @@ FMIX_STABLE_SEED_SCHEMA="1"
86
87
  FMIX_STABLE_SEED_COMPAT_VERSION="v1"
87
88
  FMIX_DEPENDENCY_ARTIFACT_SCHEMA="1"
88
89
  FMIX_DEPENDENCY_LANE_VERSION="v1"
89
- FMIX_DEPENDENCY_ARTIFACT_TTL_DAYS="${FMIX_DEPENDENCY_ARTIFACT_TTL_DAYS:-30}"
90
+ # REL-1244 intentionally replaces the historical 30-day *candidate* default
91
+ # with four hours. Explicit legacy day overrides still win when hours are
92
+ # absent. Neither this policy nor --yes releases artifact consumers for GC.
93
+ FMIX_DEPENDENCY_ARTIFACT_TTL_DAYS="${FMIX_DEPENDENCY_ARTIFACT_TTL_DAYS-}"
94
+ FMIX_DEPENDENCY_ARTIFACT_TTL_HOURS="${FMIX_DEPENDENCY_ARTIFACT_TTL_HOURS-}"
95
+ FMIX_TEMPLATE_TTL_HOURS="${FMIX_TEMPLATE_TTL_HOURS-}"
96
+ FMIX_ARTIFACT_TTL_DEFAULT_HOURS="4"
90
97
  FMIX_MIGRATION_DELTA_LIMIT="${FMIX_MIGRATION_DELTA_LIMIT:-50}"
91
98
  FMIX_COMPILE_HEARTBEAT="${FMIX_COMPILE_HEARTBEAT:-30}"
92
99
  FMIX_COMPILE_TIMEOUT="${FMIX_COMPILE_TIMEOUT:-900}"
@@ -150,9 +157,9 @@ fmix_realpath() {
150
157
  if command -v realpath >/dev/null 2>&1; then
151
158
  realpath "$1"
152
159
  elif command -v /usr/bin/python3 >/dev/null 2>&1; then
153
- /usr/bin/python3 -c "import os, sys; print(os.path.realpath(sys.argv[1]))" "$1"
160
+ /usr/bin/python3 -I -B -c "import os, sys; print(os.path.realpath(sys.argv[1]))" "$1"
154
161
  elif command -v python3 >/dev/null 2>&1; then
155
- python3 -c "import os, sys; print(os.path.realpath(sys.argv[1]))" "$1"
162
+ python3 -I -B -c "import os, sys; print(os.path.realpath(sys.argv[1]))" "$1"
156
163
  else
157
164
  # Last resort: resolve an existing directory through cd so the final
158
165
  # path component is canonical too. For files or non-existent paths,
@@ -300,7 +307,43 @@ FMIX_EARLY_PY
300
307
  FMIX_VERSION="$FMIX_VERSION" exec "$py_bin" -c "$bootstrap" "$0" "$@"
301
308
  }
302
309
 
303
- if [[ "${BASH_SOURCE[0]}" == "$0" \
310
+ fmix_timing_help_requested() {
311
+ # Mirror the timing parser's option arity. A value or forwarded argument
312
+ # named --help must never become a side-effect-free help request.
313
+ while (( $# > 0 )); do
314
+ case "$1" in
315
+ --json|--limit=*|--worktree=*) shift ;;
316
+ --limit|--worktree) (( $# >= 2 )) || return 1; shift 2 ;;
317
+ --help|-h) return 0 ;;
318
+ *) return 1 ;;
319
+ esac
320
+ done
321
+ return 1
322
+ }
323
+
324
+ fmix_readonly_entrypoint() {
325
+ local arg
326
+ case "${1:-}" in
327
+ ""|help|--help|-h|version|--version) return 0 ;;
328
+ timing)
329
+ shift
330
+ fmix_timing_help_requested "$@"
331
+ return $? ;;
332
+ gc)
333
+ for arg in "$@"; do
334
+ [[ "$arg" == "--artifacts-only" ]] && return 0
335
+ done
336
+ ;;
337
+ esac
338
+ case "${1:-}" in
339
+ test|coverage|task|format|setup|seed|cache|ensure|doctor|status|timing|gc|install|self-test)
340
+ [[ "${2:-}" == "--help" || "${2:-}" == "-h" ]] && return 0
341
+ ;;
342
+ esac
343
+ return 1
344
+ }
345
+
346
+ if ! fmix_readonly_entrypoint "$@" && [[ "${BASH_SOURCE[0]}" == "$0" \
304
347
  && "${FMIX_OBSERVABILITY_WORKER:-0}" != "1" \
305
348
  && "${1:-}" != "--fmix-observability-worker" \
306
349
  && "${FMIX_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}$ ]]; then
@@ -365,11 +408,16 @@ fmix_cow_clone() {
365
408
 
366
409
  _fmix_full_copy() {
367
410
  local src="$1" dst="$2"
368
- local t0 t1
411
+ local t0 t1 copy_rc=0
369
412
  t0=$(date +%s)
370
- cp -R "$src" "$dst"
413
+ cp -R "$src" "$dst" || copy_rc=$?
371
414
  t1=$(date +%s)
372
- echo " [fmix] full copy completed in $(( t1 - t0 ))s (FMIX_COPY_MODE=full)" >&2
415
+ if (( copy_rc == 0 )); then
416
+ echo " [fmix] full copy completed in $(( t1 - t0 ))s (FMIX_COPY_MODE=full)" >&2
417
+ else
418
+ fmix_error "Full copy failed (rc=$copy_rc); destination is not a proven clone."
419
+ fi
420
+ return "$copy_rc"
373
421
  }
374
422
 
375
423
  fmix_heal_cmake_nif_caches() {
@@ -3151,18 +3199,161 @@ fmix_dependency_lane_fingerprint() {
3151
3199
  return "$rc"
3152
3200
  }
3153
3201
 
3154
- fmix_dependency_artifact_dir() {
3202
+ fmix_artifact_v2_managed_entrypoint() {
3203
+ local py_bin runner managed_home="$FMIX_HOME"
3204
+ if [[ "${FMIX_SELF_TEST_MANAGED_REEXEC:-0}" == "1" \
3205
+ && " ${FUNCNAME[*]} " == *" cmd_self_test "* \
3206
+ && -n "${FMIX_SELF_TEST_RUNNER_HOME:-}" ]]; then
3207
+ managed_home="$FMIX_SELF_TEST_RUNNER_HOME"
3208
+ fi
3209
+ py_bin="$(fmix_python_bin)" || return 1
3210
+ runner="$(fmix_realpath "${BASH_SOURCE[0]}")" || return 1
3211
+ "$py_bin" -I -B - "$HOME" "$managed_home" "$0" "$runner" <<'PY'
3212
+ import hashlib,os,stat,sys
3213
+ user_home,fmix_home,entrypoint,runner=sys.argv[1:]
3214
+ uid=os.getuid(); euid=os.geteuid(); user_home=os.path.abspath(user_home); fmix_home=os.path.abspath(fmix_home)
3215
+ def reject(reason):
3216
+ print(reason,file=sys.stderr)
3217
+ raise SystemExit(1)
3218
+ if uid==0 or euid!=uid: reject("privileged_cleaner_forbidden")
3219
+ entrypoint=os.path.abspath(entrypoint)
3220
+ if os.path.realpath(user_home)!=user_home or os.path.realpath(fmix_home)!=fmix_home:
3221
+ reject("noncanonical_managed_home")
3222
+ known={user_home+"/.local/bin/fmix",user_home+"/.local/share/fmix/bin/fmix"}
3223
+ custom=os.environ.get("FMIX_INSTALL_DIR")
3224
+ if custom:
3225
+ custom=os.path.abspath(custom)
3226
+ if os.path.commonpath((user_home,custom))!=user_home: raise SystemExit(1)
3227
+ known.add(os.path.join(custom,"fmix"))
3228
+ if entrypoint not in known and entrypoint!=runner: reject("unrecognized_managed_entrypoint")
3229
+ paths=[]
3230
+ for path in sorted(known):
3231
+ if not os.path.lexists(path): continue
3232
+ parent=os.path.dirname(path)
3233
+ if os.path.commonpath((user_home,parent))!=user_home: raise SystemExit(1)
3234
+ rel=os.path.relpath(parent,user_home); current=user_home
3235
+ for part in (() if rel=="." else rel.split(os.sep)):
3236
+ current=os.path.join(current,part); s=os.lstat(current)
3237
+ if not stat.S_ISDIR(s.st_mode) or stat.S_ISLNK(s.st_mode) or s.st_uid!=uid or s.st_mode&0o022:
3238
+ reject("unsafe_launcher_parent")
3239
+ link=os.lstat(path)
3240
+ if not stat.S_ISLNK(link.st_mode) or link.st_uid!=uid or link.st_nlink!=1 or os.path.realpath(path)!=runner:
3241
+ reject("managed_launcher_mismatch")
3242
+ paths.append(path)
3243
+ if entrypoint not in paths and (entrypoint!=runner or not paths):
3244
+ reject("managed_launcher_missing")
3245
+ fd=os.open(runner,os.O_RDONLY|getattr(os,"O_NOFOLLOW",0))
3246
+ try:
3247
+ s=os.fstat(fd)
3248
+ if not stat.S_ISREG(s.st_mode) or s.st_uid!=uid or s.st_nlink!=1 or s.st_mode&0o222 or not s.st_mode&0o111 or s.st_size>4*1024*1024:
3249
+ reject("unsafe_runner_identity")
3250
+ parent=os.open(fmix_home+"/runtime",os.O_RDONLY|os.O_DIRECTORY|getattr(os,"O_NOFOLLOW",0))
3251
+ try:
3252
+ runtime=os.fstat(parent)
3253
+ if runtime.st_uid!=uid or runtime.st_dev!=s.st_dev or runtime.st_mode&0o022:
3254
+ reject("unsafe_runner_runtime")
3255
+ finally: os.close(parent)
3256
+ h=hashlib.sha256()
3257
+ for block in iter(lambda: os.read(fd,65536),b""): h.update(block)
3258
+ if runner!=fmix_home+"/runtime/fmix-"+h.hexdigest():
3259
+ reject("managed_launcher_runner_mismatch")
3260
+ finally: os.close(fd)
3261
+ PY
3262
+ }
3263
+ fmix_artifact_v2_producer_runner_is_known() {
3264
+ local digest="${1:-}" py_bin
3265
+ [[ "$digest" =~ ^[0-9a-f]{64}$ ]] || return 1
3266
+ py_bin="$(fmix_python_bin)" || return 1
3267
+ "$py_bin" -I -B - "$FMIX_HOME" "$digest" <<'PY'
3268
+ import hashlib,os,stat,sys
3269
+ home,digest=sys.argv[1:]; runtime=home+"/runtime"; path=runtime+"/fmix-"+digest
3270
+ try:
3271
+ d=os.lstat(runtime)
3272
+ if not stat.S_ISDIR(d.st_mode) or stat.S_ISLNK(d.st_mode) or d.st_uid!=os.getuid(): raise ValueError()
3273
+ with os.fdopen(os.open(path,os.O_RDONLY|getattr(os,"O_NOFOLLOW",0)),"rb") as f:
3274
+ s=os.fstat(f.fileno())
3275
+ if not stat.S_ISREG(s.st_mode) or s.st_uid!=os.getuid() or s.st_nlink!=1 or s.st_mode&0o222 or not s.st_mode&0o111 or s.st_size>4*1024*1024: raise ValueError()
3276
+ h=hashlib.sha256()
3277
+ for block in iter(lambda:f.read(65536),b""): h.update(block)
3278
+ if h.hexdigest()!=digest: raise ValueError()
3279
+ except (OSError,ValueError): raise SystemExit(1)
3280
+ PY
3281
+ }
3282
+ fmix_with_reused_artifact_lease() {
3283
+ local lock_name="${1:-}" operation="${2:-}" index
3284
+ shift 2
3285
+ if index="$(fmix_lock_find_index "$lock_name")"; then
3286
+ kill -0 "${FMIX_HELD_LOCK_KEEPER_PIDS[$index]}" 2>/dev/null || return 1
3287
+ "$operation" "$@"
3288
+ else
3289
+ fmix_with_artifact_lease "$lock_name" "$operation" "$@"
3290
+ fi
3291
+ }
3292
+ fmix_artifact_v2_prepare_directory() {
3293
+ local rel="${1:-}" py_bin
3294
+ [[ "$rel" == artifacts/v2/templates || "$rel" == quarantine/artifacts-v2/templates || "$rel" == quarantine/artifacts-v2/dependencies || "$rel" == artifact-access/v2/templates || "$rel" =~ ^artifacts/v2/dependencies/[0-9a-f]{64}$ || "$rel" =~ ^artifact-access/v2/dependencies/[0-9a-f]{64}$ ]] || return 1
3295
+ py_bin="$(fmix_python_bin)" || return 1
3296
+ "$py_bin" -I -B - "$FMIX_HOME" "$rel" <<'PY'
3297
+ import os,stat,sys
3298
+ home,rel=sys.argv[1:]; flags=os.O_RDONLY|os.O_DIRECTORY|getattr(os,"O_NOFOLLOW",0)
3299
+ if os.getuid()==0 or os.geteuid()!=os.getuid() or os.path.realpath(home)!=home: raise SystemExit(1)
3300
+ fd=os.open(home,flags)
3301
+ try:
3302
+ root=os.fstat(fd)
3303
+ if root.st_uid!=os.getuid(): raise ValueError()
3304
+ for part in rel.split("/"):
3305
+ try: os.mkdir(part,0o700,dir_fd=fd)
3306
+ except FileExistsError: pass
3307
+ child=os.open(part,flags,dir_fd=fd); info=os.fstat(child)
3308
+ if info.st_uid!=os.getuid() or info.st_dev!=root.st_dev or not stat.S_ISDIR(info.st_mode): os.close(child); raise ValueError()
3309
+ os.close(fd); fd=child
3310
+ os.fsync(fd)
3311
+ finally: os.close(fd)
3312
+ PY
3313
+ }
3314
+ fmix_dependency_artifact_v2_dir() {
3315
+ local lane="${1:-}" exact="${2:-}"
3316
+ [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
3317
+ printf '%s/artifacts/v2/dependencies/%s/%s\n' "$FMIX_HOME" "$lane" "$exact"
3318
+ }
3319
+ fmix_dependency_artifact_legacy_dir() {
3155
3320
  local lane="${1:-}" exact="${2:-}"
3156
3321
  [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
3157
3322
  printf '%s/dependency-artifacts/v1/%s/%s\n' "$FMIX_HOME" "$lane" "$exact"
3158
3323
  }
3324
+ fmix_dependency_artifact_dir() {
3325
+ local lane="${1:-}" exact="${2:-}" v2
3326
+ [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
3327
+ v2="$(fmix_dependency_artifact_v2_dir "$lane" "$exact")" || return 1
3328
+ if [[ -e "$v2" || -L "$v2" ]]; then printf '%s\n' "$v2"
3329
+ else fmix_dependency_artifact_legacy_dir "$lane" "$exact"; fi
3330
+ }
3159
3331
 
3160
3332
  fmix_touch_dependency_artifact_access() {
3161
- local lane="${1:-}" exact="${2:-}" root access tmp
3333
+ local lane="${1:-}" exact="${2:-}" lock_name index
3162
3334
  [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
3163
- root="$FMIX_HOME/dependency-artifact-access/$lane"
3335
+ lock_name="dependency-artifact-${lane:0:16}-${exact:0:16}"
3336
+ if index="$(fmix_lock_find_index "$lock_name")"; then
3337
+ kill -0 "${FMIX_HELD_LOCK_KEEPER_PIDS[$index]}" 2>/dev/null || return 1
3338
+ _fmix_touch_dependency_artifact_access_locked "$lane" "$exact"
3339
+ else
3340
+ fmix_with_artifact_lease "$lock_name" _fmix_touch_dependency_artifact_access_locked "$lane" "$exact"
3341
+ fi
3342
+ }
3343
+
3344
+ _fmix_touch_dependency_artifact_access_locked() {
3345
+ local lane="${1:-}" exact="${2:-}" root access tmp artifact
3346
+ [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
3347
+ artifact="$FMIX_HOME/artifacts/v2/dependencies/$lane/$exact"
3348
+ if [[ -e "$artifact" || -L "$artifact" ]]; then
3349
+ fmix_artifact_v2_managed_entrypoint || return 1
3350
+ root="$FMIX_HOME/artifact-access/v2/dependencies/$lane"
3351
+ fmix_artifact_v2_prepare_directory "artifact-access/v2/dependencies/$lane" || return 1
3352
+ else
3353
+ root="$FMIX_HOME/dependency-artifact-access/$lane"
3354
+ mkdir -p "$root" || return 1
3355
+ fi
3164
3356
  access="$root/$exact"
3165
- mkdir -p "$root" || return 1
3166
3357
  tmp="$(mktemp "${access}.tmp.XXXXXX")" || return 1
3167
3358
  printf '%s\n' "$(fmix_now)" >"$tmp" || { rm -f "$tmp"; return 1; }
3168
3359
  mv "$tmp" "$access" || { rm -f "$tmp"; return 1; }
@@ -3218,11 +3409,11 @@ PY
3218
3409
 
3219
3410
  fmix_dependency_artifact_meta_matches() {
3220
3411
  local artifact="${1:-}" expected_lane="${2:-}" expected_exact="${3:-}"
3221
- local py_bin
3412
+ local py_bin validation_output
3222
3413
  (( $# == 3 )) || return 1
3223
3414
  py_bin="$(fmix_python_bin)"
3224
- "$py_bin" - "$artifact/meta.json" "$FMIX_DEPENDENCY_ARTIFACT_SCHEMA" \
3225
- "$expected_lane" "$expected_exact" <<'PY'
3415
+ validation_output="$("$py_bin" - "$artifact/meta.json" \
3416
+ "$FMIX_DEPENDENCY_ARTIFACT_SCHEMA" "$expected_lane" "$expected_exact" <<'PY'
3226
3417
  import json
3227
3418
  import re
3228
3419
  import sys
@@ -3242,13 +3433,16 @@ try:
3242
3433
  except (OSError, ValueError, json.JSONDecodeError):
3243
3434
  raise SystemExit(1)
3244
3435
 
3436
+ is_v2 = "/artifacts/v2/dependencies/" in path
3245
3437
  required = {
3246
3438
  "schema", "lane", "dependency_fingerprint", "producer_sha",
3247
3439
  "source_clean", "manifest_sha256", "built_at",
3248
3440
  }
3441
+ if is_v2:
3442
+ required |= {"producer_runner_sha256", "consumer_protocol"}
3249
3443
  if set(data) != required:
3250
3444
  raise SystemExit(1)
3251
- if data["schema"] != schema or data["lane"] != lane:
3445
+ if data["schema"] != ("2" if is_v2 else schema) or data["lane"] != lane:
3252
3446
  raise SystemExit(1)
3253
3447
  if data["dependency_fingerprint"] != exact:
3254
3448
  raise SystemExit(1)
@@ -3260,7 +3454,16 @@ if not re.fullmatch(r"[0-9a-f]{64}", data["manifest_sha256"]):
3260
3454
  raise SystemExit(1)
3261
3455
  if not isinstance(data["built_at"], str) or not data["built_at"]:
3262
3456
  raise SystemExit(1)
3457
+ if is_v2 and (not re.fullmatch(r"[0-9a-f]{64}", data["producer_runner_sha256"])
3458
+ or data["consumer_protocol"] != "fmix-native-artifacts.v2"):
3459
+ raise SystemExit(1)
3263
3460
  PY
3461
+ )" || return 1
3462
+ if [[ "$artifact" == "$FMIX_HOME/artifacts/v2/dependencies/"* ]]; then
3463
+ local producer_runner_sha
3464
+ producer_runner_sha="$(fmix_read_state "$artifact/meta.json" producer_runner_sha256)" || return 1
3465
+ fmix_artifact_v2_producer_runner_is_known "$producer_runner_sha" || return 1
3466
+ fi
3264
3467
  }
3265
3468
 
3266
3469
  fmix_dependency_artifact_quick_ready() {
@@ -3275,10 +3478,21 @@ fmix_dependency_artifact_quick_ready() {
3275
3478
  && ! -L "$artifact/_build" \
3276
3479
  && ! -L "$artifact/_build/test" \
3277
3480
  && ! -L "$artifact/_build/test/lib" ]] || return 1
3481
+ if [[ "$artifact" == "$FMIX_HOME/artifacts/v2/dependencies/"* ]]; then
3482
+ fmix_artifact_v2_managed_entrypoint || return 1
3483
+ local producer_runner_sha
3484
+ producer_runner_sha="$(fmix_read_state "$artifact/meta.json" producer_runner_sha256)" || return 1
3485
+ fmix_artifact_v2_producer_runner_is_known "$producer_runner_sha" || return 1
3486
+ fi
3278
3487
  [[ -f "$artifact/meta.json" && ! -L "$artifact/meta.json" ]] || return 1
3279
3488
  [[ -f "$artifact/manifest.tsv" && ! -L "$artifact/manifest.tsv" ]] || return 1
3280
3489
  [[ -f "$artifact/manifest.sha256" && ! -L "$artifact/manifest.sha256" ]] || return 1
3281
- fmix_dependency_artifact_meta_matches "$artifact" "$lane" "$exact"
3490
+ if [[ "$artifact" == "$FMIX_HOME/artifacts/v2/dependencies/"* ]]; then
3491
+ fmix_artifact_v2_managed_entrypoint || return 1
3492
+ fmix_dependency_artifact_verify_full "$artifact" "$lane" "$exact"
3493
+ else
3494
+ fmix_dependency_artifact_meta_matches "$artifact" "$lane" "$exact"
3495
+ fi
3282
3496
  }
3283
3497
 
3284
3498
  fmix_dependency_artifact_is_complete() {
@@ -3313,7 +3527,7 @@ fmix_dependency_artifact_is_complete() {
3313
3527
  fi
3314
3528
  }
3315
3529
 
3316
- fmix_dependency_artifact_verify_full() {
3530
+ fmix_dependency_artifact_verify_full_unleased() {
3317
3531
  local artifact="${1:-}" lane="${2:-}" exact="${3:-}" expected actual
3318
3532
  fmix_dependency_artifact_is_complete "$artifact" "$lane" "$exact" || return 1
3319
3533
  IFS= read -r expected <"$artifact/manifest.sha256"
@@ -3321,13 +3535,29 @@ fmix_dependency_artifact_verify_full() {
3321
3535
  [[ "$actual" == "$expected" ]]
3322
3536
  }
3323
3537
 
3538
+ fmix_dependency_artifact_verify_full() {
3539
+ local artifact="${1:-}" lane="${2:-}" exact="${3:-}" lock_name index
3540
+ if [[ "$artifact" != "$FMIX_HOME/artifacts/v2/dependencies/"* ]]; then
3541
+ fmix_dependency_artifact_verify_full_unleased "$@"
3542
+ return $?
3543
+ fi
3544
+ fmix_artifact_v2_managed_entrypoint || return 1
3545
+ lock_name="dependency-artifact-${lane:0:16}-${exact:0:16}"
3546
+ if index="$(fmix_lock_find_index "$lock_name")"; then
3547
+ kill -0 "${FMIX_HELD_LOCK_KEEPER_PIDS[$index]}" 2>/dev/null || return 1
3548
+ fmix_dependency_artifact_verify_full_unleased "$@"
3549
+ else
3550
+ fmix_with_artifact_lease "$lock_name" fmix_dependency_artifact_verify_full_unleased "$@"
3551
+ fi
3552
+ }
3553
+
3324
3554
  fmix_dependency_artifact_quarantine() {
3325
3555
  local artifact="${1:-}" reason="${2:-invalid dependency artifact}" destination
3326
- [[ "$artifact" == "$FMIX_HOME/dependency-artifacts/v1/"* ]] || return 1
3556
+ [[ "$artifact" == "$FMIX_HOME/artifacts/v2/dependencies/"* ]] || return 1
3327
3557
  [[ -e "$artifact" || -L "$artifact" ]] || return 0
3328
- destination="$FMIX_HOME/quarantine/dependency-artifacts/$(basename "$(dirname "$artifact")")-$(basename "$artifact").$(fmix_epoch).$$.${RANDOM}"
3329
- mkdir -p "$(dirname "$destination")" || return 1
3330
- [[ ! -d "$artifact" || -L "$artifact" ]] || chmod u+w "$artifact" 2>/dev/null || return 1
3558
+ destination="$FMIX_HOME/quarantine/artifacts-v2/dependencies/$(basename "$(dirname "$artifact")")-$(basename "$artifact").$(fmix_epoch).$$.${RANDOM}"
3559
+ fmix_dependency_artifact_path_is_owned "$artifact" || return 1
3560
+ fmix_artifact_v2_prepare_directory "quarantine/artifacts-v2/dependencies" || return 1
3331
3561
  if mv "$artifact" "$destination"; then
3332
3562
  fmix_warn "Quarantined dependency artifact ($reason): $destination"
3333
3563
  return 0
@@ -4295,12 +4525,122 @@ fmix_seed_publish() {
4295
4525
  return $?
4296
4526
  }
4297
4527
 
4528
+ fmix_cache_filesystem_bytes() {
4529
+ local py_bin
4530
+ py_bin="$(fmix_python_bin)" || return 1
4531
+ "$py_bin" -I -B - "$FMIX_HOME" <<'PY'
4532
+ import os, stat, sys
4533
+ path = sys.argv[1]
4534
+ try:
4535
+ before = os.lstat(path)
4536
+ if (not stat.S_ISDIR(before.st_mode) or before.st_uid != os.getuid()
4537
+ or os.path.realpath(path) != path):
4538
+ raise ValueError()
4539
+ capacity = os.statvfs(path)
4540
+ after = os.lstat(path)
4541
+ if (before.st_dev, before.st_ino) != (after.st_dev, after.st_ino):
4542
+ raise ValueError()
4543
+ print(capacity.f_bavail * capacity.f_frsize, capacity.f_blocks * capacity.f_frsize)
4544
+ except (OSError, ValueError):
4545
+ raise SystemExit(1)
4546
+ PY
4547
+ }
4548
+
4549
+ fmix_optional_cache_has_headroom() {
4550
+ # Advisory prevention for optional extra cache copies, not a host quota.
4551
+ # No environment/CLI bypass; tests replace the capacity provider only in
4552
+ # their isolated sourced library. Actual cache hits allocate no new copy.
4553
+ # Canonical ordinary roots are a publication invariant; supported contained
4554
+ # nested links are materialized and counted, not authority to alias a root.
4555
+ local capacity free total estimate py_bin
4556
+ capacity="$(fmix_cache_filesystem_bytes)" || return 3
4557
+ read -r free total <<<"$capacity"
4558
+ [[ "$free" =~ ^[0-9]+$ && "$total" =~ ^[0-9]+$ \
4559
+ && ${#free} -le 15 && ${#total} -le 15 ]] || return 3
4560
+ (( free <= total && total > 0 )) || return 3
4561
+ py_bin="$(fmix_python_bin)" || return 3
4562
+ estimate="$("$py_bin" -I -B - "$@" <<'PY'
4563
+ import os, stat, sys
4564
+ try:
4565
+ if not 1 <= len(sys.argv[1:]) <= 2:
4566
+ raise ValueError()
4567
+ for path in sys.argv[1:]:
4568
+ info = os.lstat(path)
4569
+ if (not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid()
4570
+ or os.path.realpath(path) != path):
4571
+ raise ValueError()
4572
+ # Publication materializes permitted links with cp -RL. Count every
4573
+ # transport occurrence (not unique inodes or allocated source blocks),
4574
+ # including repeated link targets. Cycles/drift/unknown types hold.
4575
+ import time
4576
+ deadline = time.monotonic() + 5
4577
+ remaining = 200000
4578
+ total = 0
4579
+ def identity(info):
4580
+ return (info.st_dev, info.st_ino, info.st_uid, info.st_mode,
4581
+ info.st_size, info.st_mtime_ns, info.st_ctime_ns)
4582
+ def measure(path, ancestors):
4583
+ global remaining, total
4584
+ remaining -= 1
4585
+ if remaining < 0 or time.monotonic() > deadline:
4586
+ raise ValueError()
4587
+ link_before = os.lstat(path)
4588
+ before = os.stat(path)
4589
+ if link_before.st_uid != os.getuid() or before.st_uid != os.getuid():
4590
+ raise ValueError()
4591
+ if stat.S_ISREG(before.st_mode):
4592
+ total += ((before.st_size + 4095) // 4096) * 4096 + 4096
4593
+ elif stat.S_ISDIR(before.st_mode):
4594
+ key = (before.st_dev, before.st_ino)
4595
+ if key in ancestors:
4596
+ raise ValueError()
4597
+ total += 4096
4598
+ with os.scandir(path) as iterator:
4599
+ for entry in iterator:
4600
+ measure(os.path.join(path, entry.name), ancestors | {key})
4601
+ else:
4602
+ raise ValueError()
4603
+ if identity(before) != identity(os.stat(path)) or identity(link_before) != identity(os.lstat(path)):
4604
+ raise ValueError()
4605
+ for path in sys.argv[1:]:
4606
+ measure(path, set())
4607
+ print(total)
4608
+ except (OSError, ValueError, RecursionError):
4609
+ raise SystemExit(1)
4610
+ PY
4611
+ )" || return 3
4612
+ [[ "$estimate" =~ ^[0-9]+$ && ${#estimate} -le 15 ]] || return 3
4613
+ # Tiny metadata-sized fixture/cache copies retain the existing emergency
4614
+ # floor. Real dependency copies (>1 MiB) preserve a 10% / 200 GB buffer.
4615
+ local floor=$(( total / 10 ))
4616
+ (( floor <= 200000000000 )) || floor=200000000000
4617
+ if (( estimate <= 1048576 )); then
4618
+ floor=$(( total / 40 ))
4619
+ (( floor <= 50000000000 )) || floor=50000000000
4620
+ fi
4621
+ (( free >= floor && estimate <= free - floor )) || return 3
4622
+ return 0
4623
+ }
4624
+
4298
4625
  fmix_publish_dependency_artifact() {
4626
+ local worktree="${1:-}" expected="${2:-}" lane
4627
+ (( $# == 2 )) || return 1
4628
+ [[ "$expected" =~ ^[0-9a-f]{64}$ ]] || return 1
4629
+ lane="$(fmix_dependency_lane_fingerprint "$worktree")" || return 1
4630
+ [[ "$lane" =~ ^[0-9a-f]{64}$ ]] || return 1
4631
+ fmix_with_artifact_lease "dependency-artifact-${lane:0:16}-${expected:0:16}" \
4632
+ _fmix_publish_dependency_artifact_locked "$@"
4633
+ }
4634
+
4635
+ _fmix_publish_dependency_artifact_locked() {
4299
4636
  # Publish only after the active dependency stamp proves the exact key.
4300
4637
  # This cache is automatic and commit-agnostic; producer_sha is selection
4301
4638
  # metadata for future reconciliation, never part of exact-hit validity.
4302
- local worktree="${1:-}" expected_exact="${2:-}" real lane artifact parent tmp
4303
- local deps_root build_root build_lib producer_sha source_clean source_status manifest_sha
4639
+ # rc=3 holds a miss before publication. Other nonzero results may follow
4640
+ # verified publication (access refresh/release failure); callers preserve
4641
+ # the session and must not infer payload absence or erase the generation.
4642
+ local worktree="${1:-}" expected_exact="${2:-}" real lane artifact legacy_artifact parent tmp
4643
+ local deps_root build_root build_lib producer_sha source_clean source_status manifest_sha runner_sha
4304
4644
  local lock_name child child_name current_exact current_lane writable
4305
4645
  (( $# == 2 )) || return 1
4306
4646
  [[ "$expected_exact" =~ ^[0-9a-f]{64}$ ]] || return 1
@@ -4309,53 +4649,55 @@ fmix_publish_dependency_artifact() {
4309
4649
  [[ "$current_exact" == "$expected_exact" ]] || return 1
4310
4650
  fmix_dependency_stamp_matches "$real" "$expected_exact" || return 1
4311
4651
  lane="$(fmix_dependency_lane_fingerprint "$real")" || return 1
4312
- artifact="$(fmix_dependency_artifact_dir "$lane" "$expected_exact")" || return 1
4652
+ artifact="$(fmix_dependency_artifact_v2_dir "$lane" "$expected_exact")" || return 1
4653
+ legacy_artifact="$(fmix_dependency_artifact_legacy_dir "$lane" "$expected_exact")" || return 1
4313
4654
  lock_name="dependency-artifact-${lane:0:16}-${expected_exact:0:16}"
4314
- fmix_lock_acquire "$lock_name" "$FMIX_LOCK_TIMEOUT" \
4315
- "exact dependency artifact" || return $?
4316
-
4317
4655
  if fmix_dependency_artifact_verify_full "$artifact" "$lane" "$expected_exact"; then
4656
+ fmix_artifact_v2_managed_entrypoint || return 3
4318
4657
  fmix_touch_dependency_artifact_access "$lane" "$expected_exact" \
4319
- >/dev/null 2>&1 || true
4320
- fmix_command_lock_finish "$lock_name" 0
4321
- return $?
4658
+ >/dev/null 2>&1 || return $?
4659
+ return 0
4322
4660
  fi
4323
- if [[ -e "$artifact" || -L "$artifact" ]]; then
4324
- fmix_dependency_artifact_quarantine "$artifact" \
4325
- "failed exact integrity verification" || {
4326
- fmix_command_lock_finish "$lock_name" 1
4327
- return $?
4328
- }
4661
+ if fmix_dependency_artifact_verify_full "$legacy_artifact" "$lane" "$expected_exact"; then
4662
+ fmix_touch_dependency_artifact_access "$lane" "$expected_exact" \
4663
+ >/dev/null 2>&1 || return $?
4664
+ return 0
4329
4665
  fi
4330
-
4331
- fmix_session_normalize_links "$real" || {
4332
- fmix_command_lock_finish "$lock_name" 1
4333
- return $?
4334
- }
4335
4666
  deps_root="$(fmix_session_deps_root "$real")" || {
4336
- fmix_command_lock_finish "$lock_name" 1
4337
- return $?
4667
+ return 1
4338
4668
  }
4339
4669
  build_root="$(fmix_compile_build_root "$real")" || {
4340
- fmix_command_lock_finish "$lock_name" 1
4341
- return $?
4670
+ return 1
4342
4671
  }
4672
+ fmix_session_normalize_links "$real" || return 1
4343
4673
  build_lib="$build_root/test/lib"
4344
4674
  if ! fmix_stable_seed_artifacts_are_safe \
4345
4675
  "$deps_root" "$build_lib" 1 "$real" "$build_root"; then
4346
- fmix_command_lock_finish "$lock_name" 1
4347
- return $?
4676
+ return 1
4677
+ fi
4678
+ if ! fmix_optional_cache_has_headroom "$deps_root" "$build_lib"; then
4679
+ fmix_warn "Optional dependency-cache publication held by disk pressure or incomplete capacity observation; preserving and reusing the proven session."
4680
+ return 3
4681
+ fi
4682
+ if [[ -e "$artifact" || -L "$artifact" ]]; then
4683
+ fmix_dependency_artifact_quarantine "$artifact" \
4684
+ "failed exact integrity verification" || {
4685
+ return 1
4686
+ }
4348
4687
  fi
4349
4688
  producer_sha="$(git -C "$real" rev-parse --verify 'HEAD^{commit}' 2>/dev/null)" \
4350
4689
  || producer_sha=""
4351
4690
  [[ "$producer_sha" =~ ^[0-9a-f]{40}$ ]] || {
4352
- fmix_command_lock_finish "$lock_name" 1
4353
- return $?
4691
+ return 1
4354
4692
  }
4693
+ if ! fmix_artifact_v2_managed_entrypoint; then
4694
+ fmix_warn "Optional dependency publication held because the managed runner handoff is unproven; keeping the current session."
4695
+ return 3
4696
+ fi
4697
+ runner_sha="$(fmix_hash_stdin <"$(fmix_realpath "${BASH_SOURCE[0]}")")" || return 1
4355
4698
  source_status="$(git -C "$real" status --porcelain --untracked-files=all 2>/dev/null)" \
4356
4699
  || {
4357
- fmix_command_lock_finish "$lock_name" 1
4358
- return $?
4700
+ return 1
4359
4701
  }
4360
4702
  if [[ -z "$source_status" ]]; then
4361
4703
  source_clean=true
@@ -4363,21 +4705,15 @@ fmix_publish_dependency_artifact() {
4363
4705
  source_clean=false
4364
4706
  fi
4365
4707
 
4366
- parent="$(dirname "$artifact")"
4367
- mkdir -p "$parent" || {
4368
- fmix_command_lock_finish "$lock_name" 1
4369
- return $?
4370
- }
4708
+ fmix_artifact_v2_prepare_directory "artifacts/v2/dependencies/$lane" || return 1
4371
4709
  tmp="${artifact}.tmp-$$-${RANDOM}"
4372
4710
  if [[ -e "$tmp" || -L "$tmp" ]] || ! mkdir "$tmp"; then
4373
- fmix_command_lock_finish "$lock_name" 1
4374
- return $?
4711
+ return 1
4375
4712
  fi
4376
4713
  if ! fmix_stable_seed_clone_tree "$deps_root" "$tmp/deps" 2>/dev/null \
4377
4714
  || ! mkdir -p "$tmp/_build/test/lib"; then
4378
4715
  rm -rf "$tmp" 2>/dev/null || true
4379
- fmix_command_lock_finish "$lock_name" 1
4380
- return $?
4716
+ return 1
4381
4717
  fi
4382
4718
  for child in "$build_lib"/*; do
4383
4719
  [[ -e "$child" || -L "$child" ]] || continue
@@ -4386,36 +4722,34 @@ fmix_publish_dependency_artifact() {
4386
4722
  if ! fmix_stable_seed_clone_tree \
4387
4723
  "$child" "$tmp/_build/test/lib/$child_name" 2>/dev/null; then
4388
4724
  rm -rf "$tmp" 2>/dev/null || true
4389
- fmix_command_lock_finish "$lock_name" 1
4390
- return $?
4725
+ return 1
4391
4726
  fi
4392
4727
  done
4393
4728
  manifest_sha="$(fmix_dependency_artifact_manifest_digest \
4394
4729
  "$tmp" "$tmp/manifest.tsv")" || {
4395
4730
  rm -rf "$tmp" 2>/dev/null || true
4396
- fmix_command_lock_finish "$lock_name" 1
4397
- return $?
4731
+ return 1
4398
4732
  }
4399
4733
  printf '%s\n' "$manifest_sha" >"$tmp/manifest.sha256" || {
4400
4734
  rm -rf "$tmp" 2>/dev/null || true
4401
- fmix_command_lock_finish "$lock_name" 1
4402
- return $?
4735
+ return 1
4403
4736
  }
4404
4737
  if ! cat >"$tmp/meta.json" <<EOF
4405
4738
  {
4406
- "schema": "$FMIX_DEPENDENCY_ARTIFACT_SCHEMA",
4739
+ "schema": "2",
4407
4740
  "lane": "$lane",
4408
4741
  "dependency_fingerprint": "$expected_exact",
4409
4742
  "producer_sha": "$producer_sha",
4410
4743
  "source_clean": "$source_clean",
4411
4744
  "manifest_sha256": "$manifest_sha",
4412
- "built_at": "$(fmix_now)"
4745
+ "built_at": "$(fmix_now)",
4746
+ "producer_runner_sha256": "$runner_sha",
4747
+ "consumer_protocol": "fmix-native-artifacts.v2"
4413
4748
  }
4414
4749
  EOF
4415
4750
  then
4416
4751
  rm -rf "$tmp" 2>/dev/null || true
4417
- fmix_command_lock_finish "$lock_name" 1
4418
- return $?
4752
+ return 1
4419
4753
  fi
4420
4754
  current_exact="$(fmix_compute_dependency_fingerprint "$real")" || current_exact=""
4421
4755
  current_lane="$(fmix_dependency_lane_fingerprint "$real")" || current_lane=""
@@ -4424,75 +4758,91 @@ EOF
4424
4758
  || ! fmix_dependency_artifact_is_complete \
4425
4759
  "$tmp" "$lane" "$expected_exact" 1; then
4426
4760
  rm -rf "$tmp" 2>/dev/null || true
4427
- fmix_command_lock_finish "$lock_name" 1
4428
- return $?
4761
+ return 1
4429
4762
  fi
4430
4763
  chmod -R a-w "$tmp" || {
4431
4764
  rm -rf "$tmp" 2>/dev/null || true
4432
- fmix_command_lock_finish "$lock_name" 1
4433
- return $?
4765
+ return 1
4434
4766
  }
4435
4767
  chmod u+w "$tmp" || {
4436
4768
  rm -rf "$tmp" 2>/dev/null || true
4437
- fmix_command_lock_finish "$lock_name" 1
4438
- return $?
4769
+ return 1
4439
4770
  }
4440
4771
  writable="$(find "$tmp" -mindepth 1 -perm -u+w -print -quit 2>/dev/null)" \
4441
4772
  || writable=invalid
4773
+ if ! fmix_artifact_v2_managed_entrypoint; then
4774
+ rm -rf "$tmp" 2>/dev/null || true
4775
+ fmix_warn "Optional dependency publication held after launcher handoff changed; keeping the current session."
4776
+ return 3
4777
+ fi
4442
4778
  if [[ -n "$writable" || -e "$artifact" || -L "$artifact" ]] \
4443
4779
  || ! mv "$tmp" "$artifact"; then
4444
4780
  rm -rf "$tmp" 2>/dev/null || true
4445
- fmix_command_lock_finish "$lock_name" 1
4446
- return $?
4781
+ return 1
4447
4782
  fi
4448
4783
  chmod a-w "$artifact" || {
4449
4784
  fmix_dependency_artifact_quarantine "$artifact" \
4450
4785
  "could not seal exact publication" >/dev/null 2>&1 || true
4451
- fmix_command_lock_finish "$lock_name" 1
4452
- return $?
4786
+ return 1
4453
4787
  }
4454
4788
  if ! fmix_dependency_artifact_verify_full \
4455
4789
  "$artifact" "$lane" "$expected_exact"; then
4456
4790
  fmix_dependency_artifact_quarantine "$artifact" \
4457
4791
  "post-publication verification failed" >/dev/null 2>&1 || true
4458
- fmix_command_lock_finish "$lock_name" 1
4459
- return $?
4792
+ return 1
4460
4793
  fi
4461
4794
  fmix_touch_dependency_artifact_access "$lane" "$expected_exact" \
4462
- >/dev/null 2>&1 || true
4463
- fmix_command_lock_finish "$lock_name" 0 || return $?
4795
+ >/dev/null 2>&1 || return $?
4796
+ if ! fmix_artifact_v2_managed_entrypoint; then
4797
+ fmix_warn "Dependency generation published, but the launcher handoff changed; preserving the generation and current session."
4798
+ return 3
4799
+ fi
4464
4800
  fmix_info "Published immutable exact dependency artifact."
4465
4801
  return 0
4466
4802
  }
4467
4803
 
4804
+ fmix_dependency_reconciler_distance() {
4805
+ local candidate="$1" worktree="$2" lane="$3" exact="$4" head="$5"
4806
+ local candidate_exact producer clean distance
4807
+ candidate_exact="$(basename "$candidate")"
4808
+ fmix_dependency_artifact_path_is_owned "$candidate" || return 1
4809
+ fmix_dependency_artifact_verify_full "$candidate" "$lane" "$candidate_exact" || return 1
4810
+ clean="$(fmix_read_state "$candidate/meta.json" source_clean)"
4811
+ [[ "$clean" == "true" ]] || return 1
4812
+ producer="$(fmix_read_state "$candidate/meta.json" producer_sha)"
4813
+ [[ "$producer" =~ ^[0-9a-f]{40}$ ]] || return 1
4814
+ git -C "$worktree" merge-base --is-ancestor "$producer" "$head" >/dev/null 2>&1 || return 1
4815
+ distance="$(git -C "$worktree" rev-list --count "$producer..$head" 2>/dev/null)" || return 1
4816
+ [[ "$distance" =~ ^[0-9]+$ ]] || return 1
4817
+ printf '%s\n' "$distance"
4818
+ }
4819
+
4468
4820
  fmix_find_dependency_reconciler() {
4469
- local worktree="${1:-}" lane="${2:-}" exact="${3:-}" root head
4470
- local candidate candidate_exact producer clean distance selected="" selected_distance=""
4821
+ local worktree="${1:-}" lane="${2:-}" exact="${3:-}" root head distance
4822
+ local candidate candidate_exact selected="" selected_distance=""
4823
+ local -a roots=()
4471
4824
  (( $# == 3 )) || return 1
4472
- root="$FMIX_HOME/dependency-artifacts/v1/$lane"
4473
- [[ -d "$root" && ! -L "$root" ]] || return 1
4825
+ [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
4826
+ roots=("$FMIX_HOME/artifacts/v2/dependencies/$lane"
4827
+ "$FMIX_HOME/dependency-artifacts/v1/$lane")
4474
4828
  head="$(git -C "$worktree" rev-parse --verify 'HEAD^{commit}' 2>/dev/null)" \
4475
4829
  || return 1
4476
- for candidate in "$root"/*; do
4830
+ for root in "${roots[@]}"; do
4831
+ [[ -d "$root" && ! -L "$root" ]] || continue
4832
+ for candidate in "$root"/*; do
4477
4833
  [[ -d "$candidate" && ! -L "$candidate" ]] || continue
4478
4834
  candidate_exact="$(basename "$candidate")"
4479
4835
  [[ "$candidate_exact" =~ ^[0-9a-f]{64}$ && "$candidate_exact" != "$exact" ]] \
4480
4836
  || continue
4481
- fmix_dependency_artifact_is_complete \
4482
- "$candidate" "$lane" "$candidate_exact" || continue
4483
- clean="$(fmix_read_state "$candidate/meta.json" source_clean)"
4484
- [[ "$clean" == "true" ]] || continue
4485
- producer="$(fmix_read_state "$candidate/meta.json" producer_sha)"
4486
- [[ "$producer" =~ ^[0-9a-f]{40}$ ]] || continue
4487
- git -C "$worktree" merge-base --is-ancestor "$producer" "$head" \
4488
- >/dev/null 2>&1 || continue
4489
- distance="$(git -C "$worktree" rev-list --count "$producer..$head" 2>/dev/null)" \
4490
- || continue
4491
- [[ "$distance" =~ ^[0-9]+$ ]] || continue
4837
+ distance="$(fmix_with_reused_artifact_lease \
4838
+ "dependency-artifact-${lane:0:16}-${candidate_exact:0:16}" \
4839
+ fmix_dependency_reconciler_distance "$candidate" "$worktree" \
4840
+ "$lane" "$exact" "$head")" || continue
4492
4841
  if [[ -z "$selected_distance" || "$distance" -lt "$selected_distance" ]]; then
4493
4842
  selected="$candidate"
4494
4843
  selected_distance="$distance"
4495
4844
  fi
4845
+ done
4496
4846
  done
4497
4847
  [[ -n "$selected" ]] || return 1
4498
4848
  printf '%s\n' "$selected"
@@ -4503,17 +4853,140 @@ _fmix_dependency_install_interrupt() {
4503
4853
  dependency_install_interrupt_rc="${1:-130}"
4504
4854
  }
4505
4855
 
4856
+ fmix_effective_artifact_ttl_hours() {
4857
+ local pool="${1:-}" value legacy
4858
+ case "$pool" in
4859
+ dependency)
4860
+ value="${FMIX_DEPENDENCY_ARTIFACT_TTL_HOURS-}"
4861
+ legacy="${FMIX_DEPENDENCY_ARTIFACT_TTL_DAYS-}"
4862
+ if [[ -z "$value" && -n "$legacy" ]]; then
4863
+ [[ "$legacy" =~ ^[0-9]+$ && ${#legacy} -le 3 ]] \
4864
+ && (( 10#$legacy <= 365 )) || {
4865
+ fmix_error "Dependency cache TTL days must be an integer from 0 to 365."
4866
+ return 2
4867
+ }
4868
+ printf '%s\n' "$(( 10#$legacy * 24 ))"
4869
+ return 0
4870
+ fi ;;
4871
+ template) value="${FMIX_TEMPLATE_TTL_HOURS-}" ;;
4872
+ *) return 2 ;;
4873
+ esac
4874
+ value="${value:-$FMIX_ARTIFACT_TTL_DEFAULT_HOURS}"
4875
+ [[ "$value" =~ ^[0-9]+$ && ${#value} -le 4 ]] \
4876
+ && (( 10#$value <= 8760 )) || {
4877
+ fmix_error "Artifact cache TTL hours must be an integer from 0 to 8760."
4878
+ return 2
4879
+ }
4880
+ printf '%s\n' "$(( 10#$value ))"
4881
+ }
4882
+
4883
+ fmix_with_artifact_lease() {
4884
+ # Readers use the publisher's existing kernel/mixed-version lease for the
4885
+ # entire verification, copy and access refresh. Never nest or steal leases.
4886
+ local lock_name="$1" operation="$2" operation_rc=0 release_rc=0 acquire_rc=0
4887
+ FMIX_ARTIFACT_LEASE_RELEASE_FAILED=0
4888
+ shift 2
4889
+ fmix_lock_acquire "$lock_name" "$FMIX_LOCK_TIMEOUT" "artifact reader" \
4890
+ || acquire_rc=$?
4891
+ if (( acquire_rc != 0 )); then
4892
+ fmix_lock_failure_is_fatal "$acquire_rc" && return 70
4893
+ return "$acquire_rc"
4894
+ fi
4895
+ "$operation" "$@" || operation_rc=$?
4896
+ fmix_lock_release "$lock_name" || release_rc=$?
4897
+ if (( release_rc != 0 )); then
4898
+ FMIX_ARTIFACT_LEASE_RELEASE_FAILED=1
4899
+ printf '{"error":"artifact_lock_cleanup_failed","operation_exit_code":%d,"cleanup_exit_code":%d}\n' \
4900
+ "$operation_rc" "$release_rc" >&2
4901
+ fmix_error "Artifact reader release failed (operation rc=$operation_rc, release rc=$release_rc)."
4902
+ fi
4903
+ (( operation_rc == 0 )) || return "$operation_rc"
4904
+ (( release_rc == 0 )) || return "$release_rc"
4905
+ return 0
4906
+ }
4907
+
4908
+ fmix_with_artifact_reference_lease() {
4909
+ local lock_name="$1" operation="$2" index
4910
+ shift 2
4911
+ if index="$(fmix_lock_find_index "$lock_name")"; then
4912
+ kill -0 "${FMIX_HELD_LOCK_KEEPER_PIDS[$index]}" 2>/dev/null || return 70
4913
+ "$operation" "$@"
4914
+ else
4915
+ fmix_with_artifact_lease "$lock_name" "$operation" "$@"
4916
+ fi
4917
+ }
4918
+
4506
4919
  fmix_install_dependency_artifact() {
4920
+ local artifact="${2:-}" lane exact
4921
+ (( $# == 3 )) || return 1
4922
+ lane="$(basename "$(dirname "$artifact")")"
4923
+ exact="$(basename "$artifact")"
4924
+ [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
4925
+ [[ "$artifact" == "$FMIX_HOME/dependency-artifacts/v1/$lane/$exact" \
4926
+ || "$artifact" == "$FMIX_HOME/artifacts/v2/dependencies/$lane/$exact" ]] || return 1
4927
+ fmix_dependency_artifact_path_is_owned "$artifact" || return 1
4928
+ fmix_with_artifact_lease "dependency-artifact-${lane:0:16}-${exact:0:16}" \
4929
+ _fmix_install_dependency_artifact_locked "$@"
4930
+ }
4931
+
4932
+ fmix_dependency_artifact_path_is_owned() {
4933
+ # Every generation ancestor must belong to this home's lease namespace.
4934
+ # Final-component checks and lexical containment do not reject lane aliases.
4935
+ local py_bin
4936
+ py_bin="$(fmix_python_bin)" || return 1
4937
+ "$py_bin" -I -B - "$FMIX_HOME" "$1" <<'PY'
4938
+ import os, re, stat, sys
4939
+ home, artifact = sys.argv[1:]
4940
+ fd = None
4941
+ try:
4942
+ if os.path.realpath(home) != home:
4943
+ raise ValueError()
4944
+ if artifact.startswith(home + "/dependency-artifacts/v1/"):
4945
+ suffix = artifact[len(home + "/dependency-artifacts/v1/"):]
4946
+ components = ("dependency-artifacts", "v1", *suffix.split("/"))
4947
+ elif artifact.startswith(home + "/artifacts/v2/dependencies/"):
4948
+ suffix = artifact[len(home + "/artifacts/v2/dependencies/"):]
4949
+ components = ("artifacts", "v2", "dependencies", *suffix.split("/"))
4950
+ else:
4951
+ raise ValueError()
4952
+ if not re.fullmatch(r"[0-9a-f]{64}/[0-9a-f]{64}", suffix):
4953
+ raise ValueError()
4954
+ flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
4955
+ fd = os.open(home, flags)
4956
+ device = os.fstat(fd).st_dev
4957
+ if os.fstat(fd).st_uid != os.getuid():
4958
+ raise ValueError()
4959
+ for component in components:
4960
+ child = os.open(component, flags, dir_fd=fd)
4961
+ os.close(fd)
4962
+ fd = child
4963
+ info = os.fstat(fd)
4964
+ if info.st_uid != os.getuid() or info.st_dev != device or not stat.S_ISDIR(info.st_mode):
4965
+ raise ValueError()
4966
+ except (OSError, ValueError):
4967
+ raise SystemExit(1)
4968
+ finally:
4969
+ if fd is not None:
4970
+ os.close(fd)
4971
+ PY
4972
+ }
4973
+
4974
+ _fmix_install_dependency_artifact_locked() {
4507
4975
  # Install into mutable session staging. exact=1 establishes an exact
4508
4976
  # dependency stamp. exact=0 is explicitly unproven builder input and
4509
4977
  # removes both stamps so Mix must reconcile and publish a new exact key.
4510
4978
  local worktree="${1:-}" artifact="${2:-}" exact_mode="${3:-0}"
4511
4979
  local real deps_root build_root target_lib stage retired artifact_exact lane
4512
- local dep_stamp compile_stamp installed_deps=0 installed_lib=0
4980
+ local dep_stamp compile_stamp staged_manifest installed_deps=0 installed_lib=0
4981
+ local attempted_deps=0 attempted_lib=0 stamp_attempted=0 rollback_failed=0
4513
4982
  local had_deps=0 had_lib=0 had_dep_stamp=0 had_compile_stamp=0 ok=0 switch_failed=0
4514
4983
  local dependency_install_interrupted=0 dependency_install_interrupt_rc=0
4515
4984
  local saved_trap_int saved_trap_term saved_trap_hup
4516
4985
  (( $# == 3 )) || return 1
4986
+ fmix_dependency_artifact_path_is_owned "$artifact" || return 1
4987
+ if [[ "$artifact" == "$FMIX_HOME/artifacts/v2/dependencies/"* ]]; then
4988
+ fmix_artifact_v2_managed_entrypoint || return 3
4989
+ fi
4517
4990
  [[ "$exact_mode" == "0" || "$exact_mode" == "1" ]] || return 1
4518
4991
  [[ -n "$FMIX_ACTIVE_SESSION_ROOT" ]] || return 1
4519
4992
  real="$(fmix_realpath "$worktree")" || return 1
@@ -4530,10 +5003,10 @@ fmix_install_dependency_artifact() {
4530
5003
  mkdir -p "$build_root/test" || return 1
4531
5004
  [[ ! -L "$build_root" && ! -L "$build_root/test" \
4532
5005
  && ! -L "$target_lib" ]] || return 1
4533
- stage="$FMIX_ACTIVE_SESSION_ROOT/.dependency-install-$$-${RANDOM}"
5006
+ stage="$(mktemp -d "$FMIX_ACTIVE_SESSION_ROOT/.dependency-install.XXXXXX")" || return 1
4534
5007
  retired="$stage/retired"
4535
- mkdir -p "$stage/new-lib" "$retired" || return 1
4536
- if ! fmix_cow_clone "$artifact/deps" "$stage/new-deps"; then
5008
+ mkdir -p "$stage/new/_build/test/lib" "$retired" || return 1
5009
+ if ! fmix_cow_clone "$artifact/deps" "$stage/new/deps"; then
4537
5010
  rm -rf "$stage" 2>/dev/null || true
4538
5011
  return 1
4539
5012
  fi
@@ -4541,24 +5014,44 @@ fmix_install_dependency_artifact() {
4541
5014
  for child in "$artifact/_build/test/lib"/*; do
4542
5015
  [[ -e "$child" || -L "$child" ]] || continue
4543
5016
  child_name="$(basename "$child")"
4544
- if ! fmix_cow_clone "$child" "$stage/new-lib/$child_name"; then
5017
+ if ! fmix_cow_clone "$child" "$stage/new/_build/test/lib/$child_name"; then
4545
5018
  rm -rf "$stage" 2>/dev/null || true
4546
5019
  return 1
4547
5020
  fi
4548
5021
  done
5022
+ # Prove the staged transport before adding the mutable application build.
5023
+ staged_manifest="$(fmix_dependency_artifact_manifest_digest \
5024
+ "$stage/new" "$stage/new/manifest.tsv")" || {
5025
+ rm -rf "$stage" 2>/dev/null || true
5026
+ return 1
5027
+ }
5028
+ if [[ "$staged_manifest" != "$(fmix_read_state "$artifact/meta.json" manifest_sha256)" ]]; then
5029
+ rm -rf "$stage" 2>/dev/null || true
5030
+ return 1
5031
+ fi
4549
5032
  # Preserve the application build as a mutable incremental candidate. It
4550
5033
  # remains independently guarded by the compile fingerprint and is never
4551
5034
  # included in the shared dependency artifact.
4552
5035
  if [[ -d "$target_lib/cdrcisco" && ! -L "$target_lib/cdrcisco" ]]; then
4553
- if ! fmix_cow_clone "$target_lib/cdrcisco" "$stage/new-lib/cdrcisco"; then
5036
+ if ! fmix_cow_clone "$target_lib/cdrcisco" "$stage/new/_build/test/lib/cdrcisco"; then
4554
5037
  rm -rf "$stage" 2>/dev/null || true
4555
5038
  return 1
4556
5039
  fi
4557
5040
  fi
4558
- chmod -R u+w "$stage/new-deps" "$stage/new-lib" || {
5041
+ chmod -R u+w "$stage/new/deps" "$stage/new/_build/test/lib" || {
4559
5042
  rm -rf "$stage" 2>/dev/null || true
4560
5043
  return 1
4561
5044
  }
5045
+ if [[ "$artifact" == "$FMIX_HOME/artifacts/v2/dependencies/"* ]]; then
5046
+ if ! fmix_artifact_v2_managed_entrypoint; then
5047
+ rm -rf "$stage" 2>/dev/null || true
5048
+ return 3
5049
+ fi
5050
+ if ! fmix_dependency_artifact_verify_full "$artifact" "$lane" "$artifact_exact"; then
5051
+ rm -rf "$stage" 2>/dev/null || true
5052
+ return 1
5053
+ fi
5054
+ fi
4562
5055
 
4563
5056
  dep_stamp="$(fmix_dependency_stamp_file "$real")"
4564
5057
  compile_stamp="$(fmix_compile_stamp_file "$real")"
@@ -4598,42 +5091,75 @@ fmix_install_dependency_artifact() {
4598
5091
  fi
4599
5092
  fi
4600
5093
 
4601
- if (( switch_failed == 0 && dependency_install_interrupted == 0 )) \
4602
- && mv "$stage/new-deps" "$deps_root"; then
4603
- installed_deps=1
4604
- if (( dependency_install_interrupted == 0 )) \
4605
- && mv "$stage/new-lib" "$target_lib"; then
5094
+ if (( switch_failed == 0 && dependency_install_interrupted == 0 )); then
5095
+ attempted_deps=1
5096
+ if mv "$stage/new/deps" "$deps_root"; then installed_deps=1; else switch_failed=1; fi
5097
+ fi
5098
+ if (( switch_failed == 0 && dependency_install_interrupted == 0 )); then
5099
+ attempted_lib=1
5100
+ if mv "$stage/new/_build/test/lib" "$target_lib"; then
4606
5101
  installed_lib=1
4607
5102
  if [[ "$exact_mode" == "1" ]]; then
5103
+ stamp_attempted=1
4608
5104
  if (( dependency_install_interrupted == 0 )) \
4609
5105
  && fmix_write_dependency_stamp "$real" "$artifact_exact" \
4610
- && fmix_dependency_stamp_matches "$real" "$artifact_exact"; then
5106
+ && fmix_dependency_stamp_matches "$real" "$artifact_exact" \
5107
+ && (( dependency_install_interrupted == 0 )); then
4611
5108
  ok=1
4612
5109
  fi
4613
5110
  else
4614
5111
  if (( dependency_install_interrupted == 0 )) \
4615
- && [[ ! -e "$dep_stamp" && ! -e "$compile_stamp" ]]; then
5112
+ && [[ ! -e "$dep_stamp" && ! -e "$compile_stamp" ]] \
5113
+ && (( dependency_install_interrupted == 0 )); then
4616
5114
  ok=1
4617
5115
  fi
4618
5116
  fi
4619
5117
  fi
4620
5118
  fi
4621
5119
 
4622
- if (( ok == 0 )); then
4623
- (( installed_deps == 0 )) || rm -rf "$deps_root" 2>/dev/null || true
4624
- (( installed_lib == 0 )) || rm -rf "$target_lib" 2>/dev/null || true
4625
- (( had_deps == 0 )) || mv "$retired/deps" "$deps_root" 2>/dev/null || true
4626
- (( had_lib == 0 )) || mv "$retired/lib" "$target_lib" 2>/dev/null || true
4627
- rm -f "$dep_stamp" 2>/dev/null || true
4628
- (( had_dep_stamp == 0 )) \
4629
- || mv "$retired/dependency-stamp.json" "$dep_stamp" 2>/dev/null || true
4630
- (( had_compile_stamp == 0 )) \
4631
- || mv "$retired/compile-stamp.json" "$compile_stamp" 2>/dev/null || true
4632
- rm -rf "$stage" 2>/dev/null || true
5120
+ if (( ok == 0 || dependency_install_interrupted != 0 )); then
5121
+ [[ ! -e "$retired/deps" && ! -L "$retired/deps" ]] || had_deps=1
5122
+ [[ ! -e "$retired/lib" && ! -L "$retired/lib" ]] || had_lib=1
5123
+ [[ ! -e "$retired/dependency-stamp.json" && ! -L "$retired/dependency-stamp.json" ]] || had_dep_stamp=1
5124
+ [[ ! -e "$retired/compile-stamp.json" && ! -L "$retired/compile-stamp.json" ]] || had_compile_stamp=1
5125
+ if (( attempted_deps != 0 )) && [[ ! -e "$stage/new/deps" && ! -L "$stage/new/deps" \
5126
+ && ( -e "$deps_root" || -L "$deps_root" ) ]]; then installed_deps=1; fi
5127
+ if (( attempted_lib != 0 )) && [[ ! -e "$stage/new/_build/test/lib" && ! -L "$stage/new/_build/test/lib" \
5128
+ && ( -e "$target_lib" || -L "$target_lib" ) ]]; then installed_lib=1; fi
5129
+ (( installed_deps == 0 )) || rm -rf "$deps_root" || rollback_failed=1
5130
+ (( installed_lib == 0 )) || rm -rf "$target_lib" || rollback_failed=1
5131
+ if (( had_deps != 0 )); then
5132
+ if [[ ! -e "$deps_root" && ! -L "$deps_root" ]]; then
5133
+ mv "$retired/deps" "$deps_root" || rollback_failed=1
5134
+ else rollback_failed=1; fi
5135
+ fi
5136
+ if (( had_lib != 0 )); then
5137
+ if [[ ! -e "$target_lib" && ! -L "$target_lib" ]]; then
5138
+ mv "$retired/lib" "$target_lib" || rollback_failed=1
5139
+ else rollback_failed=1; fi
5140
+ fi
5141
+ if (( stamp_attempted != 0 || had_dep_stamp != 0 )); then
5142
+ rm -f "$dep_stamp" || rollback_failed=1
5143
+ fi
5144
+ if (( had_dep_stamp != 0 )); then
5145
+ if [[ ! -e "$dep_stamp" && ! -L "$dep_stamp" ]]; then
5146
+ mv "$retired/dependency-stamp.json" "$dep_stamp" || rollback_failed=1
5147
+ else rollback_failed=1; fi
5148
+ fi
5149
+ if (( had_compile_stamp != 0 )); then
5150
+ if [[ ! -e "$compile_stamp" && ! -L "$compile_stamp" ]]; then
5151
+ mv "$retired/compile-stamp.json" "$compile_stamp" || rollback_failed=1
5152
+ else rollback_failed=1; fi
5153
+ fi
4633
5154
  trap - INT TERM HUP
4634
5155
  [[ -n "$saved_trap_int" ]] && eval "$saved_trap_int"
4635
5156
  [[ -n "$saved_trap_term" ]] && eval "$saved_trap_term"
4636
5157
  [[ -n "$saved_trap_hup" ]] && eval "$saved_trap_hup"
5158
+ if (( rollback_failed != 0 )); then
5159
+ fmix_error "Dependency replacement rollback incomplete; preserving recovery inputs: $stage"
5160
+ return 2
5161
+ fi
5162
+ rm -rf "$stage" || fmix_warn "Owned dependency staging remains: $stage"
4637
5163
  (( dependency_install_interrupted == 0 )) \
4638
5164
  || return "$dependency_install_interrupt_rc"
4639
5165
  return 1
@@ -4646,11 +5172,12 @@ fmix_install_dependency_artifact() {
4646
5172
  [[ -n "$saved_trap_hup" ]] && eval "$saved_trap_hup"
4647
5173
  (( dependency_install_interrupted == 0 )) \
4648
5174
  || return "$dependency_install_interrupt_rc"
5175
+ fmix_touch_dependency_artifact_access "$lane" "$artifact_exact" || return 1
4649
5176
  return 0
4650
5177
  }
4651
5178
 
4652
5179
  fmix_prepare_dependency_artifacts() {
4653
- local worktree="${1:-}" exact lane artifact reconciler reconciler_exact
5180
+ local worktree="${1:-}" exact lane artifact reconciler reconciler_exact install_rc
4654
5181
  (( $# == 1 )) || return 1
4655
5182
  exact="$(fmix_compute_dependency_fingerprint "$worktree")" || return 1
4656
5183
  if fmix_dependency_stamp_matches "$worktree" "$exact"; then
@@ -4659,30 +5186,32 @@ fmix_prepare_dependency_artifacts() {
4659
5186
  lane="$(fmix_dependency_lane_fingerprint "$worktree")" || return 1
4660
5187
  artifact="$(fmix_dependency_artifact_dir "$lane" "$exact")" || return 1
4661
5188
  if [[ -e "$artifact" || -L "$artifact" ]]; then
4662
- if fmix_dependency_artifact_verify_full "$artifact" "$lane" "$exact"; then
4663
- if fmix_install_dependency_artifact "$worktree" "$artifact" 1; then
4664
- fmix_touch_dependency_artifact_access "$lane" "$exact" \
4665
- >/dev/null 2>&1 || true
4666
- fmix_info "Exact dependency artifact hit — skipping dependency resolution and compilation."
4667
- return 0
4668
- fi
4669
- fmix_warn "Exact dependency artifact could not be installed; rebuilding it."
5189
+ if fmix_install_dependency_artifact "$worktree" "$artifact" 1; then
5190
+ fmix_info "Exact dependency artifact hit — skipping dependency resolution and compilation."
5191
+ return 0
4670
5192
  else
4671
- fmix_dependency_artifact_quarantine "$artifact" \
4672
- "consumer integrity verification failed" || return 1
5193
+ install_rc=$?
5194
+ case "$install_rc" in 2|129|130|143) return "$install_rc" ;; esac
5195
+ fmix_lock_failure_is_fatal "$install_rc" && return 70
5196
+ [[ "${FMIX_ARTIFACT_LEASE_RELEASE_FAILED:-0}" == "0" ]] || return "$install_rc"
5197
+ # Consumers must not quarantine a generation on an unlocked probe:
5198
+ # a concurrent publisher may have replaced it. The leased producer
5199
+ # handles corrupt entries before publishing their replacement.
5200
+ fmix_warn "Exact dependency artifact failed verification; rebuilding under its publisher lease."
4673
5201
  fi
4674
5202
  fi
4675
5203
  if reconciler="$(fmix_find_dependency_reconciler \
4676
5204
  "$worktree" "$lane" "$exact" 2>/dev/null)"; then
4677
5205
  reconciler_exact="$(basename "$reconciler")"
4678
- if fmix_dependency_artifact_verify_full \
4679
- "$reconciler" "$lane" "$reconciler_exact" \
4680
- && fmix_install_dependency_artifact "$worktree" "$reconciler" 0; then
4681
- fmix_touch_dependency_artifact_access "$lane" "$reconciler_exact" \
4682
- >/dev/null 2>&1 || true
5206
+ if fmix_install_dependency_artifact "$worktree" "$reconciler" 0; then
4683
5207
  fmix_info "Seeded dependency reconciliation from the closest proven ancestor."
4684
5208
  fmix_info "This is builder input, not an exact cache hit; Mix must publish the new fingerprint."
4685
5209
  return 0
5210
+ else
5211
+ install_rc=$?
5212
+ case "$install_rc" in 2|129|130|143) return "$install_rc" ;; esac
5213
+ fmix_lock_failure_is_fatal "$install_rc" && return 70
5214
+ [[ "${FMIX_ARTIFACT_LEASE_RELEASE_FAILED:-0}" == "0" ]] || return "$install_rc"
4686
5215
  fi
4687
5216
  fmix_warn "Ancestor dependency seed was unusable; continuing with a cold dependency build."
4688
5217
  fi
@@ -4790,6 +5319,12 @@ fmix_artifact_state_file() {
4790
5319
  }
4791
5320
 
4792
5321
  fmix_write_artifact_state() {
5322
+ (( $# == 2 )) || return 1
5323
+ [[ "$2" =~ ^[0-9a-f]{16}$ ]] || return 1
5324
+ fmix_with_artifact_reference_lease "build-$2" _fmix_write_artifact_state_locked "$@"
5325
+ }
5326
+
5327
+ _fmix_write_artifact_state_locked() {
4793
5328
  local worktree="$1" template_key="$2" real state tmp
4794
5329
  local base_key=""
4795
5330
  [[ "$template_key" =~ ^[0-9a-f]{16}$ ]] || return 1
@@ -4880,6 +5415,15 @@ fmix_read_state() {
4880
5415
  }
4881
5416
 
4882
5417
  fmix_write_worktree_state() {
5418
+ local key="${2:-}"
5419
+ if [[ "$key" =~ ^[0-9a-f]{16}$ ]]; then
5420
+ fmix_with_artifact_reference_lease "build-$key" _fmix_write_worktree_state_locked "$@"
5421
+ else
5422
+ _fmix_write_worktree_state_locked "$@"
5423
+ fi
5424
+ }
5425
+
5426
+ _fmix_write_worktree_state_locked() {
4883
5427
  local worktree="$1" template_key="$2" db_name="$3"
4884
5428
  local mig_stamp="$4" last_used="$5"
4885
5429
  local db_schema_key="${6:-}" db_base_id="${7:-}" db_source_schema_key="${8:-${6:-}}"
@@ -4925,7 +5469,9 @@ fmix_update_last_used() {
4925
5469
 
4926
5470
  fmix_read_template_meta() {
4927
5471
  local key="$1" field="$2"
4928
- local meta="$FMIX_HOME/templates/$key/meta.json"
5472
+ local tdir meta
5473
+ tdir="$(fmix_template_dir "$key")" || return 1
5474
+ meta="$tdir/meta.json"
4929
5475
  [[ -f "$meta" ]] || return 1
4930
5476
  grep -o "\"${field}\"[[:space:]]*:[[:space:]]*\"[^\"]*\"" "$meta" 2>/dev/null \
4931
5477
  | head -1 | sed 's/.*: *"\(.*\)".*/\1/'
@@ -4936,32 +5482,70 @@ fmix_write_template_meta() {
4936
5482
  # Callers must pass the full directory path as $1 (not the key).
4937
5483
  local dir="$1" status="$2" built_at="$3" toolchain="$4" source_commit="$5"
4938
5484
  local template_key="${6:-}" manifest_sha="${7:-}"
4939
- local meta="$dir/meta.json"
5485
+ local meta="$dir/meta.json" schema="$FMIX_TEMPLATE_SCHEMA" runner_sha="" extra=""
5486
+ if [[ "$dir" == "$FMIX_HOME/artifacts/v2/templates/"* ]]; then
5487
+ runner_sha="$(fmix_hash_stdin <"$(fmix_realpath "${BASH_SOURCE[0]}")")" || return 1
5488
+ schema=2
5489
+ printf -v extra ' "producer_runner_sha256": "%s",\n "consumer_protocol": "fmix-native-artifacts.v2",' "$runner_sha"
5490
+ fi
4940
5491
  mkdir -p "$dir"
4941
5492
  cat >"$meta" <<EOF
4942
5493
  {
4943
- "schema": "$FMIX_TEMPLATE_SCHEMA",
5494
+ "schema": "$schema",
4944
5495
  "status": $(fmix_json_escape "$status"),
4945
5496
  "template_key": $(fmix_json_escape "$template_key"),
4946
5497
  "manifest_sha256": $(fmix_json_escape "$manifest_sha"),
4947
5498
  "built_at": $(fmix_json_escape "$built_at"),
4948
5499
  "toolchain": $(fmix_json_escape "$toolchain"),
5500
+ $extra
4949
5501
  "source_commit": $(fmix_json_escape "$source_commit")
4950
5502
  }
4951
5503
  EOF
4952
5504
  }
4953
5505
 
4954
5506
  fmix_template_access_file() {
4955
- printf '%s/template-access/%s\n' "$FMIX_HOME" "$1"
5507
+ local key="${1:-}" v2
5508
+ v2="$(fmix_template_v2_dir "$key")" || return 1
5509
+ if [[ -e "$v2" || -L "$v2" ]]; then
5510
+ printf '%s/artifact-access/v2/templates/%s\n' "$FMIX_HOME" "$key"
5511
+ else
5512
+ printf '%s/template-access/%s\n' "$FMIX_HOME" "$key"
5513
+ fi
4956
5514
  }
4957
5515
 
4958
5516
  fmix_update_template_last_used() {
5517
+ local key="${1:-}" lock_name index
5518
+ [[ "$key" =~ ^[0-9a-f]{16}$ ]] || return 1
5519
+ # A pressure-held producer kept a proven session, not a cache generation.
5520
+ # Do not invent a successful cache access for a generation never published.
5521
+ if [[ "${FMIX_TEMPLATE_PUBLICATION_HELD_KEY:-}" == "$key" ]] \
5522
+ && ! fmix_template_is_complete "$key"; then
5523
+ return 0
5524
+ fi
5525
+ lock_name="build-$key"
5526
+ if index="$(fmix_lock_find_index "$lock_name")"; then
5527
+ kill -0 "${FMIX_HELD_LOCK_KEEPER_PIDS[$index]}" 2>/dev/null || return 1
5528
+ _fmix_update_template_last_used_locked "$key"
5529
+ else
5530
+ fmix_with_artifact_lease "$lock_name" _fmix_update_template_last_used_locked "$key"
5531
+ fi
5532
+ }
5533
+
5534
+ _fmix_update_template_last_used_locked() {
4959
5535
  # Templates are immutable. Mutable access accounting lives beside the CAS,
4960
5536
  # never inside it, so concurrent readers cannot alter a published tree.
4961
- local key="$1" access tmp
5537
+ local key="$1" access tmp v2
4962
5538
  [[ "$key" =~ ^[0-9a-f]{16}$ ]] || return 1
5539
+ v2="$(fmix_template_v2_dir "$key")" || return 1
5540
+ if [[ -e "$v2" || -L "$v2" ]]; then
5541
+ fmix_artifact_v2_managed_entrypoint || return 1
5542
+ fi
4963
5543
  access="$(fmix_template_access_file "$key")"
4964
- mkdir -p "$(dirname "$access")" || return 1
5544
+ if [[ "$access" == "$FMIX_HOME/artifact-access/v2/templates/"* ]]; then
5545
+ fmix_artifact_v2_prepare_directory "artifact-access/v2/templates" || return 1
5546
+ else
5547
+ mkdir -p "$(dirname "$access")" || return 1
5548
+ fi
4965
5549
  tmp="${access}.tmp-$$-${RANDOM}"
4966
5550
  printf '%s\n' "$(fmix_now)" >"$tmp" || { rm -f "$tmp"; return 1; }
4967
5551
  mv "$tmp" "$access" || { rm -f "$tmp"; return 1; }
@@ -5493,6 +6077,7 @@ fmix_lock_keeper_retire() {
5493
6077
  fmix_lock_acquire() {
5494
6078
  local lock_name="${1:-}" timeout="${2:-$FMIX_LOCK_TIMEOUT}"
5495
6079
  local diagnostic_name="${3:-${1:-}}" lock_dir kernel_file deadline
6080
+ local passive="${4:-0}" metadata_file metadata_document
5496
6081
  local keeper_pid token owner_start holder_pid holder_start recorded_start
5497
6082
  local lock_mtime lock_age grace printed_wait=0 index py_bin
5498
6083
  local publication_identity publication_snapshot current_snapshot rollback_keeper_pid rollback_rc rollback_stop_at
@@ -5501,6 +6086,10 @@ fmix_lock_acquire() {
5501
6086
  fmix_error "Invalid FMix lock name: '${lock_name:-empty}'."
5502
6087
  return 1
5503
6088
  }
6089
+ [[ "$passive" == "0" || "$passive" == "1" ]] || {
6090
+ fmix_error "Invalid passive FMix lock mode."
6091
+ return 1
6092
+ }
5504
6093
  if [[ -n "$FMIX_PENDING_LOCK_KEEPER_PID" ]]; then
5505
6094
  printf '{"error":"lock_keeper_cleanup_pending"}\n' >&2
5506
6095
  return 70
@@ -5520,6 +6109,7 @@ fmix_lock_acquire() {
5520
6109
  deadline=$(( $(fmix_epoch) + timeout ))
5521
6110
  lock_dir="$FMIX_HOME/locks/$lock_name"
5522
6111
  kernel_file="$FMIX_HOME/lock-kernel/$lock_name"
6112
+ metadata_file="$FMIX_HOME/lock-metadata/${lock_name}.json"
5523
6113
  mkdir -p "$FMIX_HOME/locks" "$FMIX_HOME/lock-kernel" "$FMIX_HOME/lock-metadata" || return 1
5524
6114
 
5525
6115
  while true; do
@@ -5536,6 +6126,14 @@ fmix_lock_acquire() {
5536
6126
  fi
5537
6127
  keeper_pid="$FMIX_LAST_LOCK_KEEPER_PID"
5538
6128
 
6129
+ # Retirement is passive: do not interpret or repair legacy lock state.
6130
+ # Refuse preexisting metadata while holding the kernel lease, then release only our keeper.
6131
+ if [[ "$passive" == "1" && ( -e "$lock_dir" || -L "$lock_dir" || -e "$metadata_file" || -L "$metadata_file" ) ]]; then
6132
+ fmix_lock_keeper_retire "$keeper_pid" || return 70
6133
+ fmix_error "Passive artifact lease held by preexisting lock metadata."
6134
+ return 1
6135
+ fi
6136
+
5539
6137
  # Keep a directory-shaped record for older FMix binaries. mkdir remains
5540
6138
  # the mixed-version arbitration point, while the persistent inode above
5541
6139
  # is the authority for all v2 contenders and stays locked until release.
@@ -5587,6 +6185,10 @@ fmix_lock_acquire() {
5587
6185
 
5588
6186
  if ! mkdir "$lock_dir" 2>/dev/null; then
5589
6187
  fmix_lock_keeper_retire "$keeper_pid" || return 70
6188
+ if [[ "$passive" == "1" ]]; then
6189
+ fmix_error "Passive artifact lease lost the legacy directory-lock race."
6190
+ return 1
6191
+ fi
5590
6192
  if (( $(fmix_epoch) >= deadline )); then
5591
6193
  fmix_error "Timed out publishing lock metadata for '$diagnostic_name'."
5592
6194
  return 1
@@ -5669,8 +6271,8 @@ EOF
5669
6271
  return 70
5670
6272
  fi
5671
6273
 
5672
- # Publish structured lock-metadata
5673
- cat >"$FMIX_HOME/lock-metadata/${lock_name}.json" 2>/dev/null <<EOF
6274
+ # Publish structured lock-metadata without replacing unknown state.
6275
+ metadata_document="$(cat <<EOF
5674
6276
  {
5675
6277
  "lock_name": $(fmix_json_escape "$lock_name"),
5676
6278
  "pid": $$,
@@ -5679,7 +6281,16 @@ EOF
5679
6281
  "worktree": $(fmix_json_escape "${FMIX_ACTIVE_WORKTREE:-}")
5680
6282
  }
5681
6283
  EOF
5682
- true
6284
+ )"
6285
+ if [[ "$passive" == "1" ]]; then
6286
+ if ! (set -o noclobber; printf '%s\n' "$metadata_document" >"$metadata_file" 2>/dev/null); then
6287
+ fmix_lock_keeper_retire "$keeper_pid" || return 70
6288
+ printf '{"error":"passive_lock_metadata_collision"}\n' >&2
6289
+ return 70
6290
+ fi
6291
+ else
6292
+ printf '%s\n' "$metadata_document" >"$metadata_file" 2>/dev/null || true
6293
+ fi
5683
6294
 
5684
6295
  FMIX_HELD_LOCK_NAMES+=("$lock_name")
5685
6296
  FMIX_HELD_LOCK_KEEPER_PIDS+=("$keeper_pid")
@@ -6397,9 +7008,21 @@ fmix_check_known_nif_caches() {
6397
7008
  # Template build and artifact management
6398
7009
  # ---------------------------------------------------------------------------
6399
7010
 
6400
- fmix_template_dir() {
7011
+ fmix_template_v2_dir() {
7012
+ [[ "${1:-}" =~ ^[0-9a-f]{16}$ ]] || return 1
7013
+ printf '%s/artifacts/v2/templates/%s\n' "$FMIX_HOME" "$1"
7014
+ }
7015
+ fmix_template_legacy_dir() {
7016
+ [[ "${1:-}" =~ ^[0-9a-f]{16}$ ]] || return 1
6401
7017
  printf '%s/templates/%s\n' "$FMIX_HOME" "$1"
6402
7018
  }
7019
+ fmix_template_dir() {
7020
+ local key="${1:-}" v2
7021
+ [[ "$key" =~ ^[0-9a-f]{16}$ ]] || return 1
7022
+ v2="$(fmix_template_v2_dir "$key")" || return 1
7023
+ if [[ -e "$v2" || -L "$v2" ]]; then printf '%s\n' "$v2"
7024
+ else fmix_template_legacy_dir "$key"; fi
7025
+ }
6403
7026
 
6404
7027
  fmix_template_write_manifest() {
6405
7028
  local root="$1" manifest digest py_bin
@@ -6476,7 +7099,8 @@ fmix_template_materialize_app_priv() {
6476
7099
 
6477
7100
  fmix_template_make_readonly() {
6478
7101
  local root="$1" writable
6479
- [[ "$root" == "$FMIX_HOME/templates/"*.tmp-* ]] || return 1
7102
+ [[ "$root" == "$FMIX_HOME/templates/"*.tmp-* \
7103
+ || "$root" == "$FMIX_HOME/artifacts/v2/templates/"*.tmp-* ]] || return 1
6480
7104
  chmod -R a-w "$root" || return 1
6481
7105
  # Darwin refuses to rename a directory whose own owner-write bit is clear.
6482
7106
  # Leave only the staging root writable for the atomic rename. Consumers
@@ -6489,11 +7113,10 @@ fmix_template_make_readonly() {
6489
7113
 
6490
7114
  fmix_template_quarantine() {
6491
7115
  local path="$1" reason="$2" destination
6492
- [[ "$path" == "$FMIX_HOME/templates/"* ]] || return 1
7116
+ [[ "$path" == "$FMIX_HOME/artifacts/v2/templates/"* ]] || return 1
6493
7117
  [[ -e "$path" || -L "$path" ]] || return 0
6494
- destination="$FMIX_HOME/quarantine/templates/$(basename "$path").$(fmix_epoch).$$.${RANDOM}"
6495
- mkdir -p "$(dirname "$destination")" || return 1
6496
- [[ ! -d "$path" || -L "$path" ]] || chmod u+w "$path" 2>/dev/null || return 1
7118
+ destination="$FMIX_HOME/quarantine/artifacts-v2/templates/$(basename "$path").$(fmix_epoch).$$.${RANDOM}"
7119
+ fmix_artifact_v2_prepare_directory "quarantine/artifacts-v2/templates" || return 1
6497
7120
  if mv "$path" "$destination"; then
6498
7121
  fmix_warn "Quarantined template state ($reason): $destination"
6499
7122
  return 0
@@ -6501,8 +7124,9 @@ fmix_template_quarantine() {
6501
7124
  return 1
6502
7125
  }
6503
7126
 
6504
- fmix_template_is_complete() {
6505
- local key="$1" tdir recorded_key recorded_schema manifest_sha recorded_sha
7127
+ fmix_template_is_complete_unleased() {
7128
+ local key="$1" tdir recorded_key recorded_schema manifest_sha recorded_sha expected_schema="1"
7129
+ local producer_runner_sha consumer_protocol
6506
7130
  local writable unexpected
6507
7131
  tdir="$(fmix_template_dir "$key")"
6508
7132
  [[ -d "$tdir" && ! -L "$tdir" ]] || return 1
@@ -6521,7 +7145,15 @@ fmix_template_is_complete() {
6521
7145
  recorded_key="$(fmix_read_template_meta "$key" template_key)"
6522
7146
  recorded_sha="$(fmix_read_template_meta "$key" manifest_sha256)"
6523
7147
  IFS= read -r manifest_sha <"$tdir/manifest.sha256"
6524
- [[ "$recorded_schema" == "$FMIX_TEMPLATE_SCHEMA" ]] || return 1
7148
+ if [[ "$tdir" == "$FMIX_HOME/artifacts/v2/templates/"* ]]; then
7149
+ expected_schema="2"
7150
+ producer_runner_sha="$(fmix_read_template_meta "$key" producer_runner_sha256)"
7151
+ consumer_protocol="$(fmix_read_template_meta "$key" consumer_protocol)"
7152
+ [[ "$consumer_protocol" == "fmix-native-artifacts.v2" ]] || return 1
7153
+ fmix_artifact_v2_managed_entrypoint || return 1
7154
+ fmix_artifact_v2_producer_runner_is_known "$producer_runner_sha" || return 1
7155
+ fi
7156
+ [[ "$recorded_schema" == "$expected_schema" ]] || return 1
6525
7157
  [[ "$recorded_key" == "$key" ]] || return 1
6526
7158
  [[ "$recorded_sha" =~ ^[0-9a-f]{64}$ && "$recorded_sha" == "$manifest_sha" ]] \
6527
7159
  || return 1
@@ -6530,7 +7162,19 @@ fmix_template_is_complete() {
6530
7162
  [[ -z "$writable" ]]
6531
7163
  }
6532
7164
 
6533
- fmix_template_verify_full() {
7165
+ fmix_template_is_complete() {
7166
+ local key="${1:-}" tdir
7167
+ [[ "$key" =~ ^[0-9a-f]{16}$ ]] || return 1
7168
+ tdir="$(fmix_template_dir "$key")" || return 1
7169
+ if [[ "$tdir" != "$FMIX_HOME/artifacts/v2/templates/"* ]]; then
7170
+ fmix_template_is_complete_unleased "$key"
7171
+ return $?
7172
+ fi
7173
+ fmix_artifact_v2_managed_entrypoint || return 1
7174
+ fmix_with_reused_artifact_lease "build-$key" fmix_template_is_complete_unleased "$key"
7175
+ }
7176
+
7177
+ fmix_template_verify_full_unleased() {
6534
7178
  local key="$1" tdir expected actual_tmp actual writable py_bin
6535
7179
  fmix_template_is_complete "$key" || return 1
6536
7180
  tdir="$(fmix_template_dir "$key")"
@@ -6577,6 +7221,17 @@ PY
6577
7221
  [[ -z "$writable" ]]
6578
7222
  }
6579
7223
 
7224
+ fmix_template_verify_full() {
7225
+ local key="${1:-}" tdir
7226
+ tdir="$(fmix_template_dir "$key")" || return 1
7227
+ if [[ "$tdir" != "$FMIX_HOME/artifacts/v2/templates/"* ]]; then
7228
+ fmix_template_verify_full_unleased "$key"
7229
+ return $?
7230
+ fi
7231
+ fmix_artifact_v2_managed_entrypoint || return 1
7232
+ fmix_with_reused_artifact_lease "build-$key" fmix_template_verify_full_unleased "$key"
7233
+ }
7234
+
6580
7235
  fmix_collect_process_tree() {
6581
7236
  # Snapshot a process tree (root first). Collect BEFORE signalling: a TERM
6582
7237
  # pass that exits an intermediate process reparents its children, making
@@ -6708,6 +7363,23 @@ fmix_surface_log_tail() {
6708
7363
  return 0
6709
7364
  }
6710
7365
 
7366
+ fmix_retain_session_on_template_pressure() {
7367
+ local key="$1" tmp_dir="$2" lock_name="$3"
7368
+ fmix_warn "Optional template publication held by disk pressure or incomplete capacity observation; keeping the proven writable session."
7369
+ # This producer's staging is still empty. Never recursively erase an
7370
+ # unexpected payload or a recovery stage to manufacture a successful skip.
7371
+ if ! rmdir "$tmp_dir"; then
7372
+ fmix_lock_release "$lock_name" || fmix_error "Template lease release also failed after staging hold."
7373
+ return 1
7374
+ fi
7375
+ if ! fmix_lock_release "$lock_name"; then
7376
+ FMIX_ARTIFACT_LEASE_RELEASE_FAILED=1
7377
+ return 2
7378
+ fi
7379
+ FMIX_TEMPLATE_PUBLICATION_HELD_KEY="$key"
7380
+ return 0
7381
+ }
7382
+
6711
7383
  fmix_build_template() {
6712
7384
  # A template may be seeded only from the active session after exact
6713
7385
  # dependency and compile stamps prove those mutable artifacts. Otherwise
@@ -6717,12 +7389,15 @@ fmix_build_template() {
6717
7389
  lock_name="build-${key}"
6718
7390
  local deps_root build_root dependency_fingerprint compile_fingerprint
6719
7391
  local source_commit toolchain built_at manifest_sha proven=0
7392
+ FMIX_TEMPLATE_PUBLICATION_HELD_KEY=""
6720
7393
  tdir="$(fmix_template_dir "$key")"
6721
- tmp_dir="$FMIX_HOME/templates/${key}.tmp-$$-${RANDOM}"
7394
+ tdir="$(fmix_template_v2_dir "$key")" || return 1
7395
+ tmp_dir="$FMIX_HOME/artifacts/v2/templates/${key}.tmp-$$-${RANDOM}"
6722
7396
  log_dir="$FMIX_HOME/logs"
6723
7397
  deps_root="$(fmix_session_deps_root "$worktree")" || return 1
6724
7398
  build_root="$(fmix_compile_build_root "$worktree")" || return 1
6725
- mkdir -p "$log_dir" "$FMIX_HOME/templates"
7399
+ mkdir -p "$log_dir" || return 1
7400
+ fmix_artifact_v2_prepare_directory "artifacts/v2/templates" || return 1
6726
7401
 
6727
7402
  # An already-complete template needs no build (and therefore no
6728
7403
  # credentials); return before any preflight so offline consumers of a
@@ -6735,9 +7410,11 @@ fmix_build_template() {
6735
7410
  # artifact is a consumer hit. A closest-ancestor artifact may only seed
6736
7411
  # this producer; its stamps are removed so Mix must reconcile and prove
6737
7412
  # the final exact dependency fingerprint before publication.
6738
- if ! fmix_prepare_dependency_artifacts "$worktree"; then
7413
+ local dependency_preparation_rc=0
7414
+ fmix_prepare_dependency_artifacts "$worktree" || dependency_preparation_rc=$?
7415
+ if (( dependency_preparation_rc != 0 )); then
6739
7416
  fmix_error "Dependency artifact preparation failed closed."
6740
- return 1
7417
+ return "$dependency_preparation_rc"
6741
7418
  fi
6742
7419
 
6743
7420
  # Credential preflight BEFORE queueing on the build lock. Credentials are
@@ -6899,21 +7576,46 @@ fmix_build_template() {
6899
7576
  fi
6900
7577
 
6901
7578
 
6902
- if fmix_publish_dependency_artifact \
6903
- "$worktree" "$dependency_fingerprint"; then
6904
- :
6905
- else
6906
- local publication_rc=$?
7579
+ # Missing managed handoff is an optional publication hold, not a cold-build
7580
+ # failure. Retain the exact writable session and publish no shared generation.
7581
+ if ! fmix_artifact_v2_managed_entrypoint; then
7582
+ fmix_retain_session_on_template_pressure "$key" "$tmp_dir" "$lock_name"
7583
+ return $?
7584
+ fi
7585
+
7586
+ # The exact writable session is already proven above. Publishing another
7587
+ # full copy is optional: pressure/unknown capacity must not force a cold
7588
+ # rebuild, discard this overlay, or claim a template was published.
7589
+ if ! fmix_optional_cache_has_headroom "$deps_root" "$build_root"; then
7590
+ fmix_retain_session_on_template_pressure "$key" "$tmp_dir" "$lock_name"
7591
+ return $?
7592
+ fi
7593
+
7594
+ local publication_rc=0
7595
+ fmix_publish_dependency_artifact \
7596
+ "$worktree" "$dependency_fingerprint" || publication_rc=$?
7597
+ if (( publication_rc != 0 )); then
6907
7598
  if fmix_lock_failure_is_fatal "$publication_rc"; then
7599
+ fmix_template_quarantine "$tmp_dir" "dependency publication fatal lock outcome" >/dev/null 2>&1 || true
6908
7600
  fmix_command_lock_finish "$lock_name" "$publication_rc"
6909
7601
  return $?
6910
7602
  fi
6911
- fmix_warn "Exact dependency artifact publication failed; the full template remains authoritative."
7603
+ case "$publication_rc" in
7604
+ 2|129|130|143)
7605
+ fmix_template_quarantine "$tmp_dir" "dependency publication terminal failure" >/dev/null 2>&1 || true
7606
+ fmix_command_lock_finish "$lock_name" "$publication_rc"
7607
+ return $? ;;
7608
+ esac
7609
+ if [[ "${FMIX_ARTIFACT_LEASE_RELEASE_FAILED:-0}" != "0" ]]; then
7610
+ fmix_template_quarantine "$tmp_dir" "dependency lease release failure" >/dev/null 2>&1 || true
7611
+ fmix_command_lock_finish "$lock_name" "$publication_rc"
7612
+ return $?
7613
+ fi
7614
+ fmix_warn "Exact dependency artifact publication failed; keeping the proven session while attempting optional template publication."
6912
7615
  fi
6913
7616
 
6914
- # The session's own absolute links (e.g. a dependency build's plugin link)
6915
- # become relative before staging, so the manifest guard below judges them
6916
- # as the contained links they are.
7617
+ # A cache hit may return before its publisher normalizes session-internal
7618
+ # links; normalize here before the full-template manifest and copy.
6917
7619
  if ! fmix_session_normalize_links "$worktree" >>"$log_file" 2>&1; then
6918
7620
  fmix_error "Could not normalize session-internal symlinks. See log: $log_file"
6919
7621
  fmix_template_quarantine "$tmp_dir" "session link normalization failed" >/dev/null 2>&1 || true
@@ -6921,6 +7623,13 @@ fmix_build_template() {
6921
7623
  return $?
6922
7624
  fi
6923
7625
 
7626
+ # The dependency publication above may have consumed the earlier buffer.
7627
+ # Re-observe before the full-template copy; this remains advisory, not an
7628
+ # atomic host reservation against concurrent/nonparticipating allocators.
7629
+ if ! fmix_optional_cache_has_headroom "$deps_root" "$build_root"; then
7630
+ fmix_retain_session_on_template_pressure "$key" "$tmp_dir" "$lock_name"
7631
+ return $?
7632
+ fi
6924
7633
  fmix_info "Cloning proven session artifacts into immutable staging …"
6925
7634
  if ! fmix_cow_clone "$deps_root" "$tmp_dir/deps" >>"$log_file" 2>&1 \
6926
7635
  || ! fmix_cow_clone "$build_root" "$tmp_dir/_build" >>"$log_file" 2>&1; then
@@ -6957,6 +7666,15 @@ fmix_build_template() {
6957
7666
  fmix_command_lock_finish "$lock_name" 1
6958
7667
  return $?
6959
7668
  fi
7669
+ if ! fmix_artifact_v2_managed_entrypoint; then
7670
+ fmix_template_quarantine "$tmp_dir" "managed launcher handoff changed before publication" || {
7671
+ fmix_command_lock_finish "$lock_name" 1
7672
+ return $?
7673
+ }
7674
+ fmix_command_lock_finish "$lock_name" 0 || return $?
7675
+ FMIX_TEMPLATE_PUBLICATION_HELD_KEY="$key"
7676
+ return 0
7677
+ fi
6960
7678
  if [[ -e "$tdir" || -L "$tdir" ]] || ! mv "$tmp_dir" "$tdir"; then
6961
7679
  fmix_error "Immutable destination was occupied during publication: $tdir"
6962
7680
  fmix_template_quarantine "$tmp_dir" "publication collision" >/dev/null 2>&1 || true
@@ -7004,14 +7722,16 @@ fmix_wait_for_template() {
7004
7722
 
7005
7723
  fmix_ensure_template() {
7006
7724
  local worktree="$1" key="$2"
7725
+ FMIX_TEMPLATE_PUBLICATION_HELD_KEY=""
7007
7726
 
7008
7727
  if fmix_template_is_complete "$key"; then
7009
- fmix_update_template_last_used "$key"
7728
+ fmix_update_template_last_used "$key" || return $?
7010
7729
  return 0
7011
7730
  fi
7012
7731
 
7013
7732
  fmix_build_template "$worktree" "$key" || return $?
7014
- fmix_update_template_last_used "$key"
7733
+ [[ "${FMIX_TEMPLATE_PUBLICATION_HELD_KEY:-}" != "$key" ]] || return 0
7734
+ fmix_update_template_last_used "$key" || return $?
7015
7735
  return 0
7016
7736
  }
7017
7737
 
@@ -7209,8 +7929,24 @@ PY
7209
7929
  # ---------------------------------------------------------------------------
7210
7930
 
7211
7931
  fmix_clone_template_to_worktree() {
7212
- local worktree="$1" key="$2" tdir deps_root build_root retired
7213
- local dependency_fingerprint retired_used=0
7932
+ local key="${2:-}"
7933
+ (( $# == 2 )) || return 1
7934
+ [[ "$key" =~ ^[0-9a-f]{16}$ ]] || return 1
7935
+ fmix_with_artifact_lease "build-$key" _fmix_clone_template_to_worktree_locked "$@"
7936
+ }
7937
+
7938
+ _fmix_template_install_interrupt() {
7939
+ template_install_interrupted=1
7940
+ template_install_rc="${1:-130}"
7941
+ }
7942
+
7943
+ _fmix_clone_template_to_worktree_locked() {
7944
+ local worktree="$1" key="$2" tdir deps_root build_root stage stamp
7945
+ local dependency_fingerprint staged_manifest had_deps=0 had_build=0 had_stamp=0
7946
+ local installed_deps=0 installed_build=0 switch_failed=0 rollback_failed=0
7947
+ local attempted_deps=0 attempted_build=0 stamp_attempted=0
7948
+ local template_install_interrupted=0 template_install_rc=1
7949
+ local saved_trap_int saved_trap_term saved_trap_hup
7214
7950
  tdir="$(fmix_template_dir "$key")"
7215
7951
  deps_root="$(fmix_session_deps_root "$worktree")" || return 1
7216
7952
  build_root="$(fmix_compile_build_root "$worktree")" || return 1
@@ -7224,52 +7960,109 @@ fmix_clone_template_to_worktree() {
7224
7960
  fmix_error "Session artifact paths escaped the active session root."
7225
7961
  return 1
7226
7962
  }
7227
- fmix_template_is_complete "$key" || {
7963
+ [[ ! -L "$deps_root" && ! -L "$build_root" ]] || return 1
7964
+ fmix_template_verify_full "$key" || {
7228
7965
  fmix_error "Refusing to clone unverified template $key."
7229
7966
  return 1
7230
7967
  }
7231
7968
 
7232
7969
  fmix_info "Cloning immutable template into session overlay …"
7233
- retired="$FMIX_ACTIVE_SESSION_ROOT/retired/$(date +%Y%m%dT%H%M%S)-$$-${RANDOM}"
7234
- if [[ -e "$deps_root" || -L "$deps_root" \
7235
- || -e "$build_root" || -L "$build_root" ]]; then
7236
- mkdir -p "$retired" || return 1
7237
- retired_used=1
7238
- if [[ -e "$deps_root" || -L "$deps_root" ]]; then
7239
- mv "$deps_root" "$retired/deps" || return 1
7970
+ stage="$(mktemp -d "$FMIX_ACTIVE_SESSION_ROOT/.template-install.XXXXXX")" || return 1
7971
+ stamp="$(fmix_dependency_stamp_file "$worktree")"
7972
+ saved_trap_int="$(trap -p INT)"
7973
+ saved_trap_term="$(trap -p TERM)"
7974
+ saved_trap_hup="$(trap -p HUP)"
7975
+ trap '_fmix_template_install_interrupt 130' INT
7976
+ trap '_fmix_template_install_interrupt 143' TERM
7977
+ trap '_fmix_template_install_interrupt 129' HUP
7978
+ # Copy and prove staging before retiring the existing mutable overlay.
7979
+ if ! mkdir "$stage/new" \
7980
+ || ! fmix_cow_clone "$tdir/deps" "$stage/new/deps" \
7981
+ || ! fmix_cow_clone "$tdir/_build" "$stage/new/_build" \
7982
+ || ! chmod -R u+w "$stage/new/deps" "$stage/new/_build"; then
7983
+ switch_failed=1
7984
+ fi
7985
+ if (( switch_failed == 0 && template_install_interrupted == 0 )); then
7986
+ staged_manifest="$(fmix_template_write_manifest "$stage/new")" || switch_failed=1
7987
+ [[ "$staged_manifest" == "$(fmix_read_template_meta "$key" manifest_sha256)" ]] || switch_failed=1
7988
+ fi
7989
+ dependency_fingerprint="$(fmix_compute_dependency_fingerprint "$worktree")" \
7990
+ || switch_failed=1
7991
+ if (( switch_failed == 0 && template_install_interrupted == 0 )); then
7992
+ if [[ -e "$deps_root" ]]; then
7993
+ if mv "$deps_root" "$stage/old-deps"; then had_deps=1; else switch_failed=1; fi
7994
+ fi
7995
+ if (( switch_failed == 0 )) && [[ -e "$build_root" ]]; then
7996
+ if mv "$build_root" "$stage/old-build"; then had_build=1; else switch_failed=1; fi
7997
+ fi
7998
+ if (( switch_failed == 0 )) && [[ -e "$stamp" || -L "$stamp" ]]; then
7999
+ if [[ -f "$stamp" && ! -L "$stamp" ]] && mv "$stamp" "$stage/old-stamp"; then
8000
+ had_stamp=1
8001
+ else
8002
+ switch_failed=1
8003
+ fi
7240
8004
  fi
7241
- if [[ -e "$build_root" || -L "$build_root" ]]; then
7242
- mv "$build_root" "$retired/_build" || return 1
8005
+ if (( switch_failed == 0 && template_install_interrupted == 0 )); then
8006
+ attempted_deps=1
8007
+ if mv "$stage/new/deps" "$deps_root"; then installed_deps=1; else switch_failed=1; fi
8008
+ fi
8009
+ if (( switch_failed == 0 && template_install_interrupted == 0 )); then
8010
+ attempted_build=1
8011
+ if mv "$stage/new/_build" "$build_root"; then installed_build=1; else switch_failed=1; fi
8012
+ fi
8013
+ if (( switch_failed == 0 && template_install_interrupted == 0 )); then
8014
+ stamp_attempted=1
8015
+ fmix_write_dependency_stamp "$worktree" "$dependency_fingerprint" || switch_failed=1
8016
+ if (( switch_failed == 0 && template_install_interrupted == 0 )); then
8017
+ fmix_update_template_last_used "$key" || switch_failed=1
8018
+ fi
7243
8019
  fi
7244
- fmix_info "Prior session artifacts held for transactional replacement."
7245
8020
  fi
7246
-
7247
- if ! fmix_cow_clone "$tdir/deps" "$deps_root"; then
7248
- return 1
8021
+ if (( switch_failed != 0 || template_install_interrupted != 0 )); then
8022
+ # A rename may have completed before an interrupted child reports its
8023
+ # status. Reconcile the actual owned staging paths, not only flags.
8024
+ [[ ! -e "$stage/old-deps" && ! -L "$stage/old-deps" ]] || had_deps=1
8025
+ [[ ! -e "$stage/old-build" && ! -L "$stage/old-build" ]] || had_build=1
8026
+ [[ ! -e "$stage/old-stamp" && ! -L "$stage/old-stamp" ]] || had_stamp=1
8027
+ if (( attempted_deps != 0 )) && [[ ! -e "$stage/new/deps" && ! -L "$stage/new/deps" \
8028
+ && ( -e "$deps_root" || -L "$deps_root" ) ]]; then installed_deps=1; fi
8029
+ if (( attempted_build != 0 )) && [[ ! -e "$stage/new/_build" && ! -L "$stage/new/_build" \
8030
+ && ( -e "$build_root" || -L "$build_root" ) ]]; then installed_build=1; fi
8031
+ (( installed_deps == 0 )) || rm -rf "$deps_root" || rollback_failed=1
8032
+ (( installed_build == 0 )) || rm -rf "$build_root" || rollback_failed=1
8033
+ if (( had_deps != 0 )); then
8034
+ if [[ ! -e "$deps_root" && ! -L "$deps_root" ]]; then
8035
+ mv "$stage/old-deps" "$deps_root" || rollback_failed=1
8036
+ else rollback_failed=1; fi
8037
+ fi
8038
+ if (( had_build != 0 )); then
8039
+ if [[ ! -e "$build_root" && ! -L "$build_root" ]]; then
8040
+ mv "$stage/old-build" "$build_root" || rollback_failed=1
8041
+ else rollback_failed=1; fi
8042
+ fi
8043
+ if (( stamp_attempted != 0 || had_stamp != 0 )); then
8044
+ rm -f "$stamp" || rollback_failed=1
8045
+ fi
8046
+ if (( had_stamp != 0 )); then
8047
+ if [[ ! -e "$stamp" && ! -L "$stamp" ]]; then
8048
+ mv "$stage/old-stamp" "$stamp" || rollback_failed=1
8049
+ else rollback_failed=1; fi
8050
+ fi
8051
+ fi
8052
+ trap - INT TERM HUP
8053
+ [[ -n "$saved_trap_int" ]] && eval "$saved_trap_int"
8054
+ [[ -n "$saved_trap_term" ]] && eval "$saved_trap_term"
8055
+ [[ -n "$saved_trap_hup" ]] && eval "$saved_trap_hup"
8056
+ if (( rollback_failed != 0 )); then
8057
+ fmix_error "Template replacement rollback incomplete; preserving recovery inputs: $stage"
8058
+ return 2
7249
8059
  fi
7250
- if ! fmix_cow_clone "$tdir/_build" "$build_root"; then
7251
- mkdir -p "$retired" || true
7252
- mv "$deps_root" "$retired/failed-deps" 2>/dev/null || true
7253
- return 1
8060
+ rm -rf "$stage" || fmix_warn "Owned template staging remains: $stage"
8061
+ if (( switch_failed != 0 || template_install_interrupted != 0 )); then
8062
+ return "$template_install_rc"
7254
8063
  fi
7255
- chmod -R u+w "$deps_root" "$build_root" || {
7256
- fmix_error "Could not make session clone writable."
7257
- return 1
7258
- }
7259
-
7260
- # Post-clone manifest synchronization: touch compile manifests to prevent full DAG recompiles
8064
+ # Preserve warm compilation manifests only after transactional replacement.
7261
8065
  find "$build_root" -type f -name 'compile.*' -exec touch {} + 2>/dev/null || true
7262
-
7263
- dependency_fingerprint="$(fmix_compute_dependency_fingerprint "$worktree")" \
7264
- || return 1
7265
- fmix_write_dependency_stamp "$worktree" "$dependency_fingerprint" || return 1
7266
- if (( retired_used == 1 )); then
7267
- if fmix_guard_path "$retired" && rm -rf "$retired"; then
7268
- rmdir "$(dirname "$retired")" 2>/dev/null || true
7269
- else
7270
- fmix_warn "Session replacement succeeded, but retired artifacts remain: $retired"
7271
- fi
7272
- fi
7273
8066
  fmix_info "Template cloned into session; dependency provenance established."
7274
8067
  return 0
7275
8068
  }
@@ -7309,10 +8102,10 @@ fmix_session_has_app_manifest() {
7309
8102
  return 1
7310
8103
  }
7311
8104
 
7312
- fmix_ensure_artifacts() {
8105
+ _fmix_ensure_artifacts_impl() {
7313
8106
  FMIX_LAST_ARTIFACTS_COMPILE_FAILURE=0
7314
8107
  local worktree="$1" template_key="$2" allow_template_build="${3:-0}"
7315
- local state_file artifact_state_file
8108
+ local state_file artifact_state_file reconcile_rc donor_rc
7316
8109
  state_file="$(fmix_worktree_state_file "$worktree")"
7317
8110
  artifact_state_file="$(fmix_artifact_state_file "$worktree")"
7318
8111
 
@@ -7420,7 +8213,9 @@ fmix_ensure_artifacts() {
7420
8213
  FMIX_LAST_ARTIFACTS_OUTCOME="dependency_reconcile"
7421
8214
  return 0
7422
8215
  else
7423
- local reconcile_rc=$?
8216
+ reconcile_rc=$?
8217
+ case "$reconcile_rc" in 2|129|130|143) return "$reconcile_rc" ;; esac
8218
+ [[ "${FMIX_ARTIFACT_LEASE_RELEASE_FAILED:-0}" == "0" ]] || return "$reconcile_rc"
7424
8219
  fmix_lock_failure_is_fatal "$reconcile_rc" && return 70
7425
8220
  fi
7426
8221
  fmix_info "Artifact compatibility proof failed; a verified template clone is required."
@@ -7438,7 +8233,7 @@ fmix_ensure_artifacts() {
7438
8233
  fi
7439
8234
  # Prefer a warm peer session for the same worktree+template over a cold
7440
8235
  # template clone (avoids ~4700-file recompile when isolate/new session).
7441
- local donor="" donor_rc=0
8236
+ local donor=""
7442
8237
  if donor="$(fmix_find_warm_donor_session "$worktree" "$template_key")"; then
7443
8238
  if fmix_clone_donor_to_session "$worktree" "$donor"; then
7444
8239
  fmix_write_artifact_state "$worktree" "$template_key" || return 1
@@ -7446,6 +8241,9 @@ fmix_ensure_artifacts() {
7446
8241
  return 0
7447
8242
  else
7448
8243
  donor_rc=$?
8244
+ case "$donor_rc" in 2|129|130|143) return "$donor_rc" ;; esac
8245
+ [[ "${FMIX_ARTIFACT_LEASE_RELEASE_FAILED:-0}" == "0" ]] || return "$donor_rc"
8246
+ fmix_lock_failure_is_fatal "$donor_rc" && return 70
7449
8247
  fi
7450
8248
  # Only an ordinary donor miss permits fallback. A keeper bootstrap or
7451
8249
  # retirement failure must not admit artifacts while recovery is pending.
@@ -7455,6 +8253,11 @@ fmix_ensure_artifacts() {
7455
8253
 
7456
8254
  FMIX_TEMPLATE_BUILT_FROM_ACTIVE_SESSION=0
7457
8255
  fmix_ensure_template "$worktree" "$template_key" || return $?
8256
+ if [[ "${FMIX_TEMPLATE_PUBLICATION_HELD_KEY:-}" == "$template_key" ]]; then
8257
+ fmix_write_artifact_state "$worktree" "$template_key" || return 1
8258
+ FMIX_LAST_ARTIFACTS_OUTCOME="session_only_disk_pressure"
8259
+ return 0
8260
+ fi
7458
8261
  if [[ "${FMIX_TEMPLATE_BUILT_FROM_ACTIVE_SESSION:-0}" == "1" ]]; then
7459
8262
  fmix_write_artifact_state "$worktree" "$template_key" || return 1
7460
8263
  fmix_info "Active session produced template $template_key; keeping its proven writable overlay."
@@ -7467,9 +8270,26 @@ fmix_ensure_artifacts() {
7467
8270
  return 0
7468
8271
  }
7469
8272
 
8273
+ fmix_auto_expire_artifacts() {
8274
+ [[ "${FMIX_ARTIFACT_AUTO_EXPIRE:-1}" == "1" ]] || return 0
8275
+ case "${cmd:-${FMIX_INTERNAL_RUN_MODE:-}}" in
8276
+ test|coverage|setup|task|format) ;;
8277
+ *) return 0 ;;
8278
+ esac
8279
+ cmd_gc_artifact_retirement --artifacts-only --auto-expire >/dev/null 2>&1 || true
8280
+ return 0
8281
+ }
8282
+
8283
+ fmix_ensure_artifacts() {
8284
+ local rc=0
8285
+ _fmix_ensure_artifacts_impl "$@" || rc=$?
8286
+ (( rc == 0 )) || return "$rc"
8287
+ fmix_auto_expire_artifacts
8288
+ }
8289
+
7470
8290
  # ---------------------------------------------------------------------------
7471
8291
  # DB management
7472
- # ---------------------------------------------------------------------------
8292
+
7473
8293
 
7474
8294
  fmix_db_name_for_worktree() {
7475
8295
  local worktree="$1"
@@ -10239,6 +11059,15 @@ fmix_dependency_stamp_file() {
10239
11059
  }
10240
11060
 
10241
11061
  fmix_write_dependency_stamp() {
11062
+ local worktree="${1:-}" fingerprint="${2:-}" lane
11063
+ (( $# == 2 )) && [[ "$fingerprint" =~ ^[0-9a-f]{64}$ ]] || return 1
11064
+ lane="$(fmix_dependency_lane_fingerprint "$worktree")" || return 1
11065
+ [[ "$lane" =~ ^[0-9a-f]{64}$ ]] || return 1
11066
+ fmix_with_artifact_reference_lease "dependency-artifact-${lane:0:16}-${fingerprint:0:16}" \
11067
+ _fmix_write_dependency_stamp_locked "$@"
11068
+ }
11069
+
11070
+ _fmix_write_dependency_stamp_locked() {
10242
11071
  local worktree="$1" dependency_fingerprint="$2" real build_root guard stamp tmp
10243
11072
  local reconciliation_guard lock_identity
10244
11073
  real="$(fmix_realpath "$worktree")"
@@ -10464,14 +11293,29 @@ fmix_compute_dirty_hash() {
10464
11293
  }
10465
11294
 
10466
11295
  fmix_write_compile_stamp() {
10467
- local worktree="$1" fingerprint="$2" real build_root guard dependency_guard stamp tmp quick_guard
11296
+ local key
11297
+ (( $# == 2 )) || return 1
11298
+ key="$(fmix_compute_template_key "$1" 2>/dev/null)" || key=""
11299
+ if [[ "$key" =~ ^[0-9a-f]{16}$ ]]; then
11300
+ fmix_with_artifact_reference_lease "build-$key" _fmix_write_compile_stamp_locked "$@" "$key"
11301
+ else
11302
+ _fmix_write_compile_stamp_locked "$@" ""
11303
+ fi
11304
+ }
11305
+
11306
+ _fmix_write_compile_stamp_locked() {
11307
+ local worktree="$1" fingerprint="$2" real build_root guard dependency_guard stamp tmp quick_guard template_key
10468
11308
  local template_key tree_hash env_hash dirty_hash ignored_compile_hash source_stability_identity
10469
11309
  real="$(fmix_realpath "$worktree")"
10470
11310
  build_root="$(fmix_compile_build_root "$real")"
10471
11311
  guard="$(fmix_compile_manifest_guard "$real")" || return 1
10472
11312
  dependency_guard="$(fmix_dependency_source_guard "$real")" || return 1
10473
11313
  quick_guard="$(fmix_compile_quick_guard "$real")" || return 1
10474
- template_key="$(fmix_compute_template_key "$real" 2>/dev/null || echo "")"
11314
+ if (( $# >= 3 )); then
11315
+ template_key="${3:-}"
11316
+ else
11317
+ template_key="$(fmix_compute_template_key "$real" 2>/dev/null || echo "")"
11318
+ fi
10475
11319
  tree_hash="$(fmix_get_git_tree_hash "$real")" || return 1
10476
11320
  env_hash="$(fmix_compute_compile_env_hash "$real" 2>/dev/null || echo "")"
10477
11321
  dirty_hash="$(fmix_compute_dirty_hash "$real" 2>/dev/null)" || return 1
@@ -11953,7 +12797,7 @@ cmd_setup() {
11953
12797
  # slowing ordinary `fmix test` warm hits. Publication remains best-effort:
11954
12798
  # the full source/config template is still authoritative on failure.
11955
12799
  local setup_dependency_fingerprint setup_dependency_lane setup_dependency_artifact
11956
- local setup_dependency_stamp setup_recorded_dependency
12800
+ local setup_dependency_stamp setup_recorded_dependency setup_publication_rc=0
11957
12801
  setup_dependency_fingerprint="$(fmix_compute_dependency_fingerprint \
11958
12802
  "$real_worktree" 2>/dev/null)" || setup_dependency_fingerprint=""
11959
12803
  setup_dependency_stamp="$(fmix_dependency_stamp_file "$real_worktree")"
@@ -11976,16 +12820,27 @@ cmd_setup() {
11976
12820
  "$setup_dependency_fingerprint"; then
11977
12821
  fmix_touch_dependency_artifact_access \
11978
12822
  "$setup_dependency_lane" "$setup_dependency_fingerprint" \
11979
- >/dev/null 2>&1 || true
12823
+ >/dev/null 2>&1 || setup_publication_rc=$?
11980
12824
  else
11981
- local publication_rc=0
11982
12825
  fmix_publish_dependency_artifact \
11983
- "$real_worktree" "$setup_dependency_fingerprint" || publication_rc=$?
11984
- if fmix_lock_failure_is_fatal "$publication_rc"; then
11985
- fmix_command_lock_finish "$lock_name" "$publication_rc"
12826
+ "$real_worktree" "$setup_dependency_fingerprint" \
12827
+ || setup_publication_rc=$?
12828
+ fi
12829
+ if (( setup_publication_rc != 0 )); then
12830
+ if fmix_lock_failure_is_fatal "$setup_publication_rc"; then
12831
+ fmix_command_lock_finish "$lock_name" "$setup_publication_rc"
12832
+ return $?
12833
+ fi
12834
+ case "$setup_publication_rc" in
12835
+ 2|129|130|143)
12836
+ fmix_command_lock_finish "$lock_name" "$setup_publication_rc"
12837
+ return $? ;;
12838
+ esac
12839
+ if [[ "${FMIX_ARTIFACT_LEASE_RELEASE_FAILED:-0}" != "0" ]]; then
12840
+ fmix_command_lock_finish "$lock_name" "$setup_publication_rc"
11986
12841
  return $?
11987
12842
  fi
11988
- (( publication_rc == 0 )) || fmix_warn "Could not backfill the exact dependency artifact during setup."
12843
+ fmix_warn "Could not backfill the exact dependency artifact during setup."
11989
12844
  fi
11990
12845
  fi
11991
12846
  fmix_ensure_db "$real_worktree" "$db_name" "$rebuild_existing" "$allow_structure_build" 1 "$force_from_zero" || {
@@ -12030,15 +12885,20 @@ cmd_setup() {
12030
12885
  fmix_command_lock_finish "$lock_name" 1
12031
12886
  return $?
12032
12887
  }
12033
- fmix_update_template_last_used "$template_key"
12034
-
12035
- fmix_command_lock_finish "$lock_name" 0 || return $?
12888
+ local setup_access_rc=0 setup_finish_rc=0
12889
+ fmix_update_template_last_used "$template_key" || setup_access_rc=$?
12890
+ fmix_command_lock_finish "$lock_name" "$setup_access_rc" || setup_finish_rc=$?
12891
+ if (( setup_finish_rc != 0 )); then
12892
+ fmix_error "Setup completion failed (template access rc=$setup_access_rc, final rc=$setup_finish_rc)."
12893
+ return "$setup_finish_rc"
12894
+ fi
12036
12895
  if [[ "${FMIX_ACTIVE_DB_CLEAN_BOOTSTRAP:-0}" == "1" ]]; then
12037
12896
  fmix_info "=== setup complete; hot DB base: $published_base ==="
12038
12897
  else
12039
12898
  fmix_info "=== setup complete; scratch DB remains worktree-local ==="
12040
12899
  fi
12041
12900
  fmix_info "Run: ./fmix test --worktree $real_worktree -- <test args>"
12901
+ return 0
12042
12902
  }
12043
12903
 
12044
12904
  # ---------------------------------------------------------------------------
@@ -14340,6 +15200,1909 @@ PY
14340
15200
  return 0
14341
15201
  }
14342
15202
 
15203
+ fmix_gc_artifact_retirement_requested() {
15204
+ local arg
15205
+ for arg in "$@"; do
15206
+ case "$arg" in
15207
+ --adopt|--plan|--retire-plan|--pin|--unpin|--resume|--auto-expire) return 0 ;;
15208
+ esac
15209
+ done
15210
+ return 1
15211
+ }
15212
+
15213
+ cmd_gc_artifact_retirement() {
15214
+ local mode="" artifact_id="" consumer="" pin_id="" arg py_bin dependency_ttl template_ttl runner
15215
+ while (( $# > 0 )); do
15216
+ case "$1" in
15217
+ --artifacts-only|--json) shift ;;
15218
+ --help|-h)
15219
+ printf '%s\n' 'fmix gc --artifacts-only [--adopt ID|--plan ID|--retire-plan ID|--pin ID --consumer NAME|--unpin PIN|--auto-expire]'
15220
+ return 0 ;;
15221
+ --adopt|--plan|--retire-plan|--pin|--unpin|--resume)
15222
+ [[ -z "$mode" && $# -ge 2 ]] || return 2
15223
+ mode="${1#--}"
15224
+ case "$mode" in
15225
+ unpin|retire-plan|resume) pin_id="$2" ;;
15226
+ *) artifact_id="$2" ;;
15227
+ esac
15228
+ shift 2 ;;
15229
+ --auto-expire)
15230
+ [[ -z "$mode" ]] || return 2
15231
+ mode="auto-expire"
15232
+ shift ;;
15233
+ --consumer)
15234
+ [[ $# -ge 2 && -z "$consumer" ]] || return 2
15235
+ consumer="$2"
15236
+ shift 2 ;;
15237
+ *)
15238
+ printf '%s\n' '{"error":"unsupported_artifact_retirement_option"}'
15239
+ return 2 ;;
15240
+ esac
15241
+ done
15242
+ [[ -n "$mode" ]] || return 2
15243
+ case "$mode" in
15244
+ adopt|plan|pin)
15245
+ [[ "$artifact_id" =~ ^(template|template-v2):[0-9a-f]{16}$|^(dependency|dependency-v2):[0-9a-f]{64}/[0-9a-f]{64}$ ]] || return 2 ;;
15246
+ retire-plan|resume)
15247
+ [[ "$pin_id" =~ ^[0-9a-f]{64}$ ]] || return 2 ;;
15248
+ unpin) [[ "$pin_id" =~ ^[0-9a-f]{32}$ ]] || return 2 ;;
15249
+ auto-expire) ;;
15250
+ *) return 2 ;;
15251
+ esac
15252
+ if [[ "$mode" == "pin" || "$mode" == "unpin" ]]; then
15253
+ [[ "$consumer" =~ ^[A-Za-z0-9._-]{1,80}$ ]] || return 2
15254
+ elif [[ -n "$consumer" ]]; then return 2
15255
+ fi
15256
+ if [[ "$mode" == "auto-expire" || "$mode" == "unpin" \
15257
+ || "$mode" == "retire-plan" || "$mode" == "resume" \
15258
+ || "$artifact_id" == template-v2:* || "$artifact_id" == dependency-v2:* ]]; then
15259
+ local handoff_reason
15260
+ handoff_reason="$(fmix_artifact_v2_managed_entrypoint 2>&1)" || {
15261
+ case "$handoff_reason" in
15262
+ unsafe_launcher_parent|unsafe_runner_runtime) ;;
15263
+ *) handoff_reason="managed_launcher_handoff_unproven" ;;
15264
+ esac
15265
+ printf '{"schema":"fmix-artifact-retirement.v2","status":"held","reason":"%s"}\n' "$handoff_reason"
15266
+ return 1
15267
+ }
15268
+ fi
15269
+ fmix_prepare_command_home || return 1
15270
+ dependency_ttl="$(fmix_effective_artifact_ttl_hours dependency)" || return 2
15271
+ template_ttl="$(fmix_effective_artifact_ttl_hours template)" || return 2
15272
+ py_bin="$(fmix_python_bin)" || return 1
15273
+ runner="$(fmix_realpath "${BASH_SOURCE[0]}")" || return 1
15274
+ "$py_bin" -I -B - "$FMIX_HOME" "$runner" "$0" "$$" "$mode" "$artifact_id" "$consumer" "$pin_id" "$dependency_ttl" "$template_ttl" <<'PY'
15275
+ import contextlib, ctypes, datetime, hashlib, json, os, re, select, stat, subprocess, sys, time
15276
+
15277
+ home, runner, entrypoint, entrypoint_pid, mode, artifact_id, consumer, object_id, dep_ttl, template_ttl = sys.argv[1:]
15278
+ home = os.path.abspath(home)
15279
+ entrypoint = os.path.abspath(entrypoint)
15280
+ entrypoint_pid = int(entrypoint_pid)
15281
+ if entrypoint_pid <= 0: raise ValueError("invalid FMix entrypoint PID")
15282
+ uid = os.getuid()
15283
+ if uid == 0 or os.geteuid() != uid:
15284
+ raise ValueError("privileged_cleaner_forbidden")
15285
+ now = datetime.datetime.now(datetime.timezone.utc)
15286
+ sha = lambda value: hashlib.sha256(value).hexdigest()
15287
+ hexkey = lambda value, width: (
15288
+ isinstance(value, str)
15289
+ and re.fullmatch(r"[0-9a-f]{%d}" % width, value) is not None
15290
+ )
15291
+ retirement_deadline=time.monotonic()+45
15292
+ retirement_bytes_remaining=8*1024*1024*1024
15293
+ retirement_entries_remaining=4000000
15294
+ def retirement_bound(byte_count=0,entry_count=0):
15295
+ global retirement_bytes_remaining,retirement_entries_remaining
15296
+ if time.monotonic()>retirement_deadline: raise ValueError("retirement_work_deadline")
15297
+ retirement_bytes_remaining-=byte_count
15298
+ retirement_entries_remaining-=entry_count
15299
+ if retirement_bytes_remaining<0: raise ValueError("retirement_byte_budget")
15300
+ if retirement_entries_remaining<0: raise ValueError("retirement_entry_budget")
15301
+ def bounded_names(fd):
15302
+ names=[]
15303
+ with os.scandir(fd) as iterator:
15304
+ for entry in iterator:
15305
+ retirement_bound(entry_count=1)
15306
+ names.append(entry.name)
15307
+ return sorted(names)
15308
+ def fail(reason, status=2):
15309
+ print(json.dumps({"schema":"fmix-artifact-retirement.v2","status":"held","reason":reason},sort_keys=True))
15310
+ raise SystemExit(status)
15311
+ def canonical(value):
15312
+ return json.dumps(value,sort_keys=True,separators=(",",":"),ensure_ascii=True).encode()
15313
+ def identity(st):
15314
+ return {"device":st.st_dev,"inode":st.st_ino,"uid":st.st_uid,"mode":st.st_mode,
15315
+ "size":st.st_size,"mtime_ns":st.st_mtime_ns,"ctime_ns":st.st_ctime_ns,
15316
+ "nlink":st.st_nlink,"flags":getattr(st,"st_flags",0)}
15317
+ def safe_parts(value):
15318
+ if not isinstance(value,str) or value.startswith("/") or "\\" in value:
15319
+ raise ValueError("unsafe relative path")
15320
+ parts=value.split("/")
15321
+ if not parts or any(part in ("",".","..") for part in parts):
15322
+ raise ValueError("unsafe path component")
15323
+ return parts
15324
+ dir_flags=os.O_RDONLY|getattr(os,"O_DIRECTORY",0)|getattr(os,"O_NOFOLLOW",0)
15325
+ rootfd=os.open(home,dir_flags)
15326
+ home_st=os.fstat(rootfd)
15327
+ if os.path.realpath(home)!=home or home_st.st_uid!=uid:
15328
+ fail("unavailable_or_unsafe_home")
15329
+ def open_dir(rel):
15330
+ fd=os.dup(rootfd)
15331
+ try:
15332
+ for part in safe_parts(rel):
15333
+ nxt=os.open(part,dir_flags,dir_fd=fd)
15334
+ os.close(fd)
15335
+ fd=nxt
15336
+ st=os.fstat(fd)
15337
+ if st.st_uid!=uid or st.st_dev!=home_st.st_dev:
15338
+ raise ValueError("foreign directory")
15339
+ return fd
15340
+ except Exception:
15341
+ os.close(fd)
15342
+ raise
15343
+ def parent_and_name(rel):
15344
+ parts=safe_parts(rel)
15345
+ parent="/".join(parts[:-1])
15346
+ return (open_dir(parent) if parent else os.dup(rootfd)),parts[-1]
15347
+ def read_file(rel,limit=16*1024*1024):
15348
+ parent,name=parent_and_name(rel)
15349
+ try:
15350
+ fd=os.open(name,os.O_RDONLY|getattr(os,"O_NOFOLLOW",0)|getattr(os,"O_NONBLOCK",0),dir_fd=parent)
15351
+ finally: os.close(parent)
15352
+ try:
15353
+ before=os.fstat(fd)
15354
+ if not stat.S_ISREG(before.st_mode) or before.st_uid!=uid or before.st_dev!=home_st.st_dev or before.st_nlink!=1 or before.st_size>limit:
15355
+ raise ValueError("unsafe metadata file")
15356
+ data=bytearray()
15357
+ while True:
15358
+ block=os.read(fd,min(65536,limit+1-len(data)))
15359
+ if not block: break
15360
+ retirement_bound(len(block))
15361
+ data.extend(block)
15362
+ if len(data)>limit: raise ValueError("oversize metadata")
15363
+ after=os.fstat(fd)
15364
+ if identity(before)!=identity(after): raise ValueError("changed metadata")
15365
+ return bytes(data),identity(after)
15366
+ finally: os.close(fd)
15367
+ def no_markers(path,st):
15368
+ if getattr(st,"st_flags",0): raise ValueError("protected filesystem flags")
15369
+ if hasattr(os,"listxattr"):
15370
+ if os.path.isabs(path): raise ValueError("unsafe marker path")
15371
+ attrs=os.listxattr(os.path.join(home,path),follow_symlinks=False)
15372
+ if attrs: raise ValueError("protected extended attributes")
15373
+ def run_audit():
15374
+ result=subprocess.run(["/bin/bash",runner,"gc","--artifacts-only","--json"],
15375
+ env=os.environ.copy(),capture_output=True,timeout=10)
15376
+ retirement_bound(len(result.stdout)+len(result.stderr))
15377
+ if result.returncode or result.stderr: raise ValueError("artifact audit incomplete")
15378
+ report=strict_load(result.stdout)
15379
+ required={"schema","mutation_supported","idle_ttl_hours","observed_at","source_sha256",
15380
+ "home","holds","entries","observations","report_truncated"}
15381
+ if (not isinstance(report,dict) or set(report)!=required
15382
+ or report.get("schema")!="fmix-artifact-audit.v1" or report.get("mutation_supported") is not False
15383
+ or report.get("home")!=home or report.get("report_truncated") is not False):
15384
+ raise ValueError("artifact audit schema or output incomplete")
15385
+ if (not isinstance(report.get("holds"),list) or any(not isinstance(v,str) for v in report["holds"])
15386
+ or not isinstance(report.get("entries"),list) or not isinstance(report.get("observations"),list)):
15387
+ raise ValueError("artifact audit observation schema")
15388
+ with open(runner,"rb") as handle: runner_sha=sha(handle.read())
15389
+ if report.get("source_sha256")!=runner_sha: raise ValueError("runner digest mismatch")
15390
+ return report,runner_sha
15391
+ LEGACY_HOLDS={"external_consumers_unknown","liveness_unproven",
15392
+ "consumer_coverage_unproven","fallback_preservation_unproven",
15393
+ "missing_ps","missing_lsof"}
15394
+ def known_global_holds(report):
15395
+ # Historical/external coverage stays held until an independent owner witness exists.
15396
+ return set(report.get("holds",[]))
15397
+ def managed_launcher_paths():
15398
+ user_home=os.path.abspath(os.environ.get("HOME",""))
15399
+ if not user_home or os.path.realpath(user_home)!=user_home: raise ValueError("noncanonical_user_home")
15400
+ known={user_home+"/.local/bin/fmix",user_home+"/.local/share/fmix/bin/fmix"}
15401
+ custom=os.environ.get("FMIX_INSTALL_DIR")
15402
+ if custom:
15403
+ custom=os.path.abspath(custom)
15404
+ if os.path.commonpath((user_home,custom))!=user_home: raise ValueError("unsafe_install_root")
15405
+ known.add(os.path.join(custom,"fmix"))
15406
+ paths=[]
15407
+ for path in sorted(known):
15408
+ try: link=os.lstat(path)
15409
+ except FileNotFoundError: continue
15410
+ parent=os.path.dirname(path)
15411
+ if os.path.commonpath((user_home,parent))!=user_home: raise ValueError("launcher_outside_home")
15412
+ rel=os.path.relpath(parent,user_home); current=user_home
15413
+ for part in (() if rel=="." else rel.split(os.sep)):
15414
+ current=os.path.join(current,part); st=os.lstat(current)
15415
+ if not stat.S_ISDIR(st.st_mode) or st.st_uid!=uid or stat.S_ISLNK(st.st_mode) or st.st_mode&0o022: raise ValueError("unsafe_launcher_parent")
15416
+ if not stat.S_ISLNK(link.st_mode) or link.st_uid!=uid or link.st_nlink!=1 or os.path.realpath(path)!=runner:
15417
+ raise ValueError("managed_launcher_downgrade")
15418
+ paths.append(path)
15419
+ return user_home,paths
15420
+ def require_managed_handoff():
15421
+ if uid==0 or os.geteuid()!=uid: raise ValueError("privileged_cleaner_forbidden")
15422
+ user_home,paths=managed_launcher_paths()
15423
+ if not paths or (entrypoint not in paths and entrypoint!=runner): raise ValueError("managed_launcher_handoff_unproven")
15424
+ runtime=home+"/runtime"; st=os.lstat(runtime)
15425
+ if not stat.S_ISDIR(st.st_mode) or st.st_uid!=uid or st.st_mode&0o022 or os.path.realpath(runtime)!=runtime:
15426
+ raise ValueError("unsafe_runner_runtime")
15427
+ fd=os.open(runner,os.O_RDONLY|getattr(os,"O_NOFOLLOW",0))
15428
+ try:
15429
+ info=os.fstat(fd)
15430
+ if not stat.S_ISREG(info.st_mode) or info.st_uid!=uid or info.st_nlink!=1 or info.st_mode&0o222 or not info.st_mode&0o111 or info.st_size>4*1024*1024:
15431
+ raise ValueError("unsafe_runner_identity")
15432
+ hasher=hashlib.sha256()
15433
+ for block in iter(lambda:os.read(fd,65536),b""):
15434
+ retirement_bound(len(block)); hasher.update(block)
15435
+ if identity(info)!=identity(os.fstat(fd)): raise ValueError("runner_identity_changed")
15436
+ digest=hasher.hexdigest()
15437
+ if runner!=runtime+"/fmix-"+digest or any(os.path.realpath(path)!=runner for path in paths):
15438
+ raise ValueError("managed_launcher_runner_mismatch")
15439
+ finally: os.close(fd)
15440
+ return digest
15441
+ def process_snapshot(candidate):
15442
+ command=["ps","-axo","pid=,ppid=,uid=,command="] if sys.platform=="darwin" else ["ps","-eo","pid=,ppid=,uid=,args="]
15443
+ result=subprocess.run(command,capture_output=True,timeout=4)
15444
+ retirement_bound(len(result.stdout)+len(result.stderr))
15445
+ if result.returncode or result.stderr: raise ValueError("process census incomplete")
15446
+ rows={}
15447
+ for line in result.stdout.decode("utf-8","strict").splitlines():
15448
+ fields=line.strip().split(None,3)
15449
+ if len(fields)!=4 or not all(fields[i].isdigit() for i in range(3)):
15450
+ raise ValueError("process row schema")
15451
+ pid,ppid,process_uid=map(int,fields[:3])
15452
+ rows[pid]=(ppid,process_uid,fields[3])
15453
+ foreign=[pid for pid,(_,process_uid,_) in rows.items() if process_uid!=uid]
15454
+ if foreign:
15455
+ raise ValueError(f"foreign_consumer_unknown:uid_scope={uid}:foreign_processes={len(foreign)}")
15456
+ entrypoint_row=rows.get(entrypoint_pid)
15457
+ entrypoint_command=entrypoint_row[2] if entrypoint_row else ""
15458
+ exact_entrypoint=(entrypoint_pid==os.getppid() and entrypoint in entrypoint_command
15459
+ and re.search(r"(?:^|\s)gc\s+--artifacts-only(?:\s|$)",entrypoint_command) is not None)
15460
+ for pid,(_,process_uid,command_line) in rows.items():
15461
+ if re.search(r"(^|/)fmix(?:\s|$)",command_line,re.I) and pid!=os.getpid():
15462
+ if pid!=entrypoint_pid or not exact_entrypoint:
15463
+ raise ValueError("active_fmix_process")
15464
+ if candidate in command_line:
15465
+ raise ValueError("process_reference")
15466
+ return {"sha256":sha(result.stdout),"uid_scope":uid,"coverage":"same-uid-only;foreign-uid-presence-holds",
15467
+ "process_count":len(rows),"foreign_process_count":0}
15468
+ def open_file_snapshot(candidate):
15469
+ command=["lsof","-nP","-a","-u",str(uid),"+D",candidate,"-Fpcfn"]
15470
+ proc=subprocess.Popen(command,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
15471
+ observer_pid=proc.pid
15472
+ try: output,error=proc.communicate(timeout=5)
15473
+ except subprocess.TimeoutExpired:
15474
+ proc.kill(); proc.communicate(); raise ValueError("open_file_census_timeout")
15475
+ retirement_bound(len(output)+len(error))
15476
+ if proc.returncode not in (0,1) or error: raise ValueError("open_file_census_incomplete")
15477
+ pid=None; names=[]; count=0
15478
+ for line in output.decode("utf-8","strict").splitlines():
15479
+ if line.startswith("p") and line[1:].isdigit(): pid=int(line[1:])
15480
+ elif line.startswith("n"):
15481
+ path=line[1:]
15482
+ if pid!=observer_pid and (path==candidate or path.startswith(candidate+os.sep)): count+=1
15483
+ return {"sha256":sha(output),"open_count":count,"uid_scope":uid,"coverage":"uid-only",
15484
+ "system_open_files_observer":"unsupported"}
15485
+ def liveness(candidate):
15486
+ process=process_snapshot(candidate)
15487
+ opened=open_file_snapshot(candidate)
15488
+ if opened["open_count"]: raise ValueError("open_file_reference")
15489
+ return {"process":process,"open_files":opened}
15490
+ def strict_load(raw):
15491
+ def pairs(items):
15492
+ result={}
15493
+ for key,value in items:
15494
+ if key in result: raise ValueError("duplicate JSON key")
15495
+ result[key]=value
15496
+ return result
15497
+ return json.loads(raw,object_pairs_hook=pairs,parse_constant=lambda _: (_ for _ in ()).throw(ValueError()))
15498
+ def mkdirs_safe(rel):
15499
+ parts=safe_parts(rel); fd=os.dup(rootfd)
15500
+ try:
15501
+ for part in parts:
15502
+ try: os.mkdir(part,0o700,dir_fd=fd)
15503
+ except FileExistsError: pass
15504
+ nxt=os.open(part,dir_flags,dir_fd=fd)
15505
+ st=os.fstat(nxt)
15506
+ if not stat.S_ISDIR(st.st_mode) or st.st_uid!=uid or st.st_dev!=home_st.st_dev:
15507
+ os.close(nxt); raise ValueError("unsafe retirement directory")
15508
+ os.close(fd); fd=nxt
15509
+ os.fsync(fd)
15510
+ finally: os.close(fd)
15511
+ def rename_noreplace(srcfd,src,dstfd,dst):
15512
+ libc=ctypes.CDLL(None,use_errno=True)
15513
+ if sys.platform=="darwin":
15514
+ fn=getattr(libc,"renameatx_np",None); flags=0x4
15515
+ elif sys.platform.startswith("linux"):
15516
+ fn=getattr(libc,"renameat2",None); flags=1
15517
+ else: fn=None; flags=0
15518
+ if fn is None: raise ValueError("atomic_noreplace_unavailable")
15519
+ fn.argtypes=[ctypes.c_int,ctypes.c_char_p,ctypes.c_int,ctypes.c_char_p,ctypes.c_uint]
15520
+ fn.restype=ctypes.c_int
15521
+ rc=fn(srcfd,os.fsencode(src),dstfd,os.fsencode(dst),flags)
15522
+ if rc:
15523
+ error=ctypes.get_errno()
15524
+ raise OSError(error,os.strerror(error))
15525
+ def write_json(rel,value,replace=False):
15526
+ parent,name=parent_and_name(rel)
15527
+ temp=f".{name}.tmp.{os.getpid()}.{time.time_ns()}"
15528
+ data=canonical(value)
15529
+ fd=os.open(temp,os.O_WRONLY|os.O_CREAT|os.O_EXCL|getattr(os,"O_NOFOLLOW",0),0o600,dir_fd=parent)
15530
+ try:
15531
+ view=memoryview(data)
15532
+ while view:
15533
+ count=os.write(fd,view); view=view[count:]
15534
+ os.fsync(fd)
15535
+ finally: os.close(fd)
15536
+ try:
15537
+ if replace:
15538
+ old=os.stat(name,dir_fd=parent,follow_symlinks=False)
15539
+ if not stat.S_ISREG(old.st_mode) or old.st_uid!=uid or old.st_dev!=home_st.st_dev or old.st_nlink!=1:
15540
+ raise ValueError("unsafe replacement target")
15541
+ else:
15542
+ try: os.stat(name,dir_fd=parent,follow_symlinks=False)
15543
+ except FileNotFoundError: pass
15544
+ else: raise FileExistsError(name)
15545
+ os.rename(temp,name,src_dir_fd=parent,dst_dir_fd=parent)
15546
+ os.fsync(parent)
15547
+ except Exception:
15548
+ try: os.unlink(temp,dir_fd=parent)
15549
+ except OSError: pass
15550
+ raise
15551
+ finally: os.close(parent)
15552
+ def read_json(rel):
15553
+ raw,identity_value=read_file(rel)
15554
+ return strict_load(raw),raw,identity_value
15555
+ def artifact_id_for(row):
15556
+ pool=row["pool"]
15557
+ prefix="template-v2" if pool=="template-v2" else "template" if pool=="template" else "dependency-v2" if pool=="dependency-v2" else "dependency"
15558
+ return prefix+":"+row["key"] if pool.startswith("template") else prefix+":"+row["lane"]+"/"+row["key"]
15559
+ def parse_artifact_id(value):
15560
+ for prefix,pool in (("template-v2","template-v2"),("template","template"),
15561
+ ("dependency-v2","dependency-v2"),("dependency","dependency")):
15562
+ if pool.startswith("template"):
15563
+ match=re.fullmatch(prefix+r":([0-9a-f]{16})",value or "")
15564
+ if match: return pool,None,match.group(1)
15565
+ else:
15566
+ match=re.fullmatch(prefix+r":([0-9a-f]{64})/([0-9a-f]{64})",value or "")
15567
+ if match: return pool,match.group(1),match.group(2)
15568
+ raise ValueError("invalid artifact identifier")
15569
+ def pool_kind(pool): return "template" if pool.startswith("template") else "dependency"
15570
+ def pool_v2(pool): return pool.endswith("-v2")
15571
+ def cache_rel(pool,lane,key):
15572
+ if pool=="template": return "templates/"+key
15573
+ if pool=="template-v2": return "artifacts/v2/templates/"+key
15574
+ if pool=="dependency": return "dependency-artifacts/v1/"+lane+"/"+key
15575
+ if pool=="dependency-v2": return "artifacts/v2/dependencies/"+lane+"/"+key
15576
+ raise ValueError("unknown artifact pool")
15577
+ def candidate_row(report,artifact_id):
15578
+ pool,lane,key=parse_artifact_id(artifact_id)
15579
+ matches=[row for row in report["entries"]
15580
+ if isinstance(row,dict) and row.get("pool")==pool and row.get("lane")==lane and row.get("key")==key]
15581
+ if len(matches)!=1: raise ValueError("candidate inventory is incomplete")
15582
+ row=matches[0]
15583
+ fields={"path","pool","key","lane","status","metadata_sha256","inspection","holds","identity",
15584
+ "manifest_sha256","reference_count","references","references_truncated"}
15585
+ if (set(row)!=fields or row.get("status")!="held" or row.get("inspection")!="metadata_and_manifest_shape_checked"
15586
+ or not isinstance(row.get("holds"),list) or any(not isinstance(v,str) for v in row["holds"])
15587
+ or type(row.get("reference_count")) is not int or not isinstance(row.get("references"),list)
15588
+ or not all(isinstance(v,str) for v in row["references"]) or type(row.get("references_truncated")) is not bool):
15589
+ raise ValueError("candidate inventory schema incomplete")
15590
+ if pool_kind(pool)=="template" and row["lane"] is not None: raise ValueError("template lane schema")
15591
+ if pool_kind(pool)=="dependency" and not hexkey(row["lane"],64): raise ValueError("dependency lane schema")
15592
+ expected=home+"/"+cache_rel(pool,lane,key)
15593
+ if row.get("path")!=expected: raise ValueError("candidate path identity mismatch")
15594
+ if pool_v2(pool): require_managed_handoff()
15595
+ return row,pool,lane,key,cache_rel(pool,lane,key)
15596
+ def candidate_holds(report,row):
15597
+ holds=set(row.get("holds",[]))-{"payload_verification_unproven"}
15598
+ if pool_v2(row["pool"]):
15599
+ meta,_=read_meta(row)
15600
+ if meta.get("consumer_protocol")!="fmix-native-artifacts.v2":
15601
+ holds.add("unknown_v2_consumer_protocol")
15602
+ holds-={"external_consumers_unknown","consumer_coverage_unproven",
15603
+ "fallback_preservation_unproven","liveness_unproven"}
15604
+ else:
15605
+ holds|=known_global_holds(report)
15606
+ holds.add("legacy_generation_unenrolled")
15607
+ if report.get("report_truncated"): holds.add("report_truncated")
15608
+ if row.get("reference_count")!=0 or row.get("references_truncated"):
15609
+ holds.add("native_workspace_reference")
15610
+ if row.get("status")!="held": holds.add("unexpected_inventory_state")
15611
+ if holds: raise ValueError(",".join(sorted(holds)))
15612
+ def lock_name(pool,lane,key):
15613
+ return "build-"+key if pool_kind(pool)=="template" else "dependency-artifact-"+lane[:16]+"-"+key[:16]
15614
+ LEASE_PROVIDER = """source "$FMIX_RETIREMENT_PROVIDER_RUNNER" || exit 70
15615
+ lock_name="$1"
15616
+ fmix_lock_acquire "$lock_name" 0 "artifact retirement" 1 || exit $?
15617
+ printf 'READY\\n'
15618
+ IFS= read -r request || request=""
15619
+ protocol_rc=0
15620
+ [[ "$request" == "release" ]] || protocol_rc=1
15621
+ release_rc=0
15622
+ fmix_lock_release "$lock_name" || release_rc=$?
15623
+ printf 'RELEASED %s\\n' "$release_rc"
15624
+ (( protocol_rc == 0 && release_rc == 0 ))"""
15625
+ def acquire_named_lease(name):
15626
+ child_env=os.environ.copy()
15627
+ child_env["FMIX_RETIREMENT_PROVIDER_RUNNER"]=runner
15628
+ proc=subprocess.Popen(["/bin/bash","-c",LEASE_PROVIDER,"fmix-artifact-lease",name],
15629
+ env=child_env,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,
15630
+ text=True,bufsize=1)
15631
+ ready,_,_=select.select([proc.stdout],[],[],15)
15632
+ if not ready:
15633
+ try:
15634
+ proc.stdin.write("release\n"); proc.stdin.flush()
15635
+ except (BrokenPipeError,OSError): pass
15636
+ try: proc.wait(timeout=15)
15637
+ except subprocess.TimeoutExpired: raise ValueError("artifact_lease_acquire_unconfirmed")
15638
+ raise ValueError("artifact_lease_ready_timeout")
15639
+ line=proc.stdout.readline()
15640
+ if line!="READY\n":
15641
+ try: proc.wait(timeout=15)
15642
+ except subprocess.TimeoutExpired: raise ValueError("artifact_lease_acquire_unconfirmed")
15643
+ raise ValueError("artifact_lease_acquire_failed:"+str(proc.returncode))
15644
+ return proc
15645
+ def acquire_lease(pool,lane,key):
15646
+ return acquire_named_lease(lock_name(pool,lane,key))
15647
+ RETIRE_ROOT="artifact-retirement/v2"
15648
+ def ensure_retirement_dirs():
15649
+ for rel in ("artifact-retirement","artifact-retirement/v2",
15650
+ "artifact-retirement/v2/pins","artifact-retirement/v2/adoptions",
15651
+ "artifact-retirement/v2/plans","artifact-retirement/v2/journals",
15652
+ "artifact-retirement/v2/receipts"):
15653
+ mkdirs_safe(rel)
15654
+ def list_names(rel):
15655
+ fd=open_dir(rel)
15656
+ try: return bounded_names(fd)
15657
+ finally: os.close(fd)
15658
+ def pin_path(pin_id):
15659
+ return RETIRE_ROOT+"/pins/"+pin_id+".json"
15660
+ def load_pins():
15661
+ pins=[]
15662
+ try: names=list_names(RETIRE_ROOT+"/pins")
15663
+ except FileNotFoundError: return pins
15664
+ for name in names:
15665
+ match=re.fullmatch(r"([0-9a-f]{32})\.json",name)
15666
+ if not match: raise ValueError("unknown_consumer_pin_layout")
15667
+ doc,raw,_=read_json(RETIRE_ROOT+"/pins/"+name)
15668
+ required={"schema","pin_id","artifact_id","consumer","created_at","uid"}
15669
+ if not isinstance(doc,dict) or set(doc)!=required or doc["schema"]!="fmix-artifact-pin.v2":
15670
+ raise ValueError("unknown_consumer_pin_schema")
15671
+ if (doc["pin_id"]!=match.group(1) or type(doc["uid"]) is not int
15672
+ or doc["uid"]!=uid or not re.fullmatch(r"[A-Za-z0-9._-]{1,80}",doc["consumer"])):
15673
+ raise ValueError("invalid_consumer_pin")
15674
+ parse_artifact_id(doc["artifact_id"])
15675
+ datetime.datetime.fromisoformat(doc["created_at"].replace("Z","+00:00"))
15676
+ pins.append(doc)
15677
+ return pins
15678
+ def pins_for(pins,artifact_id):
15679
+ return [pin["pin_id"] for pin in pins if pin["artifact_id"]==artifact_id]
15680
+ def adoption_path(artifact_id,identity_sha,runner_sha):
15681
+ key=sha((artifact_id+":"+identity_sha+":"+runner_sha).encode())
15682
+ return RETIRE_ROOT+"/adoptions/"+key+".json"
15683
+ def plan_path(plan_id):
15684
+ return RETIRE_ROOT+"/plans/"+plan_id+".json"
15685
+ def journal_path(plan_id):
15686
+ return RETIRE_ROOT+"/journals/"+plan_id+".json"
15687
+ def receipt_path(plan_id):
15688
+ return RETIRE_ROOT+"/receipts/"+plan_id+".json"
15689
+ def read_meta(row):
15690
+ pool=row["pool"]; kind=pool_kind(pool); v2=pool_v2(pool); lane=row.get("lane"); key=row["key"]
15691
+ if v2: require_managed_handoff()
15692
+ rel=cache_rel(pool,lane,key)+"/meta.json"
15693
+ raw,_=read_file(rel,1024*1024)
15694
+ if sha(raw)!=row.get("metadata_sha256"): raise ValueError("metadata digest changed")
15695
+ meta=strict_load(raw)
15696
+ dep_v1={"schema","lane","dependency_fingerprint","producer_sha","source_clean","manifest_sha256","built_at"}
15697
+ template_v1={"schema","status","template_key","manifest_sha256","built_at","toolchain","source_commit"}
15698
+ expected=(dep_v1 if kind=="dependency" else template_v1)
15699
+ if v2: expected=expected|{"producer_runner_sha256","consumer_protocol"}
15700
+ if not isinstance(meta,dict) or set(meta)!=expected or meta.get("schema")!=("2" if v2 else "1"):
15701
+ raise ValueError("metadata schema")
15702
+ if kind=="template" and (meta["status"]!="complete" or meta["template_key"]!=key
15703
+ or not meta["toolchain"] or not re.fullmatch(r"[0-9a-f]{7,40}",meta["source_commit"])):
15704
+ raise ValueError("template identity")
15705
+ if kind=="dependency" and (meta["lane"]!=lane or meta["dependency_fingerprint"]!=key
15706
+ or not re.fullmatch(r"[0-9a-f]{40}",meta["producer_sha"])
15707
+ or meta["source_clean"] not in ("true","false")):
15708
+ raise ValueError("dependency identity")
15709
+ if v2:
15710
+ digest=meta.get("producer_runner_sha256")
15711
+ if not hexkey(digest,64) or meta.get("consumer_protocol")!="fmix-native-artifacts.v2":
15712
+ raise ValueError("unknown_v2_consumer_protocol")
15713
+ producer,producer_id=read_file("runtime/fmix-"+digest,4*1024*1024)
15714
+ if sha(producer)!=digest or producer_id["mode"]&0o222 or not producer_id["mode"]&0o111:
15715
+ raise ValueError("producer_runner_identity")
15716
+ if not hexkey(meta["manifest_sha256"],64): raise ValueError("manifest digest")
15717
+ built=datetime.datetime.fromisoformat(meta["built_at"].replace("Z","+00:00"))
15718
+ if built.tzinfo is None: raise ValueError("timestamp timezone")
15719
+ return meta,built
15720
+ def last_access(row,pool,lane,key,built):
15721
+ if pool_v2(pool):
15722
+ rel=("artifact-access/v2/templates/"+key if pool_kind(pool)=="template"
15723
+ else "artifact-access/v2/dependencies/"+lane+"/"+key)
15724
+ else:
15725
+ rel=("template-access/"+key if pool_kind(pool)=="template"
15726
+ else "dependency-artifact-access/"+lane+"/"+key)
15727
+ try: raw,_=read_file(rel,128)
15728
+ except FileNotFoundError: return built
15729
+ value=raw.decode("ascii").strip()
15730
+ try: access=datetime.datetime.fromisoformat(value.replace("Z","+00:00"))
15731
+ except ValueError: raise ValueError("invalid access timestamp")
15732
+ if access.tzinfo is None: raise ValueError("access timestamp timezone")
15733
+ return max(built,access)
15734
+ def fallbacks(report):
15735
+ groups={}; broken=set(); unknown_template=False
15736
+ for row in report.get("entries",[]):
15737
+ try:
15738
+ meta,built=read_meta(row)
15739
+ kind=pool_kind(row["pool"])
15740
+ group=(kind,meta["toolchain"] if kind=="template" else row["lane"])
15741
+ groups.setdefault(group,[]).append((built,artifact_id_for(row)))
15742
+ except Exception:
15743
+ if pool_kind(row["pool"])=="template": unknown_template=True
15744
+ else: broken.add(row.get("lane"))
15745
+ protected=set()
15746
+ for group,items in groups.items():
15747
+ newest=max(value for value,_ in items)
15748
+ protected.update(artifact_id for value,artifact_id in items if value==newest)
15749
+ return protected,broken,unknown_template
15750
+ def retirement_fallback_recheck(report,journal):
15751
+ pool,lane,key=parse_artifact_id(journal["artifact_id"]); kind=pool_kind(pool)
15752
+ meta=journal["snapshot"]["meta"]
15753
+ built=datetime.datetime.fromisoformat(meta["built_at"].replace("Z","+00:00"))
15754
+ protected,broken,unknown=fallbacks(report)
15755
+ if kind=="template" and unknown: raise ValueError("fallback_lane_unknown")
15756
+ if lane in broken: raise ValueError("fallback_lane_incomplete")
15757
+ group=meta["toolchain"] if kind=="template" else lane
15758
+ remaining=[]
15759
+ for row in report.get("entries",[]):
15760
+ if pool_kind(row["pool"])!=kind: continue
15761
+ try:
15762
+ other,built_other=read_meta(row)
15763
+ if (other["toolchain"] if kind=="template" else row["lane"])==group:
15764
+ remaining.append(built_other)
15765
+ except Exception: raise ValueError("fallback_lane_incomplete")
15766
+ if not remaining or max(remaining)<=built: raise ValueError("fallback_became_newest")
15767
+ def verify_tree(row,base_rel=None,allow_owner_write=False):
15768
+ pool=row["pool"]; kind=pool_kind(pool); v2=pool_v2(pool); lane=row.get("lane"); key=row["key"]
15769
+ if v2: require_managed_handoff()
15770
+ base_rel=base_rel or cache_rel(pool,lane,key)
15771
+ rootfd_cache=open_dir(base_rel); rootst=os.fstat(rootfd_cache)
15772
+ if rootst.st_uid!=uid or rootst.st_dev!=home_st.st_dev: raise ValueError("foreign cache identity")
15773
+ no_markers(base_rel,rootst)
15774
+ if rootst.st_mode&0o222 and not (allow_owner_write and rootst.st_mode&0o200 and not rootst.st_mode&0o022):
15775
+ raise ValueError("writable cache root")
15776
+ reported=row.get("identity",{})
15777
+ audit_fields={"device","inode","uid","mode","mtime_ns","ctime_ns"}
15778
+ if set(reported)!=audit_fields or any(reported.get(k)!=identity(rootst).get(k) for k in audit_fields):
15779
+ os.close(rootfd_cache); raise ValueError("candidate identity incomplete or changed")
15780
+ try:
15781
+ names=bounded_names(rootfd_cache)
15782
+ if names!=["_build","deps","manifest.sha256","manifest.tsv","meta.json"]:
15783
+ raise ValueError("unexpected cache contents")
15784
+ meta_raw,meta_id=read_file(base_rel+"/meta.json",1024*1024)
15785
+ meta=strict_load(meta_raw)
15786
+ dep_fields={"schema","lane","dependency_fingerprint","producer_sha","source_clean","manifest_sha256","built_at"}
15787
+ template_fields={"schema","status","template_key","manifest_sha256","built_at","toolchain","source_commit"}
15788
+ if v2:
15789
+ dep_fields|={"producer_runner_sha256","consumer_protocol"}
15790
+ template_fields|={"producer_runner_sha256","consumer_protocol"}
15791
+ expected_fields=dep_fields if kind=="dependency" else template_fields
15792
+ if not isinstance(meta,dict) or set(meta)!=expected_fields or meta.get("schema")!=("2" if v2 else "1"):
15793
+ raise ValueError("metadata schema")
15794
+ if kind=="dependency" and (meta["lane"]!=lane or meta["dependency_fingerprint"]!=key
15795
+ or not re.fullmatch(r"[0-9a-f]{40}",meta["producer_sha"])
15796
+ or meta["source_clean"] not in ("true","false")):
15797
+ raise ValueError("dependency metadata identity")
15798
+ if kind=="template" and (meta["status"]!="complete" or meta["template_key"]!=key
15799
+ or not meta["toolchain"] or not re.fullmatch(r"[0-9a-f]{7,40}",meta["source_commit"])):
15800
+ raise ValueError("template metadata identity")
15801
+ if v2:
15802
+ digest=meta.get("producer_runner_sha256")
15803
+ if not hexkey(digest,64) or meta.get("consumer_protocol")!="fmix-native-artifacts.v2":
15804
+ raise ValueError("unknown_v2_consumer_protocol")
15805
+ producer,producer_id=read_file("runtime/fmix-"+digest,4*1024*1024)
15806
+ if sha(producer)!=digest or producer_id["mode"]&0o222 or not producer_id["mode"]&0o111:
15807
+ raise ValueError("producer_runner_identity")
15808
+ manifest,manifest_id=read_file(base_rel+"/manifest.tsv",8*1024*1024)
15809
+ recorded,recorded_id=read_file(base_rel+"/manifest.sha256",256)
15810
+ if sha(meta_raw)!=row.get("metadata_sha256"): raise ValueError("metadata digest changed")
15811
+ if sha(manifest)!=meta.get("manifest_sha256") or recorded!=(meta["manifest_sha256"]+"\n").encode():
15812
+ raise ValueError("manifest digest mismatch")
15813
+ fields=meta
15814
+ if not isinstance(fields,dict): raise ValueError("metadata object")
15815
+ records={}
15816
+ for line in manifest.decode("utf-8","strict").splitlines():
15817
+ retirement_bound(entry_count=1)
15818
+ parts=line.split("\t")
15819
+ if len(parts)<3: raise ValueError("manifest row")
15820
+ kind,path=parts[:2]; safe_parts(path)
15821
+ if path.split("/")[0] not in ("deps","_build") or path in records:
15822
+ raise ValueError("manifest path")
15823
+ if kind=="D" and parts==["D",path,"-"]: pass
15824
+ elif kind=="F" and len(parts)==4 and parts[2].isdigit() and re.fullmatch(r"[0-9a-f]{64}",parts[3]): pass
15825
+ elif kind=="L" and len(parts)==3: pass
15826
+ else: raise ValueError("manifest entry")
15827
+ records[path]=parts
15828
+ seen=set(); nodes={"":identity(rootst)}
15829
+ directories=[]
15830
+ def walk(fd,prefix):
15831
+ for name in bounded_names(fd):
15832
+ rel=prefix+"/"+name
15833
+ st=os.stat(name,dir_fd=fd,follow_symlinks=False)
15834
+ if st.st_uid!=uid or st.st_dev!=home_st.st_dev: raise ValueError("foreign payload")
15835
+ if (not stat.S_ISLNK(st.st_mode) and st.st_mode&0o222
15836
+ and not (allow_owner_write and stat.S_ISDIR(st.st_mode)
15837
+ and st.st_mode&0o200 and not st.st_mode&0o022)):
15838
+ raise ValueError("writable payload")
15839
+ no_markers(base_rel+"/"+rel,st)
15840
+ entry=records.get(rel)
15841
+ if entry is None: raise ValueError("unmanifested payload")
15842
+ seen.add(rel); nodes[rel]=identity(st)
15843
+ if stat.S_ISLNK(st.st_mode):
15844
+ target=os.readlink(name,dir_fd=fd)
15845
+ normalized=os.path.normpath(os.path.join(prefix,target))
15846
+ if entry!=["L",rel,target] or os.path.isabs(target) or normalized==".." or normalized.startswith("../"):
15847
+ raise ValueError("unsafe manifest link")
15848
+ elif stat.S_ISDIR(st.st_mode):
15849
+ if entry!=["D",rel,"-"]: raise ValueError("directory manifest mismatch")
15850
+ directories.append(rel)
15851
+ child=os.open(name,dir_flags,dir_fd=fd)
15852
+ try: walk(child,rel)
15853
+ finally: os.close(child)
15854
+ elif stat.S_ISREG(st.st_mode):
15855
+ if len(entry)!=4 or entry[0]!="F" or st.st_nlink!=1:
15856
+ raise ValueError("file manifest mismatch")
15857
+ filefd=os.open(name,os.O_RDONLY|getattr(os,"O_NOFOLLOW",0),dir_fd=fd)
15858
+ try:
15859
+ before=os.fstat(filefd)
15860
+ if identity(before)!=identity(st): raise ValueError("payload changed")
15861
+ digest=hashlib.sha256(); size=0
15862
+ while True:
15863
+ data=os.read(filefd,1024*1024)
15864
+ if not data: break
15865
+ retirement_bound(len(data))
15866
+ size+=len(data); digest.update(data)
15867
+ if size!=int(entry[2]) or digest.hexdigest()!=entry[3]:
15868
+ raise ValueError("payload digest mismatch")
15869
+ if identity(before)!=identity(os.fstat(filefd)): raise ValueError("payload changed while hashing")
15870
+ finally: os.close(filefd)
15871
+ else: raise ValueError("special payload")
15872
+ for top in ("deps","_build"):
15873
+ topfd=os.open(top,dir_flags,dir_fd=rootfd_cache)
15874
+ try:
15875
+ topst=os.fstat(topfd)
15876
+ if topst.st_uid!=uid or topst.st_dev!=home_st.st_dev: raise ValueError("unsafe payload root")
15877
+ if topst.st_mode&0o222 and not (allow_owner_write and topst.st_mode&0o200 and not topst.st_mode&0o022):
15878
+ raise ValueError("writable payload root")
15879
+ no_markers(base_rel+"/"+top,topst)
15880
+ nodes[top]=identity(topst); directories.append(top)
15881
+ walk(topfd,top)
15882
+ finally: os.close(topfd)
15883
+ if seen!=set(records): raise ValueError("manifest path set mismatch")
15884
+ for name,info_value in (("meta.json",meta_id),("manifest.tsv",manifest_id),
15885
+ ("manifest.sha256",recorded_id)):
15886
+ st=os.stat(name,dir_fd=rootfd_cache,follow_symlinks=False)
15887
+ if st.st_uid!=uid or st.st_dev!=home_st.st_dev or st.st_nlink!=1 or not stat.S_ISREG(st.st_mode):
15888
+ raise ValueError("unsafe metadata identity")
15889
+ if st.st_mode&0o222: raise ValueError("writable metadata file")
15890
+ if identity(st)!=info_value: raise ValueError("metadata changed during inventory")
15891
+ no_markers(base_rel+"/"+name,st); nodes[name]=info_value
15892
+ snapshot={"nodes":nodes,"manifest_sha256":sha(manifest),"metadata_sha256":sha(meta_raw),
15893
+ "directories":sorted(directories),"meta":meta,"records":records}
15894
+ snapshot["identity_sha256"]=sha(canonical(nodes))
15895
+ return snapshot
15896
+ finally: os.close(rootfd_cache)
15897
+ def check_aliases(report,row):
15898
+ root_id=row.get("identity",{})
15899
+ seen=set()
15900
+ for other in report.get("entries",[]):
15901
+ ident=other.get("identity",{})
15902
+ key=(ident.get("device"),ident.get("inode"))
15903
+ if key[0] is None or key[1] is None: raise ValueError("alias census incomplete")
15904
+ if key in seen: raise ValueError("candidate alias")
15905
+ seen.add(key)
15906
+ if other is not row and key==(root_id.get("device"),root_id.get("inode")):
15907
+ raise ValueError("candidate alias")
15908
+ def evidence(report,row,artifact_id,runner_sha,allow_references=False):
15909
+ require_managed_handoff()
15910
+ if not allow_references and row.get("reference_count")!=0:
15911
+ raise ValueError("native_workspace_reference")
15912
+ pins=load_pins()
15913
+ if pins_for(pins,artifact_id): raise ValueError("consumer_pin")
15914
+ check_aliases(report,row)
15915
+ full=verify_tree(row)
15916
+ live=liveness(row["path"])
15917
+ if live["open_files"]["open_count"]: raise ValueError("open_file_reference")
15918
+ require_managed_handoff()
15919
+ return {"row":row,"pins_sha256":sha(canonical(pins)),"liveness":live,
15920
+ "full":full,"report_sha256":sha(canonical(report)),
15921
+ "runner_sha256":runner_sha}
15922
+ def adoption_record(artifact_id,proof,runner_sha):
15923
+ return {"schema":"fmix-artifact-adoption.v2","artifact_id":artifact_id,
15924
+ "uid_scope":uid,"coverage":"fmix-native-artifacts.v2+uid-only-open-files",
15925
+ "adopted_at":now.isoformat(),"runner_sha256":runner_sha,
15926
+ "report_sha256":proof["report_sha256"],
15927
+ "manifest_sha256":proof["full"]["manifest_sha256"],
15928
+ "metadata_sha256":proof["full"]["metadata_sha256"],
15929
+ "identity_sha256":proof["full"]["identity_sha256"],
15930
+ "pins_sha256":proof["pins_sha256"],
15931
+ "process_sha256":proof["liveness"]["process"]["sha256"],
15932
+ "openfile_sha256":proof["liveness"]["open_files"]["sha256"]}
15933
+ def load_adoption(artifact_id,proof,runner_sha):
15934
+ rel=adoption_path(artifact_id,proof["full"]["identity_sha256"],runner_sha)
15935
+ try: doc,raw,_=read_json(rel)
15936
+ except FileNotFoundError: return None
15937
+ required={"schema","artifact_id","uid_scope","coverage","adopted_at","runner_sha256",
15938
+ "report_sha256","manifest_sha256","metadata_sha256","identity_sha256",
15939
+ "pins_sha256","process_sha256","openfile_sha256"}
15940
+ if not isinstance(doc,dict) or set(doc)!=required or doc["schema"]!="fmix-artifact-adoption.v2":
15941
+ raise ValueError("unknown_adoption_schema")
15942
+ if doc["artifact_id"]!=artifact_id or doc["uid_scope"]!=uid or doc["coverage"]!="fmix-native-artifacts.v2+uid-only-open-files":
15943
+ raise ValueError("adoption_identity_mismatch")
15944
+ for key,value in (("runner_sha256",runner_sha),("manifest_sha256",proof["full"]["manifest_sha256"]),
15945
+ ("metadata_sha256",proof["full"]["metadata_sha256"]),
15946
+ ("identity_sha256",proof["full"]["identity_sha256"]),
15947
+ ("pins_sha256",proof["pins_sha256"])):
15948
+ if doc[key]!=value: raise ValueError("stale_adoption")
15949
+ datetime.datetime.fromisoformat(doc["adopted_at"].replace("Z","+00:00"))
15950
+ return doc
15951
+ def store_adoption(artifact_id,proof,runner_sha):
15952
+ if not pool_v2(parse_artifact_id(artifact_id)[0]): raise ValueError("legacy_generation_unenrolled")
15953
+ require_managed_handoff()
15954
+ doc=adoption_record(artifact_id,proof,runner_sha)
15955
+ require_managed_handoff()
15956
+ write_json(adoption_path(artifact_id,doc["identity_sha256"],runner_sha),doc)
15957
+ return doc
15958
+ def access_baseline(row,pool,lane,key,proof):
15959
+ meta,built=read_meta(row)
15960
+ access=last_access(row,pool,lane,key,built)
15961
+ adoption=load_adoption(artifact_id_for(row),proof,proof["runner_sha256"])
15962
+ adopted=datetime.datetime.fromisoformat(adoption["adopted_at"].replace("Z","+00:00")) if adoption else now
15963
+ return max(built,access,adopted),adoption
15964
+ def ttl_hours(pool):
15965
+ return int(dep_ttl if pool_kind(pool)=="dependency" else template_ttl)
15966
+ def make_owned_directories_writable(base_rel,snapshot):
15967
+ changes=[]
15968
+ for rel in sorted([""]+snapshot["directories"],key=lambda value:value.count("/")):
15969
+ target=base_rel+("/"+rel if rel else "")
15970
+ fd=open_dir(target)
15971
+ try:
15972
+ st=os.fstat(fd); expected=snapshot["nodes"].get(rel)
15973
+ if expected is None or st.st_uid!=uid or st.st_dev!=home_st.st_dev:
15974
+ raise ValueError("directory ownership changed")
15975
+ if (st.st_ino!=expected["inode"] or stat.S_IFMT(st.st_mode)!=stat.S_IFMT(expected["mode"])
15976
+ or st.st_mtime_ns!=expected["mtime_ns"] or st.st_size!=expected["size"]):
15977
+ raise ValueError("directory identity changed")
15978
+ no_markers(target,st)
15979
+ baseline=stat.S_IMODE(expected["mode"]); old=stat.S_IMODE(st.st_mode)
15980
+ new=baseline|stat.S_IWUSR
15981
+ if old not in (baseline,new): raise ValueError("directory permissions changed")
15982
+ if old!=new: os.fchmod(fd,new)
15983
+ after=os.fstat(fd)
15984
+ if after.st_ino!=st.st_ino or after.st_uid!=uid or stat.S_IMODE(after.st_mode)!=new:
15985
+ raise ValueError("owner-write restoration mismatch")
15986
+ changes.append({"path":rel,"from":old,"to":new})
15987
+ finally: os.close(fd)
15988
+ return changes
15989
+ def remove_verified_tree(base_rel,snapshot,delete=True):
15990
+ parent,name=parent_and_name(base_rel)
15991
+ root=os.open(name,dir_flags,dir_fd=parent)
15992
+ try:
15993
+ rootst=os.fstat(root); expected=snapshot["nodes"][""]
15994
+ if rootst.st_dev!=expected["device"] or rootst.st_ino!=expected["inode"] or rootst.st_uid!=uid:
15995
+ raise ValueError("quarantine root identity changed")
15996
+ def exact_file(fd,leaf,rel,expected_stat,digest):
15997
+ filefd=os.open(leaf,os.O_RDONLY|getattr(os,"O_NOFOLLOW",0),dir_fd=fd)
15998
+ try:
15999
+ st=os.fstat(filefd)
16000
+ if identity(st)!=expected_stat or not stat.S_ISREG(st.st_mode) or st.st_nlink!=1:
16001
+ raise ValueError("file identity changed before unlink")
16002
+ value=hashlib.sha256()
16003
+ while True:
16004
+ data=os.read(filefd,1024*1024)
16005
+ if not data: break
16006
+ retirement_bound(len(data))
16007
+ value.update(data)
16008
+ if value.hexdigest()!=digest: raise ValueError("file content changed before unlink")
16009
+ finally: os.close(filefd)
16010
+ if identity(os.stat(leaf,dir_fd=fd,follow_symlinks=False))!=expected_stat:
16011
+ raise ValueError("file replaced before unlink")
16012
+ if delete: os.unlink(leaf,dir_fd=fd)
16013
+ def walk(fd,prefix):
16014
+ for leaf in bounded_names(fd):
16015
+ rel=prefix+"/"+leaf if prefix else leaf
16016
+ expected_stat=snapshot["nodes"].get(rel)
16017
+ if expected_stat is None: raise ValueError("unreceipted quarantine entry")
16018
+ st=os.stat(leaf,dir_fd=fd,follow_symlinks=False)
16019
+ if st.st_dev!=expected_stat["device"] or st.st_ino!=expected_stat["inode"] or st.st_uid!=uid:
16020
+ raise ValueError("quarantine entry identity changed")
16021
+ no_markers(base_rel+"/"+rel,st)
16022
+ if stat.S_ISDIR(st.st_mode) and stat.S_ISDIR(expected_stat["mode"]):
16023
+ if stat.S_IMODE(st.st_mode)!=expected_stat["mode"]&0o7777:
16024
+ raise ValueError("directory mode changed")
16025
+ child=os.open(leaf,dir_flags,dir_fd=fd)
16026
+ try: walk(child,rel)
16027
+ finally: os.close(child)
16028
+ checkfd=os.open(leaf,dir_flags,dir_fd=fd)
16029
+ try:
16030
+ if delete and bounded_names(checkfd): raise ValueError("directory gained entries during removal")
16031
+ finally: os.close(checkfd)
16032
+ current=os.stat(leaf,dir_fd=fd,follow_symlinks=False)
16033
+ if current.st_dev!=st.st_dev or current.st_ino!=st.st_ino or current.st_uid!=uid:
16034
+ raise ValueError("directory replaced during removal")
16035
+ if delete: os.rmdir(leaf,dir_fd=fd)
16036
+ elif stat.S_ISREG(st.st_mode):
16037
+ if rel in snapshot["records"]:
16038
+ expected_digest=snapshot["records"][rel][3]
16039
+ elif rel=="meta.json": expected_digest=snapshot["metadata_sha256"]
16040
+ elif rel=="manifest.tsv": expected_digest=snapshot["manifest_sha256"]
16041
+ elif rel=="manifest.sha256": expected_digest=sha((snapshot["meta"]["manifest_sha256"]+"\n").encode())
16042
+ else: raise ValueError("unreceipted file")
16043
+ exact_file(fd,leaf,rel,expected_stat,expected_digest)
16044
+ elif stat.S_ISLNK(st.st_mode):
16045
+ row=snapshot["records"].get(rel)
16046
+ if not row or row[0]!="L" or os.readlink(leaf,dir_fd=fd)!=row[2]:
16047
+ raise ValueError("symlink identity changed")
16048
+ if identity(os.stat(leaf,dir_fd=fd,follow_symlinks=False))!=expected_stat:
16049
+ raise ValueError("symlink replaced before unlink")
16050
+ if delete: os.unlink(leaf,dir_fd=fd)
16051
+ else: raise ValueError("special quarantine entry")
16052
+ walk(root,"")
16053
+ if delete:
16054
+ if bounded_names(root): raise ValueError("quarantine gained entries")
16055
+ os.close(root); root=None
16056
+ current=os.stat(name,dir_fd=parent,follow_symlinks=False)
16057
+ if current.st_dev!=expected["device"] or current.st_ino!=expected["inode"] or current.st_uid!=uid:
16058
+ raise ValueError("quarantine root replaced before rmdir")
16059
+ os.rmdir(name,dir_fd=parent); os.fsync(parent)
16060
+ else:
16061
+ os.close(root); root=None
16062
+ finally:
16063
+ if root is not None: os.close(root)
16064
+ os.close(parent)
16065
+ def policy_sha(execution_mode):
16066
+ return sha(canonical({"schema":"fmix-artifact-retirement-policy.v2",
16067
+ "dependency_ttl_hours":int(dep_ttl),"template_ttl_hours":int(template_ttl),
16068
+ "max_candidates_per_preparation":1,"max_work_seconds":45,
16069
+ "max_read_bytes":8*1024*1024*1024,"max_tree_entries":4000000,
16070
+ "execution_mode":execution_mode,"uid_scope":uid,
16071
+ "fallback":"newest-per-compatible-lane"}))
16072
+ def create_plan(artifact_id,report,row,proof,runner_sha,protected,broken,unknown_template,execution_mode):
16073
+ if not pool_v2(row["pool"]): raise ValueError("legacy_generation_unenrolled")
16074
+ require_managed_handoff()
16075
+ if artifact_id in protected: raise ValueError("fallback_preserved")
16076
+ if pool_kind(row["pool"])=="template" and unknown_template: raise ValueError("fallback_lane_unknown")
16077
+ if row.get("lane") in broken: raise ValueError("fallback_lane_incomplete")
16078
+ if execution_mode not in ("manual","automatic"): raise ValueError("invalid_retirement_mode")
16079
+ adoption=load_adoption(artifact_id,proof,runner_sha)
16080
+ if adoption is None:
16081
+ adoption=store_adoption(artifact_id,proof,runner_sha)
16082
+ if execution_mode=="automatic": return None
16083
+ age=0.0
16084
+ if execution_mode=="automatic":
16085
+ baseline,_=access_baseline(row,row["pool"],row.get("lane"),row["key"],proof)
16086
+ age=(now-baseline).total_seconds()
16087
+ if age<int(ttl_hours(row["pool"]))*3600: raise ValueError("idle_ttl_not_elapsed")
16088
+ doc={"schema":"fmix-artifact-retirement-plan.v2","artifact_id":artifact_id,
16089
+ "home":home,"uid_scope":uid,"runner_sha256":runner_sha,
16090
+ "execution_mode":execution_mode,"policy_sha256":policy_sha(execution_mode),
16091
+ "report_sha256":proof["report_sha256"],"manifest_sha256":proof["full"]["manifest_sha256"],
16092
+ "metadata_sha256":proof["full"]["metadata_sha256"],
16093
+ "identity_sha256":proof["full"]["identity_sha256"],
16094
+ "pins_sha256":proof["pins_sha256"],"adoption_sha256":sha(canonical(adoption)),
16095
+ "process_sha256":proof["liveness"]["process"]["sha256"],
16096
+ "openfile_sha256":proof["liveness"]["open_files"]["sha256"],
16097
+ "created_at":now.isoformat(),"idle_hours":age/3600}
16098
+ plan_id=sha(canonical(doc)); doc["plan_id"]=plan_id
16099
+ require_managed_handoff()
16100
+ write_json(plan_path(plan_id),doc)
16101
+ return doc
16102
+ def read_plan(plan_id,allow_stale=False):
16103
+ doc,raw,_=read_json(plan_path(plan_id))
16104
+ expected={"schema","artifact_id","home","uid_scope","runner_sha256","execution_mode","policy_sha256",
16105
+ "report_sha256","manifest_sha256","metadata_sha256","identity_sha256","pins_sha256",
16106
+ "adoption_sha256","process_sha256","openfile_sha256","created_at","idle_hours","plan_id"}
16107
+ if not isinstance(doc,dict) or set(doc)!=expected or doc.get("schema")!="fmix-artifact-retirement-plan.v2":
16108
+ raise ValueError("unknown_retirement_plan_schema")
16109
+ stored=dict(doc); actual=stored.pop("plan_id",None)
16110
+ if actual!=plan_id or sha(canonical(stored))!=plan_id: raise ValueError("retirement_plan_digest_mismatch")
16111
+ if (doc.get("home")!=home or type(doc.get("uid_scope")) is not int or doc.get("uid_scope")!=uid
16112
+ or doc.get("execution_mode") not in ("manual","automatic")
16113
+ or doc.get("policy_sha256")!=policy_sha(doc["execution_mode"])):
16114
+ raise ValueError("retirement_plan_context_mismatch")
16115
+ for field in ("runner_sha256","policy_sha256","report_sha256","manifest_sha256","metadata_sha256","identity_sha256","pins_sha256","adoption_sha256","process_sha256","openfile_sha256"):
16116
+ if not hexkey(doc.get(field),64): raise ValueError("retirement_plan_digest")
16117
+ created=datetime.datetime.fromisoformat(doc["created_at"].replace("Z","+00:00"))
16118
+ if created.tzinfo is None or created>now+datetime.timedelta(seconds=30): raise ValueError("retirement_plan_timestamp")
16119
+ if (now-created).total_seconds()>600 and not allow_stale: raise ValueError("retirement_plan_stale")
16120
+ return doc
16121
+ def register_pin(artifact_id,consumer):
16122
+ require_managed_handoff()
16123
+ report,runner_sha=run_audit()
16124
+ row,pool,lane,key,rel=candidate_row(report,artifact_id)
16125
+ if not pool_v2(pool): raise ValueError("legacy_generation_unenrolled")
16126
+ verify_tree(row)
16127
+ require_managed_handoff()
16128
+ pins=load_pins()
16129
+ pin_id=sha((str(uid)+":"+artifact_id+":"+consumer).encode())[:32]
16130
+ doc={"schema":"fmix-artifact-pin.v2","pin_id":pin_id,"artifact_id":artifact_id,
16131
+ "consumer":consumer,"created_at":now.isoformat(),"uid":uid}
16132
+ for pin in pins:
16133
+ if pin["pin_id"]==pin_id:
16134
+ stable=("schema","pin_id","artifact_id","consumer","uid")
16135
+ if any(pin[field]!=doc[field] for field in stable):
16136
+ raise ValueError("consumer pin identity conflict")
16137
+ return {"status":"already_pinned","pin_id":pin_id,"artifact_id":artifact_id}
16138
+ write_json(pin_path(pin_id),doc)
16139
+ return {"status":"pinned","pin_id":pin_id,"artifact_id":artifact_id}
16140
+ def unregister_pin(pin_id,artifact_id,consumer):
16141
+ require_managed_handoff()
16142
+ pins=load_pins()
16143
+ matches=[pin for pin in pins if pin["pin_id"]==pin_id]
16144
+ if len(matches)!=1: raise ValueError("pin_not_found_or_ambiguous")
16145
+ if matches[0]["artifact_id"]!=artifact_id: raise ValueError("pin_target_changed")
16146
+ if matches[0]["consumer"]!=consumer: raise ValueError("pin_owner_mismatch")
16147
+ require_managed_handoff()
16148
+ parent,name=parent_and_name(pin_path(pin_id))
16149
+ try:
16150
+ st=os.stat(name,dir_fd=parent,follow_symlinks=False)
16151
+ if not stat.S_ISREG(st.st_mode) or st.st_uid!=uid or st.st_nlink!=1:
16152
+ raise ValueError("unsafe pin file")
16153
+ os.unlink(name,dir_fd=parent); os.fsync(parent)
16154
+ finally: os.close(parent)
16155
+ return {"status":"unpinned","pin_id":pin_id,"artifact_id":artifact_id}
16156
+ def fresh_proof(artifact_id):
16157
+ report,runner_sha=run_audit()
16158
+ row,pool,lane,key,rel=candidate_row(report,artifact_id)
16159
+ protected,broken,unknown_template=fallbacks(report)
16160
+ proof=evidence(report,row,artifact_id,runner_sha)
16161
+ if artifact_id in protected: raise ValueError("fallback_preserved")
16162
+ if pool_kind(pool)=="template" and unknown_template: raise ValueError("fallback_lane_unknown")
16163
+ if lane in broken: raise ValueError("fallback_lane_incomplete")
16164
+ candidate_holds(report,row)
16165
+ return report,runner_sha,row,pool,lane,key,rel,proof,protected
16166
+ def snapshots_match(before,after,phase="rename"):
16167
+ if (before["manifest_sha256"]!=after["manifest_sha256"]
16168
+ or before["metadata_sha256"]!=after["metadata_sha256"]
16169
+ or before["records"]!=after["records"]
16170
+ or set(before["nodes"])!=set(after["nodes"])):
16171
+ raise ValueError("quarantine manifest changed")
16172
+ directories=set(before["directories"])|{""}
16173
+ for path,old in before["nodes"].items():
16174
+ new=after["nodes"][path]
16175
+ stable=("device","inode","uid","size","mtime_ns","nlink","flags")
16176
+ if any(old.get(key)!=new.get(key) for key in stable):
16177
+ raise ValueError("quarantine identity changed")
16178
+ if path in directories and phase=="permissions":
16179
+ if new["mode"] not in (old["mode"],old["mode"]|stat.S_IWUSR):
16180
+ raise ValueError("unexpected directory mode change")
16181
+ elif old["mode"]!=new["mode"]:
16182
+ raise ValueError("unexpected payload mode change")
16183
+ if path not in directories and old.get("ctime_ns")!=new.get("ctime_ns"):
16184
+ raise ValueError("unexpected file metadata change")
16185
+ def late_references(report,pool,lane,key):
16186
+ field="template_key" if pool_kind(pool)=="template" else "dependency_fingerprint"
16187
+ for observation in report.get("observations",[]):
16188
+ refs=observation.get("references",{})
16189
+ if refs.get(field)==key: raise ValueError("late_native_workspace_reference")
16190
+ def exists_rel(rel):
16191
+ parent,name=parent_and_name(rel)
16192
+ try:
16193
+ try: os.stat(name,dir_fd=parent,follow_symlinks=False); return True
16194
+ except FileNotFoundError: return False
16195
+ finally: os.close(parent)
16196
+ def validate_journal(doc,plan_id):
16197
+ base={"schema","plan_id","artifact_id","home","uid_scope","state","source_rel",
16198
+ "quarantine_rel","runner_sha256","report_sha256","plan_sha256",
16199
+ "original_identity_sha256","original_manifest_sha256",
16200
+ "original_metadata_sha256","snapshot","created_at"}
16201
+ tails={"intent":set(),"quarantined":{"quarantined_at"},
16202
+ "permissions_pending":{"quarantined_at","permission_started_at"},
16203
+ "deleting":{"quarantined_at","permission_started_at","permission_changes","delete_started_at"},
16204
+ "complete":{"quarantined_at","permission_started_at","permission_changes","delete_started_at","completed_at"},
16205
+ "restored_hold":{"hold_reason","restored_at"}}
16206
+ if not isinstance(doc,dict) or doc.get("schema")!="fmix-artifact-retirement-journal.v2":
16207
+ raise ValueError("unknown_retirement_journal_schema")
16208
+ state=doc.get("state")
16209
+ expected=base|tails.get(state,set())
16210
+ if state=="restored_hold" and "quarantined_at" in doc: expected.add("quarantined_at")
16211
+ if state not in tails or set(doc)!=expected: raise ValueError("unknown_retirement_journal_fields")
16212
+ if doc.get("plan_id")!=plan_id or not re.fullmatch(r"[0-9a-f]{64}",plan_id):
16213
+ raise ValueError("retirement_journal_identity")
16214
+ pool,lane,key=parse_artifact_id(doc["artifact_id"])
16215
+ source_rel=cache_rel(pool,lane,key)
16216
+ quarantine_rel=source_rel.rsplit("/",1)[0]+"/.fmix-retire-"+plan_id
16217
+ if doc["source_rel"]!=source_rel or doc["quarantine_rel"]!=quarantine_rel:
16218
+ raise ValueError("retirement_journal_paths")
16219
+ if type(doc.get("uid_scope")) is not int or doc["uid_scope"]!=uid or doc.get("home")!=home or doc.get("plan_sha256")!=plan_id:
16220
+ raise ValueError("retirement_journal_context")
16221
+ for field in ("runner_sha256","report_sha256","original_identity_sha256","original_manifest_sha256","original_metadata_sha256"):
16222
+ if not hexkey(doc.get(field),64): raise ValueError("retirement_journal_digest")
16223
+ for field,value in doc.items():
16224
+ if field.endswith("_at"):
16225
+ timestamp=datetime.datetime.fromisoformat(value.replace("Z","+00:00"))
16226
+ if timestamp.tzinfo is None: raise ValueError("retirement_journal_timestamp")
16227
+ snapshot=doc.get("snapshot")
16228
+ fields={"nodes","manifest_sha256","metadata_sha256","directories","meta","records","identity_sha256"}
16229
+ if (not isinstance(snapshot,dict) or set(snapshot)!=fields or not isinstance(snapshot["nodes"],dict)
16230
+ or not isinstance(snapshot["directories"],list) or sha(canonical(snapshot["nodes"]))!=snapshot["identity_sha256"]):
16231
+ raise ValueError("retirement_journal_snapshot")
16232
+ if state in ("deleting","complete"):
16233
+ allowed=set([""]+snapshot["directories"]); changed=set()
16234
+ for item in doc["permission_changes"]:
16235
+ if not isinstance(item,dict) or set(item)!={"path","from","to"}: raise ValueError("retirement_journal_permissions")
16236
+ path=item["path"]
16237
+ if path not in allowed or path in changed or type(item["from"]) is not int or type(item["to"]) is not int:
16238
+ raise ValueError("retirement_journal_permissions")
16239
+ original=snapshot["nodes"].get(path)
16240
+ if not isinstance(original,dict) or item["from"]!=original["mode"]&0o7777 or item["to"]!=item["from"]|stat.S_IWUSR:
16241
+ raise ValueError("retirement_journal_permissions")
16242
+ changed.add(path)
16243
+ if changed!=allowed: raise ValueError("retirement_journal_permissions")
16244
+ return doc
16245
+ def load_journal(plan_id):
16246
+ doc,raw,_=read_json(journal_path(plan_id))
16247
+ return validate_journal(doc,plan_id)
16248
+ def validate_journal_plan(journal):
16249
+ plan=read_plan(journal["plan_id"],allow_stale=True)
16250
+ snapshot=journal["snapshot"]
16251
+ if (plan["artifact_id"]!=journal["artifact_id"] or plan["runner_sha256"]!=journal["runner_sha256"]
16252
+ or plan["report_sha256"]!=journal["report_sha256"]
16253
+ or plan["identity_sha256"]!=journal["original_identity_sha256"]
16254
+ or plan["manifest_sha256"]!=journal["original_manifest_sha256"]
16255
+ or plan["metadata_sha256"]!=journal["original_metadata_sha256"]
16256
+ or snapshot["identity_sha256"]!=journal["original_identity_sha256"]
16257
+ or snapshot["manifest_sha256"]!=journal["original_manifest_sha256"]
16258
+ or snapshot["metadata_sha256"]!=journal["original_metadata_sha256"]):
16259
+ raise ValueError("retirement_journal_plan_mismatch")
16260
+ return plan
16261
+ def update_journal(doc):
16262
+ write_json(journal_path(doc["plan_id"]),doc,replace=True)
16263
+ def report_clear(report,row):
16264
+ holds=known_global_holds(report)
16265
+ if pool_v2(row["pool"]):
16266
+ holds-={"external_consumers_unknown","consumer_coverage_unproven",
16267
+ "fallback_preservation_unproven","liveness_unproven"}
16268
+ if holds: raise ValueError("incomplete_observation:"+",".join(sorted(holds)))
16269
+ def persist_absence(journal,permission_changes):
16270
+ plan_id=journal["plan_id"]
16271
+ source_absent=not exists_rel(journal["source_rel"])
16272
+ quarantine_absent=not exists_rel(journal["quarantine_rel"])
16273
+ if not source_absent or not quarantine_absent: raise ValueError("absence_not_verified")
16274
+ receipt={"schema":"fmix-artifact-absence.v2","plan_id":plan_id,
16275
+ "artifact_id":journal["artifact_id"],"home":home,"uid_scope":uid,
16276
+ "source_rel":journal["source_rel"],"quarantine_rel":journal["quarantine_rel"],
16277
+ "source_absent":True,"quarantine_absent":True,
16278
+ "manifest_sha256":journal["original_manifest_sha256"],
16279
+ "identity_sha256":journal["original_identity_sha256"],
16280
+ "runner_sha256":journal["runner_sha256"],
16281
+ "report_sha256":journal["report_sha256"],
16282
+ "permission_changes_count":len(permission_changes),
16283
+ "permission_changes_sha256":sha(canonical(permission_changes)),
16284
+ "removed_at":now.isoformat()}
16285
+ receipt_rel=receipt_path(plan_id)
16286
+ try: previous,_,_=read_json(receipt_rel)
16287
+ except FileNotFoundError: write_json(receipt_rel,receipt)
16288
+ else:
16289
+ if set(previous)!=set(receipt) or any(previous[key]!=value for key,value in receipt.items() if key!="removed_at"):
16290
+ raise ValueError("absence_receipt_conflict")
16291
+ receipt=previous
16292
+ journal["state"]="complete"
16293
+ journal["completed_at"]=now.isoformat()
16294
+ update_journal(journal)
16295
+ return {"status":"retired","plan_id":plan_id,"artifact_id":journal["artifact_id"],
16296
+ "absence_receipt":receipt_path(plan_id)}
16297
+ def row_from_journal(journal,base_rel):
16298
+ pool,lane,key=parse_artifact_id(journal["artifact_id"])
16299
+ parent,name=parent_and_name(base_rel)
16300
+ try: rootst=os.stat(name,dir_fd=parent,follow_symlinks=False)
16301
+ finally: os.close(parent)
16302
+ root_identity=identity(rootst)
16303
+ audit_fields=("device","inode","uid","mode","mtime_ns","ctime_ns")
16304
+ return {"pool":pool,"lane":lane,"key":key,"path":home+"/"+journal["source_rel"],
16305
+ "metadata_sha256":journal["original_metadata_sha256"],
16306
+ "identity":{field:root_identity[field] for field in audit_fields}}
16307
+ def restore_quarantine(journal,reason):
16308
+ source=journal["source_rel"]; quarantine=journal["quarantine_rel"]
16309
+ if exists_rel(source) or not exists_rel(quarantine): raise ValueError("restore_path_ambiguous")
16310
+ row=row_from_journal(journal,quarantine)
16311
+ snapshot=verify_tree(row,quarantine)
16312
+ snapshots_match(journal["snapshot"],snapshot,"rename")
16313
+ src_parent,src_name=parent_and_name(source)
16314
+ dst_parent,dst_name=parent_and_name(quarantine)
16315
+ try:
16316
+ if src_name and exists_rel(source): raise ValueError("restore_target_appeared")
16317
+ rename_noreplace(dst_parent,dst_name,src_parent,src_name)
16318
+ os.fsync(dst_parent); os.fsync(src_parent)
16319
+ finally: os.close(src_parent); os.close(dst_parent)
16320
+ journal["state"]="restored_hold"; journal["hold_reason"]=reason
16321
+ journal["restored_at"]=now.isoformat()
16322
+ update_journal(journal)
16323
+ return {"status":"held","reason":reason,"restored":True,"plan_id":journal["plan_id"]}
16324
+ def journal_for_plan(plan,row,proof):
16325
+ plan_id=plan["plan_id"]
16326
+ return {"schema":"fmix-artifact-retirement-journal.v2","plan_id":plan_id,
16327
+ "artifact_id":plan["artifact_id"],"home":home,"uid_scope":uid,"state":"intent",
16328
+ "source_rel":cache_rel(row["pool"],row.get("lane"),row["key"]),
16329
+ "quarantine_rel":cache_rel(row["pool"],row.get("lane"),row["key"]).rsplit("/",1)[0]+"/.fmix-retire-"+plan_id,
16330
+ "runner_sha256":proof["runner_sha256"],"report_sha256":plan["report_sha256"],
16331
+ "plan_sha256":plan_id,"original_identity_sha256":proof["full"]["identity_sha256"],
16332
+ "original_manifest_sha256":proof["full"]["manifest_sha256"],
16333
+ "original_metadata_sha256":proof["full"]["metadata_sha256"],
16334
+ "snapshot":proof["full"],"created_at":now.isoformat()}
16335
+ def deleting_snapshot(journal):
16336
+ original=journal["snapshot"]
16337
+ expected=set([""]+original["directories"])
16338
+ snapshot=json.loads(canonical(original))
16339
+ seen=set()
16340
+ for item in journal["permission_changes"]:
16341
+ path=item["path"]
16342
+ if path not in expected or path in seen: raise ValueError("retirement_permission_receipt")
16343
+ mode=snapshot["nodes"][path]["mode"]
16344
+ snapshot["nodes"][path]["mode"]=(mode&~0o7777)|item["to"]
16345
+ seen.add(path)
16346
+ if seen!=expected: raise ValueError("retirement_permission_receipt")
16347
+ snapshot["identity_sha256"]=sha(canonical(snapshot["nodes"]))
16348
+ return snapshot
16349
+ def finish_journal(journal):
16350
+ state=journal.get("state"); source=journal["source_rel"]; quarantine=journal["quarantine_rel"]
16351
+ source_exists=exists_rel(source); quarantine_exists=exists_rel(quarantine)
16352
+ if state in ("complete","restored_hold"):
16353
+ return {"status":"held" if state=="restored_hold" else "already_retired",
16354
+ "reason":journal.get("hold_reason",""),"plan_id":journal["plan_id"]}
16355
+ validate_journal_plan(journal)
16356
+ if state=="intent" and source_exists and not quarantine_exists:
16357
+ return execute_plan_locked(journal["plan_id"])
16358
+ if source_exists and not quarantine_exists:
16359
+ return {"status":"held","reason":"quarantine_not_started","plan_id":journal["plan_id"]}
16360
+ if source_exists or not quarantine_exists:
16361
+ if state=="deleting" and not source_exists and not quarantine_exists:
16362
+ return persist_absence(journal,journal.get("permission_changes",[]))
16363
+ raise ValueError("quarantine_path_ambiguous")
16364
+ committed=state in ("permissions_pending","deleting")
16365
+ row=row_from_journal(journal,quarantine)
16366
+ if state=="deleting":
16367
+ current_snapshot=deleting_snapshot(journal)
16368
+ remove_verified_tree(quarantine,current_snapshot,delete=False)
16369
+ else:
16370
+ current_snapshot=verify_tree(row,quarantine,allow_owner_write=committed)
16371
+ snapshots_match(journal["snapshot"],current_snapshot,"permissions" if committed else "rename")
16372
+ try:
16373
+ report,runner_sha=run_audit()
16374
+ require_managed_handoff()
16375
+ report_clear(report,row)
16376
+ retirement_fallback_recheck(report,journal)
16377
+ if pins_for(load_pins(),journal["artifact_id"]): raise ValueError("consumer_pin")
16378
+ late_references(report,row["pool"],row.get("lane"),row["key"])
16379
+ live=liveness(home+"/"+quarantine)
16380
+ except Exception as exc:
16381
+ reason=str(exc)
16382
+ if not committed: return restore_quarantine(journal,reason)
16383
+ raise
16384
+ if state=="deleting":
16385
+ remove_verified_tree(quarantine,current_snapshot,delete=True)
16386
+ return persist_absence(journal,journal.get("permission_changes",[]))
16387
+ if state not in ("intent","quarantined","permissions_pending"):
16388
+ raise ValueError("unknown_retirement_state")
16389
+ if not committed:
16390
+ try:
16391
+ liveness(home+"/"+quarantine)
16392
+ except Exception as exc:
16393
+ return restore_quarantine(journal,str(exc))
16394
+ journal["state"]="permissions_pending"
16395
+ journal["permission_started_at"]=now.isoformat()
16396
+ update_journal(journal)
16397
+ changes=make_owned_directories_writable(quarantine,journal["snapshot"])
16398
+ after_row=row_from_journal(journal,quarantine)
16399
+ after_snapshot=verify_tree(after_row,quarantine,allow_owner_write=True)
16400
+ snapshots_match(journal["snapshot"],after_snapshot,"permissions")
16401
+ require_managed_handoff()
16402
+ fresh_report,_=run_audit()
16403
+ report_clear(fresh_report,after_row)
16404
+ retirement_fallback_recheck(fresh_report,journal)
16405
+ late_references(fresh_report,after_row["pool"],after_row.get("lane"),after_row["key"])
16406
+ if pins_for(load_pins(),journal["artifact_id"]): raise ValueError("consumer_pin")
16407
+ if liveness(home+"/"+quarantine)["open_files"]["open_count"]:
16408
+ raise ValueError("open_file_reference")
16409
+ permission_changes=[]
16410
+ for path in [""]+journal["snapshot"]["directories"]:
16411
+ old=journal["snapshot"]["nodes"][path]["mode"]&0o7777
16412
+ new=after_snapshot["nodes"][path]["mode"]&0o7777
16413
+ if old!=new: permission_changes.append({"path":path,"from":old,"to":new})
16414
+ journal["state"]="deleting"
16415
+ journal["permission_changes"]=permission_changes
16416
+ journal["delete_started_at"]=now.isoformat()
16417
+ update_journal(journal)
16418
+ remove_verified_tree(quarantine,after_snapshot,delete=False)
16419
+ remove_verified_tree(quarantine,after_snapshot,delete=True)
16420
+ return persist_absence(journal,permission_changes)
16421
+ def execute_plan_locked(plan_id):
16422
+ existing=None
16423
+ try: existing=load_journal(plan_id)
16424
+ except FileNotFoundError: pass
16425
+ resume_intent=(existing is not None and existing["state"]=="intent"
16426
+ and exists_rel(existing["source_rel"]) and not exists_rel(existing["quarantine_rel"]))
16427
+ if existing is not None and not resume_intent:
16428
+ raise ValueError("retirement_journal_already_started")
16429
+ plan=read_plan(plan_id,allow_stale=resume_intent)
16430
+ artifact_id=plan["artifact_id"]
16431
+ report,runner_sha,row,pool,lane,key,source_rel,proof,protected=fresh_proof(artifact_id)
16432
+ if runner_sha!=plan["runner_sha256"] or proof["full"]["manifest_sha256"]!=plan["manifest_sha256"]:
16433
+ raise ValueError("retirement_plan_manifest_changed")
16434
+ if (proof["full"]["metadata_sha256"]!=plan["metadata_sha256"]
16435
+ or proof["full"]["identity_sha256"]!=plan["identity_sha256"]
16436
+ or proof["pins_sha256"]!=plan["pins_sha256"]):
16437
+ raise ValueError("retirement_plan_evidence_changed")
16438
+ adoption=load_adoption(artifact_id,proof,runner_sha)
16439
+ if adoption is None or sha(canonical(adoption))!=plan["adoption_sha256"]:
16440
+ raise ValueError("retirement_adoption_changed")
16441
+ protected,broken,unknown_template=fallbacks(report)
16442
+ if artifact_id in protected or (pool=="template" and unknown_template) or lane in broken:
16443
+ raise ValueError("fallback_preserved_or_unknown")
16444
+ if plan["execution_mode"]=="automatic":
16445
+ baseline,_=access_baseline(row,pool,lane,key,proof)
16446
+ if (now-baseline).total_seconds()<ttl_hours(pool)*3600:
16447
+ raise ValueError("idle_ttl_not_elapsed")
16448
+ journal=existing or journal_for_plan(plan,row,proof)
16449
+ if len(canonical(journal))>16*1024*1024: raise ValueError("retirement_journal_budget")
16450
+ if existing is not None:
16451
+ if (journal["artifact_id"]!=artifact_id or journal["runner_sha256"]!=runner_sha
16452
+ or journal["original_identity_sha256"]!=proof["full"]["identity_sha256"]
16453
+ or journal["original_manifest_sha256"]!=proof["full"]["manifest_sha256"]
16454
+ or journal["original_metadata_sha256"]!=proof["full"]["metadata_sha256"]):
16455
+ raise ValueError("retirement_intent_evidence_changed")
16456
+ snapshots_match(journal["snapshot"],proof["full"],"rename")
16457
+ ensure_retirement_dirs()
16458
+ if existing is None: write_json(journal_path(plan_id),journal)
16459
+ source=journal["source_rel"]; quarantine=journal["quarantine_rel"]
16460
+ require_managed_handoff()
16461
+ if exists_rel(quarantine): raise ValueError("quarantine_destination_exists")
16462
+ source_parent,source_name=parent_and_name(source)
16463
+ quarantine_parent,quarantine_name=parent_and_name(quarantine)
16464
+ try:
16465
+ source_st=os.stat(source_name,dir_fd=source_parent,follow_symlinks=False)
16466
+ parent_st=os.fstat(quarantine_parent)
16467
+ if source_st.st_dev!=home_st.st_dev or parent_st.st_dev!=source_st.st_dev:
16468
+ raise ValueError("quarantine_not_same_filesystem")
16469
+ if source_st.st_ino!=proof["full"]["nodes"][""]["inode"] or source_st.st_uid!=uid:
16470
+ raise ValueError("candidate_identity_changed_before_quarantine")
16471
+ rename_noreplace(source_parent,source_name,quarantine_parent,quarantine_name)
16472
+ os.fsync(source_parent); os.fsync(quarantine_parent)
16473
+ finally:
16474
+ os.close(source_parent); os.close(quarantine_parent)
16475
+ if exists_rel(source): raise ValueError("source_path_reappeared_after_quarantine")
16476
+ journal["state"]="quarantined"
16477
+ journal["quarantined_at"]=now.isoformat()
16478
+ row_after=row_from_journal(journal,quarantine)
16479
+ moved=verify_tree(row_after,quarantine)
16480
+ snapshots_match(proof["full"],moved,"rename")
16481
+ update_journal(journal)
16482
+ return finish_journal(journal)
16483
+ def release_lease(proc):
16484
+ try:
16485
+ proc.stdin.write("release\n")
16486
+ proc.stdin.flush()
16487
+ proc.stdin.close()
16488
+ proc.wait(timeout=15)
16489
+ except (BrokenPipeError,OSError,subprocess.TimeoutExpired) as exc:
16490
+ raise ValueError("artifact_lease_release_unconfirmed") from exc
16491
+ output=proc.stdout.read()
16492
+ error=proc.stderr.read()
16493
+ proc.stdout.close()
16494
+ proc.stderr.close()
16495
+ if proc.returncode!=0 or output!="RELEASED 0\n" or error:
16496
+ raise ValueError("artifact_lease_release_failed")
16497
+ def run_locked_candidate(artifact_id,operation):
16498
+ pool,lane,key=parse_artifact_id(artifact_id)
16499
+ lease=acquire_lease(pool,lane,key)
16500
+ result=None
16501
+ operation_error=None
16502
+ try: result=operation()
16503
+ except BaseException as exc: operation_error=exc
16504
+ release_error=None
16505
+ try: release_lease(lease)
16506
+ except Exception as exc: release_error=exc
16507
+ if release_error is not None:
16508
+ reason="artifact_lease_release_failed"
16509
+ if operation_error is not None: reason+=";operation_failed:"+str(operation_error)
16510
+ raise ValueError(reason)
16511
+ if operation_error is not None: raise operation_error
16512
+ return result
16513
+ def run_locked(artifact_id,operation):
16514
+ global_lease=acquire_named_lease("artifact-retirement-v2")
16515
+ operation_error=None; result=None
16516
+ try: result=run_locked_candidate(artifact_id,operation)
16517
+ except BaseException as exc: operation_error=exc
16518
+ release_error=None
16519
+ try: release_lease(global_lease)
16520
+ except Exception as exc: release_error=exc
16521
+ if release_error is not None: raise ValueError("artifact_lease_release_failed") from release_error
16522
+ if operation_error is not None: raise operation_error
16523
+ return result
16524
+ def adopt_or_plan(artifact_id,make_plan):
16525
+ report,runner_sha,row,pool,lane,key,rel,proof,protected=fresh_proof(artifact_id)
16526
+ if not make_plan:
16527
+ adoption=load_adoption(artifact_id,proof,runner_sha)
16528
+ if adoption: return {"status":"already_adopted","artifact_id":artifact_id}
16529
+ doc=store_adoption(artifact_id,proof,runner_sha)
16530
+ return {"status":"adopted","artifact_id":artifact_id,
16531
+ "adoption_sha256":sha(canonical(doc)),"uid_scope":uid}
16532
+ plan=create_plan(artifact_id,report,row,proof,runner_sha,protected,*fallbacks(report)[1:],"manual")
16533
+ if plan is None: raise ValueError("manual_plan_unexpectedly_deferred")
16534
+ return {"status":"planned","plan_id":plan["plan_id"],"artifact_id":artifact_id,
16535
+ "execution_mode":plan["execution_mode"],"idle_hours":plan["idle_hours"]}
16536
+ def pin_operation():
16537
+ report,runner_sha=run_audit()
16538
+ row,pool,lane,key,rel=candidate_row(report,artifact_id)
16539
+ verify_tree(row)
16540
+ return register_pin(artifact_id,consumer)
16541
+ def unpin_operation():
16542
+ require_managed_handoff()
16543
+ pins=load_pins()
16544
+ matches=[pin for pin in pins if pin["pin_id"]==object_id]
16545
+ if len(matches)!=1: raise ValueError("pin_not_found_or_ambiguous")
16546
+ artifact_id=matches[0]["artifact_id"]
16547
+ return run_locked(artifact_id,lambda:unregister_pin(object_id,artifact_id,consumer))
16548
+ def mode_operation():
16549
+ ensure_retirement_dirs()
16550
+ if mode=="auto-expire": return auto_expire_one()
16551
+ if mode=="pin": return run_locked(artifact_id,pin_operation)
16552
+ if mode=="unpin": return unpin_operation()
16553
+ if mode=="adopt":
16554
+ return run_locked(artifact_id,lambda:adopt_or_plan(artifact_id,False))
16555
+ if mode=="plan":
16556
+ return run_locked(artifact_id,lambda:adopt_or_plan(artifact_id,True))
16557
+ if mode=="retire-plan":
16558
+ plan=read_plan(object_id)
16559
+ return run_locked(plan["artifact_id"],lambda:execute_plan_locked(object_id))
16560
+ if mode=="resume":
16561
+ journal=load_journal(object_id)
16562
+ return run_locked(journal["artifact_id"],lambda:finish_journal(load_journal(object_id)))
16563
+ raise ValueError("unsupported_retirement_mode")
16564
+ def auto_expire_one():
16565
+ # One v2 cache attempt per preparation; legacy/global uncertainty stays held.
16566
+ require_managed_handoff()
16567
+ try:
16568
+ journals=list_names(RETIRE_ROOT+"/journals")
16569
+ for name in journals:
16570
+ match=re.fullmatch(r"([0-9a-f]{64})\.json",name)
16571
+ if not match: raise ValueError("unknown_retirement_journal_layout")
16572
+ journal=load_journal(match.group(1))
16573
+ if journal.get("state") in ("intent","quarantined","permissions_pending","deleting"):
16574
+ return run_locked(journal["artifact_id"],lambda:finish_journal(load_journal(match.group(1))))
16575
+ report,runner_sha=run_audit()
16576
+ protected,broken,unknown_template=fallbacks(report)
16577
+ candidates=[]
16578
+ for row in report.get("entries",[]):
16579
+ if row.get("reference_count") or row.get("references_truncated"): continue
16580
+ artifact_id=artifact_id_for(row)
16581
+ if not pool_v2(row["pool"]): continue
16582
+ try: candidate_holds(report,row)
16583
+ except Exception: continue
16584
+ if artifact_id in protected or (pool_kind(row["pool"])=="template" and unknown_template) or row.get("lane") in broken: continue
16585
+ try:
16586
+ meta,built=read_meta(row)
16587
+ access=last_access(row,row["pool"],row.get("lane"),row["key"],built)
16588
+ except Exception: continue
16589
+ candidates.append((access,artifact_id))
16590
+ if not candidates: return {"status":"skipped","reason":"no_unreferenced_nonfallback_candidate"}
16591
+ _,artifact_id=min(candidates)
16592
+ return run_locked(artifact_id,lambda:auto_candidate_locked(artifact_id))
16593
+ except Exception as exc:
16594
+ return {"status":"skipped","reason":str(exc)}
16595
+ def auto_candidate_locked(artifact_id):
16596
+ report,runner_sha,row,pool,lane,key,rel,proof,protected=fresh_proof(artifact_id)
16597
+ plan=create_plan(artifact_id,report,row,proof,runner_sha,protected,*fallbacks(report)[1:],"automatic")
16598
+ if plan is None: return {"status":"adopted_waiting_ttl","artifact_id":artifact_id}
16599
+ return execute_plan_locked(plan["plan_id"])
16600
+ try:
16601
+ ensure_retirement_dirs()
16602
+ result=mode_operation()
16603
+ if not isinstance(result,dict): fail("invalid_retirement_result")
16604
+ result.setdefault("schema","fmix-artifact-retirement.v2")
16605
+ result.setdefault("uid_scope",uid)
16606
+ print(json.dumps(result,sort_keys=True))
16607
+ except SystemExit:
16608
+ raise
16609
+ except Exception as exc:
16610
+ fail(str(exc),1)
16611
+ finally:
16612
+ os.close(rootfd)
16613
+ PY
16614
+ }
16615
+
16616
+ cmd_gc_artifact_audit() {
16617
+ local arg py_bin dependency_ttl template_ttl runner
16618
+ for arg in "$@"; do
16619
+ case "$arg" in
16620
+ --artifacts-only|--json) ;;
16621
+ --help|-h)
16622
+ printf '%s\n' 'fmix gc --artifacts-only [--json]: read-only inventory; mutation unsupported'
16623
+ return 0 ;;
16624
+ *)
16625
+ printf '%s\n' '{"error":"unsupported_artifact_audit_option","mutation_supported":false}'
16626
+ return 2 ;;
16627
+ esac
16628
+ done
16629
+ dependency_ttl="$(fmix_effective_artifact_ttl_hours dependency)" || return 2
16630
+ template_ttl="$(fmix_effective_artifact_ttl_hours template)" || return 2
16631
+ py_bin="$(fmix_python_bin)" || return 1
16632
+ runner="$(fmix_realpath "${BASH_SOURCE[0]}")" || return 1
16633
+ "$py_bin" -I -B - "$FMIX_HOME" "$runner" "$dependency_ttl" "$template_ttl" <<'PY'
16634
+ import contextlib, datetime, hashlib, json, math, os, re, shutil, stat, sys, time
16635
+
16636
+ home = os.path.abspath(sys.argv[1])
16637
+ sha = lambda b: hashlib.sha256(b).hexdigest()
16638
+ hexkey = lambda v, n: isinstance(v, str) and re.fullmatch("[0-9a-f]{%d}" % n, v)
16639
+ holds = {"external_consumers_unknown", "liveness_unproven",
16640
+ "consumer_coverage_unproven", "fallback_preservation_unproven"}
16641
+ for tool in ("lsof", "ps"):
16642
+ if shutil.which(tool) is None:
16643
+ holds.add("missing_" + tool)
16644
+ entries, observations = [], []
16645
+ flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
16646
+ rootfd = None
16647
+ deadline = time.monotonic() + 10
16648
+ budgets = dict(entries=25000, metadata_bytes=64 * 1024 * 1024, manifest_rows=250000)
16649
+
16650
+ def bounded(kind=None, count=0):
16651
+ if time.monotonic() > deadline:
16652
+ holds.add("audit_deadline_reached")
16653
+ raise ValueError("audit deadline reached")
16654
+ if kind:
16655
+ budgets[kind] -= count
16656
+ if budgets[kind] < 0:
16657
+ holds.add("audit_budget_reached:" + kind)
16658
+ raise ValueError("audit budget reached")
16659
+
16660
+ def identity(s):
16661
+ return dict(device=s.st_dev, inode=s.st_ino, uid=s.st_uid,
16662
+ mode=s.st_mode, mtime_ns=s.st_mtime_ns, ctime_ns=s.st_ctime_ns)
16663
+
16664
+ @contextlib.contextmanager
16665
+ def directory(rel=""):
16666
+ fd = os.dup(rootfd)
16667
+ try:
16668
+ for part in rel.split("/") if rel else ():
16669
+ if part in ("", ".", ".."):
16670
+ raise ValueError("unsafe component")
16671
+ child = os.open(part, flags, dir_fd=fd)
16672
+ os.close(fd)
16673
+ fd = child
16674
+ if os.fstat(fd).st_uid != os.getuid():
16675
+ raise ValueError("foreign directory")
16676
+ yield fd
16677
+ finally:
16678
+ os.close(fd)
16679
+
16680
+ def children(rel):
16681
+ with directory(rel) as fd:
16682
+ names = []
16683
+ with os.scandir(fd) as iterator:
16684
+ for entry in iterator:
16685
+ bounded("entries", 1)
16686
+ names.append(entry.name)
16687
+ return sorted(names)
16688
+
16689
+ def info(rel, allow_link=False):
16690
+ bounded()
16691
+ parent, name = os.path.split(rel)
16692
+ with directory(parent) as fd:
16693
+ s = os.stat(name, dir_fd=fd, follow_symlinks=False)
16694
+ if s.st_uid != os.getuid() or (stat.S_ISLNK(s.st_mode) and not allow_link):
16695
+ raise ValueError("foreign or symlink")
16696
+ return s
16697
+
16698
+ def read(rel, limit=1024 * 1024):
16699
+ parent, name = os.path.split(rel)
16700
+ with directory(parent) as parentfd:
16701
+ fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK,
16702
+ dir_fd=parentfd)
16703
+ try:
16704
+ before = os.fstat(fd)
16705
+ if (not stat.S_ISREG(before.st_mode) or before.st_uid != os.getuid()
16706
+ or before.st_nlink != 1 or before.st_size > limit):
16707
+ raise ValueError("unsafe metadata")
16708
+ chunks, size = [], 0
16709
+ while True:
16710
+ bounded()
16711
+ chunk = os.read(fd, min(65536, limit + 1 - size))
16712
+ if not chunk:
16713
+ break
16714
+ chunks.append(chunk)
16715
+ size += len(chunk)
16716
+ bounded("metadata_bytes", len(chunk))
16717
+ if size > limit:
16718
+ raise ValueError("oversize metadata")
16719
+ if identity(before) != identity(os.fstat(fd)):
16720
+ raise ValueError("changed metadata")
16721
+ return b"".join(chunks), identity(before)
16722
+ finally:
16723
+ os.close(fd)
16724
+
16725
+ def strict_object(pairs):
16726
+ result = {}
16727
+ for key, value in pairs:
16728
+ if key in result:
16729
+ raise ValueError("duplicate JSON key")
16730
+ result[key] = value
16731
+ return result
16732
+
16733
+ def decode(raw):
16734
+ try:
16735
+ return json.loads(raw, object_pairs_hook=strict_object,
16736
+ parse_constant=lambda _: (_ for _ in ()).throw(ValueError()))
16737
+ except RecursionError:
16738
+ raise ValueError("JSON nesting limit") from None
16739
+
16740
+ specs = {
16741
+ "state.json": "path template_key db_name db_schema_key db_source_schema_key db_base_id last_migration_stamp last_used",
16742
+ "artifact-state.json": "schema path template_key verified_at",
16743
+ "dependency-stamp.json": "path build_root dependency_fingerprint reconciliation_guard lock_identity source_guard resolved_at",
16744
+ "compile-stamp.json": "schema_version path build_root template_key git_tree_hash compile_env_hash dirty_hash ignored_compile_hash fingerprint manifest_guard dependency_source_guard quick_guard source_stability_identity compiled_at",
16745
+ "meta.json": "schema session_id session_hash app_name source worktree deps_path build_path creation_time created_at last_accessed last_used ttl_days ttl_hours lockfile_hash status",
16746
+ }
16747
+
16748
+ def reference(rel, kind):
16749
+ row = {"path": rel, "status": "unknown", "sha256": None}
16750
+ observations.append(row)
16751
+ try:
16752
+ raw, row["identity"] = read(rel)
16753
+ row["sha256"] = sha(raw)
16754
+ d = decode(raw)
16755
+ expected = set(specs[kind].split())
16756
+ if not isinstance(d, dict) or set(d) != expected:
16757
+ raise ValueError("unknown schema")
16758
+ numeric = {"schema_version", "ttl_days", "ttl_hours"} & expected
16759
+ if "schema_version" in d and type(d["schema_version"]) is not int:
16760
+ raise ValueError("numeric field")
16761
+ if any(type(d[k]) not in (int, float) or d[k] < 0
16762
+ or (type(d[k]) is float and not math.isfinite(d[k]))
16763
+ for k in {"ttl_days", "ttl_hours"} & expected):
16764
+ raise ValueError("TTL field")
16765
+ if any(not isinstance(d[k], str) for k in expected - numeric):
16766
+ raise ValueError("string field")
16767
+ if kind == "artifact-state.json" and d["schema"] != "fmix-artifacts-v1":
16768
+ raise ValueError("artifact schema")
16769
+ if kind == "compile-stamp.json" and d["schema_version"] != 2:
16770
+ raise ValueError("compile schema")
16771
+ if kind == "meta.json":
16772
+ if (d["schema"] != "1" or d["session_hash"] != rel.split("/")[3]
16773
+ or d["session_id"] != d["session_hash"]
16774
+ or min(d["ttl_days"], d["ttl_hours"]) < 0):
16775
+ raise ValueError("session identity")
16776
+ source = d.get("path", d.get("worktree", ""))
16777
+ if not os.path.isabs(source) or os.path.normpath(source) != source:
16778
+ raise ValueError("source path")
16779
+ refs = {}
16780
+ for field, width in (("template_key", 16), ("dependency_fingerprint", 64)):
16781
+ if field in d:
16782
+ if not hexkey(d[field], width):
16783
+ raise ValueError("reference identity")
16784
+ refs[field] = d[field]
16785
+ row.update(status="observed", references=refs,
16786
+ declared_source_path_sha256=sha(source.encode()))
16787
+ except (OSError, ValueError, UnicodeError):
16788
+ holds.add("unknown_native_reference")
16789
+
16790
+ def census(rel, depth=0):
16791
+ try:
16792
+ names = children(rel)
16793
+ if rel == "sessions/v1" or rel.startswith("sessions/v1/"):
16794
+ if depth < 3:
16795
+ for name in names:
16796
+ if depth == 1 and not hexkey(name, 16):
16797
+ holds.add("unknown_session_layout")
16798
+ else:
16799
+ census(rel + "/" + name, depth + 1)
16800
+ else:
16801
+ for kind in specs:
16802
+ if kind in names:
16803
+ reference(rel + "/" + kind, kind)
16804
+ else:
16805
+ holds.add("incomplete_session_references")
16806
+ else:
16807
+ kind = {"worktrees": "state.json", "artifact-states": "artifact-state.json",
16808
+ "dependency-stamps": "dependency-stamp.json",
16809
+ "compile-stamps": "compile-stamp.json"}[rel]
16810
+ for name in names:
16811
+ if re.fullmatch("[0-9a-f]{8}\\.json", name):
16812
+ reference(rel + "/" + name, kind)
16813
+ else:
16814
+ holds.add("unknown_native_reference_layout")
16815
+ except (OSError, ValueError):
16816
+ holds.add("unavailable_native_reference_inventory")
16817
+
16818
+ def discover(rel, pool, key, lane=None):
16819
+ # Enumerate both pools before detailed manifest checks can consume the
16820
+ # deadline. A discovered row is not validated and never authorizes action.
16821
+ row = dict(path=home + "/" + rel, pool=pool, key=key, lane=lane,
16822
+ status="held", metadata_sha256=None, inspection="not_started",
16823
+ holds=["payload_verification_unproven", "cache_inspection_pending"])
16824
+ entries.append(row)
16825
+ try:
16826
+ row["identity"] = identity(info(rel))
16827
+ except (OSError, ValueError):
16828
+ row["holds"].append("unverifiable_cache")
16829
+
16830
+ def known_retirement_quarantine(rel,pool,lane=None):
16831
+ match=re.fullmatch(r"\.fmix-retire-([0-9a-f]{64})",rel.rsplit("/",1)[-1])
16832
+ if not pool.endswith("-v2") or not match: return False
16833
+ plan_id=match.group(1); base="artifact-retirement/v2/"
16834
+ try:
16835
+ journal=decode(read(base+"journals/"+plan_id+".json",16*1024*1024)[0])
16836
+ plan=decode(read(base+"plans/"+plan_id+".json",16*1024*1024)[0])
16837
+ if not isinstance(journal,dict) or not isinstance(plan,dict): return False
16838
+ except (OSError,ValueError,UnicodeError): return False
16839
+ state=journal.get("state"); required={"schema","plan_id","artifact_id","home","uid_scope","state","source_rel","quarantine_rel","runner_sha256","report_sha256","plan_sha256","original_identity_sha256","original_manifest_sha256","original_metadata_sha256","snapshot","created_at"}
16840
+ tails={"intent":set(),"quarantined":{"quarantined_at"},"permissions_pending":{"quarantined_at","permission_started_at"},"deleting":{"quarantined_at","permission_started_at","permission_changes","delete_started_at"}}
16841
+ if journal.get("schema")!="fmix-artifact-retirement-journal.v2" or state not in tails or set(journal)!=required|tails[state]: return False
16842
+ plan_fields={"schema","artifact_id","home","uid_scope","runner_sha256","execution_mode","policy_sha256","report_sha256","manifest_sha256","metadata_sha256","identity_sha256","pins_sha256","adoption_sha256","process_sha256","openfile_sha256","created_at","idle_hours","plan_id"}
16843
+ if set(plan)!=plan_fields or plan.get("schema")!="fmix-artifact-retirement-plan.v2": return False
16844
+ stored=dict(plan); actual=stored.pop("plan_id",None)
16845
+ if actual!=plan_id or sha(json.dumps(stored,sort_keys=True,separators=(",",":"),ensure_ascii=True).encode())!=plan_id: return False
16846
+ if plan.get("home")!=home or type(plan.get("uid_scope")) is not int or plan["uid_scope"]!=os.getuid(): return False
16847
+ snapshot=journal.get("snapshot")
16848
+ snap_fields={"nodes","manifest_sha256","metadata_sha256","directories","meta","records","identity_sha256"}
16849
+ if not isinstance(snapshot,dict) or set(snapshot)!=snap_fields or not isinstance(snapshot["nodes"],dict): return False
16850
+ if sha(json.dumps(snapshot["nodes"],sort_keys=True,separators=(",",":"),ensure_ascii=True).encode())!=snapshot.get("identity_sha256"): return False
16851
+ if (journal.get("plan_sha256")!=plan_id or journal.get("home")!=home or journal.get("uid_scope")!=os.getuid()
16852
+ or plan.get("artifact_id")!=journal.get("artifact_id") or plan.get("runner_sha256")!=journal.get("runner_sha256")
16853
+ or plan.get("report_sha256")!=journal.get("report_sha256") or plan.get("identity_sha256")!=journal.get("original_identity_sha256")
16854
+ or plan.get("manifest_sha256")!=journal.get("original_manifest_sha256") or plan.get("metadata_sha256")!=journal.get("original_metadata_sha256")
16855
+ or snapshot.get("identity_sha256")!=journal.get("original_identity_sha256")
16856
+ or snapshot.get("manifest_sha256")!=journal.get("original_manifest_sha256")
16857
+ or snapshot.get("metadata_sha256")!=journal.get("original_metadata_sha256")): return False
16858
+ aid=plan.get("artifact_id","")
16859
+ if pool=="template-v2" and re.fullmatch(r"template-v2:[0-9a-f]{16}",aid): source="artifacts/v2/templates/"+aid.split(":")[1]
16860
+ elif pool=="dependency-v2" and re.fullmatch(r"dependency-v2:[0-9a-f]{64}/[0-9a-f]{64}",aid): source="artifacts/v2/dependencies/"+aid.split(":")[1]
16861
+ else: return False
16862
+ parent=source.rsplit("/",1)[0]
16863
+ if journal.get("home")!=home or journal.get("uid_scope")!=os.getuid() or journal.get("artifact_id")!=aid or journal.get("source_rel")!=source or journal.get("quarantine_rel")!=rel or rel!=parent+"/.fmix-retire-"+plan_id: return False
16864
+ try:
16865
+ root=identity(info(rel))
16866
+ info(source)
16867
+ return False
16868
+ except FileNotFoundError:
16869
+ pass
16870
+ expected_root=journal["snapshot"]["nodes"].get("")
16871
+ if not isinstance(expected_root,dict) or root["inode"]!=expected_root.get("inode") or root["device"]!=expected_root.get("device"): return False
16872
+ try:
16873
+ phase="permissions" if state in ("permissions_pending","deleting") else "rename"
16874
+ return audit_quarantine_tree(rel,pool,lane,journal,phase)
16875
+ except Exception:
16876
+ return False
16877
+ def audit_quarantine_tree(rel,pool,lane,journal,phase):
16878
+ snapshot=journal["snapshot"]
16879
+ row={"path":home+"/"+rel,"pool":pool,"key":journal["artifact_id"].split(":")[1].split("/")[-1],
16880
+ "lane":lane,"status":"held","metadata_sha256":None,"inspection":"not_started",
16881
+ "holds":["payload_verification_unproven","cache_inspection_pending"],"identity":identity(info(rel))}
16882
+ inventory(row,allow_owner_write=phase=="permissions")
16883
+ if (row["inspection"]!="metadata_and_manifest_shape_checked"
16884
+ or row.get("metadata_sha256")!=snapshot["metadata_sha256"]
16885
+ or row.get("manifest_sha256")!=snapshot["manifest_sha256"]): return False
16886
+ directories=snapshot.get("directories")
16887
+ if not isinstance(directories,list) or directories!=sorted(set(directories)): return False
16888
+ nodes=snapshot.get("nodes")
16889
+ if not isinstance(nodes,dict): return False
16890
+ paths={""}
16891
+ for directory in [""]+directories:
16892
+ prefix=directory+"/" if directory else ""
16893
+ base=rel+"/"+directory if directory else rel
16894
+ paths.update(prefix+name for name in children(base))
16895
+ if paths!=set(nodes): return False
16896
+ return audit_quarantine_nodes(rel,snapshot,phase)
16897
+
16898
+ def audit_quarantine_nodes(rel,snapshot,phase):
16899
+ fields={"device","inode","uid","mode","size","mtime_ns","ctime_ns","nlink","flags"}
16900
+ stable=("device","inode","uid","size","mtime_ns","nlink","flags")
16901
+ directories=set(snapshot["directories"])
16902
+ for path,expected in snapshot["nodes"].items():
16903
+ target=rel+("/"+path if path else "")
16904
+ st=info(target,allow_link=True)
16905
+ current=identity(st)
16906
+ current.update(size=st.st_size,nlink=st.st_nlink,flags=getattr(st,"st_flags",0))
16907
+ if not isinstance(expected,dict) or set(expected)!=fields: return False
16908
+ if any(current[key]!=expected[key] for key in stable): return False
16909
+ is_directory=path=="" or path in directories
16910
+ if is_directory and phase=="permissions":
16911
+ if current["mode"] not in (expected["mode"],expected["mode"]|stat.S_IWUSR): return False
16912
+ elif current["mode"]!=expected["mode"]: return False
16913
+ if not is_directory and current["ctime_ns"]!=expected["ctime_ns"]: return False
16914
+ if hasattr(os,"listxattr") and os.listxattr(home+"/"+target,follow_symlinks=False): return False
16915
+ return True
16916
+
16917
+ def inventory(row, allow_owner_write=False):
16918
+ rel = row["path"][len(home) + 1:]
16919
+ pool, key, lane = row["pool"], row["key"], row["lane"]
16920
+ row["inspection"] = "incomplete"
16921
+ try:
16922
+ before = info(rel)
16923
+ if row.get("identity") != identity(before):
16924
+ raise ValueError("changed discovered identity")
16925
+ if not stat.S_ISDIR(before.st_mode) or (before.st_mode & 0o222 and not
16926
+ (allow_owner_write and before.st_mode & 0o200 and not before.st_mode & 0o022)):
16927
+ raise ValueError("unsafe cache root")
16928
+ if set(children(rel)) != {"deps", "_build", "meta.json", "manifest.tsv", "manifest.sha256"}:
16929
+ raise ValueError("unexpected cache contents")
16930
+ for child in ("deps", "_build", "_build/test", "_build/test/lib"):
16931
+ if not stat.S_ISDIR(info(rel + "/" + child).st_mode):
16932
+ raise ValueError("missing cache directory")
16933
+ if pool.startswith("dependency") and (children(rel + "/_build") != ["test"]
16934
+ or children(rel + "/_build/test") != ["lib"]):
16935
+ raise ValueError("unexpected build environment")
16936
+ raw, _ = read(rel + "/meta.json")
16937
+ row["metadata_sha256"] = sha(raw)
16938
+ d = decode(raw)
16939
+ dependency = pool.startswith("dependency")
16940
+ v2 = pool.endswith("-v2")
16941
+ fields = (("schema lane dependency_fingerprint producer_sha source_clean manifest_sha256 built_at producer_runner_sha256 consumer_protocol"
16942
+ if v2 else "schema lane dependency_fingerprint producer_sha source_clean manifest_sha256 built_at")
16943
+ if dependency else
16944
+ ("schema status template_key manifest_sha256 built_at toolchain source_commit producer_runner_sha256 consumer_protocol"
16945
+ if v2 else "schema status template_key manifest_sha256 built_at toolchain source_commit"))
16946
+ if not isinstance(d, dict) or set(d) != set(fields.split()) or any(
16947
+ not isinstance(v, str) for v in d.values()):
16948
+ raise ValueError("metadata schema")
16949
+ if d["schema"] != ("2" if v2 else "1") or not hexkey(d["manifest_sha256"], 64):
16950
+ raise ValueError("metadata identity")
16951
+ if v2 and (d["consumer_protocol"] != "fmix-native-artifacts.v2"
16952
+ or not hexkey(d["producer_runner_sha256"],64)):
16953
+ raise ValueError("consumer protocol identity")
16954
+ if v2:
16955
+ producer_runner, producer_id = read("runtime/fmix-"+d["producer_runner_sha256"], 4*1024*1024)
16956
+ if (sha(producer_runner) != d["producer_runner_sha256"] or producer_id["mode"]&0o222
16957
+ or not producer_id["mode"]&0o111):
16958
+ raise ValueError("producer runner identity")
16959
+ if dependency:
16960
+ if (d["lane"] != lane or d["dependency_fingerprint"] != key
16961
+ or not hexkey(d["producer_sha"], 40)
16962
+ or d["source_clean"] not in ("true", "false")):
16963
+ raise ValueError("dependency identity")
16964
+ else:
16965
+ if (d["status"] != "complete" or d["template_key"] != key
16966
+ or not d["toolchain"] or not re.fullmatch("[0-9a-f]{7,40}", d["source_commit"])):
16967
+ raise ValueError("template identity")
16968
+ if datetime.datetime.fromisoformat(d["built_at"].replace("Z", "+00:00")).tzinfo is None:
16969
+ raise ValueError("timestamp timezone")
16970
+ manifest, _ = read(rel + "/manifest.tsv", 8 * 1024 * 1024)
16971
+ recorded, _ = read(rel + "/manifest.sha256")
16972
+ row["manifest_sha256"] = sha(manifest)
16973
+ if recorded != (d["manifest_sha256"] + "\n").encode() or sha(manifest) != d["manifest_sha256"]:
16974
+ raise ValueError("corrupt manifest")
16975
+ seen = set()
16976
+ for line in manifest.decode().splitlines():
16977
+ bounded("manifest_rows", 1)
16978
+ parts = line.split("\t")
16979
+ if len(parts) < 3:
16980
+ raise ValueError("manifest row")
16981
+ kind, path = parts[:2]
16982
+ if (path in seen or any(p in ("", ".", "..") for p in path.split("/"))
16983
+ or path.split("/")[0] not in ("deps", "_build")):
16984
+ raise ValueError("manifest path")
16985
+ seen.add(path)
16986
+ s = info(rel + "/" + path, allow_link=kind == "L")
16987
+ if kind == "L" and len(parts) == 3 and stat.S_ISLNK(s.st_mode):
16988
+ parent, name = os.path.split(rel + "/" + path)
16989
+ with directory(parent) as fd:
16990
+ target = os.readlink(name, dir_fd=fd)
16991
+ if (target != parts[2] or os.path.isabs(target)
16992
+ or not os.path.normpath(parent + "/" + target).startswith(rel + "/")
16993
+ or identity(s) != identity(os.stat(name, dir_fd=fd, follow_symlinks=False))):
16994
+ raise ValueError("unsafe manifest link")
16995
+ continue
16996
+ if not stat.S_ISLNK(s.st_mode) and s.st_mode & 0o222 and not (
16997
+ allow_owner_write and stat.S_ISDIR(s.st_mode)
16998
+ and s.st_mode & 0o200 and not s.st_mode & 0o022):
16999
+ raise ValueError("writable payload")
17000
+ if kind == "D" and len(parts) == 3 and parts[2] == "-" and stat.S_ISDIR(s.st_mode):
17001
+ continue
17002
+ if not (kind == "F" and len(parts) == 4 and parts[2].isdigit()
17003
+ and hexkey(parts[3], 64) and stat.S_ISREG(s.st_mode)
17004
+ and s.st_size == int(parts[2])):
17005
+ raise ValueError("manifest entry")
17006
+ if identity(before) != identity(info(rel)):
17007
+ raise ValueError("changed cache identity")
17008
+ row["inspection"] = "metadata_and_manifest_shape_checked"
17009
+ row["holds"].remove("cache_inspection_pending")
17010
+ except (OSError, ValueError, UnicodeError):
17011
+ row["holds"].append("unverifiable_cache")
17012
+
17013
+ try:
17014
+ if os.path.realpath(home) != home:
17015
+ raise ValueError("noncanonical home")
17016
+ rootfd = os.open(home, flags)
17017
+ if os.fstat(rootfd).st_uid != os.getuid():
17018
+ raise ValueError("foreign home")
17019
+ for pool, base, width in (("template", "templates", 16),
17020
+ ("dependency", "dependency-artifacts/v1", 64),
17021
+ ("template-v2", "artifacts/v2/templates", 16),
17022
+ ("dependency-v2", "artifacts/v2/dependencies", 64)):
17023
+ try:
17024
+ for name in children(base):
17025
+ if not hexkey(name, width):
17026
+ rel=base+"/"+name
17027
+ if not known_retirement_quarantine(rel,pool): holds.add("unknown_pool_entry")
17028
+ elif pool.startswith("template"):
17029
+ discover(base + "/" + name, pool, name)
17030
+ else:
17031
+ for key in children(base + "/" + name):
17032
+ if hexkey(key, 64):
17033
+ discover(base + "/" + name + "/" + key, pool, key, name)
17034
+ else:
17035
+ rel=base+"/"+name+"/"+key
17036
+ if not known_retirement_quarantine(rel,pool,name): holds.add("unknown_pool_entry")
17037
+ except FileNotFoundError:
17038
+ pass
17039
+ except (OSError, ValueError):
17040
+ holds.add("unavailable_pool_inventory")
17041
+ # References may consume the entire inspection budget. Preserve both
17042
+ # bounded pool inventories before that happens; untouched rows stay held.
17043
+ for rel in ("worktrees", "artifact-states", "dependency-stamps", "compile-stamps", "sessions/v1"):
17044
+ census(rel)
17045
+ for row in entries:
17046
+ if time.monotonic() > deadline:
17047
+ holds.add("audit_deadline_reached")
17048
+ break
17049
+ inventory(row)
17050
+ except (OSError, ValueError):
17051
+ holds.add("unavailable_or_unsafe_home")
17052
+ finally:
17053
+ if rootfd is not None:
17054
+ os.close(rootfd)
17055
+ index = {}
17056
+ for observation in observations:
17057
+ for field, key in observation.get("references", {}).items():
17058
+ index.setdefault((field, key), []).append(observation["path"])
17059
+ for row in entries:
17060
+ field = "template_key" if row["pool"].startswith("template") else "dependency_fingerprint"
17061
+ references = index.get((field, row["key"]), [])
17062
+ row["reference_count"] = len(references)
17063
+ row["references"] = references[:16]
17064
+ row["references_truncated"] = len(references) > 16
17065
+ if row["references_truncated"]:
17066
+ row["holds"].append("reference_preview_truncated")
17067
+ row["holds"] = sorted(set(row["holds"]) | holds)
17068
+ source_sha256 = None
17069
+ try:
17070
+ fd = os.open(sys.argv[2], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
17071
+ with os.fdopen(fd, "rb") as runner:
17072
+ before = os.fstat(runner.fileno())
17073
+ if (not stat.S_ISREG(before.st_mode) or before.st_uid != os.getuid()
17074
+ or before.st_size > 4 * 1024 * 1024):
17075
+ raise ValueError("unsafe runner identity")
17076
+ source_sha256 = sha(runner.read(4 * 1024 * 1024 + 1))
17077
+ if identity(before) != identity(os.fstat(runner.fileno())):
17078
+ raise ValueError("runner changed")
17079
+ except (OSError, ValueError):
17080
+ holds.add("unverified_runner_identity")
17081
+ for row in entries:
17082
+ row["holds"] = sorted(set(row["holds"]) | holds)
17083
+ report = dict(schema="fmix-artifact-audit.v1", mutation_supported=False,
17084
+ idle_ttl_hours=dict(dependency=int(sys.argv[3]), template=int(sys.argv[4])),
17085
+ observed_at=datetime.datetime.now(datetime.timezone.utc).isoformat(),
17086
+ source_sha256=source_sha256, home=home, holds=sorted(holds),
17087
+ entries=entries, observations=observations, report_truncated=False)
17088
+ # Bound serialization itself, not just scan inputs. iterencode avoids building
17089
+ # an unbounded JSON string when many lanes repeat the same reference cohort.
17090
+ max_report_bytes = 16 * 1024 * 1024
17091
+ chunks, serialized_bytes = [], 0
17092
+ for chunk in json.JSONEncoder(sort_keys=True).iterencode(report):
17093
+ serialized_bytes += len(chunk.encode("utf-8"))
17094
+ if serialized_bytes + 1 > max_report_bytes:
17095
+ report.update(entries=[], observations=[], report_truncated=True,
17096
+ discovered_counts=dict(entries=len(entries), observations=len(observations)),
17097
+ holds=sorted(holds | {"report_output_budget_reached"}))
17098
+ print(json.dumps(report, sort_keys=True))
17099
+ break
17100
+ chunks.append(chunk)
17101
+ else:
17102
+ print("".join(chunks))
17103
+ PY
17104
+ }
17105
+
14343
17106
  cmd_gc() {
14344
17107
  local do_reap=0 skip_prompts=0 do_consolidate=0 worktree_filter=""
14345
17108
  while (( $# > 0 )); do
@@ -14515,29 +17278,10 @@ cmd_gc() {
14515
17278
  done <<<"$all_fmix_dbs"
14516
17279
  fi
14517
17280
 
14518
- # 2. Stale tmp template dirs (older than 1 day)
17281
+ # Incomplete producer staging can still be a recovery/verifier input.
17282
+ # Age alone never releases it, including through the legacy mixed GC.
14519
17283
  echo ""
14520
- echo "--- Stale template build dirs (> 1 day old) ---"
14521
- if [[ -d "$FMIX_HOME/templates" ]]; then
14522
- local now_epoch
14523
- now_epoch=$(fmix_epoch)
14524
- for tdir in "$FMIX_HOME/templates"/*.tmp-*/; do
14525
- [[ -d "$tdir" ]] || continue
14526
- local mtime
14527
- mtime=$(fmix_stat_mtime "$tdir" 2>/dev/null || echo 0)
14528
- local age=$(( now_epoch - mtime ))
14529
- if (( age > 86400 )); then
14530
- echo " STALE: $tdir (age: $(( age / 3600 ))h)"
14531
- actions=$(( actions + 1 ))
14532
- if (( do_reap == 1 )); then
14533
- fmix_guard_path "$tdir" \
14534
- && chmod -R u+w "$tdir" \
14535
- && rm -rf "$tdir" \
14536
- && echo " Deleted: $tdir"
14537
- fi
14538
- fi
14539
- done
14540
- fi
17284
+ echo "--- Template staging: HELD (producer/recovery release unproven) ---"
14541
17285
 
14542
17286
  # 3. Retired lock metadata. Kernel lock files persist by design, but the
14543
17287
  # directory-shaped mixed-version records are diagnostic snapshots only.
@@ -14567,122 +17311,15 @@ cmd_gc() {
14567
17311
  done
14568
17312
  done
14569
17313
 
14570
- # 4. Old templates (last_used > 30 days)
14571
- echo ""
14572
- echo "--- Templates unused > 30 days ---"
14573
- if [[ -d "$FMIX_HOME/templates" ]]; then
14574
- local now_epoch
14575
- now_epoch=$(fmix_epoch)
14576
- for tdir in "$FMIX_HOME/templates"/*/; do
14577
- [[ -d "$tdir" ]] || continue
14578
- local key
14579
- key="$(basename "$tdir")"
14580
- [[ "$key" == *.tmp-* ]] && continue
14581
- local meta="$tdir/meta.json"
14582
- [[ -f "$meta" ]] || continue
14583
- local last_used_str
14584
- last_used_str="$(fmix_read_template_last_used "$key")"
14585
- if [[ -z "$last_used_str" ]]; then
14586
- continue
14587
- fi
14588
- # Parse ISO date to epoch (python3 portable)
14589
- local last_used_epoch
14590
- last_used_epoch="$(fmix_iso_epoch "$last_used_str" 2>/dev/null)" \
14591
- || last_used_epoch=0
14592
- local age=$(( now_epoch - last_used_epoch ))
14593
- if (( age > 2592000 )); then # 30 days
14594
- echo " OLD: $key (last_used: $last_used_str, age: $(( age / 86400 ))d)"
14595
- actions=$(( actions + 1 ))
14596
- if (( do_reap == 1 )); then
14597
- local confirm="y"
14598
- if (( skip_prompts == 0 )); then
14599
- printf ' Delete template %s? [y/N] ' "$key"
14600
- read -r confirm
14601
- fi
14602
- if [[ "$confirm" =~ ^[Yy]$ ]]; then
14603
- fmix_guard_path "$tdir" \
14604
- && chmod -R u+w "$tdir" \
14605
- && rm -rf "$tdir" \
14606
- && echo " Deleted: $tdir"
14607
- fi
14608
- fi
14609
- fi
14610
- done
14611
- fi
14612
-
14613
- # 5. Exact dependency artifacts have their own access sidecars because
14614
- # the immutable artifact metadata must never be touched by consumers.
14615
- local dependency_ttl_days dependency_ttl_seconds dependency_root
14616
- dependency_ttl_days="$(fmix_uint_or_default \
14617
- "$FMIX_DEPENDENCY_ARTIFACT_TTL_DAYS" 30 \
14618
- FMIX_DEPENDENCY_ARTIFACT_TTL_DAYS)"
14619
- dependency_ttl_seconds=$(( dependency_ttl_days * 86400 ))
14620
- dependency_root="$FMIX_HOME/dependency-artifacts/v1"
17314
+ # Published artifacts are not released by age or --yes. The former
17315
+ # template path lacked reader coordination; the dependency path lacked
17316
+ # complete consumers, fresh identity and fallback preservation. Keep both
17317
+ # classes outside mixed mutation until the native exact retirement ledger
17318
+ # can prove all of those invariants. The isolated inventory is bounded and
17319
+ # reports four-hour idle policy without database/session/telemetry effects.
14621
17320
  echo ""
14622
- echo "--- Dependency artifacts unused > ${dependency_ttl_days} days ---"
14623
- if [[ -d "$dependency_root" ]]; then
14624
- local dependency_artifact lane exact access_file last_access last_epoch age
14625
- local artifact_lock confirm
14626
- for dependency_artifact in "$dependency_root"/*/*/; do
14627
- [[ -d "$dependency_artifact" && ! -L "$dependency_artifact" ]] || continue
14628
- lane="$(basename "$(dirname "${dependency_artifact%/}")")"
14629
- exact="$(basename "${dependency_artifact%/}")"
14630
- [[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || continue
14631
- access_file="$FMIX_HOME/dependency-artifact-access/$lane/$exact"
14632
- last_access="$(cat "$access_file" 2>/dev/null || true)"
14633
- if [[ -n "$last_access" ]]; then
14634
- last_epoch="$(fmix_iso_epoch "$last_access" 2>/dev/null)" \
14635
- || last_epoch=0
14636
- else
14637
- last_epoch="$(fmix_stat_mtime "$dependency_artifact" 2>/dev/null)" \
14638
- || last_epoch=0
14639
- fi
14640
- age=$(( $(fmix_epoch) - last_epoch ))
14641
- (( age > dependency_ttl_seconds )) || continue
14642
- echo " OLD: dependency artifact (age=$(( age / 86400 ))d, size=$(du -sh "$dependency_artifact" 2>/dev/null | awk '{print $1}'))"
14643
- actions=$(( actions + 1 ))
14644
- if (( do_reap == 1 )); then
14645
- confirm="y"
14646
- if (( skip_prompts == 0 )); then
14647
- printf ' Delete this dependency artifact? [y/N] '
14648
- read -r confirm
14649
- fi
14650
- if [[ "$confirm" =~ ^[Yy]$ ]]; then
14651
- artifact_lock="dependency-artifact-${lane:0:16}-${exact:0:16}"
14652
- if fmix_lock_acquire "$artifact_lock" 1 \
14653
- "dependency artifact GC" >/dev/null 2>&1; then
14654
- # A consumer may have refreshed the sidecar while GC
14655
- # was waiting. Recheck before the destructive step.
14656
- last_access="$(cat "$access_file" 2>/dev/null || true)"
14657
- if [[ -n "$last_access" ]]; then
14658
- last_epoch="$(fmix_iso_epoch "$last_access" 2>/dev/null)" \
14659
- || last_epoch=0
14660
- else
14661
- last_epoch="$(fmix_stat_mtime "$dependency_artifact" 2>/dev/null)" \
14662
- || last_epoch=0
14663
- fi
14664
- age=$(( $(fmix_epoch) - last_epoch ))
14665
- if (( age > dependency_ttl_seconds )) \
14666
- && fmix_guard_path "$dependency_artifact" \
14667
- && chmod -R u+w "$dependency_artifact" \
14668
- && rm -rf "$dependency_artifact"; then
14669
- rm -f "$access_file" 2>/dev/null || true
14670
- echo " Deleted dependency artifact."
14671
- fi
14672
- fmix_lock_release_optional "$artifact_lock" || {
14673
- local release_rc=$?
14674
- fmix_lock_failure_is_fatal "$release_rc" && return 70
14675
- true
14676
- }
14677
- else
14678
- local acquire_rc=$?
14679
- fmix_lock_failure_is_fatal "$acquire_rc" && return 70
14680
- fmix_warn "Dependency artifact is active; keeping it."
14681
- fi
14682
- fi
14683
- fi
14684
- done
14685
- fi
17321
+ echo "--- Templates and dependency artifacts: HELD (consumer release unproven) ---"
17322
+ echo " Inventory separately: fmix gc --artifacts-only --json"
14686
17323
 
14687
17324
  # 6. Expired session overlays. Reaping is lease-aware: the exact session
14688
17325
  # lock must be acquired before its artifacts or scratch DB are touched.
@@ -14827,6 +17464,36 @@ cmd_gc() {
14827
17464
  # ---------------------------------------------------------------------------
14828
17465
 
14829
17466
  cmd_self_test() {
17467
+ if ! fmix_artifact_v2_managed_entrypoint >/dev/null 2>&1; then
17468
+ if [[ "${FMIX_SELF_TEST_MANAGED_REEXEC:-0}" == "1" ]]; then
17469
+ fmix_error "Self-test could not establish a private managed runner."
17470
+ return 1
17471
+ fi
17472
+ (
17473
+ local fixture_root fixture_home fixture_bin source_runner launcher rc
17474
+ fixture_root="$(mktemp -d)" || exit 1
17475
+ fixture_root="$(fmix_realpath "$fixture_root")" || exit 1
17476
+ trap 'rm -rf "$fixture_root"' EXIT INT TERM
17477
+ fixture_home="$fixture_root/home"
17478
+ fixture_bin="$fixture_home/.local/bin"
17479
+ source_runner="$(fmix_realpath "${BASH_SOURCE[0]}")" || exit 1
17480
+ mkdir -p "$fixture_home" "$fixture_bin" || exit 1
17481
+ HOME="$fixture_home" FMIX_HOME="$fixture_root/fmix-home" \
17482
+ FMIX_INSTALL_DIR="$fixture_bin" \
17483
+ fmix_install_snapshot "$source_runner" "$fixture_bin" \
17484
+ >/dev/null || exit 1
17485
+ launcher="$fixture_bin/fmix"
17486
+ [[ -L "$launcher" ]] || exit 1
17487
+ HOME="$fixture_home" FMIX_HOME="$fixture_root/fmix-home" \
17488
+ FMIX_INSTALL_DIR="$fixture_bin" FMIX_SELF_TEST_MANAGED_REEXEC=1 \
17489
+ FMIX_SELF_TEST_RUNNER_HOME="$fixture_root/fmix-home" \
17490
+ "$launcher" self-test
17491
+ rc=$?
17492
+ exit "$rc"
17493
+ )
17494
+ return $?
17495
+ fi
17496
+
14830
17497
  local pass=0 fail=0 skip=0
14831
17498
 
14832
17499
  # Keep a pristine definition for the long self-test. Several fixtures
@@ -15499,8 +18166,15 @@ cmd_self_test() {
15499
18166
  echo ""
15500
18167
  echo "--- Stable seed identity ---"
15501
18168
  local self_test_old_home="$FMIX_HOME" self_test_seed_home
15502
- self_test_seed_home="$(mktemp -d)"
18169
+ self_test_seed_home="$(mktemp -d)" || return 1
18170
+ [[ -n "$self_test_seed_home" && -d "$self_test_seed_home" \
18171
+ && ! -L "$self_test_seed_home" ]] || return 1
18172
+ # macOS mktemp may return /var while the owned cache requires /private/var.
18173
+ # Canonicalize the isolated fixture, not the production safety check.
18174
+ self_test_seed_home="$(fmix_realpath "$self_test_seed_home")" || return 1
15503
18175
  FMIX_HOME="$self_test_seed_home"
18176
+ fmix_install_snapshot "$self_script" "$self_test_seed_home/.managed-bin" \
18177
+ >/dev/null || return 1
15504
18178
  local seed_repo seed_root seed_peer seed_outside producer_sha compat_a compat_b compat_peer
15505
18179
  local compat_absent_a compat_absent_peer
15506
18180
  local fake_seed expected_seed old_fixture_token
@@ -15803,22 +18477,29 @@ EOF
15803
18477
  fi
15804
18478
 
15805
18479
  local dependency_artifact_lane dependency_artifact_path dependency_artifact_file
18480
+ local dependency_artifact_access
18481
+ local dependency_publish_diag dependency_publish_rc=0
15806
18482
  dependency_artifact_lane="$(fmix_dependency_lane_fingerprint "$seed_root" 2>/dev/null)" \
15807
18483
  || dependency_artifact_lane=""
15808
18484
  dependency_artifact_path="$(fmix_dependency_artifact_dir \
15809
18485
  "$dependency_artifact_lane" "$publish_dep_fingerprint" 2>/dev/null)" \
15810
18486
  || dependency_artifact_path=""
18487
+ dependency_publish_diag="$(fmix_publish_dependency_artifact \
18488
+ "$seed_root" "$publish_dep_fingerprint" 2>&1)" || dependency_publish_rc=$?
18489
+ dependency_artifact_path="$(fmix_dependency_artifact_dir \
18490
+ "$dependency_artifact_lane" "$publish_dep_fingerprint" 2>/dev/null)" \
18491
+ || dependency_artifact_path=""
18492
+ dependency_artifact_access="$FMIX_HOME/artifact-access/v2/dependencies/$dependency_artifact_lane/$publish_dep_fingerprint"
15811
18493
  if [[ -n "$dependency_artifact_path" ]] \
15812
- && fmix_publish_dependency_artifact \
15813
- "$seed_root" "$publish_dep_fingerprint" >/dev/null 2>&1 \
18494
+ && (( dependency_publish_rc == 0 )) \
15814
18495
  && fmix_dependency_artifact_verify_full \
15815
18496
  "$dependency_artifact_path" "$dependency_artifact_lane" \
15816
18497
  "$publish_dep_fingerprint" \
15817
18498
  && [[ ! -e "$dependency_artifact_path/_build/test/lib/cdrcisco" ]] \
15818
- && [[ -f "$FMIX_HOME/dependency-artifact-access/$dependency_artifact_lane/$publish_dep_fingerprint" ]]; then
18499
+ && [[ -f "$dependency_artifact_access" ]]; then
15819
18500
  st_pass "exact dependency publisher excludes application artifacts and verifies content"
15820
18501
  else
15821
- st_fail "exact dependency publisher did not produce a verified dependency-only artifact"
18502
+ st_fail "exact dependency publisher did not produce a verified dependency-only artifact (rc=$dependency_publish_rc): $dependency_publish_diag"
15822
18503
  fi
15823
18504
 
15824
18505
  dependency_artifact_file="$dependency_artifact_path/deps/demo_dep/.hex"
@@ -15919,7 +18600,7 @@ EOF
15919
18600
  mv() {
15920
18601
  command mv "$@" || return $?
15921
18602
  case "${2:-}" in
15922
- "$interrupt_session"/.dependency-install-*/retired/deps)
18603
+ "$interrupt_session"/.dependency-install.*/retired/deps)
15923
18604
  kill -INT $$
15924
18605
  ;;
15925
18606
  esac
@@ -19379,15 +22060,20 @@ VERB
19379
22060
  ;;
19380
22061
  gc)
19381
22062
  cat <<'VERB'
19382
- fmix gc — reclaim stale sessions and consolidated templates.
22063
+ fmix gc — read-only artifact inventory or mixed session/DB/metadata maintenance.
19383
22064
 
19384
22065
  Usage:
22066
+ fmix gc --artifacts-only [--json]
19385
22067
  fmix gc [--reap|--consolidate] [--worktree <path>] [--yes]
19386
22068
 
19387
22069
  Notes:
22070
+ --artifacts-only is bounded read-only inventory: no initialization or eviction.
22071
+ Mixed GC can mutate sessions, databases and metadata; it is not artifact-only cleanup.
22072
+ Published dependency/template artifacts and recovery staging remain held.
19388
22073
  Review the fmix status report before --reap --yes.
19389
22074
 
19390
22075
  Examples:
22076
+ fmix gc --artifacts-only --json
19391
22077
  fmix gc
19392
22078
  fmix gc --consolidate --worktree ./cisco-cdr --yes
19393
22079
  VERB
@@ -19432,6 +22118,7 @@ Usage:
19432
22118
  ./fmix doctor
19433
22119
  ./fmix status
19434
22120
  ./fmix timing [--limit N] [--worktree <path>] # phase timings + session fragmentation
22121
+ ./fmix gc --artifacts-only [--json] # bounded read-only inventory; no eviction
19435
22122
  ./fmix gc [--reap|--consolidate] [--worktree <path>] [--yes]
19436
22123
  ./fmix install # immutable snapshot + atomic PATH link (~/.local/bin)
19437
22124
  ./fmix self-test
@@ -21056,16 +23743,21 @@ while wait_status is None:
21056
23743
  if cancellation_started is None:
21057
23744
  cancellation_started = time.monotonic()
21058
23745
  cancellation_deadline = cancellation_started + 5.0
21059
- publication_cutoff = cancellation_deadline - 0.20
23746
+ # Finish cleanup 350ms before the unchanged deadline-250ms alarm.
23747
+ # Cleanup must not consume the terminal publication reserve.
23748
+ publication_cutoff = cancellation_deadline - 0.60
21060
23749
  now = time.monotonic()
21061
23750
  escalation_at = min(cancellation_started + 4.0, publication_cutoff)
21062
23751
  if now >= escalation_at:
21063
23752
  cutoff_mask = signal.pthread_sigmask(signal.SIG_BLOCK, set(MANAGED))
23753
+ # Begin verified group termination before waiting on the sampler:
23754
+ # a slow sampler must not consume the worker/sentinel reap window.
23755
+ # Pinned-group proof, deadlines and abandonment criteria stay strict.
23756
+ kill_pinned_worker_group(publication_cutoff)
21064
23757
  sampler_deadline = min(publication_cutoff, time.monotonic() + 0.25)
21065
23758
  cleanup_sampler(sampler_deadline, immediate=True)
21066
- kill_pinned_worker_group(publication_cutoff)
21067
23759
  worker_wait_deadline = min(
21068
- publication_cutoff - 0.10, time.monotonic() + 0.25
23760
+ publication_cutoff, time.monotonic() + 0.25
21069
23761
  )
21070
23762
  observed_status = reap_worker_with_deadline(worker_wait_deadline)
21071
23763
  if observed_status is not None:
@@ -21116,7 +23808,8 @@ cleanup_deadline = (
21116
23808
  if cancellation_started is not None
21117
23809
  else worker_reaped_at + 5.0
21118
23810
  )
21119
- publication_cutoff = cleanup_deadline - 0.20
23811
+ # Reserve 350ms for terminal publication before emergency native delivery.
23812
+ publication_cutoff = cleanup_deadline - 0.60
21120
23813
 
21121
23814
  emergency_signal = first_pre_signal
21122
23815
  if (
@@ -21136,11 +23829,11 @@ if emergency_signal is not None:
21136
23829
  )
21137
23830
  signal.pthread_sigmask(signal.SIG_UNBLOCK, {signal.SIGALRM})
21138
23831
 
21139
- cleanup_sampler(publication_cutoff, immediate=cancellation_started is not None)
21140
23832
  kill_pinned_worker_group(publication_cutoff)
21141
23833
  kill_sentinel_fallback()
23834
+ cleanup_sampler(publication_cutoff, immediate=cancellation_started is not None)
21142
23835
  if not reaped and group_kill_succeeded:
21143
- worker_wait_deadline = min(publication_cutoff - 0.10, time.monotonic() + 0.25)
23836
+ worker_wait_deadline = min(publication_cutoff, time.monotonic() + 0.25)
21144
23837
  observed_status = reap_worker_with_deadline(worker_wait_deadline)
21145
23838
  if observed_status is not None:
21146
23839
  wait_status = observed_status
@@ -21669,13 +24362,16 @@ fmix_observability_validate_worker_capability() {
21669
24362
 
21670
24363
  main() {
21671
24364
  if (( $# == 0 )); then
21672
- fmix_prepare_command_home || return 1
21673
24365
  fmix_usage
21674
24366
  return 0
21675
24367
  fi
21676
24368
 
21677
24369
  local cmd="$1"
21678
24370
  shift
24371
+ if [[ "$cmd" == "timing" ]] && fmix_timing_help_requested "$@"; then
24372
+ cmd_timing "$@"
24373
+ return $?
24374
+ fi
21679
24375
  case "$cmd" in
21680
24376
  help|--help|-h)
21681
24377
  # focused help: fmix help <verb> | fmix <verb> --help
@@ -21706,6 +24402,23 @@ main() {
21706
24402
  ;;
21707
24403
  esac
21708
24404
 
24405
+ case "$cmd" in
24406
+ test|coverage|task|format|setup|seed|cache|ensure|doctor|status|timing|gc|install|self-test)
24407
+ if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
24408
+ fmix_verb_help "$cmd"
24409
+ return 0
24410
+ fi
24411
+ ;;
24412
+ esac
24413
+ if [[ "$cmd" == "gc" ]] && fmix_readonly_entrypoint gc "$@"; then
24414
+ if fmix_gc_artifact_retirement_requested "$@"; then
24415
+ cmd_gc_artifact_retirement "$@"
24416
+ else
24417
+ cmd_gc_artifact_audit "$@"
24418
+ fi
24419
+ return $?
24420
+ fi
24421
+
21709
24422
  if [[ "$cmd" == "cache" ]]; then
21710
24423
  fmix_prepare_home_readonly || return 1
21711
24424
  elif [[ "$cmd" != "test" && "$cmd" != "coverage" ]]; then
@@ -21758,7 +24471,7 @@ if [[ "${1:-}" == "--fmix-observability-worker" ]]; then
21758
24471
  main "$@"
21759
24472
  exit $?
21760
24473
  fi
21761
- if [[ "${FMIX_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}$ ]]; then
24474
+ if ! fmix_readonly_entrypoint "$@" && [[ "${FMIX_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}$ ]]; then
21762
24475
  fmix_run_embedded_supervisor "$@"
21763
24476
  exit $?
21764
24477
  fi