Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(profile): preserve affirmative capability preferences
Samir Hanna Verza8adbf19e31a1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 41307bf3..c6ddb1fe 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,13 @@ version in [`docs/changelog/`](docs/changelog/):## [Unreleased]+### Fixed++- Restored affirmative profile preferences about tools, browsers and MCP.+ The capability-ban filter also discarded statements such as "Always use+ tools to verify facts"; it now requires negative or disabling wording.+ Capability bans still need explicit cross-project scope (#1678).+## [3.2.5] - 2026-10-25### Fixeddiff --git a/crates/ai-memory-consolidate/src/profile.rs b/crates/ai-memory-consolidate/src/profile.rsindex 5707feea..3eaf865d 100644--- a/crates/ai-memory-consolidate/src/profile.rs+++ b/crates/ai-memory-consolidate/src/profile.rs@@ -163,6 +163,39 @@ const CAPABILITY_WORDS: &[&str] = &["subagentes",];+/// Disabling language that has no ordinary negation. These words belong to+/// the capability filter only: treating "off" as "not" in every topic's+/// ruling would change how unrelated preferences are compared.+const CAPABILITY_BAN_WORDS: &[&str] = &[+ "without",+ "disable",+ "disabled",+ "disabling",+ "deactivate",+ "deactivated",+ "deactivating",+ "off",+ "sem",+ "desative",+ "desativar",+ "desativado",+ "desativada",+ "desativados",+ "desativadas",+ "desabilite",+ "desabilitar",+ "desabilitado",+ "desabilitada",+ "desabilitados",+ "desabilitadas",+ "desligue",+ "desligar",+ "desligado",+ "desligada",+ "desligados",+ "desligadas",+];+/// Phrases that mark a prompt as written by a program driving the agent/// through its SDK or CLI rather than by the person (#1648): a summarizer/// call that wraps a transcript, or a demo that asks for a verbatim reply.@@ -697,6 +730,10 @@ fn has_marker(sentence: &str) -> bool {/// Whether `padded` switches off one of the agent's own capabilities.fn forgoes_a_capability(padded: &str) -> bool {CAPABILITY_WORDS.iter().any(|word| has_phrase(padded, word))+ && (ruling_sequence(padded).iter().any(|word| word == "not")+ || CAPABILITY_BAN_WORDS+ .iter()+ .any(|word| has_phrase(padded, word)))}/// Whether `text` was written by a program calling the agent as an API.@@ -2826,6 +2863,72 @@ mod tests {);}+ #[test]+ fn affirmative_capability_preferences_are_still_candidates() {+ for text in [+ "Always use tools to verify facts.",+ "I prefer the browser for visual checks.",+ "By default use MCP for database lookups.",+ "Sempre use ferramentas para verificar fatos.",+ "Prefiro usar o navegador para verificar o resultado.",+ ] {+ assert!(+ has_marker(text),+ "the LLM gate discarded a preference: {text}"+ );+ let found = detect_preferences(text);+ assert_eq!(+ found.len(),+ 1,+ "the zero-LLM gate discarded a preference: {text}"+ );+ assert_eq!(found[0].generality, ProfileGenerality::Project, "{text}");+ }+ for text in [+ "Do not use any tools.",+ "Don't use tools for lookups.",+ "Dont use tools for lookups.",+ "Never call browser_close.",+ "Always avoid shell commands.",+ "Não use ferramentas para consultas.",+ "Nunca use o navegador.",+ "Sempre evite usar ferramentas.",+ "I prefer to work without tools.",+ "Prefiro trabalhar sem ferramentas.",+ "I prefer to disable tools.",+ "By default keep tools disabled.",+ "Always keep browsing turned off.",+ "I prefer deactivating browser tools.",+ "Prefiro desativar ferramentas.",+ "Prefiro desabilitar ferramentas.",+ "Prefiro desligar o navegador.",+ "Sempre mantenha as ferramentas desativadas.",+ "Sempre mantenha as ferramentas desabilitadas.",+ "Sempre mantenha o navegador desligado.",+ ] {+ assert!(+ !has_marker(text),+ "the LLM gate admitted a capability ban: {text}"+ );+ assert!(+ detect_preferences(text).is_empty(),+ "the zero-LLM gate admitted a capability ban: {text}"+ );+ }+ for text in [+ "In all my projects, I prefer to work without tools.",+ "Em todos os meus projetos, prefiro desativar ferramentas.",+ ] {+ assert!(+ has_marker(text),+ "an explicitly scoped preference was dropped: {text}"+ );+ let found = detect_preferences(text);+ assert_eq!(found.len(), 1, "{text}");+ assert_eq!(found[0].generality, ProfileGenerality::General, "{text}");+ }+ }+#[test]fn detects_imperative_preferences_in_english_and_portuguese() {let found = detect_preferences(diff --git a/crates/ai-memory-consolidate/tests/suite/profile_harvest.rs b/crates/ai-memory-consolidate/tests/suite/profile_harvest.rsindex 0b0738c7..b7332816 100644--- a/crates/ai-memory-consolidate/tests/suite/profile_harvest.rs+++ b/crates/ai-memory-consolidate/tests/suite/profile_harvest.rs@@ -280,6 +280,58 @@ async fn a_habit_from_two_projects_becomes_a_global_entry_once() {assert_eq!(versions_of(&fx, &pages[0].0).len(), 1);}+/// The two one-shot prompts from #1648 must stay excluded even when the+/// capability filter admits ordinary affirmative preferences again.+#[tokio::test]+async fn scripted_one_shot_prompts_do_not_become_global_defaults() {+ let fx = fixture().await;+ let alpha = project(&fx, "demo").await;+ let beta = project(&fx, "summarizer").await;+ prompt(+ &fx,+ alpha,+ "Do not use any tools. Reply with exactly this markdown and nothing else: \+ Screenshot fixture ready.",+ 1,+ )+ .await;+ prompt(+ &fx,+ beta,+ "Here is a conversation between a user and a coding agent.\n\+ <conversation>\nUser: Review the test output.\nAgent: The suite passed.\n\+ </conversation>\nDo not use tools. Summarize the conversation.",+ 3,+ )+ .await;++ let report = pass(&fx, &single_user()).await;+ let pages = profile_pages(&fx, "_global");+ assert!(pages.is_empty(), "{report:?}\n{pages:#?}");+}++#[tokio::test]+async fn capability_bans_stay_out_while_affirmative_habits_need_two_projects() {+ let fx = fixture().await;+ let alpha = project(&fx, "alpha").await;+ let beta = project(&fx, "beta").await;+ let habit = "Always use tools to verify facts.";+ let ban = "Never use tools to answer questions.";+ prompt(&fx, alpha, habit, 1).await;+ prompt(&fx, alpha, ban, 1).await;+ prompt(&fx, beta, ban, 3).await;+ let first = pass(&fx, &single_user()).await;+ assert_eq!(first.candidates_added, 1, "{first:?}");+ assert!(profile_pages(&fx, "_global").is_empty());++ prompt(&fx, beta, habit, 5).await;+ let second = pass(&fx, &single_user()).await;+ let pages = profile_pages(&fx, "_global");+ assert_eq!(second.entries_written, 1, "{second:?}");+ assert_eq!(pages.len(), 1);+ assert_eq!(pages[0].1, habit);+}+/// A choice said in only one project stays out of the profile unless the/// user stated it as general.#[tokio::test]diff --git a/docs/cross-project-profile.md b/docs/cross-project-profile.mdindex a70421fd..b3126c12 100644--- a/docs/cross-project-profile.md+++ b/docs/cross-project-profile.md@@ -195,8 +195,9 @@ is new since the last one.not yours. A sentence that switches off one of the agent's own capabilities(*do not use tools*, *never call browser_close*, *do not use the browser*)only counts when you scoped it across projects, because as a default it- stops every project's agent from working. Your verbatim words are kept as- evidence.+ stops every project's agent from working. Affirmative preferences such as+ "Always use tools to verify facts" still qualify under the normal project+ threshold. Your verbatim words are kept as evidence.- **Curated pages** of the project: `_rules/`, `decisions/`, `gotchas/` and`procedures/`. A page contributes its `summary`, or else its first line ofprose; metadata fields such as `**Status:** Accepted` or `**Date:**` at thediff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex afbee773..8728746c 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -37,7 +37,7 @@ the legitimate restricted-project control and the failed-query cases.| 1e | The shared profile scopes are read-open, write-gated like `_global` | `ai-memory-store/src/project_authz.rs` `is_reserved_global` (a workspace `_profile` joins `default/_global`: on a server that distinguishes operators a write needs root or a `write` grant, creating it grants nothing); `ops.rs` `initial_access_mode` keeps `_profile` open | store `integration::profile` `shared_profiles_are_write_gated_for_database_users` (ungranted user refused for both shares; root and a write grant admitted; reads open); `server.rs` `a_workspace_profile_is_write_gated_and_read_open`; both fail with `_profile` dropped from the gate | STRONG || 1f | Event capture never lands in a profile project, and the sweep keeps them | `ai-memory-hooks/src/router.rs` project resolution refuses `ai_memory_core::profile::is_reserved_scope_project` (`_global`, `_profile`, `_profile.*`) from a directory or a marker override, falling back to the server default; `ops.rs` `sweep_hollow_projects` exempts `_profile` and `_profile.%` | `router.rs` `capture_is_never_attributed_to_a_profile_project` (override and directory spellings refused; ordinary `my_profile` control resolves), fails with the check narrowed to `_global`; store `integration::profile` `the_hollow_project_sweep_keeps_empty_profile_projects` | STRONG || 1g | The profile reaches only the sessions it is meant for: off by default on a multi-user server, suppressed by `[profile] consume = false`, and an opt-out is sticky | `ai_memory_core::profile::ProfileSettings::effective_share` (`enabled = auto` is off once operators are distinguished); `router.rs` `persist_profile_flags` (flags are tri-state: an absent forwarded value keeps the stored one, so a client that sends nothing never undoes an opt-out; every front door sends explicit `0`/`1` once a marker resolved) and `render_requested_profile_digest` (a team profile is headed "team defaults"); `server.rs` `memory_query` drops `profile/` hits for a project whose stored `profile_consume` is off; `admin_profile.rs` `handle_apply` (`ai-memory profile apply`) returns no lines for such a project and sits behind the root-only `/admin/*` gate on a multi-user server | `router.rs` `a_multi_user_server_has_no_profile_digest_by_default`, `profile_digest_honours_consume_once_per_session_and_the_server_switch`, `session_start_records_the_marker_profile_flags` (a session start with no flags after an opt-out keeps the project out of the harvest and the digest; fails when an absent flag defaults to on); `server.rs` `the_single_user_profile_lives_in_global_and_honours_consume` (fails with the consume filter removed); `admin_profile_routes.rs` `apply_lists_the_lines_for_a_project_and_honours_consume`, `apply_is_root_only_on_a_multi_user_server` (database user refused, root control admitted); core `profile::tests::effective_share_matrix` | STRONG |-| 1h | The profile learns only from what it may: the user's own prompts and curated pages, from contributing projects, never another operator's words in a private profile and never a restricted project in a shared one; stored text stays data | `ai-memory-store/src/profile.rs` `profile_prompts_since` (only `user-prompt` observations), `auto_improve_decided_by` (the decider agent a page's `auto_improve_proposal_id` resolves to), `profile_harvest_projects` / `profile_candidates` (`profile_contribute = 0` excluded, including candidates recorded before the opt-out); `ai-memory-store/src/ops.rs` `move_session` (a moved session's `session:<id>` prompt candidates are re-stamped into the target project in the same transaction, so they answer to its contribute flag and access mode, #1265); `ai-memory-consolidate/src/profile.rs` `user_written` (shared with the verbatim-residue caller in row 25: a harness turn or Codex's injected instructions stored as a prompt is skipped whole, and ai-memory's routing and untrusted-history blocks, fenced by markers on their own lines, are cut out before any sentence is read), the auto-approved-proposal skip in `harvest_project` (a page the auto-improve scheduler auto-approved is model output nobody reviewed and never becomes a candidate; a human-approved page, or one whose proposal id has no row, stays curated, #1211), `convergence_targets` (a `user` target keeps only candidates whose `contributor` is that operator, from projects the per-project choke point lets them read; a `global`/`workspace` target on an operator-distinguishing server drops restricted projects), `min_contributors` / `converge` (a team profile admits a statement only on evidence from at least two distinct operators, so one operator cannot plant a default in everyone's session start) (never rewrites a page without its `generated_by` stamp or whose body changed; `profile_entry_ledger` keeps a forgotten entry out), `classify_batch` / `merge_entry` (sanitized, JSON-encoded input; the evidence quote is always the user's sentence) | consolidate `integration::profile_harvest` `tool_output_is_never_a_candidate`, `an_opted_out_project_is_never_harvested`, `a_private_profile_never_harvests_another_operator`, `a_team_profile_never_harvests_a_restricted_project`, `a_team_profile_needs_more_than_one_operator` (one operator in two open projects not admitted; a second operator admits it; fails with the threshold at one), `a_personal_profile_admits_one_operators_habit` (control), `a_hand_edited_entry_is_never_clobbered`, `a_forgotten_entry_is_not_recreated_until_said_again`, `injected_instructions_stay_data`, `injected_instructions_and_ai_memory_blocks_are_never_candidates`, `page_metadata_fields_are_never_candidates`, `auto_approved_auto_improve_pages_are_never_candidates` (an auto-approved page refused; human-approved and hand-written controls admitted; fails with the decider check removed), consolidate `profile::tests::a_stored_page_metadata_field_is_not_a_waiting_habit` (each with a legitimate control; each fails with its guard removed); mcp `integration::admin_profile_routes` `review_and_rebuild_are_root_only_on_a_multi_user_server`; store `integration::session_move` `a_moved_sessions_profile_candidate_follows_the_target_projects_governance` (a session moved into an opted-out project stops counting and one moved into a restricted project is marked restricted; an open-target control still counts, from the target; fails with the `move_session` re-stamp removed); residue control in row 25 | STRONG |+| 1h | The profile learns only from what it may: the user's own prompts and curated pages, from contributing projects, never another operator's words in a private profile and never a restricted project in a shared one; stored text stays data | `ai-memory-store/src/profile.rs` `profile_prompts_since` (only `user-prompt` observations), `auto_improve_decided_by` (the decider agent a page's `auto_improve_proposal_id` resolves to), `profile_harvest_projects` / `profile_candidates` (`profile_contribute = 0` excluded, including candidates recorded before the opt-out); `ai-memory-store/src/ops.rs` `move_session` (a moved session's `session:<id>` prompt candidates are re-stamped into the target project in the same transaction, so they answer to its contribute flag and access mode, #1265); `ai-memory-consolidate/src/profile.rs` `user_written` (shared with the verbatim-residue caller in row 25: a harness turn or Codex's injected instructions stored as a prompt is skipped whole, and ai-memory's routing and untrusted-history blocks, fenced by markers on their own lines, are cut out before any sentence is read), `looks_like_scripted_prompt` (scripted one-shot prompts are skipped whole) and `forgoes_a_capability` (a capability ban needs explicit cross-project scope; an affirmative preference keeps the normal project threshold), the auto-approved-proposal skip in `harvest_project` (a page the auto-improve scheduler auto-approved is model output nobody reviewed and never becomes a candidate; a human-approved page, or one whose proposal id has no row, stays curated, #1211), `convergence_targets` (a `user` target keeps only candidates whose `contributor` is that operator, from projects the per-project choke point lets them read; a `global`/`workspace` target on an operator-distinguishing server drops restricted projects), `min_contributors` / `converge` (a team profile admits a statement only on evidence from at least two distinct operators, so one operator cannot plant a default in everyone's session start) (never rewrites a page without its `generated_by` stamp or whose body changed; `profile_entry_ledger` keeps a forgotten entry out), `classify_batch` / `merge_entry` (sanitized, JSON-encoded input; the evidence quote is always the user's sentence) | consolidate `integration::profile_harvest` `tool_output_is_never_a_candidate`, `an_opted_out_project_is_never_harvested`, `a_private_profile_never_harvests_another_operator`, `a_team_profile_never_harvests_a_restricted_project`, `a_team_profile_needs_more_than_one_operator` (one operator in two open projects not admitted; a second operator admits it; fails with the threshold at one), `a_personal_profile_admits_one_operators_habit` (control), `a_hand_edited_entry_is_never_clobbered`, `a_forgotten_entry_is_not_recreated_until_said_again`, `injected_instructions_stay_data`, `injected_instructions_and_ai_memory_blocks_are_never_candidates`, `scripted_one_shot_prompts_do_not_become_global_defaults`, `capability_bans_stay_out_while_affirmative_habits_need_two_projects` (bans repeated in two projects are refused; an affirmative habit needs two projects and is then admitted; fails with the capability guard removed), `page_metadata_fields_are_never_candidates`, `auto_approved_auto_improve_pages_are_never_candidates` (an auto-approved page refused; human-approved and hand-written controls admitted; fails with the decider check removed), consolidate `profile::tests::a_stored_page_metadata_field_is_not_a_waiting_habit` (each with a legitimate control; each fails with its guard removed); mcp `integration::admin_profile_routes` `review_and_rebuild_are_root_only_on_a_multi_user_server`; store `integration::session_move` `a_moved_sessions_profile_candidate_follows_the_target_projects_governance` (a session moved into an opted-out project stops counting and one moved into a restricted project is marked restricted; an open-target control still counts, from the target; fails with the `move_session` re-stamp removed); residue control in row 25 | STRONG || 1i | SessionEnd's bounded digest cannot read a foreign session by raw id | `ai-memory-store/src/reader.rs` `session_has_substantive_observation` joins the session row to the caller's `(workspace_id, project_id)`; `read_session_observations` validates that same tuple inside the read transaction before exposing its bounded snapshot, returning the same `SessionCollision` refusal for foreign and missing ids; `ai-memory-hooks/src/router.rs` supplies only the scope pinned by hook admission | `multi_session.rs` `session_end_readers_refuse_foreign_session_ids` (sibling-project and cross-workspace tuples cannot learn the substantive bit or open the snapshot; a missing id gets the same refusal; the owning tuple reads the one-row summary as the legitimate control). Removing either scope predicate fails its corresponding assertion | STRONG || 1i2 | The consolidation session read fails closed on a session with no observations in its target scope, and memory is bounded by the selection, not the session | `ai-memory-store/src/reader.rs` `read_session_observations_in_scope` opens the bounded session snapshot only when at least one observation of the session exists in the caller's `(workspace_id, project_id)` (an `EXISTS` over `observations`), returning `SessionCollision` for foreign, purged and missing alike; `SessionObservationSnapshot::projection_totals` reads `COUNT(*)` and `MIN`/`MAX(created_at)` in one aggregate inside the same read transaction; `SessionObservationSnapshot::row_by_rowid` re-reads a single row only when both `session_id = ?1` and `rowid = ?2` match, so a legitimate snapshot cannot fetch another session's body by raw rowid; `ai-memory-consolidate/src/projection.rs` `project_session_observations` streams rows one at a time, keeping only the two anchors' rowids and a bounded top-k heap of the best `limit - 2` rows (the shared `selection_key` the in-memory path sorts with), re-reading only the selected rows by rowid; residue candidate lists exist only while the opt-in residue is on; `ai-memory-consolidate/src/consolidator.rs` `consolidate_session` / `consolidate_session_multi` gate on the scope `resolve_target` already resolves (the observations' majority scope) and map the refusal to `EmptySession`, exactly as an empty session did before; auto-improve keeps its `session_project_ids` gate plus the sessions-row-gated `read_session_observations` (row 1i), and computes preflight, duration, report and prompt from one single snapshot read — a purge committed between the totals aggregate and the preflight decision cannot split the two generations, and a rowless session with the preflight minimums disabled is still reviewed with the empty `(none)` projection, as the full-load path did | `tests/suite/bounded_session_load.rs` `gated_reader_refuses_foreign_scopes` (a foreign workspace and a foreign project are refused with `SessionCollision`; the session's own scope reads the totals as the legitimate control), store `tests/suite/multi_session.rs` `rowid_fetch_refuses_foreign_sessions_with_legitimate_control` (a foreign session's rowid is refused through a legitimate snapshot in both directions; the session's own rowid reads as the control; removing only the session predicate from the rowid fetch fails it), `purged_session_is_refused_without_an_llm_call` (both entry points fail closed with `EmptySession` and no LLM call once the rows are gone), `stale_sessions_row_does_not_divert_the_write` (a sessions row frozen on another project does not move the write out of the observations' project), `hybrid_two_project_session_prompt_is_unchanged` (a two-project session keeps today's exact prompt: every row of the session id is projected, the page lands in the majority project), `streaming_projection_matches_the_frozen_base_projection` and `current_projection_matches_the_frozen_base_projection` (the new paths agree field for field with a verbatim frozen copy of the pre-change `projection.rs` — an independent rule — at the 256/257/300 sample-cap edges and below), `large_session_prompts_match_the_old_full_load_path` (at 150k, 100k and 5k rows the streaming prompts are byte-identical to the frozen projection and both `#[cfg(test)]` full-load oracles, with the top-k heap asserted bounded by the selection cap and zero residue tuples while residue is off), `auto_improve_review_uses_one_generation_of_the_session` (a purge committed inside the review's single snapshot read cannot split the report's count from the prompt's), `auto_improve_review_of_a_rowless_session_with_preflight_off` (a present rowless session with zero minimums still gets its `(none)` review), `zero_budget_streaming_path_keeps_the_old_no_budget_marker` (the zero-budget early return reaches the streaming path byte-identically), and the byte-identical equivalence tests against the full-load oracles (below and above the cap, residue on/off, character-budget pruning, `created_at` ties, 16-KiB bodies, routing text, auto-improve at/above its 48/72 limits and preflight) | STRONG — the LLM input is proven byte-identical to the pre-change full load, including against a frozen verbatim copy of the base projection; dropping the `EXISTS` predicate fails `gated_reader_refuses_foreign_scopes`; removing only the session predicate from the rowid fetch fails the store `rowid_fetch_refuses_foreign_sessions_with_legitimate_control` || 1j | Synthesized answer citations refer only to unambiguous evidence supplied in that request | `ai-memory-mcp/src/server.rs` `build_answer_request` records path-to-`PageId` identity while rendering snippets; `validate_answer_citations` refuses unknown or ambiguous paths before returning any answer text | `query_answer.rs` `answer_rejects_a_citation_not_in_the_request`, `answer_rejects_a_citation_from_an_unqueried_project`, `answer_rejects_same_path_citations_across_scopes`, `answer_global_preferences_accept_unique_paths_and_refuse_collisions`; controls: `answer_true_with_provider_synthesizes_cited_answer`, `answer_deduplicates_citations_in_model_order_and_preserves_unicode`; `server.rs` `answer_sources_distinguish_repeated_rows_from_ambiguous_paths` | STRONG for source identity (the four refusal cases fail with the validator guard removed); generated claims and citation-free abstentions are not semantically verified |