Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
Merge pull request #1354 from lhzapata/fix/oidc-issuer-https
AkitaOnRails499ee1e90bfb
diff --cc CHANGELOG.mdindex 56e12516,3aa320d8..44604fa1--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -12,28 -12,11 +12,33 @@@ version in [`docs/changelog/`](docs/cha## [Unreleased]### Fixed-- Fixed `ai-memory auth login oidc-device` sending the device code and the- issued tokens in clear text when the discovery document advertised a- plain-`http` device or token endpoint, or when the issuer itself was- plain `http`. The issuer and both endpoints must now use `https`; plain- `http` is still accepted on `localhost`, `127.0.0.1` and `::1` (#1354).++- Fixed OIDC device login and refresh sending credential-bearing requests to++ non-TLS endpoints. Issuers and advertised or persisted device/token endpoints++ must now use `https` outside loopback, and authentication requests do not++ follow redirects. Plain `http` remains available for local test issuers on++ `localhost`, `127.0.0.1` and `::1`. (#1354)+- Fixed `install-instructions` printing a false "Claude Code reads <file> instead+ of AGENTS.md" note when `$HOME` is reached through a symlink. The home+ `.claude/CLAUDE.md` skip now compares with the same canonicalising+ `paths_match` helper the import check uses, so a symlinked home matches its+ resolved path. (#1345)+- Corrected stale claims in `docs/comparison.md` and `docs/competitive-parity.md`+ that said Windows has no service step and the Windows install is experimental.+ The 3.1 `install.ps1` + `setup` Windows service step is shipped production,+ not experimental; the "3.0 (unreleased)" observation-stream note is corrected+ to reflect the released 3.0 line. (#1271)+- Made the executable auto-improvement eval policy server-owned. Manual CLI and+ HTTP reviews now use `[auto_improve.eval]` from the server process, and legacy+ requests that try to supply an `eval` object fail closed with an upgrade+ message.+- Made managed cross-harness continuation survive quota exhaustion without a+ voluntary handoff. The startup packet now places its server-authored resume+ directive outside the untrusted transcript fence, and refreshed+ `CLAUDE.md` / `AGENTS.md` routing tells an incoming agent that "continue",+ "resume", and "pick up where we left off" must consult the private+ `AI_MEMORY_PREVIOUS_SESSION_HISTORY` dossier when the managed-run variables+ are present. The dossier remains untrusted evidence and stays local to the+ launcher machine.## [3.1.0] - 2026-10-16diff --cc crates/ai-memory-cli/src/auth_bearer.rsindex ef47c40b,ef47c40b..d7be7e35--- a/crates/ai-memory-cli/src/auth_bearer.rs+++ b/crates/ai-memory-cli/src/auth_bearer.rs@@@ -27,10 -27,10 +27,10 @@@ pub async fn resolve_bearer/// Returns the access token, or `None` when there is no token. Refresh failures/// fall back to the existing token because it may still be inside the provider's/// accepted clock-skew window.--pub async fn resolve_oidc(client: &reqwest::Client, auth_path: &Path) -> Option<String> {++pub async fn resolve_oidc(_client: &reqwest::Client, auth_path: &Path) -> Option<String> {let mut token = OidcToken::load(auth_path).ok().flatten()?;if token.needs_refresh() {-- let Ok(refreshed) = refresh_access_token(client, &token).await else {++ let Ok(refreshed) = refresh_access_token(&token).await else {return Some(token.access.expose_secret().to_string());};if refreshed.save(auth_path).is_err() {diff --cc crates/ai-memory-cli/src/commands/auth.rsindex d8ce8613,d8ce8613..5fe7b35a--- a/crates/ai-memory-cli/src/commands/auth.rs+++ b/crates/ai-memory-cli/src/commands/auth.rs@@@ -315,6 -315,6 +315,10 @@@ async fn run_copilot_device_flow(clientfn auth_http_client() -> Result<reqwest::Client> {reqwest::Client::builder()++ // Authentication requests can carry device codes, authorization codes,++ // refresh tokens, or issued credentials. Do not let an IdP redirect++ // those request bodies to a different URL or a TLS downgrade.++ .redirect(reqwest::redirect::Policy::none()).timeout(Duration::from_secs(60)).user_agent(format!("ai-memory/{}", env!("CARGO_PKG_VERSION"))).build()@@@ -557,4 -557,4 +561,39 @@@ mod testsfn expiry_status_does_not_print_exact_token_time() {assert_eq!(format_duration_until(0), "expired");}++++ #[tokio::test]++ async fn auth_client_never_forwards_credentials_through_redirects() {++ use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};++++ let target = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();++ let target_url = format!("http://{}/received", target.local_addr().unwrap());++ let source = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();++ let source_url = format!("http://{}/token", source.local_addr().unwrap());++ tokio::spawn(async move {++ let (mut stream, _) = source.accept().await.unwrap();++ let mut request = [0_u8; 4096];++ let _ = stream.read(&mut request).await;++ let response = format!(++ "HTTP/1.1 307 Temporary Redirect\r\nLocation: {target_url}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"++ );++ stream.write_all(response.as_bytes()).await.unwrap();++ });++++ let response = auth_http_client()++ .unwrap()++ .post(source_url)++ .form(&[("device_code", "synthetic-secret")])++ .send()++ .await++ .unwrap();++++ assert_eq!(response.status(), reqwest::StatusCode::TEMPORARY_REDIRECT);++ assert!(++ tokio::time::timeout(Duration::from_millis(100), target.accept())++ .await++ .is_err(),++ "an authentication request body reached the redirect target"++ );++ }}diff --cc crates/ai-memory-llm/src/oidc.rsindex a46543a1,eb0edf32..1675c350--- a/crates/ai-memory-llm/src/oidc.rs+++ b/crates/ai-memory-llm/src/oidc.rs@@@ -261,12 -296,12 +296,13 @@@ pub async fn poll_token_once/// # Errors/// Returns [`LlmError::Auth`] when the refresh grant is rejected (the caller/// should fall back to the stale token or prompt a re-login).--pub async fn refresh_access_token(-- client: &reqwest::Client,-- token: &OidcToken,--) -> LlmResult<OidcToken> {++pub async fn refresh_access_token(token: &OidcToken) -> LlmResult<OidcToken> {++ require_tls("token_endpoint", &token.extra.token_endpoint)?;++ let client = reqwest::Client::builder()++ .redirect(reqwest::redirect::Policy::none())++ .build()?;let token_response = refresh_grant::<OidcTokenResponse>(-- client,++ &client,&token.extra.token_endpoint,token.refresh.expose_secret(),&token.extra.client_id,@@@ -367,4 -402,116 +403,163 @@@ mod testslet ok = OidcToken::from_token_response(&resp, "iss", "cid", "tok", Some("old-refresh"));assert_eq!(ok.unwrap().refresh.expose_secret(), "old-refresh");}++ #[test]+ fn require_tls_accepts_https_and_loopback_http_only() {+ for (url, accepted) in [+ ("https://idp.example.com/realms/team", true),+ ("http://localhost:8080/realms/team", true),+ ("http://LOCALHOST:8080/realms/team", true),+ ("http://127.0.0.1:8080/realms/team", true),+ ("http://[::1]:8080/realms/team", true),+ ("http://idp.example.com/realms/team", false),+ ("http://localhost.example.com/realms/team", false),+ ("http://192.168.1.10:8080/realms/team", false),+ ("ftp://idp.example.com/realms/team", false),+ ("idp.example.com/realms/team", false),+ ] {+ assert_eq!(require_tls("issuer", url).is_ok(), accepted, "{url}");+ }+ }++ fn discovery_json(device: &str, token: &str) -> serde_json::Value {+ serde_json::json!({+ "device_authorization_endpoint": device,+ "token_endpoint": token,+ })+ }++ #[tokio::test]+ async fn discover_refuses_plain_http_issuer_before_any_request() {+ use wiremock::matchers::{method, path};+ use wiremock::{Mock, MockServer, ResponseTemplate};++ // The mock stands in for the remote issuer through an HTTP proxy, so+ // without the guard discovery would succeed instead of failing on DNS.+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path("/realms/team/.well-known/openid-configuration"))+ .respond_with(ResponseTemplate::new(200).set_body_json(discovery_json(+ "https://idp.example.com/device",+ "https://idp.example.com/token",+ )))+ .mount(&server)+ .await;+ let client = reqwest::Client::builder()+ .proxy(reqwest::Proxy::http(server.uri()).unwrap())+ .build()+ .unwrap();++ let err = discover(&client, "http://idp.example.com/realms/team")+ .await+ .expect_err("plain-http issuer off loopback must be refused");+ assert!(+ matches!(&err, LlmError::Auth(msg) if msg.contains("must use https")),+ "{err:?}"+ );+ let requests = server.received_requests().await.unwrap_or_default();+ assert!(requests.is_empty(), "discovery must not be fetched");+ }++ #[tokio::test]+ async fn discover_refuses_plain_http_endpoints_from_the_document() {+ use wiremock::matchers::{method, path};+ use wiremock::{Mock, MockServer, ResponseTemplate};++ for (device, token) in [+ (+ "https://idp.example.com/device",+ "http://idp.example.com/token",+ ),+ (+ "http://idp.example.com/device",+ "https://idp.example.com/token",+ ),+ ] {+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path("/.well-known/openid-configuration"))+ .respond_with(+ ResponseTemplate::new(200).set_body_json(discovery_json(device, token)),+ )+ .mount(&server)+ .await;++ let err = discover(&reqwest::Client::new(), &server.uri())+ .await+ .expect_err("plain-http endpoint off loopback must be refused");+ assert!(+ matches!(&err, LlmError::Auth(msg) if msg.contains("must use https")),+ "{device} {token}: {err:?}"+ );+ }+ }++ #[tokio::test]+ async fn discover_accepts_a_loopback_issuer_and_endpoints() {+ use wiremock::matchers::{method, path};+ use wiremock::{Mock, MockServer, ResponseTemplate};++ let server = MockServer::start().await;+ let device = format!("{}/device", server.uri());+ let token = format!("{}/token", server.uri());+ Mock::given(method("GET"))+ .and(path("/.well-known/openid-configuration"))+ .respond_with(ResponseTemplate::new(200).set_body_json(discovery_json(&device, &token)))+ .mount(&server)+ .await;++ let found = discover(&reqwest::Client::new(), &server.uri())+ .await+ .unwrap();+ assert_eq!(found.token_endpoint, token);+ assert_eq!(found.device_authorization_endpoint, device);+ }++++ #[tokio::test]++ async fn refresh_refuses_a_persisted_plain_http_remote_endpoint() {++ let mut token = sample();++ token.extra.token_endpoint = "http://idp.example.com/token".into();++++ let err = refresh_access_token(&token)++ .await++ .expect_err("a persisted remote http endpoint must fail before a request");++++ assert!(++ matches!(&err, LlmError::Auth(message) if message.contains("must use https")),++ "{err:?}"++ );++ }++++ #[tokio::test]++ async fn refresh_does_not_forward_the_refresh_token_through_redirects() {++ use wiremock::matchers::{method, path};++ use wiremock::{Mock, MockServer, ResponseTemplate};++++ let target = MockServer::start().await;++ let source = MockServer::start().await;++ Mock::given(method("POST"))++ .and(path("/token"))++ .respond_with(++ ResponseTemplate::new(307)++ .insert_header("Location", format!("{}/received", target.uri())),++ )++ .mount(&source)++ .await;++ let mut token = sample();++ token.extra.token_endpoint = format!("{}/token", source.uri());++++ refresh_access_token(&token)++ .await++ .expect_err("a token endpoint redirect is not followed");++++ assert!(++ target++ .received_requests()++ .await++ .unwrap_or_default()++ .is_empty(),++ "the persisted refresh token reached the redirect target"++ );++ }}diff --cc docs/install.mdindex 3140f873,791a81ae..f8550abf--- a/docs/install.md+++ b/docs/install.md@@@ -817,6 -817,10 +817,12 @@@ ai-memory auth login oidc-device--client-id "ai-memory-cli"```+ The issuer, and the device and token endpoints its discovery document lists,+ must use `https`. Plain `http` is accepted only on `localhost`, `127.0.0.1`-and `::1`, for a local test issuer.++and `::1`, for a local test issuer. Authentication requests do not follow++redirects, and refresh revalidates the token endpoint stored by older releases++before sending a refresh token.+The stored OIDC access token is also used by thin-client HTTP commands(`status`, `search`, `read-page`, `write-page`, `backup`, `embed`, andsimilar) when no static `AI_MEMORY_AUTH_TOKEN` / `[auth].bearer_token` isdiff --cc docs/security-boundaries.mdindex 512c4114,356c946c..9fbb3dbd--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@@ -96,6 -95,7 +96,7 @@@ means the boundary is not built yet| 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, with `sanitize_events` and `append_boundary_events` scrubbing event/checkpoint/losses content *before* the 64 KiB cap so a cap-straddling secret is never cut into an unmatchable prefix (#1113); `ai-memory-store/src/workstream.rs` `finish_run` stable identity check and `stored_event`, scrubbing content with the explicitly supplied configured sanitizer before its 16 KiB store-boundary bound; 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`, `workstream_content_is_scrubbed_before_the_store_cap` (a credential straddling the 16 KiB store cap is redacted, not persisted as an unmatchable prefix; benign control verbatim; #1113); `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), `finish_run_scrubs_event_content_before_the_byte_cap` and `finish_run_scrubs_boundary_events_before_the_byte_cap` (a credential straddling the 64 KiB event cap is redacted in the raw segment and never reaches the index; checkpoint/losses and benign controls; #1113); `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 || 12c | Browser cross-origin writes refused on an unauthenticated server (a foreign page in the operator's browser, DNS rebinding, and a LAN host where browsers send no fetch metadata) | `serve.rs` `refuse_cross_origin_browser_requests` / `is_cross_origin_browser_request`, layered on the machine (`/mcp`, `/hook*`, `/handoff`, `/workstream/*`, `/identity`) and admin (`/admin/*`) routes when auth is off: `Sec-Fetch-Site` other than `same-origin`/`none` → 403, or, without fetch metadata, an `Origin` whose authority is not the `Host` → 403; and `is_non_script_browser_request`: any `Sec-Fetch-Dest` other than `empty` (case-insensitive; non-UTF-8 refused) → 403 whatever `Sec-Fetch-Site` says, so links, images, navigations, iframes and form posts are refused even as `same-origin` or `none`. Browsers send fetch metadata over plain HTTP only to a potentially trustworthy host, so on any other `Host` (a LAN address or name in the allowlist, `0.0.0.0`, `host.docker.internal`; `is_loopback_host` admits only `localhost`, `*.localhost`, `127.0.0.0/8` and `[::1]`) `handoff_fetch_lacks_client_marker` also refuses `GET`/`HEAD /handoff` without a non-empty `X-AI-Memory-Client` header (`ai_memory_hooks::CLIENT_MARKER_HEADER`) → 403 whose body names both remedies (re-stage hooks, or set a bearer token). A page cannot add that header without a preflight these routes never answer. `/handoff` is the one state-changing `GET` on these routes; the other `GET`s are reads a foreign page cannot see the answer to, and every cross-origin `POST` carries `Origin`. Every first-party client sends the marker: the native hook (`hook_capture.rs` `post_hook`/`post_batch`/`get_handoff`), CLI subcommands (`http_client.rs` `ServerEndpoint::authenticate`), every curl in `hooks/_lib.sh`, both header tables in `hooks/lib/ai-memory-hook.ps1`, and the generated TypeScript integrations (`render_shared.rs` `ts_auth_headers_fn` plus the spool drain). Loopback hosts keep accepting a fetch without it, so hooks staged before the header existed still work on a default install, except that a request carrying any proxy forwarding header (`Forwarded`, `X-Forwarded-For`/`-Host`/`-Proto`/`-Server`/`-Port`, `X-Original-Forwarded-For`, `X-Real-IP`, `X-Client-IP`, `CF-Connecting-IP`, `True-Client-IP`, `Via`; `PROXY_HEADERS`) counts as non-loopback, since a plain-HTTP proxy can rewrite `Host` to loopback while the browser behind it sent no fetch metadata. No first-party client sends those headers. Hooks, the CLI and MCP clients send none of these headers; the web UI's same-origin `/admin/pending-writes` calls are `fetch()` (`Sec-Fetch-Dest: empty`) and pass. Behind it, axum `Json` and rmcp's `Content-Type: application/json` check refuse the preflight-free content types (`text/plain`, form-urlencoded, multipart) with 415; `require_allowed_host` (and rmcp `allowed_hosts` on `/mcp`) refuses a rebinding `Host`; machine/admin routes carry no CORS layer, so a preflight never comes back permissive. A stored wiki page viewed in the built-in web UI could otherwise turn the guard's same-origin allowance into a claim: `ai-memory-web/src/markdown.rs` `safe_image_url` / `is_safe_image_target` render as `#` any image target that is root-relative, a network path, carries a `..` segment (also percent-encoded), or, for a UI mounted at the base-path root, starts with a server route segment Every `/web` surface (built-in pages including `/web/pending`, the login page, a custom SPA and `/api/v1`) answers `X-Frame-Options: DENY` and `Content-Security-Policy: frame-ancestors 'none'` (`ai-memory-web/src/mount.rs` `deny_framing`), because a framed page's own Approve/Reject `fetch()` is same-origin and the guard rightly lets it through | `cli/tests/suite/cross_origin_e2e.rs` `browser_cross_origin_requests_cannot_write_to_an_unauthenticated_loopback_server`, against the shipped `serve`: every write route (`/hook`, `/hook/batch`, MCP `memory_write_page`/`memory_delete_page`/`memory_message_send`/`memory_handoff_accept`, `/admin/write-page`/`delete-page`/`purge-project`/`messages/send`, `/workstream/runs`) × each simple content type × modern, Origin-only and fetch-metadata-only browser shapes → 4xx; body-less `GET /handoff` (which claims the single-use baton), `POST /admin/profile/rebuild` and `POST /admin/backup` → 403; a rebinding `Host` → 403; preflights answer no `Access-Control-Allow-*`; `GET /handoff` as a same-origin `document` or `image` and as a `Sec-Fetch-Site: none` `document` → 403 with the baton still open. Then a canary scan of the whole data dir, page/project/handoff survival, and legitimate controls (JSON MCP calls, a JSON hook → 202, the web UI's same-origin `/admin/pending-writes` list and approve reach their handlers, the anonymous active-project pointer is unmoved after the refused `/handoff` fetches while the closing hook-style fetch claims the baton and moves it). `serve.rs` `cross_origin_browser_request_detection` and `non_script_browser_request_detection` (header tables) and `cross_origin_browser_guard_applies_only_without_auth` (same-origin `image` and `none` `document` refused, same-origin `empty` passes, both pass with auth on); `ai-memory-web` `markdown.rs` `neutralises_images_that_reach_server_routes` (`/handoff?…`, `/admin/backup`, `//host/…`, `../` and `%2e%2e/` traversal, root-mounted route names refused) with `preserves_relative_images` as the legitimate control. `cross_origin_e2e.rs` `handoff_fetch_on_a_lan_host_requires_the_client_marker`, against a `serve` that allowlists a LAN name and address: `GET` and `HEAD /handoff` through either without the marker, and with an empty one → 403 carrying the remedy text, with the baton still open and the active-project pointer unmoved; controls: a marked fetch through the LAN name claims the baton, and a marker-less fetch through `127.0.0.1` (a hook staged before the marker) claims the next one; then a `127.0.0.1` fetch carrying each proxy forwarding header and no marker → 403 with the baton still open, and the same fetch with the marker claims it. `serve.rs` `loopback_host_detection`, `handoff_fetch_client_marker_decision` (incl. a loopback `Host` with each proxy header, refused without the marker and admitted with it, and a named row per header so none can drop out of the list) and `handoff_client_marker_guard_on_lan_hosts_and_under_a_base_path` (also under a `--base-path` nest; inactive with auth on). Front-door parity: `hook_capture.rs` `every_native_hook_request_carries_the_client_marker` (handoff GET, hook POST, batch POST), `http_client.rs` `authenticate_no_token_sets_only_the_client_marker`, the client-marker block of `tests/hooks/test_lib.sh` (every curl branch of the GET, the POST and the drain, plus a static check that every PowerShell header table carries it and every `Invoke-WebRequest` passes one), `render_shared.rs` `assert_every_ts_request_carries_client_marker` run for OpenCode, OpenCode 2, OMP, Pi and OpenClaw, `external_capture_ts.rs` (the rendered OpenCode plugin under Node sends no unmarked request) and `external_capture_powershell.rs` `every_request_carries_the_client_marker` (Windows leg); `ai-memory-web/src/mount.rs` `web_surfaces_refuse_to_be_framed` (`/web`, `/web/pending`, `/web/login`, `/api/v1/projects` all carry both headers; bites with `deny_framing` neutralized) | STRONG with listed residuals. Bite checks: with the marker check disabled, the LAN e2e marker-less `GET /handoff` returns 200 and the unit layer test fails; with the proxy-header rule disabled, the proxied loopback e2e fetch claims the baton and the unit decision test fails; dropping the marker from the native handoff GET, the shell token-drain curl, a PowerShell header table or the TypeScript spool drain fails the matching front-door test. With the guard removed, the cross-origin `GET /handoff` returns 200, consumes the baton and moves the active-project pointer (the pre-fix behaviour); with the guard treating `same-origin` as foreign, the web UI control gets 403; with the `Sec-Fetch-Dest` check removed, the same-origin `document` `GET /handoff` returns 200 and the unit guard test lets a same-origin image through; with the host layer removed, a rebound `/hook` returns 202; a permissive `CorsLayer` fails the preflight assertion; reverting `is_safe_image_target` to the pre-fix rule fails the markdown test on `/handoff?…`, dropping the percent-decoding fails it on `%2e%2e/`, and emptying the route list fails it on a root-mounted `handoff`. To reproduce the bite on the 415 layer, remove the guard and make `/hook` read a raw body instead of `Json`: a `text/plain` hook then returns 202 and the test fails. Residual, closed by setting a bearer token: a browser that sends no fetch metadata even to a loopback host (Safari before 16.4) sends no `Sec-Fetch-*` header and no `Origin` on an image `GET` or a link click, so such a request to a loopback host still reaches `/handoff` (loopback keeps accepting marker-less legacy hooks) and the other, read-only `GET` routes. On a non-loopback host the marker requirement closes `/handoff` for every browser. A plain-HTTP proxy that rewrites `Host` to its loopback upstream and adds no forwarding header (nginx's default `proxy_pass`) looks exactly like a local client, so in front of an unauthenticated server it must add `X-Forwarded-For` or keep `proxy_set_header Host $host`, or the server must sit behind TLS or use a bearer token (`security.md`, `https-via-proxy.md`). Browsers that send fetch metadata no longer have the earlier link residuals: a link opened from another app (`Sec-Fetch-Site: none`) and a link clicked in a stored page (`same-origin` navigation) both carry a non-`empty` destination and are refused. With auth on, the bearer token and the session CSRF token are the gate and this layer is a no-op || 12d | The web UI and `/api/v1` cannot write, and render stored text inert | `crates/ai-memory-web/clippy.toml` `disallowed-methods`: every `Wiki` write and destructive method (`write_page`, `write_page_if`, `apply_batch`, the delete/evict/purge/restore/move/reindex/remove-dir helpers, `commit_all`, `approve_auto_improve_proposal`) and the `writer()` / `git()` accessors are lint errors in the crate, so the `Wiki` held by `WebState` stays read-only under `cargo clippy -D warnings`; only the integration-test module carries the `allow`, for fixtures. Templates are askama with HTML auto-escaping; the history diff (`templates/history.html`) and the session timeline (`templates/session.html`) print page lines, observation titles and bodies escaped, with no `|safe`, and no captured value is interpolated into a script | `ai-memory-web` `history_replay.rs` `session_timeline_renders_captured_markup_inert` (a `<script>` title and body plus `"><img onerror>` and `' onmouseover='` payloads, checked to survive ingest first, render escaped) and `history_diff_renders_page_markup_inert` (the same payloads in a page version's diff lines); `mount.rs` `web_surfaces_refuse_to_be_framed` covers the history, timeline and history-API routes (200 with both anti-framing headers) | STRONG. Bite checks: a `Wiki::write_page` and a `Wiki::delete_page` call added to `routes/history.rs` fail `cargo clippy -p ai-memory-web --all-targets -- -D warnings` with `use of a disallowed method`; `|safe` on the observation body or a diff line fails the matching inert-render test. The lint is per crate: a write reached through another crate's helper is outside it, which review and the `/api/v1` "zero writer calls" rule still cover |-| 12e | OIDC device login never sends the device code or tokens in clear text off loopback | `ai-memory-llm/src/oidc.rs` `discover` checks the issuer with `require_tls` before fetching discovery, then the advertised `device_authorization_endpoint` and `token_endpoint`: `https` passes, plain `http` passes only for `localhost`, `127.0.0.1`/`127.0.0.0/8` and `::1`, anything else is an `LlmError::Auth` | `oidc.rs` `discover_refuses_plain_http_issuer_before_any_request` (remote `http` issuer refused with no request reaching the mock), `discover_refuses_plain_http_endpoints_from_the_document` (an `http` token or device endpoint in the document refused), `require_tls_accepts_https_and_loopback_http_only` (table incl. `localhost.example.com`); legitimate control `discover_accepts_a_loopback_issuer_and_endpoints` | STRONG |++| 12e | OIDC device login and refresh never send credential-bearing requests in clear text off loopback or through redirects | `ai-memory-llm/src/oidc.rs` `discover` checks the issuer with `require_tls` before fetching discovery, then the advertised `device_authorization_endpoint` and `token_endpoint`; `refresh_access_token` revalidates the persisted token endpoint and builds a no-redirect client; `ai-memory-cli/src/commands/auth.rs` builds every authentication-flow client with redirects disabled. `https` passes, plain `http` passes only for `localhost`, `127.0.0.1`/`127.0.0.0/8` and `::1`, anything else is an `LlmError::Auth` | `oidc.rs` `discover_refuses_plain_http_issuer_before_any_request` (remote `http` issuer refused with no request reaching the mock), `discover_refuses_plain_http_endpoints_from_the_document` (an `http` token or device endpoint in the document refused), `refresh_refuses_a_persisted_plain_http_remote_endpoint`, `refresh_does_not_forward_the_refresh_token_through_redirects`, `require_tls_accepts_https_and_loopback_http_only` (table incl. `localhost.example.com`); CLI `auth_client_never_forwards_credentials_through_redirects`; legitimate control `discover_accepts_a_loopback_issuer_and_endpoints` | 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; for Claude it moves the run's own session to a background session only when `ai-memory-workstream` `claude_continued_session` finds a `sessionKind: "bg"` record that names that exact session as its attached client and this checkout as `cwd` (#1050), and to a `/clear`ed session only when that session's own transcript records the `/clear` command and names the run's session as its launch `session_id` from this checkout or below it; `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_continued_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); `transcript.rs` `claude_continued_session_follows_only_this_launchs_clear` (an uncleared transcript, a quoted `/clear`, another checkout's clear, a concurrent launch's clear, a subagent file, and a pre-run clear refused; own clear and the newest of two as controls); `run.rs` `a_claude_run_that_attached_to_a_background_session_follows_it`, `a_claude_run_that_was_cleared_follows_the_new_session`; `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 |