Skip to content

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

Rust

fix(workstream): authorize finish imports against owner and grants

Éverton Toffanettobadfbce38619
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 762d7fbb..5b221e33 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -118,6 +118,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
older servers leave unsupported fields unknown. (#1016)
### Changed
+- Required managed-run finish imports and finished retries to pass an
+ authenticated owner check and current project access checks, repeated in the
+ writer transaction. Database users required current Write access; trusted
+ proxy operators retained their existing project policy. Active API keys
+ remained valid after human login was disabled. Shared, unattributed runs and
+ late finishes of still-active runs retained their existing behavior.
- Documented FutureInfra as an endpoint for the existing `openai-compat`
provider. (#1026)
- `.github/workflows/nix.yml` builds the flake on `x86_64-linux` for path-
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index 8674e226..d18fa64c 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -13183,25 +13183,34 @@ mod tests {
.unwrap();
state
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- run_id: first.run_id,
- native_session_id: Some("native-1".into()),
- source_cursor: Some("cursor-1".into()),
- events: vec![NewWorkstreamEvent {
- event_id: "event-1".into(),
- agent: AgentKind::Codex,
- native_session_id: "native-1".into(),
- source_record_id: Some("record-1".into()),
- kind: WorkstreamEventKind::Message,
- role: Some("assistant".into()),
- content: "LEDGER-MARKER".into(),
- occurred_at: None,
- metadata: serde_json::json!({}),
- }],
- complete: true,
- segment_path: Some("segment-1.jsonl".into()),
- exit_code: Some(0),
- })
+ .finish_workstream_run(
+ ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ FinishWorkstreamRun {
+ run_id: first.run_id,
+ native_session_id: Some("native-1".into()),
+ source_cursor: Some("cursor-1".into()),
+ events: vec![NewWorkstreamEvent {
+ event_id: "event-1".into(),
+ agent: AgentKind::Codex,
+ native_session_id: "native-1".into(),
+ source_record_id: Some("record-1".into()),
+ kind: WorkstreamEventKind::Message,
+ role: Some("assistant".into()),
+ content: "LEDGER-MARKER".into(),
+ occurred_at: None,
+ metadata: serde_json::json!({}),
+ }],
+ complete: true,
+ segment_path: Some("segment-1.jsonl".into()),
+ exit_code: Some(0),
+ },
+ )
.await
.unwrap();
// Second run: this is the SessionStart that has a ledger to deliver.
@@ -13591,25 +13600,34 @@ mod tests {
.unwrap();
state
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- run_id: first.run_id,
- native_session_id: Some("claude-session".into()),
- source_cursor: None,
- events: vec![ai_memory_core::NewWorkstreamEvent {
- event_id: "managed-event-1".into(),
- agent: AgentKind::ClaudeCode,
- native_session_id: "claude-session".into(),
- source_record_id: Some("record-1".into()),
- kind: WorkstreamEventKind::Message,
- role: Some("user".into()),
- content: "portable managed delta sentinel".into(),
- occurred_at: None,
- metadata: serde_json::json!({}),
- }],
- complete: true,
- segment_path: None,
- exit_code: Some(0),
- })
+ .finish_workstream_run(
+ ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ FinishWorkstreamRun {
+ run_id: first.run_id,
+ native_session_id: Some("claude-session".into()),
+ source_cursor: None,
+ events: vec![ai_memory_core::NewWorkstreamEvent {
+ event_id: "managed-event-1".into(),
+ agent: AgentKind::ClaudeCode,
+ native_session_id: "claude-session".into(),
+ source_record_id: Some("record-1".into()),
+ kind: WorkstreamEventKind::Message,
+ role: Some("user".into()),
+ content: "portable managed delta sentinel".into(),
+ occurred_at: None,
+ metadata: serde_json::json!({}),
+ }],
+ complete: true,
+ segment_path: None,
+ exit_code: Some(0),
+ },
+ )
.await
.unwrap();
diff --git a/crates/ai-memory-hooks/src/workstream.rs b/crates/ai-memory-hooks/src/workstream.rs
index f3a2292c..072040b3 100644
--- a/crates/ai-memory-hooks/src/workstream.rs
+++ b/crates/ai-memory-hooks/src/workstream.rs
@@ -49,6 +49,8 @@ pub struct WorkstreamState {
pub data_dir: PathBuf,
/// Whether a trusted proxy can distinguish operators without DB users.
pub trusted_proxy_identity: bool,
+ #[cfg(test)]
+ finish_barrier: Option<std::sync::Arc<(tokio::sync::Notify, tokio::sync::Notify)>>,
}
pub(crate) async fn managed_run_owner_stamp(
@@ -804,7 +806,9 @@ async fn link_run(
async fn finish_run(
State(state): State<WorkstreamState>,
level: Option<Extension<AuthLevel>>,
- actor: Option<Extension<ai_memory_core::AuthorizedViewer>>,
+ viewer: Option<Extension<ai_memory_core::AuthorizedViewer>>,
+ actor: Option<Extension<ai_memory_core::ActorContext>>,
+ user_id: Option<Extension<ai_memory_core::UserId>>,
AxumPath(raw_run_id): AxumPath<String>,
Json(mut request): Json<FinishManagedRunRequest>,
) -> Response {
@@ -815,15 +819,27 @@ async fn finish_run(
Ok(id) => id,
Err(response) => return response.into_response(),
};
- if let Err(response) = authorize_run(
- &state,
- run_id,
- actor_user(actor),
- ai_memory_store::ProjectAccess::Write,
- )
- .await
+ let authority = ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ level.map_or(AuthLevel::Anonymous, |Extension(level)| level),
+ viewer.map(|Extension(viewer)| viewer),
+ user_id.map(|Extension(user_id)| user_id),
+ &actor.map_or_else(
+ ai_memory_core::ActorContext::anonymous,
+ |Extension(actor)| actor,
+ ),
+ state.trusted_proxy_identity,
+ );
+ if let Err(failure) = state
+ .reader
+ .authorize_workstream_finish(run_id, authority.clone())
+ .await
{
- return response;
+ return store_error_response(failure);
+ }
+ #[cfg(test)]
+ if let Some(barrier) = &state.finish_barrier {
+ barrier.0.notify_one();
+ barrier.1.notified().await;
}
if request.events.len() > MAX_EVENTS_PER_FINISH {
return error(
@@ -846,15 +862,18 @@ async fn finish_run(
if status.state == "finished" {
return match state
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- run_id,
- native_session_id: None,
- source_cursor: None,
- events: Vec::new(),
- complete: true,
- segment_path: None,
- exit_code: None,
- })
+ .finish_workstream_run(
+ authority,
+ FinishWorkstreamRun {
+ run_id,
+ native_session_id: None,
+ source_cursor: None,
+ events: Vec::new(),
+ complete: true,
+ segment_path: None,
+ exit_code: None,
+ },
+ )
.await
{
Ok(result) => Json(FinishManagedRunResponse {
@@ -911,7 +930,7 @@ async fn finish_run(
segment_path: Some(segment_path),
exit_code: request.exit_code,
};
- match state.writer.finish_workstream_run(input).await {
+ match state.writer.finish_workstream_run(authority, input).await {
Ok(result) => Json(FinishManagedRunResponse {
imported_events: result.imported_events,
latest_sequence: result.latest_sequence,
@@ -927,6 +946,7 @@ fn parse_run_id(raw: &str) -> Result<ManagedRunId, ApiFailure> {
fn store_error_response(failure: StoreError) -> Response {
let status = match failure {
+ StoreError::Forbidden(_) => StatusCode::FORBIDDEN,
StoreError::WorkstreamBusy(_)
| StoreError::Duplicate(_)
| StoreError::WorkstreamNameTaken(_) => StatusCode::CONFLICT,
@@ -1127,6 +1147,7 @@ mod tests {
sanitizer: Sanitizer::default(),
data_dir: data_dir.to_path_buf(),
trusted_proxy_identity: false,
+ finish_barrier: None,
}
}
@@ -1320,15 +1341,24 @@ mod tests {
.unwrap();
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- run_id: prepared.run_id,
- native_session_id: Some("private-native-id".into()),
- source_cursor: None,
- events: Vec::new(),
- complete: true,
- segment_path: None,
- exit_code: Some(0),
- })
+ .finish_workstream_run(
+ ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ FinishWorkstreamRun {
+ run_id: prepared.run_id,
+ native_session_id: Some("private-native-id".into()),
+ source_cursor: None,
+ events: Vec::new(),
+ complete: true,
+ segment_path: None,
+ exit_code: Some(0),
+ },
+ )
.await
.unwrap();
@@ -1413,15 +1443,24 @@ mod tests {
.unwrap();
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- run_id: claude.run_id,
- native_session_id: Some("claude-current".into()),
- source_cursor: Some("cursor".into()),
- events: Vec::new(),
- complete: true,
- segment_path: None,
- exit_code: Some(0),
- })
+ .finish_workstream_run(
+ ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ FinishWorkstreamRun {
+ run_id: claude.run_id,
+ native_session_id: Some("claude-current".into()),
+ source_cursor: Some("cursor".into()),
+ events: Vec::new(),
+ complete: true,
+ segment_path: None,
+ exit_code: Some(0),
+ },
+ )
.await
.unwrap();
@@ -1491,15 +1530,24 @@ mod tests {
// Close the explicit run so the automatic prepare can take the lease.
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- run_id: prepared.run_id,
- native_session_id: Some("session_abc".into()),
- source_cursor: None,
- events: Vec::new(),
- complete: true,
- segment_path: None,
- exit_code: Some(0),
- })
+ .finish_workstream_run(
+ ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ FinishWorkstreamRun {
+ run_id: prepared.run_id,
+ native_session_id: Some("session_abc".into()),
+ source_cursor: None,
+ events: Vec::new(),
+ complete: true,
+ segment_path: None,
+ exit_code: Some(0),
+ },
+ )
.await
.unwrap();
@@ -1752,15 +1800,24 @@ mod tests {
assert_eq!(prepared.resolved_agent, Some(AgentKind::KiroCli));
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- run_id: prepared.run_id,
- native_session_id: Some("7c1d5698-204a-4c0f-ae9c-43db7fc4e41d".into()),
- source_cursor: None,
- events: Vec::new(),
- complete: true,
- segment_path: None,
- exit_code: Some(0),
- })
+ .finish_workstream_run(
+ ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ FinishWorkstreamRun {
+ run_id: prepared.run_id,
+ native_session_id: Some("7c1d5698-204a-4c0f-ae9c-43db7fc4e41d".into()),
+ source_cursor: None,
+ events: Vec::new(),
+ complete: true,
+ segment_path: None,
+ exit_code: Some(0),
+ },
+ )
.await
.unwrap();
@@ -1821,15 +1878,24 @@ mod tests {
assert_eq!(prepared.resolved_agent, Some(AgentKind::CommandCode));
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- run_id: prepared.run_id,
- native_session_id: Some("2cce5126-f57d-4ddd-8f66-e5bb409f60db".into()),
- source_cursor: None,
- events: Vec::new(),
- complete: true,
- segment_path: None,
- exit_code: Some(0),
- })
+ .finish_workstream_run(
+ ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ FinishWorkstreamRun {
+ run_id: prepared.run_id,
+ native_session_id: Some("2cce5126-f57d-4ddd-8f66-e5bb409f60db".into()),
+ source_cursor: None,
+ events: Vec::new(),
+ complete: true,
+ segment_path: None,
+ exit_code: Some(0),
+ },
+ )
.await
.unwrap();
@@ -1890,15 +1956,24 @@ mod tests {
assert_eq!(prepared.resolved_agent, Some(AgentKind::Grok));
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- run_id: prepared.run_id,
- native_session_id: Some("019f-session".into()),
- source_cursor: None,
- events: Vec::new(),
- complete: true,
- segment_path: None,
- exit_code: Some(0),
- })
+ .finish_workstream_run(
+ ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ FinishWorkstreamRun {
+ run_id: prepared.run_id,
+ native_session_id: Some("019f-session".into()),
+ source_cursor: None,
+ events: Vec::new(),
+ complete: true,
+ segment_path: None,
+ exit_code: Some(0),
+ },
+ )
.await
.unwrap();
@@ -1962,15 +2037,24 @@ mod tests {
assert_eq!(prepared.resolved_agent, Some(AgentKind::AntigravityCli));
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- run_id: prepared.run_id,
- native_session_id: Some("a0d5ac62-2501-4780-b783-76d159c56cb3".into()),
- source_cursor: None,
- events: Vec::new(),
- complete: true,
- segment_path: None,
- exit_code: Some(0),
- })
+ .finish_workstream_run(
+ ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ FinishWorkstreamRun {
+ run_id: prepared.run_id,
+ native_session_id: Some("a0d5ac62-2501-4780-b783-76d159c56cb3".into()),
+ source_cursor: None,
+ events: Vec::new(),
+ complete: true,
+ segment_path: None,
+ exit_code: Some(0),
+ },
+ )
.await
.unwrap();
@@ -2084,25 +2168,34 @@ mod tests {
.unwrap();
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- run_id: codex.run_id,
- native_session_id: Some("codex-native".into()),
- source_cursor: None,
- events: vec![NewWorkstreamEvent {
- event_id: "codex:assistant:1".into(),
- agent: AgentKind::Codex,
- native_session_id: "codex-native".into(),
- source_record_id: None,
- kind: WorkstreamEventKind::Message,
- role: Some("assistant".into()),
- content: "AMWS-CODEX-SENTINEL".into(),
- occurred_at: None,
- metadata: serde_json::json!({}),
- }],
- complete: true,
- segment_path: None,
- exit_code: Some(0),
- })
+ .finish_workstream_run(
+ ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ FinishWorkstreamRun {
+ run_id: codex.run_id,
+ native_session_id: Some("codex-native".into()),
+ source_cursor: None,
+ events: vec![NewWorkstreamEvent {
+ event_id: "codex:assistant:1".into(),
+ agent: AgentKind::Codex,
+ native_session_id: "codex-native".into(),
+ source_record_id: None,
+ kind: WorkstreamEventKind::Message,
+ role: Some("assistant".into()),
+ content: "AMWS-CODEX-SENTINEL".into(),
+ occurred_at: None,
+ metadata: serde_json::json!({}),
+ }],
+ complete: true,
+ segment_path: None,
+ exit_code: Some(0),
+ },
+ )
.await
.unwrap();
let crush = store
@@ -2381,4 +2474,188 @@ mod tests {
.await;
assert_eq!(unknown.status(), StatusCode::NOT_FOUND);
}
+
+ async fn finish_sql_snapshot(store: &Store) -> Vec<Vec<String>> {
+ store
+ .reader
+ .with_conn(|conn| {
+ let mut result = Vec::new();
+ for table in [
+ "workspaces",
+ "projects",
+ "managed_runs",
+ "workstreams",
+ "workstream_events",
+ "workstream_native_sessions",
+ "workstream_events_fts_data",
+ "workstream_events_fts_idx",
+ "workstream_events_fts_docsize",
+ "sessions",
+ ] {
+ let mut stmt = conn.prepare(&format!("SELECT * FROM {table} ORDER BY 1, 2"))?;
+ let columns = stmt.column_count();
+ result.extend(
+ stmt.query_map([], |row| {
+ (0..columns)
+ .map(|i| row.get_ref(i).map(|v| format!("{v:?}")))
+ .collect()
+ })?
+ .collect::<Result<Vec<Vec<String>>, _>>()?,
+ );
+ }
+ Ok(result)
+ })
+ .await
+ .unwrap()
+ }
+
+ #[tokio::test]
+ async fn owner_finish_revocation_between_preflight_and_both_writer_paths() {
+ let temp = TempDir::new().unwrap();
+ let store = Store::open(temp.path()).unwrap();
+ let (ws, project) = seed_scope(&store).await;
+ let alice = store
+ .writer
+ .create_human_user(
+ ai_memory_core::NewUser {
+ username: "alice".into(),
+ name: None,
+ email: None,
+ },
+ ai_memory_core::UserRole::User,
+ None,
+ false,
+ )
+ .await
+ .unwrap();
+ store
+ .writer
+ .set_access_mode(project, ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ let actor = ai_memory_core::ActorContext {
+ user: Some("alice".into()),
+ ..ai_memory_core::ActorContext::anonymous()
+ };
+ for finished in [false, true] {
+ store
+ .writer
+ .grant_memory(alice, project, ai_memory_store::GrantLevel::Write, None)
+ .await
+ .unwrap();
+ let run = store
+ .writer
+ .prepare_workstream_run_owned(
+ PrepareWorkstreamRun {
+ selection: WorkstreamSelection::New(format!("revoke-{finished}")),
+ ..prepare_input(ws, project, AgentKind::Codex, "label")
+ },
+ Some("user:alice".into()),
+ )
+ .await
+ .unwrap();
+ if finished {
+ store
+ .writer
+ .finish_workstream_run(
+ ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ AuthLevel::User,
+ Some(ai_memory_core::AuthorizedViewer(alice)),
+ Some(alice),
+ &actor,
+ false,
+ ),
+ FinishWorkstreamRun {
+ run_id: run.run_id,
+ native_session_id: None,
+ source_cursor: None,
+ events: Vec::new(),
+ complete: true,
+ segment_path: None,
+ exit_code: None,
+ },
+ )
+ .await
+ .unwrap();
+ }
+ let barrier =
+ std::sync::Arc::new((tokio::sync::Notify::new(), tokio::sync::Notify::new()));
+ let mut state = test_state(&store, temp.path());
+ state.finish_barrier = Some(barrier.clone());
+ let request = serde_json::from_value(serde_json::json!({
+ "native_session_id": "native-revoke", "source_cursor": "cursor-revoke", "checkpoint": {},
+ "complete": true, "events": [{"event_id": "revoked-event", "agent": "codex",
+ "native_session_id": "native-revoke", "kind": "message", "role": "assistant",
+ "content": "revocation race evidence", "metadata": {}}]
+ })).unwrap();
+ let (response, before) = tokio::join!(
+ finish_run(
+ State(state),
+ Some(Extension(AuthLevel::User)),
+ Some(Extension(ai_memory_core::AuthorizedViewer(alice))),
+ Some(Extension(actor.clone())),
+ Some(Extension(alice)),
+ AxumPath(run.run_id.to_string()),
+ Json(request)
+ ),
+ async {
+ barrier.0.notified().await;
+ assert!(
+ store
+ .writer
+ .revoke_memory(alice, project, None)
+ .await
+ .unwrap()
+ );
+ let before = finish_sql_snapshot(&store).await;
+ barrier.1.notify_one();
+ before
+ }
+ );
+ assert_eq!(
+ response.status(),
+ StatusCode::FORBIDDEN,
+ "both writer paths must recheck Write after preflight"
+ );
+ assert_eq!(
+ finish_sql_snapshot(&store).await,
+ before,
+ "writer refusal must change no SQL run, event, index, link or cursor"
+ );
+ let raw = temp
+ .path()
+ .join("raw/workstreams")
+ .join(run.workstream_id.to_string());
+ assert_eq!(
+ raw.exists(),
+ !finished,
+ "normal revocation race can leave an unindexed raw segment; retries write none"
+ );
+ store
+ .writer
+ .grant_memory(alice, project, ai_memory_store::GrantLevel::Write, None)
+ .await
+ .unwrap();
+ let response = finish_run(
+ State(test_state(&store, temp.path())),
+ Some(Extension(AuthLevel::User)),
+ Some(Extension(ai_memory_core::AuthorizedViewer(alice))),
+ Some(Extension(actor.clone())),
+ Some(Extension(alice)),
+ AxumPath(run.run_id.to_string()),
+ Json(
+ serde_json::from_value(serde_json::json!({
+ "checkpoint": {}, "events": [], "complete": true
+ }))
+ .unwrap(),
+ ),
+ )
+ .await;
+ assert_eq!(
+ response.status(),
+ StatusCode::OK,
+ "restored Write legitimately finishes or retries the same run"
+ );
+ }
+ }
}
diff --git a/crates/ai-memory-mcp/src/auth.rs b/crates/ai-memory-mcp/src/auth.rs
index baa7f333..565108a8 100644
--- a/crates/ai-memory-mcp/src/auth.rs
+++ b/crates/ai-memory-mcp/src/auth.rs
@@ -1719,4 +1719,895 @@ mod tests {
.unwrap();
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}
+
+ async fn owner_finish_user(store: &Store, name: &str) -> (ai_memory_core::UserId, String) {
+ let id = store
+ .writer
+ .create_human_user(
+ NewUser {
+ username: name.into(),
+ name: None,
+ email: None,
+ },
+ ai_memory_core::UserRole::User,
+ None,
+ false,
+ )
+ .await
+ .unwrap();
+ let token = ai_memory_store::generate_api_key().unwrap();
+ store
+ .writer
+ .create_api_credential(
+ ai_memory_core::ApiCredentialId::new(),
+ id,
+ "owner-finish".into(),
+ ai_memory_store::hash_token(&token, &TokenPepper::new("finish-pepper")),
+ None,
+ )
+ .await
+ .unwrap();
+ (id, token)
+ }
+
+ async fn owner_finish_run(
+ store: &Store,
+ ws: ai_memory_core::WorkspaceId,
+ project: ai_memory_core::ProjectId,
+ name: &str,
+ owner: Option<String>,
+ ) -> ai_memory_store::PreparedWorkstreamRun {
+ store
+ .writer
+ .prepare_workstream_run_owned(
+ ai_memory_store::PrepareWorkstreamRun {
+ workspace_id: ws,
+ project_id: project,
+ repo_fingerprint: "repo".into(),
+ worktree_fingerprint: "tree".into(),
+ cwd: "/repo".into(),
+ agent: ai_memory_core::AgentKind::Codex,
+ automatic_harness: false,
+ available_agents: Vec::new(),
+ selection: ai_memory_store::WorkstreamSelection::New(name.into()),
+ lease_owner: "diagnostic-only".into(),
+ },
+ owner,
+ )
+ .await
+ .unwrap()
+ }
+
+ fn owner_finish_http(store: &Store, root: &std::path::Path, auth: AuthState) -> Router {
+ ai_memory_hooks::workstream_router(ai_memory_hooks::WorkstreamState {
+ writer: store.writer.clone(),
+ reader: store.reader.clone(),
+ sanitizer: ai_memory_core::Sanitizer::default(),
+ data_dir: root.into(),
+ trusted_proxy_identity: auth.actor_proxy_bearer().is_some(),
+ })
+ .layer(axum::middleware::from_fn_with_state(
+ Arc::new(auth),
+ require_bearer,
+ ))
+ }
+
+ async fn owner_finish_request(
+ http: &Router,
+ id: ai_memory_core::ManagedRunId,
+ token: Option<&str>,
+ events: serde_json::Value,
+ complete: bool,
+ ) -> Response {
+ let mut request = Request::builder()
+ .method("POST")
+ .uri(format!("/workstream/runs/{id}/finish"))
+ .header("Content-Type", "application/json")
+ .header("X-Memory-Actor-User", "alice")
+ .header("X-Memory-Actor-Sub", "alice")
+ .header("X-Memory-Actor-Issuer", "https://idp.example");
+ if let Some(token) = token {
+ request = request.header("Authorization", format!("Bearer {token}"));
+ }
+ let payload = serde_json::json!({
+ "native_session_id": "native-owner", "source_cursor": "foreign-cursor",
+ "events": events, "complete": complete, "exit_code": 9, "checkpoint": {},
+ "actor": {"user": "alice"}, "principal": {"is_root": true}
+ });
+ let request = request.body(Body::from(payload.to_string())).unwrap();
+ http.clone().oneshot(request).await.unwrap()
+ }
+
+ fn owner_finish_events() -> serde_json::Value {
+ serde_json::json!([{
+ "event_id": "owner-finish-event", "agent": "codex", "native_session_id": "native-owner",
+ "kind": "message", "role": "assistant", "content": "owner finish evidence",
+ "metadata": {"actor_user": "alice", "owner_user": "user:alice", "is_root": true}
+ }])
+ }
+
+ async fn owner_finish_prepare_http(
+ http: &Router,
+ token: &str,
+ name: &str,
+ ) -> ai_memory_core::PrepareManagedRunResponse {
+ let response = http
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/workstream/runs")
+ .header("Content-Type", "application/json")
+ .header("Authorization", format!("Bearer {token}"))
+ .header("X-Memory-Actor-User", "alice")
+ .header("X-Memory-Actor-Issuer", "https://idp.example")
+ .header("X-Memory-Actor-Sub", "alice")
+ .body(Body::from(
+ serde_json::json!({
+ "workspace": "finish-compat", "project": "restricted", "cwd": "/repo",
+ "repo_fingerprint": "compat-repo", "worktree_fingerprint": name,
+ "agent": "codex", "new_workstream": name, "lease_owner": "display-only"
+ })
+ .to_string(),
+ ))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.status(),
+ StatusCode::OK,
+ "authenticated prepare must remain legitimate"
+ );
+ let body = axum::body::to_bytes(response.into_body(), 65536)
+ .await
+ .unwrap();
+ serde_json::from_slice(&body).unwrap()
+ }
+
+ #[tokio::test]
+ async fn owner_finish_http_trusted_proxy_preserves_restricted_lifecycle() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("finish-compat")
+ .await
+ .unwrap();
+ let project = store
+ .writer
+ .get_or_create_project(ws, "restricted", None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .set_access_mode(project, ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ // A DB user with the same display name must not change the proxy's OIDC owner.
+ let (alice, db_token) = owner_finish_user(&store, "alice").await;
+ let auth = AuthState::new(Some("root-finish-token".into()))
+ .with_trusted_proxy_bearer("proxy-finish-token")
+ .with_multiuser(
+ TokenPepper::new("finish-pepper"),
+ store.reader.clone(),
+ store.writer.clone(),
+ );
+ let http = owner_finish_http(&store, tmp.path(), auth.clone());
+ let run = owner_finish_prepare_http(&http, "proxy-finish-token", "proxy-owned").await;
+ let before = owner_finish_snapshot(&store).await;
+ for token in [None, Some("invalid-token")] {
+ assert_eq!(
+ owner_finish_request(&http, run.run_id, token, owner_finish_events(), true)
+ .await
+ .status(),
+ StatusCode::UNAUTHORIZED
+ );
+ }
+ for invalid in [true, false] {
+ let mut events = owner_finish_events();
+ if invalid {
+ events[0]["agent"] = serde_json::json!("claude-code");
+ }
+ let response = http.clone().oneshot(
+ Request::builder().method("POST").uri(format!("/workstream/runs/{}/finish", run.run_id))
+ .header("Content-Type", "application/json")
+ .header("Authorization", "Bearer proxy-finish-token")
+ .header("X-Memory-Actor-User", "alice")
+ .header("X-Memory-Actor-Issuer", "https://idp.example")
+ .header("X-Memory-Actor-Sub", "bob")
+ .body(Body::from(serde_json::json!({"events": events, "complete": true, "checkpoint": {}, "actor": {"sub": "alice"}, "principal": {"is_root": true}}).to_string())).unwrap()
+ ).await.unwrap();
+ assert_eq!(
+ response.status(),
+ StatusCode::FORBIDDEN,
+ "foreign proxy owner must be refused before payload handling"
+ );
+ }
+ let malformed = http
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri(format!("/workstream/runs/{}/finish", run.run_id))
+ .header("Content-Type", "application/json")
+ .header("Authorization", "Bearer proxy-finish-token")
+ .header("X-Memory-Actor-Issuer", "https://idp.example")
+ .body(Body::from("{\"events\":[],\"complete\":true}"))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(malformed.status(), StatusCode::BAD_REQUEST);
+ assert_eq!(owner_finish_snapshot(&store).await, before);
+ // Enabling proxy authentication never exempts an actual DB principal from grants.
+ let db_run = owner_finish_run(
+ &store,
+ ws,
+ project,
+ "db-no-grant",
+ Some("user:alice".into()),
+ )
+ .await;
+ let db_before = owner_finish_snapshot(&store).await;
+ assert_eq!(
+ owner_finish_request(
+ &http,
+ db_run.run_id,
+ Some(&db_token),
+ owner_finish_events(),
+ true
+ )
+ .await
+ .status(),
+ StatusCode::FORBIDDEN,
+ "a DB principal must retain its current project grant check with proxy enabled"
+ );
+ assert_eq!(owner_finish_snapshot(&store).await, db_before);
+ assert!(!tmp.path().join("raw/workstreams").exists());
+ // The configured server flag is also required, not just User without a DB id.
+ let without_proxy_policy =
+ ai_memory_hooks::workstream_router(ai_memory_hooks::WorkstreamState {
+ writer: store.writer.clone(),
+ reader: store.reader.clone(),
+ sanitizer: ai_memory_core::Sanitizer::default(),
+ data_dir: tmp.path().into(),
+ trusted_proxy_identity: false,
+ })
+ .layer(axum::middleware::from_fn_with_state(
+ Arc::new(auth),
+ require_bearer,
+ ));
+ assert_eq!(
+ owner_finish_request(
+ &without_proxy_policy,
+ run.run_id,
+ Some("proxy-finish-token"),
+ owner_finish_events(),
+ true
+ )
+ .await
+ .status(),
+ StatusCode::FORBIDDEN,
+ "proxy compatibility requires the server's trusted-proxy configuration"
+ );
+ assert_eq!(owner_finish_snapshot(&store).await, db_before);
+ let conn = rusqlite::Connection::open(store.db_path()).unwrap();
+ conn.execute(
+ "UPDATE managed_runs SET lease_expires_at = 0 WHERE id = ?1",
+ rusqlite::params![run.run_id.as_bytes()],
+ )
+ .unwrap();
+ let response = owner_finish_request(
+ &http,
+ run.run_id,
+ Some("proxy-finish-token"),
+ owner_finish_events(),
+ true,
+ )
+ .await;
+ assert_eq!(
+ response.status(),
+ StatusCode::OK,
+ "a genuine proxy owner must finish the restricted run it prepared"
+ );
+ let finished = owner_finish_snapshot(&store).await;
+ let foreign_retry = http.clone().oneshot(
+ Request::builder().method("POST").uri(format!("/workstream/runs/{}/finish", run.run_id))
+ .header("Content-Type", "application/json")
+ .header("Authorization", "Bearer proxy-finish-token")
+ .header("X-Memory-Actor-User", "alice")
+ .header("X-Memory-Actor-Issuer", "https://idp.example")
+ .header("X-Memory-Actor-Sub", "bob")
+ .body(Body::from(serde_json::json!({"events": owner_finish_events(), "complete": true, "checkpoint": {}}).to_string())).unwrap()
+ ).await.unwrap();
+ assert_eq!(
+ foreign_retry.status(),
+ StatusCode::FORBIDDEN,
+ "finished proxy retries must still refuse a foreign owner"
+ );
+ assert_eq!(owner_finish_snapshot(&store).await, finished);
+ let retry = owner_finish_request(
+ &http,
+ run.run_id,
+ Some("proxy-finish-token"),
+ owner_finish_events(),
+ true,
+ )
+ .await;
+ assert_eq!(retry.status(), StatusCode::OK);
+ let body = axum::body::to_bytes(retry.into_body(), 65536)
+ .await
+ .unwrap();
+ assert_eq!(
+ serde_json::from_slice::<serde_json::Value>(&body).unwrap()["imported_events"],
+ 0
+ );
+ assert_eq!(owner_finish_snapshot(&store).await, finished);
+ store
+ .writer
+ .grant_memory(alice, project, ai_memory_store::GrantLevel::Write, None)
+ .await
+ .unwrap();
+ assert_eq!(
+ owner_finish_request(
+ &http,
+ run.run_id,
+ Some(&db_token),
+ owner_finish_events(),
+ true
+ )
+ .await
+ .status(),
+ StatusCode::FORBIDDEN,
+ "a DB username cannot forge the proxy's qualified OIDC owner"
+ );
+ assert_eq!(owner_finish_snapshot(&store).await, finished);
+ assert_eq!(
+ owner_finish_request(
+ &http,
+ db_run.run_id,
+ Some(&db_token),
+ owner_finish_events(),
+ true
+ )
+ .await
+ .status(),
+ StatusCode::OK
+ );
+ }
+
+ #[tokio::test]
+ async fn owner_finish_http_active_api_key_survives_disabled_human_login() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("finish-compat")
+ .await
+ .unwrap();
+ let project = store
+ .writer
+ .get_or_create_project(ws, "restricted", None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .set_access_mode(project, ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ let (alice, token) = owner_finish_user(&store, "alice").await;
+ store
+ .writer
+ .grant_memory(alice, project, ai_memory_store::GrantLevel::Write, None)
+ .await
+ .unwrap();
+ store.writer.set_user_disabled(alice, true).await.unwrap();
+ let http = owner_finish_http(
+ &store,
+ tmp.path(),
+ AuthState::new(Some("root-finish-token".into())).with_multiuser(
+ TokenPepper::new("finish-pepper"),
+ store.reader.clone(),
+ store.writer.clone(),
+ ),
+ );
+ let run = owner_finish_prepare_http(&http, &token, "api-human-disabled").await;
+ let response =
+ owner_finish_request(&http, run.run_id, Some(&token), owner_finish_events(), true)
+ .await;
+ assert_eq!(
+ response.status(),
+ StatusCode::OK,
+ "an active API key with Write must finish after human login is disabled"
+ );
+ let revoked = owner_finish_prepare_http(&http, &token, "api-grant-revoked").await;
+ store
+ .writer
+ .revoke_memory(alice, project, None)
+ .await
+ .unwrap();
+ let before = owner_finish_snapshot(&store).await;
+ let response = owner_finish_request(
+ &http,
+ revoked.run_id,
+ Some(&token),
+ owner_finish_events(),
+ true,
+ )
+ .await;
+ assert_eq!(
+ response.status(),
+ StatusCode::FORBIDDEN,
+ "disabled human login does not waive current API-user project grants"
+ );
+ assert_eq!(owner_finish_snapshot(&store).await, before);
+ assert!(
+ !tmp.path()
+ .join(format!(
+ "raw/workstreams/{}/segments",
+ revoked.workstream_id
+ ))
+ .exists()
+ );
+ let credentials = store
+ .reader
+ .list_api_credentials_for_user(alice)
+ .await
+ .unwrap();
+ store
+ .writer
+ .revoke_api_credential(credentials[0].id)
+ .await
+ .unwrap();
+ assert_eq!(
+ owner_finish_request(&http, run.run_id, Some(&token), owner_finish_events(), true)
+ .await
+ .status(),
+ StatusCode::UNAUTHORIZED,
+ "a revoked API key must be refused by the real middleware"
+ );
+ assert_eq!(owner_finish_snapshot(&store).await, before);
+ }
+
+ async fn owner_finish_snapshot(store: &Store) -> Vec<Vec<rusqlite::types::Value>> {
+ store
+ .reader
+ .with_conn(|conn| {
+ let mut result = Vec::new();
+ for table in [
+ "managed_runs",
+ "workstreams",
+ "workstream_events",
+ "workstream_native_sessions",
+ "workstream_events_fts_data",
+ "workstream_events_fts_idx",
+ "workstream_events_fts_docsize",
+ "sessions",
+ ] {
+ let mut stmt = conn.prepare(&format!("SELECT * FROM {table} ORDER BY 1, 2"))?;
+ let count = stmt.column_count();
+ let rows =
+ stmt.query_map([], |row| (0..count).map(|i| row.get(i)).collect())?;
+ result.extend(
+ rows.collect::<rusqlite::Result<Vec<Vec<rusqlite::types::Value>>>>()?,
+ );
+ }
+ Ok(result)
+ })
+ .await
+ .unwrap()
+ }
+
+ #[tokio::test]
+ async fn owner_finish_http_refuses_another_writer_before_payload_or_segment() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("owner-finish")
+ .await
+ .unwrap();
+ let project = store
+ .writer
+ .get_or_create_project(ws, "shared", None)
+ .await
+ .unwrap();
+ let (alice, alice_token) = owner_finish_user(&store, "alice").await;
+ let (bob, bob_token) = owner_finish_user(&store, "bob").await;
+ store
+ .writer
+ .set_access_mode(project, ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ for user in [alice, bob] {
+ store
+ .writer
+ .grant_memory(user, project, ai_memory_store::GrantLevel::Write, None)
+ .await
+ .unwrap();
+ }
+ let run = owner_finish_run(&store, ws, project, "owned", Some("user:alice".into())).await;
+ let http = owner_finish_http(
+ &store,
+ tmp.path(),
+ AuthState::new(Some("root-finish-token".into())).with_multiuser(
+ TokenPepper::new("finish-pepper"),
+ store.reader.clone(),
+ store.writer.clone(),
+ ),
+ );
+ let before = owner_finish_snapshot(&store).await;
+ let mut invalid = owner_finish_events();
+ invalid[0]["agent"] = serde_json::json!("claude-code");
+ let response =
+ owner_finish_request(&http, run.run_id, Some(&bob_token), invalid, true).await;
+ assert_eq!(
+ response.status(),
+ StatusCode::FORBIDDEN,
+ "owner refusal must precede payload validation"
+ );
+ for complete in [false, true] {
+ let response = owner_finish_request(
+ &http,
+ run.run_id,
+ Some(&bob_token),
+ owner_finish_events(),
+ complete,
+ )
+ .await;
+ assert_eq!(
+ response.status(),
+ StatusCode::FORBIDDEN,
+ "Write permission must not bypass another author's owner"
+ );
+ }
+ assert_eq!(owner_finish_snapshot(&store).await, before);
+ assert!(
+ !tmp.path().join("raw/workstreams").exists(),
+ "foreign owner must write no raw segment"
+ );
+ let response = owner_finish_request(
+ &http,
+ run.run_id,
+ Some(&alice_token),
+ owner_finish_events(),
+ true,
+ )
+ .await;
+ assert_eq!(response.status(), StatusCode::OK);
+ let before = owner_finish_snapshot(&store).await;
+ let response = owner_finish_request(
+ &http,
+ run.run_id,
+ Some(&bob_token),
+ owner_finish_events(),
+ true,
+ )
+ .await;
+ assert_eq!(
+ response.status(),
+ StatusCode::FORBIDDEN,
+ "finished retries still check the owner"
+ );
+ let response = owner_finish_request(
+ &http,
+ run.run_id,
+ Some(&alice_token),
+ owner_finish_events(),
+ true,
+ )
+ .await;
+ assert_eq!(response.status(), StatusCode::OK);
+ let body = axum::body::to_bytes(response.into_body(), 65536)
+ .await
+ .unwrap();
+ assert_eq!(
+ serde_json::from_slice::<serde_json::Value>(&body).unwrap()["imported_events"],
+ 0
+ );
+ assert_eq!(owner_finish_snapshot(&store).await, before);
+ }
+
+ #[tokio::test]
+ async fn owner_finish_http_real_auth_rungs_shared_and_project_controls() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store.writer.get_or_create_workspace("rungs").await.unwrap();
+ let project = store
+ .writer
+ .get_or_create_project(ws, "shared", None)
+ .await
+ .unwrap();
+ let anonymous_http = owner_finish_http(&store, tmp.path(), AuthState::new(None));
+ let anonymous_run = owner_finish_run(&store, ws, project, "anonymous", None).await;
+ assert_eq!(
+ owner_finish_request(
+ &anonymous_http,
+ anonymous_run.run_id,
+ None,
+ owner_finish_events(),
+ true
+ )
+ .await
+ .status(),
+ StatusCode::OK
+ );
+ let (alice, token) = owner_finish_user(&store, "alice").await;
+ store
+ .writer
+ .set_access_mode(project, ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ let http = owner_finish_http(
+ &store,
+ tmp.path(),
+ AuthState::new(Some("root-finish-token".into())).with_multiuser(
+ TokenPepper::new("finish-pepper"),
+ store.reader.clone(),
+ store.writer.clone(),
+ ),
+ );
+ let shared = owner_finish_run(&store, ws, project, "shared-root", None).await;
+ let before = owner_finish_snapshot(&store).await;
+ assert_eq!(
+ owner_finish_request(
+ &anonymous_http,
+ shared.run_id,
+ None,
+ owner_finish_events(),
+ true
+ )
+ .await
+ .status(),
+ StatusCode::FORBIDDEN,
+ "an anonymous caller must not acquire root on topology reload"
+ );
+ assert_eq!(
+ owner_finish_request(&http, shared.run_id, None, owner_finish_events(), true)
+ .await
+ .status(),
+ StatusCode::UNAUTHORIZED
+ );
+ store
+ .writer
+ .grant_memory(alice, project, ai_memory_store::GrantLevel::Read, None)
+ .await
+ .unwrap();
+ assert_eq!(
+ owner_finish_request(
+ &http,
+ shared.run_id,
+ Some(&token),
+ owner_finish_events(),
+ true
+ )
+ .await
+ .status(),
+ StatusCode::FORBIDDEN,
+ "Read is insufficient for finish"
+ );
+ assert_eq!(owner_finish_snapshot(&store).await, before);
+ assert_eq!(
+ owner_finish_request(
+ &http,
+ shared.run_id,
+ Some("root-finish-token"),
+ owner_finish_events(),
+ true
+ )
+ .await
+ .status(),
+ StatusCode::OK,
+ "authenticated root without actor may finish NULL-owned runs"
+ );
+ store
+ .writer
+ .grant_memory(alice, project, ai_memory_store::GrantLevel::Write, None)
+ .await
+ .unwrap();
+ let owned =
+ owner_finish_run(&store, ws, project, "owned-user", Some("user:alice".into())).await;
+ let before = owner_finish_snapshot(&store).await;
+ assert_eq!(
+ owner_finish_request(
+ &http,
+ owned.run_id,
+ Some("root-finish-token"),
+ owner_finish_events(),
+ true
+ )
+ .await
+ .status(),
+ StatusCode::FORBIDDEN,
+ "root without actor must not become Any"
+ );
+ assert_eq!(owner_finish_snapshot(&store).await, before);
+ // Exercise the real DB-user tier with only its optional viewer marker removed.
+ let without_viewer = ai_memory_hooks::workstream_router(ai_memory_hooks::WorkstreamState {
+ writer: store.writer.clone(),
+ reader: store.reader.clone(),
+ sanitizer: ai_memory_core::Sanitizer::default(),
+ data_dir: tmp.path().into(),
+ trusted_proxy_identity: false,
+ })
+ .layer(axum::middleware::from_fn(
+ |mut request: Request<Body>, next: Next| async move {
+ request
+ .extensions_mut()
+ .remove::<ai_memory_core::AuthorizedViewer>();
+ next.run(request).await
+ },
+ ))
+ .layer(axum::middleware::from_fn_with_state(
+ Arc::new(
+ AuthState::new(Some("root-finish-token".into())).with_multiuser(
+ TokenPepper::new("finish-pepper"),
+ store.reader.clone(),
+ store.writer.clone(),
+ ),
+ ),
+ require_bearer,
+ ));
+ let response = owner_finish_request(
+ &without_viewer,
+ owned.run_id,
+ Some(&token),
+ owner_finish_events(),
+ true,
+ )
+ .await;
+ assert_eq!(
+ response.status(),
+ StatusCode::OK,
+ "DB-user authority must survive an absent optional viewer marker"
+ );
+ for (workspace, name) in [
+ (ws, "foreign-project"),
+ (
+ store
+ .writer
+ .get_or_create_workspace("other-rungs")
+ .await
+ .unwrap(),
+ "shared",
+ ),
+ ] {
+ let foreign = store
+ .writer
+ .get_or_create_project(workspace, name, None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .set_access_mode(foreign, ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ let run = owner_finish_run(&store, workspace, foreign, name, None).await;
+ let before = owner_finish_snapshot(&store).await;
+ assert_eq!(
+ owner_finish_request(&http, run.run_id, Some(&token), owner_finish_events(), true)
+ .await
+ .status(),
+ StatusCode::FORBIDDEN
+ );
+ assert_eq!(owner_finish_snapshot(&store).await, before);
+ assert!(
+ !tmp.path()
+ .join("raw/workstreams")
+ .join(run.workstream_id.to_string())
+ .exists()
+ );
+ store
+ .writer
+ .grant_memory(alice, foreign, ai_memory_store::GrantLevel::Write, None)
+ .await
+ .unwrap();
+ assert_eq!(
+ owner_finish_request(&http, run.run_id, Some(&token), owner_finish_events(), true)
+ .await
+ .status(),
+ StatusCode::OK
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn owner_finish_http_preserves_late_active_terminal_and_missing_phases() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("phases")
+ .await
+ .unwrap();
+ let project = store
+ .writer
+ .get_or_create_project(ws, "shared", None)
+ .await
+ .unwrap();
+ let http = owner_finish_http(
+ &store,
+ tmp.path(),
+ AuthState::new(Some("root-finish-token".into())),
+ );
+ let run = owner_finish_run(&store, ws, project, "late-active", None).await;
+ let conn = rusqlite::Connection::open(store.db_path()).unwrap();
+ conn.execute(
+ "UPDATE managed_runs SET lease_expires_at = 0 WHERE id = ?1",
+ [run.run_id.as_bytes()],
+ )
+ .unwrap();
+ assert_eq!(
+ owner_finish_request(
+ &http,
+ run.run_id,
+ Some("root-finish-token"),
+ owner_finish_events(),
+ true
+ )
+ .await
+ .status(),
+ StatusCode::OK,
+ "active is allowed even after the lease timestamp"
+ );
+ let before = owner_finish_snapshot(&store).await;
+ let response = owner_finish_request(
+ &http,
+ run.run_id,
+ Some("root-finish-token"),
+ owner_finish_events(),
+ true,
+ )
+ .await;
+ assert_eq!(response.status(), StatusCode::OK);
+ let body = axum::body::to_bytes(response.into_body(), 65536)
+ .await
+ .unwrap();
+ assert_eq!(
+ serde_json::from_slice::<serde_json::Value>(&body).unwrap()["imported_events"],
+ 0
+ );
+ assert_eq!(owner_finish_snapshot(&store).await, before);
+ let expired = owner_finish_run(&store, ws, project, "cancelled", None).await;
+ assert!(
+ store
+ .writer
+ .cancel_managed_run(expired.run_id)
+ .await
+ .unwrap()
+ );
+ let before = owner_finish_snapshot(&store).await;
+ assert_eq!(
+ owner_finish_request(
+ &http,
+ expired.run_id,
+ Some("root-finish-token"),
+ owner_finish_events(),
+ true
+ )
+ .await
+ .status(),
+ StatusCode::CONFLICT
+ );
+ assert_eq!(
+ owner_finish_request(
+ &http,
+ ai_memory_core::ManagedRunId::new(),
+ Some("root-finish-token"),
+ owner_finish_events(),
+ true
+ )
+ .await
+ .status(),
+ StatusCode::NOT_FOUND
+ );
+ assert_eq!(owner_finish_snapshot(&store).await, before);
+ assert!(
+ !tmp.path()
+ .join("raw/workstreams")
+ .join(expired.workstream_id.to_string())
+ .exists()
+ );
+ }
}
diff --git a/crates/ai-memory-store/src/error.rs b/crates/ai-memory-store/src/error.rs
index 698d51f4..3b130c24 100644
--- a/crates/ai-memory-store/src/error.rs
+++ b/crates/ai-memory-store/src/error.rs
@@ -163,6 +163,10 @@ pub enum StoreError {
#[error("os error: {0}")]
Os(String),
+ /// An authenticated finish authority failed an owner or project guard.
+ #[error("forbidden: {0}")]
+ Forbidden(&'static str),
+
/// A persisted row contains malformed data.
#[error("malformed record: {0}")]
MalformedRecord(String),
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index c4f07d39..5243e734 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -100,8 +100,8 @@ pub use web_sessions::{LiveWebSession, WebSession, hash_session_secret};
pub use workstream::{
FinishWorkstreamRun, FinishedWorkstreamRun, LinkOrAdoptManagedRunSession, ManagedRunContext,
ManagedRunSessionLink, PrepareWorkstreamRun, PreparedWorkstreamRun, RenameWorkstream,
- RenamedWorkstream, StoredManagedRunStatus, StoredWorkstreamSummary, WorkstreamSelection,
- WorkstreamSelector,
+ RenamedWorkstream, StoredManagedRunStatus, StoredWorkstreamSummary, WorkstreamFinishAuthority,
+ WorkstreamSelection, WorkstreamSelector,
};
pub use writer::{StartupContextAcceptance, WriterHandle};
@@ -5015,15 +5015,24 @@ mod tests {
assert_eq!(status(first.run_id).await, (Some("native-1".into()), true));
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- run_id: first.run_id,
- native_session_id: Some("native-1".into()),
- source_cursor: None,
- events: Vec::new(),
- complete: true,
- segment_path: None,
- exit_code: Some(0),
- })
+ .finish_workstream_run(
+ WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ FinishWorkstreamRun {
+ run_id: first.run_id,
+ native_session_id: Some("native-1".into()),
+ source_cursor: None,
+ events: Vec::new(),
+ complete: true,
+ segment_path: None,
+ exit_code: Some(0),
+ },
+ )
.await
.unwrap();
@@ -5070,13 +5079,31 @@ mod tests {
};
store
.writer
- .finish_workstream_run(finish("native-1", false))
+ .finish_workstream_run(
+ WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ finish("native-1", false),
+ )
.await
.unwrap();
assert_eq!(status(second.run_id).await, (Some("native-1".into()), true));
store
.writer
- .finish_workstream_run(finish("native-3", false))
+ .finish_workstream_run(
+ WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ finish("native-3", false),
+ )
.await
.unwrap();
assert_eq!(
@@ -5093,7 +5120,16 @@ mod tests {
assert_eq!(status(second.run_id).await, (Some("native-3".into()), true));
store
.writer
- .finish_workstream_run(finish("native-4", true))
+ .finish_workstream_run(
+ WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ finish("native-4", true),
+ )
.await
.unwrap();
assert_eq!(
@@ -5171,7 +5207,16 @@ mod tests {
assert_eq!(
store
.writer
- .finish_workstream_run(partial.clone())
+ .finish_workstream_run(
+ WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false
+ ),
+ partial.clone()
+ )
.await
.unwrap()
.imported_events,
@@ -5180,7 +5225,16 @@ mod tests {
assert_eq!(
store
.writer
- .finish_workstream_run(partial)
+ .finish_workstream_run(
+ WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false
+ ),
+ partial
+ )
.await
.unwrap()
.imported_events,
@@ -5199,15 +5253,24 @@ mod tests {
let finished = store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- run_id: run.run_id,
- native_session_id: Some("native-1".into()),
- source_cursor: Some("cursor-1".into()),
- events: vec![event],
- complete: true,
- segment_path: Some("segment-final.jsonl".into()),
- exit_code: Some(0),
- })
+ .finish_workstream_run(
+ WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ FinishWorkstreamRun {
+ run_id: run.run_id,
+ native_session_id: Some("native-1".into()),
+ source_cursor: Some("cursor-1".into()),
+ events: vec![event],
+ complete: true,
+ segment_path: Some("segment-final.jsonl".into()),
+ exit_code: Some(0),
+ },
+ )
.await
.unwrap();
assert_eq!(finished.imported_events, 0);
@@ -5260,15 +5323,24 @@ mod tests {
);
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- run_id: next.run_id,
- native_session_id: Some("native-2".into()),
- source_cursor: Some("cursor-2".into()),
- events: Vec::new(),
- complete: true,
- segment_path: Some("segment-native-2.jsonl".into()),
- exit_code: Some(0),
- })
+ .finish_workstream_run(
+ WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ FinishWorkstreamRun {
+ run_id: next.run_id,
+ native_session_id: Some("native-2".into()),
+ source_cursor: Some("cursor-2".into()),
+ events: Vec::new(),
+ complete: true,
+ segment_path: Some("segment-native-2.jsonl".into()),
+ exit_code: Some(0),
+ },
+ )
.await
.unwrap();
let retry = store
@@ -5291,15 +5363,24 @@ mod tests {
);
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- run_id: retry.run_id,
- native_session_id: Some("native-3".into()),
- source_cursor: Some("cursor-3".into()),
- events: Vec::new(),
- complete: true,
- segment_path: Some("segment-native-3.jsonl".into()),
- exit_code: Some(0),
- })
+ .finish_workstream_run(
+ WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ FinishWorkstreamRun {
+ run_id: retry.run_id,
+ native_session_id: Some("native-3".into()),
+ source_cursor: Some("cursor-3".into()),
+ events: Vec::new(),
+ complete: true,
+ segment_path: Some("segment-native-3.jsonl".into()),
+ exit_code: Some(0),
+ },
+ )
.await
.unwrap();
let undelivered = store.writer.prepare_workstream_run(prepare).await.unwrap();
@@ -5402,15 +5483,24 @@ mod tests {
assert!(blank.may_adopt_existing_session);
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- run_id: blank.run_id,
- native_session_id: None,
- source_cursor: None,
- events: Vec::new(),
- complete: true,
- segment_path: None,
- exit_code: Some(0),
- })
+ .finish_workstream_run(
+ WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ FinishWorkstreamRun {
+ run_id: blank.run_id,
+ native_session_id: None,
+ source_cursor: None,
+ events: Vec::new(),
+ complete: true,
+ segment_path: None,
+ exit_code: Some(0),
+ },
+ )
.await
.unwrap();
@@ -5432,15 +5522,24 @@ mod tests {
);
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- run_id: first.run_id,
- native_session_id: Some("claude-native".into()),
- source_cursor: None,
- events: Vec::new(),
- complete: true,
- segment_path: None,
- exit_code: Some(0),
- })
+ .finish_workstream_run(
+ WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ FinishWorkstreamRun {
+ run_id: first.run_id,
+ native_session_id: Some("claude-native".into()),
+ source_cursor: None,
+ events: Vec::new(),
+ complete: true,
+ segment_path: None,
+ exit_code: Some(0),
+ },
+ )
.await
.unwrap();
@@ -5489,15 +5588,24 @@ mod tests {
.unwrap();
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- run_id: claude.run_id,
- native_session_id: Some("claude-current".into()),
- source_cursor: Some("cursor".into()),
- events: Vec::new(),
- complete: true,
- segment_path: None,
- exit_code: Some(0),
- })
+ .finish_workstream_run(
+ WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ FinishWorkstreamRun {
+ run_id: claude.run_id,
+ native_session_id: Some("claude-current".into()),
+ source_cursor: Some("cursor".into()),
+ events: Vec::new(),
+ complete: true,
+ segment_path: None,
+ exit_code: Some(0),
+ },
+ )
.await
.unwrap();
@@ -5553,25 +5661,34 @@ mod tests {
.unwrap();
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- run_id: run.run_id,
- native_session_id: Some(format!("native-{workspace_name}")),
- source_cursor: Some("cursor".into()),
- events: vec![NewWorkstreamEvent {
- event_id: "same-native-event-id".into(),
- agent: AgentKind::Codex,
- native_session_id: format!("native-{workspace_name}"),
- source_record_id: None,
- kind: WorkstreamEventKind::Message,
- role: Some("assistant".into()),
- content: content.into(),
- occurred_at: None,
- metadata: serde_json::json!({}),
- }],
- complete: true,
- segment_path: None,
- exit_code: Some(0),
- })
+ .finish_workstream_run(
+ WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ FinishWorkstreamRun {
+ run_id: run.run_id,
+ native_session_id: Some(format!("native-{workspace_name}")),
+ source_cursor: Some("cursor".into()),
+ events: vec![NewWorkstreamEvent {
+ event_id: "same-native-event-id".into(),
+ agent: AgentKind::Codex,
+ native_session_id: format!("native-{workspace_name}"),
+ source_record_id: None,
+ kind: WorkstreamEventKind::Message,
+ role: Some("assistant".into()),
+ content: content.into(),
+ occurred_at: None,
+ metadata: serde_json::json!({}),
+ }],
+ complete: true,
+ segment_path: None,
+ exit_code: Some(0),
+ },
+ )
.await
.unwrap();
runs.push(run);
@@ -5729,7 +5846,16 @@ mod tests {
// Neither do finished runs.
store
.writer
- .finish_workstream_run(complete_finish(run.run_id, Vec::new()))
+ .finish_workstream_run(
+ WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ complete_finish(run.run_id, Vec::new()),
+ )
.await
.unwrap();
assert!(
@@ -5822,14 +5948,36 @@ mod tests {
};
let first = store
.writer
- .finish_workstream_run(finish.clone())
+ .finish_workstream_run(
+ WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ finish.clone(),
+ )
.await
.unwrap();
assert_eq!(first.imported_events, 2);
assert_eq!(first.latest_sequence, 2);
// Re-finishing a completed run imports nothing, even with new input.
- let second = store.writer.finish_workstream_run(finish).await.unwrap();
+ let second = store
+ .writer
+ .finish_workstream_run(
+ WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ finish,
+ )
+ .await
+ .unwrap();
assert_eq!(second.imported_events, 0);
assert_eq!(second.latest_sequence, 2);
assert_eq!(
@@ -5868,7 +6016,16 @@ mod tests {
let cancelled = store
.writer
- .finish_workstream_run(complete_finish(run.run_id, Vec::new()))
+ .finish_workstream_run(
+ WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ complete_finish(run.run_id, Vec::new()),
+ )
.await
.unwrap_err();
assert!(
@@ -5878,7 +6035,16 @@ mod tests {
let unknown = store
.writer
- .finish_workstream_run(complete_finish(ManagedRunId::new(), Vec::new()))
+ .finish_workstream_run(
+ WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ complete_finish(ManagedRunId::new(), Vec::new()),
+ )
.await
.unwrap_err();
assert!(matches!(unknown, StoreError::NotFound(_)));
@@ -5905,18 +6071,27 @@ mod tests {
// A valid event followed by another agent's event must import nothing.
let wrong_agent = store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- run_id: run.run_id,
- native_session_id: Some("native-1".into()),
- source_cursor: None,
- events: vec![
- managed_event("ev-1", AgentKind::Codex, "native-1", "valid"),
- managed_event("ev-2", AgentKind::ClaudeCode, "native-1", "foreign agent"),
- ],
- complete: false,
- segment_path: None,
- exit_code: None,
- })
+ .finish_workstream_run(
+ WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ FinishWorkstreamRun {
+ run_id: run.run_id,
+ native_session_id: Some("native-1".into()),
+ source_cursor: None,
+ events: vec![
+ managed_event("ev-1", AgentKind::Codex, "native-1", "valid"),
+ managed_event("ev-2", AgentKind::ClaudeCode, "native-1", "foreign agent"),
+ ],
+ complete: false,
+ segment_path: None,
+ exit_code: None,
+ },
+ )
.await
.unwrap_err();
assert!(
@@ -5946,20 +6121,29 @@ mod tests {
// Events from a different native session are rejected the same way.
let wrong_session = store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- run_id: run.run_id,
- native_session_id: Some("native-1".into()),
- source_cursor: None,
- events: vec![managed_event(
- "ev-3",
- AgentKind::Codex,
- "native-2",
- "foreign session",
- )],
- complete: false,
- segment_path: None,
- exit_code: None,
- })
+ .finish_workstream_run(
+ WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ FinishWorkstreamRun {
+ run_id: run.run_id,
+ native_session_id: Some("native-1".into()),
+ source_cursor: None,
+ events: vec![managed_event(
+ "ev-3",
+ AgentKind::Codex,
+ "native-2",
+ "foreign session",
+ )],
+ complete: false,
+ segment_path: None,
+ exit_code: None,
+ },
+ )
.await
.unwrap_err();
assert!(
@@ -5970,15 +6154,24 @@ mod tests {
// The run is still usable after the rejected batches.
let finished = store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- run_id: run.run_id,
- native_session_id: Some("native-1".into()),
- source_cursor: None,
- events: vec![managed_event("ev-1", AgentKind::Codex, "native-1", "valid")],
- complete: true,
- segment_path: None,
- exit_code: Some(0),
- })
+ .finish_workstream_run(
+ WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ FinishWorkstreamRun {
+ run_id: run.run_id,
+ native_session_id: Some("native-1".into()),
+ source_cursor: None,
+ events: vec![managed_event("ev-1", AgentKind::Codex, "native-1", "valid")],
+ complete: true,
+ segment_path: None,
+ exit_code: Some(0),
+ },
+ )
.await
.unwrap();
assert_eq!(finished.imported_events, 1);
@@ -6030,7 +6223,16 @@ mod tests {
store
.writer
- .finish_workstream_run(complete_finish(run.run_id, Vec::new()))
+ .finish_workstream_run(
+ WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ complete_finish(run.run_id, Vec::new()),
+ )
.await
.unwrap();
assert!(
@@ -6235,14 +6437,23 @@ mod tests {
// undelivered context window spanning the whole ledger.
store
.writer
- .finish_workstream_run(complete_finish(
- first.run_id,
- vec![
- managed_event("ev-1", AgentKind::Codex, "native-x", "one"),
- managed_event("ev-2", AgentKind::Codex, "native-x", "two"),
- managed_event("ev-3", AgentKind::Codex, "native-x", "three"),
- ],
- ))
+ .finish_workstream_run(
+ WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ complete_finish(
+ first.run_id,
+ vec![
+ managed_event("ev-1", AgentKind::Codex, "native-x", "one"),
+ managed_event("ev-2", AgentKind::Codex, "native-x", "two"),
+ managed_event("ev-3", AgentKind::Codex, "native-x", "three"),
+ ],
+ ),
+ )
.await
.unwrap();
@@ -6337,16 +6548,25 @@ mod tests {
.unwrap();
store
.writer
- .finish_workstream_run(complete_finish(
- run.run_id,
- vec![
- managed_event("ev-1", AgentKind::Codex, "native-x", "alpha one"),
- managed_event("ev-2", AgentKind::Codex, "native-x", "alpha two"),
- managed_event("ev-3", AgentKind::Codex, "native-x", "alpha zebra three"),
- managed_event("ev-4", AgentKind::Codex, "native-x", "alpha four"),
- managed_event("ev-5", AgentKind::Codex, "native-x", "alpha five"),
- ],
- ))
+ .finish_workstream_run(
+ WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ complete_finish(
+ run.run_id,
+ vec![
+ managed_event("ev-1", AgentKind::Codex, "native-x", "alpha one"),
+ managed_event("ev-2", AgentKind::Codex, "native-x", "alpha two"),
+ managed_event("ev-3", AgentKind::Codex, "native-x", "alpha zebra three"),
+ managed_event("ev-4", AgentKind::Codex, "native-x", "alpha four"),
+ managed_event("ev-5", AgentKind::Codex, "native-x", "alpha five"),
+ ],
+ ),
+ )
.await
.unwrap();
@@ -6551,15 +6771,24 @@ mod tests {
.unwrap();
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- run_id: current.run_id,
- native_session_id: Some("codex-native".into()),
- source_cursor: None,
- events: Vec::new(),
- complete: true,
- segment_path: None,
- exit_code: Some(0),
- })
+ .finish_workstream_run(
+ WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ FinishWorkstreamRun {
+ run_id: current.run_id,
+ native_session_id: Some("codex-native".into()),
+ source_cursor: None,
+ events: Vec::new(),
+ complete: true,
+ segment_path: None,
+ exit_code: Some(0),
+ },
+ )
.await
.unwrap();
let claude = store
@@ -6573,30 +6802,48 @@ mod tests {
.unwrap();
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- run_id: claude.run_id,
- native_session_id: Some("claude-native".into()),
- source_cursor: None,
- events: Vec::new(),
- complete: true,
- segment_path: None,
- exit_code: Some(0),
- })
+ .finish_workstream_run(
+ WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ FinishWorkstreamRun {
+ run_id: claude.run_id,
+ native_session_id: Some("claude-native".into()),
+ source_cursor: None,
+ events: Vec::new(),
+ complete: true,
+ segment_path: None,
+ exit_code: Some(0),
+ },
+ )
.await
.unwrap();
// A non-current workstream may finish later and therefore be more
// recently active; the selected workstream must still lead the list.
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- run_id: older.run_id,
- native_session_id: Some("open-code-native".into()),
- source_cursor: None,
- events: Vec::new(),
- complete: true,
- segment_path: None,
- exit_code: Some(0),
- })
+ .finish_workstream_run(
+ WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::Anonymous,
+ None,
+ None,
+ &ai_memory_core::ActorContext::anonymous(),
+ false,
+ ),
+ FinishWorkstreamRun {
+ run_id: older.run_id,
+ native_session_id: Some("open-code-native".into()),
+ source_cursor: None,
+ events: Vec::new(),
+ complete: true,
+ segment_path: None,
+ exit_code: Some(0),
+ },
+ )
.await
.unwrap();
diff --git a/crates/ai-memory-store/src/project_authz.rs b/crates/ai-memory-store/src/project_authz.rs
index 3255621f..23f9ea02 100644
--- a/crates/ai-memory-store/src/project_authz.rs
+++ b/crates/ai-memory-store/src/project_authz.rs
@@ -325,6 +325,59 @@ pub fn resolve_project_authz(
})
}
+/// Strict snapshot resolution used only by managed-run finish imports.
+/// The legacy resolver deliberately retains its degrade-to-open behavior.
+pub(crate) fn resolve_finish_project_authz(
+ conn: &Connection,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ principal: &ProjectPrincipal,
+ authenticated_operators: bool,
+) -> StoreResult<ProjectAuthz> {
+ use crate::StoreError;
+ let (mode, creator) = conn.query_row(
+ "SELECT p.access_mode, p.created_by FROM projects p \
+ JOIN workspaces w ON w.id = p.workspace_id \
+ WHERE p.workspace_id = ?1 AND p.id = ?2",
+ params![workspace_id.as_bytes(), project_id.as_bytes()],
+ |row| Ok((row.get::<_, String>(0)?, row.get::<_, Option<Vec<u8>>>(1)?)),
+ )?;
+ let access_mode = match mode.as_str() {
+ "open" => AccessMode::Open,
+ "restricted" => AccessMode::Restricted,
+ _ => {
+ return Err(StoreError::MalformedRecord(
+ "unknown project access mode".into(),
+ ));
+ }
+ };
+ let creator = creator.map(|raw| UserId::from_slice(&raw)).transpose()?;
+ let users_exist = crate::users::users_exist(conn)?;
+ if let Some(user_id) = principal.user_id {
+ let exists: bool = conn.query_row(
+ "SELECT EXISTS(SELECT 1 FROM users WHERE id = ?1)",
+ params![user_id.as_bytes()],
+ |row| row.get(0),
+ )?;
+ if !exists {
+ return Err(StoreError::Forbidden("authenticated user no longer exists"));
+ }
+ }
+ let grant = match principal.user_id {
+ Some(user_id) if access_mode == AccessMode::Restricted => {
+ read_grant(conn, workspace_id, project_id, user_id)?
+ }
+ _ => None,
+ };
+ Ok(ProjectAuthz {
+ distinguishes_operators: authenticated_operators || users_exist,
+ access_mode,
+ is_root: principal.is_root,
+ is_creator: creator.is_some() && creator == principal.user_id,
+ grant,
+ })
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index a2ce885f..6d0af288 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -1896,6 +1896,23 @@ impl ReaderPool {
.await
}
+ /// Check finish ownership and current Write access in one read snapshot.
+ ///
+ /// # Errors
+ /// Refuses a foreign owner, insufficient access, absent run or invalid scope;
+ /// SQL failures propagate without degrading authorization to open.
+ pub async fn authorize_workstream_finish(
+ &self,
+ run_id: ManagedRunId,
+ authority: crate::WorkstreamFinishAuthority,
+ ) -> StoreResult<()> {
+ self.with_conn(move |conn| {
+ let tx = conn.unchecked_transaction()?;
+ crate::workstream::authorize_finish(&tx, run_id, &authority)
+ })
+ .await
+ }
+
/// Return the current state of one `ai-memory run` invocation.
pub async fn managed_run_status(
&self,
diff --git a/crates/ai-memory-store/src/workstream.rs b/crates/ai-memory-store/src/workstream.rs
index f85a2c34..6ac46dcc 100644
--- a/crates/ai-memory-store/src/workstream.rs
+++ b/crates/ai-memory-store/src/workstream.rs
@@ -30,6 +30,112 @@ pub enum WorkstreamSelection {
New(String),
}
+/// Authenticated authority shared by finish preflight and the writer transaction.
+///
+/// Construct only from middleware extensions, never transcript metadata. Owner
+/// filters are derived here so this boundary cannot request `OwnerFilter::Any`.
+#[derive(Debug, Clone)]
+pub struct WorkstreamFinishAuthority {
+ principal: crate::ProjectPrincipal,
+ owner: ai_memory_core::OwnerFilter,
+ distinguishes_operators: bool,
+ project_policy: FinishProjectPolicy,
+}
+
+#[derive(Debug, Clone, Copy)]
+enum FinishProjectPolicy {
+ Grants,
+ TrustedProxyLegacy,
+}
+
+impl WorkstreamFinishAuthority {
+ /// Reduce the actual HTTP auth extensions to one immutable finish authority.
+ /// A DB user's attribution id remains authoritative without a viewer marker.
+ #[must_use]
+ pub fn from_auth(
+ level: ai_memory_core::AuthLevel,
+ viewer: Option<ai_memory_core::AuthorizedViewer>,
+ user_id: Option<ai_memory_core::UserId>,
+ actor: &ai_memory_core::ActorContext,
+ trusted_proxy_identity: bool,
+ ) -> Self {
+ use ai_memory_core::AuthLevel;
+ let user = viewer
+ .map(ai_memory_core::AuthorizedViewer::user)
+ .or(user_id);
+ let principal = match level {
+ AuthLevel::Root => crate::ProjectPrincipal::root(),
+ AuthLevel::User => user.map_or_else(
+ crate::ProjectPrincipal::anonymous,
+ crate::ProjectPrincipal::user,
+ ),
+ AuthLevel::Anonymous => crate::ProjectPrincipal::anonymous(),
+ };
+ let owner = if level == AuthLevel::Anonymous {
+ ai_memory_core::OwnerFilter::Unattributed
+ } else {
+ ai_memory_core::OwnerFilter::for_actor_context(actor)
+ };
+ // The real proxy middleware has an identity and User capability, but
+ // no DB principal. Preserve its viewer-less project policy only when
+ // this server actually enables trusted proxy authentication.
+ let project_policy = match (level, user, actor.identity_key(), trusted_proxy_identity) {
+ (AuthLevel::User, None, Some(_), true) => FinishProjectPolicy::TrustedProxyLegacy,
+ _ => FinishProjectPolicy::Grants,
+ };
+ Self {
+ principal,
+ owner,
+ distinguishes_operators: trusted_proxy_identity || level == AuthLevel::User,
+ project_policy,
+ }
+ }
+}
+
+/// Resolve only the real run scope and owner, without creating a scope or
+/// changing the active-project pointer. Both callers supply a SQL snapshot.
+pub(crate) fn authorize_finish(
+ conn: &Connection,
+ run_id: ManagedRunId,
+ authority: &WorkstreamFinishAuthority,
+) -> StoreResult<()> {
+ let (owner, workspace, project) = conn
+ .query_row(
+ "SELECT r.owner_user, w.workspace_id, w.project_id FROM managed_runs r \
+ LEFT JOIN workstreams w ON w.id = r.workstream_id WHERE r.id = ?1",
+ params![run_id.as_bytes()],
+ |row| {
+ Ok((
+ row.get::<_, Option<String>>(0)?,
+ row.get::<_, Vec<u8>>(1)?,
+ row.get::<_, Vec<u8>>(2)?,
+ ))
+ },
+ )
+ .optional()?
+ .ok_or_else(|| StoreError::NotFound("managed run not found".into()))?;
+ if !authority.owner.admits(owner.as_deref()) {
+ return Err(StoreError::Forbidden(
+ "managed run belongs to another operator",
+ ));
+ }
+ let workspace = WorkspaceId::from_slice(&workspace)?;
+ let project = ProjectId::from_slice(&project)?;
+ let project_authz = crate::project_authz::resolve_finish_project_authz(
+ conn,
+ workspace,
+ project,
+ &authority.principal,
+ authority.distinguishes_operators,
+ )?;
+ match authority.project_policy {
+ FinishProjectPolicy::TrustedProxyLegacy => Ok(()),
+ FinishProjectPolicy::Grants => project_authz
+ .authorize(crate::ProjectAccess::Write)
+ .map_err(|failure| StoreError::Forbidden(failure.message())),
+ }
+}
+
/// Store-level input for opening a managed run.
#[derive(Debug, Clone)]
pub struct PrepareWorkstreamRun {
@@ -826,10 +932,12 @@ fn accept_context_in_transaction(
/// Index one immutable source segment and close the run atomically.
pub(crate) fn finish_run(
conn: &mut Connection,
+ authority: &WorkstreamFinishAuthority,
input: &FinishWorkstreamRun,
) -> StoreResult<FinishedWorkstreamRun> {
let now = Timestamp::now().as_microsecond();
let tx = conn.transaction()?;
+ authorize_finish(&tx, input.run_id, authority)?;
let run: Option<FinishRunRow> = tx
.query_row(
"SELECT workstream_id, agent_kind, native_session_id, state, \
diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rs
index 4462d925..0df03ad7 100644
--- a/crates/ai-memory-store/src/writer.rs
+++ b/crates/ai-memory-store/src/writer.rs
@@ -748,6 +748,7 @@ pub(crate) enum WriteCmd {
reply: oneshot::Sender<StoreResult<StartupContextAcceptance>>,
},
FinishWorkstreamRun {
+ authority: crate::WorkstreamFinishAuthority,
input: FinishWorkstreamRun,
reply: oneshot::Sender<StoreResult<FinishedWorkstreamRun>>,
},
@@ -3122,11 +3123,16 @@ impl WriterHandle {
/// Index an immutable transcript segment and release the run lease.
pub async fn finish_workstream_run(
&self,
+ authority: crate::WorkstreamFinishAuthority,
input: FinishWorkstreamRun,
) -> StoreResult<FinishedWorkstreamRun> {
let (tx, rx) = oneshot::channel();
- self.send(WriteCmd::FinishWorkstreamRun { input, reply: tx })
- .await?;
+ self.send(WriteCmd::FinishWorkstreamRun {
+ authority,
+ input,
+ reply: tx,
+ })
+ .await?;
rx.await.map_err(|_| StoreError::WriterClosed)?
}
@@ -4372,8 +4378,12 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
})();
send_or_warn(reply, result, "accept_startup_context");
}
- WriteCmd::FinishWorkstreamRun { input, reply } => {
- let result = crate::workstream::finish_run(&mut conn, &input);
+ WriteCmd::FinishWorkstreamRun {
+ authority,
+ input,
+ reply,
+ } => {
+ let result = crate::workstream::finish_run(&mut conn, &authority, &input);
send_or_warn(reply, result, "finish_workstream_run");
}
WriteCmd::RenameWorkstream { input, reply } => {
diff --git a/crates/ai-memory-store/tests/suite/multi_session.rs b/crates/ai-memory-store/tests/suite/multi_session.rs
index 204f5bd0..8901a6d4 100644
--- a/crates/ai-memory-store/tests/suite/multi_session.rs
+++ b/crates/ai-memory-store/tests/suite/multi_session.rs
@@ -1114,3 +1114,946 @@ async fn stale_codex_run_recovery_fails_closed_on_ambiguity_and_active_mismatch(
);
}
}
+
+fn finish_authority(
+ level: ai_memory_core::AuthLevel,
+ user: Option<ai_memory_core::UserId>,
+ name: Option<&str>,
+) -> ai_memory_store::WorkstreamFinishAuthority {
+ ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ level,
+ user.map(ai_memory_core::AuthorizedViewer),
+ user,
+ &ActorContext {
+ user: name.map(str::to_owned),
+ ..ActorContext::anonymous()
+ },
+ false,
+ )
+}
+
+fn finish_input(run_id: ai_memory_core::ManagedRunId) -> ai_memory_store::FinishWorkstreamRun {
+ ai_memory_store::FinishWorkstreamRun {
+ run_id,
+ native_session_id: Some("native-finish".into()),
+ source_cursor: Some("cursor-finish".into()),
+ events: vec![ai_memory_core::NewWorkstreamEvent {
+ event_id: "finish-event".into(),
+ agent: AgentKind::Codex,
+ native_session_id: "native-finish".into(),
+ source_record_id: Some("record-finish".into()),
+ kind: ai_memory_core::WorkstreamEventKind::Message,
+ role: Some("assistant".into()),
+ content: "finish snapshot evidence".into(),
+ occurred_at: None,
+ metadata: serde_json::json!({"owner_user": "user:alice", "is_root": true}),
+ }],
+ complete: true,
+ segment_path: Some("raw/fixture-finish.jsonl".into()),
+ exit_code: Some(0),
+ }
+}
+
+async fn finish_snapshot(store: &Store) -> Vec<Vec<String>> {
+ store
+ .reader
+ .with_conn(|conn| {
+ let mut result = Vec::new();
+ for table in [
+ "workspaces",
+ "projects",
+ "managed_runs",
+ "workstreams",
+ "workstream_events",
+ "workstream_native_sessions",
+ "workstream_events_fts_data",
+ "workstream_events_fts_idx",
+ "workstream_events_fts_docsize",
+ "workstream_events_fts_config",
+ "sessions",
+ ] {
+ let mut stmt = conn.prepare(&format!("SELECT * FROM {table} ORDER BY 1, 2"))?;
+ let columns = stmt.column_count();
+ let rows = stmt.query_map([], |row| {
+ (0..columns)
+ .map(|i| row.get_ref(i).map(|v| format!("{v:?}")))
+ .collect()
+ })?;
+ result.push(vec![table.to_owned()]);
+ result.extend(rows.collect::<Result<Vec<Vec<String>>, _>>()?);
+ }
+ Ok(result)
+ })
+ .await
+ .unwrap()
+}
+
+struct FinishFixture {
+ _temp: tempfile::TempDir,
+ store: Store,
+ ws: WorkspaceId,
+ project: ProjectId,
+ alice: ai_memory_core::UserId,
+ bob: ai_memory_core::UserId,
+}
+
+impl FinishFixture {
+ async fn new() -> Self {
+ let temp = tempfile::tempdir().unwrap();
+ let store = Store::open(temp.path()).unwrap();
+ let (ws, project) = scope(&store).await;
+ let mut users = Vec::new();
+ for name in ["alice", "bob"] {
+ let id = store
+ .writer
+ .create_human_user(
+ NewUser {
+ username: name.into(),
+ name: None,
+ email: None,
+ },
+ UserRole::User,
+ None,
+ false,
+ )
+ .await
+ .unwrap();
+ store
+ .writer
+ .grant_memory(id, project, ai_memory_store::GrantLevel::Write, None)
+ .await
+ .unwrap();
+ users.push(id);
+ }
+ store
+ .writer
+ .set_access_mode(project, ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ Self {
+ _temp: temp,
+ store,
+ ws,
+ project,
+ alice: users[0],
+ bob: users[1],
+ }
+ }
+
+ fn alice(&self) -> ai_memory_store::WorkstreamFinishAuthority {
+ finish_authority(
+ ai_memory_core::AuthLevel::User,
+ Some(self.alice),
+ Some("alice"),
+ )
+ }
+
+ async fn run(
+ &self,
+ name: &str,
+ owner: Option<String>,
+ ) -> ai_memory_store::PreparedWorkstreamRun {
+ self.store
+ .writer
+ .prepare_workstream_run_owned(
+ PrepareWorkstreamRun {
+ workspace_id: self.ws,
+ project_id: self.project,
+ repo_fingerprint: "repo-finish".into(),
+ worktree_fingerprint: "tree-finish".into(),
+ cwd: "/repo".into(),
+ agent: AgentKind::Codex,
+ automatic_harness: false,
+ available_agents: Vec::new(),
+ selection: WorkstreamSelection::New(name.into()),
+ lease_owner: "display-only".into(),
+ },
+ owner,
+ )
+ .await
+ .unwrap()
+ }
+
+ async fn refused_unchanged(
+ &self,
+ run_id: ai_memory_core::ManagedRunId,
+ authority: ai_memory_store::WorkstreamFinishAuthority,
+ ) {
+ let before = finish_snapshot(&self.store).await;
+ assert!(
+ self.store
+ .reader
+ .authorize_workstream_finish(run_id, authority.clone())
+ .await
+ .is_err(),
+ "preflight must refuse"
+ );
+ assert!(
+ self.store
+ .writer
+ .finish_workstream_run(authority, finish_input(run_id))
+ .await
+ .is_err(),
+ "writer must refuse"
+ );
+ assert_eq!(
+ finish_snapshot(&self.store).await,
+ before,
+ "refusal must preserve every run/event/index/link/cursor row"
+ );
+ }
+}
+
+#[tokio::test]
+async fn owner_finish_store_refuses_another_writer_including_finished_retry() {
+ let f = FinishFixture::new().await;
+ let run = f.run("owned", Some(operator("alice"))).await;
+ let bob = finish_authority(ai_memory_core::AuthLevel::User, Some(f.bob), Some("bob"));
+ for complete in [false, true] {
+ let before = finish_snapshot(&f.store).await;
+ assert!(matches!(
+ f.store
+ .reader
+ .authorize_workstream_finish(run.run_id, bob.clone())
+ .await,
+ Err(StoreError::Forbidden(_))
+ ));
+ let mut input = finish_input(run.run_id);
+ input.complete = complete;
+ assert!(
+ matches!(
+ f.store
+ .writer
+ .finish_workstream_run(bob.clone(), input)
+ .await,
+ Err(StoreError::Forbidden(_))
+ ),
+ "another writer must not finish or import a batch"
+ );
+ assert_eq!(finish_snapshot(&f.store).await, before);
+ }
+ // Root has project authority but no owner identity; it never means Any.
+ f.refused_unchanged(
+ run.run_id,
+ finish_authority(ai_memory_core::AuthLevel::Root, None, None),
+ )
+ .await;
+ f.store
+ .reader
+ .authorize_workstream_finish(run.run_id, f.alice())
+ .await
+ .unwrap();
+ let result = f
+ .store
+ .writer
+ .finish_workstream_run(f.alice(), finish_input(run.run_id))
+ .await
+ .unwrap();
+ assert_eq!(result.imported_events, 1);
+ let before = finish_snapshot(&f.store).await;
+ assert!(
+ matches!(
+ f.store
+ .writer
+ .finish_workstream_run(bob, finish_input(run.run_id))
+ .await,
+ Err(StoreError::Forbidden(_))
+ ),
+ "finished retries must check the owner before the dedup return"
+ );
+ let retry = f
+ .store
+ .writer
+ .finish_workstream_run(f.alice(), finish_input(run.run_id))
+ .await
+ .unwrap();
+ assert_eq!(retry.imported_events, 0);
+ assert_eq!(retry.latest_sequence, result.latest_sequence);
+ assert_eq!(finish_snapshot(&f.store).await, before);
+ for (name, auth) in [
+ (
+ "root-shared",
+ finish_authority(ai_memory_core::AuthLevel::Root, None, None),
+ ),
+ ("user-shared", f.alice()),
+ ] {
+ let shared = f.run(name, None).await;
+ f.store
+ .reader
+ .authorize_workstream_finish(shared.run_id, auth.clone())
+ .await
+ .unwrap();
+ assert_eq!(
+ f.store
+ .writer
+ .finish_workstream_run(auth, finish_input(shared.run_id))
+ .await
+ .unwrap()
+ .imported_events,
+ 1
+ );
+ }
+}
+
+#[tokio::test]
+async fn owner_finish_store_rechecks_write_after_preflight() {
+ let f = FinishFixture::new().await;
+ let run = f.run("revoke", Some(operator("alice"))).await;
+ let auth = f.alice();
+ f.store
+ .reader
+ .authorize_workstream_finish(run.run_id, auth.clone())
+ .await
+ .unwrap();
+ f.store
+ .writer
+ .revoke_memory(f.alice, f.project, None)
+ .await
+ .unwrap();
+ let before = finish_snapshot(&f.store).await;
+ assert!(
+ matches!(
+ f.store
+ .writer
+ .finish_workstream_run(auth.clone(), finish_input(run.run_id))
+ .await,
+ Err(StoreError::Forbidden(_))
+ ),
+ "the transaction must read the current Write grant"
+ );
+ assert_eq!(finish_snapshot(&f.store).await, before);
+ f.store
+ .writer
+ .grant_memory(f.alice, f.project, ai_memory_store::GrantLevel::Read, None)
+ .await
+ .unwrap();
+ f.refused_unchanged(run.run_id, auth.clone()).await;
+ f.store
+ .writer
+ .grant_memory(f.alice, f.project, ai_memory_store::GrantLevel::Write, None)
+ .await
+ .unwrap();
+ f.store
+ .reader
+ .authorize_workstream_finish(run.run_id, auth.clone())
+ .await
+ .unwrap();
+ f.store
+ .writer
+ .set_user_disabled(f.alice, true)
+ .await
+ .unwrap();
+ f.store
+ .reader
+ .authorize_workstream_finish(run.run_id, auth.clone())
+ .await
+ .unwrap();
+ // Attribution UserId is real middleware data even if a viewer marker is absent.
+ let fallback = ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::User,
+ None,
+ Some(f.alice),
+ &ActorContext {
+ user: Some("alice".into()),
+ ..ActorContext::anonymous()
+ },
+ false,
+ );
+ assert!(
+ f.store
+ .reader
+ .authorize_workstream_finish(run.run_id, fallback.clone())
+ .await
+ .is_ok(),
+ "the real DB-user attribution id must retain its Write grant without a viewer marker"
+ );
+ assert_eq!(
+ f.store
+ .writer
+ .finish_workstream_run(fallback, finish_input(run.run_id))
+ .await
+ .unwrap()
+ .imported_events,
+ 1
+ );
+}
+
+#[tokio::test]
+async fn owner_finish_store_refuses_a_deleted_user_after_preflight() {
+ let f = FinishFixture::new().await;
+ let run = f.run("deleted-user", Some(operator("alice"))).await;
+ let auth = f.alice();
+ f.store
+ .writer
+ .set_access_mode(f.project, ai_memory_store::AccessMode::Open)
+ .await
+ .unwrap();
+ f.store
+ .reader
+ .authorize_workstream_finish(run.run_id, auth.clone())
+ .await
+ .unwrap();
+ let conn = rusqlite::Connection::open(f.store.db_path()).unwrap();
+ conn.execute_batch("PRAGMA foreign_keys=ON;").unwrap();
+ assert_eq!(
+ conn.execute(
+ "DELETE FROM users WHERE id = ?1",
+ rusqlite::params![f.alice.as_bytes()]
+ )
+ .unwrap(),
+ 1
+ );
+ let before = finish_snapshot(&f.store).await;
+ assert!(
+ matches!(
+ f.store
+ .reader
+ .authorize_workstream_finish(run.run_id, auth.clone())
+ .await,
+ Err(StoreError::Forbidden(_))
+ ),
+ "a deleted DB user must be refused even in an open project"
+ );
+ assert!(
+ matches!(
+ f.store
+ .writer
+ .finish_workstream_run(auth, finish_input(run.run_id))
+ .await,
+ Err(StoreError::Forbidden(_))
+ ),
+ "the writer must refuse a user deleted after preflight"
+ );
+ assert_eq!(finish_snapshot(&f.store).await, before);
+ let shared = f.run("existing-control", None).await;
+ let bob = finish_authority(ai_memory_core::AuthLevel::User, Some(f.bob), Some("bob"));
+ assert_eq!(
+ f.store
+ .writer
+ .finish_workstream_run(bob, finish_input(shared.run_id))
+ .await
+ .unwrap()
+ .imported_events,
+ 1
+ );
+}
+
+#[tokio::test]
+async fn owner_finish_store_proxy_policy_requires_server_and_authenticated_identity() {
+ let f = FinishFixture::new().await;
+ let run = f.run("proxy-policy", None).await;
+ let actor = ActorContext {
+ issuer: Some("https://idp.example".into()),
+ sub: Some("alice".into()),
+ ..ActorContext::anonymous()
+ };
+ for (level, identity, configured, message) in [
+ (
+ ai_memory_core::AuthLevel::Anonymous,
+ actor.clone(),
+ true,
+ "proxy compatibility requires authenticated User capability",
+ ),
+ (
+ ai_memory_core::AuthLevel::User,
+ ActorContext::anonymous(),
+ true,
+ "proxy compatibility requires a canonical authenticated identity",
+ ),
+ (
+ ai_memory_core::AuthLevel::User,
+ actor.clone(),
+ false,
+ "proxy compatibility requires trusted server configuration",
+ ),
+ ] {
+ let auth = ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ level, None, None, &identity, configured,
+ );
+ let before = finish_snapshot(&f.store).await;
+ assert!(
+ matches!(
+ f.store
+ .reader
+ .authorize_workstream_finish(run.run_id, auth.clone())
+ .await,
+ Err(StoreError::Forbidden(_))
+ ),
+ "{message}"
+ );
+ assert!(
+ matches!(
+ f.store
+ .writer
+ .finish_workstream_run(auth, finish_input(run.run_id))
+ .await,
+ Err(StoreError::Forbidden(_))
+ ),
+ "{message}"
+ );
+ assert_eq!(finish_snapshot(&f.store).await, before);
+ }
+ let proxy = ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::User,
+ None,
+ None,
+ &actor,
+ true,
+ );
+ // The legacy project exception still requires the real paired SQL scope.
+ let other_ws = f
+ .store
+ .writer
+ .get_or_create_workspace("proxy-other")
+ .await
+ .unwrap();
+ let conn = rusqlite::Connection::open(f.store.db_path()).unwrap();
+ conn.execute(
+ "UPDATE workstreams SET workspace_id = ?1 WHERE id = ?2",
+ rusqlite::params![other_ws.as_bytes(), run.workstream_id.as_bytes()],
+ )
+ .unwrap();
+ f.refused_unchanged(run.run_id, proxy.clone()).await;
+ conn.execute(
+ "UPDATE workstreams SET workspace_id = ?1 WHERE id = ?2",
+ rusqlite::params![f.ws.as_bytes(), run.workstream_id.as_bytes()],
+ )
+ .unwrap();
+ assert_eq!(
+ f.store
+ .writer
+ .finish_workstream_run(proxy, finish_input(run.run_id))
+ .await
+ .unwrap()
+ .imported_events,
+ 1
+ );
+}
+
+#[tokio::test]
+async fn owner_finish_store_raw_ids_use_the_actual_project_and_workspace() {
+ let f = FinishFixture::new().await;
+ for (ws_name, project_name) in [
+ ("acme", "foreign-project"),
+ ("foreign-workspace", "shared-app"),
+ ] {
+ let ws = f
+ .store
+ .writer
+ .get_or_create_workspace(ws_name)
+ .await
+ .unwrap();
+ let project = f
+ .store
+ .writer
+ .get_or_create_project(ws, project_name, None)
+ .await
+ .unwrap();
+ f.store
+ .writer
+ .set_access_mode(project, ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ let run = f
+ .store
+ .writer
+ .prepare_workstream_run_owned(
+ PrepareWorkstreamRun {
+ workspace_id: ws,
+ project_id: project,
+ repo_fingerprint: "foreign".into(),
+ worktree_fingerprint: "foreign".into(),
+ cwd: "/repo".into(),
+ agent: AgentKind::Codex,
+ automatic_harness: false,
+ available_agents: Vec::new(),
+ selection: WorkstreamSelection::Current,
+ lease_owner: "foreign".into(),
+ },
+ Some(operator("alice")),
+ )
+ .await
+ .unwrap();
+ f.refused_unchanged(run.run_id, f.alice()).await;
+ f.store
+ .writer
+ .grant_memory(f.alice, project, ai_memory_store::GrantLevel::Write, None)
+ .await
+ .unwrap();
+ assert_eq!(
+ f.store
+ .writer
+ .finish_workstream_run(f.alice(), finish_input(run.run_id))
+ .await
+ .unwrap()
+ .imported_events,
+ 1
+ );
+ }
+ // A well-shaped but nonexistent user id cannot inherit a creator or grant.
+ let run = f.run("missing-user", None).await;
+ f.refused_unchanged(
+ run.run_id,
+ finish_authority(
+ ai_memory_core::AuthLevel::User,
+ Some(ai_memory_core::UserId::new()),
+ Some("alice"),
+ ),
+ )
+ .await;
+}
+
+#[tokio::test]
+async fn owner_finish_store_topology_reload_and_phase_controls() {
+ let temp = tempfile::tempdir().unwrap();
+ let store = Store::open(temp.path()).unwrap();
+ let (ws, project) = scope(&store).await;
+ store
+ .writer
+ .set_access_mode(project, ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ let run = store
+ .writer
+ .prepare_workstream_run(PrepareWorkstreamRun {
+ workspace_id: ws,
+ project_id: project,
+ repo_fingerprint: "reload".into(),
+ worktree_fingerprint: "reload".into(),
+ cwd: "/repo".into(),
+ agent: AgentKind::Codex,
+ automatic_harness: false,
+ available_agents: Vec::new(),
+ selection: WorkstreamSelection::Current,
+ lease_owner: "reload".into(),
+ })
+ .await
+ .unwrap();
+ let anonymous = finish_authority(ai_memory_core::AuthLevel::Anonymous, None, None);
+ store
+ .reader
+ .authorize_workstream_finish(run.run_id, anonymous.clone())
+ .await
+ .unwrap();
+ store
+ .writer
+ .create_human_user(
+ NewUser {
+ username: "new-user".into(),
+ name: None,
+ email: None,
+ },
+ UserRole::User,
+ None,
+ false,
+ )
+ .await
+ .unwrap();
+ let before = finish_snapshot(&store).await;
+ assert!(
+ matches!(
+ store
+ .reader
+ .authorize_workstream_finish(run.run_id, anonymous.clone())
+ .await,
+ Err(StoreError::Forbidden(_))
+ ),
+ "topology must be reloaded without restarting the reader"
+ );
+ assert!(
+ matches!(
+ store
+ .writer
+ .finish_workstream_run(anonymous.clone(), finish_input(run.run_id))
+ .await,
+ Err(StoreError::Forbidden(_))
+ ),
+ "topology must be reloaded in the transaction"
+ );
+ assert_eq!(finish_snapshot(&store).await, before);
+ let root = finish_authority(ai_memory_core::AuthLevel::Root, None, None);
+ let conn = rusqlite::Connection::open(store.db_path()).unwrap();
+ conn.execute_batch("ALTER TABLE users RENAME TO unavailable_users;")
+ .unwrap();
+ let before = finish_snapshot(&store).await;
+ assert!(
+ store
+ .reader
+ .authorize_workstream_finish(run.run_id, anonymous.clone())
+ .await
+ .is_err(),
+ "unreadable topology must fail closed in preflight"
+ );
+ assert!(
+ store
+ .writer
+ .finish_workstream_run(anonymous.clone(), finish_input(run.run_id))
+ .await
+ .is_err(),
+ "unreadable topology must fail closed in the transaction"
+ );
+ assert_eq!(finish_snapshot(&store).await, before);
+ conn.execute_batch("ALTER TABLE unavailable_users RENAME TO users;")
+ .unwrap();
+ conn.execute(
+ "UPDATE managed_runs SET lease_expires_at = 0 WHERE id = ?1",
+ [run.run_id.as_bytes()],
+ )
+ .unwrap();
+ store
+ .reader
+ .authorize_workstream_finish(run.run_id, root.clone())
+ .await
+ .unwrap();
+ assert_eq!(
+ store
+ .writer
+ .finish_workstream_run(root.clone(), finish_input(run.run_id))
+ .await
+ .unwrap()
+ .imported_events,
+ 1,
+ "late active finish remains legitimate"
+ );
+ let before = finish_snapshot(&store).await;
+ assert_eq!(
+ store
+ .writer
+ .finish_workstream_run(root.clone(), finish_input(run.run_id))
+ .await
+ .unwrap()
+ .imported_events,
+ 0
+ );
+ assert_eq!(finish_snapshot(&store).await, before);
+ // Cancel and replacement both store the existing expired phase.
+ for replaced in [false, true] {
+ let old = store
+ .writer
+ .prepare_workstream_run(PrepareWorkstreamRun {
+ workspace_id: ws,
+ project_id: project,
+ repo_fingerprint: "reload".into(),
+ worktree_fingerprint: "reload".into(),
+ cwd: "/repo".into(),
+ agent: AgentKind::Codex,
+ automatic_harness: false,
+ available_agents: Vec::new(),
+ selection: WorkstreamSelection::Current,
+ lease_owner: "reload".into(),
+ })
+ .await
+ .unwrap();
+ if replaced {
+ conn.execute(
+ "UPDATE managed_runs SET lease_expires_at = 0 WHERE id = ?1",
+ [old.run_id.as_bytes()],
+ )
+ .unwrap();
+ store
+ .writer
+ .prepare_workstream_run(PrepareWorkstreamRun {
+ workspace_id: ws,
+ project_id: project,
+ repo_fingerprint: "reload".into(),
+ worktree_fingerprint: "reload".into(),
+ cwd: "/repo".into(),
+ agent: AgentKind::Codex,
+ automatic_harness: false,
+ available_agents: Vec::new(),
+ selection: WorkstreamSelection::Current,
+ lease_owner: "replacement".into(),
+ })
+ .await
+ .unwrap();
+ } else {
+ store.writer.cancel_managed_run(old.run_id).await.unwrap();
+ }
+ let before = finish_snapshot(&store).await;
+ assert!(matches!(
+ store
+ .writer
+ .finish_workstream_run(root.clone(), finish_input(old.run_id))
+ .await,
+ Err(StoreError::InvalidState(_))
+ ));
+ assert_eq!(finish_snapshot(&store).await, before);
+ }
+ let before = finish_snapshot(&store).await;
+ assert!(matches!(
+ store
+ .reader
+ .authorize_workstream_finish(ai_memory_core::ManagedRunId::new(), root.clone())
+ .await,
+ Err(StoreError::NotFound(_))
+ ));
+ assert!(matches!(
+ store
+ .writer
+ .finish_workstream_run(root, finish_input(ai_memory_core::ManagedRunId::new()))
+ .await,
+ Err(StoreError::NotFound(_))
+ ));
+ assert_eq!(finish_snapshot(&store).await, before);
+}
+
+#[tokio::test]
+async fn owner_finish_store_strict_resolution_refuses_pairing_missing_and_sql_failure() {
+ let f = FinishFixture::new().await;
+ let run = f.run("broken-scope", Some(operator("alice"))).await;
+ let conn = rusqlite::Connection::open(f.store.db_path()).unwrap();
+ conn.execute_batch("PRAGMA foreign_keys=OFF; PRAGMA ignore_check_constraints=ON;")
+ .unwrap();
+ let other_ws = f
+ .store
+ .writer
+ .get_or_create_workspace("other")
+ .await
+ .unwrap();
+ conn.execute(
+ "UPDATE workstreams SET workspace_id = ?1 WHERE id = ?2",
+ rusqlite::params![other_ws.as_bytes(), run.workstream_id.as_bytes()],
+ )
+ .unwrap();
+ let root_owner = finish_authority(ai_memory_core::AuthLevel::Root, None, Some("alice"));
+ f.refused_unchanged(run.run_id, root_owner).await;
+ conn.execute(
+ "UPDATE workstreams SET workspace_id = ?1 WHERE id = ?2",
+ rusqlite::params![f.ws.as_bytes(), run.workstream_id.as_bytes()],
+ )
+ .unwrap();
+ for bytes in [vec![1, 2, 3], WorkspaceId::new().as_bytes().to_vec()] {
+ conn.execute(
+ "UPDATE workstreams SET workspace_id = ?1 WHERE id = ?2",
+ rusqlite::params![bytes, run.workstream_id.as_bytes()],
+ )
+ .unwrap();
+ f.refused_unchanged(run.run_id, f.alice()).await;
+ }
+ conn.execute(
+ "UPDATE workstreams SET workspace_id = ?1 WHERE id = ?2",
+ rusqlite::params![f.ws.as_bytes(), run.workstream_id.as_bytes()],
+ )
+ .unwrap();
+ conn.execute(
+ "UPDATE workstreams SET project_id = ?1 WHERE id = ?2",
+ rusqlite::params![ProjectId::new().as_bytes(), run.workstream_id.as_bytes()],
+ )
+ .unwrap();
+ f.refused_unchanged(run.run_id, f.alice()).await;
+ conn.execute(
+ "UPDATE workstreams SET project_id = ?1 WHERE id = ?2",
+ rusqlite::params![f.project.as_bytes(), run.workstream_id.as_bytes()],
+ )
+ .unwrap();
+ conn.execute(
+ "UPDATE projects SET access_mode = 'unknown' WHERE id = ?1",
+ [f.project.as_bytes()],
+ )
+ .unwrap();
+ f.refused_unchanged(run.run_id, f.alice()).await;
+ conn.execute(
+ "UPDATE projects SET access_mode = 'restricted' WHERE id = ?1",
+ [f.project.as_bytes()],
+ )
+ .unwrap();
+ conn.execute_batch("ALTER TABLE project_grants RENAME TO unavailable_grants;")
+ .unwrap();
+ f.refused_unchanged(run.run_id, f.alice()).await;
+ // The legacy resolution remains fail-open; it is insufficient for finish.
+ let legacy = ai_memory_store::resolve_project_authz(
+ &conn,
+ f.ws,
+ f.project,
+ &ai_memory_store::ProjectPrincipal::user(f.alice),
+ true,
+ )
+ .unwrap();
+ assert_eq!(legacy.access_mode, ai_memory_store::AccessMode::Open);
+ conn.execute_batch("ALTER TABLE unavailable_grants RENAME TO project_grants;")
+ .unwrap();
+ conn.execute(
+ "UPDATE projects SET created_by = ?1 WHERE id = ?2",
+ rusqlite::params![vec![1_u8, 2, 3], f.project.as_bytes()],
+ )
+ .unwrap();
+ f.refused_unchanged(run.run_id, f.alice()).await;
+ conn.execute(
+ "UPDATE projects SET created_by = NULL WHERE id = ?1",
+ [f.project.as_bytes()],
+ )
+ .unwrap();
+ conn.execute(
+ "UPDATE managed_runs SET workstream_id = ?1 WHERE id = ?2",
+ rusqlite::params![
+ ai_memory_core::WorkstreamId::new().as_bytes(),
+ run.run_id.as_bytes()
+ ],
+ )
+ .unwrap();
+ f.refused_unchanged(run.run_id, f.alice()).await;
+ conn.execute(
+ "UPDATE managed_runs SET workstream_id = ?1 WHERE id = ?2",
+ rusqlite::params![run.workstream_id.as_bytes(), run.run_id.as_bytes()],
+ )
+ .unwrap();
+ f.store
+ .reader
+ .authorize_workstream_finish(run.run_id, f.alice())
+ .await
+ .unwrap();
+ assert_eq!(
+ f.store
+ .writer
+ .finish_workstream_run(f.alice(), finish_input(run.run_id))
+ .await
+ .unwrap()
+ .imported_events,
+ 1
+ );
+}
+
+#[tokio::test]
+async fn owner_finish_store_keeps_qualified_identity_namespaces() {
+ let f = FinishFixture::new().await;
+ let identity = IdentityKey::Subject {
+ issuer: "https://idp.example".into(),
+ subject: "alice".into(),
+ };
+ let run = f.run("subject-owned", Some(identity.storage_key())).await;
+ // A display username matching another identity's subject is a different owner.
+ f.refused_unchanged(run.run_id, f.alice()).await;
+ let subject = ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::User,
+ Some(ai_memory_core::AuthorizedViewer(f.alice)),
+ Some(f.alice),
+ &identity.to_actor_context(),
+ false,
+ );
+ let other_issuer = IdentityKey::Subject {
+ issuer: "https://other-idp.example".into(),
+ subject: "alice".into(),
+ };
+ let foreign = ai_memory_store::WorkstreamFinishAuthority::from_auth(
+ ai_memory_core::AuthLevel::User,
+ Some(ai_memory_core::AuthorizedViewer(f.alice)),
+ Some(f.alice),
+ &other_issuer.to_actor_context(),
+ false,
+ );
+ f.refused_unchanged(run.run_id, foreign).await;
+ f.store
+ .reader
+ .authorize_workstream_finish(run.run_id, subject.clone())
+ .await
+ .unwrap();
+ assert_eq!(
+ f.store
+ .writer
+ .finish_workstream_run(subject, finish_input(run.run_id))
+ .await
+ .unwrap()
+ .imported_events,
+ 1
+ );
+}
diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.md
index 1d4164ca..cccb60d7 100644
--- a/docs/managed-workstreams.md
+++ b/docs/managed-workstreams.md
@@ -796,6 +796,38 @@ process launch is fatal; ai-memory does not silently start an unmanaged agent.
## Privacy and storage boundaries
+Finish imports, including retries of finished runs, use the identity resolved by
+HTTP authentication. A caller must own the run (or reach a shared NULL-owned
+run). Database users must hold current Write access to its actual
+workspace/project. Another writer in the same project cannot finish a run
+attributed to a different
+operator. Root without an actor reaches only shared runs; root authentication
+does not bypass ownership. Authenticated operators behind the configured trusted
+proxy retain their existing project access policy without requiring a database
+user. Actor headers without proxy authentication and transcript metadata cannot
+supply this authority. Disabling a user's human login does not revoke an active
+API key; the HTTP authentication checks the key, and finish checks that the
+database user still exists and has current project access.
+
+With authentication disabled but database users still present, anonymous finish
+requests to restricted projects are refused. Prepare retains its existing
+compatibility path and can still succeed. Completing the run requires
+authentication and a caller satisfying the ownership and Write checks above.
+
+The server checks access before reading run status or writing a raw segment,
+then checks again in the SQLite writer transaction before any import, cursor,
+link, or run update. The transaction reads current users, project mode, creator,
+and paired grants; SQL failures and malformed or missing scope fail closed.
+This stricter resolution applies only to finish imports. An active run can still
+finish after its lease timestamp has elapsed, and an authorized finished retry
+imports zero events. Cancelled or replaced runs remain expired and refused.
+
+Raw segments are written before the SQL transaction. A Write revocation after
+the preflight can leave a sanitized raw segment without an indexed event. The
+writer refusal leaves SQL unchanged; raw-file persistence and SQL are not an
+atomic operation.
+
+
ai-memory's managed adapters do not write to Claude, Codex, OpenCode, Pi, Crush,
Kimi Code, Command Code, Kiro, OMP, Grok, or Antigravity private stores. The
launched harness retains normal ownership of its own session writes. Adapters read only
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 53774ace..5de58448 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -64,6 +64,7 @@ boundary not yet built.
| 13a | Managed Codex stale-daemon run recovery (#987; concurrent launches, project/worktree isolation, operator isolation) | `managed_runs.owner_user` (V71) uses the topology-aware `IdentityKey` owner stamp; `router.rs` resolves and authorizes the SessionStart repository before handling the untrusted run id; store `link_or_adopt_native_session` selects and links in one writer transaction and admits only the sole live, undelivered, never-linked Codex run in the exact workspace/project/checkout-cwd/owner bucket. An active supplied id must itself match every boundary; another harness, an ambiguity, or a second native session is refused | `multi_session.rs` `stale_codex_run_recovery_cannot_cross_project_owner_or_session_boundaries` (foreign owner, foreign checkout, and cross-project candidates refused; project-local controls and racing rebind), `stale_codex_run_recovery_fails_closed_on_ambiguity_and_active_mismatch` (two candidates and active foreign id refused, exact control); `workstream.rs` `prepare_stamps_the_operator_bucket_used_by_session_start_recovery` (HTTP actor stamp with foreign and legitimate controls); `router.rs` `managed_session_start_delivers_ledger_and_pending_handoff` supplies a finished stale id and proves the new run is linked and delivered | STRONG for SessionStart recovery. No candidate is selected from a run id's stale scope, another checkout, or another operator bucket; ambiguity deliberately falls back to no managed packet |
| 13b | Managed-run lease exclusivity and explicit recovery (one active run per workstream, invariant #16) | `ai-memory-store/src/workstream.rs` `prepare_run` expires lapsed leases and otherwise refuses an `active` run inside the writer transaction (`StoreError::WorkstreamBusy`). The explicit `force_unlock` path may expire and replace that row in the same transaction only when its durable `owner_user` equals the incoming actor's attribution; different operators remain isolated. `heartbeat` renews only `active` rows. `ai-memory-cli/src/commands/run.rs` normally uses `wait_out_held_lease`; `--force-unlock` instead asks once and fails immediately when refused. Neither path treats the informational `lease_owner` label as authority | `multi_session.rs` `force_unlock_replaces_only_the_same_operators_active_run` (foreign operator refused with live control, same operator succeeds, old run loses heartbeat, unattributed single-user control); hooks `workstream.rs` `force_unlock_cannot_evict_another_operator` exercises the HTTP actor boundary; CLI `run.rs` `force_unlock_asks_once_instead_of_waiting_out_the_lease`; existing controls `managed_workstream_batches_are_idempotent_and_release_the_lease`, `a_renewed_lease_is_reported_as_a_live_owner_not_taken_over`, `interactive_launch_waits_out_a_lapsing_lease_then_proceeds`, and `ctrl_c_aborts_the_held_lease_wait_immediately` | STRONG for exclusivity. The `lease_owner` label (`host:pid`) is informational only and not unique inside ai-jail (every jailed launcher reports `ai-sandbox:<ns-pid>`), so it must never become an ownership key. A shared unattributed/root context is intentionally one operator bucket; deployments needing person-level refusal must authenticate DB users |
| 14 | Per-project authorization (#708) | `ai-memory-store/src/project_authz.rs` `authorize_project` / `ProjectAuthz::authorize` choke point (V68 `project_grants` + `projects.access_mode`, default `open`; V69 `projects.created_by` feeds `is_creator`); `scope.rs` `ScopeResolver::with_project_authz` (reader pool for reads, writer actor for writes) and its free forms `authorize_scope_for` / `*_guarded`, attached for every DB user by `ai-memory-mcp` `scope_resolver_as`, `ai-memory-web` `authorize_read` / `lookup_project`, and `ai-memory-hooks` (`grants.rs` `authorize_resolved` for run/workstream ids, the capture check in `router.rs`); read-shaped mutations resolve at `ProjectAccess::Write` (`resolve_existing_args(.., need)`); unscoped reads filtered before `LIMIT` by `reader.rs` `readable_repository_sql`; `WriterHandle::authorize_project` as defense in depth. Page ids are never taken from a caller (only derived from already-authorized hits), so there is no page-id entry point to guard; incremental `recent` resolves and authorizes the requested project before decoding its scope-bound cursor; batch outcomes do not bypass the capture grant or session owner check | `tests/suite/project_authz.rs` (decision matrix, ship-inert, resolver gate); `tests/suite/access_mode.rs` `every_caller_against_both_modes`, `a_restricted_project_admits_the_team_and_refuses_the_outsider`, `new_projects_follow_the_server_default_and_admit_their_creator`; `scope.rs` `the_argument_shape_does_not_decide_the_level`, `a_user_reaches_only_what_they_were_granted`, `creating_authorizes_against_a_project_that_already_exists`, `a_refused_scope_fails_the_search_instead_of_shortening_it`; `grants.rs` `search_finds_only_what_the_viewer_may_read`, `the_limit_counts_only_what_the_viewer_may_see`, `the_workspace_handoff_comes_only_from_readable_repositories`; `ai-memory-mcp` `server.rs` `a_reader_may_read_everything_and_change_nothing`, `bob_cannot_read_alices_page_in_a_restricted_project`, `bob_cannot_find_alices_page_by_searching_in_a_restricted_project`, `bob_cannot_consolidate_a_session_in_alices_repository`, `a_restricted_projects_queues_need_write`; `ai-memory-hooks` `a_capture_needs_writer_on_the_repository_it_lands_in`, `session_start_delivers_nothing_from_a_repository_the_viewer_cannot_read`, `run_and_workstream_ids_only_answer_someone_who_may_reach_the_repository`; `ai-memory-web` `web_reads_honour_grants_in_a_restricted_project`, `metadata_shows_only_what_the_viewer_may_read` — each with a granted or open-project control, and proven to fail with the choke point (18 tests) or the SQL filter (9 tests) neutralized; `routes.rs` `api_recent_incremental_rechecks_restricted_scope_on_cursor` (a valid cursor cannot bypass a revoked grant; granted control passes), `api_recent_incremental_paginates_over_120_pages_and_binds_cursor`; `mcp_stateless_http.rs` `generic_machine_client_writes_queries_and_claims_a_handoff` (real machine key, foreign scope and partial scope refused); `router.rs` `an_unauthorized_batch_item_is_consumed_rather_than_retried`, `batch_acknowledges_foreign_collision_then_commits_next_item` (refused foreign item followed by a legitimate stored item) | STRONG — slice 3 closed both bypass classes (unscoped reads, raw-id entry points) and added the root-only management surface. Out of scope by design: per-project administrators (granting/restricting is root-only), and access modes, creators and grants live only in SQLite, so `reindex` resets them |
+| 14ap | Managed-run finish owner and current project access | `hooks/src/workstream.rs` derives `WorkstreamFinishAuthority` only from authenticated middleware extensions and checks the real run before status/payload/segment handling; `ReaderPool::authorize_workstream_finish` and `store/src/workstream.rs` `authorize_finish` use a read snapshot and the existing writer transaction, respectively. Strict finish resolution requires the actual workspace/project pair, current user existence and current Write decision for DB principals. The private trusted-proxy policy requires authenticated User capability, a canonical identity, no DB principal and server proxy configuration; it retains legacy project admission after strict scope validation, with ownership still enforced. Human-login disable does not revoke API keys. The legacy resolver and auth middleware remain unchanged. Both writer entry paths, including finished retries, require the same authority; no cross-owner bypass | MCP `auth.rs` `owner_finish_http_refuses_another_writer_before_payload_or_segment`, `owner_finish_http_trusted_proxy_preserves_restricted_lifecycle`, `owner_finish_http_active_api_key_survives_disabled_human_login`; store `multi_session.rs` `owner_finish_store_refuses_another_writer_including_finished_retry`, `owner_finish_store_rechecks_write_after_preflight`, `owner_finish_store_refuses_a_deleted_user_after_preflight`, `owner_finish_store_proxy_policy_requires_server_and_authenticated_identity`, `owner_finish_store_raw_ids_use_the_actual_project_and_workspace`, `owner_finish_store_topology_reload_and_phase_controls`, `owner_finish_store_strict_resolution_refuses_pairing_missing_and_sql_failure`, `owner_finish_store_keeps_qualified_identity_namespaces`; hooks `workstream.rs` `owner_finish_revocation_between_preflight_and_both_writer_paths`; MCP `auth.rs` `owner_finish_http_real_auth_rungs_shared_and_project_controls`, `owner_finish_http_preserves_late_active_terminal_and_missing_phases`. Guard-neutralization recipes and results accompany the local frozen patch | SQL refusal is atomic within the writer transaction; a revocation after preflight can leave an unindexed raw segment. Shared NULL ownership, trusted-proxy project admission and late still-active finishes remain intentional |
| 14b | Repository identity routing (#708) | `ai-memory-store/src/ops.rs` `resolve_project_by_identity` — one transaction; an identity already on a project is never overwritten; an unclaimed project is claimed only when the capturing user may write it (the choke point's `resolve_project_authz` on the same transaction), otherwise it is returned unclaimed; a different identity under the same name splits into a new project with no shared `repo_path`; `ai-memory-hooks/src/router.rs` `cache_key_for` keys the path cache by identity too; `ai-memory-core/src/repository_identity.rs` strips credentials from remote URLs client-side, and the server accepts only the routing rungs (`explicit`, `git_remote`) from the wire | `tests/suite/identity_resolution.rs` `an_outsider_cannot_take_an_unclaimed_projects_identity` (control: `an_existing_project_is_claimed_in_place`), `two_unrelated_repositories_with_one_folder_name_stay_apart`, `a_created_or_split_project_admits_its_creator`; `router.rs` `one_path_with_two_remotes_is_two_projects`, `two_api_checkouts_with_different_remotes_get_two_projects` (a manifest rung on the wire is ignored); `repository_identity.rs` credential and normalisation tables — the claim guard and the cache key each proven to fail their test when removed | STRONG — first claimant wins: in a restricted workspace a user who creates a project under a remote identity first holds it until root grants others |
| 14c | Client-supplied event time is bounded and self-scoped (#919) | `ai-memory-hooks/src/payload.rs` `HookEnvelope::occurred_at_micros` — a `/hook` caller's optional `occurred_at` must be `> 0` and `<= now + 5min`; it only sets the caller's *own* admitted session's `started_at`/`ended_at`/`created_at`, never another session/project/user, and the ingest dedup `seen_at`/TTL stays on `now` | `payload.rs` `occurred_at_micros_rejects_a_far_future_timestamp`, `…_rejects_non_positive_values`, `…_rejects_garbage_strings` | MEDIUM — self-scoped numeric bound; no cross-tenant surface (a client already controls its own content) |
| 14d | `include_related` shows and walks only readable projects (#708) | `ai-memory-store/src/reader.rs` `related_walk(.., viewer)` — both the outgoing and incoming hop queries carry `readable_repository_predicate("pg.project_id", viewer)`, the same far-end filter `page_links` applies, so a page in a project the viewer cannot read is neither returned nor expanded; `ai-memory-mcp/src/server.rs` `memory_read_page` passes `viewer_from_parts`, and the access bump only touches the filtered nodes | `related_walk.rs` `the_walk_hides_and_does_not_cross_projects_the_viewer_cannot_read` (an outgoing and an incoming neighbour in an ungranted restricted project are absent, and so is a granted page reachable only through one; control: a granted restricted project is shown, and no viewer walks the whole graph) — fails with the predicate removed; `ai-memory-mcp` `server.rs` `bob_does_not_see_restricted_pages_through_the_related_walk` (an ungranted user's `memory_read_page{include_related}` omits the restricted page; control: no viewer still reaches it) — fails with `memory_read_page` passing `None` instead of `viewer_from_parts` | STRONG |