Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(workstream): manage GitHub Copilot CLI as a launcher harness (#1040)
Jean Vetorello8016beaa85de
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5a907691..1aeed472 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added+- `ai-memory run` accepts `copilot` (alias `copilot-cli`) and manages GitHub+ Copilot CLI as a workstream harness: a fresh session gets a generated+ `--session-id`, a returning one is resumed with `--resume=<id>`, user+ selectors (`--resume`, `--continue`, `--session-id`, `--connect`) win,+ utility subcommands pass through, and `--yolo` maps to Copilot's native+ `--yolo`. Visible messages, tool calls and results, and compaction summaries+ are imported read-only from `$COPILOT_HOME/session-state/<uuid>/events.jsonl`+ (system prompts, hidden reasoning, hook output, and telemetry are excluded),+ and the existing SessionStart hook delivers the workstream context. The+ first managed launch auto-wires Copilot's hooks and MCP, and `doctor` now+ counts its local sessions. Verified against Copilot CLI 1.0.92. (#1040)## [2.6.0] - 2026-10-07diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 75a72da7..d308ab32 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -516,6 +516,11 @@ pub enum RunHarnessChoice {/// Google Antigravity CLI (`agy`).#[value(name = "antigravity", alias = "antigravity-cli", alias = "agy")]Antigravity,+ /// GitHub Copilot CLI (`copilot`). `run`'s positional names only+ /// command-line harnesses, so the bare name cannot mean VS Code Copilot+ /// here the way `install-mcp --client copilot` does.+ #[value(name = "copilot", alias = "copilot-cli")]+ Copilot,}/// Parses the `run` harness positional, additionally wildcarding everydiff --git a/crates/ai-memory-cli/src/commands/doctor.rs b/crates/ai-memory-cli/src/commands/doctor.rsindex ffbfb664..40d099f4 100644--- a/crates/ai-memory-cli/src/commands/doctor.rs+++ b/crates/ai-memory-cli/src/commands/doctor.rs@@ -53,6 +53,7 @@ pub(crate) const SCANNED_HARNESSES: &[ManagedHarness] = &[ManagedHarness::KiroV3,ManagedHarness::Grok,ManagedHarness::Antigravity,+ ManagedHarness::Copilot,];/// Cap the per-harness enumeration. A project with more local sessions thandiff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 15e927e5..81a57d6b 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -1622,6 +1622,7 @@ pub(crate) fn hook_config_target_with(}AgentChoice::Grok => grok_hooks_path_in(env("GROK_HOME")),AgentChoice::AntigravityCli => antigravity_hooks_path(),+ AgentChoice::CopilotCli => copilot_cli_hooks_path_in(env("COPILOT_HOME")),other => anyhow::bail!("{} is not auto-wired by `ai-memory run`",other.kind().as_str()diff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rsindex e7ce3f01..c7c432de 100644--- a/crates/ai-memory-cli/src/commands/run.rs+++ b/crates/ai-memory-cli/src/commands/run.rs@@ -448,6 +448,7 @@ const fn run_harness_choice(harness: ManagedHarness) -> RunHarnessChoice {ManagedHarness::Kiro | ManagedHarness::KiroV3 => RunHarnessChoice::Kiro,ManagedHarness::Grok => RunHarnessChoice::Grok,ManagedHarness::Antigravity => RunHarnessChoice::Antigravity,+ ManagedHarness::Copilot => RunHarnessChoice::Copilot,}}@@ -3702,6 +3703,7 @@ const fn managed_harness(choice: RunHarnessChoice) -> ManagedHarness {RunHarnessChoice::Kiro => ManagedHarness::Kiro,RunHarnessChoice::Grok => ManagedHarness::Grok,RunHarnessChoice::Antigravity => ManagedHarness::Antigravity,+ RunHarnessChoice::Copilot => ManagedHarness::Copilot,}}@@ -3726,6 +3728,7 @@ const fn managed_harness_from_agent(agent: AgentKind) -> Option<ManagedHarness>AgentKind::KiroCli => Some(ManagedHarness::Kiro),AgentKind::Grok => Some(ManagedHarness::Grok),AgentKind::AntigravityCli => Some(ManagedHarness::Antigravity),+ AgentKind::CopilotCli => Some(ManagedHarness::Copilot),_ => None,}}@@ -5382,6 +5385,35 @@ mod tests {);}+ #[test]+ fn copilot_aliases_select_the_managed_adapter() {+ for name in ["copilot", "copilot-cli"] {+ let cli = Cli::try_parse_from([+ OsStr::new("ai-memory"),+ OsStr::new("run"),+ OsStr::new(name),+ OsStr::new("--model"),+ OsStr::new("gpt-5.6"),+ ])+ .unwrap();+ let CliCommand::Run(args) = cli.command else {+ panic!("expected run command");+ };+ let choice = args.harness.expect("explicit harness");+ assert_eq!(choice, crate::cli::RunHarnessChoice::Copilot, "{name}");+ assert_eq!(managed_harness(choice), ManagedHarness::Copilot);+ assert_eq!(run_harness_choice(ManagedHarness::Copilot), choice);+ assert_eq!(+ args.native_args,+ ["--model", "gpt-5.6"].map(OsString::from).to_vec()+ );+ }+ assert_eq!(+ managed_harness_from_agent(AgentKind::CopilotCli),+ Some(ManagedHarness::Copilot)+ );+ }+#[test]fn command_code_aliases_select_the_managed_adapter() {for name in ["command-code", "commandcode", "cmdc", "cmd"] {diff --git a/crates/ai-memory-cli/src/commands/run_autowire.rs b/crates/ai-memory-cli/src/commands/run_autowire.rsindex 02843141..21fe05cc 100644--- a/crates/ai-memory-cli/src/commands/run_autowire.rs+++ b/crates/ai-memory-cli/src/commands/run_autowire.rs@@ -47,6 +47,7 @@ pub(crate) fn agent_choice_for_harness(harness: ManagedHarness) -> Option<AgentCManagedHarness::KiroV3 => AgentChoice::KiroCliV3,ManagedHarness::Grok => AgentChoice::Grok,ManagedHarness::Antigravity => AgentChoice::AntigravityCli,+ ManagedHarness::Copilot => AgentChoice::CopilotCli,// No AgentChoice / installer support.ManagedHarness::Crush => return None,})@@ -637,6 +638,7 @@ mod tests {ManagedHarness::KiroV3,ManagedHarness::Grok,ManagedHarness::Antigravity,+ ManagedHarness::Copilot,] {assert!(agent_choice_for_harness(harness).is_some(),@@ -992,6 +994,12 @@ mod tests {"hooks/ai-memory.json",Some("config.toml"),),+ (+ ManagedHarness::Copilot,+ "COPILOT_HOME",+ "hooks/ai-memory.json",+ Some("mcp-config.json"),+ ),] {let installs = planned_installs(&config, harness, &env_pair(var, &root));assert_eq!(installs.hooks.len(), 1, "{harness:?}");@@ -1134,6 +1142,7 @@ mod tests {(ManagedHarness::Kimi, &["KIMI_CODE_HOME"][..]),(ManagedHarness::KiroV3, &["KIRO_HOME"][..]),(ManagedHarness::Grok, &["GROK_HOME"][..]),+ (ManagedHarness::Copilot, &["COPILOT_HOME"][..]),] {let run_env: Vec<_> = vars.iter()@@ -1523,6 +1532,10 @@ mod tests {AgentChoice::AntigravityCli,install_hooks::antigravity_hooks_path(),),+ (+ AgentChoice::CopilotCli,+ install_hooks::copilot_cli_hooks_path(),+ ),] {assert_eq!(install_hooks::hook_config_target_with(agent, &process_env).ok(),@@ -1543,6 +1556,7 @@ mod tests {ManagedHarness::KiroV3,ManagedHarness::Grok,ManagedHarness::Antigravity,+ ManagedHarness::Copilot,] {let agent = agent_choice_for_harness(harness).unwrap();assert!(diff --git a/crates/ai-memory-hooks/src/workstream.rs b/crates/ai-memory-hooks/src/workstream.rsindex 3eefa347..8f82a1d2 100644--- a/crates/ai-memory-hooks/src/workstream.rs+++ b/crates/ai-memory-hooks/src/workstream.rs@@ -254,6 +254,7 @@ async fn prepare_run(| AgentKind::KiroCli| AgentKind::Grok| AgentKind::AntigravityCli+ | AgentKind::CopilotCli) {return error(StatusCode::BAD_REQUEST,@@ -3084,6 +3085,23 @@ mod tests {/// command-line harness" after the user already picked the harness.#[tokio::test]async fn antigravity_is_accepted_explicitly_but_not_in_the_automatic_pool() {+ assert_explicit_only_managed_harness(+ AgentKind::AntigravityCli,+ "a0d5ac62-2501-4780-b783-76d159c56cb3",+ )+ .await;+ }++ #[tokio::test]+ async fn copilot_cli_is_accepted_explicitly_but_not_in_the_automatic_pool() {+ assert_explicit_only_managed_harness(+ AgentKind::CopilotCli,+ "318db77d-e19b-4750-82df-192a6b931437",+ )+ .await;+ }++ async fn assert_explicit_only_managed_harness(agent: AgentKind, native_session_id: &str) {let temp = TempDir::new().unwrap();let store = Store::open(temp.path()).unwrap();let state = test_state(&store, temp.path());@@ -3099,7 +3117,7 @@ mod tests {cwd: "/repo".into(),repo_fingerprint: "repo".into(),worktree_fingerprint: "worktree".into(),- agent: AgentKind::AntigravityCli,+ agent,automatic_harness: false,available_agents: Vec::new(),workstream: None,@@ -3112,7 +3130,7 @@ mod tests {assert_eq!(explicit.status(), StatusCode::OK);let body = to_bytes(explicit.into_body(), 64 * 1024).await.unwrap();let prepared: PrepareManagedRunResponse = serde_json::from_slice(&body).unwrap();- assert_eq!(prepared.resolved_agent, Some(AgentKind::AntigravityCli));+ assert_eq!(prepared.resolved_agent, Some(agent));store.writer.finish_workstream_run(@@ -3126,7 +3144,7 @@ mod tests {FinishWorkstreamRun {sanitizer: ai_memory_core::Sanitizer::default(),run_id: prepared.run_id,- native_session_id: Some("a0d5ac62-2501-4780-b783-76d159c56cb3".into()),+ native_session_id: Some(native_session_id.into()),source_cursor: None,events: Vec::new(),complete: true,@@ -3148,9 +3166,9 @@ mod tests {cwd: "/repo".into(),repo_fingerprint: "repo".into(),worktree_fingerprint: "worktree".into(),- agent: AgentKind::AntigravityCli,+ agent,automatic_harness: true,- available_agents: vec![AgentKind::AntigravityCli],+ available_agents: vec![agent],workstream: None,new_workstream: None,force_unlock: false,diff --git a/crates/ai-memory-workstream/src/harness.rs b/crates/ai-memory-workstream/src/harness.rsindex 5244075b..82571162 100644--- a/crates/ai-memory-workstream/src/harness.rs+++ b/crates/ai-memory-workstream/src/harness.rs@@ -144,6 +144,8 @@ pub enum ManagedHarness {Grok,/// Google Antigravity CLI (`agy`).Antigravity,+ /// GitHub Copilot CLI (`copilot`).+ Copilot,}impl ManagedHarness {@@ -163,6 +165,7 @@ impl ManagedHarness {"kiro" | "kiro-cli" => Some(Self::Kiro),"grok" | "grok-build" => Some(Self::Grok),"antigravity" | "antigravity-cli" | "agy" => Some(Self::Antigravity),+ "copilot" | "copilot-cli" => Some(Self::Copilot),_ => None,}}@@ -192,6 +195,7 @@ impl ManagedHarness {Self::Kiro | Self::KiroV3 => AgentKind::KiroCli,Self::Grok => AgentKind::Grok,Self::Antigravity => AgentKind::AntigravityCli,+ Self::Copilot => AgentKind::CopilotCli,}}@@ -217,6 +221,7 @@ impl ManagedHarness {Self::Kiro | Self::KiroV3 => "kiro-cli",Self::Grok => "grok",Self::Antigravity => "agy",+ Self::Copilot => "copilot",}}@@ -237,6 +242,7 @@ impl ManagedHarness {Self::KiroV3 => "kiro-v3",Self::Grok => "grok",Self::Antigravity => "antigravity",+ Self::Copilot => "copilot",}}}@@ -414,7 +420,12 @@ pub fn build_launch_plan_with_env_lookup(for id in expected.as_deref().into_iter().chain(linked_session_id) {ai_memory_core::NativeSessionIdentity::parse(id, &ai_memory_core::Sanitizer::builtin())?;}- if harness == ManagedHarness::CommandCode {+ // Command Code and Copilot also resolve a session name or an id prefix;+ // only an exact UUID identifies the session before launch.+ if matches!(+ harness,+ ManagedHarness::CommandCode | ManagedHarness::Copilot+ ) {expected = expected.filter(|value| Uuid::parse_str(value).is_ok());}let mode = launch_mode(harness, &args);@@ -542,6 +553,20 @@ pub fn build_launch_plan_with_env_lookup(expected = Some(id.to_string());}}+ ManagedHarness::Copilot => {+ // `--session-id` officially sets the UUID of a new session.+ // A linked id uses `--resume=<id>`: the `=` form keeps the+ // optional-value option from consuming a following argument,+ // and a missing session fails instead of being created anew.+ if let Some(id) = linked_session_id {+ args.push(OsString::from(format!("--resume={id}")));+ expected = Some(id.to_string());+ } else {+ let id = Uuid::new_v4().to_string();+ args.extend([OsString::from("--session-id"), OsString::from(&id)]);+ expected = Some(id);+ }+ }}}@@ -577,6 +602,7 @@ pub fn apply_yolo(harness: ManagedHarness, args: &mut Vec<OsString>) {ManagedHarness::KiroV3 => None,ManagedHarness::Grok => Some("--yolo"),ManagedHarness::Antigravity => Some("--dangerously-skip-permissions"),+ ManagedHarness::Copilot => Some("--yolo"),};if let Some(flag) = flag {// Kimi's `--yolo` has hidden aliases (`--yes`, `--auto-approve`) and@@ -591,6 +617,8 @@ pub fn apply_yolo(harness: ManagedHarness, args: &mut Vec<OsString>) {// never be widened by the wrapper.ManagedHarness::Kiro => &["--trust-all-tools", "-a", "--trust-tools"],ManagedHarness::Grok => &["--yolo", "--always-approve"],+ // Copilot documents `--allow-all` as the same permission set.+ ManagedHarness::Copilot => &["--yolo", "--allow-all"],_ => &[flag],};if !has_flag(args, present) {@@ -660,6 +688,8 @@ fn noninteractive_invocation(harness: ManagedHarness, args: &[OsString]) -> bool// / `-i` is NOT: it seeds a prompt and then keeps the session open, so// it stays adoptable.ManagedHarness::Antigravity => has_flag(args, &["--print", "-p", "--prompt"]),+ // `-i`/`--interactive` seeds a prompt and keeps the session open.+ ManagedHarness::Copilot => has_flag(args, &["--prompt", "-p"]),}}@@ -922,6 +952,27 @@ fn launch_mode(harness: ManagedHarness, args: &[OsString]) -> LaunchMode {"update",].as_slice(),+ // Every root command in Copilot CLI 1.0.92 (`copilot --help`).+ ManagedHarness::Copilot => [+ "app",+ "completion",+ "config",+ "help",+ "init",+ "instruction",+ "login",+ "lsp",+ "mcp",+ "memories",+ "plugin",+ "sandbox",+ "sessions",+ "skill",+ "update",+ "version",+ "workflow",+ ]+ .as_slice(),};let first = if matches!(harness, ManagedHarness::Kiro | ManagedHarness::KiroV3) {kiro_root_subcommand(args)@@ -1017,6 +1068,12 @@ pub fn has_native_session_selector(harness: ManagedHarness, args: &[OsString]) -// naming one; that is still an explicit user choice, so nothing may be// injected over it.ManagedHarness::Antigravity => has_flag(args, &["--conversation", "--continue", "-c"]),+ // A bare `--resume` opens Copilot's session picker and `--connect`+ // attaches to a remote session; both are explicit user choices.+ ManagedHarness::Copilot => has_flag(+ args,+ &["--resume", "-r", "--continue", "--session-id", "--connect"],+ ),}}@@ -1050,6 +1107,7 @@ fn explicit_session_id(harness: ManagedHarness, args: &[OsString]) -> Option<Str// A bare `--continue` names no conversation: the id is only known// after the fact, from the conversation store.ManagedHarness::Antigravity => flag_value(args, &["--conversation"]),+ ManagedHarness::Copilot => flag_value(args, &["--resume", "-r", "--session-id"]),}}@@ -1199,6 +1257,7 @@ pub fn store_override_vars(harness: ManagedHarness) -> &'static [&'static str] {ManagedHarness::Kimi => &["KIMI_CODE_HOME"],ManagedHarness::Kiro | ManagedHarness::KiroV3 => &["KIRO_HOME"],ManagedHarness::Grok => &["GROK_HOME"],+ ManagedHarness::Copilot => &["COPILOT_HOME"],ManagedHarness::Crush | ManagedHarness::CommandCode | ManagedHarness::Antigravity => &[],}}@@ -1682,6 +1741,8 @@ fn environment_session_dir_with(ManagedHarness::Grok => value("GROK_HOME").map(|dir| dir.join("sessions")),// `agy` exposes no environment override for its conversation store.ManagedHarness::Antigravity => None,+ // Sessions live under `<COPILOT_HOME>/session-state/<id>/`.+ ManagedHarness::Copilot => value("COPILOT_HOME").map(|dir| dir.join("session-state")),}}@@ -2060,6 +2121,7 @@ mod tests {ManagedHarness::Antigravity,Some("--dangerously-skip-permissions"),),+ (ManagedHarness::Copilot, Some("--yolo")),] {let mut args = Vec::new();apply_yolo(harness, &mut args);@@ -3093,6 +3155,167 @@ mod tests {);}+ #[test]+ fn copilot_generates_then_resumes_native_session_after_user_arguments() {+ let fresh = build_launch_plan(+ ManagedHarness::Copilot,+ None,+ vec![OsString::from("--model"), OsString::from("gpt-5.6")],+ None,+ )+ .unwrap();+ let id = fresh.expected_session_id.clone().unwrap();+ assert!(Uuid::parse_str(&id).is_ok());+ assert_eq!(+ strings(&fresh.args),+ ["--model", "gpt-5.6", "--session-id", id.as_str()]+ );+ assert_eq!(fresh.mode, LaunchMode::Session);++ let resumed = build_launch_plan(+ ManagedHarness::Copilot,+ None,+ vec![OsString::from("--model"), OsString::from("gpt-5.6")],+ Some(&id),+ )+ .unwrap();+ // The `=` form keeps the optional-value `--resume` from consuming a+ // following argument.+ let selector = format!("--resume={id}");+ assert_eq!(+ strings(&resumed.args),+ ["--model", "gpt-5.6", selector.as_str()]+ );+ assert_eq!(resumed.expected_session_id.as_deref(), Some(id.as_str()));+ }++ #[test]+ fn copilot_explicit_selector_always_wins_including_bare_picker() {+ let exact = "0cb916db-26aa-40f2-86b5-1ba81b225fd2";+ for (native, expected) in [+ (+ vec![OsString::from("--resume"), OsString::from(exact)],+ Some(exact),+ ),+ (+ vec![OsString::from(format!("--session-id={exact}"))],+ Some(exact),+ ),+ (vec![OsString::from(format!("-r={exact}"))], Some(exact)),+ // Names and id prefixes resolve natively; they identify nothing+ // before launch.+ (vec![OsString::from("--resume=my feature")], None),+ (vec![OsString::from("--resume=0cb916d")], None),+ (vec![OsString::from("--continue")], None),+ (vec![OsString::from("--connect")], None),+ // A bare `--resume` opens the native picker; still an explicit+ // choice, so nothing may be injected.+ (vec![OsString::from("--resume")], None),+ ] {+ let plan = build_launch_plan(+ ManagedHarness::Copilot,+ None,+ native.clone(),+ Some("linked"),+ )+ .unwrap();+ assert_eq!(plan.args, native, "{native:?} must stay byte-identical");+ assert_eq!(plan.expected_session_id.as_deref(), expected, "{native:?}");+ assert!(!allows_native_session_adoption(+ ManagedHarness::Copilot,+ &native+ ));+ }+ }++ #[test]+ fn copilot_utility_subcommands_are_passed_through() {+ for utility in [+ "login", "sessions", "mcp", "plugin", "update", "version", "help", "config", "init",+ ] {+ let plan = build_launch_plan(+ ManagedHarness::Copilot,+ None,+ vec![OsString::from(utility)],+ Some("linked"),+ )+ .unwrap();+ assert_eq!(plan.mode, LaunchMode::Passthrough, "{utility}");+ assert_eq!(strings(&plan.args), [utility]);+ }+ for flag in ["--help", "-h", "--version", "-v"] {+ let plan = build_launch_plan(+ ManagedHarness::Copilot,+ None,+ vec![OsString::from(flag)],+ None,+ )+ .unwrap();+ assert_eq!(plan.mode, LaunchMode::Passthrough, "{flag}");+ assert_eq!(strings(&plan.args), [flag]);+ }+ }++ #[test]+ fn copilot_prompt_blocks_adoption_but_interactive_seed_does_not() {+ for args in [+ vec![OsString::from("-p"), OsString::from("summarize")],+ vec![OsString::from("--prompt=summarize")],+ ] {+ assert!(!allows_native_session_adoption(+ ManagedHarness::Copilot,+ &args+ ));+ // A one-shot prompt still records a native session.+ let plan = build_launch_plan(ManagedHarness::Copilot, None, args, None).unwrap();+ assert_eq!(plan.mode, LaunchMode::Session);+ }+ assert!(allows_native_session_adoption(+ ManagedHarness::Copilot,+ &[OsString::from("-i"), OsString::from("summarize")]+ ));+ }++ #[test]+ fn copilot_yolo_respects_the_allow_all_alias() {+ for already in ["--yolo", "--allow-all"] {+ let mut args = vec![OsString::from(already)];+ apply_yolo(ManagedHarness::Copilot, &mut args);+ assert_eq!(strings(&args), [already], "{already} must not duplicate");+ }+ // Narrower grants are additive in Copilot; the wrapper's request+ // still has to widen them explicitly.+ let mut args = vec![OsString::from("--allow-all-tools")];+ apply_yolo(ManagedHarness::Copilot, &mut args);+ assert_eq!(strings(&args), ["--allow-all-tools", "--yolo"]);+ }++ #[test]+ fn copilot_names_parse_to_one_variant() {+ for name in ["copilot", "copilot-cli"] {+ assert_eq!(+ ManagedHarness::from_name(name),+ Some(ManagedHarness::Copilot)+ );+ }+ assert_eq!(ManagedHarness::Copilot.agent_kind(), AgentKind::CopilotCli);+ assert_eq!(ManagedHarness::Copilot.executable(), "copilot");+ assert!(!ManagedHarness::Copilot.lacks_session_end_hook());+ }++ #[test]+ fn copilot_home_environment_override_points_at_session_state() {+ let get = |name: &str| (name == "COPILOT_HOME").then(|| OsString::from("/stores/copilot"));+ assert_eq!(+ environment_session_dir_with(ManagedHarness::Copilot, None, None, get).as_deref(),+ Some(std::path::Path::new("/stores/copilot/session-state"))+ );+ assert_eq!(+ store_override_vars(ManagedHarness::Copilot),+ ["COPILOT_HOME"]+ );+ }+#[test]fn kimi_home_environment_override_points_at_sessions_root() {let get =diff --git a/crates/ai-memory-workstream/src/transcript.rs b/crates/ai-memory-workstream/src/transcript.rsindex 20c9f03b..a4be75c5 100644--- a/crates/ai-memory-workstream/src/transcript.rs+++ b/crates/ai-memory-workstream/src/transcript.rs@@ -56,9 +56,9 @@ struct FileCursor {flavor: Option<FileFlavor>,/// Hash of every committed byte through `offset`. Kimi Code and Grok can/// rewrite their journals in place (Kimi on fork/compaction/resume, Grok- /// on rewind); Kiro's append-only behavior is not documented. Those- /// adapters validate this prefix before trusting the byte offset. Other- /// JSONL adapters remain offset-only.+ /// on rewind); Kiro's and Copilot's append-only behavior is not+ /// documented. Those adapters validate this prefix before trusting the+ /// byte offset. Other JSONL adapters remain offset-only.#[serde(default, skip_serializing_if = "Option::is_none")]prefix_sha256: Option<String>,}@@ -94,7 +94,11 @@ const fn file_flavor(harness: ManagedHarness) -> Option<FileFlavor> {const fn journal_rewrites_in_place(harness: ManagedHarness) -> bool {matches!(harness,- ManagedHarness::Kimi | ManagedHarness::Kiro | ManagedHarness::KiroV3 | ManagedHarness::Grok+ ManagedHarness::Kimi+ | ManagedHarness::Kiro+ | ManagedHarness::KiroV3+ | ManagedHarness::Grok+ | ManagedHarness::Copilot)}@@ -717,6 +721,13 @@ fn export_jsonl(&mut events,&mut losses,),+ ManagedHarness::Copilot => parse_copilot(+ &value,+ native_session_id,+ &record_id,+ &mut events,+ &mut losses,+ ),ManagedHarness::OpenCode| ManagedHarness::OpenCode2| ManagedHarness::Crush@@ -1978,6 +1989,146 @@ fn parse_grok(}}+/// Copilot CLI `events.jsonl` records (verified on 1.0.92). Each record is+/// `{type, data, id, timestamp, parentId}`. Only the user's typed text, the+/// assistant's visible text and tool requests, completed tool output, and+/// compaction summaries are imported. `transformedContent` (the prompt with+/// injected datetime/context), `reasoningText`/`reasoningOpaque`, hook output+/// (where ai-memory's own startup packet lands), permission prompts, model+/// snapshots, and session telemetry never reach the ledger.+fn parse_copilot(+ value: &Value,+ session: &str,+ record_id: &str,+ events: &mut Vec<NewWorkstreamEvent>,+ losses: &mut Vec<String>,+) {+ let record_type = value+ .get("type")+ .and_then(Value::as_str)+ .unwrap_or_default();+ let data = value.get("data").unwrap_or(&Value::Null);+ match record_type {+ "system.message" => {+ losses.push("Copilot system prompt records were intentionally excluded".into());+ }+ "model.messages_snapshot" => {+ losses.push("Copilot model message snapshots were intentionally excluded".into());+ }+ "user.message" => {+ if let Some(text) = data.get("content").and_then(Value::as_str) {+ push_event(+ events,+ AgentKind::CopilotCli,+ session,+ record_id,+ 0,+ WorkstreamEventKind::Message,+ Some("user"),+ text,+ timestamp(value),+ json!({}),+ );+ }+ }+ "assistant.message" => {+ if ["reasoningText", "reasoningOpaque", "reasoningBlocks"]+ .iter()+ .any(|key| data.get(*key).is_some_and(|value| !value.is_null()))+ {+ losses.push("Copilot hidden reasoning was intentionally excluded".into());+ }+ let block_count = match data.get("content").and_then(Value::as_str) {+ Some(text) if !text.trim().is_empty() => {+ push_event(+ events,+ AgentKind::CopilotCli,+ session,+ record_id,+ 0,+ WorkstreamEventKind::Message,+ Some("assistant"),+ text,+ timestamp(value),+ json!({}),+ );+ 1+ }+ _ => 0,+ };+ let requests = data+ .get("toolRequests")+ .and_then(Value::as_array)+ .map_or(&[][..], Vec::as_slice);+ for (index, request) in requests.iter().enumerate() {+ let name = first_string(request, &["name"]).unwrap_or("tool");+ let arguments = request+ .get("arguments")+ .map(compact_json)+ .unwrap_or_default();+ push_event(+ events,+ AgentKind::CopilotCli,+ session,+ record_id,+ block_count + index,+ WorkstreamEventKind::ToolCall,+ Some("assistant"),+ &format!("{name}: {arguments}"),+ timestamp(value),+ json!({"tool": name}),+ );+ }+ }+ "tool.execution_complete" => {+ let success = data.get("success").and_then(Value::as_bool);+ // `detailedContent` repeats the output as a diff carrying absolute+ // paths; the model-visible `content` is the portable record.+ let body = if success == Some(false) {+ data.get("error")+ .and_then(|error| error.get("message"))+ .and_then(Value::as_str)+ .map(|message| format!("error: {message}"))+ } else {+ data.get("result")+ .and_then(|result| result.get("content"))+ .map(value_text)+ };+ push_event(+ events,+ AgentKind::CopilotCli,+ session,+ record_id,+ 0,+ WorkstreamEventKind::ToolResult,+ Some("tool"),+ body.as_deref().unwrap_or_default(),+ timestamp(value),+ json!({"success": success}),+ );+ }+ "session.compaction_complete" => {+ if data.get("success").and_then(Value::as_bool) == Some(true)+ && let Some(text) = data.get("summaryContent").and_then(Value::as_str)+ {+ push_event(+ events,+ AgentKind::CopilotCli,+ session,+ record_id,+ 0,+ WorkstreamEventKind::Compaction,+ Some("assistant"),+ text,+ timestamp(value),+ json!({}),+ );+ }+ }+ _ => {}+ }+}+#[allow(clippy::too_many_arguments)]fn parse_content_blocks(agent: AgentKind,@@ -2483,6 +2634,15 @@ fn locate_session_file(let exact = root.join(format!("{id}.db"));return Ok(session_path_matches(harness, &exact, id, cwd)?.then_some(exact));}+ if harness == ManagedHarness::Copilot {+ // The session directory is named by its UUID, so no scan is needed;+ // the header still has to name this checkout.+ if Uuid::parse_str(id).is_err() {+ return Ok(None);+ }+ let exact = root.join(id).join("events.jsonl");+ return Ok(session_path_matches(harness, &exact, id, cwd)?.then_some(exact));+ }if harness == ManagedHarness::Claude {let encoded = cwd.to_string_lossy().replace('/', "-");let exact = root.join(encoded).join(format!("{id}.jsonl"));@@ -2631,6 +2791,16 @@ fn transcript_file(harness: ManagedHarness, path: &Path) -> bool {// One SQLite database per conversation, named by its id.return path.extension().is_some_and(|ext| ext == "db");}+ if harness == ManagedHarness::Copilot {+ // `<session-state>/<uuid>/events.jsonl` only; checkpoints, files and+ // research artifacts in the same directory are not transcripts.+ return path.file_name().and_then(|name| name.to_str()) == Some("events.jsonl")+ && path+ .parent()+ .and_then(|dir| dir.file_name())+ .and_then(|name| name.to_str())+ .is_some_and(|name| Uuid::parse_str(name).is_ok());+ }path.extension().is_some_and(|ext| ext == "jsonl")|| matches!(harness, ManagedHarness::Pi | ManagedHarness::Omp) && temporary_transcript(path)}@@ -2659,6 +2829,9 @@ fn session_header(harness: ManagedHarness, path: &Path) -> Result<Option<(Stringif harness == ManagedHarness::Antigravity {return antigravity_session_header(path);}+ if harness == ManagedHarness::Copilot {+ return copilot_session_header(path);+ }let mut reader = BufReader::new(File::open(path)?);let mut line = String::new();for _ in 0..64 {@@ -2693,7 +2866,8 @@ fn session_header(harness: ManagedHarness, path: &Path) -> Result<Option<(String| ManagedHarness::Kiro| ManagedHarness::KiroV3| ManagedHarness::Grok- | ManagedHarness::Antigravity => (None, None),+ | ManagedHarness::Antigravity+ | ManagedHarness::Copilot => (None, None),};if let (Some(id), Some(cwd)) = (id, cwd) {return Ok(Some((id.to_string(), PathBuf::from(cwd))));@@ -2745,6 +2919,46 @@ fn command_code_session_header(path: &Path) -> Result<Option<(String, PathBuf)>>Ok(Some((id.to_string(), cwd)))}+/// Copilot CLI opens every `events.jsonl` with a `session.start` record+/// naming the session and its working directory. Fail closed when that first+/// record is missing, oversized, or disagrees with the directory name.+fn copilot_session_header(path: &Path) -> Result<Option<(String, PathBuf)>> {+ let Some(dir_id) = path+ .parent()+ .and_then(|dir| dir.file_name())+ .and_then(|name| name.to_str())+ else {+ return Ok(None);+ };+ let mut reader = BufReader::new(File::open(path)?);+ let mut line = String::new();+ let read =+ std::io::Read::take(&mut reader, (MAX_EVENT_BYTES + 1) as u64).read_line(&mut line)?;+ if read == 0 || read > MAX_EVENT_BYTES {+ return Ok(None);+ }+ let Ok(header) = serde_json::from_str::<Value>(&line) else {+ return Ok(None);+ };+ if header.get("type").and_then(Value::as_str) != Some("session.start") {+ return Ok(None);+ }+ let data = header.get("data").unwrap_or(&Value::Null);+ let (Some(id), Some(cwd)) = (+ data.get("sessionId").and_then(Value::as_str),+ data.get("context")+ .and_then(|context| context.get("cwd"))+ .and_then(Value::as_str),+ ) else {+ return Ok(None);+ };+ let cwd = PathBuf::from(cwd);+ if id != dir_id || Uuid::parse_str(id).is_err() || !cwd.is_absolute() {+ return Ok(None);+ }+ Ok(Some((id.to_string(), cwd)))+}+fn session_header_for_cwd(harness: ManagedHarness,path: &Path,@@ -3612,6 +3826,7 @@ fn session_root(harness: ManagedHarness, home: &Path, override_dir: Option<&PathManagedHarness::KiroV3 => home.join(".kiro/sessions"),ManagedHarness::Grok => home.join(".grok/sessions"),ManagedHarness::Antigravity => home.join(".gemini/antigravity-cli/conversations"),+ ManagedHarness::Copilot => home.join(".copilot/session-state"),}}@@ -3835,8 +4050,9 @@ mod tests {json!({"type":"session","id":"other-id","cwd":other})),// Kimi's header lives in state.json and Grok's in- // summary.json, not the journal; covered by their own- // discovery tests.+ // summary.json, not the journal; Copilot's journal must+ // sit in a UUID-named directory. All are covered by their+ // own discovery tests.ManagedHarness::OpenCode| ManagedHarness::OpenCode2| ManagedHarness::Crush@@ -3845,7 +4061,8 @@ mod tests {| ManagedHarness::Kiro| ManagedHarness::KiroV3| ManagedHarness::Grok- | ManagedHarness::Antigravity => {+ | ManagedHarness::Antigravity+ | ManagedHarness::Copilot => {unreachable!()}},@@ -5741,6 +5958,209 @@ mod tests {);}+ fn copilot_session_start(id: &str, cwd: &Path) -> Value {+ json!({"type":"session.start","data":{"sessionId":id,"version":1,+ "producer":"copilot-agent","copilotVersion":"1.0.92",+ "context":{"cwd":cwd}},"id":"start","timestamp":"2026-10-07T13:00:33.339Z"})+ }++ #[tokio::test]+ async fn copilot_discovery_requires_uuid_directory_header_and_checkout() {+ let temp = tempfile::tempdir().unwrap();+ let cwd = temp.path().join("repo");+ let other = temp.path().join("other");+ let root = temp.path().join("session-state");+ fs::create_dir_all(&cwd).unwrap();+ fs::create_dir_all(&other).unwrap();++ let matching = "318db77d-e19b-4750-82df-192a6b931437";+ let wrong_checkout = "c79ce9b8-de85-442e-915a-1c6ec4f74719";+ let mismatched_header = "0e88ebd2-ed54-4f5a-9056-46e041e3b44d";+ let phantom = "5b1f0c3e-7a2d-4e8b-9c6f-1d2e3f4a5b6c";+ for (dir, header) in [+ (matching, copilot_session_start(matching, &cwd)),+ (+ wrong_checkout,+ copilot_session_start(wrong_checkout, &other),+ ),+ // A header naming a session other than its directory must never+ // surface that phantom id as a candidate.+ (mismatched_header, copilot_session_start(phantom, &cwd)),+ ] {+ fs::create_dir_all(root.join(dir)).unwrap();+ fs::write(root.join(dir).join("events.jsonl"), format!("{header}\n")).unwrap();+ }+ // Workspace metadata and non-UUID directories are not transcripts.+ fs::write(root.join(matching).join("workspace.yaml"), "id: x\n").unwrap();+ fs::create_dir_all(root.join("not-a-uuid")).unwrap();+ fs::write(+ root.join("not-a-uuid/events.jsonl"),+ format!("{}\n", copilot_session_start("not-a-uuid", &cwd)),+ )+ .unwrap();++ let sessions =+ list_native_sessions(ManagedHarness::Copilot, temp.path(), &cwd, Some(&root), 8)+ .await+ .unwrap();+ let ids: Vec<_> = sessions+ .iter()+ .map(|session| session.native_session_id.as_str())+ .collect();+ assert_eq!(ids, [matching]);++ let found = locate_session_file(+ ManagedHarness::Copilot,+ temp.path(),+ &cwd,+ Some(&root),+ matching,+ )+ .unwrap();+ assert_eq!(found, Some(root.join(matching).join("events.jsonl")));+ for foreign in [+ wrong_checkout,+ mismatched_header,+ phantom,+ "not-a-uuid",+ "../x",+ ] {+ assert!(+ !native_session_exists(+ ManagedHarness::Copilot,+ temp.path(),+ &cwd,+ Some(&root),+ foreign+ )+ .unwrap(),+ "{foreign} must not resolve for this checkout"+ );+ }+ }++ #[test]+ fn copilot_store_defaults_below_home() {+ let home = Path::new("/home/user");+ assert_eq!(+ session_root(ManagedHarness::Copilot, home, None),+ home.join(".copilot/session-state")+ );+ }++ /// Record shapes captured from a real Copilot CLI 1.0.92 session (paths,+ /// ids, and long fields shortened).+ #[test]+ fn copilot_adapter_excludes_private_records_and_keeps_visible_history() {+ let temp = tempfile::tempdir().unwrap();+ let path = temp.path().join("events.jsonl");+ let records = [+ copilot_session_start("318db77d-e19b-4750-82df-192a6b931437", temp.path()),+ json!({"type":"session.model_change","data":{"newModel":"claude-sonnet-5"},"id":"r1"}),+ json!({"type":"user.message","data":{"content":"read note.txt",+ "transformedContent":"<current_datetime>2026-10-07</current_datetime>\n\nread note.txt"},+ "id":"r2","timestamp":"2026-10-07T13:00:35.074Z"}),+ json!({"type":"system.message","data":{"role":"system","content":"You are the GitHub Copilot CLI"},"id":"r3"}),+ json!({"type":"hook.end","data":{"hookType":"sessionStart","success":true,+ "output":{"additionalContext":"ai-memory startup packet"}},"id":"r4"}),+ json!({"type":"assistant.message","data":{"content":"","reasoningText":"private plan",+ "reasoningOpaque":"opaque","toolRequests":[{"toolCallId":"call-1","name":"view",+ "arguments":{"path":"note.txt"},"type":"function"}]},"id":"r5"}),+ json!({"type":"tool.execution_start","data":{"toolCallId":"call-1","toolName":"view",+ "arguments":{"path":"note.txt"}},"id":"r6"}),+ json!({"type":"permission.requested","data":{"permissionRequest":{"kind":"shell"}},"id":"r7"}),+ json!({"type":"tool.execution_complete","data":{"toolCallId":"call-1","success":true,+ "result":{"content":"hello\n","detailedContent":"diff --git a/abs/path"}},"id":"r8"}),+ json!({"type":"tool.execution_complete","data":{"toolCallId":"call-2","success":false,+ "result":null,"error":{"message":"Permission denied","code":"denied"}},"id":"r9"}),+ json!({"type":"assistant.message","data":{"content":"hello","toolRequests":[]},"id":"r10"}),+ json!({"type":"session.resume","data":{"context":{"cwd":temp.path()}},"id":"r11"}),+ json!({"type":"model.messages_snapshot","data":{"messages":[{"role":"system","content":"private"}]},"id":"r12"}),+ json!({"type":"session.compaction_complete","data":{"success":true,+ "summaryContent":"<overview>read a file</overview>"},"id":"r13"}),+ json!({"type":"session.compaction_complete","data":{"success":false,+ "summaryContent":"failed attempt"},"id":"r14"}),+ ];+ let body = records+ .iter()+ .map(|record| format!("{record}\n"))+ .collect::<String>();+ fs::write(&path, body).unwrap();++ let export = export_jsonl(ManagedHarness::Copilot, &path, "copilot-session", None).unwrap();+ let contents: Vec<_> = export+ .events+ .iter()+ .map(|event| (event.kind, event.content.as_str()))+ .collect();+ assert_eq!(+ contents,+ [+ (WorkstreamEventKind::Message, "read note.txt"),+ (+ WorkstreamEventKind::ToolCall,+ "view: {\"path\":\"note.txt\"}"+ ),+ (WorkstreamEventKind::ToolResult, "hello\n"),+ (WorkstreamEventKind::ToolResult, "error: Permission denied"),+ (WorkstreamEventKind::Message, "hello"),+ (+ WorkstreamEventKind::Compaction,+ "<overview>read a file</overview>"+ ),+ ]+ );+ assert!(export.events.iter().all(|event| {+ event.agent == AgentKind::CopilotCli+ && !event.content.contains("private")+ && !event.content.contains("startup packet")+ && !event.content.contains("current_datetime")+ && !event.content.contains("abs/path")+ }));+ for expected in [+ "system prompt records",+ "hidden reasoning",+ "message snapshots",+ ] {+ assert!(+ export.losses.iter().any(|loss| loss.contains(expected)),+ "missing loss annotation for {expected}"+ );+ }+ let cursor: FileCursor = serde_json::from_str(&export.source_cursor.unwrap()).unwrap();+ assert!(cursor.prefix_sha256.is_some());+ }++ #[test]+ fn copilot_export_is_incremental_and_holds_back_an_incomplete_record() {+ let temp = tempfile::tempdir().unwrap();+ let path = temp.path().join("events.jsonl");+ let first_line = json!({"type":"user.message","data":{"content":"one"},"id":"a"});+ let second_line = json!({"type":"assistant.message","data":{"content":"two"},"id":"b"});+ // A record still being written has no trailing newline yet.+ let partial = second_line.to_string();+ fs::write(&path, format!("{first_line}\n{}", &partial[..10])).unwrap();+ let first = export_jsonl(ManagedHarness::Copilot, &path, "s", None).unwrap();+ assert_eq!(first.events.len(), 1);+ assert!(first.losses.is_empty());++ fs::write(&path, format!("{first_line}\n{second_line}\n")).unwrap();+ let second = export_jsonl(+ ManagedHarness::Copilot,+ &path,+ "s",+ first.source_cursor.as_deref(),+ )+ .unwrap();+ assert_eq!(second.events.len(), 1);+ assert_eq!(second.events[0].content, "two");++ // Re-reading from scratch yields identical event ids.+ let replay = export_jsonl(ManagedHarness::Copilot, &path, "s", None).unwrap();+ assert_eq!(replay.events[0].event_id, first.events[0].event_id);+ assert_eq!(replay.events[1].event_id, second.events[0].event_id);+ }+fn push_protobuf_varint(output: &mut Vec<u8>, mut value: u64) {loop {let byte = (value & 0x7f) as u8;diff --git a/docs/design-decisions.md b/docs/design-decisions.mdindex 47baecda..da108a4b 100644--- a/docs/design-decisions.md+++ b/docs/design-decisions.md@@ -325,7 +325,7 @@ Top-line rules carved into the codebase:Managed cross-harness continuity is explicitly opt-in through `ai-memory run`.Direct Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, Command Code, Kiro-CLI, OMP, Grok Build CLI, and Antigravity CLI launches retain the existing hook+CLI, OMP, Grok Build CLI, Antigravity CLI, and GitHub Copilot CLI launches retain the existing hookand single-use handoff behavior. There isno process-global mode or manual harness switch: the wrapper selects thecurrent repository/worktree workstream and each adapter applies that harness'sdiff --git a/docs/install.md b/docs/install.mdindex 8c9e5231..d7623812 100644--- a/docs/install.md+++ b/docs/install.md@@ -1362,8 +1362,9 @@ repository hook files (`.github/hooks/*.json`) are versioned, shared with theteam and loaded by the Copilot cloud agent, while ai-memory's hook entriescarry this machine's absolute executable and data-dir paths; committing themwould point every teammate at one person's install and server.-`ai-memory run copilot` is not shipped yet; `install-mcp --client copilot`-remains the VS Code Copilot client.+`ai-memory run copilot` (alias `copilot-cli`) launches Copilot CLI as a+managed workstream harness (see [managed workstreams](managed-workstreams.md));+`install-mcp --client copilot` remains the VS Code Copilot client.### Hermes Agent (Nous Research)@@ -2329,7 +2330,7 @@ docker run --rm akitaonrails/ai-memory:latest --help # full subcommand tree| Subcommand | Pattern | What it does ||---|---|---|| `serve` | `docker compose up -d` (already done) | Run the HTTP MCP server |-| `run [harness] [args...]` | host wrapper or native binary | Opt into one managed cross-harness workstream; omit the harness to resume the newest usable local session, or name Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, Command Code, Kiro CLI v2/v3, OMP, Grok Build CLI, or Antigravity CLI explicitly; exact `--yolo` and `--fresh` flags are wrapper-owned and other native arguments pass through |+| `run [harness] [args...]` | host wrapper or native binary | Opt into one managed cross-harness workstream; omit the harness to resume the newest usable local session, or name Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, Command Code, Kiro CLI v2/v3, OMP, Grok Build CLI, Antigravity CLI, or GitHub Copilot CLI explicitly; exact `--yolo` and `--fresh` flags are wrapper-owned and other native arguments pass through || `show [--json]` | host wrapper or native binary | Choose a client-local checkout and installed managed harness, or return structured discovery data without launching; remote servers never provide checkout paths || `continue [--workspace NAME]` | host wrapper or native binary | From any directory, revalidate and resume the newest client-local managed checkout; accepts `--yolo` and `--fresh` but no harness-native arguments || `resume [--all] [--workspace NAME] [--search TERM] [--limit N]` | host wrapper or native binary | Interactively choose from all workstreams in the current checkout (no default cutoff), or with `--all` from every valid client-local linked checkout; type to search names, Up/Down selects, Left/Right cycles `auto` plus installed harnesses, Enter launches, and Escape clears the search or cancels; an explicit limit caps initial search results; accepts `--yolo` and `--fresh` |diff --git a/docs/managed-harness-contributions.md b/docs/managed-harness-contributions.mdindex ba09f13c..b0501e73 100644--- a/docs/managed-harness-contributions.md+++ b/docs/managed-harness-contributions.md@@ -2,7 +2,7 @@Managed-workstream support is narrower than MCP or lifecycle-hook support. Thisrelease can manage Claude Code, Codex, OpenCode, OpenCode 2 beta, Pi, Crush, Kimi Code, Command-Code, Kiro CLI v2/v3, OMP, Grok Build CLI, and Antigravity CLI. Gemini CLI,+Code, Kiro CLI v2/v3, OMP, Grok Build CLI, Antigravity CLI, and GitHub Copilot CLI. Gemini CLI,Devin CLI, Cursor, and the other integrations in the README support matrix donot become managed merely because ai-memory can capture their hooks.diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.mdindex 6394349e..3a3bad51 100644--- a/docs/managed-workstreams.md+++ b/docs/managed-workstreams.md@@ -2,7 +2,7 @@`ai-memory run` is an opt-in launcher that lets one logical coding session movebetween Claude Code, Codex, OpenCode, OpenCode 2 beta, Pi, Crush, Kimi Code, Command Code, Kiro-CLI v2/v3, OMP, Grok Build CLI, and Antigravity CLI. Direct agent launches+CLI v2/v3, OMP, Grok Build CLI, Antigravity CLI, and GitHub Copilot CLI. Direct agent launcheskeep their existing ai-memory behavior. There is no global mode toggle and no`switch` command: using `run` selects the current workstream and transparentlycreates or resumes the correct native session for the requested harness.@@ -134,7 +134,7 @@ ai-memory run [--workspace NAME] [--project NAME][--workstream NAME | --new NAME] [--executable PATH][--yolo] [--fresh] [--force-unlock] [--profile NAME][--env KEY=VALUE]... [--env-file PATH] [--require-server]- [claude|claude*|codex|opencode|opencode2|pi|crush|omp|kimi|command-code|kiro|grok|antigravity]+ [claude|claude*|codex|opencode|opencode2|pi|crush|omp|kimi|command-code|kiro|grok|antigravity|copilot][native arguments...]```@@ -341,7 +341,7 @@ takes precedence: ai-memory resumes the most recently linked harness that stillhas a usable local session. It never chooses a newer but obsolete session fromanother harness merely because that file has a later timestamp. Kiro's v2 andv3 candidates share one server agent identity, but the selected native engine-flavor remains exact. OMP, Grok, and Antigravity remain available explicitly+flavor remains exact. OMP, Grok, Antigravity, and Copilot remain available explicitlybut are not in the automatic pool. OpenCode's resolved major contributes oneadapter to the pool, so shared V1/V2 storage never duplicates a candidate.@@ -603,6 +603,7 @@ change does not add an atomic disk/SQL seal or change lease/retry policy.| OMP | native default creation | `--resume=<id>` | `<agent dir>/sessions/**/*.jsonl`, or the XDG session directory described below || Grok Build CLI | generated `--session-id` | `--resume <id>` | `$GROK_HOME/sessions/*/*/chat_history.jsonl` || Antigravity CLI | native default creation | `--conversation <id>` | `~/.gemini/antigravity-cli/conversations/<id>.db` metadata plus lifecycle-hook capture |+| GitHub Copilot CLI | generated `--session-id` | `--resume=<id>` | `$COPILOT_HOME/session-state/<uuid>/events.jsonl` (`COPILOT_HOME` defaults to `~/.copilot`) |OMP's agent directory is `~/.omp/agent` for the default profile and`~/.omp/profiles/<name>/agent` for a named profile. `PI_CONFIG_DIR` changes the@@ -626,7 +627,8 @@ The default executable is `command-code` on Unix and `cmdc` on native Windows;The experimental unsandboxed Mod API is not used.An explicit native selector such as Claude's `--resume`, OpenCode's `--session`,-Codex's `resume`, or Antigravity's `--conversation` / `--continue` wins.+Codex's `resume`, Antigravity's `--conversation` / `--continue`, or Copilot's+`--resume` / `--continue` / `--session-id` / `--connect` wins.ai-memory links the selected native session and resets an unrelated adaptercursor rather than assuming it belongs to the old session.@@ -756,8 +758,9 @@ the harness's native dangerous mode. The translation is Claude Code`--dangerously-bypass-approvals-and-sandbox`, OpenCode `--auto`, Pi `--approve`,Crush `--yolo`, Kimi Code `--yolo`, Command Code `--yolo`, Kiro CLI v2`--trust-all-tools`, Grok Build CLI `--yolo` (equivalent to its-`--always-approve` option), and Antigravity CLI-`--dangerously-skip-permissions`. Kiro v3 replaced the trust-all flag with+`--always-approve` option), Antigravity CLI+`--dangerously-skip-permissions`, and GitHub Copilot CLI `--yolo` (equivalent+to its `--allow-all` option). Kiro v3 replaced the trust-all flag with`permissions.yaml`, so ai-memory prints a notice and adds no unverified flag.OMP currently needs no added flag. ai-memory does not add a duplicate when thetranslated native flag is already present.@@ -913,6 +916,36 @@ fails with a message saying so. The managed launcher accepts `antigravity`,Antigravity CLI v1.1.7. Antigravity is not part of the no-argumentauto-detection set; name it explicitly.+GitHub Copilot CLI keeps each session in+`$COPILOT_HOME/session-state/<session-id>/` (`COPILOT_HOME` defaults to+`~/.copilot`). Copilot officially accepts a caller-chosen UUID through+`--session-id`, so a fresh launch generates one; a linked resume passes+`--resume=<id>`, in the `=` form because `--resume` takes an optional value and+would otherwise consume the next argument. A user-supplied `--resume`, `-r`,+`--continue`, `--session-id`, or `--connect` is an explicit choice and is never+overridden; a resume by session name or id prefix is resolved by Copilot and+linked after the fact. Discovery reads the first `events.jsonl` record,+`session.start`, and requires its `sessionId` to match the UUID directory name+and its `context.cwd` to match the checkout. Export imports the typed+`user.message` text (not the `transformedContent` copy carrying injected+datetime and context), visible `assistant.message` text and `toolRequests`,+the model-visible output of each `tool.execution_complete` (or the error+message of a failed call), and successful `session.compaction_complete`+summaries. System prompts, hidden reasoning (`reasoningText`,+`reasoningOpaque`, `reasoningBlocks`), model message snapshots, hook output+(where ai-memory's own startup packet is recorded), permission prompts, and+session telemetry are excluded. The journal stayed append-only across resume+and compaction in testing, but that is not documented, so the cursor stores a+prefix hash and replays with content-hash event ids if the file is ever+rewritten. Context is delivered by Copilot's existing SessionStart hook through+its top-level `additionalContext`. `--yolo` maps to Copilot's native `--yolo`;+an existing `--yolo` or `--allow-all` is not duplicated. The managed launcher+accepts `copilot` and `copilot-cli`: `run` launches only command-line+harnesses, so the bare name means the CLI here, while `install-mcp --client+copilot` keeps meaning VS Code Copilot. The native contract was verified+against GitHub Copilot CLI 1.0.92. Copilot is not part of the no-argument+auto-detection set; name it explicitly.+Crush needs no ai-memory hook installation for managed mode. The launcher readsits one-time context from the server, copies the global Crush JSON the launchwould read (`$CRUSH_GLOBAL_CONFIG/crush.json`, else@@ -1054,7 +1087,7 @@ atomic operation.ai-memory's managed adapters do not write to Claude, Codex, OpenCode, Pi, Crush,-Kimi Code, Command Code, Kiro, OMP, Grok, or Antigravity private stores. The+Kimi Code, Command Code, Kiro, OMP, Grok, Antigravity, or Copilot private stores. Thelaunched harness retains normal ownership of its own session writes. Adapters read onlydocumented or observed local session formats. Provider credentials, encryptedcontent, system/developer prompt records, and hidden reasoning are not copied. The@@ -1073,8 +1106,9 @@ checkout, or native harness session. If the source checkout path itself isrenamed, absolute-path session locators used by Claude Code, Codex, OpenCode,Pi, Kimi Code (`state.json`'s `cwd` or legacy `workDir`), Command Code (v3header `cwd`), Kiro v2-(`<uuid>.json`'s `cwd`), Kiro v3 (`session.json`'s `workspacePaths`), OMP, and-Antigravity may still reference the old path; Crush's project-local `.crush`+(`<uuid>.json`'s `cwd`), Kiro v3 (`session.json`'s `workspacePaths`), OMP,+Antigravity, and Copilot (`session.start`'s `context.cwd`) may still reference+the old path; Crush's project-local `.crush`database moves with the checkout.There is no portable, supported API that rewrites every harness's private@@ -1091,7 +1125,7 @@ checkout to match exactly.The opt-in acceptance runner exercises launcher edge cases and then orchestratesthe locally installed Claude, Codex, OpenCode, Pi, Crush, OMP, Kimi, Command-Code, Grok, and Antigravity CLIs through one real workstream:+Code, Grok, Antigravity, and Copilot CLIs through one real workstream:```bashscripts/managed-workstream-acceptance.sh@@ -1106,11 +1140,13 @@ copied settings. Crush uses its existing global provider configuration and anisolated project database. Kimi Code runs with an isolated `$KIMI_CODE_HOME`seeded with the operator's provider configuration. Command Code runs with anisolated `HOME` seeded only with `auth.json` and `config.json`. Antigravity runs-with an isolated `HOME` seeded only with the operator's OAuth and settings files. The+with an isolated `HOME` seeded only with the operator's OAuth and settings files.+Copilot runs with an isolated `$COPILOT_HOME` seeded only with `config.json`. Thedeterministic phase also covers first-run adoption, bare-mode selection andempty-directory failure, wrapper `--yolo`, lease exclusion, Crush contextcleanup, fake-mode Kimi and Command Code store/resume/import round trips, an-Antigravity hook/link/resume round trip, a fake-mode Kiro v2+Antigravity hook/link/resume round trip, a fake-mode Copilot+store/hook/resume/import round trip, a fake-mode Kiro v2store/resume/import round trip,the equivalent Kiro v3 nested-store round trip with transparent engine recovery,private-trajectory exclusion, and the@@ -1145,7 +1181,7 @@ report that exact endpoint as `sync_through` with `context_delivered = 1`. Itdoes not require the model to quote a prior sentinel: Claude Code mayexternalize a large hook result to a file, and whether a model chooses to readthat file is not a deterministic continuity signal. The deterministic fake-Grok and Antigravity cross-harness fixtures exercise the same assertion helper+Grok, Antigravity, and Copilot cross-harness fixtures exercise the same assertion helperwithout credentials or model calls.Setdiff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex dbf8d5f4..82db8ff0 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -237,9 +237,10 @@ native HTTP or generated bridge paths.## GitHub Copilot CLI-**Status:** MCP and lifecycle hooks are supported. Handoffs are not injected-at `SessionStart` yet (see below), and there is no managed workstream-(`ai-memory run copilot`).+**Status:** MCP and lifecycle hooks are supported, the `SessionStart` hook+injects the pending handoff (see below), and `ai-memory run copilot` launches+Copilot CLI as a managed workstream harness (see+[managed workstreams](managed-workstreams.md)).**Config files:** `$COPILOT_HOME/mcp-config.json` for MCP and`$COPILOT_HOME/hooks/ai-memory.json` for lifecycle hooks (`COPILOT_HOME`diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 3f43e2d6..1c8e6382 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -81,7 +81,7 @@ boundary not yet built.| 14 | Per-project authorization (#708) | `ai-memory-store/src/project_authz.rs` `authorize_project` / `ProjectAuthz::authorize` choke point (V68 `project_grants` + `projects.access_mode`, default `open`; V69 `projects.created_by` feeds `is_creator`); `scope.rs` `ScopeResolver::with_project_authz` (reader pool for reads, writer actor for writes) and its free forms `authorize_scope_for` / `*_guarded`, attached for every DB user by `ai-memory-mcp` `scope_resolver_as`, `ai-memory-web` `authorize_read` / `lookup_project`, and `ai-memory-hooks` (`grants.rs` `authorize_resolved` for run/workstream ids, the capture check in `router.rs`); read-shaped mutations resolve at `ProjectAccess::Write` (`resolve_existing_args(.., need)`); unscoped reads filtered before `LIMIT` by `reader.rs` `readable_repository_sql`; `WriterHandle::authorize_project` as defense in depth. Page ids are never taken from a caller (only derived from already-authorized hits), so there is no page-id entry point to guard; incremental `recent` resolves and authorizes the requested project before decoding its scope-bound cursor; batch outcomes do not bypass the capture grant or session owner check | `tests/suite/project_authz.rs` (decision matrix, ship-inert, resolver gate); `tests/suite/access_mode.rs` `every_caller_against_both_modes`, `a_restricted_project_admits_the_team_and_refuses_the_outsider`, `new_projects_follow_the_server_default_and_admit_their_creator`; `scope.rs` `the_argument_shape_does_not_decide_the_level`, `a_user_reaches_only_what_they_were_granted`, `creating_authorizes_against_a_project_that_already_exists`, `a_refused_scope_fails_the_search_instead_of_shortening_it`; `grants.rs` `search_finds_only_what_the_viewer_may_read`, `the_limit_counts_only_what_the_viewer_may_see`, `the_workspace_handoff_comes_only_from_readable_repositories`; `ai-memory-mcp` `server.rs` `a_reader_may_read_everything_and_change_nothing`, `bob_cannot_read_alices_page_in_a_restricted_project`, `bob_cannot_find_alices_page_by_searching_in_a_restricted_project`, `bob_cannot_consolidate_a_session_in_alices_repository`, `a_restricted_projects_queues_need_write`; `ai-memory-hooks` `a_capture_needs_writer_on_the_repository_it_lands_in`, `session_start_delivers_nothing_from_a_repository_the_viewer_cannot_read`, `run_and_workstream_ids_only_answer_someone_who_may_reach_the_repository` (foreign raw workstream id refuses populated provenance; granted reader receives the source record and tool correlation); `ai-memory-web` `web_reads_honour_grants_in_a_restricted_project`, `metadata_shows_only_what_the_viewer_may_read` — each with a granted or open-project control, and proven to fail with the choke point (18 tests) or the SQL filter (9 tests) neutralized; `routes.rs` `api_recent_incremental_rechecks_restricted_scope_on_cursor` (a valid cursor cannot bypass a revoked grant; granted control passes), `api_recent_incremental_paginates_over_120_pages_and_binds_cursor`; `mcp_stateless_http.rs` `generic_machine_client_writes_queries_and_claims_a_handoff` (real machine key, foreign scope and partial scope refused); `router.rs` `an_unauthorized_batch_item_is_consumed_rather_than_retried`, `batch_acknowledges_foreign_collision_then_commits_next_item` (refused foreign item followed by a legitimate stored item) | STRONG — slice 3 closed both bypass classes (unscoped reads, raw-id entry points) and added the root-only management surface. Out of scope by design: per-project administrators (granting/restricting is root-only), and access modes, creators and grants live only in SQLite, so `reindex` resets them || 14aa | Companion capture privacy before persistence and delivery | `companions/ai-memory-client/src/lib.rs` `reject_sensitive`, `sanitize_external_value`, `check_body`; `src/scrub.rs` `sanitize_external_text`; relay `identity::validate`, `check_scope`, `relay::init` and `flush_locked`; importer `plan_external_conversation`, `planned_hook_event`, `truncate_utf8`, `ImportClient::post_hook_batch` | SDK secret-position, nested key, numeric metric (11 names plus numeric `*_tokens` counts; string values still redact), bounded schema and literal-marker tests; relay `sensitive_envelope_is_rejected_before_enqueue_with_clean_control`, `new_native_bodies_are_sanitized_before_hash_enqueue_and_exact_retry`, `unsafe_legacy_pending_is_dropped_locally_and_never_blocks_its_session`, `unsafe_legacy_native_identity_is_dropped_and_its_session_continues`, `legacy_binding_scope_spaces_are_preserved_on_delivery`; importer `sensitive_native_identity_is_refused_before_manifest_and_http_with_unicode_control`, `shared_key_sanitation_precedes_plan_manifest_transport_and_exact_retry`, `preview_and_manifest_use_scrubbed_bodies_and_digest`, `forged_body_authority_is_refused_before_transport`, `sanitized_redaction_markers_survive_utf8_byte_caps_in_bodies_and_titles`. Controls preserve opaque native Unicode IDs, metric representation and untrusted provenance. An unsafe item queued before these checks never reaches the wire (body or request line); it leaves the queue as a local `dropped_policy` receipt so the rest of its session ships. Guard-removal runtime probes target the final formatted sources and restore identical hashes. | Client-side privacy only; server scope, auth, admission and capture-policy guards remain authoritative || 14ap | Managed-run mutation owner and current project access (finish, cancel, heartbeat, native-session link, context acceptance) | `hooks/src/workstream.rs` `authorize_run_owner` derives `ManagedRunAuthority` only from authenticated middleware extensions and checks the real run before any mutation — for finish before status/payload/segment handling; cancel, heartbeat, link and context acceptance go through the same helper, so none is a side door around finish's rule; `ReaderPool::authorize_managed_run` and `store/src/workstream.rs` `authorize_run_mutation` use a read snapshot and the existing writer transaction, respectively. Strict resolution (`project_authz.rs` `resolve_project_authz_strict`, the canonical decision with a fail-closed resolution mode, so the reserved global-scope write gate applies here too) requires the actual workspace/project pair, current user existence and current Write decision for DB principals. The private trusted-proxy policy requires authenticated User capability, a canonical identity, no DB principal and server proxy configuration; it retains legacy project admission after strict scope validation, with ownership still enforced. Human-login disable does not revoke API keys. The legacy resolver and auth middleware remain unchanged. Both writer entry paths, including finished retries, require the same authority; no cross-owner bypass | MCP `auth.rs` `owner_finish_http_refuses_another_writer_before_payload_or_segment`, `owner_finish_http_trusted_proxy_preserves_restricted_lifecycle`, `owner_finish_http_active_api_key_survives_disabled_human_login`; store `multi_session.rs` `owner_finish_store_refuses_another_writer_including_finished_retry`, `owner_finish_store_rechecks_write_after_preflight`, `owner_finish_store_refuses_a_deleted_user_after_preflight`, `owner_finish_store_proxy_policy_requires_server_and_authenticated_identity`, `owner_finish_store_raw_ids_use_the_actual_project_and_workspace`, `owner_finish_store_topology_reload_and_phase_controls`, `owner_finish_store_strict_resolution_refuses_pairing_missing_and_sql_failure`, `owner_finish_store_keeps_qualified_identity_namespaces`; hooks `workstream.rs` `owner_finish_revocation_between_preflight_and_both_writer_paths`; MCP `auth.rs` `owner_finish_http_real_auth_rungs_shared_and_project_controls`, `owner_finish_http_preserves_late_active_terminal_and_missing_phases`; hooks `workstream.rs` `run_mutation_routes_refuse_another_operator` (another operator and root under another identity refused on heartbeat/link/accept/cancel, run left active; owner admitted); store `project_authz.rs` `strict_resolution_shares_the_global_gate_and_fails_closed_on_a_gap`. Guard-neutralization recipes and results accompany the local frozen patch | SQL refusal is atomic within finish's writer transaction; a revocation after preflight can leave an unindexed raw segment. Cancel, heartbeat, link and acceptance check one read snapshot immediately before a single-row update (a run's owner never changes). A later hook event carrying `AI_MEMORY_RUN_ID` links its native session only through `link_native_session_in_scope`, which applies the SessionStart boundary (`ManagedRunBoundaryRow::admits`: the run's own project and operator) and refuses a foreign run id while the event itself is still captured (`router.rs` `hook_event_links_a_managed_run_only_from_its_operator`, `hook_event_in_another_project_does_not_link_the_run`, control `hook_event_links_a_shared_run_on_a_single_operator_server`; #1082). Shared NULL ownership, trusted-proxy project admission and late still-active finishes remain intentional |-| 14au | Exact native managed identity and privacy (invariant #16) | `core/src/workstream.rs` `NativeSessionIdentity` validates original bytes and exact scrub equality; `workstream/src/harness.rs` and `transcript.rs` retain selector/path restrictions; CLI `run.rs` validates old-server prepare/status, planned selectors and finish transport; hooks `workstream.rs` checks payload and selected identity before raw segments, with the existing owner/current Write preflight first; `router.rs` validates both managed auto-links while preserving legacy shared capture; store `workstream.rs` carries validated identities into link/finish SQL after finish authority and before mutation. Store, HTTP search and CLI search project invalid historical identity to empty String without rewriting history | Core `native_identity_original_bytes_limits_privacy_and_collisions`; harness `native_identity_selector_rejects_original_before_resume_arguments`; transcript `native_identity_adapter_preserves_exact_and_rejects_privacy_changes`; store multi-session `native_identity_store_link_refuses_original_dirty_bytes`, `native_identity_store_adoption_refuses_before_link`, `native_identity_store_finish_refuses_without_sql_or_index_mutation`, `native_identity_store_history_projects_unknown_without_rewriting`; hooks `native_identity_http_link_refuses_before_status_or_sql`, `native_identity_http_finish_refuses_before_segment_or_sql`, `native_identity_http_event_guard_and_configured_history_projection`, `native_identity_http_stored_identity_refuses_before_raw_segment`, router `native_identity_managed_start_refuses_but_keeps_shared_legacy_capture`; CLI `native_identity_run_preflight_refuses_before_resume_or_private_path`, `native_identity_run_old_server_refusal_prevents_child_and_transport`, `native_identity_finish_transport_refuses_before_request_and_preserves_exact_control`, `native_identity_run_status_and_expected_refuse_before_discovery`, `native_identity_run_configured_selector_refuses_before_link_or_child`, `native_identity_run_configured_old_status_refuses_before_native_io_and_finish`, `native_identity_run_configured_discovery_refuses_before_export`, suite `native_identity_search_old_server_json_projects_unknown_and_keeps_history` | Representation/privacy only: no native authenticity, file-existence, run/event correlation or outcome proof. Original legacy rows and shared observation semantics remain intact; parent finish owner/current Write rules remain mandatory |+| 14au | Exact native managed identity and privacy (invariant #16) | `core/src/workstream.rs` `NativeSessionIdentity` validates original bytes and exact scrub equality; `workstream/src/harness.rs` and `transcript.rs` retain selector/path restrictions; CLI `run.rs` validates old-server prepare/status, planned selectors and finish transport; hooks `workstream.rs` checks payload and selected identity before raw segments, with the existing owner/current Write preflight first; `router.rs` validates both managed auto-links while preserving legacy shared capture; store `workstream.rs` carries validated identities into link/finish SQL after finish authority and before mutation. Store, HTTP search and CLI search project invalid historical identity to empty String without rewriting history | Core `native_identity_original_bytes_limits_privacy_and_collisions`; harness `native_identity_selector_rejects_original_before_resume_arguments`; transcript `native_identity_adapter_preserves_exact_and_rejects_privacy_changes`, `copilot_discovery_requires_uuid_directory_header_and_checkout` (another checkout's session, a `session.start` naming a different session than its directory, and non-UUID or `../` ids refused; exact-checkout control); store multi-session `native_identity_store_link_refuses_original_dirty_bytes`, `native_identity_store_adoption_refuses_before_link`, `native_identity_store_finish_refuses_without_sql_or_index_mutation`, `native_identity_store_history_projects_unknown_without_rewriting`; hooks `native_identity_http_link_refuses_before_status_or_sql`, `native_identity_http_finish_refuses_before_segment_or_sql`, `native_identity_http_event_guard_and_configured_history_projection`, `native_identity_http_stored_identity_refuses_before_raw_segment`, router `native_identity_managed_start_refuses_but_keeps_shared_legacy_capture`; CLI `native_identity_run_preflight_refuses_before_resume_or_private_path`, `native_identity_run_old_server_refusal_prevents_child_and_transport`, `native_identity_finish_transport_refuses_before_request_and_preserves_exact_control`, `native_identity_run_status_and_expected_refuse_before_discovery`, `native_identity_run_configured_selector_refuses_before_link_or_child`, `native_identity_run_configured_old_status_refuses_before_native_io_and_finish`, `native_identity_run_configured_discovery_refuses_before_export`, suite `native_identity_search_old_server_json_projects_unknown_and_keeps_history` | Representation/privacy only: no native authenticity, file-existence, run/event correlation or outcome proof. Original legacy rows and shared observation semantics remain intact; parent finish owner/current Write rules remain mandatory || 14b | Repository identity routing (#708) | `ai-memory-store/src/ops.rs` `resolve_project_by_identity` — one transaction; an identity already on a project is never overwritten; an unclaimed project is claimed only when the capturing user may write it (the choke point's `resolve_project_authz` on the same transaction), otherwise it is returned unclaimed; a different identity under the same name splits into a new project with no shared `repo_path`; when a Phase-5 client explicitly sends `IdentityStyle::Path` (#1033) a project it creates takes `path_style_name` only while no different full identity in the workspace claims that canonical key (checked in the same transaction), so the same path on another forge falls back instead of being merged; authorized captures can claim/promote compatible legacy rows in that transaction while preserving UUID, but handoff/static reads never rename; explicit `host_path` remains the opt-out; `ai-memory-hooks/src/router.rs` `cache_key_for` keys the path cache by identity and style; `ai-memory-core/src/repository_identity.rs` strips credentials from remote URLs client-side, and the server accepts only the routing rungs (`explicit`, `git_remote`) from the wire | `tests/suite/identity_resolution.rs` `an_outsider_cannot_take_an_unclaimed_projects_identity` (control: `an_existing_project_is_claimed_in_place`), `two_unrelated_repositories_with_one_folder_name_stay_apart`, `a_created_or_split_project_admits_its_creator`, `the_same_path_on_another_forge_falls_back_instead_of_merging`, `an_unclaimed_project_holding_the_path_name_is_not_taken`, `old_client_omitted_style_stays_host_path_and_does_not_promote`, `explicit_path_capture_claims_and_promotes_an_identityless_legacy_name_in_one_transaction`, `unauthorized_capture_cannot_claim_or_promote_an_identityless_legacy_name`, and `explicit_path_capture_falls_back_when_another_identity_claims_the_canonical_key` (controls: `the_path_style_names_a_new_project_from_the_host_less_path`, `opting_in_leaves_existing_projects_where_they_are`), `multi_session.rs` `two_operators_on_two_clones_of_one_repository_share_its_path_named_project`; `router.rs` `the_path_style_names_a_new_repository_and_never_merges_another_forge`, `one_path_with_two_remotes_is_two_projects`, `two_api_checkouts_with_different_remotes_get_two_projects` (a manifest rung on the wire is ignored); `repository_identity.rs` credential and normalisation tables — the claim guard and the cache key each proven to fail their test when removed | STRONG — first claimant wins: in a restricted workspace a user who creates a project under a remote identity first holds it until root grants others || 14bb | Local marker aliases cannot cross repository or workspace boundaries (#1033) | `ai-memory-core/src/repository_identity.rs` owns the bounded `MarkerAliases` type and exact one-line/root-level portable grammar; native/POSIX/PowerShell/generated TypeScript clients forward one normalized JSON-array query value only with marker provenance and a hostful git-remote identity; `ai-memory-store/src/project_coordinates.rs` probes exact names only inside the selected workspace, deduplicates by UUID, and requires the selected row's full stored git-remote identity; `ops.rs` authorizes in the writer transaction and reuses Phase 1 `promotion_target`, additionally requiring marker `project` to equal the canonical path-style name derived from that remote; handoff uses the read-only path and capture uses the write-authorized path; `router.rs` includes aliases, provenance, and read/write mode in its cache key | Core/CLI shared `marker_aliases` fixture parity covers duplicate keys, table placement, multiline arrays, trailing junk/comma, escapes, max length and duplicate-heavy over-count; store `marker_aliases_require_same_remote_identity_and_preserve_uuid`, `marker_aliases_cannot_promote_to_an_arbitrary_marker_project`, `hostile_ambiguous_and_cross_workspace_marker_aliases_fail_closed`; hooks `hook_and_handoff_queries_validate_aliases_identically`, `malformed_aliases_are_rejected_before_subagent_scope_resolution`, `empty_aliases_preserve_marker_project_precedence`, `capture_promotes_an_alias_but_handoff_only_reads_it`, `project_cache_separates_alias_sets`; shell `marker aliases keep canonical project and forward remote identity`; Windows PowerShell parity and capture-only marker transparency run in Windows CI; OpenClaw `openclaw_runtime_preserves_marker_and_home_identity_precedence` proves no-marker remote routing sends explicit `path`, ordinary project markers keep name precedence and omit identity, while alias markers and home identity routes forward it | STRONG: hostile arbitrary-name, different-identity and ambiguous aliases refuse or resolve without rename with a legitimate canonical same-identity control; another workspace is never searched; no alias table or persistent fallback exists || 14bb2 | Operator-home route selectors cannot silently cross repository or path boundaries (#1033) | `ai-memory-cli/src/marker.rs` returns a typed invalid result for malformed/oversized maps; command scope resolution propagates it unless both CLI scope fields are explicit, while native hooks drop before spool/network. The native, POSIX, PowerShell, generated TypeScript and OpenClaw parsers enforce the shared 64-route/64-KiB/512-byte grammar, recognize malformed `[routes`, `routes =`, `routes.`, and orphan `route_*` syntax before any no-routes return, preserve legacy parsing for malformed root-only settings without route syntax, apply global duplicate-field/raw-selector/normalized-path checks, require exact hostful identities (including host-edge-dot refusal), match paths component-wise, and enforce a no-escape boundary for `~/` selectors. A route replaces only routing fields; root privacy/behavior flags survive. Bounded native/PowerShell/TypeScript reads reject before full-file allocation where their APIs permit. | `ai-memory-core/fixtures/home_route_cases.json` is executed by native `marker.rs`, POSIX, PowerShell, generated TypeScript, and OpenClaw runtime parity, including malformed route syntax and root-only malformed legacy behavior; shell `test_lib.sh` also exercises route selection, sibling refusal, root-setting retention and invalid-map drop; Windows `powershell_marker_aliases.rs` executes drive and UNC path routing independently of identity; generated TypeScript runtime tests assert marker versus repo-root `project_src`; CLI tests prove unscoped/partial refusal and complete-explicit bypass. | STRONG for native/POSIX/generated TypeScript/OpenClaw on this platform; PowerShell runtime evidence is enforced on Windows CI and skipped where PowerShell is unavailable |diff --git a/docs/support-matrix.md b/docs/support-matrix.mdindex 9ebf4b9e..b16390db 100644--- a/docs/support-matrix.md+++ b/docs/support-matrix.md@@ -22,7 +22,7 @@| Oh My Pi / OMP | Supported | Use `--client omp` / `--agent omp` (or `oh-my-pi`) for native `.omp` MCP config + TypeScript extension; generated extension enforces capture exclusions. || Pi | Supported | Generated `~/.pi/agent/extensions/ai-memory-pi.ts` extension provides lifecycle capture and an HTTP MCP bridge; generated extension enforces capture exclusions. || Crush | Managed-only | `ai-memory run crush` resumes its project-local session database and supplies portable context through a temporary supported global-context file; no lifecycle-hook installer is provided. |-| Managed workstreams | Opt-in | `ai-memory run` provides transparent cross-harness continuity for Claude Code, Codex, OpenCode, OpenCode 2 beta, Pi, Crush, Kimi Code, Command Code, both incompatible Kiro CLI engines, OMP, Grok Build CLI, and Antigravity CLI. Direct launches remain unchanged. See [`docs/managed-workstreams.md`](managed-workstreams.md). |+| Managed workstreams | Opt-in | `ai-memory run` provides transparent cross-harness continuity for Claude Code, Codex, OpenCode, OpenCode 2 beta, Pi, Crush, Kimi Code, Command Code, both incompatible Kiro CLI engines, OMP, Grok Build CLI, Antigravity CLI, and GitHub Copilot CLI. Direct launches remain unchanged. See [`docs/managed-workstreams.md`](managed-workstreams.md). || `--yolo` safety + ai-jail | Linux/macOS; Windows partial | `ai-memory run --yolo` warns before it disarms an agent's permission prompts and, on Linux/macOS, offers to re-exec the session inside [ai-jail](https://github.com/akitaonrails/ai-jail) when it is usable — installed and with its sandbox backend present (`bwrap` / `sandbox-exec`); otherwise it asks nothing and proceeds (`--network`, forwarding only already-set credential/config env vars). Accepting the offer shows a checklist of ai-jail toggles pre-marked with smart defaults (credentials present on the host, SSH for an SSH `origin`, worktree metadata in a linked worktree; Docker socket, GPU, display, Pictures, Tailscale unchecked). `--jail` re-runs inside ai-jail without asking (also without `--yolo` and non-interactively; it errors when ai-jail is not usable), `--jail=github,aws,no-mise` is exact (every unnamed checklist row is forced off with `--no-X`; `all`/`none` too; the checklist likewise passes unchecked rows as `--no-X`, while bare `--jail` leaves unmarked rows to your ai-jail config), and `--no-jail` skips the offer. Only toggles the installed ai-jail supports are offered; the credential mounts (`github`, `aws`, `kube`, `gcloud`, `docker-config`) need ai-jail 2.5.0. A project `.ai-jail` in the launch directory replaces the checklist and the bare-`--jail` defaults (ai-jail loads it as-is; `--jail=…` still overrides), and every re-exec passes `--no-save-config` so ai-jail never writes the run's flags into it. Both prompts are skipped on a non-interactive stdin/stderr and when already detected inside ai-jail. Windows gets the warning but never the ai-jail offer (ai-jail is Linux/macOS-only). Opt-in `--true-yolo` implies `--yolo` and, for Claude only, additionally forces `bypassPermissions` over any settings `defaultMode` (interchangeable with `--yolo` for other harnesses); `claude_true_yolo` applies the same Claude extra to `--yolo` launches. Claude's own explicit `ask` rules and command-safety checks still prompt in every mode. See [`docs/design-yolo-safety-ai-jail.md`](design-yolo-safety-ai-jail.md). || Claude Desktop (Chat) | MCP-only | Uses `mcp-remote`; the ordinary Chat surface does not run plugin hooks. Cowork plugins can run hooks, but ai-memory does not yet ship a Cowork plugin integration; see the explicit boundary in [`mcp-install.md`](mcp-install.md#claude-desktop). || OpenClaw | Supported | MCP config + native plugin lifecycle hooks; generated plugin enforces capture exclusions. |@@ -34,7 +34,7 @@| Kimi Code | Supported | MCP config (`url` entry in `~/.kimi-code/mcp.json`) + lifecycle hooks (`[[hooks]]` in `~/.kimi-code/config.toml`, 10 events including subagent start/stop and `PostToolUseFailure` for tool-failure capture); both paths honor `$KIMI_CODE_HOME`. Handoffs inject via `UserPromptSubmit` stdout (Kimi Code discards `SessionStart` hook stdout); `ai-memory run kimi` adds managed workstream resume. || Kiro CLI | Supported | MCP config uses `install-mcp --client kiro-cli` (alias `kiro`) and Kiro's Bedrock-compatible schema flavor. `install-hooks --agent kiro-cli` merges v2 hooks into existing agent configs; the explicit `--agent kiro-cli-v3` target writes the incompatible standalone v3 registration. Both preserve unrelated entries, honor `$KIRO_HOME`, enforce capture exclusions, and inject pending handoffs at session start. Kiro has no true SessionEnd hook; use `ai-memory finalize-session --agent kiro-cli`, with `--session-id <uuid>` for concurrent sessions, unless it is an interactive session launched with `ai-memory run kiro`, which finalizes it automatically when it exits if the run can tie the session to itself (see [`docs/managed-workstreams.md`](managed-workstreams.md)). `ai-memory run kiro` manages v2; add `--v3`, `--mode`, or `--agent-engine v3` for version-safe v3 resume. || Pool | Hooks-only | Poolside Agent CLI (`pool`). Lifecycle-hook capture via `install-hooks --agent pool` (alias `poolside`): Pool reads project-scoped hooks from the repo-root `.poolside/settings.yaml`, so ai-memory stages the scripts and prints a ready-to-paste `hooks:` snippet rather than writing committed project files; native commands enforce capture exclusions. Five Claude-shaped events (`SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `Stop`) and no true session-end — `Stop` is a turn boundary, so run `ai-memory finalize-session --agent pool` after the final turn. `SessionStart` stdout injection is not demonstrated, so capture works but handoff injection does not — recover handoffs via MCP `memory_handoff_list` then `memory_handoff_accept` with that `handoff_id`. No first-party `install-mcp` client and no managed workstream (`ai-memory run pool`) are claimed: Pool's native session-store contract is not demonstrated (see [`docs/managed-harness-contributions.md`](managed-harness-contributions.md)). Verified against Poolside CLI v1.0.16. |-| GitHub Copilot CLI | Supported | MCP config (`install-mcp --client copilot-cli` → `$COPILOT_HOME/mcp-config.json`, root `mcpServers`, `type: "http"`) + lifecycle hooks: `install-hooks --agent copilot-cli` writes `$COPILOT_HOME/hooks/ai-memory.json` (`COPILOT_HOME` defaults to `~/.copilot`). Configured with PascalCase event names, so Copilot sends the VS Code/Claude-compatible payload (`session_id`, `cwd`, `tool_name`, `tool_input`, `tool_result`) and native commands enforce capture exclusions; 10 events, Claude Code's nine plus `PostToolUseFailure`. Entries are flat with no `matcher`, because Copilot rejects it on `SessionStart`/`Stop`/`SessionEnd` and subagent events. The `SessionStart` hook delivers the prior session's handoff through Copilot's top-level `additionalContext`. `--scope project` is intentionally unsupported: Copilot's repository hook files (`.github/hooks/*.json`) are versioned and shared with the team and the cloud agent, so they cannot carry this machine's absolute executable and data-dir paths. `ai-memory run copilot` is a follow-up (#1040). The bare `--client copilot` alias keeps meaning VS Code Copilot. |+| GitHub Copilot CLI | Supported | MCP config (`install-mcp --client copilot-cli` → `$COPILOT_HOME/mcp-config.json`, root `mcpServers`, `type: "http"`) + lifecycle hooks: `install-hooks --agent copilot-cli` writes `$COPILOT_HOME/hooks/ai-memory.json` (`COPILOT_HOME` defaults to `~/.copilot`). Configured with PascalCase event names, so Copilot sends the VS Code/Claude-compatible payload (`session_id`, `cwd`, `tool_name`, `tool_input`, `tool_result`) and native commands enforce capture exclusions; 10 events, Claude Code's nine plus `PostToolUseFailure`. Entries are flat with no `matcher`, because Copilot rejects it on `SessionStart`/`Stop`/`SessionEnd` and subagent events. The `SessionStart` hook delivers the prior session's handoff through Copilot's top-level `additionalContext`. `--scope project` is intentionally unsupported: Copilot's repository hook files (`.github/hooks/*.json`) are versioned and shared with the team and the cloud agent, so they cannot carry this machine's absolute executable and data-dir paths. `ai-memory run copilot` (alias `copilot-cli`) adds managed workstream resume: a generated `--session-id` for a fresh session, `--resume=<id>` to return, and visible-history import from `$COPILOT_HOME/session-state/<uuid>/events.jsonl` (see [`docs/managed-workstreams.md`](managed-workstreams.md)). The bare `--client copilot` alias of `install-mcp` keeps meaning VS Code Copilot. || VS Code Copilot | MCP-only | `.vscode/mcp.json` for Copilot agent mode; no lifecycle hooks (Copilot does not expose them yet). || Zed | MCP-only | Native remote MCP under `context_servers` in Zed's user `settings.json`; no lifecycle hooks or managed-workstream support. || Muse Code | MCP-only | `install-mcp --client muse` merges a native streamable-HTTP entry with bearer `headers` into the snake_case `mcp_servers` map of `~/.config/muse/settings.json`, preserving sibling servers. The writer adds the mandatory `"schema_version": 1` when absent (without it every `muse` command fails at startup) and never rewrites an existing value, and it sets `"mode": "optional"` because Muse's default `required` aborts the whole run when the server is unreachable. Skills need no extra step: Muse reads `~/.agents/skills`, which `install-skills` already writes. Lifecycle capture and managed workstreams are not claimed — Muse documents a hook surface, but the output contract of its `SessionStart` event is not specified. |diff --git a/docs/use-cases.md b/docs/use-cases.mdindex f42987ed..378a76d8 100644--- a/docs/use-cases.md+++ b/docs/use-cases.md@@ -82,7 +82,7 @@ai-memory detects the orphan before launch and starts fresh; `--fresh` forcesthat recovery for one harness. Managed mode currently covers Claude Code,Codex, OpenCode, OpenCode 2 beta, Pi, Crush, Kimi Code, Command Code, Kiro CLI v2/v3, OMP,- Grok Build CLI, and Antigravity CLI; direct harness launches remain unchanged. See+ Grok Build CLI, Antigravity CLI, and GitHub Copilot CLI; direct harness launches remain unchanged. See[Managed cross-harness workstreams](managed-workstreams.md).- **"Just put me back where I was."** From any directory, with no name totype and no list to read: