Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(hooks): deliver the opted-in project brief on SubagentStart
TiagoSnows5c6f02d4a112
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ea2d59b3..6a48efab 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,18 @@ version in [`docs/changelog/`](docs/changelog/):### Added+- Added `[briefing] inject_on_subagent_start` to `.ai-memory.toml`. A project+ that sets it hands each `claude-code` subagent the project brief when the+ subagent starts: the same pinned, `_rules/` and `_slots/` brief that+ `inject_on_session_start` adds at session start, kept within `max_chars` and+ within the 10,000-character limit of that agent's hook context. The hook+ reads it from a new read-only `GET /brief`, which resolves and authorizes the+ project as `/handoff` does but never reads or claims a handoff, so a subagent+ cannot take its parent session's baton. A server without the route answers+ 404 and the subagent starts as before. The native hook and the+ `hooks/claude-code` shell and PowerShell scripts deliver it, and every marker+ parser treats the key as a settings boundary. It is off by default (#1715).+- `ai-memory audit-contamination` reports projects whose names differ only byspelling: two rows whose names are equal after case folding, Unicodecomposition and separators (`renato` / `Renato` / `Rénato`). That is thediff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rsindex b74fe9b5..b266938a 100644--- a/crates/ai-memory-cli/src/commands/hook.rs+++ b/crates/ai-memory-cli/src/commands/hook.rs@@ -34,8 +34,9 @@ use sha2::{Digest as _, Sha256};use super::hook_capture::{HookScope, build_client, canonical_context, capture_policy, extract_cwd, get_handoff,- hook_scope, marker_capture_policy, marker_query_suffix, marker_query_suffix_without_briefing,- marker_requests_briefing, resolve_cwd_with_fallbacks, url_encode,+ hook_scope, marker_capture_policy, marker_query_suffix, marker_query_suffix_for_subagent_brief,+ marker_query_suffix_without_briefing, marker_requests_briefing,+ marker_requests_subagent_briefing, resolve_cwd_with_fallbacks, url_encode,};use super::hook_drain_process;use super::hook_spool;@@ -1013,6 +1014,17 @@ fn session_start_handoff_envelope(agent: AgentKind, handoff: String) -> serde_js}}+/// The `claude-code` agent adds a `SubagentStart` hook's `additionalContext`+/// to the subagent's context before its first prompt.+fn subagent_start_brief_envelope(brief: &str) -> serde_json::Value {+ serde_json::json!({+ "hookSpecificOutput": {+ "hookEventName": "SubagentStart",+ "additionalContext": brief,+ }+ })+}+/// Hermes adds a hook's stdout to the turn only as a JSON object whose/// `context` is a non-blank string (`_parse_context` in/// `agent/shell_hooks.py`); plain text and every other key are dropped.@@ -1202,6 +1214,9 @@ where// UserPromptSubmit stdout is discarded); that path is context delivery// too, so external capture must not suppress it.|| (hook_event == HookEvent::PostToolUse && agent_kind.post_tool_injects_handoff())+ // A subagent start delivers the `[briefing] inject_on_subagent_start`+ // brief.+ || (hook_event == HookEvent::SubagentStart && agent_kind.subagent_start_injects_context())// On an Antigravity build without SessionStart, the first turn's// PreInvocation delivers the handoff in its place.|| (agent_kind == AgentKind::AntigravityCli@@ -1729,6 +1744,39 @@ where}}+ // subagent-start: a repository that opted into `[briefing]+ // inject_on_subagent_start` gives each subagent its project brief, for+ // agents whose `SubagentStart` hook injects context. A subagent runs+ // inside its parent's session, so the brief comes from the read-only+ // `/brief`, never from `/handoff`, whose fetch would claim the parent's+ // baton; a server that predates `/brief` answers 404 and the subagent+ // gets the `{}` it always got. Cursor also runs these hook settings, and+ // its handling of this envelope is unverified, so a Cursor payload gets+ // nothing.+ if hook_event == HookEvent::SubagentStart+ && agent_kind.subagent_start_injects_context()+ && ai_memory_hooks::agent_from_payload(&json) != Some(AgentKind::Cursor)+ && let Some(cwd) = policy_cwd.as_deref()+ && marker_requests_subagent_briefing(cwd)+ {+ let client = build_client();+ let bearer = hook_spool::resolve_bearer(&client, &dd, effective_token).await;+ let brief_url = format!(+ "{base}/brief?agent={}{}",+ args.agent,+ marker_query_suffix_for_subagent_brief(+ cwd,+ args.project_strategy.and_then(|s| s.baked())+ )+ );+ if let Some(brief) =+ get_handoff(&client, &brief_url, bearer.as_deref(), handoff_timeout()).await+ {+ writeln!(stdout, "{}", subagent_start_brief_envelope(&brief))?;+ return Ok(());+ }+ }+// "reload context": a recap of the window the last compaction dropped.// Claude Code and Codex add the UserPromptSubmit envelope to this turn.// Cursor runs Claude Code's settings too; its handling of this envelope@@ -7506,6 +7554,221 @@ mod tests {assert_eq!(run("droid", "user-prompt-submit").await.trim(), "{}");}+ // ── `[briefing] inject_on_subagent_start` ─────────────────────────────++ fn subagent_start_payload(cwd: &Path) -> serde_json::Value {+ serde_json::json!({+ "session_id": "parent-session",+ "transcript_path": cwd.join("parent.jsonl"),+ "cwd": cwd,+ "hook_event_name": "SubagentStart",+ "agent_id": "agent-abc123",+ "agent_type": "Explore"+ })+ }++ async fn run_subagent_start(+ data_dir: &Path,+ args: HookArgs,+ payload: serde_json::Value,+ ) -> String {+ let mut stdout = Vec::new();+ run_with_payload(+ Some(data_dir.to_path_buf()),+ args,+ payload.to_string(),+ &mut stdout,+ |_, _| Ok(()),+ )+ .await+ .unwrap();+ String::from_utf8(stdout).unwrap()+ }++ async fn recorded_requests(+ requests: &mut tokio::sync::mpsc::UnboundedReceiver<String>,+ ) -> Vec<String> {+ let mut recorded = Vec::new();+ while let Some(request) = first_request(requests).await {+ recorded.push(request);+ }+ recorded+ }++ /// A repository that opted into `[briefing] inject_on_subagent_start`+ /// hands its subagents the project brief: the hook reads it from the+ /// read-only `/brief` route and prints the `SubagentStart` envelope the+ /// agent adds to the subagent's context. It never asks `/handoff`, whose+ /// fetch would claim the parent session's baton, and the event itself is+ /// still captured.+ #[tokio::test]+ async fn subagent_start_delivers_the_opted_in_brief() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().join("data");+ let repo = repo_with_marker(+ tmp.path(),+ "repo",+ "[briefing]\ninject_on_subagent_start = true\nmax_chars = 6000\n",+ );+ let (base, mut requests) = serve_requests("200 OK", "SUBAGENT-BRIEF").await;++ let stdout = run_subagent_start(+ &data_dir,+ claude_args("subagent-start", &base),+ subagent_start_payload(&repo),+ )+ .await;++ let envelope: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap();+ assert_eq!(+ envelope,+ serde_json::json!({+ "hookSpecificOutput": {+ "hookEventName": "SubagentStart",+ "additionalContext": "SUBAGENT-BRIEF",+ }+ })+ );+ let recorded = recorded_requests(&mut requests).await;+ let brief = recorded+ .iter()+ .find(|request| request.starts_with("GET /brief?"))+ .unwrap_or_else(|| panic!("no brief fetch: {recorded:?}"));+ assert!(brief.contains("agent=claude-code"), "{brief}");+ assert!(brief.contains("&cwd="), "{brief}");+ assert!(brief.contains("&briefing=true"), "{brief}");+ assert!(brief.contains("&briefing_budget=6000"), "{brief}");+ assert!(+ !recorded+ .iter()+ .any(|request| request.starts_with("GET /handoff")),+ "a subagent start must never fetch the handoff: {recorded:?}"+ );+ let spooled = spooled_entries(&data_dir);+ assert_eq!(spooled.len(), 1, "the event is still captured");+ assert_eq!(+ query_param(&spooled[0].url, "event"),+ Some("subagent-start")+ );+ }++ /// Without the subagent opt-in nothing changes: no request, and the `{}`+ /// a subagent start always printed — also when the repository opted into+ /// the session-start brief only.+ #[tokio::test]+ async fn subagent_start_without_the_opt_in_prints_what_it_always_did() {+ let tmp = tempfile::tempdir().unwrap();+ let (base, mut requests) = serve_requests("200 OK", "SUBAGENT-BRIEF").await;+ for (name, marker) in [+ ("unmarked", None),+ (+ "session-brief-only",+ Some("[briefing]\ninject_on_session_start = true\n"),+ ),+ (+ "opted-out",+ Some("[briefing]\ninject_on_subagent_start = false\n"),+ ),+ ] {+ let repo = match marker {+ Some(marker) => repo_with_marker(tmp.path(), name, marker),+ None => {+ let repo = tmp.path().join(name);+ std::fs::create_dir_all(&repo).unwrap();+ repo+ }+ };+ let stdout = run_subagent_start(+ &tmp.path().join(format!("data-{name}")),+ claude_args("subagent-start", &base),+ subagent_start_payload(&repo),+ )+ .await;+ assert_eq!(stdout, "{}\n", "{name}");+ }+ let recorded = recorded_requests(&mut requests).await;+ assert!(recorded.is_empty(), "{recorded:?}");+ }++ /// An empty `/brief` body (nothing to brief) and a 404 (a server that+ /// predates the route) both leave the subagent with the `{}` it got+ /// before, and neither falls back to `/handoff`.+ #[tokio::test]+ async fn subagent_start_with_no_brief_prints_an_empty_reply() {+ for status in ["200 OK", "404 Not Found"] {+ let tmp = tempfile::tempdir().unwrap();+ let repo = repo_with_marker(+ tmp.path(),+ "repo",+ "[briefing]\ninject_on_subagent_start = true\n",+ );+ let (base, mut requests) = serve_requests(status, "").await;++ let stdout = run_subagent_start(+ &tmp.path().join("data"),+ claude_args("subagent-start", &base),+ subagent_start_payload(&repo),+ )+ .await;++ assert_eq!(stdout, "{}\n", "{status}");+ let recorded = recorded_requests(&mut requests).await;+ assert!(+ recorded+ .iter()+ .any(|request| request.starts_with("GET /brief?")),+ "{status}: {recorded:?}"+ );+ assert!(+ !recorded+ .iter()+ .any(|request| request.starts_with("GET /handoff")),+ "{status}: {recorded:?}"+ );+ }+ }++ /// Only the `claude-code` agent documents `SubagentStart` context. Another+ /// agent with the same marker asks for nothing and replies as before, and+ /// so does a Cursor payload arriving through the same hook settings, whose+ /// handling of the envelope is unverified.+ #[tokio::test]+ async fn subagent_brief_skips_agents_without_subagent_context() {+ let tmp = tempfile::tempdir().unwrap();+ let repo = repo_with_marker(+ tmp.path(),+ "repo",+ "[briefing]\ninject_on_subagent_start = true\n",+ );+ let (base, mut requests) = serve_requests("200 OK", "SUBAGENT-BRIEF").await;++ let stdout = run_subagent_start(+ &tmp.path().join("data-codex"),+ codex_args("subagent-start", &base),+ subagent_start_payload(&repo),+ )+ .await;+ assert_eq!(stdout.trim(), "{}");++ let mut cursor = subagent_start_payload(&repo);+ cursor["cursor_version"] = "2.0.0".into();+ let stdout = run_subagent_start(+ &tmp.path().join("data-cursor"),+ claude_args("subagent-start", &base),+ cursor,+ )+ .await;+ assert_eq!(stdout.trim(), "{}");++ let recorded = recorded_requests(&mut requests).await;+ assert!(+ !recorded+ .iter()+ .any(|request| request.starts_with("GET /brief")),+ "{recorded:?}"+ );+ }+// ── #992: per-repository server profiles ─────────────────────────────/// Register `name` in `data_dir` with a token and the given roots.diff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rsindex 0b6159a6..268f0036 100644--- a/crates/ai-memory-cli/src/commands/hook_capture.rs+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs@@ -293,7 +293,34 @@ pub fn url_encode(s: &str) -> String {/// routing win; otherwise a valid remote's canonical path wins, and repo-root/// is only the host-side no-valid-remote fallback.pub fn marker_query_suffix(cwd: &str, default_strategy: Option<&str>) -> String {- marker_query_suffix_impl(cwd, default_strategy, true)+ marker_query_suffix_impl(cwd, default_strategy, Some(BriefingKey::SessionStart))+}++/// [`marker_query_suffix`] whose `&briefing` pair carries the+/// `[briefing] inject_on_subagent_start` opt-in instead: the query a subagent+/// start sends to `GET /brief`.+pub fn marker_query_suffix_for_subagent_brief(cwd: &str, default_strategy: Option<&str>) -> String {+ marker_query_suffix_impl(cwd, default_strategy, Some(BriefingKey::SubagentStart))+}++/// Which `[briefing]` opt-in a request forwards as its `&briefing` pair.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum BriefingKey {+ /// `inject_on_session_start`: the brief the session-start `/handoff`+ /// fetch appends.+ SessionStart,+ /// `inject_on_subagent_start`: the brief a subagent starts with, from+ /// `/brief`.+ SubagentStart,+}++impl BriefingKey {+ fn marker_key(self) -> &'static str {+ match self {+ Self::SessionStart => "inject_on_session_start",+ Self::SubagentStart => "inject_on_subagent_start",+ }+ }}/// [`marker_query_suffix`] without the `[briefing]` pair@@ -306,7 +333,7 @@ pub fn marker_query_suffix(cwd: &str, default_strategy: Option<&str>) -> String/// cheap and self-limiting (empty body when nothing is pending) — without the/// briefing params, so the server does not recompose the brief per prompt.pub fn marker_query_suffix_without_briefing(cwd: &str, default_strategy: Option<&str>) -> String {- marker_query_suffix_impl(cwd, default_strategy, false)+ marker_query_suffix_impl(cwd, default_strategy, None)}/// Whether the marker that routes `cwd` explicitly enables the compiled@@ -319,16 +346,24 @@ pub fn marker_query_suffix_without_briefing(cwd: &str, default_strategy: Option</// Kimi Code uses this before creating its local once-per-session marker so/// repositories that did not opt in do not accumulate marker files.pub fn marker_requests_briefing(cwd: &str) -> bool {- marker_requests_briefing_with_home(cwd, home_dir().as_deref())+ marker_requests_briefing_with_home(cwd, home_dir().as_deref(), BriefingKey::SessionStart)}-/// [`marker_requests_briefing`] resolved against `home` instead of the-/// operator's home directory.-fn marker_requests_briefing_with_home(cwd: &str, home: Option<&Path>) -> bool {+/// Whether the marker that routes `cwd` explicitly enables the subagent+/// brief (`[briefing] inject_on_subagent_start`), read from the selection+/// [`marker_query_suffix_for_subagent_brief`] reads, so a subagent start asks+/// `/brief` only when its query would carry the opt-in.+pub fn marker_requests_subagent_briefing(cwd: &str) -> bool {+ marker_requests_briefing_with_home(cwd, home_dir().as_deref(), BriefingKey::SubagentStart)+}++/// [`marker_requests_briefing`] for the opt-in `key`, resolved against `home`+/// instead of the operator's home directory.+fn marker_requests_briefing_with_home(cwd: &str, home: Option<&Path>, key: BriefingKey) -> bool {crate::marker::routing_selection_with_home(cwd, cwd, home, false).ok().flatten()- .and_then(|selection| parse_toml_flag(&selection.path, "inject_on_session_start"))+ .and_then(|selection| parse_toml_flag(&selection.path, key.marker_key())).is_some_and(|value| is_truthy(&value))}@@ -628,19 +663,19 @@ fn profile_flag_value(raw: Option<String>) -> &'static str {fn marker_query_suffix_impl(cwd: &str,default_strategy: Option<&str>,- include_briefing: bool,+ briefing_key: Option<BriefingKey>,) -> String {let selection = match routing_selection(cwd) {Ok(selection) => selection,Err(_) => return String::new(),};- marker_query_suffix_impl_from_selection(cwd, default_strategy, include_briefing, selection)+ marker_query_suffix_impl_from_selection(cwd, default_strategy, briefing_key, selection)}fn marker_query_suffix_impl_from_selection(cwd: &str,default_strategy: Option<&str>,- include_briefing: bool,+ briefing_key: Option<BriefingKey>,selection: Option<RoutingSelection>,) -> String {let mut qs = format!("&cwd={}", url_encode(cwd));@@ -660,9 +695,12 @@ fn marker_query_suffix_impl_from_selection(default_global = parse_toml_flag(&marker, "default_global");// `[briefing] inject_on_session_start = true` + optional// `max_chars = N` — opt this repo into the compiled project brief- // appended to the session-start handoff fetch (#176).- briefing = parse_toml_flag(&marker, "inject_on_session_start");- briefing_budget = parse_toml_flag(&marker, "max_chars");+ // appended to the session-start handoff fetch (#176); the subagent+ // brief reads `inject_on_subagent_start` instead.+ if let Some(key) = briefing_key {+ briefing = parse_toml_flag(&marker, key.marker_key());+ briefing_budget = parse_toml_flag(&marker, "max_chars");+ }// `[profile] contribute` / `consume` (quoted or bare), always sent// explicitly once a marker resolved: a falsy value sends `0`, anything// else (an absent key included) `1`. Removing the key re-enables; no@@ -725,19 +763,18 @@ fn marker_query_suffix_impl_from_selection(if handoff_off {qs.push_str("&handoff=0");}- // Per-repo session-start brief opt-in: forwarded on every request for- // simplicity (the capture path ignores it); only the `/handoff` GET at- // session start acts on it. Truthiness and the char-budget clamp are- // decided server-side. Callers that deliver the brief once per session- // (the kimi user-prompt path) pass `include_briefing = false` after the- // first delivery so the server stops recomposing the brief per request.- if include_briefing {- if let Some(val) = briefing.filter(|v| !v.is_empty()) {- qs.push_str(&format!("&briefing={}", url_encode(&val)));- }- if let Some(val) = briefing_budget.filter(|v| !v.is_empty()) {- qs.push_str(&format!("&briefing_budget={}", url_encode(&val)));- }+ // Per-repo brief opt-in: forwarded on every request for simplicity (the+ // capture path ignores it); only the `/handoff` GET at session start, or+ // `/brief` at a subagent start, acts on it. Truthiness and the+ // char-budget clamp are decided server-side. Callers that deliver the+ // brief once per session (the kimi user-prompt path) pass no key after+ // the first delivery so the server stops recomposing the brief per+ // request.+ if let Some(val) = briefing.filter(|v| !v.is_empty()) {+ qs.push_str(&format!("&briefing={}", url_encode(&val)));+ }+ if let Some(val) = briefing_budget.filter(|v| !v.is_empty()) {+ qs.push_str(&format!("&briefing_budget={}", url_encode(&val)));}qs}@@ -1087,9 +1124,12 @@ mod tests {Some(home.path()),false,) {- Ok(selection) => {- marker_query_suffix_impl_from_selection(cwd, default_strategy, true, selection)- }+ Ok(selection) => marker_query_suffix_impl_from_selection(+ cwd,+ default_strategy,+ Some(BriefingKey::SessionStart),+ selection,+ ),Err(_) => String::new(),}}@@ -1104,7 +1144,7 @@ mod tests {/// reason.fn marker_requests_briefing(cwd: &str) -> bool {let home = tempfile::TempDir::new().unwrap();- marker_requests_briefing_with_home(cwd, Some(home.path()))+ marker_requests_briefing_with_home(cwd, Some(home.path()), BriefingKey::SessionStart)}async fn serve_once(status: &'static str, body: &'static str) -> String {@@ -1733,8 +1773,12 @@ mod tests {false,).unwrap();- let query =- marker_query_suffix_impl_from_selection(repo.to_str().unwrap(), None, true, selection);+ let query = marker_query_suffix_impl_from_selection(+ repo.to_str().unwrap(),+ None,+ Some(BriefingKey::SessionStart),+ selection,+ );for expected in ["&workspace=right","&project=api",@@ -1770,7 +1814,7 @@ mod tests {).unwrap();let query =- marker_query_suffix_impl_from_selection(repo.to_str().unwrap(), None, false, selection);+ marker_query_suffix_impl_from_selection(repo.to_str().unwrap(), None, None, selection);assert!(query.contains("&workspace=path&project=api"), "{query}");assert!(!query.contains("aliases="), "{query}");assert!(!query.contains("identity_src="), "{query}");@@ -1967,6 +2011,79 @@ drop_subagent_captures = "true"assert!(!qs.contains("briefing"), "{qs}");}+ /// `[briefing] inject_on_subagent_start` is its own opt-in: it rides only+ /// the subagent-start query, and the session-start query keeps forwarding+ /// `inject_on_session_start` alone, so neither turns the other on.+ #[test]+ fn subagent_brief_query_forwards_only_its_own_opt_in() {+ let tmp = tempfile::TempDir::new().unwrap();+ let cwd = tmp.path().to_str().unwrap();+ let marker = tmp.path().join(".ai-memory.toml");+ let subagent_query = || {+ let home = tempfile::TempDir::new().unwrap();+ let selection = super::super::super::marker::routing_selection_with_home(+ cwd,+ cwd,+ Some(home.path()),+ false,+ );+ marker_query_suffix_impl_from_selection(+ cwd,+ None,+ Some(BriefingKey::SubagentStart),+ selection.unwrap(),+ )+ };++ std::fs::write(+ &marker,+ "[briefing]\ninject_on_subagent_start = true\nmax_chars = 6000\n",+ )+ .unwrap();+ let qs = subagent_query();+ assert!(qs.contains("&cwd="), "{qs}");+ assert!(qs.contains("&briefing=true"), "{qs}");+ assert!(qs.contains("&briefing_budget=6000"), "{qs}");+ // `max_chars` rides along with or without an opt-in, as it always has;+ // only `&briefing=` turns a brief on.+ let qs = marker_query_suffix(cwd, None);+ assert!(+ !qs.contains("&briefing="),+ "session start must not inherit it: {qs}"+ );++ std::fs::write(+ &marker,+ "[briefing]\ninject_on_session_start = true\nmax_chars = 6000\n",+ )+ .unwrap();+ let qs = subagent_query();+ assert!(+ !qs.contains("&briefing="),+ "subagents must not inherit it: {qs}"+ );+ assert!(marker_query_suffix(cwd, None).contains("&briefing=true"));+ }++ #[test]+ fn marker_requests_subagent_briefing_only_for_its_own_truthy_opt_in() {+ let tmp = tempfile::TempDir::new().unwrap();+ let marker = tmp.path().join(".ai-memory.toml");+ let cwd = tmp.path().to_str().unwrap();+ let home = tempfile::TempDir::new().unwrap();+ let requested = || {+ marker_requests_briefing_with_home(cwd, Some(home.path()), BriefingKey::SubagentStart)+ };++ assert!(!requested());+ std::fs::write(&marker, "[briefing]\ninject_on_session_start = true\n").unwrap();+ assert!(!requested());+ std::fs::write(&marker, "[briefing]\ninject_on_subagent_start = off\n").unwrap();+ assert!(!requested());+ std::fs::write(&marker, "[briefing]\ninject_on_subagent_start = \"yes\"\n").unwrap();+ assert!(requested());+ }+#[test]fn marker_requests_briefing_only_for_truthy_opt_in() {let tmp = tempfile::TempDir::new().unwrap();@@ -2010,18 +2127,31 @@ drop_subagent_captures = "true"Some(home.path()),false,);- marker_query_suffix_impl_from_selection(cwd, None, true, selection.unwrap())+ marker_query_suffix_impl_from_selection(+ cwd,+ None,+ Some(BriefingKey::SessionStart),+ selection.unwrap(),+ )};let qs = query();assert!(qs.contains("&briefing=true"), "{qs}");- assert!(marker_requests_briefing_with_home(cwd, Some(home.path())));+ assert!(marker_requests_briefing_with_home(+ cwd,+ Some(home.path()),+ BriefingKey::SessionStart+ ));// The repo's own settings marker wins over the home marker for both.std::fs::write(repo.path().join(".ai-memory.toml"), "project = \"repo\"\n").unwrap();let qs = query();assert!(!qs.contains("briefing"), "{qs}");- assert!(!marker_requests_briefing_with_home(cwd, Some(home.path())));+ assert!(!marker_requests_briefing_with_home(+ cwd,+ Some(home.path()),+ BriefingKey::SessionStart+ ));}#[test]diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 3522e9c7..496efd8a 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -4422,7 +4422,7 @@ pub(crate) const TS_FIND_SETTINGS_MARKER: &str = r#"function declaresSettings(te}if (/^\s*aliases\s*=/m.test(text)) return true;if (/^\s*server\s*=/m.test(text)) return true;- for (const key of ["default_global", "inject_on_session_start", "max_chars", "contribute", "consume", "deliver_on_session_start"]) {+ for (const key of ["default_global", "inject_on_session_start", "inject_on_subagent_start", "max_chars", "contribute", "consume", "deliver_on_session_start"]) {if (tomlFlag(text, key) !== undefined) return true;}return false;@@ -13137,7 +13137,7 @@ model = "gpt-5"));assert!(plugin.contains("if (/^\\s*aliases\\s*=/m.test(text)) return true;"));assert!(plugin.contains(- "for (const key of [\"default_global\", \"inject_on_session_start\", \"max_chars\", \"contribute\", \"consume\", \"deliver_on_session_start\"])"+ "for (const key of [\"default_global\", \"inject_on_session_start\", \"inject_on_subagent_start\", \"max_chars\", \"contribute\", \"consume\", \"deliver_on_session_start\"])"));assert!(plugin.contains("if (declaresSettings(text)) return marker;"));assert!(plugin.contains(diff --git a/crates/ai-memory-cli/src/marker.rs b/crates/ai-memory-cli/src/marker.rsindex 91911883..e82767e4 100644--- a/crates/ai-memory-cli/src/marker.rs+++ b/crates/ai-memory-cli/src/marker.rs@@ -1254,9 +1254,10 @@ fn declares_more_than_capture(text: &str) -> bool {"identity","identity_style",];- const FLAG_KEYS: [&str; 6] = [+ const FLAG_KEYS: [&str; 7] = ["default_global","inject_on_session_start",+ "inject_on_subagent_start","max_chars","contribute","consume",@@ -2382,6 +2383,7 @@ project = "infra" # this is fine"drop_subagent_captures = \"true\"\n","[recall]\ndefault_global = true\n","[briefing]\ninject_on_session_start = true\n",+ "[briefing]\ninject_on_subagent_start = true\n","[briefing]\nmax_chars = 4000\n","[handoff]\ndeliver_on_session_start = false\n",] {diff --git a/crates/ai-memory-cli/tests/suite/external_capture.rs b/crates/ai-memory-cli/tests/suite/external_capture.rsindex 6424133d..133b8e4b 100644--- a/crates/ai-memory-cli/tests/suite/external_capture.rs+++ b/crates/ai-memory-cli/tests/suite/external_capture.rs@@ -260,6 +260,81 @@ fn external_capture_still_delivers_the_compaction_recap() {}}+/// The subagent brief is context delivery too: under an external capture+/// owner, a repository that opted into `[briefing] inject_on_subagent_start`+/// still hands the subagent its brief, and the event itself is+/// left to the owner.+#[test]+fn external_capture_still_delivers_the_subagent_brief() {+ const BRIEF: &str = "SUBAGENT_BRIEF_SENTINEL";+ let guard = tempfile::tempdir().unwrap();+ let root = guard.path().to_path_buf();+ std::fs::write(+ root.join(".ai-memory.toml"),+ "[briefing]\ninject_on_subagent_start = true\n",+ )+ .unwrap();+ let (server, stop, served) = serve_one_request(BRIEF);++ let mut child = hermetic(BIN)+ .args(["--data-dir"])+ .arg(root.join("data"))+ .args([+ "hook",+ "--agent",+ "claude-code",+ "--event",+ "subagent-start",+ "--server-url",+ &server,+ ])+ .env("AI_MEMORY_HOME", &root)+ .env("HOME", &root)+ .env("AI_MEMORY_CAPTURE_OWNER", "example.runtime")+ .current_dir(&root)+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .expect("spawn hook");+ child+ .stdin+ .take()+ .unwrap()+ .write_all(+ json!({+ "session_id": "external-subagent-test",+ "cwd": root,+ "hook_event_name": "SubagentStart",+ "agent_id": "agent-1",+ "agent_type": "Explore"+ })+ .to_string()+ .as_bytes(),+ )+ .unwrap();+ let output = child.wait_with_output().unwrap();+ assert!(output.status.success(), "{output:?}");++ stop.store(true, Ordering::SeqCst);+ let stdout = String::from_utf8_lossy(&output.stdout).into_owned();+ let request = served+ .join()+ .unwrap()+ .unwrap_or_else(|| panic!("the brief GET never reached the server; stdout was {stdout:?}"));+ assert!(request.starts_with("GET /brief?"), "{request}");+ let envelope: Value = serde_json::from_str(stdout.trim()).unwrap();+ assert_eq!(+ envelope["hookSpecificOutput"]["hookEventName"],+ "SubagentStart"+ );+ assert_eq!(envelope["hookSpecificOutput"]["additionalContext"], BRIEF);+ let spooled = std::fs::read_dir(root.join("data/hook-spool"))+ .map(|entries| entries.flatten().count())+ .unwrap_or(0);+ assert_eq!(spooled, 0, "the event must be left to its capture owner");+}+mod slow {use super::*;use std::process::Command;diff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rsindex c2cf52cb..5a7c7a14 100644--- a/crates/ai-memory-core/src/ids.rs+++ b/crates/ai-memory-core/src/ids.rs@@ -569,6 +569,19 @@ impl AgentKind {)}+ /// Whether this agent adds a `SubagentStart` hook's+ /// `hookSpecificOutput.additionalContext` to the subagent's context.+ ///+ /// [`Self::ClaudeCode`] adds it before the subagent's first prompt, within+ /// the same 10,000-character limit as every hook context string (its hooks+ /// reference, `SubagentStart` section). No other supported harness+ /// documents a context channel on its subagent-start event, so the+ /// `[briefing] inject_on_subagent_start` brief goes to that agent only.+ #[must_use]+ pub fn subagent_start_injects_context(self) -> bool {+ matches!(self, Self::ClaudeCode)+ }+/// Whether `PostToolUse` stdout is model-visible context.////// Grok Build reads that stdout and delivers `hookSpecificOutput.additionalContext`@@ -749,6 +762,16 @@ mod tests {}}+ #[test]+ fn only_one_agent_kind_takes_subagent_start_context() {+ assert!(AgentKind::ClaudeCode.subagent_start_injects_context());+ for other in AgentKind::ALL {+ if other != AgentKind::ClaudeCode {+ assert!(!other.subagent_start_injects_context(), "{other:?}");+ }+ }+ }+#[test]fn agent_kind_pool_round_trips_without_claiming_handoff_delivery() {assert_eq!(AgentKind::Pool.as_str(), "pool");diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex 5c74afeb..9c699d02 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -727,8 +727,9 @@ fn admission_skips(}/// Build a router with `POST /hook` (event ingress), `GET /handoff`-/// (synchronous handoff-fetch for session-start hooks) and `GET /recap`-/// (the read-only compaction recap for a "reload context" prompt).+/// (synchronous handoff-fetch for session-start hooks), `GET /brief` (the+/// read-only project brief for a subagent start) and `GET /recap` (the+/// read-only compaction recap for a "reload context" prompt).pub fn hook_router(state: HookState) -> Router {Router::new().route(@@ -740,6 +741,7 @@ pub fn hook_router(state: HookState) -> Router {post(handle_hook_batch).route_layer(from_fn(repair_hook_json)),).route("/handoff", get(handle_handoff))+ .route("/brief", get(handle_brief)).route("/recap", get(crate::recap::handle_recap)).with_state(Arc::new(state))}@@ -1765,14 +1767,6 @@ async fn fetch_and_accept_handoff_at(now: jiff::Timestamp,) -> anyhow::Result<Option<String>> {let agent = query.agent.as_deref().map_or(AgentKind::Other, parse_agent);- let repository = query.repository_identity();- let aliases = crate::payload::marker_aliases_from_wire(- query.project.as_deref(),- ProjectSource::parse(query.project_src.as_deref()),- repository.as_ref(),- query.aliases.as_deref(),- )- .map_err(|_| anyhow::anyhow!("invalid marker aliases"))?;// Keep the active-project key compatible with MCP transports: the native// session id is carried separately below to bind a destructive handoff// claim to its exact receiver.@@ -1780,32 +1774,9 @@ async fn fetch_and_accept_handoff_at(user: actor.as_ref().map(IdentityKey::storage_key),session_id: None,};- let (ws, proj) = resolve_project_ids_inner(- state,- query.cwd.as_deref(),- query.workspace.as_deref(),- query.project.as_deref(),- ProjectStrategy::parse(query.project_strategy.as_deref()),- repository.as_ref(),- query.identity_style(),- &aliases,- ProjectSource::parse(query.project_src.as_deref()),- false,- viewer,- )- .await?;- // Everything below returns this repository's content — its handoff and- // its pinned, rules and slot pages — and claims its handoff, all keyed- // only on a project the caller named or a directory they are in (#708).- // Checked before the active-project pointer is published, so a refused+ // Authorized before the active-project pointer is published, so a refused// repository does not become the caller's default for later calls.- crate::grants::authorize_resolved(- &state.reader,- Some((ws, proj)),- viewer,- ai_memory_store::ProjectAccess::Read,- )- .await?;+ let (ws, proj) = resolve_authorized_startup_scope(state, &query, viewer).await?;// A managed run's ledger is additive, not a replacement. Resolve and// authorize the request's repository before interpreting the run id: a// shared Codex daemon may carry a terminal id from another checkout, and@@ -1857,7 +1828,8 @@ async fn fetch_and_accept_handoff_at(// The brief is additive and non-destructive: unlike the handoff (a// single-use slot claimed below), it is recomposed on every opted-in// session start — exactly what a Claude Code `/clear` needs (#176).- let brief_md = render_requested_session_brief(state, &query, ws, proj, actor.as_ref()).await?;+ let brief_md =+ render_requested_session_brief(state, &query, ws, proj, actor.as_ref(), None).await?;// The `[profile]` flags are project-wide settings every operator of the// project inherits, so recording them is a write: a viewer granted only// Read may narrow their own session but must not change the project.@@ -2082,6 +2054,91 @@ async fn fetch_and_accept_handoff_at())}+/// The repository a startup-context request names — by cwd, marker or+/// explicit scope — once the caller is authorized to read it. What `/handoff`+/// and `/brief` return is this repository's content (its handoff, its pinned,+/// rules and slot pages), keyed only on a project the caller named or a+/// directory they are in (#708), so both resolve it here: a subagent's brief+/// always comes from the repository its session start reads.+async fn resolve_authorized_startup_scope(+ state: &HookState,+ query: &HandoffQuery,+ viewer: Option<ai_memory_core::UserId>,+) -> anyhow::Result<(WorkspaceId, ProjectId)> {+ let repository = query.repository_identity();+ let aliases = crate::payload::marker_aliases_from_wire(+ query.project.as_deref(),+ ProjectSource::parse(query.project_src.as_deref()),+ repository.as_ref(),+ query.aliases.as_deref(),+ )+ .map_err(|_| anyhow::anyhow!("invalid marker aliases"))?;+ let (ws, proj) = resolve_project_ids_inner(+ state,+ query.cwd.as_deref(),+ query.workspace.as_deref(),+ query.project.as_deref(),+ ProjectStrategy::parse(query.project_strategy.as_deref()),+ repository.as_ref(),+ query.identity_style(),+ &aliases,+ ProjectSource::parse(query.project_src.as_deref()),+ false,+ viewer,+ )+ .await?;+ crate::grants::authorize_resolved(+ &state.reader,+ Some((ws, proj)),+ viewer,+ ai_memory_store::ProjectAccess::Read,+ )+ .await?;+ Ok((ws, proj))+}++/// `GET /brief`: the project brief a subagent starts with when its+/// repository's marker sets `[briefing] inject_on_subagent_start`. A subagent+/// runs inside its parent's session, so this route returns only the brief: it+/// never reads or claims a handoff, publishes no active project and records no+/// `[profile]` flags. A refusal is a 403 carrying the reason, as on+/// `/handoff`; any other failure is an empty 200, which the hook reads as+/// nothing to inject.+async fn handle_brief(+ State(state): State<Arc<HookState>>,+ Query(query): Query<HandoffQuery>,+ actor_ext: Option<axum::Extension<ai_memory_core::ActorContext>>,+ viewer_ext: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,+) -> impl IntoResponse {+ let actor = actor_identity(actor_ext);+ let viewer = viewer_ext.map(|axum::Extension(viewer)| viewer.user());+ match fetch_brief(&state, &query, actor.as_ref(), viewer).await {+ Ok(brief) => (StatusCode::OK, brief.unwrap_or_default()),+ Err(e) => match e.downcast_ref::<ai_memory_store::ScopeResolutionError>() {+ Some(refusal) if refusal.is_forbidden() => (StatusCode::FORBIDDEN, refusal.to_string()),+ _ => {+ warn!(error = %e, "brief fetch failed");+ (StatusCode::OK, String::new())+ }+ },+ }+}++async fn fetch_brief(+ state: &HookState,+ query: &HandoffQuery,+ actor: Option<&IdentityKey>,+ viewer: Option<ai_memory_core::UserId>,+) -> anyhow::Result<Option<String>> {+ let (ws, proj) = resolve_authorized_startup_scope(state, query, viewer).await?;+ let agent = query.agent.as_deref().map_or(AgentKind::Other, parse_agent);+ // An `additionalContext` over that agent's limit is swapped for a file+ // path and a short preview, which would cut the brief's closing fence;+ // render it to fit inline instead.+ let ceiling = (agent == AgentKind::ClaudeCode).then_some(CLAUDE_ADDITIONAL_CONTEXT_CHARS);+ render_requested_session_brief(state, query, ws, proj, actor, ceiling).await+}+/// Non-consuming notice for a pending handoff left unclaimed by/// `claim_handoff_on_session_start = false` (design: #959). Mirrors/// `render_inbox_notice`'s security bar: metadata only (id, `from_agent`,@@ -2392,12 +2449,16 @@ async fn fetch_managed_context(}))}+/// The `[briefing]` brief the query opted into, or `None`. `budget_ceiling`+/// lowers the clamped `max_chars` for a harness whose context field holds less+/// than [`BRIEF_BUDGET_MAX`].async fn render_requested_session_brief(state: &HookState,query: &HandoffQuery,workspace_id: WorkspaceId,project_id: ProjectId,viewer: Option<&ai_memory_core::IdentityKey>,+ budget_ceiling: Option<usize>,) -> anyhow::Result<Option<String>> {if !crate::payload::query_flag_truthy(query.briefing.as_deref()) {return Ok(None);@@ -2407,7 +2468,8 @@ async fn render_requested_session_brief(.as_deref().and_then(|v| v.trim().parse::<usize>().ok()).unwrap_or(BRIEF_BUDGET_DEFAULT)- .clamp(BRIEF_BUDGET_MIN, BRIEF_BUDGET_MAX);+ .clamp(BRIEF_BUDGET_MIN, BRIEF_BUDGET_MAX)+ .min(budget_ceiling.unwrap_or(BRIEF_BUDGET_MAX));let (core, recent) = state.reader.session_brief_pages_with_slot_visibility(@@ -19162,6 +19224,368 @@ pub(crate) mod tests {);}+ /// The query a `claude-code` subagent start sends to `/brief` for `cwd`.+ fn subagent_brief_query(cwd: &str, briefing: Option<&str>) -> HandoffQuery {+ HandoffQuery {+ agent: Some("claude-code".into()),+ cwd: Some(cwd.into()),+ briefing: briefing.map(Into::into),+ ..HandoffQuery::default()+ }+ }++ async fn subagent_brief(state: &Arc<HookState>, query: HandoffQuery) -> (StatusCode, String) {+ read_handoff_response(handle_brief(State(state.clone()), Query(query), None, None).await)+ .await+ }++ async fn upsert_brief_page(state: &HookState, cwd: &str, path: &str, body: &str) {+ let (ws, proj) = resolve_project_ids(+ state,+ Some(cwd),+ None,+ None,+ ProjectStrategy::Basename,+ &ai_memory_core::ActorKey::default(),+ )+ .await+ .unwrap();+ state+ .writer+ .upsert_page(brief_page(ws, proj, path, body, true))+ .await+ .unwrap();+ }++ /// A subagent starts with the brief its repository opted into:+ /// `GET /brief` compiles the brief a session start appends, slot bodies+ /// included, inside the untrusted-history fence.+ #[tokio::test]+ async fn brief_endpoint_returns_the_project_brief_with_its_slots() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let cwd = "/home/u/subagent-brief-repo";+ upsert_brief_page(+ &state,+ cwd,+ "_slots/essential-pages.md",+ "read notes/architecture.md before acting",+ )+ .await;++ let (status, body) =+ subagent_brief(&Arc::new(state), subagent_brief_query(cwd, Some("true"))).await;++ assert_eq!(status, StatusCode::OK);+ let slot = body+ .find("read notes/architecture.md before acting")+ .unwrap_or_else(|| panic!("the slot body must be delivered: {body}"));+ let start = body.find(UNTRUSTED_HISTORY_START).expect("the fence opens");+ let end = body.find(UNTRUSTED_HISTORY_END).expect("the fence closes");+ assert!(+ start < slot && slot < end,+ "the slot must sit inside the fence: {body}"+ );+ }++ /// Without the opt-in a subagent start gets nothing, as a session start+ /// without `[briefing]` gets no brief.+ #[tokio::test]+ async fn brief_endpoint_is_empty_without_the_opt_in() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let cwd = "/home/u/unbriefed-repo";+ upsert_brief_page(&state, cwd, "_slots/focus.md", "SLOT-BODY").await;+ let state = Arc::new(state);++ for briefing in [None, Some("false"), Some("0")] {+ let (status, body) = subagent_brief(&state, subagent_brief_query(cwd, briefing)).await;+ assert_eq!(status, StatusCode::OK, "{briefing:?}");+ assert!(body.is_empty(), "{briefing:?}: {body}");+ }+ }++ /// A subagent runs inside its parent's session, so its start must never+ /// take a baton meant for the parent's next session start: `/brief`+ /// neither renders nor claims a pending handoff. Control: the same query+ /// on `/handoff` delivers it, so the baton was there to take.+ #[tokio::test]+ async fn brief_endpoint_never_claims_a_pending_handoff() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ state+ .writer+ .upsert_page(brief_page(+ state.workspace_id,+ state.project_id,+ "_slots/focus.md",+ "SLOT-BODY",+ true,+ ))+ .await+ .unwrap();+ state+ .writer+ .insert_handoff(NewHandoff {+ workspace_id: state.workspace_id,+ project_id: state.project_id,+ from_session_id: None,+ from_agent: AgentKind::ClaudeCode,+ to_agent: None,+ cwd: None,+ summary: "HANDOFF-MARKER".to_string(),+ open_questions: Vec::new(),+ next_steps: Vec::new(),+ files_touched: Vec::new(),+ owner_user: None,+ })+ .await+ .unwrap();+ let query = HandoffQuery {+ workspace: Some("default".into()),+ project: Some("scratch".into()),+ ..subagent_brief_query(&tmp.path().to_string_lossy(), Some("true"))+ };+ let state = Arc::new(state);++ let (status, body) = subagent_brief(&state, query.clone()).await;+ assert_eq!(status, StatusCode::OK);+ assert!(body.contains("SLOT-BODY"), "{body}");+ assert!(+ !body.contains("HANDOFF-MARKER"),+ "a subagent start rendered the parent's baton: {body}"+ );+ assert!(+ open_handoff_exists(&state).await,+ "a subagent start consumed the parent's baton"+ );++ let (_, body) = read_handoff_response(+ handle_handoff(+ State(state.clone()),+ Query(query),+ None,+ None,+ None,+ HeaderMap::new(),+ )+ .await,+ )+ .await;+ assert!(body.contains("HANDOFF-MARKER"), "{body}");+ }++ /// The brief keeps to the marker's `max_chars` and, for `claude-code`, to+ /// its 10,000-character `additionalContext` ceiling, past which the text+ /// is swapped for a file path and a 2,000-character preview. Control:+ /// another agent gets the budget it asked for.+ #[tokio::test]+ async fn brief_endpoint_keeps_to_the_budget_and_to_the_context_ceiling() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let cwd = "/home/u/crowded-repo";+ for i in 0..BRIEF_CORE_PAGES_LIMIT {+ upsert_brief_page(+ &state,+ cwd,+ &format!("_rules/rule-{i:02}.md"),+ &format!(+ "Rule {i}: {}",+ "route every write through the single writer actor. ".repeat(30)+ ),+ )+ .await;+ }+ let state = Arc::new(state);+ let brief = |agent: &'static str, budget: &'static str| {+ let state = state.clone();+ async move {+ let query = HandoffQuery {+ agent: Some(agent.into()),+ briefing_budget: Some(budget.into()),+ ..subagent_brief_query(cwd, Some("true"))+ };+ let (status, body) = subagent_brief(&state, query).await;+ assert_eq!(status, StatusCode::OK);+ body+ }+ };++ let small = brief("claude-code", "2000").await;+ assert!(+ !small.is_empty() && small.len() <= 2_000,+ "{} bytes",+ small.len()+ );+ let capped = brief("claude-code", "20000").await;+ assert!(+ capped.len() > 2_000 && capped.len() <= CLAUDE_ADDITIONAL_CONTEXT_CHARS,+ "{} bytes",+ capped.len()+ );+ let other = brief("codex", "20000").await;+ assert!(+ other.len() > CLAUDE_ADDITIONAL_CONTEXT_CHARS,+ "the ceiling applies to one agent only: {} bytes",+ other.len()+ );+ }++ /// With `[slots] per_user` on, `/brief` carries the requesting operator's+ /// own slot and withholds everybody else's, as the session-start brief+ /// does.+ #[tokio::test]+ async fn per_user_subagent_brief_carries_own_slot_body_and_not_others() {+ let tmp = TempDir::new().unwrap();+ let mut state = make_state(&tmp).await;+ state.per_user_slots = true;+ let cwd = "/home/u/per-user-subagent-repo";+ let carol = ai_memory_core::ActorContext {+ user: Some("carol".into()),+ ..ai_memory_core::ActorContext::default()+ };+ let carol_ns = carol.identity_key().unwrap().path_segment();+ let bob_ns = ai_memory_core::IdentityKey::User("bob".into()).path_segment();+ for (path, body) in [+ ("_slots/current-focus.md".to_string(), "SHARED-CONTEXT"),+ (format!("_slots/{carol_ns}/focus.md"), "CAROL-SECRET"),+ (format!("_slots/{bob_ns}/focus.md"), "BOB-SECRET"),+ ] {+ upsert_brief_page(&state, cwd, &path, body).await;+ }++ let (status, body) = read_handoff_response(+ handle_brief(+ State(Arc::new(state)),+ Query(subagent_brief_query(cwd, Some("true"))),+ Some(axum::Extension(carol)),+ None,+ )+ .await,+ )+ .await;+ assert_eq!(status, StatusCode::OK);+ assert!(body.contains("SHARED-CONTEXT"), "{body}");+ assert!(body.contains("CAROL-SECRET"), "{body}");+ assert!(+ !body.contains("BOB-SECRET"),+ "another operator's slot body leaked into this brief: {body}"+ );+ }++ /// `/brief` returns a repository's pinned and slot pages keyed on a+ /// project the caller names (#708), so it enforces `/handoff`'s Read gate:+ /// Bob, holding nothing on a restricted project, gets the 403 with its+ /// reason and none of the brief; Alice, granted Read, gets the brief.+ #[tokio::test]+ async fn brief_endpoint_delivers_nothing_from_a_repository_the_viewer_cannot_read() {+ use ai_memory_core::{AuthorizedViewer, NewUser, UserRole};+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ state+ .writer+ .set_access_mode(state.project_id, ai_memory_store::AccessMode::Restricted)+ .await+ .unwrap();+ state+ .writer+ .upsert_page(brief_page(+ state.workspace_id,+ state.project_id,+ "_slots/focus.md",+ "SLOT-SECRET",+ true,+ ))+ .await+ .unwrap();+ let human = |name: &'static str| {+ let writer = state.writer.clone();+ async move {+ writer+ .create_human_user(+ NewUser {+ username: name.into(),+ name: None,+ email: None,+ },+ UserRole::User,+ None,+ false,+ )+ .await+ .unwrap()+ }+ };+ let alice = human("alice").await;+ let bob = human("bob").await;+ state+ .writer+ .grant_memory(+ alice,+ state.project_id,+ ai_memory_store::GrantLevel::Read,+ None,+ )+ .await+ .unwrap();+ let query = HandoffQuery {+ workspace: Some("default".into()),+ project: Some("scratch".into()),+ ..subagent_brief_query(&tmp.path().to_string_lossy(), Some("1"))+ };+ let state = Arc::new(state);+ let brief = |viewer: ai_memory_core::UserId| {+ let state = state.clone();+ let query = query.clone();+ async move {+ read_handoff_response(+ handle_brief(+ State(state),+ Query(query),+ None,+ Some(axum::Extension(AuthorizedViewer(viewer))),+ )+ .await,+ )+ .await+ }+ };++ let (status, body) = brief(bob).await;+ assert_eq!(status, StatusCode::FORBIDDEN, "{body}");+ assert!(body.contains("not authorized for scratch"), "{body}");+ assert!(!body.contains("SLOT-SECRET"), "leaked the brief: {body}");++ let (status, body) = brief(alice).await;+ assert_eq!(status, StatusCode::OK);+ assert!(body.contains("SLOT-SECRET"), "{body}");+ }++ /// The route is mounted: a hook reaches `/brief` through the router.+ #[tokio::test]+ async fn hook_router_serves_the_brief() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ upsert_brief_page(+ &state,+ "/home/u/routed-repo",+ "_slots/focus.md",+ "ROUTED-SLOT",+ )+ .await;+ let request = Request::builder()+ .method("GET")+ .uri("/brief?agent=claude-code&cwd=%2Fhome%2Fu%2Frouted-repo&briefing=true")+ .body(Body::empty())+ .unwrap();++ let response = hook_router(state).oneshot(request).await.unwrap();++ let (status, body) = read_handoff_response(response).await;+ assert_eq!(status, StatusCode::OK);+ assert!(body.contains("ROUTED-SLOT"), "{body}");+ }+/// `briefing=true` on the `/handoff` query returns the compiled project/// brief even with NO pending handoff — the `/clear` case of #176 — and/// a truthy value combined with a pending handoff returns both, handoffdiff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex cff33fc3..00ccbf4b 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -307,6 +307,16 @@ closing footer are never traded for content. The accepted algorithm and itsbudget invariants are recorded in[`design-tiered-session-brief.md`](design-tiered-session-brief.md).+**Subagent brief:** when the marker sets `[briefing] inject_on_subagent_start`,+the `claude-code` agent's `SubagentStart` hook prints the same brief as the subagent's+`additionalContext`. It comes from `GET /brief`, which resolves and authorizes+the project exactly as `/handoff` does (one shared helper) and renders only the+brief: it never reads or claims a handoff, publishes no active project and+records no `[profile]` flags, since a subagent runs inside its parent's+session. For that agent the budget is also capped at 9,800 characters, under+the 10,000-character hook context limit. A server without the route answers+404 and the hook prints `{}` as before; it never falls back to `/handoff`.+**Cross-project profile:** after the project brief, SessionStart appends afenced, byte-budgeted, byte-stable digest of the user's usual choices from otherprojects (`docs/cross-project-profile.md`), filtered by the stack the project'sdiff --git a/docs/marker-file.md b/docs/marker-file.mdindex 369a93b6..2244526c 100644--- a/docs/marker-file.md+++ b/docs/marker-file.md@@ -191,6 +191,16 @@ inject_on_session_start = "true"# defaults to 4000.max_chars = 4000+# Optional. Hand the same brief to each `claude-code` subagent when it starts+# (`SubagentStart`), so a delegated task begins with the project's rules and+# slots too. Independent of `inject_on_session_start`; `max_chars` bounds it,+# and that agent's 10,000-character hook context limit caps it. It comes+# from the read-only `GET /brief`, which never reads or claims a handoff, so a+# subagent cannot take its parent session's baton; a server without that+# route answers 404 and the subagent starts without a brief. Off by default:+# every subagent pays for the brief in tokens, so opt in per repo.+inject_on_subagent_start = "true"+# Optional. Stop delivering this project's handoff at session start. Only an# explicit false / "no" / "off" / "0" turns it off; the default is to deliver.# Handoffs are still created when a session ends, and stay open (an agent can@@ -320,7 +330,7 @@ scoped to the current project and cover every project only when you pass[usage.md](usage.md#search-from-the-terminal) and[usage.md](usage.md#recent-pages-from-the-terminal)).-`default_global` and `inject_on_session_start` accept a truthy value+`default_global`, `inject_on_session_start` and `inject_on_subagent_start` accept a truthy value(`true` / `1` / `yes` / `on`, quoted or bare; section-style keys areparsed leniently); anything else behaves as absent. `max_chars` is aplain integer.diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 46be9fa6..f2683ba7 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -67,6 +67,7 @@ the legitimate restricted-project control and the failed-query cases.| 4k | The idle-session auto-end (`[sessions] idle_end_after_hours`) never ends a session it does not own: idle-threshold + active-run exclusion at selection, guarded CAS stamp, conditional page write, owner attribution | `ai-memory-store/src/reader.rs` `idle_open_sessions` — ONE statement: the idle-threshold predicate (`ended_at IS NULL` + `COALESCE(MAX(observations.created_at), started_at) < cutoff`), `ORDER BY last_activity ASC` capped at the batch, and a correlated `pages` subquery bound to the session's own `workspace_id`/`project_id` and to the path rendered in SQL from the id blob (`lower(hex(id))` with 8-4-4-4-12 hyphens — byte-for-byte the Rust `format!("sessions/{session_id}.md")`, proven by the selection test with a page present and absent) capturing the latest `sessions/<id>.md` version as the tick's write precondition — a read path, never a write; `active_managed_run_native_session_ids` (only `state = 'active'` managed runs). `ai-memory-store/src/ops.rs` `idle_end_sessions` — per-candidate `UPDATE sessions … WHERE id AND workspace_id AND project_id AND ended_at IS NULL` that also re-verifies the session's observation count (EVERY row of the session — the digest's population, no per-row scope filter) and the latest page version; `ended_at` = the tick's clock (last activity kept in the audit detail), `ended_observation_count` counted at the stamp, one `idle_session_end` audit row in the same transaction, and the consolidation gate: the job is enqueued INSIDE the stamp's transaction (`session_consolidation::enqueue_in_tx`), so a failed enqueue rolls back the stamp, the audit row and the job, while the page the tick already wrote stays as an ordinary version; a lost stamp skips the enqueue and never aborts the batch. The lifecycle-only gate applies the same scope/open guard before any mutation, re-checks substantiveness atomically, reuses `end_lifecycle_only_session_in_tx` (releasing the accepted handoff), and writes its OWN `idle_session_end` audit row distinct from the `release_lifecycle_only_handoff` row. `ai-memory-hooks/src/idle_end.rs` `run_idle_end_tick` — excludes active-run sessions in Rust via `SessionId::from_native` BEFORE the batch bound (the serve loop over-fetches, so an excluded backlog cannot starve the batch), classifies via `session_has_substantive_observation`, builds the page and its count from one digest snapshot (`SessionDigest::load_with_count` — the count the CAS guard re-verifies), writes the page with `Wiki::write_page_if` under `PagePrecondition::Latest(seen)`/`Absent` (`Mismatch` skips the whole session), keeps an agent-written page (`session_page_written_by_agent`), and attributes via `router.rs` `stored_session_identity` (the hook path's own fail-closed parse). The tick creates no additional handoff: the consolidation gate and the lifecycle-only release gate are its only handoff-affecting effects | `store` `tests/suite/idle_session_end.rs` — guard by guard: `idle_end_loses_to_an_already_ended_session` (the `ended_at IS NULL` predicate; fails with it removed), `idle_end_counts_the_same_observation_population_as_the_digest` (a multi-project session ends with `ended_observation_count` = 2; fails if the CAS count's population diverges from the digest/counter's), `idle_end_cas_rejects_a_stale_observation_count` (the count guard; fails with it removed), `idle_end_cas_rejects_a_moved_latest_page` (the page-version guard; fails with it removed), `idle_end_pre_stamp_non_end_observation_in_window_loses_the_cas` / `idle_end_pre_stamp_checkpoint_page_in_window_loses_the_cas` / `idle_end_pre_stamp_real_session_end_in_window_loses_the_cas` (the test-only seam runs on the writer connection BEFORE the candidate's stamp transaction and injects the SQL effects a concurrent writer would leave in the read-to-stamp window — simulated effects, not a run of the hook's `SessionEnd` handler; a `Lost` with the consolidation gate on creates no job; each fails with its guard removed), `idle_end_candidate_cannot_cross_the_project_boundary` (a foreign-scope candidate is refused; same-scope control ends), `idle_end_lifecycle_only_refuses_a_foreign_scope_candidate` (the lifecycle-only scope/open guard: `Lost`, no audit, the claimed handoff stays `Accepted`; fails with the guard removed), `idle_end_lifecycle_only_refuses_an_already_ended_session_with_control` (dedicated already-ended case: `Lost` with no audit and no handoff release, next to the open control in the same fixture that ends and releases), `idle_end_lifecycle_only_loses_to_a_substantive_race` (the atomic substantiveness re-check), `idle_end_reopens_the_handoff_a_lifecycle_only_session_claimed` (exactly one `idle_session_end` row, distinct from the release row), `idle_end_watermark_converges_a_late_real_session_end` (a late real `SessionEnd` converges through `AlreadyEnded`/`ReEnd`), `idle_end_batch_stamps_every_candidate_in_one_command`, `idle_selection_is_cutoff_scoped_ordered_and_bounded` (threshold, order, bound; `seen_page_id` captured with a page present and `None` without — the `session_page_path` rendering), `idle_end_stamps_watermark_audit_page_and_consolidation`, `idle_end_consolidation_enqueue_shares_the_callers_transaction` + `idle_end_consolidation_enqueue_failure_rolls_back_and_retries` (the in-transaction enqueue; fails out-of-transaction), `session_observation_count_refuses_foreign_and_missing_scopes` (foreign workspace / foreign project / missing id each count 0; the right tuple counts — the raw-id reader's scope join), `enqueue_in_tx_refuses_a_foreign_scope_and_leaves_the_foreign_queue` (a foreign tuple enqueues nothing and the foreign project's queue is unchanged; the right tuple enqueues — the job INSERT's scope binding). `hooks` `tests/suite/idle_end.rs` + `src/synth.rs` `load_with_count_scopes`: `foreign_and_missing_tuples_load_nothing_the_right_tuple_loads` (`SessionDigest::load_with_count` refuses a foreign tuple and a missing id as `SessionCollision`; the right tuple loads and counts — the tuple validation; fails with it removed), `idle_tick_skips_a_session_ended_by_a_real_session_end_between_selection_and_write` (a real `/hook` `SessionEnd` landing between selection and page write leaves the hook's page as the only version and no additional handoff from the tick; fails with the conditional write removed — the CAS itself is proven by the store tests above), `idle_tick_late_real_session_end_with_new_work_reends_with_handoff` (the late real end re-ends with exactly one handoff), `idle_tick_excludes_active_managed_run_sessions` (+control after `cancel_managed_run`), `idle_tick_excluded_backlog_cannot_starve_the_batch` (25 excluded sessions cannot consume the batch), `idle_tick_ends_idle_substantive_session_with_page_job_and_no_handoff` (owner attribution via `last_modified_by.username`; no additional handoff from the tick), `idle_tick_lifecycle_only_ends_without_page_or_job_and_creates_no_handoff`, `idle_tick_skips_active_sessions_and_respects_the_batch`, `idle_tick_keeps_a_session_page_written_by_the_agent`; `cli` `serve.rs` `idle_end_tick_does_not_start_when_disabled_or_maintenance_off` and `idle_end_tick_ends_an_idle_session_on_the_first_pass` (tick-clock `ended_at`, paused `tokio::time`), `config.rs` `sessions_idle_end_defaults_off_loads_from_toml_and_rejects_out_of_range` | STRONG || 4l | The cut-off-session pointer (session-start notice, `memory_briefing` `recent_sessions`, `memory_handoff_list` `newer_unended_session`) names only the caller's own or shared sessions, carries no captured text, and claims nothing; `memory_read_session_observations` without a `session_id` defaults through the same owner-filtered, scope-bound ordering | `ai-memory-store/src/reader.rs` `recent_session_activity` applies the same `OwnerFilter` clause on the session row as `sessions_for_scope` (`actor_user IS NULL OR = :actor`, or `IS NULL` for an unattributed caller) inside the resolved, authorized `(workspace, project)`; `ai-memory-hooks/src/router.rs` `render_continuity_notice` renders only the stored agent kind, the session UUID, an age and the scope's server-side names (the `render_handoff_notice`/`render_inbox_notice` bar) and is computed after `authorize_resolved`; the MCP fields reuse the tool's own resolved scope and owner filter | router `session_start_never_names_another_operators_cut_off_session` (adversarial: with registered users, bob's cut-off session is not named to alice; control: bob's next session is pointed at it; fails with the owner clause removed), `session_start_names_a_session_cut_off_without_ending` (the notice carries none of the session's prompt, command or output text); store `session_activity.rs` `the_owner_filter_hides_another_operators_sessions`; MCP `memory_read_session_observations_default_never_crosses_owner_or_project` (adversarial: bob's newer open session in alice's cwd and alice's newer session in another project are never alice's default; control: alice's own older session is, and bob's default is his own; fails with the owner filter set to `Any`); CLI `harness_switch_e2e.rs` (real server and hook binary; no captured text in the notice) | STRONG || 4m | A project's `[handoff] deliver_on_session_start = false` hides and claims only its own session-start baton | `ai-memory-hooks/src/router.rs` `fetch_and_accept_handoff_at` reads `HandoffQuery.handoff` for the one resolved `(workspace, project)`: opted out, it neither reads (`startup_handoff`), claims, announces nor renders the continuity notice; the handoff stays `open`, and the SessionEnd path that creates it is untouched | `router.rs` `handoff_opt_out_leaves_the_baton_open_and_undelivered` (falsy values hide the baton and leave it open; `1` still delivers and claims) and `handoff_opt_out_is_scoped_to_the_requesting_project` (a second project keeps receiving its own baton, never the opted-out one's, and does not consume it) | STRONG |+| 4n | A subagent's brief reads only its repository's brief and never claims, publishes or records | `ai-memory-hooks/src/router.rs` `handle_brief`/`fetch_brief` — the project comes from `resolve_readable_startup_scope`, the helper `/handoff` also uses (cwd, marker or explicit scope, then `grants::authorize_resolved(.., ProjectAccess::Read)`, whose refusal is a `403` with its reason); only the brief is rendered, with `[slots] per_user` visibility for the requesting identity and stored text inside the untrusted-history fence; no handoff is read or claimed, no active project is published and no `[profile]` flag is written. Clients (`ai-memory hook`, `hooks/claude-code/subagent-start.{sh,ps1}`) fetch it only for the `claude-code` agent's `SubagentStart` and only with the marker's `[briefing] inject_on_subagent_start`, and never fall back to `/handoff` when the route is missing | `router.rs` `brief_endpoint_never_claims_a_pending_handoff` (the baton stays open; control: `/handoff` with the same query delivers it), `brief_endpoint_delivers_nothing_from_a_repository_the_viewer_cannot_read` (no grant: `403` and no page text; control: a Read grant), `per_user_subagent_brief_carries_own_slot_body_and_not_others` (another operator's slot withheld; own slot delivered), `brief_endpoint_is_empty_without_the_opt_in`; `hook.rs` `subagent_start_delivers_the_opted_in_brief` (no `/handoff` request), `subagent_start_with_no_brief_prints_an_empty_reply` (a `404` never falls back to `/handoff`), `subagent_brief_skips_agents_without_subagent_context`; `tests/hooks/test_lib.sh` (the shell bundle never asks `/handoff`) | STRONG || 5a | Pages shared: `author_id` is never a read filter (invariant #16) | `ai-memory-store/src/reader.rs` `search_pages`/`page_body_by_ids` — `author_id` is an attribution JOIN only, never a WHERE term; `observation_stream_votes` lets every session vote whatever its owner (the owner filter only withholds the observation excerpt and ids, never the vote or the page) | `multi_session.rs` — a page with a **non-null** `author_id` (operator A) is readable by operator B in the same project; `multi_session.rs` `another_operators_observations_lift_their_session_page_in_a_shared_project` (operator B's owned session, authored page and observations lift that page for operator A's query); `ai-memory-mcp` `server.rs` `observation_stream_evidence_stays_inside_a_restricted_project` (a second operator with only a read grant gets the session page lifted by the first operator's observation); `multi_session.rs` `observation_excerpts_follow_the_session_owner_while_the_vote_stays_shared` (B still gets A's session page ranked by A's observation, with the page's own snippet) | STRONG || 5b | Page supersession (loser stays reachable) | `ai-memory-store/src/ops.rs` `upsert_page_in_tx` — demote `is_latest=0` (never delete) + `supersedes` chain; read side: `reader.rs` `page_versions` lists every row at the path, with no `is_latest` filter, for `/web/w/…/h/*path` and `/api/v1/…/history/*path`. It does apply TTL expiry (`reader.rs` `history_visible`): a version whose own `expires_at` passed is neither listed nor readable by id, a path whose live version expired shows no history at all (the forget sweep hard-deletes every row there), and a `supersedes` link to a hidden version reads as `null`. Expiry is the only thing that hides a superseded version; a concurrent write never does | `multi_session.rs` `concurrent_writes_to_one_path_supersede_rather_than_destroy`; `retrieval_superseded.rs`; `multi_session.rs` `page_history_keeps_the_overwritten_version_and_stays_in_scope`; `ai-memory-web` `history_replay.rs` `history_keeps_both_sides_of_a_concurrent_divergent_write` (two attributed writers on one base: all three versions and both authors listed, one `is_latest`, the two writers' versions diff by id) and `history_lists_k_plus_one_versions_newest_first_and_diffs_the_latest`; bite: an `is_latest = 1` filter in `page_versions` fails both; `history_hides_expired_versions_and_expired_pages` (an expired superseded version and every version of a page whose live version expired answer 404 by path and by id on HTML and JSON, and the live successor's `supersedes` is `null`; control: a TTL in the future is listed and diffable; bites with the per-row predicate removed, with the live-version clause disabled, and with the `supersedes` hiding removed) | STRONG || 5c | Watcher reindex and Wiki writes share per-page serialization (invariant #16) | `ai-memory-wiki/src/wiki.rs` `reindex_page` takes `mutation_lock.read` before `reindex_page_locked` takes `lock_page`, covering disk read through the single-writer upsert; callers already holding the exclusive global guard do not reacquire it. `write_page` uses the same page mutex and `apply_batch` retains sorted, deduplicated locks; embedding runs after both guards are released | `wiki.rs` `reindex_page_lock_waits_before_reading_and_allows_another_path` (transient snapshot refused while locked, another path progresses, release indexes the committed bytes without rewriting disk), `reindex_page_lock_serializes_write_through_the_upsert` and `reindex_page_lock_and_reversed_duplicate_batches_do_not_deadlock` (real concurrent operations, final disk/SQL winner and supersession ancestry preserved); all three fail with the reindex page guard removed. `reindex_page_lock_releases_both_guards_before_embedding` checks both body and abstract embedding; `decay_cleanup_reindex_does_not_embed_under_the_exclusive_lock` covers the exclusive caller | STRONG for a shared Wiki handle and its clones. External editors and independently constructed Wiki handles do not participate in these locks |diff --git a/hooks/_lib.sh b/hooks/_lib.shindex ee7165c8..a88b1b0c 100644--- a/hooks/_lib.sh+++ b/hooks/_lib.sh@@ -115,7 +115,7 @@ ai_memory_marker_declares_settings() {ai_memory_strip_utf8_bom <"$file" \| LC_ALL=C grep -Eq '^[[:space:]]*aliases[[:space:]]*=' && return 0ai_memory_marker_declares_server "$file" && return 0- for key in default_global inject_on_session_start max_chars contribute consume deliver_on_session_start; do+ for key in default_global inject_on_session_start inject_on_subagent_start max_chars contribute consume deliver_on_session_start; do[ -n "$(ai_memory_parse_toml_flag "$file" "$key")" ] && return 0donereturn 1@@ -817,8 +817,9 @@ ai_memory_marker_qs() {}# Build `&briefing=<v>[&briefing_budget=<v>]` from the `[briefing]` section-# of the marker walked up from "$1" (inject_on_session_start + optional-# max_chars). Prints nothing when cwd is absent or the repo did not opt in.+# of the marker walked up from "$1" (the opt-in key "$2", by default+# inject_on_session_start, + optional max_chars). Prints nothing when cwd is+# absent or the repo did not opt in.# NOT part of ai_memory_marker_qs on purpose: agents that deliver the brief# once per session (kimi-code, via the first user prompt — kimi discards# SessionStart hook stdout) append this only on the first fetch, so the@@ -826,13 +827,14 @@ ai_memory_marker_qs() {# is decided server-side.ai_memory_briefing_qs() {cwd="$1"+ _ambkey="${2:-inject_on_session_start}"[ -z "$cwd" ] && return 0# Settings walk (#668): a nested capture-only marker must not shadow an# outer marker's [briefing] opt-in.marker=$(ai_memory_find_settings_marker "$cwd")[ -n "$marker" ] || return 0qs=""- briefing=$(ai_memory_parse_toml_flag "$marker" inject_on_session_start)+ briefing=$(ai_memory_parse_toml_flag "$marker" "$_ambkey")case "$(printf '%s' "$briefing" | tr '[:upper:]' '[:lower:]')" in1|true|yes|on) ;;*) return 0 ;;@@ -843,6 +845,13 @@ ai_memory_briefing_qs() {printf '%s' "$qs"}+# The `[briefing] inject_on_subagent_start` pair for cwd "$1": the query a+# subagent start sends to `/brief`. Prints nothing without that+# opt-in, whatever `inject_on_session_start` says.+ai_memory_subagent_briefing_qs() {+ ai_memory_briefing_qs "$1" inject_on_subagent_start+}+# Path of the once-per-session "brief delivered" marker for "$1" (a session# id or a caller-built fallback key), sanitized to a safe file name under# the shared state dir.@@ -1038,6 +1047,14 @@ ai_memory_get_handoff() {fi}+# GET the read-only subagent brief at URL "$1", with ai_memory_get_handoff's+# guards: a URL without `cwd`, or for a server-routed repository, is never+# sent. It keeps a name of its own because `/brief` claims nothing, while+# every ai_memory_get_handoff caller claims a baton.+ai_memory_get_brief() {+ ai_memory_get_handoff "$1"+}+# Encode stdin as a JSON string (with surrounding quotes). Used by hooks# whose stdout contract is JSON rather than raw context text: Antigravity's# PreInvocation hook and Claude Code's session-start hook (which wraps thediff --git a/hooks/claude-code/subagent-start.ps1 b/hooks/claude-code/subagent-start.ps1index fd1fb259..69beed7b 100644--- a/hooks/claude-code/subagent-start.ps1+++ b/hooks/claude-code/subagent-start.ps1@@ -1,3 +1,3 @@. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"-Invoke-AiMemoryHook -Event "subagent-start" -Agent "claude-code"+Invoke-AiMemoryHook -Event "subagent-start" -Agent "claude-code" -SubagentStartBriefexit 0diff --git a/hooks/claude-code/subagent-start.sh b/hooks/claude-code/subagent-start.shindex f8d341ba..7448fc25 100755--- a/hooks/claude-code/subagent-start.sh+++ b/hooks/claude-code/subagent-start.sh@@ -2,6 +2,12 @@# Claude Code subagent-start hook — forwards the event so the server can seed# the subagent's session id for drop_subagent_captures (so the whole nested# session, incl. the unmarked tail, is dropped). Mirrors stop.sh.+#+# A repository that opts into `[briefing] inject_on_subagent_start` also hands+# the subagent its project brief, as the native hook does. It comes from the+# read-only `/brief`, never `/handoff`, whose fetch would claim the parent+# session's baton. Cursor also runs these hook settings, and its handling of+# the envelope is unverified, so a Cursor payload gets no brief._lib_dir="$(dirname "$0")"[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/..". "$_lib_dir/_lib.sh"@@ -10,8 +16,20 @@ SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"PAYLOAD=$(cat)CWD=$(ai_memory_extract_cwd "$PAYLOAD")QS=$(ai_memory_marker_qs "$CWD")+BRIEF_QS=$(ai_memory_subagent_briefing_qs "$CWD")+case "$PAYLOAD" in+ *'"cursor_version"'*) BRIEF_QS="" ;;+esacprintf '%s' "$PAYLOAD" \| ai_memory_post_hook "$SERVER/hook?event=subagent-start&agent=claude-code${QS}" >/dev/null 2>&1 || true-printf '{}\n'++BRIEF=""+[ -n "$BRIEF_QS" ] && BRIEF=$(ai_memory_get_brief "$SERVER/brief?agent=claude-code${QS}${BRIEF_QS}" 2>/dev/null || true)+if [ -n "$BRIEF" ]; then+ printf '{"hookSpecificOutput":{"hookEventName":"SubagentStart","additionalContext":%s}}\n' \+ "$(printf '%s' "$BRIEF" | ai_memory_json_string)"+else+ printf '{}\n'+fiexit 0diff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1index 81440d6a..65f707a7 100644--- a/hooks/lib/ai-memory-hook.ps1+++ b/hooks/lib/ai-memory-hook.ps1@@ -65,7 +65,7 @@ function Test-AiMemoryMarkerDeclaresSettings {}if ([regex]::IsMatch($text, '(?m)^\s*aliases\s*=')) { return $true }if ([regex]::IsMatch($text, '(?m)^[\s]*server\s*=')) { return $true }- foreach ($key in @("default_global", "inject_on_session_start", "max_chars", "contribute", "consume", "deliver_on_session_start")) {+ foreach ($key in @("default_global", "inject_on_session_start", "inject_on_subagent_start", "max_chars", "contribute", "consume", "deliver_on_session_start")) {if ([regex]::IsMatch($text, "(?m)^\s*$key\s*=")) { return $true }}return $false@@ -420,17 +420,18 @@ function Test-AiMemoryTruthy {}# Build `&briefing=<v>[&briefing_budget=<v>]` from the `[briefing]` section-# of the marker walked up from $Cwd. Returns "" when the repo did not opt-# in. Used by agents that deliver the compiled project brief once per-# session (kimi-code, via the first user prompt — kimi discards-# SessionStart hook stdout) so the server does not recompose the brief on-# every request. The char-budget clamp is server-side.+# of the marker walked up from $Cwd, for the opt-in $Key (by default+# inject_on_session_start; a subagent start passes inject_on_subagent_start).+# Returns "" when the repo did not opt in. Used by agents that deliver the+# compiled project brief once per session (kimi-code, via the first user+# prompt — kimi discards SessionStart hook stdout) so the server does not+# recompose the brief on every request. The char-budget clamp is server-side.function Get-AiMemoryBriefingQuery {- param([string] $Cwd)+ param([string] $Cwd, [string] $Key = "inject_on_session_start")if (-not $Cwd) { return "" }$marker = Get-AiMemoryMarkerToml -Cwd $Cwdif (-not $marker) { return "" }- $briefing = Get-AiMemoryTomlFlag -File $marker -Key "inject_on_session_start"+ $briefing = Get-AiMemoryTomlFlag -File $marker -Key $Keyif (-not (Test-AiMemoryTruthy -Value $briefing)) { return "" }$budget = Get-AiMemoryTomlFlag -File $marker -Key "max_chars"$qs = "&briefing=$([uri]::EscapeDataString($briefing))"@@ -1011,7 +1012,10 @@ function Invoke-AiMemoryHook {[switch] $BriefingOncePerSession,# Grok PostToolUse: wrap a fetched handoff as additionalContext and# only fetch once per session. Other events must not set this.- [switch] $GrokPostTool+ [switch] $GrokPostTool,+ # `claude-code` SubagentStart: hand the subagent the `[briefing]+ # inject_on_subagent_start` brief from the read-only `/brief`.+ [switch] $SubagentStartBrief)$Server = if ($env:AI_MEMORY_HOOK_URL) { $env:AI_MEMORY_HOOK_URL } else { "http://127.0.0.1:49374" }@@ -1109,6 +1113,38 @@ function Invoke-AiMemoryHook {Clear-AiMemorySessionId -Agent $Agent}+ # A subagent runs inside its parent's session, so its brief comes from the+ # read-only `/brief`, never `/handoff`, whose fetch would claim the+ # parent's baton (parity with the native hook and subagent-start.sh). A+ # Cursor payload gets none: its handling of the envelope is unverified.+ # No brief prints nothing, as this hook always did.+ if ($SubagentStartBrief) {+ if ($Cwd -and -not $Payload.Contains('"cursor_version"')) {+ $BriefQS = Get-AiMemoryBriefingQuery -Cwd $Cwd -Key "inject_on_subagent_start"+ if ($BriefQS) {+ $NoProxy = Get-AiMemoryNoProxy+ try {+ $Response = Invoke-WebRequest @NoProxy `+ -UseBasicParsing `+ -TimeoutSec 2 `+ -Uri "$Server/brief?agent=$Agent$QS$BriefQS" `+ -Headers $Headers+ if ($null -ne $Response -and $Response.Content) {+ $Wrapped = @{+ hookSpecificOutput = @{+ hookEventName = "SubagentStart"+ additionalContext = [string]$Response.Content+ }+ }+ [Console]::Out.Write(($Wrapped | ConvertTo-Json -Depth 5 -Compress))+ }+ } catch {+ }+ }+ }+ return+ }+# `GET /handoff` claims the newest open baton in whatever project the# server resolves. A payload that names no directory would send no `cwd`,# the server would fall back to its default or the caller's last activediff --git a/tests/hooks/test_lib.sh b/tests/hooks/test_lib.shindex 5923a20a..249aa417 100755--- a/tests/hooks/test_lib.sh+++ b/tests/hooks/test_lib.sh@@ -541,6 +541,23 @@ assert_eq "marker_qs omits handoff for a sibling project and for a truthy value"assert_eq "marker_qs omits handoff when deliver_on_session_start is true" \"&cwd=$(ai_memory_url_encode "$TMP/handoff-on")&profile_contribute=1&profile_consume=1" \"$(ai_memory_marker_qs "$TMP/handoff-on")"+# `[briefing] inject_on_subagent_start` alone is a settings boundary too, and+# only the subagent-start query forwards it; the session-start opt-in stays+# its own.+mkdir -p "$TMP/subagent-only/inner" "$TMP/subagent-key-only/inner" "$TMP/session-brief-only"+printf 'workspace = "outer"\n' >"$TMP/subagent-only/.ai-memory.toml"+printf '[briefing]\ninject_on_subagent_start = true\nmax_chars = 6000\n' >"$TMP/subagent-only/inner/.ai-memory.toml"+printf 'workspace = "outer"\n' >"$TMP/subagent-key-only/.ai-memory.toml"+printf '[briefing]\ninject_on_subagent_start = true\n' >"$TMP/subagent-key-only/inner/.ai-memory.toml"+printf '[briefing]\ninject_on_session_start = true\n' >"$TMP/session-brief-only/.ai-memory.toml"+assert_eq "subagent-brief-only marker is a settings boundary" \+ "$TMP/subagent-key-only/inner/.ai-memory.toml" "$(ai_memory_find_settings_marker "$TMP/subagent-key-only/inner")"+assert_eq "the subagent briefing query forwards its own opt-in" \+ "&briefing=true&briefing_budget=6000" "$(ai_memory_subagent_briefing_qs "$TMP/subagent-only/inner")"+assert_eq "the session-start briefing query ignores the subagent opt-in" \+ "" "$(ai_memory_briefing_qs "$TMP/subagent-only/inner")"+assert_eq "the subagent briefing query ignores the session-start opt-in" \+ "" "$(ai_memory_subagent_briefing_qs "$TMP/session-brief-only")"HF_PS=$(grep -q 'deliver_on_session_start' hooks/lib/ai-memory-hook.ps1 \&& grep -q '&handoff=0' hooks/lib/ai-memory-hook.ps1 && printf 'ok' || printf 'missing')assert_eq "powershell marker query forwards the [handoff] opt-out (static)" "ok" "$HF_PS"@@ -566,6 +583,20 @@ else&& printf 'ok' || printf 'missing')assert_eq "powershell marker query forwards [profile] flags (static)" "ok" "$PS_PROFILE"fi+if [ -n "$PSH" ]; then+ PS_SUB_CWD=$(host_path "$TMP/subagent-only/inner")+ PS_SUB_MARKER=$(host_path "$TMP/subagent-key-only/inner/.ai-memory.toml")+ PS_SUB=$(HOME="$TMP" "$PSH" -NoProfile -ExecutionPolicy Bypass -Command \+ ". '$PS_LIB'; (Get-AiMemoryBriefingQuery -Cwd '$PS_SUB_CWD' -Key 'inject_on_subagent_start') + '|' + (Get-AiMemoryBriefingQuery -Cwd '$PS_SUB_CWD') + '|' + (Test-AiMemoryMarkerDeclaresSettings -File '$PS_SUB_MARKER')")+ assert_eq "powershell forwards only the subagent opt-in, a settings boundary" \+ "&briefing=true&briefing_budget=6000||True" "$PS_SUB"+else+ PS_SUB=$(grep -q '"inject_on_subagent_start"' hooks/lib/ai-memory-hook.ps1 \+ && grep -q '/brief?agent=' hooks/lib/ai-memory-hook.ps1 \+ && grep -q 'SubagentStartBrief' hooks/claude-code/subagent-start.ps1 \+ && printf 'ok' || printf 'missing')+ assert_eq "powershell delivers the subagent brief (static)" "ok" "$PS_SUB"+fi# A capture-only marker with no scope-declaring ancestor: still transparent,# and resolution falls back exactly as it does with no marker at all.@@ -1204,6 +1235,57 @@ doneassert_eq "session-start bundles that fetch the handoff were found" "yes" \"$([ "$BRIEF_BUNDLES" -ge 9 ] && printf 'yes' || printf 'no (%s)' "$BRIEF_BUNDLES")"+# --- the subagent-start bundle hands the subagent its brief --------------+# `[briefing] inject_on_subagent_start` gives each subagent the+# project brief from the read-only `/brief` route, as the native hook does,+# and never asks `/handoff`, whose fetch claims the parent session's baton.+# Without that opt-in (the session-start one alone included) the bundle+# replies `{}` as it always did.+SUB_CURL_BIN="$TMP/fake-brief-curl-bin"+mkdir -p "$SUB_CURL_BIN"+cat >"$SUB_CURL_BIN/curl" <<'EOF'+#!/bin/sh+printf '%s\n' "$*" >>"$AI_MEMORY_CURL_LOG"+case "$*" in+ *'/brief?'*) printf 'subagent-brief-context' ;;+ *'/handoff?'*) printf 'parent-handoff' ;;+esac+EOF+chmod +x "$SUB_CURL_BIN/curl"+SUB_REPO="$TMP/subagent-brief-on"+mkdir -p "$SUB_REPO"+printf '[briefing]\ninject_on_subagent_start = true\nmax_chars = 6000\n' >"$SUB_REPO/.ai-memory.toml"++# Runs the subagent-start.sh bundle from repository "$1" and prints its stdout.+subagent_start_output() {+ rm -rf "$TMP/subagent-data" "$FAKE_CURL_LOG"+ printf '{"cwd":"%s","session_id":"parent-s","hook_event_name":"SubagentStart","agent_id":"agent-1","agent_type":"Explore"}' "$1" \+ | PATH="$SUB_CURL_BIN:$PATH" AI_MEMORY_CURL_LOG="$FAKE_CURL_LOG" \+ AI_MEMORY_DATA_DIR="$TMP/subagent-data" AI_MEMORY_HOOK_URL='http://memory.test' \+ sh "$(dirname "$0")/../../hooks/claude-code/subagent-start.sh" 2>/dev/null+}++assert_eq "the subagent-start bundle injects the opted-in brief" \+ '{"hookSpecificOutput":{"hookEventName":"SubagentStart","additionalContext":"subagent-brief-context"}}' \+ "$(subagent_start_output "$SUB_REPO")"+assert_eq "the subagent brief GET carries the opt-in and the budget" "yes" \+ "$(grep -q '/brief?agent=claude-code&cwd=.*&briefing=true&briefing_budget=6000' "$FAKE_CURL_LOG" && printf 'yes' || printf 'no')"+assert_eq "a subagent start never fetches the handoff" "no" \+ "$(grep -q '/handoff?' "$FAKE_CURL_LOG" && printf 'yes' || printf 'no')"+assert_eq "a subagent start without the subagent opt-in replies {}" "{}" \+ "$(subagent_start_output "$BRIEF_REPO")"+assert_eq "a subagent start without the subagent opt-in asks for no brief" "no" \+ "$(grep -q '/brief?' "$FAKE_CURL_LOG" 2>/dev/null && printf 'yes' || printf 'no')"+# Hook scripts run without `set -e`; this suite's would end the substitution at+# the auth-header lookup's non-zero status.+rm -f "$FAKE_CURL_LOG"+assert_eq "get_brief refuses a URL without cwd" "" \+ "$(set +e; export PATH="$SUB_CURL_BIN:$PATH" AI_MEMORY_CURL_LOG="$FAKE_CURL_LOG"+ ai_memory_get_brief 'http://memory.test/brief?agent=claude-code&briefing=true')"+assert_eq "get_brief fetches a URL with cwd" "subagent-brief-context" \+ "$(set +e; export PATH="$SUB_CURL_BIN:$PATH" AI_MEMORY_CURL_LOG="$FAKE_CURL_LOG"+ ai_memory_get_brief 'http://memory.test/brief?agent=claude-code&cwd=%2Frepo&briefing=true')"+# --- a handoff is never claimed without a project directory -------------# `GET /handoff` claims the newest open handoff in whatever project the server# resolves. A payload that names no directory sent no `cwd`, so the server fell@@ -1308,6 +1390,37 @@ PS_BRIEF_STATIC=$(grep -Fq 'if ($Event -eq "session-start" -and -not $BriefingOn&& printf 'ok' || printf 'missing')assert_eq "powershell session-start handoff GET carries the briefing keys" "ok" "$PS_BRIEF_STATIC"+# The PowerShell subagent-start brief, with Invoke-WebRequest shadowed: the+# subagent opt-in reads `/brief`, never `/handoff`, and prints the+# SubagentStart envelope; the session-start opt-in alone asks for nothing.+if [ -n "$PSH" ]; then+ ps_subagent_start() {+ rm -f "$TMP/ps-subagent.log"+ printf '{"session_id":"ps-sub","cwd":"%s","hook_event_name":"SubagentStart","agent_id":"a-1","agent_type":"Explore"}' \+ "$(host_path "$1" | sed 's/\\/\\\\/g')" \+ | (HOME="$TMP" AI_MEMORY_DATA_DIR="$TMP/ps-subagent-data" \+ AI_MEMORY_TEST_LOG="$(host_path "$TMP/ps-subagent.log")" "$PSH" -NoProfile -ExecutionPolicy Bypass -Command \+ ". '$PS_LIB'; function Invoke-WebRequest { param([switch] \$UseBasicParsing, [int] \$TimeoutSec, [string] \$Method = 'Get', [string] \$Uri, \$Headers, [string] \$ContentType, \$Body) Add-Content -LiteralPath \$env:AI_MEMORY_TEST_LOG -Value ('{0} {1}' -f \$Method.ToUpperInvariant(), \$Uri); if (\$Method -eq 'Post') { return \$null }; return [pscustomobject]@{ Content = 'SUBAGENT-BRIEF' } }; Invoke-AiMemoryHook -Event 'subagent-start' -Agent 'claude-code' -SubagentStartBrief") 2>/dev/null+ }+ PS_SUB_OUT=$(ps_subagent_start "$SUB_REPO")+ case "$PS_SUB_OUT" in+ *'"hookEventName":"SubagentStart"'*) case "$PS_SUB_OUT" in+ *'"additionalContext":"SUBAGENT-BRIEF"'*) PS_SUB_ENVELOPE=ok ;;+ *) PS_SUB_ENVELOPE="got: $PS_SUB_OUT" ;;+ esac ;;+ *) PS_SUB_ENVELOPE="got: $PS_SUB_OUT" ;;+ esac+ assert_eq "powershell: a subagent start injects the opted-in brief" "ok" "$PS_SUB_ENVELOPE"+ assert_eq "powershell: the subagent brief GET carries the opt-in" "yes" \+ "$(grep -q 'GET .*/brief?agent=claude-code&cwd=.*&briefing=true&briefing_budget=6000' "$TMP/ps-subagent.log" && printf 'yes' || printf 'no')"+ assert_eq "powershell: a subagent start never fetches the handoff" "no" \+ "$(grep -q '/handoff?' "$TMP/ps-subagent.log" && printf 'yes' || printf 'no')"+ assert_eq "powershell: a subagent start without the subagent opt-in prints nothing" "" \+ "$(ps_subagent_start "$BRIEF_REPO")"+ assert_eq "powershell: a subagent start without the subagent opt-in asks for no brief" "no" \+ "$(grep -q '/brief?' "$TMP/ps-subagent.log" 2>/dev/null && printf 'yes' || printf 'no')"+fi+# --- client marker header on every request ------------------------------# An unauthenticated server reached through a non-loopback host name refuses# a handoff fetch without `X-AI-Memory-Client`, which a web page cannot add.