Skip to main content

cloud/reconciler/
mod.rs

1//! Reconciler abstraction — bring a workload up against a mirror's
2//! provider slots.
3//!
4//! A reconciler is the kind-specific code that knows how to deploy one
5//! workload kind (`mesofact-static`, `container`, future `almanac`, …) to a
6//! mirror. Selection: a [`ServiceComponent`](crate::ServiceComponent)'s
7//! `kind` field picks which reconciler runs; the reconciler then dispatches
8//! on the mirror's provider slot (e.g. `mesofact-static` →
9//! `providers.static` slot → `local-static` inline or `cloudflare` ref).
10//!
11//! T3 ships [`MesofactStaticReconciler`] with the `local-static` path
12//! wired (spawn `mesofact-dev` as a child process). The Cloudflare path is
13//! a stub — the production reconciler lands once `mesofact-publisher`
14//! integration is on the roadmap.
15//!
16//!
17//! @yah:ticket(R419-F2, "Implement CloudflareWorkerReconciler (kind=cloudflare-worker)")
18//! @yah:assignee(agent:claude)
19//! @yah:at(2026-06-03T08:02:49Z)
20//! @yah:status(review)
21//! @yah:parent(R419)
22//! @yah:handoff("Landed CloudflareWorkerReconciler in crates/yah/cloud/src/reconciler/cloudflare_worker.rs and re-exported it through reconciler/mod.rs + cloud/src/lib.rs. up() validates the registry slot (must be `use = \"cloudflare\"` with non-empty `zone` + `domain`), reads workload.toml's `[build]` + `[[bindings]]`, matches each binding against a sibling mirror slot by `binding` field, runs build, reads the bundled entrypoint (default dist/index.js), idempotently lists+creates R2 buckets, deploys via deploy_worker_script with WorkerBinding::R2Bucket entries (R419-F1 surface), then attaches the custom domain via the new upsert_worker_custom_domain method on CloudflareClient. Returns RunningWorkload::adopted with public_url=https://<domain>. All config validation runs BEFORE any CF API call (R330-B5 fail-fast discipline).")
23//! @yah:handoff("Added CloudflareClient::upsert_worker_custom_domain (cloudflare.rs) — separate from upsert_worker_route because Worker Routes are zone-scoped pattern matches and Custom Domains are account-scoped hostname attachments. List-first idempotency: skips PUT when the (hostname, service, zone_id) tuple is already bound.")
24//! @yah:verify("cargo check -p cloud --lib — clean")
25//! @yah:depends_on(R419-F1)
26//!
27//! @yah:ticket(R419-F3, "Register cloudflare-worker reconciler in CLI + desktop dispatch")
28//! @yah:assignee(agent:claude)
29//! @yah:at(2026-06-03T08:02:58Z)
30//! @yah:status(review)
31//! @yah:parent(R419)
32//! @yah:handoff("Added match arm `\"cloudflare-worker\" => CloudflareWorkerReconciler::new().up(ctx)` in both dispatchers: app/yah/cli/src/cloud.rs:reconcile_component and app/yah/desktop/src/mirror_run.rs's component.kind.as_str() match. Imported CloudflareWorkerReconciler at the top of each file. Updated the desktop file-level docstring to list the new kind. Pre-existing fallback arm still produces a clean error for unknown kinds.")
33//! @yah:verify("cargo check -p cloud --lib — clean")
34//! @yah:verify("cargo check -p yah --lib --bins — clean (warnings unchanged from baseline)")
35//! @yah:verify("cargo check -p desktop --lib — clean (warnings unchanged from baseline)")
36//! @yah:depends_on(R419-F2)
37//!
38//! @yah:ticket(R419-F4, "Regression tests: misconfig fail-fast for cloudflare-worker reconciler")
39//! @yah:assignee(agent:claude)
40//! @yah:at(2026-06-03T08:03:09Z)
41//! @yah:status(review)
42//! @yah:parent(R419)
43//! @yah:handoff("Three fail-fast tests in reconciler::cloudflare_worker::tests — Fixture builds an in-tempdir yah-cr-shaped workspace (writes workload.toml + .yah/infra/providers/cloudflare.toml). up_bails_on_registry_missing_domain (case 3) drops domain off the registry slot. up_bails_on_binding_name_drift (case 2) puts binding=\"STORAGE\" in the cache slot while workload.toml binds CACHE. up_bails_on_cache_slot_missing_bucket (case 1) keeps binding=\"CACHE\" but omits bucket. Each test asserts the error message names the offending field, the slot role, the service, and the env — no CF HTTP call is made because validation runs before any client construction.")
44//! @yah:verify("cargo test -p cloud --lib reconciler::cloudflare_worker — 3 passed")
45//! @yah:verify("cargo test -p cloud --lib — 246 passed (1 pre-existing failure cloud_init::tests::embedded_template_matches_workspace_canonical is unrelated R092-F2 template drift, not caused by R419)")
46//! @yah:depends_on(R419-F2)
47//!
48//! @yah:relay(R458, "Cloud reconciler for .yah/domains/*.toml — R2 custom-domain shape")
49//! @yah:at(2026-06-05T08:40:57Z)
50//! @yah:status(open)
51//! @yah:next("F1: implement ensure_r2_custom_domain (mirror of ensure_r2_bucket) + wire into yah cloud apply as a post-services pass. Scope: domains with cdn_bucket set and no [[routes]] (today: cdn-yah-dev.toml). Worker-routed shape (yah-dev, app-yah-dev) is a separate surface.")
52//! @arch:see(.yah/domains/cdn-yah-dev.toml)
53//!
54//! @yah:ticket(R458-F1, "ensure_r2_custom_domain (CF API) + apply-time orchestration")
55//! @yah:at(2026-06-05T08:41:07Z)
56//! @yah:status(review)
57//! @yah:assignee(agent:claude)
58//! @yah:parent(R458)
59//! @arch:see(.yah/domains/cdn-yah-dev.toml)
60//! @yah:next("R458 can be archived once F1 is signed off, unless we want to keep it open for the routed-domain (Worker) reconciler shape — that's a much larger surface (DNS + Worker route management + bundle deploy) than this F1's bucket-binding.")
61//! @yah:handoff("Live-verified end-to-end. cdn.yah.dev now resolves to CF anycast IPs (104.21.43.100, 172.67.178.4) and curl HTTP/2 200s against https://cdn.yah.dev/yah-desktop/whisper/distil-large-v3-q5_1.bin (content-length 584567555 = the q5_1 bytes R422-F11 published). Second apply is idempotent — the list-first path skips the POST when the binding is already present. Files touched: (1) crates/yah/cloud/src/provider/cloudflare.rs — new R2CustomDomain output type + CloudflareClient::list_r2_custom_domains and CloudflareClient::add_r2_custom_domain methods (GET / POST /accounts/{id}/r2/buckets/{bucket}/domains/custom). The POST body needs zone_id even though the endpoint is bucket-scoped (CF rejects with 'JSON not well formed' otherwise — caught live and added on the second iteration). Re-exported through provider/mod.rs + cloud/src/lib.rs. (2) crates/yah/cloud/src/reconciler/domain.rs — new module with ensure_r2_custom_domain(account_id, bucket, domain) mirroring static_asset::ensure_r2_bucket's list-first idempotency. Resolves the parent zone id via the existing CloudflareClient::zone_id_for_name and a parent_zone_name(domain) heuristic that takes the last two labels (correct for every yah-owned zone today; the doc comment names the longest-suffix-match upgrade path for future three-label-apex zones). 3 unit tests cover apex / subdomain / deeper-subdomain. (3) crates/yah/cloud/src/reconciler/mod.rs — declared `pub mod domain` + re-exported ensure_r2_custom_domain. (4) app/yah/cli/src/cloud.rs — new DomainOutcome enum + a post-services domain pass in handle_apply that walks cfg.domains, dispatches the R2-custom-domain shape (cdn_bucket set, no [[routes]]), and routes routed-shape domains (yah-dev, app-yah-dev) into a Skipped row labelled 'has [[routes]] — Worker-routed shape'. Gated on a cloudflare provider being declared (pond-only setups print 'skip domain pass: no cloudflare provider declared'). Originally also gated on empty --service filter; that gate dropped on review — domains are workspace-scoped and the operator wants them reconciled even when narrowing services. New print_domain_summary mirrors print_apply_summary's table + JSON output. Required CF token scopes (verified live): Workers R2 Storage: Edit + Zone: Read. The existing cloudflare-api-token slot carries both.\n\nLive verification command + transcript:\n\n  $ ./target/debug/yah cloud apply --env cloud --service yah-desktop\n  ==> yah-desktop/cloud: reconciling 2 component(s)\n      component desktop (kind=binary)\n      component whisper-models (kind=static-asset)\n  ==> domain cdn-yah-dev (cdn.yah.dev): ensuring R2 custom-domain binding on bucket yah-dev\n  apply summary (cloud):\n    yah-desktop  ok       2 component(s) reconciled\n  domain summary (cloud):\n    cdn-yah-dev  ok       R2 custom domain bound\n  $ dig +short cdn.yah.dev\n  104.21.43.100\n  172.67.178.4\n  $ curl -sI https://cdn.yah.dev/yah-desktop/whisper/distil-large-v3-q5_1.bin | head -4\n  HTTP/2 200\n  content-length: 584567555\n\nUnblocks R422-T13's client-side `cdn_fallback = \"https://cdn.yah.dev/yah-desktop/whisper/{blake3}\"` — the URL now actually resolves and serves the bytes.")
62//! @yah:verify("cargo test -p cloud --lib reconciler::domain --locked  # 3 pass")
63//! @yah:verify("cargo check --workspace --locked  # clean")
64//! @yah:verify("./target/debug/yah cloud apply --env cloud --service yah-desktop  # domain summary shows cdn-yah-dev=ok, yah-dev/app-yah-dev=skipped (routed)")
65//! @yah:verify("curl -sI https://cdn.yah.dev/yah-desktop/whisper/distil-large-v3-q5_1.bin  # HTTP/2 200, content-length 584567555")
66
67use std::collections::{BTreeMap, VecDeque};
68use std::path::{Path, PathBuf};
69use std::sync::Arc;
70
71use anyhow::{Context, Result};
72use async_trait::async_trait;
73use serde::{Deserialize, Serialize};
74use tokio::sync::{oneshot, Mutex as AsyncMutex};
75
76use workload_spec::{NamespaceId, TenantId};
77
78use crate::{GitSource, MirrorConfig, MirrorProviderSlot, ServiceComponent, ServiceConfig};
79
80pub mod bundle_store;
81pub(crate) mod cf_creds;
82pub mod cloudflare_worker;
83pub mod container;
84pub mod derive_cache_prune;
85pub mod domain;
86pub mod headscale;
87pub mod ingress;
88pub mod ingress_verify;
89pub mod local_process;
90pub mod mesofact_bundle;
91pub mod mesofact_static;
92mod native_support;
93pub mod pg_driver;
94pub mod pond;
95pub mod pond_door;
96pub mod pond_publish;
97pub mod publish_beacon;
98pub mod r2_publish;
99pub mod service_discovery;
100pub mod static_asset;
101pub mod static_asset_prune;
102pub mod sync_status;
103
104#[cfg(test)]
105mod lowering_golden;
106
107pub use bundle_store::{publish_bundle_to_r2, PublishReport as BundlePublishReport};
108pub use cloudflare_worker::CloudflareWorkerReconciler;
109pub use container::{ContainerOptions, ContainerReconciler};
110pub use derive_cache_prune::{
111    collect_live_derive_hashes, compute_derive_cache_candidates, execute_derive_cache_prune,
112    DeriveCacheLiveHashes, DerivePruneCandidate,
113};
114pub use domain::{
115    deploy_domain_passway, diff_apex_records, ensure_passway_apex, ensure_r2_custom_domain,
116    list_live_apex_records, plan_domain_passway, plan_passway_apex, public_origins, ApexRecordDiff,
117    DomainPasswayPlan, LiveApexRecord, PasswayApexOutcome, PasswayOrigin,
118};
119pub use headscale::{
120    DeclaredHeadscale, DeclaredPolicy, DeclaredPreauthKey, HeadscaleReconciler,
121    WORKLOAD_KIND as HEADSCALE_WORKLOAD_KIND,
122};
123pub use ingress::{
124    collate_front_doors, declared as ingress_declared, ensure_tunnel_ingress, machine_mesh_addrs,
125    plan_ingress, publish_tunnel_ingress, resolve_ingress_candidates, resolve_ingress_placements,
126    Collation, IngressPlan, IngressRule, NodeFrontDoor, PlannedEdge, TunnelIngressOutcome,
127};
128pub use ingress_verify::{
129    apply_public_path, resolve_upstreams_reporting, verify_collation, BeaconFetch, DialOutcome,
130    EndpointCheck, PublicReadings, RuleResolution, RuleResolutions, RuleVerdict, VerifyFinding,
131    VerifyReport,
132};
133pub use local_process::LocalProcessReconciler;
134pub use mesofact_bundle::{
135    resolve_bundle_machines, BundleSlot, MesofactBundleReconciler, RevalidateSlot,
136    SLOT_ROLE as BUNDLE_SLOT_ROLE,
137};
138pub use mesofact_static::{LocalStaticOptions, MesofactStaticReconciler};
139pub use pond::{PondOptions, PondState};
140pub use pond_door::{
141    door_env, door_state_dir, ensure_pond_cert, ensure_pond_cert_as, is_root, plan_pond_door,
142    pond_hostname, resolve_passway_binary, spawn_pond_door, CertPair, PondDoorPlan,
143    DEFAULT_DOOR_PORT, POND_TLD,
144};
145pub use pond_publish::{derive_minio_key, publish_to_pond, PondPublishReport};
146pub use r2_publish::{
147    publish_to_r2, R2PublishReport, R2PurgeOpts, R2_ACCESS_KEY_ENV, R2_ACCESS_KEY_SLOT,
148    R2_SECRET_KEY_ENV, R2_SECRET_KEY_SLOT,
149};
150pub use service_discovery::{
151    DiscoveredRecord, RecordVisibility, ServiceRecordFanout, UnknownReason,
152};
153pub use static_asset::StaticAssetReconciler;
154pub use static_asset_prune::{
155    compute_live_set, compute_prune_candidates, execute_prune, load_service_and_mirror,
156    PruneCandidate, PruneOutcome, PruneReport,
157};
158pub use sync_status::{
159    compute_cell, compute_service, new_sync_id, summarize, CellStatus, DriftEntry, HealthState,
160    MirrorObservation, Runtime, ServiceStatus, StatusSummary, SyncHistoryEntry, SyncOutcome,
161    SyncState, WireContainerStatus,
162};
163
164// ─── Log buffer ─────────────────────────────────────────────────────────────
165
166const LOG_CAP: usize = 500;
167
168#[derive(Debug, Default)]
169struct LogRing {
170    lines: VecDeque<String>,
171    /// Monotonically increasing total lines ever pushed (never decrements).
172    total: usize,
173}
174
175/// Bounded ring buffer for child-process stdout/stderr (R263-F3).
176/// Shared between the reader tasks and the Tauri `mirror_run_logs` command.
177#[derive(Debug, Clone, Default)]
178pub struct LogBuffer(Arc<AsyncMutex<LogRing>>);
179
180impl LogBuffer {
181    pub fn new() -> Self {
182        Self::default()
183    }
184
185    /// Append a line; drops the oldest entry when over capacity.
186    pub async fn push(&self, line: String) {
187        let mut ring = self.0.lock().await;
188        ring.total += 1;
189        ring.lines.push_back(line);
190        if ring.lines.len() > LOG_CAP {
191            ring.lines.pop_front();
192        }
193    }
194
195    /// Return lines not yet seen by the caller.
196    ///
197    /// `since` is the `total` cursor from the previous call (0 = nothing
198    /// seen yet). Returns `(new_lines, new_cursor)`. Pass `new_cursor` back
199    /// on the next call to receive only incremental output.
200    pub async fn since(&self, since: usize) -> (Vec<String>, usize) {
201        let ring = self.0.lock().await;
202        let oldest = ring.total.saturating_sub(ring.lines.len());
203        let skip = since.saturating_sub(oldest);
204        let new_lines: Vec<String> = ring.lines.iter().skip(skip).cloned().collect();
205        (new_lines, ring.total)
206    }
207
208    /// Current write cursor — the `total` [`Self::since`] would hand back
209    /// right now if nothing more were pushed. Lets a producer mark a boundary
210    /// (e.g. "everything before this point was the build phase") for a later
211    /// reader to seek past without re-reading lines it doesn't want.
212    pub async fn cursor(&self) -> usize {
213        self.0.lock().await.total
214    }
215}
216
217/// Shared cell for one phase-boundary cursor a reconciler can publish
218/// mid-`up()`, so a poller sees a multi-phase bring-up's internal transition
219/// (e.g. build → run) before the whole call returns — the same problem
220/// [`LogBuffer`] solves for output, for a single position instead of a ring.
221/// `None` until the reconciler reaches that phase; a caller registers one
222/// before calling `up()` to observe it live, same pattern as
223/// [`LogBuffer::clone`]-and-hand-in.
224#[derive(Debug, Clone, Default)]
225pub struct PhaseCursor(Arc<AsyncMutex<Option<usize>>>);
226
227impl PhaseCursor {
228    pub fn new() -> Self {
229        Self::default()
230    }
231
232    pub async fn set(&self, cursor: usize) {
233        *self.0.lock().await = Some(cursor);
234    }
235
236    pub async fn get(&self) -> Option<usize> {
237        *self.0.lock().await
238    }
239}
240
241/// The `(tenant, namespace)` a bring-up is scoped to (W206). Reconcilers that
242/// touch a credentialed provider resolve it at this scope
243/// ([`CfProvider::resolve_scoped`](super::reconciler::cf_creds)) so a namespace's
244/// Cloudflare zone/account/keystore slots come from its own scope rather than the
245/// workspace-global defaults. Defaults to the singleton `(default, default)`,
246/// which collapses every scoped lookup back to the historical global slots — so
247/// single-namespace deployments are unaffected.
248#[derive(Debug, Clone)]
249pub struct ProviderScope {
250    pub tenant: TenantId,
251    pub namespace: NamespaceId,
252}
253
254impl ProviderScope {
255    /// The degenerate single-tenant / single-namespace scope. Scoped provider
256    /// lookups made against it resolve to the pre-W206 global keystore slots.
257    pub fn singleton() -> Self {
258        Self {
259            tenant: TenantId::singleton(),
260            namespace: NamespaceId::singleton(),
261        }
262    }
263}
264
265impl Default for ProviderScope {
266    fn default() -> Self {
267        Self::singleton()
268    }
269}
270
271/// Inputs a reconciler sees for one bring-up.
272pub struct ReconcileCtx<'a> {
273    /// Workspace root (parent of `.yah/`). Used to resolve relative paths
274    /// on the component.
275    pub workspace_root: &'a Path,
276    /// Service that owns the component.
277    pub service: &'a ServiceConfig,
278    /// Component being brought up.
279    pub component: &'a ServiceComponent,
280    /// Mirror manifest the bring-up targets.
281    pub mirror: &'a MirrorConfig,
282    /// Environment name (file stem of `mirrors/<env>.toml`).
283    pub env: &'a str,
284    /// `(tenant, namespace)` this bring-up is scoped to (W206). Credentialed
285    /// providers resolve at this scope; defaults to [`ProviderScope::singleton`].
286    pub scope: ProviderScope,
287}
288
289impl<'a> ReconcileCtx<'a> {
290    /// Absolute path to the component's workload directory (the parent of
291    /// `workload.toml`).
292    ///
293    /// In-tree components resolve to `<workspace_root>/<path>`. For
294    /// `git`-sourced components (R561-F1, "BYO git") this points into the
295    /// local clone — `<source_cache>/<subdir>/<path>` — which is empty until
296    /// [`materialize`](Self::materialize) runs (approach A: clone-at-reconcile,
297    /// so config load + validation stay offline).
298    pub fn workload_dir(&self) -> PathBuf {
299        match &self.component.git {
300            None => self.workspace_root.join(&self.component.path),
301            Some(git) => {
302                let mut dir = self.source_cache_dir();
303                if let Some(subdir) = &git.subdir {
304                    dir = dir.join(subdir);
305                }
306                dir.join(&self.component.path)
307            }
308        }
309    }
310
311    /// Root of the local clone for a `git`-sourced component:
312    /// `<workspace_root>/.yah/infra/state/sources/<service>/<component_id>`.
313    fn source_cache_dir(&self) -> PathBuf {
314        self.workspace_root
315            .join(".yah/infra/state/sources")
316            .join(&self.service.name)
317            .join(&self.component.id)
318    }
319
320    /// Ensure a `git`-sourced component's code is present locally before build
321    /// (R561-F1, approach A). No-op for in-tree components. Idempotent: clones
322    /// on the first call, fetches + re-checks-out the pinned ref thereafter.
323    ///
324    /// Reconcilers MUST call this at the top of [`up`](Reconciler::up) before
325    /// reading [`workload_dir`](Self::workload_dir) for a remote component.
326    pub async fn materialize(&self) -> Result<()> {
327        let Some(git) = &self.component.git else {
328            return Ok(());
329        };
330        materialize_git_source(git, &self.source_cache_dir())
331            .await
332            .with_context(|| {
333                format!(
334                    "materializing git source {}@{} for {}/{}",
335                    git.repo, git.r#ref, self.service.name, self.component.id
336                )
337            })
338    }
339
340    /// Read `<workload_dir>/workload.toml` and extract just the `kind`
341    /// discriminator.
342    ///
343    /// Why this and not the strongly-typed [`workload_spec::Workload`]
344    /// parse: the on-disk `schema_version = 1` form predates the
345    /// `SchemaVersion::V1` enum and won't round-trip through the strong
346    /// types until B3 lands (see `crates/yah/cloud/src/config.rs` test
347    /// `web_workload_round_trips`). Reconcilers only need the kind to
348    /// dispatch; per-kind tooling (e.g. `mesofact-dev`'s
349    /// `WatchOptions::from_workload`) does its own parsing for the
350    /// build/out_dir fields it cares about.
351    pub fn workload_kind(&self) -> Result<String> {
352        workload_kind(&self.workload_dir())
353    }
354
355    /// Look up a provider slot by role (e.g. `"static"`, `"compute"`).
356    ///
357    /// Tries the component-qualified key first (`"<role>:<component id>"`)
358    /// before falling back to the bare role. A mirror role is normally
359    /// service-wide — one `providers.static` slot serves every static-kind
360    /// component — but a service can declare more than one component with
361    /// the same role (e.g. two `mesofact-static`/`mesofact-spa` components
362    /// sharing one mirror), and those need distinct ports to ever both come
363    /// up. The qualified key is how a mirror opts a specific component out
364    /// of sharing the bare-role slot:
365    ///
366    /// ```toml
367    /// [providers."static:site"]
368    /// kind = "local-static"
369    /// port = 4331
370    ///
371    /// [providers."static:app"]
372    /// kind = "local-static"
373    /// port = 4332
374    /// ```
375    ///
376    /// A mirror with only the bare role (the common, single-component case)
377    /// is unaffected — the qualified lookup misses and falls through.
378    pub fn slot(&self, role: &str) -> Option<&'a MirrorProviderSlot> {
379        let qualified = format!("{role}:{}", self.component.id);
380        self.mirror
381            .providers
382            .get(qualified.as_str())
383            .or_else(|| self.mirror.providers.get(role))
384    }
385}
386
387/// An explicit teardown hook for a workload this process did not spawn as a
388/// child — see [`RunningWorkload::with_teardown`] (R714-B1).
389///
390/// Boxed rather than a generic parameter because [`RunningWorkload`] is stored
391/// in heterogeneous collections (the desktop's mirror registry) and cannot
392/// carry a type parameter.
393/// `Sync` on the boxed closure is load-bearing, not belt-and-braces: without
394/// it `RunningWorkload` stops being `Sync`, so `&RunningWorkload` stops being
395/// `Send`, and every desktop `#[tauri::command]` that holds one across an
396/// `.await` (`mirror_run_logs` iterates the registry's handles) fails to
397/// compile with "future cannot be sent between threads safely". The captures a
398/// teardown needs — a container name and a workspace root — are `Sync` anyway.
399type TeardownFuture = std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send>>;
400type TeardownFn = Box<dyn FnOnce() -> TeardownFuture + Send + Sync + 'static>;
401
402/// Newtype so [`RunningWorkload`] can keep its `#[derive(Debug)]` — a boxed
403/// closure is not `Debug`.
404struct Teardown(TeardownFn);
405
406impl std::fmt::Debug for Teardown {
407    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
408        f.write_str("Teardown(<fn>)")
409    }
410}
411
412/// Handle to a workload that's been brought up. Owns the lifecycle: drop
413/// or call [`RunningWorkload::shutdown`] to take it back down.
414#[derive(Debug)]
415pub struct RunningWorkload {
416    /// Workload kind that was reconciled (e.g. `"mesofact-static"`).
417    pub kind: String,
418    /// Slot role this workload occupies on the mirror (e.g. `"static"`).
419    pub slot: String,
420    /// Local URL the workload exposes, when applicable. `None` for
421    /// workloads that publish to a non-local artifact store (e.g. R2).
422    pub dev_url: Option<String>,
423    /// Notional URL of the deployed artifact in the production case
424    /// (e.g. `https://yah.dev`). `None` until Cloudflare/R2 wiring lands.
425    pub public_url: Option<String>,
426    /// Secondary local UI console, if the workload exposes one (e.g. MinIO
427    /// console on a pond tier). Surfaced as a separate chip in the Services
428    /// matrix next to `dev_url`.
429    pub console_url: Option<String>,
430    /// Ring buffer for stdout/stderr from the workload's child process.
431    /// `None` for workloads that don't capture stdio (e.g. container-backed).
432    pub log_buffer: Option<LogBuffer>,
433
434    /// R546-B12: human-readable lines the reconciler wants the operator to see
435    /// on THIS run — what it actually did, not what is configured. A clean
436    /// static-asset reconcile used to print nothing at all, so a successful
437    /// publish and a successful no-op were indistinguishable at the apply
438    /// surface, and the one view that would have disambiguated them (`yah cloud
439    /// status`) was itself blind.
440    ///
441    /// Deliberately NOT on [`RunningWorkloadSummary`]: that type is serialized
442    /// across the process boundary to the desktop UI, and this is per-run
443    /// console output, not state the UI should cache.
444    pub notes: Vec<String>,
445
446    /// Sender that signals the supervisor task to tear down. Closing the
447    /// channel (drop) is equivalent to sending — supervisor exits on
448    /// channel close.
449    shutdown: Option<oneshot::Sender<()>>,
450    /// Joinable task that owns any child process and reaps it on signal.
451    supervisor: Option<tokio::task::JoinHandle<Result<()>>>,
452    /// R714-B1: teardown for a workload that runs OUTSIDE this process, so
453    /// there is no child to reap and no supervisor to signal.
454    ///
455    /// Deliberately run from [`RunningWorkload::shutdown`] only, never from
456    /// `Drop`. The two are different intents and conflating them breaks both
457    /// directions: a container the desktop started is meant to outlive the
458    /// desktop (the next launch re-adopts it with `adopt_only`), so quitting
459    /// the app must not `docker rm -f` it; but the ■ button IS an explicit
460    /// stop, and must.
461    teardown: Option<Teardown>,
462
463    /// R715-F4: where to ask this workload for a live status document, when
464    /// it declared a process-control channel (W315). `None` for a workload
465    /// with no channel — polling is then simply skipped, not an error.
466    ///
467    /// The desktop holds `RunningWorkload` in-process (it links this crate
468    /// directly, unlike the ad-hoc `run.spawn` path which lives behind the
469    /// camp daemon's socket), so a live poll is [`crate::proc_control::fetch_status`]
470    /// called straight against this endpoint — no RPC hop, no handle registry.
471    control: Option<crate::proc_control::ControlEndpoint>,
472
473    /// [`LogBuffer`] cursor marking the end of the build phase, for a
474    /// component that was compiled before being spawned (`local-process`
475    /// with `cargo_package` set). Lines before this index in `log_buffer` are
476    /// `cargo build` output; lines at or after are the spawned process's own
477    /// stdout/stderr. `None` when nothing was built (no `cargo_package`, or a
478    /// reconciler that predates this field).
479    pub build_log_end: Option<usize>,
480}
481
482impl RunningWorkload {
483    /// Create a handle for a workload that's already running externally
484    /// (e.g. embedded in yah-camp). No subprocess is owned; shutdown is a
485    /// no-op so the caller can call `shutdown()` uniformly.
486    pub fn adopted(
487        kind: impl Into<String>,
488        slot: impl Into<String>,
489        dev_url: Option<String>,
490    ) -> Self {
491        Self {
492            kind: kind.into(),
493            slot: slot.into(),
494            dev_url,
495            public_url: None,
496            console_url: None,
497            log_buffer: None,
498            notes: Vec::new(),
499            shutdown: None,
500            supervisor: None,
501            teardown: None,
502            control: None,
503            build_log_end: None,
504        }
505    }
506
507    /// Attach an explicit teardown to a handle for an externally-running
508    /// workload (R714-B1).
509    ///
510    /// `adopted()` alone gives a handle whose `shutdown()` is a documented
511    /// no-op. That is right for workloads another process owns and will keep
512    /// re-asserting (pond containers under camp's yubaba), and wrong for ones
513    /// this process started and nobody else will ever stop — for those the ■
514    /// button reported success while the container kept running.
515    ///
516    /// `teardown` runs on `shutdown()` and NOT on `Drop`; see [`Self::teardown`].
517    pub fn with_teardown<F, Fut>(mut self, teardown: F) -> Self
518    where
519        F: FnOnce() -> Fut + Send + Sync + 'static,
520        Fut: std::future::Future<Output = Result<()>> + Send + 'static,
521    {
522        self.teardown = Some(Teardown(Box::new(move || Box::pin(teardown()))));
523        self
524    }
525
526    /// Whether this handle carries a real teardown — i.e. whether a failed
527    /// [`Self::shutdown`] means the workload is **still running**.
528    ///
529    /// The stop path needs this to decide between an operator-facing error and
530    /// a log line, and R875-B1 is why it is a property of the handle rather
531    /// than a list of kinds at the call site. That list started as
532    /// `kind == "container"` when R714-B1 gave containers a teardown, and was
533    /// silently wrong the moment a second kind grew one: an adopted
534    /// mesofact-dev whose teardown failed reported a successful stop with the
535    /// server still serving. A handle knows whether it owns the workload; a
536    /// string comparison at the call site only knows what it was last taught.
537    pub fn owns_teardown(&self) -> bool {
538        self.teardown.is_some()
539    }
540
541    /// Attach per-run operator-facing lines (R546-B12). See [`Self::notes`].
542    pub fn with_notes(mut self, notes: Vec<String>) -> Self {
543        self.notes = notes;
544        self
545    }
546
547    /// Record where to poll this workload's process-control channel, when it
548    /// declared one (R715-F4). A no-op (leaves `control: None`) when the
549    /// argument is `None` — callers can pass the reconciler's resolved
550    /// endpoint straight through without an `if let`.
551    pub fn with_control(mut self, control: Option<crate::proc_control::ControlEndpoint>) -> Self {
552        self.control = control;
553        self
554    }
555
556    /// Ask this workload's process-control channel for a live status
557    /// document (R715-F4). `None` when no channel was declared, or when the
558    /// endpoint didn't answer — both are "nothing new to show", not errors;
559    /// see [`crate::proc_control::fetch_status`] for why a poll failure isn't
560    /// itself meaningful.
561    pub async fn poll_control(&self) -> Option<crate::proc_control::ProcStatus> {
562        let endpoint = self.control.as_ref()?;
563        crate::proc_control::fetch_status(endpoint).await.ok()
564    }
565
566    /// Whether the supervisor task that owns this workload's child process is
567    /// still running. `spawn_native_log_supervisor` (native_support.rs) exits
568    /// as soon as `NativeRuntime::get_workload` reports a terminal state —
569    /// which itself comes from a real `child.wait()` in kamaji's native
570    /// backend, so this catches a crash (segfault, panic, `SIGKILL`) the same
571    /// way it catches a clean exit, not just an unresponsive process.
572    ///
573    /// A workload with no supervisor (`RunningWorkload::adopted` — runs
574    /// outside this process, e.g. a pond container camp re-asserts) has
575    /// nothing to check here and reports alive unconditionally; its liveness
576    /// is whatever tracks it, not this handle.
577    pub fn is_alive(&self) -> bool {
578        self.supervisor.as_ref().is_none_or(|h| !h.is_finished())
579    }
580
581    /// Record where the build phase ends in `log_buffer`, for a component
582    /// that was compiled before being spawned. See [`Self::build_log_end`].
583    pub fn with_build_log_end(mut self, cursor: Option<usize>) -> Self {
584        self.build_log_end = cursor;
585        self
586    }
587
588    /// Set the public URL for a published workload (e.g. `"https://yah.dev"`).
589    pub fn with_public_url(mut self, url: impl Into<String>) -> Self {
590        self.public_url = Some(url.into());
591        self
592    }
593
594    /// Set the console URL for a workload that exposes a secondary local UI
595    /// (e.g. MinIO console on a pond tier).
596    pub fn with_console_url(mut self, url: impl Into<String>) -> Self {
597        self.console_url = Some(url.into());
598        self
599    }
600
601    /// Gracefully tear down: signal the supervisor, await its exit, then run
602    /// any explicit teardown hook.
603    ///
604    /// The hook runs LAST and its error propagates. A stop that could not tear
605    /// the workload down must surface as an error, never as a silent success —
606    /// that silence is the whole of R714-B1.
607    pub async fn shutdown(mut self) -> Result<()> {
608        if let Some(tx) = self.shutdown.take() {
609            let _ = tx.send(());
610        }
611        if let Some(handle) = self.supervisor.take() {
612            handle
613                .await
614                .context("joining workload supervisor")?
615                .context("workload supervisor")?;
616        }
617        if let Some(Teardown(hook)) = self.teardown.take() {
618            hook().await.context("workload teardown")?;
619        }
620        Ok(())
621    }
622}
623
624impl Drop for RunningWorkload {
625    fn drop(&mut self) {
626        // Best-effort signal. The supervisor task is detached and will
627        // reap its child when it observes the closed channel.
628        if let Some(tx) = self.shutdown.take() {
629            let _ = tx.send(());
630        }
631    }
632}
633
634/// Bring one workload up. Each impl handles one [`ServiceComponent::kind`].
635#[async_trait]
636pub trait Reconciler: Send + Sync {
637    /// Workload kind this reconciler handles (matches `ServiceComponent.kind`).
638    fn kind(&self) -> &'static str;
639
640    /// Bring the workload up. Returns a handle whose lifecycle is tied to
641    /// the mirror being up.
642    async fn up(&self, ctx: ReconcileCtx<'_>) -> Result<RunningWorkload>;
643}
644
645/// Read `<workload_dir>/workload.toml` and return just the `kind` field.
646/// See [`ReconcileCtx::workload_kind`] for why we don't deserialize through
647/// the strong types yet.
648pub fn workload_kind(workload_dir: &Path) -> Result<String> {
649    let path = workload_dir.join("workload.toml");
650    let src =
651        std::fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;
652    let value: toml::Value =
653        toml::from_str(&src).with_context(|| format!("parsing {}", path.display()))?;
654    let kind = value
655        .get("kind")
656        .and_then(|v| v.as_str())
657        .with_context(|| format!("{}: missing `kind` field", path.display()))?;
658    Ok(kind.to_string())
659}
660
661/// Shallow-clone (or update) a [`GitSource`] into `dir` (R561-F1). Idempotent:
662/// clones when `dir/.git` is absent, otherwise fetches the pinned ref and
663/// force-checks-it-out. Uses the system `git` so it inherits the operator's
664/// credential helpers / SSH agent — no in-process git library.
665///
666/// `pub` (R615-T3 / W274): `yah infra sync` reuses this verbatim for
667/// `InfraSourceKind::Git` sources rather than a second shallow-clone-or-pull
668/// implementation — same "one git-source shape, reused" discipline R615-F1
669/// already applied to the type.
670pub async fn materialize_git_source(git: &GitSource, dir: &Path) -> Result<()> {
671    use tokio::process::Command;
672
673    async fn run_git(args: &[&std::ffi::OsStr]) -> Result<()> {
674        let out = Command::new("git")
675            .args(args)
676            .output()
677            .await
678            .context("spawning git")?;
679        if !out.status.success() {
680            anyhow::bail!(
681                "git {} failed: {}",
682                args.iter()
683                    .map(|a| a.to_string_lossy())
684                    .collect::<Vec<_>>()
685                    .join(" "),
686                String::from_utf8_lossy(&out.stderr).trim()
687            );
688        }
689        Ok(())
690    }
691
692    use std::ffi::OsStr;
693    let dir_os = dir.as_os_str();
694    let r#ref = git.r#ref.as_str();
695
696    if dir.join(".git").is_dir() {
697        // Existing checkout — update to the pinned ref.
698        run_git(&[
699            OsStr::new("-C"),
700            dir_os,
701            OsStr::new("fetch"),
702            OsStr::new("--depth"),
703            OsStr::new("1"),
704            OsStr::new("origin"),
705            OsStr::new(r#ref),
706        ])
707        .await?;
708        run_git(&[
709            OsStr::new("-C"),
710            dir_os,
711            OsStr::new("checkout"),
712            OsStr::new("--force"),
713            OsStr::new("FETCH_HEAD"),
714        ])
715        .await?;
716    } else {
717        if let Some(parent) = dir.parent() {
718            tokio::fs::create_dir_all(parent)
719                .await
720                .with_context(|| format!("creating {}", parent.display()))?;
721        }
722        // `--branch` accepts a branch or tag. Pinning to a bare commit SHA is a
723        // follow-up (needs clone-then-fetch); the common case is a branch/tag.
724        run_git(&[
725            OsStr::new("clone"),
726            OsStr::new("--depth"),
727            OsStr::new("1"),
728            OsStr::new("--branch"),
729            OsStr::new(r#ref),
730            OsStr::new(git.repo.as_str()),
731            dir_os,
732        ])
733        .await?;
734    }
735    Ok(())
736}
737
738/// Build a `RunningWorkload` from the pieces a reconciler produces.
739pub(crate) fn into_running(
740    kind: impl Into<String>,
741    slot: impl Into<String>,
742    dev_url: Option<String>,
743    public_url: Option<String>,
744    log_buffer: Option<LogBuffer>,
745    shutdown: oneshot::Sender<()>,
746    supervisor: tokio::task::JoinHandle<Result<()>>,
747) -> RunningWorkload {
748    RunningWorkload {
749        kind: kind.into(),
750        slot: slot.into(),
751        dev_url,
752        public_url,
753        console_url: None,
754        log_buffer,
755        notes: Vec::new(),
756        shutdown: Some(shutdown),
757        supervisor: Some(supervisor),
758        teardown: None,
759        control: None,
760        build_log_end: None,
761    }
762}
763
764/// Wait for a TCP port to start accepting connections. Returns `true` if
765/// the port came up within `timeout`, `false` otherwise. Useful for
766/// reconcilers that spawn a server and need to know when it's reachable
767/// before reporting success.
768pub(crate) async fn wait_for_port(
769    addr: std::net::SocketAddr,
770    timeout: std::time::Duration,
771) -> bool {
772    let deadline = tokio::time::Instant::now() + timeout;
773    loop {
774        if tokio::net::TcpStream::connect(addr).await.is_ok() {
775            return true;
776        }
777        if tokio::time::Instant::now() >= deadline {
778            return false;
779        }
780        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
781    }
782}
783
784// `wait_for_http_ready` lived here pre-R374-F3 to back the MinIO health
785// probe in pond's bring-up path. That logic moved to
786// `local_driver::pond_minio::wait_for_http_ready` so yubaba + cloud share
787// it. The mesofact-static reconciler arm uses [`wait_for_port`] for
788// dev-tier port readiness; nothing else needs an HTTP-level probe today.
789
790/// Pluck a `u16` out of a [`MirrorProviderSlot`]'s inline `fields` map.
791/// Returns `None` if the key is absent or out of range.
792pub(crate) fn slot_field_u16(fields: &BTreeMap<String, toml::Value>, key: &str) -> Option<u16> {
793    fields
794        .get(key)
795        .and_then(|v| v.as_integer())
796        .and_then(|n| u16::try_from(n).ok())
797}
798
799/// Serializable summary of a running workload — what the desktop / CLI
800/// hands to the UI. Subset of [`RunningWorkload`] that's safe to cross
801/// process boundaries.
802#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
803pub struct RunningWorkloadSummary {
804    pub kind: String,
805    pub slot: String,
806    pub dev_url: Option<String>,
807    pub public_url: Option<String>,
808    pub console_url: Option<String>,
809    /// Operator-facing lines from [`RunningWorkload::notes`] (R546-B12).
810    ///
811    /// These used to stop here — the summary dropped them, so every note a
812    /// reconciler attached was written into a struct nobody read. They matter
813    /// most for a workload with no `dev_url` to click (R715-T2): the notes are
814    /// then the only structured thing the Run tab has to show about it.
815    #[serde(default, skip_serializing_if = "Vec::is_empty")]
816    pub notes: Vec<String>,
817    /// See [`RunningWorkload::build_log_end`]. Lets a log-tail consumer skip
818    /// straight to run-phase output, or show everything from 0 when the
819    /// operator wants the build log too (e.g. after a compile failure).
820    #[serde(default, skip_serializing_if = "Option::is_none")]
821    pub build_log_end: Option<usize>,
822}
823
824impl From<&RunningWorkload> for RunningWorkloadSummary {
825    fn from(r: &RunningWorkload) -> Self {
826        Self {
827            kind: r.kind.clone(),
828            slot: r.slot.clone(),
829            dev_url: r.dev_url.clone(),
830            public_url: r.public_url.clone(),
831            console_url: r.console_url.clone(),
832            notes: r.notes.clone(),
833            build_log_end: r.build_log_end,
834        }
835    }
836}
837
838#[cfg(test)]
839mod source_seam_tests {
840    //! R561-F1 — the BYO-git source seam: path resolution + materialization.
841    use super::*;
842    use std::collections::BTreeMap;
843
844    fn component(git: Option<GitSource>) -> ServiceComponent {
845        ServiceComponent {
846            mount: None,
847            id: "site".into(),
848            kind: "mesofact-static".into(),
849            path: "site".into(),
850            role: "static".into(),
851            publishes: None,
852            wave: 0,
853            git,
854        }
855    }
856
857    fn service(comp: ServiceComponent) -> ServiceConfig {
858        ServiceConfig {
859            schema_version: 1,
860            name: "scrabcake".into(),
861            domain: "scrabcake.example".into(),
862            components: vec![comp],
863            db: crate::DbCatalog::default(),
864        }
865    }
866
867    fn mirror() -> MirrorConfig {
868        MirrorConfig {
869            schema_version: 1,
870            shape: crate::MirrorShape::Local,
871            providers: BTreeMap::new(),
872            ingress: Default::default(),
873            ingress_machines: Vec::new(),
874            drivers: Default::default(),
875            asset_aliases: BTreeMap::new(),
876        }
877    }
878
879    fn ctx<'a>(ws: &'a Path, svc: &'a ServiceConfig, mir: &'a MirrorConfig) -> ReconcileCtx<'a> {
880        ReconcileCtx {
881            workspace_root: ws,
882            service: svc,
883            component: &svc.components[0],
884            mirror: mir,
885            env: "dev",
886            scope: ProviderScope::singleton(),
887        }
888    }
889
890    #[test]
891    fn workload_dir_in_tree_joins_workspace_root() {
892        let svc = service(component(None));
893        let mir = mirror();
894        assert_eq!(
895            ctx(Path::new("/ws"), &svc, &mir).workload_dir(),
896            Path::new("/ws/site")
897        );
898    }
899
900    #[test]
901    fn workload_dir_git_resolves_into_source_cache_with_subdir() {
902        let git = GitSource {
903            repo: "https://example.com/r.git".into(),
904            r#ref: "main".into(),
905            subdir: Some("apps".into()),
906        };
907        let svc = service(component(Some(git)));
908        let mir = mirror();
909        assert_eq!(
910            ctx(Path::new("/ws"), &svc, &mir).workload_dir(),
911            Path::new("/ws/.yah/infra/state/sources/scrabcake/site/apps/site")
912        );
913    }
914
915    #[tokio::test]
916    async fn materialize_is_noop_for_in_tree_component() {
917        let svc = service(component(None));
918        let mir = mirror();
919        // No git source → Ok, and nothing is written under the workspace.
920        ctx(Path::new("/nonexistent-ws"), &svc, &mir)
921            .materialize()
922            .await
923            .unwrap();
924    }
925
926    #[tokio::test]
927    async fn materialize_clones_git_source_offline() {
928        fn git(args: &[&str], cwd: &Path) {
929            let out = std::process::Command::new("git")
930                .args(args)
931                .current_dir(cwd)
932                .env("GIT_AUTHOR_NAME", "t")
933                .env("GIT_AUTHOR_EMAIL", "t@t")
934                .env("GIT_COMMITTER_NAME", "t")
935                .env("GIT_COMMITTER_EMAIL", "t@t")
936                .output()
937                .unwrap();
938            assert!(
939                out.status.success(),
940                "git {args:?}: {}",
941                String::from_utf8_lossy(&out.stderr)
942            );
943        }
944
945        let tmp = tempfile::tempdir().unwrap();
946        let src = tmp.path().join("src-repo");
947        std::fs::create_dir_all(&src).unwrap();
948        git(&["init", "-b", "main"], &src);
949        std::fs::write(src.join("hello.txt"), "hi").unwrap();
950        git(&["add", "."], &src);
951        git(&["commit", "-m", "init"], &src);
952
953        let source = GitSource {
954            repo: format!("file://{}", src.display()),
955            r#ref: "main".into(),
956            subdir: None,
957        };
958        let dest = tmp.path().join("cache");
959
960        // First call clones.
961        materialize_git_source(&source, &dest).await.unwrap();
962        assert!(dest.join("hello.txt").is_file());
963
964        // Second call takes the update path and stays green (idempotent).
965        materialize_git_source(&source, &dest).await.unwrap();
966        assert!(dest.join("hello.txt").is_file());
967    }
968}
969
970#[cfg(test)]
971mod teardown_tests {
972    //! R714-B1 — the explicit-teardown contract on [`RunningWorkload`].
973    //!
974    //! These are about WHEN the hook runs, not what it does. The bug being
975    //! fixed was a `shutdown()` that reported success having done nothing, and
976    //! the trap in fixing it is a `Drop` that tears down a container which is
977    //! supposed to survive the process.
978    use super::*;
979    use std::sync::atomic::{AtomicUsize, Ordering};
980
981    fn counting() -> (RunningWorkload, Arc<AtomicUsize>) {
982        let hits = Arc::new(AtomicUsize::new(0));
983        let seen = hits.clone();
984        let w = RunningWorkload::adopted("container", "compute", None)
985            .with_teardown(move || {
986                let seen = seen.clone();
987                async move {
988                    seen.fetch_add(1, Ordering::SeqCst);
989                    Ok(())
990                }
991            });
992        (w, hits)
993    }
994
995    /// Attaching a teardown must not cost `RunningWorkload` its auto traits.
996    /// The desktop stores these handles in a shared registry and its Tauri
997    /// commands iterate them across `.await` points, which needs `Sync` — a
998    /// hook that is `Send` but not `Sync` takes it away here and surfaces two
999    /// crates over as "future cannot be sent between threads safely", with a
1000    /// span pointing at `mirror_run_logs` rather than at this file.
1001    #[test]
1002    fn a_teardown_does_not_cost_the_handle_send_or_sync() {
1003        fn assert_send_sync<T: Send + Sync>() {}
1004        assert_send_sync::<RunningWorkload>();
1005    }
1006
1007    #[tokio::test]
1008    async fn shutdown_runs_the_teardown() {
1009        let (w, hits) = counting();
1010        w.shutdown().await.unwrap();
1011        assert_eq!(hits.load(Ordering::SeqCst), 1);
1012    }
1013
1014    #[tokio::test]
1015    async fn dropping_the_handle_does_NOT_run_the_teardown() {
1016        // A container this process started is meant to outlive it — the next
1017        // launch re-adopts it. Quitting the app must not `docker rm -f` it.
1018        let (w, hits) = counting();
1019        drop(w);
1020        // Yield so a stray spawned task would have had a chance to run.
1021        tokio::task::yield_now().await;
1022        assert_eq!(hits.load(Ordering::SeqCst), 0);
1023    }
1024
1025    #[tokio::test]
1026    async fn a_failing_teardown_makes_shutdown_fail() {
1027        // The whole of R714-B1: a stop that could not tear the workload down
1028        // must not report success.
1029        let w = RunningWorkload::adopted("container", "compute", None)
1030            .with_teardown(|| async { anyhow::bail!("docker stop refused") });
1031        let err = w.shutdown().await.unwrap_err();
1032        assert!(format!("{err:#}").contains("docker stop refused"), "{err:#}");
1033    }
1034
1035    #[tokio::test]
1036    async fn an_adopted_handle_without_a_teardown_still_shuts_down_cleanly() {
1037        // Pond containers are owned by camp's yubaba and stop through
1038        // `workload.stop`; their no-op shutdown is correct and must stay.
1039        let w = RunningWorkload::adopted("mesofact-static", "static", None);
1040        w.shutdown().await.unwrap();
1041    }
1042
1043    /// R875-B1. The stop path decides "still running, tell the operator" vs
1044    /// "untidy supervisor, log it" from this, so it has to answer for the
1045    /// handle in front of it rather than for the kind string it carries — the
1046    /// two disagreed for every adopted mesofact-dev.
1047    #[test]
1048    fn owns_teardown_tracks_the_hook_not_the_kind() {
1049        let (owned, _) = counting();
1050        assert!(owned.owns_teardown());
1051        assert!(
1052            !RunningWorkload::adopted("container", "compute", None).owns_teardown(),
1053            "a bare adopted handle owns nothing, whatever its kind says"
1054        );
1055        assert!(
1056            RunningWorkload::adopted("mesofact-static", "static", None)
1057                .with_teardown(|| async { Ok(()) })
1058                .owns_teardown(),
1059            "a non-container kind with a teardown owns its workload"
1060        );
1061    }
1062
1063    #[tokio::test]
1064    async fn the_teardown_runs_after_the_supervisor_is_joined() {
1065        // Ordering matters for a workload that has both: reap the child first,
1066        // then remove the container it was talking to.
1067        let order = Arc::new(AsyncMutex::new(Vec::<&'static str>::new()));
1068        let (tx, rx) = oneshot::channel::<()>();
1069        let sup_order = order.clone();
1070        let supervisor = tokio::spawn(async move {
1071            let _ = rx.await;
1072            sup_order.lock().await.push("supervisor");
1073            Ok(())
1074        });
1075        let hook_order = order.clone();
1076        let w = into_running("container", "compute", None, None, None, tx, supervisor)
1077            .with_teardown(move || {
1078                let hook_order = hook_order.clone();
1079                async move {
1080                    hook_order.lock().await.push("teardown");
1081                    Ok(())
1082                }
1083            });
1084
1085        w.shutdown().await.unwrap();
1086        assert_eq!(*order.lock().await, vec!["supervisor", "teardown"]);
1087    }
1088}