Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

test(inbox): cover queued message editing in browser and mutation gates

Aldo Junior8c9e38436f81
diff --git a/crates/ai-memory-store/tests/suite/agent_messages.rs b/crates/ai-memory-store/tests/suite/agent_messages.rs
index d5b743e4..0a659a17 100644
--- a/crates/ai-memory-store/tests/suite/agent_messages.rs
+++ b/crates/ai-memory-store/tests/suite/agent_messages.rs
@@ -478,21 +478,34 @@ async fn a_message_being_edited_leaves_the_queue_until_it_is_saved() {
let a = project(&store, "team", "sender").await;
let b = project(&store, "team", "receiver").await;
let other = project(&store, "team", "other").await;
+ let other_workspace = project(&store, "other-team", "receiver").await;
let id = store
.writer
.insert_message(message(a, b, "first draft"))
.await
.unwrap();
- assert!(
- store
- .writer
- .begin_message_edit(other.0, other.1, id)
- .await
- .unwrap()
- .is_none(),
- "a project that does not own the mailbox cannot hold the message"
- );
+ for foreign in [other, other_workspace] {
+ assert!(
+ store
+ .writer
+ .begin_message_edit(foreign.0, foreign.1, id)
+ .await
+ .unwrap()
+ .is_none(),
+ "another project or workspace cannot hold the message"
+ );
+ }
+ for replacement in [None, Some((Some("unheld".into()), "unheld".into()))] {
+ assert!(
+ !store
+ .writer
+ .finish_message_edit(b.0, b.1, id, replacement)
+ .await
+ .unwrap(),
+ "save and release require a held message"
+ );
+ }
assert_eq!(
store.reader.pending_message_count(b.0, b.1).await.unwrap(),
1
@@ -536,14 +549,18 @@ async fn a_message_being_edited_leaves_the_queue_until_it_is_saved() {
.is_none(),
"a held message cannot be held again"
);
- assert!(
- !store
- .writer
- .finish_message_edit(other.0, other.1, id, None)
- .await
- .unwrap(),
- "a foreign project cannot release the message"
- );
+ for foreign in [other, other_workspace] {
+ for replacement in [None, Some((Some("foreign".into()), "foreign".into()))] {
+ assert!(
+ !store
+ .writer
+ .finish_message_edit(foreign.0, foreign.1, id, replacement)
+ .await
+ .unwrap(),
+ "another project or workspace cannot save or release the held message"
+ );
+ }
+ }
assert!(
store
diff --git a/crates/ai-memory-web/tests/suite/operations.rs b/crates/ai-memory-web/tests/suite/operations.rs
index 0d1f51e7..760025b8 100644
--- a/crates/ai-memory-web/tests/suite/operations.rs
+++ b/crates/ai-memory-web/tests/suite/operations.rs
@@ -1663,37 +1663,110 @@ async fn operations_edit_needs_write_access_to_the_sender_project_too() {
.to_string();
let app = router(store.reader.clone(), wiki);
let scope = json!({"workspace": "team", "project": "dest"});
- let as_user = || {
- edit(&id, "edit")
+ let as_user = |action: &str| {
+ let mut payload = scope.clone();
+ payload["subject"] = json!("Edited subject");
+ payload["body"] = json!("Edited request.");
+ edit(&id, action)
.extension(AuthLevel::User)
.extension(AuthorizedViewer(user))
- .body(Body::from(scope.to_string()))
+ .body(Body::from(payload.to_string()))
.unwrap()
};
+ for action in ["edit", "save", "release"] {
+ let anonymous = edit(&id, action)
+ .extension(AuthLevel::Anonymous)
+ .body(Body::from(scope.to_string()))
+ .unwrap();
+ assert_eq!(
+ app.clone().oneshot(anonymous).await.unwrap().status(),
+ StatusCode::UNAUTHORIZED,
+ "{action}: an anonymous caller cannot edit a human operator's mail"
+ );
+ }
+ for action in ["edit", "save", "release"] {
+ assert_eq!(
+ app.clone().oneshot(as_user(action)).await.unwrap().status(),
+ StatusCode::FORBIDDEN,
+ "{action}: mailbox write access cannot rewrite a sender with only read access"
+ );
+ }
assert_eq!(
- app.clone().oneshot(as_user()).await.unwrap().status(),
- StatusCode::FORBIDDEN,
- "write access to the mailbox alone does not let a user rewrite another project's mail"
+ store.reader.pending_message_count(ws, dest).await.unwrap(),
+ 1
);
+ store
+ .writer
+ .grant_memory(user, source, GrantLevel::Write, None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .grant_memory(user, dest, GrantLevel::Read, None)
+ .await
+ .unwrap();
+ for action in ["edit", "save", "release"] {
+ assert_eq!(
+ app.clone().oneshot(as_user(action)).await.unwrap().status(),
+ StatusCode::FORBIDDEN,
+ "{action}: sender write access cannot rewrite a read-only mailbox"
+ );
+ }
assert_eq!(
store.reader.pending_message_count(ws, dest).await.unwrap(),
- 1,
- "the refusal left the message queued"
+ 1
);
store
.writer
- .grant_memory(user, source, GrantLevel::Write, None)
+ .grant_memory(user, dest, GrantLevel::Write, None)
.await
.unwrap();
assert_eq!(
- app.clone().oneshot(as_user()).await.unwrap().status(),
+ app.clone().oneshot(as_user("edit")).await.unwrap().status(),
StatusCode::OK
);
assert_eq!(
store.reader.pending_message_count(ws, dest).await.unwrap(),
0
);
+
+ // Recheck authorization on a held message: a grant may change after Edit.
+ for restricted in [source, dest] {
+ store
+ .writer
+ .grant_memory(user, restricted, GrantLevel::Read, None)
+ .await
+ .unwrap();
+ for action in ["save", "release"] {
+ assert_eq!(
+ app.clone().oneshot(as_user(action)).await.unwrap().status(),
+ StatusCode::FORBIDDEN,
+ "{action}: losing either write grant must keep the message held"
+ );
+ }
+ assert_eq!(
+ store.reader.pending_message_count(ws, dest).await.unwrap(),
+ 0
+ );
+ store
+ .writer
+ .grant_memory(user, restricted, GrantLevel::Write, None)
+ .await
+ .unwrap();
+ }
+ assert_eq!(
+ app.clone().oneshot(as_user("save")).await.unwrap().status(),
+ StatusCode::OK
+ );
+ assert_eq!(
+ store.reader.pending_message_count(ws, dest).await.unwrap(),
+ 1
+ );
+ assert_eq!(
+ app.clone().oneshot(as_user("edit")).await.unwrap().status(),
+ StatusCode::OK
+ );
assert_eq!(
app.oneshot(
edit(&id, "release")
@@ -1707,4 +1780,11 @@ async fn operations_edit_needs_write_access_to_the_sender_project_too() {
StatusCode::OK,
"root can release a held message"
);
+ let popped = store
+ .writer
+ .pop_message(codex_claim(ws, dest), Some(id.parse().unwrap()))
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(popped.body, "Edited request.");
}
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index f6200c04..3f6018df 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -93,7 +93,7 @@ the legitimate restricted-project control and the failed-query cases.
| 8f | Messaging: the web mailbox shows a restricted sender's name and a card's count only to a reader of that repository; it never consumes mail | `ai-memory-store/src/reader.rs` `list_inbox_with_senders` (`readable_repository_predicate("sp.id", viewer)` on the sender join, so the name is `NULL` for an unreadable sender) and `pending_inbox_counts` (`readable_repository_predicate("p.id", viewer)`); `ai-memory-web/src/routes/project.rs` `mailbox` is `list`-only, no pop/cancel route exists, and `mailbox_scope` matches the URL's exact project name (as `list_pages` does), so an alias never shows another project's mail | `routes.rs` `web_mailbox_hides_restricted_sender_names_and_cards` (a granted reader of the recipient is shown "a project you cannot read", the restricted sender's name and card never reach the grid, alice as the control; fails with either predicate removed), `web_mailbox_lists_only_this_projects_inbox_and_never_consumes_it` (sender and bystander pages show nothing of the recipient's mail, a POST is 405 and the message is still pending, the body is HTML-escaped), `web_mailbox_does_not_follow_a_project_alias` (a legacy key that resolves to `acme-api` shows none of its mail on `/w/default/api`; `acme-api` itself is the control) | STRONG |
| 8h | Per-response usage stays scoped to project/session/owner and cannot be inflated by replay or reduced by partial reports | `ai-memory-store/src/reader.rs` `token_usage_report_page` applies the resolved project/session, `OwnerFilter`, search and signals before ordering/pagination; summary totals retain the full authorized scope; `ops.rs` `upsert_token_calls` keys native ids by session and merges monotonic counters in the writer transaction | Hooks `live_token_calls_update_open_sessions_without_an_end_event` attempts a foreign workspace/project and owner with an authorized control; web `operations_agent_aggregates_and_drilldowns_apply_ownership_before_totals`; hooks `live_token_calls_scrub_private_labels_before_truncating` refuses private/malformed ids and tests a secret crossing the model-label size bound with a public control; store `live_token_usage.rs` checks replayed/partial row and aggregate consistency and reused native ids across sessions, harnesses and projects; the Rust mutation campaign requires lowered response counters and wrong Codex cache accounting to fail their regression tests. `token_call_queries_search_and_order_before_pagination_with_scope_and_owner_guards` checks a tiny newest response beyond fifty larger ones, search, pages, foreign session and owner isolation with root controls; mutation probes remove the owner/search predicates and require assertion failures. CLI cursor tests cover 300 responses, byte windows, incomplete records and enqueue failure; the native hook and cursor mutation probes require failures if progress resets or advances before enqueue. Browser `capture-backlog`, `call-history` and `session-live-usage` exercise native capture through delivery, full-history queries and live session updates. | STRONG |
| 8i | Live sidebar notifications and browser mailbox context hide restricted project names/counts; message sends preserve write authorization on both coordinates, sanitization and admission; directed mail can only be claimed by its harness | `ai-memory-web/src/routes/inbox.rs` derives queue context from viewer-filtered projects and grouped pending counts, honors explicit scope and refuses partial/foreign scope; it uses `Capability::NormalWrite` and guarded source/target scope lookups; `Wiki::send_agent_message` sanitizes and admits before the writer; `ops.rs` checks `to_agent` in selection and the atomic claim | `notifications.rs` uses viewer-filtered grouped counts, returns at most five project names without message content and disables caching; state-filtered history retains both coordinate guards before pagination, and received mail defaults to pending. `operations_notifications_are_read_only_and_hide_restricted_projects` attempts disclosure with root/read controls and tests non-consumption; the mutation gate removes its viewer filter and requires failure. Browser `notifications` checks anonymous refusal, live appearance/collection, correct project links and clearing stale data on a 403. `operations.rs` `operations_inbox_queue_context_hides_foreign_projects_and_preserves_mail` attempts restricted-project disclosure and explicit/partial-scope access with legitimate read/root controls; the core mutation gate removes the project visibility filter and requires failure. Browser `mailbox-context` exercises same-name projects in different workspaces, navigation, responsive links and non-consuming reads. `operations.rs` tests anonymous/read-only refusal with write/root controls, write grants on both coordinates, sanitizer/admission refusals and explicit cross-workspace delivery; `agent_messages.rs` `addressed_messages_are_claimed_once_only_by_the_selected_harness`; real HTTP/Chromium `web_dashboard_browser.mjs` `delivery` verifies legacy GET-only auth, cleared one-request credentials, escaped text, wrong-harness refusal and claim-once; `check-dashboard-core-mutations.py` removes harness checks and requires the claim test to fail | STRONG |
-| 8j | Editing a queued message needs write access to its mailbox and to the project it came from, and a held message cannot be claimed | `ai-memory-web/src/routes/inbox.rs` `editable_message` resolves the mailbox with `ProjectAccess::Write`, then finds the sending project among the viewer's visible projects and requires `ProjectAccess::Write` on it; `ops.rs` `begin_message_edit` and `finish_message_edit` match the recipient coordinate and the expected state in one `UPDATE`; the claim path selects only `pending` | web `operations_edit_needs_write_access_to_the_sender_project_too` (write on the mailbox alone is refused, a user with both grants and root succeed), `operations_edit_refuses_foreign_collected_and_malformed_requests` (missing UI header, cross-origin, foreign mailbox, collected, not held); store `a_message_being_edited_leaves_the_queue_until_it_is_saved` (a foreign project cannot hold or release it, a held message cannot be popped even by id) and `collected_or_cancelled_mail_cannot_be_taken_for_editing` | STRONG |
+| 8j | Editing a queued message needs write access to its mailbox and to the project it came from, and a held message cannot be claimed | `ai-memory-web/src/routes/inbox.rs` `editable_message` resolves the mailbox with `ProjectAccess::Write`, then finds the sending project among the viewer's visible projects and requires `ProjectAccess::Write` on it; `ops.rs` `begin_message_edit` and `finish_message_edit` match the recipient coordinate and the expected state in one `UPDATE`; the claim path selects only `pending` | web `operations_edit_needs_write_access_to_the_sender_project_too` (write on the mailbox alone is refused, a user with both grants and root succeed), `operations_edit_refuses_foreign_collected_and_malformed_requests` (missing UI header, cross-origin, foreign mailbox, collected, not held); store `a_message_being_edited_leaves_the_queue_until_it_is_saved` (a foreign project cannot hold or release it, a held message cannot be popped even by id) and `collected_or_cancelled_mail_cannot_be_taken_for_editing`; the web test attempts edit/save/release with read-only access to either coordinate, also after the message is held, with both-grant and root controls. The store test refuses both same-workspace foreign projects and a same-name project in another workspace, for hold/save/release. Core mutations `edit-mail-with-read-only-mailbox`, `edit-mail-with-read-only-sender`, `hold-foreign-mail-for-editing`, `finish-editing-foreign-mail`, `edit-collected-or-cancelled-mail`, `finish-editing-unheld-mail` and `claim-mail-held-for-editing` require a passing baseline and the focused assertion failure. Browser `message-editing` uses real HTTP and native claims to exercise save, discard, reload recovery and collected-mail refusal; three browser faults break hold/save/discard | STRONG |
| 9 | Scope resolution fail-closed | `ai-memory-store/src/scope.rs` no-create `lookup_existing_*`; identity-aware lookup accepts exact/canonical/v2-basename keys only when they deduplicate to one UUID; `ops.rs` `resolve_project_name_for_write` performs write authorization, optional name-only promotion, and audit in one writer transaction; create only via `create_explicit_scope`; `ops.rs` `get_or_create_project_as` — the capture and managed-run creator path — consults the same coordinate lookup before inserting, so a name a promoted project still answers to (its `legacy_name` or `canonical_name`) reuses that row, an ambiguous name is refused, and no twin is minted under a key the read path already resolves (the lookup is skipped only while the schema predates V76, via `project_coordinates::supports_coordinates`). The admin destructive project routes (`admin.rs` `resolve_target_for_admin`, used by `purge-project` / `rename-project` / `move-project`) accept a bare `project_id` as an alternative to the name: it is parsed to a UUID (400 on a malformed one), looked up **within the workspace the request named** via `ReaderPool::project_name_by_id` (404 when it names no row there, so a real id from another workspace is refused rather than resolved), and the two spellings are mutually exclusive (both or neither is a 400). `list-projects` carries the id in each row, and inherits the same row-level visibility filter as the name, so a restricted project leaks neither. `ProjectNameAmbiguous` refuses cross-forge/multi-candidate keys before mutation; its message names each holder and the key it matched by, but a restricted holder only as "a restricted project", because the lookup runs before any caller is authorized and the project list hides restricted names from callers without a grant; an audit failure after the name UPDATE rolls the transaction back. V76's derived-key indexes bound hot lookup to exact/canonical/legacy equality probes with at most four rows. Promoting public APIs return `ResolvedWriteScope` metadata (no untraced promotion API); MCP, admin, and managed-workstream write entry points make Wiki refresh/checkpoint the committed scope manifest after promotion and surface `manifest_warning` on success or any later operation failure; pure managed-run input validation precedes promotion. A managed run whose `project` is the name its checkout's git remote derives (`PrepareManagedRunRequest.repository_identity`, accepted only through `accept_wire_identity` and only when `path_style_name` equals the requested name) resolves through `resolve_project_by_identity_for_capture` — the identity holder, else the cwd-prefix project with `$HOME` excluded, claimed or renamed only for a writer — and then `authorize_scope_for(Write)` on the writer connection, so an identity can neither redirect a differently named run nor open, claim, or create a project the caller may not write; Project manifests persist the typed full identity/source and derived keys so clean reindex restores the same UUID and lookup behavior. Also `ai-memory-hooks/src/router.rs` `workspace_override_is_rescope` — the hook router's session-sticky gate resolves a marker's `workspace` override via this same no-create `lookup_existing_workspace` (never a hand-rolled lookup) and fails closed (treats it as a rescope, disqualifying sticky) on a different or unresolvable workspace; only an override that resolves to the session's OWN workspace is not a rescope (#976) | `scope.rs` `read_resolution_table_driven`, `multi_scope_resolution_deduplicates_and_validates`, `identity_resolution.rs` `a_capture_naming_a_promoted_projects_legacy_key_reuses_it` (a capture naming the promoted project's legacy key lands in it, creates nothing and leaves the name resolvable), `a_capture_of_an_existing_exact_name_still_lands_there`, `a_capture_of_a_new_name_still_creates_its_project` (controls: the fallback runs only after the exact-name miss and still records the creator), hooks `two_api_checkouts_with_different_remotes_get_two_projects` (an identity-less capture under a key two projects claim refuses and creates nothing; a fresh folder-named capture still creates its project as the control), `a_slashed_label_reaches_only_a_project_the_caller_may_use` (a `workspace/project` label passed as the project is authorized as the pair it names and creates nothing when refused; granted control), `a_slashed_write_resolves_its_own_pair_and_never_creates`, `an_existing_slashed_project_wins_over_the_split`, no-auto-create + `unscoped_write_with_unresolvable_coordinate_errors`; `dual_key_scope.rs` `page_write_failure_after_promotion_preserves_manifest_warning`, `handoff_failure_after_promotion_preserves_manifest_warning`; `workstream.rs` `managed_run_rejects_mutually_exclusive_selection_before_promotion`, `managed_run_downstream_failure_after_promotion_preserves_manifest_warning`; `identity_resolution.rs` `canonical_and_legacy_reads_resolve_one_legacy_row_without_renaming`, `authorized_write_promotes_in_place_and_preserves_dependents_and_legacy_lookup`, `read_only_user_cannot_promote_a_legacy_name`, `canonical_target_conflict_rolls_back_the_promotion`, `audit_failure_rolls_back_promotion_and_keeps_the_writer_alive`, `exact_name_that_is_another_forges_canonical_key_fails_closed`, `an_ambiguous_name_names_its_holders_but_not_a_restricted_one` (restricted holder unnamed; open holder named as the control), `concurrent_legacy_and_canonical_resolve_or_create_converge_on_one_uuid`; admin `admin_purge.rs` `purge_project_refuses_a_real_id_from_another_workspace` (a row that really exists in another workspace answers 404 from `default` and is left intact), admin_rename/admin_move `rename_project_refuses_a_real_id_from_another_workspace` / `move_project_refuses_a_real_id_from_another_workspace` (the same for rename and move, the foreign project keeps its name and workspace, with the same id accepted from its own workspace as the control), `purge_project_still_refuses_an_ambiguous_name_by_default` (a name held by two rows -- one via its `legacy_name` -- stays a 400 and purges nothing), `purge_project_by_id_reaches_the_twin_and_leaves_the_name_holder_intact` (legitimate control: the id reaches the row the name could not, and the name-holder survives with its name), and store `list_projects_with_stats_hides_a_restricted_projects_id_from_an_ungranted_viewer` (the id is absent exactly where the name is, for an ungranted viewer, and present for the operator -- bite-checked with the visibility filter removed); `project_coordinates.rs` `shared_candidate_query_deduplicates_before_bound_and_uses_only_indexes`; wiki `promoted_identity_round_trips_through_manifest_and_clean_reindex`, `old_project_manifest_without_identity_still_reindexes`, `reindex_rejects_project_coordinate_fields_that_do_not_match_identity`; admin `write_page_surfaces_manifest_failure_after_promotion`, `bootstrap_surfaces_manifest_failure_after_promotion`, `move_project_merge_surfaces_destination_promotion_manifest_warning`, `move_session_create_surfaces_destination_promotion_manifest_warning`; `multi_session.rs` `two_operators_promote_two_clone_keys_to_one_uuid_without_moving_active_pointers`; MCP `dual_key_scope.rs`; hooks `workstream.rs` `managed_run_by_remote_identity_claims_the_folder_named_project`, `managed_run_by_remote_identity_routes_past_an_identityless_twin` (name-only control is ambiguous), `managed_run_identity_never_redirects_another_project_name`, `managed_run_by_remote_identity_refuses_a_viewer_without_write` (outsider refused with no project created; granted member admitted as the control), `managed_run_identity_never_claims_a_restricted_legacy_project` (an outsider whose cwd sits in a restricted identity-less project is refused, the identity stays unrecorded and no twin appears; fails with either the writer's claim check or the route's write check removed; a granted member claims it as the control), `managed_run_identity_routing_stays_inside_the_requested_workspace`, `concurrent_identity_runs_on_a_legacy_project_converge_on_it` (invariant #16), `managed_run_promotion_refreshes_the_scope_manifest`, `managed_run_discloses_manifest_failure_after_committed_promotion` static read/write/authz/cross-workspace/cross-forge cases; `router.rs` `workspace_override_is_rescope_only_on_a_genuine_workspace_change` (same/different/unresolvable workspace cases), `sticky_routing_keeps_the_session_project_across_a_sibling_checkout` (regression: same workspace forwarded on every event + `project_src=repo-root` from a nested checkout stays sticky), `sticky_routing_still_rescopes_when_marker_names_a_different_workspace_mid_session` (opposite direction: a genuinely different workspace still rescopes even under `sticky`) | STRONG |
| 10 | Destructive-op live-process refusal + confirm flags (invariant #9); `purge-project`'s `dry_run` always wins over `confirm` so a preview request can never become destructive; an explicitly empty or whitespace-only CLI scope flag cannot silently select the checkout | `ai-memory-cli/src/commands/process_guard.rs` `sibling_processes` + confirm flags in `reset`/`restore`/`reindex`/`uninstall --purge-data`/`purge_project`; `admin.rs` `handle_purge_project` checks `req.dry_run` unconditionally, before `req.confirm`, mirroring `reclaim-ledger-versions`; `ai-memory-cli/src/commands/mod.rs` `resolve_scope_noting_marker_project`, `resolve_scope_with_marker`, and `resolve_workspace` call `commands::refuse_empty_explicit` at the shared choke point before resolution or HTTP | `admin_purge.rs` confirm→400; `removal.rs` — injected live-sibling makes each destructive command bail before touching the data dir; `uninstall.rs` `purge_guard_refuses_a_live_sibling_before_stopping_the_service` — `uninstall --purge-data` checks for siblings (the `setup` service's own pid excepted) before it stops that service, and `purge_guard_rechecks_after_stopping_the_service` refuses when the stopped service is still alive; `admin_purge.rs` `purge_project_confirm_true_and_dry_run_true_still_only_previews` — `{"confirm": true, "dry_run": true}` deletes nothing (the regression this row now also covers); `ops.rs` `purge_project_dry_run_changes_nothing` — every project-scoped row count, the `purged_scopes` tombstone, and the `audit_log` row are identical before/after a `PurgeMode::Preview` run; `ops.rs` `purge_project_counts_collateral_damage_in_another_project` and `admin_purge.rs` `purge_project_dry_run_and_confirmed_purge_both_report_collateral_damage_in_another_project` — a purge of project P collaterally deletes an observation, and orphans a handoff's session reference, in a *different* project Q (via `sessions` cascading out of P), and both the preview and the confirmed report count it; CLI `commands::tests::resolve_scope_and_workspace_refuse_empty_and_whitespace_flags` and `tests/suite/marker_scope.rs` `restore_page_refuses_empty_scope_flags_without_sending_a_mutation` refuse empty and whitespace-only `--workspace`/`--project` with no POST; omitted, partially explicit and fully explicit scopes reach only the expected target as controls. Without the guard, the shipped binary sends the restore to the marker scope and the test fails | STRONG |
| 10b | Session purge is scope+owner-bound (no cross-session/project over-delete); `purge-session`'s `dry_run` always wins over `confirm`, same as `purge-project` | `ai-memory-store/src/ops.rs` `purge_session` — selection scoped to `(workspace_id, project_id)` and keyed on this session's own `summary_page_id` **or** `path='sessions/<sid>.md'` + `json_extract(frontmatter_json,'$.session_id')=<sid>` (frontmatter owner, not the recursive latest-chain); `in_scope==0 → NotFound` fail-closed; the session's prompt `profile_candidates` (`source_ref = 'session:<sid>'`, a globally unique id) are deleted in whichever project the harvest filed them, matching the `observations` cascade they were harvested from; whole op in one transaction, and the tombstone it leaves is checked by `begin_session_row` and by the new-session arm of `admit_hook_session_event`; `move_project_workspace` re-stamps the `purged_sessions` tombstone with the rest of the project so it still matches after a move; `admin.rs` `handle_purge_session` checks `req.dry_run` unconditionally, before `req.confirm` | `ops.rs` `purge_session_leaves_a_sibling_session_in_the_same_project_intact`, `…refuses_a_session_from_another_project_and_deletes_nothing`, `…refuses_a_session_from_another_workspace`, `…does_not_delete_an_identically_pathed_page_in_another_project`, `…removes_older_summary_versions_without_deleting_prior_manual_page` (#862); `admin_purge.rs` `purge_session_confirm_true_and_dry_run_true_still_only_previews` — `{"confirm": true, "dry_run": true}` deletes nothing; `ops.rs` `purge_session_dry_run_changes_nothing` — every table a session purge touches, the `purged_sessions` tombstone, and the `audit_log` row are identical before/after a `PurgeMode::Preview` run; `ops.rs` `purge_session_counts_collateral_damage_in_another_project` and `admin_purge.rs` `purge_session_dry_run_and_confirmed_purge_both_report_collateral_damage_in_another_project` — purging session S collaterally deletes an observation, and orphans a handoff's session reference, in a *different* project (via `S`'s own id cascading), and both the preview and the confirmed report count it; `admin_purge.rs` `purge_session_dry_run_refuses_a_session_outside_its_named_scope` — the same session previewed under a different real project (same workspace) or a different real workspace whose project shares the name both 404 with no counts in the body, with the session's own scope as the 200 control; the `purged_sessions` tombstone holds against live hook ingest as well as `begin_session`: `ops.rs` `a_purged_session_is_not_recreated_by_hook_admission` (`admit_hook_session_event` refuses a purged session and writes nothing, with a sibling session and the same id in another project admitted as controls) and `router.rs` `async_processing_drops_events_of_a_purged_session` (the late delivery is a terminal `dropped_invalid`, not a failure the client retries) and `batch_drops_a_purged_session_then_commits_next_item` (the batch endpoint acknowledges it as `dropped_invalid` and commits the next item instead of stopping fail-fast); the user's own sentences the profile harvested from the session's prompts go with it: `ops.rs` `purge_session_deletes_the_profile_candidates_harvested_from_it` (including the candidate harvested from a prompt the session recorded in another project, whose observation the purge deletes through the cascade; a sibling session's candidates in both projects and a page candidate survive); `ops.rs` `a_purged_session_stays_purged_after_its_project_moves` (after `move-project`, `begin_session` for the purged id in the destination is refused with `SessionPurged`; a fresh session there is admitted as the control) | STRONG |
diff --git a/docs/testing-dashboard.md b/docs/testing-dashboard.md
index a872e7be..711d40b9 100644
--- a/docs/testing-dashboard.md
+++ b/docs/testing-dashboard.md
@@ -15,6 +15,8 @@ cargo build --locked --bin ai-memory
npx --yes [email protected] install --with-deps --only-shell chromium
node tests/e2e/web_dashboard_browser.mjs
node tests/e2e/web_dashboard_mutations.mjs
+# Focused edit flow, including its three browser faults.
+node tests/e2e/web_dashboard_mutations.mjs --case=message-editing
python3 scripts/check-dashboard-core-mutations.py
# Focused mailbox isolation probe (the CI gate runs every case).
python3 scripts/check-dashboard-core-mutations.py --case expose-restricted-mailbox-projects
@@ -70,6 +72,8 @@ guessed coordinates.
| Pending notification links and the default received mailbox find older messages behind collected history; explicit all/claimed filters retain history | Rust `operations_pending_mail_is_filtered_before_history_pagination`; server state predicate runs before LIMIT/OFFSET |
| Resumed substantive work reopens scoped API/detail reads, leaves completed listings, refuses a foreign project and closes after another SessionEnd | Browser `resumed-session`; store `session_activity` tests preserve the persisted watermark and owner/project controls |
| Legacy browser reads cannot send; invalid tokens are refused and cleared; authorized sends reach the chosen harness once | Browser `delivery`, against real HTTP auth and native CLI claims; Rust `operations_message_write_obeys_root_user_and_project_grants`, `operations_message_requires_write_access_to_both_project_coordinates`, store `addressed_messages_are_claimed_once_only_by_the_selected_harness` |
+| Editing holds mail outside the native claim queue; save preserves the edited text and id, discard preserves the original, held edits survive navigation/reload, and stale edits refuse collected mail | Browser `message-editing`; its `skip-message-edit-hold`, `lose-saved-message-text` and `save-discarded-message-text` faults must fail the same case |
+| Every edit/save/release requires write access to both mailbox and sender, including after a grant changes; foreign workspaces/projects and invalid lifecycle states cannot be edited | Rust `operations_edit_needs_write_access_to_the_sender_project_too`, `a_message_being_edited_leaves_the_queue_until_it_is_saved`, `collected_or_cancelled_mail_cannot_be_taken_for_editing`; seven core mutation probes remove these guards |
| Sanitization, admission rejection, foreign origin and unknown recipients | Rust `operations_browser_messages_use_the_configured_sanitizer_and_admission`, `operations_browser_send_refuses_cross_origin_unknown_recipient_and_empty_body`; browser `delivery` checks escaped message text |
| Usage reaches the server before session-end, repeated reports do not add calls, refresh preserves active tab/filter/focus | Browser `live-usage`; hooks `live_token_calls_update_open_sessions_without_an_end_event` |
| More than 256 responses and a transcript larger than 4 MiB recover across successive hook processes, without advancing on enqueue failure or duplicating responses | Browser `capture-backlog` uses native hooks, spool drain, the real server and dashboard; CLI `native_hook_recovers_a_response_backlog_and_does_not_advance_on_spool_failure`, `live_token_cursor_replays_until_commit_then_recovers_every_response`, `live_token_cursor_crosses_byte_windows_and_retries_partial_usage` |
@@ -123,6 +127,12 @@ counts only if the response was changed and the intended behavioral case failed.
| Count Codex cache as fresh input | Codex transcript parser regression |
| Overwrite a response with lower replayed counters | Response/session consistency regression |
| Remove harness checks from the claim lookup and atomic update | Directed harness claim regression |
+| Open the editor without holding the message on the server | `message-editing` |
+| Send different text on save or overwrite the original on discard | `message-editing` |
+| Accept read-only access to the mailbox or sender during editing | Edit authorization regression, including grant changes on held mail |
+| Remove mailbox coordinates from hold or save/release | Foreign project/workspace edit regression |
+| Hold collected/cancelled mail or save/release unheld mail | Edit lifecycle regressions |
+| Let claim selection, metadata and atomic update accept held mail | Held-mail claim regression |
Browser results are summarized in `target/web-dashboard-mutations.json`. The
source anchors used to inject a fault need updating when the implementation is
diff --git a/scripts/check-dashboard-core-mutations.py b/scripts/check-dashboard-core-mutations.py
index 3ed6820d..d5eed610 100644
--- a/scripts/check-dashboard-core-mutations.py
+++ b/scripts/check-dashboard-core-mutations.py
@@ -101,6 +101,51 @@ CASES = [
"replacements": [("(to_agent IS NULL OR to_agent = ?3)", "(?3 IS NOT NULL)", 2), ("(to_agent IS NULL OR to_agent = ?4)", "(?4 IS NOT NULL)", 1)],
"command": ["cargo", "test", "-p", "ai-memory-store", "--lib", "addressed_messages_are_claimed_once_only_by_the_selected_harness"],
},
+ {
+ "name": "edit-mail-with-read-only-mailbox", "file": "crates/ai-memory-web/src/routes/inbox.rs",
+ "start": "async fn editable_message(", "end": "/// Take a queued message",
+ "before": "&input.project,\n writer.viewer,\n ProjectAccess::Write",
+ "after": "&input.project,\n writer.viewer,\n ProjectAccess::Read",
+ "command": ["cargo", "test", "-p", "ai-memory-web", "--lib", "operations_edit_needs_write_access_to_the_sender_project_too"],
+ },
+ {
+ "name": "edit-mail-with-read-only-sender", "file": "crates/ai-memory-web/src/routes/inbox.rs",
+ "start": "async fn editable_message(", "end": "/// Take a queued message",
+ "before": "&origin.project_name,\n writer.viewer,\n ProjectAccess::Write",
+ "after": "&origin.project_name,\n writer.viewer,\n ProjectAccess::Read",
+ "command": ["cargo", "test", "-p", "ai-memory-web", "--lib", "operations_edit_needs_write_access_to_the_sender_project_too"],
+ },
+ {
+ "name": "hold-foreign-mail-for-editing", "file": "crates/ai-memory-store/src/ops.rs",
+ "start": "pub fn begin_message_edit(", "end": "/// Put an `editing` message",
+ "before": "to_workspace_id = ?2 AND to_project_id = ?3",
+ "after": "?2 IS NOT NULL AND ?3 IS NOT NULL",
+ "command": ["cargo", "test", "-p", "ai-memory-store", "--lib", "a_message_being_edited_leaves_the_queue_until_it_is_saved"],
+ },
+ {
+ "name": "finish-editing-foreign-mail", "file": "crates/ai-memory-store/src/ops.rs",
+ "start": "pub fn finish_message_edit(", "end": "fn observation_kind_as_str(",
+ "replacements": [("to_workspace_id = ?2 AND to_project_id = ?3", "?2 IS NOT NULL AND ?3 IS NOT NULL", 2)],
+ "command": ["cargo", "test", "-p", "ai-memory-store", "--lib", "a_message_being_edited_leaves_the_queue_until_it_is_saved"],
+ },
+ {
+ "name": "edit-collected-or-cancelled-mail", "file": "crates/ai-memory-store/src/ops.rs",
+ "start": "pub fn begin_message_edit(", "end": "/// Put an `editing` message",
+ "before": "state = 'pending'", "after": "state IN ('pending', 'claimed', 'cancelled')",
+ "command": ["cargo", "test", "-p", "ai-memory-store", "--lib", "collected_or_cancelled_mail_cannot_be_taken_for_editing"],
+ },
+ {
+ "name": "finish-editing-unheld-mail", "file": "crates/ai-memory-store/src/ops.rs",
+ "start": "pub fn finish_message_edit(", "end": "fn observation_kind_as_str(",
+ "replacements": [("state = 'editing'", "state IN ('editing', 'pending')", 2)],
+ "command": ["cargo", "test", "-p", "ai-memory-store", "--lib", "a_message_being_edited_leaves_the_queue_until_it_is_saved"],
+ },
+ {
+ "name": "claim-mail-held-for-editing", "file": "crates/ai-memory-store/src/ops.rs",
+ "start": "pub(crate) fn pop_message_in_transaction(", "end": "/// Cancel",
+ "replacements": [("state = 'pending'", "state IN ('pending', 'editing')", 3)],
+ "command": ["cargo", "test", "-p", "ai-memory-store", "--lib", "a_message_being_edited_leaves_the_queue_until_it_is_saved"],
+ },
]
parser = argparse.ArgumentParser(description=__doc__)
diff --git a/tests/e2e/web_dashboard_browser.mjs b/tests/e2e/web_dashboard_browser.mjs
index d8244d2d..bbf56172 100644
--- a/tests/e2e/web_dashboard_browser.mjs
+++ b/tests/e2e/web_dashboard_browser.mjs
@@ -22,6 +22,7 @@ function contrast(a, b) {
return (values[0] + 0.05) / (values[1] + 0.05);
}
const mutation = process.argv.find(arg => arg.startsWith('--mutation='))?.split('=')[1];
+const selectedCase = process.argv.find(arg => arg.startsWith('--case='))?.split('=')[1];
const mutations = {
'all-panels-visible': {test: 'tabs', from: 'panel.hidden=!selected', to: 'panel.hidden=false'},
'ignore-recipient-workspace': {test: 'recipients', from: 'option.dataset.workspace===scope.dataset.workspace&&', to: ''},
@@ -40,6 +41,9 @@ const mutations = {
'ignore-mailbox-workspace': {test: 'mailbox-context', from: 'url.searchParams.set("workspace",o.dataset.workspace);', to: 'url.searchParams.set("workspace","team");'},
'disable-inbox-notifications': {test: 'notifications', from: ' refreshInboxNotifications();\n})();', to: ' void refreshInboxNotifications;\n})();'},
'ignore-notification-workspace': {test: 'notifications', from: 'url.searchParams.set("workspace",project.workspace);', to: 'url.searchParams.set("workspace","team");'},
+ 'skip-message-edit-hold': {test: 'message-editing', from: 'var data=await call(id,"edit");', to: 'var data={subject:row.dataset.subject||"",body:row.querySelector(".message-body").textContent};'},
+ 'lose-saved-message-text': {test: 'message-editing', from: 'subject:subjectInput.value,body:bodyInput.value', to: 'subject:subjectInput.value,body:"Lost edited request."'},
+ 'save-discarded-message-text': {test: 'message-editing', from: 'await call(id,"release");', to: 'await call(id,"save",{subject:"Discard mutation",body:"Discard mutation"});'},
};
assert(!mutation || mutations[mutation], 'Unknown mutation');
const report = {mutation: mutation || null, mutationApplied: 0, cases: []};
@@ -312,6 +316,69 @@ async function main() {
};
assert.equal(pop('codex'), null);assert.equal(pop('gemini-cli').id, messageId);assert.equal(pop('gemini-cli'), null);
},
+ async 'message-editing'() {
+ const inbox = base + '/web/inbox?workspace=team&project=app';
+ const row = messageId => '.mail-row[data-message-id="' + messageId + '"]';
+ const queue = async (subject, body) => (await (await request('/web/messages', {from_workspace:'team',from_project:'other',to_workspace:'team',to_project:'app',to_agent:'codex',subject,body})).json()).message_id;
+ const pop = messageId => {
+ const result = spawnSync(binary, ['message','pop','--workspace','team','--project','app','--agent','codex','--id',messageId,'--json'], {env:{...env,AI_MEMORY_SERVER_URL:base,AI_MEMORY_DATA_DIR:path.join(artifacts,'edit-client')},encoding:'utf8',timeout:15000});
+ assert.equal(result.status, 0, 'Native claim failed: ' + result.stderr);return JSON.parse(result.stdout).message;
+ };
+ const open = async (messageId, action) => {
+ await cdp.evaluate(`(()=>{const row=document.querySelector(${literal(row(messageId))});if(!row.open)row.querySelector('summary').click();row.querySelector('[data-message-action="${action}"]').click();})()`);
+ await until(() => cdp.evaluate(`!!document.querySelector(${literal(row(messageId) + ' .mail-editor')})`), 'Message editor did not open');
+ };
+ const fill = async (messageId, subject, body) => cdp.evaluate(`document.getElementById(${literal('edit-subject-' + messageId)}).value=${literal(subject)};document.getElementById(${literal('edit-body-' + messageId)}).value=${literal(body)}`);
+ const requeued = messageId => until(() => cdp.evaluate(`document.readyState==='complete'&&!!document.querySelector(${literal(row(messageId) + '[data-state=pending]')})`), 'Edited message did not return to the queue');
+ const savedId = await queue('Original subject', 'Original request.');
+ await cdp.goto(inbox, row(savedId));
+ assert.equal(await cdp.evaluate(`document.querySelector(${literal(row(savedId) + ' [data-message-action]')})`), null, 'Legacy read-only login must not offer editing');
+ assert.equal(await cdp.evaluate(`fetch(new URL('messages/'+${literal(savedId)}+'/edit',document.baseURI),{method:'POST',headers:{'Content-Type':'application/json','X-Ai-Memory-UI':'1'},body:JSON.stringify({workspace:'team',project:'app'})}).then(r=>r.status)`), 401, 'Legacy read-only credentials must not hold mail through the edit route');
+ // The normal suite uses the legacy read-only cookie. This case supplies
+ // an actual root bearer to exercise writes without persisting credentials.
+ await cdp.send('Network.setExtraHTTPHeaders', {headers:{Authorization:'Bearer ' + token}});
+ try {
+ await cdp.reload();await open(savedId, 'begin');
+ assert.equal(await cdp.evaluate(`document.getElementById(${literal('edit-body-' + savedId)}).value`), 'Original request.');
+ assert.equal(pop(savedId), null, 'Opening the editor must hold the real queued message, even for a claim by id');
+ const editedBody = 'Updated <b>literal text</b> for the agent.';
+ await fill(savedId, 'Updated subject', editedBody);
+ await cdp.evaluate(`document.querySelector(${literal(row(savedId) + ' .mail-editor button[type=submit]')}).click()`);
+ await requeued(savedId);
+ assert(await cdp.evaluate(`document.querySelector(${literal(row(savedId) + ' .message-body')}).textContent===${literal(editedBody)}&&!document.querySelector(${literal(row(savedId) + ' .message-body b')})`), 'Saved text must render escaped');
+ const saved = pop(savedId);assert.equal(saved.id, savedId);assert.equal(saved.subject, 'Updated subject');assert.equal(saved.body, editedBody);assert.equal(pop(savedId), null);
+
+ const discardId = await queue('Keep this subject', 'Keep this request.');
+ await cdp.goto(inbox, row(discardId));await open(discardId, 'begin');
+ assert.equal(pop(discardId), null);
+ await fill(discardId, 'Unsaved subject', 'Unsaved request.');
+ await cdp.evaluate(`document.querySelector(${literal(row(discardId) + ' .mail-editor button[type=button]')}).click()`);
+ await requeued(discardId);
+ const discarded = pop(discardId);assert.equal(discarded.id, discardId);assert.equal(discarded.subject, 'Keep this subject');assert.equal(discarded.body, 'Keep this request.');
+
+ const resumedId = await queue('Recover this edit', 'Recover the original request.');
+ await cdp.goto(inbox, row(resumedId));await open(resumedId, 'begin');
+ await fill(resumedId, 'Unsaved before navigation', 'Unsaved before navigation.');
+ await cdp.goto(base + '/web/docs', '.docs-search');await cdp.goto(inbox, '.held-note');
+ assert(await cdp.evaluate('document.querySelector(".held-note").textContent.includes("1 held for editing")'));
+ assert.equal(pop(resumedId), null, 'Leaving the editor must not release held mail');
+ const heldHref = await cdp.evaluate('document.querySelector(".held-note a").href');
+ assert.equal(new URL(heldHref).searchParams.get('state'), 'editing');
+ await cdp.goto(heldHref, row(resumedId));await cdp.reload();await open(resumedId, 'resume');
+ assert.equal(await cdp.evaluate(`document.getElementById(${literal('edit-body-' + resumedId)}).value`), 'Recover the original request.');
+ await cdp.reload();
+ await cdp.evaluate(`(()=>{const row=document.querySelector(${literal(row(resumedId))});row.querySelector('summary').click();row.querySelector('[data-message-action=release]').click();})()`);
+ await until(() => cdp.evaluate(`document.readyState==='complete'&&!document.querySelector('.held-note')&&!document.querySelector(${literal(row(resumedId))})`), 'Discarding a recovered edit must clear the held list');
+ assert.equal(pop(resumedId).body, 'Recover the original request.');
+
+ const collectedId = await queue('Claim race', 'Collected before Edit.');
+ await cdp.goto(inbox, row(collectedId));assert.equal(pop(collectedId).id, collectedId);
+ await cdp.evaluate(`(()=>{const row=document.querySelector(${literal(row(collectedId))});row.querySelector('summary').click();row.querySelector('[data-message-action=begin]').click();})()`);
+ await until(() => cdp.evaluate(`document.querySelector(${literal(row(collectedId) + ' .edit-error')})?.textContent.includes('already collected')`), 'A stale Edit must explain that the agent already collected the message');
+ assert.equal(await cdp.evaluate(`document.querySelector(${literal(row(collectedId) + ' .mail-editor')})`), null);
+ assert.equal(pop(collectedId), null, 'A refused edit must not requeue collected mail');
+ } finally {await cdp.send('Network.setExtraHTTPHeaders', {headers:{}});}
+ },
async 'live-usage'() {
await cdp.goto(project + '?tab=tokens', '#token-usage');await selected('tokens');
assert.equal(await cdp.evaluate('Number(document.querySelector(".usage-metrics strong").textContent)'), 5);
@@ -522,7 +589,10 @@ async function main() {
}
},
};
+ assert(!selectedCase || Object.hasOwn(cases, selectedCase), 'Unknown browser case');
+ assert(!selectedCase || !mutation || mutations[mutation].test === selectedCase, 'Mutation targets another browser case');
for (const [name, run] of Object.entries(cases)) {
+ if (selectedCase && selectedCase !== name) continue;
if (mutation && mutations[mutation].test !== name) continue;
try {await run();report.cases.push({name, passed: true});console.log('PASS ' + name);}
catch (error) {
diff --git a/tests/e2e/web_dashboard_mutations.mjs b/tests/e2e/web_dashboard_mutations.mjs
index 0ec87011..0c56f3b9 100644
--- a/tests/e2e/web_dashboard_mutations.mjs
+++ b/tests/e2e/web_dashboard_mutations.mjs
@@ -26,10 +26,16 @@ const faults = [
['ignore-mailbox-workspace', 'mailbox-context'],
['disable-inbox-notifications', 'notifications'],
['ignore-notification-workspace', 'notifications'],
+ ['skip-message-edit-hold', 'message-editing'],
+ ['lose-saved-message-text', 'message-editing'],
+ ['save-discarded-message-text', 'message-editing'],
];
+const selectedCase = process.argv.find(arg => arg.startsWith('--case='))?.split('=')[1];
+assert(!selectedCase || faults.some(([, name]) => name === selectedCase), 'Unknown browser mutation case');
+
async function run(mutation) {
- const child = spawn(process.execPath, [path.join(here, 'web_dashboard_browser.mjs'), ...(mutation ? ['--mutation=' + mutation] : [])], {env: process.env});
+ const child = spawn(process.execPath, [path.join(here, 'web_dashboard_browser.mjs'), ...(mutation ? ['--mutation=' + mutation] : []), ...(selectedCase ? ['--case=' + selectedCase] : [])], {env: process.env});
let output = '', errors = '';
child.stdout.on('data', data => {output += data;});
child.stderr.on('data', data => {errors += data;});
@@ -44,10 +50,11 @@ async function run(mutation) {
try {
const baseline = await run();
assert.equal(baseline.code, 0, 'Baseline must pass; inspect ' + baseline.directory);
- assert(baseline.result.cases.length >= 16 && baseline.result.cases.every(c => c.passed));
+ assert((selectedCase ? baseline.result.cases.length === 1 : baseline.result.cases.length >= 17) && baseline.result.cases.every(c => c.passed));
manifest.baseline = baseline.directory;
console.log('PASS unmodified server and browser baseline');
for (const [fault, name] of faults) {
+ if (selectedCase && selectedCase !== name) continue;
const mutant = await run(fault);
assert.equal(mutant.code, 1, fault + ' survived or the runner crashed');
assert(mutant.result.mutationApplied > 0, fault + ' never reached the served application');