Skip to content

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

Rust

feat(web,store): edit a queued message from the inbox

Aldo Junior6bd9ac300677
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b01aff3e..c79624a6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,16 @@ version in [`docs/changelog/`](docs/changelog/):
### Added
+- Added editing for queued messages in the web inbox. Edit takes a message that
+ is still waiting out of the queue, so no agent can collect it, and opens an
+ inline editor. Saving puts the new text back at the message's original place
+ in the queue, after the usual sanitizer, size caps and `message_send`
+ admission. Discarding returns it unchanged. A held message shows as Editing,
+ with a count above the list and a way back into the editor. Editing needs
+ write access to the mailbox project and to the project the message came from,
+ and a message an agent already collected cannot be edited. Held messages use a
+ new `editing` state (migration V95) that no claim path selects (#NNN).
+
- Added server-side response investigation to the project dashboard. Responses
can be filtered by UTC period, exact model, harness, session, turn and tool,
with complete pagination, filtered token totals and bounded native turn and
diff --git a/crates/ai-memory-core/src/message.rs b/crates/ai-memory-core/src/message.rs
index 362e1633..0e81eeff 100644
--- a/crates/ai-memory-core/src/message.rs
+++ b/crates/ai-memory-core/src/message.rs
@@ -42,6 +42,9 @@ pub enum MessageState {
Claimed,
/// The sender retracted it before it was popped.
Cancelled,
+ /// The sender took it out of the queue to edit it. It cannot be popped
+ /// until the edit is saved or released, which returns it to `Pending`.
+ Editing,
}
impl MessageState {
@@ -52,6 +55,7 @@ impl MessageState {
Self::Pending => "pending",
Self::Claimed => "claimed",
Self::Cancelled => "cancelled",
+ Self::Editing => "editing",
}
}
}
@@ -64,6 +68,7 @@ impl std::str::FromStr for MessageState {
"pending" => Ok(Self::Pending),
"claimed" => Ok(Self::Claimed),
"cancelled" => Ok(Self::Cancelled),
+ "editing" => Ok(Self::Editing),
other => Err(crate::MemoryError::MalformedRecord(format!(
"unknown message state: {other}"
))),
diff --git a/crates/ai-memory-store/migrations/V93__message_editing_state.sql b/crates/ai-memory-store/migrations/V93__message_editing_state.sql
new file mode 100644
index 00000000..95ebad41
--- /dev/null
+++ b/crates/ai-memory-store/migrations/V93__message_editing_state.sql
@@ -0,0 +1,64 @@
+-- Let a queued message be held out of the queue while its sender edits it.
+--
+-- `agent_messages.state` gains 'editing'. The claim path only ever selects
+-- `state = 'pending'`, so a held message cannot be popped by any harness until
+-- the edit is saved or released, which sets it back to 'pending'. The row keeps
+-- its id and its place in the queue (`created_at`), and `edited_at` records
+-- when the text last changed.
+--
+-- SQLite cannot alter a CHECK constraint, so the table is rebuilt. `Store::open`
+-- turns foreign keys off around the migration runner (a PRAGMA inside
+-- refinery's transaction is ignored), which keeps the DROP from cascading.
+-- Nothing references `agent_messages`. V64 and V91 created its indexes.
+
+CREATE TABLE agent_messages_new (
+ id BLOB PRIMARY KEY NOT NULL,
+ from_workspace_id BLOB NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
+ from_project_id BLOB NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
+ from_agent TEXT NOT NULL,
+ from_session_id BLOB REFERENCES sessions(id) ON DELETE SET NULL,
+ from_owner_user TEXT,
+ to_workspace_id BLOB NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
+ to_project_id BLOB NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
+ subject TEXT,
+ body TEXT NOT NULL,
+ state TEXT NOT NULL DEFAULT 'pending'
+ CHECK (state IN ('pending','claimed','cancelled','editing')),
+ created_at INTEGER NOT NULL,
+ claimed_at INTEGER,
+ claimed_by_session BLOB REFERENCES sessions(id) ON DELETE SET NULL,
+ claimed_by_agent TEXT,
+ claimed_by_user TEXT,
+ to_agent TEXT,
+ edited_at INTEGER,
+ FOREIGN KEY (from_session_id) REFERENCES sessions(id) ON DELETE SET NULL,
+ FOREIGN KEY (claimed_by_session) REFERENCES sessions(id) ON DELETE SET NULL
+);
+
+INSERT INTO agent_messages_new (
+ id, from_workspace_id, from_project_id, from_agent, from_session_id,
+ from_owner_user, to_workspace_id, to_project_id, subject, body, state,
+ created_at, claimed_at, claimed_by_session, claimed_by_agent,
+ claimed_by_user, to_agent
+)
+SELECT
+ id, from_workspace_id, from_project_id, from_agent, from_session_id,
+ from_owner_user, to_workspace_id, to_project_id, subject, body, state,
+ created_at, claimed_at, claimed_by_session, claimed_by_agent,
+ claimed_by_user, to_agent
+FROM agent_messages;
+
+DROP TABLE agent_messages;
+
+ALTER TABLE agent_messages_new RENAME TO agent_messages;
+
+CREATE INDEX idx_agent_messages_inbox
+ ON agent_messages(to_workspace_id, to_project_id, created_at)
+ WHERE state = 'pending';
+
+CREATE INDEX idx_agent_messages_outbox
+ ON agent_messages(from_workspace_id, from_project_id, created_at)
+ WHERE state = 'pending';
+
+CREATE INDEX idx_messages_agent_inbox
+ ON agent_messages(to_workspace_id, to_project_id, state, to_agent, created_at);
diff --git a/crates/ai-memory-store/src/api_credentials.rs b/crates/ai-memory-store/src/api_credentials.rs
index c5dadf19..44704269 100644
--- a/crates/ai-memory-store/src/api_credentials.rs
+++ b/crates/ai-memory-store/src/api_credentials.rs
@@ -470,7 +470,7 @@ mod tests {
|row| row.get(0),
)
.unwrap();
- assert_eq!(version, 92, "update the pin when adding a migration");
+ assert_eq!(version, 93, "update the pin when adding a migration");
let cols: i64 = conn
.query_row(
"SELECT COUNT(*) FROM pragma_table_info('users') \
@@ -748,10 +748,10 @@ mod tests {
)
.unwrap();
assert_eq!(
- cols, 17,
+ cols, 18,
"id, from_workspace_id, from_project_id, from_agent, from_session_id, \
from_owner_user, to_workspace_id, to_project_id, subject, body, state, \
- created_at, claimed_at, claimed_by_session, claimed_by_agent, claimed_by_user, to_agent"
+ created_at, claimed_at, claimed_by_session, claimed_by_agent, claimed_by_user, to_agent, edited_at"
);
}
diff --git a/crates/ai-memory-store/src/dashboard.rs b/crates/ai-memory-store/src/dashboard.rs
index 0cced338..9eef260d 100644
--- a/crates/ai-memory-store/src/dashboard.rs
+++ b/crates/ai-memory-store/src/dashboard.rs
@@ -190,6 +190,30 @@ impl ReaderPool {
.await
}
+ /// Read one message addressed to this recipient project, in any state.
+ /// The recipient coordinate is part of the predicate, so an id belonging to
+ /// another project reads as absent.
+ pub async fn message_in_mailbox(
+ &self,
+ ws: WorkspaceId,
+ project: ProjectId,
+ id: ai_memory_core::MessageId,
+ ) -> StoreResult<Option<AgentMessage>> {
+ self.with_conn(move |conn| {
+ let mut stmt = conn.prepare(&format!(
+ "SELECT {} FROM agent_messages \
+ WHERE id=?1 AND to_workspace_id=?2 AND to_project_id=?3",
+ crate::ops::MESSAGE_COLUMNS
+ ))?;
+ let mut rows = stmt.query_map(
+ params![id.as_bytes(), ws.as_bytes(), project.as_bytes()],
+ crate::ops::row_to_agent_message,
+ )?;
+ rows.next().map(|r| r?).transpose()
+ })
+ .await
+ }
+
/// Read this session's response ledger after applying scope and ownership.
pub async fn session_token_usage(
&self,
diff --git a/crates/ai-memory-store/src/migrations.rs b/crates/ai-memory-store/src/migrations.rs
index ec5fd32a..08eb594a 100644
--- a/crates/ai-memory-store/src/migrations.rs
+++ b/crates/ai-memory-store/src/migrations.rs
@@ -212,6 +212,110 @@ mod tests {
assert_eq!(claude, 1000);
}
+ /// V93 rebuilds `agent_messages` so a message can be held in `editing`.
+ /// Existing mail keeps its text, state, order and addressee, the three
+ /// indexes come back, and `editing` is the only value the constraint gained.
+ #[test]
+ fn v93_accepts_the_editing_state_and_keeps_existing_messages() {
+ let mut conn = Connection::open_in_memory().unwrap();
+ conn.pragma_update(None, "foreign_keys", "OFF").unwrap();
+ run_to(&mut conn, 92).unwrap();
+ conn.execute_batch(
+ "INSERT INTO workspaces(id,name,created_at) VALUES(zeroblob(16),'mail',1);
+ INSERT INTO projects(id,workspace_id,name,created_at) VALUES(zeroblob(16),zeroblob(16),'mail',1);
+ INSERT INTO agent_messages(id,from_workspace_id,from_project_id,from_agent,to_workspace_id,to_project_id,subject,body,state,created_at,to_agent,from_owner_user)
+ VALUES(x'01000000000000000000000000000000',zeroblob(16),zeroblob(16),'other',zeroblob(16),zeroblob(16),'s','queued','pending',5,'codex','user:sender');
+ INSERT INTO agent_messages(id,from_workspace_id,from_project_id,from_agent,to_workspace_id,to_project_id,body,state,created_at,claimed_at,claimed_by_agent)
+ VALUES(x'02000000000000000000000000000000',zeroblob(16),zeroblob(16),'other',zeroblob(16),zeroblob(16),'done','claimed',6,7,'codex');",
+ )
+ .unwrap();
+ run(&mut conn).unwrap();
+ run(&mut conn).unwrap();
+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();
+
+ let rows: Vec<(String, String, i64, Option<String>)> = conn
+ .prepare(
+ "SELECT state, body, created_at, to_agent FROM agent_messages ORDER BY created_at",
+ )
+ .unwrap()
+ .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)))
+ .unwrap()
+ .collect::<Result<_, _>>()
+ .unwrap();
+ assert_eq!(
+ rows,
+ vec![
+ (
+ "pending".to_owned(),
+ "queued".to_owned(),
+ 5,
+ Some("codex".to_owned())
+ ),
+ ("claimed".to_owned(), "done".to_owned(), 6, None),
+ ]
+ );
+ conn.execute(
+ "UPDATE agent_messages SET state='editing' WHERE body='queued'",
+ [],
+ )
+ .unwrap();
+ assert!(
+ conn.execute(
+ "UPDATE agent_messages SET state='held' WHERE body='queued'",
+ [],
+ )
+ .is_err(),
+ "the state constraint must still reject unknown values"
+ );
+ let indexes: i64 = conn
+ .query_row(
+ "SELECT COUNT(*) FROM sqlite_master WHERE type='index' AND tbl_name='agent_messages' \
+ AND name IN ('idx_agent_messages_inbox','idx_agent_messages_outbox','idx_messages_agent_inbox')",
+ [],
+ |r| r.get(0),
+ )
+ .unwrap();
+ assert_eq!(indexes, 3);
+ let edited_at: i64 = conn
+ .query_row(
+ "SELECT COUNT(*) FROM pragma_table_info('agent_messages') WHERE name='edited_at'",
+ [],
+ |r| r.get(0),
+ )
+ .unwrap();
+ assert_eq!(edited_at, 1);
+ let provenance: (Option<String>, Option<String>) = conn
+ .query_row(
+ "SELECT from_owner_user, subject FROM agent_messages WHERE body='queued'",
+ [],
+ |r| Ok((r.get(0)?, r.get(1)?)),
+ )
+ .unwrap();
+ assert_eq!(
+ provenance,
+ (Some("user:sender".to_owned()), Some("s".to_owned())),
+ "the sender identity and subject survive the rebuild"
+ );
+ assert!(
+ conn.execute(
+ "UPDATE agent_messages SET from_session_id=zeroblob(16) WHERE body='queued'",
+ [],
+ )
+ .is_err(),
+ "the sender-session foreign key survives the rebuild"
+ );
+ conn.execute_batch("INSERT INTO sessions(id,workspace_id,project_id,agent_kind,started_at) VALUES(zeroblob(16),zeroblob(16),zeroblob(16),'codex',1);
+ UPDATE agent_messages SET from_session_id=zeroblob(16) WHERE body='queued';").unwrap();
+ let dangling: i64 = conn
+ .query_row(
+ "SELECT COUNT(*) FROM pragma_foreign_key_check('agent_messages')",
+ [],
+ |r| r.get(0),
+ )
+ .unwrap();
+ assert_eq!(dangling, 0);
+ }
+
/// A store migrated by a newer build (an applied version above anything
/// this binary embeds) must fail to open with the actionable
/// `DataSchemaAhead` error, not refinery's raw "missing from the
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index da30641a..9731bf5c 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -6020,6 +6020,114 @@ pub fn cancel_messages(
Ok(changed as u64)
}
+/// Take a pending message out of its recipient's queue so it can be edited.
+///
+/// `pending` becomes `editing` in one guarded `UPDATE` scoped to the recipient
+/// coordinate, so a message that another session already popped, a foreign
+/// project's message and an unknown id all change nothing and return `None`.
+/// While the row is `editing` no claim path can select it. The returned row is
+/// the content to edit.
+pub fn begin_message_edit(
+ conn: &mut Connection,
+ to_workspace_id: &WorkspaceId,
+ to_project_id: &ProjectId,
+ id: MessageId,
+) -> StoreResult<Option<ai_memory_core::AgentMessage>> {
+ let now = Timestamp::now().as_microsecond();
+ let tx = conn.transaction()?;
+ let changed = tx.execute(
+ "UPDATE agent_messages SET state = 'editing' \
+ WHERE id = ?1 AND to_workspace_id = ?2 AND to_project_id = ?3 \
+ AND state = 'pending'",
+ params![
+ id.as_bytes(),
+ to_workspace_id.as_bytes(),
+ to_project_id.as_bytes()
+ ],
+ )?;
+ if changed == 0 {
+ return Ok(None);
+ }
+ let message = tx.query_row(
+ &format!("SELECT {MESSAGE_COLUMNS} FROM agent_messages WHERE id = ?1"),
+ params![id.as_bytes()],
+ row_to_agent_message,
+ )??;
+ audit(
+ &tx,
+ "edit_message_begin",
+ Some(to_workspace_id.as_bytes()),
+ Some(to_project_id.as_bytes()),
+ None,
+ None,
+ now,
+ )?;
+ tx.commit()?;
+ Ok(Some(message))
+}
+
+/// Put an `editing` message back in the queue, optionally with new text.
+///
+/// With `replacement` the subject and body are replaced (bounded like a new
+/// message) and `edited_at` is stamped; without it the message returns
+/// unchanged. The `UPDATE` only matches a row still in `editing` inside the
+/// recipient coordinate, so a message that was already released, collected or
+/// belongs to another project is left alone and `false` is returned. The
+/// message keeps its `created_at`, so it returns to its original place.
+pub fn finish_message_edit(
+ conn: &mut Connection,
+ to_workspace_id: &WorkspaceId,
+ to_project_id: &ProjectId,
+ id: MessageId,
+ replacement: Option<(Option<&str>, &str)>,
+) -> StoreResult<bool> {
+ let now = Timestamp::now().as_microsecond();
+ let tx = conn.transaction()?;
+ let changed = match replacement {
+ Some((subject, body)) => tx.execute(
+ "UPDATE agent_messages \
+ SET state = 'pending', subject = ?4, body = ?5, edited_at = ?6 \
+ WHERE id = ?1 AND to_workspace_id = ?2 AND to_project_id = ?3 \
+ AND state = 'editing'",
+ params![
+ id.as_bytes(),
+ to_workspace_id.as_bytes(),
+ to_project_id.as_bytes(),
+ subject.map(bound_message_field),
+ bound_message_field(body),
+ now,
+ ],
+ )?,
+ None => tx.execute(
+ "UPDATE agent_messages SET state = 'pending' \
+ WHERE id = ?1 AND to_workspace_id = ?2 AND to_project_id = ?3 \
+ AND state = 'editing'",
+ params![
+ id.as_bytes(),
+ to_workspace_id.as_bytes(),
+ to_project_id.as_bytes()
+ ],
+ )?,
+ };
+ if changed > 0 {
+ audit(
+ &tx,
+ if replacement.is_some() {
+ "edit_message_save"
+ } else {
+ "edit_message_release"
+ },
+ Some(to_workspace_id.as_bytes()),
+ Some(to_project_id.as_bytes()),
+ None,
+ None,
+ now,
+ )?;
+ }
+ tx.commit()?;
+ Ok(changed > 0)
+}
+
fn observation_kind_as_str(kind: ObservationKind) -> &'static str {
kind.as_str()
}
diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rs
index aa5c5493..70cbb9ac 100644
--- a/crates/ai-memory-store/src/writer.rs
+++ b/crates/ai-memory-store/src/writer.rs
@@ -389,6 +389,21 @@ pub(crate) enum WriteCmd {
specific_id: Option<MessageId>,
reply: oneshot::Sender<StoreResult<Option<AgentMessage>>>,
},
+ /// Take a pending message out of the queue so its sender can edit it.
+ BeginMessageEdit {
+ to_workspace_id: WorkspaceId,
+ to_project_id: ProjectId,
+ message_id: MessageId,
+ reply: oneshot::Sender<StoreResult<Option<AgentMessage>>>,
+ },
+ /// Return an `editing` message to the queue, with new text or unchanged.
+ FinishMessageEdit {
+ to_workspace_id: WorkspaceId,
+ to_project_id: ProjectId,
+ message_id: MessageId,
+ replacement: Option<(Option<String>, String)>,
+ reply: oneshot::Sender<StoreResult<bool>>,
+ },
/// Retract still-pending outbox messages a project has sent.
CancelMessages {
from_workspace_id: WorkspaceId,
@@ -2075,6 +2090,55 @@ impl WriterHandle {
rx.await.map_err(|_| StoreError::WriterClosed)?
}
+ /// Take a pending message out of its recipient's queue so it can be
+ /// edited. Returns the message to edit, or `None` when it is no longer
+ /// pending in that project (already collected, held, or not there).
+ ///
+ /// # Errors
+ /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
+ pub async fn begin_message_edit(
+ &self,
+ to_workspace_id: WorkspaceId,
+ to_project_id: ProjectId,
+ message_id: MessageId,
+ ) -> StoreResult<Option<AgentMessage>> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::BeginMessageEdit {
+ to_workspace_id,
+ to_project_id,
+ message_id,
+ reply: tx,
+ })
+ .await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
+ /// Return an `editing` message to the queue. With `replacement` the
+ /// subject and body are replaced; without it the message returns
+ /// unchanged. Returns `false` when the message is not in `editing` in that
+ /// project.
+ ///
+ /// # Errors
+ /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
+ pub async fn finish_message_edit(
+ &self,
+ to_workspace_id: WorkspaceId,
+ to_project_id: ProjectId,
+ message_id: MessageId,
+ replacement: Option<(Option<String>, String)>,
+ ) -> StoreResult<bool> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::FinishMessageEdit {
+ to_workspace_id,
+ to_project_id,
+ message_id,
+ replacement,
+ reply: tx,
+ })
+ .await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
/// Retract still-pending outbox messages a project has sent. With
/// `specific_id`, cancels just that one; otherwise every pending message
/// this project sent. Returns how many were cancelled.
@@ -4369,6 +4433,38 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
let result = ops::pop_message(&mut conn, &claim, specific_id);
send_or_warn(reply, result, "pop_message");
}
+ WriteCmd::BeginMessageEdit {
+ to_workspace_id,
+ to_project_id,
+ message_id,
+ reply,
+ } => {
+ let result = ops::begin_message_edit(
+ &mut conn,
+ &to_workspace_id,
+ &to_project_id,
+ message_id,
+ );
+ send_or_warn(reply, result, "begin_message_edit");
+ }
+ WriteCmd::FinishMessageEdit {
+ to_workspace_id,
+ to_project_id,
+ message_id,
+ replacement,
+ reply,
+ } => {
+ let result = ops::finish_message_edit(
+ &mut conn,
+ &to_workspace_id,
+ &to_project_id,
+ message_id,
+ replacement
+ .as_ref()
+ .map(|(subject, body)| (subject.as_deref(), body.as_str())),
+ );
+ send_or_warn(reply, result, "finish_message_edit");
+ }
WriteCmd::CancelMessages {
from_workspace_id,
from_project_id,
diff --git a/crates/ai-memory-store/tests/suite/agent_messages.rs b/crates/ai-memory-store/tests/suite/agent_messages.rs
index bdac62ba..d5b743e4 100644
--- a/crates/ai-memory-store/tests/suite/agent_messages.rs
+++ b/crates/ai-memory-store/tests/suite/agent_messages.rs
@@ -9,7 +9,8 @@
//! recipient inbox is bounded so a flood cannot exhaust its context/storage.
use ai_memory_core::{
- AgentKind, MessageBox, MessageClaim, NewAgentMessage, ProjectId, WorkspaceId,
+ AgentKind, MessageBox, MessageClaim, MessageState, NewAgentMessage, ProjectId,
+ WorkspaceId,
};
use ai_memory_store::{MAX_PENDING_INBOX_MESSAGES, Store};
@@ -467,3 +468,211 @@ async fn a_full_inbox_rejects_further_sends() {
.await
.expect("a send succeeds once the inbox drops below the cap");
}
+
+/// A message being edited leaves the queue: it cannot be popped, counted or held
+/// twice, and only its own recipient project can hold, save or release it.
+#[tokio::test]
+async fn a_message_being_edited_leaves_the_queue_until_it_is_saved() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let a = project(&store, "team", "sender").await;
+ let b = project(&store, "team", "receiver").await;
+ let other = project(&store, "team", "other").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"
+ );
+ assert_eq!(
+ store.reader.pending_message_count(b.0, b.1).await.unwrap(),
+ 1
+ );
+
+ let held = store
+ .writer
+ .begin_message_edit(b.0, b.1, id)
+ .await
+ .unwrap()
+ .expect("a pending message can be held");
+ assert_eq!(held.body, "first draft");
+ assert_eq!(held.state, MessageState::Editing);
+ assert_eq!(
+ store.reader.pending_message_count(b.0, b.1).await.unwrap(),
+ 0
+ );
+ assert!(
+ store
+ .writer
+ .pop_message(claim(b), None)
+ .await
+ .unwrap()
+ .is_none()
+ );
+ assert!(
+ store
+ .writer
+ .pop_message(claim(b), Some(id))
+ .await
+ .unwrap()
+ .is_none(),
+ "a held message cannot be popped even by id"
+ );
+ assert!(
+ store
+ .writer
+ .begin_message_edit(b.0, b.1, id)
+ .await
+ .unwrap()
+ .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"
+ );
+
+ assert!(
+ store
+ .writer
+ .finish_message_edit(
+ b.0,
+ b.1,
+ id,
+ Some((Some("new subject".into()), "second draft".into())),
+ )
+ .await
+ .unwrap()
+ );
+ assert_eq!(
+ store.reader.pending_message_count(b.0, b.1).await.unwrap(),
+ 1
+ );
+ let popped = store
+ .writer
+ .pop_message(claim(b), None)
+ .await
+ .unwrap()
+ .expect("the saved message is back in the queue");
+ assert_eq!(popped.body, "second draft");
+ assert_eq!(popped.subject.as_deref(), Some("new subject"));
+ assert!(
+ !store
+ .writer
+ .finish_message_edit(b.0, b.1, id, None)
+ .await
+ .unwrap(),
+ "a message that is no longer held cannot be saved again"
+ );
+}
+
+/// Releasing an edit without changes puts the message back unchanged and in its
+/// original place in the queue.
+#[tokio::test]
+async fn releasing_an_edit_keeps_the_text_and_the_queue_order() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let a = project(&store, "team", "sender").await;
+ let b = project(&store, "team", "receiver").await;
+ let first = store
+ .writer
+ .insert_message(message(a, b, "one"))
+ .await
+ .unwrap();
+ store
+ .writer
+ .insert_message(message(a, b, "two"))
+ .await
+ .unwrap();
+ let before = store
+ .reader
+ .message_in_mailbox(b.0, b.1, first)
+ .await
+ .unwrap()
+ .unwrap();
+
+ store
+ .writer
+ .begin_message_edit(b.0, b.1, first)
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(
+ store
+ .writer
+ .finish_message_edit(b.0, b.1, first, None)
+ .await
+ .unwrap()
+ );
+ let after = store
+ .reader
+ .message_in_mailbox(b.0, b.1, first)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(after.state, MessageState::Pending);
+ assert_eq!(after.body, before.body);
+ assert_eq!(after.created_at, before.created_at);
+
+ let popped = store
+ .writer
+ .pop_message(claim(b), None)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(popped.body, "one", "the released message is still first");
+}
+
+/// Only a pending message can be held: collected and cancelled mail is final.
+#[tokio::test]
+async fn collected_or_cancelled_mail_cannot_be_taken_for_editing() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let a = project(&store, "team", "sender").await;
+ let b = project(&store, "team", "receiver").await;
+ let collected = store
+ .writer
+ .insert_message(message(a, b, "collected"))
+ .await
+ .unwrap();
+ store
+ .writer
+ .pop_message(claim(b), Some(collected))
+ .await
+ .unwrap()
+ .unwrap();
+ let cancelled = store
+ .writer
+ .insert_message(message(a, b, "cancelled"))
+ .await
+ .unwrap();
+ store
+ .writer
+ .cancel_messages(a.0, a.1, Some(cancelled))
+ .await
+ .unwrap();
+
+ for id in [collected, cancelled] {
+ assert!(
+ store
+ .writer
+ .begin_message_edit(b.0, b.1, id)
+ .await
+ .unwrap()
+ .is_none()
+ );
+ }
+}
diff --git a/crates/ai-memory-web/src/routes/inbox.rs b/crates/ai-memory-web/src/routes/inbox.rs
index 132f0fd9..cefe01da 100644
--- a/crates/ai-memory-web/src/routes/inbox.rs
+++ b/crates/ai-memory-web/src/routes/inbox.rs
@@ -152,6 +152,24 @@ pub(crate) async fn handler(
};
let more = messages.len() > 50;
messages.truncate(50);
+ let editing_count = match (&scope, inbox) {
+ (Some(scope), true) => match state
+ .reader
+ .message_history_filtered(
+ scope.workspace_id,
+ scope.project_id,
+ MessageBox::Inbox,
+ Some(MessageState::Editing),
+ 100,
+ 0,
+ )
+ .await
+ {
+ Ok(held) => held.len(),
+ Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
+ },
+ _ => 0,
+ };
let rows = messages
.into_iter()
.map(|m| {
@@ -166,8 +184,10 @@ pub(crate) async fn handler(
.get(&(m.to_workspace_id.to_string(), m.to_project_id.to_string()))
.cloned()
.unwrap_or_else(|| "A project you cannot read".into());
+ let raw_subject = m.subject.clone().unwrap_or_default();
MessageRow {
id: m.id.to_string(),
+ raw_subject,
subject: m
.subject
.filter(|s| !s.is_empty())
@@ -184,6 +204,7 @@ pub(crate) async fn handler(
MessageState::Pending => "Queued",
MessageState::Claimed => "Collected",
MessageState::Cancelled => "Cancelled",
+ MessageState::Editing => "Editing",
},
when: humanize(&m.created_at.to_string()),
}
@@ -211,6 +232,11 @@ pub(crate) async fn handler(
.fold(0_u64, |total, s| total.saturating_add(s.pending)),
pending_projects: scopes.iter().filter(|s| s.pending > 0).count(),
scopes,
+ editing_count,
+ editing_href: format!(
+ "{}&state=editing",
+ mailbox_href(&workspace, &project, false, 0)
+ ),
inbox_href: filtered_href(false, 0),
outbox_href: filtered_href(true, 0),
state: message_state.map_or("", |s| s.as_str()).into(),
@@ -256,18 +282,28 @@ fn error(status: StatusCode, message: &str) -> Response {
(status, Json(serde_json::json!({"error":message}))).into_response()
}
-pub(crate) async fn send(
- State(state): State<Arc<WebState>>,
+/// What a browser write needs after the checks every write shares.
+struct BrowserWriter {
+ viewer: Option<ai_memory_core::UserId>,
+ distinguishes: bool,
+}
+
+/// The checks every browser write to the mailbox shares: the UI header, the
+/// same-origin check, a signed-in operator when operators are distinguished,
+/// and the normal-write capability.
+async fn authorize_browser_write(
+ state: &WebState,
viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
- actor: Option<axum::Extension<ActorContext>>,
level: Option<axum::Extension<AuthLevel>>,
- headers: HeaderMap,
- Json(input): Json<ComposeMessage>,
-) -> Response {
+ headers: &HeaderMap,
+) -> Result<BrowserWriter, Response> {
// A custom header plus JSON prevents a cross-site form from using cached
// Basic credentials. Cookie sessions additionally pass dual-auth CSRF.
if headers.get("x-ai-memory-ui").and_then(|h| h.to_str().ok()) != Some("1") {
- return error(StatusCode::FORBIDDEN, "Refresh the inbox and try again.");
+ return Err(error(
+ StatusCode::FORBIDDEN,
+ "Refresh the inbox and try again.",
+ ));
}
if let Some(origin) = headers.get("origin").and_then(|h| h.to_str().ok()) {
let authority = origin
@@ -275,34 +311,55 @@ pub(crate) async fn send(
.ok()
.and_then(|u| u.authority().map(|a| a.as_str().to_owned()));
if authority.as_deref() != headers.get("host").and_then(|h| h.to_str().ok()) {
- return error(
+ return Err(error(
StatusCode::FORBIDDEN,
"Messages must be sent from this dashboard.",
- );
+ ));
}
}
- let distinguishes = match state
+ let distinguishes = state
.reader
.distinguishes_operators(state.trusted_proxy_identity)
.await
- {
- Ok(v) => v,
- Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
- };
+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response())?;
let level = level.map_or(AuthLevel::Anonymous, |l| l.0);
if distinguishes && level == AuthLevel::Anonymous {
- return error(StatusCode::UNAUTHORIZED, "Sign in to send a message.");
+ return Err(error(
+ StatusCode::UNAUTHORIZED,
+ "Sign in to send a message.",
+ ));
}
if level
.authorize(Capability::NormalWrite, distinguishes)
.is_err()
{
- return StatusCode::FORBIDDEN.into_response();
+ return Err(StatusCode::FORBIDDEN.into_response());
}
let viewer = viewer.map(|v| v.0.user());
if level == AuthLevel::User && viewer.is_none() {
- return StatusCode::FORBIDDEN.into_response();
+ return Err(StatusCode::FORBIDDEN.into_response());
}
+ Ok(BrowserWriter {
+ viewer,
+ distinguishes,
+ })
+}
+
+pub(crate) async fn send(
+ State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
+ actor: Option<axum::Extension<ActorContext>>,
+ level: Option<axum::Extension<AuthLevel>>,
+ headers: HeaderMap,
+ Json(input): Json<ComposeMessage>,
+) -> Response {
+ let BrowserWriter {
+ viewer,
+ distinguishes,
+ } = match authorize_browser_write(&state, viewer, level, &headers).await {
+ Ok(writer) => writer,
+ Err(refusal) => return refusal,
+ };
let source = match lookup_existing_scope_guarded(
&state.reader,
&input.from_workspace,
@@ -392,3 +449,206 @@ pub(crate) async fn send(
}
}
}
+
+#[derive(Deserialize)]
+pub(crate) struct EditMessage {
+ workspace: String,
+ project: String,
+ #[serde(default)]
+ subject: Option<String>,
+ #[serde(default)]
+ body: Option<String>,
+}
+
+/// Resolve the message a browser edit targets, and refuse unless the caller
+/// could have sent it: write access to the recipient mailbox it sits in and to
+/// the project it came from. Without the second check, anyone who can write to
+/// a project could rewrite what another project's agent asked it to do.
+async fn editable_message(
+ state: &WebState,
+ writer: &BrowserWriter,
+ raw_id: &str,
+ input: &EditMessage,
+) -> Result<
+ (
+ ai_memory_core::WorkspaceId,
+ ai_memory_core::ProjectId,
+ ai_memory_core::MessageId,
+ ),
+ Response,
+> {
+ let id = raw_id
+ .parse::<ai_memory_core::MessageId>()
+ .map_err(|_| error(StatusCode::BAD_REQUEST, "That is not a message id."))?;
+ let target = lookup_existing_scope_guarded(
+ &state.reader,
+ &input.workspace,
+ &input.project,
+ writer.viewer,
+ ProjectAccess::Write,
+ )
+ .await
+ .map_err(|e| super::page::refusal_response(&e))?;
+ let message = state
+ .reader
+ .message_in_mailbox(target.workspace_id, target.project_id, id)
+ .await
+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response())?
+ .ok_or_else(|| {
+ error(
+ StatusCode::NOT_FOUND,
+ "That message is not in this mailbox.",
+ )
+ })?;
+ let visible = state
+ .reader
+ .list_projects_with_stats(writer.viewer)
+ .await
+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response())?;
+ let Some(origin) = visible.into_iter().find(|p| {
+ p.workspace_id == message.origin.from_workspace_id.to_string()
+ && p.project_id == message.origin.from_project_id.to_string()
+ }) else {
+ return Err(error(
+ StatusCode::FORBIDDEN,
+ "You cannot edit mail sent from a project you cannot write to.",
+ ));
+ };
+ lookup_existing_scope_guarded(
+ &state.reader,
+ &origin.workspace_name,
+ &origin.project_name,
+ writer.viewer,
+ ProjectAccess::Write,
+ )
+ .await
+ .map_err(|e| super::page::refusal_response(&e))?;
+ Ok((target.workspace_id, target.project_id, id))
+}
+
+/// Take a queued message out of the queue so it can be edited.
+pub(crate) async fn begin_edit(
+ State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
+ level: Option<axum::Extension<AuthLevel>>,
+ headers: HeaderMap,
+ axum::extract::Path(raw_id): axum::extract::Path<String>,
+ Json(input): Json<EditMessage>,
+) -> Response {
+ let writer = match authorize_browser_write(&state, viewer, level, &headers).await {
+ Ok(writer) => writer,
+ Err(refusal) => return refusal,
+ };
+ let (workspace_id, project_id, id) =
+ match editable_message(&state, &writer, &raw_id, &input).await {
+ Ok(target) => target,
+ Err(refusal) => return refusal,
+ };
+ match state
+ .wiki
+ .begin_agent_message_edit(workspace_id, project_id, id)
+ .await
+ {
+ Ok(Some(message)) => Json(serde_json::json!({
+ "message_id": message.id.to_string(),
+ "state": message.state.as_str(),
+ "subject": message.subject.unwrap_or_default(),
+ "body": message.body,
+ }))
+ .into_response(),
+ Ok(None) => error(
+ StatusCode::CONFLICT,
+ "An agent already collected this message, or it is no longer queued.",
+ ),
+ Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
+ }
+}
+
+/// Save new text for a held message and return it to the queue.
+pub(crate) async fn save_edit(
+ State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
+ actor: Option<axum::Extension<ActorContext>>,
+ level: Option<axum::Extension<AuthLevel>>,
+ headers: HeaderMap,
+ axum::extract::Path(raw_id): axum::extract::Path<String>,
+ Json(input): Json<EditMessage>,
+) -> Response {
+ let writer = match authorize_browser_write(&state, viewer, level, &headers).await {
+ Ok(writer) => writer,
+ Err(refusal) => return refusal,
+ };
+ let (workspace_id, project_id, id) =
+ match editable_message(&state, &writer, &raw_id, &input).await {
+ Ok(target) => target,
+ Err(refusal) => return refusal,
+ };
+ let body = input.body.clone().unwrap_or_default();
+ let subject = input.subject.clone().unwrap_or_default();
+ if body.trim().is_empty() || body.chars().count() > 8_000 || subject.chars().count() > 200 {
+ return error(
+ StatusCode::BAD_REQUEST,
+ "Enter a message up to 8,000 characters and a subject up to 200 characters.",
+ );
+ }
+ let actor = actor.map_or_else(ActorContext::anonymous, |a| a.0);
+ match state
+ .wiki
+ .save_agent_message_edit(
+ workspace_id,
+ project_id,
+ id,
+ Some(subject.trim().to_owned()),
+ body.trim().to_owned(),
+ actor,
+ )
+ .await
+ {
+ Ok(true) => Json(serde_json::json!({"message_id": id.to_string(), "state": "pending"}))
+ .into_response(),
+ Ok(false) => error(
+ StatusCode::CONFLICT,
+ "This message is no longer being edited.",
+ ),
+ Err(e) => {
+ tracing::warn!(error=%e,"browser message edit refused");
+ error(
+ StatusCode::FORBIDDEN,
+ "The message could not be saved. Check project access and message admission policy.",
+ )
+ }
+ }
+}
+
+/// Return a held message to the queue without changing it.
+pub(crate) async fn release_edit(
+ State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
+ level: Option<axum::Extension<AuthLevel>>,
+ headers: HeaderMap,
+ axum::extract::Path(raw_id): axum::extract::Path<String>,
+ Json(input): Json<EditMessage>,
+) -> Response {
+ let writer = match authorize_browser_write(&state, viewer, level, &headers).await {
+ Ok(writer) => writer,
+ Err(refusal) => return refusal,
+ };
+ let (workspace_id, project_id, id) =
+ match editable_message(&state, &writer, &raw_id, &input).await {
+ Ok(target) => target,
+ Err(refusal) => return refusal,
+ };
+ match state
+ .wiki
+ .release_agent_message_edit(workspace_id, project_id, id)
+ .await
+ {
+ Ok(true) => Json(serde_json::json!({"message_id": id.to_string(), "state": "pending"}))
+ .into_response(),
+ Ok(false) => error(
+ StatusCode::CONFLICT,
+ "This message is no longer being edited.",
+ ),
+ Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
+ }
+}
diff --git a/crates/ai-memory-web/src/routes/mod.rs b/crates/ai-memory-web/src/routes/mod.rs
index c59c85ae..369eedbf 100644
--- a/crates/ai-memory-web/src/routes/mod.rs
+++ b/crates/ai-memory-web/src/routes/mod.rs
@@ -123,6 +123,9 @@ pub(crate) fn build(state: Arc<WebState>) -> Router {
.route("/inbox", get(inbox::handler))
.route("/inbox/notifications", get(notifications::handler))
.route("/messages", post(inbox::send))
+ .route("/messages/{id}/edit", post(inbox::begin_edit))
+ .route("/messages/{id}/save", post(inbox::save_edit))
+ .route("/messages/{id}/release", post(inbox::release_edit))
.route(
"/w/{workspace}/{project}/agents/{agent}",
get(agents::handler),
diff --git a/crates/ai-memory-web/src/views.rs b/crates/ai-memory-web/src/views.rs
index 149fcff5..9d9877e6 100644
--- a/crates/ai-memory-web/src/views.rs
+++ b/crates/ai-memory-web/src/views.rs
@@ -35,6 +35,7 @@ pub(crate) struct RecipientOption {
pub(crate) struct MessageRow {
pub id: String,
pub subject: String,
+ pub raw_subject: String,
pub body: String,
pub from: String,
pub to: String,
@@ -56,6 +57,8 @@ pub(crate) struct InboxView {
pub recipients: Vec<RecipientOption>,
pub rows: Vec<MessageRow>,
pub inbox: bool,
+ pub editing_count: usize,
+ pub editing_href: String,
pub state: String,
pub inbox_href: String,
pub outbox_href: String,
diff --git a/crates/ai-memory-web/templates/inbox.html b/crates/ai-memory-web/templates/inbox.html
index ffe38b3c..3742de3c 100644
--- a/crates/ai-memory-web/templates/inbox.html
+++ b/crates/ai-memory-web/templates/inbox.html
@@ -13,9 +13,10 @@
<section class="surface inbox-list" aria-labelledby="mail-title">
<div class="panel-heading"><label class="field-label" for="mail-project">PROJECT MAILBOX</label><select id="mail-project" class="field-input">{% for scope in scopes %}<option data-workspace="{{ scope.workspace }}" data-project="{{ scope.project }}" {% if scope.selected %}selected{% endif %}>{{ scope.workspace }} / {{ scope.project }}{% if scope.pending > 0 %} · {{ scope.pending }} queued{% endif %}</option>{% endfor %}</select>
<nav class="segmented-tabs" aria-label="Mailbox"><a id="mail-title" href="{{ inbox_href }}" {% if inbox %}aria-current="page"{% endif %}>Received</a><a href="{{ outbox_href }}" {% if !inbox %}aria-current="page"{% endif %}>Sent</a></nav>
- <form action="inbox" method="get" class="mail-state-filter"><input type="hidden" name="workspace" value="{{ workspace }}"><input type="hidden" name="project" value="{{ project }}"><input type="hidden" name="box" value="{% if inbox %}inbox{% else %}outbox{% endif %}"><label for="mail-state" class="field-label">Message state</label><select id="mail-state" name="state" class="field-input"><option value="" {% if state == "" %}selected{% endif %}>All messages</option><option value="pending" {% if state == "pending" %}selected{% endif %}>Awaiting collection</option><option value="claimed" {% if state == "claimed" %}selected{% endif %}>Collected</option><option value="cancelled" {% if state == "cancelled" %}selected{% endif %}>Cancelled</option></select><noscript><button class="secondary-button" type="submit">Filter</button></noscript></form></div>
+ <form action="inbox" method="get" class="mail-state-filter"><input type="hidden" name="workspace" value="{{ workspace }}"><input type="hidden" name="project" value="{{ project }}"><input type="hidden" name="box" value="{% if inbox %}inbox{% else %}outbox{% endif %}"><label for="mail-state" class="field-label">Message state</label><select id="mail-state" name="state" class="field-input"><option value="" {% if state == "" %}selected{% endif %}>All messages</option><option value="pending" {% if state == "pending" %}selected{% endif %}>Awaiting collection</option><option value="claimed" {% if state == "claimed" %}selected{% endif %}>Collected</option><option value="cancelled" {% if state == "cancelled" %}selected{% endif %}>Cancelled</option><option value="editing" {% if state == "editing" %}selected{% endif %}>Editing</option></select><noscript><button class="secondary-button" type="submit">Filter</button></noscript></form></div>
+ {% if inbox && editing_count > 0 %}<p class="section-note held-note" role="status"><strong>{{ editing_count }} held for editing.</strong> Agents cannot collect {% if editing_count == 1 %}it{% else %}them{% endif %} until {% if editing_count == 1 %}it is{% else %}they are{% endif %} saved or discarded. <a href="{{ editing_href }}">Show {% if editing_count == 1 %}it{% else %}them{% endif %}</a></p>{% endif %}
{% if rows.is_empty() %}<div class="empty-state mail-empty"><span aria-hidden="true">✉</span><h2>A little breathing room</h2><p>{% if state != "" %}No messages match this state in the selected mailbox.{% else if inbox %}No messages received by this project yet.{% else %}No messages sent from this project yet.{% endif %}</p><p>Choose an agent and leave a clear request for its next inbox check.</p></div>{% else %}
- <div class="mail-rows">{% for row in rows %}<details class="mail-row" data-state="{{ row.state }}"><summary><span class="mail-avatar" aria-hidden="true">✉</span><span class="mail-preview"><strong>{{ row.subject }}</strong><span>{{ row.from }} → {{ row.to }}</span><small>{{ row.agent }} · {{ row.when }}</small></span><span class="status-pill message-{{ row.state }}">{{ row.state_label }}</span><span class="mail-chevron" aria-hidden="true">⌄</span></summary><div class="mail-detail"><p class="mail-id mono">{{ row.id }}</p><p class="message-body">{{ row.body }}</p>{% if row.state == "claimed" %}<p class="section-note">Collected by an agent. This is not confirmation that the request has been completed.</p>{% endif %}</div></details>{% endfor %}</div>{% endif %}
+ <div class="mail-rows">{% for row in rows %}<details class="mail-row" data-state="{{ row.state }}" data-message-id="{{ row.id }}" data-subject="{{ row.raw_subject }}"><summary><span class="mail-avatar" aria-hidden="true">✉</span><span class="mail-preview"><strong>{{ row.subject }}</strong><span>{{ row.from }} → {{ row.to }}</span><small>{{ row.agent }} · {{ row.when }}</small></span><span class="status-pill message-{{ row.state }}">{{ row.state_label }}</span><span class="mail-chevron" aria-hidden="true">⌄</span></summary><div class="mail-detail"><p class="mail-id mono">{{ row.id }}</p><p class="message-body">{{ row.body }}</p>{% if row.state == "claimed" %}<p class="section-note">Collected by an agent. This is not confirmation that the request has been completed.</p>{% endif %}{% if inbox && !needs_write_token %}{% if row.state == "pending" %}<div class="mail-actions"><button type="button" class="secondary-button" data-message-action="begin">Edit</button></div>{% else if row.state == "editing" %}<p class="section-note held-hint">Held while it is edited. Agents cannot collect it until it is saved or discarded.</p><div class="mail-actions"><button type="button" class="secondary-button" data-message-action="resume">Continue editing</button> <button type="button" class="secondary-button" data-message-action="release">Discard changes</button></div>{% endif %}{% endif %}</div></details>{% endfor %}</div>{% endif %}
<nav class="pagination" aria-label="Message pages">{% if previous != "" %}<a href="{{ previous }}" class="secondary-button">← Newer</a>{% endif %}{% if next != "" %}<a href="{{ next }}" class="secondary-button">Older →</a>{% endif %}</nav>
</section>
<aside id="compose" class="surface composer" aria-labelledby="compose-title">
@@ -79,4 +80,71 @@
});
})();
</script>
+<script>
+(function(){
+ var list=document.querySelector(".mail-rows");if(!list)return;
+ {% include "_js_cookie.html" %}
+ var picker=document.getElementById("mail-project");
+ function scope(){var o=picker.selectedOptions[0];return {workspace:o.dataset.workspace,project:o.dataset.project};}
+ async function call(id,action,payload){
+ var headers={"Content-Type":"application/json","X-Ai-Memory-UI":"1","X-CSRF-Token":decodeURIComponent(cookie("ai_memory_csrf")||"")};
+ var controller=new AbortController(),timeout=setTimeout(function(){controller.abort();},15000);
+ try{
+ var response=await fetch(new URL("messages/"+encodeURIComponent(id)+"/"+action,document.baseURI),{method:"POST",credentials:"same-origin",signal:controller.signal,headers:headers,body:JSON.stringify(Object.assign(scope(),payload||{}))});
+ if(response.redirected)throw new Error("Your session expired. Sign in again before editing.");
+ var data={};try{data=await response.json();}catch(ignored){}
+ if(!response.ok)throw new Error(data.error||"The request was refused.");
+ return data;
+ }catch(error){
+ if(error.name==="AbortError")throw new Error("No answer from the server. Reload to see whether the change was applied.");
+ throw error;
+ }finally{clearTimeout(timeout);}
+ }
+ function field(label,node,id){var wrap=document.createElement("div"),text=document.createElement("label");node.id=id;text.className="field-label";text.htmlFor=id;text.textContent=label;wrap.appendChild(text);wrap.appendChild(node);return wrap;}
+ function openEditor(row,subject,body){
+ var detail=row.querySelector(".mail-detail"),id=row.dataset.messageId;
+ detail.querySelectorAll(".mail-actions,.message-body,.held-hint,.edit-error").forEach(function(node){node.remove();});
+ row.dataset.state="editing";
+ var pill=row.querySelector(".status-pill");pill.textContent="Editing";pill.className="status-pill message-editing";
+ var form=document.createElement("form"),subjectInput=document.createElement("input"),bodyInput=document.createElement("textarea"),status=document.createElement("p"),actions=document.createElement("div"),save=document.createElement("button"),discard=document.createElement("button"),hint=document.createElement("p");
+ form.className="mail-editor";
+ subjectInput.className="field-input";subjectInput.maxLength=200;subjectInput.value=subject;
+ bodyInput.className="field-input";bodyInput.rows=8;bodyInput.maxLength=8000;bodyInput.required=true;bodyInput.value=body;
+ hint.className="section-note";hint.textContent="This message is held while you edit it. Agents cannot collect it until you save or discard.";
+ status.setAttribute("role","status");status.setAttribute("aria-live","polite");
+ actions.className="mail-actions";
+ save.type="submit";save.className="primary-button";save.textContent="Save and requeue";
+ discard.type="button";discard.className="secondary-button";discard.textContent="Discard changes";
+ actions.appendChild(save);actions.appendChild(discard);
+ form.appendChild(hint);form.appendChild(field("Subject",subjectInput,"edit-subject-"+id));form.appendChild(field("Message",bodyInput,"edit-body-"+id));form.appendChild(status);form.appendChild(actions);
+ detail.appendChild(form);bodyInput.focus();
+ function busy(on){save.disabled=on;discard.disabled=on;}
+ form.addEventListener("submit",async function(event){
+ event.preventDefault();if(!form.reportValidity())return;
+ busy(true);status.textContent="Saving…";
+ try{await call(id,"save",{subject:subjectInput.value,body:bodyInput.value});document.dispatchEvent(new Event("inbox:changed"));location.reload();}
+ catch(error){status.textContent=error.message;busy(false);}
+ });
+ discard.addEventListener("click",async function(){
+ busy(true);status.textContent="Returning to the queue…";
+ try{await call(id,"release");document.dispatchEvent(new Event("inbox:changed"));location.reload();}
+ catch(error){status.textContent=error.message;busy(false);}
+ });
+ }
+ list.addEventListener("click",async function(event){
+ var button=event.target.closest("[data-message-action]");if(!button)return;
+ var row=button.closest(".mail-row"),id=row.dataset.messageId,action=button.dataset.messageAction;
+ if(action==="resume"){openEditor(row,row.dataset.subject||"",row.querySelector(".message-body").textContent);return;}
+ button.disabled=true;
+ try{
+ if(action==="begin"){var data=await call(id,"edit");document.dispatchEvent(new Event("inbox:changed"));openEditor(row,data.subject||"",data.body||"");}
+ else if(action==="release"){await call(id,"release");document.dispatchEvent(new Event("inbox:changed"));location.reload();}
+ }catch(error){
+ var note=row.querySelector(".edit-error")||document.createElement("p");
+ note.className="send-error edit-error";note.setAttribute("role","alert");note.textContent=error.message;
+ row.querySelector(".mail-detail").appendChild(note);button.disabled=false;
+ }
+ });
+})();
+</script>
{% endblock %}
diff --git a/crates/ai-memory-web/tests/suite/operations.rs b/crates/ai-memory-web/tests/suite/operations.rs
index 6ca571c3..0d1f51e7 100644
--- a/crates/ai-memory-web/tests/suite/operations.rs
+++ b/crates/ai-memory-web/tests/suite/operations.rs
@@ -1305,3 +1305,406 @@ async fn operations_response_search_and_pagination_cover_the_full_project_and_se
}
}
}
+
+fn edit(id: &str, action: &str) -> axum::http::request::Builder {
+ Request::builder()
+ .method("POST")
+ .uri(format!("/messages/{id}/{action}"))
+ .header("content-type", "application/json")
+ .header("x-ai-memory-ui", "1")
+}
+
+fn codex_claim(
+ ws: ai_memory_core::WorkspaceId,
+ project: ai_memory_core::ProjectId,
+) -> ai_memory_core::MessageClaim {
+ ai_memory_core::MessageClaim {
+ workspace_id: ws,
+ project_id: project,
+ claiming_agent: AgentKind::Codex,
+ claiming_session: None,
+ claiming_user: None,
+ }
+}
+
+async fn queue_message(app: &axum::Router) -> String {
+ let response = app
+ .clone()
+ .oneshot(send().body(Body::from(body().to_string())).unwrap())
+ .await
+ .unwrap();
+ assert_eq!(response.status(), StatusCode::CREATED);
+ let created: Value = serde_json::from_str(&text(response).await).unwrap();
+ created["message_id"].as_str().unwrap().to_owned()
+}
+
+#[tokio::test]
+async fn operations_edit_holds_a_queued_message_until_it_is_saved_or_discarded() {
+ let (_tmp, store, wiki, ws, project, _) = fixture().await;
+ let app = router(store.reader.clone(), wiki);
+ let scope = json!({"workspace": "team", "project": "app"});
+ let id = queue_message(&app).await;
+
+ let held = app
+ .clone()
+ .oneshot(
+ edit(&id, "edit")
+ .body(Body::from(scope.to_string()))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(held.status(), StatusCode::OK);
+ let held: Value = serde_json::from_str(&text(held).await).unwrap();
+ assert_eq!(held["state"], "editing");
+ assert_eq!(held["body"], "Please inspect the large context.");
+ assert_eq!(
+ store
+ .reader
+ .pending_message_count(ws, project)
+ .await
+ .unwrap(),
+ 0,
+ "a held message leaves the queue"
+ );
+ assert!(
+ store
+ .writer
+ .pop_message(codex_claim(ws, project), None)
+ .await
+ .unwrap()
+ .is_none()
+ );
+
+ let page = text(
+ app.clone()
+ .oneshot(
+ Request::builder()
+ .uri("/inbox?workspace=team&project=app")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap(),
+ )
+ .await;
+ assert!(page.contains("1 held for editing"), "{page}");
+ let held_rows = text(
+ app.clone()
+ .oneshot(
+ Request::builder()
+ .uri("/inbox?workspace=team&project=app&state=editing")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap(),
+ )
+ .await;
+ assert!(held_rows.contains("data-message-action=\"resume\""));
+ assert!(held_rows.contains("data-message-action=\"release\""));
+ assert!(!held_rows.contains("data-message-action=\"begin\""));
+
+ let mut edited = scope.clone();
+ edited["subject"] = json!("Updated subject");
+ edited["body"] = json!("Updated request body.");
+ let saved = app
+ .clone()
+ .oneshot(
+ edit(&id, "save")
+ .body(Body::from(edited.to_string()))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(saved.status(), StatusCode::OK);
+ assert_eq!(
+ store
+ .reader
+ .pending_message_count(ws, project)
+ .await
+ .unwrap(),
+ 1
+ );
+ let popped = store
+ .writer
+ .pop_message(codex_claim(ws, project), None)
+ .await
+ .unwrap()
+ .expect("the saved message is back in the queue");
+ assert_eq!(popped.body, "Updated request body.");
+ assert_eq!(popped.subject.as_deref(), Some("Updated subject"));
+
+ let second = queue_message(&app).await;
+ for action in ["edit", "release"] {
+ let response = app
+ .clone()
+ .oneshot(
+ edit(&second, action)
+ .body(Body::from(scope.to_string()))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status(), StatusCode::OK, "{action}");
+ }
+ let back = store
+ .writer
+ .pop_message(codex_claim(ws, project), None)
+ .await
+ .unwrap()
+ .expect("a discarded edit returns the message to the queue");
+ assert_eq!(back.body, "Please inspect the large context.");
+}
+
+#[tokio::test]
+async fn operations_edit_refuses_foreign_collected_and_malformed_requests() {
+ let (_tmp, store, wiki, ws, project, _) = fixture().await;
+ store
+ .writer
+ .get_or_create_project(ws, "other", None)
+ .await
+ .unwrap();
+ let app = router(store.reader.clone(), wiki);
+ let scope = json!({"workspace": "team", "project": "app"});
+ let id = queue_message(&app).await;
+ let status = |request: Request<Body>| {
+ let app = app.clone();
+ async move { app.oneshot(request).await.unwrap().status() }
+ };
+
+ assert_eq!(
+ status(
+ Request::builder()
+ .method("POST")
+ .uri(format!("/messages/{id}/edit"))
+ .header("content-type", "application/json")
+ .body(Body::from(scope.to_string()))
+ .unwrap()
+ )
+ .await,
+ StatusCode::FORBIDDEN,
+ "the UI header is required"
+ );
+ assert_eq!(
+ status(
+ edit(&id, "edit")
+ .header("origin", "https://elsewhere.example")
+ .header("host", "localhost")
+ .body(Body::from(scope.to_string()))
+ .unwrap()
+ )
+ .await,
+ StatusCode::FORBIDDEN,
+ "a cross-origin edit is refused"
+ );
+ assert_eq!(
+ status(
+ edit("not-a-message-id", "edit")
+ .body(Body::from(scope.to_string()))
+ .unwrap()
+ )
+ .await,
+ StatusCode::BAD_REQUEST
+ );
+ assert_eq!(
+ status(
+ edit(&ai_memory_core::MessageId::new().to_string(), "edit")
+ .body(Body::from(scope.to_string()))
+ .unwrap()
+ )
+ .await,
+ StatusCode::NOT_FOUND
+ );
+ assert_eq!(
+ status(
+ edit(&id, "edit")
+ .body(Body::from(
+ json!({"workspace": "team", "project": "other"}).to_string()
+ ))
+ .unwrap()
+ )
+ .await,
+ StatusCode::NOT_FOUND,
+ "a message cannot be held through another project's mailbox"
+ );
+ assert_eq!(
+ store
+ .reader
+ .pending_message_count(ws, project)
+ .await
+ .unwrap(),
+ 1,
+ "the refused requests left the message queued"
+ );
+
+ // Saving or releasing a message nobody is editing changes nothing.
+ for action in ["save", "release"] {
+ let mut payload = scope.clone();
+ payload["body"] = json!("replacement");
+ assert_eq!(
+ status(
+ edit(&id, action)
+ .body(Body::from(payload.to_string()))
+ .unwrap()
+ )
+ .await,
+ StatusCode::CONFLICT,
+ "{action}"
+ );
+ }
+ assert_eq!(
+ status(
+ edit(&id, "edit")
+ .body(Body::from(scope.to_string()))
+ .unwrap()
+ )
+ .await,
+ StatusCode::OK,
+ "the owning mailbox can hold the same message"
+ );
+ assert_eq!(
+ status(
+ edit(&id, "save")
+ .body(Body::from(
+ json!({"workspace": "team", "project": "app", "body": " "}).to_string()
+ ))
+ .unwrap()
+ )
+ .await,
+ StatusCode::BAD_REQUEST,
+ "an empty message cannot be saved"
+ );
+ assert_eq!(
+ status(
+ edit(&id, "release")
+ .body(Body::from(scope.to_string()))
+ .unwrap()
+ )
+ .await,
+ StatusCode::OK
+ );
+
+ // Collected mail is final.
+ store
+ .writer
+ .pop_message(codex_claim(ws, project), Some(id.parse().unwrap()))
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ status(
+ edit(&id, "edit")
+ .body(Body::from(scope.to_string()))
+ .unwrap()
+ )
+ .await,
+ StatusCode::CONFLICT
+ );
+}
+
+#[tokio::test]
+async fn operations_edit_needs_write_access_to_the_sender_project_too() {
+ let (_tmp, store, wiki, ws, source, _) = fixture().await;
+ let dest = store
+ .writer
+ .get_or_create_project(ws, "dest", None)
+ .await
+ .unwrap();
+ for project in [source, dest] {
+ store
+ .writer
+ .set_access_mode(project, ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ }
+ let user = store
+ .writer
+ .create_human_user(
+ NewUser {
+ username: "alice".into(),
+ name: None,
+ email: None,
+ },
+ UserRole::User,
+ None,
+ false,
+ )
+ .await
+ .unwrap();
+ store
+ .writer
+ .grant_memory(user, dest, GrantLevel::Write, None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .grant_memory(user, source, GrantLevel::Read, None)
+ .await
+ .unwrap();
+ let id = store
+ .writer
+ .insert_message(ai_memory_core::NewAgentMessage {
+ from_workspace_id: ws,
+ from_project_id: source,
+ from_agent: AgentKind::Other,
+ from_session_id: None,
+ from_owner_user: None,
+ to_workspace_id: ws,
+ to_project_id: dest,
+ to_agent: Some(AgentKind::Codex),
+ subject: Some("from the source project".into()),
+ body: "do the thing".into(),
+ nature: ai_memory_core::MessageNature::Unknown,
+ evidence: None,
+ })
+ .await
+ .unwrap()
+ .to_string();
+ let app = router(store.reader.clone(), wiki);
+ let scope = json!({"workspace": "team", "project": "dest"});
+ let as_user = || {
+ edit(&id, "edit")
+ .extension(AuthLevel::User)
+ .extension(AuthorizedViewer(user))
+ .body(Body::from(scope.to_string()))
+ .unwrap()
+ };
+
+ 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"
+ );
+ assert_eq!(
+ store.reader.pending_message_count(ws, dest).await.unwrap(),
+ 1,
+ "the refusal left the message queued"
+ );
+ store
+ .writer
+ .grant_memory(user, source, GrantLevel::Write, None)
+ .await
+ .unwrap();
+ assert_eq!(
+ app.clone().oneshot(as_user()).await.unwrap().status(),
+ StatusCode::OK
+ );
+ assert_eq!(
+ store.reader.pending_message_count(ws, dest).await.unwrap(),
+ 0
+ );
+ assert_eq!(
+ app.oneshot(
+ edit(&id, "release")
+ .extension(AuthLevel::Root)
+ .body(Body::from(scope.to_string()))
+ .unwrap()
+ )
+ .await
+ .unwrap()
+ .status(),
+ StatusCode::OK,
+ "root can release a held message"
+ );
+}
diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rs
index 5d92171c..44094e39 100644
--- a/crates/ai-memory-wiki/src/wiki.rs
+++ b/crates/ai-memory-wiki/src/wiki.rs
@@ -345,6 +345,71 @@ impl Wiki {
Ok(id)
}
+ /// Take a pending message out of its recipient's queue so its sender can
+ /// edit it. Until it is saved or released no harness can collect it.
+ /// Returns `None` when the message is not pending in that project.
+ /// Callers must authorize both project coordinates.
+ pub async fn begin_agent_message_edit(
+ &self,
+ to_workspace_id: ai_memory_core::WorkspaceId,
+ to_project_id: ai_memory_core::ProjectId,
+ id: ai_memory_core::MessageId,
+ ) -> WikiResult<Option<ai_memory_core::AgentMessage>> {
+ Ok(self
+ .writer
+ .begin_message_edit(to_workspace_id, to_project_id, id)
+ .await?)
+ }
+
+ /// Return a held message to the queue unchanged. Returns `false` when it
+ /// is not being edited in that project.
+ pub async fn release_agent_message_edit(
+ &self,
+ to_workspace_id: ai_memory_core::WorkspaceId,
+ to_project_id: ai_memory_core::ProjectId,
+ id: ai_memory_core::MessageId,
+ ) -> WikiResult<bool> {
+ Ok(self
+ .writer
+ .finish_message_edit(to_workspace_id, to_project_id, id, None)
+ .await?)
+ }
+
+ /// Save new text for a held message and return it to the queue. The text
+ /// goes through the same sanitization, size caps and `message_send`
+ /// admission as a new message. Returns `false` when the message is not
+ /// being edited in that project.
+ pub async fn save_agent_message_edit(
+ &self,
+ to_workspace_id: ai_memory_core::WorkspaceId,
+ to_project_id: ai_memory_core::ProjectId,
+ id: ai_memory_core::MessageId,
+ subject: Option<String>,
+ body: String,
+ actor: ActorContext,
+ ) -> WikiResult<bool> {
+ let body: String = self.sanitizer.scrub(&body).chars().take(8_000).collect();
+ let subject =
+ subject.map(|s| -> String { self.sanitizer.scrub(&s).chars().take(200).collect() });
+ let admission = self
+ .authorize_operation(
+ to_workspace_id,
+ to_project_id,
+ AdmissionOp::MessageSend,
+ actor,
+ Vec::new(),
+ )
+ .await?;
+ let saved = self
+ .writer
+ .finish_message_edit(to_workspace_id, to_project_id, id, Some((subject, body)))
+ .await?;
+ if saved && let Some(ctx) = admission.as_ref() {
+ self.notify_operation_observers(ctx);
+ }
+ Ok(saved)
+ }
+
/// Attach an embedder. When set, every page-writing path (`write_page`,
/// `apply_batch`, auto-improvement approval, checkpoint restore and the
/// watcher's reindex) computes + stores an embedding for the new version
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 2b49f61c..5d882466 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -614,6 +614,7 @@ prunable rather than only after it ages in place.
| `token_calls` | V90 per-session native response identities with content-free input, output and cache counters. Live hooks merge partial/replayed responses with column-wise maxima in one writer transaction, then refresh cumulative session usage. Project reads authorize the project and apply session ownership before counting or ranking. V90 also converts historical Codex input totals to fresh input, excluding cache reads. |
| `agent_messages.to_agent` | V91 optional registered harness recipient; NULL keeps the shared project inbox. Both claim guards enforce addressed delivery. |
| `token_calls` context and `token_call_tools` | V92 nullable native turn/response coordinates and response time, plus bounded tool references keyed by session/response. One writer transaction persists counters, provenance and session totals; tools cascade with their response. Missing context stays unknown. Server-side UTC/model/harness/session/turn/tool filters run after scope/owner checks and before pagination. |
+| `agent_messages.state` `editing` | V95 lets a sender hold a pending message out of the queue while editing it. The claim path selects only `pending`, so a held message cannot be popped by order or by id. The row keeps its id and `created_at`, and `edited_at` records the last text change. `ops::begin_message_edit` and `finish_message_edit` are single `UPDATE`s scoped to the recipient coordinate and the expected state, so a collected, cancelled or foreign message is left alone. Saving goes through the sanitizer and `message_send` admission. |
| `client_activity` | Server-wide MCP tool-call counters split into reads/writes and bucketed by UTC day. The MCP request choke point flushes buffered calls on a one-minute background interval; failed batches retry from bounded memory. Each day stores at most 128 sanitized client labels plus `other`, so an untrusted `clientInfo.name` cannot create traffic-proportional rows. |
| `auto_improve_proposals` | Staged learning and maintenance edits with immutable target snapshots and append-only decision events. Pending-target uniqueness is scoped by the qualified staging identity; unattributed proposals retain the historical shared bucket. |
| `entities`, `entity_page_links` | V38 noun index derived from canonical frontmatter. Names are normalized and unique per project; links target immutable page versions while retrieval filters to the latest version. Scope-pairing triggers prevent cross-project links. Powers the fourth RRF retrieval stream. |
diff --git a/docs/agent-messaging.md b/docs/agent-messaging.md
index 3e5abb90..0c5ca0eb 100644
--- a/docs/agent-messaging.md
+++ b/docs/agent-messaging.md
@@ -333,6 +333,21 @@ CLI senders keep `to_agent: null` and claim as before. The harness selector
routes a request inside an authorized project. It is not a per-person
confidentiality boundary.
+A queued message can be edited from the Received view. Edit takes it out of the
+queue, so no harness can collect it, and opens its subject and text in an inline
+editor. "Save and requeue" sends the new text through the same sanitizer, size
+caps and `message_send` admission as a new message and puts the message back in
+its original place in the queue. "Discard changes" puts it back unchanged. The
+message keeps its id either way. A message an agent collected in the meantime
+cannot be edited, and the editor says so. Editing needs write access to the
+project that holds the mailbox and to the project the message came from, the
+same access that sending it needed. While held, a message shows as Editing, a
+banner above the list counts the held messages and links to them, and Continue
+editing or Discard changes works from any tab. A held message stays out of the
+queue until someone saves or discards it, so an editor left open in a closed tab
+keeps it from the agent until it is released. The legacy GET-only login cannot
+edit.
+
Queuing a message does not start or wake an agent, or authorize it to follow
the request. The recipient checks its inbox independently and evaluates the
request under the same untrusted-input rules as other cross-project mail. Session-start notices count
diff --git a/docs/features.md b/docs/features.md
index 78b17d4f..4ca4b601 100644
--- a/docs/features.md
+++ b/docs/features.md
@@ -148,6 +148,12 @@ Verify: inspect "Sent". "Queued" means pending; "Collected" means an
agent claimed the message, not that it completed the work. Reading the web
inbox never claims mail or launches an agent.
+To change a message that is still queued, open it in "Received" and select
+"Edit". The message leaves the queue while you edit, so no agent can collect it.
+"Save and requeue" puts the new text back in its original place, and "Discard
+changes" puts the old text back. Held messages show as "Editing" and are counted
+above the list. A message an agent already collected cannot be edited.
+
A static MCP client explicitly names the project and receiving harness:
```json
diff --git a/docs/frontend-api.md b/docs/frontend-api.md
index c255e1ba..da9dd746 100644
--- a/docs/frontend-api.md
+++ b/docs/frontend-api.md
@@ -1022,6 +1022,14 @@ the UI header and the normal browser-session CSRF checks. It does not mutate
wiki pages, pop messages or run an agent. See
[agent messaging](agent-messaging.md#in-the-web-ui).
+Three more POST routes edit a queued message: `/web/messages/{id}/edit` holds it
+out of the queue and returns its text, `/web/messages/{id}/save` replaces the
+subject and text and requeues it, and `/web/messages/{id}/release` requeues it
+unchanged. The body names the mailbox (`workspace`, `project`), and `save` adds
+`subject` and `body`. They need the same checks as sending, plus write access to
+the project the message came from. A message that is not in the expected state
+answers 409.
+
## Bundled documentation for agents
The documentation catalog is at `GET /api/v1/docs?q=token`. Each entry has an
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index a28aff9e..f6200c04 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -93,6 +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 |
| 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/usage.md b/docs/usage.md
index 8540e9e0..e2d16f86 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -987,7 +987,10 @@ Expanding a row shows its plain text. New message picks a source project and a
recipient harness from the agents that already have sessions in visible
projects. Sending needs write access to both projects and goes through the
configured sanitizer and message admission policy. Browser sessions use the
-existing CSRF checks.
+existing CSRF checks. A queued message has an Edit button. It takes the message
+out of the queue while you change its subject or text, and it goes back, in its
+original place, when you save or discard. A message an agent already collected
+cannot be edited.
A queued request does not launch an agent. The addressed harness collects it the
next time it checks its inbox, and "Collected" records that claim, not that the