Skip to main content

cloud/reconciler/
mesofact_static.rs

1//! [`Reconciler`] implementation for `kind = "mesofact-static"` components.
2//!
3//! Dispatches on the mirror's `providers.static` slot:
4//!
5//! - **`kind = "local-static"` (inline)** — spawn `mesofact-dev` as a child
6//!   process on `127.0.0.1:<port>`. Pointer-swap + auto-rebuild come from
7//!   the binary's built-in watcher (R255-T2); the reconciler just owns
8//!   start/stop and the dev URL.
9//! - **`use = "cloudflare"` (reference)** — not yet implemented; production
10//!   pipeline integrates `mesofact-publisher` once R157 catches up.
11//!
12//! Binary discovery for the local path: caller may pass an explicit path
13//! via [`LocalStaticOptions::binary`]; otherwise the reconciler reads the
14//! `MESOFACT_DEV_BIN` env var; otherwise it relies on PATH resolution of
15//! the bare name `mesofact-dev`.
16//!
17//! @yah:ticket(R255-F6, "Split tier-1 into native fast-path vs managed-subprocess fallback")
18//! @yah:assignee(agent:claude)
19//! @yah:at(2026-05-25T20:08:16Z)
20//! @yah:status(review)
21//! @yah:parent(R255)
22//! @yah:next("native fast-path: blessed mesofact stack, bun in-process, axum-as-ingress, camp daemon runs the build job (current mesofact-dev watcher path)")
23//! @yah:next("managed-subprocess fallback: generic app runs as a managed child subprocess behind axum-as-ingress")
24//! @yah:next("make reconciler dispatch select the two paths explicitly rather than branching on if-compatible inside one arm")
25//! @yah:assumes("not all projects have a valid in-process tier-1 — only the blessed mesofact stack (in-process bun, axum ingress) qualifies")
26//! @yah:handoff("Two-path dispatch already landed in R274 (filed after F6 was opened). Native fast-path = spawn_mesofact_dev in-process in camp.rs:575 (R274-F1). Managed-subprocess fallback = adopt_only:false arm in MesofactStaticReconciler.up_local_static (mesofact_static.rs:168). Desktop sets adopt_only:true so it adopts the camp server; CLI/CI path sets adopt_only:false and spawns the binary. The 'generic app subprocess behind axum-as-ingress for non-mesofact workloads' vision is a future ticket, not R255 scope. No code change needed here.")
27//! @yah:verify("Verify dispatch: (1) cargo check --workspace --locked; (2) with camp running, mirror_run_up adopts the in-process server (jit port file); (3) with camp NOT running and adopt_only:false, reconciler spawns mesofact-dev binary.")
28//!
29//! @yah:relay(R320, "Cloudflare first-class Infra provider + yah.dev R2 publish")
30//! @yah:at(2026-05-26T00:19:09Z)
31//! @yah:status(open)
32//! @arch:see(.yah/docs/working/W074-cloudflare-infra-provider.md)
33//!
34//! @yah:ticket(R320-T8, "Wire cloudflare reference path into MesofactStaticReconciler")
35//! @yah:assignee(agent:claude)
36//! @yah:at(2026-05-26T00:42:37Z)
37//! @yah:status(review)
38//! @yah:phase(P2)
39//! @yah:parent(R320)
40//! @yah:depends_on(R320-F7)
41//! @yah:handoff("Cloudflare reference path wired into MesofactStaticReconciler.up(). Reference arm now dispatches to up_cloudflare_r2() for provider_id=cloudflare, bails for any other reference provider. Method loads ProviderConfig from .yah/infra/providers/cloudflare.toml (needs account_id field), resolves R2 S3 keys from keystore/env, calls publish_to_r2, returns RunningWorkload with public_url=https://<zone>. CDN purge fires if cloudflare-api-token is present in keystore. read_workload_out_dir helper reads build.out_dir from workload.toml (defaults to dist).")
42//! @yah:verify("cargo check -p cloud — clean (verified)")
43//! @yah:verify("cargo test -p cloud --lib — 175 passed (verified)")
44//! @yah:verify("yah cloud mirror up dev-yah --env prod (requires account_id in cloudflare.toml + R2 S3 keys in keystore)")
45//!
46//! @yah:relay(R327, "CF Worker provisioner: static→R2 + SSR/SPA→origin routing for mesofact sites")
47//! @yah:at(2026-05-26T07:25:51Z)
48//! @yah:status(review)
49//! @yah:next("Design the Worker script template: static routes fetch from R2 bucket binding, SSR routes proxy to origin (yubaba service URL), SPA shell falls back to R2 index.html for unmatched paths")
50//! @yah:next("Add CF Workers API calls to up_cloudflare_r2: upload Worker script, create KV/R2 bucket binding, wire Routes or Custom Domain to the Worker")
51//! @yah:next("Worker replaces the Transform Rule workaround (R320-T11) as the general solution — both static-only and SSR/SPA sites go through the Worker")
52//! @yah:gotcha("Pure-static sites (Mode 1) still need the Worker to serve index.html for / — R2 custom domains alone don't auto-index")
53//! @yah:gotcha("Worker script must be idempotent across mirror up re-runs: re-deploy only when content hash changes")
54//! @yah:gotcha("R2 bucket binding in the Worker requires the bucket name matches the mirror config — keep them in sync")
55//! @yah:handoff("Worker script provisioner implemented. CloudflareClient gained deploy_worker_script (multipart PUT, ES module format, R2 ASSETS binding) and upsert_worker_route (idempotent GET+POST/PUT). MesofactStaticReconciler.up_cloudflare_r2 now: (1) parses mode/origin_url/ssr_prefixes from slot_fields; (2) renders WorkerMode-aware JS script (static/spa/ssr); (3) compares SHA256 hash against .yah/jit/worker-script-hashes.json — skips redeploy if unchanged; (4) upserts zone route {zone}/* → {service.name}-worker. Transform Rule call removed. Worker script handles / → index.html, trailing-slash directory indexes, SSR proxy to origin, SPA/SSR fallback to index.html. 21 new unit tests + 215 total passing.")
56//! @yah:next("Validate live E2E: yah cloud mirror up dev-yah --env prod — Worker script deployed to CF, route yah.dev/* → dev-yah-worker, curl https://yah.dev serves index.html via Worker (not Transform Rule)")
57//! @yah:next("Update MESOFACT_STATIC_GRANTS to add 'Workers Scripts Write' + 'Zone Workers Routes Write' permission groups (need to validate their CF permission-group UUIDs live against /accounts/{id}/tokens/permission_groups)")
58//! @yah:next("Consider whether to keep upsert_index_rewrite as belt-and-suspenders or drop it entirely once Worker is confirmed stable")
59//! @yah:verify("cargo test -p cloud --lib: 215 passed (verified)")
60//! @yah:verify("cargo check --workspace: clean (verify before merge)")
61//! @yah:gotcha("cloudflare-api-token must have Workers Scripts: Edit (account-scoped) + Zone Workers Routes: Edit (zone-scoped) — both now in MESOFACT_STATIC_GRANTS as 'Workers Scripts Write' + 'Workers Routes Write' with fallback IDs sourced from global CF catalog (2026-05-26)")
62//! @yah:gotcha("build_worker_multipart uses a manual multipart body (reqwest multipart feature not enabled in cloud Cargo.toml) — boundary is 'yahWorkerUpload0'")
63//! @yah:gotcha("Worker route pattern is '{zone}/*' not '*{zone}/*' — only catches apex requests, not subdomains. Add a wildcard route if subdomains need Worker routing")
64//! @yah:gotcha("CF Workers ES module format requires 'main_module' in metadata and the part name must match that filename ('worker.js')")
65//! @yah:handoff("Added Workers Scripts Write (account-scoped, fallback e086da7e...) + Workers Routes Write (zone-scoped, fallback 28f4b596...) to MESOFACT_STATIC_GRANTS. IDs sourced from the global CF permission-groups catalog (gist.github.com/f3l1x/13d3e43933e6d770aabee95410f8ee1d, validated against CF naming conventions). Test token_body_splits_scopes_and_resolves_ids extended to assert both new fallback IDs. Gotcha annotation updated: Workers grants are now in MESOFACT_STATIC_GRANTS. 215 tests pass, cargo check --workspace clean.")
66//! @yah:verify("cargo test -p cloud --lib — 215 passed")
67//! @yah:verify("cargo check --workspace — clean (warnings only, no errors)")
68//! @yah:verify("Live E2E (user must run): yah cloud mirror up dev-yah --env prod — Worker script deployed to CF, zone route yah.dev/* → dev-yah-worker, curl https://yah.dev returns index.html served by the Worker (not the old Transform Rule)")
69//!
70//! @yah:ticket(R327-F1, "Extract Worker router from Rust string literal to a typechecked TS source + miniflare test")
71//! @yah:assignee(agent:claude)
72//! @yah:at(2026-05-26T16:33:58Z)
73//! @yah:status(review)
74//! @yah:parent(R327)
75//! @yah:next("render_worker_script (mesofact_static.rs:536) builds the Worker as JS interpolated inside a Rust format! — untyped, validated only by string.contains() tests. Move the router to a real .ts source, typecheck + bundle (esbuild/bun), embed the bundled output.")
76//! @yah:next("Inject mode/bucket/ssr_prefixes/origin_url as a binding or generated config module rather than string interpolation, so the router source is static and unit-testable.")
77//! @yah:next("Add a miniflare test asserting routing behaviour (static index-at-root, SPA index fallback, SSR proxy to origin) against real workerd, replacing the substring assertions.")
78//! @yah:next("Keep the deploy hash-gate (read_worker_script_hash) working on the bundled output.")
79//! @yah:gotcha("The extracted TS router reads assets via fetch(ASSET_ORIGIN + key), NOT the R2 binding (see R327-F2 decision 2026-05-26) — take ASSET_ORIGIN as config/env, drop the ASSETS binding and the writeHttpMetadata/httpEtag handling. The router becomes a generic 'route + fetch from an origin' script, not CF-coupled.")
80//! @yah:gotcha("deploy_worker_script (cloudflare.rs:743) uploads a single JS main_module part; if bundling emits multiple modules, build_worker_multipart must emit each as its own multipart part.")
81//! @yah:gotcha("wasm intentionally out of scope: React-based mesofact SSR is JS, so the heavy-lifting path stays JS. wasm only enters if heavy compute becomes Rust (a Rust SSR engine / image transforms), which a React mesofact never introduces.")
82//! @yah:handoff("Router extracted from Rust format! string to crates/yah/cloud/worker/router.ts (TypeScript, typechecked). Bundle at router.bundle.js is embedded via include_str! as WORKER_SCRIPT const in mesofact_static.rs. Config injected via plain_text Worker bindings: ASSET_ORIGIN (read from slot_fields.asset_origin, defaults empty), WORKER_MODE (static/spa/ssr), SSR_ORIGIN, SSR_PREFIXES (JSON array). deploy_worker_script + build_worker_multipart in cloudflare.rs updated: R2 bucket binding dropped, plain_text bindings accepted instead. render_worker_script removed; replaced by worker_config_bindings(mode, asset_origin) returning Vec<(String,String)>. Hash-gate now covers script + bindings (sha256 of bundle bytes + NUL + JSON-encoded bindings). 11 miniflare tests in worker/tests/router.test.ts cover static index-at-root, 404.html fallback, plain 404 when absent, SPA fallback, known-asset passthrough, SSR prefix proxy, SSR non-prefix fallback. 220 cargo tests pass; cargo check --workspace clean.")
83//! @yah:verify("cargo test -p cloud --lib — 220 passed")
84//! @yah:verify("bun test tests/ in crates/yah/cloud/worker — 11 passed")
85//! @yah:verify("cargo check --workspace — clean (warnings only)")
86//! @yah:verify("Live E2E (user): set slot_fields.asset_origin to the R2 bucket public URL, run yah cloud mirror up dev-yah --env prod")
87//!
88//! @yah:ticket(R432-B2, "Stale jit ports file: don't re-probe a dead recorded port and call it a 'dynamic fallback'")
89//! @yah:assignee(agent:claude)
90//! @yah:at(2026-06-04T01:13:39Z)
91//! @yah:status(review)
92//! @yah:parent(R432)
93//! @yah:severity(minor)
94//! @yah:next("In up_local_static, after reading read_jit_port: if the recorded port == the configured port AND the first probe already failed, skip the second probe — it's the same dead address.")
95//! @yah:next("If the jit file claims a different port and that also fails to connect, treat the file as stale (don't pretend we exhaustively probed).")
96//! @yah:next("Consider: should camp purge the entry on shutdown? Lower priority; the read-side fix above is enough to clear the misleading error.")
97//! @yah:verify("With stale .yah/jit/mesofact-dev-ports.json (port not bound), the error no longer contains 'or any dynamic fallback port' — instead it says camp isn't running.")
98//! @yah:handoff("Fixed in mesofact_static.rs::up_local_static. Lifted jit_port outside the conditional block so the error arm can inspect it. Error message now: no jit note when file absent or records same port as configured; precise 'jit file recorded port N — also not bound' note when a genuinely different port was probed and also dead. Phrase 'or any dynamic fallback port' removed in all cases. Also fixed pre-existing MirrorConfig asset_aliases missing-field compile errors across cloud/config.rs, pond.rs, cloudflare_worker.rs, mesofact_static.rs, camp.rs (all tests now compile).")
99//! @yah:verify("cargo test -p cloud --lib reconciler::mesofact_static — 26 passed (includes two new R432-B2 regression tests)")
100//! @yah:verify("adopt_only_stale_jit_same_port_omits_dynamic_fallback_phrase: passes")
101//! @yah:verify("adopt_only_stale_jit_different_port_names_it: passes")
102//!
103//! @yah:ticket(R432-F3, "Split adopt_only error: distinguish 'camp not running' from 'camp running but didn't bind'")
104//! @yah:assignee(agent:claude)
105//! @yah:at(2026-06-04T01:13:52Z)
106//! @yah:status(review)
107//! @yah:parent(R432)
108//! @yah:next("Detect camp presence (e.g., socket path exists / camp_socket connectable) before composing the error.")
109//! @yah:next("Case A — no camp: 'mesofact-dev not running for component {id}; attach this workspace in the desktop or run yah camp from a terminal.'")
110//! @yah:next("Case B — camp up, no listener: 'camp is up but mesofact-dev did not bind for component {id} (configured port {port}, jit recorded {actual?}); check spawn_mesofact_dev workspace gating.'")
111//! @yah:next("Drop the 'or any dynamic fallback port' phrasing — it implies a probe that didn't actually happen.")
112//! @yah:verify("Both error variants surface in the desktop Up flow under the right conditions; neither mentions a probe we didn't run.")
113//! @yah:depends_on(R432-B2)
114//! @yah:handoff("Added camp_socket: Option<PathBuf> to LocalStaticOptions. In up_local_static adopt_only error arm: probes the socket via is_unix_socket_live helper (sync UnixStream::connect, cfg(unix) + no-op cfg(not(unix))). Case A (socket absent/unreachable) — 'mesofact-dev not running for this workspace — attach the workspace in the desktop or run yah camp from a terminal.' Case B (socket reachable, mesofact-dev not bound) — 'camp is up but mesofact-dev did not bind on port {port}{jit_note} — check spawn_mesofact_dev workspace gating or camp logs.' Desktop mirror_run.rs now passes camp_socket: Some(rpc::camp_socket_path(&workspace_root)). Updated B2 test adopt_only_stale_jit_different_port_names_it to use a live socket so jit note appears in Case-B path. 28 tests pass, desktop check clean.")
115//! @yah:verify("cargo test -p cloud --lib reconciler::mesofact_static — 28 passed")
116//! @yah:verify("cargo check -p desktop — clean")
117//! @yah:verify("adopt_only_no_camp_socket_gives_attach_message: passes")
118//! @yah:verify("adopt_only_live_camp_socket_gives_didnt_bind_message: passes")
119//!
120//! @yah:ticket(R434-F4, "Pond reconciler: spin ssr_runtime container when service has any mode:\"ssr\" route")
121//! @yah:assignee(agent:claude)
122//! @yah:at(2026-06-04T19:12:09Z)
123//! @yah:status(review)
124//! @yah:phase(P2)
125//! @yah:parent(R434)
126//! @arch:see(.yah/docs/working/W173-mesofact-render-cube.md)
127//! @yah:next("Live smoke: declare a workload.toml [ssr_runtime] block + a mirror.toml mode=\"ssr\" route, start camp, confirm bun container + miniflare proxy work end-to-end via YAH_LOCAL_SIM_E2E pond_smoke")
128//! @yah:next("R434-F5 (open) — convert one marketing route to mode:\"ssr\" — unblocked by F4; that's the first real SSR consumer")
129//! @yah:next("Optional: persist read_manifest_ssr_prefixes results across pond rebuilds so a stale dist/manifest.json fall-back doesn't bite (not needed today — manifest is always fresh after a mesofact-dev rebuild)")
130//! @yah:handoff("Phase A — Worker matcher + miniflare env plumbing. (1) router.ts:39 now uses segment-aware `path === p || path.startsWith(p + \"/\")`; rebuilt router.bundle.js; 4 new miniflare tests cover /api/health vs /api/healthcheck + trailing-slash boundary (16/16 pass). (2) local_driver::pond_miniflare::MiniflareSpec gained worker_mode/ssr_origin/ssr_prefixes fields; spawn_miniflare reads them from spec instead of hardcoding static. (3) cloud::reconciler::pond::spawn_miniflare_child + up_pond mirror the change; new public helpers parse_worker_mode and worker_mode_triple let camp derive the triple from mirror slot_fields. (4) camp::build_miniflare_deploy_spec calls parse_worker_mode → worker_mode_triple so flipping a mirror.toml to mode=ssr now works end-to-end.")
131//! @yah:handoff("Phase B — SSR runtime container slot in yubaba. (1) New local_driver::pond_ssr_runtime module with SsrRuntimeSpec, ensure_ssr_runtime_running, SsrRuntimeRunning, and lower_workload_spec(ws, host_port, name, label, timeout) → SsrRuntimeSpec. Lowering pulls image (with digest preference), command, literal env vars (FromSecret/FromMesh rejected with clear errors), Bind volumes, and expose.mesh.ports[0] as container_port (default 3000). 8/8 unit tests pass. (2) New yubaba::pond::ssr_runtime module with SsrRuntimeReconciler (probe + restart) and SsrRuntimeSupervision, mirroring MinioReconciler. (3) yubaba::pond::PondDeployReq gained ssr_runtime: Option<SsrRuntimeSpec>. The deploy handler brings SSR up BETWEEN MinIO and miniflare, overriding effective_miniflare.ssr_origin to point at the bound container so miniflare proxies correctly. RegistryEntry tracks ssr_runtime supervision alongside minio + miniflare; shutdown_all + mark_failed drain it.")
132//! @yah:handoff("Phase C — manifest-derived SSR_PREFIXES + camp wiring. (1) camp::build_ssr_runtime_deploy_spec reads <workload_dir>/workload.toml's MesofactStaticWorkload.ssr_runtime: Option<WorkloadSpec> and lowers it. Host port comes from static_fields.ssr_port (default 4324); collision with miniflare's port is rejected up-front. (2) camp::read_manifest_ssr_prefixes reads <workload_dir>/dist/manifest.json's top-level ssr_prefixes (R015-F2 contract). When present + non-empty, overrides miniflare's spec.ssr_prefixes (mirror.toml override path stays as fallback). (3) Camp's deploy loop now: builds miniflare → builds optional ssr_runtime → overrides miniflare.worker_mode=ssr + ssr_origin when runtime is present → overrides ssr_prefixes from manifest when available → POSTs full req. 9 new camp::r434_f4_ssr_pond_tests pass.")
133//! @yah:handoff("Verify lines satisfied: (a) Worker test /api/health vs /api/healthcheck DIRECTLY covered by tests/router.test.ts segment-aware matcher tests. (b) Pure static/spa pond mirrors still reconcile without spinning ssr_runtime — covered by build_ssr_runtime_deploy_spec_returns_none_without_ssr_runtime_field + existing 25 cloud reconciler::pond tests stay green. (c) End-to-end 'spins bun container and miniflare proxies prefix' is wired and unit-tested at the spec-build/registry layer; live smoke requires an actual workload with ssr_runtime declared + docker available (pond_smoke or YAH_LOCAL_SIM_E2E run). 5 pre-existing mesofact_static test flakes ignored — caused by a real desktop process on 127.0.0.1:4321 on the dev box, not by F4.")
134//! @yah:verify("cd crates/yah/cloud/worker && bun test tests/ → 16 pass (4 new R434-F4 segment-aware tests)")
135//! @yah:verify("cargo test -p local-driver --lib → 46 pass (8 new pond_ssr_runtime tests)")
136//! @yah:verify("cargo test -p yubaba --lib pond → 9 pass (registry handles ssr_runtime supervision)")
137//! @yah:verify("cargo test -p cloud --lib -- reconciler::pond:: reconciler::mesofact_static::tests::config_bindings reconciler::mesofact_static::tests::parse_worker_mode reconciler::mesofact_static::tests::worker_script → 21 pass")
138//! @yah:verify("cargo test -p yah --lib r434_f4_ssr_pond_tests → 9 pass (camp helpers: workload.toml subtree read, manifest ssr_prefixes read, build_ssr_runtime_deploy_spec)")
139//! @yah:verify("cargo check -p local-driver -p yubaba -p cloud -p yah → clean (warnings only, none from F4)")
140//! @yah:verify("Live smoke (user): workload.toml with [ssr_runtime] block + mirror.toml with providers.static.mode=\"ssr\" → yah camp → desktop adopts pond and the SSR prefix routes to the bun container")
141//!
142//! @yah:ticket(R438-T6, "W165 wiring: lower MesofactStaticWorkload.build_mode to ForgeCommand")
143//! @yah:assignee(agent:claude)
144//! @yah:at(2026-06-04T21:07:20Z)
145//! @yah:status(review)
146//! @yah:phase(P2)
147//! @yah:parent(R438)
148//! @yah:next("Replace run_build_command shell-out with run_build(workload_dir, &BuildConfig, &BuildMode)")
149//! @yah:next("Lower BuildMode::HostSide → ForgeSpec{Subprocess, TaskRuntime::Native}; InContainer{image} → {Subprocess(image), TaskRuntime::Container}")
150//! @yah:next("Hand ForgeSpec to task::local::execute — same path QED uses for image-build steps")
151//! @yah:next("TaskLocation::Local; cwd = workload_dir bind-mounted into container")
152//! @yah:verify("BuildMode::HostSide lowers to TaskRuntime::Native; InContainer{image} lowers to TaskRuntime::Container with pinned digest")
153//! @yah:verify("In-tree workload with build_mode=in_container runs build in configured image; host_side runs on host; identical out_dir bytes")
154//! @yah:gotcha("local-static arm behavior decision deferred to F1 (W165 OQ#1) — default-skip with warning is the proposed initial behavior")
155//! @arch:see(.yah/docs/working/W165-mesofact-build-mode-lowering.md)
156//! @yah:depends_on(R438-T3)
157//! @yah:handoff("T6 landed. (1) MesofactStaticReconciler gains executor: Arc<dyn ForgeExecutor> field + with_executor() setter; default Arc::new(LocalForgeDriver::default()) — mirrors T15's static_asset pattern. (2) rebuild_static now reads (BuildConfig, BuildMode) from workload.toml via new read_mesofact_build helper and hands them to run_build, which lowers to ForgeSpec{Subprocess{sh -c <cmd>, image?}, TaskPlacement{Local, runtime}} and dispatches through ForgeExecutor::execute. BuildMode::HostSide → image=None + TaskRuntime::Native; InContainer{image} → Some(image) + TaskRuntime::Container. ExecContext::default().with_cwd(workload_dir). (3) Old shell-out (sh -c with tokio::process::Command) deleted. (4) Critical: read_mesofact_build uses raw toml::Value subtree extraction (kind→build→build_mode), NOT the full workload_spec::Workload envelope — production marketing/dashboard workload.tomls carry schema_version = 1 (integer) which the typed envelope rejects; the subtree reader stays tolerant of that legacy shape while still typed-deserializing the build/build_mode subtrees to BuildConfig/BuildMode. ImageRef digest-pin enforcement inherits automatically via T3 (rejects bare-tag at deserialize). (5) 7 new tests under reconciler::mesofact_static::tests: read_mesofact_build_extracts_host_side_default, _extracts_in_container_with_digest, _rejects_in_container_without_digest, _returns_none_for_other_kinds, _returns_none_when_file_absent, rebuild_static_lifts_build_mode_through_executor (e2e: workload.toml→executor with digest round-trip), rebuild_static_defaults_to_host_side_when_build_mode_omitted, rebuild_static_skips_build_when_workload_toml_missing, plus run_build_host_side_lowers_to_native_subprocess, _in_container_lowers_to_container_runtime_with_pinned_digest, _surfaces_stderr_on_nonzero_exit (CaptureExecutor + FailingExecutor mocks). cargo test -p cloud --lib: 293 pass; 5 pre-existing failures (4 adopt_only port-4321 dev-box collision + 1 cloud_init drift — R441-B4 umbrella, unrelated). cargo check --workspace clean.")
158//! @yah:next("Sign off → archive R438-T6")
159//! @yah:next("R438-F9 (local-static arm: respect or skip container build_mode) is now unblocked — picker can decide default-skip vs honor for the local arm")
160//! @yah:next("R438-T8 (worked examples) can now add a mesofact-static workload with build_mode=in_container as an e2e fixture")
161//! @yah:verify("cargo test -p cloud --lib reconciler::mesofact_static — 35 pass; 4 R441-B4 adopt_only failures pre-existing")
162//! @yah:verify("cargo check --workspace --locked — clean (warnings only)")
163//! @yah:verify("BuildMode::HostSide → TaskRuntime::Native, image=None; InContainer{image} → TaskRuntime::Container, Some(pinned_image) (asserted by run_build_*_lowers_to_* tests)")
164//! @yah:verify("Legacy schema_version = 1 (integer) workload.tomls still parse — read_mesofact_build uses raw toml::Value subtree extraction")
165//! @yah:gotcha("read_mesofact_build uses raw toml::Value subtree extraction rather than the workload_spec::Workload envelope — production marketing/dashboard workload.tomls carry schema_version = 1 (integer) which the typed envelope rejects (SchemaVersion is enum V1, expects \"V1\" string). Until the workspace-wide schema_version migration ships, T4-style envelope parsing is unsafe in this path. If/when that migration lands, swap read_mesofact_build for a full envelope load.")
166//! @yah:gotcha("rebuild_static is only called from almanac_dispatch (OnChange::MesofactRebuild) — local-static arm bring-up via up() does NOT run the build step (the host watcher handles rebuilds). That gates W165 OQ#1 (R438-F9): the local arm question is purely about whether OnChange feeds should honor container build_mode locally.")
167//!
168//! @yah:ticket(R438-F9, "local-static arm: respect or skip container build_mode? (W165 OQ#1)")
169//! @yah:assignee(agent:claude)
170//! @yah:at(2026-06-04T21:07:57Z)
171//! @yah:status(review)
172//! @yah:parent(R438)
173//! @yah:next("Decide: container build for CI parity vs default-skip (no docker dependency for dev)")
174//! @yah:next("Default-skip with one-line warning is the proposed initial behavior")
175//! @yah:next("If skip: ensure log line is visible in dashboard/task-pane (per long-running→yah surface rule)")
176//! @arch:see(.yah/docs/working/W165-mesofact-build-mode-lowering.md)
177//! @yah:depends_on(R438-T6)
178//! @yah:handoff("F9 landed. Decision: local-static arm + InContainer build_mode → warn + fall back to HostSide (W165 OQ#1). Implementation: rebuild_static gains a 3-line pattern-guard before calling run_build; if slot is local-static and build_mode is InContainer, emit warn!(\"build_mode = in_container ignored for local-static; running host-side\") and override to BuildMode::HostSide. No new fields, no new types. Two test changes: (1) rebuild_static_lifts_build_mode_through_executor switched from local_static_slot(0) to cloudflare_reference_slot() — it now covers the CF publish arm (still asserts TaskRuntime::Container); (2) new rebuild_static_local_static_in_container_falls_back_to_host_side asserts TaskRuntime::Native + image=None when slot=local-static + build_mode=InContainer. cargo test -p cloud --lib reconciler::mesofact_static: 37 pass; 4 pre-existing R441-B4 adopt_only failures. cargo check -p cloud: clean.")
179//! @yah:verify("cargo test -p cloud --lib reconciler::mesofact_static::tests::rebuild_static_local_static_in_container_falls_back_to_host_side -- passes (TaskRuntime::Native, image=None)")
180//! @yah:verify("cargo test -p cloud --lib reconciler::mesofact_static::tests::rebuild_static_lifts_build_mode_through_executor -- passes (CF arm still uses TaskRuntime::Container)")
181//! @yah:verify("cargo check -p cloud -- clean")
182//!
183//! @yah:relay(R441, "Workspace test breakage on main (surfaced via R438-T3 sweep)")
184//! @yah:at(2026-06-04T22:55:58Z)
185//! @yah:status(open)
186//! @yah:next("4 independent pre-existing test failures on main, all caught while running `cargo test --workspace` during R438-T3 ImageRef tightening. Each surfaces test signal that's been silently broken; pick up the child tickets and route them to the right owner per area.")
187//! @yah:gotcha("These aren't ImageRef-related and didn't break during R438-T3 — they were broken on main before that work started. The umbrella is a discovery channel, not a regression.")
188//! @arch:see(.yah/docs/working/W164-derived-static-assets.md)
189//!
190//! @yah:ticket(R441-B4, "mesofact_static adopt_only_* tests expect Err but get Ok(RunningWorkload)")
191//! @yah:assignee(agent:claude)
192//! @yah:at(2026-06-04T22:56:20Z)
193//! @yah:status(review)
194//! @yah:parent(R441)
195//! @yah:next("Four tests panic at mesofact_static.rs:1188 with `called Result::unwrap_err() on an Ok value: RunningWorkload {...}`: adopt_only_no_camp_socket_gives_attach_message, adopt_only_live_camp_socket_gives_didnt_bind_message, adopt_only_stale_jit_same_port_omits_dynamic_fallback_phrase, adopt_only_stale_jit_different_port_names_it.")
196//! @yah:next("Reconciler changed: adopt-only paths now succeed (return RunningWorkload) where they used to error with operator-facing messages. This is a real behavior question, not a mechanical fix — either revert the reconciler change or update the four tests to assert on the new Ok-shape contract (likely the latter; check the most recent reconciler commit for intent).")
197//! @yah:next("Coordinate with whoever last touched the mesofact-static reconciler before flipping the assertions.")
198//! @yah:verify("cargo test -p cloud --lib reconciler::mesofact_static::tests::adopt_only_  # all 4 pass")
199//! @yah:handoff("Root cause: all four tests used hardcoded port 4321 which a running camp's mesofact-dev occupies, causing up_local_static to adopt it as Ok instead of reaching the adopt_only error path. Fix: added pick_unused_port() helper (bind :0, read port, drop listener) and replaced local_static_slot(4321) with pick_unused_port() in all four tests. stale_jit_different_port_names_it also replaced hardcoded 9999 with a second pick_unused_port() so the assertion checks the dynamic value. All 4 pass.")
200//!
201//! R535-T1 ("Split rebuild_static: revalidate-only path... called by
202//! almanac_dispatch", W225 §3) landed here: see [`MesofactStaticReconciler::
203//! revalidate_static`] and [`MesofactStaticReconciler::rebuild_static`]'s docs
204//! for the split, and `crate::almanac_dispatch` for the caller-side switch.
205//! Ticket record lives in `.yah/docs/working/W225-mesofact-consumer-deployment-model.md`
206//! (single declaration site — not duplicated here per Rule11).
207
208/// Bundled Worker script embedded at compile time from `worker/router.bundle.js`.
209///
210/// The source of truth is `@mesofact/edge`
211/// (`oss/mesofact/packages/mesofact-edge`) — the manifest-driven serving
212/// artifact mesofact owns (W270 §3, R595-F3). Its built bundle is *vendored*
213/// into `worker/router.bundle.js` by `scripts/check-worker-bundle.sh` so this
214/// crate stays standalone-exportable across the OSS mirror boundary (a
215/// cross-boundary `include_str!` into `oss/mesofact` would break yubaba's
216/// export). Run `scripts/check-worker-bundle.sh --update` after editing the
217/// worker; do NOT hand-edit `router.bundle.js`.
218///
219/// Used both for prod deployment and as the miniflare-sim artifact in the pond
220/// tier.
221pub const WORKER_SCRIPT: &str = include_str!("../../worker/router.bundle.js");
222
223use std::net::{IpAddr, Ipv4Addr, SocketAddr};
224use std::path::{Path, PathBuf};
225use std::sync::Arc;
226use std::time::Duration;
227
228use anyhow::{Context, Result};
229use async_trait::async_trait;
230use tokio::sync::oneshot;
231use tracing::{info, warn};
232
233use kamaji::native::NativeRuntime;
234use kamaji::{Kamaji, MeshAssignment, MeshIdent};
235use velveteen::{
236    ForgeCommand, ForgeSpec, Initiator, MeshAccess, TaskLocation, TaskPlacement, TaskRuntime,
237};
238use velveteen_exec::{ExecContext, ForgeExecutor, LocalForgeDriver};
239use workload_spec::{
240    BuildConfig, BuildMode, EnvVar, ExposeSpec, ImageRef, MeshExpose, Millis, NamespaceId,
241    ResourceLimits, RestartPolicy, SchemaVersion, StopPolicy, TenantId, TierTag, WorkloadSpec,
242};
243
244use super::native_support::{
245    capture_paths, native_spec, sanitize_ident, spawn_native_log_supervisor, NATIVE_IDENTITY_DIGEST,
246};
247use super::{
248    into_running, pond, slot_field_u16, wait_for_port, LogBuffer, ReconcileCtx, Reconciler,
249    RunningWorkload,
250};
251use crate::{MirrorProviderSlot, Provider};
252
253/// Workload kind this reconciler handles. Matches `ServiceComponent.kind`
254/// and the `kind = "..."` line in `workload.toml`.
255pub const WORKLOAD_KIND: &str = "mesofact-static";
256
257/// SPA sibling of [`WORKLOAD_KIND`]: mesofact emits a hydrate-bundle-loading
258/// HTML shell instead of a fully-rendered page per route. The serving path is
259/// identical (assets in a bucket behind the Worker/miniflare router); the only
260/// behavioral difference is the Worker's fallback mode, so the same reconciler
261/// handles both kinds.
262pub const WORKLOAD_KIND_SPA: &str = "mesofact-spa";
263
264/// True for the component kinds served by [`MesofactStaticReconciler`].
265pub fn is_mesofact_site_kind(kind: &str) -> bool {
266    kind == WORKLOAD_KIND || kind == WORKLOAD_KIND_SPA
267}
268
269/// Default port for the `local-static` provider slot — matches
270/// `mesofact-dev`'s `DEFAULT_PORT` and the canonical
271/// `.yah/services/dev-yah/mirrors/local.toml`.
272pub const DEFAULT_LOCAL_STATIC_PORT: u16 = 4321;
273
274/// Knobs for the `local-static` bring-up path.
275#[derive(Debug, Clone, Default)]
276pub struct LocalStaticOptions {
277    /// Explicit path to the `mesofact-dev` binary. Overrides the env-var
278    /// and PATH lookup.
279    pub binary: Option<PathBuf>,
280    /// Extra args to pass after the workload directory (e.g. `--no-watch`).
281    pub extra_args: Vec<String>,
282    /// How long to wait for the spawned process's port to start accepting
283    /// connections before declaring the up failed. Default: 10s.
284    pub ready_timeout: Option<Duration>,
285    /// When `true`, adopt an already-running server (TCP probe + jit file)
286    /// but never fall through to spawning a subprocess. Desktop sets this
287    /// because the server is embedded in yah-camp; there is no separate
288    /// binary to spawn.
289    pub adopt_only: bool,
290    /// Unix socket path of the camp daemon for this workspace. When set and
291    /// `adopt_only` is true, the error message distinguishes "camp not
292    /// running" (socket unreachable) from "camp up but server didn't bind"
293    /// (socket reachable, mesofact-dev port not bound).
294    pub camp_socket: Option<PathBuf>,
295}
296
297impl LocalStaticOptions {
298    /// Resolve the binary path: explicit > `MESOFACT_DEV_BIN` env > bare
299    /// `mesofact-dev` (will be looked up on `PATH` at spawn time).
300    pub fn resolved_binary(&self) -> PathBuf {
301        if let Some(ref p) = self.binary {
302            return p.clone();
303        }
304        if let Some(p) = std::env::var_os("MESOFACT_DEV_BIN") {
305            return PathBuf::from(p);
306        }
307        PathBuf::from("mesofact-dev")
308    }
309}
310
311/// Reconciles `kind = "mesofact-static"` components.
312///
313/// The `executor` field handles the build step (W165): `build.command` is
314/// lowered to a [`ForgeSpec`] and dispatched through
315/// [`ForgeExecutor::execute`]. Default is [`LocalForgeDriver`]; callers
316/// wanting to redirect (e.g. tests with a mock executor) use
317/// [`Self::with_executor`].
318pub struct MesofactStaticReconciler {
319    pub local_static: LocalStaticOptions,
320    pub pond: pond::PondOptions,
321    executor: Arc<dyn ForgeExecutor>,
322}
323
324impl MesofactStaticReconciler {
325    pub fn new() -> Self {
326        Self {
327            local_static: LocalStaticOptions::default(),
328            pond: pond::PondOptions::default(),
329            executor: Arc::new(LocalForgeDriver::default()),
330        }
331    }
332
333    pub fn with_local_static(mut self, opts: LocalStaticOptions) -> Self {
334        self.local_static = opts;
335        self
336    }
337
338    pub fn with_pond(mut self, opts: pond::PondOptions) -> Self {
339        self.pond = opts;
340        self
341    }
342
343    /// Swap the [`ForgeExecutor`] used to run the build step. Production
344    /// callers take the [`LocalForgeDriver`] default; tests inject a mock
345    /// to assert the lowered [`ForgeSpec`] without spawning a subprocess.
346    pub fn with_executor(mut self, executor: Arc<dyn ForgeExecutor>) -> Self {
347        self.executor = executor;
348        self
349    }
350}
351
352impl Default for MesofactStaticReconciler {
353    fn default() -> Self {
354        Self::new()
355    }
356}
357
358#[async_trait]
359impl Reconciler for MesofactStaticReconciler {
360    fn kind(&self) -> &'static str {
361        WORKLOAD_KIND
362    }
363
364    async fn up(&self, ctx: ReconcileCtx<'_>) -> Result<RunningWorkload> {
365        // BYO git (R561-F1): if the component is git-sourced, shallow-clone it
366        // into the source cache before anything reads workload_dir(). No-op for
367        // in-tree components.
368        ctx.materialize().await?;
369
370        // Validate that the workload manifest agrees with the component's
371        // declared kind. Mismatch is an authoring error (service.toml
372        // points at a workload of the wrong shape).
373        let kind = ctx.workload_kind().context("loading workload.toml")?;
374        if kind != ctx.component.kind {
375            anyhow::bail!(
376                "component {component_id} kind=\"{component_kind}\" but {workload_dir}/workload.toml declares kind=\"{kind}\"",
377                component_id = ctx.component.id,
378                component_kind = ctx.component.kind,
379                workload_dir = ctx.workload_dir().display(),
380            );
381        }
382
383        let slot = ctx.slot("static").with_context(|| {
384            format!(
385                "mirror has no `providers.static` slot — required for kind=\"mesofact-static\" (service={}, env={})",
386                ctx.service.name, ctx.env,
387            )
388        })?;
389
390        match slot {
391            MirrorProviderSlot::Inline {
392                kind: Provider::LocalStatic,
393                fields,
394            } => {
395                let port = slot_field_u16(fields, "port").unwrap_or(DEFAULT_LOCAL_STATIC_PORT);
396                self.up_local_static(&ctx, port).await
397            }
398            MirrorProviderSlot::Inline {
399                kind: Provider::MiniflareContainer,
400                fields,
401            } => pond::up_pond(&ctx, &self.pond, fields, WORKER_SCRIPT).await,
402            MirrorProviderSlot::Inline { kind, .. } => {
403                anyhow::bail!(
404                    "providers.static.kind = \"{kind:?}\" not supported by mesofact-static reconciler (only local-static + miniflare-container for now)",
405                )
406            }
407            MirrorProviderSlot::Reference {
408                provider_id,
409                fields,
410            } => {
411                // Dispatch on the resolved provider *kind*, not the literal
412                // name, so a workspace can name several cloudflare providers
413                // (e.g. `cloudflare` + `cloudflare-scrabcake`).
414                let cf = super::cf_creds::CfProvider::resolve_scoped(
415                    ctx.workspace_root,
416                    provider_id,
417                    &ctx.scope.tenant,
418                    &ctx.scope.namespace,
419                )?;
420                anyhow::ensure!(
421                    matches!(cf.cfg.kind, Provider::Cloudflare),
422                    "providers.static.use = {provider_id:?} (kind={:?}) — only cloudflare-kind \
423                     reference providers are supported for mesofact-static",
424                    cf.cfg.kind,
425                );
426                self.up_cloudflare_r2(&ctx, cf, fields).await
427            }
428        }
429    }
430}
431
432impl MesofactStaticReconciler {
433    /// Re-sync a *running* mirror in place — re-publish the built dist without
434    /// rebuilding or restarting the serve stack. Only the pond
435    /// (miniflare-container) slot supports this: it re-publishes `dist/` into
436    /// the already-running MinIO bucket via [`pond::sync_pond`], returning the
437    /// number of assets uploaded.
438    ///
439    /// This is what the desktop's `⟳` affordance calls for local mirrors.
440    /// `up`'s desktop adopt path returns before the publish step, so a re-click
441    /// of `▶` never re-publishes; `sync` is the correct re-sync entry point.
442    /// local-static (dev) serves from disk and cloudflare goes through the
443    /// publish-assets pipeline, so neither has an in-place bucket re-sync.
444    pub async fn sync(&self, ctx: ReconcileCtx<'_>) -> Result<usize> {
445        ctx.materialize().await?;
446        let slot = ctx.slot("static").with_context(|| {
447            format!(
448                "mirror has no `providers.static` slot — required for kind=\"mesofact-static\" (service={}, env={})",
449                ctx.service.name, ctx.env,
450            )
451        })?;
452        match slot {
453            MirrorProviderSlot::Inline {
454                kind: Provider::MiniflareContainer,
455                fields,
456            } => pond::sync_pond(&ctx, &self.pond, fields).await,
457            MirrorProviderSlot::Inline { kind, .. } => anyhow::bail!(
458                "providers.static.kind = \"{kind:?}\" has no in-place re-sync — only miniflare-container (pond) supports ⟳ sync",
459            ),
460            MirrorProviderSlot::Reference { .. } => anyhow::bail!(
461                "reference (cloud) providers re-sync through the publish-assets pipeline, not the pond reconciler",
462            ),
463        }
464    }
465
466    /// Build the workload (re-running `build.command`) then publish it to its
467    /// configured provider slot.
468    ///
469    /// This is the **full rebuild** path — source/template changes, a fresh
470    /// `mirror up`, or any case where the compiled bundle itself may be
471    /// stale. It is *not* what `almanac_dispatch` calls for a data-only feed
472    /// change — see [`Self::revalidate_static`] for that (W225 §3: a data
473    /// change is "revalidate", not "build", and never needs the bundler).
474    ///
475    /// For the Cloudflare reference arm this publishes the freshly-built
476    /// `dist/` to R2 and purges the CDN cache-tag `page:releases`. For the
477    /// `local-static` arm the build still runs (useful for verifying the
478    /// output) but no publish happens — the watcher handles hot-reload.
479    pub async fn rebuild_static(&self, ctx: ReconcileCtx<'_>) -> Result<RunningWorkload> {
480        let workload_dir = ctx.workload_dir();
481        if let Some((build, build_mode)) = read_mesofact_build(&workload_dir)? {
482            // For the local-static arm, container build_mode is skipped — the host
483            // watcher drives rebuilds and dev machines may not have docker (W165 OQ#1).
484            let effective_mode = match &build_mode {
485                BuildMode::InContainer { .. }
486                    if ctx.slot("static").and_then(|s| s.inline_kind())
487                        == Some(Provider::LocalStatic) =>
488                {
489                    warn!(
490                        workload = %workload_dir.display(),
491                        "build_mode = in_container ignored for local-static; running host-side"
492                    );
493                    BuildMode::HostSide
494                }
495                _ => build_mode,
496            };
497            run_build(&workload_dir, &build, &effective_mode, &*self.executor).await?;
498        }
499        self.up(ctx).await
500    }
501
502    /// Publish the workload's **already-built** artifact directory — never
503    /// runs `build.command` (W225 §3, R535-T1).
504    ///
505    /// This is the path `almanac_dispatch` calls for
506    /// `OnChangeConfig::MesofactRebuild`: an almanac feed change is *data*,
507    /// not a source/template change, so re-running the bundler is wasted
508    /// work (and, for CI-gated `in_container` builds, wasted pull/cold-start
509    /// too). Per the doc: "almanac = revalidate = data → SSG output on the
510    /// already-built bundle... no recompilation, no CI gate, because nothing
511    /// executable changed."
512    ///
513    /// When the workload declares `build.render_command` (R535-T7), the
514    /// data-only re-render runs first — `{route}` substituted with the
515    /// invalidated route pattern, executed against the **already-built**
516    /// bundle via the same [`ForgeExecutor`] lowering as the build step
517    /// (host-side or in-container per `build_mode`), but never
518    /// `build.command` itself. The canonical command is `mesofact-build
519    /// render <dir> --route {route} --all`, which re-expands the route's
520    /// prerender params fresh and rewrites `out_dir`'s HTML for that route
521    /// only. Without `render_command` this republishes whatever bytes sit in
522    /// `build.out_dir` (the pre-T7 behavior, still correct when the bundle's
523    /// HTML was refreshed by some other actor).
524    ///
525    /// The `local-static` arm skips the render entirely — the host
526    /// `mesofact-dev` watcher already re-renders on data-file changes
527    /// independently of this reconciler (see the `rebuild_static` doc on the
528    /// pre-existing "local watcher handles rebuilds" behavior it inherits).
529    pub async fn revalidate_static(
530        &self,
531        ctx: ReconcileCtx<'_>,
532        route: &str,
533    ) -> Result<RunningWorkload> {
534        let workload_dir = ctx.workload_dir();
535        let is_local_static =
536            ctx.slot("static").and_then(|s| s.inline_kind()) == Some(Provider::LocalStatic);
537        if !is_local_static {
538            if let Some((build, build_mode)) = read_mesofact_build(&workload_dir)? {
539                if let Some(render_command) = &build.render_command {
540                    let render = BuildConfig {
541                        command: Some(render_command.replace("{route}", route)),
542                        out_dir: build.out_dir.clone(),
543                        render_command: None,
544                    };
545                    run_build(&workload_dir, &render, &build_mode, &*self.executor).await?;
546                }
547            }
548        }
549        self.up(ctx).await
550    }
551
552    async fn up_local_static(&self, ctx: &ReconcileCtx<'_>, port: u16) -> Result<RunningWorkload> {
553        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port);
554        let svc = &ctx.service.name;
555        let comp = &ctx.component.id;
556
557        // If a mesofact-dev server is already running on the configured port
558        // (e.g. a prior `mirror up` in this session), adopt it rather than
559        // spawning a second instance — keeps re-runs idempotent. But adopt ONLY
560        // when it identifies as THIS (service, component): a bare port probe is
561        // identity-blind, so a different service's dev server (or a foreign
562        // process) on a colliding host port would be silently hijacked and
563        // serve the wrong site (R602-B4). `/__mesofact/info` is the oracle;
564        // identity mismatch is a hard error, not a fall-through to spawn (the
565        // port is taken — there is nothing safe to do but surface it).
566        if let Some(adopted) = try_adopt_identified(addr, svc, comp, "configured").await? {
567            return Ok(adopted);
568        }
569
570        // Camp may have fallen back to a dynamic port (OS-assigned when configured
571        // port was taken). Check the jit ports file it writes after binding.
572        let jit_port = read_jit_port(ctx.workspace_root, &ctx.service.name, &ctx.component.id);
573        if let Some(actual_port) = jit_port {
574            if actual_port != port {
575                let actual_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), actual_port);
576                if let Some(adopted) =
577                    try_adopt_identified(actual_addr, svc, comp, "dynamic").await?
578                {
579                    return Ok(adopted);
580                }
581            }
582        }
583
584        if self.local_static.adopt_only {
585            let jit_note = jit_port
586                .filter(|&p| p != port)
587                .map(|p| format!(" (jit file recorded port {p} — also not bound)"))
588                .unwrap_or_default();
589
590            // Distinguish "camp not attached" from "camp up but server didn't bind"
591            // so the operator gets an actionable message.
592            let camp_live = self
593                .local_static
594                .camp_socket
595                .as_deref()
596                .map(is_unix_socket_live)
597                .unwrap_or(false);
598
599            if camp_live {
600                anyhow::bail!(
601                    "component {}: a yah daemon is up but mesofact-dev did not bind on port {}{} \
602                     — check that the mesofact-dev workload reconciled, or inspect its logs",
603                    ctx.component.id,
604                    port,
605                    jit_note,
606                );
607            } else {
608                anyhow::bail!(
609                    "component {}: mesofact-dev not running for this workspace \
610                     — attach the workspace in the desktop or run `yah camp` from a terminal",
611                    ctx.component.id,
612                );
613            }
614        }
615
616        let binary = self.local_static.resolved_binary();
617        let workload_dir = ctx.workload_dir();
618
619        // Prefer the configured port; fall back to OS-assigned when it's taken.
620        // Web entrypoints are browser handles — the port number itself doesn't
621        // matter to the operator, so floating to any free port is fine.
622        let spawn_port = {
623            let preferred = std::net::SocketAddr::new(
624                std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST),
625                port,
626            );
627            match std::net::TcpListener::bind(preferred) {
628                Ok(_probe) => {
629                    // Probe succeeded: preferred port is free. Drop the probe
630                    // so the child can bind it. Tiny race window; fine for dev.
631                    port
632                }
633                Err(_) => {
634                    let fallback = std::net::TcpListener::bind("127.0.0.1:0")
635                        .context("could not bind any port for mesofact-dev")?;
636                    let p = fallback.local_addr()?.port();
637                    if port != 0 {
638                        info!(
639                            preferred = port,
640                            actual = p,
641                            "preferred port taken; mesofact-dev will use OS-assigned port"
642                        );
643                    }
644                    p
645                }
646            }
647        };
648
649        // R490-F2: spawn mesofact-dev through kamaji's Native (fork+exec)
650        // backend rather than a bespoke Command::spawn. NativeRuntime owns the
651        // fork+exec, stdio capture, and SIGTERM→grace→SIGKILL teardown; the
652        // reconciler keeps only the WorkloadSpec lowering, the readiness probe,
653        // and a file-tail→LogBuffer bridge that preserves the Run-tab's live
654        // log surface (NativeRuntime captures stdio to files, not a pipe).
655        self.spawn_via_constable(ctx, &binary, &workload_dir, spawn_port)
656            .await
657    }
658
659    /// Lower the mesofact-dev invocation to a [`WorkloadSpec`], deploy it on a
660    /// per-bring-up [`NativeRuntime`], wait for the port, and wrap the result
661    /// in a [`RunningWorkload`] whose shutdown tears the workload back down.
662    async fn spawn_via_constable(
663        &self,
664        ctx: &ReconcileCtx<'_>,
665        binary: &Path,
666        workload_dir: &Path,
667        spawn_port: u16,
668    ) -> Result<RunningWorkload> {
669        // NativeRuntime captures stdout/stderr under <state_dir>/<ident>/.
670        // Scope it per-workspace so concurrent camps don't collide.
671        let state_dir = ctx.workspace_root.join(".yah/jit/native");
672        let ident_str = native_ident(&ctx.service.name, &ctx.component.id);
673        let ident = MeshIdent(ident_str.clone());
674
675        let mut argv: Vec<String> = vec![
676            binary.display().to_string(),
677            workload_dir.display().to_string(),
678            "--port".to_string(),
679            spawn_port.to_string(),
680            // Stamp logical identity so the child answers /__mesofact/info and a
681            // later adopt re-run can confirm the port holds *this* server rather
682            // than a colliding foreign listener (R602-B4).
683            "--service".to_string(),
684            ctx.service.name.clone(),
685            "--component".to_string(),
686            ctx.component.id.clone(),
687        ];
688        argv.extend(self.local_static.extra_args.iter().cloned());
689        let spec = native_spec(&ident_str, argv, Vec::new());
690
691        let runtime = Arc::new(NativeRuntime::new(&state_dir));
692        let mesh = MeshAssignment::inlined(Ipv4Addr::LOCALHOST);
693
694        info!(
695            binary = %binary.display(),
696            workload = %workload_dir.display(),
697            port = spawn_port,
698            ident = %ident_str,
699            "spawning mesofact-dev (kamaji native backend)",
700        );
701
702        let deployed = runtime
703            .deploy_workload(&spec, &mesh)
704            .await
705            .with_context(|| {
706                format!(
707                    "deploying mesofact-dev via kamaji native backend \
708                     — install with `cargo install --path oss/mesofact/crates/mesofact-dev` \
709                     or ensure the bundled sidecar is on the path ({})",
710                    binary.display(),
711                )
712            })?;
713
714        let (stdout_path, stderr_path) = capture_paths(&state_dir, &ident_str);
715
716        // Wait for the server to bind. If it doesn't, tear it down and return
717        // an error so the caller doesn't hand the UI a dead URL.
718        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), spawn_port);
719        let timeout = self
720            .local_static
721            .ready_timeout
722            .unwrap_or(Duration::from_secs(10));
723        if !wait_for_port(addr, timeout).await {
724            warn!(addr = %addr, "mesofact-dev did not bind within timeout; tearing down");
725            runtime.teardown_workload(&ident).await.ok();
726            anyhow::bail!("mesofact-dev failed to bind {addr} within {:?}", timeout);
727        }
728
729        let dev_url = format!("http://{addr}");
730        info!(dev_url = %dev_url, port = spawn_port, pid = deployed.task_pid, "mesofact-dev ready");
731
732        // Bridge NativeRuntime's file capture into the Run-tab LogBuffer and
733        // own teardown on shutdown.
734        let log_buf = LogBuffer::new();
735        let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>();
736        let supervisor = spawn_native_log_supervisor(
737            runtime,
738            ident,
739            log_buf.clone(),
740            stdout_path,
741            stderr_path,
742            shutdown_rx,
743        );
744
745        Ok(into_running(
746            "mesofact-static",
747            "static",
748            Some(dev_url),
749            None,
750            Some(log_buf),
751            shutdown_tx,
752            supervisor,
753        ))
754    }
755
756    /// Cloudflare R2 publish path: upload `dist/` to R2, optionally purge CDN
757    /// cache tags, and return a `RunningWorkload` with `public_url` set.
758    async fn up_cloudflare_r2(
759        &self,
760        ctx: &ReconcileCtx<'_>,
761        cf_provider: super::cf_creds::CfProvider,
762        slot_fields: &std::collections::BTreeMap<String, toml::Value>,
763    ) -> Result<RunningWorkload> {
764        use super::r2_publish::{publish_to_r2, R2PurgeOpts};
765        use crate::provider::cloudflare::{CloudflareClient, WorkerBinding};
766
767        // account_id + credentials come from the resolved provider.
768        let account_id = cf_provider.account_id.clone();
769
770        // Extract bucket + zone from the mirror's static slot.
771        let bucket = slot_fields
772            .get("bucket")
773            .and_then(|v| v.as_str())
774            .context("providers.static missing `bucket` field for cloudflare R2 publish")?
775            .to_string();
776        let zone = slot_fields
777            .get("zone")
778            .and_then(|v| v.as_str())
779            .context("providers.static missing `zone` field for cloudflare R2 publish")?
780            .to_string();
781
782        // asset_origin is the public HTTP URL the Worker fetches assets from.
783        // publish_to_r2 lays files down under `<svc>/<env>/<key>`, so this URL
784        // must include the same prefix. Validate up front — without it the
785        // Worker would 404 every request in prod.
786        let asset_origin =
787            slot_fields
788                .get("asset_origin")
789                .and_then(|v| v.as_str())
790                .filter(|s| !s.is_empty())
791                .with_context(|| {
792                    format!(
793                "providers.static.asset_origin missing or empty (service={svc}, env={env}) — \
794                 set it to the R2 public URL with the publish prefix, e.g. \
795                 \"https://cdn.{zone}/{svc}/{env}\"",
796                svc = ctx.service.name, env = ctx.env, zone = zone,
797            )
798                })?
799                .to_string();
800
801        // R2 S3 access keys (distinct from the management API token).
802        let (access_key, secret_key) = cf_provider.r2_keys()?;
803
804        // Management API token — used for cache-tag purge and Transform Rules.
805        // Optional: publish itself only needs the R2 S3 keys.
806        let cf_api_token: Option<String> = cf_provider.api_token_opt();
807        let purge = cf_api_token.clone().map(|token| R2PurgeOpts {
808            zone_name: zone.clone(),
809            api_token: token,
810        });
811
812        // Resolve dist dir from workload.toml build.out_dir (default: "dist").
813        let workload_dir = ctx.workload_dir();
814        let out_dir = read_workload_out_dir(&workload_dir).unwrap_or_else(|| "dist".to_string());
815        let dist_dir = workload_dir.join(&out_dir);
816
817        let mirror_prefix =
818            publish_prefix(&ctx.service.name, ctx.env, ctx.component.mount.as_deref());
819        let report = publish_to_r2(
820            &dist_dir,
821            &account_id,
822            &bucket,
823            &access_key,
824            &secret_key,
825            Some(&mirror_prefix),
826            purge,
827        )
828        .await
829        .with_context(|| format!("publishing to R2 bucket {bucket:?} (account {account_id})"))?;
830
831        info!(
832            uploaded = report.uploaded.len(),
833            purged = report.purged_tags.len(),
834            bucket,
835            zone,
836            "R2 publish complete",
837        );
838
839        // Deploy CF Worker script (replaces the Transform Rule workaround).
840        // Worker serves assets via ASSET_ORIGIN with mode-aware routing:
841        // static 404-fallback, SPA index.html fallback, or SSR proxy to origin.
842        // Non-fatal: warn if token lacks Workers Scripts: Edit scope.
843        if let Some(ref token) = cf_api_token {
844            let cf = CloudflareClient::new(token.clone());
845            let mode = parse_worker_mode(&ctx.component.kind, slot_fields);
846            let worker_name = slot_fields
847                .get("worker_name")
848                .and_then(|v| v.as_str())
849                .map(|s| s.to_string())
850                .unwrap_or_else(|| format!("{}-worker", ctx.service.name));
851            let backends = BackendOrigins::from_slot_fields(slot_fields);
852            let route_headers = crate::config::route_headers_for_service(
853                ctx.workspace_root,
854                &ctx.service.name,
855            )?;
856            let bindings =
857                worker_config_bindings(&mode, &asset_origin, &backends, &route_headers);
858            let worker_bindings: Vec<WorkerBinding<'_>> = bindings
859                .iter()
860                .map(|(k, v)| WorkerBinding::PlainText {
861                    name: k.as_str(),
862                    text: v.as_str(),
863                })
864                .collect();
865            // Hash script + bindings so config changes trigger redeploy.
866            let script_hash = {
867                let mut input = WORKER_SCRIPT.as_bytes().to_vec();
868                input.push(0);
869                input.extend_from_slice(
870                    serde_json::to_string(&bindings)
871                        .unwrap_or_default()
872                        .as_bytes(),
873                );
874                sha256_hex(&input)
875            };
876
877            let worker_result = async {
878                let zone_id = cf.zone_id_for_name(&zone).await?;
879
880                // Skip redeploy when script + config are unchanged across re-runs.
881                let cached = read_worker_script_hash(ctx.workspace_root, &worker_name);
882                if cached.as_deref() != Some(&script_hash) {
883                    cf.deploy_worker_script(
884                        &account_id,
885                        &worker_name,
886                        WORKER_SCRIPT,
887                        &worker_bindings,
888                    )
889                    .await?;
890                    let _ =
891                        write_worker_script_hash(ctx.workspace_root, &worker_name, &script_hash);
892                    info!(worker_name, "CF Worker script deployed");
893                } else {
894                    info!(
895                        worker_name,
896                        "CF Worker script unchanged — skipping redeploy"
897                    );
898                }
899
900                // Upsert zone route: `{zone}/*` → worker script.
901                let route_pattern = format!("{zone}/*");
902                cf.upsert_worker_route(&zone_id, &route_pattern, &worker_name)
903                    .await?;
904                anyhow::Ok(())
905            }
906            .await;
907
908            // R703-B4 — how loudly this fails depends on whether the Worker is
909            // the door the public actually comes through.
910            //
911            // It was unconditionally non-fatal, and that is how the yah.dev
912            // Worker ended up 19 days behind the router bundle in-tree: the
913            // token lacked `Workers Scripts: Edit`, every apply warned into a
914            // logger the CLI never installed, and every apply reported ok. A
915            // front door that cannot be updated is not a warning — it is the
916            // failure. When the zone's manifest declares `front_door =
917            // "worker"`, a failed deploy is fatal.
918            //
919            // For any other declared front door the Worker is a warm rollback
920            // lever rather than the live door, so a warning remains right: it
921            // should not be able to fail an apply for a surface serving no
922            // traffic.
923            if let Err(e) = worker_result {
924                let is_live_front_door = matches!(
925                    super::publish_beacon::declared_front_door(ctx.workspace_root, &zone),
926                    Some((_, crate::config::FrontDoor::Worker))
927                );
928                if is_live_front_door {
929                    return Err(e).with_context(|| {
930                        format!(
931                            "deploying the Cloudflare Worker for {zone} (script {worker_name}).\n\
932                         \n\
933                         .yah/domains/*.toml declares front_door = \"worker\" for this zone, so \
934                         this Worker IS the public front door — it cannot be left at whatever \
935                         version happens to be deployed. The publish above succeeded; what \
936                         failed is updating the thing that serves it.\n\
937                         \n\
938                         An `Authentication error` here means the configured Cloudflare \
939                         token cannot touch Workers. Test that DIRECTLY — a token-validity \
940                         check will not tell you, because the token is almost certainly \
941                         valid and merely under-scoped:\n\
942                         \n\
943                           curl -sS -H \"Authorization: Bearer $(yah keys get <slot>)\" \\\n\
944                             https://api.cloudflare.com/client/v4/accounts/<acct>/workers/scripts\n\
945                         \n\
946                         DO NOT reach for https://api.cloudflare.com/client/v4/user/tokens/verify \
947                         to triage this. An account-scoped token (`cfat_` prefix) is rejected \
948                         there with a flat `code 1000, Invalid API Token`, which reads \
949                         exactly like a revoked credential and sends you hunting for a token \
950                         that is fine. That misdiagnosis has now happened twice. The valid \
951                         health check for an account token is \
952                         /accounts/<acct>/tokens/verify.\n\
953                         \n\
954                         THE FIX, if the workers/scripts GET is denied: mint a token that \
955                         carries the grants, rather than editing one by hand —\n\
956                         \n\
957                           yah cloud cf token create --zone <zone> \\\n\
958                             --store-slot cloudflare-mesofact-static \\\n\
959                             --bootstrap-slot <a slot holding API Tokens: Edit>\n\
960                         \n\
961                         then point `credentials` in .yah/infra/providers/cloudflare.toml at \
962                         that slot. It builds MESOFACT_STATIC_GRANTS, which includes \
963                         `Workers Scripts: Write` (account) and `Workers Routes: Write` \
964                         (zone). The command's own summary line prints only five scopes and \
965                         omits both — that text is stale, the policy is not.\n\
966                         \n\
967                         Whatever the cause, it is silent everywhere else: the R2 publish \
968                         uses separate S3 keys and keeps working, so the bucket stays \
969                         current while the Worker — the thing that serves it — freezes."
970                        )
971                    });
972                }
973                warn!(
974                    zone,
975                    worker_name,
976                    error = %e,
977                    "CF Worker deploy/route failed (non-fatal — this zone's declared \
978                     front door is not the Worker, so it serves no traffic today) — \
979                     ensure cloudflare-api-token has Workers Scripts: Edit \
980                     and Zone Workers Routes: Edit scope"
981                );
982            }
983        }
984
985        // R703-B4 — the publish is not the deliverable; the served page is.
986        self.verify_serving(ctx, slot_fields, &zone, &asset_origin, &report.beacon)
987            .await?;
988
989        Ok(RunningWorkload::adopted("mesofact-static", "static", None)
990            .with_public_url(format!("https://{zone}")))
991    }
992
993    /// Fetch the just-written publish beacon back through the origin and the
994    /// public front door, and fail the apply if the front door is serving
995    /// anything else.
996    ///
997    /// R703-B4. Everything upstream of here reports success on the *write*:
998    /// R2 accepted the objects, the Worker API accepted the script, the apply
999    /// exits 0. None of that is evidence that the bytes reached a reader, and
1000    /// twice now they did not — once because a declared-but-unready bundle
1001    /// tier disabled this chain, once because the apex had been cut over to an
1002    /// origin nothing republishes. Both presented as HTTP 200 on a stale page.
1003    ///
1004    /// The origin probe is checked first and separately on purpose: it splits
1005    /// "the publish did not land" from "the publish landed and the front door
1006    /// is elsewhere", which are different tickets with identical symptoms.
1007    async fn verify_serving(
1008        &self,
1009        ctx: &ReconcileCtx<'_>,
1010        slot_fields: &std::collections::BTreeMap<String, toml::Value>,
1011        zone: &str,
1012        asset_origin: &str,
1013        beacon: &super::publish_beacon::PublishBeacon,
1014    ) -> Result<()> {
1015        use super::publish_beacon as pb;
1016
1017        // Opt-out for a deliberately in-flight front-door migration. Declared
1018        // in config rather than passed as a CLI flag so that turning it off is
1019        // a reviewable diff next to a comment naming the ticket, not an
1020        // invocation habit that quietly becomes permanent.
1021        let verify = slot_fields
1022            .get("verify_serving")
1023            .and_then(|v| v.as_bool())
1024            .unwrap_or(true);
1025        if !verify {
1026            warn!(
1027                zone,
1028                "verify_serving = false — publish NOT checked against the live \
1029                 front door; the site can go stale without this apply failing"
1030            );
1031            return Ok(());
1032        }
1033
1034        let verdict = pb::check_serving(
1035            ctx.workspace_root,
1036            zone,
1037            Some(asset_origin),
1038            beacon,
1039            pb::EDGE_PROBE_ATTEMPTS,
1040            pb::EDGE_PROBE_DELAY,
1041        )
1042        .await;
1043
1044        if verdict.is_ok() {
1045            info!(
1046                zone,
1047                digest = %beacon.digest,
1048                files = beacon.files,
1049                "front door is serving this publish"
1050            );
1051            return Ok(());
1052        }
1053
1054        // A stale or absent front door means the deployed Worker (if any) may
1055        // be older than the bundle this build embeds, and the local hash cache
1056        // would otherwise skip redeploying it forever — that cache is a claim
1057        // about the live Worker made from an untracked file on one laptop.
1058        // Drop the entry so the next apply cannot take the skip branch.
1059        if !verdict.front_door.is_match() {
1060            let worker_name = slot_fields
1061                .get("worker_name")
1062                .and_then(|v| v.as_str())
1063                .map(|s| s.to_string())
1064                .unwrap_or_else(|| format!("{}-worker", ctx.service.name));
1065            forget_worker_script_hash(ctx.workspace_root, &worker_name);
1066        }
1067
1068        Err(verdict.into_error(beacon))
1069    }
1070}
1071
1072/// Read the `[build]` + `[build_mode]` subtrees from
1073/// `<workload_dir>/workload.toml`. Used by [`MesofactStaticReconciler::rebuild_static`]
1074/// to drive [`run_build`] without forcing the whole workload through the
1075/// `workload_spec::Workload` envelope — many in-tree workload manifests
1076/// still carry `schema_version = 1` (integer) which the typed envelope
1077/// rejects. Parsing only the subtrees we use keeps this path tolerant of
1078/// the legacy shape while still giving us typed [`BuildConfig`] and
1079/// [`BuildMode`] values to lower.
1080///
1081/// Returns:
1082/// - `Ok(None)` when `workload.toml` is absent, isn't a `mesofact-static`
1083///   workload, or has no `[build]` table — `rebuild_static` then skips the
1084///   build step (the subsequent `up()` will surface the missing-manifest
1085///   error if relevant).
1086/// - `Ok(Some((build, build_mode)))` on success; `build_mode` defaults to
1087///   `HostSide` when the field is absent.
1088fn read_mesofact_build(workload_dir: &std::path::Path) -> Result<Option<(BuildConfig, BuildMode)>> {
1089    let path = workload_dir.join("workload.toml");
1090    let src = match std::fs::read_to_string(&path) {
1091        Ok(s) => s,
1092        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1093        Err(e) => return Err(anyhow::Error::new(e).context(format!("reading {}", path.display()))),
1094    };
1095    let value: toml::Value =
1096        toml::from_str(&src).with_context(|| format!("parsing {}", path.display()))?;
1097
1098    if value.get("kind").and_then(|v| v.as_str()) != Some(WORKLOAD_KIND) {
1099        return Ok(None);
1100    }
1101
1102    let Some(build_value) = value.get("build") else {
1103        return Ok(None);
1104    };
1105    let build: BuildConfig = build_value
1106        .clone()
1107        .try_into()
1108        .with_context(|| format!("parsing [build] table in {}", path.display()))?;
1109
1110    let build_mode = match value.get("build_mode") {
1111        Some(v) => v
1112            .clone()
1113            .try_into()
1114            .with_context(|| format!("parsing [build_mode] table in {}", path.display()))?,
1115        None => BuildMode::default(),
1116    };
1117
1118    Ok(Some((build, build_mode)))
1119}
1120
1121/// Lower (`build`, `build_mode`) to a [`ForgeSpec`] (W165).
1122///
1123/// - [`BuildMode::HostSide`] → `TaskRuntime::Native`, `image=None` — the
1124///   build inherits the host's PATH and toolchain.
1125/// - [`BuildMode::InContainer { image }`] → `TaskRuntime::Container` with
1126///   the pinned image attached to the `Subprocess` command. The executor
1127///   bind-mounts `workload_dir` as the container's working directory via
1128///   the [`ExecContext`] passed alongside.
1129///
1130/// `None` when the manifest declares no `build.command` (R838-B1) — there is
1131/// no subprocess to lower, because the project builds through the in-process
1132/// `mesofact-dev` pipeline rather than an external bundler. Callers skip the
1133/// build step rather than lowering an empty `sh -c ""`, which would "succeed"
1134/// having produced nothing.
1135///
1136/// Pure function: no I/O, no subprocess. Exposed at `pub(crate)` for
1137/// golden-test parity with the recipe-lowering helper (R438-T7).
1138pub(crate) fn lower_build_to_forge_spec(
1139    workload_dir: &std::path::Path,
1140    build: &BuildConfig,
1141    build_mode: &BuildMode,
1142) -> Option<ForgeSpec> {
1143    let command = build.command.clone()?;
1144    let (image, runtime) = match build_mode {
1145        BuildMode::HostSide => (None, TaskRuntime::Native),
1146        BuildMode::InContainer { image } => (Some(image.clone()), TaskRuntime::Container),
1147    };
1148    Some(ForgeSpec {
1149        command: ForgeCommand::Subprocess {
1150            argv: vec!["sh".into(), "-c".into(), command],
1151            image,
1152        },
1153        where_: TaskPlacement::new(TaskLocation::Local, runtime),
1154        timeout: None,
1155        label: Some(format!("mesofact-static-build:{}", workload_dir.display())),
1156        initiator: Initiator::Gnome {
1157            camp: "mesofact-static-reconciler".into(),
1158            shift: "build".into(),
1159        },
1160        mesh_access: MeshAccess::default(),
1161    })
1162}
1163
1164/// Lower (`build`, `build_mode`) to a [`ForgeSpec`] and run it through the
1165/// supplied [`ForgeExecutor`] (W165). Thin wrapper over
1166/// [`lower_build_to_forge_spec`] — separated so the lowering is testable
1167/// without spawning a subprocess.
1168///
1169/// A manifest with no `build.command` is a no-op here (R838-B1): the project
1170/// has no external bundler step, so there is nothing for this reconciler to
1171/// shell out to. Same outcome as a workload with no `workload.toml` at all,
1172/// which `rebuild_static` has always skipped.
1173async fn run_build(
1174    workload_dir: &std::path::Path,
1175    build: &BuildConfig,
1176    build_mode: &BuildMode,
1177    executor: &dyn ForgeExecutor,
1178) -> Result<()> {
1179    let mode_tag = match build_mode {
1180        BuildMode::HostSide => "host_side",
1181        BuildMode::InContainer { .. } => "in_container",
1182    };
1183    let Some(spec) = lower_build_to_forge_spec(workload_dir, build, build_mode) else {
1184        tracing::info!(
1185            workload = %workload_dir.display(),
1186            "workload.toml declares no [build] command — skipping the build step \
1187             (the project builds in-process)"
1188        );
1189        return Ok(());
1190    };
1191    let cmd_str = build
1192        .command
1193        .clone()
1194        .expect("lower_build_to_forge_spec returns Some only when command is Some");
1195    tracing::info!(
1196        workload = %workload_dir.display(),
1197        cmd = %cmd_str,
1198        mode = mode_tag,
1199        "running mesofact-static build"
1200    );
1201
1202    let exec_ctx = ExecContext::default().with_cwd(workload_dir.to_path_buf());
1203
1204    let outcome = executor
1205        .execute(spec, exec_ctx, None)
1206        .await
1207        .with_context(|| format!("executing build command: {cmd_str}"))?;
1208
1209    if !outcome.succeeded() {
1210        anyhow::bail!(
1211            "build command failed ({}): {} — {}",
1212            outcome.status.discriminant(),
1213            cmd_str,
1214            outcome.stderr_tail,
1215        );
1216    }
1217    Ok(())
1218}
1219
1220/// Read `build.out_dir` from a workload's `workload.toml`. Returns `None`
1221/// when the file is absent, unreadable, or the field is missing — callers
1222/// default to `"dist"`.
1223pub(crate) fn read_workload_out_dir(workload_dir: &std::path::Path) -> Option<String> {
1224    let path = workload_dir.join("workload.toml");
1225    let src = std::fs::read_to_string(&path).ok()?;
1226    let value: toml::Value = toml::from_str(&src).ok()?;
1227    value
1228        .get("build")?
1229        .get("out_dir")?
1230        .as_str()
1231        .map(str::to_string)
1232}
1233
1234// ---------- CF Worker script rendering ----------
1235
1236/// Routing mode baked into the Worker script at deploy time. Shared between
1237/// the Cloudflare-Worker arm (this file) and the pond arm via `pub` so camp's
1238/// `build_miniflare_deploy_spec` can derive the same mode from a mirror's
1239/// static slot when populating `local_driver::pond_miniflare::MiniflareSpec`.
1240pub enum WorkerMode {
1241    /// All routes served from R2; `/` and directory paths → `index.html`;
1242    /// unknown paths → `404.html` (if present) or a 404 response.
1243    Static,
1244    /// Unknown paths fall back to `index.html` for client-side routing.
1245    Spa,
1246    /// Paths matching `prefixes` are proxied to `origin_url`; the rest uses
1247    /// the SPA index.html fallback.
1248    Ssr {
1249        origin_url: String,
1250        prefixes: Vec<String>,
1251    },
1252}
1253
1254/// Parse the Worker routing mode from the mirror's static slot fields. Public
1255/// so camp's pond bring-up can mirror the cloudflare-arm semantics without
1256/// duplicating the field-name conventions.
1257///
1258/// When the slot declares no explicit `mode`, the default derives from the
1259/// component's kind: `mesofact-spa` → SPA fallback, everything else → static.
1260/// An explicit `mode` field always wins.
1261pub fn parse_worker_mode(
1262    component_kind: &str,
1263    fields: &std::collections::BTreeMap<String, toml::Value>,
1264) -> WorkerMode {
1265    let default_mode = if component_kind == WORKLOAD_KIND_SPA {
1266        "spa"
1267    } else {
1268        "static"
1269    };
1270    match fields
1271        .get("mode")
1272        .and_then(|v| v.as_str())
1273        .unwrap_or(default_mode)
1274    {
1275        "spa" => WorkerMode::Spa,
1276        "ssr" => {
1277            let origin_url = fields
1278                .get("origin_url")
1279                .and_then(|v| v.as_str())
1280                .unwrap_or_default()
1281                .to_string();
1282            let prefixes = fields
1283                .get("ssr_prefixes")
1284                .and_then(|v| v.as_array())
1285                .map(|a| {
1286                    a.iter()
1287                        .filter_map(|v| v.as_str().map(String::from))
1288                        .collect()
1289                })
1290                .unwrap_or_default();
1291            WorkerMode::Ssr {
1292                origin_url,
1293                prefixes,
1294            }
1295        }
1296        _ => WorkerMode::Static,
1297    }
1298}
1299
1300/// Backend origins the edge router proxies `/api/*` prefixes to (R455-T4).
1301///
1302/// Distinct from `SSR_ORIGIN`: SSR proxies *page* routes to a renderer, these
1303/// proxy *API* routes to a service that owns state. Both are read off the
1304/// mirror's static slot (`issues_origin` / `backend_origin`).
1305///
1306/// These MUST be emitted here rather than set by hand on the Worker. Every
1307/// apply re-uploads the whole binding list, so a binding this function does
1308/// not produce is *deleted* on the next `yah cloud apply` — which is how a
1309/// hand-set `ISSUES_ORIGIN` silently reverts to a 404 (R330-F13, R752-B2).
1310#[derive(Debug, Clone, Default, PartialEq, Eq)]
1311pub struct BackendOrigins {
1312    /// `ISSUES_ORIGIN` — issue-tracker surface; `/api/issues*` proxied here.
1313    pub issues: String,
1314    /// `MESOFACT_BACKEND_ORIGIN` — almanac surface; `/api/releases*`.
1315    pub releases: String,
1316}
1317
1318impl BackendOrigins {
1319    /// Read the optional backend-origin fields off a mirror's static slot.
1320    /// Absent or empty → an empty binding, and the router's `env.X &&` guard
1321    /// leaves that prefix unrouted (a real 404, never a half-configured proxy).
1322    pub fn from_slot_fields(fields: &std::collections::BTreeMap<String, toml::Value>) -> Self {
1323        let field = |name: &str| {
1324            fields
1325                .get(name)
1326                .and_then(|v| v.as_str())
1327                .unwrap_or_default()
1328                .trim_end_matches('/')
1329                .to_string()
1330        };
1331        Self {
1332            issues: field("issues_origin"),
1333            releases: field("backend_origin"),
1334        }
1335    }
1336}
1337
1338/// The R2 key prefix a static component publishes under (R746).
1339///
1340/// `<service>/<env>` for an unmounted component — every pre-R746 component, and
1341/// the only shape `asset_origin` in a mirror manifest is written against.
1342/// `mount` appends its normalized form, which is what lets two static
1343/// components of one service coexist: before it, both wrote `index.html` to the
1344/// same key and the second deploy of the day silently replaced the first site
1345/// with the other.
1346///
1347/// The front door resolves a request by its own path (`${ASSET_ORIGIN}/<path>`),
1348/// so the mount is simultaneously the storage prefix and the URL prefix — by
1349/// construction, not by two manifests agreeing.
1350fn publish_prefix(service: &str, env: &str, mount: Option<&str>) -> String {
1351    let base = format!("{service}/{env}");
1352    match mount.map(crate::config::normalize_mount) {
1353        None => base,
1354        Some(m) if m.is_empty() => base,
1355        Some(m) => format!("{base}/{m}"),
1356    }
1357}
1358
1359/// Build the plain_text Worker binding values for the given routing mode.
1360///
1361/// These are uploaded alongside [`WORKER_SCRIPT`] as `plain_text` bindings
1362/// and appear as `env.ASSET_ORIGIN`, `env.WORKER_MODE`, etc. inside the Worker.
1363fn worker_config_bindings(
1364    mode: &WorkerMode,
1365    asset_origin: &str,
1366    backends: &BackendOrigins,
1367    route_headers: &str,
1368) -> Vec<(String, String)> {
1369    let (mode_str, ssr_origin, ssr_prefixes) = match mode {
1370        WorkerMode::Static => ("static", String::new(), "[]".to_string()),
1371        WorkerMode::Spa => ("spa", String::new(), "[]".to_string()),
1372        WorkerMode::Ssr {
1373            origin_url,
1374            prefixes,
1375        } => (
1376            "ssr",
1377            origin_url.clone(),
1378            serde_json::to_string(prefixes).unwrap_or_else(|_| "[]".to_string()),
1379        ),
1380    };
1381    vec![
1382        ("ASSET_ORIGIN".to_string(), asset_origin.to_string()),
1383        // Pointer-store origin for instance-addressed routes (W270 §3): the
1384        // @mesofact/edge worker reads `p/<key>` records here. Pointers live
1385        // under the `p/` prefix in the same bucket as content, so this defaults
1386        // to ASSET_ORIGIN; it stays a distinct binding so a future consumer can
1387        // front the (uncached) pointer reads separately.
1388        ("POINTER_ORIGIN".to_string(), asset_origin.to_string()),
1389        // Reserved upload seam (R490-T8): prod has no upload origin yet, so the
1390        // binding is empty and the Worker returns 404 on /uploads/*. A future
1391        // dynamic-bucket consumer sets this to the user-writable origin.
1392        ("UPLOAD_ORIGIN".to_string(), String::new()),
1393        ("WORKER_MODE".to_string(), mode_str.to_string()),
1394        ("SSR_ORIGIN".to_string(), ssr_origin),
1395        ("SSR_PREFIXES".to_string(), ssr_prefixes),
1396        ("ISSUES_ORIGIN".to_string(), backends.issues.clone()),
1397        (
1398            "MESOFACT_BACKEND_ORIGIN".to_string(),
1399            backends.releases.clone(),
1400        ),
1401        // R746: per-route response headers, straight from the domain manifest's
1402        // route table (`DomainConfig::route_headers_json`). `"[]"` when no
1403        // domain routes this service or none of its routes declare headers —
1404        // the Worker then leaves every response untouched.
1405        ("ROUTE_HEADERS".to_string(), route_headers.to_string()),
1406    ]
1407}
1408
1409fn sha256_hex(data: &[u8]) -> String {
1410    use sha2::Digest;
1411    hex::encode(sha2::Sha256::digest(data))
1412}
1413
1414/// Read the last deployed Worker script hash from the jit cache.
1415fn read_worker_script_hash(workspace_root: &std::path::Path, worker_name: &str) -> Option<String> {
1416    let path = workspace_root.join(".yah/jit/worker-script-hashes.json");
1417    let s = std::fs::read_to_string(&path).ok()?;
1418    let map: serde_json::Map<String, serde_json::Value> = serde_json::from_str(&s).ok()?;
1419    map.get(worker_name)
1420        .and_then(|v| v.as_str())
1421        .map(|s| s.to_string())
1422}
1423
1424/// Write the deployed Worker script hash to the jit cache.
1425fn write_worker_script_hash(
1426    workspace_root: &std::path::Path,
1427    worker_name: &str,
1428    hash: &str,
1429) -> std::io::Result<()> {
1430    let path = workspace_root.join(".yah/jit/worker-script-hashes.json");
1431    let mut map: serde_json::Map<String, serde_json::Value> = if path.exists() {
1432        std::fs::read_to_string(&path)
1433            .ok()
1434            .and_then(|s| serde_json::from_str(&s).ok())
1435            .unwrap_or_default()
1436    } else {
1437        serde_json::Map::new()
1438    };
1439    map.insert(
1440        worker_name.to_string(),
1441        serde_json::Value::String(hash.to_string()),
1442    );
1443    if let Some(parent) = path.parent() {
1444        std::fs::create_dir_all(parent)?;
1445    }
1446    std::fs::write(
1447        &path,
1448        serde_json::to_string_pretty(&serde_json::Value::Object(map)).unwrap_or_default(),
1449    )
1450}
1451
1452/// Drop a Worker's cached script hash so the next reconcile redeploys it.
1453///
1454/// R703-B4. The cache at `.yah/jit/worker-script-hashes.json` is an untracked
1455/// local file asserting something about a *remote* Worker, so it can be right
1456/// on one machine and wrong on the next — and while it is wrong, every apply
1457/// takes the "unchanged — skipping redeploy" branch and the live Worker never
1458/// catches up. It sat 19 days behind the in-tree router bundle that way. When
1459/// the front door is demonstrably not serving the current publish, the cache
1460/// has lost the right to be believed.
1461///
1462/// Best-effort: a cache we could not clear only costs one more manual redeploy,
1463/// and the serving check that called us is already returning an error.
1464fn forget_worker_script_hash(workspace_root: &std::path::Path, worker_name: &str) {
1465    let path = workspace_root.join(".yah/jit/worker-script-hashes.json");
1466    let Ok(s) = std::fs::read_to_string(&path) else {
1467        return;
1468    };
1469    let Ok(mut map) = serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(&s) else {
1470        return;
1471    };
1472    if map.remove(worker_name).is_none() {
1473        return;
1474    }
1475    let _ = std::fs::write(
1476        &path,
1477        serde_json::to_string_pretty(&serde_json::Value::Object(map)).unwrap_or_default(),
1478    );
1479    warn!(
1480        worker_name,
1481        "cleared cached Worker script hash — next apply will redeploy the script"
1482    );
1483}
1484
1485/// Return `true` when a Unix-domain socket at `path` accepts connections.
1486/// Uses a blocking connect so it can be called from sync or async context
1487/// without spawning a task. The connect attempt is instantaneous for a live
1488/// listener and fails immediately for a missing/stale socket file.
1489#[cfg(unix)]
1490fn is_unix_socket_live(path: &std::path::Path) -> bool {
1491    std::os::unix::net::UnixStream::connect(path).is_ok()
1492}
1493
1494#[cfg(not(unix))]
1495fn is_unix_socket_live(_path: &std::path::Path) -> bool {
1496    false
1497}
1498
1499/// Adopt a mesofact-dev already listening on `addr` — but only when it
1500/// identifies as `(expected_service, expected_component)` via `/__mesofact/info`
1501/// (R602-B4). Returns:
1502/// - `Ok(None)` — nothing is listening on `addr` (caller falls through to the
1503///   next candidate / spawns a fresh server).
1504/// - `Ok(Some(_))` — a matching mesofact-dev is running; adopt it.
1505/// - `Err(_)` — a listener is present but is a *different* service/component,
1506///   or is not an identifiable mesofact-dev at all. Adoption is refused; the
1507///   port is taken by a foreign workload, so there is nothing to spawn — surface
1508///   the collision instead of silently serving the wrong site.
1509///
1510/// `label` distinguishes the "configured" vs jit "dynamic" port in logs.
1511async fn try_adopt_identified(
1512    addr: SocketAddr,
1513    expected_service: &str,
1514    expected_component: &str,
1515    label: &str,
1516) -> Result<Option<RunningWorkload>> {
1517    // Liveness gate first: no listener → nothing to adopt (spawn path).
1518    if tokio::net::TcpStream::connect(addr).await.is_err() {
1519        return Ok(None);
1520    }
1521
1522    match probe_dev_identity(addr).await {
1523        Some((svc, comp)) if svc == expected_service && comp == expected_component => {
1524            let dev_url = format!("http://{addr}");
1525            info!(
1526                dev_url = %dev_url,
1527                port = addr.port(),
1528                %label,
1529                "mesofact-dev already running; identity matches, adopting"
1530            );
1531            Ok(Some(RunningWorkload::adopted(
1532                "mesofact-static",
1533                "static",
1534                Some(dev_url),
1535            )))
1536        }
1537        Some((svc, comp)) => anyhow::bail!(
1538            "port {} is serving {svc}/{comp}, but component {expected_component} of service \
1539             {expected_service} expected it — refusing to adopt another workload's dev server. \
1540             This is a host-port collision; give each service a distinct port \
1541             (check `.yah/services/*/mirrors/*.toml`, or run `yah cloud validate`).",
1542            addr.port(),
1543        ),
1544        None => anyhow::bail!(
1545            "port {} is occupied by a process that is not an identifiable mesofact-dev \
1546             (no /__mesofact/info) — refusing to adopt a foreign listener for component \
1547             {expected_component} of service {expected_service}. Free the port or point this \
1548             component at an unused one.",
1549            addr.port(),
1550        ),
1551    }
1552}
1553
1554/// Query `GET http://{addr}/__mesofact/info` and return the server's logical
1555/// `(service, component)` identity. `None` when the endpoint is unreachable,
1556/// non-2xx (older/identity-less mesofact-dev, or a foreign server), or the body
1557/// is not the expected JSON shape. Short timeout — this is a loopback probe on
1558/// the reconcile hot path.
1559async fn probe_dev_identity(addr: SocketAddr) -> Option<(String, String)> {
1560    let url = format!("http://{addr}/__mesofact/info");
1561    let resp = reqwest::Client::new()
1562        .get(&url)
1563        .timeout(Duration::from_secs(2))
1564        .send()
1565        .await
1566        .ok()?;
1567    if !resp.status().is_success() {
1568        return None;
1569    }
1570    let body: serde_json::Value = resp.json().await.ok()?;
1571    let svc = body.get("service")?.as_str()?.to_string();
1572    let comp = body.get("component")?.as_str()?.to_string();
1573    Some((svc, comp))
1574}
1575
1576/// Read the actual port recorded in `.yah/jit/mesofact-dev-ports.json` after
1577/// a mesofact-dev bind. Returns `None` when the file is absent or the entry
1578/// is missing. `pub` since R490 follow-through: the desktop's dev-cell
1579/// observation probes this port when the camp's `mesofact_dev.list` has no
1580/// entry (the camp stopped spawning mesofact-dev in R490-F2, so its list no
1581/// longer sees desktop-spawned processes).
1582pub fn read_jit_port(workspace_root: &std::path::Path, svc: &str, component: &str) -> Option<u16> {
1583    let path = workspace_root
1584        .join(".yah")
1585        .join("jit")
1586        .join("mesofact-dev-ports.json");
1587    let s = std::fs::read_to_string(&path).ok()?;
1588    let map: serde_json::Map<String, serde_json::Value> = serde_json::from_str(&s).ok()?;
1589    map.get(&format!("{svc}/{component}"))
1590        .and_then(|v| v.as_u64())
1591        .and_then(|n| u16::try_from(n).ok())
1592}
1593
1594/// mesofact-dev's ident namespace: `mesofact-dev-<service>-<component>`,
1595/// sanitized by [`sanitize_ident`] into a slug that is both DNS-segment shaped
1596/// (kamaji's contract) and safe as a path component (NativeRuntime joins it
1597/// under its state dir).
1598fn native_ident(service: &str, component: &str) -> String {
1599    sanitize_ident(&format!("mesofact-dev-{service}-{component}"))
1600}
1601
1602#[cfg(test)]
1603mod tests {
1604    use super::*;
1605    use crate::{MirrorConfig, MirrorShape, ServiceComponent, ServiceConfig};
1606    use std::collections::BTreeMap;
1607    use tempfile::tempdir;
1608
1609    /// Build a minimal in-memory ctx for unit tests, with the component's
1610    /// workload dir set up to look like a mesofact-static workload.
1611    struct Fixture {
1612        _workspace: tempfile::TempDir,
1613        workspace_root: PathBuf,
1614        service: ServiceConfig,
1615        component: ServiceComponent,
1616        mirror: MirrorConfig,
1617        env: String,
1618    }
1619
1620    impl Fixture {
1621        fn new(slot: MirrorProviderSlot, write_workload: bool) -> Self {
1622            let workspace = tempdir().unwrap();
1623            let workspace_root = workspace.path().to_path_buf();
1624            let workload_dir = workspace_root.join("app/web");
1625            std::fs::create_dir_all(workload_dir.join("dist/html")).unwrap();
1626            std::fs::write(workload_dir.join("dist/html/index.html"), "<h1>x</h1>").unwrap();
1627            if write_workload {
1628                std::fs::write(
1629                    workload_dir.join("workload.toml"),
1630                    r#"schema_version = 1
1631kind = "mesofact-static"
1632routes = "./routes.ts"
1633
1634[build]
1635command = "echo built"
1636out_dir = "dist"
1637"#,
1638                )
1639                .unwrap();
1640            }
1641
1642            let mut providers = BTreeMap::new();
1643            providers.insert("static".to_string(), slot);
1644            let mirror = MirrorConfig {
1645                schema_version: 1,
1646                shape: MirrorShape::Local,
1647                providers,
1648                ingress: Default::default(),
1649                ingress_machines: Vec::new(),
1650                drivers: Default::default(),
1651                asset_aliases: Default::default(),
1652            };
1653            let service = ServiceConfig {
1654                schema_version: 1,
1655                name: "test-svc".to_string(),
1656                domain: "test.local".to_string(),
1657                components: vec![],
1658                db: crate::DbCatalog::default(),
1659            };
1660            let component = ServiceComponent {
1661                mount: None,
1662                id: "site".to_string(),
1663                kind: "mesofact-static".to_string(),
1664                path: "app/web".to_string(),
1665                role: "static".to_string(),
1666                publishes: None,
1667                wave: 0,
1668                git: None,
1669            };
1670            Self {
1671                _workspace: workspace,
1672                workspace_root,
1673                service,
1674                component,
1675                mirror,
1676                env: "local".to_string(),
1677            }
1678        }
1679
1680        fn ctx(&self) -> ReconcileCtx<'_> {
1681            ReconcileCtx {
1682                workspace_root: &self.workspace_root,
1683                service: &self.service,
1684                component: &self.component,
1685                mirror: &self.mirror,
1686                env: &self.env,
1687                scope: crate::reconciler::ProviderScope::singleton(),
1688            }
1689        }
1690    }
1691
1692    fn local_static_slot(port: u16) -> MirrorProviderSlot {
1693        let mut fields = BTreeMap::new();
1694        fields.insert("port".to_string(), toml::Value::Integer(port as i64));
1695        MirrorProviderSlot::Inline {
1696            kind: Provider::LocalStatic,
1697            fields,
1698        }
1699    }
1700
1701    /// Bind to 127.0.0.1:0, read the assigned port, drop the listener.
1702    /// Used in adopt_only tests that must exercise the "port not bound" path:
1703    /// a dynamically chosen port is almost certainly free immediately after
1704    /// the listener drops, unlike the hardcoded 4321 which a running camp will
1705    /// have occupied.
1706    fn pick_unused_port() -> u16 {
1707        let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1708        l.local_addr().unwrap().port()
1709    }
1710
1711    fn cloudflare_reference_slot() -> MirrorProviderSlot {
1712        MirrorProviderSlot::Reference {
1713            provider_id: "cloudflare".to_string(),
1714            fields: BTreeMap::new(),
1715        }
1716    }
1717
1718    #[test]
1719    fn resolved_binary_prefers_explicit_path() {
1720        let opts = LocalStaticOptions {
1721            binary: Some(PathBuf::from("/explicit/path")),
1722            ..Default::default()
1723        };
1724        assert_eq!(opts.resolved_binary(), PathBuf::from("/explicit/path"));
1725    }
1726
1727    #[test]
1728    fn resolved_binary_falls_back_to_bare_name() {
1729        // Clearing the env var requires unsafe in test isolation; instead
1730        // assume MESOFACT_DEV_BIN is unset (best-effort).
1731        let opts = LocalStaticOptions::default();
1732        if std::env::var_os("MESOFACT_DEV_BIN").is_none() {
1733            assert_eq!(opts.resolved_binary(), PathBuf::from("mesofact-dev"));
1734        }
1735    }
1736
1737    #[test]
1738    fn slot_field_u16_extracts_port() {
1739        let mut fields = BTreeMap::new();
1740        fields.insert("port".to_string(), toml::Value::Integer(4321));
1741        assert_eq!(slot_field_u16(&fields, "port"), Some(4321));
1742    }
1743
1744    #[test]
1745    fn slot_field_u16_returns_none_for_missing_key() {
1746        let fields = BTreeMap::new();
1747        assert_eq!(slot_field_u16(&fields, "port"), None);
1748    }
1749
1750    #[tokio::test]
1751    async fn up_bails_when_workload_toml_missing() {
1752        let fx = Fixture::new(local_static_slot(4321), /*write_workload*/ false);
1753        let reconciler = MesofactStaticReconciler::new();
1754        let err = reconciler.up(fx.ctx()).await.unwrap_err();
1755        let msg = format!("{err:#}");
1756        assert!(msg.contains("workload.toml"), "got: {msg}");
1757    }
1758
1759    #[tokio::test]
1760    async fn up_bails_when_workload_kind_mismatches() {
1761        let fx = Fixture::new(local_static_slot(4321), /*write_workload*/ false);
1762        // Hand-write a container-kind workload at the right path. We
1763        // don't need the full container schema; the reconciler dispatches
1764        // off the `kind` field alone.
1765        std::fs::write(
1766            fx.workspace_root.join("app/web/workload.toml"),
1767            r#"schema_version = 1
1768kind = "container"
1769"#,
1770        )
1771        .unwrap();
1772        let reconciler = MesofactStaticReconciler::new();
1773        let err = reconciler.up(fx.ctx()).await.unwrap_err();
1774        let msg = format!("{err:#}");
1775        assert!(msg.contains("kind=\"container\""), "got: {msg}");
1776    }
1777
1778    #[tokio::test]
1779    async fn up_bails_when_static_slot_missing() {
1780        let mut fx = Fixture::new(local_static_slot(4321), true);
1781        fx.mirror.providers.clear();
1782        let reconciler = MesofactStaticReconciler::new();
1783        let err = reconciler.up(fx.ctx()).await.unwrap_err();
1784        let msg = format!("{err:#}");
1785        assert!(msg.contains("providers.static"), "got: {msg}");
1786    }
1787
1788    /// R602-B4 follow-up: a service with two static-kind components sharing
1789    /// one mirror (e.g. `site` + `app`) must be able to give them distinct
1790    /// ports. `slot()` resolves the component-qualified key
1791    /// (`"static:<id>"`) before the bare role, so `providers."static:site"`
1792    /// wins over `providers.static` for a component whose id is `site`.
1793    #[test]
1794    fn slot_prefers_component_qualified_key_over_bare_role() {
1795        let mut fx = Fixture::new(local_static_slot(4321), true);
1796        fx.mirror
1797            .providers
1798            .insert("static:site".to_string(), local_static_slot(9999));
1799        let slot = fx.ctx().slot("static").expect("slot present");
1800        let MirrorProviderSlot::Inline { fields, .. } = slot else {
1801            panic!("expected inline slot");
1802        };
1803        assert_eq!(slot_field_u16(fields, "port"), Some(9999));
1804    }
1805
1806    /// A component whose id has no qualified entry falls back to the bare
1807    /// role — the pre-existing single-slot-per-mirror behavior is unchanged
1808    /// for services that never declared a qualified key.
1809    #[test]
1810    fn slot_falls_back_to_bare_role_for_unqualified_component() {
1811        let mut fx = Fixture::new(local_static_slot(4321), true);
1812        fx.mirror
1813            .providers
1814            .insert("static:other-component".to_string(), local_static_slot(9999));
1815        let slot = fx.ctx().slot("static").expect("slot present");
1816        let MirrorProviderSlot::Inline { fields, .. } = slot else {
1817            panic!("expected inline slot");
1818        };
1819        assert_eq!(slot_field_u16(fields, "port"), Some(4321));
1820    }
1821
1822    fn miniflare_container_slot(port: u16) -> MirrorProviderSlot {
1823        let mut fields = BTreeMap::new();
1824        fields.insert("port".to_string(), toml::Value::Integer(port as i64));
1825        fields.insert(
1826            "bucket".to_string(),
1827            toml::Value::String("yah-dev".to_string()),
1828        );
1829        MirrorProviderSlot::Inline {
1830            kind: Provider::MiniflareContainer,
1831            fields,
1832        }
1833    }
1834
1835    #[tokio::test]
1836    async fn up_miniflare_container_bails_when_object_store_slot_missing() {
1837        // MiniflareContainer dispatches into pond::up_pond, which
1838        // requires a sibling providers.object_store slot. Missing → clear
1839        // error before we attempt to talk to docker.
1840        let fx = Fixture::new(miniflare_container_slot(4322), true);
1841        let reconciler = MesofactStaticReconciler::new();
1842        let err = reconciler.up(fx.ctx()).await.unwrap_err();
1843        let msg = format!("{err:#}");
1844        assert!(
1845            msg.contains("providers.object_store"),
1846            "error must mention the missing sibling slot; got: {msg}"
1847        );
1848        assert!(
1849            msg.contains("pond"),
1850            "error must name the requesting code path; got: {msg}"
1851        );
1852    }
1853
1854    #[tokio::test]
1855    async fn up_miniflare_container_bails_when_object_store_kind_wrong() {
1856        let mut fx = Fixture::new(miniflare_container_slot(4322), true);
1857        // Drop in a non-MinIO inline slot at object_store.
1858        fx.mirror.providers.insert(
1859            "object_store".into(),
1860            MirrorProviderSlot::Inline {
1861                kind: Provider::LocalStatic,
1862                fields: BTreeMap::new(),
1863            },
1864        );
1865        let reconciler = MesofactStaticReconciler::new();
1866        let err = reconciler.up(fx.ctx()).await.unwrap_err();
1867        let msg = format!("{err:#}");
1868        assert!(
1869            msg.contains("minio-container"),
1870            "error must name the expected kind; got: {msg}"
1871        );
1872    }
1873
1874    #[tokio::test]
1875    async fn up_bails_on_cloudflare_reference_slot() {
1876        let cloudflare = MirrorProviderSlot::Reference {
1877            provider_id: "cloudflare".to_string(),
1878            fields: BTreeMap::new(),
1879        };
1880        let fx = Fixture::new(cloudflare, true);
1881        let reconciler = MesofactStaticReconciler::new();
1882        let err = reconciler.up(fx.ctx()).await.unwrap_err();
1883        let msg = format!("{err:#}");
1884        assert!(msg.contains("cloudflare"), "got: {msg}");
1885    }
1886
1887    /// Regression for R330-B5: a cloud mirror that supplies bucket+zone but
1888    /// omits `asset_origin` must fail loudly at reconcile time. Otherwise the
1889    /// Worker silently gets `env.ASSET_ORIGIN=""` and 404s every request in
1890    /// prod (R327-F2 gotcha).
1891    #[tokio::test]
1892    async fn up_bails_on_cloudflare_reference_missing_asset_origin() {
1893        let mut fields = BTreeMap::new();
1894        fields.insert(
1895            "bucket".to_string(),
1896            toml::Value::String("yah-dev".to_string()),
1897        );
1898        fields.insert(
1899            "zone".to_string(),
1900            toml::Value::String("yah.dev".to_string()),
1901        );
1902        let cloudflare = MirrorProviderSlot::Reference {
1903            provider_id: "cloudflare".to_string(),
1904            fields,
1905        };
1906        let fx = Fixture::new(cloudflare, true);
1907        // Write a minimal cloudflare provider config so the asset_origin
1908        // check is the first thing that fails (otherwise the missing
1909        // provider file aborts the run earlier).
1910        let providers_dir = fx.workspace_root.join(".yah/infra/providers");
1911        std::fs::create_dir_all(&providers_dir).unwrap();
1912        std::fs::write(
1913            providers_dir.join("cloudflare.toml"),
1914            r#"schema_version = 1
1915id = "cloudflare"
1916kind = "cloudflare"
1917account_id = "test-account"
1918"#,
1919        )
1920        .unwrap();
1921        let reconciler = MesofactStaticReconciler::new();
1922        let err = reconciler.up(fx.ctx()).await.unwrap_err();
1923        let msg = format!("{err:#}");
1924        assert!(
1925            msg.contains("asset_origin"),
1926            "error must name asset_origin; got: {msg}"
1927        );
1928    }
1929
1930    /// R432-B2: stale jit file claiming the configured port must not produce
1931    /// "dynamic fallback" language — no second probe was attempted.
1932    #[tokio::test]
1933    async fn adopt_only_stale_jit_same_port_omits_dynamic_fallback_phrase() {
1934        let port = pick_unused_port();
1935        let fx = Fixture::new(local_static_slot(port), true);
1936        let jit_dir = fx.workspace_root.join(".yah/jit");
1937        std::fs::create_dir_all(&jit_dir).unwrap();
1938        std::fs::write(
1939            jit_dir.join("mesofact-dev-ports.json"),
1940            format!(r#"{{"test-svc/site": {port}}}"#),
1941        )
1942        .unwrap();
1943        let reconciler = MesofactStaticReconciler::new().with_local_static(LocalStaticOptions {
1944            adopt_only: true,
1945            ..Default::default()
1946        });
1947        let err = reconciler.up(fx.ctx()).await.unwrap_err();
1948        let msg = format!("{err:#}");
1949        assert!(
1950            !msg.contains("dynamic fallback"),
1951            "stale jit at configured port must not claim a dynamic probe; got: {msg}"
1952        );
1953        assert!(
1954            !msg.contains("jit file"),
1955            "same-port jit entry must not appear in the error; got: {msg}"
1956        );
1957    }
1958
1959    /// R432-B2: when camp is up but jit records a different dead port, name it.
1960    /// Requires a live socket so the error takes the Case-B "camp up" branch.
1961    #[cfg(unix)]
1962    #[tokio::test]
1963    async fn adopt_only_stale_jit_different_port_names_it() {
1964        use std::os::unix::net::UnixListener;
1965
1966        let port = pick_unused_port();
1967        let jit_port = pick_unused_port();
1968        let fx = Fixture::new(local_static_slot(port), true);
1969        let jit_dir = fx.workspace_root.join(".yah/jit");
1970        std::fs::create_dir_all(&jit_dir).unwrap();
1971        std::fs::write(
1972            jit_dir.join("mesofact-dev-ports.json"),
1973            format!(r#"{{"test-svc/site": {jit_port}}}"#),
1974        )
1975        .unwrap();
1976        let socket_path = fx.workspace_root.join("camp.sock");
1977        let _listener = UnixListener::bind(&socket_path).unwrap();
1978        let reconciler = MesofactStaticReconciler::new().with_local_static(LocalStaticOptions {
1979            adopt_only: true,
1980            camp_socket: Some(socket_path),
1981            ..Default::default()
1982        });
1983        let err = reconciler.up(fx.ctx()).await.unwrap_err();
1984        let msg = format!("{err:#}");
1985        assert!(
1986            msg.contains(&jit_port.to_string()),
1987            "error must name the dead jit port; got: {msg}"
1988        );
1989        assert!(
1990            !msg.contains("dynamic fallback"),
1991            "precise port naming replaces generic 'dynamic fallback'; got: {msg}"
1992        );
1993    }
1994
1995    /// R432-F3: no camp socket → "not running" / attach message (no socket probe noise).
1996    #[tokio::test]
1997    async fn adopt_only_no_camp_socket_gives_attach_message() {
1998        let fx = Fixture::new(local_static_slot(pick_unused_port()), true);
1999        let reconciler = MesofactStaticReconciler::new().with_local_static(LocalStaticOptions {
2000            adopt_only: true,
2001            camp_socket: None, // no socket path — treated as camp not running
2002            ..Default::default()
2003        });
2004        let err = reconciler.up(fx.ctx()).await.unwrap_err();
2005        let msg = format!("{err:#}");
2006        assert!(
2007            msg.contains("not running") || msg.contains("attach"),
2008            "no-socket path must indicate camp is not attached; got: {msg}"
2009        );
2010    }
2011
2012    /// R432-F3: live camp socket but no server → "camp is up but didn't bind".
2013    #[cfg(unix)]
2014    #[tokio::test]
2015    async fn adopt_only_live_camp_socket_gives_didnt_bind_message() {
2016        use std::os::unix::net::UnixListener;
2017
2018        let fx = Fixture::new(local_static_slot(pick_unused_port()), true);
2019        let socket_path = fx.workspace_root.join("camp.sock");
2020        let _listener = UnixListener::bind(&socket_path).unwrap();
2021
2022        let reconciler = MesofactStaticReconciler::new().with_local_static(LocalStaticOptions {
2023            adopt_only: true,
2024            camp_socket: Some(socket_path),
2025            ..Default::default()
2026        });
2027        let err = reconciler.up(fx.ctx()).await.unwrap_err();
2028        let msg = format!("{err:#}");
2029        assert!(
2030            msg.contains("a yah daemon is up but"),
2031            "live socket must give 'daemon is up but didn't bind' message; got: {msg}"
2032        );
2033        assert!(
2034            msg.contains("did not bind"),
2035            "message must name the bind failure; got: {msg}"
2036        );
2037    }
2038
2039    #[tokio::test]
2040    async fn up_bails_when_binary_not_found() {
2041        let fx = Fixture::new(local_static_slot(0), true);
2042        let reconciler = MesofactStaticReconciler::new().with_local_static(LocalStaticOptions {
2043            binary: Some(PathBuf::from("/definitely/not/a/binary")),
2044            ready_timeout: Some(Duration::from_millis(50)),
2045            ..Default::default()
2046        });
2047        let err = reconciler.up(fx.ctx()).await.unwrap_err();
2048        let msg = format!("{err:#}");
2049        assert!(msg.contains("spawning"), "got: {msg}");
2050    }
2051
2052    /// R490-F2: native_ident produces a DNS-/path-safe slug.
2053    #[test]
2054    fn native_ident_sanitizes_to_path_safe_slug() {
2055        assert_eq!(
2056            native_ident("dev-yah", "static"),
2057            "mesofact-dev-dev-yah-static"
2058        );
2059        // Non-alphanumerics (incl. slashes, dots) collapse to '-'; lowercased.
2060        assert_eq!(native_ident("Foo.Bar", "a/b"), "mesofact-dev-foo-bar-a-b");
2061    }
2062
2063    /// R490-F2: the mesofact-dev invocation lowers into the Native backend's
2064    /// container-`command` shape with the no-pull identity digest.
2065    #[test]
2066    fn native_mesofact_spec_lowers_argv_and_identity() {
2067        let spec = native_spec(
2068            "mesofact-dev-site-static",
2069            vec![
2070                "/bin/mesofact-dev".into(),
2071                "/wd".into(),
2072                "--port".into(),
2073                "4321".into(),
2074            ],
2075            Vec::new(),
2076        );
2077        assert_eq!(spec.name, "mesofact-dev-site-static");
2078        assert_eq!(spec.entrypoint, None);
2079        assert_eq!(spec.command.as_deref().unwrap()[0], "/bin/mesofact-dev");
2080        assert_eq!(spec.expose.mesh.identity.0, "mesofact-dev-site-static");
2081        assert_eq!(spec.image.digest, NATIVE_IDENTITY_DIGEST);
2082        assert_eq!(spec.replicas, 1);
2083    }
2084
2085    /// Wait-for-port: bind a local TCP listener in-process, confirm
2086    /// `wait_for_port` returns true within timeout.
2087    #[tokio::test]
2088    async fn wait_for_port_returns_true_when_port_bound() {
2089        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
2090        let addr = listener.local_addr().unwrap();
2091        assert!(wait_for_port(addr, Duration::from_millis(500)).await);
2092        drop(listener);
2093    }
2094
2095    #[tokio::test]
2096    async fn wait_for_port_returns_false_when_port_idle() {
2097        // Bind + drop to get an ephemeral port that's now definitely
2098        // unbound (modulo races; ignore the rare false flake).
2099        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
2100        let addr = listener.local_addr().unwrap();
2101        drop(listener);
2102        assert!(!wait_for_port(addr, Duration::from_millis(100)).await);
2103    }
2104
2105    // ---------- Worker script + config bindings ----------
2106
2107    #[test]
2108    fn worker_script_maps_root_to_index_html() {
2109        assert!(
2110            WORKER_SCRIPT.contains("index.html"),
2111            "bundled Worker must route / to index.html; got: {WORKER_SCRIPT}"
2112        );
2113    }
2114
2115    #[test]
2116    fn worker_script_has_no_r2_binding_calls() {
2117        assert!(
2118            !WORKER_SCRIPT.contains("env.ASSETS"),
2119            "bundled Worker must not reference R2 binding env.ASSETS; got: {WORKER_SCRIPT}"
2120        );
2121        assert!(
2122            !WORKER_SCRIPT.contains("writeHttpMetadata"),
2123            "bundled Worker must not use R2 writeHttpMetadata; got: {WORKER_SCRIPT}"
2124        );
2125    }
2126
2127    #[test]
2128    fn worker_script_uses_asset_origin_fetch() {
2129        assert!(
2130            WORKER_SCRIPT.contains("ASSET_ORIGIN"),
2131            "bundled Worker must fetch from ASSET_ORIGIN; got: {WORKER_SCRIPT}"
2132        );
2133    }
2134
2135    /// The vendored @mesofact/edge bundle must carry the W270 §3 serving logic:
2136    /// manifest read, pointer-store resolution for instance-addressed routes,
2137    /// and manifest error_routes. Substring markers (not behavior — behavior is
2138    /// covered by the miniflare tests in oss/mesofact/packages/mesofact-edge).
2139    #[test]
2140    fn worker_script_resolves_pointers_and_error_routes() {
2141        assert!(
2142            WORKER_SCRIPT.contains("manifest.json"),
2143            "bundled Worker must read the published manifest; got: {WORKER_SCRIPT}"
2144        );
2145        assert!(
2146            WORKER_SCRIPT.contains("POINTER_ORIGIN"),
2147            "bundled Worker must resolve pointers via POINTER_ORIGIN; got: {WORKER_SCRIPT}"
2148        );
2149        assert!(
2150            WORKER_SCRIPT.contains("error_routes"),
2151            "bundled Worker must honor manifest error_routes; got: {WORKER_SCRIPT}"
2152        );
2153    }
2154
2155    /// The binding is only useful if the vendored bundle actually reads it —
2156    /// `scripts/check-worker-bundle.sh` keeps the two in sync, and this catches
2157    /// a bundle vendored from before R746.
2158    #[test]
2159    fn bundled_worker_reads_route_headers() {
2160        assert!(
2161            WORKER_SCRIPT.contains("ROUTE_HEADERS"),
2162            "bundled Worker must apply per-route response headers; got: {WORKER_SCRIPT}"
2163        );
2164    }
2165
2166    // ── R746: component mount → publish prefix ──
2167
2168    #[test]
2169    fn unmounted_component_publishes_at_the_service_root() {
2170        assert_eq!(publish_prefix("noisetable-marketing", "cloud", None), "noisetable-marketing/cloud");
2171    }
2172
2173    #[test]
2174    fn a_mount_extends_the_prefix_and_is_slash_insensitive() {
2175        for m in ["/app", "app", "app/", "/app/"] {
2176            assert_eq!(
2177                publish_prefix("noisetable-marketing", "cloud", Some(m)),
2178                "noisetable-marketing/cloud/app",
2179                "mount {m:?}"
2180            );
2181        }
2182    }
2183
2184    /// A root mount is the same thing as no mount — not a trailing-slash key
2185    /// prefix, which would publish every asset one directory too deep.
2186    #[test]
2187    fn a_root_mount_is_the_service_root() {
2188        assert_eq!(publish_prefix("svc", "cloud", Some("/")), "svc/cloud");
2189        assert_eq!(publish_prefix("svc", "cloud", Some("")), "svc/cloud");
2190    }
2191
2192    /// The whole point: two static components of one service must not collide.
2193    #[test]
2194    fn two_components_of_one_service_get_disjoint_prefixes() {
2195        let site = publish_prefix("noisetable-marketing", "cloud", None);
2196        let app = publish_prefix("noisetable-marketing", "cloud", Some("/app"));
2197        assert_ne!(site, app);
2198        assert!(app.starts_with(&format!("{site}/")), "{app} under {site}");
2199    }
2200
2201    #[test]
2202    fn config_bindings_carry_the_route_header_table() {
2203        let table = r#"[{"path":"/app/*","headers":{"Cross-Origin-Opener-Policy":"same-origin"}}]"#;
2204        let b: std::collections::HashMap<_, _> = worker_config_bindings(
2205            &WorkerMode::Static,
2206            "https://assets.example.com",
2207            &BackendOrigins::default(),
2208            table,
2209        )
2210        .into_iter()
2211        .collect();
2212        assert_eq!(b["ROUTE_HEADERS"], table);
2213    }
2214
2215    #[test]
2216    fn config_bindings_static_mode() {
2217        let b: std::collections::HashMap<_, _> = worker_config_bindings(
2218            &WorkerMode::Static,
2219            "https://assets.example.com",
2220            &BackendOrigins::default(),
2221            "[]",
2222        )
2223        .into_iter()
2224        .collect();
2225        assert_eq!(b["WORKER_MODE"], "static");
2226        assert_eq!(b["ASSET_ORIGIN"], "https://assets.example.com");
2227        // Pointer origin defaults to the asset origin (W270 §3).
2228        assert_eq!(b["POINTER_ORIGIN"], "https://assets.example.com");
2229        assert_eq!(b["SSR_ORIGIN"], "");
2230        assert_eq!(b["SSR_PREFIXES"], "[]");
2231        // Undeclared backends are emitted EMPTY, not omitted: the binding list
2232        // is authoritative, so an omitted key would leave a stale value from an
2233        // earlier deploy in place.
2234        assert_eq!(b["ISSUES_ORIGIN"], "");
2235        assert_eq!(b["MESOFACT_BACKEND_ORIGIN"], "");
2236    }
2237
2238    #[test]
2239    fn config_bindings_spa_mode() {
2240        let b: std::collections::HashMap<_, _> = worker_config_bindings(
2241            &WorkerMode::Spa,
2242            "https://assets.example.com",
2243            &BackendOrigins::default(),
2244            "[]",
2245        )
2246        .into_iter()
2247        .collect();
2248        assert_eq!(b["WORKER_MODE"], "spa");
2249        assert_eq!(b["SSR_ORIGIN"], "");
2250    }
2251
2252    /// R330-F13: `/api/issues*` reaches the issue-tracker only when the static
2253    /// slot's `issues_origin` becomes an `ISSUES_ORIGIN` Worker binding.
2254    #[test]
2255    fn config_bindings_carry_backend_origins() {
2256        let mut fields = std::collections::BTreeMap::new();
2257        fields.insert(
2258            "issues_origin".to_string(),
2259            // Trailing slash trimmed — the router concatenates "/issues".
2260            toml::Value::String("https://issues.example.com/".to_string()),
2261        );
2262        fields.insert(
2263            "backend_origin".to_string(),
2264            toml::Value::String("https://almanac.example.com".to_string()),
2265        );
2266        let backends = BackendOrigins::from_slot_fields(&fields);
2267        assert_eq!(backends.issues, "https://issues.example.com");
2268
2269        let b: std::collections::HashMap<_, _> = worker_config_bindings(
2270            &WorkerMode::Static,
2271            "https://assets.example.com",
2272            &backends,
2273            "[]",
2274        )
2275        .into_iter()
2276        .collect();
2277        assert_eq!(b["ISSUES_ORIGIN"], "https://issues.example.com");
2278        assert_eq!(b["MESOFACT_BACKEND_ORIGIN"], "https://almanac.example.com");
2279    }
2280
2281    /// The vendored bundle must actually read the binding this reconciler now
2282    /// emits — otherwise the config lands and nothing routes.
2283    #[test]
2284    fn worker_script_reads_issues_origin() {
2285        assert!(
2286            WORKER_SCRIPT.contains("ISSUES_ORIGIN"),
2287            "bundled Worker must route /api/issues* via ISSUES_ORIGIN"
2288        );
2289    }
2290
2291    #[test]
2292    fn config_bindings_ssr_mode() {
2293        let mode = WorkerMode::Ssr {
2294            origin_url: "https://ssr.example.com".to_string(),
2295            prefixes: vec!["/api/".to_string(), "/rpc/".to_string()],
2296        };
2297        let b: std::collections::HashMap<_, _> = worker_config_bindings(
2298            &mode,
2299            "https://assets.example.com",
2300            &BackendOrigins::default(),
2301            "[]",
2302        )
2303        .into_iter()
2304        .collect();
2305        assert_eq!(b["WORKER_MODE"], "ssr");
2306        assert_eq!(b["SSR_ORIGIN"], "https://ssr.example.com");
2307        let prefixes: Vec<String> = serde_json::from_str(&b["SSR_PREFIXES"]).unwrap();
2308        assert!(prefixes.contains(&"/api/".to_string()));
2309        assert!(prefixes.contains(&"/rpc/".to_string()));
2310    }
2311
2312    #[test]
2313    fn worker_script_hash_roundtrip() {
2314        let tmp = tempdir().unwrap();
2315        let root = tmp.path();
2316        assert!(read_worker_script_hash(root, "test-worker").is_none());
2317        write_worker_script_hash(root, "test-worker", "abc123").unwrap();
2318        assert_eq!(
2319            read_worker_script_hash(root, "test-worker").as_deref(),
2320            Some("abc123")
2321        );
2322        // Writing a second worker doesn't clobber the first.
2323        write_worker_script_hash(root, "other-worker", "def456").unwrap();
2324        assert_eq!(
2325            read_worker_script_hash(root, "test-worker").as_deref(),
2326            Some("abc123")
2327        );
2328    }
2329
2330    #[test]
2331    fn parse_worker_mode_defaults_to_static() {
2332        let fields = BTreeMap::new();
2333        assert!(matches!(
2334            parse_worker_mode(WORKLOAD_KIND, &fields),
2335            WorkerMode::Static
2336        ));
2337    }
2338
2339    #[test]
2340    fn parse_worker_mode_spa_kind_defaults_to_spa() {
2341        let fields = BTreeMap::new();
2342        assert!(matches!(
2343            parse_worker_mode(WORKLOAD_KIND_SPA, &fields),
2344            WorkerMode::Spa
2345        ));
2346    }
2347
2348    #[test]
2349    fn parse_worker_mode_explicit_mode_beats_kind_default() {
2350        let mut fields = BTreeMap::new();
2351        fields.insert(
2352            "mode".to_string(),
2353            toml::Value::String("static".to_string()),
2354        );
2355        assert!(matches!(
2356            parse_worker_mode(WORKLOAD_KIND_SPA, &fields),
2357            WorkerMode::Static
2358        ));
2359    }
2360
2361    #[test]
2362    fn parse_worker_mode_spa() {
2363        let mut fields = BTreeMap::new();
2364        fields.insert("mode".to_string(), toml::Value::String("spa".to_string()));
2365        assert!(matches!(
2366            parse_worker_mode(WORKLOAD_KIND, &fields),
2367            WorkerMode::Spa
2368        ));
2369    }
2370
2371    #[test]
2372    fn parse_worker_mode_ssr_extracts_origin_and_prefixes() {
2373        let mut fields = BTreeMap::new();
2374        fields.insert("mode".to_string(), toml::Value::String("ssr".to_string()));
2375        fields.insert(
2376            "origin_url".to_string(),
2377            toml::Value::String("https://origin.example.com".to_string()),
2378        );
2379        fields.insert(
2380            "ssr_prefixes".to_string(),
2381            toml::Value::Array(vec![toml::Value::String("/api/".to_string())]),
2382        );
2383        if let WorkerMode::Ssr {
2384            origin_url,
2385            prefixes,
2386        } = parse_worker_mode(WORKLOAD_KIND, &fields)
2387        {
2388            assert_eq!(origin_url, "https://origin.example.com");
2389            assert_eq!(prefixes, vec!["/api/"]);
2390        } else {
2391            panic!("expected Ssr mode");
2392        }
2393    }
2394
2395    // ---------- W165: BuildMode → ForgeSpec lowering (R438-T6) ----------
2396
2397    use std::sync::Mutex as StdMutex;
2398    use tokio::sync::mpsc::UnboundedSender;
2399    use velveteen::ForgeStatus;
2400    use velveteen_exec::executor::{ExecEvent, ExecOutcome, ForgeExecutorError};
2401
2402    /// Captures the [`ForgeSpec`] handed to `execute(...)` and returns
2403    /// success without spawning anything.
2404    struct CaptureExecutor {
2405        captured: Arc<StdMutex<Vec<(ForgeSpec, ExecContext)>>>,
2406    }
2407
2408    impl CaptureExecutor {
2409        fn new() -> (Arc<Self>, Arc<StdMutex<Vec<(ForgeSpec, ExecContext)>>>) {
2410            let captured = Arc::new(StdMutex::new(Vec::new()));
2411            (
2412                Arc::new(Self {
2413                    captured: captured.clone(),
2414                }),
2415                captured,
2416            )
2417        }
2418    }
2419
2420    #[async_trait]
2421    impl ForgeExecutor for CaptureExecutor {
2422        async fn execute(
2423            &self,
2424            spec: ForgeSpec,
2425            ctx: ExecContext,
2426            _sink: Option<UnboundedSender<ExecEvent>>,
2427        ) -> Result<ExecOutcome, ForgeExecutorError> {
2428            self.captured.lock().unwrap().push((spec, ctx));
2429            Ok(ExecOutcome {
2430                status: ForgeStatus::Done {
2431                    exit_code: 0,
2432                    ended_at: 0,
2433                },
2434                stderr_tail: String::new(),
2435            })
2436        }
2437    }
2438
2439    /// Executor whose runs all return a non-zero exit + canned stderr —
2440    /// used to assert error-message shape from [`run_build`].
2441    struct FailingExecutor {
2442        stderr: String,
2443    }
2444
2445    #[async_trait]
2446    impl ForgeExecutor for FailingExecutor {
2447        async fn execute(
2448            &self,
2449            _spec: ForgeSpec,
2450            _ctx: ExecContext,
2451            _sink: Option<UnboundedSender<ExecEvent>>,
2452        ) -> Result<ExecOutcome, ForgeExecutorError> {
2453            Ok(ExecOutcome {
2454                status: ForgeStatus::Done {
2455                    exit_code: 2,
2456                    ended_at: 0,
2457                },
2458                stderr_tail: self.stderr.clone(),
2459            })
2460        }
2461    }
2462
2463    fn host_side_build() -> (BuildConfig, BuildMode) {
2464        (
2465            BuildConfig {
2466                command: Some("bun run build".into()),
2467                out_dir: PathBuf::from("dist"),
2468                render_command: None,
2469            },
2470            BuildMode::HostSide,
2471        )
2472    }
2473
2474    fn in_container_build() -> (BuildConfig, BuildMode) {
2475        let image = workload_spec::ImageRef {
2476            registry: "ghcr.io".into(),
2477            repository: "org/app-build".into(),
2478            tag: "v1.2".into(),
2479            digest: workload_spec::testing::test_digest(),
2480        };
2481        (
2482            BuildConfig {
2483                command: Some("bun run build".into()),
2484                out_dir: PathBuf::from("dist"),
2485                render_command: None,
2486            },
2487            BuildMode::InContainer { image },
2488        )
2489    }
2490
2491    #[tokio::test]
2492    async fn run_build_host_side_lowers_to_native_subprocess() {
2493        let (capture, captured) = CaptureExecutor::new();
2494        let tmp = tempdir().unwrap();
2495        let (build, mode) = host_side_build();
2496        run_build(tmp.path(), &build, &mode, &*capture)
2497            .await
2498            .unwrap();
2499
2500        let captured = captured.lock().unwrap();
2501        assert_eq!(captured.len(), 1, "build executed exactly once");
2502        let (spec, ctx) = &captured[0];
2503        assert_eq!(spec.where_.runtime, TaskRuntime::Native);
2504        assert_eq!(spec.where_.location, TaskLocation::Local);
2505        match &spec.command {
2506            ForgeCommand::Subprocess { argv, image } => {
2507                assert!(image.is_none(), "host_side carries no image; got {image:?}");
2508                assert_eq!(
2509                    argv,
2510                    &vec!["sh".to_string(), "-c".into(), "bun run build".into()]
2511                );
2512            }
2513            other => panic!("expected Subprocess, got {other:?}"),
2514        }
2515        assert_eq!(ctx.cwd.as_deref(), Some(tmp.path()));
2516    }
2517
2518    #[tokio::test]
2519    async fn run_build_in_container_lowers_to_container_runtime_with_pinned_digest() {
2520        let (capture, captured) = CaptureExecutor::new();
2521        let tmp = tempdir().unwrap();
2522        let (build, mode) = in_container_build();
2523        run_build(tmp.path(), &build, &mode, &*capture)
2524            .await
2525            .unwrap();
2526
2527        let captured = captured.lock().unwrap();
2528        let (spec, ctx) = &captured[0];
2529        assert_eq!(spec.where_.runtime, TaskRuntime::Container);
2530        assert_eq!(spec.where_.location, TaskLocation::Local);
2531        match &spec.command {
2532            ForgeCommand::Subprocess { argv, image } => {
2533                let image = image.as_ref().expect("in_container lowers with an image");
2534                assert_eq!(image.registry, "ghcr.io");
2535                assert_eq!(image.repository, "org/app-build");
2536                assert_eq!(image.tag, "v1.2");
2537                assert_eq!(image.digest, workload_spec::testing::test_digest());
2538                assert_eq!(
2539                    argv,
2540                    &vec!["sh".to_string(), "-c".into(), "bun run build".into()]
2541                );
2542            }
2543            other => panic!("expected Subprocess, got {other:?}"),
2544        }
2545        assert_eq!(ctx.cwd.as_deref(), Some(tmp.path()));
2546    }
2547
2548    #[tokio::test]
2549    async fn run_build_surfaces_stderr_on_nonzero_exit() {
2550        let executor = Arc::new(FailingExecutor {
2551            stderr: "TypeError: Cannot find module 'react'".into(),
2552        });
2553        let tmp = tempdir().unwrap();
2554        let (build, mode) = host_side_build();
2555        let err = run_build(tmp.path(), &build, &mode, &*executor)
2556            .await
2557            .unwrap_err();
2558        let msg = format!("{err:#}");
2559        assert!(msg.contains("Cannot find module 'react'"), "got: {msg}");
2560        assert!(msg.contains("bun run build"), "got: {msg}");
2561    }
2562
2563    #[tokio::test]
2564    async fn read_mesofact_build_extracts_host_side_default() {
2565        let tmp = tempdir().unwrap();
2566        // Use the legacy `schema_version = 1` integer shape — production
2567        // marketing/dashboard workload.tomls carry this and rebuild_static
2568        // must keep working against them. The subtree reader skips the
2569        // envelope so this round-trips.
2570        std::fs::write(
2571            tmp.path().join("workload.toml"),
2572            r#"schema_version = 1
2573kind = "mesofact-static"
2574routes = "./routes.ts"
2575
2576[build]
2577command = "bun run build"
2578out_dir = "dist"
2579"#,
2580        )
2581        .unwrap();
2582        let (build, mode) = read_mesofact_build(tmp.path()).unwrap().unwrap();
2583        assert_eq!(build.command.as_deref(), Some("bun run build"));
2584        assert_eq!(build.out_dir, PathBuf::from("dist"));
2585        assert!(matches!(mode, BuildMode::HostSide));
2586    }
2587
2588    #[tokio::test]
2589    async fn read_mesofact_build_extracts_in_container_with_digest() {
2590        let tmp = tempdir().unwrap();
2591        let digest = workload_spec::testing::test_digest();
2592        std::fs::write(
2593            tmp.path().join("workload.toml"),
2594            format!(
2595                r#"schema_version = 1
2596kind = "mesofact-static"
2597routes = "./routes.ts"
2598
2599[build]
2600command = "bun run build"
2601out_dir = "dist"
2602
2603[build_mode.in_container.image]
2604registry = "ghcr.io"
2605repository = "org/app-build"
2606tag = "v1.2"
2607digest = "{digest}"
2608"#
2609            ),
2610        )
2611        .unwrap();
2612        let (build, mode) = read_mesofact_build(tmp.path()).unwrap().unwrap();
2613        assert_eq!(build.command.as_deref(), Some("bun run build"));
2614        match mode {
2615            BuildMode::InContainer { image } => {
2616                assert_eq!(image.registry, "ghcr.io");
2617                assert_eq!(image.repository, "org/app-build");
2618                assert_eq!(image.tag, "v1.2");
2619                assert_eq!(image.digest, digest);
2620            }
2621            other => panic!("expected InContainer, got {other:?}"),
2622        }
2623    }
2624
2625    #[tokio::test]
2626    async fn read_mesofact_build_rejects_in_container_without_digest() {
2627        let tmp = tempdir().unwrap();
2628        std::fs::write(
2629            tmp.path().join("workload.toml"),
2630            r#"schema_version = 1
2631kind = "mesofact-static"
2632routes = "./routes.ts"
2633
2634[build]
2635command = "bun run build"
2636out_dir = "dist"
2637
2638[build_mode.in_container]
2639image = "ghcr.io/org/app-build:v1.2"
2640"#,
2641        )
2642        .unwrap();
2643        let err = read_mesofact_build(tmp.path()).unwrap_err();
2644        let msg = format!("{err:#}");
2645        assert!(
2646            msg.contains("digest") || msg.contains("sha256"),
2647            "in_container with bare tag must reject at parse; got: {msg}"
2648        );
2649    }
2650
2651    #[tokio::test]
2652    async fn read_mesofact_build_returns_none_for_other_kinds() {
2653        let tmp = tempdir().unwrap();
2654        std::fs::write(
2655            tmp.path().join("workload.toml"),
2656            r#"schema_version = 1
2657kind = "static-asset"
2658"#,
2659        )
2660        .unwrap();
2661        assert!(read_mesofact_build(tmp.path()).unwrap().is_none());
2662    }
2663
2664    #[tokio::test]
2665    async fn read_mesofact_build_returns_none_when_file_absent() {
2666        let tmp = tempdir().unwrap();
2667        assert!(read_mesofact_build(tmp.path()).unwrap().is_none());
2668    }
2669
2670    /// R838-B1: a `[build]` table declaring only `out_dir` is the shape
2671    /// `mesofact new` scaffolds — the project builds through the in-process
2672    /// pipeline and has no shell command to run.
2673    #[tokio::test]
2674    async fn read_mesofact_build_accepts_a_build_table_with_no_command() {
2675        let tmp = tempdir().unwrap();
2676        std::fs::write(
2677            tmp.path().join("workload.toml"),
2678            r#"schema_version = 1
2679kind = "mesofact-static"
2680routes = "./mesofact.routes.ts"
2681
2682[build]
2683out_dir = "dist"
2684"#,
2685        )
2686        .unwrap();
2687        let (build, mode) = read_mesofact_build(tmp.path()).unwrap().unwrap();
2688        assert_eq!(build.command, None);
2689        assert_eq!(build.out_dir, PathBuf::from("dist"));
2690        assert!(matches!(mode, BuildMode::HostSide));
2691    }
2692
2693    /// R838-B1: no `build.command` → no build step, not `sh -c ""`.
2694    ///
2695    /// An empty shell command exits 0 having produced nothing, so the
2696    /// reconciler would report a successful build and then publish whatever
2697    /// stale bytes were in `out_dir`. The skip has to happen at the lowering,
2698    /// which is what `lower_build_to_forge_spec` returning `None` pins.
2699    #[tokio::test]
2700    async fn rebuild_static_skips_the_build_step_when_no_command_is_declared() {
2701        let fx = Fixture::new(cloudflare_reference_slot(), /*write_workload*/ false);
2702        let workload_dir = fx.workspace_root.join("app/web");
2703        std::fs::write(
2704            workload_dir.join("workload.toml"),
2705            r#"schema_version = 1
2706kind = "mesofact-static"
2707routes = "./mesofact.routes.ts"
2708
2709[build]
2710out_dir = "dist"
2711"#,
2712        )
2713        .unwrap();
2714
2715        let (capture, captured) = CaptureExecutor::new();
2716        let reconciler = MesofactStaticReconciler::new().with_executor(capture.clone());
2717
2718        // As in the sibling tests, up_cloudflare_r2 fails for want of provider
2719        // config — but only AFTER the build step would have run.
2720        let _ = reconciler.rebuild_static(fx.ctx()).await;
2721
2722        assert!(
2723            captured.lock().unwrap().is_empty(),
2724            "a manifest with no build.command must dispatch nothing to the executor"
2725        );
2726    }
2727
2728    /// The lowering itself is the seam, so pin it directly too — a future
2729    /// caller that reaches `lower_build_to_forge_spec` without going through
2730    /// `run_build` inherits the same refusal.
2731    #[test]
2732    fn lowering_a_build_with_no_command_yields_no_forge_spec() {
2733        let build = BuildConfig {
2734            command: None,
2735            out_dir: PathBuf::from("dist"),
2736            render_command: None,
2737        };
2738        assert!(lower_build_to_forge_spec(
2739            std::path::Path::new("/workspace/app/web"),
2740            &build,
2741            &BuildMode::HostSide,
2742        )
2743        .is_none());
2744    }
2745
2746    #[tokio::test]
2747    async fn rebuild_static_lifts_build_mode_through_executor() {
2748        // End-to-end smoke through rebuild_static → run_build → executor for
2749        // the cloudflare publish arm. InContainer build_mode must reach the
2750        // executor as TaskRuntime::Container (the CF path does not skip container
2751        // builds — only local-static does, per W165 OQ#1, tested separately).
2752        // up_cloudflare_r2 will fail (no provider config), but the build step
2753        // runs first so the CaptureExecutor still records the lowered ForgeSpec.
2754        let fx = Fixture::new(cloudflare_reference_slot(), /*write_workload*/ false);
2755        let workload_dir = fx.workspace_root.join("app/web");
2756        let digest = workload_spec::testing::test_digest();
2757        std::fs::write(
2758            workload_dir.join("workload.toml"),
2759            format!(
2760                r#"schema_version = 1
2761kind = "mesofact-static"
2762routes = "./routes.ts"
2763
2764[build]
2765command = "bun run build"
2766out_dir = "dist"
2767
2768[build_mode.in_container.image]
2769registry = "ghcr.io"
2770repository = "org/app-build"
2771tag = "v1.2"
2772digest = "{digest}"
2773"#
2774            ),
2775        )
2776        .unwrap();
2777
2778        let (capture, captured) = CaptureExecutor::new();
2779        let reconciler = MesofactStaticReconciler::new().with_executor(capture.clone());
2780
2781        // up_cloudflare_r2 will fail (no provider config on disk) but only
2782        // AFTER the build step ran. We only care that the build path produced
2783        // a captured ForgeSpec with the right runtime.
2784        let _ = reconciler.rebuild_static(fx.ctx()).await;
2785
2786        let captured = captured.lock().unwrap();
2787        assert_eq!(captured.len(), 1, "build step executed exactly once");
2788        let (spec, _ctx) = &captured[0];
2789        assert_eq!(spec.where_.runtime, TaskRuntime::Container);
2790        match &spec.command {
2791            ForgeCommand::Subprocess { image, .. } => {
2792                let image = image.as_ref().unwrap();
2793                assert_eq!(image.digest, digest, "digest survives the round-trip");
2794            }
2795            other => panic!("expected Subprocess, got {other:?}"),
2796        }
2797    }
2798
2799    #[tokio::test]
2800    async fn rebuild_static_local_static_in_container_falls_back_to_host_side() {
2801        // W165 OQ#1 (R438-F9): local-static arm + in_container build_mode must
2802        // warn and fall back to host-side (TaskRuntime::Native). Dev machines
2803        // may not have docker, and the host watcher handles hot-reload.
2804        let fx = Fixture::new(local_static_slot(0), /*write_workload*/ false);
2805        let workload_dir = fx.workspace_root.join("app/web");
2806        let digest = workload_spec::testing::test_digest();
2807        std::fs::write(
2808            workload_dir.join("workload.toml"),
2809            format!(
2810                r#"schema_version = 1
2811kind = "mesofact-static"
2812routes = "./routes.ts"
2813
2814[build]
2815command = "bun run build"
2816out_dir = "dist"
2817
2818[build_mode.in_container.image]
2819registry = "ghcr.io"
2820repository = "org/app-build"
2821tag = "v1.2"
2822digest = "{digest}"
2823"#
2824            ),
2825        )
2826        .unwrap();
2827
2828        let (capture, captured) = CaptureExecutor::new();
2829        let reconciler = MesofactStaticReconciler::new()
2830            .with_executor(capture.clone())
2831            .with_local_static(LocalStaticOptions {
2832                binary: Some(PathBuf::from("/definitely/not/a/binary")),
2833                ready_timeout: Some(Duration::from_millis(50)),
2834                ..Default::default()
2835            });
2836        let _ = reconciler.rebuild_static(fx.ctx()).await;
2837
2838        let captured = captured.lock().unwrap();
2839        assert_eq!(
2840            captured.len(),
2841            1,
2842            "build step still ran (host-side fallback)"
2843        );
2844        let (spec, _) = &captured[0];
2845        assert_eq!(
2846            spec.where_.runtime,
2847            TaskRuntime::Native,
2848            "in_container overridden to Native for local-static arm"
2849        );
2850        match &spec.command {
2851            ForgeCommand::Subprocess { image, .. } => {
2852                assert!(
2853                    image.is_none(),
2854                    "image must be stripped when falling back to host-side; got {image:?}"
2855                );
2856            }
2857            other => panic!("expected Subprocess, got {other:?}"),
2858        }
2859    }
2860
2861    #[tokio::test]
2862    async fn rebuild_static_defaults_to_host_side_when_build_mode_omitted() {
2863        // Fixture writes a workload.toml without [build_mode] (the common
2864        // shape today). rebuild_static must default to HostSide.
2865        let fx = Fixture::new(local_static_slot(0), /*write_workload*/ true);
2866        let (capture, captured) = CaptureExecutor::new();
2867        let reconciler = MesofactStaticReconciler::new()
2868            .with_executor(capture.clone())
2869            .with_local_static(LocalStaticOptions {
2870                binary: Some(PathBuf::from("/definitely/not/a/binary")),
2871                ready_timeout: Some(Duration::from_millis(50)),
2872                ..Default::default()
2873            });
2874        let _ = reconciler.rebuild_static(fx.ctx()).await;
2875        let captured = captured.lock().unwrap();
2876        assert_eq!(
2877            captured.len(),
2878            1,
2879            "default build_mode still runs the build step"
2880        );
2881        assert_eq!(captured[0].0.where_.runtime, TaskRuntime::Native);
2882    }
2883
2884    #[tokio::test]
2885    async fn rebuild_static_skips_build_when_workload_toml_missing() {
2886        // No workload.toml on disk — rebuild_static must not panic in the
2887        // build step; the subsequent up() call surfaces the missing-manifest
2888        // error to the operator.
2889        let fx = Fixture::new(local_static_slot(0), /*write_workload*/ false);
2890        let (capture, captured) = CaptureExecutor::new();
2891        let reconciler = MesofactStaticReconciler::new().with_executor(capture.clone());
2892        let err = reconciler.rebuild_static(fx.ctx()).await.unwrap_err();
2893        let msg = format!("{err:#}");
2894        assert!(msg.contains("workload.toml"), "got: {msg}");
2895        assert!(
2896            captured.lock().unwrap().is_empty(),
2897            "no build executed when manifest missing",
2898        );
2899    }
2900
2901    // ── revalidate_static (R535-T1) ──────────────────────────────────────────
2902
2903    #[tokio::test]
2904    async fn revalidate_static_without_render_command_never_touches_executor() {
2905        // W225 §3 / R535-T1: an almanac on_change is a data-only trigger — it
2906        // must never re-run build.command, regardless of provider arm or
2907        // whether the subsequent publish step succeeds. The fixture's
2908        // workload.toml carries a real [build] table (write_workload=true)
2909        // but NO render_command — so the executor must record zero calls
2910        // (R535-T7 only runs the executor for a declared render_command).
2911        let fx = Fixture::new(cloudflare_reference_slot(), /*write_workload*/ true);
2912        let (capture, captured) = CaptureExecutor::new();
2913        let reconciler = MesofactStaticReconciler::new().with_executor(capture.clone());
2914
2915        // up_cloudflare_r2 will fail (no provider config on disk) — that's
2916        // expected and irrelevant here; only the executor call count matters.
2917        let _ = reconciler.revalidate_static(fx.ctx(), "/releases").await;
2918
2919        assert!(
2920            captured.lock().unwrap().is_empty(),
2921            "revalidate_static without render_command must never invoke the executor"
2922        );
2923    }
2924
2925    #[tokio::test]
2926    async fn revalidate_static_delegates_to_up() {
2927        // Without a render_command, revalidate_static's publish behavior must
2928        // be indistinguishable from calling up() directly. Same fixture, same
2929        // reconciler, two independent ReconcileCtx borrows: both arms must
2930        // hit the identical error (missing
2931        // .yah/infra/providers/cloudflare.toml) with byte-identical text.
2932        let fx = Fixture::new(cloudflare_reference_slot(), /*write_workload*/ true);
2933        let reconciler = MesofactStaticReconciler::new();
2934
2935        let revalidate_err = reconciler
2936            .revalidate_static(fx.ctx(), "/releases")
2937            .await
2938            .unwrap_err();
2939        let up_err = reconciler.up(fx.ctx()).await.unwrap_err();
2940
2941        assert_eq!(
2942            format!("{revalidate_err:#}"),
2943            format!("{up_err:#}"),
2944            "revalidate_static must delegate straight to up() with no extra behavior"
2945        );
2946    }
2947
2948    #[tokio::test]
2949    async fn revalidate_static_skips_build_when_workload_toml_missing() {
2950        // Mirrors rebuild_static_skips_build_when_workload_toml_missing:
2951        // revalidate_static must not panic when workload.toml is absent (no
2952        // [build] table → no render_command → no executor call); the
2953        // missing-manifest error surfaces from deeper in up().
2954        let fx = Fixture::new(local_static_slot(0), /*write_workload*/ false);
2955        let (capture, captured) = CaptureExecutor::new();
2956        let reconciler = MesofactStaticReconciler::new().with_executor(capture.clone());
2957        let err = reconciler
2958            .revalidate_static(fx.ctx(), "/releases")
2959            .await
2960            .unwrap_err();
2961        let msg = format!("{err:#}");
2962        assert!(msg.contains("workload.toml"), "got: {msg}");
2963        assert!(
2964            captured.lock().unwrap().is_empty(),
2965            "no build executed by revalidate_static",
2966        );
2967    }
2968
2969    // ── revalidate_static render_command (R535-T7) ───────────────────────────
2970
2971    fn write_workload_with_render_command(fx: &Fixture) {
2972        std::fs::write(
2973            fx.workspace_root.join("app/web/workload.toml"),
2974            r#"schema_version = 1
2975kind = "mesofact-static"
2976routes = "./routes.ts"
2977
2978[build]
2979command = "echo built"
2980out_dir = "dist"
2981render_command = "echo render {route} --all"
2982"#,
2983        )
2984        .unwrap();
2985    }
2986
2987    #[tokio::test]
2988    async fn revalidate_static_runs_render_command_with_route_substituted() {
2989        // R535-T7: a declared render_command runs exactly once before the
2990        // publish step — {route} substituted, host-side lowering (Native, no
2991        // image), cwd = workload dir — and NEVER build.command.
2992        let fx = Fixture::new(cloudflare_reference_slot(), /*write_workload*/ true);
2993        write_workload_with_render_command(&fx);
2994        let (capture, captured) = CaptureExecutor::new();
2995        let reconciler = MesofactStaticReconciler::new().with_executor(capture.clone());
2996
2997        // up_cloudflare_r2 still fails after the render step (no provider
2998        // config on disk) — only the executor capture matters here.
2999        let _ = reconciler.revalidate_static(fx.ctx(), "/issues/:id").await;
3000
3001        let captured = captured.lock().unwrap();
3002        assert_eq!(captured.len(), 1, "render executed exactly once");
3003        let (spec, ctx) = &captured[0];
3004        assert_eq!(spec.where_.runtime, TaskRuntime::Native);
3005        match &spec.command {
3006            ForgeCommand::Subprocess { argv, image } => {
3007                assert!(image.is_none(), "host_side render carries no image");
3008                assert_eq!(
3009                    argv,
3010                    &vec![
3011                        "sh".to_string(),
3012                        "-c".into(),
3013                        "echo render /issues/:id --all".into()
3014                    ],
3015                    "route pattern substituted into {{route}}"
3016                );
3017            }
3018            other => panic!("expected Subprocess, got {other:?}"),
3019        }
3020        assert_eq!(
3021            ctx.cwd.as_deref(),
3022            Some(fx.workspace_root.join("app/web").as_path())
3023        );
3024    }
3025
3026    #[tokio::test]
3027    async fn revalidate_static_local_static_skips_render_command() {
3028        // The local-static arm never runs the render step — the host
3029        // mesofact-dev watcher re-renders on data-file changes independently.
3030        let fx = Fixture::new(local_static_slot(0), /*write_workload*/ true);
3031        write_workload_with_render_command(&fx);
3032        let (capture, captured) = CaptureExecutor::new();
3033        let reconciler = MesofactStaticReconciler::new().with_executor(capture.clone());
3034
3035        let _ = reconciler.revalidate_static(fx.ctx(), "/issues/:id").await;
3036
3037        assert!(
3038            captured.lock().unwrap().is_empty(),
3039            "local-static revalidate must not run render_command"
3040        );
3041    }
3042
3043    /// Validate the in-tree fixture at `testdata/mesofact-in-container/workload.toml`.
3044    ///
3045    /// Verifies that `read_mesofact_build` returns `BuildMode::InContainer` for an
3046    /// on-disk workload that declares `[build_mode] mode = "in_container"`.  No
3047    /// build is executed — this is a parse + lowering-shape test that runs in CI
3048    /// without docker (R438-T8 "in-tree mesofact-static workload with
3049    /// build_mode=in_container builds green in CI").
3050    #[test]
3051    fn in_container_fixture_roundtrips_as_container_build_mode() {
3052        let manifest_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
3053        let fixture_dir = manifest_dir.join("testdata/mesofact-in-container");
3054        let (build, build_mode) = read_mesofact_build(&fixture_dir)
3055            .expect("testdata/mesofact-in-container/workload.toml must parse cleanly")
3056            .expect("fixture must have a [build] section");
3057        assert!(
3058            matches!(build_mode, BuildMode::InContainer { .. }),
3059            "expected BuildMode::InContainer but got {build_mode:?}",
3060        );
3061        assert!(
3062            build.command.as_deref().is_some_and(|c| !c.is_empty()),
3063            "build.command must be declared and non-empty"
3064        );
3065    }
3066
3067    /// Spin up a throwaway loopback server that answers `/__mesofact/info` with
3068    /// `identity` (Some → 200 JSON `{service,component}`, None → 404), for the
3069    /// adopt identity-check tests (R602-B4). Returns the bound port.
3070    async fn spawn_info_server(identity: Option<(&str, &str)>) -> u16 {
3071        use axum::response::IntoResponse;
3072        use axum::routing::get;
3073        use axum::Router;
3074
3075        let json = identity.map(|(s, c)| format!(r#"{{"service":"{s}","component":"{c}"}}"#));
3076        let app = Router::new().route(
3077            "/__mesofact/info",
3078            get(move || {
3079                let json = json.clone();
3080                async move {
3081                    match json {
3082                        Some(b) => ([(reqwest::header::CONTENT_TYPE, "application/json")], b)
3083                            .into_response(),
3084                        None => axum::http::StatusCode::NOT_FOUND.into_response(),
3085                    }
3086                }
3087            }),
3088        );
3089        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3090        let port = listener.local_addr().unwrap().port();
3091        tokio::spawn(async move {
3092            axum::serve(listener, app).await.unwrap();
3093        });
3094        // Let the accept loop come up before the probe connects.
3095        tokio::time::sleep(Duration::from_millis(50)).await;
3096        port
3097    }
3098
3099    fn loopback(port: u16) -> SocketAddr {
3100        SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port)
3101    }
3102
3103    #[tokio::test]
3104    async fn adopt_identified_matches_and_adopts() {
3105        let port = spawn_info_server(Some(("scrabcake", "site"))).await;
3106        let got = try_adopt_identified(loopback(port), "scrabcake", "site", "configured")
3107            .await
3108            .unwrap();
3109        assert!(got.is_some(), "matching identity should adopt");
3110    }
3111
3112    #[tokio::test]
3113    async fn adopt_identified_mismatch_bails_naming_both() {
3114        // The headline repro: scrabcake dev finds yah-marketing on the port.
3115        let port = spawn_info_server(Some(("yah-marketing", "pond"))).await;
3116        let err = try_adopt_identified(loopback(port), "scrabcake", "site", "configured")
3117            .await
3118            .unwrap_err();
3119        let msg = err.to_string();
3120        assert!(msg.contains("yah-marketing/pond"), "msg was: {msg}");
3121        assert!(msg.contains("scrabcake"), "msg was: {msg}");
3122    }
3123
3124    #[tokio::test]
3125    async fn adopt_identified_foreign_listener_bails() {
3126        // Listener present but no /__mesofact/info (a foreign server, e.g.
3127        // workerd, or an identity-less mesofact-dev) → refuse to adopt.
3128        let port = spawn_info_server(None).await;
3129        let err = try_adopt_identified(loopback(port), "scrabcake", "site", "configured")
3130            .await
3131            .unwrap_err();
3132        assert!(
3133            err.to_string().contains("not an identifiable mesofact-dev"),
3134            "msg was: {err}"
3135        );
3136    }
3137
3138    #[tokio::test]
3139    async fn adopt_identified_no_listener_returns_none() {
3140        let port = pick_unused_port();
3141        let got = try_adopt_identified(loopback(port), "scrabcake", "site", "configured")
3142            .await
3143            .unwrap();
3144        assert!(got.is_none(), "no listener → nothing to adopt");
3145    }
3146}