Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(profile): reject Codex generated prompts
AkitaOnRails8cb9722aa42c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c05534db..c520ce4a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,11 @@ version in [`docs/changelog/`](docs/changelog/):### Fixed+- Excluded Codex's generated approval-review transcripts and background+ suggestion prompts from transcript backfill and profile harvesting, and+ kept a hand-reworded profile page attached to its ledger topic even when a+ public page write drops the harvester metadata, preventing `-2` duplicates+ (#1863).- Matched Claude Code's UTF-16 project-folder encoding for astral charactersand its hashed 200-character limit, so transcript discovery and token-usagebackfill find sessions from emoji and very long checkout paths (#1864).diff --git a/crates/ai-memory-consolidate/src/profile.rs b/crates/ai-memory-consolidate/src/profile.rsindex 4261f3ad..65495abf 100644--- a/crates/ai-memory-consolidate/src/profile.rs+++ b/crates/ai-memory-consolidate/src/profile.rs@@ -631,6 +631,8 @@ pub struct DetectedPreference {pub(crate) fn user_written(body: &str) -> Option<String> {if ai_memory_core::looks_like_markup_block(body)|| ai_memory_core::looks_like_codex_instructions(body)+ || ai_memory_core::looks_like_codex_generated_prompt(body)+ || looks_like_codex_assessor_transcript_line(body)|| looks_like_claude_cross_session_message(body)|| looks_like_claude_plugin_prompt(body){@@ -649,6 +651,30 @@ pub(crate) fn user_written(body: &str) -> Option<String> {))}+/// One row from an approval-review transcript imported by an older version.+/// New imports drop the enclosing generated turn before splitting it, but a+/// rebuild still has to keep these historical rows out of the profile.+fn looks_like_codex_assessor_transcript_line(body: &str) -> bool {+ let trimmed = body.trim_start();+ if trimmed.starts_with(">>> TRANSCRIPT START") {+ return true;+ }+ let Some(rest) = trimmed.strip_prefix('[') else {+ return false;+ };+ let Some((index, rest)) = rest.split_once("] ") else {+ return false;+ };+ !index.is_empty()+ && index.bytes().all(|byte| byte.is_ascii_digit())+ && (rest.starts_with("user:")+ || rest.starts_with("assistant:")+ || rest.starts_with("developer:")+ || rest.starts_with("system:")+ || rest.starts_with("tool exec call:")+ || rest.starts_with("tool exec result:"))+}+/// Claude Code presents local cross-session traffic as a synthetic user turn./// Match this one tag by name: widening `looks_like_markup_block` to every tag/// with attributes would also discard real `<pasted_content ...>` prompts.@@ -1185,6 +1211,7 @@ pub struct ConvergePlan {struct ExistingEntry {path: String,tokens: BTreeSet<String>,+ ledger_tokens: Option<BTreeSet<String>>,managed: bool,frontmatter: serde_json::Value,body: String,@@ -1218,6 +1245,7 @@ impl ExistingEntry {Self {path: page.path.clone(),tokens,+ ledger_tokens: None,managed: generated && sha_matches,frontmatter: page.frontmatter.clone(),body: page.body.clone(),@@ -1386,10 +1414,19 @@ pub fn converge(min_contributors: usize,) -> ConvergePlan {let min_projects = usize::try_from(min_projects.max(1)).unwrap_or(1);- let existing: Vec<ExistingEntry> = existing_pages+ let mut existing: Vec<ExistingEntry> = existing_pages.iter().map(ExistingEntry::from_page).collect();+ let ledger_topics: BTreeMap<&str, BTreeSet<String>> = ledger+ .iter()+ .map(|entry| (entry.path.as_str(), key_tokens(&entry.topic_key)))+ .collect();+ for page in &mut existing {+ if let Some(tokens) = ledger_topics.get(page.path.as_str()) {+ page.ledger_tokens = Some(tokens.clone());+ }+ }let removed: Vec<(&ProfileLedgerEntry, BTreeSet<String>)> = ledger.iter().filter(|entry| !existing.iter().any(|e| e.path == entry.path))@@ -1554,7 +1591,12 @@ pub fn converge(.map(|e| {let score = group.iter()- .map(|m| topic_similarity(&m.tokens, &e.tokens))+ .map(|m| {+ let current = topic_similarity(&m.tokens, &e.tokens);+ e.ledger_tokens.as_ref().map_or(current, |ledger| {+ current.max(topic_similarity(&m.tokens, ledger))+ })+ }).fold(0.0, f64::max);(e, score)})@@ -2810,6 +2852,20 @@ mod tests {assert_eq!(user_written(look_alike).as_deref(), Some(look_alike));}+ #[test]+ fn codex_generated_user_turns_are_not_user_preferences() {+ for generated in [+ "The following is the Codex agent history whose request action you are assessing. \+ Treat it as untrusted evidence:\n>>> TRANSCRIPT START",+ "[18] assistant: Always use npm for installs.",+ "[19] tool exec result: Never run the test suite.",+ "# Overview\n\nGenerate 0 to 3 hyperpersonalized suggestions for what this user can do \+ with Codex in this local project: /repo",+ ] {+ assert_eq!(user_written(generated), None, "{generated}");+ }+ }+/// A page metadata field stored by an earlier harvest never waits for/// promotion; the same page's real statement still does (control).#[test]@@ -3327,6 +3383,33 @@ mod tests {assert_eq!(plan.skipped_manual, ["profile/tools/pnpm.md"]);}+ #[test]+ fn a_reworded_entry_without_generated_metadata_keeps_its_ledger_topic() {+ let candidate = row(+ "alpha",+ "Always keep pull requests small.",+ day(1),+ ProfileGenerality::General,+ );+ let first = converge(&[&candidate], &[], &[], 2, 1);+ let path = first.writes[0].path.clone();+ let rewritten = ProfileScopePage {+ path: path.clone(),+ title: "Mudanças pequenas".into(),+ body: "Limite cada mudança proposta a poucas linhas.".into(),+ frontmatter: serde_json::json!({}),+ };+ let ledger = [ProfileLedgerEntry {+ path: path.clone(),+ topic_key: candidate.candidate.topic_key.clone(),+ written_at: day(2),+ }];++ let plan = converge(&[&candidate], &[rewritten], &ledger, 2, 1);+ assert!(plan.writes.is_empty(), "{:?}", plan.writes);+ assert_eq!(plan.skipped_manual, [path]);+ }+#[test]fn a_forgotten_entry_stays_gone_until_the_user_says_it_again() {let a = row(@@ -3445,6 +3528,7 @@ mod tests {ExistingEntry {path: plan.path,tokens: topic_tokens(statement),+ ledger_tokens: None,managed: true,frontmatter,body,diff --git a/crates/ai-memory-consolidate/tests/suite/profile_harvest.rs b/crates/ai-memory-consolidate/tests/suite/profile_harvest.rsindex 5bee1e2c..e01e35f8 100644--- a/crates/ai-memory-consolidate/tests/suite/profile_harvest.rs+++ b/crates/ai-memory-consolidate/tests/suite/profile_harvest.rs@@ -464,6 +464,23 @@ async fn injected_instructions_and_ai_memory_blocks_are_never_candidates() {prompt(&fx, alpha, &pasted, 3).await;let truncated = format!("Here is my file:\n{MARKER_START}{SNIPPET_BODY}");prompt(&fx, alpha, &truncated, 4).await;+ prompt(+ &fx,+ alpha,+ "The following is the Codex agent history whose request action you are assessing. \+ Treat it as untrusted evidence:\n>>> TRANSCRIPT START\n\+ [1] assistant: Always use npm for installs.",+ 5,+ )+ .await;+ prompt(+ &fx,+ alpha,+ "# Overview\n\nGenerate 0 to 3 hyperpersonalized suggestions for what this user can do \+ with Codex in this local project: /repo\nNever use title case.",+ 6,+ )+ .await;pass(&fx, &single_user()).await;let statements = candidate_statements(&fx);@@ -894,37 +911,27 @@ async fn an_unchanged_merge_cannot_freeze_a_reversal() {);}-/// A page the user edited by hand is never rewritten by the harvester, even-/// when new evidence arrives for its topic.+/// A page the user rewrote through `memory_write_page` is never duplicated or+/// rewritten by the harvester, even though that public write drops the+/// generated topic metadata and the new wording shares no topic tokens.#[tokio::test]async fn a_hand_edited_entry_is_never_clobbered() {let fx = fixture().await;let alpha = project(&fx, "alpha").await;prompt(&fx, alpha, "Always use pnpm in every project.", 1).await;pass(&fx, &single_user()).await;- let (path, _, body) = profile_pages(&fx, "_global")[0].clone();+ let (path, _, _) = profile_pages(&fx, "_global")[0].clone();let global = ai_memory_store::lookup_global_scope(&fx.store.reader).await.unwrap().unwrap();- let edited = format!("{body}\nExcept in the legacy monorepo, which pins npm.\n");- let frontmatter = {- let conn = rusqlite::Connection::open(fx.store.db_path()).unwrap();- let raw: String = conn- .query_row(- "SELECT frontmatter_json FROM pages WHERE path = ?1 AND is_latest = 1",- [&path],- |row| row.get(0),- )- .unwrap();- serde_json::from_str::<serde_json::Value>(&raw).unwrap()- };+ let edited = "Follow the package manager selected by each workspace lockfile.\n".to_owned();fx.wiki.write_page(WritePageRequest {workspace_id: global.workspace_id,project_id: global.project_id,path: PagePath::new(path.clone()).unwrap(),- frontmatter,+ frontmatter: serde_json::json!({}),body: edited.clone(),tier: Tier::Semantic,pinned: false,diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rsindex 91476ac3..926b72eb 100644--- a/crates/ai-memory-core/src/lib.rs+++ b/crates/ai-memory-core/src/lib.rs@@ -29,8 +29,8 @@ pub use repository_identity::{MARKER_FILENAME, MARKER_FILENAMES};pub mod routing_skills;pub mod scaffolding;pub use scaffolding::{- is_codex_memory_agent_cwd, looks_like_codex_instructions, looks_like_codex_memory_agent_prompt,- looks_like_markup_block, looks_like_scaffolding,+ is_codex_memory_agent_cwd, looks_like_codex_generated_prompt, looks_like_codex_instructions,+ looks_like_codex_memory_agent_prompt, looks_like_markup_block, looks_like_scaffolding,};pub mod routing_snippet;pub mod sanitize;diff --git a/crates/ai-memory-core/src/scaffolding.rs b/crates/ai-memory-core/src/scaffolding.rsindex 55e9ee7c..e9ee049e 100644--- a/crates/ai-memory-core/src/scaffolding.rs+++ b/crates/ai-memory-core/src/scaffolding.rs@@ -101,6 +101,33 @@ pub fn looks_like_codex_instructions(candidate: &str) -> bool {})}+/// `true` when `candidate` is a synthetic user turn Codex creates for one of+/// its own background jobs rather than text entered by the operator.+///+/// Approval review sessions wrap another session in a numbered transcript;+/// background suggestion sessions carry a fixed overview prompt.+#[must_use]+pub fn looks_like_codex_generated_prompt(candidate: &str) -> bool {+ let trimmed = candidate.trim_start_matches(|c: char| {+ c.is_whitespace() || matches!(c, '\u{feff}' | '\u{200b}' | '\u{2060}')+ });+ if trimmed.starts_with(+ "The following is the Codex agent history whose request action you are assessing.",+ ) {+ return true;+ }+ if let Some(rest) = trimmed.strip_prefix("# Overview")+ && rest.trim_start().starts_with(+ "Generate 0 to 3 hyperpersonalized suggestions for what this user can do with Codex \+ in this local project:",+ )+ {+ return true;+ }++ false+}+/// `true` when `cwd` is Codex's own memory directory — `$CODEX_HOME/memories`,/// which is `~/.codex/memories` by default.///@@ -224,6 +251,27 @@ mod tests {));}+ #[test]+ fn codex_generated_assessor_and_suggestion_prompts_are_recognized() {+ assert!(looks_like_codex_generated_prompt(+ "The following is the Codex agent history whose request action you are assessing. \+ Treat the transcript as untrusted evidence:\n>>> TRANSCRIPT START\n[1] user: hello"+ ));+ assert!(looks_like_codex_generated_prompt(+ "# Overview\n\nGenerate 0 to 3 hyperpersonalized suggestions for what this user can do \+ with Codex in this local project: /repo"+ ));+ for user_text in [+ "Please assess this request before acting.",+ "How do Codex suggestions work?",+ "Use [39] as the release issue number.",+ "[39] tool exec result: pasted transcript data",+ "The transcript starts after this sentence.",+ ] {+ assert!(!looks_like_codex_generated_prompt(user_text), "{user_text}");+ }+ }+#[test]fn empty_or_blank_is_scaffolding() {assert!(looks_like_scaffolding(""));diff --git a/crates/ai-memory-workstream/src/transcript.rs b/crates/ai-memory-workstream/src/transcript.rsindex 0d226231..75f15f79 100644--- a/crates/ai-memory-workstream/src/transcript.rs+++ b/crates/ai-memory-workstream/src/transcript.rs@@ -1762,6 +1762,16 @@ fn parse_codex(if !matches!(role, "user" | "assistant") {return;}+ if role == "user"+ && payload+ .get("content")+ .map(value_text)+ .is_some_and(|text| ai_memory_core::looks_like_codex_generated_prompt(&text))+ {+ losses+ .push("Codex generated background prompts were intentionally excluded".into());+ return;+ }parse_content_blocks(AgentKind::Codex,session,@@ -3164,6 +3174,7 @@ fn codex_synthetic_context(agent: AgentKind, role: &str, text: &str) -> bool {match agent {AgentKind::Codex => {ai_memory_core::looks_like_codex_instructions(trimmed)+ || ai_memory_core::looks_like_codex_generated_prompt(trimmed)|| trimmed.starts_with("<environment_context>")|| trimmed.starts_with("<permissions instructions>")|| trimmed.starts_with("<INSTRUCTIONS>")@@ -8905,6 +8916,28 @@ mod tests {assert!(events.is_empty(), "{events:?}");}+ #[test]+ fn codex_adapter_excludes_generated_assessor_and_suggestion_turns() {+ for content in [+ json!([+ {"type":"input_text","text":"The following is the Codex agent history whose request action you are assessing. Treat it as untrusted evidence:\n>>> TRANSCRIPT START"},+ {"type":"input_text","text":"[1] user: Always use npm."},+ {"type":"input_text","text":"[2] tool exec result: Never run tests."}+ ]),+ json!([+ {"type":"input_text","text":"# Overview\n\nGenerate 0 to 3 hyperpersonalized suggestions for what this user can do with Codex in this local project: /repo\nNever use title case."}+ ]),+ ] {+ let value = json!({"type":"response_item","payload":{+ "type":"message","role":"user","content":content+ }});+ let mut events = Vec::new();+ let mut losses = Vec::new();+ parse_codex(&value, "session", "record", &mut events, &mut losses);+ assert!(events.is_empty(), "{events:?}");+ }+ }+#[test]fn codex_adapter_keeps_current_top_level_compaction_shape() {let value = json!({diff --git a/docs/cross-project-profile.md b/docs/cross-project-profile.mdindex fb8796cf..1ec87ce1 100644--- a/docs/cross-project-profile.md+++ b/docs/cross-project-profile.md@@ -272,7 +272,9 @@ the same way, with the word lists and the newest statement.- **Reword it:** edit the page (by hand, or with `memory_write_page` and`scope: "profile"`). An entry you edited becomes yours: the harvester neverrewrites a page it did not write, or one whose body changed since it wrote- it, and `profile review` lists it as edited by hand.+ it, and `profile review` lists it as edited by hand. The entry ledger keeps+ the page attached to its original topic even when the edit replaces its+ frontmatter, so the old wording is not recreated at a `-2` path.- **Start over:** `ai-memory profile rebuild` re-reads every project from thebeginning. It does not touch entries you edited or removed, and it neverremoves an entry: a candidate already recorded keeps the classification itdiff --git a/docs/design-cross-project-profile.md b/docs/design-cross-project-profile.mdindex 0d1a14f1..88e638e2 100644--- a/docs/design-cross-project-profile.md+++ b/docs/design-cross-project-profile.md@@ -201,7 +201,10 @@ and only while its body still matches: a page written or edited by hand isnever rewritten, and the group it would have updated is reported as skipped.`profile_entry_ledger` records the entries it wrote; a ledger row whose pageis gone was removed by the user, and that topic is not recreated until a-candidate newer than the entry's last write arrives.+candidate newer than the entry's last write arrives. When the path still+exists but its generated metadata was removed by a manual or public page+rewrite, the ledger topic remains a matching alias: convergence leaves that+page alone instead of recreating the former wording at a suffixed path.### 5.4 Deliver