Skip to main content

cloud/reconciler/
static_asset.rs

1//! Reconciler for `kind = "static-asset"` components (R429-F2).
2//!
3//! Syncs a content-addressed file catalog declared in `workload.toml` to the
4//! mirror's `providers.object_store` slot (Cloudflare R2 or pond MinIO).
5//!
6//! ## Per-asset pipeline
7//!
8//! For each `[[asset]]` row:
9//! 1. Read the source file from disk.
10//! 2. Compute its BLAKE3 hash; compare to `entry.blake3`. Mismatch → surface
11//!    as a hard error and skip upload (don't push bad data).
12//! 3. HEAD the object key in the bucket — if already present, skip PUT.
13//! 4. PUT the file (single-part; R2 accepts up to 5 GB per PUT).
14//!
15//! ## Drift detection (v1)
16//!
17//! A `_yah-asset-catalog.json` sidecar stored in the bucket records what was
18//! uploaded. On the next run, the manifest∖current-catalog delta surfaces as
19//! prune candidates (logged as warnings; nothing is deleted). Exhaustive bucket
20//! listing via S3 ListObjects (which would find bucket∖catalog stragglers added
21//! outside of yah) is deferred to v2 when an XML list response parser exists.
22//!
23//! ## Auto-delete is OFF
24//!
25//! The reconciler NEVER deletes from the bucket. Prune candidates are reported
26//! for operator review; deletion requires `yah service prune`.
27//!
28//! @arch:see(.yah/docs/working/W164-derived-static-assets.md)
29//!
30//! @yah:ticket(R438-T8, "Worked examples: whisper-derive e2e + mesofact in-container build")
31//! @yah:assignee(agent:claude)
32//! @yah:at(2026-06-04T21:07:41Z)
33//! @yah:status(review)
34//! @yah:phase(P3)
35//! @yah:parent(R438)
36//! @yah:next("Whisper-derive e2e against fake R2: cargo run --example whisper_derive_e2e — two consecutive runs upload-then-skip")
37//! @yah:next("Post-prune --derive run re-materializes from scratch and produces bit-identical bytes (reproducibility check)")
38//! @yah:next("In-tree mesofact-static workload with build_mode=in_container builds green in CI")
39//! @yah:verify("Examples run green in CI matrix")
40//! @yah:verify("Reproducibility: independent operator/machine yields identical output blake3 (pinned container guarantees this)")
41//! @arch:see(.yah/docs/working/W164-derived-static-assets.md)
42//! @arch:see(.yah/docs/working/W165-mesofact-build-mode-lowering.md)
43//! @yah:depends_on(R438-T7)
44//! @yah:handoff("T8 landed. Three artifacts: (1) crates/yah/cloud/testdata/mesofact-in-container/workload.toml — in-tree fixture with build_mode = { mode = \"in_container\", image = \"oven/bun:1.2.13@sha256:aaa...\" }; (2) new test in_container_fixture_roundtrips_as_container_build_mode in mesofact_static.rs tests: loads fixture via read_mesofact_build, asserts BuildMode::InContainer returned, runs in CI without docker — passes; (3) crates/yah/cloud/tests/whisper_derive_e2e.rs — integration test derive_pipeline_upload_skip_prune_reproducibility. Uses in-process axum fake-S3 (HEAD/GET/PUT, state map) + fake upstream HTTP server + MockCopyExecutor (copies argv[1]→argv[2], counts invocations). Three-run scenario: run1=cold→executor invoked 1x, model.bin PUT; run2=warm→executor NOT invoked again, HEAD 200 skip; run3=prune cache+evict S3 object→executor invoked again, re-uploaded bytes have identical BLAKE3. cargo test -p cloud --lib: 304 pass, 5 pre-existing failures (port collision + cloud_init drift, same as T6 gotcha). cargo test -p cloud --test whisper_derive_e2e: 1 pass. cargo check --workspace --locked: clean.")
45//! @yah:verify("cargo test -p cloud --lib reconciler::mesofact_static::tests::in_container_fixture_roundtrips_as_container_build_mode  # 1 pass")
46//! @yah:verify("cargo test -p cloud --test whisper_derive_e2e  # 1 pass")
47//! @yah:verify("cargo check --workspace --locked  # clean")
48//!
49//! @yah:ticket(R438-F11, "HTTP fetch retry/resume policy for materialize step (W164 OQ#4)")
50//! @yah:assignee(agent:claude)
51//! @yah:at(2026-06-04T21:08:05Z)
52//! @yah:status(review)
53//! @yah:parent(R438)
54//! @yah:next("Exponential backoff with bounded attempts on transient network failures")
55//! @yah:next("Range: header for resumable downloads on multi-GB blobs (whisper-large is 1.5GB)")
56//! @yah:next("Surface progress to yah QED/task-pane per long-running→yah-surface rule (not Bash bg)")
57//! @yah:verify("Simulated 50%-mid-download disconnect resumes via Range and completes")
58//! @arch:see(.yah/docs/working/W164-derived-static-assets.md)
59//! @yah:depends_on(R438-T5)
60//! @yah:handoff("F11 landed. HTTP fetch retry + Range resume for materialize_fetch (W164 OQ#4). Changes: (1) Added stream feature to reqwest in cloud/Cargo.toml. (2) Replaced the single-shot reqwest::get+bytes() call in materialize_fetch with: FETCH_MAX_ATTEMPTS=5 (1 in test) retry loop with exponential backoff (FETCH_BASE_DELAY_MS=1000ms, capped at 30s; 1ms/5ms in tests so suite stays fast); fetch_once helper streams via resp.chunk() to a <hash>.partial file; Range: bytes=<offset>- header sent on retry when partial file exists; 206 response appended, 200 response truncates-and-restarts, 416 clears partial and retries fresh, 4xx is fatal (no retry), 5xx/429 is transient (retry). (3) Progress logged via info!() every 100MiB (FETCH_LOG_INTERVAL_BYTES) to surface through task-pane. (4) FetchOnceFail enum (Fatal/Transient) separates non-retriable from transient outcomes. After successful fetch_once, blake3 is verified on the partial file then atomic renamed to <hash>.bin. (5) Two new tests: materialize_fetch_retries_on_server_error (500 first, 200 second, asserts 2 requests made) and materialize_fetch_resumes_via_range_header (pre-writes half to .partial, server verifies Range header and returns 206+second-half, asserts full body in cache). cargo test -p cloud --lib reconciler::static_asset: 34 pass. cargo check -p cloud: clean.")
61//! @yah:verify("cargo test -p cloud --lib reconciler::static_asset::tests::materialize_fetch_retries_on_server_error  # passes")
62//! @yah:verify("cargo test -p cloud --lib reconciler::static_asset::tests::materialize_fetch_resumes_via_range_header  # passes, Range header asserted")
63//! @yah:verify("cargo check -p cloud  # clean")
64//!
65//! @yah:ticket(R438-T15, "cloud reconciler materialize step: HTTP fetch + recipe lowering + content-addressed cache")
66//! @yah:at(2026-06-05T00:03:49Z)
67//! @yah:status(review)
68//! @yah:phase(P2)
69//! @yah:parent(R438)
70//! @yah:next("Inject executor: Arc<dyn ForgeExecutor> via StaticAssetReconciler::with_executor(...) setter (defaults to Arc::new(LocalForgeDriver::default())).")
71//! @yah:verify("Two consecutive runs against a fake R2 / MinIO mock: upload-then-skip; derive-mode assets resolve through cache and round-trip.")
72//! @arch:see(.yah/docs/working/W164-derived-static-assets.md)
73//! @yah:depends_on(R438-T13)
74//! @yah:handoff("T15 landed. Cloud reconciler materialize step (W164) wired end-to-end. Changes: (1) StaticAssetReconciler gains `executor: Arc<dyn ForgeExecutor>` field + `with_executor(...)` setter; default Arc::new(LocalForgeDriver::default()). Threaded through up→sync_to_r2/sync_to_minio→sync_assets. (2) New materialize_asset() in crates/yah/cloud/src/reconciler/static_asset.rs lifts legacy `source=...` to disk path verbatim; derive-mode lowers to materialize_fetch() + optional materialize_transform(). (3) materialize_fetch: HTTP GET cached by upstream-blake3 to .yah/cache/derive/fetch/<hex>.bin; cache HIT verifies hash to catch bit-rot; cache MISS does atomic tmp+rename. (4) materialize_transform: TransformRecipeLoader.load → substitute_argv binds YAH_TRANSFORM_IN_0/_OUT + recipe.params at argv-element granularity → lowers each step to ForgeSpec{Subprocess{argv, image}, TaskPlacement{Local, recipe.runtime}, timeout, label, initiator=Gnome{static-asset-reconciler}}, hands to executor.execute(); cached by output-blake3. Unresolved {{placeholder}} after substitute_argv is a hard error. (5) Materialized path replaces entry.source for the existing BLAKE3-verify + S3 PUT loop — derive-mode assets ride the same upload path as legacy ones.")
75//! @yah:next("Sign off → archive R438-T15.")
76//! @yah:next("R422-F11 unblocked. Picker can resume: workload.toml gets [[asset]] + [asset.derive.fetch] + [asset.derive.transform], and the recipe TOML at .yah/qed/transforms/whisper-quantize.toml needs to be authored (R438-T8 worked-example covers the e2e verification).")
77//! @yah:next("Follow-up R438-F11 (HTTP fetch retry/resume policy) is the natural next-step for production whisper-large fetches; today's path single-shots reqwest::get.")
78//! @yah:verify("cargo test -p cloud --lib reconciler::static_asset  # 32 pass including 7 new W164 tests: materialize_legacy_source_returns_workload_dir_path + materialize_fetch_cache_miss_then_hit + materialize_fetch_blake3_mismatch_is_hard_error + materialize_transform_cache_miss_then_hit + materialize_transform_blake3_mismatch_on_output_is_hard_error + materialize_transform_recipe_failure_surfaces_stderr + materialize_derive_fetch_only_uses_fetch_path_for_upload")
79//! @yah:verify("cargo check --workspace  # clean (only pre-existing warnings in desktop)")
80//! @yah:verify("no new cloud→qed dep edge — cloud's new dep is task only (verified via cloud/Cargo.toml diff)")
81//! @yah:gotcha("Architectural decision during T15: moved qed::transforms → task::transforms because cloud cannot dep on qed (per the original T5 verify clause). transforms.rs only deps on task::TaskRuntime + workload_spec::ImageRef; task is the right home. qed re-exports dropped (no external callers existed). Added `toml = '0.8'` + `pub mod transforms;` to task/Cargo.toml + task/src/lib.rs. Cloud's Cargo.toml now has `task = { path = '../task' }`. The W164 doc's piece-placement table that says 'Recipe TOML loader | qed (existing)' is now stale; transforms lives in task.")
82//! @yah:gotcha("Stale test fixed: task::transforms::tests::rejects_recipe_with_struct_image_missing_digest now expects RecipeError::Parse (was ImageNotPinned). After R438-T3 tightened ImageRef.digest to non-Optional String, struct-form bare-tag fails at serde-deserialize, not at the post-parse ImageNotPinned check (which is now belt-and-braces against an empty-string digest).")
83//! @yah:gotcha("Reconciler is per-asset sequential — W164 calls for bounded semaphore (default 4) cross-asset concurrency. Filed as R438-F11-style follow-up rather than added in this ticket to keep the diff focused on correctness. Not blocking for R422-F11.")
84//!
85//! @yah:ticket(R546-B6, "yah cloud cache seed computes the fetched-input blake3 then discards it — leaves [asset.derive.fetch].blake3 sentinel unfilled, silently disarming the shared lock fast-path")
86//! @yah:phase(P1)
87//! @yah:status(review)
88//! @yah:assignee(agent:bundle-anthropic-ashguard)
89//! @yah:at(2026-08-02T23:38:04Z)
90//! @yah:parent(R546)
91//! @yah:next("Make `yah cloud cache seed` print the fetched-input blake3 alongside the other three, e.g. `[asset.derive.fetch].blake3 = \"<fetched_hash>\"`, so the operator can paste all four and arm BOTH skip layers. The value is already in scope as `fetched_hash` in seed_derivation_for_target — this is a print-line change plus threading it out through SeededDerivation.")
92//! @yah:next("Verified fix shape by hand for the x86_64 row: fetch.blake3 = 3568931fb074a4e1b4d43098db5810e683cdadd06887a8bdd964a5719bca6481 (b3sum of the rusty_v8-149.4.0 archive; the fetch cache is content-addressed so the blob FILENAME is the blake3). After pasting, a re-seed reproduces the identical derive_key 6238d80e..., i.e. lock_skip_hash's recomputation now matches the lock.")
93//! @yah:next("Consider also asserting it: if seed writes a lock whose fast-path cannot engage (fetch pin still sentinel), emit a warning rather than printing a success message that implies the job is done.")
94//! @yah:gotcha("Surfaced 2026-07-20 by leif while closing R546-T3: 'why wasn't fetch.blake3 filled in already?'. `seed_derivation_for_target` ALREADY has the value — it calls materialize_fetch(&derive.fetch, ...) and binds `fetched_hash`, uses it to compute the derive_key, then prints ONLY [[asset]].blake3 + lock.input_hash + lock.output_blake3. The fetched-input hash is dropped on the floor.")
95//! @yah:gotcha("CONSEQUENCE (non-obvious, cost real time to find): with [asset.derive.fetch].blake3 left as the zero sentinel, lock_skip_hash() bails at its FIRST guard (`is_bootstrap_sentinel(&derive.fetch.blake3.0) -> return None`, static_asset.rs ~line 770). So the W212 substituter fast-path never engages. The local action cache still skips the build, which MASKS the problem on the seeding machine — but a clean checkout / CI / another operator gets no skip at all. The seed command's whole purpose is 'prepare a no-rebuild apply', so leaving this unfilled defeats the shared half of it.")
96//! @yah:handoff("DONE. `yah cloud cache seed` now prints all FOUR paste-back values and a pin verdict. (1) oss/yubaba/crates/cloud/src/reconciler/static_asset.rs: SeededDerivation gains fetch_blake3 (the fetched-input hash the derive_key was keyed on, previously computed then dropped) and fetch_pin: Option<FetchPinState>; new pub enum FetchPinState {Pinned, Sentinel, Mismatch{committed}} plus pure fn classify_fetch_pin(committed, fetched). seed_transform_derivation fills fetch_blake3 and logs it; seed_derivation_for_target classifies the COMMITTED [asset.derive.fetch].blake3 against what it actually fetched. (2) app/yah/cli/src/cloud.rs handle_cache_seed: prints [asset.derive.fetch].blake3 first (columns realigned), then a per-verdict block -- Pinned = fast-path arms as soon as the lock lands; Sentinel = WARNING that lock_skip_hash declines and the skip is local-action-cache-only so CI / a clean checkout / another operator still rebuilds; Mismatch = WARNING printing both hashes (moved version anchor or wrong pin).")
97//! @yah:verify("LIVE-VERIFIED offline against the real workload (fetch anchor + artifact both already cached): `./target/debug/yah cloud cache seed --workload .yah/services/yah-cloud/components/rusty-v8-musl/workload.toml --target x86_64-unknown-linux-musl --artifact .yah/cache/artifacts/567e8f9c...` printed [asset.derive.fetch].blake3 = 3568931fb074a4e1b4d43098db5810e683cdadd06887a8bdd964a5719bca6481 -- byte-identical to the value leif verified by hand in this ticket -- and input_hash f188580181d5ae26004ecd3267b48ca7703b68969e8ad1e1db68e6c4b94d5207, reproducing the committed lock exactly. Verdict line printed: 'fetch pin already committed - the W212 fast-path arms as soon as the lock lands' (both rows of that workload were pinned by hand in an earlier session, so Pinned is correct there).")
98//! @yah:verify("Tests: 2 new in static_asset.rs. seed_surfaces_fetched_input_hash_and_pin_state drives seed_derivation_for_target end-to-end with a pre-warmed fetch cache (materialize_fetch HIT path = hermetic, no network) and asserts (a) fetch_blake3 equals the fetched hash, (b) fetch_pin == Pinned, (c) derivation_key(fetch_blake3, recipe_bk, params) reproduces seeded.derive_key -- i.e. the surfaced value really IS the key input. classify_fetch_pin_covers_all_three_verdicts covers Sentinel / Pinned (case-insensitive) / Mismatch without a network fetch. `cargo test -p yah-cloud --lib` from oss/yubaba: 595 passed, 1 pre-existing flake (reconciler::pond::tests::ensure_sim_port_free_ok_when_unbound -- binds a real port, passes in isolation, unrelated). `cargo check -p yah --bin yah` clean.")
99//! @yah:gotcha("RESOLVED-IN-PLACE, not a leftover: the two [asset.derive.fetch].blake3 rows in .yah/services/yah-cloud/components/rusty-v8-musl/workload.toml were ALREADY pinned to 3568931f... by hand in an earlier session, so this workload's fast-path is armed today. This ticket fixed the TOOLING that made them get missed; nothing in the workload needed editing. Consequence for review: the Sentinel and Mismatch warning branches are covered by unit test only, not by a live run -- exercising Sentinel live would require an unpinned workload and a real network fetch.")
100//!
101//! @yah:ticket(R546-B8, "static-asset transform passes a RELATIVE YAH_TRANSFORM_OUT into the container — any recipe that chdirs writes its artifact inside the container and silently loses it (cost a ~2h rusty-v8 arm64 build)")
102//! @yah:phase(P1)
103//! @yah:status(review)
104//! @yah:assignee(agent:bundle-anthropic-ashguard)
105//! @yah:at(2026-08-03T00:53:38Z)
106//! @yah:parent(R546)
107//! @yah:next("FIX LANDED: canonicalize `cache_dir` and join the filename (the tmp file itself does not exist yet so it cannot be canonicalized directly); also canonicalize `input_path` for the YAH_TRANSFORM_IN_0 binding for the same reason. static_asset tests 46/46 green.")
108//! @yah:next("ADD A REGRESSION TEST that asserts both YAH_TRANSFORM_IN_0 and YAH_TRANSFORM_OUT bindings are absolute after substitution. Not added yet — the existing tests exercise recipes that never chdir, so they cannot catch this class. A cheap version: assert Path::new(&params[ENV_TRANSFORM_OUT]).is_absolute().")
109//! @yah:next("HARDENING: the reconciler should fail LOUDLY when a transform step exits 0 but produces no output at YAH_TRANSFORM_OUT — today the missing-file error surfaces as a confusing BLAKE3 read failure that reads like cache corruption rather than 'your recipe never wrote its output'.")
110//! @yah:gotcha("FAILURE MODE IS SILENT AND EXPENSIVE: the step exits 0, no 'step failed' is reported, and the reconciler dies afterwards on `reading transform output ./.yah/cache/derive/transform/<derive_key>.tmp for BLAKE3: No such file or directory`. Hit 2026-07-20 after a ~2h native arm64 V8 build that had actually SUCCEEDED — the finished tar was written inside the container and thrown away with it.")
111//! @yah:gotcha("ROOT CAUSE: materialize_transform built `tmp_output = cache_dir.join(\"<derive_key>.tmp\")` from `workspace_root`, which is \".\" by CLI default, then bound that RELATIVE string into the recipe argv as {{YAH_TRANSFORM_OUT}}. Note the code immediately below it already canonicalized `workspace_abs` for the container cwd (docker rejects `-w .`) — the OUT binding just never got the same treatment. A relative OUT only survives if the recipe never leaves its cwd: true for the whisper recipes (which is why this went unnoticed for months), FALSE for rusty-v8 because build-v8.sh chdirs into /tmp/tmp.XXXX/v8src to build V8.")
112//! @yah:gotcha("CONTRAST: the QED/P018 offload path was unaffected because it passes an ABSOLUTE container path (/yah/produced/...). Only the LOCAL static-asset transform path had the relative binding.")
113//! @yah:handoff("DONE — both remaining next-steps landed (the canonicalize fix itself was already in the tree when I picked this up). (1) REGRESSION TEST: reconciler::static_asset::tests::transform_bindings_are_absolute_from_a_relative_workspace_root asserts BOTH YAH_TRANSFORM_IN_0 and YAH_TRANSFORM_OUT are absolute in the substituted argv. New ArgvCapture test executor records the argv (and can decline to write the output while still reporting exit 0 — the exact shape of the bug). (2) HARDENING: materialize_transform now checks tmp_output exists before reading it and bails with 'recipe X completed successfully but produced no output at <path> (YAH_TRANSFORM_OUT)' plus the three things to check. Covered by transform_that_writes_no_output_names_the_recipe_contract, which also asserts the raw 'No such file or directory' does NOT leak — that string is what sent the last reader into the cache subsystem instead of the recipe.")
114//! @yah:handoff("THE FIXTURE IS THE LOAD-BEARING PART OF THE TEST, and it is not obvious: it uses tempfile::TempDir::new_in(\".\") and rebuilds the relative form by hand (new_in returns an ABSOLUTE path), because `yah cloud apply` defaults --path to \".\". The repo's standard Fixture uses an absolute tempdir, and against an absolute root cache_dir is absolute either way — so an absolute-tempdir version of this test passes against the BUGGY code and proves nothing. Commented at the test.")
115//! @yah:handoff("ALSO recorded the invariant at the definition site so a future edit cannot re-break it silently: oss/qed/crates/velveteen-exec/src/transforms.rs — ENV_TRANSFORM_OUT / ENV_TRANSFORM_IN_0 doc comments now state 'Bind an ABSOLUTE path', why (a recipe is free to cd), and what it cost. Doc-only, no behaviour change; cargo check -p velveteen-exec clean.")
116//! @yah:handoff("SWEEP: grepped every ENV_TRANSFORM_IN_0/ENV_TRANSFORM_OUT binding site across oss/yubaba, oss/qed and app/yah/cli. static_asset.rs is the only production binder; velveteen-exec only defines the constants and its own test already uses absolute paths. The QED/P018 offload path was never affected (it passes /yah/produced/... absolute), confirming the ticket's contrast note. No other instance of this bug class exists.")
117//! @yah:verify("THE TEST WAS PROVEN TO FAIL AGAINST THE BUG, not just to pass against the fix. I reverted both canonicalizations in place (tmp_output back to cache_dir.join(...), input_abs back to input_path.to_path_buf()), re-ran, and got: 'YAH_TRANSFORM_IN_0 binding must be absolute, got \"./.tmpX7vsrP/.yah/cache/derive/fetch/in.bin\"'. Then restored both and re-ran green. Without this step the test would have been indistinguishable from one that can never fire.")
118//! @yah:verify("GREEN: cargo test -p yah-cloud --lib — 617 passed, 0 failed, 4 ignored (the pond real-port flakes did not fire this run; they are unrelated and pass in isolation). cargo test -p yah-cloud --test whisper_derive_e2e — 1/1. cargo check -p velveteen-exec clean.")
119//!
120//! @yah:ticket(R546-B10, "static-asset publish skips PUT on key EXISTENCE (HEAD), not content — bucket keeps stale bytes while the manifest records the new hash")
121//! @yah:status(review)
122//! @yah:assignee(agent:claude)
123//! @yah:at(2026-07-21T21:00:26Z)
124//! @yah:parent(R546)
125//! @yah:severity(high)
126//! @yah:next("Repro (real, cost this relay a wrong pin): static_asset.rs:670 does `if object_exists(...) { report.already_synced.push(key); new_manifest.insert(key, actual_hash); continue; }`. object_exists issues an existence-only probe (HTTP-verb HEAD) with no content comparison. So when the locally-materialized artifact differs from the object already at that key, the reconciler skips the PUT (bucket keeps the OLD bytes) yet still records the NEW locally-computed hash in the manifest. The published _yah-asset-catalog.json then advertises a hash that describes bytes which were never uploaded.")
127//! @yah:next("Live evidence: cdn.yah.dev/yah-cloud/rusty-v8/v149.4.0/rusty-v8-aarch64-unknown-linux-musl.tar.gz serves blake3 d322b4a1… (last-modified 2026-06-20, hand-uploaded), while _yah-asset-catalog.json claims ebdd842d… — the artifact the 2026-07-20 apply built and then silently declined to upload. Both hashes are real; they describe different tarballs.")
128//! @yah:next("Fix shape: when the object already exists, compare its hash against actual_hash before skipping. Cheapest probe is the ETag when it is a plain MD5 (single-part upload), but ETag is NOT a content hash for multipart uploads — do not key correctness on it alone. Preferred: store the blake3 as object metadata (x-amz-meta-blake3) at PUT time and compare that on the existence probe; fall back to re-PUT when the metadata is absent (older objects). Re-PUT on mismatch instead of skipping.")
129//! @yah:next("Also decide the drift POSTURE, not just the mechanism: a content mismatch at a stable key is exactly the DriftBucket condition the journal already models (AssetState::DriftBucket, used at static_asset.rs:645 for source-vs-declared mismatch). Emitting the same event here, rather than silently overwriting, is probably the right default for a published CDN object — make it explicit rather than incidental.")
130//! @yah:verify("Regression test: seed a bucket object at key K with bytes A, run the reconciler with a workload whose materialized artifact for K is bytes B (B != A), assert the object at K afterwards is B (or that a DriftBucket event was emitted) AND that the manifest never records B while the bucket still holds A.")
131//! @yah:gotcha("Latent for most assets, which is why it went unnoticed for so long: W164 catalogs put the VERSION IN THE PATH (yah-cloud/rusty-v8/v149.4.0/…), so bytes at a given key normally never change and the skip is correct. It only bites when an object is placed at a key out-of-band (hand-uploaded) or when a rebuild is non-deterministic — both true for rusty-v8 arm64.")
132//! @yah:gotcha("The manifest is NOT load-bearing for consumer correctness, so do not overstate the blast radius: prior_manifest is read only for PRUNE-candidate detection (static_asset.rs:534-549), and consumers verify pulled bytes against [[asset]].blake3 in workload.toml, not against the catalog JSON. The damage is a lying audit record + a silently-skipped publish, not corrupted downloads.")
133//! @yah:assumes("Tier: Cleric — mechanism is a few lines, but the drift posture (overwrite vs refuse-and-report) is a real design call, and the ETag/multipart trap makes the naive fix wrong.")
134
135use std::collections::{BTreeMap, HashMap};
136use std::path::{Path, PathBuf};
137use std::sync::Arc;
138
139use anyhow::{Context, Result};
140use async_trait::async_trait;
141use chrono::Utc;
142use sha2::{Digest, Sha256};
143use tracing::{debug, info, warn};
144
145use super::{ReconcileCtx, Reconciler, RunningWorkload};
146use crate::asset_journal::{AssetState, AssetStatusEvent, AssetStatusJournal};
147use crate::provider::cloudflare::CloudflareClient;
148use crate::reconciler::pond::DEFAULT_MINIO_PASSWORD;
149use crate::reconciler::pond::DEFAULT_MINIO_USER;
150use crate::{MirrorProviderSlot, Provider};
151
152use local_driver::s3_sign::{sign_s3_empty_body, sign_s3_put_object, uri_encode_key};
153use velveteen::{ForgeCommand, ForgeSpec, Initiator, MeshAccess, TaskLocation, TaskPlacement};
154use velveteen_exec::transforms::{
155    substitute_argv, RecipeStep, TransformRecipe, TransformRecipeLoader, ENV_TRANSFORM_IN_0,
156    ENV_TRANSFORM_OUT,
157};
158use velveteen_exec::{ExecContext, ForgeExecutor, LocalForgeDriver, PlacementRouter};
159use workload_spec::validate::shape_static_asset;
160use workload_spec::{AssetEntry, FetchSource, Millis, StaticAssetWorkload, TransformSpec};
161
162/// Workload kind handled by this reconciler.
163pub const WORKLOAD_KIND: &str = "static-asset";
164
165/// S3 region string for Cloudflare R2.
166const R2_REGION: &str = "auto";
167/// S3 region string for MinIO (SigV4 requires a non-empty value).
168const MINIO_REGION: &str = "us-east-1";
169
170/// Bucket key for the per-run catalog manifest sidecar.
171const CATALOG_MANIFEST_KEY: &str = "_yah-asset-catalog.json";
172
173/// 64 zero hex digits — the "not yet pinned" sentinel for `BlakeHash`.
174///
175/// Bootstrap mode: a derive-mode asset can ship with this value in any
176/// `blake3` field (`[[asset]].blake3` or `[asset.derive.fetch].blake3`)
177/// before its first apply. The reconciler computes the actual hash, accepts
178/// the bytes, uploads, and surfaces the discovered hash in the report for
179/// paste-back. Once pinned, subsequent runs verify normally. Treats the
180/// `blake3` field as the lockfile's *output*, not its precondition — first
181/// publish or disaster-recovery hydration just works.
182#[allow(dead_code)] // referenced by tests + serves as documentation of the sentinel literal
183const ZERO_SENTINEL_HEX: &str = "0000000000000000000000000000000000000000000000000000000000000000";
184
185/// True when `hex` is the 64-zero "not pinned yet" sentinel for `BlakeHash`.
186fn is_bootstrap_sentinel(hex: &str) -> bool {
187    hex.len() == 64 && hex.bytes().all(|b| b == b'0')
188}
189
190/// W209/F4: per-bootstrap output key on `$YAH_OUTPUTS`. The filename is
191/// included so multi-asset workloads round-trip — each asset's bind in the
192/// publish-assets pipeline TOML references its own key. Key shape:
193///   - `discovered_asset_blake3:<filename>` for post-transform output
194///   - `discovered_fetch_blake3:<filename>` for upstream content pin
195fn bootstrap_output_key(b: &BootstrappedHash) -> String {
196    let prefix = match b.kind {
197        BootstrapHashKind::Output => "discovered_asset_blake3",
198        BootstrapHashKind::Fetch => "discovered_fetch_blake3",
199        // W212/R518: the derivation key for the in-tree `[asset.derive.lock]`.
200        BootstrapHashKind::Input => "discovered_input_hash",
201    };
202    format!("{prefix}:{}", b.filename)
203}
204
205/// Append discovered BLAKE3 values to `$YAH_OUTPUTS` so the QED runner's
206/// per-step output collector picks them up after `yah cloud apply` returns
207/// (W209/F4). No-op outside a QED pipeline (env var unset).
208fn write_bootstrap_outputs(bootstrapped: &[BootstrappedHash]) -> std::io::Result<()> {
209    let Some(path) = std::env::var_os("YAH_OUTPUTS") else {
210        return Ok(());
211    };
212    append_bootstrap_outputs(Path::new(&path), bootstrapped)
213}
214
215/// Inner write — extracted so unit tests can exercise the format without
216/// racing on the `YAH_OUTPUTS` env var (cargo's parallel test runner makes
217/// process-wide env mutation unsafe).
218fn append_bootstrap_outputs(path: &Path, bootstrapped: &[BootstrappedHash]) -> std::io::Result<()> {
219    use std::io::Write;
220    let mut file = std::fs::OpenOptions::new()
221        .create(true)
222        .append(true)
223        .open(path)?;
224    for b in bootstrapped {
225        writeln!(file, "{}={}", bootstrap_output_key(b), b.hash)?;
226    }
227    Ok(())
228}
229
230/// Where a discovered BLAKE3 belongs in `workload.toml` for paste-back.
231#[derive(Debug, Clone, Copy, PartialEq, Eq)]
232pub enum BootstrapHashKind {
233    /// `[[asset]].blake3` — post-transform (or post-fetch when no transform) output.
234    Output,
235    /// `[asset.derive.fetch].blake3` — upstream content pin.
236    Fetch,
237    /// W212/R518: `[asset.derive.lock].input_hash` — the input-addressed
238    /// derivation key. Emitted on every successful transform build so the bind
239    /// path refreshes the lock whenever the inputs change.
240    Input,
241}
242
243/// One BLAKE3 value discovered during a bootstrap-mode apply.
244///
245/// Operator pastes `hash` into the field named by `kind` for the row matching
246/// `filename`. Subsequent runs verify against the pinned value.
247#[derive(Debug, Clone)]
248pub struct BootstrappedHash {
249    pub filename: String,
250    pub kind: BootstrapHashKind,
251    pub hash: String,
252}
253
254/// In-bucket sidecar: maps object key → blake3_hex for what was last uploaded.
255/// Used to detect prune candidates across runs without listing the bucket.
256type CatalogManifest = HashMap<String, String>;
257
258/// Summary of a completed static-asset sync.
259#[derive(Debug, Default)]
260pub struct StaticAssetSyncReport {
261    /// Asset filenames that were already present in the bucket with a matching
262    /// BLAKE3 stamp (genuinely skipped — the bytes are known to be current).
263    pub already_synced: Vec<String>,
264    /// Asset filenames uploaded this run.
265    pub uploaded: Vec<String>,
266    /// R546-B10: filenames whose bucket object existed but did NOT match the
267    /// declared artifact — either drifted content or a legacy object with no
268    /// `x-amz-meta-blake3` stamp — and was therefore re-uploaded. A key showing
269    /// up here repeatedly across runs means something outside this reconciler
270    /// keeps rewriting it; a key appearing exactly once is the expected
271    /// one-time heal of a pre-metadata object.
272    pub republished: Vec<String>,
273    /// Asset filenames whose source BLAKE3 hash didn't match the manifest.
274    /// These are NOT uploaded — operator must rebuild or fix the declaration.
275    pub hash_mismatch: Vec<String>,
276    /// Asset filenames that were in the stored catalog manifest but are no
277    /// longer in the current `workload.toml`. Prune candidates — not deleted.
278    pub prune_candidates: Vec<String>,
279    /// BLAKE3 values discovered during a bootstrap-mode apply (a `blake3` field
280    /// shipped as the zero sentinel). Operator pastes these into the catalog
281    /// to pin it; the assets were nonetheless uploaded this run.
282    pub bootstrapped: Vec<BootstrappedHash>,
283}
284
285/// Reconciles `kind = "static-asset"` components.
286///
287/// The `executor` field handles W164 transform recipes for derive-mode assets
288/// (R438-T15). Default is a [`PlacementRouter`] over `LocalForgeDriver` with no
289/// remote side: local recipes run on the host that owns the cache, and a
290/// remotely-placed one is refused with a message naming the missing wiring.
291///
292/// It is a router rather than a bare `LocalForgeDriver` because this crate
293/// *cannot* build the remote half — a `RemoteForgeDriver` needs a
294/// `WardenClient` over the camp's machine inventory, which lives one layer up
295/// in the CLI (R555-F3). So the default has to be the honest "no cloud from
296/// here" case, and the caller that does have one injects it through
297/// [`Self::with_executor`] (see `yah cloud apply`).
298pub struct StaticAssetReconciler {
299    executor: Arc<dyn ForgeExecutor>,
300}
301
302impl StaticAssetReconciler {
303    pub fn new() -> Self {
304        Self {
305            executor: Arc::new(PlacementRouter::local_only(Arc::new(
306                LocalForgeDriver::default(),
307            ))),
308        }
309    }
310
311    /// Swap the [`ForgeExecutor`] used to materialize derive-mode transforms.
312    /// Production callers inject a router that can also reach the camp's fleet;
313    /// tests inject a mock.
314    pub fn with_executor(mut self, executor: Arc<dyn ForgeExecutor>) -> Self {
315        self.executor = executor;
316        self
317    }
318}
319
320impl Default for StaticAssetReconciler {
321    fn default() -> Self {
322        Self::new()
323    }
324}
325
326#[async_trait]
327impl Reconciler for StaticAssetReconciler {
328    fn kind(&self) -> &'static str {
329        WORKLOAD_KIND
330    }
331
332    async fn up(&self, ctx: ReconcileCtx<'_>) -> Result<RunningWorkload> {
333        let workload_dir = ctx.workload_dir();
334
335        // Load and shape-validate the workload.
336        let workload = load_workload(&workload_dir)?;
337        shape_static_asset(&workload).with_context(|| {
338            format!(
339                "{}/workload.toml: closed-catalog invariant violated",
340                workload_dir.display()
341            )
342        })?;
343
344        // Resolve the object_store provider slot.
345        let slot = ctx.slot("object_store").with_context(|| {
346            format!(
347                "mirror has no `providers.object_store` slot — required for \
348                 kind=\"static-asset\" (service={}, env={})",
349                ctx.service.name, ctx.env,
350            )
351        })?;
352
353        let journal = AssetStatusJournal::at_workspace(ctx.workspace_root);
354        let service_name = ctx.service.name.as_str();
355
356        let report = match slot {
357            MirrorProviderSlot::Reference {
358                provider_id,
359                fields,
360            } => {
361                // Any cloudflare-*kind* provider routes here (dispatch is on
362                // the resolved kind, not the literal name) so a workspace can
363                // declare several — e.g. `cloudflare` + `cloudflare-scrabcake`.
364                let cf = super::cf_creds::CfProvider::resolve_scoped(
365                    ctx.workspace_root,
366                    provider_id,
367                    &ctx.scope.tenant,
368                    &ctx.scope.namespace,
369                )?;
370                anyhow::ensure!(
371                    matches!(cf.cfg.kind, Provider::Cloudflare),
372                    "providers.object_store.use = {provider_id:?} (kind={:?}) not supported \
373                     for static-asset — only cloudflare-kind reference providers are",
374                    cf.cfg.kind,
375                );
376                sync_to_r2(
377                    &ctx,
378                    cf,
379                    &workload,
380                    fields,
381                    self.executor.clone(),
382                    service_name,
383                    &journal,
384                )
385                .await?
386            }
387            MirrorProviderSlot::Inline {
388                kind: Provider::MinioContainer,
389                fields,
390            } => {
391                sync_to_minio(
392                    &ctx,
393                    &workload,
394                    fields,
395                    self.executor.clone(),
396                    service_name,
397                    &journal,
398                )
399                .await?
400            }
401            MirrorProviderSlot::Inline { kind, .. } => {
402                anyhow::bail!(
403                    "providers.object_store.kind = {kind:?} not supported for static-asset \
404                     (expected minio-container or a cloudflare reference)"
405                );
406            }
407        };
408
409        if !report.hash_mismatch.is_empty() {
410            warn!(
411                files = ?report.hash_mismatch,
412                "BLAKE3 mismatch for {} asset(s) — rebuild source files before syncing",
413                report.hash_mismatch.len(),
414            );
415            anyhow::bail!(
416                "static-asset sync failed: {} source file(s) have BLAKE3 mismatches: {:?}",
417                report.hash_mismatch.len(),
418                report.hash_mismatch,
419            );
420        }
421
422        if !report.prune_candidates.is_empty() {
423            warn!(
424                files = ?report.prune_candidates,
425                "{} file(s) no longer in catalog — run `yah service prune` to remove",
426                report.prune_candidates.len(),
427            );
428        }
429
430        // Surface bootstrap-mode discoveries as pipeline outputs (W209 §
431        // Migration #1). When this reconciler runs inside a QED step, the
432        // runner sets `$YAH_OUTPUTS` to a per-step KEY=VALUE sidechannel;
433        // discovered BLAKE3s flow into the run's OutputMap and feed any
434        // `[[bind]]` declarations in the publish-assets pipeline TOML — the
435        // applier writes them back into workload.toml mid-pipeline. Key
436        // shape encodes the asset filename so multi-asset workloads round-
437        // trip: `discovered_asset_blake3:<filename>=<hex>`.
438        if !report.bootstrapped.is_empty() {
439            if let Err(err) = write_bootstrap_outputs(&report.bootstrapped) {
440                // A write failure shouldn't poison the apply — the operator
441                // still has the summary info! line below for triage.
442                warn!(error = %err, "failed to write discovered BLAKE3s to $YAH_OUTPUTS");
443            }
444            info!(
445                count = report.bootstrapped.len(),
446                discoveries = ?report
447                    .bootstrapped
448                    .iter()
449                    .map(|b| format!("{}={}", bootstrap_output_key(b), b.hash))
450                    .collect::<Vec<_>>(),
451                "discovered {} BLAKE3 value(s) — surfaced via $YAH_OUTPUTS for pipeline bind",
452                report.bootstrapped.len(),
453            );
454        }
455
456        info!(
457            uploaded = report.uploaded.len(),
458            already_synced = report.already_synced.len(),
459            prune_candidates = report.prune_candidates.len(),
460            bootstrapped = report.bootstrapped.len(),
461            "static-asset sync complete",
462        );
463
464        Ok(
465            RunningWorkload::adopted(WORKLOAD_KIND, "object_store", None)
466                .with_notes(render_sync_notes(&report)),
467        )
468    }
469}
470
471/// R546-B12: what this run actually DID, one line per outcome class, for the
472/// apply console.
473///
474/// Everything above goes to `info!`, which the CLI does not render — so a clean
475/// static-asset reconcile printed the component header and then nothing at all.
476/// A successful publish and a successful no-op looked identical, and the view
477/// that would have told them apart (`yah cloud status`) was blind for the same
478/// underlying reason. The no-op case is stated explicitly rather than omitted:
479/// "nothing to do" is a result, and silence is not.
480fn render_sync_notes(report: &StaticAssetSyncReport) -> Vec<String> {
481    let mut notes = Vec::new();
482    if !report.uploaded.is_empty() {
483        notes.push(format!("published {} asset(s):", report.uploaded.len()));
484        notes.extend(report.uploaded.iter().map(|k| format!("  + {k}")));
485    }
486    if !report.republished.is_empty() {
487        notes.push(format!(
488            "re-published {} asset(s) whose bucket bytes did not match the declared hash:",
489            report.republished.len()
490        ));
491        notes.extend(report.republished.iter().map(|k| format!("  ~ {k}")));
492    }
493    if !report.already_synced.is_empty() {
494        notes.push(format!(
495            "{} asset(s) already current (bucket hash matches) — no upload",
496            report.already_synced.len()
497        ));
498    }
499    if !report.bootstrapped.is_empty() {
500        notes.push(format!(
501            "discovered {} BLAKE3 value(s) for paste-back into workload.toml:",
502            report.bootstrapped.len()
503        ));
504        notes.extend(
505            report
506                .bootstrapped
507                .iter()
508                .map(|b| format!("  {} = {}", bootstrap_output_key(b), b.hash)),
509        );
510    }
511    if !report.prune_candidates.is_empty() {
512        notes.push(format!(
513            "{} bucket object(s) no longer declared — `yah cloud cache prune` to review",
514            report.prune_candidates.len()
515        ));
516    }
517    if notes.is_empty() {
518        notes.push("no assets declared — nothing to reconcile".to_string());
519    }
520    notes
521}
522
523// ── Backend dispatch ──────────────────────────────────────────────────────────
524
525async fn sync_to_r2(
526    ctx: &ReconcileCtx<'_>,
527    cf_provider: super::cf_creds::CfProvider,
528    workload: &StaticAssetWorkload,
529    slot_fields: &std::collections::BTreeMap<String, toml::Value>,
530    executor: Arc<dyn ForgeExecutor>,
531    service_name: &str,
532    journal: &AssetStatusJournal,
533) -> Result<StaticAssetSyncReport> {
534    // `cf_provider` resolved from the mirror slot's `use = "<id>"` — supplies
535    // account_id + management token + R2 S3 keys, all per-provider.
536    let account_id = cf_provider.account_id.clone();
537
538    let bucket = slot_fields
539        .get("bucket")
540        .and_then(|v| v.as_str())
541        .context("providers.object_store missing `bucket` field for cloudflare static-asset sync")?
542        .to_string();
543
544    let (access_key, secret_key) = cf_provider.r2_keys()?;
545    let api_token = cf_provider.api_token()?;
546
547    ensure_r2_bucket(&api_token, &account_id, &bucket).await?;
548
549    let endpoint = format!("https://{account_id}.r2.cloudflarestorage.com");
550    let client = reqwest::Client::new();
551
552    sync_assets(
553        workload,
554        ctx.workspace_root,
555        &ctx.workload_dir(),
556        &client,
557        &endpoint,
558        &bucket,
559        R2_REGION,
560        &access_key,
561        &secret_key,
562        executor,
563        service_name,
564        journal,
565    )
566    .await
567}
568
569async fn sync_to_minio(
570    ctx: &ReconcileCtx<'_>,
571    workload: &StaticAssetWorkload,
572    slot_fields: &std::collections::BTreeMap<String, toml::Value>,
573    executor: Arc<dyn ForgeExecutor>,
574    service_name: &str,
575    journal: &AssetStatusJournal,
576) -> Result<StaticAssetSyncReport> {
577    use super::slot_field_u16;
578    use crate::reconciler::pond::DEFAULT_MINIO_API_PORT;
579
580    let api_port = slot_field_u16(slot_fields, "api_port").unwrap_or(DEFAULT_MINIO_API_PORT);
581    let bucket = slot_fields
582        .get("bucket")
583        .and_then(|v| v.as_str())
584        .context(
585            "providers.object_store missing `bucket` field for minio-container static-asset sync",
586        )?
587        .to_string();
588
589    let endpoint = format!("http://127.0.0.1:{api_port}");
590    let client = reqwest::Client::new();
591
592    sync_assets(
593        workload,
594        ctx.workspace_root,
595        &ctx.workload_dir(),
596        &client,
597        &endpoint,
598        &bucket,
599        MINIO_REGION,
600        DEFAULT_MINIO_USER,
601        DEFAULT_MINIO_PASSWORD,
602        executor,
603        service_name,
604        journal,
605    )
606    .await
607}
608
609// ── Core sync logic ───────────────────────────────────────────────────────────
610
611async fn sync_assets(
612    workload: &StaticAssetWorkload,
613    workspace_root: &Path,
614    workload_dir: &Path,
615    client: &reqwest::Client,
616    endpoint: &str,
617    bucket: &str,
618    region: &str,
619    access_key: &str,
620    secret_key: &str,
621    executor: Arc<dyn ForgeExecutor>,
622    service_name: &str,
623    journal: &AssetStatusJournal,
624) -> Result<StaticAssetSyncReport> {
625    let mut report = StaticAssetSyncReport::default();
626    let endpoint = endpoint.trim_end_matches('/');
627
628    // Load the stored catalog manifest to detect prune candidates.
629    let prior_manifest =
630        load_catalog_manifest(client, endpoint, bucket, region, access_key, secret_key).await;
631
632    // Catalog set for prune detection: current catalog filenames.
633    let current_filenames: std::collections::HashSet<&str> = workload
634        .assets
635        .iter()
636        .map(|a| a.filename.as_str())
637        .collect();
638
639    // Prune candidates: filenames in the stored manifest but not in current catalog.
640    for prior_key in prior_manifest.keys() {
641        if !current_filenames.contains(prior_key.as_str()) {
642            report.prune_candidates.push(prior_key.clone());
643        }
644    }
645
646    // Updated manifest built from this run.
647    let mut new_manifest = CatalogManifest::new();
648
649    for entry in &workload.assets {
650        // W212/R518: substituter fast-path. When the committed `[asset.derive.lock]`
651        // still matches the inputs recomputed from the current pins (purely
652        // local — no fetch) AND the bucket already holds the output, skip the
653        // entire build: no model download, no Docker transform, no PUT. This is
654        // the Nix-substituter / Bazel-remote-cache behaviour, backed by the
655        // checked-in lock as the action cache and R2 as the CAS.
656        if let Some(out_hash) = lock_skip_hash(entry, workspace_root).await {
657            // R630-B1: encode at URL-construction time (see `uri_encode_key`).
658            let object_url = format!("{endpoint}/{bucket}/{}", uri_encode_key(&entry.filename));
659            // R546-B10: the lock says WHAT the output should be; the bucket must
660            // actually hold it. An unstamped legacy object is not evidence of a
661            // match, so it falls through and rebuilds rather than blessing bytes
662            // we cannot identify — the expensive-but-correct direction.
663            let remote = head_object(client, &object_url, region, access_key, secret_key).await?;
664            if remote.matches(&out_hash) {
665                debug!(
666                    filename = %entry.filename,
667                    "derivation lock in sync + object content matches — skipping build",
668                );
669                report.already_synced.push(entry.filename.clone());
670                new_manifest.insert(entry.filename.clone(), out_hash);
671                continue;
672            }
673            if remote.exists() {
674                debug!(
675                    filename = %entry.filename,
676                    "derivation lock in sync but bucket object is unstamped or drifted \
677                     — not trusting it, falling through to build/publish",
678                );
679            }
680        }
681
682        // R438-T15: derive-mode assets materialize to a content-addressed cache
683        // path (W164); legacy `source = "..."` assets read straight from disk.
684        // Both arms return a real on-disk path that the existing BLAKE3 verify +
685        // S3 PUT loop below treats uniformly.
686        let materialized =
687            materialize_asset(entry, workspace_root, workload_dir, executor.as_ref())
688                .await
689                .with_context(|| format!("materializing asset {:?}", entry.filename))?;
690        let source_path = materialized.path;
691        // Capture before the discovered_fetch_hash is moved out below.
692        let fetch_was_bootstrap = materialized.discovered_fetch_hash.is_some();
693        // W212/R518: derivation key for this build — emitted below so the bind
694        // path refreshes `[asset.derive.lock].input_hash`.
695        let build_derive_key = materialized.derive_key.clone();
696
697        // Surface any discovered upstream BLAKE3 (bootstrap mode for
698        // `[asset.derive.fetch].blake3`). Collected into `report.bootstrapped`
699        // and emitted to `$YAH_OUTPUTS` by the summary block in `up` (W209/F4).
700        if let Some(hash) = materialized.discovered_fetch_hash {
701            debug!(
702                filename = %entry.filename,
703                discovered = %hash,
704                "bootstrap discovered upstream blake3",
705            );
706            report.bootstrapped.push(BootstrappedHash {
707                filename: entry.filename.clone(),
708                kind: BootstrapHashKind::Fetch,
709                hash,
710            });
711        }
712
713        // Read source file.
714        let body = tokio::fs::read(&source_path).await.with_context(|| {
715            format!(
716                "reading source file {} for asset {:?}",
717                source_path.display(),
718                entry.filename
719            )
720        })?;
721
722        // BLAKE3 verification — strict mode rejects mismatch and skips upload;
723        // bootstrap mode (entry.blake3 == zero sentinel) accepts the computed
724        // hash and surfaces it in the report for paste-back. The bytes are
725        // uploaded either way — the difference is whether the pin is being
726        // *verified against* (strict) or *discovered* (bootstrap).
727        let actual_hash = blake3_hex(&body);
728        if is_bootstrap_sentinel(&entry.blake3.0) {
729            debug!(
730                filename = %entry.filename,
731                discovered = %actual_hash,
732                "bootstrap discovered asset blake3",
733            );
734            report.bootstrapped.push(BootstrappedHash {
735                filename: entry.filename.clone(),
736                kind: BootstrapHashKind::Output,
737                hash: actual_hash.clone(),
738            });
739        } else if !hashes_equal(&actual_hash, &entry.blake3.0) {
740            warn!(
741                filename = %entry.filename,
742                declared = %entry.blake3.0,
743                actual = %actual_hash,
744                "BLAKE3 mismatch — source file doesn't match declared hash",
745            );
746            report.hash_mismatch.push(entry.filename.clone());
747            journal
748                .append(&AssetStatusEvent {
749                    at: Utc::now(),
750                    asset: format!("{service_name}:{}", entry.filename),
751                    from: None,
752                    to: AssetState::DriftBucket,
753                    bytes: None,
754                    blake3: None,
755                })
756                .await;
757            continue;
758        }
759
760        // W212/R518: a verified build emits its derivation key so the bind path
761        // refreshes `[asset.derive.lock].input_hash`. Paired with the output
762        // hash above, this records the action-cache entry the next run's
763        // substituter fast-path consults. Only emitted when a build actually
764        // ran (the lock-skip path `continue`d before reaching here).
765        if let Some(dk) = &build_derive_key {
766            report.bootstrapped.push(BootstrappedHash {
767                filename: entry.filename.clone(),
768                kind: BootstrapHashKind::Input,
769                hash: dk.clone(),
770            });
771        }
772
773        let key = &entry.filename;
774        // R630-B1: encode at URL-construction time (see `uri_encode_key`).
775        let object_url = format!("{endpoint}/{bucket}/{}", uri_encode_key(key));
776
777        // R546-B10: skip the PUT only when the bucket demonstrably holds THESE
778        // bytes. Existence alone is not enough — an object placed at this key
779        // out-of-band, or a rebuild that isn't byte-reproducible, leaves content
780        // that differs from the artifact we just verified. Skipping on mere
781        // existence let the bucket keep stale bytes while `new_manifest` below
782        // recorded the new hash, so the published catalog described bytes that
783        // were never uploaded.
784        //
785        // Note `actual_hash` is already verified equal to the declared
786        // `entry.blake3` at this point (the mismatch arm above `continue`s), so
787        // re-PUTting on drift converges the bucket toward the committed catalog
788        // rather than clobbering it with something unvetted.
789        let remote = head_object(client, &object_url, region, access_key, secret_key).await?;
790        if remote.matches(&actual_hash) {
791            debug!(key, "already present with matching blake3 — skipping PUT");
792            report.already_synced.push(key.clone());
793            new_manifest.insert(key.clone(), actual_hash);
794            continue;
795        }
796        if remote.exists() {
797            // Drifted, or a legacy object predating the metadata stamp. Either
798            // way re-PUT: identical bytes make it a cheap idempotent overwrite
799            // that heals the missing stamp, and differing bytes are exactly the
800            // case that must not be skipped. Legacy objects therefore cost ONE
801            // re-upload, after which the stamp makes the skip work again.
802            warn!(
803                key,
804                expected = %actual_hash,
805                remote = ?match &remote {
806                    RemoteObject::Present { blake3 } => blake3.as_deref(),
807                    RemoteObject::Absent => None,
808                },
809                "bucket object does not match the declared artifact — re-publishing",
810            );
811            report.republished.push(key.clone());
812        }
813
814        // PUT the file.
815        let body_sha256 = sha256_hex(&body);
816        let content_length = body.len();
817        let content_type = content_type_for(&source_path);
818        let headers = sign_s3_put_object(
819            &object_url,
820            &body_sha256,
821            content_type,
822            content_length,
823            region,
824            access_key,
825            secret_key,
826            // R546-B10: stamp the content hash so a later run can tell whether
827            // the bucket already holds these exact bytes.
828            Some(actual_hash.as_str()),
829        )
830        .with_context(|| format!("signing PUT {object_url}"))?;
831
832        let resp = client
833            .put(&object_url)
834            .headers(headers)
835            .body(body)
836            .send()
837            .await
838            .with_context(|| format!("PUT {object_url}"))?;
839
840        if !resp.status().is_success() {
841            let status = resp.status();
842            let body_text = resp.text().await.unwrap_or_default();
843            anyhow::bail!("PUT {object_url} → {status}: {}", body_text.trim());
844        }
845
846        info!(key, "uploaded");
847        report.uploaded.push(key.clone());
848        new_manifest.insert(key.clone(), actual_hash.clone());
849        let from_state = if fetch_was_bootstrap {
850            AssetState::PlaceholderFetch
851        } else if is_bootstrap_sentinel(&entry.blake3.0) {
852            AssetState::PlaceholderOutput
853        } else {
854            AssetState::PinnedNotPublished
855        };
856        journal
857            .append(&AssetStatusEvent {
858                at: Utc::now(),
859                asset: format!("{service_name}:{key}"),
860                from: Some(from_state),
861                to: AssetState::Published,
862                bytes: Some(content_length as u64),
863                blake3: Some(actual_hash),
864            })
865            .await;
866    }
867
868    // Save the updated manifest (non-fatal: data is already in the bucket).
869    if let Err(e) = save_catalog_manifest(
870        client,
871        endpoint,
872        bucket,
873        &new_manifest,
874        region,
875        access_key,
876        secret_key,
877    )
878    .await
879    {
880        warn!(
881            error = %e,
882            "failed to save asset catalog manifest (non-fatal) — prune detection may miss \
883             candidates on the next run"
884        );
885    }
886
887    Ok(report)
888}
889
890// ── W164 materialize step (R438-T15) ──────────────────────────────────────────
891
892/// Output of [`materialize_asset`]: the on-disk path the upload loop reads,
893/// plus any BLAKE3 discovered during bootstrap-mode fetch.
894struct MaterializedAsset {
895    path: PathBuf,
896    /// Set when `derive.fetch.blake3` was the zero sentinel and the reconciler
897    /// computed the actual upstream hash. Operator pastes this back into
898    /// `[asset.derive.fetch].blake3`. `None` in strict mode and for legacy
899    /// `source = "..."` assets.
900    discovered_fetch_hash: Option<String>,
901    /// W212/R518: the input-addressed derivation key for this build, emitted to
902    /// `$YAH_OUTPUTS` so the bind path refreshes `[asset.derive.lock].input_hash`.
903    /// `None` for `source` / no-transform assets.
904    derive_key: Option<String>,
905}
906
907/// BLAKE3 of a transform recipe's TOML bytes — an input to the derivation key
908/// (W212). The file carries the pinned container digest, steps, and placement,
909/// so hashing it captures every recipe-side input in one value. `None` when the
910/// recipe file is unreadable (the caller treats that as "can't memoize").
911async fn recipe_blake3(workspace_root: &Path, recipe: &str) -> Option<String> {
912    let path = workspace_root
913        .join(".yah/qed/transforms")
914        .join(format!("{recipe}.toml"));
915    let bytes = tokio::fs::read(&path).await.ok()?;
916    Some(blake3_hex(&bytes))
917}
918
919/// W212/R518: the substituter fast-path. Returns `Some(output_hash)` when the
920/// asset's committed `[asset.derive.lock]` is *current* — i.e. the derivation
921/// key recomputed from the COMMITTED pins (no network) equals `lock.input_hash`
922/// and the lock describes the currently-pinned output. The caller still
923/// confirms the bytes exist in the bucket before skipping the build. Returns
924/// `None` (→ build normally) for source assets, no-transform assets, bootstrap
925/// rows, a missing lock, or any input drift.
926async fn lock_skip_hash(entry: &AssetEntry, workspace_root: &Path) -> Option<String> {
927    let derive = entry.derive.as_ref()?;
928    let transform = derive.transform.as_ref()?;
929    let lock = derive.lock.as_ref()?;
930    // A sentinel pin means nothing has been pinned yet → must build.
931    if is_bootstrap_sentinel(&entry.blake3.0) || is_bootstrap_sentinel(&derive.fetch.blake3.0) {
932        return None;
933    }
934    // The lock must describe the currently-pinned output, else it's stale.
935    if !hashes_equal(&lock.output_blake3, &entry.blake3.0) {
936        return None;
937    }
938    // Recompute the derivation key from the committed pins — purely local, no
939    // fetch. The fetch pin is the declared input identity (a fixed-output
940    // derivation), so in strict mode it equals the bytes that fed the build.
941    let recipe_bk = recipe_blake3(workspace_root, &transform.recipe).await?;
942    let key = derivation_key(&derive.fetch.blake3.0, &recipe_bk, &transform.params);
943    (key == lock.input_hash).then(|| entry.blake3.0.clone())
944}
945
946/// Resolve an `[[asset]]` row to an on-disk path the upload loop can read.
947///
948/// Two modes:
949///
950/// - **Legacy `source`**: returns `workload_dir.join(source_rel)` — bytes are
951///   already on disk, the rest of the pipeline is unchanged.
952/// - **Derive (`derive.fetch[+transform]`)**: fetches the upstream blob into
953///   `.yah/cache/derive/fetch/<upstream-blake3>.bin`, optionally runs the
954///   transform recipe into `.yah/cache/derive/transform/<output-blake3>.bin`,
955///   and returns whichever cache path holds the final bytes. The shape
956///   validator (`shape_static_asset`) guarantees exactly one of the two is
957///   set, so the `else` branch is total.
958///
959/// **Bootstrap mode.** When `derive.fetch.blake3` or `entry.blake3` is the
960/// zero sentinel, the reconciler discovers the actual hash instead of
961/// verifying against the pinned value. The discovered upstream hash is
962/// returned in `discovered_fetch_hash`; the discovered output hash is
963/// computed at the upload site (the bytes are read there anyway) and
964/// surfaced separately.
965async fn materialize_asset(
966    entry: &AssetEntry,
967    workspace_root: &Path,
968    workload_dir: &Path,
969    executor: &dyn ForgeExecutor,
970) -> Result<MaterializedAsset> {
971    if let Some(source_rel) = entry.source.as_ref() {
972        return Ok(MaterializedAsset {
973            path: workload_dir.join(source_rel),
974            discovered_fetch_hash: None,
975            derive_key: None,
976        });
977    }
978
979    let derive = entry
980        .derive
981        .as_ref()
982        .expect("AssetEntry shape: exactly one of source/derive must be set (shape_static_asset)");
983
984    let cache_root = workspace_root.join(".yah/cache/derive");
985    let fetch_bootstrap = is_bootstrap_sentinel(&derive.fetch.blake3.0);
986    let (fetched_path, fetched_hash) =
987        materialize_fetch(&derive.fetch, &cache_root.join("fetch")).await?;
988    let discovered_fetch_hash = fetch_bootstrap.then(|| fetched_hash.clone());
989
990    let path = if let Some(transform) = &derive.transform {
991        materialize_transform(
992            transform,
993            &fetched_path,
994            &fetched_hash,
995            &entry.blake3.0,
996            &cache_root.join("transform"),
997            workspace_root,
998            executor,
999        )
1000        .await?
1001    } else {
1002        // No transform — the fetched bytes ARE the output. In strict mode,
1003        // fetch.blake3 must equal entry.blake3; let the upload loop's BLAKE3
1004        // verify surface any mismatch. In bootstrap mode the upload loop
1005        // discovers entry.blake3 directly from the file bytes.
1006        fetched_path
1007    };
1008
1009    // W212/R518: derivation key for this build — the same value the local action
1010    // cache used (fetched-input hash ⊕ recipe-file hash ⊕ params). Surfaced so
1011    // the bind path can refresh `[asset.derive.lock].input_hash`.
1012    let derive_key = match &derive.transform {
1013        Some(transform) => recipe_blake3(workspace_root, &transform.recipe)
1014            .await
1015            .map(|rb| derivation_key(&fetched_hash, &rb, &transform.params)),
1016        None => None,
1017    };
1018
1019    Ok(MaterializedAsset {
1020        path,
1021        discovered_fetch_hash,
1022        derive_key,
1023    })
1024}
1025
1026/// Maximum number of fetch attempts (initial try + retries).
1027#[cfg(not(test))]
1028const FETCH_MAX_ATTEMPTS: u32 = 5;
1029#[cfg(test)]
1030const FETCH_MAX_ATTEMPTS: u32 = 3; // fewer retries in tests
1031
1032/// Initial backoff between retries in milliseconds (doubles each attempt).
1033#[cfg(not(test))]
1034const FETCH_BASE_DELAY_MS: u64 = 1_000;
1035#[cfg(test)]
1036const FETCH_BASE_DELAY_MS: u64 = 1; // near-instant in tests
1037
1038/// Ceiling on retry backoff in milliseconds.
1039#[cfg(not(test))]
1040const FETCH_MAX_DELAY_MS: u64 = 30_000;
1041#[cfg(test)]
1042const FETCH_MAX_DELAY_MS: u64 = 5; // near-instant in tests
1043
1044/// Log download progress every N bytes.
1045const FETCH_LOG_INTERVAL_BYTES: u64 = 100 * 1024 * 1024; // 100 MiB
1046
1047/// Outcome of a single download attempt that did not fully succeed. Used by
1048/// [`fetch_once`] to distinguish a transient failure (retry + Range resume)
1049/// from a non-retriable 4xx (bail immediately).
1050enum FetchOnceFail {
1051    /// Server returned a non-retriable 4xx. Caller should surface and stop.
1052    Fatal(reqwest::StatusCode),
1053    /// Network error or retriable server response (5xx / 429). Partial file
1054    /// is preserved on disk for Range-header resumption on the next attempt.
1055    Transient(anyhow::Error),
1056}
1057
1058/// Fetch `fetch.url` into `<cache_dir>/<fetch.blake3>.bin`, verifying BLAKE3.
1059///
1060/// On cache HIT the network is skipped entirely; a hash mismatch surfaces as a
1061/// hard error (bit-rot / hand-edited cache, not silently re-fetched).
1062///
1063/// Cache MISS downloads the blob with:
1064/// - **Streaming to disk** — `Response::chunk()` rather than buffering the full
1065///   body in RAM (required for multi-GB blobs like whisper-large at 1.5 GB).
1066/// - **Exponential-backoff retry** — up to [`FETCH_MAX_ATTEMPTS`] attempts on
1067///   transient network errors and 5xx / 429 HTTP responses.
1068/// - **Range-header resume** — if a `.partial` file exists from a prior attempt,
1069///   subsequent tries send `Range: bytes=<offset>-` to avoid re-downloading
1070///   already-received bytes.
1071/// - **Progress logging** — `info!()` every 100 MiB surfaces download progress
1072///   through the task-pane / QED log surface (W164 OQ#4).
1073async fn materialize_fetch(fetch: &FetchSource, cache_dir: &Path) -> Result<(PathBuf, String)> {
1074    let bootstrap = is_bootstrap_sentinel(&fetch.blake3.0);
1075
1076    tokio::fs::create_dir_all(cache_dir)
1077        .await
1078        .with_context(|| format!("creating fetch cache dir {}", cache_dir.display()))?;
1079
1080    // Cache HIT — only meaningful when we know the expected hash. Bootstrap
1081    // mode has no stable cache key to look up; it always re-downloads on the
1082    // first run, then strict mode (after the operator pins the discovered
1083    // hash) takes the HIT path on subsequent runs.
1084    if !bootstrap {
1085        let cache_path = cache_dir.join(format!("{}.bin", fetch.blake3.0));
1086        if tokio::fs::try_exists(&cache_path).await.unwrap_or(false) {
1087            verify_blake3_path(&cache_path, &fetch.blake3.0)
1088                .await
1089                .with_context(|| {
1090                    format!(
1091                        "fetch cache HIT for {} but bytes don't match pinned BLAKE3 — \
1092                     rm the cache entry or fix the pin",
1093                        cache_path.display()
1094                    )
1095                })?;
1096            debug!(url = %fetch.url, "fetch cache HIT");
1097            return Ok((cache_path, fetch.blake3.0.clone()));
1098        }
1099    }
1100
1101    // Partial filename: stable per (URL, mode) so Range resume works across
1102    // attempts. In bootstrap mode every fetch shares the zero "expected" hash,
1103    // so partials are namespaced by URL hash to avoid cross-asset collisions.
1104    let partial_path = if bootstrap {
1105        cache_dir.join(format!(
1106            "bootstrap-{}.partial",
1107            blake3_hex(fetch.url.as_bytes())
1108        ))
1109    } else {
1110        cache_dir.join(format!("{}.partial", fetch.blake3.0))
1111    };
1112
1113    let client = reqwest::Client::new();
1114    let mut last_err = anyhow::anyhow!("no attempt made");
1115
1116    for attempt in 0..FETCH_MAX_ATTEMPTS {
1117        if attempt > 0 {
1118            let delay_ms = (FETCH_BASE_DELAY_MS << (attempt - 1)).min(FETCH_MAX_DELAY_MS);
1119            warn!(
1120                url = %fetch.url,
1121                attempt,
1122                delay_ms,
1123                err = %last_err,
1124                "fetch transient failure; retrying with backoff",
1125            );
1126            tokio::time::sleep(tokio::time::Duration::from_millis(delay_ms)).await;
1127        }
1128
1129        match fetch_once(&client, &fetch.url, &partial_path).await {
1130            Ok(()) => {
1131                // Compute hash once — used for verify (strict) and cache
1132                // naming (both modes; bootstrap mode names by the discovered
1133                // value rather than the zero placeholder).
1134                let bytes = tokio::fs::read(&partial_path)
1135                    .await
1136                    .with_context(|| format!("reading {} for BLAKE3", partial_path.display()))?;
1137                let actual = blake3_hex(&bytes);
1138                drop(bytes);
1139
1140                if !bootstrap && !hashes_equal(&actual, &fetch.blake3.0) {
1141                    anyhow::bail!(
1142                        "downloaded {} but BLAKE3 doesn't match pin — \
1143                         check the pin in workload.toml (actual {actual} != expected {})",
1144                        fetch.url,
1145                        fetch.blake3.0,
1146                    );
1147                }
1148
1149                let cache_path = cache_dir.join(format!("{actual}.bin"));
1150                tokio::fs::rename(&partial_path, &cache_path)
1151                    .await
1152                    .with_context(|| {
1153                        format!(
1154                            "promoting {} → {}",
1155                            partial_path.display(),
1156                            cache_path.display()
1157                        )
1158                    })?;
1159                if bootstrap {
1160                    info!(url = %fetch.url, discovered = %actual, "fetch complete (bootstrap)");
1161                } else {
1162                    info!(url = %fetch.url, "fetch complete");
1163                }
1164                return Ok((cache_path, actual));
1165            }
1166            Err(FetchOnceFail::Fatal(status)) => {
1167                anyhow::bail!("GET {} → HTTP {status} (not retriable)", fetch.url);
1168            }
1169            Err(FetchOnceFail::Transient(e)) => {
1170                last_err = e;
1171            }
1172        }
1173    }
1174
1175    Err(last_err).with_context(|| {
1176        format!(
1177            "GET {} failed after {FETCH_MAX_ATTEMPTS} attempts",
1178            fetch.url
1179        )
1180    })
1181}
1182
1183/// Single download attempt: GET `url` (with `Range` if `partial_path` is non-empty),
1184/// stream the response body to `partial_path`, and return once the body is exhausted.
1185///
1186/// Returns `Ok(())` when all bytes were received and flushed to disk.
1187/// Returns `Err(FetchOnceFail::Fatal)` for non-retriable 4xx responses.
1188/// Returns `Err(FetchOnceFail::Transient)` for connection errors, 5xx, or 429;
1189/// the partial file is left intact so the next attempt can resume via `Range`.
1190async fn fetch_once(
1191    client: &reqwest::Client,
1192    url: &str,
1193    partial_path: &Path,
1194) -> Result<(), FetchOnceFail> {
1195    use tokio::io::AsyncWriteExt;
1196
1197    let resume_offset = tokio::fs::metadata(partial_path)
1198        .await
1199        .ok()
1200        .map(|m| m.len())
1201        .filter(|&n| n > 0);
1202
1203    let mut req = client.get(url);
1204    if let Some(offset) = resume_offset {
1205        req = req.header(reqwest::header::RANGE, format!("bytes={offset}-"));
1206        info!(url, offset, "resuming partial download");
1207    } else {
1208        info!(url, "downloading");
1209    }
1210
1211    let resp = req
1212        .send()
1213        .await
1214        .map_err(|e| FetchOnceFail::Transient(anyhow::anyhow!("connecting to {url}: {e}")))?;
1215
1216    let status = resp.status();
1217    let is_partial_response = status == reqwest::StatusCode::PARTIAL_CONTENT;
1218
1219    if status == reqwest::StatusCode::RANGE_NOT_SATISFIABLE {
1220        // Partial file may already hold all bytes (prior complete-but-not-verified
1221        // attempt). Delete it and let the next retry start fresh.
1222        let _ = tokio::fs::remove_file(partial_path).await;
1223        return Err(FetchOnceFail::Transient(anyhow::anyhow!(
1224            "GET {url} → 416 Range Not Satisfiable; partial cleared"
1225        )));
1226    }
1227    if status.is_client_error() {
1228        return Err(FetchOnceFail::Fatal(status));
1229    }
1230    if status.is_server_error() || status == reqwest::StatusCode::TOO_MANY_REQUESTS {
1231        return Err(FetchOnceFail::Transient(anyhow::anyhow!(
1232            "GET {url} → HTTP {status}"
1233        )));
1234    }
1235    if !status.is_success() && !is_partial_response {
1236        return Err(FetchOnceFail::Fatal(status));
1237    }
1238
1239    // Server returned 200 instead of 206 — it ignored our Range request.
1240    // Discard any partial bytes and stream the full body fresh.
1241    if !is_partial_response && resume_offset.is_some() {
1242        let _ = tokio::fs::remove_file(partial_path).await;
1243    }
1244
1245    let mut file = tokio::fs::OpenOptions::new()
1246        .write(true)
1247        .create(true)
1248        .append(is_partial_response)
1249        .truncate(!is_partial_response)
1250        .open(partial_path)
1251        .await
1252        .map_err(|e| {
1253            FetchOnceFail::Transient(anyhow::anyhow!("opening {}: {e}", partial_path.display()))
1254        })?;
1255
1256    let mut downloaded = if is_partial_response {
1257        resume_offset.unwrap_or(0)
1258    } else {
1259        0
1260    };
1261    let mut resp = resp;
1262    loop {
1263        match resp.chunk().await {
1264            Ok(Some(chunk)) => {
1265                file.write_all(&chunk).await.map_err(|e| {
1266                    FetchOnceFail::Transient(anyhow::anyhow!(
1267                        "writing chunk to {}: {e}",
1268                        partial_path.display()
1269                    ))
1270                })?;
1271                let prev = downloaded;
1272                downloaded += chunk.len() as u64;
1273                if downloaded / FETCH_LOG_INTERVAL_BYTES > prev / FETCH_LOG_INTERVAL_BYTES {
1274                    info!(
1275                        url,
1276                        downloaded_mib = downloaded / (1024 * 1024),
1277                        "fetch progress",
1278                    );
1279                }
1280            }
1281            Ok(None) => break,
1282            Err(e) => {
1283                return Err(FetchOnceFail::Transient(anyhow::anyhow!(
1284                    "reading body from {url}: {e}"
1285                )));
1286            }
1287        }
1288    }
1289
1290    file.flush().await.map_err(|e| {
1291        FetchOnceFail::Transient(anyhow::anyhow!("flushing {}: {e}", partial_path.display()))
1292    })?;
1293
1294    Ok(())
1295}
1296
1297/// Run the transform recipe against `input_path`, writing the output to
1298/// `<cache_dir>/<actual_blake3>.bin`. In strict mode the actual hash is
1299/// verified against `output_blake3`; in bootstrap mode (`output_blake3` ==
1300/// zero sentinel) the actual hash is accepted as-is and named accordingly.
1301/// Cache HIT (file present + hash matches) skips recipe execution; bootstrap
1302/// mode has no stable cache key and always re-runs the recipe.
1303/// W212 schema version for the derivation key. Bump when the *way* we hash or
1304/// lower inputs changes (not when an individual recipe changes — that's
1305/// captured by the recipe-file hash). A bump invalidates every action-cache
1306/// entry, forcing a clean rebuild under the new keying.
1307const DERIVE_KEY_SCHEMA: u32 = 1;
1308
1309/// Compute the input-addressed action-cache key for a derive-mode transform
1310/// (W212). A pure function of the complete declared input set:
1311///
1312/// - `input_hash` — BLAKE3 of the fetched transform input (the fixed-output /
1313///   version anchor; for whisper this is `config.json`, which the model's repo
1314///   version tracks).
1315/// - `recipe_blake3` — BLAKE3 of the recipe TOML bytes. The file carries the
1316///   pinned container digest, the steps, and the placement, so hashing it
1317///   covers all three: a digest bump or a step edit flips the key.
1318/// - `params` — the workload-side invocation params (`BTreeMap` is already
1319///   sorted, so the encoding is deterministic).
1320///
1321/// **Hermeticity invariant:** every input that can change the output bytes MUST
1322/// feed this key. A missing dimension reintroduces the W164/R438 silent-stale
1323/// cache bug. The per-dimension unit test guards this.
1324fn derivation_key(
1325    input_hash: &str,
1326    recipe_blake3: &str,
1327    params: &BTreeMap<String, String>,
1328) -> String {
1329    let mut buf = String::new();
1330    buf.push_str(&format!("derive-key-v{DERIVE_KEY_SCHEMA}\n"));
1331    buf.push_str(&format!("input={input_hash}\n"));
1332    buf.push_str(&format!("recipe={recipe_blake3}\n"));
1333    for (k, v) in params {
1334        buf.push_str(&format!("param.{k}={v}\n"));
1335    }
1336    blake3_hex(buf.as_bytes())
1337}
1338
1339/// Read a recorded action-cache output hash, if present. A missing or
1340/// unreadable / empty entry is a cache miss, never an error.
1341async fn read_action_cache(ac_path: &Path) -> Option<String> {
1342    let raw = tokio::fs::read_to_string(ac_path).await.ok()?;
1343    let hash = raw.trim();
1344    (!hash.is_empty()).then(|| hash.to_string())
1345}
1346
1347/// Record an action-cache entry (`derive_key → output hash`). Written
1348/// atomically via tmp + rename so a crashed run never leaves a half-written
1349/// entry a later run would trust.
1350async fn write_action_cache(ac_path: &Path, output_hash: &str) -> Result<()> {
1351    if let Some(parent) = ac_path.parent() {
1352        tokio::fs::create_dir_all(parent)
1353            .await
1354            .with_context(|| format!("creating action-cache dir {}", parent.display()))?;
1355    }
1356    let tmp = ac_path.with_extension("out.tmp");
1357    tokio::fs::write(&tmp, format!("{output_hash}\n"))
1358        .await
1359        .with_context(|| format!("writing action-cache tmp {}", tmp.display()))?;
1360    tokio::fs::rename(&tmp, ac_path)
1361        .await
1362        .with_context(|| format!("promoting action-cache entry {}", ac_path.display()))?;
1363    Ok(())
1364}
1365
1366async fn materialize_transform(
1367    transform: &TransformSpec,
1368    input_path: &Path,
1369    input_hash: &str,
1370    output_blake3: &str,
1371    cache_dir: &Path,
1372    workspace_root: &Path,
1373    executor: &dyn ForgeExecutor,
1374) -> Result<PathBuf> {
1375    let bootstrap = is_bootstrap_sentinel(output_blake3);
1376
1377    tokio::fs::create_dir_all(cache_dir)
1378        .await
1379        .with_context(|| format!("creating transform cache dir {}", cache_dir.display()))?;
1380
1381    // Load + hash the recipe up front: the recipe TOML's bytes are an INPUT to
1382    // the derivation key (W212), so the key — and therefore the cache decision —
1383    // depends on them. The file carries the pinned container digest, steps, and
1384    // placement, so a change to any of those flips the key and forces a rebuild.
1385    let transforms_dir = workspace_root.join(".yah/qed/transforms");
1386    let loader = TransformRecipeLoader::new(&transforms_dir);
1387    let recipe_path = loader.recipe_path(&transform.recipe);
1388    let recipe = loader.load(&transform.recipe).with_context(|| {
1389        format!(
1390            "loading recipe {:?} from {}",
1391            transform.recipe,
1392            transforms_dir.display()
1393        )
1394    })?;
1395    let recipe_bytes = tokio::fs::read(&recipe_path).await.with_context(|| {
1396        format!(
1397            "reading recipe {} for derivation key",
1398            recipe_path.display()
1399        )
1400    })?;
1401    let recipe_blake3 = blake3_hex(&recipe_bytes);
1402
1403    // W212: input-addressed action cache. The skip decision is a pure function
1404    // of the declared INPUTS (fetched input content ⊕ recipe definition ⊕
1405    // invocation params ⊕ lowering-schema version), not of the expected output
1406    // hash. A recipe / digest / param change flips `derive_key` → guaranteed
1407    // miss → rebuild, eliminating the warm-cache silent-stale skip (the
1408    // W164/R438 defect this fixes). Applies in bootstrap mode too: identical
1409    // inputs surface the recorded output without re-running.
1410    let derive_key = derivation_key(input_hash, &recipe_blake3, &transform.params);
1411    let ac_path = cache_dir.join("ac").join(format!("{derive_key}.out"));
1412
1413    if let Some(recorded) = read_action_cache(&ac_path).await {
1414        let cas_path = cache_dir.join(format!("{recorded}.bin"));
1415        if tokio::fs::try_exists(&cas_path).await.unwrap_or(false)
1416            && verify_blake3_path(&cas_path, &recorded).await.is_ok()
1417        {
1418            // The output pin (`entry.blake3`) is still enforced downstream by
1419            // the upload loop's strict BLAKE3 verify, so a pin that has drifted
1420            // from the inputs surfaces there even though we skip the transform.
1421            debug!(recipe = %recipe.name, derive_key, "derivation cache HIT — skipping transform");
1422            return Ok(cas_path);
1423        }
1424        // AC entry present but the CAS bytes are gone / corrupt → fall through
1425        // and re-materialise (the AC records what the output should be; the CAS
1426        // lost the bytes).
1427    }
1428
1429    // Absolute workspace_root for the container bind-mount — docker rejects
1430    // `-w .` ("the working directory '.' is invalid"). Callers may pass a
1431    // relative path (the CLI `--path` default is "."), so canonicalize once.
1432    let workspace_abs = workspace_root
1433        .canonicalize()
1434        .with_context(|| format!("canonicalizing workspace root {}", workspace_root.display()))?;
1435
1436    // R546-B8: the IN/OUT bindings handed to the recipe MUST be absolute.
1437    // `cache_dir` is derived from workspace_root, which is "." by CLI default,
1438    // so these used to be relative (`./.yah/cache/derive/transform/<key>.tmp`).
1439    // A relative path only survives if the recipe never leaves its cwd — true
1440    // for whisper's recipes, FALSE for rusty-v8: build-v8.sh chdirs into a
1441    // scratch dir (/tmp/tmp.XXXX/v8src) to build V8, so it wrote its finished
1442    // tar to "<scratch>/./.yah/cache/..." INSIDE the container, invisible to the
1443    // host. The step then exited 0 and the reconciler failed reading a file that
1444    // was never going to be there — after a ~2h build. Canonicalize the parent
1445    // (it exists; created above) and join the filename, since the tmp output
1446    // itself does not exist yet and cannot be canonicalized directly.
1447    let cache_dir_abs = cache_dir
1448        .canonicalize()
1449        .with_context(|| format!("canonicalizing transform cache dir {}", cache_dir.display()))?;
1450
1451    // Tmp output is named by the derivation key — unique per input set, so
1452    // concurrent rows (and zero-sentinel bootstrap rows) never collide on it.
1453    let tmp_output = cache_dir_abs.join(format!("{derive_key}.tmp"));
1454
1455    let input_abs = input_path
1456        .canonicalize()
1457        .unwrap_or_else(|_| input_path.to_path_buf());
1458
1459    // R555-F3: a remotely-placed recipe runs on a worker with its own
1460    // filesystem, so the IN/OUT contract has to be re-read there. `remote_out`
1461    // is the worker-side path bound as {{YAH_TRANSFORM_OUT}}; the bytes are
1462    // pulled back to `tmp_output` after the step, and everything downstream
1463    // (exists-check, BLAKE3, rename, action cache) is untouched.
1464    let remote_out = match &recipe.placement.location {
1465        TaskLocation::Local => {
1466            refuse_secrets_on_a_local_recipe(&recipe)?;
1467            None
1468        }
1469        _ => Some(remote_transform_out(&recipe, &derive_key)?),
1470    };
1471
1472    let mut params: BTreeMap<String, String> = BTreeMap::new();
1473    params.insert(
1474        ENV_TRANSFORM_IN_0.to_string(),
1475        input_abs.to_string_lossy().into_owned(),
1476    );
1477    params.insert(
1478        ENV_TRANSFORM_OUT.to_string(),
1479        remote_out
1480            .as_ref()
1481            .unwrap_or(&tmp_output)
1482            .to_string_lossy()
1483            .into_owned(),
1484    );
1485    for (k, v) in &transform.params {
1486        params.insert(k.clone(), v.clone());
1487    }
1488
1489    info!(recipe = %recipe.name, "transform cache MISS, running");
1490    for step in &recipe.steps {
1491        let argv = substitute_argv(&step.argv, &params);
1492        // substitute_argv preserves `{{key}}` for unknown keys (no shell, no
1493        // string concat). Surface a missing-binding bug as a hard error rather
1494        // than letting the subprocess receive a literal placeholder.
1495        if let Some(unresolved) = argv.iter().find(|a| a.contains("{{")) {
1496            anyhow::bail!(
1497                "recipe {:?} step {:?}: unresolved placeholder in argv element {:?}",
1498                recipe.name,
1499                step.name,
1500                unresolved,
1501            );
1502        }
1503        // R555-T2 opened the recipe surface to `remote` / `remote_any`, so the
1504        // lowered spec carries whatever the recipe declared and reaches the
1505        // matching driver through the injected router (R555-F3). The two
1506        // placements need different execution context, and the difference is
1507        // invisible at the type level — hence the split below rather than one
1508        // shared `ctx`.
1509        let spec = lower_recipe_step_to_forge_spec(&recipe, step, argv);
1510        let mut ctx = ExecContext::default();
1511        if let Some(remote_out) = &remote_out {
1512            // NO cwd: `workspace_abs` is a path on THIS box. The local driver
1513            // bind-mounts it; a remote workdir is just a string interpreted on
1514            // the worker, where that path doesn't exist. A recipe needing a
1515            // source tree on the worker must bring it (the rusty-v8 builder
1516            // image clones its own).
1517            ctx = ctx.with_produced(remote_out.clone(), tmp_output.clone());
1518            // R555-F4 / W235 §(c): a signed recipe carries its admission grant
1519            // to kamaji. The grant is DERIVED from the recipe here rather than
1520            // stored in the TOML, so editing what a recipe runs un-signs it;
1521            // `None` for an unsigned recipe, which a node running the default
1522            // `permissive` policy still admits.
1523            if let Some(envelope) =
1524                velveteen_exec::envelope_for_recipe_step(&recipe, step)
1525                    .with_context(|| format!("deriving admission grant for recipe {:?}", recipe.name))?
1526            {
1527                ctx = ctx.with_admission(envelope);
1528            }
1529            // R555-F5: the credentials the recipe declared, mounted per run.
1530            // Only ever on the remote leg — the local driver refuses them,
1531            // because a dev box has no cluster secret store to resolve them
1532            // from and a silently-dropped credential fails deep inside the
1533            // build instead of here.
1534            if !recipe.secrets.is_empty() {
1535                ctx = ctx
1536                    .with_secrets(recipe.secrets.iter().map(|s| s.to_mount()).collect());
1537            }
1538        } else {
1539            ctx = ctx.with_cwd(workspace_abs.clone());
1540            // `platform` asks a HOST container runtime for foreign-arch
1541            // emulation. It has no remote referent — a remote run picks
1542            // architecture by scheduling (mesh_tags) — and RemoteForgeDriver
1543            // refuses it rather than handing back a wrong-arch artifact, so it
1544            // is only ever applied on the local leg.
1545            if let Some(platform) = &recipe.placement.platform {
1546                ctx = ctx.with_platform(platform.clone());
1547            }
1548        }
1549        let outcome = executor
1550            .execute(spec, ctx, None)
1551            .await
1552            .with_context(|| format!("executing recipe {:?} step {:?}", recipe.name, step.name))?;
1553        if !outcome.succeeded() {
1554            anyhow::bail!(
1555                "recipe {:?} step {:?} failed ({}): {}",
1556                recipe.name,
1557                step.name,
1558                outcome.status.discriminant(),
1559                outcome.stderr_tail
1560            );
1561        }
1562    }
1563
1564    // R546-B8: every step exited 0, so if the output is missing the recipe
1565    // simply never wrote it. Say THAT, rather than letting the `read` below
1566    // surface `No such file or directory` on a cache path — which reads like
1567    // cache corruption and sent the last person debugging the wrong subsystem
1568    // after a ~2h build. The relative-OUT bug that caused it is fixed above,
1569    // but a recipe can still write to the wrong place on its own, and this is
1570    // the only moment we can tell the operator exactly which contract broke.
1571    if !tokio::fs::try_exists(&tmp_output).await.unwrap_or(false) {
1572        anyhow::bail!(
1573            "recipe {:?} completed successfully but produced no output at {} \
1574             ({ENV_TRANSFORM_OUT}). The recipe's last step must write its artifact \
1575             to that exact path — check that it doesn't chdir and then write to a \
1576             relative location, and that it isn't writing to a directory instead \
1577             of a file.",
1578            recipe.name,
1579            // A remote run was told a worker-side path; naming `tmp_output` (a
1580            // local path it never saw) would send the reader hunting for a
1581            // binding bug that isn't there.
1582            remote_out.as_ref().unwrap_or(&tmp_output).display(),
1583        );
1584    }
1585
1586    // Compute the actual hash once — used for verify (strict) and cache
1587    // naming (both modes). Bootstrap mode names by the discovered value;
1588    // strict mode names by the expected value (which equals actual after
1589    // the verify below).
1590    let output_bytes = tokio::fs::read(&tmp_output).await.with_context(|| {
1591        format!(
1592            "reading transform output {} for BLAKE3",
1593            tmp_output.display()
1594        )
1595    })?;
1596    let actual = blake3_hex(&output_bytes);
1597    drop(output_bytes);
1598
1599    if !bootstrap && !hashes_equal(&actual, output_blake3) {
1600        anyhow::bail!(
1601            "transform output from recipe {:?} doesn't match pinned BLAKE3 \
1602             (actual {actual} != expected {output_blake3})",
1603            recipe.name
1604        );
1605    }
1606
1607    // tmp_output already lives in cache_dir — atomic publish is one rename.
1608    let cache_path = cache_dir.join(format!("{actual}.bin"));
1609    tokio::fs::rename(&tmp_output, &cache_path)
1610        .await
1611        .with_context(|| {
1612            format!(
1613                "renaming {} → {}",
1614                tmp_output.display(),
1615                cache_path.display()
1616            )
1617        })?;
1618
1619    // W212: record the action-cache entry (derive_key → output hash) so the
1620    // next run with identical inputs skips this transform entirely.
1621    write_action_cache(&ac_path, &actual)
1622        .await
1623        .with_context(|| format!("recording action-cache entry {}", ac_path.display()))?;
1624
1625    if bootstrap {
1626        info!(
1627            recipe = %recipe.name,
1628            discovered = %actual,
1629            "transform complete (bootstrap)",
1630        );
1631    }
1632
1633    Ok(cache_path)
1634}
1635
1636/// State of the committed `[asset.derive.fetch].blake3` pin, relative to the
1637/// fetched-input hash a seed run actually keyed its derivation on (R546-B6).
1638///
1639/// The W212 substituter fast-path ([`lock_skip_hash`]) recomputes the derivation
1640/// key from the COMMITTED pins with no network access, so it bails immediately
1641/// when the fetch pin is still the zero sentinel. Seeding a lock without also
1642/// pinning the fetch input therefore leaves that fast-path disarmed for every
1643/// machine except the one that seeded (whose local action cache masks it).
1644#[derive(Debug, Clone, PartialEq, Eq)]
1645pub enum FetchPinState {
1646    /// Committed pin equals the fetched-input hash — the fast-path can engage.
1647    Pinned,
1648    /// Committed pin is the 64-zero sentinel — the fast-path is disarmed until
1649    /// the operator pastes the fetched-input hash back into the workload.
1650    Sentinel,
1651    /// Committed pin names a DIFFERENT blob than the one this seed fetched.
1652    /// Either the version anchor moved or the pin is wrong; the fast-path will
1653    /// silently decline (input drift) until they agree.
1654    Mismatch { committed: String },
1655}
1656
1657/// Classify the committed `[asset.derive.fetch].blake3` against the hash the
1658/// fetch actually resolved to (R546-B6). Pure so the three arms are testable
1659/// without a network fetch.
1660fn classify_fetch_pin(committed: &str, fetched: &str) -> FetchPinState {
1661    if is_bootstrap_sentinel(committed) {
1662        FetchPinState::Sentinel
1663    } else if hashes_equal(committed, fetched) {
1664        FetchPinState::Pinned
1665    } else {
1666        FetchPinState::Mismatch {
1667            committed: committed.to_string(),
1668        }
1669    }
1670}
1671
1672/// Outcome of seeding the transform derivation cache from a pre-built artifact
1673/// (the qed→W164 bridge, R546-T3).
1674#[derive(Debug, Clone)]
1675pub struct SeededDerivation {
1676    /// The W212 derivation key the seeded action-cache entry is filed under —
1677    /// byte-identical to the one [`materialize_transform`] will look up, so the
1678    /// next `yah cloud apply` HITs it. Equals the value to paste into
1679    /// `[asset.derive.lock].input_hash`.
1680    pub derive_key: String,
1681    /// BLAKE3 of the pre-built artifact — the transform output hash. Equals the
1682    /// value to paste into `[[asset]].blake3` and `[asset.derive.lock].output_blake3`.
1683    pub output_blake3: String,
1684    /// BLAKE3 of the fetched *input* the derivation key was keyed on — the
1685    /// fourth paste-back value, `[asset.derive.fetch].blake3` (R546-B6). Without
1686    /// it the seeded lock is unusable off the seeding machine.
1687    pub fetch_blake3: String,
1688    /// What the workload currently commits for that pin, when the caller went
1689    /// through [`seed_derivation_for_target`] (which has the `[[asset]]` row in
1690    /// hand). `None` for direct [`seed_transform_derivation`] callers.
1691    pub fetch_pin: Option<FetchPinState>,
1692    /// The content-addressed store path the artifact was landed at.
1693    pub cas_path: PathBuf,
1694}
1695
1696/// Seed the transform derivation cache (AC + CAS) from an artifact built OUT OF
1697/// BAND — the qed→W164 bridge (R546-T3).
1698///
1699/// # Why this exists
1700///
1701/// The static-asset reconciler lowers every transform to
1702/// [`TaskLocation::Local`](task::TaskLocation::Local) (see
1703/// [`lower_recipe_step_to_forge_spec`]) — it has no fleet-offload path, so on a
1704/// foreign-arch host it can only build the recipe under emulation (which OOMs for
1705/// the rusty_v8 musl build, the reason R546 exists). `yah qed run <pipeline>`
1706/// (e.g. rusty-v8-musl) DOES offload to an arch-matched build-worker and, via R590-F6,
1707/// retrieves the produced tar content-addressed onto the caller. This function
1708/// bridges that pre-built tar into the W164 substituter: it writes the exact
1709/// action-cache + CAS entries [`materialize_transform`] would have written, so
1710/// the next `yah cloud apply` finds a HIT and PUBLISHES the pre-built bytes to
1711/// the consumer key + records the lock, instead of re-running the transform.
1712///
1713/// # Hermeticity
1714///
1715/// The derivation key is computed with the reconciler's OWN [`derivation_key`] +
1716/// [`recipe_blake3`], keyed on the SAME `fetched_hash` the reconciler derives
1717/// from the version anchor. Reusing those (not reimplementing) is what makes the
1718/// seeded key byte-identical to the lookup key — a drift would reintroduce the
1719/// W164/R438 silent-stale-cache bug. `fetched_hash` MUST be the value
1720/// [`materialize_fetch`] returns for `derive.fetch` (see [`seed_derivation_for_target`]).
1721pub async fn seed_transform_derivation(
1722    workspace_root: &Path,
1723    transform: &TransformSpec,
1724    fetched_hash: &str,
1725    artifact_path: &Path,
1726) -> Result<SeededDerivation> {
1727    let recipe_bk = recipe_blake3(workspace_root, &transform.recipe)
1728        .await
1729        .ok_or_else(|| {
1730            anyhow::anyhow!(
1731                "recipe {:?} unreadable under .yah/qed/transforms — cannot compute derivation key",
1732                transform.recipe,
1733            )
1734        })?;
1735    let derive_key = derivation_key(fetched_hash, &recipe_bk, &transform.params);
1736
1737    let bytes = tokio::fs::read(artifact_path)
1738        .await
1739        .with_context(|| format!("reading pre-built artifact {}", artifact_path.display()))?;
1740    let output_blake3 = blake3_hex(&bytes);
1741
1742    let cache_dir = workspace_root.join(".yah/cache/derive/transform");
1743    tokio::fs::create_dir_all(&cache_dir)
1744        .await
1745        .with_context(|| format!("creating transform cache dir {}", cache_dir.display()))?;
1746
1747    // CAS: <cache_dir>/<output_blake3>.bin — the exact name materialize_transform
1748    // renames its output to (so its HIT-path verify_blake3_path passes). Atomic
1749    // tmp+rename; idempotent when the entry already exists.
1750    let cas_path = cache_dir.join(format!("{output_blake3}.bin"));
1751    if !tokio::fs::try_exists(&cas_path).await.unwrap_or(false) {
1752        let tmp = cache_dir.join(format!("{output_blake3}.seed.tmp"));
1753        tokio::fs::write(&tmp, &bytes)
1754            .await
1755            .with_context(|| format!("writing CAS tmp {}", tmp.display()))?;
1756        tokio::fs::rename(&tmp, &cas_path)
1757            .await
1758            .with_context(|| format!("promoting CAS entry {}", cas_path.display()))?;
1759    }
1760
1761    // Action cache: <cache_dir>/ac/<derive_key>.out = <output_blake3>. Reuses the
1762    // reconciler's writer so the on-disk format can't drift from the reader.
1763    let ac_path = cache_dir.join("ac").join(format!("{derive_key}.out"));
1764    write_action_cache(&ac_path, &output_blake3)
1765        .await
1766        .with_context(|| format!("recording seeded action-cache entry {}", ac_path.display()))?;
1767
1768    info!(
1769        recipe = %transform.recipe,
1770        derive_key,
1771        output_blake3,
1772        fetch_blake3 = fetched_hash,
1773        "seeded transform derivation cache from pre-built artifact (qed→W164 bridge)",
1774    );
1775
1776    Ok(SeededDerivation {
1777        derive_key,
1778        output_blake3,
1779        fetch_blake3: fetched_hash.to_string(),
1780        fetch_pin: None,
1781        cas_path,
1782    })
1783}
1784
1785/// CLI-facing entry for the qed→W164 bridge (R546-T3): seed the derivation cache
1786/// for the `[[asset]]` row whose `derive.transform.params["target"]` equals
1787/// `target`, from a pre-built `artifact_path`.
1788///
1789/// Loads the static-asset workload, resolves the matching asset row, computes the
1790/// fetched-input hash via the reconciler's own [`materialize_fetch`] (downloading
1791/// the version anchor once; cached thereafter), then delegates to
1792/// [`seed_transform_derivation`]. After this returns, `yah cloud apply` on the
1793/// same service publishes the pre-built bytes without re-running the transform.
1794pub async fn seed_derivation_for_target(
1795    workspace_root: &Path,
1796    workload_path: &Path,
1797    target: &str,
1798    artifact_path: &Path,
1799) -> Result<SeededDerivation> {
1800    let raw = tokio::fs::read_to_string(workload_path)
1801        .await
1802        .with_context(|| format!("reading workload {}", workload_path.display()))?;
1803    let workload: StaticAssetWorkload = toml::from_str(&raw)
1804        .with_context(|| format!("parsing static-asset workload {}", workload_path.display()))?;
1805
1806    let entry = workload
1807        .assets
1808        .iter()
1809        .find(|a| {
1810            a.derive
1811                .as_ref()
1812                .and_then(|d| d.transform.as_ref())
1813                .map(|t| t.params.get("target").map(String::as_str) == Some(target))
1814                .unwrap_or(false)
1815        })
1816        .ok_or_else(|| {
1817            anyhow::anyhow!(
1818                "no [[asset]] with derive.transform.params.target = {target:?} in {}",
1819                workload_path.display(),
1820            )
1821        })?;
1822
1823    let derive = entry
1824        .derive
1825        .as_ref()
1826        .expect("asset matched by derive.transform above");
1827    let transform = derive
1828        .transform
1829        .as_ref()
1830        .expect("asset matched by derive.transform above");
1831
1832    // Recompute the fetched-input hash exactly as the reconciler will — same
1833    // fetch source, same cache dir.
1834    let cache_root = workspace_root.join(".yah/cache/derive");
1835    let (_fetched_path, fetched_hash) =
1836        materialize_fetch(&derive.fetch, &cache_root.join("fetch")).await?;
1837
1838    // R546-B6: classify the COMMITTED fetch pin against what we just fetched, so
1839    // the caller can tell the operator whether the W212 fast-path is armed. A
1840    // seeded lock with a sentinel fetch pin skips builds only on this machine
1841    // (via the local action cache) — everywhere else `lock_skip_hash` declines.
1842    let fetch_pin = classify_fetch_pin(&derive.fetch.blake3.0, &fetched_hash);
1843
1844    let mut seeded =
1845        seed_transform_derivation(workspace_root, transform, &fetched_hash, artifact_path).await?;
1846    seeded.fetch_pin = Some(fetch_pin);
1847    Ok(seeded)
1848}
1849
1850/// Lower a single recipe step to a [`ForgeSpec`] (W164).
1851///
1852/// - `image` is always `Some(recipe.image)` — recipes always run inside the
1853///   pinned container.
1854/// - `where_` mirrors `recipe.placement` straight through — both the
1855///   recipe-declared location and runtime. Until W235 this hard-coded
1856///   `TaskLocation::Local` because `RecipeLocation` had no other variant;
1857///   R555-T2 opened the recipe surface to `remote` / `remote_any`, so pinning
1858///   here would have quietly demoted every remote recipe back to the dev box.
1859/// - `timeout=0` in the recipe means "no timeout" (omitted from the spec).
1860/// - `label = "transform:<recipe>:<step>"`; initiator carries the reconciler
1861///   identity in the Gnome variant so audit traces attribute the run.
1862///
1863/// Pure function: callers feed it the already-substituted argv (or the raw
1864/// one in tests) and decide what to do with the resulting spec. Exposed at
1865/// `pub(crate)` for golden-test parity with the BuildMode lowering helper
1866/// (R438-T7).
1867pub(crate) fn lower_recipe_step_to_forge_spec(
1868    recipe: &TransformRecipe,
1869    step: &RecipeStep,
1870    substituted_argv: Vec<String>,
1871) -> ForgeSpec {
1872    ForgeSpec {
1873        command: ForgeCommand::Subprocess {
1874            argv: substituted_argv,
1875            image: Some(recipe.image.clone()),
1876        },
1877        where_: TaskPlacement::new(recipe.placement.location.clone(), recipe.placement.runtime),
1878        timeout: if step.timeout == 0 {
1879            None
1880        } else {
1881            Some(Millis::from_secs(step.timeout))
1882        },
1883        label: Some(format!("transform:{}:{}", recipe.name, step.name)),
1884        initiator: Initiator::Gnome {
1885            camp: "static-asset-reconciler".into(),
1886            shift: format!("derive-{}", recipe.name),
1887        },
1888        mesh_access: MeshAccess::default(),
1889        cache_key: None,
1890    }
1891}
1892
1893/// Validate a remotely-placed transform recipe and return the worker-side path
1894/// its output must be written to (R555-F3).
1895///
1896/// Three things a local recipe may do that a remote one may not, each refused
1897/// here rather than at the point it would produce a wrong artifact:
1898///
1899/// 1. **Reference `{{YAH_TRANSFORM_IN_0}}`.** The fetched input lives on this
1900///    box. [`velveteen_exec::WardenClient`] has a retrieval leg
1901///    (`fetch_produced_file`) and no upload leg, so there is no transport that
1902///    puts those bytes on the worker. Substituting the host path would hand
1903///    the recipe a path that doesn't resolve there — and the recipes that
1904///    ignore IN_0 entirely (rusty-v8-musl, whisper-bundle-tar drive their own
1905///    source) are exactly the ones worth dispatching, so this is a real
1906///    boundary rather than a stopgap.
1907/// 2. **Declare more than one step.** Each step is a separate one-shot
1908///    workload with its own container and its own produced dir — locally the
1909///    steps share a filesystem, remotely they share nothing. A two-step remote
1910///    recipe would silently lose whatever step 1 wrote.
1911/// 3. **Declare `[placement] platform`.** That asks a *host* container runtime
1912///    for foreign-arch emulation; a yubaba node has no such knob and picks
1913///    architecture by scheduling instead. `RemoteForgeDriver` refuses it too —
1914///    this refusal exists so the message names the recipe (R555-T7 is the
1915///    ticket that collapses the per-arch recipe fork onto `mesh_tags`).
1916fn remote_transform_out(recipe: &TransformRecipe, derive_key: &str) -> Result<PathBuf> {
1917    if recipe.steps.len() > 1 {
1918        anyhow::bail!(
1919            "recipe {:?} declares {} steps and a remote placement. Each step dispatches as \
1920             its own one-shot workload with its own container and produced dir, so steps \
1921             cannot hand files to each other the way they do locally — collapse them into \
1922             one step (the builder image is the right place for the sequencing), or run \
1923             the recipe locally",
1924            recipe.name,
1925            recipe.steps.len(),
1926        );
1927    }
1928    if let Some(platform) = &recipe.placement.platform {
1929        anyhow::bail!(
1930            "recipe {:?} declares [placement] platform = {:?} together with a remote \
1931             location. `platform` asks a host container runtime for foreign-arch \
1932             emulation; a remote node has no such knob and selects architecture by \
1933             scheduling instead. Drop it and express the arch as mesh tags, e.g. \
1934             location = {{ kind = \"remote_any\", tier = \"infra\", mesh_tags = \
1935             [\"tag:build-worker\", \"arch:x86\", \"os:linux\"] }}",
1936            recipe.name,
1937            platform,
1938        );
1939    }
1940    let in_0 = format!("{{{{{ENV_TRANSFORM_IN_0}}}}}");
1941    for step in &recipe.steps {
1942        if step.argv.iter().any(|a| a.contains(&in_0)) {
1943            anyhow::bail!(
1944                "recipe {:?} step {:?} references {} but is placed remotely. The fetched \
1945                 input lives on this machine and there is no upload leg to the worker \
1946                 (WardenClient can retrieve produced files, not send inputs), so the \
1947                 binding would name a path that does not exist on the node. Either have \
1948                 the recipe fetch its own input, or run it locally",
1949                recipe.name,
1950                step.name,
1951                in_0,
1952            );
1953        }
1954    }
1955    Ok(PathBuf::from(workload_spec::forge_produced::CONTAINER_DIR).join(format!("{derive_key}.out")))
1956}
1957
1958/// The mirror of [`remote_transform_out`]'s refusals, for the local leg: one
1959/// thing a remote recipe may do that a local one may not (R555-F5).
1960///
1961/// Vault credentials are resolved by yubaba on the node that runs the workload,
1962/// against the cluster secret store and that node's KEK. A local run has no such
1963/// node, so `LocalForgeDriver` refuses `ExecContext::secrets` outright. Refused
1964/// here as well so the message names the *recipe* — a `location = "local"`
1965/// recipe with a `[[secrets]]` block is a mistake in the recipe, and a driver
1966/// error names only the dispatch.
1967fn refuse_secrets_on_a_local_recipe(recipe: &TransformRecipe) -> Result<()> {
1968    if !recipe.secrets.is_empty() {
1969        anyhow::bail!(
1970            "recipe {:?} declares {} [[secrets]] entr{} but is placed locally. Vault \
1971             credentials are resolved by yubaba on the node that runs the workload, \
1972             and a local run has no such node — give the recipe a remote placement \
1973             (location = {{ kind = \"remote_any\", … }}), or drop the secret and have \
1974             the step read its credential from the environment it already runs in \
1975             (W235 §(c) / R555-F5)",
1976            recipe.name,
1977            recipe.secrets.len(),
1978            if recipe.secrets.len() == 1 { "y" } else { "ies" },
1979        );
1980    }
1981    Ok(())
1982}
1983
1984/// Read `path` and assert its BLAKE3 hex matches `expected_hex` (case-insensitive).
1985async fn verify_blake3_path(path: &Path, expected_hex: &str) -> Result<()> {
1986    let bytes = tokio::fs::read(path)
1987        .await
1988        .with_context(|| format!("reading {} for BLAKE3 verify", path.display()))?;
1989    let actual = blake3_hex(&bytes);
1990    if !hashes_equal(&actual, expected_hex) {
1991        anyhow::bail!(
1992            "BLAKE3 mismatch for {}: actual {} != expected {}",
1993            path.display(),
1994            actual,
1995            expected_hex,
1996        );
1997    }
1998    Ok(())
1999}
2000
2001// ── Manifest helpers ──────────────────────────────────────────────────────────
2002
2003async fn load_catalog_manifest(
2004    client: &reqwest::Client,
2005    endpoint: &str,
2006    bucket: &str,
2007    region: &str,
2008    access_key: &str,
2009    secret_key: &str,
2010) -> CatalogManifest {
2011    let url = format!("{endpoint}/{bucket}/{CATALOG_MANIFEST_KEY}");
2012    let Ok(headers) = sign_s3_empty_body("GET", &url, region, access_key, secret_key) else {
2013        return HashMap::new();
2014    };
2015    let Ok(resp) = client.get(&url).headers(headers).send().await else {
2016        return HashMap::new();
2017    };
2018    if !resp.status().is_success() {
2019        return HashMap::new();
2020    }
2021    let Ok(bytes) = resp.bytes().await else {
2022        return HashMap::new();
2023    };
2024    serde_json::from_slice(&bytes).unwrap_or_default()
2025}
2026
2027async fn save_catalog_manifest(
2028    client: &reqwest::Client,
2029    endpoint: &str,
2030    bucket: &str,
2031    manifest: &CatalogManifest,
2032    region: &str,
2033    access_key: &str,
2034    secret_key: &str,
2035) -> Result<()> {
2036    let body = serde_json::to_vec(manifest).context("serializing catalog manifest")?;
2037    let body_sha256 = sha256_hex(&body);
2038    let url = format!("{endpoint}/{bucket}/{CATALOG_MANIFEST_KEY}");
2039    let headers = sign_s3_put_object(
2040        &url,
2041        &body_sha256,
2042        "application/json",
2043        body.len(),
2044        region,
2045        access_key,
2046        secret_key,
2047        // The manifest sidecar is rewritten every run by definition — stamping it
2048        // would be noise, and nothing skips a PUT on it (R546-B10).
2049        None,
2050    )
2051    .context("signing manifest PUT")?;
2052    let resp = client
2053        .put(&url)
2054        .headers(headers)
2055        .body(body)
2056        .send()
2057        .await
2058        .context("PUT catalog manifest")?;
2059    if !resp.status().is_success() {
2060        let status = resp.status();
2061        let body_text = resp.text().await.unwrap_or_default();
2062        anyhow::bail!("PUT {url} → {status}: {}", body_text.trim());
2063    }
2064    Ok(())
2065}
2066
2067// ── S3 helpers ────────────────────────────────────────────────────────────────
2068
2069/// What a HEAD probe found at an object key (R546-B10).
2070///
2071/// The distinction that matters is *not* present-vs-absent but whether the
2072/// present bytes are the ones we are about to publish. `Present { blake3: None }`
2073/// is an object written before we started stamping `x-amz-meta-blake3` — its
2074/// content is unknowable from a HEAD, so callers must treat it as "might be
2075/// stale" rather than "matches".
2076#[derive(Debug, Clone, PartialEq, Eq)]
2077enum RemoteObject {
2078    Absent,
2079    Present { blake3: Option<String> },
2080}
2081
2082impl RemoteObject {
2083    /// True only when the remote object is known to hold exactly `expected`.
2084    /// Unknown provenance (no metadata) is deliberately NOT a match.
2085    fn matches(&self, expected: &str) -> bool {
2086        matches!(self, RemoteObject::Present { blake3: Some(b3) } if hashes_equal(b3, expected))
2087    }
2088
2089    fn exists(&self) -> bool {
2090        matches!(self, RemoteObject::Present { .. })
2091    }
2092}
2093
2094/// HEAD an object key and report existence *plus* the recorded BLAKE3.
2095///
2096/// R546-B10: the previous `object_exists` returned a bare bool, so the publish
2097/// loop could not tell "same bytes already there" from "different bytes already
2098/// there" and skipped the PUT for both — leaving stale content in the bucket
2099/// while the catalog manifest advertised the new hash. We read our own
2100/// `x-amz-meta-blake3` stamp rather than the ETag, because ETag is only an MD5
2101/// of the content for single-part uploads; for multipart it is a digest-of-
2102/// digests and comparing it to a content hash is simply wrong.
2103async fn head_object(
2104    client: &reqwest::Client,
2105    url: &str,
2106    region: &str,
2107    access_key: &str,
2108    secret_key: &str,
2109) -> Result<RemoteObject> {
2110    let headers = sign_s3_empty_body("HEAD", url, region, access_key, secret_key)
2111        .with_context(|| format!("signing HEAD {url}"))?;
2112    let resp = client
2113        .head(url)
2114        .headers(headers)
2115        .send()
2116        .await
2117        .with_context(|| format!("HEAD {url}"))?;
2118    if !resp.status().is_success() {
2119        return Ok(RemoteObject::Absent);
2120    }
2121    let blake3 = resp
2122        .headers()
2123        .get("x-amz-meta-blake3")
2124        .and_then(|v| v.to_str().ok())
2125        .map(str::to_string);
2126    Ok(RemoteObject::Present { blake3 })
2127}
2128
2129// ── Crypto helpers ────────────────────────────────────────────────────────────
2130
2131fn blake3_hex(body: &[u8]) -> String {
2132    hex::encode(blake3::hash(body).as_bytes())
2133}
2134
2135fn sha256_hex(body: &[u8]) -> String {
2136    hex::encode(Sha256::digest(body))
2137}
2138
2139/// Case-insensitive hex comparison (BLAKE3 crate outputs lowercase; stored
2140/// hashes may have been authored in uppercase).
2141fn hashes_equal(a: &str, b: &str) -> bool {
2142    a.eq_ignore_ascii_case(b)
2143}
2144
2145// ── Content-type ──────────────────────────────────────────────────────────────
2146
2147fn content_type_for(path: &Path) -> &'static str {
2148    match path.extension().and_then(|e| e.to_str()).unwrap_or("") {
2149        "bin" => "application/octet-stream",
2150        "json" => "application/json",
2151        "txt" => "text/plain; charset=utf-8",
2152        "wasm" => "application/wasm",
2153        _ => "application/octet-stream",
2154    }
2155}
2156
2157// ── Bucket auto-create ────────────────────────────────────────────────────────
2158
2159/// List R2 buckets under `account_id`; create `bucket_name` only when absent.
2160///
2161/// Takes the management `api_token` already resolved from the service's
2162/// provider (see [`super::cf_creds::CfProvider`]). Mirrors the idempotent pattern in
2163/// `cloudflare_worker.rs::ensure_r2_bucket` — list-first keeps the reconcile
2164/// loop safe to re-run without depending on CF's 4xx error shape on duplicate
2165/// create. R422-T12: lets the first `yah cloud apply --env cloud --service <s>`
2166/// against a static-asset mirror provision its bucket without an out-of-band
2167/// dashboard step.
2168async fn ensure_r2_bucket(api_token: &str, account_id: &str, bucket_name: &str) -> Result<()> {
2169    let cf = CloudflareClient::new(api_token.to_string());
2170    let existing = cf
2171        .list_r2_buckets(account_id)
2172        .await
2173        .context("listing R2 buckets")?;
2174    if existing.iter().any(|b| b.name == bucket_name) {
2175        debug!(bucket_name, "R2 bucket already exists — skipping create");
2176        return Ok(());
2177    }
2178    cf.create_r2_bucket(account_id, bucket_name)
2179        .await
2180        .with_context(|| format!("creating R2 bucket {bucket_name}"))?;
2181    info!(bucket_name, "R2 bucket created");
2182    Ok(())
2183}
2184
2185// ── Workload loading ──────────────────────────────────────────────────────────
2186
2187fn load_workload(workload_dir: &Path) -> Result<StaticAssetWorkload> {
2188    let path = workload_dir.join("workload.toml");
2189    let src =
2190        std::fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;
2191    // R546-B7 (RESOLVED — this comment used to say the envelope was unusable).
2192    // `workload_spec::Workload` is no longer externally tagged for text
2193    // formats: its hand-written Deserialize branches on `is_human_readable`, so
2194    // TOML/JSON get the flat `kind`-tagged shape real files use while postcard
2195    // keeps the variant-index encoding the kamaji UDS needs.
2196    //
2197    // This path still probes `kind` and deserializes `StaticAssetWorkload`
2198    // directly rather than matching on the envelope, because it needs to reject
2199    // a non-static-asset workload with a precise message naming the kind it
2200    // found — an envelope match would only say "expected variant". The bypass
2201    // is now a choice, not a workaround.
2202    #[derive(serde::Deserialize)]
2203    struct KindProbe {
2204        kind: String,
2205    }
2206    let probe: KindProbe =
2207        toml::from_str(&src).with_context(|| format!("parsing {}", path.display()))?;
2208    if probe.kind != "static-asset" {
2209        anyhow::bail!(
2210            "{}: expected kind=\"static-asset\" but found kind={:?}",
2211            path.display(),
2212            probe.kind
2213        );
2214    }
2215    let workload: StaticAssetWorkload =
2216        toml::from_str(&src).with_context(|| format!("parsing {}", path.display()))?;
2217
2218    // R546-B7: enforce the closed-catalog invariant the type's docs promise
2219    // ("every value in [aliases] must be a filename that exists in [[asset]],
2220    // enforced by validate::shape_static_asset"). It was NOT actually being run
2221    // here — `up_bails_when_catalog_alias_orphaned` only passed because the old
2222    // fixture failed to PARSE, so the expected error came from the wrong place.
2223    // With parsing fixed, an orphaned alias would have silently reconciled.
2224    workload_spec::validate::shape_static_asset(&workload)
2225        .map_err(|e| anyhow::anyhow!("{}: {e}", path.display()))?;
2226
2227    Ok(workload)
2228}
2229
2230// ── Tests ─────────────────────────────────────────────────────────────────────
2231
2232#[cfg(test)]
2233mod tests {
2234    use super::*;
2235    use crate::asset_journal::AssetStatusJournal;
2236    use crate::{MirrorConfig, MirrorShape, ServiceComponent, ServiceConfig};
2237    use std::collections::BTreeMap;
2238    use std::path::PathBuf;
2239    use tempfile::tempdir;
2240    use workload_spec::{AssetEntry, BlakeHash};
2241
2242    const HASH_64: &str = "abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890";
2243
2244    /// Minimal test fixture that mirrors the mesofact_static test pattern.
2245    struct Fixture {
2246        _workspace: tempfile::TempDir,
2247        workspace_root: PathBuf,
2248        service: ServiceConfig,
2249        component: ServiceComponent,
2250        mirror: MirrorConfig,
2251        env: String,
2252    }
2253
2254    impl Fixture {
2255        fn new(slot: MirrorProviderSlot) -> Self {
2256            let workspace = tempdir().unwrap();
2257            let workspace_root = workspace.path().to_path_buf();
2258            let workload_dir = workspace_root.join("app/assets/whisper");
2259            std::fs::create_dir_all(&workload_dir).unwrap();
2260
2261            let mut providers = BTreeMap::new();
2262            providers.insert("object_store".to_string(), slot);
2263            let mirror = MirrorConfig {
2264                schema_version: 1,
2265                shape: MirrorShape::Local,
2266                providers,
2267                ingress: Default::default(),
2268                ingress_machines: Vec::new(),
2269                drivers: Default::default(),
2270                asset_aliases: BTreeMap::new(),
2271            };
2272            let service = ServiceConfig {
2273                schema_version: 1,
2274                name: "yah-desktop".to_string(),
2275                domain: "releases.yah.dev".to_string(),
2276                components: vec![],
2277                db: crate::DbCatalog::default(),
2278            };
2279            let component = ServiceComponent {
2280                mount: None,
2281                id: "whisper-models".to_string(),
2282                kind: "static-asset".to_string(),
2283                path: "app/assets/whisper".to_string(),
2284                role: "assets".to_string(),
2285                publishes: None,
2286                wave: 0,
2287                git: None,
2288            };
2289            Self {
2290                _workspace: workspace,
2291                workspace_root,
2292                service,
2293                component,
2294                mirror,
2295                env: "pond".to_string(),
2296            }
2297        }
2298
2299        fn ctx(&self) -> ReconcileCtx<'_> {
2300            ReconcileCtx {
2301                workspace_root: &self.workspace_root,
2302                service: &self.service,
2303                component: &self.component,
2304                mirror: &self.mirror,
2305                env: &self.env,
2306                scope: crate::reconciler::ProviderScope::singleton(),
2307            }
2308        }
2309
2310        fn workload_dir(&self) -> PathBuf {
2311            self.workspace_root.join("app/assets/whisper")
2312        }
2313
2314        fn write_workload(&self, extra: &str) {
2315            // R546-B7: emit the FLAT shape every real on-disk workload.toml uses
2316            // (`kind = "static-asset"` beside `schema_version`), not the
2317            // externally-tagged `[static-asset]` wrapper. The old fixture encoded
2318            // the `workload_spec::Workload` enum's (untagged) representation,
2319            // which NO real file has ever used — so these tests were asserting a
2320            // shape that could not occur in production and masked the fact that
2321            // `yah cloud apply` could not parse any actual catalog.
2322            let toml = format!(
2323                r#"schema_version = "V1"
2324kind = "static-asset"
2325{extra}
2326"#
2327            );
2328            std::fs::write(self.workload_dir().join("workload.toml"), toml).unwrap();
2329        }
2330
2331        fn write_source_file(&self, name: &str, content: &[u8]) -> PathBuf {
2332            let path = self.workload_dir().join(name);
2333            if let Some(parent) = path.parent() {
2334                std::fs::create_dir_all(parent).unwrap();
2335            }
2336            std::fs::write(&path, content).unwrap();
2337            path
2338        }
2339    }
2340
2341    fn minio_slot() -> MirrorProviderSlot {
2342        let mut fields = BTreeMap::new();
2343        fields.insert("api_port".to_string(), toml::Value::Integer(9000));
2344        fields.insert(
2345            "bucket".to_string(),
2346            toml::Value::String("yah-dev".to_string()),
2347        );
2348        MirrorProviderSlot::Inline {
2349            kind: Provider::MinioContainer,
2350            fields,
2351        }
2352    }
2353
2354    /// Default executor for tests that don't exercise transforms — legacy
2355    /// `source = "..."` assets never touch the executor, so any impl works.
2356    fn test_executor() -> Arc<dyn ForgeExecutor> {
2357        Arc::new(LocalForgeDriver::default())
2358    }
2359
2360    // ── Mock executor for W164 materialize-transform tests ────────────────────
2361
2362    use tokio::sync::mpsc::UnboundedSender;
2363    use tokio::sync::Mutex;
2364    use velveteen::ForgeStatus;
2365    use velveteen_exec::executor::{ExecEvent, ExecOutcome, ForgeExecutorError};
2366
2367    /// Executor that writes a caller-supplied byte string to whatever path the
2368    /// recipe sets `YAH_TRANSFORM_OUT` to (via the substituted argv). Returns
2369    /// success unless `fail_with` is set. Tracks invocation count for HIT/MISS
2370    /// assertions.
2371    struct MockExecutor {
2372        out_bytes: Vec<u8>,
2373        invocations: Arc<Mutex<u32>>,
2374        fail_with: Option<String>,
2375    }
2376
2377    impl MockExecutor {
2378        fn new(out_bytes: Vec<u8>) -> (Arc<Self>, Arc<Mutex<u32>>) {
2379            let counter = Arc::new(Mutex::new(0));
2380            let me = Arc::new(Self {
2381                out_bytes,
2382                invocations: counter.clone(),
2383                fail_with: None,
2384            });
2385            (me, counter)
2386        }
2387
2388        fn failing(reason: String) -> Arc<Self> {
2389            Arc::new(Self {
2390                out_bytes: Vec::new(),
2391                invocations: Arc::new(Mutex::new(0)),
2392                fail_with: Some(reason),
2393            })
2394        }
2395    }
2396
2397    #[async_trait]
2398    impl ForgeExecutor for MockExecutor {
2399        async fn execute(
2400            &self,
2401            spec: ForgeSpec,
2402            _ctx: ExecContext,
2403            _sink: Option<UnboundedSender<ExecEvent>>,
2404        ) -> Result<ExecOutcome, ForgeExecutorError> {
2405            *self.invocations.lock().await += 1;
2406            if let Some(reason) = &self.fail_with {
2407                return Ok(ExecOutcome {
2408                    status: ForgeStatus::Done {
2409                        exit_code: 1,
2410                        ended_at: 0,
2411                    },
2412                    stderr_tail: reason.clone(),
2413                });
2414            }
2415            // Find the YAH_TRANSFORM_OUT path in the substituted argv. The
2416            // recipe convention is that {{YAH_TRANSFORM_OUT}} resolves to the
2417            // tmp path we want to write to; it appears as a positional arg.
2418            let ForgeCommand::Subprocess { argv, .. } = &spec.command else {
2419                return Err(ForgeExecutorError::Unsupported(
2420                    "mock only handles Subprocess",
2421                ));
2422            };
2423            // The test recipes follow the W164 convention: argv contains the
2424            // tmp output path verbatim. materialize_transform writes to
2425            // `<cache_dir>/<output_blake3>.tmp` (then renames to .bin on hash
2426            // match), so the output element is the one ending in `.tmp`.
2427            let out_path = argv.iter().find(|a| a.ends_with(".tmp")).ok_or(
2428                ForgeExecutorError::Unsupported("mock recipe must pass a .tmp output path"),
2429            )?;
2430            std::fs::write(out_path, &self.out_bytes).map_err(ForgeExecutorError::Io)?;
2431            Ok(ExecOutcome {
2432                status: ForgeStatus::Done {
2433                    exit_code: 0,
2434                    ended_at: 0,
2435                },
2436                stderr_tail: String::new(),
2437            })
2438        }
2439    }
2440
2441    /// R546-B8: records the substituted argv and, optionally, declines to write
2442    /// the output while still reporting exit 0 — the exact shape of a recipe
2443    /// that chdirs and then writes its artifact to a relative path inside the
2444    /// container.
2445    struct ArgvCapture {
2446        argv: Arc<Mutex<Vec<String>>>,
2447        write_output: bool,
2448    }
2449
2450    impl ArgvCapture {
2451        fn new(write_output: bool) -> (Arc<Self>, Arc<Mutex<Vec<String>>>) {
2452            let argv = Arc::new(Mutex::new(Vec::new()));
2453            let me = Arc::new(Self {
2454                argv: argv.clone(),
2455                write_output,
2456            });
2457            (me, argv)
2458        }
2459    }
2460
2461    #[async_trait]
2462    impl ForgeExecutor for ArgvCapture {
2463        async fn execute(
2464            &self,
2465            spec: ForgeSpec,
2466            _ctx: ExecContext,
2467            _sink: Option<UnboundedSender<ExecEvent>>,
2468        ) -> Result<ExecOutcome, ForgeExecutorError> {
2469            let ForgeCommand::Subprocess { argv, .. } = &spec.command else {
2470                return Err(ForgeExecutorError::Unsupported(
2471                    "capture only handles Subprocess",
2472                ));
2473            };
2474            *self.argv.lock().await = argv.clone();
2475            if self.write_output {
2476                let out = argv.iter().find(|a| a.ends_with(".tmp")).ok_or(
2477                    ForgeExecutorError::Unsupported("recipe must pass a .tmp output path"),
2478                )?;
2479                std::fs::write(out, b"produced").map_err(ForgeExecutorError::Io)?;
2480            }
2481            Ok(ExecOutcome {
2482                status: ForgeStatus::Done {
2483                    exit_code: 0,
2484                    ended_at: 0,
2485                },
2486                stderr_tail: String::new(),
2487            })
2488        }
2489    }
2490
2491    /// Write a `whisper-quantize.toml`-style recipe under
2492    /// `<workspace>/.yah/qed/transforms/<name>.toml`. Returns nothing — the
2493    /// recipe loader resolves the path itself.
2494    fn write_recipe(workspace_root: &Path, name: &str) {
2495        let transforms_dir = workspace_root.join(".yah/qed/transforms");
2496        std::fs::create_dir_all(&transforms_dir).unwrap();
2497        let toml = format!(
2498            r#"
2499name  = "{name}"
2500label = "test recipe"
2501image = "ghcr.io/test/tool:v1@sha256:{HASH_64}"
2502
2503[placement]
2504location = "local"
2505runtime  = "container"
2506
2507[[steps]]
2508name = "transform"
2509argv = ["./tool", "{{{{YAH_TRANSFORM_IN_0}}}}", "{{{{YAH_TRANSFORM_OUT}}}}"]
2510"#
2511        );
2512        std::fs::write(transforms_dir.join(format!("{name}.toml")), toml).unwrap();
2513    }
2514
2515    /// Like [`write_recipe`] but with a caller-chosen container digest, so a
2516    /// test can simulate a digest bump (which must invalidate the W212 action
2517    /// cache and force a re-run).
2518    fn write_recipe_with_digest(workspace_root: &Path, name: &str, digest: &str) {
2519        let transforms_dir = workspace_root.join(".yah/qed/transforms");
2520        std::fs::create_dir_all(&transforms_dir).unwrap();
2521        let toml = format!(
2522            r#"
2523name  = "{name}"
2524label = "test recipe"
2525image = "ghcr.io/test/tool:v1@sha256:{digest}"
2526
2527[placement]
2528location = "local"
2529runtime  = "container"
2530
2531[[steps]]
2532name = "transform"
2533argv = ["./tool", "{{{{YAH_TRANSFORM_IN_0}}}}", "{{{{YAH_TRANSFORM_OUT}}}}"]
2534"#
2535        );
2536        std::fs::write(transforms_dir.join(format!("{name}.toml")), toml).unwrap();
2537    }
2538
2539    /// Write a remotely-placed recipe. `placement_extra` appends lines to the
2540    /// `[placement]` table (e.g. a `platform` the remote leg must refuse) and
2541    /// `steps` is the whole `[[steps]]` block, so a test can pass two of them.
2542    fn write_remote_recipe(
2543        workspace_root: &Path,
2544        name: &str,
2545        placement_extra: &str,
2546        steps: &str,
2547    ) {
2548        let transforms_dir = workspace_root.join(".yah/qed/transforms");
2549        std::fs::create_dir_all(&transforms_dir).unwrap();
2550        let toml = format!(
2551            r#"
2552name  = "{name}"
2553label = "test remote recipe"
2554image = "ghcr.io/test/tool:v1@sha256:{HASH_64}"
2555
2556[placement]
2557location = {{ kind = "remote_any", tier = "infra", mesh_tags = ["arch:x86"] }}
2558runtime  = "container"
2559{placement_extra}
2560
2561{steps}
2562"#
2563        );
2564        std::fs::write(transforms_dir.join(format!("{name}.toml")), toml).unwrap();
2565    }
2566
2567    /// Stands in for `RemoteForgeDriver`: records the context it was handed and
2568    /// performs the retrieval half by writing the "built" bytes to
2569    /// `ctx.produced.dest`, exactly as the real driver does after
2570    /// `fetch_produced_file`.
2571    struct RemoteMock {
2572        out_bytes: Vec<u8>,
2573        seen: Arc<Mutex<Option<(Vec<String>, ExecContext)>>>,
2574    }
2575
2576    impl RemoteMock {
2577        fn new(out_bytes: Vec<u8>) -> (Arc<Self>, Arc<Mutex<Option<(Vec<String>, ExecContext)>>>) {
2578            let seen = Arc::new(Mutex::new(None));
2579            let me = Arc::new(Self {
2580                out_bytes,
2581                seen: seen.clone(),
2582            });
2583            (me, seen)
2584        }
2585    }
2586
2587    #[async_trait]
2588    impl ForgeExecutor for RemoteMock {
2589        async fn execute(
2590            &self,
2591            spec: ForgeSpec,
2592            ctx: ExecContext,
2593            _sink: Option<UnboundedSender<ExecEvent>>,
2594        ) -> Result<ExecOutcome, ForgeExecutorError> {
2595            let ForgeCommand::Subprocess { argv, .. } = &spec.command else {
2596                return Err(ForgeExecutorError::Unsupported("remote mock: Subprocess only"));
2597            };
2598            assert!(
2599                !matches!(spec.where_.location, TaskLocation::Local),
2600                "the remote mock must only ever see a remotely-placed spec",
2601            );
2602            if let Some(produced) = &ctx.produced {
2603                std::fs::write(&produced.dest, &self.out_bytes).map_err(ForgeExecutorError::Io)?;
2604            }
2605            *self.seen.lock().await = Some((argv.clone(), ctx));
2606            Ok(ExecOutcome {
2607                status: ForgeStatus::Done {
2608                    exit_code: 0,
2609                    ended_at: 0,
2610                },
2611                stderr_tail: String::new(),
2612            })
2613        }
2614    }
2615
2616    /// R555-F3, the whole point: a remotely-placed recipe binds its output to
2617    /// the worker's durable produced dir, and the bytes come back to the local
2618    /// derivation cache so the publish leg above is untouched.
2619    #[tokio::test]
2620    async fn a_remote_recipe_binds_out_on_the_worker_and_lands_the_bytes_locally() {
2621        let fx = Fixture::new(minio_slot());
2622        write_remote_recipe(
2623            &fx.workspace_root,
2624            "remote-recipe",
2625            "",
2626            "[[steps]]\nname = \"build\"\nargv = [\"build.sh\", \"{{YAH_TRANSFORM_OUT}}\"]",
2627        );
2628        let out_bytes = b"remotely built".to_vec();
2629        let out_hash = blake3_hex(&out_bytes);
2630        let (mock, seen) = RemoteMock::new(out_bytes.clone());
2631        let executor: Arc<dyn ForgeExecutor> = mock;
2632
2633        let fetch_path = fx.workspace_root.join(".yah/cache/derive/fetch/in.bin");
2634        std::fs::create_dir_all(fetch_path.parent().unwrap()).unwrap();
2635        std::fs::write(&fetch_path, b"anchor").unwrap();
2636
2637        let landed = materialize_transform(
2638            &TransformSpec {
2639                recipe: "remote-recipe".to_string(),
2640                params: BTreeMap::new(),
2641            },
2642            &fetch_path,
2643            &blake3_hex(b"anchor"),
2644            &out_hash,
2645            &fx.workspace_root.join(".yah/cache/derive/transform"),
2646            &fx.workspace_root,
2647            executor.as_ref(),
2648        )
2649        .await
2650        .unwrap();
2651
2652        assert_eq!(std::fs::read(&landed).unwrap(), out_bytes);
2653
2654        let seen = seen.lock().await;
2655        let (argv, ctx) = seen.as_ref().expect("the remote step ran");
2656        let bound_out = argv.last().expect("argv carries the OUT binding");
2657        assert!(
2658            bound_out.starts_with(workload_spec::forge_produced::CONTAINER_DIR),
2659            "OUT must be bound under the worker's durable produced dir, got {bound_out}",
2660        );
2661        let produced = ctx.produced.as_ref().expect("retrieval must be requested");
2662        assert_eq!(produced.remote_path, PathBuf::from(bound_out));
2663        // A host path handed to a remote workdir names a directory that does
2664        // not exist on the node.
2665        assert!(ctx.cwd.is_none(), "no host cwd may travel to a worker");
2666    }
2667
2668    /// The fetched input lives on this box and there is no upload leg, so a
2669    /// remote recipe that reads it would be handed an unresolvable path.
2670    #[tokio::test]
2671    async fn a_remote_recipe_reading_the_fetched_input_is_refused() {
2672        let fx = Fixture::new(minio_slot());
2673        write_remote_recipe(
2674            &fx.workspace_root,
2675            "needs-input",
2676            "",
2677            "[[steps]]\nname = \"build\"\nargv = [\"tool\", \"{{YAH_TRANSFORM_IN_0}}\", \"{{YAH_TRANSFORM_OUT}}\"]",
2678        );
2679        let msg = remote_refusal(&fx, "needs-input").await;
2680        assert!(msg.contains("YAH_TRANSFORM_IN_0"), "got: {msg}");
2681        assert!(msg.contains("no upload leg"), "got: {msg}");
2682    }
2683
2684    /// Steps share a filesystem locally and share nothing remotely.
2685    #[tokio::test]
2686    async fn a_multi_step_remote_recipe_is_refused() {
2687        let fx = Fixture::new(minio_slot());
2688        write_remote_recipe(
2689            &fx.workspace_root,
2690            "two-steps",
2691            "",
2692            "[[steps]]\nname = \"one\"\nargv = [\"a\"]\n\n[[steps]]\nname = \"two\"\nargv = [\"b\", \"{{YAH_TRANSFORM_OUT}}\"]",
2693        );
2694        let msg = remote_refusal(&fx, "two-steps").await;
2695        assert!(msg.contains("one-shot workload"), "got: {msg}");
2696    }
2697
2698    /// R555-F5: the recipe's declared vault credentials have to reach the
2699    /// driver as mounts, or the build runs without the credential it asked for
2700    /// and fails as a missing-auth error deep inside itself.
2701    #[tokio::test]
2702    async fn a_remote_recipe_hands_its_declared_secrets_to_the_driver() {
2703        let fx = Fixture::new(minio_slot());
2704        write_remote_recipe(
2705            &fx.workspace_root,
2706            "needs-r2",
2707            "",
2708            "[[steps]]\nname = \"build\"\nargv = [\"build.sh\", \"{{YAH_TRANSFORM_OUT}}\"]\n\n\
2709             [[secrets]]\ncluster = \"r2/write\"\npath = \"/run/yah/r2.json\"",
2710        );
2711        let out_bytes = b"built with a credential".to_vec();
2712        let (mock, seen) = RemoteMock::new(out_bytes.clone());
2713        let executor: Arc<dyn ForgeExecutor> = mock;
2714
2715        let fetch_path = fx.workspace_root.join(".yah/cache/derive/fetch/in.bin");
2716        std::fs::create_dir_all(fetch_path.parent().unwrap()).unwrap();
2717        std::fs::write(&fetch_path, b"anchor").unwrap();
2718
2719        materialize_transform(
2720            &TransformSpec {
2721                recipe: "needs-r2".to_string(),
2722                params: BTreeMap::new(),
2723            },
2724            &fetch_path,
2725            &blake3_hex(b"anchor"),
2726            &blake3_hex(&out_bytes),
2727            &fx.workspace_root.join(".yah/cache/derive/transform"),
2728            &fx.workspace_root,
2729            executor.as_ref(),
2730        )
2731        .await
2732        .unwrap();
2733
2734        let seen = seen.lock().await;
2735        let (_, ctx) = seen.as_ref().expect("the remote step ran");
2736        assert_eq!(
2737            ctx.secrets,
2738            vec![workload_spec::SecretMount {
2739                source: workload_spec::SecretRef::Cluster {
2740                    name: "r2/write".into()
2741                },
2742                target: workload_spec::SecretTarget::File {
2743                    path: PathBuf::from("/run/yah/r2.json"),
2744                    // Owner-only is the default a recipe gets without asking.
2745                    mode: 0o400,
2746                },
2747            }]
2748        );
2749    }
2750
2751    /// The local mirror: yubaba resolves credentials on the node that runs the
2752    /// workload, and a local run has no node. Refused by name so the operator
2753    /// is pointed at the recipe rather than at a driver error.
2754    #[tokio::test]
2755    async fn a_local_recipe_declaring_secrets_is_refused_before_dispatch() {
2756        let fx = Fixture::new(minio_slot());
2757        let transforms_dir = fx.workspace_root.join(".yah/qed/transforms");
2758        std::fs::create_dir_all(&transforms_dir).unwrap();
2759        std::fs::write(
2760            transforms_dir.join("local-with-secret.toml"),
2761            format!(
2762                r#"
2763name  = "local-with-secret"
2764label = "test local recipe"
2765image = "ghcr.io/test/tool:v1@sha256:{HASH_64}"
2766
2767[placement]
2768location = "local"
2769runtime  = "container"
2770
2771[[steps]]
2772name = "build"
2773argv = ["build.sh", "{{{{YAH_TRANSFORM_OUT}}}}"]
2774
2775[[secrets]]
2776cluster = "r2/write"
2777path    = "/run/yah/r2.json"
2778"#
2779            ),
2780        )
2781        .unwrap();
2782        let msg = remote_refusal(&fx, "local-with-secret").await;
2783        assert!(msg.contains("placed locally"), "got: {msg}");
2784        assert!(msg.contains("local-with-secret"), "got: {msg}");
2785    }
2786
2787    /// `platform` is host-emulation; remote picks arch by scheduling. Silently
2788    /// dropping it is how R546 got a wrong-arch artifact in the first place.
2789    #[tokio::test]
2790    async fn a_remote_recipe_declaring_a_platform_is_refused_and_named_mesh_tags() {
2791        let fx = Fixture::new(minio_slot());
2792        write_remote_recipe(
2793            &fx.workspace_root,
2794            "emulated",
2795            "platform = \"linux/amd64\"",
2796            "[[steps]]\nname = \"build\"\nargv = [\"build.sh\", \"{{YAH_TRANSFORM_OUT}}\"]",
2797        );
2798        let msg = remote_refusal(&fx, "emulated").await;
2799        assert!(msg.contains("mesh_tags"), "got: {msg}");
2800    }
2801
2802    /// Run `recipe` through `materialize_transform` with an executor that
2803    /// panics if reached, and return the refusal message. Every caller here
2804    /// asserts the recipe is rejected *before* anything is dispatched.
2805    async fn remote_refusal(fx: &Fixture, recipe: &str) -> String {
2806        struct NeverRuns;
2807        #[async_trait]
2808        impl ForgeExecutor for NeverRuns {
2809            async fn execute(
2810                &self,
2811                _spec: ForgeSpec,
2812                _ctx: ExecContext,
2813                _sink: Option<UnboundedSender<ExecEvent>>,
2814            ) -> Result<ExecOutcome, ForgeExecutorError> {
2815                panic!("the recipe must be refused before dispatch");
2816            }
2817        }
2818        let fetch_path = fx.workspace_root.join(".yah/cache/derive/fetch/in.bin");
2819        std::fs::create_dir_all(fetch_path.parent().unwrap()).unwrap();
2820        std::fs::write(&fetch_path, b"anchor").unwrap();
2821        let executor: Arc<dyn ForgeExecutor> = Arc::new(NeverRuns);
2822        let err = materialize_transform(
2823            &TransformSpec {
2824                recipe: recipe.to_string(),
2825                params: BTreeMap::new(),
2826            },
2827            &fetch_path,
2828            &blake3_hex(b"anchor"),
2829            &blake3_hex(b"whatever"),
2830            &fx.workspace_root.join(".yah/cache/derive/transform"),
2831            &fx.workspace_root,
2832            executor.as_ref(),
2833        )
2834        .await
2835        .expect_err("remote recipe must be refused");
2836        format!("{err:#}")
2837    }
2838
2839    // ── Slot validation ───────────────────────────────────────────────────────
2840
2841    #[tokio::test]
2842    async fn up_bails_when_object_store_slot_missing() {
2843        let mut fx = Fixture::new(minio_slot());
2844        fx.mirror.providers.clear();
2845        fx.write_workload("");
2846        let err = StaticAssetReconciler::new().up(fx.ctx()).await.unwrap_err();
2847        let msg = format!("{err:#}");
2848        assert!(msg.contains("providers.object_store"), "got: {msg}");
2849    }
2850
2851    #[tokio::test]
2852    async fn up_bails_on_unsupported_inline_slot_kind() {
2853        let slot = MirrorProviderSlot::Inline {
2854            kind: Provider::LocalStatic,
2855            fields: BTreeMap::new(),
2856        };
2857        let fx = Fixture::new(slot);
2858        fx.write_workload("");
2859        let err = StaticAssetReconciler::new().up(fx.ctx()).await.unwrap_err();
2860        let msg = format!("{err:#}");
2861        assert!(msg.contains("minio-container"), "got: {msg}");
2862    }
2863
2864    #[tokio::test]
2865    async fn up_bails_on_unsupported_reference_provider() {
2866        let slot = MirrorProviderSlot::Reference {
2867            provider_id: "hetzner".to_string(),
2868            fields: BTreeMap::new(),
2869        };
2870        let fx = Fixture::new(slot);
2871        fx.write_workload("");
2872        // Declare a real non-cloudflare provider so dispatch resolves it and
2873        // reaches the kind check (the new dispatch keys on kind, not name).
2874        let providers_dir = fx.workspace_root.join(".yah/infra/providers");
2875        std::fs::create_dir_all(&providers_dir).unwrap();
2876        std::fs::write(
2877            providers_dir.join("hetzner.toml"),
2878            "schema_version = 1\nid = \"hetzner\"\nkind = \"hetzner\"\naccount_id = \"x\"\n",
2879        )
2880        .unwrap();
2881        let err = StaticAssetReconciler::new().up(fx.ctx()).await.unwrap_err();
2882        let msg = format!("{err:#}");
2883        assert!(msg.contains("cloudflare-kind"), "got: {msg}");
2884    }
2885
2886    #[tokio::test]
2887    async fn up_bails_when_workload_toml_missing() {
2888        let fx = Fixture::new(minio_slot());
2889        // No workload.toml written.
2890        let err = StaticAssetReconciler::new().up(fx.ctx()).await.unwrap_err();
2891        let msg = format!("{err:#}");
2892        assert!(msg.contains("workload.toml"), "got: {msg}");
2893    }
2894
2895    #[tokio::test]
2896    async fn up_bails_when_catalog_alias_orphaned() {
2897        // Alias points at a filename not in the catalog — shape_static_asset rejects it.
2898        let fx = Fixture::new(minio_slot());
2899        fx.write_workload(
2900            r#"[aliases]
2901"default" = "nonexistent/file.bin"
2902"#,
2903        );
2904        let err = StaticAssetReconciler::new().up(fx.ctx()).await.unwrap_err();
2905        let msg = format!("{err:#}");
2906        assert!(
2907            msg.contains("closed-catalog") || msg.contains("aliases"),
2908            "got: {msg}"
2909        );
2910    }
2911
2912    // ── BLAKE3 verification ───────────────────────────────────────────────────
2913
2914    #[test]
2915    fn blake3_mismatch_detected() {
2916        let body = b"hello world";
2917        let actual = blake3_hex(body);
2918        // Fabricate a hash that's wrong.
2919        let wrong = HASH_64;
2920        assert!(!hashes_equal(&actual, wrong));
2921    }
2922
2923    #[test]
2924    fn blake3_match_is_case_insensitive() {
2925        let body = b"hello world";
2926        let lower = blake3_hex(body);
2927        let upper = lower.to_uppercase();
2928        assert!(hashes_equal(&lower, &upper));
2929    }
2930
2931    #[test]
2932    fn sha256_hex_is_64_chars() {
2933        let h = sha256_hex(b"test");
2934        assert_eq!(h.len(), 64);
2935    }
2936
2937    /// Core scenario: source file whose BLAKE3 matches the declared hash should
2938    /// be identified as upload-ready (no mismatch). Tests the in-memory path
2939    /// without hitting any S3 endpoint.
2940    #[test]
2941    fn matching_blake3_produces_no_mismatch_entry() {
2942        let body = b"real model weights here";
2943        let real_hash = blake3_hex(body);
2944        // Simulate what the reconciler checks.
2945        let stored = BlakeHash(real_hash.clone());
2946        assert!(hashes_equal(&real_hash, &stored.0));
2947    }
2948
2949    #[tokio::test]
2950    async fn blake3_mismatch_on_source_file_is_caught() {
2951        let fx = Fixture::new(minio_slot());
2952        let body = b"real model content";
2953        let real_hash = blake3_hex(body);
2954        // Write a workload that declares the correct hash but we'll give it
2955        // a different file content to verify the check fires before any network.
2956        let wrong_content = b"tampered content";
2957        fx.write_source_file("model.bin", wrong_content);
2958        let wrong_hash_for_real = blake3_hex(wrong_content);
2959        // Sanity: the wrong content should produce a different hash.
2960        assert_ne!(real_hash, wrong_hash_for_real);
2961
2962        let workload = StaticAssetWorkload {
2963            schema_version: workload_spec::SchemaVersion::V1,
2964            assets: vec![AssetEntry {
2965                filename: "model.bin".to_string(),
2966                source: Some("model.bin".into()),
2967                derive: None,
2968                blake3: BlakeHash(real_hash),
2969            }],
2970            aliases: BTreeMap::new(),
2971        };
2972
2973        // Drive the sync with a non-existent MinIO so it would fail on network
2974        // if it ever got past the BLAKE3 check.
2975        let client = reqwest::Client::new();
2976        let journal = AssetStatusJournal::new(fx.workspace_root.join(".yah/cloud/status.jsonl"));
2977        let report = sync_assets(
2978            &workload,
2979            &fx.workspace_root,
2980            &fx.workload_dir(),
2981            &client,
2982            "http://127.0.0.1:19999", // unreachable
2983            "test-bucket",
2984            MINIO_REGION,
2985            "user",
2986            "pass",
2987            test_executor(),
2988            "test-service",
2989            &journal,
2990        )
2991        .await
2992        .unwrap();
2993
2994        assert_eq!(report.hash_mismatch, vec!["model.bin"]);
2995        assert!(report.uploaded.is_empty());
2996    }
2997
2998    #[tokio::test]
2999    async fn correct_blake3_proceeds_to_s3_head() {
3000        let fx = Fixture::new(minio_slot());
3001        let body = b"correct content";
3002        let hash = blake3_hex(body);
3003        fx.write_source_file("model.bin", body);
3004
3005        let workload = StaticAssetWorkload {
3006            schema_version: workload_spec::SchemaVersion::V1,
3007            assets: vec![AssetEntry {
3008                filename: "model.bin".to_string(),
3009                source: Some("model.bin".into()),
3010                derive: None,
3011                blake3: BlakeHash(hash),
3012            }],
3013            aliases: BTreeMap::new(),
3014        };
3015
3016        // BLAKE3 passes → reconciler proceeds to HEAD the S3 endpoint.
3017        // The unreachable endpoint causes a network error (not a BLAKE3 error).
3018        let client = reqwest::Client::new();
3019        let journal = AssetStatusJournal::new(fx.workspace_root.join(".yah/cloud/status.jsonl"));
3020        let err = sync_assets(
3021            &workload,
3022            &fx.workspace_root,
3023            &fx.workload_dir(),
3024            &client,
3025            "http://127.0.0.1:19999", // unreachable
3026            "test-bucket",
3027            MINIO_REGION,
3028            "user",
3029            "pass",
3030            test_executor(),
3031            "test-service",
3032            &journal,
3033        )
3034        .await
3035        .unwrap_err();
3036
3037        // Error must be about network, not BLAKE3.
3038        let msg = format!("{err:#}");
3039        assert!(
3040            !msg.contains("BLAKE3") && !msg.contains("mismatch"),
3041            "should fail at network, not BLAKE3; got: {msg}"
3042        );
3043    }
3044
3045    // ── Catalog manifest ──────────────────────────────────────────────────────
3046
3047    #[test]
3048    fn catalog_manifest_roundtrip() {
3049        let mut m = CatalogManifest::new();
3050        m.insert("whisper/model-v1.bin".to_string(), HASH_64.to_string());
3051        let json = serde_json::to_vec(&m).unwrap();
3052        let m2: CatalogManifest = serde_json::from_slice(&json).unwrap();
3053        assert_eq!(m, m2);
3054    }
3055
3056    // ── R546-B10: publish-skip must be content-aware, not existence-aware ─────
3057
3058    /// The defect this encodes: an object that EXISTS is not evidence that the
3059    /// object holds the bytes we are about to publish. Skipping the PUT on mere
3060    /// existence left stale bytes in the bucket while the catalog manifest
3061    /// advertised the new hash — the published catalog described bytes that were
3062    /// never uploaded (real incident: rusty-v8 aarch64, bucket held d322b4a1
3063    /// while the manifest claimed ebdd842d).
3064    #[test]
3065    fn remote_object_matches_only_on_identical_content() {
3066        let expected = "a".repeat(64);
3067        let other = "b".repeat(64);
3068
3069        // Same bytes → genuine no-op, safe to skip the PUT.
3070        assert!(RemoteObject::Present {
3071            blake3: Some(expected.clone())
3072        }
3073        .matches(&expected));
3074
3075        // Different bytes → MUST NOT be treated as synced. This is the bug.
3076        assert!(!RemoteObject::Present {
3077            blake3: Some(other)
3078        }
3079        .matches(&expected));
3080
3081        // Absent → nothing to match.
3082        assert!(!RemoteObject::Absent.matches(&expected));
3083        assert!(!RemoteObject::Absent.exists());
3084    }
3085
3086    /// A legacy object written before we stamped `x-amz-meta-blake3` has
3087    /// unknowable content. It must NOT count as a match — otherwise every
3088    /// pre-existing object keeps its old bytes forever. It re-PUTs once, which
3089    /// installs the stamp and restores the cheap skip on subsequent runs.
3090    #[test]
3091    fn unstamped_remote_object_is_not_a_match_but_does_exist() {
3092        let expected = "c".repeat(64);
3093        let legacy = RemoteObject::Present { blake3: None };
3094        assert!(
3095            !legacy.matches(&expected),
3096            "unstamped object must not be trusted as current"
3097        );
3098        assert!(
3099            legacy.exists(),
3100            "it does exist — caller re-publishes rather than treating as absent"
3101        );
3102    }
3103
3104    /// Hashes may have been authored in either case; comparison goes through
3105    /// `hashes_equal`, so an uppercase stamp must still match.
3106    #[test]
3107    fn remote_object_match_is_case_insensitive() {
3108        let lower = "abcdef".repeat(10) + "abcd";
3109        let upper = lower.to_uppercase();
3110        assert_eq!(lower.len(), 64);
3111        assert!(RemoteObject::Present {
3112            blake3: Some(upper)
3113        }
3114        .matches(&lower));
3115    }
3116
3117    // ── Prune candidate detection ─────────────────────────────────────────────
3118
3119    #[tokio::test]
3120    async fn prune_candidate_from_prior_manifest() {
3121        let fx = Fixture::new(minio_slot());
3122        let body = b"current content";
3123        let hash = blake3_hex(body);
3124        fx.write_source_file("current.bin", body);
3125
3126        // Workload only has "current.bin"; prior manifest also had "old.bin".
3127        let workload = StaticAssetWorkload {
3128            schema_version: workload_spec::SchemaVersion::V1,
3129            assets: vec![AssetEntry {
3130                filename: "current.bin".to_string(),
3131                source: Some("current.bin".into()),
3132                derive: None,
3133                blake3: BlakeHash(hash),
3134            }],
3135            aliases: BTreeMap::new(),
3136        };
3137
3138        // We can't inject a prior manifest without a real/mock server, but we
3139        // can verify the prune detection logic directly.
3140        let current_filenames: std::collections::HashSet<&str> = workload
3141            .assets
3142            .iter()
3143            .map(|a| a.filename.as_str())
3144            .collect();
3145        let prior: CatalogManifest = [("old.bin".to_string(), HASH_64.to_string())]
3146            .into_iter()
3147            .collect();
3148
3149        let prune: Vec<_> = prior
3150            .keys()
3151            .filter(|k| !current_filenames.contains(k.as_str()))
3152            .cloned()
3153            .collect();
3154        assert_eq!(prune, vec!["old.bin"]);
3155    }
3156
3157    // ── W164 materialize step (R438-T15) ──────────────────────────────────────
3158
3159    use workload_spec::{AssetDerive, FetchSource, License, TransformSpec};
3160
3161    /// Helper: build an `AssetEntry` whose `source` is already on disk —
3162    /// the legacy arm of `materialize_asset` should return the disk path
3163    /// verbatim without ever consulting `derive`/cache/executor.
3164    fn legacy_entry(filename: &str, source_rel: &str, hash: &str) -> AssetEntry {
3165        AssetEntry {
3166            filename: filename.to_string(),
3167            source: Some(source_rel.into()),
3168            derive: None,
3169            blake3: BlakeHash(hash.to_string()),
3170        }
3171    }
3172
3173    #[tokio::test]
3174    async fn materialize_legacy_source_returns_workload_dir_path() {
3175        let fx = Fixture::new(minio_slot());
3176        let body = b"on-disk bytes";
3177        fx.write_source_file("model.bin", body);
3178        let entry = legacy_entry("model.bin", "model.bin", &blake3_hex(body));
3179
3180        let materialized = materialize_asset(
3181            &entry,
3182            &fx.workspace_root,
3183            &fx.workload_dir(),
3184            test_executor().as_ref(),
3185        )
3186        .await
3187        .expect("legacy materialize must succeed");
3188
3189        assert_eq!(materialized.path, fx.workload_dir().join("model.bin"));
3190        assert!(
3191            materialized.discovered_fetch_hash.is_none(),
3192            "legacy source mode has no fetch step → never bootstrap-discovers"
3193        );
3194    }
3195
3196    #[tokio::test]
3197    async fn materialize_fetch_cache_miss_then_hit() {
3198        let fx = Fixture::new(minio_slot());
3199        let body = b"upstream bytes";
3200        let hash = blake3_hex(body);
3201
3202        // Server returns the body once; second call would 500 if hit.
3203        use axum::routing::get;
3204        let counter = Arc::new(std::sync::atomic::AtomicU32::new(0));
3205        let counter_c = counter.clone();
3206        let body_c = body.to_vec();
3207        let app = axum::Router::new().route(
3208            "/blob.bin",
3209            get(move || {
3210                let counter = counter_c.clone();
3211                let body = body_c.clone();
3212                async move {
3213                    counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
3214                    body
3215                }
3216            }),
3217        );
3218        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3219        let addr = listener.local_addr().unwrap();
3220        tokio::spawn(async move {
3221            axum::serve(listener, app).await.unwrap();
3222        });
3223
3224        let fetch = FetchSource {
3225            url: format!("http://{addr}/blob.bin"),
3226            blake3: BlakeHash(hash.clone()),
3227            license: License::Mit,
3228        };
3229        let cache_dir = fx.workspace_root.join(".yah/cache/derive/fetch");
3230
3231        // MISS — fetch + write to cache.
3232        let (p1, h1) = materialize_fetch(&fetch, &cache_dir).await.unwrap();
3233        assert_eq!(counter.load(std::sync::atomic::Ordering::SeqCst), 1);
3234        assert!(p1.exists(), "cache file must exist after MISS");
3235        assert_eq!(h1, hash, "strict mode returns the pinned hash");
3236
3237        // HIT — no second HTTP call.
3238        let (p2, h2) = materialize_fetch(&fetch, &cache_dir).await.unwrap();
3239        assert_eq!(p1, p2);
3240        assert_eq!(h1, h2, "HIT returns the same hash");
3241        assert_eq!(
3242            counter.load(std::sync::atomic::Ordering::SeqCst),
3243            1,
3244            "cache HIT must not re-fetch"
3245        );
3246    }
3247
3248    #[tokio::test]
3249    async fn materialize_fetch_blake3_mismatch_is_hard_error() {
3250        let fx = Fixture::new(minio_slot());
3251        let actual_body = b"real bytes";
3252        let actual_hash = blake3_hex(actual_body);
3253        let pinned_hash = HASH_64; // deliberately wrong
3254        assert_ne!(actual_hash, pinned_hash);
3255
3256        use axum::routing::get;
3257        let body_c = actual_body.to_vec();
3258        let app = axum::Router::new().route(
3259            "/blob.bin",
3260            get(move || {
3261                let body = body_c.clone();
3262                async move { body }
3263            }),
3264        );
3265        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3266        let addr = listener.local_addr().unwrap();
3267        tokio::spawn(async move {
3268            axum::serve(listener, app).await.unwrap();
3269        });
3270
3271        let fetch = FetchSource {
3272            url: format!("http://{addr}/blob.bin"),
3273            blake3: BlakeHash(pinned_hash.to_string()),
3274            license: License::Mit,
3275        };
3276        let err = materialize_fetch(&fetch, &fx.workspace_root.join(".yah/cache/derive/fetch"))
3277            .await
3278            .expect_err("BLAKE3 mismatch must surface as hard error");
3279        let msg = format!("{err:#}");
3280        assert!(
3281            msg.contains("BLAKE3") || msg.contains(&actual_hash),
3282            "got: {msg}"
3283        );
3284        assert!(msg.contains(pinned_hash), "diff must mention pin: {msg}");
3285    }
3286
3287    #[tokio::test]
3288    async fn materialize_fetch_retries_on_server_error() {
3289        // First request returns 500 (transient); second returns 200 with the body.
3290        // Verifies exponential-backoff retry (W164 OQ#4, R438-F11).
3291        use axum::http::StatusCode;
3292        use axum::routing::get;
3293
3294        let fx = Fixture::new(minio_slot());
3295        let body: Vec<u8> = b"retry-me bytes".to_vec();
3296        let hash = blake3_hex(&body);
3297
3298        let counter = Arc::new(std::sync::atomic::AtomicU32::new(0));
3299        let counter_c = counter.clone();
3300        let body_c = body.clone();
3301        let app = axum::Router::new().route(
3302            "/blob.bin",
3303            get(move || {
3304                let n = counter_c.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
3305                let body = body_c.clone();
3306                async move {
3307                    if n == 0 {
3308                        (StatusCode::INTERNAL_SERVER_ERROR, vec![])
3309                    } else {
3310                        (StatusCode::OK, body)
3311                    }
3312                }
3313            }),
3314        );
3315        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3316        let addr = listener.local_addr().unwrap();
3317        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
3318
3319        let fetch = FetchSource {
3320            url: format!("http://{addr}/blob.bin"),
3321            blake3: BlakeHash(hash.clone()),
3322            license: License::Mit,
3323        };
3324        let cache_dir = fx.workspace_root.join(".yah/cache/derive/fetch");
3325        let (path, _hash) = materialize_fetch(&fetch, &cache_dir).await.unwrap();
3326        assert!(
3327            path.exists(),
3328            "cache file must exist after successful retry"
3329        );
3330        assert_eq!(
3331            counter.load(std::sync::atomic::Ordering::SeqCst),
3332            2,
3333            "exactly two attempts: one 500 + one 200"
3334        );
3335        assert_eq!(tokio::fs::read(&path).await.unwrap(), body);
3336    }
3337
3338    #[tokio::test]
3339    async fn materialize_fetch_resumes_via_range_header() {
3340        // Pre-populate the partial file with the first half of the blob. The
3341        // server should receive a Range header and return 206 + the second half.
3342        // Verifies Range-resume logic (W164 OQ#4, R438-F11).
3343        use axum::body::Body;
3344        use axum::http::{HeaderMap, StatusCode};
3345        use axum::routing::get;
3346
3347        let fx = Fixture::new(minio_slot());
3348        let body: Vec<u8> = (0u8..100u8).collect();
3349        let half = body.len() / 2;
3350        let hash = blake3_hex(&body);
3351
3352        // Pre-write first half to the .partial file.
3353        let cache_dir = fx.workspace_root.join(".yah/cache/derive/fetch");
3354        tokio::fs::create_dir_all(&cache_dir).await.unwrap();
3355        let partial_path = cache_dir.join(format!("{hash}.partial"));
3356        tokio::fs::write(&partial_path, &body[..half])
3357            .await
3358            .unwrap();
3359
3360        let body_c = body.clone();
3361        let received_range: Arc<std::sync::Mutex<Option<String>>> =
3362            Arc::new(std::sync::Mutex::new(None));
3363        let received_range_c = received_range.clone();
3364        let app = axum::Router::new().route(
3365            "/blob.bin",
3366            get(move |headers: HeaderMap| {
3367                let body = body_c.clone();
3368                let received = received_range_c.clone();
3369                async move {
3370                    let range_hdr = headers
3371                        .get("range")
3372                        .and_then(|v| v.to_str().ok())
3373                        .map(str::to_string);
3374                    *received.lock().unwrap() = range_hdr.clone();
3375
3376                    let Some(range) = range_hdr else {
3377                        return axum::response::Response::builder()
3378                            .status(StatusCode::BAD_REQUEST)
3379                            .body(Body::empty())
3380                            .unwrap();
3381                    };
3382                    let offset: usize = range
3383                        .strip_prefix("bytes=")
3384                        .and_then(|s| s.strip_suffix('-'))
3385                        .and_then(|s| s.parse().ok())
3386                        .unwrap_or(0);
3387                    let total = body.len();
3388                    axum::response::Response::builder()
3389                        .status(StatusCode::PARTIAL_CONTENT)
3390                        .header(
3391                            "Content-Range",
3392                            format!("bytes {offset}-{}/{total}", total - 1),
3393                        )
3394                        .body(Body::from(body[offset..].to_vec()))
3395                        .unwrap()
3396                }
3397            }),
3398        );
3399        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3400        let addr = listener.local_addr().unwrap();
3401        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
3402
3403        let fetch = FetchSource {
3404            url: format!("http://{addr}/blob.bin"),
3405            blake3: BlakeHash(hash.clone()),
3406            license: License::Mit,
3407        };
3408        let (path, _hash) = materialize_fetch(&fetch, &cache_dir).await.unwrap();
3409
3410        // Range header must carry the pre-existing partial size.
3411        let range = received_range.lock().unwrap().clone().unwrap();
3412        assert_eq!(
3413            range,
3414            format!("bytes={half}-"),
3415            "Range header must resume from partial offset"
3416        );
3417        // Final cache file must contain the complete body.
3418        assert_eq!(
3419            tokio::fs::read(&path).await.unwrap(),
3420            body,
3421            "cache file must contain the full blob after Range resume"
3422        );
3423    }
3424
3425    #[tokio::test]
3426    async fn materialize_transform_cache_miss_then_hit() {
3427        let fx = Fixture::new(minio_slot());
3428        write_recipe(&fx.workspace_root, "noop-recipe");
3429        let out_bytes = b"transformed output".to_vec();
3430        let out_hash = blake3_hex(&out_bytes);
3431        let (mock, invocations) = MockExecutor::new(out_bytes.clone());
3432        let executor: Arc<dyn ForgeExecutor> = mock;
3433
3434        // Pre-seed a fetch cache entry the transform reads from.
3435        let fetch_path = fx.workspace_root.join(".yah/cache/derive/fetch/in.bin");
3436        std::fs::create_dir_all(fetch_path.parent().unwrap()).unwrap();
3437        std::fs::write(&fetch_path, b"fetch bytes").unwrap();
3438
3439        let transform = TransformSpec {
3440            recipe: "noop-recipe".to_string(),
3441            params: BTreeMap::new(),
3442        };
3443        let cache_dir = fx.workspace_root.join(".yah/cache/derive/transform");
3444
3445        // MISS — runs the recipe.
3446        let p1 = materialize_transform(
3447            &transform,
3448            &fetch_path,
3449            &blake3_hex(b"fetch bytes"),
3450            &out_hash,
3451            &cache_dir,
3452            &fx.workspace_root,
3453            executor.as_ref(),
3454        )
3455        .await
3456        .unwrap();
3457        assert!(p1.exists());
3458        assert_eq!(*invocations.lock().await, 1);
3459
3460        // HIT — recipe NOT re-run.
3461        let p2 = materialize_transform(
3462            &transform,
3463            &fetch_path,
3464            &blake3_hex(b"fetch bytes"),
3465            &out_hash,
3466            &cache_dir,
3467            &fx.workspace_root,
3468            executor.as_ref(),
3469        )
3470        .await
3471        .unwrap();
3472        assert_eq!(p1, p2);
3473        assert_eq!(*invocations.lock().await, 1, "cache HIT must not re-run");
3474    }
3475
3476    /// R546-T3 qed→W164 bridge: seeding the derivation cache from a pre-built
3477    /// artifact makes the NEXT `materialize_transform` a HIT that returns the
3478    /// seeded bytes without running the recipe. This is the whole point —
3479    /// offload the arch-locked, expensive build to a fleet worker (rusty-v8-musl), retrieve
3480    /// its tar (R590-F6), seed the cache, and let `yah cloud apply` publish the
3481    /// pre-built bytes instead of re-building under emulation.
3482    #[tokio::test]
3483    async fn seed_transform_derivation_makes_next_transform_a_hit() {
3484        let fx = Fixture::new(minio_slot());
3485        write_recipe(&fx.workspace_root, "noop-recipe");
3486
3487        let transform = TransformSpec {
3488            recipe: "noop-recipe".to_string(),
3489            params: BTreeMap::new(),
3490        };
3491        let fetched_hash = blake3_hex(b"fetch bytes");
3492
3493        // A pre-built artifact standing in for the F6-retrieved rusty_v8 tar.
3494        let prebuilt = fx.workspace_root.join("prebuilt.tar.gz");
3495        let prebuilt_bytes = b"prebuilt rusty_v8 tarball".to_vec();
3496        std::fs::write(&prebuilt, &prebuilt_bytes).unwrap();
3497
3498        let seeded =
3499            seed_transform_derivation(&fx.workspace_root, &transform, &fetched_hash, &prebuilt)
3500                .await
3501                .unwrap();
3502        assert_eq!(seeded.output_blake3, blake3_hex(&prebuilt_bytes));
3503        assert!(seeded.cas_path.exists(), "CAS entry must be written");
3504
3505        // A materialize_transform with the SAME inputs must HIT the seeded cache:
3506        // the executor is never invoked and the returned bytes are the seeded
3507        // artifact (NOT what the recipe would have produced).
3508        let fetch_path = fx.workspace_root.join(".yah/cache/derive/fetch/in.bin");
3509        std::fs::create_dir_all(fetch_path.parent().unwrap()).unwrap();
3510        std::fs::write(&fetch_path, b"fetch bytes").unwrap();
3511        let cache_dir = fx.workspace_root.join(".yah/cache/derive/transform");
3512        let (mock, invocations) = MockExecutor::new(b"RECIPE OUTPUT (must not appear)".to_vec());
3513
3514        let out = materialize_transform(
3515            &transform,
3516            &fetch_path,
3517            &fetched_hash,
3518            &seeded.output_blake3,
3519            &cache_dir,
3520            &fx.workspace_root,
3521            mock.as_ref(),
3522        )
3523        .await
3524        .unwrap();
3525
3526        assert_eq!(
3527            *invocations.lock().await,
3528            0,
3529            "seeded derivation cache must make the transform a HIT (no recipe run)"
3530        );
3531        assert_eq!(
3532            std::fs::read(&out).unwrap(),
3533            prebuilt_bytes,
3534            "HIT must return the seeded pre-built bytes",
3535        );
3536    }
3537
3538    /// W212/R518: the derivation key is hermetic — every declared input
3539    /// dimension flips it, and identical inputs reproduce it. This is the
3540    /// correctness invariant that makes the silent-stale-cache bug impossible:
3541    /// a missing dimension would let two distinct inputs collide on one key.
3542    #[test]
3543    fn derivation_key_is_hermetic_over_every_input_dimension() {
3544        let input = "a".repeat(64);
3545        let recipe = "b".repeat(64);
3546        let mut params = BTreeMap::new();
3547        params.insert("quant".to_string(), "q5_1".to_string());
3548
3549        let base = derivation_key(&input, &recipe, &params);
3550
3551        // Fetched-input content (the model/version anchor) flips it.
3552        assert_ne!(base, derivation_key(&"c".repeat(64), &recipe, &params));
3553        // Recipe-file bytes (steps / pinned container digest / placement) flip it.
3554        assert_ne!(base, derivation_key(&input, &"d".repeat(64), &params));
3555        // A changed param value flips it.
3556        let mut p2 = params.clone();
3557        p2.insert("quant".to_string(), "q4_0".to_string());
3558        assert_ne!(base, derivation_key(&input, &recipe, &p2));
3559        // An added param flips it.
3560        let mut p3 = params.clone();
3561        p3.insert("extra".to_string(), "x".to_string());
3562        assert_ne!(base, derivation_key(&input, &recipe, &p3));
3563        // Identical inputs reproduce the key (deterministic, order-stable).
3564        assert_eq!(base, derivation_key(&input, &recipe, &params));
3565    }
3566
3567    /// W212/R518: the action cache is keyed on INPUTS, so a recipe change (here
3568    /// a container-digest bump) forces a re-run even on a warm cache. This is
3569    /// the regression guard against the W164/R438 output-keyed silent-stale
3570    /// skip — the exact defect this relay fixes.
3571    #[tokio::test]
3572    async fn transform_recipe_change_busts_cache_and_reruns() {
3573        let fx = Fixture::new(minio_slot());
3574        let digest_a = HASH_64;
3575        let digest_b = "1".repeat(64);
3576        write_recipe_with_digest(&fx.workspace_root, "pinned", digest_a);
3577
3578        let out_bytes = b"transformed output".to_vec();
3579        let out_hash = blake3_hex(&out_bytes);
3580        let (mock, invocations) = MockExecutor::new(out_bytes);
3581        let executor: Arc<dyn ForgeExecutor> = mock;
3582
3583        let fetch_path = fx.workspace_root.join(".yah/cache/derive/fetch/in.bin");
3584        std::fs::create_dir_all(fetch_path.parent().unwrap()).unwrap();
3585        std::fs::write(&fetch_path, b"fetch bytes").unwrap();
3586        let in_hash = blake3_hex(b"fetch bytes");
3587
3588        let transform = TransformSpec {
3589            recipe: "pinned".to_string(),
3590            params: BTreeMap::new(),
3591        };
3592        let cache_dir = fx.workspace_root.join(".yah/cache/derive/transform");
3593        let wr = &fx.workspace_root;
3594
3595        // Run 1 — cold, digest A.
3596        materialize_transform(
3597            &transform,
3598            &fetch_path,
3599            &in_hash,
3600            &out_hash,
3601            &cache_dir,
3602            wr,
3603            executor.as_ref(),
3604        )
3605        .await
3606        .unwrap();
3607        assert_eq!(*invocations.lock().await, 1);
3608
3609        // Re-run with the SAME recipe → warm HIT, no re-run.
3610        materialize_transform(
3611            &transform,
3612            &fetch_path,
3613            &in_hash,
3614            &out_hash,
3615            &cache_dir,
3616            wr,
3617            executor.as_ref(),
3618        )
3619        .await
3620        .unwrap();
3621        assert_eq!(*invocations.lock().await, 1, "identical inputs must skip");
3622
3623        // Bump the container digest A → B. Output-keyed caching silently
3624        // skipped this; input-addressed caching MUST re-run.
3625        write_recipe_with_digest(&fx.workspace_root, "pinned", &digest_b);
3626        materialize_transform(
3627            &transform,
3628            &fetch_path,
3629            &in_hash,
3630            &out_hash,
3631            &cache_dir,
3632            wr,
3633            executor.as_ref(),
3634        )
3635        .await
3636        .unwrap();
3637        assert_eq!(
3638            *invocations.lock().await,
3639            2,
3640            "a digest bump must invalidate the cache and re-run",
3641        );
3642    }
3643
3644    /// W212/R518-P2b: the substituter fast-path honours the committed lock —
3645    /// `Some(output)` when the key recomputed from the pins matches, `None` the
3646    /// moment any input drifts (here a recipe-digest bump).
3647    #[tokio::test]
3648    async fn lock_skip_hash_honours_committed_lock() {
3649        let fx = Fixture::new(minio_slot());
3650        write_recipe_with_digest(&fx.workspace_root, "pinned", HASH_64);
3651
3652        let fetch_pin = "a".repeat(64);
3653        let out_pin = "b".repeat(64);
3654        // The lock's input_hash must equal the key the reconciler recomputes
3655        // from the committed pins.
3656        let recipe_bk = recipe_blake3(&fx.workspace_root, "pinned").await.unwrap();
3657        let key = derivation_key(&fetch_pin, &recipe_bk, &BTreeMap::new());
3658
3659        let toml = format!(
3660            r#"kind = "static-asset"
3661schema_version = "V1"
3662
3663[[asset]]
3664filename = "whisper/coreml.tar.gz"
3665blake3   = "{out_pin}"
3666
3667[asset.derive.fetch]
3668url     = "https://example/config.json"
3669blake3  = "{fetch_pin}"
3670license = "mit"
3671
3672[asset.derive.transform]
3673recipe = "pinned"
3674
3675[asset.derive.lock]
3676input_hash    = "{key}"
3677output_blake3 = "{out_pin}"
3678"#
3679        );
3680        let workload: StaticAssetWorkload = toml::from_str(&toml).unwrap();
3681        let entry = &workload.assets[0];
3682
3683        // Lock current → Some(output hash) (caller then HEADs the bucket).
3684        assert_eq!(
3685            lock_skip_hash(entry, &fx.workspace_root).await.as_deref(),
3686            Some(out_pin.as_str()),
3687        );
3688
3689        // Bump the recipe digest → recipe-file hash changes → recomputed key no
3690        // longer matches the lock → None (must rebuild). The exact drift the
3691        // output-keyed cache missed.
3692        write_recipe_with_digest(&fx.workspace_root, "pinned", &"1".repeat(64));
3693        assert!(
3694            lock_skip_hash(entry, &fx.workspace_root).await.is_none(),
3695            "a stale recipe must not skip the build",
3696        );
3697    }
3698
3699    /// W212/R518-P2b: a bootstrap (zero-sentinel) row never short-circuits via
3700    /// the lock — there is no pinned output to trust yet.
3701    #[tokio::test]
3702    async fn lock_skip_hash_declines_bootstrap_rows() {
3703        let fx = Fixture::new(minio_slot());
3704        write_recipe_with_digest(&fx.workspace_root, "pinned", HASH_64);
3705        let sentinel = "0".repeat(64);
3706        let toml = format!(
3707            r#"kind = "static-asset"
3708schema_version = "V1"
3709
3710[[asset]]
3711filename = "whisper/coreml.tar.gz"
3712blake3   = "{sentinel}"
3713
3714[asset.derive.fetch]
3715url     = "https://example/config.json"
3716blake3  = "{sentinel}"
3717license = "mit"
3718
3719[asset.derive.transform]
3720recipe = "pinned"
3721
3722[asset.derive.lock]
3723input_hash    = "whatever"
3724output_blake3 = "{sentinel}"
3725"#
3726        );
3727        let workload: StaticAssetWorkload = toml::from_str(&toml).unwrap();
3728        assert!(
3729            lock_skip_hash(&workload.assets[0], &fx.workspace_root)
3730                .await
3731                .is_none(),
3732            "bootstrap rows must always build",
3733        );
3734    }
3735
3736    /// R546-B6: the fetched-input hash is the FOURTH paste-back value. Seeding
3737    /// used to compute it, key the derivation on it, and drop it — leaving
3738    /// `[asset.derive.fetch].blake3` at the sentinel, which makes
3739    /// `lock_skip_hash` decline at its first guard for everyone but the seeding
3740    /// machine (whose local action cache masks it).
3741    #[tokio::test]
3742    async fn seed_surfaces_fetched_input_hash_and_pin_state() {
3743        let fx = Fixture::new(minio_slot());
3744        write_recipe(&fx.workspace_root, "pinned");
3745
3746        // Warm the fetch cache so materialize_fetch takes its HIT path — no
3747        // network, and the committed pin is already correct (Pinned arm).
3748        let fetch_bytes = b"upstream source tarball".to_vec();
3749        let fetch_hash = blake3_hex(&fetch_bytes);
3750        let fetch_cache = fx.workspace_root.join(".yah/cache/derive/fetch");
3751        std::fs::create_dir_all(&fetch_cache).unwrap();
3752        std::fs::write(fetch_cache.join(format!("{fetch_hash}.bin")), &fetch_bytes).unwrap();
3753
3754        let sentinel = "0".repeat(64);
3755        let workload_path = fx.workspace_root.join("workload.toml");
3756        std::fs::write(
3757            &workload_path,
3758            format!(
3759                r#"kind = "static-asset"
3760schema_version = "V1"
3761
3762[[asset]]
3763filename = "rusty-v8/x86_64.tar.gz"
3764blake3   = "{sentinel}"
3765
3766[asset.derive.fetch]
3767url     = "https://example/v8.tar.gz"
3768blake3  = "{fetch_hash}"
3769license = "mit"
3770
3771[asset.derive.transform]
3772recipe = "pinned"
3773params = {{ target = "x86_64-unknown-linux-musl" }}
3774"#
3775            ),
3776        )
3777        .unwrap();
3778
3779        let prebuilt = fx.workspace_root.join("prebuilt.tar.gz");
3780        std::fs::write(&prebuilt, b"prebuilt rusty_v8 tarball").unwrap();
3781
3782        let seeded = seed_derivation_for_target(
3783            &fx.workspace_root,
3784            &workload_path,
3785            "x86_64-unknown-linux-musl",
3786            &prebuilt,
3787        )
3788        .await
3789        .unwrap();
3790
3791        assert_eq!(
3792            seeded.fetch_blake3, fetch_hash,
3793            "the hash the derivation key was keyed on must be surfaced for paste-back",
3794        );
3795        assert_eq!(seeded.fetch_pin, Some(FetchPinState::Pinned));
3796
3797        // And it really is the key input: recomputing from the surfaced value
3798        // reproduces the seeded lock's input_hash.
3799        let recipe_bk = recipe_blake3(&fx.workspace_root, "pinned").await.unwrap();
3800        let mut params = BTreeMap::new();
3801        params.insert(
3802            "target".to_string(),
3803            "x86_64-unknown-linux-musl".to_string(),
3804        );
3805        assert_eq!(
3806            derivation_key(&seeded.fetch_blake3, &recipe_bk, &params),
3807            seeded.derive_key,
3808        );
3809    }
3810
3811    /// R546-B6: the three pin verdicts the seed command reports on. `Sentinel`
3812    /// is the disarmed case the ticket was filed for; `Mismatch` catches a
3813    /// moved version anchor before the operator pastes a lock that can only
3814    /// ever decline on input drift.
3815    #[test]
3816    fn classify_fetch_pin_covers_all_three_verdicts() {
3817        let fetched = blake3_hex(b"upstream");
3818        assert_eq!(
3819            classify_fetch_pin(&"0".repeat(64), &fetched),
3820            FetchPinState::Sentinel,
3821        );
3822        assert_eq!(
3823            classify_fetch_pin(&fetched.to_uppercase(), &fetched),
3824            FetchPinState::Pinned,
3825            "hash comparison is case-insensitive like the rest of the reconciler",
3826        );
3827        let stale = blake3_hex(b"a different upstream");
3828        assert_eq!(
3829            classify_fetch_pin(&stale, &fetched),
3830            FetchPinState::Mismatch {
3831                committed: stale.clone()
3832            },
3833        );
3834    }
3835
3836    /// R546-B12: a clean reconcile must SAY something. The failure this guards
3837    /// is not a wrong line, it is an absent one — a successful publish and a
3838    /// successful no-op printing identically (i.e. nothing), which is what made
3839    /// the blind `yah cloud status` view so costly to notice.
3840    #[test]
3841    fn sync_notes_distinguish_publish_from_no_op_and_are_never_empty() {
3842        // Published.
3843        let mut report = StaticAssetSyncReport::default();
3844        report.uploaded.push("a/one.bin".to_string());
3845        let notes = render_sync_notes(&report);
3846        assert!(
3847            notes.iter().any(|n| n.contains("published 1 asset")),
3848            "{notes:?}"
3849        );
3850        assert!(notes.iter().any(|n| n.contains("a/one.bin")), "{notes:?}");
3851
3852        // No-op: everything already current. Must NOT look like a publish, and
3853        // must not be silent.
3854        let mut report = StaticAssetSyncReport::default();
3855        report.already_synced.push("a/one.bin".to_string());
3856        let notes = render_sync_notes(&report);
3857        assert!(
3858            notes.iter().any(|n| n.contains("already current")),
3859            "{notes:?}"
3860        );
3861        assert!(
3862            !notes.iter().any(|n| n.contains("published")),
3863            "a no-op must not read as a publish: {notes:?}"
3864        );
3865
3866        // Bootstrap discoveries are paste-back values — the operator needs the
3867        // hashes themselves, not a count.
3868        let mut report = StaticAssetSyncReport::default();
3869        report.bootstrapped.push(BootstrappedHash {
3870            filename: "a/one.bin".into(),
3871            kind: BootstrapHashKind::Output,
3872            hash: HASH_64.to_string(),
3873        });
3874        let notes = render_sync_notes(&report);
3875        assert!(notes.iter().any(|n| n.contains(HASH_64)), "{notes:?}");
3876
3877        // The degenerate case still speaks.
3878        let notes = render_sync_notes(&StaticAssetSyncReport::default());
3879        assert_eq!(notes.len(), 1, "{notes:?}");
3880        assert!(notes[0].contains("nothing to reconcile"), "{notes:?}");
3881    }
3882
3883    #[test]
3884    fn bootstrap_output_key_input_variant() {
3885        let b = BootstrappedHash {
3886            filename: "whisper/coreml.tar.gz".into(),
3887            kind: BootstrapHashKind::Input,
3888            hash: "deadbeef".into(),
3889        };
3890        assert_eq!(
3891            bootstrap_output_key(&b),
3892            "discovered_input_hash:whisper/coreml.tar.gz",
3893        );
3894    }
3895
3896    /// R546-B8: both recipe bindings must be ABSOLUTE, even when the caller
3897    /// passes a relative workspace root.
3898    ///
3899    /// The fixture deliberately uses `TempDir::new_in(".")` rather than the
3900    /// usual absolute tempdir — that is the whole point. `yah cloud apply`
3901    /// defaults `--path` to `"."`, so `cache_dir` came out relative
3902    /// (`./.yah/cache/derive/transform/<key>.tmp`) and got handed to the recipe
3903    /// verbatim. A relative OUT survives only while the recipe stays in its
3904    /// cwd, which is why the whisper recipes never tripped it; rusty-v8's
3905    /// build-v8.sh chdirs into a scratch dir to build V8, so it wrote the
3906    /// finished tar to `<scratch>/./.yah/cache/...` inside the container and the
3907    /// bytes died with it — after a ~2h build, with the step reporting exit 0.
3908    ///
3909    /// An absolute-tempdir fixture cannot catch this: `cache_dir` is then
3910    /// absolute either way and the assertion passes against the buggy code too.
3911    #[tokio::test]
3912    async fn transform_bindings_are_absolute_from_a_relative_workspace_root() {
3913        // `TempDir::new_in(".")` hands back an ABSOLUTE path, so rebuild the
3914        // relative form by hand — cargo runs tests with cwd at the package root,
3915        // so `./<name>` resolves to the same directory.
3916        let tmp = tempfile::TempDir::new_in(".").expect("tempdir beside cwd");
3917        let workspace_root = Path::new(".").join(tmp.path().file_name().unwrap());
3918        assert!(
3919            workspace_root.is_relative(),
3920            "fixture must reproduce the relative-root case, got {}",
3921            workspace_root.display(),
3922        );
3923
3924        write_recipe(&workspace_root, "noop-recipe");
3925        let cache_dir = workspace_root.join(".yah/cache/derive/transform");
3926        std::fs::create_dir_all(&cache_dir).unwrap();
3927        let fetch_path = workspace_root.join(".yah/cache/derive/fetch/in.bin");
3928        std::fs::create_dir_all(fetch_path.parent().unwrap()).unwrap();
3929        std::fs::write(&fetch_path, b"fetch bytes").unwrap();
3930
3931        let (capture, argv) = ArgvCapture::new(true);
3932        let executor: Arc<dyn ForgeExecutor> = capture;
3933        let transform = TransformSpec {
3934            recipe: "noop-recipe".to_string(),
3935            params: BTreeMap::new(),
3936        };
3937
3938        materialize_transform(
3939            &transform,
3940            &fetch_path,
3941            &blake3_hex(b"fetch bytes"),
3942            ZERO_SENTINEL_HEX, // bootstrap: accept whatever hash comes out
3943            &cache_dir,
3944            &workspace_root,
3945            executor.as_ref(),
3946        )
3947        .await
3948        .expect("transform must succeed");
3949
3950        // Recipe argv is ["./tool", "{{YAH_TRANSFORM_IN_0}}", "{{YAH_TRANSFORM_OUT}}"].
3951        let argv = argv.lock().await.clone();
3952        assert_eq!(argv.len(), 3, "unexpected argv shape: {argv:?}");
3953        assert!(
3954            Path::new(&argv[1]).is_absolute(),
3955            "{ENV_TRANSFORM_IN_0} binding must be absolute, got {:?}",
3956            argv[1],
3957        );
3958        assert!(
3959            Path::new(&argv[2]).is_absolute(),
3960            "{ENV_TRANSFORM_OUT} binding must be absolute, got {:?}",
3961            argv[2],
3962        );
3963    }
3964
3965    /// R546-B8 hardening: a recipe that exits 0 without writing its artifact
3966    /// must be named as such. Before this, the missing file surfaced as
3967    /// `reading transform output …: No such file or directory` on a path under
3968    /// `.yah/cache/`, which reads like cache corruption and sends the reader
3969    /// into the wrong subsystem.
3970    #[tokio::test]
3971    async fn transform_that_writes_no_output_names_the_recipe_contract() {
3972        let fx = Fixture::new(minio_slot());
3973        write_recipe(&fx.workspace_root, "writes-nothing");
3974        let cache_dir = fx.workspace_root.join(".yah/cache/derive/transform");
3975        let fetch_path = fx.workspace_root.join(".yah/cache/derive/fetch/in.bin");
3976        std::fs::create_dir_all(fetch_path.parent().unwrap()).unwrap();
3977        std::fs::write(&fetch_path, b"fetch bytes").unwrap();
3978
3979        // Exit 0, write nothing — exactly what the relative-OUT bug looked like
3980        // from the reconciler's side.
3981        let (capture, _) = ArgvCapture::new(false);
3982        let executor: Arc<dyn ForgeExecutor> = capture;
3983        let transform = TransformSpec {
3984            recipe: "writes-nothing".to_string(),
3985            params: BTreeMap::new(),
3986        };
3987
3988        let err = materialize_transform(
3989            &transform,
3990            &fetch_path,
3991            &blake3_hex(b"fetch bytes"),
3992            ZERO_SENTINEL_HEX,
3993            &cache_dir,
3994            &fx.workspace_root,
3995            executor.as_ref(),
3996        )
3997        .await
3998        .expect_err("a recipe that writes nothing must fail");
3999
4000        let msg = format!("{err:#}");
4001        assert!(msg.contains("produced no output"), "{msg}");
4002        assert!(msg.contains("writes-nothing"), "{msg}");
4003        assert!(
4004            !msg.contains("No such file or directory"),
4005            "must not leak the raw io error that reads like cache corruption: {msg}",
4006        );
4007    }
4008
4009    #[tokio::test]
4010    async fn materialize_transform_blake3_mismatch_on_output_is_hard_error() {
4011        let fx = Fixture::new(minio_slot());
4012        write_recipe(&fx.workspace_root, "wrong-output");
4013        let out_bytes = b"actual output".to_vec();
4014        let actual_hash = blake3_hex(&out_bytes);
4015        let pinned_hash = HASH_64; // deliberately wrong
4016        assert_ne!(actual_hash, pinned_hash);
4017        let (mock, _) = MockExecutor::new(out_bytes);
4018        let executor: Arc<dyn ForgeExecutor> = mock;
4019
4020        let fetch_path = fx.workspace_root.join(".yah/cache/derive/fetch/in.bin");
4021        std::fs::create_dir_all(fetch_path.parent().unwrap()).unwrap();
4022        std::fs::write(&fetch_path, b"fetch bytes").unwrap();
4023
4024        let transform = TransformSpec {
4025            recipe: "wrong-output".to_string(),
4026            params: BTreeMap::new(),
4027        };
4028        let err = materialize_transform(
4029            &transform,
4030            &fetch_path,
4031            &blake3_hex(b"fetch bytes"),
4032            pinned_hash,
4033            &fx.workspace_root.join(".yah/cache/derive/transform"),
4034            &fx.workspace_root,
4035            executor.as_ref(),
4036        )
4037        .await
4038        .expect_err("transform output mismatch must surface");
4039        let msg = format!("{err:#}");
4040        assert!(msg.contains("BLAKE3"), "{msg}");
4041        assert!(msg.contains(pinned_hash), "{msg}");
4042    }
4043
4044    #[tokio::test]
4045    async fn materialize_transform_recipe_failure_surfaces_stderr() {
4046        let fx = Fixture::new(minio_slot());
4047        write_recipe(&fx.workspace_root, "failing-recipe");
4048        let executor: Arc<dyn ForgeExecutor> = MockExecutor::failing("tool exploded".to_string());
4049
4050        let fetch_path = fx.workspace_root.join(".yah/cache/derive/fetch/in.bin");
4051        std::fs::create_dir_all(fetch_path.parent().unwrap()).unwrap();
4052        std::fs::write(&fetch_path, b"fetch bytes").unwrap();
4053
4054        let transform = TransformSpec {
4055            recipe: "failing-recipe".to_string(),
4056            params: BTreeMap::new(),
4057        };
4058        let err = materialize_transform(
4059            &transform,
4060            &fetch_path,
4061            &blake3_hex(b"fetch bytes"),
4062            HASH_64,
4063            &fx.workspace_root.join(".yah/cache/derive/transform"),
4064            &fx.workspace_root,
4065            executor.as_ref(),
4066        )
4067        .await
4068        .expect_err("failing recipe must surface");
4069        let msg = format!("{err:#}");
4070        assert!(msg.contains("failing-recipe"), "{msg}");
4071        assert!(msg.contains("tool exploded"), "{msg}");
4072    }
4073
4074    #[tokio::test]
4075    async fn materialize_derive_fetch_only_uses_fetch_path_for_upload() {
4076        // No transform — materialize_asset returns the fetch cache path
4077        // directly. The downstream BLAKE3 verify happens in sync_assets.
4078        let fx = Fixture::new(minio_slot());
4079        let body = b"weights v1";
4080        let hash = blake3_hex(body);
4081
4082        use axum::routing::get;
4083        let body_c = body.to_vec();
4084        let app = axum::Router::new().route(
4085            "/w.bin",
4086            get(move || {
4087                let body = body_c.clone();
4088                async move { body }
4089            }),
4090        );
4091        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4092        let addr = listener.local_addr().unwrap();
4093        tokio::spawn(async move {
4094            axum::serve(listener, app).await.unwrap();
4095        });
4096
4097        let entry = AssetEntry {
4098            filename: "w.bin".to_string(),
4099            source: None,
4100            derive: Some(AssetDerive {
4101                fetch: FetchSource {
4102                    url: format!("http://{addr}/w.bin"),
4103                    blake3: BlakeHash(hash.clone()),
4104                    license: License::Mit,
4105                },
4106                transform: None,
4107                lock: None,
4108            }),
4109            blake3: BlakeHash(hash.clone()),
4110        };
4111        let materialized = materialize_asset(
4112            &entry,
4113            &fx.workspace_root,
4114            &fx.workload_dir(),
4115            test_executor().as_ref(),
4116        )
4117        .await
4118        .expect("fetch-only materialize");
4119        assert!(materialized
4120            .path
4121            .to_string_lossy()
4122            .contains(".yah/cache/derive/fetch/"));
4123        assert_eq!(std::fs::read(&materialized.path).unwrap(), body);
4124        assert!(
4125            materialized.discovered_fetch_hash.is_none(),
4126            "strict mode: pinned fetch.blake3 → no discovery"
4127        );
4128    }
4129
4130    #[tokio::test]
4131    async fn materialize_fetch_bootstrap_sentinel_accepts_actual_hash() {
4132        // fetch.blake3 ships as the zero sentinel; reconciler accepts the
4133        // computed hash and names the cache by the discovered value.
4134        let fx = Fixture::new(minio_slot());
4135        let body = b"discovered-upstream";
4136        let actual_hash = blake3_hex(body);
4137
4138        use axum::routing::get;
4139        let body_c = body.to_vec();
4140        let app = axum::Router::new().route(
4141            "/blob.bin",
4142            get(move || {
4143                let body = body_c.clone();
4144                async move { body }
4145            }),
4146        );
4147        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4148        let addr = listener.local_addr().unwrap();
4149        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
4150
4151        let fetch = FetchSource {
4152            url: format!("http://{addr}/blob.bin"),
4153            blake3: BlakeHash(ZERO_SENTINEL_HEX.to_string()),
4154            license: License::Mit,
4155        };
4156        let cache_dir = fx.workspace_root.join(".yah/cache/derive/fetch");
4157        let (path, discovered) = materialize_fetch(&fetch, &cache_dir).await.unwrap();
4158        assert!(path.exists(), "cache file must exist after bootstrap fetch");
4159        assert_eq!(
4160            discovered, actual_hash,
4161            "discovered hash = actual content hash"
4162        );
4163        assert!(
4164            path.file_name()
4165                .and_then(|s| s.to_str())
4166                .map(|s| s.starts_with(&actual_hash))
4167                .unwrap_or(false),
4168            "bootstrap mode names cache by discovered hash, got {path:?}",
4169        );
4170    }
4171
4172    #[tokio::test]
4173    async fn materialize_derive_fetch_bootstrap_surfaces_discovered_hash() {
4174        // End-to-end: AssetEntry with sentinel fetch.blake3 → materialize_asset
4175        // populates discovered_fetch_hash so sync_assets can surface it.
4176        let fx = Fixture::new(minio_slot());
4177        let body = b"upstream-bytes";
4178        let actual_hash = blake3_hex(body);
4179
4180        use axum::routing::get;
4181        let body_c = body.to_vec();
4182        let app = axum::Router::new().route(
4183            "/w.bin",
4184            get(move || {
4185                let body = body_c.clone();
4186                async move { body }
4187            }),
4188        );
4189        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4190        let addr = listener.local_addr().unwrap();
4191        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
4192
4193        let entry = AssetEntry {
4194            filename: "w.bin".to_string(),
4195            source: None,
4196            derive: Some(AssetDerive {
4197                fetch: FetchSource {
4198                    url: format!("http://{addr}/w.bin"),
4199                    blake3: BlakeHash(ZERO_SENTINEL_HEX.to_string()),
4200                    license: License::Mit,
4201                },
4202                transform: None,
4203                lock: None,
4204            }),
4205            // entry.blake3 still sentinel — upload-side verify in sync_assets
4206            // handles the output-hash discovery; here we only assert the
4207            // fetch-side discovery threads up correctly.
4208            blake3: BlakeHash(ZERO_SENTINEL_HEX.to_string()),
4209        };
4210        let materialized = materialize_asset(
4211            &entry,
4212            &fx.workspace_root,
4213            &fx.workload_dir(),
4214            test_executor().as_ref(),
4215        )
4216        .await
4217        .expect("bootstrap materialize");
4218        assert_eq!(
4219            materialized.discovered_fetch_hash.as_deref(),
4220            Some(actual_hash.as_str()),
4221            "fetch.blake3 sentinel → discovered hash returned",
4222        );
4223    }
4224
4225    /// W209/F4: discovered hashes write to `$YAH_OUTPUTS` with one line per
4226    /// (kind, filename) pair so the QED runner can route them through
4227    /// OutputMap into pipeline binds. Key shape encodes the filename so
4228    /// multi-asset workloads round-trip; the value is the raw blake3 hex.
4229    #[test]
4230    fn bootstrap_outputs_format_round_trip() {
4231        let dir = tempdir().unwrap();
4232        let outputs = dir.path().join("outputs");
4233        let bootstrapped = vec![
4234            BootstrappedHash {
4235                filename: "yah-desktop/whisper/distil-large-v3-coreml.tar.gz".to_string(),
4236                kind: BootstrapHashKind::Output,
4237                hash: "fb0afc9f3d966f5347c6dfd335adab12f1dc8ee6df18cf9e9ff90fe86f0416c0"
4238                    .to_string(),
4239            },
4240            BootstrappedHash {
4241                filename: "yah-desktop/whisper/distil-large-v3-coreml.tar.gz".to_string(),
4242                kind: BootstrapHashKind::Fetch,
4243                hash: "050ffe562134208781dc316181b146a725821fff005fb4ffb6de2a6ada334a9b"
4244                    .to_string(),
4245            },
4246        ];
4247        append_bootstrap_outputs(&outputs, &bootstrapped).expect("write outputs");
4248        let content = std::fs::read_to_string(&outputs).expect("read outputs");
4249        let lines: Vec<&str> = content.lines().collect();
4250        assert_eq!(lines.len(), 2, "one line per discovery");
4251        assert!(
4252            lines.contains(
4253                &"discovered_asset_blake3:yah-desktop/whisper/distil-large-v3-coreml.tar.gz=\
4254                  fb0afc9f3d966f5347c6dfd335adab12f1dc8ee6df18cf9e9ff90fe86f0416c0"
4255            ),
4256            "asset output key encodes filename: {content:?}",
4257        );
4258        assert!(
4259            lines.contains(
4260                &"discovered_fetch_blake3:yah-desktop/whisper/distil-large-v3-coreml.tar.gz=\
4261                  050ffe562134208781dc316181b146a725821fff005fb4ffb6de2a6ada334a9b"
4262            ),
4263            "fetch output key encodes filename: {content:?}",
4264        );
4265    }
4266
4267    /// Append, not truncate: a step that materializes N assets and emits
4268    /// other outputs in the same step must not clobber what's already in
4269    /// the file.
4270    #[test]
4271    fn bootstrap_outputs_append_preserves_prior_lines() {
4272        let dir = tempdir().unwrap();
4273        let outputs = dir.path().join("outputs");
4274        std::fs::write(&outputs, "prior_key=prior_value\n").unwrap();
4275        let bootstrapped = vec![BootstrappedHash {
4276            filename: "a.bin".to_string(),
4277            kind: BootstrapHashKind::Output,
4278            hash: HASH_64.to_string(),
4279        }];
4280        append_bootstrap_outputs(&outputs, &bootstrapped).expect("append");
4281        let content = std::fs::read_to_string(&outputs).expect("read");
4282        assert!(content.starts_with("prior_key=prior_value\n"), "prior kept");
4283        assert!(
4284            content.contains(&format!("discovered_asset_blake3:a.bin={HASH_64}")),
4285            "new line appended: {content:?}",
4286        );
4287    }
4288}