Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
A production-floor card is never a dead end: allow a guessed migration without a backup, Where resolves $R (22f part 1) (#696)
Oleksandr Ivanchenko79628ad0ed77
diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.ymlindex 77b10574..d0885724 100644--- a/.github/workflows/windows.yml+++ b/.github/workflows/windows.yml@@ -85,7 +85,7 @@ jobs:# Exactly this many tests must run (Rigel's F-2): a renamed or moved test that no longer# matches the filters fails here instead of quietly dropping out. Change it with the filters.# 16 since #446: floor.rs gained head_branch_needs_objects_and_refs_like_git, _keeps_a_worktree_gitdir_in_the_bot_folder and _refuses_a_working_folder_outside_the_bot_folder.- EXPECTED_TESTS: 16+ EXPECTED_TESTS: 18run: |set -euo pipefailcargo test --locked --lib --no-fail-fast -- server::dev::floor:: server::dev::poller::tests::fresh_means server::dev::poller::tests::candidates_go_newest server::dev::poller::tests::the_skipped_count server::dev::git::tests::diff_output_parses server::dev::git::tests::patches_are_matched 2>&1 | tee dev-readers.logdiff --git a/src/db/mod.rs b/src/db/mod.rsindex fe2c1692..ca87450f 100644--- a/src/db/mod.rs+++ b/src/db/mod.rs@@ -703,6 +703,12 @@ impl Database {Ok(row)}+ /// Rewrites a card's details (its JSON `parameters`), e.g. to record how it was answered.+ pub async fn update_approval_parameters(&self, id: &str, parameters: &str) -> Result<(), DbError> {+ sqlx::query("UPDATE approvals SET parameters = ? WHERE id = ?").bind(parameters).bind(id).execute(&self.pool).await?;+ Ok(())+ }+pub async fn update_approval_status(&self, id: &str, status: &str) -> Result<(), DbError> {sqlx::query("UPDATE approvals SET status = ? WHERE id = ?").bind(status)diff --git a/src/mcp/prod_floor.rs b/src/mcp/prod_floor.rsindex 70d36fd4..499237cb 100644--- a/src/mcp/prod_floor.rs+++ b/src/mcp/prod_floor.rs@@ -46,6 +46,19 @@ impl FloorKind {}}+/// Whether a [`FloorKind::DeployMigration`] step is known to change the database (`yes`: it runs+/// migrations, or the caller knows the code does) or only counts as one because kwant can't tell+/// (`guess`). Only a guess may be allowed without a backup, and only by the person (22f).+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum Migration {+ Yes,+ Guess,+}++/// The Database row of a deploy kwant can't tell about.+const GUESS_ROW: &str = "Might change it. The app can't tell from the command.";+/// Why a call hits the floor, with the blast-radius rows the card shows (only what's known).#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pub struct Floor {@@ -58,11 +71,17 @@ pub struct Floor {/// If it fails. Serialised as `[label, value]` pairs.pub blast: Vec<(String, String)>,pub needs_backup: bool,+ /// Only on a [`FloorKind::DeployMigration`]: whether the migration is known or a guess.+ /// Serialised as `"migration": "yes" | "guess"`, absent on every other kind.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub migration: Option<Migration>,}impl Floor {+ /// A migration deploy made here is a known one; only [`DevCtx::deploy`] makes a guess.fn new(kind: FloorKind, why: impl Into<String>) -> Self {- Floor { kind, why: why.into(), blast: Vec::new(), needs_backup: kind.needs_backup() }+ let migration = (kind == FloorKind::DeployMigration).then_some(Migration::Yes);+ Floor { kind, why: why.into(), blast: Vec::new(), needs_backup: kind.needs_backup(), migration }}fn row(mut self, label: &str, value: impl Into<String>) -> Self {@@ -74,14 +93,23 @@ impl Floor {}/// The stronger of two findings; rows of both are kept.+ /// A migration deploy stays a guess only when every migration in it is one: a known one wins,+ /// with its own Database row.fn merge(self, other: Floor) -> Floor {let (mut keep, extra) = if other.kind.rank() > self.kind.rank() { (other, self) } else { (self, other) };+ if keep.migration == Some(Migration::Guess) && extra.migration == Some(Migration::Yes) {+ keep.migration = Some(Migration::Yes);+ keep.blast.retain(|(l, _)| l != "Database");+ }for (l, v) in extra.blast {if !keep.blast.iter().any(|(k, _)| *k == l) {keep.blast.push((l, v));}}keep.needs_backup = keep.kind.needs_backup();+ if keep.kind != FloorKind::DeployMigration {+ keep.migration = None;+ }keep}}@@ -122,11 +150,11 @@ impl DevCtx {let migration = !self.no_data() && self.migration != Some(false);if migration {let known = self.migration == Some(true);- Floor::new(FloorKind::DeployMigration, why).row(- "Migration",- if known { "This deploy changes the database." } else { "kwant can't tell whether this deploy changes the database, so it counts as one." },- )- .row("If it fails", "The app goes back on its own. The database goes back only from a backup.")+ let mut f = Floor::new(FloorKind::DeployMigration, why).row("Database", if known { "This deploy changes it." } else { GUESS_ROW });+ if !known {+ f.migration = Some(Migration::Guess);+ }+ f.row("If it fails", "The app goes back on its own. The database goes back only from a backup.")} else {let f = Floor::new(FloorKind::Deploy, why);if self.no_data() {@@ -513,6 +541,9 @@ fn shell_reason_at(command: &str, ctx: &DevCtx, depth: usize, over_ssh: bool) ->}}let mut ssh_host: Option<String> = None;+ // `[email protected]; ssh $R …`: plain assignments made in this command, so Where can name the+ // server (22f). `None` marks a name whose value can't be told.+ let mut vars: Vec<(String, Option<String>)> = Vec::new();// A `git checkout`/`git switch` earlier in the chain changes what a bare `git push` pusheslet mut cur = ctx.clone();// `ssh host 'cd /srv && docker compose up -d'`: the quoted remote command spans segments;@@ -534,10 +565,12 @@ fn shell_reason_at(command: &str, ctx: &DevCtx, depth: usize, over_ssh: bool) ->// Env assignments, and wrappers that run the rest of the line (with their own flags)let mut i = 0;let mut env_prod = false;+ let mut assigned: Vec<&str> = Vec::new();while i < words.len() {let w = words[i].as_str();if w.contains('=') && !w.starts_with('-') {env_prod |= prod_env(w);+ assigned.push(w);i += 1;} else if let Some(n) = wrapper_len(w.trim_start_matches('\\'), &words[i + 1..]) {i = (i + n).min(words.len());@@ -545,6 +578,15 @@ fn shell_reason_at(command: &str, ctx: &DevCtx, depth: usize, over_ssh: bool) ->break;}}+ // A bare `R=…` (or `export R=…`) sets R for the rest of this command; `R=… cmd` only for+ // cmd. Assignments in the remote half of `ssh host '…'` are the server's, not ours.+ let export = words.get(i).is_some_and(|w| w == "export" || w == "declare" || w == "local" || w == "readonly");+ if !remote && (i == words.len() || export) {+ let more = if export { &words[i + 1..] } else { &[][..] };+ for w in assigned.iter().copied().chain(more.iter().map(String::as_str).filter(|w| !w.starts_with('-'))) {+ set_var(&mut vars, w);+ }+ }let Some((program, args)) = words[i..].split_first() else { continue };// `\git` skips aliases and still runs gitlet program = program.trim_start_matches('\\');@@ -555,6 +597,7 @@ fn shell_reason_at(command: &str, ctx: &DevCtx, depth: usize, over_ssh: bool) ->match program.as_str() {"ssh" => {if let Some((host, rest)) = ssh_target(&a) {+ let host = where_host(&host, &vars);ssh_host = Some(host.clone());ssh_quote = ['\'', '"'].into_iter().find(|q| segment.matches(*q).count() % 2 == 1);if !rest.is_empty() {@@ -720,7 +763,64 @@ fn remote_url(v: &str) -> bool {}}-/// `ssh [options] host [command…]` → host and command words.+/// Records `NAME=value` in `vars` (a later one wins). A value that names a variable kwant can't+/// tell, or runs a command, makes the name unknown.+fn set_var(vars: &mut Vec<(String, Option<String>)>, assign: &str) {+ let Some((name, value)) = assign.split_once('=') else { return };+ if !var_name(name) {+ return;+ }+ let value = value.trim_matches(|c| c == '\'' || c == '"');+ let known = if value.contains("$(") || value.contains('`') { None } else { expand(value, vars) };+ vars.retain(|(n, _)| n != name);+ vars.push((name.to_string(), known));+}++fn var_name(name: &str) -> bool {+ let mut cs = name.chars();+ cs.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_') && cs.all(|c| c.is_ascii_alphanumeric() || c == '_')+}++/// `text` with `$NAME` and `${NAME}` replaced from `vars`, or `None` when one can't be told.+fn expand(text: &str, vars: &[(String, Option<String>)]) -> Option<String> {+ let mut out = String::new();+ let mut rest = text;+ while let Some(at) = rest.find('$') {+ out.push_str(&rest[..at]);+ let after = &rest[at + 1..];+ let (name, used) = match after.strip_prefix('{') {+ Some(b) => {+ let end = b.find('}')?;+ (&b[..end], end + 2)+ }+ None => {+ let end = after.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).unwrap_or(after.len());+ (&after[..end], end)+ }+ };+ if !var_name(name) {+ return None;+ }+ out.push_str(vars.iter().rev().find(|(n, _)| n == name)?.1.as_deref()?);+ rest = &after[used..];+ }+ out.push_str(rest);+ Some(out)+}++/// The ssh target as Where shows it: `$R` resolved from the command's own `R=…`, or, when it+/// can't be, a sentence that says so (never a bare `$R`).+fn where_host(host: &str, vars: &[(String, Option<String>)]) -> String {+ if !host.contains('$') {+ return host.to_string();+ }+ match expand(host, vars) {+ Some(h) if !h.trim().is_empty() => h,+ _ => format!("a server named by {host} in the command"),+ }+}++/// `ssh [options] [user@]host [command…]` → the target as written and the command words.fn ssh_target<'a>(args: &[&'a str]) -> Option<(String, Vec<&'a str>)> {let mut i = 0;while i < args.len() {@@ -731,8 +831,7 @@ fn ssh_target<'a>(args: &[&'a str]) -> Option<(String, Vec<&'a str>)> {i += if takes { 2 } else { 1 };continue;}- let host = a.rsplit('@').next().unwrap_or(a).to_string();- return Some((host, args[i + 1..].to_vec()));+ return Some((a.to_string(), args[i + 1..].to_vec()));}None}@@ -880,7 +979,7 @@ fn program_reason(program: &str, a: &[&str], ctx: &DevCtx, env_prod: bool, over_"redis-cli" => a.iter().any(|x| x.eq_ignore_ascii_case("flushall") || x.eq_ignore_ascii_case("flushdb")).then(|| destroy("redis-cli empties the store".into())),// Migrations run against production_ if migrate_cmd(program, a) => (env_prod || a.iter().any(|x| is_prod_flag(x) || prod_env(x)) || flag_value(a, &["--settings"]).is_some_and(prod_settings))- .then(|| Floor::new(FloorKind::DeployMigration, format!("{program} migrates a production database")).row("Migration", "Runs database migrations on production.")),+ .then(|| Floor::new(FloorKind::DeployMigration, format!("{program} migrates a production database")).row("Database", "This command changes it on production.")),_ => None,}}@@ -1333,7 +1432,7 @@ mod tests {assert!(!f.needs_backup);let unknown = shell_reason("fly deploy", &ctx()).unwrap();assert!(unknown.needs_backup);- assert!(unknown.blast.iter().any(|(l, v)| l == "Migration" && v.contains("can't tell")));+ assert!(unknown.blast.iter().any(|(l, v)| l == "Database" && v.contains("can't tell")));}#[test]@@ -1398,7 +1497,74 @@ mod tests {assert!(f.blast.iter().any(|(l, v)| l == "Where" && v == "Fly app demo-app"));assert!(f.blast.iter().any(|(l, _)| l == "What changes"));let f = shell_reason("ssh [email protected] docker compose up -d", &ctx()).unwrap();- assert!(f.blast.iter().any(|(l, v)| l == "Where" && v == "kwant.example.com"), "{:?}", f.blast);+ assert!(f.blast.iter().any(|(l, v)| l == "Where" && v == "[email protected]"), "{:?}", f.blast);+ }++ /// Oleks's deploy on Nov 15 (22f), verbatim from his card: `ssh $R` names+ /// `[email protected]` set earlier in the same command.+ const OLEKS_DEPLOY: &str = r#"set -e; [email protected]; D=/opt/tradebot; timeout 120 ssh -o BatchMode=yes -o ConnectTimeout=15 $R "cd $D && cp -p catalyst-linux [redacted] && sha256sum [redacted] timeout 300 scp -o BatchMode=yes /tmp/builder-deploy/catalyst-linux $R:$D/catalyst-linux.new; timeout 120 ssh -o BatchMode=yes -o ConnectTimeout=15 $R "cd $D && chmod +x catalyst-linux.new && sha256sum catalyst-linux.new && mv catalyst-linux.new catalyst-linux && sha256sum catalyst-linux && docker compose up -d --no-deps --force-recreate catalyst 2>&1 && sleep 20 && docker compose ps catalyst && echo '--- env flag names:' && docker exec tradebot-catalyst-1 env | grep -c '^TREND_MAKER_FIRST=' || true && docker compose logs --tail 25 catalyst | cut -c1-260"; echo "exit=$?""#;++ fn where_of(f: &Floor) -> Option<&str> {+ f.blast.iter().find(|(l, _)| l == "Where").map(|(_, v)| v.as_str())+ }++ #[test]+ fn where_names_the_server_a_variable_holds() {+ let f = shell_reason(OLEKS_DEPLOY, &ctx()).expect("a deploy");+ assert_eq!(f.kind, FloorKind::DeployMigration);+ assert_eq!(where_of(&f), Some("[email protected]"), "{:?}", f.blast);+ assert_eq!(f.migration, Some(Migration::Guess));+ for (cmd, want) in [+ ("[email protected]; ssh $R 'docker compose up -d'", "[email protected]"),+ ("[email protected] && ssh \"$R\" 'docker compose up -d'", "[email protected]"),+ ("[email protected]; ssh ${R} 'docker compose up -d'", "[email protected]"),+ ("export R=\"[email protected]\"; ssh -p 2222 $R docker compose up -d", "[email protected]"),+ ("H=1.2.3.4; R=root@$H; ssh $R docker compose up -d", "[email protected]"),+ ("U=deploy; ssh [email protected] docker compose up -d", "[email protected]"),+ // A later assignment wins+ ("R=a.example.com; R=b.example.com; ssh $R docker compose up -d", "b.example.com"),+ // Never resolved: set elsewhere, set only for one command, or by a command's output+ ("ssh $R 'docker compose up -d'", "a server named by $R in the command"),+ ("R=x.example.com ssh $R docker compose up -d", "a server named by $R in the command"),+ ("R=$(cat host.txt); ssh $R docker compose up -d", "a server named by $R in the command"),+ ("R=$HOST; ssh $R docker compose up -d", "a server named by $R in the command"),+ // An assignment on the server doesn't name it+ ("ssh $R 'R=evil.example.com; docker compose up -d'", "a server named by $R in the command"),+ ("ssh [email protected] docker compose up -d", "[email protected]"),+ ] {+ let f = shell_reason(cmd, &ctx()).unwrap_or_else(|| panic!("no floor for {cmd}"));+ assert_eq!(where_of(&f), Some(want), "{cmd}: {:?}", f.blast);+ }+ }++ #[test]+ fn a_migration_says_whether_it_is_known_or_a_guess() {+ let c = ctx();+ let json = |cmd: &str, c: &DevCtx| serde_json::to_value(shell_reason(cmd, c).unwrap()).unwrap();+ // kwant can't tell: a guess+ let v = json("docker compose up -d", &c);+ assert_eq!((v["kind"].as_str(), v["migration"].as_str()), (Some("deploy_migration"), Some("guess")));+ // Known: the caller knows the code changes the database, or the command runs migrations+ let v = json("docker compose up -d", &DevCtx { migration: Some(true), ..ctx() });+ assert_eq!(v["migration"], "yes");+ let v = json("RAILS_ENV=production bin/rails db:migrate", &c);+ assert_eq!((v["kind"].as_str(), v["migration"].as_str()), (Some("deploy_migration"), Some("yes")), "{v}");+ // A deploy plus a known migration is a known one, with the known row+ let f = shell_reason("docker compose up -d && RAILS_ENV=production bin/rails db:migrate", &c).unwrap();+ assert_eq!(f.migration, Some(Migration::Yes));+ assert!(!f.blast.iter().any(|(_, v)| v == GUESS_ROW), "{:?}", f.blast);+ let f = shell_reason("RAILS_ENV=production bin/rails db:migrate && docker compose up -d", &c).unwrap();+ assert_eq!(f.migration, Some(Migration::Yes));+ // No migration field on any other kind, even when a guessed deploy is in the command+ for cmd in ["rm -rf /srv/app/data", "docker compose up -d && rm -rf /srv/app/data", "ssh $R 'docker compose up -d; rm -rf /srv/app/data'", "git push origin main"] {+ let v = json(cmd, &c);+ assert_ne!(v["kind"], "deploy_migration", "{cmd}");+ assert!(v.get("migration").is_none(), "{cmd}: {v}");+ }+ // No data, or known not to change it: a plain deploy+ let v = json("docker compose up -d", &DevCtx { migration: Some(false), ..ctx() });+ assert_eq!(v["kind"], "deploy");+ assert!(v.get("migration").is_none());}#[test]diff --git a/src/server/dev/floor.rs b/src/server/dev/floor.rsindex 2739d2c7..622048a0 100644--- a/src/server/dev/floor.rs+++ b/src/server/dev/floor.rs@@ -227,27 +227,92 @@ pub async fn for_shell(db: &Database, kwant_id: &str, command: &str, cwd: &Path)Some((floor, p))}+/// Whether this card's step may be allowed without a backup when the person says so (22f): only+/// a migration deploy that counts as one because kwant can't tell (`migration: "guess"`). Never a+/// destructive step and never a known migration: those always need a fresh backup.+pub fn may_skip_backup(floor: &Value) -> bool {+ floor["kind"] == "deploy_migration" && floor["migration"] == "guess"+}+/// Why **Allow** is refused on this card now, or `None`: the card carries a `prod_floor` that/// needs a backup, and the space has no `ok` backup at most 10 minutes old. Checked when the/// person answers, not when the card was made, so a backup taken in between counts and one that/// went old doesn't.-pub async fn allow_refusal(db: &Database, details: &Value) -> Option<Value> {- let f = details.get("prod_floor")?;+///+/// `without_backup` is the person's "Allow without a backup": it lets the step through only when+/// [`may_skip_backup`] says so; on any other card it is refused like a plain Allow, with+/// `code: "backup_required"`. Every refusal says `can_allow_without_backup`, so the card (and+/// Telegram's text) can offer that way forward. Only the app's own route passes `true`: it is+/// person-only (`auth::person_only`), and Telegram never does.+pub async fn allow_refusal(db: &Database, details: &Value, without_backup: bool) -> Option<Value> {+ allow_check(db, details, without_backup).await.err()+}++/// [`allow_refusal`] as one check: `Ok(true)` when Allow goes through **because** of+/// `without_backup` (no fresh backup, so it is recorded as such), `Ok(false)` when it goes through+/// anyway, `Err(refusal)` when it is refused.+pub async fn allow_check(db: &Database, details: &Value, without_backup: bool) -> Result<bool, Value> {+ let Some(f) = details.get("prod_floor") else { return Ok(false) };if f["needs_backup"] != true {- return None;+ return Ok(false);}- let space_id = f["space_id"].as_str()?;+ let Some(space_id) = f["space_id"].as_str() else { return Ok(false) };let (_, ok) = db.latest_dev_backups(space_id).await.unwrap_or((None, None));if super::backup::is_fresh(ok.as_ref(), super::now()) {- return None;+ return Ok(false);+ }+ let skippable = may_skip_backup(f);+ if without_backup && skippable {+ return Ok(true);}let backup = super::backup::state_of(db, space_id, false).await;- Some(json!({- "error": "Back up first: this step needs a backup from the last 10 minutes",+ let (code, error) = if without_backup {+ ("backup_required", "This step needs a fresh backup before it runs. It can't be allowed without one.")+ } else {+ ("needs_backup", "Back up first: this step needs a backup from the last 10 minutes")+ };+ Err(json!({+ "error": error,+ "code": code,"backup": backup,+ "can_allow_without_backup": skippable,}))}+/// The audit line on the card's own record: `prod_floor.allowed_without_backup`.+pub const WITHOUT_BACKUP_LINE: &str = "Allowed without a backup by you";++/// Records on the approval itself that the person allowed it without a backup, where every+/// answer is kept (`approvals.parameters`), and in the server log.+pub async fn record_without_backup(db: &Database, ticket_id: &str, details: &Value, via: Option<&str>) {+ let mut d = details.clone();+ d["prod_floor"]["allowed_without_backup"] = json!({+ "by": "person",+ "via": via.unwrap_or("app"),+ "at": super::now(),+ "line": WITHOUT_BACKUP_LINE,+ });+ if let Err(e) = db.update_approval_parameters(ticket_id, &d.to_string()).await {+ tracing::warn!(ticket = %ticket_id, error = %e, "floor: couldn't record Allow without a backup");+ }+ tracing::warn!(+ ticket = %ticket_id,+ space = %details["prod_floor"]["space_id"].as_str().unwrap_or(""),+ kwant = %details["kwant_id"].as_str().unwrap_or(""),+ "floor: {WITHOUT_BACKUP_LINE} (kwant couldn't tell whether the deploy changes the database)"+ );+}++/// The card's `backup` object for a space now, as `payload` builds it: `no_data` follows the+/// space's deploy hint the same way [`ctx_for_kwant`] reads it.+pub async fn backup_state(db: &Database, space_id: &str) -> Value {+ let mode = db.dev_mode(space_id).await.ok().flatten();+ let repos = db.dev_repos(space_id).await.unwrap_or_default();+ let deploy_hint = repos.iter().find_map(|r| r.deploy_hint.clone()).or(mode.and_then(|m| m.deploy_hint));+ let ctx = DevCtx { deploy_hint, ..DevCtx::default() };+ super::backup::state_of(db, space_id, ctx.no_data()).await+}+#[cfg(test)]mod tests {use super::*;@@ -598,24 +663,75 @@ mod tests {let db = Database::init(tmp.path()).await.unwrap();let card = json!({"prod_floor": {"kind": "migration", "needs_backup": true, "space_id": "s1"}});// No backup at all, and then no backup command either- let r = allow_refusal(&db, &card).await.expect("refused with no backup");+ let r = allow_refusal(&db, &card, false).await.expect("refused with no backup");assert!(r["error"].as_str().unwrap().starts_with("Back up first"));assert_eq!(r["backup"]["state"], "no_command");db.put_dev_mode("s1", true, "demo-org/demo-app", "main", None, Some("pg_dump demo > /tmp/demo.sql")).await.unwrap();- assert_eq!(allow_refusal(&db, &card).await.unwrap()["backup"]["state"], "none");+ assert_eq!(allow_refusal(&db, &card, false).await.unwrap()["backup"]["state"], "none");// Only a failed one, and an ok one 11 minutes olddb.insert_dev_backup(&backup("s1", false, 5)).await.unwrap();db.insert_dev_backup(&backup("s1", true, 660)).await.unwrap();- assert!(allow_refusal(&db, &card).await.is_some(), "a failed or old backup doesn't count");+ assert!(allow_refusal(&db, &card, false).await.is_some(), "a failed or old backup doesn't count");// Another space's fresh backup doesn't count eitherdb.insert_dev_backup(&backup("s2", true, 5)).await.unwrap();- assert!(allow_refusal(&db, &card).await.is_some());+ assert!(allow_refusal(&db, &card, false).await.is_some());// A fresh ok one in this space doesdb.insert_dev_backup(&backup("s1", true, 30)).await.unwrap();- assert!(allow_refusal(&db, &card).await.is_none());+ assert!(allow_refusal(&db, &card, false).await.is_none());// A step that needs no backup, or a card that isn't the floor's, is never refused here- assert!(allow_refusal(&db, &json!({"prod_floor": {"needs_backup": false, "space_id": "s3"}})).await.is_none());- assert!(allow_refusal(&db, &json!({"source": "mcp"})).await.is_none());+ assert!(allow_refusal(&db, &json!({"prod_floor": {"needs_backup": false, "space_id": "s3"}}), false).await.is_none());+ assert!(allow_refusal(&db, &json!({"source": "mcp"}), false).await.is_none());+ }++ /// 22f: `without_backup` lets only a guessed migration deploy through; a destructive step or a+ /// known migration still needs a fresh backup, and every refusal says whether the way exists.+ #[tokio::test]+ async fn without_backup_lets_only_a_guessed_migration_through() {+ let tmp = tempfile::tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ let card = |kind: &str, migration: Option<&str>| {+ let mut f = json!({"kind": kind, "needs_backup": true, "space_id": "s1"});+ if let Some(m) = migration {+ f["migration"] = json!(m);+ }+ json!({"prod_floor": f})+ };+ let guess = card("deploy_migration", Some("guess"));+ // Without the flag it is refused like before, and says the way exists+ let r = allow_check(&db, &guess, false).await.unwrap_err();+ assert_eq!((r["code"].as_str(), r["can_allow_without_backup"].as_bool()), (Some("needs_backup"), Some(true)));+ assert_eq!(r["backup"]["state"], "no_command");+ // With it: through, and it counts as allowed without a backup+ assert_eq!(allow_check(&db, &guess, true).await, Ok(true));+ assert!(allow_refusal(&db, &guess, true).await.is_none());+ // Never for a destructive step or a known migration, nor a card from before 22f (no field)+ for c in [card("destructive", None), card("destructive", Some("guess")), card("deploy_migration", Some("yes")), card("deploy_migration", None)] {+ let r = allow_check(&db, &c, true).await.unwrap_err();+ assert_eq!(r["code"], "backup_required", "{c}");+ assert_eq!(r["can_allow_without_backup"], false, "{c}");+ assert!(r["error"].as_str().unwrap().contains("can't be allowed without one"), "{r}");+ assert_eq!(allow_check(&db, &c, false).await.unwrap_err()["code"], "needs_backup");+ }+ // A fresh backup: everything goes through, and nothing counts as skipped+ db.insert_dev_backup(&backup("s1", true, 30)).await.unwrap();+ assert_eq!(allow_check(&db, &guess, true).await, Ok(false));+ assert_eq!(allow_check(&db, &card("destructive", None), true).await, Ok(false));+ }++ #[tokio::test]+ async fn the_backup_state_follows_the_command_and_the_space() {+ let tmp = tempfile::tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ assert_eq!(backup_state(&db, "s1").await["state"], "no_command");+ db.put_dev_mode("s1", true, "demo-org/demo-app", "main", None, Some("pg_dump demo > /tmp/demo.sql")).await.unwrap();+ assert_eq!(backup_state(&db, "s1").await["state"], "none");+ db.insert_dev_backup(&backup("s1", true, 30)).await.unwrap();+ let v = backup_state(&db, "s1").await;+ assert_eq!(v["state"], "fresh");+ assert_eq!(v["path"], "/tmp/demo.sql");+ // A Pages site keeps no data+ db.put_dev_mode("s2", true, "demo-org/demo-site", "main", Some("cloudflare_pages"), None).await.unwrap();+ assert_eq!(backup_state(&db, "s2").await["state"], "no_data");}#[tokio::test]diff --git a/src/server/dev/routes.rs b/src/server/dev/routes.rsindex c6a34f23..760082fa 100644--- a/src/server/dev/routes.rs+++ b/src/server/dev/routes.rs@@ -384,7 +384,7 @@ pub async fn put_mode(State(state): State<AppState>, headers: HeaderMap, Path(idSome(Some(c)) => {let c = c.trim().to_string();if c.chars().count() > BACKUP_COMMAND_CHARS || c.contains('\0') {- return coded(StatusCode::BAD_REQUEST, "backup_too_long", format!("the backup command must be at most {BACKUP_COMMAND_CHARS} characters"));+ return coded(StatusCode::BAD_REQUEST, "backup_too_long", "That command is too long. Keep it to 2,000 characters.");}(!c.is_empty()).then_some(c)}@@ -1358,6 +1358,17 @@ pub async fn release_notes(State(state): State<AppState>, headers: HeaderMap, Pa(StatusCode::ACCEPTED, Json(card_json(&row))).into_response()}+/// `GET /api/spaces/:id/dev/backup`: the space's backup state now, the same object as a floor+/// card's `prod_floor.backup` (22f), so an open card can refresh after the person sets a backup+/// command or takes a backup elsewhere. Person-only, like every Dev mode route.+pub async fn backup_state(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>) -> Response {+ let space = match guard(&state, &headers, &id).await {+ Ok(s) => s,+ Err(r) => return r,+ };+ Json(super::floor::backup_state(&state.db, space.as_str()).await).into_response()+}+pub async fn take_backup(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>) -> Response {let space = match guard(&state, &headers, &id).await {Ok(s) => s,diff --git a/src/server/mod.rs b/src/server/mod.rsindex 47522135..b0c0a5bf 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -331,7 +331,7 @@ pub fn create_router(state: AppState) -> Router {.route("/api/spaces/:id/dev/landed/seen", post(dev::routes::seen)).route("/api/spaces/:id/dev/reviews", get(dev::routes::reviews)).route("/api/spaces/:id/dev/release_notes", post(dev::routes::release_notes))- .route("/api/spaces/:id/dev/backup", post(dev::routes::take_backup))+ .route("/api/spaces/:id/dev/backup", get(dev::routes::backup_state).post(dev::routes::take_backup)).route("/api/spaces/:id/dev/worktrees", get(dev::worktrees::list).post(dev::worktrees::create_route)).route("/api/dev/worktrees/:id", delete(dev::worktrees::remove_route)).route("/api/dev/worktrees/:id/done", post(dev::worktrees::done_route))diff --git a/src/server/routes.rs b/src/server/routes.rsindex a025d95d..d1cfb106 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -5066,6 +5066,10 @@ fn with_held(reply: &mut serde_json::Value, held: Option<serde_json::Value>) {#[derive(Debug, Deserialize)]pub struct ResolveApprovalPayload {pub decision: String, // "allow_once", "always_allow", "deny"+ /// The person's "Allow without a backup" on a production-floor card whose migration is only+ /// kwant's guess (22f). Refused on any other card that needs a backup.+ #[serde(default)]+ pub without_backup: bool,}pub async fn resolve_approval(@@ -5078,7 +5082,7 @@ pub async fn resolve_approval("always_allow" => ApprovalDecision::AlwaysAllowSession,_ => ApprovalDecision::Deny,};- let (status, body) = resolve_approval_inner(&state, &ticket_id, decision, None).await;+ let (status, body) = resolve_approval_inner(&state, &ticket_id, decision, None, payload.without_backup).await;Ok((status, Json(body)).into_response())}@@ -5102,11 +5106,15 @@ pub async fn retry_expired_approval(State(state): State<AppState>, Path(ticket_i/// Answers an approval card: the app's route, and Telegram's Allow once (`via: "telegram"`, which/// is recorded as the card's `answered_via`). Same checks either way: the production floor, and/// only a card still waiting (or one kwant kept over a restart) can be answered.+///+/// `without_backup` is the person's "Allow without a backup" (22f): only the app's route, which is+/// person-only, ever passes `true`; see [`super::dev::floor::allow_check`] for which cards take it.pub(crate) async fn resolve_approval_inner(state: &AppState,ticket_id: &str,decision: ApprovalDecision,via: Option<&str>,+ without_backup: bool,) -> (StatusCode, serde_json::Value) {let status_str = match decision {ApprovalDecision::AllowOnce => "allowed_once",@@ -5116,6 +5124,8 @@ pub(crate) async fn resolve_approval_inner(// The production floor (plan §3.5): Allow on a step that needs a backup is refused here,// not only greyed out on the card, until the space has an ok backup at most 10 minutes old+ // (or the person allows a guessed migration without one, 22f)+ let mut skipped_backup: Option<serde_json::Value> = None;if decision != ApprovalDecision::Deny {let details = state.db@@ -5125,11 +5135,15 @@ pub(crate) async fn resolve_approval_inner(.flatten().and_then(|a| serde_json::from_str::<serde_json::Value>(&a.parameters).ok());if let Some(details) = details {- if let Some(mut refusal) = super::dev::floor::allow_refusal(&state.db, &details).await {- refusal["ticket_id"] = json!(ticket_id);- refusal["resolved"] = json!(false);- refusal["status"] = json!("needs_backup");- return (StatusCode::CONFLICT, refusal);+ match super::dev::floor::allow_check(&state.db, &details, without_backup).await {+ Err(mut refusal) => {+ refusal["ticket_id"] = json!(ticket_id);+ refusal["resolved"] = json!(false);+ refusal["status"] = json!("needs_backup");+ return (StatusCode::CONFLICT, refusal);+ }+ Ok(true) => skipped_backup = Some(details),+ Ok(false) => {}}}}@@ -5148,6 +5162,10 @@ pub(crate) async fn resolve_approval_inner(super::missions::listener::refresh_needs_you(state).await;return match reply {Some(mut reply) => {+ if let Some(details) = &skipped_backup {+ super::dev::floor::record_without_backup(&state.db, ticket_id, details, via).await;+ reply["without_backup"] = json!(true);+ }super::telegram::bridge::approval_answered(state, ticket_id, via).await;reply["ticket_id"] = json!(ticket_id);reply["resolved"] = json!(true);@@ -5169,6 +5187,9 @@ pub(crate) async fn resolve_approval_inner(if let Some(via) = via {let _ = state.db.set_answered_via("approvals", ticket_id, via).await;}+ if let Some(details) = &skipped_backup {+ super::dev::floor::record_without_backup(&state.db, ticket_id, details, via).await;+ }// The card is answered: a task that waited on it is working again (Mission Control)super::missions::listener::refresh_needs_you(state).await;// Telegram edits its copy of the card ("✓ Answered in kwant")@@ -5179,11 +5200,17 @@ pub(crate) async fn resolve_approval_inner((StatusCode::OK,- json!({- "ticket_id": ticket_id,- "resolved": resolved,- "status": status_str- }),+ {+ let mut body = json!({+ "ticket_id": ticket_id,+ "resolved": resolved,+ "status": status_str+ });+ if skipped_backup.is_some() {+ body["without_backup"] = json!(true);+ }+ body+ },)}diff --git a/src/server/telegram/bridge.rs b/src/server/telegram/bridge.rsindex d23690ea..4a423062 100644--- a/src/server/telegram/bridge.rs+++ b/src/server/telegram/bridge.rs@@ -376,15 +376,16 @@ async fn allow_once(state: &AppState, runner: &Runner, link: &TelegramLink, ask:let _ = runner.client.answer_callback(cb_id, Some(copy::ALREADY_ANSWERED)).await;return;}- let (status, body) = crate::server::routes::resolve_approval_inner(state, &ask.ref_id, ApprovalDecision::AllowOnce, Some("telegram")).await;+ let (status, body) = crate::server::routes::resolve_approval_inner(state, &ask.ref_id, ApprovalDecision::AllowOnce, Some("telegram"), false).await;if status.is_success() {let _ = runner.client.answer_callback(cb_id, None).await;edit_answered(state, runner, ask, &format!("{TEAL_CHECK} Allowed once from Telegram · {}", hhmm(state).await)).await;} else if body["status"] == "needs_backup" {let _ = state.db.telegram_reopen_ask(&ask.id).await;let _ = state.db.telegram_ask_link_only(&ask.id).await;- let _ = runner.client.answer_callback(cb_id, Some(copy::NEEDS_BACKUP)).await;- let html = format!("{}\n\n<i>{}</i>", ask.text, text::escape(copy::NEEDS_BACKUP));+ let why = copy::needs_backup(&body);+ let _ = runner.client.answer_callback(cb_id, Some(why)).await;+ let html = format!("{}\n\n<i>{}</i>", ask.text, text::escape(why));edit(state, runner, ask, html, open_markup(state, link, &runner.space, None).await);} else {let _ = runner.client.answer_callback(cb_id, Some(copy::NO_LONGER_WAITING)).await;@@ -874,6 +875,24 @@ mod tests {assert_eq!(excluded_reason(None, true), "Approve it in kwant.");}+ /// 22f: a deploy kwant only guesses changes the database says it can be allowed without a+ /// backup in the app; a destructive step or a known migration doesn't.+ #[test]+ fn a_guessed_migration_says_it_can_go_without_a_backup_in_kwant() {+ let why = |d: Value| super::super::link_only_reason(&d);+ let guess = json!({"source": "mcp", "prod_floor": {"kind": "deploy_migration", "migration": "guess", "needs_backup": true}});+ assert_eq!(+ excluded_reason(why(guess), true),+ "This is a production deploy: it needs a fresh backup, or you can allow it without one. Approve it in kwant."+ );+ for f in [json!({"kind": "deploy_migration", "migration": "yes", "needs_backup": true}), json!({"kind": "destructive", "needs_backup": true})] {+ assert_eq!(excluded_reason(why(json!({"source": "mcp", "prod_floor": f})), true), "This is a production connection. Approve it in kwant.");+ }+ assert_eq!(copy::needs_backup(&json!({"can_allow_without_backup": true})), copy::NEEDS_BACKUP_OR_SKIP);+ assert_eq!(copy::needs_backup(&json!({"can_allow_without_backup": false})), copy::NEEDS_BACKUP);+ assert_eq!(copy::needs_backup(&json!({})), copy::NEEDS_BACKUP);+ }+#[test]fn constant_time_compare() {assert!(constant_eq(b"abc", b"abc"));diff --git a/src/server/telegram/mod.rs b/src/server/telegram/mod.rsindex 2a2b7160..44d072e4 100644--- a/src/server/telegram/mod.rs+++ b/src/server/telegram/mod.rs@@ -90,6 +90,12 @@ pub fn approvable(details: &Value) -> bool {pub fn link_only_reason(details: &Value) -> Option<&'static str> {let set = |k: &str| details.get(k).is_some_and(|v| !v.is_null());if set("prod_floor") {+ // A deploy kwant only guesses changes the database can be allowed without a backup, in+ // the app only (22f)+ let f = &details["prod_floor"];+ if f["needs_backup"] == true && crate::server::dev::floor::may_skip_backup(f) {+ return Some("This is a production deploy: it needs a fresh backup, or you can allow it without one.");+ }return Some("This is a production connection.");}if set("payment_reason") {@@ -214,6 +220,17 @@ pub mod copy {pub const OPEN_IN_KWANT: &str = "Open in kwant";pub const ALLOW_ONCE: &str = "Allow once";pub const NEEDS_BACKUP: &str = "This step needs a fresh backup first. Approve it in kwant.";+ /// A deploy kwant only guesses changes the database (22f): the app can allow it without one.+ pub const NEEDS_BACKUP_OR_SKIP: &str = "This step needs a fresh backup first, or you can allow it without a backup in kwant.";++ /// The refusal text for a `needs_backup` answer from `resolve_approval_inner`.+ pub fn needs_backup(refusal: &serde_json::Value) -> &'static str {+ if refusal["can_allow_without_backup"] == true {+ NEEDS_BACKUP_OR_SKIP+ } else {+ NEEDS_BACKUP+ }+ }pub const NOT_SENT: &str = "kwant couldn't take that message. Try again, or open kwant.";pub const SIGN_INS_IN_KWANT: &str = "Sign-ins happen in kwant, never here.";/// The spending stop held a turn while the person writes from Telegram: their message isdiff --git a/tests/dev_floor_test.rs b/tests/dev_floor_test.rsindex 1e0c8485..a2f3bebb 100644--- a/tests/dev_floor_test.rs+++ b/tests/dev_floor_test.rs@@ -43,11 +43,17 @@ fn request(env: &Env, command: &str) -> ToolApprovalRequest {}}+/// The card stores the command JSON-escaped, so look for it the way it is stored.+fn stored(command: &str) -> String {+ let s = serde_json::to_string(command).unwrap();+ s[1..s.len() - 1].to_string()+}+/// Runs one call nobody answers and returns its waiting card.async fn unanswered(env: &Env, command: &str) -> (String, Value) {assert_eq!(approver(env).decide(request(env, command)).await, ApprovalOutcome::Unanswered);let rows = env.state.db.list_approvals(&kwnt::db::spaces::SpaceId::default_space(), Some("waiting"), Some(&env.a)).await.unwrap();- let row = rows.into_iter().find(|r| r.parameters.contains(command)).expect("a waiting card");+ let row = rows.into_iter().find(|r| r.parameters.contains(&stored(command))).expect("a waiting card");let details: Value = serde_json::from_str(&row.parameters).unwrap();(row.id, details)}@@ -188,9 +194,112 @@ async fn the_floor_still_asks_with_approvals_off_in_a_kwant_started_turn() {for command in ["git push origin main", "sqlite3 demo.db 'DROP TABLE demo_auto'"] {assert_eq!(started.decide(request(&env, command)).await, ApprovalOutcome::Unanswered, "{command}");let rows = env.state.db.list_approvals(&kwnt::db::spaces::SpaceId::default_space(), Some("waiting"), Some(&env.a)).await.unwrap();- let row = rows.into_iter().find(|r| r.parameters.contains(command)).expect("a waiting card");+ let row = rows.into_iter().find(|r| r.parameters.contains(&stored(command))).expect("a waiting card");let details: Value = serde_json::from_str(&row.parameters).unwrap();assert!(details["prod_floor"].is_object(), "{command}: {details}");assert_eq!(details["started_by"], "Loose ends");}}++/// A bot's own API token for a turn of A (what a bot's `curl` to kwant would carry).+async fn bot_token(env: &Env) -> String {+ use kwnt::server::continuity::{SelfScope, TurnOrigin};+ use kwnt::server::mcp_runtime;+ let bot = env.state.db.get_kwant(&env.a).await.unwrap().unwrap();+ let scope = SelfScope {+ kwant_id: bot.id.clone(),+ kwant_name: bot.name.clone(),+ origin: Some(TurnOrigin { direct_kwant_id: Some(bot.id.clone()), ..Default::default() }),+ cancel: Some(tokio_util::sync::CancellationToken::new()),+ turn_id: Some("turn-floor-bot".into()),+ sandbox_target: Some(bot.id.clone()),+ ..Default::default()+ };+ mcp_runtime::prepare_turn_with_self(&env.state, &bot, Some("turn-floor-bot".into()), None, Some(scope)).await.unwrap().1+}++/// 22f (Oleks, Nov 15): a deploy kwant only guesses changes the database is never a dead end. With+/// no backup command, the person can allow it without a backup (recorded on the card); a bot+/// can't; and a destructive step or a known migration still can't go without a fresh backup, even+/// through a hand-made API call.+#[tokio::test]+async fn a_guessed_migration_can_be_allowed_without_a_backup_by_the_person_only() {+ let env = setup().await;+ let space = space_of_a(&env).await;+ env.state.db.put_dev_mode(&space, true, "demo-org/demo-app", "main", None, None).await.unwrap();+ let resolve = |t: &str| format!("/api/approvals/{t}/resolve");++ // The deploy: a guess, with no backup command+ let (ticket, details) = unanswered(&env, "ssh [email protected] 'cd /srv/app && docker compose up -d'").await;+ let floor = &details["prod_floor"];+ assert_eq!(floor["kind"], "deploy_migration", "{details}");+ assert_eq!(floor["migration"], "guess");+ assert_eq!(floor["backup"]["state"], "no_command");++ // A plain Allow is refused, and says the way forward exists+ let (s, v) = call(&env.app, "POST", &resolve(&ticket), Some(json!({"decision": "allow_once"}))).await;+ assert_eq!(s.as_u16(), 409, "{v}");+ assert_eq!((v["status"].as_str(), v["code"].as_str()), (Some("needs_backup"), Some("needs_backup")));+ assert_eq!(v["can_allow_without_backup"], true);++ // A bot can't send it: the route is the person's+ let token = bot_token(&env).await;+ let auth = format!("Bearer {token}");+ let (s, v) = call_with(&env.app, "POST", &resolve(&ticket), Some(json!({"decision": "allow_once", "without_backup": true})), &[("authorization", auth.as_str())]).await;+ assert_eq!(s.as_u16(), 403, "{v}");+ assert_eq!(env.state.db.get_approval(&ticket).await.unwrap().unwrap().status, "waiting");++ // The backup state reads the same as the card's, for the person only+ let backup_uri = format!("/api/spaces/{space}/dev/backup");+ let (s, v) = call(&env.app, "GET", &backup_uri, None).await;+ assert_eq!(s.as_u16(), 200, "{v}");+ assert_eq!(v, floor["backup"]);+ let (s, _) = call_with(&env.app, "GET", &backup_uri, None, &[("authorization", auth.as_str())]).await;+ assert_eq!(s.as_u16(), 403);+ // Setting a command (the same PUT as Dev mode settings) moves it on+ let (s, v) = call(&env.app, "PUT", &format!("/api/spaces/{space}/dev_mode"), Some(json!({"backup_command": "pg_dump demo > /tmp/demo.sql"}))).await;+ assert_eq!(s.as_u16(), 200, "{v}");+ assert_eq!(call(&env.app, "GET", &backup_uri, None).await.1["state"], "none");++ // The person's Allow without a backup goes through, and is recorded on the card+ let (s, v) = call(&env.app, "POST", &resolve(&ticket), Some(json!({"decision": "allow_once", "without_backup": true}))).await;+ assert_eq!(s.as_u16(), 200, "{v}");+ assert_eq!(v["without_backup"], true);+ let row = env.state.db.get_approval(&ticket).await.unwrap().unwrap();+ assert_eq!(row.status, "allowed_once");+ let saved: Value = serde_json::from_str(&row.parameters).unwrap();+ let rec = &saved["prod_floor"]["allowed_without_backup"];+ assert_eq!(rec["line"], "Allowed without a backup by you", "{saved}");+ assert_eq!((rec["by"].as_str(), rec["via"].as_str()), (Some("person"), Some("app")));+ assert!(rec["at"].is_string());+ wait_for("the resumed turn to end", || async { env.state.turns.active_turns().is_empty() }).await;++ // A destructive step and a known migration: a hand-made call with without_backup is refused+ for cmd in ["ssh [email protected] 'rm -rf /srv/app/data'", "RAILS_ENV=production bin/rails db:migrate"] {+ let (ticket, details) = unanswered(&env, cmd).await;+ assert_eq!(details["prod_floor"]["needs_backup"], true, "{details}");+ assert_ne!(details["prod_floor"]["migration"], "guess", "{details}");+ for decision in ["allow_once", "always_allow"] {+ let (s, v) = call(&env.app, "POST", &resolve(&ticket), Some(json!({"decision": decision, "without_backup": true}))).await;+ assert_eq!(s.as_u16(), 409, "{cmd}: {v}");+ assert_eq!((v["status"].as_str(), v["code"].as_str()), (Some("needs_backup"), Some("backup_required")), "{cmd}");+ assert_eq!(v["can_allow_without_backup"], false);+ }+ let row = env.state.db.get_approval(&ticket).await.unwrap().unwrap();+ assert_eq!(row.status, "waiting", "{cmd}");+ assert!(!row.parameters.contains("allowed_without_backup"));+ }+}++/// 22f: Oleks's own deploy, verbatim: the card names the server `$R` stands for.+#[tokio::test]+async fn where_names_the_server_of_olekss_deploy() {+ let env = setup().await;+ let space = space_of_a(&env).await;+ env.state.db.put_dev_mode(&space, true, "demo-org/demo-app", "main", None, None).await.unwrap();+ let cmd = r#"set -e; [email protected]; D=/opt/tradebot; timeout 120 ssh -o BatchMode=yes -o ConnectTimeout=15 $R "cd $D && chmod +x catalyst-linux.new && docker compose up -d --no-deps --force-recreate catalyst 2>&1 && docker compose ps catalyst"; echo "exit=$?""#;+ let (_, details) = unanswered(&env, cmd).await;+ let blast = details["prod_floor"]["blast"].as_array().unwrap().clone();+ assert!(blast.contains(&json!(["Where", "[email protected]"])), "{blast:?}");+ assert_eq!(details["prod_floor"]["migration"], "guess");+}diff --git a/tests/dev_seams_test.rs b/tests/dev_seams_test.rsindex 3b0175c7..6e681ff9 100644--- a/tests/dev_seams_test.rs+++ b/tests/dev_seams_test.rs@@ -31,16 +31,16 @@ async fn the_clock_seam_ages_a_backup_past_ten_minutes() {}).await.unwrap();- assert_eq!(floor::allow_refusal(&db, &card).await, None, "a backup taken just now is fresh");+ assert_eq!(floor::allow_refusal(&db, &card, false).await, None, "a backup taken just now is fresh");dev::set_clock_skew(9 * 60);- assert_eq!(floor::allow_refusal(&db, &card).await, None, "9 minutes on, still fresh");+ assert_eq!(floor::allow_refusal(&db, &card, false).await, None, "9 minutes on, still fresh");dev::set_clock_skew(11 * 60);assert!((dev::now() - Utc::now() - Duration::minutes(11)).num_seconds().abs() <= 1);- let refusal = floor::allow_refusal(&db, &card).await.expect("11 minutes on, Allow is refused");+ let refusal = floor::allow_refusal(&db, &card, false).await.expect("11 minutes on, Allow is refused");assert_eq!(refusal["backup"]["state"], "old", "{refusal}");dev::set_clock_skew(0);- assert_eq!(floor::allow_refusal(&db, &card).await, None);+ assert_eq!(floor::allow_refusal(&db, &card, false).await, None);}#[tokio::test]