From 33a4351716c6d22f000e540840a6c14dc60c812a Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 3 Oct 2026 14:08:34 +0000 Subject: [PATCH 1/5] Add eight school catalog challenges with extra win predicates. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Extend server-authoritative challenge wins with pH, temperature, aqueous ions, filter-paper solids, HCl mass fraction, and acid-into-water dilution order so labs 3–7, 9, 10, and 12 can be judged without teaching banners. Co-authored-by: Arnoud --- apps/web/src/components/labBenchTestFetch.ts | 7 +- .../src/components/labBenchTestFixtures.ts | 81 ++++ apps/web/src/generated/ItemProperties.ts | 7 +- apps/web/src/lib/challenges.ts | 52 ++ crates/chemlab-contracts/src/convert.rs | 2 + crates/chemlab-contracts/src/lib.rs | 16 + crates/chemlab-core/src/challenges.rs | 450 +++++++++++++++++- crates/chemlab-core/src/scene.rs | 25 + .../src/scene_tests/challenges.rs | 332 ++++++++++++- .../src/routes/routes_tests/challenges.rs | 58 +++ docs/challenges.md | 149 +++++- 11 files changed, 1160 insertions(+), 19 deletions(-) diff --git a/apps/web/src/components/labBenchTestFetch.ts b/apps/web/src/components/labBenchTestFetch.ts index 8582942..3092d7e 100644 --- a/apps/web/src/components/labBenchTestFetch.ts +++ b/apps/web/src/components/labBenchTestFetch.ts @@ -4,11 +4,10 @@ import type { LabAction, LabScene } from '../generated/contracts' import { optionalArray } from '../lib/scene' import { FREE_MODE } from '../lib/challenges' import { - CREATE_TABLE_SALT_LAYOUT, - SEPARATE_NACL_SIO2_LAYOUT, challengeStartScene, cloneScene, initialScene, + layoutForMode, withFilledMainBeaker, } from './labBenchTestFixtures' import { @@ -34,8 +33,8 @@ import { /** Mirror of the server's mode-aware reset: back to the start scene of the current mode. */ function startSceneForMode(mode: string): LabScene { if (mode === FREE_MODE) return initialScene() - if (mode === CREATE_TABLE_SALT_LAYOUT.mode) return challengeStartScene(CREATE_TABLE_SALT_LAYOUT) - if (mode === SEPARATE_NACL_SIO2_LAYOUT.mode) return challengeStartScene(SEPARATE_NACL_SIO2_LAYOUT) + const layout = layoutForMode(mode) + if (layout) return challengeStartScene(layout) // Unknown mode: fall back to Free (safer than inventing a challenge layout). return initialScene() } diff --git a/apps/web/src/components/labBenchTestFixtures.ts b/apps/web/src/components/labBenchTestFixtures.ts index 93c67c7..dd4732f 100644 --- a/apps/web/src/components/labBenchTestFixtures.ts +++ b/apps/web/src/components/labBenchTestFixtures.ts @@ -445,6 +445,87 @@ export const CREATE_TABLE_SALT_LAYOUT: ChallengeStartLayout = { distilledWaterMl: null, } +export const CREATE_SODIUM_SULFATE_LAYOUT: ChallengeStartLayout = { + mode: 'create-sodium-sulfate', + allowedStockItemIds: ['beaker-h2o', 'beaker-h2so4', 'beaker-naoh', 'beaker-na2so4'], + emptyStockItemIds: ['beaker-na2so4'], + mainBeakerSolids: [], + distilledWaterMl: null, +} + +export const PRECIPITATE_GYPSUM_LAYOUT: ChallengeStartLayout = { + mode: 'precipitate-gypsum', + allowedStockItemIds: ['beaker-h2o', 'beaker-cacl2', 'beaker-na2so4', 'beaker-h2so4'], + emptyStockItemIds: [], + mainBeakerSolids: [], + distilledWaterMl: null, +} + +export const MAKE_HCL_FROM_GYPSUM_LAYOUT: ChallengeStartLayout = { + mode: 'make-hcl-from-gypsum', + allowedStockItemIds: ['beaker-h2o', 'beaker-cacl2', 'beaker-h2so4'], + emptyStockItemIds: [], + mainBeakerSolids: [], + distilledWaterMl: null, +} + +export const HOT_PACK_CACL2_LAYOUT: ChallengeStartLayout = { + mode: 'hot-pack-cacl2', + allowedStockItemIds: ['beaker-h2o', 'beaker-cacl2'], + emptyStockItemIds: [], + mainBeakerSolids: [], + distilledWaterMl: 10, +} + +export const COMMON_ION_NACL_LAYOUT: ChallengeStartLayout = { + mode: 'common-ion-nacl', + allowedStockItemIds: ['beaker-h2o', 'beaker-hcl', 'beaker-nacl'], + emptyStockItemIds: [], + mainBeakerSolids: [], + distilledWaterMl: 5, +} + +export const NEUTRALIZE_TO_PH7_LAYOUT: ChallengeStartLayout = { + mode: 'neutralize-to-ph7', + allowedStockItemIds: ['beaker-h2o', 'beaker-hcl', 'beaker-naoh'], + emptyStockItemIds: [], + mainBeakerSolids: [], + distilledWaterMl: null, +} + +export const DILUTE_SULFURIC_SAFE_LAYOUT: ChallengeStartLayout = { + mode: 'dilute-sulfuric-safe', + allowedStockItemIds: ['beaker-h2o', 'beaker-h2so4'], + emptyStockItemIds: [], + mainBeakerSolids: [], + distilledWaterMl: null, +} + +export const CONCENTRATE_HCL_AZEOTROPE_LAYOUT: ChallengeStartLayout = { + mode: 'concentrate-hcl-azeotrope', + allowedStockItemIds: ['beaker-h2o', 'beaker-hcl'], + emptyStockItemIds: [], + mainBeakerSolids: [], + distilledWaterMl: null, +} + +const CHALLENGE_START_LAYOUTS: ChallengeStartLayout[] = [ + SEPARATE_NACL_SIO2_LAYOUT, + CREATE_TABLE_SALT_LAYOUT, + CREATE_SODIUM_SULFATE_LAYOUT, + PRECIPITATE_GYPSUM_LAYOUT, + MAKE_HCL_FROM_GYPSUM_LAYOUT, + HOT_PACK_CACL2_LAYOUT, + COMMON_ION_NACL_LAYOUT, + NEUTRALIZE_TO_PH7_LAYOUT, + DILUTE_SULFURIC_SAFE_LAYOUT, + CONCENTRATE_HCL_AZEOTROPE_LAYOUT, +] + +export function layoutForMode(mode: string): ChallengeStartLayout | null { + return CHALLENGE_START_LAYOUTS.find((layout) => layout.mode === mode) ?? null +} + /** @deprecated Prefer `challengeStartScene(SEPARATE_NACL_SIO2_LAYOUT)` or a snapshot. */ export function challengeScene(): LabScene { return challengeStartScene(SEPARATE_NACL_SIO2_LAYOUT) diff --git a/apps/web/src/generated/ItemProperties.ts b/apps/web/src/generated/ItemProperties.ts index c118d06..ea61c19 100644 --- a/apps/web/src/generated/ItemProperties.ts +++ b/apps/web/src/generated/ItemProperties.ts @@ -21,4 +21,9 @@ on?: boolean | null, * Last vessel a pipette drew from, the vessel tongs currently hold, or the * dish a spoon scoop came from. */ -source_item_id?: string | null, }; +source_item_id?: string | null, +/** + * Dilution order for concentrated H₂SO₄: `true` acid-into-water, `false` + * water-onto-acid. Omitted when unset. Server-authored; used by challenge wins. + */ +h2so4_dilution_into_water?: boolean | null, }; diff --git a/apps/web/src/lib/challenges.ts b/apps/web/src/lib/challenges.ts index 9f783a0..50065ba 100644 --- a/apps/web/src/lib/challenges.ts +++ b/apps/web/src/lib/challenges.ts @@ -27,6 +27,58 @@ export const CHALLENGES: Challenge[] = [ prompt: "We're out of NaCl again, can you create some for us?", done: 'Thank you again.', }, + { + id: 'create-sodium-sulfate', + title: 'Create sodium sulfate', + prompt: "We're out of sodium sulfate, can you make some from sulfuric acid and sodium hydroxide?", + done: 'Thank you.', + }, + { + id: 'precipitate-gypsum', + title: 'Precipitate gypsum', + prompt: 'We need gypsum. Mix calcium chloride with a sulfate and filter off the solid.', + done: 'Thank you.', + }, + { + id: 'make-hcl-from-gypsum', + title: 'Make hydrochloric acid', + prompt: + 'Make hydrochloric acid by mixing calcium chloride with sulfuric acid, then filter off the gypsum.', + done: 'Thank you.', + }, + { + id: 'hot-pack-cacl2', + title: 'Hot pack', + prompt: + 'Dissolve the calcium chloride in a little distilled water and check that the beaker warms up.', + done: 'Thank you.', + }, + { + id: 'common-ion-nacl', + title: 'Crash salt with acid', + prompt: 'Make a salty solution, then add hydrochloric acid until extra salt crashes out.', + done: 'Thank you.', + }, + { + id: 'neutralize-to-ph7', + title: 'Neutralise to pH 7', + prompt: 'Neutralise sodium hydroxide with hydrochloric acid until the inspect pH is about 7.', + done: 'Thank you.', + }, + { + id: 'dilute-sulfuric-safe', + title: 'Dilute sulfuric acid safely', + prompt: + 'Dilute the concentrated sulfuric acid the safe way: add the acid into water, not water onto the acid.', + done: 'Thank you.', + }, + { + id: 'concentrate-hcl-azeotrope', + title: 'Concentrate hydrochloric acid', + prompt: + 'Heat hydrochloric acid in the dish and stop near the azeotrope — you cannot boil it to pure HCl.', + done: 'Thank you.', + }, ] /** Picker options: Free mode first (the default), then the catalog. */ diff --git a/crates/chemlab-contracts/src/convert.rs b/crates/chemlab-contracts/src/convert.rs index c44025f..880396c 100644 --- a/crates/chemlab-contracts/src/convert.rs +++ b/crates/chemlab-contracts/src/convert.rs @@ -45,6 +45,7 @@ impl From for ItemProperties { holding: props.holding.into_iter().map(Into::into).collect(), on: props.on, source_item_id: props.source_item_id, + h2so4_dilution_into_water: props.h2so4_dilution_into_water, } } } @@ -61,6 +62,7 @@ impl From for chemlab_core::ItemProperties { holding: props.holding.into_iter().map(Into::into).collect(), on: props.on, source_item_id: props.source_item_id, + h2so4_dilution_into_water: props.h2so4_dilution_into_water, } } } diff --git a/crates/chemlab-contracts/src/lib.rs b/crates/chemlab-contracts/src/lib.rs index fdaa4b7..f3ea299 100644 --- a/crates/chemlab-contracts/src/lib.rs +++ b/crates/chemlab-contracts/src/lib.rs @@ -144,6 +144,10 @@ pub struct ItemProperties { /// dish a spoon scoop came from. #[serde(default, skip_serializing_if = "Option::is_none")] pub source_item_id: Option, + /// Dilution order for concentrated H₂SO₄: `true` acid-into-water, `false` + /// water-onto-acid. Omitted when unset. Server-authored; used by challenge wins. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub h2so4_dilution_into_water: Option, } /// A single item in the lab scene (beaker, spoon, …). @@ -442,6 +446,7 @@ mod tests { }], on: None, source_item_id: None, + h2so4_dilution_into_water: None, }, }; let scene = LabScene { @@ -481,6 +486,7 @@ mod tests { holding: vec![], on: None, source_item_id: None, + h2so4_dilution_into_water: None, }; let json = serde_json::to_string(&props).unwrap(); assert!(!json.contains("composition")); @@ -488,6 +494,7 @@ mod tests { assert!(!json.contains("fill_ml")); assert!(!json.contains("on")); assert!(!json.contains("source_item_id")); + assert!(!json.contains("h2so4_dilution_into_water")); let back: ItemProperties = serde_json::from_str(&json).unwrap(); assert_eq!(props, back); } @@ -532,6 +539,7 @@ mod tests { }], on: None, source_item_id: Some("beaker-water".into()), + h2so4_dilution_into_water: None, }, }; let dish = Item { @@ -549,6 +557,7 @@ mod tests { holding: vec![], on: None, source_item_id: None, + h2so4_dilution_into_water: None, }, }; let burner = Item { @@ -566,6 +575,7 @@ mod tests { holding: vec![], on: Some(false), source_item_id: None, + h2so4_dilution_into_water: None, }, }; let scene = LabScene { @@ -619,6 +629,7 @@ mod tests { holding: vec![], on: None, source_item_id: None, + h2so4_dilution_into_water: None, }, }; let json = serde_json::to_string(&item).unwrap(); @@ -651,6 +662,7 @@ mod tests { holding: vec![], on: None, source_item_id: Some("beaker-water".into()), + h2so4_dilution_into_water: None, }, }; let water = Item { @@ -675,6 +687,7 @@ mod tests { holding: vec![], on: None, source_item_id: None, + h2so4_dilution_into_water: None, }, }; let json = serde_json::to_string(&tongs).unwrap(); @@ -722,6 +735,7 @@ mod tests { ], on: None, source_item_id: Some("dish-1".into()), + h2so4_dilution_into_water: None, }, }; let json = serde_json::to_string(&spoon).unwrap(); @@ -751,6 +765,7 @@ mod tests { holding: vec![], on: None, source_item_id: None, + h2so4_dilution_into_water: None, }, }; let json = serde_json::to_string(&item).unwrap(); @@ -787,6 +802,7 @@ mod tests { holding: vec![], on: None, source_item_id: None, + h2so4_dilution_into_water: None, }, }; let json = serde_json::to_string(&item).unwrap(); diff --git a/crates/chemlab-core/src/challenges.rs b/crates/chemlab-core/src/challenges.rs index 47a8258..32291e5 100644 --- a/crates/chemlab-core/src/challenges.rs +++ b/crates/chemlab-core/src/challenges.rs @@ -5,7 +5,14 @@ //! empty, what the main beaker is preloaded with, and when it is won), so a new //! challenge is one more [`Challenge`] entry plus a section in the doc. -use crate::scene::{solid_amount_g, Scene}; +use crate::composition::aqueous_mol; +use crate::h2so4::liquid_h2so4_ml; +use crate::hcl::{ph_of_item, HclInventory}; +use crate::scene::{ + solid_amount_g, Scene, SceneItem, AMBIENT_TEMPERATURE_C, CACL2_MOLAR_MASS_G_PER_MOL, + CASO4_MOLAR_MASS_G_PER_MOL, NA2SO4_MOLAR_MASS_G_PER_MOL, NACL_MOLAR_MASS_G_PER_MOL, + NAOH_MOLAR_MASS_G_PER_MOL, +}; /// Mode id of the default bench. Never "completed". pub const FREE_MODE: &str = "free"; @@ -16,6 +23,9 @@ pub const FREE_MODE: &str = "free"; /// float compare would make a finished challenge unwinnable. pub const CHALLENGE_MASS_TOLERANCE_G: f64 = 1e-6; +/// Aqueous "present" floor for win checks (mol). +const AQ_PRESENT_MOL: f64 = 1e-6; + /// How a [`StockTarget`] mass is compared against the stock's solid grams. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum WinCompare { @@ -25,7 +35,7 @@ pub enum WinCompare { AtLeast, } -/// One "this stock holds about this much of this species" clause of a win condition. +/// One "this vessel holds about this much of this solid species" clause. #[derive(Debug, Clone, Copy, PartialEq)] pub struct StockTarget { pub item_id: &'static str, @@ -34,6 +44,53 @@ pub struct StockTarget { pub compare: WinCompare, } +/// Extra win predicates (pH, T, aqueous ions, leftover solid/liquid, HCl w/w). +/// +/// Solid mass still uses [`StockTarget`] (any vessel, including filter paper). +/// `item_ids` clauses hold when **any** listed vessel satisfies the predicate. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum WinCheck { + Ph { + item_ids: &'static [&'static str], + min: f64, + max: f64, + }, + TemperatureAtLeast { + item_id: &'static str, + min_c: f64, + }, + AqueousAtLeast { + item_ids: &'static [&'static str], + substance_id: &'static str, + amount_mol: f64, + }, + SolidAtMost { + item_id: &'static str, + substance_id: &'static str, + amount_g: f64, + }, + /// Any listed vessel holds at least this much solid. + SolidAtLeast { + item_ids: &'static [&'static str], + substance_id: &'static str, + amount_g: f64, + }, + LiquidAtMost { + item_id: &'static str, + substance_id: &'static str, + amount_ml: f64, + }, + HclWw { + item_ids: &'static [&'static str], + min: f64, + max: f64, + }, + /// Vessel received liquid H₂SO₄ into water, and never water-onto-acid. + AcidAddedIntoWater { + item_id: &'static str, + }, +} + /// A challenge as both product copy and engine rules. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Challenge { @@ -52,8 +109,10 @@ pub struct Challenge { pub main_beaker_solids: &'static [(&'static str, f64)], /// Starting liquid ml in `beaker-h2o`. `None` keeps Free mode's full stock. pub distilled_water_ml: Option, - /// All clauses must hold for the challenge to be complete. + /// Solid-mass clauses (stocks, filter paper, main beaker, …). pub win: &'static [StockTarget], + /// Non-mass clauses; all must hold together with [`Challenge::win`]. + pub checks: &'static [WinCheck], } /// Separate a mixed 2 g NaCl / 2 g SiO₂ solid back into its stock beakers. @@ -80,6 +139,7 @@ pub const SEPARATE_NACL_SIO2: Challenge = Challenge { compare: WinCompare::Exact, }, ], + checks: &[], }; /// Neutralize HCl with NaOH, evaporate, and return solid NaCl to its empty stock. @@ -98,10 +158,257 @@ pub const CREATE_TABLE_SALT: Challenge = Challenge { amount_g: 0.20, compare: WinCompare::AtLeast, }], + checks: &[], +}; + +/// Neutralize H₂SO₄ with NaOH, evaporate, return solid Na₂SO₄ to its empty stock. +pub const CREATE_SODIUM_SULFATE: Challenge = Challenge { + id: "create-sodium-sulfate", + title: "Create sodium sulfate", + prompt: + "We're out of sodium sulfate, can you make some from sulfuric acid and sodium hydroxide?", + done: "Thank you.", + allowed_stock_item_ids: &["beaker-h2o", "beaker-h2so4", "beaker-naoh", "beaker-na2so4"], + empty_stock_item_ids: &["beaker-na2so4"], + main_beaker_solids: &[], + distilled_water_ml: None, + win: &[], + checks: &[WinCheck::SolidAtLeast { + item_ids: &["beaker-na2so4", "dish-1"], + substance_id: "na2so4", + amount_g: 0.20, + }], +}; + +/// Mix CaCl₂ with a sulfate source and filter off gypsum. +pub const PRECIPITATE_GYPSUM: Challenge = Challenge { + id: "precipitate-gypsum", + title: "Precipitate gypsum", + prompt: "We need gypsum. Mix calcium chloride with a sulfate and filter off the solid.", + done: "Thank you.", + allowed_stock_item_ids: &[ + "beaker-h2o", + "beaker-cacl2", + "beaker-na2so4", + "beaker-h2so4", + ], + empty_stock_item_ids: &[], + main_beaker_solids: &[], + distilled_water_ml: None, + win: &[StockTarget { + item_id: "filter-paper-1", + substance_id: "caso4", + amount_g: 0.15, + compare: WinCompare::AtLeast, + }], + checks: &[], +}; + +/// CaCl₂ + H₂SO₄ → gypsum + aqueous HCl; filter. +pub const MAKE_HCL_FROM_GYPSUM: Challenge = Challenge { + id: "make-hcl-from-gypsum", + title: "Make hydrochloric acid", + prompt: "Make hydrochloric acid by mixing calcium chloride with sulfuric acid, then filter off the gypsum.", + done: "Thank you.", + allowed_stock_item_ids: &["beaker-h2o", "beaker-cacl2", "beaker-h2so4"], + empty_stock_item_ids: &[], + main_beaker_solids: &[], + distilled_water_ml: None, + win: &[StockTarget { + item_id: "filter-paper-1", + substance_id: "caso4", + amount_g: 0.15, + compare: WinCompare::AtLeast, + }], + checks: &[ + WinCheck::Ph { + item_ids: &["beaker-filtrate", "dish-1"], + min: f64::NEG_INFINITY, + max: 3.0, + }, + WinCheck::AqueousAtLeast { + item_ids: &["beaker-filtrate", "dish-1"], + substance_id: "h+", + amount_mol: AQ_PRESENT_MOL, + }, + WinCheck::AqueousAtLeast { + item_ids: &["beaker-filtrate", "dish-1"], + substance_id: "cl-", + amount_mol: AQ_PRESENT_MOL, + }, + ], +}; + +/// Dissolve CaCl₂ and inspect the exothermic temperature rise. +/// +/// Vessel heat capacity caps the rise well below a calorimeter 30 °C, so the +/// judged bar is ≥ 25 °C after dissolving the 2 g stock into a small water volume. +pub const HOT_PACK_CACL2: Challenge = Challenge { + id: "hot-pack-cacl2", + title: "Hot pack", + prompt: "Dissolve the calcium chloride in a little distilled water and check that the beaker warms up.", + done: "Thank you.", + allowed_stock_item_ids: &["beaker-h2o", "beaker-cacl2"], + empty_stock_item_ids: &[], + main_beaker_solids: &[], + distilled_water_ml: Some(10.0), + win: &[], + checks: &[ + WinCheck::TemperatureAtLeast { + item_id: "beaker-water", + min_c: 25.0, + }, + WinCheck::AqueousAtLeast { + item_ids: &["beaker-water"], + substance_id: "ca2+", + amount_mol: AQ_PRESENT_MOL, + }, + WinCheck::AqueousAtLeast { + item_ids: &["beaker-water"], + substance_id: "cl-", + amount_mol: AQ_PRESENT_MOL, + }, + WinCheck::SolidAtMost { + item_id: "beaker-water", + substance_id: "cacl2", + amount_g: 1e-4, + }, + ], +}; + +/// Near-saturated NaCl, then 30% HCl until extra solid salt appears. +pub const COMMON_ION_NACL: Challenge = Challenge { + id: "common-ion-nacl", + title: "Crash salt with acid", + prompt: "Make a salty solution, then add hydrochloric acid until extra salt crashes out.", + done: "Thank you.", + allowed_stock_item_ids: &["beaker-h2o", "beaker-hcl", "beaker-nacl"], + empty_stock_item_ids: &[], + main_beaker_solids: &[], + distilled_water_ml: Some(5.0), + win: &[StockTarget { + item_id: "beaker-water", + substance_id: "nacl", + amount_g: 0.05, + compare: WinCompare::AtLeast, + }], + checks: &[ + WinCheck::AqueousAtLeast { + item_ids: &["beaker-water"], + substance_id: "h+", + amount_mol: AQ_PRESENT_MOL, + }, + WinCheck::AqueousAtLeast { + item_ids: &["beaker-water"], + substance_id: "na+", + amount_mol: 1e-4, + }, + ], +}; + +/// NaOH + HCl to inspect pH near 7, without evaporating. +pub const NEUTRALIZE_TO_PH7: Challenge = Challenge { + id: "neutralize-to-ph7", + title: "Neutralise to pH 7", + prompt: "Neutralise sodium hydroxide with hydrochloric acid until the inspect pH is about 7.", + done: "Thank you.", + allowed_stock_item_ids: &["beaker-h2o", "beaker-hcl", "beaker-naoh"], + empty_stock_item_ids: &[], + main_beaker_solids: &[], + distilled_water_ml: None, + win: &[], + checks: &[ + WinCheck::Ph { + item_ids: &["beaker-water"], + min: 6.5, + max: 7.5, + }, + WinCheck::AqueousAtLeast { + item_ids: &["beaker-water"], + substance_id: "na+", + amount_mol: AQ_PRESENT_MOL, + }, + WinCheck::AqueousAtLeast { + item_ids: &["beaker-water"], + substance_id: "cl-", + amount_mol: AQ_PRESENT_MOL, + }, + WinCheck::SolidAtMost { + item_id: "beaker-water", + substance_id: "naoh", + amount_g: 1e-4, + }, + ], +}; + +/// Add concentrated H₂SO₄ into water (never the reverse). +pub const DILUTE_SULFURIC_SAFE: Challenge = Challenge { + id: "dilute-sulfuric-safe", + title: "Dilute sulfuric acid safely", + prompt: "Dilute the concentrated sulfuric acid the safe way: add the acid into water, not water onto the acid.", + done: "Thank you.", + allowed_stock_item_ids: &["beaker-h2o", "beaker-h2so4"], + empty_stock_item_ids: &[], + main_beaker_solids: &[], + distilled_water_ml: None, + win: &[], + checks: &[ + WinCheck::AcidAddedIntoWater { + item_id: "beaker-water", + }, + WinCheck::LiquidAtMost { + item_id: "beaker-water", + substance_id: "h2so4", + amount_ml: 1e-6, + }, + WinCheck::AqueousAtLeast { + item_ids: &["beaker-water"], + substance_id: "h+", + amount_mol: AQ_PRESENT_MOL, + }, + WinCheck::TemperatureAtLeast { + item_id: "beaker-water", + min_c: AMBIENT_TEMPERATURE_C + 0.5, + }, + WinCheck::Ph { + item_ids: &["beaker-water"], + min: f64::NEG_INFINITY, + max: 2.0, + }, + ], +}; + +/// Boil dish HCl toward the ~20% w/w azeotrope. +pub const CONCENTRATE_HCL_AZEOTROPE: Challenge = Challenge { + id: "concentrate-hcl-azeotrope", + title: "Concentrate hydrochloric acid", + prompt: "Heat hydrochloric acid in the dish and stop near the azeotrope — you cannot boil it to pure HCl.", + done: "Thank you.", + allowed_stock_item_ids: &["beaker-h2o", "beaker-hcl"], + empty_stock_item_ids: &[], + main_beaker_solids: &[], + distilled_water_ml: None, + win: &[], + checks: &[WinCheck::HclWw { + item_ids: &["dish-1"], + min: 0.18, + max: 0.22, + }], }; /// Every challenge, in picker order (Free mode is not a challenge). -pub const CHALLENGES: &[Challenge] = &[SEPARATE_NACL_SIO2, CREATE_TABLE_SALT]; +pub const CHALLENGES: &[Challenge] = &[ + SEPARATE_NACL_SIO2, + CREATE_TABLE_SALT, + CREATE_SODIUM_SULFATE, + PRECIPITATE_GYPSUM, + MAKE_HCL_FROM_GYPSUM, + HOT_PACK_CACL2, + COMMON_ION_NACL, + NEUTRALIZE_TO_PH7, + DILUTE_SULFURIC_SAFE, + CONCENTRATE_HCL_AZEOTROPE, +]; /// Whether `mode` is the default bench rather than a challenge. pub fn is_free_mode(mode: &str) -> bool { @@ -122,21 +429,142 @@ pub fn is_completed(scene: &Scene) -> bool { .win .iter() .all(|target| stock_holds_target(scene, target)) + && challenge + .checks + .iter() + .all(|check| check_holds(scene, check)) } fn stock_holds_target(scene: &Scene, target: &StockTarget) -> bool { let Some(item) = scene.items.iter().find(|item| item.id == target.item_id) else { return false; }; - let grams: f64 = item - .properties - .composition - .iter() - .filter(|entry| entry.phase == "solid" && entry.substance_id == target.substance_id) - .map(solid_amount_g) - .sum(); + let grams = solid_grams(item, target.substance_id); match target.compare { WinCompare::Exact => (grams - target.amount_g).abs() <= CHALLENGE_MASS_TOLERANCE_G, WinCompare::AtLeast => grams + CHALLENGE_MASS_TOLERANCE_G >= target.amount_g, } } + +fn check_holds(scene: &Scene, check: &WinCheck) -> bool { + match *check { + WinCheck::Ph { item_ids, min, max } => item_ids.iter().any(|id| { + scene + .items + .iter() + .find(|item| item.id == *id) + .and_then(ph_of_item) + .is_some_and(|ph| ph >= min && ph <= max) + }), + WinCheck::TemperatureAtLeast { item_id, min_c } => scene + .items + .iter() + .find(|item| item.id == item_id) + .and_then(|item| item.properties.temperature_c) + .is_some_and(|t| t + CHALLENGE_MASS_TOLERANCE_G >= min_c), + WinCheck::AqueousAtLeast { + item_ids, + substance_id, + amount_mol, + } => item_ids.iter().any(|id| { + scene + .items + .iter() + .find(|item| item.id == *id) + .is_some_and(|item| aqueous_mol(item, substance_id) + 1e-12 >= amount_mol) + }), + WinCheck::SolidAtMost { + item_id, + substance_id, + amount_g, + } => scene + .items + .iter() + .find(|item| item.id == item_id) + .is_some_and(|item| { + solid_grams(item, substance_id) <= amount_g + CHALLENGE_MASS_TOLERANCE_G + }), + WinCheck::SolidAtLeast { + item_ids, + substance_id, + amount_g, + } => item_ids.iter().any(|id| { + scene + .items + .iter() + .find(|item| item.id == *id) + .is_some_and(|item| { + solid_grams(item, substance_id) + CHALLENGE_MASS_TOLERANCE_G >= amount_g + }) + }), + WinCheck::LiquidAtMost { + item_id, + substance_id, + amount_ml, + } => scene + .items + .iter() + .find(|item| item.id == item_id) + .is_some_and(|item| { + liquid_ml(item, substance_id) <= amount_ml + CHALLENGE_MASS_TOLERANCE_G + }), + WinCheck::HclWw { item_ids, min, max } => item_ids.iter().any(|id| { + scene + .items + .iter() + .find(|item| item.id == *id) + .is_some_and(|item| { + let inv = HclInventory::from_item(item); + inv.total_mass_g() > 1e-6 && { + let w = inv.w_hcl(); + w >= min && w <= max + } + }) + }), + WinCheck::AcidAddedIntoWater { item_id } => scene + .items + .iter() + .find(|item| item.id == item_id) + .is_some_and(|item| item.properties.h2so4_dilution_into_water == Some(true)), + } +} + +fn solid_grams(item: &SceneItem, substance_id: &str) -> f64 { + item.properties + .composition + .iter() + .filter(|entry| entry.phase == "solid" && entry.substance_id == substance_id) + .map(|entry| { + if let Some(g) = entry.amount_g { + return g; + } + if let Some(n) = entry.amount_mol { + return n * molar_mass_g_per_mol(substance_id); + } + solid_amount_g(entry) + }) + .sum() +} + +fn molar_mass_g_per_mol(substance_id: &str) -> f64 { + match substance_id { + "nacl" => NACL_MOLAR_MASS_G_PER_MOL, + "cacl2" => CACL2_MOLAR_MASS_G_PER_MOL, + "naoh" => NAOH_MOLAR_MASS_G_PER_MOL, + "na2so4" => NA2SO4_MOLAR_MASS_G_PER_MOL, + "caso4" => CASO4_MOLAR_MASS_G_PER_MOL, + _ => 0.0, + } +} + +fn liquid_ml(item: &SceneItem, substance_id: &str) -> f64 { + if substance_id == "h2so4" { + return liquid_h2so4_ml(item); + } + item.properties + .composition + .iter() + .filter(|entry| entry.phase == "liquid" && entry.substance_id == substance_id) + .filter_map(|entry| entry.amount_ml) + .sum() +} diff --git a/crates/chemlab-core/src/scene.rs b/crates/chemlab-core/src/scene.rs index 1d9f7cd..029a4a0 100644 --- a/crates/chemlab-core/src/scene.rs +++ b/crates/chemlab-core/src/scene.rs @@ -160,6 +160,12 @@ pub struct ItemProperties { /// Last vessel a pipette drew from, the vessel tongs currently hold, or the /// dish a spoon scoop came from. pub source_item_id: Option, + /// Dilution order for concentrated H₂SO₄ in this vessel. + /// + /// `Some(true)` — liquid acid was added into water already in the vessel. + /// `Some(false)` — water was added onto concentrated liquid acid (unsafe). + /// Unsafe latches and is never overwritten back to safe. + pub h2so4_dilution_into_water: Option, } /// A single item in the lab scene (beaker, spoon, …). @@ -1982,6 +1988,7 @@ fn mix_transfer_into( transferred: &[CompositionEntry], source_t: Option, ) -> bool { + note_h2so4_dilution_order(target, transferred); let dest_hcl_before = crate::hcl::HclInventory::from_item(target); let added_hcl = crate::hcl::HclInventory::from_entries(transferred); let dest_h2so4_before = crate::h2so4::H2so4Inventory::from_item(target); @@ -2001,6 +2008,7 @@ fn mix_transfer_into( } fn mix_aliquot_into(target: &mut SceneItem, aliquot: &[CompositionEntry], aliquot_t: f64) -> bool { + note_h2so4_dilution_order(target, aliquot); let dest_hcl_before = crate::hcl::HclInventory::from_item(target); let added_hcl = crate::hcl::HclInventory::from_entries(aliquot); let dest_h2so4_before = crate::h2so4::H2so4Inventory::from_item(target); @@ -2020,6 +2028,23 @@ fn mix_aliquot_into(target: &mut SceneItem, aliquot: &[CompositionEntry], aliquo spit_hcl || spit_h2so4 } +/// Record whether this mix was acid-into-water or water-onto-acid. +fn note_h2so4_dilution_order(target: &mut SceneItem, transferred: &[CompositionEntry]) { + let dest_liquid_acid = crate::h2so4::liquid_h2so4_mol_entries(&target.properties.composition); + let dest_water = crate::composition::liquid_water_ml_entries(&target.properties.composition); + let add_liquid_acid = crate::h2so4::liquid_h2so4_mol_entries(transferred); + let add_water = crate::composition::liquid_water_ml_entries(transferred); + if dest_liquid_acid > AMOUNT_EPS && add_water > AMOUNT_EPS && add_liquid_acid <= AMOUNT_EPS { + target.properties.h2so4_dilution_into_water = Some(false); + return; + } + if dest_water > AMOUNT_EPS && add_liquid_acid > AMOUNT_EPS { + if target.properties.h2so4_dilution_into_water != Some(false) { + target.properties.h2so4_dilution_into_water = Some(true); + } + } +} + fn apply_hcl_dilution_temperature( target: &mut SceneItem, dest_before: crate::hcl::HclInventory, diff --git a/crates/chemlab-core/src/scene_tests/challenges.rs b/crates/chemlab-core/src/scene_tests/challenges.rs index d5376a1..fcb1532 100644 --- a/crates/chemlab-core/src/scene_tests/challenges.rs +++ b/crates/chemlab-core/src/scene_tests/challenges.rs @@ -51,9 +51,17 @@ fn free_is_the_default_mode_and_is_never_completed() { #[test] fn catalog_entry_matches_the_docs_copy() { - assert_eq!(CHALLENGES.len(), 2); + assert_eq!(CHALLENGES.len(), 10); assert_eq!(&CHALLENGES[0], &SEPARATE_NACL_SIO2); assert_eq!(&CHALLENGES[1], &CREATE_TABLE_SALT); + assert_eq!(CHALLENGES[2].id, "create-sodium-sulfate"); + assert_eq!(CHALLENGES[3].id, "precipitate-gypsum"); + assert_eq!(CHALLENGES[4].id, "make-hcl-from-gypsum"); + assert_eq!(CHALLENGES[5].id, "hot-pack-cacl2"); + assert_eq!(CHALLENGES[6].id, "common-ion-nacl"); + assert_eq!(CHALLENGES[7].id, "neutralize-to-ph7"); + assert_eq!(CHALLENGES[8].id, "dilute-sulfuric-safe"); + assert_eq!(CHALLENGES[9].id, "concentrate-hcl-azeotrope"); let challenge = find_challenge(SEPARATE).expect("catalog entry"); assert_eq!(challenge, &SEPARATE_NACL_SIO2); @@ -89,6 +97,7 @@ fn catalog_entry_matches_the_docs_copy() { assert_eq!(create.win[0].substance_id, "nacl"); assert_eq!(create.win[0].amount_g, 0.20); assert_eq!(create.win[0].compare, WinCompare::AtLeast); + assert!(create.checks.is_empty()); assert_eq!(find_challenge("nope"), None); assert_eq!(find_challenge(FREE_MODE), None); @@ -520,3 +529,324 @@ fn move_all_solids(scene: &mut Scene, source_id: &str, stock_id: &str) { } panic!("solids never ran out in {source_id}"); } + +fn scene_for(id: &str) -> Scene { + initial_scene_for_mode("lab-test", id).expect("challenge scene") +} + +fn allowed_ids(scene: &Scene) -> Vec<&str> { + scene.items.iter().map(|i| i.id.as_str()).collect() +} + +fn assert_tools_present(ids: &[&str]) { + for tool_id in [ + "spoon-1", + "pipette-1", + "tongs-1", + "filter-paper-1", + "dish-1", + "burner-1", + ] { + assert!(ids.contains(&tool_id), "missing {tool_id}"); + } +} + +fn pipette_into(scene: &mut Scene, source_id: &str, dest_id: &str) { + fill_pipette_from(scene, source_id); + apply_action( + scene, + Action::UseTool { + tool_item_id: "pipette-1".into(), + target_item_id: dest_id.into(), + }, + ) + .unwrap(); +} + +fn spoon_into(scene: &mut Scene, stock_id: &str, dest_id: &str) { + apply_action( + scene, + Action::UseTool { + tool_item_id: "spoon-1".into(), + target_item_id: stock_id.into(), + }, + ) + .unwrap(); + apply_action( + scene, + Action::UseTool { + tool_item_id: "spoon-1".into(), + target_item_id: dest_id.into(), + }, + ) + .unwrap(); +} + +#[test] +fn create_sodium_sulfate_starts_with_empty_product_stock() { + let scene = scene_for("create-sodium-sulfate"); + let ids = allowed_ids(&scene); + assert!(ids.contains(&"beaker-h2so4")); + assert!(ids.contains(&"beaker-naoh")); + assert!(ids.contains(&"beaker-na2so4")); + assert!(!ids.contains(&"beaker-hcl")); + assert!(!ids.contains(&"beaker-nacl")); + assert_eq!(solid_g(item(&scene, "beaker-na2so4"), "na2so4"), 0.0); + assert_tools_present(&ids); + assert!(!is_completed(&scene)); +} + +#[test] +fn create_sodium_sulfate_wins_on_solid_product_stock() { + let mut scene = scene_for("create-sodium-sulfate"); + fill_stock(&mut scene, "beaker-na2so4", "na2so4", 0.19); + assert!(!is_completed(&scene)); + fill_stock(&mut scene, "beaker-na2so4", "na2so4", 0.20); + assert!(is_completed(&scene)); +} + +#[test] +fn create_sodium_sulfate_solved_by_neutralize_evaporate_and_return() { + let mut scene = scene_for("create-sodium-sulfate"); + for _ in 0..5 { + pipette_into(&mut scene, "beaker-h2o", "beaker-water"); + } + pipette_into(&mut scene, "beaker-h2so4", "beaker-water"); + spoon_into(&mut scene, "beaker-naoh", "beaker-water"); + spoon_into(&mut scene, "beaker-naoh", "beaker-water"); + while liquid_ml(&scene, "beaker-water") > 1e-9 { + use_tongs_pour(&mut scene, "beaker-water", "dish-1"); + boil_dish_dry(&mut scene); + } + let recovered = solid_g(item(&scene, "dish-1"), "na2so4"); + assert!( + recovered + 1e-6 >= 0.20, + "expected ≥ 0.20 g solid Na2SO4 in the dish, got {recovered}; {:?}", + item(&scene, "dish-1").properties.composition + ); + assert!(is_completed(&scene)); +} + +#[test] +fn precipitate_gypsum_starts_with_sulfate_sources() { + let scene = scene_for("precipitate-gypsum"); + let ids = allowed_ids(&scene); + assert!(ids.contains(&"beaker-cacl2")); + assert!(ids.contains(&"beaker-na2so4")); + assert!(ids.contains(&"beaker-h2so4")); + assert!(!ids.contains(&"beaker-sand")); + assert_eq!(solid_g(item(&scene, "filter-paper-1"), "caso4"), 0.0); + assert!(!is_completed(&scene)); +} + +#[test] +fn precipitate_gypsum_wins_on_filter_paper_solids() { + let mut scene = scene_for("precipitate-gypsum"); + fill_stock(&mut scene, "filter-paper-1", "caso4", 0.14); + assert!(!is_completed(&scene)); + fill_stock(&mut scene, "filter-paper-1", "caso4", 0.15); + assert!(is_completed(&scene)); +} + +#[test] +fn precipitate_gypsum_solved_by_mix_and_filter() { + let mut scene = scene_for("precipitate-gypsum"); + use_tongs_pour(&mut scene, "beaker-h2o", "beaker-water"); + use_tongs_pour(&mut scene, "beaker-cacl2", "beaker-water"); + use_tongs_pour(&mut scene, "beaker-na2so4", "beaker-water"); + finish_kinetic_dissolve(&mut scene); + use_tongs_pour(&mut scene, "beaker-water", "filter-paper-1"); + let gypsum = solid_g(item(&scene, "filter-paper-1"), "caso4"); + assert!( + gypsum + 1e-6 >= 0.15, + "expected ≥ 0.15 g CaSO4 on paper, got {gypsum}" + ); + assert!(is_completed(&scene)); +} + +#[test] +fn make_hcl_from_gypsum_requires_acidic_filtrate_and_gypsum() { + let mut scene = scene_for("make-hcl-from-gypsum"); + assert!(!ids_has_hcl(&scene)); + fill_stock(&mut scene, "filter-paper-1", "caso4", 0.20); + assert!(!is_completed(&scene), "acidic HCl still missing"); +} + +fn ids_has_hcl(scene: &Scene) -> bool { + scene.items.iter().any(|i| i.id == "beaker-hcl") +} + +#[test] +fn make_hcl_from_gypsum_solved_by_filter() { + let mut scene = scene_for("make-hcl-from-gypsum"); + use_tongs_pour(&mut scene, "beaker-h2o", "beaker-water"); + use_tongs_pour(&mut scene, "beaker-cacl2", "beaker-water"); + finish_kinetic_dissolve(&mut scene); + pipette_into(&mut scene, "beaker-h2so4", "beaker-water"); + pipette_into(&mut scene, "beaker-h2so4", "beaker-water"); + finish_kinetic_dissolve(&mut scene); + use_tongs_pour(&mut scene, "beaker-water", "filter-paper-1"); + let gypsum = solid_g(item(&scene, "filter-paper-1"), "caso4"); + let ph = crate::hcl::ph_of_item(item(&scene, "beaker-filtrate")); + assert!( + gypsum + 1e-6 >= 0.15, + "gypsum on paper {gypsum}; filtrate pH {ph:?}" + ); + assert!(is_completed(&scene), "filtrate pH {ph:?}"); +} + +#[test] +fn hot_pack_starts_with_ten_ml_water() { + let scene = scene_for("hot-pack-cacl2"); + let ids = allowed_ids(&scene); + assert!(ids.contains(&"beaker-cacl2")); + assert!(!ids.contains(&"beaker-nacl")); + assert_eq!(item(&scene, "beaker-h2o").properties.fill_ml, Some(10.0)); + assert!(!is_completed(&scene)); +} + +#[test] +fn hot_pack_solved_by_dissolving_cacl2() { + let mut scene = scene_for("hot-pack-cacl2"); + use_tongs_pour(&mut scene, "beaker-h2o", "beaker-water"); + use_tongs_pour(&mut scene, "beaker-cacl2", "beaker-water"); + finish_kinetic_dissolve(&mut scene); + let t = item(&scene, "beaker-water") + .properties + .temperature_c + .unwrap_or(0.0); + assert!(t >= 25.0, "expected warm beaker, got {t}"); + assert_eq!(solid_g(item(&scene, "beaker-water"), "cacl2"), 0.0); + assert!(is_completed(&scene)); +} + +#[test] +fn common_ion_nacl_not_won_by_dry_salt_alone() { + let mut scene = scene_for("common-ion-nacl"); + fill_stock(&mut scene, "beaker-water", "nacl", 2.0); + assert!(!is_completed(&scene)); +} + +#[test] +fn common_ion_nacl_solved_by_adding_hcl_to_brine() { + let mut scene = scene_for("common-ion-nacl"); + use_tongs_pour(&mut scene, "beaker-h2o", "beaker-water"); + use_tongs_pour(&mut scene, "beaker-nacl", "beaker-water"); + finish_kinetic_dissolve(&mut scene); + let solid_before = solid_g(item(&scene, "beaker-water"), "nacl"); + pipette_into(&mut scene, "beaker-hcl", "beaker-water"); + pipette_into(&mut scene, "beaker-hcl", "beaker-water"); + finish_kinetic_dissolve(&mut scene); + let solid_after = solid_g(item(&scene, "beaker-water"), "nacl"); + assert!( + solid_after + 1e-6 >= 0.05, + "solid before {solid_before} after {solid_after}; h+ {}", + aqueous_mol(item(&scene, "beaker-water"), "h+") + ); + assert!(is_completed(&scene)); +} + +#[test] +fn neutralize_to_ph7_wins_in_the_inspect_band() { + let mut scene = scene_for("neutralize-to-ph7"); + assert!(!is_completed(&scene)); + let beaker = scene + .items + .iter_mut() + .find(|item| item.id == "beaker-water") + .unwrap(); + beaker.properties.fill_ml = Some(50.0); + beaker.properties.composition = vec![ + CompositionEntry { + substance_id: "water".into(), + phase: "liquid".into(), + amount_ml: Some(50.0), + amount_scoop: None, + amount_g: None, + amount_mol: None, + }, + CompositionEntry { + substance_id: "na+".into(), + phase: "aqueous".into(), + amount_ml: None, + amount_scoop: None, + amount_g: None, + amount_mol: Some(0.01), + }, + CompositionEntry { + substance_id: "cl-".into(), + phase: "aqueous".into(), + amount_ml: None, + amount_scoop: None, + amount_g: None, + amount_mol: Some(0.01), + }, + ]; + apply_elapsed(&mut scene, 0.0); + let ph = crate::hcl::ph_of_item(item(&scene, "beaker-water")).unwrap(); + assert!( + (6.5..=7.5).contains(&ph), + "expected near-neutral inspect pH, got {ph}" + ); + assert!(is_completed(&scene)); +} + +#[test] +fn dilute_sulfuric_safe_rewards_acid_into_water_only() { + let mut unsafe_scene = scene_for("dilute-sulfuric-safe"); + use_tongs_pour(&mut unsafe_scene, "beaker-h2so4", "beaker-water"); + use_tongs_pour(&mut unsafe_scene, "beaker-h2o", "beaker-water"); + assert_eq!( + item(&unsafe_scene, "beaker-water") + .properties + .h2so4_dilution_into_water, + Some(false) + ); + assert!(!is_completed(&unsafe_scene), "water-onto-acid must not win"); + + let mut scene = scene_for("dilute-sulfuric-safe"); + use_tongs_pour(&mut scene, "beaker-h2o", "beaker-water"); + pipette_into(&mut scene, "beaker-h2so4", "beaker-water"); + assert_eq!( + item(&scene, "beaker-water") + .properties + .h2so4_dilution_into_water, + Some(true) + ); + let t = item(&scene, "beaker-water") + .properties + .temperature_c + .unwrap_or(0.0); + let ph = crate::hcl::ph_of_item(item(&scene, "beaker-water")); + assert!(t >= 20.5, "T {t}"); + assert!(is_completed(&scene), "T {t} pH {ph:?}"); +} + +#[test] +fn concentrate_hcl_solved_by_boiling_stock_toward_azeotrope() { + let mut scene = scene_for("concentrate-hcl-azeotrope"); + assert!(!is_completed(&scene)); + use_tongs_pour(&mut scene, "beaker-hcl", "dish-1"); + apply_action( + &mut scene, + Action::ToggleBurner { + burner_item_id: "burner-1".into(), + }, + ) + .unwrap(); + for _ in 0..400 { + apply_elapsed(&mut scene, 1.0); + let w = crate::hcl::HclInventory::from_item(item(&scene, "dish-1")).w_hcl(); + if (0.18..=0.22).contains(&w) && is_completed(&scene) { + return; + } + if liquid_ml(&scene, "dish-1") <= 1e-9 { + break; + } + } + let w = crate::hcl::HclInventory::from_item(item(&scene, "dish-1")).w_hcl(); + panic!( + "dish never reached 18–22% w/w HCl (w={w}, completed={})", + is_completed(&scene) + ); +} diff --git a/crates/chemlab-server/src/routes/routes_tests/challenges.rs b/crates/chemlab-server/src/routes/routes_tests/challenges.rs index 49886e2..186e15f 100644 --- a/crates/chemlab-server/src/routes/routes_tests/challenges.rs +++ b/crates/chemlab-server/src/routes/routes_tests/challenges.rs @@ -306,3 +306,61 @@ async fn create_table_salt_completes_with_at_least_one_scoop() { true ); } + +#[tokio::test] +async fn hot_pack_select_mode_keeps_ten_ml_water_and_cacl2() { + let app = test_app().await; + let (csrf_token, csrf_cookie, session_cookie) = + register_user(&app, "mode-hot-pack@chemlab.local").await; + let cookies = format!("{session_cookie}; {csrf_cookie}"); + + let response = post_action( + &app, + &cookies, + Some(&csrf_token), + select_mode("hot-pack-cacl2"), + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + let scene = body_json(response).await["scene"].clone(); + assert_eq!(scene["mode"], "hot-pack-cacl2"); + let ids = scene_ids(&scene); + assert!(ids.contains(&"beaker-cacl2".to_string())); + assert!(ids.contains(&"beaker-h2o".to_string())); + assert!(!ids.contains(&"beaker-nacl".to_string())); + assert_eq!( + scene_item(&scene, "beaker-h2o")["properties"]["fill_ml"], + 10.0 + ); + assert_eq!(scene["challenge_completed"], false); +} + +#[tokio::test] +async fn precipitate_gypsum_completes_from_filter_paper_solid() { + let (app, state) = test_app_state().await; + let (csrf_token, csrf_cookie, session_cookie) = + register_user(&app, "mode-gypsum-win@chemlab.local").await; + let cookies = format!("{session_cookie}; {csrf_cookie}"); + assert_eq!( + post_action( + &app, + &cookies, + Some(&csrf_token), + select_mode("precipitate-gypsum") + ) + .await + .status(), + StatusCode::OK + ); + + persist_stock_solid(&state, &app, &cookies, "filter-paper-1", "caso4", 0.14).await; + assert_eq!( + body_json(get_scene(&app, Some(&cookies)).await).await["challenge_completed"], + false + ); + persist_stock_solid(&state, &app, &cookies, "filter-paper-1", "caso4", 0.15).await; + assert_eq!( + body_json(get_scene(&app, Some(&cookies)).await).await["challenge_completed"], + true + ); +} diff --git a/docs/challenges.md b/docs/challenges.md index 1ec21db..b37a0f7 100644 --- a/docs/challenges.md +++ b/docs/challenges.md @@ -17,8 +17,9 @@ in the web mirror + tests. rebuilds that mode's start scene; there is no partial progress across a switch. - **Reset resets the current mode.** The bench Reset button rebuilds the start scene of the mode the lab is in, not always Free. -- **Free mode is never "completed".** Completion (`challenge_completed` on the scene) is derived - after every action from the challenge's win condition, so undoing the winning move un-wins it. +Win clauses may be **solid mass in any named vessel** (stocks, filter paper, main beaker) +and extra server-side checks (pH, temperature, aqueous ions, leftover liquid/solid, HCl w/w, +acid-into-water dilution order). The browser never evaluates wins. - A challenge start scene is the Free bench with the challenge's edits applied: ingredient stocks outside the allowed list are removed, listed stocks start empty, and the main beaker (`beaker-water`) is preloaded with the listed dry solids. Optional `distilled_water_ml` @@ -32,6 +33,14 @@ in the web mirror + tests. | Free mode | `free` | yes | | Separate salt from sand | `separate-nacl-sio2` | no | | Create table salt | `create-table-salt` | no | +| Create sodium sulfate | `create-sodium-sulfate` | no | +| Precipitate gypsum | `precipitate-gypsum` | no | +| Make hydrochloric acid | `make-hcl-from-gypsum` | no | +| Hot pack | `hot-pack-cacl2` | no | +| Crash salt with acid | `common-ion-nacl` | no | +| Neutralise to pH 7 | `neutralize-to-ph7` | no | +| Dilute sulfuric acid safely | `dilute-sulfuric-safe` | no | +| Concentrate hydrochloric acid | `concentrate-hcl-azeotrope` | no | ## `separate-nacl-sio2` — Separate salt from sand @@ -68,3 +77,139 @@ salt, then spoon each solid back into its own stock beaker. Intended solution: combine aqueous HCl with solid NaOH (acid excess preferred), evaporate the brine to dryness, then spoon pure solid NaCl back into the empty NaCl stock. + +## `create-sodium-sulfate` — Create sodium sulfate + +| Field | Value | +| --- | --- | +| Id | `create-sodium-sulfate` | +| Title | Create sodium sulfate | +| Prompt | We're out of sodium sulfate, can you make some from sulfuric acid and sodium hydroxide? | +| Done | Thank you. | +| Main beaker (`beaker-water`) | Empty (no preload) | +| Allowed ingredient stocks | `beaker-h2o` (full), `beaker-h2so4` (full), `beaker-naoh` (full), `beaker-na2so4` | +| Empty at start | `beaker-na2so4` | +| Removed from the bench | `beaker-hcl`, `beaker-nacl`, `beaker-cacl2`, `beaker-sand` | +| Win | **at least** 0.20 g solid `na2so4` in `beaker-na2so4` **or** `dish-1` (leftover liquid H₂SO₄ can block spooning from the dish, so the dish solid also counts) | +| Tools | Full set | + +Intended solution: combine H₂SO₄ with NaOH (about 1 : 2), evaporate in the dish. Spoon into the empty stock when the dish is dry; if leftover sulfuric remains as liquid, the solid in the dish still counts. + +## `precipitate-gypsum` — Precipitate gypsum + +| Field | Value | +| --- | --- | +| Id | `precipitate-gypsum` | +| Title | Precipitate gypsum | +| Prompt | We need gypsum. Mix calcium chloride with a sulfate and filter off the solid. | +| Done | Thank you. | +| Main beaker (`beaker-water`) | Empty (no preload) | +| Allowed ingredient stocks | `beaker-h2o` (full), `beaker-cacl2` (full), `beaker-na2so4` (full), `beaker-h2so4` (full) | +| Empty at start | none | +| Removed from the bench | `beaker-hcl`, `beaker-nacl`, `beaker-naoh`, `beaker-sand` | +| Win | `filter-paper-1` holds **at least** 0.15 g solid `caso4` (AtLeast; filter-paper solids count) | +| Tools | Full set | + +Intended solution: dissolve CaCl₂ and Na₂SO₄ (or add H₂SO₄), mix so gypsum precipitates, pour through the filter. + +## `make-hcl-from-gypsum` — Make hydrochloric acid + +| Field | Value | +| --- | --- | +| Id | `make-hcl-from-gypsum` | +| Title | Make hydrochloric acid | +| Prompt | Make hydrochloric acid by mixing calcium chloride with sulfuric acid, then filter off the gypsum. | +| Done | Thank you. | +| Main beaker (`beaker-water`) | Empty (no preload) | +| Allowed ingredient stocks | `beaker-h2o` (full), `beaker-cacl2` (full), `beaker-h2so4` (full) | +| Empty at start | none | +| Removed from the bench | `beaker-hcl`, `beaker-nacl`, `beaker-naoh`, `beaker-na2so4`, `beaker-sand` | +| Win | `filter-paper-1` holds **at least** 0.15 g solid `caso4`, **and** the filtrate **or** dish is acidic HCl (pH ≤ 3 with aqueous `h+` and `cl-`) | +| Tools | Full set | + +Intended solution: dissolve CaCl₂, add H₂SO₄ so gypsum forms and aqueous HCl remains, filter. Optional dish boil toward the azeotrope is not required. + +## `hot-pack-cacl2` — Hot pack + +| Field | Value | +| --- | --- | +| Id | `hot-pack-cacl2` | +| Title | Hot pack | +| Prompt | Dissolve the calcium chloride in a little distilled water and check that the beaker warms up. | +| Done | Thank you. | +| Main beaker (`beaker-water`) | Empty (no preload) | +| Allowed ingredient stocks | `beaker-h2o` (10 ml), `beaker-cacl2` (full 2 g) | +| Empty at start | none | +| Removed from the bench | `beaker-hcl`, `beaker-h2so4`, `beaker-nacl`, `beaker-naoh`, `beaker-na2so4`, `beaker-sand` | +| Win | Main beaker T ≥ **25 °C**, aqueous `ca2+` and `cl-` present, leftover solid `cacl2` negligible. (Beaker heat capacity keeps a 2 g dump well below a calorimeter 30 °C; 25 °C is the judged bar.) | +| Tools | Full set | + +Intended solution: pour the 10 ml water into the main beaker, dump the CaCl₂ stock, wait for kinetic dissolve, inspect temperature. + +## `common-ion-nacl` — Crash salt with acid + +| Field | Value | +| --- | --- | +| Id | `common-ion-nacl` | +| Title | Crash salt with acid | +| Prompt | Make a salty solution, then add hydrochloric acid until extra salt crashes out. | +| Done | Thank you. | +| Main beaker (`beaker-water`) | Empty (no preload) | +| Allowed ingredient stocks | `beaker-h2o` (5 ml), `beaker-hcl` (full), `beaker-nacl` (full) | +| Empty at start | none | +| Removed from the bench | `beaker-h2so4`, `beaker-naoh`, `beaker-na2so4`, `beaker-cacl2`, `beaker-sand` | +| Win | Main beaker holds **at least** 0.05 g solid `nacl`, plus aqueous `h+` and `na+` (so the solid is not just dry leftover salt with no brine) | +| Tools | Full set | + +Intended solution: dissolve NaCl in the limited water, pipette in 30% HCl so the common-ion effect crashes extra solid. + +## `neutralize-to-ph7` — Neutralise to pH 7 + +| Field | Value | +| --- | --- | +| Id | `neutralize-to-ph7` | +| Title | Neutralise to pH 7 | +| Prompt | Neutralise sodium hydroxide with hydrochloric acid until the inspect pH is about 7. | +| Done | Thank you. | +| Main beaker (`beaker-water`) | Empty (no preload) | +| Allowed ingredient stocks | `beaker-h2o` (full), `beaker-hcl` (full), `beaker-naoh` (full) | +| Empty at start | none | +| Removed from the bench | `beaker-h2so4`, `beaker-nacl`, `beaker-na2so4`, `beaker-cacl2`, `beaker-sand` | +| Win | Main beaker inspect pH in **6.5–7.5**, aqueous `na+` and `cl-` present, leftover solid `naoh` negligible | +| Tools | Full set | + +Intended solution: dissolve NaOH, add HCl while watching inspect pH. A 1 ml pipette is coarse around neutrality; the win is the inspect band, not a concordant titre. + +## `dilute-sulfuric-safe` — Dilute sulfuric acid safely + +| Field | Value | +| --- | --- | +| Id | `dilute-sulfuric-safe` | +| Title | Dilute sulfuric acid safely | +| Prompt | Dilute the concentrated sulfuric acid the safe way: add the acid into water, not water onto the acid. | +| Done | Thank you. | +| Main beaker (`beaker-water`) | Empty (no preload) | +| Allowed ingredient stocks | `beaker-h2o` (full), `beaker-h2so4` (full) | +| Empty at start | none | +| Removed from the bench | `beaker-hcl`, `beaker-nacl`, `beaker-naoh`, `beaker-na2so4`, `beaker-cacl2`, `beaker-sand` | +| Win | Main beaker: acid was added **into water** (water-onto-acid does not count), no leftover liquid `h2so4`, aqueous `h+` present, T ≥ 20.5 °C, pH ≤ 2 | +| Tools | Full set | + +Intended solution: water in the main beaker first, then pipette or pour concentrated H₂SO₄ into that water. + +## `concentrate-hcl-azeotrope` — Concentrate hydrochloric acid + +| Field | Value | +| --- | --- | +| Id | `concentrate-hcl-azeotrope` | +| Title | Concentrate hydrochloric acid | +| Prompt | Heat hydrochloric acid in the dish and stop near the azeotrope — you cannot boil it to pure HCl. | +| Done | Thank you. | +| Main beaker (`beaker-water`) | Empty (no preload) | +| Allowed ingredient stocks | `beaker-h2o` (full), `beaker-hcl` (full 30% w/w) | +| Empty at start | none | +| Removed from the bench | `beaker-h2so4`, `beaker-nacl`, `beaker-naoh`, `beaker-na2so4`, `beaker-cacl2`, `beaker-sand` | +| Win | Dish liquid HCl mass fraction in **18–22% w/w** | +| Tools | Full set | + +Intended solution: transfer HCl to the dish (optionally with extra water), heat on the burner, inspect as composition moves toward ~20% w/w rather than pure acid. From aa07409d8cb39f3649521126b4adcd45eefc5c5e Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 3 Oct 2026 14:11:54 +0000 Subject: [PATCH 2/5] Fix clippy collapsible_if on H2SO4 dilution order. Nested if in note_h2so4_dilution_order failed CI -D warnings. Co-authored-by: Arnoud --- crates/chemlab-core/src/scene.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/chemlab-core/src/scene.rs b/crates/chemlab-core/src/scene.rs index 029a4a0..fd37c63 100644 --- a/crates/chemlab-core/src/scene.rs +++ b/crates/chemlab-core/src/scene.rs @@ -2038,10 +2038,11 @@ fn note_h2so4_dilution_order(target: &mut SceneItem, transferred: &[CompositionE target.properties.h2so4_dilution_into_water = Some(false); return; } - if dest_water > AMOUNT_EPS && add_liquid_acid > AMOUNT_EPS { - if target.properties.h2so4_dilution_into_water != Some(false) { - target.properties.h2so4_dilution_into_water = Some(true); - } + if dest_water > AMOUNT_EPS + && add_liquid_acid > AMOUNT_EPS + && target.properties.h2so4_dilution_into_water != Some(false) + { + target.properties.h2so4_dilution_into_water = Some(true); } } From 2bd7b5add9706961e4e146f7bab516c8ca310949 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 3 Oct 2026 14:27:38 +0000 Subject: [PATCH 3/5] Fix catalog win fairness and azeotrope inspect. Widen neutralize pH to a pipette-reachable band, require common-ion crash after a clear 10 ml brine, bundle gypsum HCl on one vessel, and require a lean-then-boil VLE rise for the azeotrope. Restore the Free-mode completion docs bullet and show HCl % w/w on inspect. Co-authored-by: Arnoud --- apps/web/src/App.test.tsx | 4 + .../web/src/components/BeakerInspectPanel.tsx | 6 + .../src/components/LabBench.inspect.test.tsx | 1 + .../src/components/labBenchTestFixtures.ts | 2 +- apps/web/src/lib/benchAmounts.ts | 5 +- apps/web/src/lib/challenges.ts | 5 +- apps/web/src/lib/compositionDisplay.test.tsx | 21 ++ apps/web/src/lib/compositionDisplay.tsx | 9 +- apps/web/src/lib/solutionChemistry.ts | 17 ++ crates/chemlab-contracts/src/convert.rs | 1 + crates/chemlab-core/src/aqueous_pipeline.rs | 3 +- crates/chemlab-core/src/challenges.rs | 77 +++--- crates/chemlab-core/src/scene.rs | 16 ++ .../src/scene_tests/challenges.rs | 231 ++++++++++++++---- docs/challenges.md | 26 +- 15 files changed, 330 insertions(+), 94 deletions(-) diff --git a/apps/web/src/App.test.tsx b/apps/web/src/App.test.tsx index ed1d1ba..f89e09e 100644 --- a/apps/web/src/App.test.tsx +++ b/apps/web/src/App.test.tsx @@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import App from './App' import { clearCsrfTokenCache } from './lib/api' import { STOCK_FULL_MASS_G, STOCK_FULL_SCOOPS, HCL_STOCK_CAPACITY_ML, HCL_STOCK_WATER_ML, HCL_STOCK_HCL_MOLES } from './lib/benchAmounts' +import { CHALLENGES } from './lib/challenges' const userPayload = { id: 'u1', @@ -309,6 +310,9 @@ describe('App', () => { expect(free).toBeChecked() expect(screen.getByRole('radio', { name: 'Separate salt from sand' })).not.toBeChecked() expect(screen.getByRole('radio', { name: 'Create table salt' })).not.toBeChecked() + for (const challenge of CHALLENGES) { + expect(screen.getByRole('radio', { name: challenge.title })).toBeInTheDocument() + } expect(screen.queryByText(/lab bench below/i)).not.toBeInTheDocument() expect(screen.queryByText(/pick a solid/i)).not.toBeInTheDocument() }) diff --git a/apps/web/src/components/BeakerInspectPanel.tsx b/apps/web/src/components/BeakerInspectPanel.tsx index 7c53a40..c8e73f1 100644 --- a/apps/web/src/components/BeakerInspectPanel.tsx +++ b/apps/web/src/components/BeakerInspectPanel.tsx @@ -3,7 +3,9 @@ import { CompositionInspectLine, formatTemperatureC, formatPh, + formatHclWw, phFromComposition, + hclInventoryMassFraction, solventVolumeLitres, } from '../lib/compositionDisplay' import { optionalArray } from '../lib/scene' @@ -22,6 +24,7 @@ export function BeakerInspectPanel({ const temperatureC = itemTemperatureC(scene, item) const solventL = solventVolumeLitres(composition) const ph = phFromComposition(composition) + const hclWw = hclInventoryMassFraction(composition) return (