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        //
623        // R844-F2: this is the LOCAL tier's half of the one allocation
624        // contract the remote (kamaji) tier answers through as well. It was
625        // hand-rolled here and nowhere else, which is exactly the shape that
626        // lets a service running both locally and remotely learn its port from
627        // two mechanisms that can disagree; `kamaji::ports::EphemeralPorts` is
628        // this logic, named, so the two tiers cannot drift. Ephemeral rather
629        // than ledger-backed on purpose: a camp port is disposable, nothing
630        // publishes it, and a fresh one each run is fine.
631        let spawn_port = {
632            use kamaji::ports::PortAllocator;
633            kamaji::ports::EphemeralPorts
634                .resolve(
635                    &ctx.component.id,
636                    kamaji::ports::LOOPBACK,
637                    (port != 0).then_some(port),
638                )
639                .context("could not bind any port for mesofact-dev")?
640        };
641
642        // R490-F2: spawn mesofact-dev through kamaji's Native (fork+exec)
643        // backend rather than a bespoke Command::spawn. NativeRuntime owns the
644        // fork+exec, stdio capture, and SIGTERM→grace→SIGKILL teardown; the
645        // reconciler keeps only the WorkloadSpec lowering, the readiness probe,
646        // and a file-tail→LogBuffer bridge that preserves the Run-tab's live
647        // log surface (NativeRuntime captures stdio to files, not a pipe).
648        self.spawn_via_constable(ctx, &binary, &workload_dir, spawn_port)
649            .await
650    }
651
652    /// Lower the mesofact-dev invocation to a [`WorkloadSpec`], deploy it on a
653    /// per-bring-up [`NativeRuntime`], wait for the port, and wrap the result
654    /// in a [`RunningWorkload`] whose shutdown tears the workload back down.
655    async fn spawn_via_constable(
656        &self,
657        ctx: &ReconcileCtx<'_>,
658        binary: &Path,
659        workload_dir: &Path,
660        spawn_port: u16,
661    ) -> Result<RunningWorkload> {
662        // NativeRuntime captures stdout/stderr under <state_dir>/<ident>/.
663        // Scope it per-workspace so concurrent camps don't collide.
664        let state_dir = ctx.workspace_root.join(".yah/jit/native");
665        let ident_str = native_ident(&ctx.service.name, &ctx.component.id);
666        let ident = MeshIdent(ident_str.clone());
667
668        let mut argv: Vec<String> = vec![
669            binary.display().to_string(),
670            workload_dir.display().to_string(),
671            "--port".to_string(),
672            spawn_port.to_string(),
673            // Stamp logical identity so the child answers /__mesofact/info and a
674            // later adopt re-run can confirm the port holds *this* server rather
675            // than a colliding foreign listener (R602-B4).
676            "--service".to_string(),
677            ctx.service.name.clone(),
678            "--component".to_string(),
679            ctx.component.id.clone(),
680        ];
681        argv.extend(self.local_static.extra_args.iter().cloned());
682        let spec = native_spec(&ident_str, argv, Vec::new());
683
684        let runtime = Arc::new(NativeRuntime::new(&state_dir));
685        let mesh = MeshAssignment::inlined(Ipv4Addr::LOCALHOST);
686
687        info!(
688            binary = %binary.display(),
689            workload = %workload_dir.display(),
690            port = spawn_port,
691            ident = %ident_str,
692            "spawning mesofact-dev (kamaji native backend)",
693        );
694
695        let deployed = runtime
696            .deploy_workload(&spec, &mesh)
697            .await
698            .with_context(|| {
699                format!(
700                    "deploying mesofact-dev via kamaji native backend \
701                     — install with `cargo install --path oss/mesofact/crates/mesofact-dev` \
702                     or ensure the bundled sidecar is on the path ({})",
703                    binary.display(),
704                )
705            })?;
706
707        let (stdout_path, stderr_path) = capture_paths(&state_dir, &ident_str);
708
709        // Wait for the server to bind. If it doesn't, tear it down and return
710        // an error so the caller doesn't hand the UI a dead URL.
711        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), spawn_port);
712        let timeout = self
713            .local_static
714            .ready_timeout
715            .unwrap_or(Duration::from_secs(10));
716        if !wait_for_port(addr, timeout).await {
717            warn!(addr = %addr, "mesofact-dev did not bind within timeout; tearing down");
718            runtime.teardown_workload(&ident).await.ok();
719            anyhow::bail!("mesofact-dev failed to bind {addr} within {:?}", timeout);
720        }
721
722        let dev_url = format!("http://{addr}");
723        info!(dev_url = %dev_url, port = spawn_port, pid = deployed.task_pid, "mesofact-dev ready");
724
725        // Bridge NativeRuntime's file capture into the Run-tab LogBuffer and
726        // own teardown on shutdown.
727        let log_buf = LogBuffer::new();
728        let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>();
729        let supervisor = spawn_native_log_supervisor(
730            runtime,
731            ident,
732            log_buf.clone(),
733            stdout_path,
734            stderr_path,
735            shutdown_rx,
736        );
737
738        Ok(into_running(
739            "mesofact-static",
740            "static",
741            Some(dev_url),
742            None,
743            Some(log_buf),
744            shutdown_tx,
745            supervisor,
746        ))
747    }
748
749    /// Cloudflare R2 publish path: upload `dist/` to R2, optionally purge CDN
750    /// cache tags, and return a `RunningWorkload` with `public_url` set.
751    async fn up_cloudflare_r2(
752        &self,
753        ctx: &ReconcileCtx<'_>,
754        cf_provider: super::cf_creds::CfProvider,
755        slot_fields: &std::collections::BTreeMap<String, toml::Value>,
756    ) -> Result<RunningWorkload> {
757        use super::r2_publish::{publish_to_r2, R2PurgeOpts};
758        use crate::provider::cloudflare::{CloudflareClient, WorkerBinding};
759
760        // account_id + credentials come from the resolved provider.
761        let account_id = cf_provider.account_id.clone();
762
763        // Extract bucket + zone from the mirror's static slot.
764        let bucket = slot_fields
765            .get("bucket")
766            .and_then(|v| v.as_str())
767            .context("providers.static missing `bucket` field for cloudflare R2 publish")?
768            .to_string();
769        let zone = slot_fields
770            .get("zone")
771            .and_then(|v| v.as_str())
772            .context("providers.static missing `zone` field for cloudflare R2 publish")?
773            .to_string();
774
775        // asset_origin is the public HTTP URL the Worker fetches assets from.
776        // publish_to_r2 lays files down under `<svc>/<env>/<key>`, so this URL
777        // must include the same prefix. Validate up front — without it the
778        // Worker would 404 every request in prod.
779        let asset_origin =
780            slot_fields
781                .get("asset_origin")
782                .and_then(|v| v.as_str())
783                .filter(|s| !s.is_empty())
784                .with_context(|| {
785                    format!(
786                "providers.static.asset_origin missing or empty (service={svc}, env={env}) — \
787                 set it to the R2 public URL with the publish prefix, e.g. \
788                 \"https://cdn.{zone}/{svc}/{env}\"",
789                svc = ctx.service.name, env = ctx.env, zone = zone,
790            )
791                })?
792                .to_string();
793
794        // R2 S3 access keys (distinct from the management API token).
795        let (access_key, secret_key) = cf_provider.r2_keys()?;
796
797        // Management API token — used for cache-tag purge and Transform Rules.
798        // Optional: publish itself only needs the R2 S3 keys.
799        let cf_api_token: Option<String> = cf_provider.api_token_opt();
800        let purge = cf_api_token.clone().map(|token| R2PurgeOpts {
801            zone_name: zone.clone(),
802            api_token: token,
803        });
804
805        // Resolve dist dir from workload.toml build.out_dir (default: "dist").
806        let workload_dir = ctx.workload_dir();
807        let out_dir = read_workload_out_dir(&workload_dir).unwrap_or_else(|| "dist".to_string());
808        let dist_dir = workload_dir.join(&out_dir);
809
810        let mirror_prefix =
811            publish_prefix(&ctx.service.name, ctx.env, ctx.component.mount.as_deref());
812        let report = publish_to_r2(
813            &dist_dir,
814            &account_id,
815            &bucket,
816            &access_key,
817            &secret_key,
818            Some(&mirror_prefix),
819            purge,
820        )
821        .await
822        .with_context(|| format!("publishing to R2 bucket {bucket:?} (account {account_id})"))?;
823
824        info!(
825            uploaded = report.uploaded.len(),
826            purged = report.purged_tags.len(),
827            bucket,
828            zone,
829            "R2 publish complete",
830        );
831
832        // Deploy CF Worker script (replaces the Transform Rule workaround).
833        // Worker serves assets via ASSET_ORIGIN with mode-aware routing:
834        // static 404-fallback, SPA index.html fallback, or SSR proxy to origin.
835        // Non-fatal: warn if token lacks Workers Scripts: Edit scope.
836        if let Some(ref token) = cf_api_token {
837            let cf = CloudflareClient::new(token.clone());
838            let mode = parse_worker_mode(&ctx.component.kind, slot_fields);
839            let worker_name = slot_fields
840                .get("worker_name")
841                .and_then(|v| v.as_str())
842                .map(|s| s.to_string())
843                .unwrap_or_else(|| format!("{}-worker", ctx.service.name));
844            let backends = BackendOrigins::from_slot_fields(slot_fields);
845            let route_headers = crate::config::route_headers_for_service(
846                ctx.workspace_root,
847                &ctx.service.name,
848            )?;
849            let bindings =
850                worker_config_bindings(&mode, &asset_origin, &backends, &route_headers);
851            let worker_bindings: Vec<WorkerBinding<'_>> = bindings
852                .iter()
853                .map(|(k, v)| WorkerBinding::PlainText {
854                    name: k.as_str(),
855                    text: v.as_str(),
856                })
857                .collect();
858            // Hash script + bindings so config changes trigger redeploy.
859            let script_hash = {
860                let mut input = WORKER_SCRIPT.as_bytes().to_vec();
861                input.push(0);
862                input.extend_from_slice(
863                    serde_json::to_string(&bindings)
864                        .unwrap_or_default()
865                        .as_bytes(),
866                );
867                sha256_hex(&input)
868            };
869
870            let worker_result = async {
871                let zone_id = cf.zone_id_for_name(&zone).await?;
872
873                // Skip redeploy when script + config are unchanged across re-runs.
874                let cached = read_worker_script_hash(ctx.workspace_root, &worker_name);
875                if cached.as_deref() != Some(&script_hash) {
876                    cf.deploy_worker_script(
877                        &account_id,
878                        &worker_name,
879                        WORKER_SCRIPT,
880                        &worker_bindings,
881                    )
882                    .await?;
883                    let _ =
884                        write_worker_script_hash(ctx.workspace_root, &worker_name, &script_hash);
885                    info!(worker_name, "CF Worker script deployed");
886                } else {
887                    info!(
888                        worker_name,
889                        "CF Worker script unchanged — skipping redeploy"
890                    );
891                }
892
893                // Upsert zone route: `{zone}/*` → worker script.
894                let route_pattern = format!("{zone}/*");
895                cf.upsert_worker_route(&zone_id, &route_pattern, &worker_name)
896                    .await?;
897                anyhow::Ok(())
898            }
899            .await;
900
901            // R703-B4 — how loudly this fails depends on whether the Worker is
902            // the door the public actually comes through.
903            //
904            // It was unconditionally non-fatal, and that is how the yah.dev
905            // Worker ended up 19 days behind the router bundle in-tree: the
906            // token lacked `Workers Scripts: Edit`, every apply warned into a
907            // logger the CLI never installed, and every apply reported ok. A
908            // front door that cannot be updated is not a warning — it is the
909            // failure. When the zone's manifest declares `front_door =
910            // "worker"`, a failed deploy is fatal.
911            //
912            // For any other declared front door the Worker is a warm rollback
913            // lever rather than the live door, so a warning remains right: it
914            // should not be able to fail an apply for a surface serving no
915            // traffic.
916            if let Err(e) = worker_result {
917                let is_live_front_door = matches!(
918                    super::publish_beacon::declared_front_door(ctx.workspace_root, &zone),
919                    Some((_, crate::config::FrontDoor::Worker))
920                );
921                if is_live_front_door {
922                    return Err(e).with_context(|| {
923                        format!(
924                            "deploying the Cloudflare Worker for {zone} (script {worker_name}).\n\
925                         \n\
926                         .yah/domains/*.toml declares front_door = \"worker\" for this zone, so \
927                         this Worker IS the public front door — it cannot be left at whatever \
928                         version happens to be deployed. The publish above succeeded; what \
929                         failed is updating the thing that serves it.\n\
930                         \n\
931                         An `Authentication error` here means the configured Cloudflare \
932                         token cannot touch Workers. Test that DIRECTLY — a token-validity \
933                         check will not tell you, because the token is almost certainly \
934                         valid and merely under-scoped:\n\
935                         \n\
936                           curl -sS -H \"Authorization: Bearer $(yah keys get <slot>)\" \\\n\
937                             https://api.cloudflare.com/client/v4/accounts/<acct>/workers/scripts\n\
938                         \n\
939                         DO NOT reach for https://api.cloudflare.com/client/v4/user/tokens/verify \
940                         to triage this. An account-scoped token (`cfat_` prefix) is rejected \
941                         there with a flat `code 1000, Invalid API Token`, which reads \
942                         exactly like a revoked credential and sends you hunting for a token \
943                         that is fine. That misdiagnosis has now happened twice. The valid \
944                         health check for an account token is \
945                         /accounts/<acct>/tokens/verify.\n\
946                         \n\
947                         THE FIX, if the workers/scripts GET is denied: mint a token that \
948                         carries the grants, rather than editing one by hand —\n\
949                         \n\
950                           yah cloud cf token create --zone <zone> \\\n\
951                             --store-slot cloudflare-mesofact-static \\\n\
952                             --bootstrap-slot <a slot holding API Tokens: Edit>\n\
953                         \n\
954                         then point `credentials` in .yah/infra/providers/cloudflare.toml at \
955                         that slot. It builds MESOFACT_STATIC_GRANTS, which includes \
956                         `Workers Scripts: Write` (account) and `Workers Routes: Write` \
957                         (zone). The command's own summary line prints only five scopes and \
958                         omits both — that text is stale, the policy is not.\n\
959                         \n\
960                         Whatever the cause, it is silent everywhere else: the R2 publish \
961                         uses separate S3 keys and keeps working, so the bucket stays \
962                         current while the Worker — the thing that serves it — freezes."
963                        )
964                    });
965                }
966                warn!(
967                    zone,
968                    worker_name,
969                    error = %e,
970                    "CF Worker deploy/route failed (non-fatal — this zone's declared \
971                     front door is not the Worker, so it serves no traffic today) — \
972                     ensure cloudflare-api-token has Workers Scripts: Edit \
973                     and Zone Workers Routes: Edit scope"
974                );
975            }
976        }
977
978        // R703-B4 — the publish is not the deliverable; the served page is.
979        self.verify_serving(ctx, slot_fields, &zone, &asset_origin, &report.beacon)
980            .await?;
981
982        Ok(RunningWorkload::adopted("mesofact-static", "static", None)
983            .with_public_url(format!("https://{zone}")))
984    }
985
986    /// Fetch the just-written publish beacon back through the origin and the
987    /// public front door, and fail the apply if the front door is serving
988    /// anything else.
989    ///
990    /// R703-B4. Everything upstream of here reports success on the *write*:
991    /// R2 accepted the objects, the Worker API accepted the script, the apply
992    /// exits 0. None of that is evidence that the bytes reached a reader, and
993    /// twice now they did not — once because a declared-but-unready bundle
994    /// tier disabled this chain, once because the apex had been cut over to an
995    /// origin nothing republishes. Both presented as HTTP 200 on a stale page.
996    ///
997    /// The origin probe is checked first and separately on purpose: it splits
998    /// "the publish did not land" from "the publish landed and the front door
999    /// is elsewhere", which are different tickets with identical symptoms.
1000    async fn verify_serving(
1001        &self,
1002        ctx: &ReconcileCtx<'_>,
1003        slot_fields: &std::collections::BTreeMap<String, toml::Value>,
1004        zone: &str,
1005        asset_origin: &str,
1006        beacon: &super::publish_beacon::PublishBeacon,
1007    ) -> Result<()> {
1008        use super::publish_beacon as pb;
1009
1010        // Opt-out for a deliberately in-flight front-door migration. Declared
1011        // in config rather than passed as a CLI flag so that turning it off is
1012        // a reviewable diff next to a comment naming the ticket, not an
1013        // invocation habit that quietly becomes permanent.
1014        let verify = slot_fields
1015            .get("verify_serving")
1016            .and_then(|v| v.as_bool())
1017            .unwrap_or(true);
1018        if !verify {
1019            warn!(
1020                zone,
1021                "verify_serving = false — publish NOT checked against the live \
1022                 front door; the site can go stale without this apply failing"
1023            );
1024            return Ok(());
1025        }
1026
1027        let verdict = pb::check_serving(
1028            ctx.workspace_root,
1029            zone,
1030            Some(asset_origin),
1031            beacon,
1032            pb::EDGE_PROBE_ATTEMPTS,
1033            pb::EDGE_PROBE_DELAY,
1034        )
1035        .await;
1036
1037        if verdict.is_ok() {
1038            info!(
1039                zone,
1040                digest = %beacon.digest,
1041                files = beacon.files,
1042                "front door is serving this publish"
1043            );
1044            return Ok(());
1045        }
1046
1047        // A stale or absent front door means the deployed Worker (if any) may
1048        // be older than the bundle this build embeds, and the local hash cache
1049        // would otherwise skip redeploying it forever — that cache is a claim
1050        // about the live Worker made from an untracked file on one laptop.
1051        // Drop the entry so the next apply cannot take the skip branch.
1052        if !verdict.front_door.is_match() {
1053            let worker_name = slot_fields
1054                .get("worker_name")
1055                .and_then(|v| v.as_str())
1056                .map(|s| s.to_string())
1057                .unwrap_or_else(|| format!("{}-worker", ctx.service.name));
1058            forget_worker_script_hash(ctx.workspace_root, &worker_name);
1059        }
1060
1061        Err(verdict.into_error(beacon))
1062    }
1063}
1064
1065/// Read the `[build]` + `[build_mode]` subtrees from
1066/// `<workload_dir>/workload.toml`. Used by [`MesofactStaticReconciler::rebuild_static`]
1067/// to drive [`run_build`] without forcing the whole workload through the
1068/// `workload_spec::Workload` envelope — many in-tree workload manifests
1069/// still carry `schema_version = 1` (integer) which the typed envelope
1070/// rejects. Parsing only the subtrees we use keeps this path tolerant of
1071/// the legacy shape while still giving us typed [`BuildConfig`] and
1072/// [`BuildMode`] values to lower.
1073///
1074/// Returns:
1075/// - `Ok(None)` when `workload.toml` is absent, isn't a `mesofact-static`
1076///   workload, or has no `[build]` table — `rebuild_static` then skips the
1077///   build step (the subsequent `up()` will surface the missing-manifest
1078///   error if relevant).
1079/// - `Ok(Some((build, build_mode)))` on success; `build_mode` defaults to
1080///   `HostSide` when the field is absent.
1081fn read_mesofact_build(workload_dir: &std::path::Path) -> Result<Option<(BuildConfig, BuildMode)>> {
1082    let path = workload_dir.join("workload.toml");
1083    let src = match std::fs::read_to_string(&path) {
1084        Ok(s) => s,
1085        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1086        Err(e) => return Err(anyhow::Error::new(e).context(format!("reading {}", path.display()))),
1087    };
1088    let value: toml::Value =
1089        toml::from_str(&src).with_context(|| format!("parsing {}", path.display()))?;
1090
1091    if value.get("kind").and_then(|v| v.as_str()) != Some(WORKLOAD_KIND) {
1092        return Ok(None);
1093    }
1094
1095    let Some(build_value) = value.get("build") else {
1096        return Ok(None);
1097    };
1098    let build: BuildConfig = build_value
1099        .clone()
1100        .try_into()
1101        .with_context(|| format!("parsing [build] table in {}", path.display()))?;
1102
1103    let build_mode = match value.get("build_mode") {
1104        Some(v) => v
1105            .clone()
1106            .try_into()
1107            .with_context(|| format!("parsing [build_mode] table in {}", path.display()))?,
1108        None => BuildMode::default(),
1109    };
1110
1111    Ok(Some((build, build_mode)))
1112}
1113
1114/// Lower (`build`, `build_mode`) to a [`ForgeSpec`] (W165).
1115///
1116/// - [`BuildMode::HostSide`] → `TaskRuntime::Native`, `image=None` — the
1117///   build inherits the host's PATH and toolchain.
1118/// - [`BuildMode::InContainer { image }`] → `TaskRuntime::Container` with
1119///   the pinned image attached to the `Subprocess` command. The executor
1120///   bind-mounts `workload_dir` as the container's working directory via
1121///   the [`ExecContext`] passed alongside.
1122///
1123/// `None` when the manifest declares no `build.command` (R838-B1) — there is
1124/// no subprocess to lower, because the project builds through the in-process
1125/// `mesofact-dev` pipeline rather than an external bundler. Callers skip the
1126/// build step rather than lowering an empty `sh -c ""`, which would "succeed"
1127/// having produced nothing.
1128///
1129/// Pure function: no I/O, no subprocess. Exposed at `pub(crate)` for
1130/// golden-test parity with the recipe-lowering helper (R438-T7).
1131pub(crate) fn lower_build_to_forge_spec(
1132    workload_dir: &std::path::Path,
1133    build: &BuildConfig,
1134    build_mode: &BuildMode,
1135) -> Option<ForgeSpec> {
1136    let command = build.command.clone()?;
1137    let (image, runtime) = match build_mode {
1138        BuildMode::HostSide => (None, TaskRuntime::Native),
1139        BuildMode::InContainer { image } => (Some(image.clone()), TaskRuntime::Container),
1140    };
1141    Some(ForgeSpec {
1142        command: ForgeCommand::Subprocess {
1143            argv: vec!["sh".into(), "-c".into(), command],
1144            image,
1145        },
1146        where_: TaskPlacement::new(TaskLocation::Local, runtime),
1147        timeout: None,
1148        label: Some(format!("mesofact-static-build:{}", workload_dir.display())),
1149        initiator: Initiator::Gnome {
1150            camp: "mesofact-static-reconciler".into(),
1151            shift: "build".into(),
1152        },
1153        mesh_access: MeshAccess::default(),
1154    })
1155}
1156
1157/// Lower (`build`, `build_mode`) to a [`ForgeSpec`] and run it through the
1158/// supplied [`ForgeExecutor`] (W165). Thin wrapper over
1159/// [`lower_build_to_forge_spec`] — separated so the lowering is testable
1160/// without spawning a subprocess.
1161///
1162/// A manifest with no `build.command` is a no-op here (R838-B1): the project
1163/// has no external bundler step, so there is nothing for this reconciler to
1164/// shell out to. Same outcome as a workload with no `workload.toml` at all,
1165/// which `rebuild_static` has always skipped.
1166async fn run_build(
1167    workload_dir: &std::path::Path,
1168    build: &BuildConfig,
1169    build_mode: &BuildMode,
1170    executor: &dyn ForgeExecutor,
1171) -> Result<()> {
1172    let mode_tag = match build_mode {
1173        BuildMode::HostSide => "host_side",
1174        BuildMode::InContainer { .. } => "in_container",
1175    };
1176    let Some(spec) = lower_build_to_forge_spec(workload_dir, build, build_mode) else {
1177        tracing::info!(
1178            workload = %workload_dir.display(),
1179            "workload.toml declares no [build] command — skipping the build step \
1180             (the project builds in-process)"
1181        );
1182        return Ok(());
1183    };
1184    let cmd_str = build
1185        .command
1186        .clone()
1187        .expect("lower_build_to_forge_spec returns Some only when command is Some");
1188    tracing::info!(
1189        workload = %workload_dir.display(),
1190        cmd = %cmd_str,
1191        mode = mode_tag,
1192        "running mesofact-static build"
1193    );
1194
1195    let exec_ctx = ExecContext::default().with_cwd(workload_dir.to_path_buf());
1196
1197    let outcome = executor
1198        .execute(spec, exec_ctx, None)
1199        .await
1200        .with_context(|| format!("executing build command: {cmd_str}"))?;
1201
1202    if !outcome.succeeded() {
1203        anyhow::bail!(
1204            "build command failed ({}): {} — {}",
1205            outcome.status.discriminant(),
1206            cmd_str,
1207            outcome.stderr_tail,
1208        );
1209    }
1210    Ok(())
1211}
1212
1213/// Read `build.out_dir` from a workload's `workload.toml`. Returns `None`
1214/// when the file is absent, unreadable, or the field is missing — callers
1215/// default to `"dist"`.
1216pub(crate) fn read_workload_out_dir(workload_dir: &std::path::Path) -> Option<String> {
1217    let path = workload_dir.join("workload.toml");
1218    let src = std::fs::read_to_string(&path).ok()?;
1219    let value: toml::Value = toml::from_str(&src).ok()?;
1220    value
1221        .get("build")?
1222        .get("out_dir")?
1223        .as_str()
1224        .map(str::to_string)
1225}
1226
1227// ---------- CF Worker script rendering ----------
1228
1229/// Routing mode baked into the Worker script at deploy time. Shared between
1230/// the Cloudflare-Worker arm (this file) and the pond arm via `pub` so camp's
1231/// `build_miniflare_deploy_spec` can derive the same mode from a mirror's
1232/// static slot when populating `local_driver::pond_miniflare::MiniflareSpec`.
1233pub enum WorkerMode {
1234    /// All routes served from R2; `/` and directory paths → `index.html`;
1235    /// unknown paths → `404.html` (if present) or a 404 response.
1236    Static,
1237    /// Unknown paths fall back to `index.html` for client-side routing.
1238    Spa,
1239    /// Paths matching `prefixes` are proxied to `origin_url`; the rest uses
1240    /// the SPA index.html fallback.
1241    Ssr {
1242        origin_url: String,
1243        prefixes: Vec<String>,
1244    },
1245}
1246
1247/// Parse the Worker routing mode from the mirror's static slot fields. Public
1248/// so camp's pond bring-up can mirror the cloudflare-arm semantics without
1249/// duplicating the field-name conventions.
1250///
1251/// When the slot declares no explicit `mode`, the default derives from the
1252/// component's kind: `mesofact-spa` → SPA fallback, everything else → static.
1253/// An explicit `mode` field always wins.
1254pub fn parse_worker_mode(
1255    component_kind: &str,
1256    fields: &std::collections::BTreeMap<String, toml::Value>,
1257) -> WorkerMode {
1258    let default_mode = if component_kind == WORKLOAD_KIND_SPA {
1259        "spa"
1260    } else {
1261        "static"
1262    };
1263    match fields
1264        .get("mode")
1265        .and_then(|v| v.as_str())
1266        .unwrap_or(default_mode)
1267    {
1268        "spa" => WorkerMode::Spa,
1269        "ssr" => {
1270            let origin_url = fields
1271                .get("origin_url")
1272                .and_then(|v| v.as_str())
1273                .unwrap_or_default()
1274                .to_string();
1275            let prefixes = fields
1276                .get("ssr_prefixes")
1277                .and_then(|v| v.as_array())
1278                .map(|a| {
1279                    a.iter()
1280                        .filter_map(|v| v.as_str().map(String::from))
1281                        .collect()
1282                })
1283                .unwrap_or_default();
1284            WorkerMode::Ssr {
1285                origin_url,
1286                prefixes,
1287            }
1288        }
1289        _ => WorkerMode::Static,
1290    }
1291}
1292
1293/// Backend origins the edge router proxies `/api/*` prefixes to (R455-T4).
1294///
1295/// Distinct from `SSR_ORIGIN`: SSR proxies *page* routes to a renderer, these
1296/// proxy *API* routes to a service that owns state. Both are read off the
1297/// mirror's static slot (`issues_origin` / `backend_origin`).
1298///
1299/// These MUST be emitted here rather than set by hand on the Worker. Every
1300/// apply re-uploads the whole binding list, so a binding this function does
1301/// not produce is *deleted* on the next `yah cloud apply` — which is how a
1302/// hand-set `ISSUES_ORIGIN` silently reverts to a 404 (R330-F13, R752-B2).
1303#[derive(Debug, Clone, Default, PartialEq, Eq)]
1304pub struct BackendOrigins {
1305    /// `ISSUES_ORIGIN` — issue-tracker surface; `/api/issues*` proxied here.
1306    pub issues: String,
1307    /// `MESOFACT_BACKEND_ORIGIN` — almanac surface; `/api/releases*`.
1308    pub releases: String,
1309}
1310
1311impl BackendOrigins {
1312    /// Read the optional backend-origin fields off a mirror's static slot.
1313    /// Absent or empty → an empty binding, and the router's `env.X &&` guard
1314    /// leaves that prefix unrouted (a real 404, never a half-configured proxy).
1315    pub fn from_slot_fields(fields: &std::collections::BTreeMap<String, toml::Value>) -> Self {
1316        let field = |name: &str| {
1317            fields
1318                .get(name)
1319                .and_then(|v| v.as_str())
1320                .unwrap_or_default()
1321                .trim_end_matches('/')
1322                .to_string()
1323        };
1324        Self {
1325            issues: field("issues_origin"),
1326            releases: field("backend_origin"),
1327        }
1328    }
1329}
1330
1331/// The R2 key prefix a static component publishes under (R746).
1332///
1333/// `<service>/<env>` for an unmounted component — every pre-R746 component, and
1334/// the only shape `asset_origin` in a mirror manifest is written against.
1335/// `mount` appends its normalized form, which is what lets two static
1336/// components of one service coexist: before it, both wrote `index.html` to the
1337/// same key and the second deploy of the day silently replaced the first site
1338/// with the other.
1339///
1340/// The front door resolves a request by its own path (`${ASSET_ORIGIN}/<path>`),
1341/// so the mount is simultaneously the storage prefix and the URL prefix — by
1342/// construction, not by two manifests agreeing.
1343fn publish_prefix(service: &str, env: &str, mount: Option<&str>) -> String {
1344    let base = format!("{service}/{env}");
1345    match mount.map(crate::config::normalize_mount) {
1346        None => base,
1347        Some(m) if m.is_empty() => base,
1348        Some(m) => format!("{base}/{m}"),
1349    }
1350}
1351
1352/// Build the plain_text Worker binding values for the given routing mode.
1353///
1354/// These are uploaded alongside [`WORKER_SCRIPT`] as `plain_text` bindings
1355/// and appear as `env.ASSET_ORIGIN`, `env.WORKER_MODE`, etc. inside the Worker.
1356fn worker_config_bindings(
1357    mode: &WorkerMode,
1358    asset_origin: &str,
1359    backends: &BackendOrigins,
1360    route_headers: &str,
1361) -> Vec<(String, String)> {
1362    let (mode_str, ssr_origin, ssr_prefixes) = match mode {
1363        WorkerMode::Static => ("static", String::new(), "[]".to_string()),
1364        WorkerMode::Spa => ("spa", String::new(), "[]".to_string()),
1365        WorkerMode::Ssr {
1366            origin_url,
1367            prefixes,
1368        } => (
1369            "ssr",
1370            origin_url.clone(),
1371            serde_json::to_string(prefixes).unwrap_or_else(|_| "[]".to_string()),
1372        ),
1373    };
1374    vec![
1375        ("ASSET_ORIGIN".to_string(), asset_origin.to_string()),
1376        // Pointer-store origin for instance-addressed routes (W270 §3): the
1377        // @mesofact/edge worker reads `p/<key>` records here. Pointers live
1378        // under the `p/` prefix in the same bucket as content, so this defaults
1379        // to ASSET_ORIGIN; it stays a distinct binding so a future consumer can
1380        // front the (uncached) pointer reads separately.
1381        ("POINTER_ORIGIN".to_string(), asset_origin.to_string()),
1382        // Reserved upload seam (R490-T8): prod has no upload origin yet, so the
1383        // binding is empty and the Worker returns 404 on /uploads/*. A future
1384        // dynamic-bucket consumer sets this to the user-writable origin.
1385        ("UPLOAD_ORIGIN".to_string(), String::new()),
1386        ("WORKER_MODE".to_string(), mode_str.to_string()),
1387        ("SSR_ORIGIN".to_string(), ssr_origin),
1388        ("SSR_PREFIXES".to_string(), ssr_prefixes),
1389        ("ISSUES_ORIGIN".to_string(), backends.issues.clone()),
1390        (
1391            "MESOFACT_BACKEND_ORIGIN".to_string(),
1392            backends.releases.clone(),
1393        ),
1394        // R746: per-route response headers, straight from the domain manifest's
1395        // route table (`DomainConfig::route_headers_json`). `"[]"` when no
1396        // domain routes this service or none of its routes declare headers —
1397        // the Worker then leaves every response untouched.
1398        ("ROUTE_HEADERS".to_string(), route_headers.to_string()),
1399    ]
1400}
1401
1402fn sha256_hex(data: &[u8]) -> String {
1403    use sha2::Digest;
1404    hex::encode(sha2::Sha256::digest(data))
1405}
1406
1407/// Read the last deployed Worker script hash from the jit cache.
1408fn read_worker_script_hash(workspace_root: &std::path::Path, worker_name: &str) -> Option<String> {
1409    let path = workspace_root.join(".yah/jit/worker-script-hashes.json");
1410    let s = std::fs::read_to_string(&path).ok()?;
1411    let map: serde_json::Map<String, serde_json::Value> = serde_json::from_str(&s).ok()?;
1412    map.get(worker_name)
1413        .and_then(|v| v.as_str())
1414        .map(|s| s.to_string())
1415}
1416
1417/// Write the deployed Worker script hash to the jit cache.
1418fn write_worker_script_hash(
1419    workspace_root: &std::path::Path,
1420    worker_name: &str,
1421    hash: &str,
1422) -> std::io::Result<()> {
1423    let path = workspace_root.join(".yah/jit/worker-script-hashes.json");
1424    let mut map: serde_json::Map<String, serde_json::Value> = if path.exists() {
1425        std::fs::read_to_string(&path)
1426            .ok()
1427            .and_then(|s| serde_json::from_str(&s).ok())
1428            .unwrap_or_default()
1429    } else {
1430        serde_json::Map::new()
1431    };
1432    map.insert(
1433        worker_name.to_string(),
1434        serde_json::Value::String(hash.to_string()),
1435    );
1436    if let Some(parent) = path.parent() {
1437        std::fs::create_dir_all(parent)?;
1438    }
1439    std::fs::write(
1440        &path,
1441        serde_json::to_string_pretty(&serde_json::Value::Object(map)).unwrap_or_default(),
1442    )
1443}
1444
1445/// Drop a Worker's cached script hash so the next reconcile redeploys it.
1446///
1447/// R703-B4. The cache at `.yah/jit/worker-script-hashes.json` is an untracked
1448/// local file asserting something about a *remote* Worker, so it can be right
1449/// on one machine and wrong on the next — and while it is wrong, every apply
1450/// takes the "unchanged — skipping redeploy" branch and the live Worker never
1451/// catches up. It sat 19 days behind the in-tree router bundle that way. When
1452/// the front door is demonstrably not serving the current publish, the cache
1453/// has lost the right to be believed.
1454///
1455/// Best-effort: a cache we could not clear only costs one more manual redeploy,
1456/// and the serving check that called us is already returning an error.
1457fn forget_worker_script_hash(workspace_root: &std::path::Path, worker_name: &str) {
1458    let path = workspace_root.join(".yah/jit/worker-script-hashes.json");
1459    let Ok(s) = std::fs::read_to_string(&path) else {
1460        return;
1461    };
1462    let Ok(mut map) = serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(&s) else {
1463        return;
1464    };
1465    if map.remove(worker_name).is_none() {
1466        return;
1467    }
1468    let _ = std::fs::write(
1469        &path,
1470        serde_json::to_string_pretty(&serde_json::Value::Object(map)).unwrap_or_default(),
1471    );
1472    warn!(
1473        worker_name,
1474        "cleared cached Worker script hash — next apply will redeploy the script"
1475    );
1476}
1477
1478/// Return `true` when a Unix-domain socket at `path` accepts connections.
1479/// Uses a blocking connect so it can be called from sync or async context
1480/// without spawning a task. The connect attempt is instantaneous for a live
1481/// listener and fails immediately for a missing/stale socket file.
1482#[cfg(unix)]
1483fn is_unix_socket_live(path: &std::path::Path) -> bool {
1484    std::os::unix::net::UnixStream::connect(path).is_ok()
1485}
1486
1487#[cfg(not(unix))]
1488fn is_unix_socket_live(_path: &std::path::Path) -> bool {
1489    false
1490}
1491
1492/// Adopt a mesofact-dev already listening on `addr` — but only when it
1493/// identifies as `(expected_service, expected_component)` via `/__mesofact/info`
1494/// (R602-B4). Returns:
1495/// - `Ok(None)` — nothing is listening on `addr` (caller falls through to the
1496///   next candidate / spawns a fresh server).
1497/// - `Ok(Some(_))` — a matching mesofact-dev is running; adopt it.
1498/// - `Err(_)` — a listener is present but is a *different* service/component,
1499///   or is not an identifiable mesofact-dev at all. Adoption is refused; the
1500///   port is taken by a foreign workload, so there is nothing to spawn — surface
1501///   the collision instead of silently serving the wrong site.
1502///
1503/// `label` distinguishes the "configured" vs jit "dynamic" port in logs.
1504async fn try_adopt_identified(
1505    addr: SocketAddr,
1506    expected_service: &str,
1507    expected_component: &str,
1508    label: &str,
1509) -> Result<Option<RunningWorkload>> {
1510    // Liveness gate first: no listener → nothing to adopt (spawn path).
1511    if tokio::net::TcpStream::connect(addr).await.is_err() {
1512        return Ok(None);
1513    }
1514
1515    match probe_dev_identity(addr).await {
1516        Some((svc, comp)) if svc == expected_service && comp == expected_component => {
1517            let dev_url = format!("http://{addr}");
1518            info!(
1519                dev_url = %dev_url,
1520                port = addr.port(),
1521                %label,
1522                "mesofact-dev already running; identity matches, adopting"
1523            );
1524            Ok(Some(RunningWorkload::adopted(
1525                "mesofact-static",
1526                "static",
1527                Some(dev_url),
1528            )))
1529        }
1530        Some((svc, comp)) => anyhow::bail!(
1531            "port {} is serving {svc}/{comp}, but component {expected_component} of service \
1532             {expected_service} expected it — refusing to adopt another workload's dev server. \
1533             This is a host-port collision; give each service a distinct port \
1534             (check `.yah/services/*/mirrors/*.toml`, or run `yah cloud validate`).",
1535            addr.port(),
1536        ),
1537        None => anyhow::bail!(
1538            "port {} is occupied by a process that is not an identifiable mesofact-dev \
1539             (no /__mesofact/info) — refusing to adopt a foreign listener for component \
1540             {expected_component} of service {expected_service}. Free the port or point this \
1541             component at an unused one.",
1542            addr.port(),
1543        ),
1544    }
1545}
1546
1547/// Query `GET http://{addr}/__mesofact/info` and return the server's logical
1548/// `(service, component)` identity. `None` when the endpoint is unreachable,
1549/// non-2xx (older/identity-less mesofact-dev, or a foreign server), or the body
1550/// is not the expected JSON shape. Short timeout — this is a loopback probe on
1551/// the reconcile hot path.
1552async fn probe_dev_identity(addr: SocketAddr) -> Option<(String, String)> {
1553    let url = format!("http://{addr}/__mesofact/info");
1554    let resp = reqwest::Client::new()
1555        .get(&url)
1556        .timeout(Duration::from_secs(2))
1557        .send()
1558        .await
1559        .ok()?;
1560    if !resp.status().is_success() {
1561        return None;
1562    }
1563    let body: serde_json::Value = resp.json().await.ok()?;
1564    let svc = body.get("service")?.as_str()?.to_string();
1565    let comp = body.get("component")?.as_str()?.to_string();
1566    Some((svc, comp))
1567}
1568
1569/// Read the actual port recorded in `.yah/jit/mesofact-dev-ports.json` after
1570/// a mesofact-dev bind. Returns `None` when the file is absent or the entry
1571/// is missing. `pub` since R490 follow-through: the desktop's dev-cell
1572/// observation probes this port when the camp's `mesofact_dev.list` has no
1573/// entry (the camp stopped spawning mesofact-dev in R490-F2, so its list no
1574/// longer sees desktop-spawned processes).
1575pub fn read_jit_port(workspace_root: &std::path::Path, svc: &str, component: &str) -> Option<u16> {
1576    let path = workspace_root
1577        .join(".yah")
1578        .join("jit")
1579        .join("mesofact-dev-ports.json");
1580    let s = std::fs::read_to_string(&path).ok()?;
1581    let map: serde_json::Map<String, serde_json::Value> = serde_json::from_str(&s).ok()?;
1582    map.get(&format!("{svc}/{component}"))
1583        .and_then(|v| v.as_u64())
1584        .and_then(|n| u16::try_from(n).ok())
1585}
1586
1587/// mesofact-dev's ident namespace: `mesofact-dev-<service>-<component>`,
1588/// sanitized by [`sanitize_ident`] into a slug that is both DNS-segment shaped
1589/// (kamaji's contract) and safe as a path component (NativeRuntime joins it
1590/// under its state dir).
1591fn native_ident(service: &str, component: &str) -> String {
1592    sanitize_ident(&format!("mesofact-dev-{service}-{component}"))
1593}
1594
1595#[cfg(test)]
1596mod tests {
1597    use super::*;
1598    use crate::{MirrorConfig, MirrorShape, ServiceComponent, ServiceConfig};
1599    use std::collections::BTreeMap;
1600    use tempfile::tempdir;
1601
1602    /// Build a minimal in-memory ctx for unit tests, with the component's
1603    /// workload dir set up to look like a mesofact-static workload.
1604    struct Fixture {
1605        _workspace: tempfile::TempDir,
1606        workspace_root: PathBuf,
1607        service: ServiceConfig,
1608        component: ServiceComponent,
1609        mirror: MirrorConfig,
1610        env: String,
1611    }
1612
1613    impl Fixture {
1614        fn new(slot: MirrorProviderSlot, write_workload: bool) -> Self {
1615            let workspace = tempdir().unwrap();
1616            let workspace_root = workspace.path().to_path_buf();
1617            let workload_dir = workspace_root.join("app/web");
1618            std::fs::create_dir_all(workload_dir.join("dist/html")).unwrap();
1619            std::fs::write(workload_dir.join("dist/html/index.html"), "<h1>x</h1>").unwrap();
1620            if write_workload {
1621                std::fs::write(
1622                    workload_dir.join("workload.toml"),
1623                    r#"schema_version = 1
1624kind = "mesofact-static"
1625routes = "./routes.ts"
1626
1627[build]
1628command = "echo built"
1629out_dir = "dist"
1630"#,
1631                )
1632                .unwrap();
1633            }
1634
1635            let mut providers = BTreeMap::new();
1636            providers.insert("static".to_string(), slot);
1637            let mirror = MirrorConfig {
1638                schema_version: 1,
1639                shape: MirrorShape::Local,
1640                providers,
1641                ingress: Default::default(),
1642                ingress_machines: Vec::new(),
1643                drivers: Default::default(),
1644                asset_aliases: Default::default(),
1645            };
1646            let service = ServiceConfig {
1647                schema_version: 1,
1648                name: "test-svc".to_string(),
1649                domain: "test.local".to_string(),
1650                components: vec![],
1651                db: crate::DbCatalog::default(),
1652            };
1653            let component = ServiceComponent {
1654                mount: None,
1655                id: "site".to_string(),
1656                kind: "mesofact-static".to_string(),
1657                path: "app/web".to_string(),
1658                role: "static".to_string(),
1659                publishes: None,
1660                wave: 0,
1661                git: None,
1662            };
1663            Self {
1664                _workspace: workspace,
1665                workspace_root,
1666                service,
1667                component,
1668                mirror,
1669                env: "local".to_string(),
1670            }
1671        }
1672
1673        fn ctx(&self) -> ReconcileCtx<'_> {
1674            ReconcileCtx {
1675                workspace_root: &self.workspace_root,
1676                service: &self.service,
1677                component: &self.component,
1678                mirror: &self.mirror,
1679                env: &self.env,
1680                scope: crate::reconciler::ProviderScope::singleton(),
1681            }
1682        }
1683    }
1684
1685    fn local_static_slot(port: u16) -> MirrorProviderSlot {
1686        let mut fields = BTreeMap::new();
1687        fields.insert("port".to_string(), toml::Value::Integer(port as i64));
1688        MirrorProviderSlot::Inline {
1689            kind: Provider::LocalStatic,
1690            fields,
1691        }
1692    }
1693
1694    /// Bind to 127.0.0.1:0, read the assigned port, drop the listener.
1695    /// Used in adopt_only tests that must exercise the "port not bound" path:
1696    /// a dynamically chosen port is almost certainly free immediately after
1697    /// the listener drops, unlike the hardcoded 4321 which a running camp will
1698    /// have occupied.
1699    fn pick_unused_port() -> u16 {
1700        let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1701        l.local_addr().unwrap().port()
1702    }
1703
1704    fn cloudflare_reference_slot() -> MirrorProviderSlot {
1705        MirrorProviderSlot::Reference {
1706            provider_id: "cloudflare".to_string(),
1707            fields: BTreeMap::new(),
1708        }
1709    }
1710
1711    #[test]
1712    fn resolved_binary_prefers_explicit_path() {
1713        let opts = LocalStaticOptions {
1714            binary: Some(PathBuf::from("/explicit/path")),
1715            ..Default::default()
1716        };
1717        assert_eq!(opts.resolved_binary(), PathBuf::from("/explicit/path"));
1718    }
1719
1720    #[test]
1721    fn resolved_binary_falls_back_to_bare_name() {
1722        // Clearing the env var requires unsafe in test isolation; instead
1723        // assume MESOFACT_DEV_BIN is unset (best-effort).
1724        let opts = LocalStaticOptions::default();
1725        if std::env::var_os("MESOFACT_DEV_BIN").is_none() {
1726            assert_eq!(opts.resolved_binary(), PathBuf::from("mesofact-dev"));
1727        }
1728    }
1729
1730    #[test]
1731    fn slot_field_u16_extracts_port() {
1732        let mut fields = BTreeMap::new();
1733        fields.insert("port".to_string(), toml::Value::Integer(4321));
1734        assert_eq!(slot_field_u16(&fields, "port"), Some(4321));
1735    }
1736
1737    #[test]
1738    fn slot_field_u16_returns_none_for_missing_key() {
1739        let fields = BTreeMap::new();
1740        assert_eq!(slot_field_u16(&fields, "port"), None);
1741    }
1742
1743    #[tokio::test]
1744    async fn up_bails_when_workload_toml_missing() {
1745        let fx = Fixture::new(local_static_slot(4321), /*write_workload*/ false);
1746        let reconciler = MesofactStaticReconciler::new();
1747        let err = reconciler.up(fx.ctx()).await.unwrap_err();
1748        let msg = format!("{err:#}");
1749        assert!(msg.contains("workload.toml"), "got: {msg}");
1750    }
1751
1752    #[tokio::test]
1753    async fn up_bails_when_workload_kind_mismatches() {
1754        let fx = Fixture::new(local_static_slot(4321), /*write_workload*/ false);
1755        // Hand-write a container-kind workload at the right path. We
1756        // don't need the full container schema; the reconciler dispatches
1757        // off the `kind` field alone.
1758        std::fs::write(
1759            fx.workspace_root.join("app/web/workload.toml"),
1760            r#"schema_version = 1
1761kind = "container"
1762"#,
1763        )
1764        .unwrap();
1765        let reconciler = MesofactStaticReconciler::new();
1766        let err = reconciler.up(fx.ctx()).await.unwrap_err();
1767        let msg = format!("{err:#}");
1768        assert!(msg.contains("kind=\"container\""), "got: {msg}");
1769    }
1770
1771    #[tokio::test]
1772    async fn up_bails_when_static_slot_missing() {
1773        let mut fx = Fixture::new(local_static_slot(4321), true);
1774        fx.mirror.providers.clear();
1775        let reconciler = MesofactStaticReconciler::new();
1776        let err = reconciler.up(fx.ctx()).await.unwrap_err();
1777        let msg = format!("{err:#}");
1778        assert!(msg.contains("providers.static"), "got: {msg}");
1779    }
1780
1781    /// R602-B4 follow-up: a service with two static-kind components sharing
1782    /// one mirror (e.g. `site` + `app`) must be able to give them distinct
1783    /// ports. `slot()` resolves the component-qualified key
1784    /// (`"static:<id>"`) before the bare role, so `providers."static:site"`
1785    /// wins over `providers.static` for a component whose id is `site`.
1786    #[test]
1787    fn slot_prefers_component_qualified_key_over_bare_role() {
1788        let mut fx = Fixture::new(local_static_slot(4321), true);
1789        fx.mirror
1790            .providers
1791            .insert("static:site".to_string(), local_static_slot(9999));
1792        let slot = fx.ctx().slot("static").expect("slot present");
1793        let MirrorProviderSlot::Inline { fields, .. } = slot else {
1794            panic!("expected inline slot");
1795        };
1796        assert_eq!(slot_field_u16(fields, "port"), Some(9999));
1797    }
1798
1799    /// A component whose id has no qualified entry falls back to the bare
1800    /// role — the pre-existing single-slot-per-mirror behavior is unchanged
1801    /// for services that never declared a qualified key.
1802    #[test]
1803    fn slot_falls_back_to_bare_role_for_unqualified_component() {
1804        let mut fx = Fixture::new(local_static_slot(4321), true);
1805        fx.mirror
1806            .providers
1807            .insert("static:other-component".to_string(), local_static_slot(9999));
1808        let slot = fx.ctx().slot("static").expect("slot present");
1809        let MirrorProviderSlot::Inline { fields, .. } = slot else {
1810            panic!("expected inline slot");
1811        };
1812        assert_eq!(slot_field_u16(fields, "port"), Some(4321));
1813    }
1814
1815    fn miniflare_container_slot(port: u16) -> MirrorProviderSlot {
1816        let mut fields = BTreeMap::new();
1817        fields.insert("port".to_string(), toml::Value::Integer(port as i64));
1818        fields.insert(
1819            "bucket".to_string(),
1820            toml::Value::String("yah-dev".to_string()),
1821        );
1822        MirrorProviderSlot::Inline {
1823            kind: Provider::MiniflareContainer,
1824            fields,
1825        }
1826    }
1827
1828    #[tokio::test]
1829    async fn up_miniflare_container_bails_when_object_store_slot_missing() {
1830        // MiniflareContainer dispatches into pond::up_pond, which
1831        // requires a sibling providers.object_store slot. Missing → clear
1832        // error before we attempt to talk to docker.
1833        let fx = Fixture::new(miniflare_container_slot(4322), true);
1834        let reconciler = MesofactStaticReconciler::new();
1835        let err = reconciler.up(fx.ctx()).await.unwrap_err();
1836        let msg = format!("{err:#}");
1837        assert!(
1838            msg.contains("providers.object_store"),
1839            "error must mention the missing sibling slot; got: {msg}"
1840        );
1841        assert!(
1842            msg.contains("pond"),
1843            "error must name the requesting code path; got: {msg}"
1844        );
1845    }
1846
1847    #[tokio::test]
1848    async fn up_miniflare_container_bails_when_object_store_kind_wrong() {
1849        let mut fx = Fixture::new(miniflare_container_slot(4322), true);
1850        // Drop in a non-MinIO inline slot at object_store.
1851        fx.mirror.providers.insert(
1852            "object_store".into(),
1853            MirrorProviderSlot::Inline {
1854                kind: Provider::LocalStatic,
1855                fields: BTreeMap::new(),
1856            },
1857        );
1858        let reconciler = MesofactStaticReconciler::new();
1859        let err = reconciler.up(fx.ctx()).await.unwrap_err();
1860        let msg = format!("{err:#}");
1861        assert!(
1862            msg.contains("minio-container"),
1863            "error must name the expected kind; got: {msg}"
1864        );
1865    }
1866
1867    #[tokio::test]
1868    async fn up_bails_on_cloudflare_reference_slot() {
1869        let cloudflare = MirrorProviderSlot::Reference {
1870            provider_id: "cloudflare".to_string(),
1871            fields: BTreeMap::new(),
1872        };
1873        let fx = Fixture::new(cloudflare, true);
1874        let reconciler = MesofactStaticReconciler::new();
1875        let err = reconciler.up(fx.ctx()).await.unwrap_err();
1876        let msg = format!("{err:#}");
1877        assert!(msg.contains("cloudflare"), "got: {msg}");
1878    }
1879
1880    /// Regression for R330-B5: a cloud mirror that supplies bucket+zone but
1881    /// omits `asset_origin` must fail loudly at reconcile time. Otherwise the
1882    /// Worker silently gets `env.ASSET_ORIGIN=""` and 404s every request in
1883    /// prod (R327-F2 gotcha).
1884    #[tokio::test]
1885    async fn up_bails_on_cloudflare_reference_missing_asset_origin() {
1886        let mut fields = BTreeMap::new();
1887        fields.insert(
1888            "bucket".to_string(),
1889            toml::Value::String("yah-dev".to_string()),
1890        );
1891        fields.insert(
1892            "zone".to_string(),
1893            toml::Value::String("yah.dev".to_string()),
1894        );
1895        let cloudflare = MirrorProviderSlot::Reference {
1896            provider_id: "cloudflare".to_string(),
1897            fields,
1898        };
1899        let fx = Fixture::new(cloudflare, true);
1900        // Write a minimal cloudflare provider config so the asset_origin
1901        // check is the first thing that fails (otherwise the missing
1902        // provider file aborts the run earlier).
1903        let providers_dir = fx.workspace_root.join(".yah/infra/providers");
1904        std::fs::create_dir_all(&providers_dir).unwrap();
1905        std::fs::write(
1906            providers_dir.join("cloudflare.toml"),
1907            r#"schema_version = 1
1908id = "cloudflare"
1909kind = "cloudflare"
1910account_id = "test-account"
1911"#,
1912        )
1913        .unwrap();
1914        let reconciler = MesofactStaticReconciler::new();
1915        let err = reconciler.up(fx.ctx()).await.unwrap_err();
1916        let msg = format!("{err:#}");
1917        assert!(
1918            msg.contains("asset_origin"),
1919            "error must name asset_origin; got: {msg}"
1920        );
1921    }
1922
1923    /// R432-B2: stale jit file claiming the configured port must not produce
1924    /// "dynamic fallback" language — no second probe was attempted.
1925    #[tokio::test]
1926    async fn adopt_only_stale_jit_same_port_omits_dynamic_fallback_phrase() {
1927        let port = pick_unused_port();
1928        let fx = Fixture::new(local_static_slot(port), true);
1929        let jit_dir = fx.workspace_root.join(".yah/jit");
1930        std::fs::create_dir_all(&jit_dir).unwrap();
1931        std::fs::write(
1932            jit_dir.join("mesofact-dev-ports.json"),
1933            format!(r#"{{"test-svc/site": {port}}}"#),
1934        )
1935        .unwrap();
1936        let reconciler = MesofactStaticReconciler::new().with_local_static(LocalStaticOptions {
1937            adopt_only: true,
1938            ..Default::default()
1939        });
1940        let err = reconciler.up(fx.ctx()).await.unwrap_err();
1941        let msg = format!("{err:#}");
1942        assert!(
1943            !msg.contains("dynamic fallback"),
1944            "stale jit at configured port must not claim a dynamic probe; got: {msg}"
1945        );
1946        assert!(
1947            !msg.contains("jit file"),
1948            "same-port jit entry must not appear in the error; got: {msg}"
1949        );
1950    }
1951
1952    /// R432-B2: when camp is up but jit records a different dead port, name it.
1953    /// Requires a live socket so the error takes the Case-B "camp up" branch.
1954    #[cfg(unix)]
1955    #[tokio::test]
1956    async fn adopt_only_stale_jit_different_port_names_it() {
1957        use std::os::unix::net::UnixListener;
1958
1959        let port = pick_unused_port();
1960        let jit_port = pick_unused_port();
1961        let fx = Fixture::new(local_static_slot(port), true);
1962        let jit_dir = fx.workspace_root.join(".yah/jit");
1963        std::fs::create_dir_all(&jit_dir).unwrap();
1964        std::fs::write(
1965            jit_dir.join("mesofact-dev-ports.json"),
1966            format!(r#"{{"test-svc/site": {jit_port}}}"#),
1967        )
1968        .unwrap();
1969        let socket_path = fx.workspace_root.join("camp.sock");
1970        let _listener = UnixListener::bind(&socket_path).unwrap();
1971        let reconciler = MesofactStaticReconciler::new().with_local_static(LocalStaticOptions {
1972            adopt_only: true,
1973            camp_socket: Some(socket_path),
1974            ..Default::default()
1975        });
1976        let err = reconciler.up(fx.ctx()).await.unwrap_err();
1977        let msg = format!("{err:#}");
1978        assert!(
1979            msg.contains(&jit_port.to_string()),
1980            "error must name the dead jit port; got: {msg}"
1981        );
1982        assert!(
1983            !msg.contains("dynamic fallback"),
1984            "precise port naming replaces generic 'dynamic fallback'; got: {msg}"
1985        );
1986    }
1987
1988    /// R432-F3: no camp socket → "not running" / attach message (no socket probe noise).
1989    #[tokio::test]
1990    async fn adopt_only_no_camp_socket_gives_attach_message() {
1991        let fx = Fixture::new(local_static_slot(pick_unused_port()), true);
1992        let reconciler = MesofactStaticReconciler::new().with_local_static(LocalStaticOptions {
1993            adopt_only: true,
1994            camp_socket: None, // no socket path — treated as camp not running
1995            ..Default::default()
1996        });
1997        let err = reconciler.up(fx.ctx()).await.unwrap_err();
1998        let msg = format!("{err:#}");
1999        assert!(
2000            msg.contains("not running") || msg.contains("attach"),
2001            "no-socket path must indicate camp is not attached; got: {msg}"
2002        );
2003    }
2004
2005    /// R432-F3: live camp socket but no server → "camp is up but didn't bind".
2006    #[cfg(unix)]
2007    #[tokio::test]
2008    async fn adopt_only_live_camp_socket_gives_didnt_bind_message() {
2009        use std::os::unix::net::UnixListener;
2010
2011        let fx = Fixture::new(local_static_slot(pick_unused_port()), true);
2012        let socket_path = fx.workspace_root.join("camp.sock");
2013        let _listener = UnixListener::bind(&socket_path).unwrap();
2014
2015        let reconciler = MesofactStaticReconciler::new().with_local_static(LocalStaticOptions {
2016            adopt_only: true,
2017            camp_socket: Some(socket_path),
2018            ..Default::default()
2019        });
2020        let err = reconciler.up(fx.ctx()).await.unwrap_err();
2021        let msg = format!("{err:#}");
2022        assert!(
2023            msg.contains("a yah daemon is up but"),
2024            "live socket must give 'daemon is up but didn't bind' message; got: {msg}"
2025        );
2026        assert!(
2027            msg.contains("did not bind"),
2028            "message must name the bind failure; got: {msg}"
2029        );
2030    }
2031
2032    #[tokio::test]
2033    async fn up_bails_when_binary_not_found() {
2034        let fx = Fixture::new(local_static_slot(0), true);
2035        let reconciler = MesofactStaticReconciler::new().with_local_static(LocalStaticOptions {
2036            binary: Some(PathBuf::from("/definitely/not/a/binary")),
2037            ready_timeout: Some(Duration::from_millis(50)),
2038            ..Default::default()
2039        });
2040        let err = reconciler.up(fx.ctx()).await.unwrap_err();
2041        let msg = format!("{err:#}");
2042        assert!(msg.contains("spawning"), "got: {msg}");
2043    }
2044
2045    /// R490-F2: native_ident produces a DNS-/path-safe slug.
2046    #[test]
2047    fn native_ident_sanitizes_to_path_safe_slug() {
2048        assert_eq!(
2049            native_ident("dev-yah", "static"),
2050            "mesofact-dev-dev-yah-static"
2051        );
2052        // Non-alphanumerics (incl. slashes, dots) collapse to '-'; lowercased.
2053        assert_eq!(native_ident("Foo.Bar", "a/b"), "mesofact-dev-foo-bar-a-b");
2054    }
2055
2056    /// R490-F2: the mesofact-dev invocation lowers into the Native backend's
2057    /// container-`command` shape with the no-pull identity digest.
2058    #[test]
2059    fn native_mesofact_spec_lowers_argv_and_identity() {
2060        let spec = native_spec(
2061            "mesofact-dev-site-static",
2062            vec![
2063                "/bin/mesofact-dev".into(),
2064                "/wd".into(),
2065                "--port".into(),
2066                "4321".into(),
2067            ],
2068            Vec::new(),
2069        );
2070        assert_eq!(spec.name, "mesofact-dev-site-static");
2071        assert_eq!(spec.entrypoint, None);
2072        assert_eq!(spec.command.as_deref().unwrap()[0], "/bin/mesofact-dev");
2073        assert_eq!(spec.expose.mesh.identity.0, "mesofact-dev-site-static");
2074        assert_eq!(spec.image.digest, NATIVE_IDENTITY_DIGEST);
2075        assert_eq!(spec.replicas, 1);
2076    }
2077
2078    /// Wait-for-port: bind a local TCP listener in-process, confirm
2079    /// `wait_for_port` returns true within timeout.
2080    #[tokio::test]
2081    async fn wait_for_port_returns_true_when_port_bound() {
2082        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
2083        let addr = listener.local_addr().unwrap();
2084        assert!(wait_for_port(addr, Duration::from_millis(500)).await);
2085        drop(listener);
2086    }
2087
2088    #[tokio::test]
2089    async fn wait_for_port_returns_false_when_port_idle() {
2090        // Bind + drop to get an ephemeral port that's now definitely
2091        // unbound (modulo races; ignore the rare false flake).
2092        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
2093        let addr = listener.local_addr().unwrap();
2094        drop(listener);
2095        assert!(!wait_for_port(addr, Duration::from_millis(100)).await);
2096    }
2097
2098    // ---------- Worker script + config bindings ----------
2099
2100    #[test]
2101    fn worker_script_maps_root_to_index_html() {
2102        assert!(
2103            WORKER_SCRIPT.contains("index.html"),
2104            "bundled Worker must route / to index.html; got: {WORKER_SCRIPT}"
2105        );
2106    }
2107
2108    #[test]
2109    fn worker_script_has_no_r2_binding_calls() {
2110        assert!(
2111            !WORKER_SCRIPT.contains("env.ASSETS"),
2112            "bundled Worker must not reference R2 binding env.ASSETS; got: {WORKER_SCRIPT}"
2113        );
2114        assert!(
2115            !WORKER_SCRIPT.contains("writeHttpMetadata"),
2116            "bundled Worker must not use R2 writeHttpMetadata; got: {WORKER_SCRIPT}"
2117        );
2118    }
2119
2120    #[test]
2121    fn worker_script_uses_asset_origin_fetch() {
2122        assert!(
2123            WORKER_SCRIPT.contains("ASSET_ORIGIN"),
2124            "bundled Worker must fetch from ASSET_ORIGIN; got: {WORKER_SCRIPT}"
2125        );
2126    }
2127
2128    /// The vendored @mesofact/edge bundle must carry the W270 §3 serving logic:
2129    /// manifest read, pointer-store resolution for instance-addressed routes,
2130    /// and manifest error_routes. Substring markers (not behavior — behavior is
2131    /// covered by the miniflare tests in oss/mesofact/packages/mesofact-edge).
2132    #[test]
2133    fn worker_script_resolves_pointers_and_error_routes() {
2134        assert!(
2135            WORKER_SCRIPT.contains("manifest.json"),
2136            "bundled Worker must read the published manifest; got: {WORKER_SCRIPT}"
2137        );
2138        assert!(
2139            WORKER_SCRIPT.contains("POINTER_ORIGIN"),
2140            "bundled Worker must resolve pointers via POINTER_ORIGIN; got: {WORKER_SCRIPT}"
2141        );
2142        assert!(
2143            WORKER_SCRIPT.contains("error_routes"),
2144            "bundled Worker must honor manifest error_routes; got: {WORKER_SCRIPT}"
2145        );
2146    }
2147
2148    /// The binding is only useful if the vendored bundle actually reads it —
2149    /// `scripts/check-worker-bundle.sh` keeps the two in sync, and this catches
2150    /// a bundle vendored from before R746.
2151    #[test]
2152    fn bundled_worker_reads_route_headers() {
2153        assert!(
2154            WORKER_SCRIPT.contains("ROUTE_HEADERS"),
2155            "bundled Worker must apply per-route response headers; got: {WORKER_SCRIPT}"
2156        );
2157    }
2158
2159    // ── R746: component mount → publish prefix ──
2160
2161    #[test]
2162    fn unmounted_component_publishes_at_the_service_root() {
2163        assert_eq!(publish_prefix("noisetable-marketing", "cloud", None), "noisetable-marketing/cloud");
2164    }
2165
2166    #[test]
2167    fn a_mount_extends_the_prefix_and_is_slash_insensitive() {
2168        for m in ["/app", "app", "app/", "/app/"] {
2169            assert_eq!(
2170                publish_prefix("noisetable-marketing", "cloud", Some(m)),
2171                "noisetable-marketing/cloud/app",
2172                "mount {m:?}"
2173            );
2174        }
2175    }
2176
2177    /// A root mount is the same thing as no mount — not a trailing-slash key
2178    /// prefix, which would publish every asset one directory too deep.
2179    #[test]
2180    fn a_root_mount_is_the_service_root() {
2181        assert_eq!(publish_prefix("svc", "cloud", Some("/")), "svc/cloud");
2182        assert_eq!(publish_prefix("svc", "cloud", Some("")), "svc/cloud");
2183    }
2184
2185    /// The whole point: two static components of one service must not collide.
2186    #[test]
2187    fn two_components_of_one_service_get_disjoint_prefixes() {
2188        let site = publish_prefix("noisetable-marketing", "cloud", None);
2189        let app = publish_prefix("noisetable-marketing", "cloud", Some("/app"));
2190        assert_ne!(site, app);
2191        assert!(app.starts_with(&format!("{site}/")), "{app} under {site}");
2192    }
2193
2194    #[test]
2195    fn config_bindings_carry_the_route_header_table() {
2196        let table = r#"[{"path":"/app/*","headers":{"Cross-Origin-Opener-Policy":"same-origin"}}]"#;
2197        let b: std::collections::HashMap<_, _> = worker_config_bindings(
2198            &WorkerMode::Static,
2199            "https://assets.example.com",
2200            &BackendOrigins::default(),
2201            table,
2202        )
2203        .into_iter()
2204        .collect();
2205        assert_eq!(b["ROUTE_HEADERS"], table);
2206    }
2207
2208    #[test]
2209    fn config_bindings_static_mode() {
2210        let b: std::collections::HashMap<_, _> = worker_config_bindings(
2211            &WorkerMode::Static,
2212            "https://assets.example.com",
2213            &BackendOrigins::default(),
2214            "[]",
2215        )
2216        .into_iter()
2217        .collect();
2218        assert_eq!(b["WORKER_MODE"], "static");
2219        assert_eq!(b["ASSET_ORIGIN"], "https://assets.example.com");
2220        // Pointer origin defaults to the asset origin (W270 §3).
2221        assert_eq!(b["POINTER_ORIGIN"], "https://assets.example.com");
2222        assert_eq!(b["SSR_ORIGIN"], "");
2223        assert_eq!(b["SSR_PREFIXES"], "[]");
2224        // Undeclared backends are emitted EMPTY, not omitted: the binding list
2225        // is authoritative, so an omitted key would leave a stale value from an
2226        // earlier deploy in place.
2227        assert_eq!(b["ISSUES_ORIGIN"], "");
2228        assert_eq!(b["MESOFACT_BACKEND_ORIGIN"], "");
2229    }
2230
2231    #[test]
2232    fn config_bindings_spa_mode() {
2233        let b: std::collections::HashMap<_, _> = worker_config_bindings(
2234            &WorkerMode::Spa,
2235            "https://assets.example.com",
2236            &BackendOrigins::default(),
2237            "[]",
2238        )
2239        .into_iter()
2240        .collect();
2241        assert_eq!(b["WORKER_MODE"], "spa");
2242        assert_eq!(b["SSR_ORIGIN"], "");
2243    }
2244
2245    /// R330-F13: `/api/issues*` reaches the issue-tracker only when the static
2246    /// slot's `issues_origin` becomes an `ISSUES_ORIGIN` Worker binding.
2247    #[test]
2248    fn config_bindings_carry_backend_origins() {
2249        let mut fields = std::collections::BTreeMap::new();
2250        fields.insert(
2251            "issues_origin".to_string(),
2252            // Trailing slash trimmed — the router concatenates "/issues".
2253            toml::Value::String("https://issues.example.com/".to_string()),
2254        );
2255        fields.insert(
2256            "backend_origin".to_string(),
2257            toml::Value::String("https://almanac.example.com".to_string()),
2258        );
2259        let backends = BackendOrigins::from_slot_fields(&fields);
2260        assert_eq!(backends.issues, "https://issues.example.com");
2261
2262        let b: std::collections::HashMap<_, _> = worker_config_bindings(
2263            &WorkerMode::Static,
2264            "https://assets.example.com",
2265            &backends,
2266            "[]",
2267        )
2268        .into_iter()
2269        .collect();
2270        assert_eq!(b["ISSUES_ORIGIN"], "https://issues.example.com");
2271        assert_eq!(b["MESOFACT_BACKEND_ORIGIN"], "https://almanac.example.com");
2272    }
2273
2274    /// The vendored bundle must actually read the binding this reconciler now
2275    /// emits — otherwise the config lands and nothing routes.
2276    #[test]
2277    fn worker_script_reads_issues_origin() {
2278        assert!(
2279            WORKER_SCRIPT.contains("ISSUES_ORIGIN"),
2280            "bundled Worker must route /api/issues* via ISSUES_ORIGIN"
2281        );
2282    }
2283
2284    #[test]
2285    fn config_bindings_ssr_mode() {
2286        let mode = WorkerMode::Ssr {
2287            origin_url: "https://ssr.example.com".to_string(),
2288            prefixes: vec!["/api/".to_string(), "/rpc/".to_string()],
2289        };
2290        let b: std::collections::HashMap<_, _> = worker_config_bindings(
2291            &mode,
2292            "https://assets.example.com",
2293            &BackendOrigins::default(),
2294            "[]",
2295        )
2296        .into_iter()
2297        .collect();
2298        assert_eq!(b["WORKER_MODE"], "ssr");
2299        assert_eq!(b["SSR_ORIGIN"], "https://ssr.example.com");
2300        let prefixes: Vec<String> = serde_json::from_str(&b["SSR_PREFIXES"]).unwrap();
2301        assert!(prefixes.contains(&"/api/".to_string()));
2302        assert!(prefixes.contains(&"/rpc/".to_string()));
2303    }
2304
2305    #[test]
2306    fn worker_script_hash_roundtrip() {
2307        let tmp = tempdir().unwrap();
2308        let root = tmp.path();
2309        assert!(read_worker_script_hash(root, "test-worker").is_none());
2310        write_worker_script_hash(root, "test-worker", "abc123").unwrap();
2311        assert_eq!(
2312            read_worker_script_hash(root, "test-worker").as_deref(),
2313            Some("abc123")
2314        );
2315        // Writing a second worker doesn't clobber the first.
2316        write_worker_script_hash(root, "other-worker", "def456").unwrap();
2317        assert_eq!(
2318            read_worker_script_hash(root, "test-worker").as_deref(),
2319            Some("abc123")
2320        );
2321    }
2322
2323    #[test]
2324    fn parse_worker_mode_defaults_to_static() {
2325        let fields = BTreeMap::new();
2326        assert!(matches!(
2327            parse_worker_mode(WORKLOAD_KIND, &fields),
2328            WorkerMode::Static
2329        ));
2330    }
2331
2332    #[test]
2333    fn parse_worker_mode_spa_kind_defaults_to_spa() {
2334        let fields = BTreeMap::new();
2335        assert!(matches!(
2336            parse_worker_mode(WORKLOAD_KIND_SPA, &fields),
2337            WorkerMode::Spa
2338        ));
2339    }
2340
2341    #[test]
2342    fn parse_worker_mode_explicit_mode_beats_kind_default() {
2343        let mut fields = BTreeMap::new();
2344        fields.insert(
2345            "mode".to_string(),
2346            toml::Value::String("static".to_string()),
2347        );
2348        assert!(matches!(
2349            parse_worker_mode(WORKLOAD_KIND_SPA, &fields),
2350            WorkerMode::Static
2351        ));
2352    }
2353
2354    #[test]
2355    fn parse_worker_mode_spa() {
2356        let mut fields = BTreeMap::new();
2357        fields.insert("mode".to_string(), toml::Value::String("spa".to_string()));
2358        assert!(matches!(
2359            parse_worker_mode(WORKLOAD_KIND, &fields),
2360            WorkerMode::Spa
2361        ));
2362    }
2363
2364    #[test]
2365    fn parse_worker_mode_ssr_extracts_origin_and_prefixes() {
2366        let mut fields = BTreeMap::new();
2367        fields.insert("mode".to_string(), toml::Value::String("ssr".to_string()));
2368        fields.insert(
2369            "origin_url".to_string(),
2370            toml::Value::String("https://origin.example.com".to_string()),
2371        );
2372        fields.insert(
2373            "ssr_prefixes".to_string(),
2374            toml::Value::Array(vec![toml::Value::String("/api/".to_string())]),
2375        );
2376        if let WorkerMode::Ssr {
2377            origin_url,
2378            prefixes,
2379        } = parse_worker_mode(WORKLOAD_KIND, &fields)
2380        {
2381            assert_eq!(origin_url, "https://origin.example.com");
2382            assert_eq!(prefixes, vec!["/api/"]);
2383        } else {
2384            panic!("expected Ssr mode");
2385        }
2386    }
2387
2388    // ---------- W165: BuildMode → ForgeSpec lowering (R438-T6) ----------
2389
2390    use std::sync::Mutex as StdMutex;
2391    use tokio::sync::mpsc::UnboundedSender;
2392    use velveteen::ForgeStatus;
2393    use velveteen_exec::executor::{ExecEvent, ExecOutcome, ForgeExecutorError};
2394
2395    /// Captures the [`ForgeSpec`] handed to `execute(...)` and returns
2396    /// success without spawning anything.
2397    struct CaptureExecutor {
2398        captured: Arc<StdMutex<Vec<(ForgeSpec, ExecContext)>>>,
2399    }
2400
2401    impl CaptureExecutor {
2402        fn new() -> (Arc<Self>, Arc<StdMutex<Vec<(ForgeSpec, ExecContext)>>>) {
2403            let captured = Arc::new(StdMutex::new(Vec::new()));
2404            (
2405                Arc::new(Self {
2406                    captured: captured.clone(),
2407                }),
2408                captured,
2409            )
2410        }
2411    }
2412
2413    #[async_trait]
2414    impl ForgeExecutor for CaptureExecutor {
2415        async fn execute(
2416            &self,
2417            spec: ForgeSpec,
2418            ctx: ExecContext,
2419            _sink: Option<UnboundedSender<ExecEvent>>,
2420        ) -> Result<ExecOutcome, ForgeExecutorError> {
2421            self.captured.lock().unwrap().push((spec, ctx));
2422            Ok(ExecOutcome {
2423                status: ForgeStatus::Done {
2424                    exit_code: 0,
2425                    ended_at: 0,
2426                },
2427                stderr_tail: String::new(),
2428            })
2429        }
2430    }
2431
2432    /// Executor whose runs all return a non-zero exit + canned stderr —
2433    /// used to assert error-message shape from [`run_build`].
2434    struct FailingExecutor {
2435        stderr: String,
2436    }
2437
2438    #[async_trait]
2439    impl ForgeExecutor for FailingExecutor {
2440        async fn execute(
2441            &self,
2442            _spec: ForgeSpec,
2443            _ctx: ExecContext,
2444            _sink: Option<UnboundedSender<ExecEvent>>,
2445        ) -> Result<ExecOutcome, ForgeExecutorError> {
2446            Ok(ExecOutcome {
2447                status: ForgeStatus::Done {
2448                    exit_code: 2,
2449                    ended_at: 0,
2450                },
2451                stderr_tail: self.stderr.clone(),
2452            })
2453        }
2454    }
2455
2456    fn host_side_build() -> (BuildConfig, BuildMode) {
2457        (
2458            BuildConfig {
2459                command: Some("bun run build".into()),
2460                out_dir: PathBuf::from("dist"),
2461                render_command: None,
2462            },
2463            BuildMode::HostSide,
2464        )
2465    }
2466
2467    fn in_container_build() -> (BuildConfig, BuildMode) {
2468        let image = workload_spec::ImageRef {
2469            registry: "ghcr.io".into(),
2470            repository: "org/app-build".into(),
2471            tag: "v1.2".into(),
2472            digest: workload_spec::testing::test_digest(),
2473        };
2474        (
2475            BuildConfig {
2476                command: Some("bun run build".into()),
2477                out_dir: PathBuf::from("dist"),
2478                render_command: None,
2479            },
2480            BuildMode::InContainer { image },
2481        )
2482    }
2483
2484    #[tokio::test]
2485    async fn run_build_host_side_lowers_to_native_subprocess() {
2486        let (capture, captured) = CaptureExecutor::new();
2487        let tmp = tempdir().unwrap();
2488        let (build, mode) = host_side_build();
2489        run_build(tmp.path(), &build, &mode, &*capture)
2490            .await
2491            .unwrap();
2492
2493        let captured = captured.lock().unwrap();
2494        assert_eq!(captured.len(), 1, "build executed exactly once");
2495        let (spec, ctx) = &captured[0];
2496        assert_eq!(spec.where_.runtime, TaskRuntime::Native);
2497        assert_eq!(spec.where_.location, TaskLocation::Local);
2498        match &spec.command {
2499            ForgeCommand::Subprocess { argv, image } => {
2500                assert!(image.is_none(), "host_side carries no image; got {image:?}");
2501                assert_eq!(
2502                    argv,
2503                    &vec!["sh".to_string(), "-c".into(), "bun run build".into()]
2504                );
2505            }
2506            other => panic!("expected Subprocess, got {other:?}"),
2507        }
2508        assert_eq!(ctx.cwd.as_deref(), Some(tmp.path()));
2509    }
2510
2511    #[tokio::test]
2512    async fn run_build_in_container_lowers_to_container_runtime_with_pinned_digest() {
2513        let (capture, captured) = CaptureExecutor::new();
2514        let tmp = tempdir().unwrap();
2515        let (build, mode) = in_container_build();
2516        run_build(tmp.path(), &build, &mode, &*capture)
2517            .await
2518            .unwrap();
2519
2520        let captured = captured.lock().unwrap();
2521        let (spec, ctx) = &captured[0];
2522        assert_eq!(spec.where_.runtime, TaskRuntime::Container);
2523        assert_eq!(spec.where_.location, TaskLocation::Local);
2524        match &spec.command {
2525            ForgeCommand::Subprocess { argv, image } => {
2526                let image = image.as_ref().expect("in_container lowers with an image");
2527                assert_eq!(image.registry, "ghcr.io");
2528                assert_eq!(image.repository, "org/app-build");
2529                assert_eq!(image.tag, "v1.2");
2530                assert_eq!(image.digest, workload_spec::testing::test_digest());
2531                assert_eq!(
2532                    argv,
2533                    &vec!["sh".to_string(), "-c".into(), "bun run build".into()]
2534                );
2535            }
2536            other => panic!("expected Subprocess, got {other:?}"),
2537        }
2538        assert_eq!(ctx.cwd.as_deref(), Some(tmp.path()));
2539    }
2540
2541    #[tokio::test]
2542    async fn run_build_surfaces_stderr_on_nonzero_exit() {
2543        let executor = Arc::new(FailingExecutor {
2544            stderr: "TypeError: Cannot find module 'react'".into(),
2545        });
2546        let tmp = tempdir().unwrap();
2547        let (build, mode) = host_side_build();
2548        let err = run_build(tmp.path(), &build, &mode, &*executor)
2549            .await
2550            .unwrap_err();
2551        let msg = format!("{err:#}");
2552        assert!(msg.contains("Cannot find module 'react'"), "got: {msg}");
2553        assert!(msg.contains("bun run build"), "got: {msg}");
2554    }
2555
2556    #[tokio::test]
2557    async fn read_mesofact_build_extracts_host_side_default() {
2558        let tmp = tempdir().unwrap();
2559        // Use the legacy `schema_version = 1` integer shape — production
2560        // marketing/dashboard workload.tomls carry this and rebuild_static
2561        // must keep working against them. The subtree reader skips the
2562        // envelope so this round-trips.
2563        std::fs::write(
2564            tmp.path().join("workload.toml"),
2565            r#"schema_version = 1
2566kind = "mesofact-static"
2567routes = "./routes.ts"
2568
2569[build]
2570command = "bun run build"
2571out_dir = "dist"
2572"#,
2573        )
2574        .unwrap();
2575        let (build, mode) = read_mesofact_build(tmp.path()).unwrap().unwrap();
2576        assert_eq!(build.command.as_deref(), Some("bun run build"));
2577        assert_eq!(build.out_dir, PathBuf::from("dist"));
2578        assert!(matches!(mode, BuildMode::HostSide));
2579    }
2580
2581    #[tokio::test]
2582    async fn read_mesofact_build_extracts_in_container_with_digest() {
2583        let tmp = tempdir().unwrap();
2584        let digest = workload_spec::testing::test_digest();
2585        std::fs::write(
2586            tmp.path().join("workload.toml"),
2587            format!(
2588                r#"schema_version = 1
2589kind = "mesofact-static"
2590routes = "./routes.ts"
2591
2592[build]
2593command = "bun run build"
2594out_dir = "dist"
2595
2596[build_mode.in_container.image]
2597registry = "ghcr.io"
2598repository = "org/app-build"
2599tag = "v1.2"
2600digest = "{digest}"
2601"#
2602            ),
2603        )
2604        .unwrap();
2605        let (build, mode) = read_mesofact_build(tmp.path()).unwrap().unwrap();
2606        assert_eq!(build.command.as_deref(), Some("bun run build"));
2607        match mode {
2608            BuildMode::InContainer { image } => {
2609                assert_eq!(image.registry, "ghcr.io");
2610                assert_eq!(image.repository, "org/app-build");
2611                assert_eq!(image.tag, "v1.2");
2612                assert_eq!(image.digest, digest);
2613            }
2614            other => panic!("expected InContainer, got {other:?}"),
2615        }
2616    }
2617
2618    #[tokio::test]
2619    async fn read_mesofact_build_rejects_in_container_without_digest() {
2620        let tmp = tempdir().unwrap();
2621        std::fs::write(
2622            tmp.path().join("workload.toml"),
2623            r#"schema_version = 1
2624kind = "mesofact-static"
2625routes = "./routes.ts"
2626
2627[build]
2628command = "bun run build"
2629out_dir = "dist"
2630
2631[build_mode.in_container]
2632image = "ghcr.io/org/app-build:v1.2"
2633"#,
2634        )
2635        .unwrap();
2636        let err = read_mesofact_build(tmp.path()).unwrap_err();
2637        let msg = format!("{err:#}");
2638        assert!(
2639            msg.contains("digest") || msg.contains("sha256"),
2640            "in_container with bare tag must reject at parse; got: {msg}"
2641        );
2642    }
2643
2644    #[tokio::test]
2645    async fn read_mesofact_build_returns_none_for_other_kinds() {
2646        let tmp = tempdir().unwrap();
2647        std::fs::write(
2648            tmp.path().join("workload.toml"),
2649            r#"schema_version = 1
2650kind = "static-asset"
2651"#,
2652        )
2653        .unwrap();
2654        assert!(read_mesofact_build(tmp.path()).unwrap().is_none());
2655    }
2656
2657    #[tokio::test]
2658    async fn read_mesofact_build_returns_none_when_file_absent() {
2659        let tmp = tempdir().unwrap();
2660        assert!(read_mesofact_build(tmp.path()).unwrap().is_none());
2661    }
2662
2663    /// R838-B1: a `[build]` table declaring only `out_dir` is the shape
2664    /// `mesofact new` scaffolds — the project builds through the in-process
2665    /// pipeline and has no shell command to run.
2666    #[tokio::test]
2667    async fn read_mesofact_build_accepts_a_build_table_with_no_command() {
2668        let tmp = tempdir().unwrap();
2669        std::fs::write(
2670            tmp.path().join("workload.toml"),
2671            r#"schema_version = 1
2672kind = "mesofact-static"
2673routes = "./mesofact.routes.ts"
2674
2675[build]
2676out_dir = "dist"
2677"#,
2678        )
2679        .unwrap();
2680        let (build, mode) = read_mesofact_build(tmp.path()).unwrap().unwrap();
2681        assert_eq!(build.command, None);
2682        assert_eq!(build.out_dir, PathBuf::from("dist"));
2683        assert!(matches!(mode, BuildMode::HostSide));
2684    }
2685
2686    /// R838-B1: no `build.command` → no build step, not `sh -c ""`.
2687    ///
2688    /// An empty shell command exits 0 having produced nothing, so the
2689    /// reconciler would report a successful build and then publish whatever
2690    /// stale bytes were in `out_dir`. The skip has to happen at the lowering,
2691    /// which is what `lower_build_to_forge_spec` returning `None` pins.
2692    #[tokio::test]
2693    async fn rebuild_static_skips_the_build_step_when_no_command_is_declared() {
2694        let fx = Fixture::new(cloudflare_reference_slot(), /*write_workload*/ false);
2695        let workload_dir = fx.workspace_root.join("app/web");
2696        std::fs::write(
2697            workload_dir.join("workload.toml"),
2698            r#"schema_version = 1
2699kind = "mesofact-static"
2700routes = "./mesofact.routes.ts"
2701
2702[build]
2703out_dir = "dist"
2704"#,
2705        )
2706        .unwrap();
2707
2708        let (capture, captured) = CaptureExecutor::new();
2709        let reconciler = MesofactStaticReconciler::new().with_executor(capture.clone());
2710
2711        // As in the sibling tests, up_cloudflare_r2 fails for want of provider
2712        // config — but only AFTER the build step would have run.
2713        let _ = reconciler.rebuild_static(fx.ctx()).await;
2714
2715        assert!(
2716            captured.lock().unwrap().is_empty(),
2717            "a manifest with no build.command must dispatch nothing to the executor"
2718        );
2719    }
2720
2721    /// The lowering itself is the seam, so pin it directly too — a future
2722    /// caller that reaches `lower_build_to_forge_spec` without going through
2723    /// `run_build` inherits the same refusal.
2724    #[test]
2725    fn lowering_a_build_with_no_command_yields_no_forge_spec() {
2726        let build = BuildConfig {
2727            command: None,
2728            out_dir: PathBuf::from("dist"),
2729            render_command: None,
2730        };
2731        assert!(lower_build_to_forge_spec(
2732            std::path::Path::new("/workspace/app/web"),
2733            &build,
2734            &BuildMode::HostSide,
2735        )
2736        .is_none());
2737    }
2738
2739    #[tokio::test]
2740    async fn rebuild_static_lifts_build_mode_through_executor() {
2741        // End-to-end smoke through rebuild_static → run_build → executor for
2742        // the cloudflare publish arm. InContainer build_mode must reach the
2743        // executor as TaskRuntime::Container (the CF path does not skip container
2744        // builds — only local-static does, per W165 OQ#1, tested separately).
2745        // up_cloudflare_r2 will fail (no provider config), but the build step
2746        // runs first so the CaptureExecutor still records the lowered ForgeSpec.
2747        let fx = Fixture::new(cloudflare_reference_slot(), /*write_workload*/ false);
2748        let workload_dir = fx.workspace_root.join("app/web");
2749        let digest = workload_spec::testing::test_digest();
2750        std::fs::write(
2751            workload_dir.join("workload.toml"),
2752            format!(
2753                r#"schema_version = 1
2754kind = "mesofact-static"
2755routes = "./routes.ts"
2756
2757[build]
2758command = "bun run build"
2759out_dir = "dist"
2760
2761[build_mode.in_container.image]
2762registry = "ghcr.io"
2763repository = "org/app-build"
2764tag = "v1.2"
2765digest = "{digest}"
2766"#
2767            ),
2768        )
2769        .unwrap();
2770
2771        let (capture, captured) = CaptureExecutor::new();
2772        let reconciler = MesofactStaticReconciler::new().with_executor(capture.clone());
2773
2774        // up_cloudflare_r2 will fail (no provider config on disk) but only
2775        // AFTER the build step ran. We only care that the build path produced
2776        // a captured ForgeSpec with the right runtime.
2777        let _ = reconciler.rebuild_static(fx.ctx()).await;
2778
2779        let captured = captured.lock().unwrap();
2780        assert_eq!(captured.len(), 1, "build step executed exactly once");
2781        let (spec, _ctx) = &captured[0];
2782        assert_eq!(spec.where_.runtime, TaskRuntime::Container);
2783        match &spec.command {
2784            ForgeCommand::Subprocess { image, .. } => {
2785                let image = image.as_ref().unwrap();
2786                assert_eq!(image.digest, digest, "digest survives the round-trip");
2787            }
2788            other => panic!("expected Subprocess, got {other:?}"),
2789        }
2790    }
2791
2792    #[tokio::test]
2793    async fn rebuild_static_local_static_in_container_falls_back_to_host_side() {
2794        // W165 OQ#1 (R438-F9): local-static arm + in_container build_mode must
2795        // warn and fall back to host-side (TaskRuntime::Native). Dev machines
2796        // may not have docker, and the host watcher handles hot-reload.
2797        let fx = Fixture::new(local_static_slot(0), /*write_workload*/ false);
2798        let workload_dir = fx.workspace_root.join("app/web");
2799        let digest = workload_spec::testing::test_digest();
2800        std::fs::write(
2801            workload_dir.join("workload.toml"),
2802            format!(
2803                r#"schema_version = 1
2804kind = "mesofact-static"
2805routes = "./routes.ts"
2806
2807[build]
2808command = "bun run build"
2809out_dir = "dist"
2810
2811[build_mode.in_container.image]
2812registry = "ghcr.io"
2813repository = "org/app-build"
2814tag = "v1.2"
2815digest = "{digest}"
2816"#
2817            ),
2818        )
2819        .unwrap();
2820
2821        let (capture, captured) = CaptureExecutor::new();
2822        let reconciler = MesofactStaticReconciler::new()
2823            .with_executor(capture.clone())
2824            .with_local_static(LocalStaticOptions {
2825                binary: Some(PathBuf::from("/definitely/not/a/binary")),
2826                ready_timeout: Some(Duration::from_millis(50)),
2827                ..Default::default()
2828            });
2829        let _ = reconciler.rebuild_static(fx.ctx()).await;
2830
2831        let captured = captured.lock().unwrap();
2832        assert_eq!(
2833            captured.len(),
2834            1,
2835            "build step still ran (host-side fallback)"
2836        );
2837        let (spec, _) = &captured[0];
2838        assert_eq!(
2839            spec.where_.runtime,
2840            TaskRuntime::Native,
2841            "in_container overridden to Native for local-static arm"
2842        );
2843        match &spec.command {
2844            ForgeCommand::Subprocess { image, .. } => {
2845                assert!(
2846                    image.is_none(),
2847                    "image must be stripped when falling back to host-side; got {image:?}"
2848                );
2849            }
2850            other => panic!("expected Subprocess, got {other:?}"),
2851        }
2852    }
2853
2854    #[tokio::test]
2855    async fn rebuild_static_defaults_to_host_side_when_build_mode_omitted() {
2856        // Fixture writes a workload.toml without [build_mode] (the common
2857        // shape today). rebuild_static must default to HostSide.
2858        let fx = Fixture::new(local_static_slot(0), /*write_workload*/ true);
2859        let (capture, captured) = CaptureExecutor::new();
2860        let reconciler = MesofactStaticReconciler::new()
2861            .with_executor(capture.clone())
2862            .with_local_static(LocalStaticOptions {
2863                binary: Some(PathBuf::from("/definitely/not/a/binary")),
2864                ready_timeout: Some(Duration::from_millis(50)),
2865                ..Default::default()
2866            });
2867        let _ = reconciler.rebuild_static(fx.ctx()).await;
2868        let captured = captured.lock().unwrap();
2869        assert_eq!(
2870            captured.len(),
2871            1,
2872            "default build_mode still runs the build step"
2873        );
2874        assert_eq!(captured[0].0.where_.runtime, TaskRuntime::Native);
2875    }
2876
2877    #[tokio::test]
2878    async fn rebuild_static_skips_build_when_workload_toml_missing() {
2879        // No workload.toml on disk — rebuild_static must not panic in the
2880        // build step; the subsequent up() call surfaces the missing-manifest
2881        // error to the operator.
2882        let fx = Fixture::new(local_static_slot(0), /*write_workload*/ false);
2883        let (capture, captured) = CaptureExecutor::new();
2884        let reconciler = MesofactStaticReconciler::new().with_executor(capture.clone());
2885        let err = reconciler.rebuild_static(fx.ctx()).await.unwrap_err();
2886        let msg = format!("{err:#}");
2887        assert!(msg.contains("workload.toml"), "got: {msg}");
2888        assert!(
2889            captured.lock().unwrap().is_empty(),
2890            "no build executed when manifest missing",
2891        );
2892    }
2893
2894    // ── revalidate_static (R535-T1) ──────────────────────────────────────────
2895
2896    #[tokio::test]
2897    async fn revalidate_static_without_render_command_never_touches_executor() {
2898        // W225 §3 / R535-T1: an almanac on_change is a data-only trigger — it
2899        // must never re-run build.command, regardless of provider arm or
2900        // whether the subsequent publish step succeeds. The fixture's
2901        // workload.toml carries a real [build] table (write_workload=true)
2902        // but NO render_command — so the executor must record zero calls
2903        // (R535-T7 only runs the executor for a declared render_command).
2904        let fx = Fixture::new(cloudflare_reference_slot(), /*write_workload*/ true);
2905        let (capture, captured) = CaptureExecutor::new();
2906        let reconciler = MesofactStaticReconciler::new().with_executor(capture.clone());
2907
2908        // up_cloudflare_r2 will fail (no provider config on disk) — that's
2909        // expected and irrelevant here; only the executor call count matters.
2910        let _ = reconciler.revalidate_static(fx.ctx(), "/releases").await;
2911
2912        assert!(
2913            captured.lock().unwrap().is_empty(),
2914            "revalidate_static without render_command must never invoke the executor"
2915        );
2916    }
2917
2918    #[tokio::test]
2919    async fn revalidate_static_delegates_to_up() {
2920        // Without a render_command, revalidate_static's publish behavior must
2921        // be indistinguishable from calling up() directly. Same fixture, same
2922        // reconciler, two independent ReconcileCtx borrows: both arms must
2923        // hit the identical error (missing
2924        // .yah/infra/providers/cloudflare.toml) with byte-identical text.
2925        let fx = Fixture::new(cloudflare_reference_slot(), /*write_workload*/ true);
2926        let reconciler = MesofactStaticReconciler::new();
2927
2928        let revalidate_err = reconciler
2929            .revalidate_static(fx.ctx(), "/releases")
2930            .await
2931            .unwrap_err();
2932        let up_err = reconciler.up(fx.ctx()).await.unwrap_err();
2933
2934        assert_eq!(
2935            format!("{revalidate_err:#}"),
2936            format!("{up_err:#}"),
2937            "revalidate_static must delegate straight to up() with no extra behavior"
2938        );
2939    }
2940
2941    #[tokio::test]
2942    async fn revalidate_static_skips_build_when_workload_toml_missing() {
2943        // Mirrors rebuild_static_skips_build_when_workload_toml_missing:
2944        // revalidate_static must not panic when workload.toml is absent (no
2945        // [build] table → no render_command → no executor call); the
2946        // missing-manifest error surfaces from deeper in up().
2947        let fx = Fixture::new(local_static_slot(0), /*write_workload*/ false);
2948        let (capture, captured) = CaptureExecutor::new();
2949        let reconciler = MesofactStaticReconciler::new().with_executor(capture.clone());
2950        let err = reconciler
2951            .revalidate_static(fx.ctx(), "/releases")
2952            .await
2953            .unwrap_err();
2954        let msg = format!("{err:#}");
2955        assert!(msg.contains("workload.toml"), "got: {msg}");
2956        assert!(
2957            captured.lock().unwrap().is_empty(),
2958            "no build executed by revalidate_static",
2959        );
2960    }
2961
2962    // ── revalidate_static render_command (R535-T7) ───────────────────────────
2963
2964    fn write_workload_with_render_command(fx: &Fixture) {
2965        std::fs::write(
2966            fx.workspace_root.join("app/web/workload.toml"),
2967            r#"schema_version = 1
2968kind = "mesofact-static"
2969routes = "./routes.ts"
2970
2971[build]
2972command = "echo built"
2973out_dir = "dist"
2974render_command = "echo render {route} --all"
2975"#,
2976        )
2977        .unwrap();
2978    }
2979
2980    #[tokio::test]
2981    async fn revalidate_static_runs_render_command_with_route_substituted() {
2982        // R535-T7: a declared render_command runs exactly once before the
2983        // publish step — {route} substituted, host-side lowering (Native, no
2984        // image), cwd = workload dir — and NEVER build.command.
2985        let fx = Fixture::new(cloudflare_reference_slot(), /*write_workload*/ true);
2986        write_workload_with_render_command(&fx);
2987        let (capture, captured) = CaptureExecutor::new();
2988        let reconciler = MesofactStaticReconciler::new().with_executor(capture.clone());
2989
2990        // up_cloudflare_r2 still fails after the render step (no provider
2991        // config on disk) — only the executor capture matters here.
2992        let _ = reconciler.revalidate_static(fx.ctx(), "/issues/:id").await;
2993
2994        let captured = captured.lock().unwrap();
2995        assert_eq!(captured.len(), 1, "render executed exactly once");
2996        let (spec, ctx) = &captured[0];
2997        assert_eq!(spec.where_.runtime, TaskRuntime::Native);
2998        match &spec.command {
2999            ForgeCommand::Subprocess { argv, image } => {
3000                assert!(image.is_none(), "host_side render carries no image");
3001                assert_eq!(
3002                    argv,
3003                    &vec![
3004                        "sh".to_string(),
3005                        "-c".into(),
3006                        "echo render /issues/:id --all".into()
3007                    ],
3008                    "route pattern substituted into {{route}}"
3009                );
3010            }
3011            other => panic!("expected Subprocess, got {other:?}"),
3012        }
3013        assert_eq!(
3014            ctx.cwd.as_deref(),
3015            Some(fx.workspace_root.join("app/web").as_path())
3016        );
3017    }
3018
3019    #[tokio::test]
3020    async fn revalidate_static_local_static_skips_render_command() {
3021        // The local-static arm never runs the render step — the host
3022        // mesofact-dev watcher re-renders on data-file changes independently.
3023        let fx = Fixture::new(local_static_slot(0), /*write_workload*/ true);
3024        write_workload_with_render_command(&fx);
3025        let (capture, captured) = CaptureExecutor::new();
3026        let reconciler = MesofactStaticReconciler::new().with_executor(capture.clone());
3027
3028        let _ = reconciler.revalidate_static(fx.ctx(), "/issues/:id").await;
3029
3030        assert!(
3031            captured.lock().unwrap().is_empty(),
3032            "local-static revalidate must not run render_command"
3033        );
3034    }
3035
3036    /// Validate the in-tree fixture at `testdata/mesofact-in-container/workload.toml`.
3037    ///
3038    /// Verifies that `read_mesofact_build` returns `BuildMode::InContainer` for an
3039    /// on-disk workload that declares `[build_mode] mode = "in_container"`.  No
3040    /// build is executed — this is a parse + lowering-shape test that runs in CI
3041    /// without docker (R438-T8 "in-tree mesofact-static workload with
3042    /// build_mode=in_container builds green in CI").
3043    #[test]
3044    fn in_container_fixture_roundtrips_as_container_build_mode() {
3045        let manifest_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
3046        let fixture_dir = manifest_dir.join("testdata/mesofact-in-container");
3047        let (build, build_mode) = read_mesofact_build(&fixture_dir)
3048            .expect("testdata/mesofact-in-container/workload.toml must parse cleanly")
3049            .expect("fixture must have a [build] section");
3050        assert!(
3051            matches!(build_mode, BuildMode::InContainer { .. }),
3052            "expected BuildMode::InContainer but got {build_mode:?}",
3053        );
3054        assert!(
3055            build.command.as_deref().is_some_and(|c| !c.is_empty()),
3056            "build.command must be declared and non-empty"
3057        );
3058    }
3059
3060    /// Spin up a throwaway loopback server that answers `/__mesofact/info` with
3061    /// `identity` (Some → 200 JSON `{service,component}`, None → 404), for the
3062    /// adopt identity-check tests (R602-B4). Returns the bound port.
3063    async fn spawn_info_server(identity: Option<(&str, &str)>) -> u16 {
3064        use axum::response::IntoResponse;
3065        use axum::routing::get;
3066        use axum::Router;
3067
3068        let json = identity.map(|(s, c)| format!(r#"{{"service":"{s}","component":"{c}"}}"#));
3069        let app = Router::new().route(
3070            "/__mesofact/info",
3071            get(move || {
3072                let json = json.clone();
3073                async move {
3074                    match json {
3075                        Some(b) => ([(reqwest::header::CONTENT_TYPE, "application/json")], b)
3076                            .into_response(),
3077                        None => axum::http::StatusCode::NOT_FOUND.into_response(),
3078                    }
3079                }
3080            }),
3081        );
3082        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3083        let port = listener.local_addr().unwrap().port();
3084        tokio::spawn(async move {
3085            axum::serve(listener, app).await.unwrap();
3086        });
3087        // Let the accept loop come up before the probe connects.
3088        tokio::time::sleep(Duration::from_millis(50)).await;
3089        port
3090    }
3091
3092    fn loopback(port: u16) -> SocketAddr {
3093        SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port)
3094    }
3095
3096    #[tokio::test]
3097    async fn adopt_identified_matches_and_adopts() {
3098        let port = spawn_info_server(Some(("scrabcake", "site"))).await;
3099        let got = try_adopt_identified(loopback(port), "scrabcake", "site", "configured")
3100            .await
3101            .unwrap();
3102        assert!(got.is_some(), "matching identity should adopt");
3103    }
3104
3105    #[tokio::test]
3106    async fn adopt_identified_mismatch_bails_naming_both() {
3107        // The headline repro: scrabcake dev finds yah-marketing on the port.
3108        let port = spawn_info_server(Some(("yah-marketing", "pond"))).await;
3109        let err = try_adopt_identified(loopback(port), "scrabcake", "site", "configured")
3110            .await
3111            .unwrap_err();
3112        let msg = err.to_string();
3113        assert!(msg.contains("yah-marketing/pond"), "msg was: {msg}");
3114        assert!(msg.contains("scrabcake"), "msg was: {msg}");
3115    }
3116
3117    #[tokio::test]
3118    async fn adopt_identified_foreign_listener_bails() {
3119        // Listener present but no /__mesofact/info (a foreign server, e.g.
3120        // workerd, or an identity-less mesofact-dev) → refuse to adopt.
3121        let port = spawn_info_server(None).await;
3122        let err = try_adopt_identified(loopback(port), "scrabcake", "site", "configured")
3123            .await
3124            .unwrap_err();
3125        assert!(
3126            err.to_string().contains("not an identifiable mesofact-dev"),
3127            "msg was: {err}"
3128        );
3129    }
3130
3131    #[tokio::test]
3132    async fn adopt_identified_no_listener_returns_none() {
3133        let port = pick_unused_port();
3134        let got = try_adopt_identified(loopback(port), "scrabcake", "site", "configured")
3135            .await
3136            .unwrap();
3137        assert!(got.is_none(), "no listener → nothing to adopt");
3138    }
3139}