Craft Anything: understand how any software works, and craft your own.
Rust
Keep pasted picture names unique, create atomic-write temp files exclusively, and keep distinct replay samples (#995)
BFlate0922f4ff456
diff --git a/crates/analysis/src/standin.rs b/crates/analysis/src/standin.rsindex c2c4541b..a6a1cc74 100644--- a/crates/analysis/src/standin.rs+++ b/crates/analysis/src/standin.rs@@ -843,7 +843,17 @@ pub fn build(har: &Har, opts: &BuildOptions) -> StandIn {for n in &s.query_names {push_unique_sorted(&mut route.query_names, n);}- if route.samples.len() >= opts.max_samples_per_route {+ let full = route.samples.len() >= opts.max_samples_per_route;+ let replace = if full {+ let request_key = sample_request_key(s, &scrub);+ route+ .samples+ .iter()+ .position(|sample| sample.status == 304 && sample.path == s.path && sample.query == s.query && sample.request_key == request_key)+ } else {+ None+ };+ if full && replace.is_none() {route.samples_left_out = route.samples_left_out.saturating_add(1);// Still read its headers, so what's dropped is counted the same however many are kept.let _ = scrub.headers(&s.entry.response.headers);@@ -852,16 +862,7 @@ pub fn build(har: &Har, opts: &BuildOptions) -> StandIn {}let mut sample = make_sample(s, opts, &mut scrub);// A request polled over and over gives the same answer many times; one is enough.- let repeats_last = |sample: &Sample| {- route.samples.last().is_some_and(|p| {- p.path == sample.path- && p.query == sample.query- && p.request_key == sample.request_key- && p.status == sample.status- && p.text == sample.text- && p.base64 == sample.base64- })- };+ let repeats_last = |sample: &Sample| route.samples.last().is_some_and(|last| same_sample(last, sample));let mut repeat = repeats_last(&sample);if !repeat {let size = sample.text.as_ref().map_or(0, String::len).saturating_add(sample.base64.as_ref().map_or(0, String::len));@@ -881,7 +882,18 @@ pub fn build(har: &Har, opts: &BuildOptions) -> StandIn {}}note_status(route, sample.status, sample.content_type.as_deref(), &mut scrub);+ if replace.is_some() && (sample.status == 304 || sample.body_left_out.is_some_and(|reason| reason != BodyLeftOut::NotRecorded)) {+ // A missing cached body or a refused body cannot improve the stored evidence. Neither was charged.+ route.samples_left_out = route.samples_left_out.saturating_add(1);+ continue;+ }if !repeat {+ if let Some(at) = replace {+ // The position came from this unchanged sample list. Remove only an unavailable+ // answer to this exact request; append the replacement in recording order.+ route.samples.remove(at);+ route.samples_left_out = route.samples_left_out.saturating_add(1);+ }route.samples.push(sample);}}@@ -902,6 +914,34 @@ pub fn build(har: &Har, opts: &BuildOptions) -> StandIn {}}+fn same_sample(left: &Sample, right: &Sample) -> bool {+ // Keep this exhaustive so a new response field cannot silently disappear from repeat checks.+ let Sample { path, query, request_key, status, content_type, headers, text, base64, body_left_out, was_not_modified } = left;+ path == &right.path+ && query == &right.query+ && request_key == &right.request_key+ && status == &right.status+ && content_type == &right.content_type+ && text == &right.text+ && base64 == &right.base64+ && body_left_out == &right.body_left_out+ && was_not_modified == &right.was_not_modified+ && same_headers(headers, &right.headers)+}++fn same_headers(left: &[(String, String)], right: &[(String, String)]) -> bool {+ // Header names are case-insensitive; different names may move, but values for one name+ // must keep their order. Capture caps this list, and the stored representation stays intact.+ left == right+ || (left.len() == right.len()+ && left.iter().all(|(name, _)| {+ left.iter()+ .filter(|(key, _)| key.eq_ignore_ascii_case(name))+ .map(|(_, value)| value)+ .eq(right.iter().filter(|(key, _)| key.eq_ignore_ascii_case(name)).map(|(_, value)| value))+ }))+}+fn push_unique_sorted(list: &mut Vec<String>, value: &str) {if list.len() < MAX_LISTED&& let Err(i) = list.binary_search_by(|x| x.as_str().cmp(value))@@ -929,12 +969,16 @@ fn note_status(route: &mut StandInRoute, status: u16, mime: Option<&str>, scrub:}}+fn sample_request_key(s: &Seen<'_>, scrub: &Scrub) -> Option<String> {+ s.entry.request.post.as_ref().and_then(|p| p.text.as_deref()).and_then(|t| request_key(t.as_bytes())).filter(|k| !scrub.holds_hidden(k))+}+fn make_sample(s: &Seen<'_>, opts: &BuildOptions, scrub: &mut Scrub) -> Sample {let r = &s.entry.response;let mut sample = Sample {path: s.path.clone(),query: s.query.clone(),- request_key: s.entry.request.post.as_ref().and_then(|p| p.text.as_deref()).and_then(|t| request_key(t.as_bytes())).filter(|k| !scrub.holds_hidden(k)),+ request_key: sample_request_key(s, scrub),status: u16::try_from(r.status).unwrap_or(500),content_type: clean_mime(r.mime.as_deref(), scrub),headers: scrub.headers(&r.headers),diff --git a/crates/analysis/tests/regression_standin_header_capacity.rs b/crates/analysis/tests/regression_standin_header_capacity.rsnew file mode 100644index 00000000..5d28b1a8--- /dev/null+++ b/crates/analysis/tests/regression_standin_header_capacity.rs@@ -0,0 +1,238 @@+use craft_anything_analysis::standin::{Answer, BodyLeftOut, BuildOptions, NoMatchReason, StandIn, Turns, answer, build_from_bytes};+use serde_json::{Value, json};++fn entry(url: &str, status: u16, body: &str, headers: Value) -> Value {+ json!({+ "request": {"method": "GET", "url": url},+ "response": {"status": status, "headers": headers, "content": {"mimeType": "text/plain", "text": body}}+ })+}++fn operation(name: &str, status: u16, body: &str) -> Value {+ let mut value = entry("https://example.test/graphql", status, body, json!([]));+ value["request"]["method"] = json!("POST");+ value["request"]["postData"] = json!({"text": json!({"operationName": name}).to_string()});+ value+}++fn capture(entries: Vec<Value>, opts: &BuildOptions) -> StandIn {+ build_from_bytes(&serde_json::to_vec(&json!({"log": {"entries": entries}})).unwrap(), opts).unwrap()+}++fn get(standin: &StandIn, turns: &mut Turns, path: &str, query: &str) -> Answer {+ answer(standin, turns, "GET", path, query, b"")+}++fn assert_unavailable(answer: Answer) {+ let Answer::NoMatch(missing) = answer else { panic!("a missing cached body must not use another request's answer") };+ assert_eq!(missing.reason, NoMatchReason::CachedBodyUnavailable);+}++#[test]+fn equivalent_headers_do_not_consume_sample_capacity() {+ let first = entry(+ "https://example.test/resource",+ 200,+ "same",+ json!([{"name": "X-Mode", "value": "first"}, {"name": "X-Other", "value": "other"}, {"name": "x-MODE", "value": "second"}]),+ );+ let equivalent = entry(+ "https://example.test/resource",+ 200,+ "same",+ json!([{"name": "x-other", "value": "other"}, {"name": "x-mode", "value": "first"}, {"name": "X-MODE", "value": "second"}]),+ );+ let later = entry("https://example.test/resource", 200, "later", json!([]));+ let opts = BuildOptions { max_samples_per_route: 2, ..Default::default() };+ let standin = capture(vec![first.clone(), equivalent, first, later], &opts);+ let route = &standin.routes[0];+ assert_eq!((route.requests, route.samples.len(), route.samples_left_out), (4, 2, 0));+ assert_eq!(route.samples[0].headers, vec![("X-Mode".into(), "first".into()), ("X-Other".into(), "other".into()), ("x-MODE".into(), "second".into())]);+ let mut turns = Turns::default();+ for expected in ["same", "later"] {+ let Answer::Found(found) = get(&standin, &mut turns, "/resource", "") else { panic!("missing recorded answer") };+ assert_eq!(found.body, expected.as_bytes());+ }+}++#[test]+fn repeated_header_values_keep_their_order_and_count() {+ let headers = [+ json!([{"name": "X-Mode", "value": "first"}, {"name": "X-Other", "value": "other"}, {"name": "x-mode", "value": "second"}]),+ json!([{"name": "x-MODE", "value": "second"}, {"name": "x-other", "value": "other"}, {"name": "X-MODE", "value": "first"}]),+ json!([{"name": "x-mode", "value": "first"}, {"name": "x-other", "value": "other"}, {"name": "X-Other", "value": "other"}]),+ ];+ let standin = capture(headers.into_iter().map(|h| entry("https://example.test/resource", 200, "same", h)).collect(), &BuildOptions::default());+ assert_eq!(standin.routes[0].samples.len(), 3);+ let mut turns = Turns::default();+ for expected in [vec!["first", "second"], vec!["second", "first"], vec!["first"]] {+ let Answer::Found(found) = get(&standin, &mut turns, "/resource", "") else { panic!("missing distinct header values") };+ let values: Vec<_> = found.headers.iter().filter(|(name, _)| name.eq_ignore_ascii_case("x-mode")).map(|(_, value)| value.as_str()).collect();+ assert_eq!(values, expected);+ }+}++#[test]+fn full_routes_replace_matching_304s_in_recording_order() {+ let opts = BuildOptions::default();+ assert_eq!(opts.max_samples_per_route, 16);+ let mut entries: Vec<_> =+ (0..16).map(|i| entry("https://example.test/resource", 304, "", json!([{"name": "X-Request-Id", "value": format!("poll-{i}")}]))).collect();+ entries.push(entry("https://example.test/resource", 200, "first", json!([])));+ entries.push(entry("https://example.test/resource", 200, "second", json!([])));+ let standin = capture(entries, &opts);+ let route = &standin.routes[0];+ assert_eq!((route.requests, route.samples.len(), route.samples_left_out), (18, 16, 2));+ assert_eq!(route.statuses, vec![200, 304]);+ for (sample, i) in route.samples.iter().take(14).zip(2..16) {+ assert_eq!(sample.status, 304);+ assert_eq!(sample.headers, vec![("X-Request-Id".into(), format!("poll-{i}"))]);+ }+ assert_eq!(route.samples[14].text.as_deref(), Some("first"));+ assert_eq!(route.samples[15].text.as_deref(), Some("second"));+ let mut turns = Turns::default();+ for expected in ["first", "second", "first"] {+ let Answer::Found(found) = get(&standin, &mut turns, "/resource", "") else { panic!("a usable answer was displaced by unavailable 304s") };+ assert_eq!((found.status, found.body), (200, expected.as_bytes().to_vec()));+ }+}++#[test]+fn full_routes_preserve_missing_queries_and_resources() {+ for (missing_url, ready_url, missing_path, missing_query) in [+ ("https://example.test/items/1?view=missing", "https://example.test/items/1?view=ready", "/items/1", "view=missing"),+ ("https://example.test/items/1", "https://example.test/items/2", "/items/1", ""),+ ] {+ let opts = BuildOptions { max_samples_per_route: 2, ..Default::default() };+ let standin =+ capture(vec![entry(missing_url, 304, "", json!([])), entry(ready_url, 304, "", json!([])), entry(ready_url, 200, "ready", json!([]))], &opts);+ let route = &standin.routes[0];+ assert_eq!((route.requests, route.samples.len(), route.samples_left_out), (3, 2, 1));+ assert_eq!(route.samples[0].status, 304);+ assert_eq!(route.samples[1].text.as_deref(), Some("ready"));+ assert_unavailable(get(&standin, &mut Turns::default(), missing_path, missing_query));+ }+}++#[test]+fn full_routes_preserve_missing_graphql_operations() {+ let opts = BuildOptions { max_samples_per_route: 2, ..Default::default() };+ let standin = capture(vec![operation("Missing", 304, ""), operation("Ready", 304, ""), operation("Ready", 200, "ready")], &opts);+ let route = &standin.routes[0];+ assert_eq!((route.requests, route.samples.len(), route.samples_left_out), (3, 2, 1));+ assert_eq!(route.samples[0].request_key.as_deref(), Some("op:Missing"));+ assert_unavailable(answer(&standin, &mut Turns::default(), "POST", "/graphql", "", br#"{"operationName":"Missing"}"#));+ let Answer::Found(found) = answer(&standin, &mut Turns::default(), "POST", "/graphql", "", br#"{"operationName":"Ready"}"#) else {+ panic!("missing usable operation");+ };+ assert_eq!(found.body, b"ready");++ let opts = BuildOptions { max_samples_per_route: 1, hidden_values: vec!["Hidden".into()], ..Default::default() };+ let standin = capture(vec![operation("Hidden", 304, ""), operation("Hidden", 200, "ok")], &opts);+ assert_eq!(standin.routes[0].samples[0].request_key, None);+ let Answer::Found(found) = answer(&standin, &mut Turns::default(), "POST", "/graphql", "", br#"{"operationName":"Hidden"}"#) else {+ panic!("replacement used an unsanitized request key");+ };+ assert_eq!(found.body, b"ok");+}++#[test]+fn zero_and_single_sample_limits_remain_bounded() {+ for limit in [0, 1] {+ for status in [200, 304] {+ let opts = BuildOptions { max_samples_per_route: limit, ..Default::default() };+ let standin = capture(+ vec![entry("https://example.test/resource", 304, "", json!([])), entry("https://example.test/resource", status, "ok", json!([]))],+ &opts,+ );+ let route = &standin.routes[0];+ assert_eq!(route.samples.len(), limit);+ assert_eq!(route.samples_left_out, if limit == 0 { 2 } else { 1 });+ if limit == 1 {+ assert_eq!(route.samples[0].text.as_deref(), Some("ok"));+ assert_eq!(route.samples[0].was_not_modified, status == 304);+ let Answer::Found(found) = get(&standin, &mut Turns::default(), "/resource", "") else { panic!("missing replacement") };+ assert_eq!((found.status, found.body), (200, b"ok".to_vec()));+ }+ }+ }+}++#[test]+fn rejected_replacements_leave_budget_for_other_routes() {+ for (url, status, body) in [+ ("https://example.test/resource", 304, "long"),+ ("https://example.test/resource", 200, "long"),+ ("https://example.test/resource?other=true", 200, "no"),+ ] {+ let opts = BuildOptions { max_samples_per_route: 1, max_total_body_bytes: 2, ..Default::default() };+ let standin = capture(+ vec![+ entry("https://example.test/resource", 304, "", json!([{"name": "X-Request-Id", "value": "original"}])),+ entry(url, status, body, json!([])),+ entry("https://example.test/later", 200, "ok", json!([])),+ ],+ &opts,+ );+ let route = standin.routes.iter().find(|route| route.template == "/resource").unwrap();+ assert_eq!((route.requests, route.samples.len(), route.samples_left_out), (2, 1, 1));+ assert_eq!(route.samples[0].status, 304);+ assert_eq!(route.samples[0].body_left_out, Some(BodyLeftOut::NotRecorded));+ assert_eq!(route.samples[0].headers, vec![("X-Request-Id".into(), "original".into())]);+ assert_unavailable(get(&standin, &mut Turns::default(), "/resource", ""));+ let Answer::Found(found) = get(&standin, &mut Turns::default(), "/later", "") else { panic!("rejected sample used the remaining budget") };+ assert_eq!(found.body, b"ok");+ }+}++#[test]+fn a_repeat_at_capacity_preserves_the_304_without_charging_its_body() {+ for budget in [2, 4] {+ let opts = BuildOptions { max_samples_per_route: 2, max_total_body_bytes: budget, ..Default::default() };+ let usable = entry("https://example.test/resource", 200, "ok", json!([]));+ let mut entries = vec![entry("https://example.test/resource", 304, "", json!([])), usable.clone(), usable];+ if budget == 4 {+ entries.push(entry("https://example.test/later", 200, "zz", json!([])));+ }+ let standin = capture(entries, &opts);+ let route = standin.routes.iter().find(|route| route.template == "/resource").unwrap();+ assert_eq!((route.requests, route.samples.len()), (3, 2));+ assert_eq!(route.samples_left_out, 0);+ assert_eq!(route.samples[0].status, 304);+ assert_eq!(route.samples[1].text.as_deref(), Some("ok"));+ let mut turns = Turns::default();+ for _ in 0..3 {+ let Answer::Found(found) = get(&standin, &mut turns, "/resource", "") else { panic!("missing retained answer") };+ assert_eq!(found.body, b"ok");+ }+ if budget == 4 {+ let Answer::Found(found) = get(&standin, &mut Turns::default(), "/later", "") else { panic!("duplicate body was charged") };+ assert_eq!(found.body, b"zz");+ }+ }+}++#[test]+fn refused_bodies_keep_missing_evidence_and_count_headers_once() {+ let mut invalid = entry("https://example.test/resource", 200, "%%%", json!([]));+ invalid["response"]["content"]["encoding"] = json!("base64");+ let private_key_marker = ["PRIVATE ", "KEY-----"].concat();+ let cases = [+ (entry("https://example.test/resource", 200, "large", json!([])), BuildOptions { max_body_bytes: 1, ..Default::default() }),+ (invalid, BuildOptions::default()),+ (entry("https://example.test/resource", 200, &private_key_marker, json!([])), BuildOptions::default()),+ ];+ for (mut refused, mut opts) in cases {+ opts.max_samples_per_route = 1;+ refused["response"]["headers"] = json!([{"name": "Authorization", "value": "Bearer fake-token"}]);+ let standin =+ capture(vec![entry("https://example.test/resource", 304, "", json!([])), refused, entry("https://example.test/later", 200, "z", json!([]))], &opts);+ let route = standin.routes.iter().find(|route| route.template == "/resource").unwrap();+ assert_eq!((route.samples.len(), route.samples_left_out), (1, 1));+ assert_eq!(route.samples[0].body_left_out, Some(BodyLeftOut::NotRecorded));+ assert_eq!(standin.dropped.headers, 1);+ assert_unavailable(get(&standin, &mut Turns::default(), "/resource", ""));+ let Answer::Found(found) = get(&standin, &mut Turns::default(), "/later", "") else { panic!("a refused body consumed the budget") };+ assert_eq!(found.body, b"z");+ }+}diff --git a/crates/analysis/tests/regression_standin_sample_metadata.rs b/crates/analysis/tests/regression_standin_sample_metadata.rsnew file mode 100644index 00000000..6b871519--- /dev/null+++ b/crates/analysis/tests/regression_standin_sample_metadata.rs@@ -0,0 +1,62 @@+use craft_anything_analysis::standin::{Answer, BodyLeftOut, BuildOptions, StandIn, Turns, answer, build_from_bytes};+use serde_json::{Value, json};++fn entry(status: u16, mime: &str, body: &str, headers: Value) -> Value {+ json!({+ "request": {"method": "GET", "url": "https://example.test/resource"},+ "response": {"status": status, "headers": headers, "content": {"mimeType": mime, "text": body}}+ })+}++fn capture(entries: Vec<Value>, opts: &BuildOptions) -> StandIn {+ build_from_bytes(&serde_json::to_vec(&json!({"log": {"entries": entries}})).unwrap(), opts).unwrap()+}++#[test]+fn redirects_with_different_destinations_remain_separate_samples() {+ let make = |destination| entry(302, "text/plain", "", json!([{"name": "Location", "value": destination}]));+ let standin = capture(vec![make("/first"), make("/second")], &BuildOptions::default());+ assert_eq!(standin.routes[0].samples.len(), 2);+ let mut turns = Turns::default();+ for expected in ["/first", "/second"] {+ let Answer::Found(found) = answer(&standin, &mut turns, "GET", "/resource", "", b"") else {+ panic!("missing redirect");+ };+ let destination = found.headers.iter().find(|(name, _)| name.eq_ignore_ascii_case("location")).map(|(_, value)| value.as_str());+ assert_eq!(destination, Some(expected));+ }+}++#[test]+fn equal_bodies_with_different_content_types_remain_distinct() {+ let standin = capture(vec![entry(200, "application/json", "{}", json!([])), entry(200, "text/plain", "{}", json!([]))], &BuildOptions::default());+ assert_eq!(standin.routes[0].samples.len(), 2);+ assert_eq!(standin.routes[0].samples[0].content_type.as_deref(), Some("application/json"));+ assert_eq!(standin.routes[0].samples[1].content_type.as_deref(), Some("text/plain"));+}++#[test]+fn missing_bodies_keep_their_different_explanations() {+ let options = BuildOptions { max_body_bytes: 1, ..Default::default() };+ let standin = capture(vec![entry(200, "text/plain", "", json!([])), entry(200, "text/plain", "long", json!([]))], &options);+ assert_eq!(standin.routes[0].samples.len(), 2);+ assert_eq!(standin.routes[0].samples[0].body_left_out, Some(BodyLeftOut::NotRecorded));+ assert_eq!(standin.routes[0].samples[1].body_left_out, Some(BodyLeftOut::TooLarge));+}++#[test]+fn cached_304_bodies_keep_their_recorded_status_marker() {+ let standin = capture(vec![entry(200, "application/json", "{}", json!([])), entry(304, "application/json", "{}", json!([]))], &BuildOptions::default());+ let samples = &standin.routes[0].samples;+ assert_eq!(samples.len(), 2);+ assert_eq!((samples[0].status, samples[0].was_not_modified), (200, false));+ assert_eq!((samples[1].status, samples[1].was_not_modified), (200, true));+}++#[test]+fn identical_answers_still_collapse() {+ let one = entry(200, "application/json", "{}", json!([]));+ let standin = capture(vec![one.clone(), one], &BuildOptions::default());+ assert_eq!(standin.routes[0].requests, 2);+ assert_eq!(standin.routes[0].samples.len(), 1);+}diff --git a/crates/engine/src/inbox.rs b/crates/engine/src/inbox.rsindex 5797c441..c8c1ba26 100644--- a/crates/engine/src/inbox.rs+++ b/crates/engine/src/inbox.rs@@ -87,6 +87,12 @@ pub fn now_ms() -> u64 {SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)}+/// A number that never repeats within this process, for names that must stay unique even when+/// two are made in the same millisecond (or a name was just freed by deletion).+pub fn next_counter() -> u64 {+ COUNTER.fetch_add(1, Ordering::SeqCst)+}+/// Ids are `[0-9a-z-]` only, so they are always safe as file names.fn valid_id(id: &str) -> bool {!id.is_empty() && id.len() <= 64 && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')@@ -119,7 +125,7 @@ impl Inbox {action: Option<String>,) -> Result<String, ToolError> {std::fs::create_dir_all(&self.dir).map_err(|e| ToolError::io(self.dir.display(), e))?;- let n = COUNTER.fetch_add(1, Ordering::SeqCst);+ let n = next_counter();let id = format!("{}-{}-{n}", now_ms(), std::process::id());let req = Request { id: id.clone(), kind, title: title.to_string(), detail: detail.to_string(), choices, allow_text, action, created_ms: now_ms() };let bytes = serde_json::to_vec_pretty(&req).map_err(|e| ToolError::internal(e.to_string()))?;diff --git a/crates/engine/src/workspace.rs b/crates/engine/src/workspace.rsindex 5d858e0f..7075bd3f 100644--- a/crates/engine/src/workspace.rs+++ b/crates/engine/src/workspace.rs@@ -17,7 +17,7 @@//! already has their files, they're either the app itself (`app_in_root`: the builder edits them in//! place and the folders above sit beside them) or material to start from, with the app in app/.-use crate::inbox::now_ms;+use crate::inbox::{next_counter, now_ms};use crate::project::write_atomic;use crate::versioned::{self, upgrade};use craft_anything_evidence::{ErrorCode, ToolError};@@ -1147,7 +1147,7 @@ pub fn pasted_dir() -> PathBuf {dirs::cache_dir().or_else(|| dirs::home_dir().map(|h| h.join(".cache"))).unwrap_or_else(std::env::temp_dir).join("Craft Anything").join("pasted")}-/// Save a picture pasted from the clipboard (8-bit RGBA, `width`×`height`) as `pasted-<time>.png`+/// Save a picture pasted from the clipboard (8-bit RGBA, `width`×`height`) as `pasted-<time>-<n>.png`/// in `dir`, readable only by this person, where it waits until its message is sent (which/// copies it into the project). Pastes from earlier days are cleared out first, except those in/// `keep` (still attached to a draft or a message).@@ -1173,11 +1173,13 @@ pub fn save_pasted_picture(dir: &Path, width: u32, height: u32, rgba: Vec<u8>, klet _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));}forget_old_pastes(dir, keep);- // The name is taken with create_new, so two pastes (or two copies of the app) never share one.+ // The counter makes the name unique within this process, so a paste never reuses a name that+ // forget_old_pastes just freed in the same millisecond; create_new still guards two app copies.let ms = now_ms();+ let c = next_counter();let mut n = 1u32;let path = loop {- let path = if n == 1 { dir.join(format!("pasted-{ms}.png")) } else { dir.join(format!("pasted-{ms}-{n}.png")) };+ let path = if n == 1 { dir.join(format!("pasted-{ms}-{c}.png")) } else { dir.join(format!("pasted-{ms}-{c}-{n}.png")) };match std::fs::OpenOptions::new().write(true).create_new(true).open(&path) {Ok(_) => break path,Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists && n < 1000 => n = n.saturating_add(1),diff --git a/crates/platform/src/fs.rs b/crates/platform/src/fs.rsindex af7d4add..29413f4c 100644--- a/crates/platform/src/fs.rs+++ b/crates/platform/src/fs.rs@@ -25,12 +25,9 @@ fn write_impl(path: &Path, bytes: &[u8], private: bool) -> Result<(), ToolError>None => return Err(ToolError::invalid(format!("{} has no parent folder", path.display()))),};std::fs::create_dir_all(&dir).map_err(|e| ToolError::io(dir.display(), e))?;- let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "file".into());- let n = COUNTER.fetch_add(1, Ordering::Relaxed);- let tmp = dir.join(format!(".{name}.tmp-{}-{n}", std::process::id()));let existing_perms = std::fs::metadata(path).ok().map(|m| m.permissions());+ let (tmp, mut f) = create_temp(&dir, path, private, &COUNTER)?;let result = (|| {- let mut f = std::fs::File::create(&tmp).map_err(|e| ToolError::io(tmp.display(), e))?;if private {set_private(&tmp)?;} else if let Some(p) = existing_perms {@@ -47,6 +44,39 @@ fn write_impl(path: &Path, bytes: &[u8], private: bool) -> Result<(), ToolError>result}+/// Reserve a short, new temporary file before entering the cleanup scope. A collision belongs to+/// another write, so it must never be truncated or removed by this call.+fn create_temp(dir: &Path, destination: &Path, private: bool, counter: &AtomicU64) -> Result<(std::path::PathBuf, std::fs::File), ToolError> {+ let mut options = std::fs::OpenOptions::new();+ options.write(true).create_new(true);+ #[cfg(unix)]+ {+ use std::os::unix::fs::OpenOptionsExt as _;+ if private {+ options.mode(0o600);+ }+ }+ #[cfg(not(unix))]+ let _ = private;+ let destination_name = destination.file_name().and_then(|name| name.to_str());+ for _ in 0..64 {+ let n = counter.fetch_add(1, Ordering::Relaxed);+ let name = format!(".craft-anything.tmp-{}-{n}", std::process::id());+ // Conservatively exclude case-insensitive and Windows trailing-dot/space aliases.+ if destination_name.is_some_and(|destination| destination.trim_end_matches(['.', ' ']).eq_ignore_ascii_case(&name)) {+ continue;+ }+ let tmp = dir.join(name);+ match options.open(&tmp) {+ Ok(file) => return Ok((tmp, file)),+ Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,+ Err(error) => return Err(ToolError::io(tmp.display(), error)),+ }+ }+ let error = std::io::Error::new(std::io::ErrorKind::AlreadyExists, "could not reserve an unused temporary file");+ Err(ToolError::io(dir.display(), error))+}+/// On Windows a file another program has open for a moment (an antivirus scan, the search/// indexer) can't be replaced: try again briefly before giving up.fn rename_retrying(from: &Path, to: &Path) -> std::io::Result<()> {@@ -114,6 +144,44 @@ mod tests {assert_eq!(std::fs::read_dir(dir.path().join("sub")).unwrap().count(), 1);}+ #[cfg(unix)]+ #[test]+ fn temporary_file_creation_permissions_respect_private_flag() {+ use std::os::unix::fs::PermissionsExt as _;++ let dir = tempfile::tempdir().unwrap();+ let counter = AtomicU64::new(0);+ let destination = dir.path().join("settings.json");+ let (_, private) = create_temp(dir.path(), &destination, true, &counter).unwrap();+ // Observe the new file directly, before write_impl can call set_private.+ assert_eq!(private.metadata().unwrap().permissions().mode() & 0o077, 0);++ let regular = std::fs::File::create(dir.path().join("regular")).unwrap();+ let (_, non_private) = create_temp(dir.path(), &destination, false, &counter).unwrap();+ assert_eq!(non_private.metadata().unwrap().permissions().mode() & 0o777, regular.metadata().unwrap().permissions().mode() & 0o777);+ }++ #[test]+ fn temporary_candidates_exclude_destination_aliases() {+ let name = format!(".craft-anything.tmp-{}-0", std::process::id());+ for (component, next_counter) in [+ (name.clone(), 2),+ (name.to_ascii_uppercase(), 2),+ (format!("{name}. "), 2),+ (format!("{}. ", name.to_ascii_uppercase()), 2),+ ("settings.json".into(), 1),+ ] {+ let dir = tempfile::tempdir().unwrap();+ let counter = AtomicU64::new(0);+ let destination = dir.path().join(".").join(component);+ let (temporary, file) = create_temp(dir.path(), &destination, false, &counter).unwrap();+ assert!(!destination.exists());+ assert_eq!(counter.load(Ordering::Relaxed), next_counter);+ assert_eq!(temporary, dir.path().join(format!(".craft-anything.tmp-{}-{}", std::process::id(), next_counter - 1)));+ assert_eq!(file.metadata().unwrap().len(), 0);+ }+ }+#[test]fn backup_is_never_overwritten() {let dir = tempfile::tempdir().unwrap();diff --git a/crates/platform/tests/regression_atomic_temp_creation.rs b/crates/platform/tests/regression_atomic_temp_creation.rsnew file mode 100644index 00000000..83c01f9a--- /dev/null+++ b/crates/platform/tests/regression_atomic_temp_creation.rs@@ -0,0 +1,89 @@+use craft_anything_platform::fs::write_atomic;+#[cfg(unix)]+use craft_anything_platform::fs::write_atomic_private;+use std::path::{Path, PathBuf};++fn temporary(dir: &Path, counter: u64) -> PathBuf {+ dir.join(format!(".craft-anything.tmp-{}-{counter}", std::process::id()))+}++#[test]+fn atomic_writes_preserve_colliding_files_and_links() {+ let dir = tempfile::tempdir().unwrap();+ let target = dir.path().join("settings.json");+ let stale: Vec<_> = (0..4).map(|n| temporary(dir.path(), n)).collect();+ for file in &stale {+ std::fs::write(file, b"existing temporary data").unwrap();+ }+ write_atomic(&target, b"new settings").unwrap();+ assert_eq!(std::fs::read(&target).unwrap(), b"new settings");+ for file in &stale {+ assert_eq!(std::fs::read(file).unwrap(), b"existing temporary data");+ }++ #[cfg(unix)]+ {+ use std::os::unix::fs::{PermissionsExt, symlink};+ let private_dir = tempfile::tempdir().unwrap();+ let other = private_dir.path().join("other.txt");+ std::fs::write(&other, b"keep this file").unwrap();+ let links: Vec<_> = (0..16).map(|n| temporary(private_dir.path(), n)).collect();+ for link in &links {+ symlink(&other, link).unwrap();+ }+ let private = private_dir.path().join("private.json");+ write_atomic_private(&private, b"private fixture").unwrap();+ assert_eq!(std::fs::read(&other).unwrap(), b"keep this file");+ assert_eq!(std::fs::read(&private).unwrap(), b"private fixture");+ assert_eq!(std::fs::metadata(&private).unwrap().permissions().mode() & 0o777, 0o600);+ assert!(links.iter().all(|link| std::fs::symlink_metadata(link).unwrap().file_type().is_symlink()));++ std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o640)).unwrap();+ write_atomic(&target, b"replacement settings").unwrap();+ assert_eq!(std::fs::metadata(&target).unwrap().permissions().mode() & 0o777, 0o640);+ }++ // A bounded retry must leave both the destination and every colliding file alone.+ let crowded_dir = tempfile::tempdir().unwrap();+ let destination = crowded_dir.path().join("crowded.json");+ std::fs::write(&destination, b"original settings").unwrap();+ let occupied: Vec<_> = (0..256).map(|n| temporary(crowded_dir.path(), n)).collect();+ for file in &occupied {+ std::fs::write(file, b"someone else's temporary data").unwrap();+ }+ assert!(write_atomic(&destination, b"replacement").is_err());+ assert_eq!(std::fs::read(&destination).unwrap(), b"original settings");+ for file in &occupied {+ assert_eq!(std::fs::read(file).unwrap(), b"someone else's temporary data");+ }++ // An error after creating our temporary file cleans up only that new file.+ let blocked_dir = tempfile::tempdir().unwrap();+ let blocked = blocked_dir.path().join("directory.json");+ std::fs::create_dir(&blocked).unwrap();+ let mut before: Vec<_> = std::fs::read_dir(blocked_dir.path()).unwrap().map(|entry| entry.unwrap().path()).collect();+ before.sort();+ assert!(write_atomic(&blocked, b"cannot replace a directory").is_err());+ let mut after: Vec<_> = std::fs::read_dir(blocked_dir.path()).unwrap().map(|entry| entry.unwrap().path()).collect();+ after.sort();+ assert_eq!(after, before);++ // Probe at most 255 names, retaining the longest this filesystem can create.+ let long_dir = tempfile::tempdir().unwrap();+ let mut long_target = None;+ for length in (1..=255).rev() {+ let path = long_dir.path().join("s".repeat(length));+ match std::fs::write(&path, b"original long-name settings") {+ Ok(()) => {+ long_target = Some(path);+ break;+ }+ Err(error) if error.kind() == std::io::ErrorKind::InvalidFilename => continue,+ Err(error) => panic!("could not create the long-name fixture: {error}"),+ }+ }+ let long_target = long_target.expect("the test filesystem must support a destination filename");+ write_atomic(&long_target, b"replacement long-name settings").unwrap();+ assert_eq!(std::fs::read(&long_target).unwrap(), b"replacement long-name settings");+ assert_eq!(std::fs::read_dir(long_dir.path()).unwrap().count(), 1);+}diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex c9d7adf1..4c5b81c3 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -734,6 +734,8 @@ Gaps found while using the app for real projects.- [x] Agent paragraphs with glossary terms and long file links wrap together without pushingtheir card or later messages under the sidebar (#523); Project and Ask bounds checked at two sizes— claimed: carl-dourado, branch hotfix/r2.9-523-message-width+- [x] Create atomic-write temporary files exclusively with short names distinct from the destination and private Unix permissions from creation.+ — claimed: Afloat16, branch bugfix/r2.9-atomic-temp-creation-20261103b- [x] A prompt brought back with Up keeps its pictures (their paths are absolute, so they don'tcome back after the project is moved)- [ ] Change a project's builder from its page (a tool, so the CLI and MCP can too) — in PR #245@@ -909,6 +911,16 @@ Owner: open · Status: in progress- [ ] Bun: take source maps and bytecode out as files; a standalone `.pyz`- [ ] `native_source_folder_write` uses the built-in decompiler only: use Ghidra in Deep mode whenit's there+- [x] Keep stand-in response samples distinct when headers, content types or body-availability metadata differ.+ Compare header names without case and ignore ordering between different names, preserving each name's value order.+ At the sample cap, a usable answer can replace an unavailable 304 for the same path, query and request key;+ other requests keep their missing-body evidence. Refused bodies cannot replace that evidence.+ Compare complete samples before charging retained bytes, using #717's retained-budget accounting.+ Historical revision `f79dc0bd` passed [full Linux CI](https://github.com/storytold/craft-anything/actions/runs/41793241151):+ all five original metadata regressions and nine header and capacity regressions passed.+ All 24 combined replay regressions pass locally on the refresh onto `cf414ff4`.+ See this PR's checks for the refreshed revision's complete gate.+ — claimed: Afloat16, branch bugfix/r3.11-standin-sample-metadata-20261103b- [ ] `native_publisher_show` hashes the file minus the signature fields, not section by section;a file with unusual gaps between sections can read as different- [x] Enforce stand-in per-body and total byte budgets on the text that is actually retained after redaction;diff --git a/docs/STATUS.md b/docs/STATUS.mdindex 12e66e12..a268fdbd 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -42,6 +42,7 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi| Java decompilation | `java_vineflower_decompile` decompiles a real JAR to source with the pinned Vineflower 1.12.0, run through the configured Java | Live run on Linux x86-64 (OpenJDK 21.0.12.1) against Apache Commons IO 2.16.1 (497 KB, 374 entries): 253 source files, exit 0; `org.apache.commons.io.FileUtils` returned 1,350 lines with the class and its file-reading methods present. The engine install matched the pinned SHA-256. Not checked: Windows and macOS, a `.class` input, or a second JAR || Conversation width | Agent paragraphs, inline code and fenced code stay within the message column, including glossary terms followed by long file links (#523) | UI regression checks painted text and subsequent answers against the composer bounds in Project and Ask at 1920 × 1032 and 1280 × 820; Unicode/formatted glossary hover check || Settings saved on exit | Pending app settings merge the session's latest AI table when its guard is available. A busy session defers non-AI edits in `config.pending.toml` without waiting for the tool; startup recovers them with the latest committed AI table | Isolated child-process regression exercises idle and busy exit saves, a late AI commit, startup recovery and pending non-AI edits; engine tests cover sidecar migrations and damaged/newer files. No live desktop shutdown was exercised |+| Atomic-write temporary files | Reserve short temporary names distinct from the destination and its filename aliases, with exclusive creation and bounded collision retries. Private files have owner-only Unix permissions from creation; cleanup removes only a file reserved by the current write. | Original implementation `5f0f1ce2` passed [full Linux CI](https://github.com/storytold/craft-anything/actions/runs/41687019068). The review follow-up preserves collision, symlink, inherited-permission, retry-limit and cleanup assertions, and adds a bounded probe for a valid long name, direct creation-permission checks and deterministic destination-alias exclusion checks. `27e5d631` passed [full Linux CI](https://github.com/storytold/craft-anything/actions/runs/41792023953). || SQLite payload limits | Capped records retain column positions, disclose partial TEXT and BLOB values, omit incomplete BLOB hashes, and report partial coverage with read notes | Hand-built overflow-page regressions for five oversized records (including WITHOUT ROWID in declaration order) and two controls; table and index engine coverage and limitation regressions || SQLite added columns | Short records include missing trailing fields using literal column defaults, or NULL when absent; unsupported default expressions produce NULL with a row note. Stored fields and records longer than the schema retain their values. Defaults are filled before restoring rowid aliases | Nine hand-built parser regressions and an engine tool test cover added-column defaults, rewritten records and short records with a rowid alias, including a missing alias field || OpenCode models and thinking | OpenCode V2 locally and over SSH; Settings → AI lists only that instance's enabled chat models and supported Low/Medium/High/Xhigh/Max variants. Selection is validated and saved through UI, CLI and `ai_models_list` / `ai_model_set`. Explicit selections run natively with the Craft Anything MCP server (local runs; none over SSH yet). See [OpenCode](opencode.md). | Stand-in catalogue/process, persistence, remote-command and UI tests; local live catalogue checks (34 models, all five depths represented). Regression checks route explicit selections natively and parse V2 tool events. Live (2026-11-04, Windows, OpenCode 2.2.5, opencode-go/deepseek-v4.1-flash): a `--standalone` run connected the server (38 tools) and called `core_session_show`. No live SSH host or paid generation used |@@ -66,6 +67,8 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi| Program facts across builds | `native_library_calls_list` (delay-load too), `native_offered_symbols_list`, `native_publisher_show` (checks the file hash and the signature, not Windows trust), `app_builds_line_up` pairs functions across two builds and says how, `native_source_folder_write` writes pseudo-C to a folder and picks up where it stopped, `android_components_list` | Unit tests. Real PE, ELF and Mach-O files; two builds of a 276 MB program; a signed Microsoft DLL; Android components from one real APK, spot-checked || ARM32 value flow | A32 and Thumb calls define ARM scratch registers, and word results flow through `r0` into returns in `native_value_flow_show`. Conditional A32 calls retain the earlier value when skipped and a possible returned result; calls to known non-returning targets keep only the skipped path | Synthetic instruction fixtures for leaf results and indirect calls in both modes, with AArch64 and x86-64 controls; direct and indirect A32 conditional calls within and across basic blocks, including a named `abort` target and unconditional controls. This correction was not checked on real ARM binaries or devices || Stand-in backends | `web_standin_build` turns a HAR into `standin.json` (secrets dropped, varying path parts templated); `web_standin_start` answers from it on loopback; `web_standin_show` lists what it had no answer for. A 304 without a usable cached body is counted at build time and skipped during replay; if its matching group has no usable answer, requests get a 404 with `cached_body_unavailable`, also shown in the request log. Writes replay what was recorded and don't change later reads. Older saved query variants keep explicit empty pairs when credential rules are reapplied; raw separators remain ignored and the 200-pair limit matches capture. App maps list GraphQL and tRPC operations; `web_walkthrough_check` checks a scripted session without a browser | Unit tests, real loopback requests, and a run with curl on a hand-written HAR. The 304 correction passes 99 analysis tests and a real-loopback regression, covering mixed samples, omitted bodies, matching boundaries and existing v1 files. [Hosted CI for #543](https://github.com/storytold/craft-anything/actions/runs/41585168291) also passed the full engine tests and workspace gates. Public capture/replay regressions cover legacy empty pairs, raw separators and the query-pair limit. No browser-made recording or real front end yet |+| Stand-in sample metadata | Consecutive samples compare all response fields before retained bytes are charged. Header comparison ignores name case and ordering between different names, while preserving repeated-value order and the stored headers. At capacity, a usable response replaces only an unavailable 304 for the same path, query and request key; refused bodies preserve existing evidence. | All 24 combined replay regressions pass locally on the refresh onto `cf414ff4`. The same replay implementation and four regression files passed in [frozen candidate `8758b6df`](https://github.com/Afloat16/craft-anything/actions/runs/41833977848) on base `b2d7e89e`. Historical standalone revision `f79dc0bd` passed its 14 metadata and header/capacity regressions in [full Linux CI](https://github.com/storytold/craft-anything/actions/runs/41793241151). See this PR's checks for the current revision's complete gate. |+| Websites as targets | `web_site_open` keeps a private browser for the session and deletes its temporary profile when the browser closes or fails to start; every browser tool inspects that page; `web_site_capture` records screenshots at each width (desktop, tablet and phone), rendered HTML, design tokens (colours in hex, spacing, content widths), the CSS breakpoints, the layout at each width (page width, heading sizes, each section's padding, gap, content column and items per row), page health (script and console errors, failed requests) and an accessibility outline, layout outline, assets with font files and requests, links and form outlines. In Clean room the capture keeps only what a visitor sees (no HTML, CSS rules, scripts, requests or errors), and opening a site reports no load errors | Live runs on example.com and a local page with Chromium on Linux, including profile cleanup after success and failed startup; unit tests. Brave on macOS was not run || Websites as targets | `web_site_open` keeps a private browser for the session and deletes its temporary profile when the browser closes or fails to start; every browser tool inspects that page; `web_site_capture` records screenshots at each width (desktop, tablet and phone), rendered HTML, design tokens (colours in hex, spacing, content widths), the CSS breakpoints, the layout at each width (page width, heading sizes, each section's padding, gap, content column and items per row), page health (script and console errors, failed requests) and an accessibility outline, layout outline, assets with font files and requests, links and form outlines. In Clean room the capture keeps only what a visitor sees (no HTML, CSS rules, scripts, requests or errors), and opening a site reports no load errors. The Flatpak build can't start a browser on the computer (#841) | Live runs on example.com and a local page with Chromium on Linux, including profile cleanup after success and failed startup; unit tests. Brave on macOS was not run || Electron window comparisons | `app_graphs_compare` retains every unassigned window and every construction with a reused local binding. Windows are paired by module, binding and occurrence, so inserting comments does not hide preference changes. Colliding display labels receive a separate `#N` suffix without changing literal binding names or occurrence indices | Synthetic applications parsed through the ordinary analyzer exercise anonymous and reused bindings, shifted source lines, unequal counts, literal names resembling occurrence or collision suffixes, and stable labels when only one window changes. Pairing remains positional within each binding group; reordered constructions and real application releases were not checked for this correction || Rebuild workflow (Study → Build → Check → Refine) | `crates/ai/src/rebuild/` (kinds, checks and stacks are pluggable: docs/extending.md). Three kinds: website, app, game (a project whose stack is a game engine is always a game). The request decides how to build: a language, framework, engine or platform it names wins over the kind's default stack (Rust + egui for apps, Unity for games, the original's for websites), and the build check, the recorded stack and Play follow what was built (an Electron app opens in its own Electron; a plain static site has nothing to build and passes the build check as it is). Websites: Study also captures up to 4 other pages of the site; menus are opened on a computer and on a phone; the check serves the build on loopback and compares every page at 1440, 768 and 390 px (likeness = mean of layout and perceptual detail, SSIM, averaged over pages, leaving out the parts of the original that change by themselves, found by photographing it three times; the note adds text, page structure, the colours, font, text sizes and spacing the build misses, and per width a page that scrolls sideways, heading sizes and sections whose padding, items per row or content column differ, the errors, failed requests and accessibility gaps the build adds, and the opened menus and pop-ups). A stack or library named in the request (Next.js, shadcn/ui, Tailwind CSS…, `stacks.toml`) is what the builder uses; with none named, a website's stack is the builder's choice (told to match what the original is built with) and the stack it used is recorded from app/package.json. The builder leads: it studies, asks the tools follow-up questions, records what it can't find out as unknowns (`core_unknown_add`; the run reports the open ones), and tests its own build mid-turn with `rebuild_check` (the same checks, for every kind); a check with anything it couldn't compare, or any claim that fails (a website page that scrolls sideways, logs new errors, fails to load a file, lacks a landmark, or a menu that doesn't open; for games each self-test step, for Deep-mode sheets each original number in the code, for console apps the same exit and output as the original's runs), isn't good enough; apps and games by whether they build. Up to 6 refinement rounds, or until a website reaches 90% likeness. A turn cut off by a time limit, crash or dropped connection resumes (up to 3 times); builder turns may run 24 h. A project copied from another computer (or moved to another folder) keeps building with Claude Code: the project keeps a copy of the builder's session (`agent-session.jsonl`) after every turn and puts it back where Claude Code finds it on a computer without it, so the same conversation carries on (#451); when the session still isn't there, a new one starts from the brief, what's in app/ and the kept requests and replies (or the last summary), and questions about the build put the kept session back too, else are answered from the files and forget the missing session (#452). Live runs with Claude Code 2.1.316 on one Mac (2026-11-02), a second computer stood in for by a separate signed-in `CLAUDE_CONFIG_DIR`: a copied project's session was put back and resumed (the builder recalled its first reply from memory); a kept copy of another session was refused and the new session used the handoff; a real project synced from Windows whose session was missing started afresh and reached Ready. Not yet run between two real computers | Unit tests for prompts, stack choice, site detection, feed folding; live runs reached Build and decompiling (below) |diff --git a/docs/pitfalls.md b/docs/pitfalls.mdindex 028ea7c3..19fc3200 100644--- a/docs/pitfalls.md+++ b/docs/pitfalls.md@@ -422,6 +422,14 @@ navigation vanished from the run's network capture. Only the code that owns a rudrains its event queue; steps leave events where they are, and the run keeps them all, taggedwith the step they arrived in.+**Exclusive creation left a permission window.** Opening a private temporary file with default+permissions could let another process retain a readable descriptor before a later chmod. Set+mode 0600 in the first Unix open for private files. Temporary names must also stay short and+independent of the destination name: adding a prefix and suffix can exceed the component limit+even when the destination name is valid. Keep the temporary file in the destination directory,+but exclude the destination component before creating a candidate, including case and trailing+dot/space aliases. Probe a supported long name in tests instead of assuming a fixed filename limit.+**Two writers to one file.** The app and the rebuild run both wrote `feed.json`. Give each persistedfile one owner; when another writer is unavoidable (an answer given from the CLI while a run isgoing), merge what's on disk before saving instead of overwriting it.@@ -620,6 +628,15 @@ broke, and "Basic Membership" lost a word. It also tested whole tokens, so a secafter `ref=` passed. Test a scrubber on what must survive as well as what must go, and on eachkind of content it can receive.+**Response metadata that fills a replay limit.** Comparing stored HTTP headers literally kept+equivalent polls apart: names ignore case, and only values for the same name retain order.+Compare that way without rewriting the saved headers. Unavailable 304 samples still prove which+request lacked a cached body. At capacity, replace one only with a usable response for the same+path, query and request key, then append it in recording order. Keep other requests' evidence,+count the displaced sample, and do not replace anything with a body refused by a size or secret+check. Compare complete samples before charging retained bytes, so repeats need no refund. Test an+exact total-body limit and one with room remaining, preserving the unavailable 304 and remaining budget.+**A strict tool that sent an AI off to write its own.** `game_pak_extract` refused an outputwhose folder didn't exist and took one file per call; the extractor model hit that twice, thenwrote its own pak reader in Python for a large archive. Tools an AI drives make what they