Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(consolidate): preserve concurrent edits during cold-page merges
Samir Hanna Verzaad89edf3bae3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e65cba04..94d6c539 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,9 @@ version in [`docs/changelog/`](docs/changelog/):### Fixed+- Kept concurrent page edits current during opt-in cold-cluster dedup and dream+ merges. Each write batch now skips if a selected source version changed,+ preserving the newer body, tier and pin along with unchanged peers (#PR).- Refused empty and whitespace-only `--workspace` and `--project` flags at theshared CLI scope-resolution choke point (`resolve_scope`,`resolve_scope_noting_marker_project`, `resolve_scope_with_marker`, anddiff --git a/crates/ai-memory-consolidate/src/dream.rs b/crates/ai-memory-consolidate/src/dream.rsindex 17d103da..82962ebb 100644--- a/crates/ai-memory-consolidate/src/dream.rs+++ b/crates/ai-memory-consolidate/src/dream.rs@@ -24,7 +24,9 @@//! consolidator's dry run.//! - **Gated apply.** Each survivor rewrite runs `preflight_admission`//! (`AdmissionOp::Consolidate`) before the LLM and writes through-//! `Wiki::apply_batch` (single-writer actor, invariant #2).+//! `Wiki::apply_batch_if` (single-writer actor, invariant #2). If any source+//! changed since selection, the whole cluster is skipped, preserving newer+//! edits and leaving the other members untouched.//! - **JSON-schema structured output only** (invariant #7): [`DreamMergedPage`].//! - **Bounded + cancellable** (invariant #5 spirit): at most//! [`DreamConfig::max_clusters_per_run`] clusters per run, and a cheap@@ -48,8 +50,10 @@ use ai_memory_llm::{ChatMessage, ChatRequest, LlmOperationId, LlmProvider, LlmWorkload, Role,complete_structured_with_operation_id,};-use ai_memory_store::{DecayParams, ReaderPool};-use ai_memory_wiki::{AdmissionContext, AdmissionOp, Wiki, WritePageRequest};+use ai_memory_store::{DecayParams, PagePrecondition, ReaderPool};+use ai_memory_wiki::{+ AdmissionContext, AdmissionOp, ConditionalBatchWrite, Wiki, WritePageRequest,+};use schemars::JsonSchema;use serde::{Deserialize, Serialize};use thiserror::Error;@@ -566,7 +570,7 @@ enum MergeOutcome {Skipped,}-/// Merge one selected cluster: preflight admission → LLM rewrite → `apply_batch`+/// Merge one selected cluster: preflight admission → LLM rewrite → `apply_batch_if`/// (survivor rewrite + loser merge-note supersessions). Any failure at any step/// skips the cluster without touching a source.async fn merge_one_cluster(@@ -774,16 +778,33 @@ async fn merge_one_cluster(// Gated apply, part 2: one batched write through the single-writer actor// (invariant #2). Survivor is request 0.let superseded = plan.losers.len();- match wiki.apply_batch(requests).await {- Ok(new_ids) => match new_ids.first().copied() {+ // Selection predates the LLM call. Compare every source version while the+ // wiki holds the page locks, so a fresh correction to either the survivor+ // or a loser refuses the whole cluster, including its unchanged peers.+ let source_ids = std::iter::once(survivor.id).chain(plan.losers.iter().map(|loser| loser.id));+ let conditional = requests+ .into_iter()+ .zip(source_ids.map(PagePrecondition::Latest))+ .collect();+ match wiki.apply_batch_if(conditional).await {+ Ok(ConditionalBatchWrite::Written(new_ids)) => match new_ids.first().copied() {Some(new_survivor_id) => MergeOutcome::Applied {new_survivor_id,superseded,},None => MergeOutcome::Skipped,},+ Ok(ConditionalBatchWrite::Mismatch { index, current }) => {+ tracing::debug!(+ path = %survivor.path.as_str(),+ index,+ ?current,+ "dream pass: source changed during merge; skipping cluster"+ );+ MergeOutcome::Skipped+ }Err(error) => {- tracing::warn!(path = %survivor.path.as_str(), %error, "dream pass: apply_batch failed; skipping cluster (retried next run)");+ tracing::warn!(path = %survivor.path.as_str(), %error, "dream pass: apply_batch_if failed; skipping cluster (retried next run)");MergeOutcome::Skipped}}diff --git a/crates/ai-memory-consolidate/src/sweep.rs b/crates/ai-memory-consolidate/src/sweep.rsindex baab71d4..79aa7d50 100644--- a/crates/ai-memory-consolidate/src/sweep.rs+++ b/crates/ai-memory-consolidate/src/sweep.rs@@ -505,6 +505,8 @@ pub async fn run_sweep_with_compaction(/// [`run_sweep_with_compaction`]. With no embeddings for the configured triple —/// or no embedder configured at all — A3 is a clean no-op (invariant #13: it/// reads only already-stored vectors, never a provider).+/// The whole dedup batch is conditional on the selected source versions: a+/// concurrent edit leaves every planned merge unapplied for this sweep.////// # Errors/// Same as [`run_sweep_with_options`].@@ -731,8 +733,8 @@ pub(crate) async fn run_sweep_at(match wiki {Some(wiki) => {let requests = std::mem::take(&mut dedup_requests);- match wiki.apply_batch(requests).await {- Ok(new_ids) => {+ match wiki.apply_batch_if(requests).await {+ Ok(ConditionalBatchWrite::Written(new_ids)) => {for (cluster, &req_idx) inmerged.iter_mut().zip(dedup_survivor_req_index.iter()){@@ -740,6 +742,13 @@ pub(crate) async fn run_sweep_at(cluster.new_survivor_id = new_ids.get(req_idx).copied();}}+ Ok(ConditionalBatchWrite::Mismatch { index, current }) => {+ tracing::debug!(+ index,+ ?current,+ "forget sweep: source changed during dedup; skipping batch"+ );+ }Err(error) => tracing::warn!(%error,"forget sweep: cold-cluster dedup batch failed; retrying on next sweep"@@ -1224,7 +1233,7 @@ pub(crate) async fn materialize_cold_set(struct DedupPlan {report: Vec<MergedCluster>,claimed: HashSet<PageId>,- requests: Vec<WritePageRequest>,+ requests: Vec<(WritePageRequest, PagePrecondition)>,/// For each entry in `report`, the index into `requests` of that cluster's/// survivor write, so the applied `new_survivor_id` can be mapped back.survivor_req_index: Vec<usize>,@@ -1355,7 +1364,7 @@ async fn plan_cold_cluster_dedup(};let mut union_body = survivor_md.body.clone();let mut loser_paths: Vec<String> = Vec::new();- let mut loser_requests: Vec<WritePageRequest> = Vec::new();+ let mut loser_requests: Vec<(WritePageRequest, PagePrecondition)> = Vec::new();let mut evidence: Vec<PageEvidence> = Vec::new();let mut read_failed = false;for (pos, member) in member_entries.iter().enumerate() {@@ -1408,20 +1417,23 @@ async fn plan_cold_cluster_dedup("merged_into".to_string(),serde_json::Value::String(survivor.path.as_str().to_string()),);- loser_requests.push(WritePageRequest {- workspace_id,- project_id,- path: member.path.clone(),- frontmatter: serde_json::Value::Object(stub_fm),- body: stub_body,- tier: Tier::Episodic,- pinned: false,- title: None,- admission_ctx: None,- author_id: None,- actor: ActorContext::anonymous(),- evidence: Vec::new(),- });+ loser_requests.push((+ WritePageRequest {+ workspace_id,+ project_id,+ path: member.path.clone(),+ frontmatter: serde_json::Value::Object(stub_fm),+ body: stub_body,+ tier: Tier::Episodic,+ pinned: false,+ title: None,+ admission_ctx: None,+ author_id: None,+ actor: ActorContext::anonymous(),+ evidence: Vec::new(),+ },+ PagePrecondition::Latest(member.id),+ ));}if read_failed || loser_paths.is_empty() {continue;@@ -1466,7 +1478,8 @@ async fn plan_cold_cluster_dedup(// Record. Survivor write goes first in this cluster's slice, so its// index is the current request length.let survivor_req_index = plan.requests.len();- plan.requests.push(survivor_request);+ plan.requests+ .push((survivor_request, PagePrecondition::Latest(survivor.id)));plan.requests.extend(loser_requests);plan.claimed.insert(survivor.id);for member in &member_entries {diff --git a/crates/ai-memory-consolidate/tests/suite/cold_cluster_sweep.rs b/crates/ai-memory-consolidate/tests/suite/cold_cluster_sweep.rsindex f9703a42..05c9a624 100644--- a/crates/ai-memory-consolidate/tests/suite/cold_cluster_sweep.rs+++ b/crates/ai-memory-consolidate/tests/suite/cold_cluster_sweep.rs@@ -244,6 +244,203 @@ const DUP_B: &str = "Investigated the flaky retention sweep test failure again aconst FAR: &str = "Kubernetes pod scheduling node selector affinity rules for the cluster \autoscaler deployment on the staging namespace.";+async fn concurrent_member_write_skips_dedup_batch(edit_survivor: bool) {+ use ai_memory_wiki::{AdmissionChain, AdmissionOp, FailurePolicy, WebhookConfig};+ use std::io::{Read, Write};++ let fx = seed_fixture(true).await;+ write(&fx, "sessions/a.md", DUP_A).await;+ write(&fx, "sessions/b.md", DUP_B).await;+ for path in ["sessions/a.md", "sessions/b.md"] {+ backdate_latest(&fx, path, COLD_DAYS);+ }+ let params = DecayParams::default();+ let plan = run_sweep_with_hygiene(+ &fx.store.reader,+ &fx.store.writer,+ Some(&fx.wiki),+ fx.ws,+ fx.proj,+ ¶ms,+ 0.0,+ ObservationRetention::default(),+ false,+ dedup_on(),+ true,+ )+ .await+ .unwrap();+ assert_eq!(plan.merged.len(), 1);+ let cluster = &plan.merged[0];+ let (edited_path, peer_path) = if edit_survivor {+ (&cluster.survivor, &cluster.merged[0])+ } else {+ (&cluster.merged[0], &cluster.survivor)+ };+ let peer_body = latest_body(&fx, peer_path);+ let peer_id = fx+ .store+ .reader+ .latest_page_id_by_ids(fx.ws, fx.proj, peer_path.clone())+ .await+ .unwrap();++ // Both replacements have been derived when the first admission request+ // arrives. Land a real Wiki edit before the batch obtains any page lock.+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let url = format!("http://{}", listener.local_addr().unwrap());+ let (started_tx, started_rx) = tokio::sync::oneshot::channel();+ let (release_tx, release_rx) = std::sync::mpsc::channel();+ let server = std::thread::spawn(move || {+ let mut first = Some(started_tx);+ for _ in 0..2 {+ let (mut stream, _) = listener.accept().unwrap();+ stream+ .set_read_timeout(Some(std::time::Duration::from_secs(10)))+ .unwrap();+ let mut bytes = Vec::new();+ let mut buf = [0_u8; 4096];+ let header_end = loop {+ if let Some(pos) = bytes.windows(4).position(|window| window == b"\r\n\r\n") {+ break pos + 4;+ }+ let read = stream.read(&mut buf).unwrap();+ assert!(read > 0);+ bytes.extend_from_slice(&buf[..read]);+ };+ let headers = String::from_utf8_lossy(&bytes[..header_end]).to_lowercase();+ let length = headers+ .lines()+ .find_map(|line| line.strip_prefix("content-length:"))+ .unwrap()+ .trim()+ .parse::<usize>()+ .unwrap();+ while bytes.len() < header_end + length {+ let read = stream.read(&mut buf).unwrap();+ assert!(read > 0);+ bytes.extend_from_slice(&buf[..read]);+ }+ if let Some(started) = first.take() {+ started.send(()).unwrap();+ release_rx+ .recv_timeout(std::time::Duration::from_secs(10))+ .unwrap();+ }+ stream+ .write_all(+ b"HTTP/1.1 204 No Content\r\ncontent-length: 0\r\nconnection: close\r\n\r\n",+ )+ .unwrap();+ }+ });+ let sweep_wiki = fx.wiki.clone().with_admission_chain(+ AdmissionChain::new(vec![WebhookConfig {+ name: "pause-stale-dedup".into(),+ url,+ timeout_ms: 15_000,+ failure_policy: FailurePolicy::Reject,+ events: vec![AdmissionOp::WritePage],+ blocking: true,+ }])+ .unwrap(),+ );+ let sweep = run_sweep_with_hygiene(+ &fx.store.reader,+ &fx.store.writer,+ Some(&sweep_wiki),+ fx.ws,+ fx.proj,+ ¶ms,+ 0.0,+ ObservationRetention::default(),+ false,+ dedup_on(),+ false,+ );+ let fresh_body = "Fresh human correction: this page is current, semantic and pinned.";+ let update = async {+ tokio::time::timeout(std::time::Duration::from_secs(10), started_rx)+ .await+ .unwrap()+ .unwrap();+ let fresh_id = fx+ .wiki+ .write_page(WritePageRequest {+ workspace_id: fx.ws,+ project_id: fx.proj,+ path: PagePath::new(edited_path.clone()).unwrap(),+ frontmatter: serde_json::json!({"title": "Fresh correction"}),+ body: fresh_body.into(),+ tier: Tier::Semantic,+ pinned: true,+ title: Some("Fresh correction".into()),+ admission_ctx: None,+ author_id: None,+ actor: ActorContext::anonymous(),+ evidence: Vec::new(),+ })+ .await+ .unwrap();+ release_tx.send(()).unwrap();+ fresh_id+ };+ let (report, fresh_id) = tokio::join!(sweep, update);+ server.join().unwrap();+ let report = report.unwrap();+ assert_eq!(report.merged.len(), 1);+ assert!(!report.merged[0].applied, "the stale batch must not land");+ assert_eq!(report.merged[0].new_survivor_id, None);+ assert!(+ report.evicted.is_empty(),+ "no fallback deletion of selected pages"+ );+ assert!(report.compacted.is_empty());++ for (path, expected_body, expected_id) in [+ (edited_path, fresh_body, Some(fresh_id)),+ (peer_path, peer_body.as_str(), peer_id),+ ] {+ assert_eq!(latest_body(&fx, path), expected_body);+ assert_eq!(+ fx.wiki+ .read_page(fx.ws, fx.proj, &PagePath::new(path.clone()).unwrap())+ .unwrap()+ .body,+ expected_body+ );+ assert_eq!(+ fx.store+ .reader+ .latest_page_id_by_ids(fx.ws, fx.proj, path.clone())+ .await+ .unwrap(),+ expected_id+ );+ }+ let conn = rusqlite::Connection::open(fx.tmp.path().join("db/memory.sqlite")).unwrap();+ let metadata: (String, bool) = conn+ .query_row(+ "SELECT tier, pinned FROM pages WHERE id = ?1",+ params![fresh_id.as_bytes()],+ |row| Ok((row.get(0)?, row.get(1)?)),+ )+ .unwrap();+ assert_eq!(metadata, ("semantic".to_string(), true));+ assert!(superseded_bodies(&fx, peer_path).is_empty());+ assert_eq!(superseded_bodies(&fx, edited_path).len(), 1);+}++#[tokio::test]+async fn concurrent_survivor_write_skips_dedup_batch() {+ concurrent_member_write_skips_dedup_batch(true).await;+}++#[tokio::test]+async fn concurrent_loser_write_skips_dedup_batch() {+ concurrent_member_write_skips_dedup_batch(false).await;+}+/// Flag OFF: nothing clusters or merges — byte-identical to before A3.#[tokio::test]async fn flag_off_never_merges() {diff --git a/crates/ai-memory-consolidate/tests/suite/dream_pass.rs b/crates/ai-memory-consolidate/tests/suite/dream_pass.rsindex fb4324af..f7d30b13 100644--- a/crates/ai-memory-consolidate/tests/suite/dream_pass.rs+++ b/crates/ai-memory-consolidate/tests/suite/dream_pass.rs@@ -47,6 +47,7 @@ struct FakeMergeLlm {calls: Arc<AtomicUsize>,saw_schema_field: Arc<AtomicUsize>,cancel_after_first: Option<DreamCancel>,+ edit_during_merge: Option<(Wiki, WorkspaceId, ProjectId, String)>,}impl FakeMergeLlm {@@ -55,6 +56,7 @@ impl FakeMergeLlm {calls: Arc::new(AtomicUsize::new(0)),saw_schema_field: Arc::new(AtomicUsize::new(0)),cancel_after_first: None,+ edit_during_merge: None,}}}@@ -94,6 +96,7 @@ impl LlmProvider for FakeMergeLlm {let calls = self.calls.clone();let saw_schema = self.saw_schema_field.clone();let cancel = self.cancel_after_first.clone();+ let edit = self.edit_during_merge.clone();Box::pin(async move {let n = calls.fetch_add(1, Ordering::SeqCst);// Invariant #7: the merge must be a JSON-schema structured call, and@@ -111,6 +114,26 @@ impl LlmProvider for FakeMergeLlm {{cancel.cancel();}+ // The merge has read every source before this provider call. A+ // user correction here must not be replaced by that old snapshot.+ if let Some((wiki, ws, proj, path)) = edit {+ wiki.write_page(WritePageRequest {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new(&path).unwrap(),+ frontmatter: serde_json::json!({"title": "Fresh correction"}),+ body: FRESH_CORRECTION.into(),+ tier: Tier::Semantic,+ pinned: true,+ title: None,+ admission_ctx: None,+ author_id: None,+ actor: ActorContext::anonymous(),+ evidence: Vec::new(),+ })+ .await+ .unwrap();+ }let prompt = request.messages.first()@@ -357,6 +380,117 @@ const K8S_A: &str = "Kubernetes pod scheduling node selector affinity rules forconst K8S_B: &str = "Kubernetes pod scheduling node selector affinity rules for the cluster \autoscaler deployment on the staging namespace were tuned for the unique setting max-nodes-99.";+const FRESH_CORRECTION: &str =+ "Fresh user correction: this semantic, pinned page must remain current.";++async fn concurrent_member_write_skips_whole_cluster(edit_survivor: bool) {+ let fx = seed_fixture(true).await;+ write(&fx, "sessions/a.md", DUP_A).await;+ write(&fx, "sessions/b.md", DUP_B).await;+ for path in ["sessions/a.md", "sessions/b.md"] {+ backdate_latest(&fx, path, COLD_DAYS);+ }+ let cfg = dream_on();+ let mut llm = FakeMergeLlm::new();+ let plan = run_dream_pass(+ &fx.store.reader,+ &fx.wiki,+ Some(&llm),+ fx.ws,+ fx.proj,+ &DecayParams::default(),+ 0.0,+ &cfg,+ &DreamCancel::new(),+ true,+ )+ .await+ .unwrap();+ assert_eq!(plan.merges.len(), 1);+ let merge = &plan.merges[0];+ let (edited, peer) = if edit_survivor {+ (&merge.survivor, &merge.merged[0])+ } else {+ (&merge.merged[0], &merge.survivor)+ };+ let peer_body = latest_body(&fx, peer);+ let peer_id = fx+ .store+ .reader+ .latest_page_id_by_ids(fx.ws, fx.proj, peer.clone())+ .await+ .unwrap();+ llm.edit_during_merge = Some((fx.wiki.clone(), fx.ws, fx.proj, edited.clone()));++ let report = run_dream_pass(+ &fx.store.reader,+ &fx.wiki,+ Some(&llm),+ fx.ws,+ fx.proj,+ &DecayParams::default(),+ 0.0,+ &cfg,+ &DreamCancel::new(),+ false,+ )+ .await+ .unwrap();++ assert_eq!(llm.calls.load(Ordering::SeqCst), 1);+ assert_eq!(report.clusters_considered, 1);+ assert_eq!(+ report.clusters_merged, 0,+ "a changed member refuses the whole cluster"+ );+ assert_eq!(report.skipped, 1);+ assert_eq!(report.pages_rewritten, 0);+ assert_eq!(report.pages_superseded, 0);+ assert!(report.merges.is_empty());+ assert_eq!(latest_body(&fx, edited), FRESH_CORRECTION);+ let fm = latest_frontmatter(&fx, edited);+ assert_eq!(fm.get("tier"), Some(&serde_json::json!("semantic")));+ assert_eq!(fm.get("pinned"), Some(&serde_json::json!(true)));+ assert_eq!(+ fx.wiki+ .read_page(fx.ws, fx.proj, &PagePath::new(edited).unwrap())+ .unwrap()+ .body,+ FRESH_CORRECTION+ );+ assert_eq!(latest_body(&fx, peer), peer_body);+ assert_eq!(+ fx.wiki+ .read_page(fx.ws, fx.proj, &PagePath::new(peer).unwrap())+ .unwrap()+ .body,+ peer_body+ );+ assert_eq!(+ fx.store+ .reader+ .latest_page_id_by_ids(fx.ws, fx.proj, peer.clone())+ .await+ .unwrap(),+ peer_id+ );+ assert_eq!(+ superseded_row_count(&fx),+ 1,+ "only the user correction superseded a page"+ );+}++#[tokio::test]+async fn concurrent_survivor_write_skips_whole_cluster() {+ concurrent_member_write_skips_whole_cluster(true).await;+}++#[tokio::test]+async fn concurrent_loser_write_skips_whole_cluster() {+ concurrent_member_write_skips_whole_cluster(false).await;+}+/// B2: flag ON — the near-duplicates collapse to one LLM-rewritten survivor; the/// survivor keeps every source fact; the loser is superseded (reachable); the/// merge is recorded in `page_evidence`; the LLM was called with the schema.diff --git a/docs/design-memory-aging.md b/docs/design-memory-aging.mdindex 186c0e94..b0e48707 100644--- a/docs/design-memory-aging.md+++ b/docs/design-memory-aging.md@@ -222,7 +222,10 @@ Everything in A works with no provider and does not require ranking changes.(bounded, not the whole corpus). Adaptive eps from the k-distance elbow. Collapse= write one survivor, supersede the rest with a merge note pointing at thesurvivor. Zero-LLM: the survivor is the highest-retention member, body chosen by- A2's extractive rules; the *LLM* rewrite of a cluster is B2, opt-in.+ A2's extractive rules; the *LLM* rewrite of a cluster is B2, opt-in. Every+ replacement is conditional on its selected source version. If any source+ changed before the write, the whole dedup batch stays unapplied in the report;+ those selected pages are not evicted or compacted by the same sweep.- *Schema delta:* none beyond A2's marker; merge provenance goes in `page_evidence`(`source_kind`) and supersession.- *Invariants:* #2 (cluster on the already-materialized cold set, one batch write);@@ -511,7 +514,10 @@ in a boot migration.before it may default on. An existing user sees no ranking change until they opt in.- **B2 dream rewrite/merge: never deletes a source.** Originals live in git andthe supersession chain; `dry_run` first; R2-gated; opt-in LLM. The zero-LLM- default path (#13) is untouched; a provider-less store never runs B2.+ default path (#13) is untouched; a provider-less store never runs B2. Each+ merge checks that every selected source version is still current when the+ batch writes. If any member changed, the whole cluster is skipped and counted+ in the report; newer edits and unchanged peers stay intact for a later pass.- **C1 access reinforcement on more read paths: strictly non-destructive.** Itonly raises retention scores (keeps memory a little longer); it can never lower ascore or delete anything, and it still cannot block TTL cleanup (the TTL passdiff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 23b2d5a6..1f49c4fb 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -155,7 +155,7 @@ the legitimate restricted-project control and the failed-query cases.| 27 | Plain-HTTP human authentication stays fail-closed beyond loopback unless the operator supplies the dedicated dangerous override (#1383) | `ai-memory-cli/src/cli.rs` exposes `serve --allow-insecure-human-auth` separately from `--allow-insecure-no-auth`; `serve.rs` `validate_http_exposure` accepts it only when authentication and human mode are both active and the listener is non-loopback with a Non-Secure cookie, while the ordinary unauthenticated guard still runs otherwise. `HttpExposure::InsecureHumanAuthByOverride` gives that path its own unconditional stderr banner and structured warning, naming passwords, API credentials, session cookies, and memory data as plaintext. The default remains refusal, and `secure_cookie=true` or loopback remains the safe path | `serve.rs` `human_auth_non_loopback_requires_secure_cookie_posture` (default refusal, the no-auth override cannot substitute, the dedicated override succeeds, and that override cannot expose a server with no authentication even under inconsistent human-mode input; secure-cookie and loopback controls), `every_unsafe_exposure_produces_an_operator_banner` (the dedicated banner names the flag and session-cookie risk), and `cli.rs` `serve_parses_insecure_transport_overrides` (both dangerous flags remain distinct) | STRONG for the startup boundary. This is an explicit operator acceptance of transport risk, not encryption; authorization, CSRF, rate limits, Host validation, and the unauthenticated exposure refusal are unchanged || 27a | Provider credentials stay on the configured origin | `ai-memory-llm/src/redirect.rs` `same_origin_redirects`, set on every provider and embedder client (`anthropic.rs`, `codex.rs`, `copilot.rs`, `embedding.rs`, `gemini.rs`, `google.rs`, `openai.rs`, `openai_oauth.rs`, `opencode.rs`): a redirect is followed only when scheme, host and port match the previous request, with reqwest's ten-hop limit; any other redirect fails the request. reqwest's own guard strips only `Authorization`, cookies and the proxy headers, so `x-api-key`, `x-goog-api-key` and `llm_headers` values depend on this one. The local model download (`local.rs`) carries no credential and keeps the default policy for its CDN redirects; OIDC and CLI login requests refuse every redirect on clients of their own (`oidc.rs`, `auth.rs` `auth_http_client`) | `ai-memory-llm` `tests/suite/redirect_credentials.rs` `gemini_api_key_does_not_follow_a_cross_origin_redirect`, `anthropic_api_key_does_not_follow_a_cross_origin_redirect`, `operator_headers_do_not_follow_a_cross_origin_redirect` (with `Authorization` stripped as the control), `google_embedder_key_does_not_follow_a_cross_origin_redirect`, `a_refused_redirect_says_where_it_pointed`; legitimate control `a_same_origin_redirect_still_reaches_the_provider` (the key follows a path redirect on one origin); each cross-origin test fails with the policy removed | STRONG for the provider and embedder clients in `ai-memory-llm` || 27b | LLM workload telemetry cannot turn prompts, outputs, scopes, projects, or caller text into status data or unbounded metric labels | `ai-memory-llm/src/types.rs` `LlmWorkload` is a closed enum carried beside, but absent from the display/wire form of, `LlmOperationId`; `health.rs` `LlmWorkloadHealth` uses one fixed array and fixed latency buckets and records only counts/times/coarse estimates/reported usage/redacted error class and status; `ProviderHealth::snapshot` omits the rows when LLM support is disabled; `/admin/status` remains behind the common admin gate | `ai-memory-llm` `workload_snapshot_is_bounded_redacted_and_percentiled` (private prompt, output and upstream body absent; fixed row count, recovery-preserved last error, and percentile controls), `llm_wrapper_forwards_the_callers_operation_id` (label recorded while the same UUID-only id reaches the provider), `types::tests::workload_labels_are_stable_and_do_not_change_the_wire_operation_id`; `ai-memory-mcp` `status_reports_bounded_content_free_llm_workload_telemetry` (private prompt absent from serialized status, one fixed row per label), `status_reports_provider_health_block` (disabled LLM emits no rows) | STRONG for content/cardinality and the existing root-only admin surface |-| 27c | A maintenance compaction cannot replace a newer user page or partly apply a stale batch | `ai-memory-consolidate/src/sweep.rs` carries each selected source `PageId` into `Wiki::apply_batch_if`; `ai-memory-wiki/src/wiki.rs` checks the preconditions after locking every page, installs files with rollback snapshots, and delegates the decisive check to `WriterHandle::upsert_pages_batch_if`; `ai-memory-store/src/ops.rs` validates every latest id and writes every replacement in one SQLite transaction, returning a mismatch before any write | store `conditional_page_batch_is_all_or_nothing`; wiki `conditional_batch_rejects_every_page_when_one_version_changed` (file and DB controls); consolidate `compaction_does_not_supersede_a_concurrent_fresh_write` (an admission barrier lands a semantic pinned correction after A2 reads the old body, then proves the correction remains latest and the selected batch stays uncommitted) | STRONG; all-or-nothing intentionally retries unchanged peers with the next sweep instead of weakening invariant #2 into per-page writes |+| 27c | A maintenance compaction, cold-cluster dedup or dream merge cannot replace a newer user page or partly apply a stale batch | `ai-memory-consolidate/src/sweep.rs` and `dream.rs` carry each selected source `PageId` into `Wiki::apply_batch_if`; `ai-memory-wiki/src/wiki.rs` checks the preconditions after locking every page, installs files with rollback snapshots, and delegates the decisive check to `WriterHandle::upsert_pages_batch_if`; `ai-memory-store/src/ops.rs` validates every latest id and writes every replacement in one SQLite transaction, returning a mismatch before any write | store `conditional_page_batch_is_all_or_nothing`; wiki `conditional_batch_rejects_every_page_when_one_version_changed` (file and DB controls); consolidate `compaction_does_not_supersede_a_concurrent_fresh_write` (an admission barrier lands a semantic pinned correction after A2 reads the old body, then proves the correction remains latest and the selected batch stays uncommitted); dream `concurrent_survivor_write_skips_whole_cluster` and `concurrent_loser_write_skips_whole_cluster` (a fake provider writes a semantic pinned correction after B2 reads both members; the correction remains latest in file and DB, the unchanged peer retains its version, and the cluster is counted as skipped; both fail without the version guards), with `flag_on_merges_cluster_via_llm` as the unchanged-cluster control; cold-cluster `concurrent_survivor_write_skips_dedup_batch` and `concurrent_loser_write_skips_dedup_batch` (an admission barrier lands a correction after A3 derives both replacements; file/DB versions and metadata survive, no replacement is applied, and no fallback eviction occurs; both fail without the version guards), with `flag_on_collapses_a_pair_with_no_other_cold_page` as the unchanged-cluster control | STRONG; all-or-nothing intentionally retries unchanged peers with the next sweep instead of weakening invariant #2 into per-page writes || 28 | An Antigravity hook reads, and uploads as prompts, only the named conversation's own transcript, within bounds | `ai-memory-hooks/src/antigravity.rs` `antigravity_transcript_path` accepts the payload's `transcriptPath` only when it is absolute, has no `..`, names `transcript.jsonl` or `transcript_full.jsonl`, and its canonical directory equals `canonical(<home>/.gemini/<app>/brain)/<conversationId>/.system_generated/logs` for `<app>` `antigravity`, `antigravity-cli` or `antigravity-ide`, with `conversationId` a plain id (`antigravity_conversation_id`); `read_transcript_prompts` opens only a regular, non-symlink file that is still the same file once open (`open_regular_file`, opened with `O_NOFOLLOW | O_NONBLOCK` so a symlink or FIFO swapped in after the check is refused without blocking, and on Linux only when the opened descriptor's `/proc/self/fd` path is the checked one, so a directory swapped for a symlink after the containment check is refused too), reads at most `MAX_TRANSCRIPT_SCAN_BYTES` per hook and parses lines up to `MAX_TRANSCRIPT_LINE_BYTES`, and returns only `USER_INPUT` steps whose `source` is absent or `USER_EXPLICIT`; `ai-memory-cli/src/commands/hook.rs` `antigravity_transcript_prompt_events` runs inside the spool block, so after the capture allowlist, routing, server-profile and external-capture gates, with the home `run_with_payload` resolved once; its path checks, bounded cursor load and transcript read run behind `ANTIGRAVITY_TRANSCRIPT_READ_BUDGET`, and a timeout advances no cursor so a later hook retries; cursor replacement uses the canonical atomic writer; each prompt is capped and scrubbed client-side, keyed by conversation and step, and sanitized again by the server (row 7) | `antigravity.rs` `transcript_path_refuses_anything_outside_the_conversations_own_logs` (another conversation's transcript, the same layout outside the home, another file in the logs directory, an unknown app directory, `..`, a traversal or empty id, a relative path, a missing or non-string path; the conversation's own transcript is the control), `transcript_path_refuses_symlinked_directories_that_leave_the_conversation` (a symlinked `.system_generated` and `brain/<id>` refused; a symlinked `~/.gemini` accepted as the control), `transcript_reader_refuses_symlinks_and_special_files` (a symlinked transcript and a directory refused; the same bytes as a regular file are read), `skips_injected_malformed_empty_and_non_prompt_steps`, `a_line_longer_than_the_scan_budget_is_skipped_across_reads`, `one_read_returns_a_bounded_number_of_prompts`; `hook.rs` `antigravity_transcript_reads_are_confined_to_the_conversations_own_logs` (end to end through the native hook: a forged path outside the home, another conversation's transcript and an arbitrary JSONL file under the home spool no prompt; the conversation's own transcript spools one), `antigravity_transcript_prompts_follow_the_capture_allowlist` (a repository the allowlist leaves out is not read), `antigravity_transcript_read_deadline_does_not_wait_for_blocked_work`, and `antigravity_transcript_cursor_store_is_atomic_and_bounded` (oversized cursor refused) | STRONG on Linux, including the opened descriptor path. Stable symlink escapes and special files are refused on every platform; without Linux `/proc/self/fd`, a same-user process able to replace an ancestor in the narrow interval between canonicalization and open could redirect the read, which still remains size- and time-bounded. The directory-swap bite test is Linux-only; the other symlink cases are `cfg(unix)` |### IBM Bob evidence