Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(config): seed the managed cloud provider when a workspace is created

M3gA-Mind365c2e71fafb
diff --git a/src/openhuman/config/migrations/mod.rs b/src/openhuman/config/migrations/mod.rs
index 23b7f72206..9db122c222 100644
--- a/src/openhuman/config/migrations/mod.rs
+++ b/src/openhuman/config/migrations/mod.rs
@@ -36,7 +36,38 @@ mod retire_local_whisper_stt;
mod unify_ai_provider_settings;
/// Current target schema version. Bumped alongside every new migration.
-pub const CURRENT_SCHEMA_VERSION: u32 = 10;
+pub const CURRENT_SCHEMA_VERSION: u32 = 11;
+
+/// Give a brand-new [`Config`] the managed `openhuman` cloud-provider entry.
+///
+/// A fresh workspace is created already stamped at [`CURRENT_SCHEMA_VERSION`]
+/// (`Config::load_or_init`), so **every** version gate in [`run_pending`] is
+/// false on its first launch — including the `== 1` step that is the only place
+/// the managed entry has ever been seeded. Nothing was missed and no migration
+/// failed: the entry was simply never created, and no later run can create it,
+/// because the gate that would have is behind a version the workspace skipped.
+///
+/// That is why this is called at the creation site rather than expressed as a
+/// migration. A migration cannot fix a config that is born at the target
+/// version, and bumping [`CURRENT_SCHEMA_VERSION`] to add one only moves the
+/// same hole forward a number.
+///
+/// Seeding is *not* folded into `Config::default()` on purpose. `Config` has no
+/// container-level `#[serde(default)]`, so a default-constructed provider list
+/// would not reach deserialization anyway — but it would reach every test and
+/// helper that builds a `Config` from `Default`, and [`seed_cloud_providers`]
+/// early-returns on a non-empty list. The migration tests that assert "empty
+/// list gets seeded" would then be asserting nothing at all.
+///
+/// [`seed_cloud_providers`]: unify_ai_provider_settings::seed_cloud_providers
+pub(crate) fn seed_new_workspace(config: &mut Config) {
+ let mut stats = unify_ai_provider_settings::MigrationStats::default();
+ unify_ai_provider_settings::seed_cloud_providers(config, &mut stats);
+ log::debug!(
+ "[migrations] new workspace seeded with {} cloud provider(s)",
+ stats.cloud_providers_seeded
+ );
+}
/// Run any migrations whose `schema_version` gate hasn't yet been
/// crossed for this workspace.
@@ -511,6 +542,62 @@ pub async fn run_pending(config: &mut Config) {
}
}
}
+
+ // 10 -> 11: backfill `cloud_providers` for workspaces that never got the
+ // managed `openhuman` entry.
+ //
+ // This is the repair half, not the fix. The cause is at the creation site:
+ // a fresh workspace is stamped at `CURRENT_SCHEMA_VERSION` and therefore
+ // crosses no gate at all, so the `== 1` step that seeds the managed entry
+ // never ran for it. `seed_new_workspace` closes that hole going forward;
+ // this step exists only for the workspaces already on disk without an
+ // entry, which no creation-site fix can reach. Observed on every workspace
+ // on a developer machine (two production users and one staging), all at
+ // `schema_version = 10` with `cloud_providers = []` — none of which was
+ // ever at version 1, which is what pointed at the creation site.
+ //
+ // The symptom is not subtle now that #6201 lists the managed OpenRouter
+ // catalog in the model picker: `inference_list_models("openhuman")` fails
+ // its lookup in `inference::provider::ops::models` before any HTTP request
+ // is made, the picker renders "Could not load models from this provider.",
+ // and the failure reaches Sentry through `rpc.invoke_method` — the same
+ // string `is_unknown_provider_user_config` was written to keep out of it.
+ //
+ // Reuses `seed_cloud_providers`, which early-returns when the list is
+ // already populated, so this is a no-op for every healthy workspace and
+ // cannot disturb a user's configured providers.
+ if config.schema_version == 10 {
+ let mut stats = unify_ai_provider_settings::MigrationStats::default();
+ unify_ai_provider_settings::seed_cloud_providers(config, &mut stats);
+ let previous_version = config.schema_version;
+ let seeded = stats.cloud_providers_seeded;
+ config.schema_version = 11;
+ if let Err(err) = config.save().await {
+ // Roll back BOTH the version and the seeded entries: leaving them
+ // in memory would hand `load_or_init` a config whose providers are
+ // not on disk, and the next launch would seed a second copy.
+ //
+ // Safe to revert unconditionally only because `save` now fails
+ // exclusively *before* it replaces the file: a post-rename
+ // directory-fsync failure warns instead of returning `Err` (see
+ // `Config::save`). While it did return `Err` there, this rollback
+ // could revert state that was genuinely committed, leaving the
+ // process on 10 with no providers while disk held 11 with one.
+ if seeded > 0 {
+ config.cloud_providers.clear();
+ }
+ config.schema_version = previous_version;
+ log::warn!(
+ "[migrations] reseed_cloud_providers ran but config.save failed: {err:#} — \
+ rolled in-memory schema_version back to {previous_version} and dropped {seeded} \
+ seeded entr(y/ies), will retry on next launch"
+ );
+ return;
+ }
+ log::info!(
+ "[migrations] schema_version bumped to 11 (reseed_cloud_providers seeded={seeded})"
+ );
+ }
}
#[cfg(test)]
diff --git a/src/openhuman/config/migrations/mod_tests.rs b/src/openhuman/config/migrations/mod_tests.rs
index 98b7f80fb6..3721a8679f 100644
--- a/src/openhuman/config/migrations/mod_tests.rs
+++ b/src/openhuman/config/migrations/mod_tests.rs
@@ -596,3 +596,69 @@ async fn a_hand_written_empty_allowlist_is_also_widened() {
);
}
}
+
+/// The stuck-workspace case the 10 -> 11 step exists for.
+///
+/// `unify_ai_provider_settings` is the only code that seeds the managed
+/// `openhuman` entry, and its step is guarded on `schema_version == 1`. A
+/// workspace that reached a later version without the entry could therefore
+/// never acquire one: observed on every workspace on a developer machine (two
+/// production users and one staging), all at `schema_version = 10` with
+/// `cloud_providers = []`.
+///
+/// The user-visible consequence is that `inference_list_models("openhuman")`
+/// fails its provider lookup before making any HTTP request, so the model
+/// picker's managed pane renders "Could not load models from this provider."
+#[tokio::test]
+async fn a_v10_workspace_with_no_cloud_providers_is_reseeded() {
+ let tmp = TempDir::new().unwrap();
+ fs::create_dir_all(tmp.path().join("workspace")).unwrap();
+
+ let mut config = config_in(&tmp);
+ config.schema_version = 10;
+ config.cloud_providers = Vec::new();
+
+ run_pending(&mut config).await;
+
+ assert!(
+ config.cloud_providers.iter().any(|e| e.slug == "openhuman"),
+ "a v10 workspace with an empty provider list must gain the managed entry, \
+ otherwise the model picker can never load the managed catalog"
+ );
+ assert_eq!(
+ config.schema_version, CURRENT_SCHEMA_VERSION,
+ "the re-seed step must advance the schema version"
+ );
+}
+
+/// The re-seed must not touch a workspace that already has providers.
+///
+/// `seed_cloud_providers` early-returns on a non-empty list, so this is the
+/// guard that keeps the new step a no-op for every healthy install — including
+/// one whose only entry is a BYO provider the user configured themselves.
+#[tokio::test]
+async fn a_v10_workspace_that_already_has_providers_is_left_alone() {
+ let tmp = TempDir::new().unwrap();
+ fs::create_dir_all(tmp.path().join("workspace")).unwrap();
+
+ let mut config = config_in(&tmp);
+ config.schema_version = 10;
+ config.cloud_providers = vec![
+ crate::openhuman::config::schema::cloud_providers::CloudProviderCreds {
+ id: "prov_user_owned".to_string(),
+ slug: "custom".to_string(),
+ label: "My own endpoint".to_string(),
+ endpoint: "https://llm.example.com/v1".to_string(),
+ ..Default::default()
+ },
+ ];
+
+ run_pending(&mut config).await;
+
+ assert_eq!(
+ config.cloud_providers.len(),
+ 1,
+ "an existing provider list must not be added to"
+ );
+ assert_eq!(config.cloud_providers[0].id, "prov_user_owned");
+}
diff --git a/src/openhuman/config/migrations/unify_ai_provider_settings.rs b/src/openhuman/config/migrations/unify_ai_provider_settings.rs
index 64362a9df6..e025f67bc3 100644
--- a/src/openhuman/config/migrations/unify_ai_provider_settings.rs
+++ b/src/openhuman/config/migrations/unify_ai_provider_settings.rs
@@ -76,7 +76,7 @@ pub fn run(config: &mut Config) -> anyhow::Result<MigrationStats> {
/// Seed `cloud_providers` with an OpenHuman entry (and optionally a Custom
/// entry derived from a legacy `inference_url`).
-fn seed_cloud_providers(config: &mut Config, stats: &mut MigrationStats) {
+pub(super) fn seed_cloud_providers(config: &mut Config, stats: &mut MigrationStats) {
if !config.cloud_providers.is_empty() {
log::debug!(
"[migrations][unify-ai] cloud_providers already populated ({} entries), skipping seed",
diff --git a/src/openhuman/config/schema/load/atomic_commit.rs b/src/openhuman/config/schema/load/atomic_commit.rs
new file mode 100644
index 0000000000..a23f1f5c57
--- /dev/null
+++ b/src/openhuman/config/schema/load/atomic_commit.rs
@@ -0,0 +1,196 @@
+//! The commit half of an atomic `config.toml` write.
+//!
+//! `Config::save` writes and fsyncs a temporary file, then hands it here to be
+//! swapped into place. Splitting the two apart is what makes the commit point
+//! nameable: everything before this function can fail with nothing written,
+//! and everything after the rename inside it has already taken effect.
+//!
+//! That distinction is load-bearing for callers, not cosmetic. Several of them
+//! roll in-memory state back when `save` returns `Err` — the config-migration
+//! runner reverts both `schema_version` and any entries it seeded. A failure
+//! reported *after* the replacement had committed would leave the process
+//! disagreeing with the file on disk (#6205 review), which is the
+//! asymmetric-rollback shape #6143 was about, reached from the other side.
+
+use std::path::Path;
+
+use anyhow::Context;
+use tokio::fs;
+
+/// Swap `temp_path` over `config_path`, preserving the replaced config as
+/// `.bak` — verbatim unless this save is upgrading its secrets, which
+/// [`back_up_previous`] explains.
+///
+/// Returns `Err` **only while the live config is still the old one**, so a
+/// caller may treat an error as "nothing was written" and roll back safely.
+pub(super) async fn commit_replacement(
+ temp_path: &Path,
+ config_path: &Path,
+ parent_dir: &Path,
+ backup_path: &Path,
+) -> anyhow::Result<()> {
+ back_up_previous(config_path, backup_path).await;
+
+ // Parallel test/runtime cleanup can remove an otherwise valid config
+ // directory after the temporary file is written. Recreate it directly
+ // before the rename so the atomic replacement retains its guarantee.
+ fs::create_dir_all(parent_dir).await.with_context(|| {
+ format!(
+ "Failed to recreate config directory before atomic replace: {}",
+ parent_dir.display()
+ )
+ })?;
+
+ let replace = fs::rename(temp_path, config_path).await;
+ // A concurrently-cleaning test or runtime can still remove the parent in
+ // the narrow window after the create_dir_all above. Retry the rename once
+ // after recreating it; the temp file lives alongside the target and remains
+ // available across that directory-entry race.
+ let replace = match replace {
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
+ fs::create_dir_all(parent_dir).await.with_context(|| {
+ format!(
+ "Failed to recreate config directory for atomic replace retry: {}",
+ parent_dir.display()
+ )
+ })?;
+ fs::rename(temp_path, config_path).await
+ }
+ result => result,
+ };
+
+ if let Err(e) = replace {
+ // Nothing to restore. `fs::rename` is all-or-nothing, so a failure here
+ // leaves the live config exactly as it was — already correct. The
+ // previous code copied `.bak` back over it, which (with `.bak` holding
+ // the *new* bytes) published the very write this function is about to
+ // report as failed, on the error path. Discard the temp file and let
+ // the untouched original stand.
+ let _ = fs::remove_file(temp_path).await;
+ anyhow::bail!("Failed to atomically replace config file: {e}");
+ }
+
+ // Past the commit point: the rename above has replaced the live config and
+ // every reader on this machine already sees the new bytes. The file's own
+ // contents were fsynced before it, so all this directory fsync adds is
+ // durability of the *rename* across a power loss — a weaker guarantee, not
+ // a failed save. Warn rather than return `Err`, so the promise in this
+ // function's doc comment holds.
+ if let Err(e) = super::sync_directory(parent_dir).await {
+ tracing::warn!(
+ path = %parent_dir.display(),
+ error = %e,
+ "[config] config was replaced but its directory entry could not be \
+ fsynced; the write is visible now but may not survive a power loss"
+ );
+ }
+
+ Ok(())
+}
+
+/// Preserve the config that is about to be replaced, as `.bak`.
+///
+/// Sourced from the live config, not from `temp_path`. Backing up the temp file
+/// made `.bak` a duplicate of the config being written the moment the rename
+/// landed, so the previous one was gone and `load_or_init`'s corruption
+/// recovery had nothing older to fall back to — the one job this file has.
+///
+/// **Byte-for-byte, except when the save is a secret upgrade.** A verbatim copy
+/// is what a backup should be: it keeps whatever the previous file held,
+/// including keys this build does not model and would drop on a round trip
+/// through `Config` — and a rollback or a bad migration is exactly when that
+/// matters. So that is the default.
+///
+/// The exception is narrow and load-bearing. `encrypt_config_secrets` only
+/// encrypts values that are not already encrypted, so a save can be an in-place
+/// upgrade of the file it is replacing: plaintext to `enc2:`, or the forced
+/// `enc:` (XOR) to `enc2:` migration that `load_or_init` triggers a save for
+/// with the express purpose of making "the insecure ciphertext stop living on
+/// disk (audit C8)". Copying those bytes into a `.bak` that nothing ever cleans
+/// would defeat that save exactly, so in that case the *upgraded* form is
+/// written instead. This is what `config_secrets_encrypted_on_save_decrypted_on_load`
+/// pins, and it is why the backup used to be taken from the temp file — which
+/// bought that property by giving the recovery guarantee away.
+///
+/// The test for "is this an upgrade" is the upgrade itself: re-encrypt a copy
+/// of the previous config and see whether anything changed. Nothing changed
+/// means the file was already at rest, which is the overwhelmingly common case,
+/// and it takes the verbatim path.
+///
+/// Best-effort throughout. A backup is a convenience for a corrupt-config
+/// recovery that may never happen; none of its failure modes justify failing a
+/// save that is otherwise fine, and every early return here leaves any existing
+/// `.bak` untouched rather than replacing it with something worse.
+async fn back_up_previous(config_path: &Path, backup_path: &Path) {
+ // No existing config: a first-ever write has nothing to preserve. Read
+ // rather than test-then-read, so a concurrent removal is the same path.
+ let Ok(existing) = fs::read_to_string(config_path).await else {
+ return;
+ };
+ let Ok(mut previous) = toml::from_str::<crate::openhuman::config::Config>(&existing) else {
+ // Unparseable, so it cannot be checked for at-rest secrets and cannot
+ // be trusted not to hold one. It is also worthless to recovery, which
+ // parses what it finds here.
+ tracing::debug!(
+ path = %config_path.display(),
+ "[config] previous config did not parse; skipping backup"
+ );
+ return;
+ };
+ // The parsed copy carries no `config_path` — it is not a serialized field —
+ // and `encrypt_config_secrets` resolves its key material relative to one.
+ previous.config_path = config_path.to_path_buf();
+
+ let mut upgraded = previous.clone();
+ if let Err(e) = super::secrets::encrypt_config_secrets(&mut upgraded) {
+ tracing::debug!(
+ path = %config_path.display(),
+ error = %e,
+ "[config] could not check the previous config for at-rest secrets; skipping backup"
+ );
+ return;
+ }
+ let (Ok(as_found), Ok(as_upgraded)) = (
+ toml::to_string_pretty(&previous),
+ toml::to_string_pretty(&upgraded),
+ ) else {
+ return;
+ };
+
+ if as_found == as_upgraded {
+ // Already at rest: nothing this save would strip, so keep the file
+ // exactly as it is, unknown keys and all.
+ if fs::copy(config_path, backup_path).await.is_err() {
+ return;
+ }
+ } else if fs::write(backup_path, as_upgraded).await.is_err() {
+ return;
+ }
+ harden_backup(backup_path).await;
+}
+
+/// Restrict a freshly written `.bak` to `0600`.
+///
+/// `fs::copy` carries the source file's mode and `fs::write` creates at
+/// `0o666 & ~umask` (0644 under the usual 022) — and a config predating the
+/// load-time hardening can still be `0644` on disk. The backup holds the same
+/// `enc2:` provider keys and channel tokens as the config itself, which `save`
+/// hardens for exactly that reason. Best-effort for the
+/// same reason that hardening is: filesystems without chmod (CIFS/SMB, exFAT,
+/// some FUSE mounts) must not turn a working save into a hard failure.
+async fn harden_backup(backup_path: &Path) {
+ #[cfg(unix)]
+ {
+ use std::{fs::Permissions, os::unix::fs::PermissionsExt};
+ if let Err(e) = fs::set_permissions(backup_path, Permissions::from_mode(0o600)).await {
+ tracing::warn!(
+ path = %backup_path.display(),
+ error = %e,
+ "[security][config] could not restrict config backup to 0600; \
+ it may be readable by other local users"
+ );
+ }
+ }
+ #[cfg(not(unix))]
+ let _ = backup_path;
+}
diff --git a/src/openhuman/config/schema/load/impl_load.rs b/src/openhuman/config/schema/load/impl_load.rs
index b7d0a6c46f..15fca2ef48 100644
--- a/src/openhuman/config/schema/load/impl_load.rs
+++ b/src/openhuman/config/schema/load/impl_load.rs
@@ -491,6 +491,16 @@ impl Config {
schema_version: crate::openhuman::config::migrations::CURRENT_SCHEMA_VERSION,
..Default::default()
};
+ // A workspace created here is stamped at the *current* schema
+ // version, so the `run_pending` call below has no gate left to
+ // cross — including the `== 1` step that is the only place the
+ // managed `openhuman` cloud provider has ever been seeded. Without
+ // this, every fresh install starts with `cloud_providers = []` and
+ // can never acquire the entry, which is what left real workspaces
+ // failing `inference_list_models("openhuman")` before any request
+ // was made. Seed before the first `save` so the entry is on disk
+ // from the very first write rather than on some later one.
+ crate::openhuman::config::migrations::seed_new_workspace(&mut config);
config.save().await?;
#[cfg(unix)]
@@ -692,57 +702,17 @@ impl Config {
.context("Failed to fsync temporary config file")?;
drop(temp_file);
- let had_existing_config = tokio::fs::try_exists(&self.config_path)
- .await
- .unwrap_or(false);
- if had_existing_config {
- fs::copy(&temp_path, &backup_path).await.with_context(|| {
- format!(
- "Failed to create config backup before atomic replace: {}",
- backup_path.display()
- )
- })?;
- }
-
- // Parallel test/runtime cleanup can remove an otherwise valid config
- // directory after the temporary file is written. Recreate it directly
- // before the rename so the atomic replacement retains its guarantee.
- fs::create_dir_all(parent_dir).await.with_context(|| {
- format!(
- "Failed to recreate config directory before atomic replace: {}",
- parent_dir.display()
- )
- })?;
-
- let replace = fs::rename(&temp_path, &self.config_path).await;
- // A concurrently-cleaning test or runtime can still remove the parent
- // in the narrow window after the create_dir_all above. Retry the rename
- // once after recreating it; the temp file lives alongside the target and
- // remains available across that directory-entry race.
- let replace = match replace {
- Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
- fs::create_dir_all(parent_dir).await.with_context(|| {
- format!(
- "Failed to recreate config directory for atomic replace retry: {}",
- parent_dir.display()
- )
- })?;
- fs::rename(&temp_path, &self.config_path).await
- }
- result => result,
- };
-
- if let Err(e) = replace {
- let _ = fs::remove_file(&temp_path).await;
- if had_existing_config && backup_path.exists() {
- fs::copy(&backup_path, &self.config_path)
- .await
- .context("Failed to restore config backup")?;
- }
- anyhow::bail!("Failed to atomically replace config file: {e}");
- }
-
- super::sync_directory(parent_dir).await?;
+ // Everything above can still fail with the live config untouched.
+ // `commit_replacement` owns the swap, and returns `Err` only while the
+ // old config is still in place — see its docs for why callers that roll
+ // back on `Err` depend on that.
+ super::atomic_commit::commit_replacement(
+ &temp_path,
+ &self.config_path,
+ parent_dir,
+ &backup_path,
+ )
+ .await?;
Ok(())
}
diff --git a/src/openhuman/config/schema/load/mod.rs b/src/openhuman/config/schema/load/mod.rs
index 818351d22f..a8f9352ddd 100644
--- a/src/openhuman/config/schema/load/mod.rs
+++ b/src/openhuman/config/schema/load/mod.rs
@@ -57,6 +57,8 @@ pub(crate) use migrate::{migrate_cloud_provider_slugs, migrate_legacy_inference_
#[cfg(test)]
pub(crate) use std::path::PathBuf;
+mod atomic_commit;
+
#[cfg(unix)]
pub(super) async fn sync_directory(path: &std::path::Path) -> anyhow::Result<()> {
use anyhow::Context;
diff --git a/src/openhuman/config/schema/load_tests.rs b/src/openhuman/config/schema/load_tests.rs
index 44c94a7e0c..48676dc35e 100644
--- a/src/openhuman/config/schema/load_tests.rs
+++ b/src/openhuman/config/schema/load_tests.rs
@@ -108,3 +108,5 @@ mod part_02_tests;
mod part_03_tests;
#[path = "load_tests_part_04_tests.rs"]
mod part_04_tests;
+#[path = "load_tests_part_05_tests.rs"]
+mod part_05_tests;
diff --git a/src/openhuman/config/schema/load_tests_part_04_tests.rs b/src/openhuman/config/schema/load_tests_part_04_tests.rs
index 302aeed9b5..4245beef07 100644
--- a/src/openhuman/config/schema/load_tests_part_04_tests.rs
+++ b/src/openhuman/config/schema/load_tests_part_04_tests.rs
@@ -545,3 +545,88 @@ fn resolve_action_dir_rejects_empty_override() {
"empty override must be ignored, falling back to default"
);
}
+
+// ── fresh-install provider seeding (#6205) ──────────────────────────────
+//
+// The case neither the original fix nor its tests covered, and the one that
+// regressed: a workspace created *today*, not one migrated from an older
+// schema.
+
+/// A brand-new workspace must be born with the managed `openhuman` cloud
+/// provider.
+///
+/// `load_or_init` stamps a fresh config with `CURRENT_SCHEMA_VERSION`, so the
+/// `run_pending` call that follows crosses no gate at all — including the
+/// `== 1` step that is the only place this entry has ever been seeded. Without
+/// creation-site seeding the list is empty, and no later migration can repair
+/// it, because the workspace is already past every gate that would have.
+///
+/// This is what made `inference_list_models("openhuman")` fail its lookup in
+/// `inference::provider::ops::models` before any HTTP request was made, which
+/// is what #6201's model picker surfaced as "Could not load models from this
+/// provider."
+#[tokio::test]
+async fn a_brand_new_workspace_is_born_with_the_managed_provider() {
+ use crate::openhuman::config::schema::cloud_providers::AuthStyle;
+
+ let tmp = tempfile::tempdir().unwrap();
+ let config = load_or_init_for_workspace(tmp.path()).await;
+
+ let managed = config
+ .cloud_providers
+ .iter()
+ .find(|p| p.slug == "openhuman")
+ .unwrap_or_else(|| {
+ panic!(
+ "a fresh workspace must carry the managed provider, got {:?}",
+ config
+ .cloud_providers
+ .iter()
+ .map(|p| p.slug.as_str())
+ .collect::<Vec<_>>()
+ )
+ });
+ assert_eq!(managed.auth_style, AuthStyle::OpenhumanJwt);
+ assert!(
+ !managed.endpoint.trim().is_empty(),
+ "the seeded entry needs a resolvable endpoint"
+ );
+
+ // Seeded before the first `save`, so it is on disk from the very first
+ // write — not merely in memory awaiting some later persist.
+ let on_disk = tokio::fs::read_to_string(&config.config_path)
+ .await
+ .unwrap();
+ assert!(
+ on_disk.contains("slug = \"openhuman\""),
+ "the seeded entry must be persisted by the initial save, got:\n{on_disk}"
+ );
+}
+
+/// Re-opening that workspace must not seed a second copy.
+///
+/// `seed_cloud_providers` early-returns on a non-empty list, and the version
+/// gate is already past, so the second load has to be a no-op. A duplicate here
+/// would mean the entry is being created on a path that does not check first.
+#[tokio::test]
+async fn reopening_a_seeded_workspace_does_not_duplicate_the_provider() {
+ let tmp = tempfile::tempdir().unwrap();
+ let first = load_or_init_for_workspace(tmp.path()).await;
+ let seeded = first
+ .cloud_providers
+ .iter()
+ .filter(|p| p.slug == "openhuman")
+ .count();
+ assert_eq!(seeded, 1, "first load seeds exactly one managed entry");
+
+ let second = load_or_init_for_workspace(tmp.path()).await;
+ assert_eq!(
+ second
+ .cloud_providers
+ .iter()
+ .filter(|p| p.slug == "openhuman")
+ .count(),
+ 1,
+ "re-opening the workspace must not seed a second managed entry"
+ );
+}
diff --git a/src/openhuman/config/schema/load_tests_part_05_tests.rs b/src/openhuman/config/schema/load_tests_part_05_tests.rs
new file mode 100644
index 0000000000..51bb5f0700
--- /dev/null
+++ b/src/openhuman/config/schema/load_tests_part_05_tests.rs
@@ -0,0 +1,178 @@
+use super::*;
+
+// ── config.toml.bak holds the PREVIOUS config (#6205 review) ────────────
+//
+// Found in review, not by us: the backup was copied from the temp file, so
+// `.bak` became a duplicate of the config that had just been written and the
+// previous one was gone. Recovery had nothing older to fall back to, and the
+// failed-rename path copied those new bytes over the live config while
+// reporting `Err`.
+
+/// After a save, `config.toml.bak` must hold what `config.toml` held *before*
+/// it — not a second copy of what was just written.
+///
+/// `load_or_init`'s corruption recovery reads this file to get back a working
+/// config. A `.bak` that mirrors the live file cannot do that, and the mismatch
+/// is invisible until the day it is needed.
+#[tokio::test]
+async fn a_save_backs_up_the_previous_config_not_the_new_one() {
+ let tmp = tempfile::tempdir().unwrap();
+ let mut config = load_or_init_for_workspace(tmp.path()).await;
+ config.default_model = Some("first-generation-model".to_string());
+ config.save().await.expect("first save");
+
+ // The config as it stands on disk immediately before the save under test.
+ let previous = tokio::fs::read_to_string(&config.config_path)
+ .await
+ .unwrap();
+ assert!(
+ previous.contains("first-generation-model")
+ && !previous.contains("second-generation-model"),
+ "precondition: disk holds the first generation and not the second"
+ );
+
+ config.default_model = Some("second-generation-model".to_string());
+ config.save().await.expect("second save");
+
+ let backup_path = config.config_path.with_file_name("config.toml.bak");
+ let backed_up = tokio::fs::read_to_string(&backup_path)
+ .await
+ .expect("a save over an existing config must leave a .bak");
+ let live = tokio::fs::read_to_string(&config.config_path)
+ .await
+ .unwrap();
+
+ assert!(
+ live.contains("second-generation-model"),
+ "the live config must hold the new contents"
+ );
+ assert!(
+ !backed_up.contains("second-generation-model"),
+ "the backup must hold the PREVIOUS config, not a copy of the new one"
+ );
+ // Not asserted byte-for-byte: the backup is re-serialized through the same
+ // secret encryption the live config gets, so that replacing a legacy
+ // plaintext config cannot leave the plaintext behind in `.bak`
+ // (`config_secrets_encrypted_on_save_decrypted_on_load` pins that). What
+ // must hold is that it *describes the previous config* and that recovery,
+ // which parses this file, can still load it.
+ assert!(
+ backed_up.contains("first-generation-model"),
+ "the backup must hold the previous config's contents, got:\n{backed_up}"
+ );
+ let recovered: crate::openhuman::config::Config = toml::from_str(&backed_up)
+ .expect("the backup must parse as a config, since recovery loads it");
+ assert_eq!(
+ recovered.default_model.as_deref(),
+ Some("first-generation-model"),
+ "the backup must describe the config that was replaced"
+ );
+}
+
+/// A first-ever write has no existing config to preserve, and that must not be
+/// an error — nor may it invent a `.bak` seeded with the new contents.
+#[tokio::test]
+async fn a_first_ever_save_succeeds_without_writing_a_backup() {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = load_or_init_for_workspace(tmp.path()).await;
+
+ assert!(
+ tokio::fs::try_exists(&config.config_path).await.unwrap(),
+ "the initial save must have written the config"
+ );
+ let backup_path = config.config_path.with_file_name("config.toml.bak");
+ assert!(
+ !tokio::fs::try_exists(&backup_path).await.unwrap(),
+ "a first-ever write has nothing to back up, so no .bak should exist"
+ );
+}
+
+/// A backup of an already-at-rest config must be the file itself, byte for
+/// byte — including anything this build does not model.
+///
+/// `Config` ignores unknown keys, so a round trip through parse-and-serialize
+/// silently drops them. A rollback, a downgrade or a bad migration is exactly
+/// when a backup is read, and exactly when the dropped keys would be wanted, so
+/// the verbatim copy is the default and only a secret upgrade displaces it.
+#[tokio::test]
+async fn a_backup_of_an_at_rest_config_is_byte_for_byte() {
+ let tmp = tempfile::tempdir().unwrap();
+ let mut config = load_or_init_for_workspace(tmp.path()).await;
+
+ // Something a future build wrote and this one has never heard of.
+ let doctored = format!(
+ "{}\nkey_from_a_build_we_do_not_know = \"preserve-me\"\n",
+ tokio::fs::read_to_string(&config.config_path)
+ .await
+ .unwrap()
+ );
+ tokio::fs::write(&config.config_path, &doctored)
+ .await
+ .unwrap();
+
+ config.default_model = Some("post-doctoring-model".to_string());
+ config.save().await.expect("save over the doctored config");
+
+ let backup_path = config.config_path.with_file_name("config.toml.bak");
+ let backed_up = tokio::fs::read_to_string(&backup_path).await.unwrap();
+
+ assert_eq!(
+ backed_up, doctored,
+ "an at-rest config must be backed up verbatim, not re-serialized"
+ );
+ assert!(
+ backed_up.contains("key_from_a_build_we_do_not_know"),
+ "a key this build does not model must survive into the backup"
+ );
+ assert!(
+ !tokio::fs::read_to_string(&config.config_path)
+ .await
+ .unwrap()
+ .contains("key_from_a_build_we_do_not_know"),
+ "precondition: the live config does drop it, which is why the backup must not"
+ );
+}
+
+/// The narrow exception: when the save is upgrading secrets in place, the
+/// backup must hold the upgraded form, not the pre-upgrade bytes.
+///
+/// `load_or_init` triggers exactly this save when it force-migrates a legacy
+/// `enc:` secret, for the stated purpose of making the insecure ciphertext stop
+/// living on disk. A verbatim `.bak` would keep it there permanently.
+#[tokio::test]
+async fn a_backup_never_preserves_a_secret_the_save_is_upgrading() {
+ let tmp = tempfile::tempdir().unwrap();
+ let workspace_dir = tmp.path().join("workspace");
+ std::fs::create_dir_all(&workspace_dir).unwrap();
+ let config_path = tmp.path().join("config.toml");
+ let secret = "plaintext-token-that-must-not-survive";
+
+ std::fs::write(
+ &config_path,
+ format!("[channels_config.telegram]\nbot_token = \"{secret}\"\nallowed_users = []\n"),
+ )
+ .unwrap();
+
+ let mut cfg = Config {
+ config_path: config_path.clone(),
+ workspace_dir,
+ ..Default::default()
+ };
+ cfg.channels_config.telegram = Some(TelegramConfig {
+ bot_token: secret.to_string(),
+ chat_id: None,
+ allowed_users: vec![],
+ stream_mode: StreamMode::Off,
+ draft_update_interval_ms: 1000,
+ silent_streaming: true,
+ mention_only: false,
+ });
+ cfg.save().await.unwrap();
+
+ let backup_path = config_path.with_file_name("config.toml.bak");
+ let backed_up = tokio::fs::read_to_string(&backup_path).await.unwrap();
+ assert!(
+ !backed_up.contains(secret),
+ "the pre-upgrade plaintext secret must not survive in .bak, got:\n{backed_up}"
+ );
+}