Skip to content

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

Rust

Merge release/2.6 into PR #1075

AkitaOnRails52c9e38452c4
diff --cc CHANGELOG.md
index c79acc67,170601a7..e8780141
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -116,14 -128,60 +128,66 @@@ and this project adheres to [Semantic V
or distinct extensions, including backfill).
Mixed-source counts preserve scope, session ownership and time-window filters;
older servers leave unsupported fields unknown. (#1016)
+ - Added bounded, sanitized native-record and adapter correlation provenance to
+ managed-workstream search/tail results and the CLI's text/JSON output, with
+ compatible optional fields and sanitization of legacy provenance on reads. (#1057)
+ - Added Portuguese history phrases to the existing opt-in session-recall
+ router (`[retrieval] query_intent`), including accented and unaccented spellings of
+ "última sessão", "onde paramos ontem", and "decisão anterior". Word
+ boundaries and explicit history phrases keep technical session queries
+ unchanged; routing remains off by default. (#1056)
+ - Added shared, typed and bounded `entities`, `abstract`, and `relations`
+ metadata to MCP `memory_write_page` and admin `/admin/write-page`, plus bounded
+ MCP `kind` while preserving the admin's legacy `kind` adapter. Kept existing
+ request shapes, entity normalization, authenticated attribution and the wiki
+ write pipeline. Documented whole-page replacement, raw-input metadata bounds
+ and trimmed relation scope components. (#1055)
+ - Added structured results for the existing auto-improvement eval execution in
+ review reports, staged run metadata, and accepted proposal sidecars, with
+ server-generated eval IDs, evaluated request/body digests, checker invocation
+ identity, observed success/rejection/failure/timeout, and sanitized bounded
+ reasons. Report deserialization discarded supplied eval observations. (#1053)
+ - Added `grizzybot` as a recognised agent (wire value `grizzybot`, alias
+ `grizzy-bot`), so GrizzyBot's lifecycle events are attributed to it instead
+ of `other` and its tool calls are captured as closed-schema tool families,
+ like other Claude Code-shaped agents. GrizzyBot posts to `/hook` and
+ `/mcp` itself, so there is nothing to install. Adds migration V72 to extend
+ the `sessions.agent_kind` CHECK constraint. (#1036)
+ - Added GitHub Copilot CLI as a hooked agent: `install-hooks --agent
+ copilot-cli` writes `$COPILOT_HOME/hooks/ai-memory.json` (default
+ `~/.copilot/hooks/ai-memory.json`) with Copilot's flat, matcher-less entries
+ and PascalCase event names, so Copilot sends its VS Code/Claude-compatible
+ payload. Ten events — Claude Code's nine plus `PostToolUseFailure` — with
+ native commands enforcing capture exclusions; tool output is read from
+ `tool_result.text_result_for_llm` and the outcome from
+ `tool_result.result_type`. The `SessionStart` hook delivers the prior
+ session's handoff through Copilot's top-level `additionalContext` (ported
+ from #1069). There is deliberately no `--scope project`. The bare
+ `install-mcp --client copilot` alias keeps meaning VS Code Copilot;
+ `ai-memory run copilot` follows separately. (#1040)
+ - Added `install-mcp --client copilot-cli`, which merges ai-memory's remote
+ entry (`type: "http"`, `url`, bearer `headers`, `tools: ["*"]`) into the root
+ `mcpServers` map of `$COPILOT_HOME/mcp-config.json` (default
+ `~/.copilot/mcp-config.json`), preserving other servers. `install-hooks
+ --agent copilot-cli` without `--server-url` now reads the server URL and
+ bearer back from that entry, and `uninstall` removes it. (#1040)
+ - Added an optional `session_id` to `memory_write_page`, so an agent can
+ write a session's page with its own model and keep it traceable to the
+ session. The session must belong to the project the page is written to, and
+ the page records it as session evidence. A page that cites a session does
+ not overwrite a pinned page. Writing `sessions/<id>.md` also stamps the
+ frontmatter `memory_consolidate` writes there (`session_id`, `agent`,
+ `consolidated`, plus `consolidated_by: agent`), defaults the tier to
+ `episodic`, applies the same duplicate-title suffix, and marks the session's
+ queued SessionEnd consolidation job completed. (#1038)
### 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. (#1075)
- 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 --cc crates/ai-memory-hooks/src/router.rs
index d18fa64c,8400a110..eefff6ec
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@@ -13183,34 -13652,26 +13652,35 @@@ mod tests
.unwrap();
state
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- sanitizer: ai_memory_core::Sanitizer::default(),
- 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 {
++ sanitizer: ai_memory_core::Sanitizer::default(),
+ 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.
@@@ -13600,34 -14061,26 +14070,35 @@@
.unwrap();
state
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- sanitizer: ai_memory_core::Sanitizer::default(),
- 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 {
++ sanitizer: ai_memory_core::Sanitizer::default(),
+ 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 --cc crates/ai-memory-hooks/src/workstream.rs
index 072040b3,102cc510..2f40a3ff
--- a/crates/ai-memory-hooks/src/workstream.rs
+++ b/crates/ai-memory-hooks/src/workstream.rs
@@@ -862,18 -857,16 +873,19 @@@ async fn finish_run
if status.state == "finished" {
return match state
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- sanitizer: state.sanitizer.clone(),
- 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 {
++ sanitizer: state.sanitizer.clone(),
+ 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 {
@@@ -1185,6 -1174,266 +1195,272 @@@ mod tests
(workspace_id, project_id)
}
+ #[tokio::test]
+ async fn workstream_provenance_finish_scrubs_before_raw_segment_and_search() {
+ let temp = TempDir::new().unwrap();
+ let store = Store::open(temp.path()).unwrap();
+ let mut state = test_state(&store, temp.path());
+ state.sanitizer = Sanitizer::new(&ai_memory_core::SanitizeConfig {
+ extra_patterns: vec!["private-correlation".into()],
+ allowlist: Vec::new(),
+ })
+ .unwrap();
+ let (workspace_id, project_id) = seed_scope(&store).await;
+ let run = store
+ .writer
+ .prepare_workstream_run(prepare_input(
+ workspace_id,
+ project_id,
+ AgentKind::Codex,
+ "launcher",
+ ))
+ .await
+ .unwrap();
+ let response = finish_run(
- State(state.clone()), None, None, AxumPath(run.run_id.to_string()),
++ State(state.clone()), None, None, None, None, AxumPath(run.run_id.to_string()),
+ Json(FinishManagedRunRequest {
+ native_session_id: Some("native-1".into()), source_cursor: None,
+ events: vec![NewWorkstreamEvent {
+ event_id: "event-1".into(), agent: AgentKind::Codex,
+ native_session_id: "native-1".into(),
+ source_record_id: Some("private-correlation".into()),
+ kind: WorkstreamEventKind::ToolResult, role: Some("tool".into()),
+ content: "portable provenance sentinel".into(), occurred_at: None,
+ metadata: serde_json::json!({"tool_call_id": "call-1", "parent_id": "private-correlation", "dump": "private payload"}),
+ }],
+ complete: false, checkpoint: Default::default(), exit_code: None, losses: Vec::new(),
+ }),
+ ).await;
+ assert_eq!(response.status(), StatusCode::OK);
+ let segment_dir = temp
+ .path()
+ .join("raw/workstreams")
+ .join(run.workstream_id.to_string())
+ .join("segments");
+ let path = std::fs::read_dir(segment_dir)
+ .unwrap()
+ .next()
+ .unwrap()
+ .unwrap()
+ .path();
+ let raw = std::fs::read_to_string(path).unwrap();
+ assert!(
+ !raw.contains("private-correlation"),
+ "raw segment leaked source id"
+ );
+ assert!(!raw.contains("private payload"));
+ for q in ["", "portable"] {
+ let response = search_events(
+ State(state.clone()),
+ None,
+ None,
+ AxumPath(run.workstream_id.to_string()),
+ Query(EventQuery {
+ q: q.into(),
+ ..Default::default()
+ }),
+ )
+ .await;
+ assert_eq!(response.status(), StatusCode::OK);
+ let body = to_bytes(response.into_body(), 64 * 1024).await.unwrap();
+ let events: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(events[0]["source_record_id"], "[REDACTED:custom]");
+ assert_eq!(events[0]["metadata"]["parent_id"], "[REDACTED:custom]");
+ assert_eq!(events[0]["metadata"]["tool_call_id"], "call-1");
+ assert!(events[0]["metadata"].get("dump").is_none());
+ }
+ let original: NewWorkstreamEvent = serde_json::from_str(raw.trim()).unwrap();
+ let mut next = original.clone();
+ next.event_id = "event-2".into();
+ next.source_record_id = Some("record-2".into());
+ let mut collision = original.clone();
+ collision.kind = WorkstreamEventKind::Message;
+ let import = |events| {
+ finish_run(
+ State(state.clone()),
+ None,
+ None,
++ None,
++ None,
+ AxumPath(run.run_id.to_string()),
+ Json(FinishManagedRunRequest {
+ native_session_id: Some("native-1".into()),
+ source_cursor: None,
+ events,
+ complete: false,
+ checkpoint: Default::default(),
+ exit_code: None,
+ losses: Vec::new(),
+ }),
+ )
+ };
+ assert_eq!(
+ import(vec![next.clone(), collision]).await.status(),
+ StatusCode::BAD_REQUEST
+ );
+ let read = || {
+ store.reader.search_workstream_events(
+ run.workstream_id,
+ String::new(),
+ 10,
+ state.sanitizer.clone(),
+ )
+ };
+ assert_eq!(
+ read().await.unwrap().len(),
+ 1,
+ "failed segment must not become indexed history"
+ );
+ let recovered = import(vec![next, original]).await;
+ assert_eq!(recovered.status(), StatusCode::OK);
+ let body = to_bytes(recovered.into_body(), 64 * 1024).await.unwrap();
+ let recovered: FinishManagedRunResponse = serde_json::from_slice(&body).unwrap();
+ assert_eq!(recovered.imported_events, 1);
+ assert_eq!(recovered.latest_sequence, 2);
+ assert_eq!(read().await.unwrap().len(), 2);
+ let original: NewWorkstreamEvent = serde_json::from_str(raw.trim()).unwrap();
+ let complete = |events| {
+ finish_run(
+ State(state.clone()),
+ None,
+ None,
++ None,
++ None,
+ AxumPath(run.run_id.to_string()),
+ Json(FinishManagedRunRequest {
+ native_session_id: Some("native-1".into()),
+ source_cursor: None,
+ events,
+ complete: true,
+ checkpoint: Default::default(),
+ exit_code: None,
+ losses: Vec::new(),
+ }),
+ )
+ };
+ assert_eq!(
+ complete(vec![original.clone()]).await.status(),
+ StatusCode::OK
+ );
+ let mut changed = original.clone();
+ changed.source_record_id = Some("different-record".into());
+ let mut late = original.clone();
+ late.event_id = "late-new-event".into();
+ assert_eq!(complete(vec![changed, late]).await.status(), StatusCode::OK);
+ assert_eq!(complete(vec![original]).await.status(), StatusCode::OK);
+ let hits = read().await.unwrap();
+ assert_eq!(hits.len(), 3);
+ assert!(
+ hits.iter()
+ .any(|hit| hit.kind == WorkstreamEventKind::Checkpoint)
+ );
+ assert!(!hits.iter().any(|hit| hit.event_id == "late-new-event"));
+ }
+
+ #[tokio::test]
+ async fn workstream_provenance_client_cannot_use_server_event_ids() {
+ let temp = TempDir::new().unwrap();
+ let store = Store::open(temp.path()).unwrap();
+ let state = test_state(&store, temp.path());
+ let (workspace_id, project_id) = seed_scope(&store).await;
+ let run = store
+ .writer
+ .prepare_workstream_run(prepare_input(
+ workspace_id,
+ project_id,
+ AgentKind::Codex,
+ "launcher",
+ ))
+ .await
+ .unwrap();
+ let import = |id: String, complete| {
+ finish_run(
+ State(state.clone()),
+ None,
+ None,
++ None,
++ None,
+ AxumPath(run.run_id.to_string()),
+ Json(FinishManagedRunRequest {
+ native_session_id: Some("native-1".into()),
+ source_cursor: None,
+ events: vec![NewWorkstreamEvent {
+ event_id: id,
+ agent: AgentKind::Codex,
+ native_session_id: "native-1".into(),
+ source_record_id: Some("record-1".into()),
+ kind: WorkstreamEventKind::Message,
+ role: Some("assistant".into()),
+ content: "legitimate native event".into(),
+ occurred_at: None,
+ metadata: serde_json::Value::Null,
+ }],
+ complete,
+ checkpoint: Default::default(),
+ exit_code: Some(0),
+ losses: if complete {
+ vec!["missing native record".into()]
+ } else {
+ Vec::new()
+ },
+ }),
+ )
+ };
+ // Legitimate native ids work before and after the attempted forgery.
+ assert_eq!(
+ import("native-event".into(), false).await.status(),
+ StatusCode::OK
+ );
+ let segment_dir = temp
+ .path()
+ .join("raw/workstreams")
+ .join(run.workstream_id.to_string())
+ .join("segments");
+ for id in [
+ format!("managed-run:{}:checkpoint", run.run_id),
+ format!("managed-run:{}:losses", run.run_id),
+ "managed-run:other-run:annotation".into(),
+ ] {
+ assert_eq!(import(id, false).await.status(), StatusCode::BAD_REQUEST);
+ assert_eq!(
+ std::fs::read_dir(&segment_dir).unwrap().count(),
+ 1,
+ "reserved ids must be refused before writing raw segments"
+ );
+ }
+ assert_eq!(
+ import("native-event".into(), true).await.status(),
+ StatusCode::OK
+ );
+ let hits = store
+ .reader
+ .search_workstream_events(
+ run.workstream_id,
+ String::new(),
+ 10,
+ state.sanitizer.clone(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(hits.len(), 3);
+ assert!(hits.iter().any(|hit| hit.event_id == "native-event"));
+ for (suffix, kind) in [
+ ("checkpoint", WorkstreamEventKind::Checkpoint),
+ ("losses", WorkstreamEventKind::Annotation),
+ ] {
+ assert!(hits.iter().any(|hit| hit.event_id
+ == format!("managed-run:{}:{suffix}", run.run_id)
+ && hit.kind == kind
+ && hit.source_record_id.is_none()));
+ }
+ assert_eq!(
+ import("managed-run:late:checkpoint".into(), false)
+ .await
+ .status(),
+ StatusCode::BAD_REQUEST
+ );
+ }
+
/// The launcher reads whether the run's child linked a session from the
/// run status, so the route must carry it.
#[tokio::test]
@@@ -1341,24 -1590,16 +1617,25 @@@
.unwrap();
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- sanitizer: ai_memory_core::Sanitizer::default(),
- 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 {
++ sanitizer: ai_memory_core::Sanitizer::default(),
+ 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();
@@@ -1443,24 -1684,16 +1720,25 @@@
.unwrap();
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- sanitizer: ai_memory_core::Sanitizer::default(),
- 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 {
++ sanitizer: ai_memory_core::Sanitizer::default(),
+ 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();
@@@ -1530,24 -1763,16 +1808,25 @@@
// Close the explicit run so the automatic prepare can take the lease.
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- sanitizer: ai_memory_core::Sanitizer::default(),
- 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 {
++ sanitizer: ai_memory_core::Sanitizer::default(),
+ 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();
@@@ -1800,24 -2025,16 +2079,25 @@@
assert_eq!(prepared.resolved_agent, Some(AgentKind::KiroCli));
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- sanitizer: ai_memory_core::Sanitizer::default(),
- 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 {
++ sanitizer: ai_memory_core::Sanitizer::default(),
+ 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();
@@@ -1878,24 -2095,16 +2158,25 @@@
assert_eq!(prepared.resolved_agent, Some(AgentKind::CommandCode));
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- sanitizer: ai_memory_core::Sanitizer::default(),
- 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 {
++ sanitizer: ai_memory_core::Sanitizer::default(),
+ 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();
@@@ -1956,24 -2165,16 +2237,25 @@@
assert_eq!(prepared.resolved_agent, Some(AgentKind::Grok));
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- sanitizer: ai_memory_core::Sanitizer::default(),
- 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 {
++ sanitizer: ai_memory_core::Sanitizer::default(),
+ 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();
@@@ -2037,24 -2238,16 +2319,25 @@@
assert_eq!(prepared.resolved_agent, Some(AgentKind::AntigravityCli));
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- sanitizer: ai_memory_core::Sanitizer::default(),
- 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 {
++ sanitizer: ai_memory_core::Sanitizer::default(),
+ 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();
@@@ -2168,34 -2361,26 +2451,35 @@@
.unwrap();
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- sanitizer: ai_memory_core::Sanitizer::default(),
- 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 {
++ sanitizer: ai_memory_core::Sanitizer::default(),
+ 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
@@@ -2365,6 -2550,30 +2649,39 @@@
.await
.unwrap()
.expect("the run was just prepared");
+ store
+ .writer
- .finish_workstream_run(FinishWorkstreamRun {
- sanitizer: state.sanitizer.clone(),
- run_id: prepared.run_id,
- native_session_id: Some("claude-native".into()),
- source_cursor: None,
- events: vec![NewWorkstreamEvent {
- event_id: "scope-provenance".into(),
- agent: AgentKind::ClaudeCode,
- native_session_id: "claude-native".into(),
- source_record_id: Some("record-1".into()),
- kind: WorkstreamEventKind::ToolResult,
- role: Some("tool".into()),
- content: "scope provenance sentinel".into(),
- occurred_at: None,
- metadata: serde_json::json!({"tool_use_id": "call-1"}),
- }],
- complete: false,
- segment_path: None,
- exit_code: None,
- })
++ .finish_workstream_run(
++ ai_memory_store::WorkstreamFinishAuthority::from_auth(
++ AuthLevel::Anonymous,
++ None,
++ None,
++ &ai_memory_core::ActorContext::anonymous(),
++ false,
++ ),
++ FinishWorkstreamRun {
++ sanitizer: state.sanitizer.clone(),
++ run_id: prepared.run_id,
++ native_session_id: Some("claude-native".into()),
++ source_cursor: None,
++ events: vec![NewWorkstreamEvent {
++ event_id: "scope-provenance".into(),
++ agent: AgentKind::ClaudeCode,
++ native_session_id: "claude-native".into(),
++ source_record_id: Some("record-1".into()),
++ kind: WorkstreamEventKind::ToolResult,
++ role: Some("tool".into()),
++ content: "scope provenance sentinel".into(),
++ occurred_at: None,
++ metadata: serde_json::json!({"tool_use_id": "call-1"}),
++ }],
++ complete: false,
++ segment_path: None,
++ exit_code: None,
++ },
++ )
+ .await
+ .unwrap();
let human = |name: &'static str| {
let writer = store.writer.clone();
@@@ -2474,188 -2691,4 +2799,189 @@@
.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 {
++ sanitizer: ai_memory_core::Sanitizer::default(),
+ 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 --cc crates/ai-memory-store/src/lib.rs
index 5243e734,b3eaf643..4c5e2167
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@@ -5015,24 -5015,16 +5015,25 @@@ mod tests
assert_eq!(status(first.run_id).await, (Some("native-1".into()), true));
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- sanitizer: ai_memory_core::Sanitizer::default(),
- 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 {
++ sanitizer: ai_memory_core::Sanitizer::default(),
+ 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();
@@@ -5253,24 -5202,16 +5256,25 @@@
let finished = store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- sanitizer: ai_memory_core::Sanitizer::default(),
- 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 {
++ sanitizer: ai_memory_core::Sanitizer::default(),
+ 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);
@@@ -5323,24 -5269,16 +5332,25 @@@
);
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- sanitizer: ai_memory_core::Sanitizer::default(),
- 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 {
++ sanitizer: ai_memory_core::Sanitizer::default(),
+ 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
@@@ -5363,24 -5301,16 +5373,25 @@@
);
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- sanitizer: ai_memory_core::Sanitizer::default(),
- 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 {
++ sanitizer: ai_memory_core::Sanitizer::default(),
+ 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();
@@@ -5483,24 -5413,16 +5494,25 @@@
assert!(blank.may_adopt_existing_session);
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- sanitizer: ai_memory_core::Sanitizer::default(),
- 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 {
++ sanitizer: ai_memory_core::Sanitizer::default(),
+ 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();
@@@ -5522,24 -5444,16 +5534,25 @@@
);
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- sanitizer: ai_memory_core::Sanitizer::default(),
- 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 {
++ sanitizer: ai_memory_core::Sanitizer::default(),
+ 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();
@@@ -5588,24 -5502,16 +5601,25 @@@
.unwrap();
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- sanitizer: ai_memory_core::Sanitizer::default(),
- 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 {
++ sanitizer: ai_memory_core::Sanitizer::default(),
+ 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();
@@@ -5661,34 -5567,26 +5675,35 @@@
.unwrap();
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- sanitizer: ai_memory_core::Sanitizer::default(),
- 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 {
++ sanitizer: ai_memory_core::Sanitizer::default(),
+ 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);
@@@ -6071,27 -5937,19 +6103,28 @@@
// A valid event followed by another agent's event must import nothing.
let wrong_agent = store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- sanitizer: ai_memory_core::Sanitizer::default(),
- 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 {
++ sanitizer: ai_memory_core::Sanitizer::default(),
+ 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!(
@@@ -6121,29 -5984,21 +6159,30 @@@
// Events from a different native session are rejected the same way.
let wrong_session = store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- sanitizer: ai_memory_core::Sanitizer::default(),
- 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 {
++ sanitizer: ai_memory_core::Sanitizer::default(),
+ 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!(
@@@ -6154,24 -6009,16 +6193,25 @@@
// The run is still usable after the rejected batches.
let finished = store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- sanitizer: ai_memory_core::Sanitizer::default(),
- 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 {
++ sanitizer: ai_memory_core::Sanitizer::default(),
+ 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);
@@@ -6771,24 -6621,16 +6841,25 @@@
.unwrap();
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- sanitizer: ai_memory_core::Sanitizer::default(),
- 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 {
++ sanitizer: ai_memory_core::Sanitizer::default(),
+ 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
@@@ -6802,48 -6644,32 +6873,50 @@@
.unwrap();
store
.writer
- .finish_workstream_run(FinishWorkstreamRun {
- sanitizer: ai_memory_core::Sanitizer::default(),
- 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 {
++ sanitizer: ai_memory_core::Sanitizer::default(),
+ 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 {
- sanitizer: ai_memory_core::Sanitizer::default(),
- 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 {
++ sanitizer: ai_memory_core::Sanitizer::default(),
+ 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 --cc crates/ai-memory-store/src/project_authz.rs
index 23f9ea02,242e08aa..dacf3ab0
--- a/crates/ai-memory-store/src/project_authz.rs
+++ b/crates/ai-memory-store/src/project_authz.rs
@@@ -252,6 -293,11 +293,49 @@@ fn read_project_row(conn: &Connection,
}
}
++/// [`read_project_row`] without degrading: the project must exist in the
++/// given workspace, its access mode must be a known value and its creator a
++/// well-formed id.
++fn read_project_row_strict(
++ conn: &Connection,
++ workspace_id: WorkspaceId,
++ project_id: ProjectId,
++) -> StoreResult<ProjectRow> {
++ let (mode, creator, project, workspace) = conn.query_row(
++ "SELECT p.access_mode, p.created_by, p.name, w.name 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)?,
++ row.get::<_, String>(2)?,
++ row.get::<_, String>(3)?,
++ ))
++ },
++ )?;
++ let access_mode = match mode.as_str() {
++ "open" => AccessMode::Open,
++ "restricted" => AccessMode::Restricted,
++ _ => {
++ return Err(crate::StoreError::MalformedRecord(
++ "unknown project access mode".into(),
++ ));
++ }
++ };
++ Ok(ProjectRow {
++ access_mode,
++ creator: creator.map(|raw| UserId::from_slice(&raw)).transpose()?,
++ reserved_global: is_reserved_global(&workspace, &project),
++ })
++}
++
+ fn is_reserved_global(workspace: &str, project: &str) -> bool {
+ workspace == ai_memory_core::DEFAULT_WORKSPACE_NAME
+ && project == ai_memory_core::GLOBAL_SCOPE_PROJECT
+ }
+
/// Look up a caller's grant on a project. Returns the failure so the caller can
/// decide how to degrade (a restricted project degrades to open when its grants
/// cannot be read).
@@@ -293,13 -339,31 +377,98 @@@ pub fn resolve_project_authz
project_id: ProjectId,
principal: &ProjectPrincipal,
distinguishes_operators: bool,
+) -> StoreResult<ProjectAuthz> {
- let (mut access_mode, creator) = read_project_row(conn, project_id);
++ resolve(
++ conn,
++ workspace_id,
++ project_id,
++ principal,
++ distinguishes_operators,
++ Resolution::DegradeToOpen,
++ )
++}
++
++/// [`resolve_project_authz`] for a managed-run write that releases or replaces
++/// another operator's state (finish, cancel, heartbeat, link, context
++/// acceptance). The decision is the same; only a resolution gap differs: an
++/// unreadable or unknown project, an unknown access mode, a deleted user or an
++/// unreadable grant is an error instead of degrading to `open`, and a server
++/// with database users distinguishes operators even when the caller's auth
++/// level does not say so.
++pub(crate) fn resolve_project_authz_strict(
++ conn: &Connection,
++ workspace_id: WorkspaceId,
++ project_id: ProjectId,
++ principal: &ProjectPrincipal,
++ distinguishes_operators: bool,
++) -> StoreResult<ProjectAuthz> {
++ resolve(
++ conn,
++ workspace_id,
++ project_id,
++ principal,
++ distinguishes_operators,
++ Resolution::Strict,
++ )
++}
++
++/// How [`resolve`] treats a gap in what it can read.
++#[derive(Debug, Clone, Copy, PartialEq, Eq)]
++enum Resolution {
++ /// Degrade to `open` and log (#678).
++ DegradeToOpen,
++ /// Fail the request.
++ Strict,
++}
++
++fn resolve(
++ conn: &Connection,
++ workspace_id: WorkspaceId,
++ project_id: ProjectId,
++ principal: &ProjectPrincipal,
++ mut distinguishes_operators: bool,
++ resolution: Resolution,
+ ) -> StoreResult<ProjectAuthz> {
+ let ProjectRow {
+ mut access_mode,
+ creator,
+ reserved_global,
- } = read_project_row(conn, project_id);
++ } = match resolution {
++ Resolution::DegradeToOpen => read_project_row(conn, project_id),
++ Resolution::Strict => {
++ let row = read_project_row_strict(conn, workspace_id, project_id)?;
++ distinguishes_operators |= 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(crate::StoreError::Forbidden(
++ "authenticated user no longer exists",
++ ));
++ }
++ }
++ row
++ }
++ };
let is_creator = principal.is_creator || (creator.is_some() && creator == principal.user_id);
- let grant = if access_mode == AccessMode::Restricted {
- let grant = if reserved_global {
- // The global scope's write gate needs the grant in either mode. An
- // unreadable grant admits no write; reads stay open regardless.
- principal.user_id.and_then(|user_id| {
- read_grant(conn, workspace_id, project_id, user_id)
- .inspect_err(|err| {
++ let grant = if reserved_global || access_mode == AccessMode::Restricted {
+ match principal.user_id {
+ Some(user_id) => match read_grant(conn, workspace_id, project_id, user_id) {
+ Ok(grant) => grant,
++ Err(err) if resolution == Resolution::Strict => return Err(err.into()),
++ // The global scope's write gate needs the grant in either
++ // mode; an unreadable grant admits no write there, while reads
++ // stay open.
++ Err(err) if reserved_global => {
+ tracing::warn!(
+ error = %err,
+ "could not read project_grants for the global scope; refusing writes",
+ );
- })
- .ok()
- .flatten()
- })
- } else if access_mode == AccessMode::Restricted {
- match principal.user_id {
- Some(user_id) => match read_grant(conn, workspace_id, project_id, user_id) {
- Ok(grant) => grant,
++ None
++ }
Err(err) => {
// The grants table cannot be read: degrade to open rather
// than lock everyone out of a restricted project (#678).
diff --cc crates/ai-memory-store/src/workstream.rs
index 6ac46dcc,b8991b42..a2a920f0
--- a/crates/ai-memory-store/src/workstream.rs
+++ b/crates/ai-memory-store/src/workstream.rs
@@@ -30,112 -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(
++ let project_authz = crate::project_authz::resolve_project_authz_strict(
+ 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 {
diff --cc crates/ai-memory-store/tests/suite/multi_session.rs
index 8901a6d4,204f5bd0..cf67eece
--- a/crates/ai-memory-store/tests/suite/multi_session.rs
+++ b/crates/ai-memory-store/tests/suite/multi_session.rs
@@@ -1114,946 -1114,3 +1114,947 @@@ async fn stale_codex_run_recovery_fails
);
}
}
+
+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 {
++ sanitizer: ai_memory_core::Sanitizer::default(),
+ 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 --cc crates/ai-memory-store/tests/suite/workstream_provenance.rs
index 00000000,73afd677..709dc19b
mode 000000,100644..100644
--- a/crates/ai-memory-store/tests/suite/workstream_provenance.rs
+++ b/crates/ai-memory-store/tests/suite/workstream_provenance.rs
@@@ -1,0 -1,531 +1,559 @@@
+ //! Provenance uses the configured privacy strip on writes and legacy reads.
+
+ use ai_memory_core::{AgentKind, NewWorkstreamEvent, WorkstreamEventKind};
+ use ai_memory_store::{FinishWorkstreamRun, PrepareWorkstreamRun, Store, WorkstreamSelection};
+ use rusqlite::{Connection, params};
+ use serde_json::{Value, json};
+
+ fn event(id: &str, source: &str, metadata: Value) -> NewWorkstreamEvent {
+ NewWorkstreamEvent {
+ event_id: id.into(),
+ agent: AgentKind::Codex,
+ native_session_id: "native-1".into(),
+ source_record_id: Some(source.into()),
+ kind: WorkstreamEventKind::ToolResult,
+ role: Some("tool".into()),
+ content: "portable provenance sentinel".into(),
+ occurred_at: None,
+ metadata,
+ }
+ }
+
+ async fn prepare(store: &Store) -> ai_memory_store::PreparedWorkstreamRun {
+ let workspace_id = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let project_id = store
+ .writer
+ .get_or_create_project(workspace_id, "managed", None)
+ .await
+ .unwrap();
+ store
+ .writer
+ .prepare_workstream_run(PrepareWorkstreamRun {
+ workspace_id,
+ project_id,
+ repo_fingerprint: "repo".into(),
+ worktree_fingerprint: "worktree".into(),
+ cwd: "/repo".into(),
+ agent: AgentKind::Codex,
+ automatic_harness: false,
+ available_agents: Vec::new(),
+ selection: WorkstreamSelection::Current,
+ lease_owner: "test".into(),
+ })
+ .await
+ .unwrap()
+ }
+
+ fn finish(
+ run_id: ai_memory_core::ManagedRunId,
+ events: Vec<NewWorkstreamEvent>,
+ ) -> FinishWorkstreamRun {
+ FinishWorkstreamRun {
+ sanitizer: ai_memory_core::Sanitizer::default(),
+ run_id,
+ native_session_id: Some("native-1".into()),
+ source_cursor: None,
+ events,
+ complete: false,
+ segment_path: None,
+ exit_code: None,
+ }
+ }
+
+ #[tokio::test]
+ async fn workstream_provenance_is_bounded_scrubbed_and_idempotent_before_storage() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let run = prepare(&store).await;
+ // The credential crosses the cap: truncate-before-scrub would leak it.
+ let hostile = format!("{}sk-{}\u{1b}[31m", "é".repeat(250), "a".repeat(40));
+ let oversized = format!("{}-one", "é".repeat(600));
+ let batch = finish(
+ run.run_id,
+ vec![
+ event(
+ "hostile",
+ &hostile,
+ json!({
+ "tool": "Read", "tool_call_id": "call-1", "parent_id": "record-0",
+ "is_error": false, "status": "completed", "summary_type": "branch_summary",
+ "tool_use_id": "sk-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "exit_code": 0, "loss_count": 2,
+ "unknown": {"prompt": "private dump"}, "authority": "root",
+ }),
+ ),
+ event(
+ "oversized-one",
+ &oversized,
+ json!({"tool": ["private dump"]}),
+ ),
+ event(
+ "oversized-two",
+ &oversized.replace("-one", "-two"),
+ json!({}),
+ ),
+ event("legitimate", "record-1", json!({"tool_call_id": "call-1"})),
+ ],
+ );
+ assert_eq!(
+ store
+ .writer
- .finish_workstream_run(batch.clone())
++ .finish_workstream_run(local_authority(), batch.clone())
+ .await
+ .unwrap()
+ .imported_events,
+ 4
+ );
+ assert_eq!(
+ store
+ .writer
- .finish_workstream_run(batch)
++ .finish_workstream_run(local_authority(), batch)
+ .await
+ .unwrap()
+ .imported_events,
+ 0
+ );
+ let conn = Connection::open(store.db_path()).unwrap();
+ let (source, metadata): (String, String) = conn.query_row(
+ "SELECT source_record_id, metadata_json FROM workstream_events WHERE event_id = 'hostile'",
+ [], |row| Ok((row.get(0)?, row.get(1)?)),
+ ).unwrap();
+ assert!(!source.contains("sk-"), "source id leaked a credential");
+ assert!(!source.contains('\u{1b}'));
+ assert!(source.len() <= 512);
+ let metadata: Value = serde_json::from_str(&metadata).unwrap();
+ assert!(metadata.get("unknown").is_none());
+ assert!(metadata.get("authority").is_none());
+ assert_eq!(metadata["tool"], "Read");
+ assert_eq!(metadata["tool_call_id"], "call-1");
+ assert_eq!(metadata["parent_id"], "record-0");
+ assert_eq!(metadata["summary_type"], "branch_summary");
+ assert_eq!(metadata["is_error"], false);
+ assert_eq!(metadata["status"], "completed");
+ assert_eq!(metadata["exit_code"], 0);
+ assert_eq!(metadata["loss_count"], 2);
+ assert!(!metadata["tool_use_id"].as_str().unwrap().contains("sk-"));
+ for query in ["", "portable"] {
+ let hits = store
+ .reader
+ .search_workstream_events(
+ run.workstream_id,
+ query.into(),
+ 10,
+ ai_memory_core::Sanitizer::default(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ hits.len(),
+ 4,
+ "distinct event ids must survive source-id truncation"
+ );
+ let hit = serde_json::to_value(
+ hits.iter()
+ .find(|hit| hit.event_id == "legitimate")
+ .unwrap(),
+ )
+ .unwrap();
+ assert_eq!(hit["source_record_id"], "record-1");
+ assert_eq!(hit["metadata"]["tool_call_id"], "call-1");
+ for hit in hits
+ .iter()
+ .filter(|hit| hit.event_id.starts_with("oversized"))
+ {
+ assert!(hit.source_record_id.as_ref().unwrap().len() <= 512);
+ assert!(hit.metadata.is_null());
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn workstream_provenance_legacy_reads_strip_secrets_and_unknown_metadata() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let run = prepare(&store).await;
+ store
+ .writer
- .finish_workstream_run(finish(
- run.run_id,
- vec![event("legacy", "record-1", json!({}))],
- ))
++ .finish_workstream_run(
++ local_authority(),
++ finish(run.run_id, vec![event("legacy", "record-1", json!({}))]),
++ )
+ .await
+ .unwrap();
+ // Simulate rows written before provenance was scrubbed at ingress.
+ let conn = Connection::open(store.db_path()).unwrap();
+ conn.execute("UPDATE workstream_events SET source_record_id = ?1, metadata_json = ?2 WHERE event_id = 'legacy'",
+ params!["sk-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", json!({"parent_id": "record-0", "tool_call_id": "sk-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "dump": "private"}).to_string()]).unwrap();
+ for query in ["", "portable"] {
+ let hits = store
+ .reader
+ .search_workstream_events(
+ run.workstream_id,
+ query.into(),
+ 10,
+ ai_memory_core::Sanitizer::default(),
+ )
+ .await
+ .unwrap();
+ let hit = serde_json::to_value(&hits[0]).unwrap();
+ assert!(
+ hit["source_record_id"].as_str().is_some(),
+ "legacy provenance must be returned safely"
+ );
+ assert!(!hit.to_string().contains("sk-"));
+ assert_eq!(hit["metadata"]["parent_id"], "record-0");
+ assert!(hit["metadata"].get("dump").is_none());
+ }
+ for malformed in ["not JSON".to_string(), "x".repeat(16 * 1024 + 1)] {
+ conn.execute(
+ "UPDATE workstream_events SET metadata_json = ?1 WHERE event_id = 'legacy'",
+ params![malformed],
+ )
+ .unwrap();
+ let hits = store
+ .reader
+ .search_workstream_events(
+ run.workstream_id,
+ "portable".into(),
+ 10,
+ ai_memory_core::Sanitizer::default(),
+ )
+ .await
+ .unwrap();
+ assert!(hits[0].metadata.is_null());
+ assert!(!hits[0].source_record_id.as_ref().unwrap().contains("sk-"));
+ }
+ }
+
+ #[tokio::test]
+ async fn workstream_provenance_reused_event_id_retains_data_and_refuses_identity_change() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let run = prepare(&store).await;
+ let first = event("stable-id", "record-1", json!({"tool_call_id": "call-1"}));
+ store
+ .writer
- .finish_workstream_run(finish(run.run_id, vec![first.clone()]))
++ .finish_workstream_run(local_authority(), finish(run.run_id, vec![first.clone()]))
+ .await
+ .unwrap();
+ let mut reused = first.clone();
+ reused.source_record_id = Some("record-2".into());
+ reused.content = "different source content".into();
+ reused.metadata = json!({"tool_call_id": "call-2"});
+ reused.role = Some("assistant".into());
+ reused.occurred_at = Some("2026-10-02T00:00:00Z".into());
+ assert_eq!(
+ store
+ .writer
- .finish_workstream_run(finish(run.run_id, vec![reused.clone()]))
++ .finish_workstream_run(local_authority(), finish(run.run_id, vec![reused.clone()]))
+ .await
+ .unwrap()
+ .imported_events,
+ 0
+ );
+ reused.kind = WorkstreamEventKind::Message;
+ assert!(matches!(
+ store
+ .writer
- .finish_workstream_run(finish(
- run.run_id,
- vec![event("new-before-collision", "record-3", json!({})), reused,]
- ))
++ .finish_workstream_run(
++ local_authority(),
++ finish(
++ run.run_id,
++ vec![event("new-before-collision", "record-3", json!({})), reused,]
++ )
++ )
+ .await,
+ Err(ai_memory_store::StoreError::InvalidState(_))
+ ));
+ let hits = store
+ .reader
+ .search_workstream_events(
+ run.workstream_id,
+ "".into(),
+ 10,
+ ai_memory_core::Sanitizer::default(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ hits.len(),
+ 1,
+ "the rejected batch must roll back earlier inserts"
+ );
+ assert_eq!(hits[0].content, first.content);
+ assert_eq!(hits[0].source_record_id, first.source_record_id);
+ assert_eq!(hits[0].metadata, first.metadata);
+ assert_eq!(hits[0].role, first.role);
+ assert_eq!(hits[0].occurred_at, first.occurred_at);
+ assert_eq!(
+ store
+ .writer
- .finish_workstream_run(finish(run.run_id, vec![first]))
++ .finish_workstream_run(local_authority(), finish(run.run_id, vec![first]))
+ .await
+ .unwrap()
+ .imported_events,
+ 0
+ );
+ }
+
+ #[tokio::test]
+ async fn workstream_provenance_finished_run_ignores_late_events() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let run = prepare(&store).await;
+ let first = event("stable-id", "record-1", json!({"tool_call_id": "call-1"}));
+ let mut batch = finish(run.run_id, vec![first]);
+ batch.complete = true;
+ assert_eq!(
+ store
+ .writer
- .finish_workstream_run(batch.clone())
++ .finish_workstream_run(local_authority(), batch.clone())
+ .await
+ .unwrap()
+ .imported_events,
+ 1
+ );
+ assert_eq!(
+ store
+ .writer
- .finish_workstream_run(batch.clone())
++ .finish_workstream_run(local_authority(), batch.clone())
+ .await
+ .unwrap()
+ .imported_events,
+ 0
+ );
+ batch.events[0].source_record_id = Some("record-2".into());
+ batch
+ .events
+ .push(event("late-new-event", "record-3", json!({})));
- let result = store.writer.finish_workstream_run(batch).await.unwrap();
++ let result = store
++ .writer
++ .finish_workstream_run(local_authority(), batch)
++ .await
++ .unwrap();
+ assert_eq!(result.imported_events, 0);
+ assert_eq!(result.latest_sequence, 1);
+ let hits = store
+ .reader
+ .search_workstream_events(
+ run.workstream_id,
+ String::new(),
+ 10,
+ ai_memory_core::Sanitizer::default(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(hits.len(), 1);
+ assert_eq!(hits[0].source_record_id.as_deref(), Some("record-1"));
+ }
+
+ #[tokio::test]
+ async fn workstream_provenance_replay_survives_sanitizer_changes() {
+ let token = format!("sk-{}", "a".repeat(40));
+ for (source, old_config, new_config) in [
+ (
+ "private-correlation".to_string(),
+ ai_memory_core::SanitizeConfig {
+ extra_patterns: Vec::new(),
+ allowlist: Vec::new(),
+ },
+ ai_memory_core::SanitizeConfig {
+ extra_patterns: vec!["private-correlation".into()],
+ allowlist: Vec::new(),
+ },
+ ),
+ (
+ token.clone(),
+ ai_memory_core::SanitizeConfig {
+ extra_patterns: Vec::new(),
+ allowlist: vec![token],
+ },
+ ai_memory_core::SanitizeConfig {
+ extra_patterns: Vec::new(),
+ allowlist: Vec::new(),
+ },
+ ),
+ ] {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let run = prepare(&store).await;
+ let mut original = event("stable-id", &source, json!({"parent_id": source}));
+ original.content = format!("portable {source}");
+ let mut batch = finish(run.run_id, vec![original.clone()]);
+ batch.sanitizer = ai_memory_core::Sanitizer::new(&old_config).unwrap();
+ batch.events[0].content = batch.sanitizer.scrub(&original.content);
+ assert_eq!(
+ store
+ .writer
- .finish_workstream_run(batch.clone())
++ .finish_workstream_run(local_authority(), batch.clone())
+ .await
+ .unwrap()
+ .imported_events,
+ 1
+ );
+ let conn = Connection::open(store.db_path()).unwrap();
+ let read_raw = || {
+ conn.query_row(
+ "SELECT content, source_record_id, metadata_json FROM workstream_events WHERE event_id = 'stable-id'",
+ [], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?, row.get::<_, String>(2)?)),
+ ).unwrap()
+ };
+ let first = read_raw();
+ batch.sanitizer = ai_memory_core::Sanitizer::new(&new_config).unwrap();
+ batch.events[0].content = batch.sanitizer.scrub(&original.content);
+ assert_ne!(batch.events[0].content, first.0);
+ assert_eq!(
+ store
+ .writer
- .finish_workstream_run(batch.clone())
++ .finish_workstream_run(local_authority(), batch.clone())
+ .await
+ .unwrap()
+ .imported_events,
+ 0
+ );
+ assert_eq!(
+ read_raw(),
+ first,
+ "replay must retain the first stored version"
+ );
+ let hits = store
+ .reader
+ .search_workstream_events(
+ run.workstream_id,
+ String::new(),
+ 10,
+ batch.sanitizer.clone(),
+ )
+ .await
+ .unwrap();
+ assert!(!hits[0].source_record_id.as_ref().unwrap().contains(&source));
+ assert!(!hits[0].metadata.to_string().contains(&source));
+ batch.events[0].kind = WorkstreamEventKind::Message;
+ assert!(matches!(
- store.writer.finish_workstream_run(batch).await,
++ store
++ .writer
++ .finish_workstream_run(local_authority(), batch)
++ .await,
+ Err(ai_memory_store::StoreError::InvalidState(_))
+ ));
+ }
+ }
+
+ #[tokio::test]
+ async fn workstream_provenance_replay_preserves_legacy_rows_above_bounds() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let run = prepare(&store).await;
+ let mut original = event(
+ "legacy",
+ &"s".repeat(2048),
+ json!({"parent_id": "p".repeat(2048), "dump": "x".repeat(20 * 1024)}),
+ );
+ original.content = "portable ".repeat(4096);
+ store
+ .writer
- .finish_workstream_run(finish(run.run_id, vec![original.clone()]))
++ .finish_workstream_run(
++ local_authority(),
++ finish(run.run_id, vec![original.clone()]),
++ )
+ .await
+ .unwrap();
+ let conn = Connection::open(store.db_path()).unwrap();
+ // Legacy data can exceed today's write bounds; replay must not rewrite it.
+ conn.execute("UPDATE workstream_events SET content = ?1, source_record_id = ?2, metadata_json = ?3 WHERE event_id = 'legacy'",
+ params![original.content, original.source_record_id, original.metadata.to_string()]).unwrap();
+ assert_eq!(
+ store
+ .writer
- .finish_workstream_run(finish(run.run_id, vec![original.clone()]))
++ .finish_workstream_run(
++ local_authority(),
++ finish(run.run_id, vec![original.clone()])
++ )
+ .await
+ .unwrap()
+ .imported_events,
+ 0
+ );
+ let raw: (String, String, String) = conn.query_row(
+ "SELECT content, source_record_id, metadata_json FROM workstream_events WHERE event_id = 'legacy'",
+ [], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
+ ).unwrap();
+ assert_eq!(
+ raw,
+ (
+ original.content,
+ original.source_record_id.unwrap(),
+ original.metadata.to_string()
+ )
+ );
+ for query in ["", "portable"] {
+ let hits = store
+ .reader
+ .search_workstream_events(
+ run.workstream_id,
+ query.into(),
+ 10,
+ ai_memory_core::Sanitizer::default(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(hits.len(), 1);
+ assert_eq!(hits[0].source_record_id.as_ref().unwrap().len(), 512);
+ assert!(hits[0].metadata.is_null());
+ }
+ }
+
+ #[tokio::test]
+ async fn workstream_provenance_retry_with_marker_matching_pattern_is_idempotent() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let run = prepare(&store).await;
+ let mut batch = finish(
+ run.run_id,
+ vec![event(
+ "stable-id",
+ "custom-source",
+ json!({"parent_id": "custom-parent"}),
+ )],
+ );
+ // Valid operator patterns can also match the scrubber's own markers.
+ batch.sanitizer = ai_memory_core::Sanitizer::new(&ai_memory_core::SanitizeConfig {
+ extra_patterns: vec!["custom".into()],
+ allowlist: Vec::new(),
+ })
+ .unwrap();
+ assert_eq!(
+ store
+ .writer
- .finish_workstream_run(batch.clone())
++ .finish_workstream_run(local_authority(), batch.clone())
+ .await
+ .unwrap()
+ .imported_events,
+ 1
+ );
+ assert_eq!(
+ store
+ .writer
- .finish_workstream_run(batch)
++ .finish_workstream_run(local_authority(), batch)
+ .await
+ .unwrap()
+ .imported_events,
+ 0
+ );
+ }
++
++/// A single-user (no database users) caller: the finish gate admits it, so
++/// these provenance tests exercise only the storage boundary.
++fn local_authority() -> ai_memory_store::WorkstreamFinishAuthority {
++ ai_memory_store::WorkstreamFinishAuthority::from_auth(
++ ai_memory_core::AuthLevel::Anonymous,
++ None,
++ None,
++ &ai_memory_core::ActorContext::anonymous(),
++ false,
++ )
++}
diff --cc docs/security-boundaries.md
index 5de58448,c2270b69..94b320e3
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@@ -59,12 -63,14 +63,15 @@@ boundary not yet built
| 11e | Native self-upgrade archive confinement (#1025) | `ai-memory-cli/src/commands/upgrade.rs` normalizes every tar/zip path, rejects links and special entries, extracts only the binary and `hooks/`, accepts only the exact non-runtime support layout emitted by `release.yml`, and caps both entry count and declared expanded bytes before writing | `upgrade.rs` `release_workflow_support_assets_are_exact_and_ignored` (shipped support paths admitted, near-miss docs/packaging/template paths refused), `extracts_archive_built_like_release_yml` and `extracts_zip_happy_path_with_hooks` (real workflow-shaped archives succeed but support assets are not written), `validate_rejects_path_traversal`, `zip_extract_rejects_path_traversal`, `tar_extract_rejects_declared_expansion_past_limit`, with binary/hooks extraction as the legitimate control | STRONG |
| 11f | Native hook executable-path integrity after self-replacement (#1027) | `ai-memory-cli/src/commands/render_shared.rs` `hook_embedded_exe_path` is the single executable resolver for every persisted native hook form (POSIX/Windows command, Windows exec, Zero, ZCode, OpenCode 2 assistant capture): it prefers an existing literal path, strips Linux's trailing ` (deleted)` procfs marker only when the stripped installed binary exists, and otherwise falls back to the platform command name. Upgrade keeps the already-loaded config and refreshes in-process | `render_shared.rs` `embedded_exe_strips_the_marker_when_the_stripped_path_exists`, `embedded_exe_preserves_a_real_file_whose_name_has_the_marker_suffix`, `embedded_exe_falls_back_when_the_resolved_path_is_missing`, `hook_embedded_exe_path_names_an_existing_file_without_marker`; `upgrade_e2e.rs` `native_upgrade_refreshes_hooks_without_a_deleted_path_or_losing_cli_data_dir` reproduces the replacement window through the shipped binary, plants the corrupt suffix, and proves refresh removes it while preserving a CLI-only data dir | STRONG on Linux reproduction plus platform-neutral resolver/render coverage; Windows path rendering remains covered by its existing command/exec tests and full Windows CI |
| 11g | Cross-project file attribution cannot bypass destination capture or server routing (#932) | `ai-memory-hooks/src/capture_policy.rs` `absolute_file_tool_paths` accepts only bounded, recognized, absolute file-tool candidates; `ai-memory-cli/src/commands/hook.rs` `file_tool_routing_cwd` requires every path to prove the same repository/marker boundary and resolves that destination before capture policy, server profile, scope hints, or spool credentials. Relative, mixed-project, unsupported, and arbitrary non-project paths keep the payload cwd | `hook.rs` `absolute_file_target_uses_destination_scope_and_capture_policy` (hostile content under the destination exclusion is never spooled; a public control is routed there), `absolute_file_target_cannot_escape_a_destination_server_profile` (unregistered destination profile drops instead of falling back to source/install default), `file_target_routing_refuses_relative_external_and_mixed_project_paths` | STRONG for native `ai-memory hook`; generated and compatibility hooks retain cwd-only routing |
+ | 11h | Docker-wrapper capture-policy capability (#1002) | `bin/ai-memory` routes ordinary Linux/macOS `install-hooks` and upgrade refreshes through the stable checksum-verified native host client, so the hook process executes the capture-policy boundary in 11b before spool/network. Only an explicit `AI_MEMORY_HOOK_PLATFORM=posix|windows` retains the documented script compatibility path and its warning; `AI_MEMORY_NATIVE_BIN` may not point back to the wrapper | `scripts/check-native-packaging.sh` `Checking host-launch wrapper routing`: a default allowlist install reaches the fake native client while a Docker executable that always fails proves no container fallback occurred; the explicit `posix` control reaches fake Docker and adds no native invocation; the self-referential native override is refused | STRONG on the shipped Linux/macOS wrapper. Windows and remote/manual script installers remain explicitly outside capture-policy v1 |
| 12 | Network/auth posture | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer`; `serve.rs` mounts `/identity` inside the host and machine-auth gates even with web disabled; `nix/nixos-module.nix` treats only literal `127.0.0.1`/`::1` as loopback, requires exactly one secret environment source for other binds, keeps secret auth and `llm_headers` values out of the Nix store, and brackets IPv6 in `ExecStart` | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401; `serve.rs` `machine_identity_remains_authenticated_with_web_disabled_and_expired_keys` (wrong and expired keys refused, valid machine key accepted, web remains disabled); `flake.nix` `nixos-module-eval` refuses `localhost` and `0.0.0.0` without a secret source, refuses two secret sources, `settings.auth` secrets, and `settings.llm_headers`, with literal IPv4/IPv6 loopback and one-source controls | STRONG |
- | 13 | Managed-run transcript attribution (concurrent launches in one checkout, invariant #16) | `ai-memory-store/src/workstream.rs` `link_native_session` stamps `native_session_linked_at` on its own run only, both `finish` updates drop the stamp when the session changes, `run_status` reports it; `ai-memory-cli/src/commands/run.rs` `resolve_native_session_after_run` takes a linked session only when `ai-memory-workstream` `native_session_in_checkout` holds it for this checkout (OpenCode by recorded directory), never falls back to a link it set aside, and turns an `AmbiguousNativeSession` into a warning with nothing imported; `ai-memory-workstream/src/transcript.rs` `discover_crush` claims only the one top-level session created (or, with `--continue`, touched) during the run, and in a data directory outside the project only one that edited a file in it | `multi_session.rs` `a_session_linked_by_one_managed_run_is_not_another_runs`; `run.rs` `a_session_linked_during_the_run_wins_over_discovery` (concurrent newer session, another checkout's link refused, no fallback to it, unlinked control); `transcript.rs` `native_session_in_checkout_checks_the_opencode_directory`; `store/src/lib.rs` `managed_run_status_reports_a_link_made_during_the_run`; `run.rs` `ambiguous_crush_discovery_keeps_the_run`; `transcript.rs` `crush_discovery_claims_only_the_session_the_run_created`, `crush_discovery_in_a_shared_store_claims_only_an_edit_here` | PARTIAL: a run whose child links nothing still falls back to discovering the newest session in the checkout; Crush, which has no hooks, relies on that discovery alone and claims nothing when it is ambiguous |
+ | 12b | Managed-workstream provenance privacy, stable replay identity and server event namespace | `ai-memory-core/src/workstream.rs` `scrub_workstream_provenance`; `ai-memory-hooks/src/workstream.rs` `finish_run` reserved client-id check and `sanitize_events` before immutable segments; `ai-memory-store/src/workstream.rs` `finish_run` stable identity check and `stored_event`, using an explicitly supplied configured sanitizer; no changes to the typed observation boundary | `store/tests/suite/workstream_provenance.rs` `workstream_provenance_is_bounded_scrubbed_and_idempotent_before_storage` (hostile and oversized source ids, unknown metadata, legitimate correlation, retry and distinct event ids), `workstream_provenance_legacy_reads_strip_secrets_and_unknown_metadata` (search and tail, malformed/oversized legacy JSON), `workstream_provenance_reused_event_id_retains_data_and_refuses_identity_change` (first indexed version retained, identity refusal and batch rollback), `workstream_provenance_replay_survives_sanitizer_changes` (new extra patterns and removal of a built-in-pattern allowlist exemption, with identity-refusal control), `workstream_provenance_replay_preserves_legacy_rows_above_bounds`, `workstream_provenance_finished_run_ignores_late_events`, `workstream_provenance_retry_with_marker_matching_pattern_is_idempotent`; `hooks` `workstream_provenance_finish_scrubs_before_raw_segment_and_search` (custom sanitizer, immutable segment, SQL recovery and finished-run no-op), `workstream_provenance_client_cannot_use_server_event_ids` (reserved ids refused before raw writes, normal client event and server-generated checkpoint/loss controls); `cli/tests/suite/workstream_provenance.rs` (text/JSON and old server DTOs) | STRONG: privacy, stable-identity and reserved-namespace regressions fail with their guards bypassed; an isolated allowlist bypass fails on the unknown key, and bypassing the raw-id search authorization returns 200 where its test requires 403. No provenance is emitted in startup packets, and old raw segments are not rewritten |
+ | 13 | Managed-run transcript attribution (concurrent launches in one checkout, invariant #16) | `ai-memory-store/src/workstream.rs` `link_native_session` stamps `native_session_linked_at` on its own run only, both `finish` updates drop the stamp when the session changes, `run_status` reports it; `ai-memory-cli/src/commands/run.rs` `resolve_native_session_after_run` takes a linked session only when `ai-memory-workstream` `native_session_in_checkout` holds it for this checkout (OpenCode by recorded directory), never falls back to a link it set aside, and turns an `AmbiguousNativeSession` into a warning with nothing imported; for Claude it moves the run's own session to a background session only when `ai-memory-workstream` `claude_attached_background_session` finds a `sessionKind: "bg"` record that names that exact session as its attached client and this checkout as `cwd` (#1050); `ai-memory-workstream/src/transcript.rs` `discover_crush` claims only the one top-level session created (or, with `--continue`, touched) during the run, and in a data directory outside the project only one that edited a file in it | `multi_session.rs` `a_session_linked_by_one_managed_run_is_not_another_runs`; `run.rs` `a_session_linked_during_the_run_wins_over_discovery` (concurrent newer session, another checkout's link refused, no fallback to it, unlinked control); `transcript.rs` `claude_attached_background_session_follows_only_this_checkouts_bg_records` (a concurrent launch's background session, another checkout's, and a non-background record refused; own attachment control); `run.rs` `a_claude_run_that_attached_to_a_background_session_follows_it`; `transcript.rs` `native_session_in_checkout_checks_the_opencode_directory`; `store/src/lib.rs` `managed_run_status_reports_a_link_made_during_the_run`; `run.rs` `ambiguous_crush_discovery_keeps_the_run`; `transcript.rs` `crush_discovery_claims_only_the_session_the_run_created`, `crush_discovery_in_a_shared_store_claims_only_an_edit_here` | PARTIAL: a run whose child links nothing still falls back to discovering the newest session in the checkout; Crush, which has no hooks, relies on that discovery alone and claims nothing when it is ambiguous |
| 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 |
+ | 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` (foreign raw workstream id refuses populated provenance; granted reader receives the source record and tool correlation); `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 |
+ | 14aa | Companion capture privacy before persistence and delivery | `companions/ai-memory-client/src/lib.rs` `reject_sensitive`, `sanitize_external_value`, `check_body`; `src/scrub.rs` `sanitize_external_text`; relay `identity::validate`, `check_scope`, `relay::init` and `flush_locked`; importer `plan_external_conversation`, `planned_hook_event`, `truncate_utf8`, `ImportClient::post_hook_batch` | SDK secret-position, nested key, numeric metric (11 names plus numeric `*_tokens` counts; string values still redact), bounded schema and literal-marker tests; relay `sensitive_envelope_is_rejected_before_enqueue_with_clean_control`, `new_native_bodies_are_sanitized_before_hash_enqueue_and_exact_retry`, `unsafe_legacy_pending_is_dropped_locally_and_never_blocks_its_session`, `unsafe_legacy_native_identity_is_dropped_and_its_session_continues`, `legacy_binding_scope_spaces_are_preserved_on_delivery`; importer `sensitive_native_identity_is_refused_before_manifest_and_http_with_unicode_control`, `shared_key_sanitation_precedes_plan_manifest_transport_and_exact_retry`, `preview_and_manifest_use_scrubbed_bodies_and_digest`, `forged_body_authority_is_refused_before_transport`, `sanitized_redaction_markers_survive_utf8_byte_caps_in_bodies_and_titles`. Controls preserve opaque native Unicode IDs, metric representation and untrusted provenance. An unsafe item queued before these checks never reaches the wire (body or request line); it leaves the queue as a local `dropped_policy` receipt so the rest of its session ships. Guard-removal runtime probes target the final formatted sources and restore identical hashes. | Client-side privacy only; server scope, auth, admission and capture-policy guards remain authoritative |
+| 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 |