Skip to content

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

Rust

feat(hooks): add GitHub Copilot CLI as a hooked agent (#1040)

Maxsuel Einstein30416a8f82ba
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 762d7fbb..a73c087c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- Added GitHub Copilot CLI as a hooked agent: `install-hooks --agent
+ copilot-cli` writes `$COPILOT_HOME/hooks/ai-memory.json` (default
+ `~/.copilot/hooks/ai-memory.json`) with Copilot's flat, matcher-less entries
+ and PascalCase event names, so Copilot sends its VS Code/Claude-compatible
+ payload. Ten events — Claude Code's nine plus `PostToolUseFailure` — with
+ native commands enforcing capture exclusions; tool output is read from
+ `tool_result.text_result_for_llm` and the outcome from
+ `tool_result.result_type`. Copilot reads a top-level `additionalContext` on
+ `SessionStart` rather than Claude Code's envelope, so handoffs are not
+ injected yet: recover them with `memory_handoff_accept`. The bare
+ `install-mcp --client copilot` alias keeps meaning VS Code Copilot;
+ `install-mcp --client copilot-cli` and `ai-memory run copilot` follow
+ separately. (#1040)
- Added `install-hooks --agent claude-code --scope project`, which writes the
hook configuration to the checkout's gitignored `.claude/settings.local.json`
(where Claude Code reads it: the git root, or the launch directory on
diff --git a/README.md b/README.md
index a6b262f0..1b346eeb 100644
--- a/README.md
+++ b/README.md
@@ -132,6 +132,7 @@ caveats is in [`docs/support-matrix.md`](docs/support-matrix.md).
| Kimi Code | Supported |
| Kiro CLI | Supported |
| Pool | Hooks-only |
+| GitHub Copilot CLI | Hooks-only |
| VS Code Copilot | MCP-only |
| Zed | MCP-only |
| Muse Code | MCP-only |
@@ -311,7 +312,7 @@ docker run -d --name ai-memory \
# 3. Wire your agent CLI in two commands. The wrapper takes care of
# mounts and each client's config-path detection. Re-run with
# `--agent codex`, `--agent command-code`, `--agent devin`, `--agent opencode`, `--agent opencode2`, `--agent gemini-cli`,
-# `--agent grok`, `--agent kimi-code`, `--agent kiro-cli`, `--agent omp`,
+# `--agent grok`, `--agent kimi-code`, `--agent kiro-cli`, `--agent copilot-cli`, `--agent omp`,
# `--agent oh-my-pi`, `--client cursor`,
# `--client gemini-cli`, `--client grok`, `--client kiro-cli`, etc.
# for additional agents; full list in docs/install.md.
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 076677aa..ba5d267b 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -2249,6 +2249,18 @@ pub enum AgentChoice {
/// `install-hooks --agent hermes` prints the ready-to-paste block.
#[value(alias = "hermes-agent")]
Hermes,
+ /// GitHub Copilot CLI — JSON-config lifecycle hooks in
+ /// `$COPILOT_HOME/hooks/ai-memory.json` (default
+ /// `~/.copilot/hooks/ai-memory.json`). Configured with PascalCase event
+ /// names, so Copilot sends the VS Code/Claude-compatible payload and the
+ /// existing key-based extraction applies (#1040). No bare `copilot`
+ /// alias: that word is already `install-mcp --client copilot`'s alias for
+ /// the unrelated VS Code MCP client. NOTE: Copilot CLI reads a top-level
+ /// `additionalContext` on `SessionStart`, not Claude Code's envelope, so
+ /// capture works but handoff injection does not yet — recover the prior
+ /// session's handoff via the MCP `memory_handoff_accept` tool.
+ #[value(name = "copilot-cli")]
+ CopilotCli,
}
impl AgentChoice {
@@ -2279,6 +2291,7 @@ impl AgentChoice {
Self::Pool => AgentKind::Pool,
Self::Zcode => AgentKind::Zcode,
Self::Hermes => AgentKind::Hermes,
+ Self::CopilotCli => AgentKind::CopilotCli,
}
}
@@ -4170,6 +4183,21 @@ mod tests {
}
}
+ #[test]
+ fn copilot_cli_install_hooks_agent_parses_without_a_bare_copilot_alias() {
+ let hooks = Cli::try_parse_from(["ai-memory", "install-hooks", "--agent", "copilot-cli"])
+ .expect("copilot-cli should parse");
+ let Command::InstallHooks(args) = hooks.command else {
+ panic!("expected install-hooks");
+ };
+ assert_eq!(args.agent, AgentChoice::CopilotCli);
+ assert_eq!(args.agent.kind(), ai_memory_core::AgentKind::CopilotCli);
+ assert_eq!(args.agent.script_hook_subdir(), Some("copilot-cli"));
+ // `copilot` already means the VS Code MCP client on `install-mcp`;
+ // it must not silently select the CLI hook agent here.
+ assert!(Cli::try_parse_from(["ai-memory", "install-hooks", "--agent", "copilot"]).is_err());
+ }
+
#[test]
fn swival_mcp_client_parses() {
let cli = Cli::try_parse_from([
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index a5d7371e..fffec76c 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -31,10 +31,10 @@ use crate::commands::openclaw_plugin;
use crate::commands::path_util::{home_dir, strip_windows_verbatim_prefix};
use crate::commands::render_shared::{
ANTIGRAVITY_LIFECYCLE_EVENTS, ANTIGRAVITY_TOOL_EVENTS, CODEX_PROFILE, COMMAND_CODE_PROFILE,
- CURSOR_PROFILE, GEMINI_PROFILE, KIMI_CODE_EVENTS, KIRO_CLI_V2_EVENTS, KIRO_CLI_V3_EVENTS,
- POOL_EVENTS, build_antigravity_payload_with_data_dir, build_claude_code_payload_with_data_dir,
- build_devin_payload_with_data_dir, build_grok_payload_with_data_dir,
- build_kiro_cli_v2_hooks_value, build_kiro_cli_v3_hooks_value,
+ COPILOT_CLI_PROFILE, CURSOR_PROFILE, GEMINI_PROFILE, KIMI_CODE_EVENTS, KIRO_CLI_V2_EVENTS,
+ KIRO_CLI_V3_EVENTS, POOL_EVENTS, build_antigravity_payload_with_data_dir,
+ build_claude_code_payload_with_data_dir, build_devin_payload_with_data_dir,
+ build_grok_payload_with_data_dir, build_kiro_cli_v2_hooks_value, build_kiro_cli_v3_hooks_value,
build_pool_settings_yaml_with_data_dir, build_profile_payload_for_agent,
hook_embedded_exe_path, hook_script_for_claude_code, hook_script_for_current_platform,
kimi_code_hook_commands, local_hook_policy_v1_supported, ts_capture_policy_v1,
@@ -252,6 +252,28 @@ pub(crate) fn command_code_settings_path() -> anyhow::Result<std::path::PathBuf>
.join("settings.json"))
}
+/// `$COPILOT_HOME/hooks/ai-memory.json` when set, else
+/// `~/.copilot/hooks/ai-memory.json` — GitHub Copilot CLI user-level
+/// lifecycle hooks (#1040).
+pub(crate) fn copilot_cli_hooks_path() -> anyhow::Result<std::path::PathBuf> {
+ copilot_cli_hooks_path_in(std::env::var_os("COPILOT_HOME"))
+}
+
+/// The env value comes in as a parameter so tests can exercise both
+/// branches without mutating process env (mirrors [`codex_hooks_path_in`]).
+fn copilot_cli_hooks_path_in(
+ env_override: Option<std::ffi::OsString>,
+) -> anyhow::Result<std::path::PathBuf> {
+ if let Some(dir) = crate::commands::path_util::agent_config_home(env_override) {
+ return Ok(dir.join("hooks").join("ai-memory.json"));
+ }
+ Ok(home_dir()
+ .context("could not locate $HOME for ~/.copilot/hooks/ai-memory.json")?
+ .join(".copilot")
+ .join("hooks")
+ .join("ai-memory.json"))
+}
+
/// `~/.cursor/hooks.json`.
pub(crate) fn cursor_hooks_path() -> anyhow::Result<std::path::PathBuf> {
Ok(home_dir()
@@ -810,6 +832,11 @@ pub fn run(config: &Config, mut args: InstallHooksArgs) -> Result<()> {
resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent, &config.data_dir)?;
apply_to_pool(&hooks_dir, &server_url, auth, &config.data_dir, &args)
}
+ AgentChoice::CopilotCli => {
+ let hooks_dir =
+ resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent, &config.data_dir)?;
+ apply_to_copilot_cli_hooks(&hooks_dir, &server_url, auth, &config.data_dir, &args)
+ }
};
}
let strategy = args.project_strategy.and_then(ProjectStrategyArg::baked);
@@ -952,6 +979,18 @@ pub fn run(config: &Config, mut args: InstallHooksArgs) -> Result<()> {
resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent, &config.data_dir)?;
render_pool(&hooks_dir, &server_url, auth, &config.data_dir, strategy)
}
+ AgentChoice::CopilotCli => {
+ let hooks_dir =
+ resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent, &config.data_dir)?;
+ render_agent(
+ "copilot-cli",
+ &hooks_dir,
+ &server_url,
+ auth,
+ strategy,
+ &[COPILOT_CLI_PROFILE.events],
+ )
+ }
}
}
@@ -1141,6 +1180,7 @@ fn existing_agent_config(args: &InstallHooksArgs) -> Option<String> {
// user-global file the installer could re-read a baked strategy from.
AgentChoice::Pool => return None,
AgentChoice::KiroCliV3 => kiro_cli_v3_hooks_path().ok()?,
+ AgentChoice::CopilotCli => copilot_cli_hooks_path().ok()?,
}
};
std::fs::read_to_string(path).ok()
@@ -1548,6 +1588,9 @@ pub(crate) fn mcp_client_for_agent(agent: AgentChoice) -> Option<McpClient> {
// No first-party Hermes MCP installer ships yet, so there is no config
// file to infer a server URL or token from.
AgentChoice::Hermes => None,
+ // `install-mcp --client copilot-cli` is tracked separately (#1040
+ // PR2); until it lands there is no config file to scrape.
+ AgentChoice::CopilotCli => None,
}
}
@@ -2269,6 +2312,108 @@ fn apply_to_command_code_settings_with_payload(
Ok(())
}
+/// Mutate `~/.copilot/hooks/ai-memory.json` (creating it if absent) so
+/// Copilot CLI fires the ai-memory scripts on every lifecycle event. The file
+/// is Copilot's standalone hook format: `{"version": 1, "hooks": {...}}` with
+/// flat, matcher-less entries (`COPILOT_CLI_PROFILE`, #1040).
+fn apply_to_copilot_cli_hooks(
+ hooks_dir: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
+ data_dir: &Path,
+ args: &InstallHooksArgs,
+) -> Result<()> {
+ let staged = stage_hook_scripts(hooks_dir, "copilot-cli", data_dir)?;
+ apply_to_copilot_cli_hooks_with_staged(&staged, server_url, auth_token, data_dir, args)
+}
+
+#[cfg(test)]
+fn apply_to_copilot_cli_hooks_in(
+ hooks_dir: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
+ data_dir: &Path,
+ staging_data_local: &Path,
+ args: &InstallHooksArgs,
+) -> Result<()> {
+ let staged = stage_hook_scripts_in(hooks_dir, "copilot-cli", staging_data_local)?;
+ let command_dir = staged_command_dir(&staged, "copilot-cli");
+ let payload = crate::commands::render_shared::build_profile_script_payload_for_test(
+ &COPILOT_CLI_PROFILE,
+ &command_dir,
+ server_url,
+ auth_token,
+ "copilot-cli",
+ Some(data_dir),
+ args.project_strategy.and_then(ProjectStrategyArg::baked),
+ );
+ apply_to_copilot_cli_hooks_with_payload(payload, args)
+}
+
+fn apply_to_copilot_cli_hooks_with_staged(
+ staged: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
+ data_dir: &Path,
+ args: &InstallHooksArgs,
+) -> Result<()> {
+ let command_dir = staged_command_dir(staged, "copilot-cli");
+ let payload = build_profile_payload_for_agent(
+ &COPILOT_CLI_PROFILE,
+ &command_dir,
+ server_url,
+ auth_token,
+ "copilot-cli",
+ Some(data_dir),
+ args.project_strategy.and_then(ProjectStrategyArg::baked),
+ // Copilot CLI is refused by `capture_assistant_allowed`; never bake it.
+ false,
+ );
+ apply_to_copilot_cli_hooks_with_payload(payload, args)
+}
+
+fn apply_to_copilot_cli_hooks_with_payload(
+ payload: serde_json::Value,
+ args: &InstallHooksArgs,
+) -> Result<()> {
+ let path = match &args.config_file {
+ Some(path) => path.clone(),
+ None => copilot_cli_hooks_path()?,
+ };
+ let our_hooks = payload
+ .get("hooks")
+ .and_then(serde_json::Value::as_object)
+ .context("internal: Copilot CLI payload did not return a hooks object")?
+ .clone();
+ let outcome = apply_atomic(&path, |existing| {
+ mutate_json(existing, |root| {
+ // Copilot CLI hook files are versioned ("version": 1), like
+ // Cursor's hooks.json — overwrite unconditionally.
+ root.insert("version".into(), serde_json::json!(1));
+ let hooks = root
+ .entry("hooks")
+ .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()))
+ .as_object_mut()
+ .context("`hooks` is present in the hooks file but not an object")?;
+ for (event, value) in &our_hooks {
+ overlay_event_hooks(hooks, event, value);
+ }
+ Ok(())
+ })
+ })?;
+ println!(
+ "✓ {} {} ({})",
+ outcome.verb(),
+ path.display(),
+ match outcome {
+ ApplyOutcome::Created => "new file",
+ ApplyOutcome::Updated => "backup written next to it",
+ ApplyOutcome::NoOp => "already up to date",
+ }
+ );
+ Ok(())
+}
+
/// Mutate `~/.codex/hooks.json` (creating it if absent) so Codex's
/// lifecycle hook runner fires the ai-memory scripts on every
/// session/prompt/tool event.
@@ -6595,6 +6740,7 @@ mod tests {
KiroCliV3,
Pool,
Zcode,
+ CopilotCli,
] {
assert!(
!capture_assistant_allowed(agent),
@@ -6830,6 +6976,101 @@ mod tests {
assert_eq!(hooks.len(), COMMAND_CODE_PROFILE.events.len());
}
+ #[test]
+ fn copilot_cli_apply_uses_claude_compatible_events_and_preserves_user_settings() {
+ let source = TempDir::new().unwrap();
+ stub_scripts(
+ source.path(),
+ &[
+ "session-start.sh",
+ "user-prompt-submit.sh",
+ "pre-tool-use.sh",
+ "post-tool-use.sh",
+ "pre-compact.sh",
+ "stop.sh",
+ "session-end.sh",
+ "subagent-start.sh",
+ "subagent-stop.sh",
+ ],
+ );
+ let staging_root = TempDir::new().unwrap();
+ let staging = staging_root.path().join("ai-memory");
+ let config_dir = TempDir::new().unwrap();
+ let config_path = config_dir.path().join("ai-memory.json");
+ fs::write(
+ &config_path,
+ serde_json::json!({
+ "hooks": {
+ "SessionStart": [{"type": "command", "command": "third-party"}]
+ }
+ })
+ .to_string(),
+ )
+ .unwrap();
+ let args = InstallHooksArgs {
+ agent: AgentChoice::CopilotCli,
+ config_file: Some(config_path.clone()),
+ ..default_hook_args()
+ };
+
+ apply_to_copilot_cli_hooks_in(
+ source.path(),
+ "http://memory:49374",
+ Some("token"),
+ config_dir.path(),
+ &staging,
+ &args,
+ )
+ .unwrap();
+ let first = fs::read_to_string(&config_path).unwrap();
+ apply_to_copilot_cli_hooks_in(
+ source.path(),
+ "http://memory:49374",
+ Some("token"),
+ config_dir.path(),
+ &staging,
+ &args,
+ )
+ .unwrap();
+ let second = fs::read_to_string(&config_path).unwrap();
+ assert_eq!(first, second, "re-apply must be idempotent");
+
+ let value: serde_json::Value = serde_json::from_str(&second).unwrap();
+ assert_eq!(value["version"], 1, "Copilot CLI requires version: 1");
+ let hooks = value["hooks"].as_object().unwrap();
+ for (event, _) in COPILOT_CLI_PROFILE.events {
+ let entries = hooks[*event].as_array().unwrap();
+ let ours = entries
+ .iter()
+ .find(|entry| serde_json::to_string(entry).unwrap().contains("ai-memory"))
+ .unwrap_or_else(|| panic!("missing ai-memory entry for {event}"));
+ // Flat entry: the handler sits directly in the event array.
+ assert_eq!(ours["type"], "command", "event: {event}");
+ assert!(ours["command"].is_string(), "event: {event}");
+ assert!(ours.get("hooks").is_none(), "event: {event}");
+ assert!(
+ ours.get("matcher").is_none(),
+ "Copilot CLI rejects matcher on several events, so it must never be present \
+ (event: {event})"
+ );
+ }
+ assert_eq!(
+ hooks["SessionStart"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .filter(|entry| serde_json::to_string(entry)
+ .unwrap()
+ .contains("third-party"))
+ .count(),
+ 1,
+ "third-party hook must survive"
+ );
+ // PostToolUseFailure reuses post-tool-use.sh, same script as
+ // PostToolUse, but is still its own distinct event key.
+ assert_eq!(hooks["PostToolUseFailure"], hooks["PostToolUse"].clone());
+ }
+
#[test]
fn overlay_event_hooks_inserts_when_event_absent() {
let mut hooks = serde_json::Map::new();
@@ -11390,6 +11631,28 @@ command = "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kimi-code/sessio
}
}
+ /// `COPILOT_HOME` relocates Copilot CLI's config home, hooks included
+ /// (`$COPILOT_HOME/hooks/`, per Copilot's hooks reference).
+ #[test]
+ fn copilot_cli_hooks_path_honours_copilot_home() {
+ let custom = if cfg!(windows) {
+ r"C:\custom\copilot"
+ } else {
+ "/custom/copilot"
+ };
+ let path = copilot_cli_hooks_path_in(Some(std::ffi::OsString::from(custom))).unwrap();
+ assert_eq!(path, Path::new(custom).join("hooks").join("ai-memory.json"));
+
+ for env in [None, Some(std::ffi::OsString::new())] {
+ let path = copilot_cli_hooks_path_in(env).unwrap();
+ assert!(
+ path.ends_with(Path::new(".copilot").join("hooks").join("ai-memory.json")),
+ "default must be ~/.copilot/hooks/ai-memory.json, got {}",
+ path.display()
+ );
+ }
+ }
+
/// The test-only Claude Code wrapper must stage scripts under its injected
/// data-local root and wire that stable path into the generated config.
#[test]
diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rs
index 0f7f0ef8..819b07a8 100644
--- a/crates/ai-memory-cli/src/commands/render_shared.rs
+++ b/crates/ai-memory-cli/src/commands/render_shared.rs
@@ -77,6 +77,30 @@ pub(crate) const KIMI_CODE_EVENTS: [(&str, &str); 10] = [
("SubagentStop", "subagent-stop.sh"),
];
+/// GitHub Copilot CLI's lifecycle events, configured with PascalCase event
+/// names so the payload comes in the Claude Code/VS-Code-compatible shape
+/// (`session_id`, `cwd`, `tool_name`, `tool_input`, `tool_result`) instead of
+/// its native camelCase one — this lets it free-ride on the same key-based
+/// payload extraction as Claude Code/Codex/Zcode (see `tool_observation_metadata`
+/// in `capture_policy.rs`) rather than needing a dedicated parser (#1040).
+/// Same vocabulary as `KIMI_CODE_EVENTS`: Claude Code's 9 events plus
+/// `PostToolUseFailure`, which Copilot (per
+/// <https://docs.github.com/en/copilot/reference/hooks-configuration>) fires
+/// instead of `PostToolUse` when a tool call errors — the server already
+/// aliases it to `PostToolUse` (`HookEvent::parse`), so it reuses that script.
+pub(crate) const COPILOT_CLI_EVENTS: [(&str, &str); 10] = [
+ ("SessionStart", "session-start.sh"),
+ ("UserPromptSubmit", "user-prompt-submit.sh"),
+ ("PreToolUse", "pre-tool-use.sh"),
+ ("PostToolUse", "post-tool-use.sh"),
+ ("PostToolUseFailure", "post-tool-use.sh"),
+ ("PreCompact", "pre-compact.sh"),
+ ("Stop", "stop.sh"),
+ ("SessionEnd", "session-end.sh"),
+ ("SubagentStart", "subagent-start.sh"),
+ ("SubagentStop", "subagent-stop.sh"),
+];
+
/// Kiro CLI v2-engine lifecycle events. Each pair is
/// `(trigger-name-in-agent-config, POSIX hook-script-filename)`.
///
@@ -875,6 +899,14 @@ pub(crate) enum HookShape {
/// `hooks.json` also requires a sibling `version: 1` key at
/// the top level — handled by the caller's apply path.
Flat,
+ /// GitHub Copilot CLI: `"E": [ { "type":"command", "command":"..." } ]`.
+ /// Entries sit directly in the event array like Cursor's, but with no
+ /// `matcher`: Copilot rejects it on `sessionStart`/`sessionEnd`/
+ /// `userPromptSubmitted`/`agentStop`/`subagentStop`/`errorOccurred` and
+ /// treats it as an optional filter elsewhere, so omitting it everywhere
+ /// means "fire on every invocation". The file's top-level `version: 1` is
+ /// handled by the caller's apply path, as for Cursor.
+ FlatWithoutMatcher,
}
/// One hook profile = (event vocabulary, JSON shape). Each agent
@@ -962,6 +994,13 @@ pub(crate) const COMMAND_CODE_PROFILE: HookProfile = HookProfile {
events: &COMMAND_CODE_EVENTS,
shape: HookShape::NestedWithoutMatcher,
};
+/// Copilot keeps its flat entry shape even with PascalCase event names — only
+/// the payload sent to the script switches to snake_case — so this is
+/// `FlatWithoutMatcher`, not Claude's `Nested` (see the variant's doc).
+pub(crate) const COPILOT_CLI_PROFILE: HookProfile = HookProfile {
+ events: &COPILOT_CLI_EVENTS,
+ shape: HookShape::FlatWithoutMatcher,
+};
pub(crate) const CURSOR_PROFILE: HookProfile = HookProfile {
events: &CURSOR_EVENTS,
shape: HookShape::Flat,
@@ -1500,6 +1539,7 @@ fn build_hook_payload_for_platform(
"hooks": [handler],
}]),
HookShape::Flat => Value::Array(vec![hook_handler_with_matcher(handler)]),
+ HookShape::FlatWithoutMatcher => Value::Array(vec![handler]),
};
hooks_block.insert((*event).to_string(), entry);
}
@@ -2851,6 +2891,38 @@ if (inheritOnly) {
/// outer level — which made Claude Code refuse to load
/// settings.json with "hooks: Expected array, but received
/// undefined" on every event.
+ /// Copilot CLI keeps its flat entry shape even when the event names are
+ /// PascalCase (only the payload sent to the script changes), and rejects
+ /// `matcher` on session/stop/subagent events — so every entry must be a
+ /// bare `{type, command}` handler: no nested `hooks`, no `matcher`.
+ #[test]
+ fn copilot_cli_payload_uses_flat_entries_without_matcher() {
+ let root = PathBuf::from("/host/hooks/copilot-cli");
+ let v = build_posix_hook_payload(
+ COPILOT_CLI_PROFILE.events,
+ &root,
+ "http://localhost:49374",
+ None,
+ COPILOT_CLI_PROFILE.shape,
+ );
+ let hooks = v.pointer("/hooks").and_then(|h| h.as_object()).unwrap();
+ assert_eq!(hooks.len(), COPILOT_CLI_EVENTS.len());
+ for (event, _) in COPILOT_CLI_EVENTS {
+ let entry = v
+ .pointer(&format!("/hooks/{event}/0"))
+ .and_then(|e| e.as_object())
+ .unwrap_or_else(|| panic!("missing /hooks/{event}/0"));
+ assert_eq!(
+ entry.get("type").and_then(|t| t.as_str()),
+ Some("command"),
+ "{event}"
+ );
+ assert!(entry.contains_key("command"), "{event}: {entry:?}");
+ assert!(!entry.contains_key("hooks"), "{event}: {entry:?}");
+ assert!(!entry.contains_key("matcher"), "{event}: {entry:?}");
+ }
+ }
+
#[test]
fn cursor_payload_uses_flat_shape() {
// Flat shape: no inner `hooks: [...]` array; each event
@@ -3267,7 +3339,9 @@ if (inheritOnly) {
HookShape::Nested | HookShape::NestedWithoutMatcher => {
v.pointer("/hooks/SessionStart/0/hooks/0").unwrap().clone()
}
- HookShape::Flat => v.pointer("/hooks/SessionStart/0").unwrap().clone(),
+ HookShape::Flat | HookShape::FlatWithoutMatcher => {
+ v.pointer("/hooks/SessionStart/0").unwrap().clone()
+ }
}
}
@@ -3313,6 +3387,7 @@ if (inheritOnly) {
("antigravity-cli", HookShape::Flat),
("grok", HookShape::Nested),
("devin", HookShape::Nested),
+ ("copilot-cli", HookShape::FlatWithoutMatcher),
] {
let handler = handler_for(HookCommandPlatform::WindowsNative, agent, shape);
assert!(
diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rs
index 327cb164..61e5ca30 100644
--- a/crates/ai-memory-cli/src/commands/setup_agent.rs
+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs
@@ -40,9 +40,9 @@ use crate::cli::{AgentChoice, SetupAgentArgs};
use crate::commands::install_mcp;
use crate::commands::render_shared::{
ANTIGRAVITY_LIFECYCLE_EVENTS, ANTIGRAVITY_TOOL_EVENTS, CODEX_PROFILE, COMMAND_CODE_PROFILE,
- CURSOR_PROFILE, GEMINI_PROFILE, KIMI_CODE_EVENTS, KIRO_CLI_V2_EVENTS, KIRO_CLI_V3_EVENTS,
- build_claude_code_payload, build_devin_payload, build_grok_payload, build_pool_settings_yaml,
- hook_script_for_current_platform,
+ COPILOT_CLI_PROFILE, CURSOR_PROFILE, GEMINI_PROFILE, KIMI_CODE_EVENTS, KIRO_CLI_V2_EVENTS,
+ KIRO_CLI_V3_EVENTS, build_claude_code_payload, build_devin_payload, build_grok_payload,
+ build_pool_settings_yaml, hook_script_for_current_platform,
};
use crate::config::{Config, DEFAULT_SERVER_URL};
@@ -176,6 +176,9 @@ pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {
emit_other(&emit_root, agent_sub, &args, &[&KIRO_CLI_V3_EVENTS]);
}
AgentChoice::Pool => emit_pool(&emit_root, &args),
+ AgentChoice::CopilotCli => {
+ emit_other(&emit_root, agent_sub, &args, &[COPILOT_CLI_PROFILE.events]);
+ }
AgentChoice::OpenCode
| AgentChoice::OpenCode2
| AgentChoice::Pi
diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rs
index 9957418e..7f41de3c 100644
--- a/crates/ai-memory-cli/src/commands/uninstall.rs
+++ b/crates/ai-memory-cli/src/commands/uninstall.rs
@@ -209,6 +209,12 @@ fn build_plan(args: &UninstallArgs, data_dir: &Path) -> anyhow::Result<Vec<Plann
hook_files.push((project_local, HookConfigShape::NestedHooksKey));
}
hook_files.extend([
+ // Copilot CLI's standalone file keeps flat entries under the usual
+ // `hooks` key next to its `version: 1`, like Cursor's.
+ (
+ install_hooks::copilot_cli_hooks_path()?,
+ HookConfigShape::NestedHooksKey,
+ ),
(
install_hooks::codex_hooks_path()?,
HookConfigShape::NestedHooksKey,
diff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rs
index 43719951..791f5a12 100644
--- a/crates/ai-memory-core/src/ids.rs
+++ b/crates/ai-memory-core/src/ids.rs
@@ -280,6 +280,9 @@ pub enum AgentKind {
Pool,
/// ZCode (z.ai) coding agent.
Zcode,
+ /// GitHub Copilot CLI (`copilot`), configured with PascalCase hook event
+ /// names for a Claude Code/VS-Code-compatible payload shape (#1040).
+ CopilotCli,
/// Anything else (manual capture, future agents).
Other,
}
@@ -290,7 +293,7 @@ impl AgentKind {
/// CHECK constraint accepts every kind (the Zero integration shipped
/// with the enum variant but without the V26 migration and only a
/// live test caught it). Extend together with the enum.
- pub const ALL: [Self; 21] = [
+ pub const ALL: [Self; 22] = [
Self::ClaudeCode,
Self::Codex,
Self::OpenCode,
@@ -311,6 +314,7 @@ impl AgentKind {
Self::Hermes,
Self::Pool,
Self::Zcode,
+ Self::CopilotCli,
Self::Other,
];
@@ -338,6 +342,7 @@ impl AgentKind {
Self::Hermes => "hermes",
Self::Pool => "pool",
Self::Zcode => "zcode",
+ Self::CopilotCli => "copilot-cli",
Self::Other => "other",
}
}
@@ -368,6 +373,7 @@ impl AgentKind {
"hermes" | "hermes-agent" => Self::Hermes,
"pool" | "poolside" => Self::Pool,
"zcode" | "zai" => Self::Zcode,
+ "copilot-cli" | "copilot_cli" => Self::CopilotCli,
_ => Self::Other,
}
}
@@ -407,6 +413,15 @@ impl AgentKind {
/// `<system-reminder>` text block of the first user message sent to the
/// model (verified live against the embedded engine v0.16.5, capture logs
/// 2026-08-28), so its native hook fetches the handoff like Claude Code's.
+ ///
+ /// GitHub Copilot CLI documents `SessionStart` context injection, but
+ /// through a top-level `additionalContext` key — not Claude Code's
+ /// `hookSpecificOutput` envelope, which is what the native hook emits —
+ /// even in its PascalCase/VS-Code-compatible payload mode, and no live
+ /// capture proves the model sees it. Fails safe like Pool/Hermes until a
+ /// Copilot-specific envelope is wired and verified: the handoff stays
+ /// available on demand via `memory_handoff_accept` rather than risking a
+ /// destructive fetch-and-discard.
#[must_use]
pub fn session_start_injects_handoff(self) -> bool {
!matches!(
@@ -417,6 +432,7 @@ impl AgentKind {
| Self::KimiCode
| Self::Hermes
| Self::Pool
+ | Self::CopilotCli
| Self::Other
)
}
@@ -619,6 +635,33 @@ mod tests {
assert!(!AgentKind::Pool.user_prompt_injects_handoff());
}
+ #[test]
+ fn agent_kind_copilot_cli_round_trips_without_claiming_handoff_delivery() {
+ assert_eq!(AgentKind::CopilotCli.as_str(), "copilot-cli");
+ assert_eq!(AgentKind::from_wire("copilot-cli"), AgentKind::CopilotCli);
+ assert_eq!(AgentKind::from_wire("copilot_cli"), AgentKind::CopilotCli);
+ assert_eq!(
+ serde_json::to_string(&AgentKind::CopilotCli).unwrap(),
+ "\"copilot-cli\""
+ );
+ assert_eq!(
+ serde_json::from_str::<AgentKind>("\"copilot-cli\"").unwrap(),
+ AgentKind::CopilotCli
+ );
+ // The bare "copilot" word is deliberately NOT an alias here: it is
+ // already claimed by the unrelated `McpClient::VsCodeCopilot` client
+ // (#1040), and aliasing both to different things would be confusing.
+ assert_eq!(AgentKind::from_wire("copilot"), AgentKind::Other);
+ // Unknown tags still degrade to Other.
+ assert_eq!(AgentKind::from_wire("copilot-cli-2"), AgentKind::Other);
+ // Copilot CLI reads a top-level `additionalContext`, not the
+ // `hookSpecificOutput` envelope the native hook prints, so the
+ // destructive handoff fetch must not happen from its native hook yet
+ // (see the doc comment on `session_start_injects_handoff`).
+ assert!(!AgentKind::CopilotCli.session_start_injects_handoff());
+ assert!(!AgentKind::CopilotCli.user_prompt_injects_handoff());
+ }
+
#[test]
fn agent_kind_zcode_round_trips_and_injects_session_start_handoff() {
assert_eq!(AgentKind::Zcode.as_str(), "zcode");
diff --git a/crates/ai-memory-hooks/src/capture_policy.rs b/crates/ai-memory-hooks/src/capture_policy.rs
index 7b061b8f..26762794 100644
--- a/crates/ai-memory-hooks/src/capture_policy.rs
+++ b/crates/ai-memory-hooks/src/capture_policy.rs
@@ -171,11 +171,17 @@ pub(crate) fn tool_observation_metadata(
// Grok Build CLI posts Claude Code's snake_case aliases
// (`tool_name` / `tool_input` / `tool_use_id`) on its tool hooks
// alongside camelCase, so it shares this mapping (#931).
+ // GitHub Copilot CLI, configured with PascalCase hook event names per
+ // its own docs, emits the same Claude-compatible `tool_name`/
+ // `tool_input` shape (#1040) — unverified against a real tool-call id
+ // field, but `tool_use_id` extraction degrades to `None` gracefully
+ // if absent.
AgentKind::ClaudeCode
| AgentKind::CommandCode
| AgentKind::Codex
| AgentKind::Grok
- | AgentKind::Zcode => (
+ | AgentKind::Zcode
+ | AgentKind::CopilotCli => (
object.get("tool_name")?.as_str()?,
object.get("tool_use_id").and_then(Value::as_str),
),
@@ -225,6 +231,7 @@ pub(crate) fn tool_observation_metadata(
| AgentKind::KiroCli
| AgentKind::Pool
| AgentKind::Zcode
+ | AgentKind::CopilotCli
) {
"tool_input"
} else {
@@ -277,6 +284,29 @@ pub(crate) fn tool_observation_outcome(agent: AgentKind, raw: &Value) -> ToolOut
{
ToolOutcome::Error
}
+ // GitHub Copilot CLI's VS-Code-compatible `PostToolUse` carries
+ // `tool_result.result_type` (#1040). Only `success` and an explicit
+ // failure prove an outcome; any other value (a denied or rejected
+ // call, a future type) stays unknown. `PostToolUseFailure` is aliased
+ // to `PostToolUse`, so an `error` string with no `tool_result` is the
+ // failure form, as for ZCode.
+ AgentKind::CopilotCli => match raw
+ .get("tool_result")
+ .and_then(|result| result.get("result_type"))
+ .and_then(Value::as_str)
+ {
+ Some("success") => ToolOutcome::Success,
+ Some("failure" | "error") => ToolOutcome::Error,
+ Some(_) => ToolOutcome::Unknown,
+ None if raw
+ .get("error")
+ .and_then(Value::as_str)
+ .is_some_and(|error| !error.is_empty()) =>
+ {
+ ToolOutcome::Error
+ }
+ None => ToolOutcome::Unknown,
+ },
// Codex PostToolUse also fires for failed commands. Its native exec
// response is output text, with no separate success/exit-code field;
// neither the event nor arbitrary response JSON proves an outcome.
@@ -720,7 +750,10 @@ fn extract(agent: AgentKind, raw: &Value) -> Extracted<'_> {
| AgentKind::Pool
// ZCode mirrors Claude Code's snake_case `tool_name`/`tool_input`
// aliases on every tool event (live-captured, #512).
- | AgentKind::Zcode => object
+ | AgentKind::Zcode
+ // GitHub Copilot CLI, PascalCase-configured for the Claude-compatible
+ // payload shape (#1040).
+ | AgentKind::CopilotCli => object
.get("tool_name")
.and_then(Value::as_str)
.map(|name| (name, object.get("tool_input"))),
@@ -1829,6 +1862,41 @@ mod tests {
);
}
+ #[test]
+ fn copilot_cli_outcome_reads_only_proven_result_types() {
+ let outcome = |raw: Value| tool_observation_outcome(AgentKind::CopilotCli, &raw);
+ let with_type = |result_type: &str| {
+ json!({"tool_name": "bash", "tool_result": {
+ "result_type": result_type, "text_result_for_llm": "x"
+ }})
+ };
+ assert_eq!(outcome(with_type("success")), ToolOutcome::Success);
+ assert_eq!(outcome(with_type("failure")), ToolOutcome::Error);
+ assert_eq!(outcome(with_type("error")), ToolOutcome::Error);
+ // A denied or rejected call is not a tool failure, and a future type
+ // proves nothing.
+ assert_eq!(outcome(with_type("denied")), ToolOutcome::Unknown);
+ // PostToolUseFailure (aliased to PostToolUse) carries `error` and no
+ // `tool_result`.
+ assert_eq!(
+ outcome(json!({"tool_name": "bash", "error": "permission denied"})),
+ ToolOutcome::Error
+ );
+ assert_eq!(outcome(json!({"tool_name": "bash"})), ToolOutcome::Unknown);
+ }
+
+ #[test]
+ fn copilot_cli_tool_metadata_uses_the_claude_compatible_keys() {
+ let pre = json!({
+ "tool_name": "edit",
+ "tool_input": {"path": "src/lib.rs"},
+ });
+ assert!(tool_observation_metadata(AgentKind::CopilotCli, &pre, true).is_some());
+ // PreToolUse without a proven input shape stays metadata-less.
+ let no_input = json!({"tool_name": "edit"});
+ assert!(tool_observation_metadata(AgentKind::CopilotCli, &no_input, true).is_none());
+ }
+
#[test]
fn command_code_official_tool_shape_is_closed_and_honors_exclusions() {
let policy = CapturePolicy::resolve(
diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rs
index 02d6a9c6..44688b22 100644
--- a/crates/ai-memory-hooks/src/payload.rs
+++ b/crates/ai-memory-hooks/src/payload.rs
@@ -725,6 +725,7 @@ const fn closed_tool_agent(agent: AgentKind) -> bool {
| AgentKind::Hermes
| AgentKind::Pool
| AgentKind::Zcode
+ | AgentKind::CopilotCli
)
}
@@ -799,6 +800,14 @@ fn safe_tool_body(
// Codex's native schema has one top-level JSON response.
// Do not promote unrelated aliases or nested payloads to output.
raw.get("tool_response").and_then(value_to_text)
+ } else if agent == AgentKind::CopilotCli {
+ // Copilot CLI's VS-Code-compatible `PostToolUse` nests the
+ // model-facing text at `tool_result.text_result_for_llm`
+ // (#1040); read only that documented field so `result_type`
+ // never leaks in through an object-stringify fallback.
+ raw.pointer("/tool_result/text_result_for_llm")
+ .and_then(value_to_text)
+ .or_else(|| extract_content(raw, &["error"]))
} else {
extract_content(raw, &["tool_response", "tool_output", "output", "result"])
.or_else(|| extract_content(raw, &["error"]))
@@ -2390,6 +2399,40 @@ mod tests {
);
}
+ /// Copilot CLI's VS-Code-compatible `PostToolUse` nests the output at
+ /// `tool_result.text_result_for_llm` (#1040). Without Copilot in
+ /// `closed_tool_agent` the observation would be stored with an empty body,
+ /// the #931 failure mode Grok had; without the dedicated path the
+ /// `result_type` envelope would leak into the excerpt.
+ #[test]
+ fn copilot_cli_post_tool_excerpt_reads_text_result_for_llm() {
+ let q = HookQuery {
+ event: "post-tool-use".into(),
+ agent: Some("copilot-cli".into()),
+ ..Default::default()
+ };
+ let env = HookEnvelope::from_query_and_body(
+ q,
+ serde_json::json!({
+ "hook_event_name": "PostToolUse",
+ "session_id": "copilot-session",
+ "cwd": "/repo",
+ "tool_name": "bash",
+ "tool_input": {"command": "ls"},
+ "tool_result": {
+ "result_type": "success",
+ "text_result_for_llm": "MARKER_COPILOT_1040",
+ },
+ }),
+ );
+ let body = env
+ .body_excerpt
+ .expect("copilot-cli post-tool body should not be empty");
+ assert!(body.contains("MARKER_COPILOT_1040"), "{body:?}");
+ assert!(body.contains("outcome: success"), "{body:?}");
+ assert!(!body.contains("result_type"), "{body:?}");
+ }
+
/// End-to-end: a native-hook user prompt (`event=user-prompt-submit`,
/// string `prompt`) maps to `UserPrompt` and keeps its body text.
#[test]
diff --git a/crates/ai-memory-store/migrations/V72__sessions_copilot_cli_agent_kind.sql b/crates/ai-memory-store/migrations/V72__sessions_copilot_cli_agent_kind.sql
new file mode 100644
index 00000000..cc91c793
--- /dev/null
+++ b/crates/ai-memory-store/migrations/V72__sessions_copilot_cli_agent_kind.sql
@@ -0,0 +1,73 @@
+-- Expand sessions.agent_kind CHECK for GitHub Copilot CLI (#1040).
+--
+-- Keep the complete V51 schema, indexes, and scope-pairing triggers while
+-- adding the `copilot-cli` wire value.
+
+PRAGMA foreign_keys = OFF;
+
+DROP TRIGGER IF EXISTS auto_improve_scheduler_claims_session_pairing_ai;
+DROP TRIGGER IF EXISTS session_consolidation_jobs_session_pairing_ai;
+
+CREATE TABLE sessions_new (
+ id BLOB PRIMARY KEY NOT NULL,
+ workspace_id BLOB NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
+ project_id BLOB NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
+ agent_kind TEXT NOT NULL CHECK (agent_kind IN ('claude-code','codex','open-code','cursor','gemini-cli','claude-desktop','openclaw','antigravity-cli','omp','pi','crush','grok','zero','devin','kimi-code','kiro-cli','command-code','hermes','pool','zcode','copilot-cli','other')),
+ cwd TEXT,
+ started_at INTEGER NOT NULL,
+ ended_at INTEGER,
+ summary_page_id BLOB REFERENCES pages(id) ON DELETE SET NULL,
+ ended_observation_count INTEGER NOT NULL DEFAULT 0 CHECK (ended_observation_count >= 0),
+ actor_user TEXT
+);
+
+INSERT INTO sessions_new (
+ id, workspace_id, project_id, agent_kind, cwd, started_at, ended_at,
+ summary_page_id, ended_observation_count, actor_user
+)
+SELECT
+ id, workspace_id, project_id, agent_kind, cwd, started_at, ended_at,
+ summary_page_id, ended_observation_count, actor_user
+FROM sessions;
+
+DROP TABLE sessions;
+
+ALTER TABLE sessions_new RENAME TO sessions;
+
+CREATE INDEX idx_sessions_recent ON sessions(workspace_id, project_id, started_at DESC);
+CREATE INDEX idx_sessions_project ON sessions(project_id);
+CREATE INDEX idx_sessions_started_at ON sessions(started_at DESC);
+CREATE INDEX idx_sessions_scope_ended
+ ON sessions(workspace_id, project_id, ended_at ASC)
+ WHERE ended_at IS NOT NULL;
+CREATE INDEX idx_sessions_open_owner
+ ON sessions(workspace_id, project_id, agent_kind, actor_user)
+ WHERE ended_at IS NULL;
+
+CREATE TRIGGER sessions_ws_proj_pairing_ai
+BEFORE INSERT ON sessions
+FOR EACH ROW
+WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM projects WHERE id = NEW.project_id)
+BEGIN
+ SELECT RAISE(ABORT, 'sessions.workspace_id does not match the project''s workspace');
+END;
+
+CREATE TRIGGER auto_improve_scheduler_claims_session_pairing_ai
+BEFORE INSERT ON auto_improve_scheduler_claims
+FOR EACH ROW
+WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM sessions WHERE id = NEW.session_id)
+ OR NEW.project_id IS NOT (SELECT project_id FROM sessions WHERE id = NEW.session_id)
+BEGIN
+ SELECT RAISE(ABORT, 'auto_improve_scheduler_claims scope does not match the session scope');
+END;
+
+CREATE TRIGGER session_consolidation_jobs_session_pairing_ai
+BEFORE INSERT ON session_consolidation_jobs
+FOR EACH ROW
+WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM sessions WHERE id = NEW.session_id)
+ OR NEW.project_id IS NOT (SELECT project_id FROM sessions WHERE id = NEW.session_id)
+BEGIN
+ SELECT RAISE(ABORT, 'session_consolidation_jobs scope does not match the session scope');
+END;
+
+PRAGMA foreign_keys = ON;
diff --git a/crates/ai-memory-store/src/api_credentials.rs b/crates/ai-memory-store/src/api_credentials.rs
index ac3e16af..dfc953c3 100644
--- a/crates/ai-memory-store/src/api_credentials.rs
+++ b/crates/ai-memory-store/src/api_credentials.rs
@@ -411,7 +411,7 @@ mod tests {
|row| row.get(0),
)
.unwrap();
- assert_eq!(version, 71, "update the pin when adding a migration");
+ assert_eq!(version, 72, "update the pin when adding a migration");
let cols: i64 = conn
.query_row(
"SELECT COUNT(*) FROM pragma_table_info('users') WHERE name = 'token_hash'",
diff --git a/crates/ai-memory-store/src/migrations.rs b/crates/ai-memory-store/src/migrations.rs
index d6c3b2cb..1726b3ec 100644
--- a/crates/ai-memory-store/src/migrations.rs
+++ b/crates/ai-memory-store/src/migrations.rs
@@ -897,6 +897,74 @@ mod tests {
}
}
+ #[test]
+ fn v71_to_v72_preserves_session_state_and_accepts_copilot_cli() {
+ let mut conn = Connection::open_in_memory().unwrap();
+ run_to(&mut conn, 71).unwrap();
+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();
+ let workspace_id = crate::ops::get_or_create_workspace(&mut conn, "default").unwrap();
+ let project_id =
+ crate::ops::get_or_create_project(&mut conn, &workspace_id, "project", None).unwrap();
+ let existing = SessionId::new();
+ conn.execute(
+ "INSERT INTO sessions \
+ (id, workspace_id, project_id, agent_kind, cwd, started_at, ended_at, \
+ ended_observation_count, actor_user) \
+ VALUES (?1, ?2, ?3, 'zcode', '/repo', 1, 2, 7, 'user:alice')",
+ params![
+ existing.as_bytes(),
+ workspace_id.as_bytes(),
+ project_id.as_bytes(),
+ ],
+ )
+ .unwrap();
+
+ conn.pragma_update(None, "foreign_keys", "OFF").unwrap();
+ run(&mut conn).unwrap();
+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();
+
+ let preserved: (String, String, i64, Option<String>) = conn
+ .query_row(
+ "SELECT agent_kind, cwd, ended_observation_count, actor_user \
+ FROM sessions WHERE id = ?1",
+ params![existing.as_bytes()],
+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
+ )
+ .unwrap();
+ assert_eq!(
+ preserved,
+ ("zcode".into(), "/repo".into(), 7, Some("user:alice".into()))
+ );
+
+ crate::ops::begin_session(
+ &mut conn,
+ &NewSession {
+ occurred_at: None,
+ id: SessionId::new(),
+ workspace_id,
+ project_id,
+ agent_kind: AgentKind::CopilotCli,
+ cwd: Some("/repo".into()),
+ actor_user: Some("user:alice".into()),
+ },
+ )
+ .unwrap();
+
+ for name in [
+ "idx_sessions_open_owner",
+ "sessions_ws_proj_pairing_ai",
+ "auto_improve_scheduler_claims_session_pairing_ai",
+ "session_consolidation_jobs_session_pairing_ai",
+ ] {
+ let kind = if name.starts_with("idx_") {
+ "index"
+ } else {
+ "trigger"
+ };
+ assert_eq!(schema_object_count(&conn, kind, name), 1, "missing {name}");
+ }
+ }
+
/// V62 was reshaped in place (#776) from an in-migration backfill to
/// DDL-only + a boot-path backfill, changing its checksum. A store that
/// applied the ORIGINAL V62 recorded the old checksum; `run` must still
diff --git a/docs/install.md b/docs/install.md
index 782ce273..98934017 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -1301,6 +1301,40 @@ ai-memory finalize-session --agent zcode --session-id <uuid>
No first-party `install-mcp` client and no managed workstream
(`ai-memory run zcode`) are claimed yet.
+### GitHub Copilot CLI
+
+Copilot CLI loads user-level hook files from `~/.copilot/hooks/` (or
+`$COPILOT_HOME/hooks/`). `install-hooks --agent copilot-cli` writes
+`ai-memory.json` there — Copilot's standalone `{"version": 1, "hooks": {…}}`
+format — merging around any third-party entries already in the file:
+
+```bash
+ai-memory install-hooks --agent copilot-cli --apply \
+ --server-url "http://homelab:49374" \
+ --auth-token "$TOKEN"
+```
+
+The events are configured with PascalCase names (`SessionStart`,
+`PreToolUse`, …), which makes Copilot send the VS Code/Claude-compatible
+snake_case payload (`session_id`, `cwd`, `tool_name`, `tool_input`,
+`tool_result`), so ai-memory's existing extraction applies and native commands
+enforce `[capture] ignore_paths`. Ten events are wired: Claude Code's nine plus
+`PostToolUseFailure`, which Copilot fires instead of `PostToolUse` when a tool
+errors. Entries sit directly in each event array with no `matcher`: Copilot
+rejects `matcher` on `SessionStart`, `Stop`, `SessionEnd`, and the subagent
+events, and omitting it elsewhere means "every invocation". Tool output is
+read from `tool_result.text_result_for_llm`.
+
+Copilot reads a top-level `additionalContext` from `SessionStart` stdout, not
+Claude Code's `hookSpecificOutput` envelope, so the prior session's handoff is
+not injected yet; recover it via MCP `memory_handoff_list` then
+`memory_handoff_accept` with that `handoff_id`. There is no `--scope project`:
+Copilot's repository hook files (`.github/hooks/*.json`) are shared with the
+team and loaded by the Copilot cloud agent, so they cannot carry per-machine
+script paths. `install-mcp --client copilot-cli` and `ai-memory run copilot`
+are not shipped yet; `install-mcp --client copilot` remains the VS Code
+Copilot client.
+
### Hermes Agent (Nous Research)
Hermes declares lifecycle hooks in the `hooks:` block of
diff --git a/docs/support-matrix.md b/docs/support-matrix.md
index a9379906..c25865df 100644
--- a/docs/support-matrix.md
+++ b/docs/support-matrix.md
@@ -34,6 +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 | Hooks-only | `install-hooks --agent copilot-cli` writes lifecycle hooks to `$COPILOT_HOME/hooks/ai-memory.json` (default `~/.copilot/hooks/ai-memory.json`). 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. Copilot reads a top-level `additionalContext` on `SessionStart` rather than Claude Code's envelope, so capture works but handoff injection does not yet — recover handoffs via MCP `memory_handoff_list` then `memory_handoff_accept` with that `handoff_id`. No `--scope project`: Copilot's repository hook files (`.github/hooks/*.json`) are shared with the team and the cloud agent, so they cannot carry per-machine script paths. `install-mcp --client copilot-cli` and `ai-memory run copilot` are follow-ups (#1040). The bare `--client copilot` alias 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/hooks/copilot-cli/post-tool-use.ps1 b/hooks/copilot-cli/post-tool-use.ps1
new file mode 100644
index 00000000..00ed6e67
--- /dev/null
+++ b/hooks/copilot-cli/post-tool-use.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "post-tool-use" -Agent "copilot-cli"
+exit 0
diff --git a/hooks/copilot-cli/post-tool-use.sh b/hooks/copilot-cli/post-tool-use.sh
new file mode 100755
index 00000000..2c130f8e
--- /dev/null
+++ b/hooks/copilot-cli/post-tool-use.sh
@@ -0,0 +1,23 @@
+#!/bin/sh
+# GitHub Copilot CLI PostToolUse / PostToolUseFailure hook.
+# Forwards the event JSON to the ai-memory server, fire-and-forget.
+# Walks up from the payload's cwd for a .ai-memory.toml marker file;
+# if found, appends marker query params to the URL so the server
+# applies the declared workspace/project/strategy instead of
+# bucketing by basename(cwd) under the default workspace.
+# At runtime (after `install-hooks --apply`) `_lib.sh` is staged
+# alongside this script. From the source tree it lives one dir up.
+_lib_dir="$(dirname "$0")"
+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."
+. "$_lib_dir/_lib.sh"
+
+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")
+
+printf '%s' "$PAYLOAD" \
+ | ai_memory_post_hook "$SERVER/hook?event=post-tool-use&agent=copilot-cli${QS}" >/dev/null 2>&1 || true
+# Acknowledge with an empty JSON object: this hook injects no context.
+printf '{}\n'
+exit 0
diff --git a/hooks/copilot-cli/pre-compact.ps1 b/hooks/copilot-cli/pre-compact.ps1
new file mode 100644
index 00000000..85f58946
--- /dev/null
+++ b/hooks/copilot-cli/pre-compact.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "pre-compact" -Agent "copilot-cli"
+exit 0
diff --git a/hooks/copilot-cli/pre-compact.sh b/hooks/copilot-cli/pre-compact.sh
new file mode 100755
index 00000000..72fda571
--- /dev/null
+++ b/hooks/copilot-cli/pre-compact.sh
@@ -0,0 +1,23 @@
+#!/bin/sh
+# GitHub Copilot CLI PreCompact hook.
+# Forwards the event JSON to the ai-memory server, fire-and-forget.
+# Walks up from the payload's cwd for a .ai-memory.toml marker file;
+# if found, appends marker query params to the URL so the server
+# applies the declared workspace/project/strategy instead of
+# bucketing by basename(cwd) under the default workspace.
+# At runtime (after `install-hooks --apply`) `_lib.sh` is staged
+# alongside this script. From the source tree it lives one dir up.
+_lib_dir="$(dirname "$0")"
+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."
+. "$_lib_dir/_lib.sh"
+
+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")
+
+printf '%s' "$PAYLOAD" \
+ | ai_memory_post_hook "$SERVER/hook?event=pre-compact&agent=copilot-cli${QS}" >/dev/null 2>&1 || true
+# Acknowledge with an empty JSON object: this hook injects no context.
+printf '{}\n'
+exit 0
diff --git a/hooks/copilot-cli/pre-tool-use.ps1 b/hooks/copilot-cli/pre-tool-use.ps1
new file mode 100644
index 00000000..17c22dea
--- /dev/null
+++ b/hooks/copilot-cli/pre-tool-use.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "pre-tool-use" -Agent "copilot-cli"
+exit 0
diff --git a/hooks/copilot-cli/pre-tool-use.sh b/hooks/copilot-cli/pre-tool-use.sh
new file mode 100755
index 00000000..7661a57b
--- /dev/null
+++ b/hooks/copilot-cli/pre-tool-use.sh
@@ -0,0 +1,23 @@
+#!/bin/sh
+# GitHub Copilot CLI PreToolUse hook.
+# Forwards the event JSON to the ai-memory server, fire-and-forget.
+# Walks up from the payload's cwd for a .ai-memory.toml marker file;
+# if found, appends marker query params to the URL so the server
+# applies the declared workspace/project/strategy instead of
+# bucketing by basename(cwd) under the default workspace.
+# At runtime (after `install-hooks --apply`) `_lib.sh` is staged
+# alongside this script. From the source tree it lives one dir up.
+_lib_dir="$(dirname "$0")"
+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."
+. "$_lib_dir/_lib.sh"
+
+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")
+
+printf '%s' "$PAYLOAD" \
+ | ai_memory_post_hook "$SERVER/hook?event=pre-tool-use&agent=copilot-cli${QS}" >/dev/null 2>&1 || true
+# Acknowledge with an empty JSON object: this hook injects no context.
+printf '{}\n'
+exit 0
diff --git a/hooks/copilot-cli/session-end.ps1 b/hooks/copilot-cli/session-end.ps1
new file mode 100644
index 00000000..741c1dcd
--- /dev/null
+++ b/hooks/copilot-cli/session-end.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "session-end" -Agent "copilot-cli"
+exit 0
diff --git a/hooks/copilot-cli/session-end.sh b/hooks/copilot-cli/session-end.sh
new file mode 100755
index 00000000..118b5552
--- /dev/null
+++ b/hooks/copilot-cli/session-end.sh
@@ -0,0 +1,23 @@
+#!/bin/sh
+# GitHub Copilot CLI SessionEnd hook.
+# Forwards the event JSON to the ai-memory server, fire-and-forget.
+# Walks up from the payload's cwd for a .ai-memory.toml marker file;
+# if found, appends marker query params to the URL so the server
+# applies the declared workspace/project/strategy instead of
+# bucketing by basename(cwd) under the default workspace.
+# At runtime (after `install-hooks --apply`) `_lib.sh` is staged
+# alongside this script. From the source tree it lives one dir up.
+_lib_dir="$(dirname "$0")"
+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."
+. "$_lib_dir/_lib.sh"
+
+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")
+
+printf '%s' "$PAYLOAD" \
+ | ai_memory_post_hook "$SERVER/hook?event=session-end&agent=copilot-cli${QS}" >/dev/null 2>&1 || true
+# Acknowledge with an empty JSON object: this hook injects no context.
+printf '{}\n'
+exit 0
diff --git a/hooks/copilot-cli/session-start.ps1 b/hooks/copilot-cli/session-start.ps1
new file mode 100644
index 00000000..ada159f5
--- /dev/null
+++ b/hooks/copilot-cli/session-start.ps1
@@ -0,0 +1,8 @@
+# GitHub Copilot CLI session-start hook.
+# Capture only — Copilot CLI's SessionStart stdout injection is not
+# demonstrated live, so no -FetchHandoff: accepting a handoff is destructive
+# and the context could be silently lost. Recover handoffs via MCP
+# `memory_handoff_accept`.
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "session-start" -Agent "copilot-cli"
+exit 0
diff --git a/hooks/copilot-cli/session-start.sh b/hooks/copilot-cli/session-start.sh
new file mode 100755
index 00000000..515a6daa
--- /dev/null
+++ b/hooks/copilot-cli/session-start.sh
@@ -0,0 +1,23 @@
+#!/bin/sh
+# GitHub Copilot CLI SessionStart hook.
+# Copilot CLI reads a top-level `additionalContext` from SessionStart stdout
+# (not Claude Code's `hookSpecificOutput` envelope), and that injection is not
+# demonstrated live, so this hook captures the event only. Do NOT fetch
+# /handoff here: accepting a handoff is destructive and an undelivered handoff
+# would be silently lost. Recover a prior session's handoff via the MCP
+# `memory_handoff_accept` tool instead.
+# At runtime (after `install-hooks --apply`) `_lib.sh` is staged
+# alongside this script. From the source tree it lives one dir up.
+_lib_dir="$(dirname "$0")"
+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."
+. "$_lib_dir/_lib.sh"
+
+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")
+
+printf '%s' "$PAYLOAD" \
+ | ai_memory_post_hook "$SERVER/hook?event=session-start&agent=copilot-cli${QS}" >/dev/null 2>&1 || true
+printf '{}\n'
+exit 0
diff --git a/hooks/copilot-cli/stop.ps1 b/hooks/copilot-cli/stop.ps1
new file mode 100644
index 00000000..0822752f
--- /dev/null
+++ b/hooks/copilot-cli/stop.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "stop" -Agent "copilot-cli"
+exit 0
diff --git a/hooks/copilot-cli/stop.sh b/hooks/copilot-cli/stop.sh
new file mode 100755
index 00000000..2b9a27a5
--- /dev/null
+++ b/hooks/copilot-cli/stop.sh
@@ -0,0 +1,23 @@
+#!/bin/sh
+# GitHub Copilot CLI Stop hook.
+# Forwards the event JSON to the ai-memory server, fire-and-forget.
+# Walks up from the payload's cwd for a .ai-memory.toml marker file;
+# if found, appends marker query params to the URL so the server
+# applies the declared workspace/project/strategy instead of
+# bucketing by basename(cwd) under the default workspace.
+# At runtime (after `install-hooks --apply`) `_lib.sh` is staged
+# alongside this script. From the source tree it lives one dir up.
+_lib_dir="$(dirname "$0")"
+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."
+. "$_lib_dir/_lib.sh"
+
+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")
+
+printf '%s' "$PAYLOAD" \
+ | ai_memory_post_hook "$SERVER/hook?event=stop&agent=copilot-cli${QS}" >/dev/null 2>&1 || true
+# Acknowledge with an empty JSON object: this hook injects no context.
+printf '{}\n'
+exit 0
diff --git a/hooks/copilot-cli/subagent-start.ps1 b/hooks/copilot-cli/subagent-start.ps1
new file mode 100644
index 00000000..5bbaaaab
--- /dev/null
+++ b/hooks/copilot-cli/subagent-start.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "subagent-start" -Agent "copilot-cli"
+exit 0
diff --git a/hooks/copilot-cli/subagent-start.sh b/hooks/copilot-cli/subagent-start.sh
new file mode 100755
index 00000000..5c26d4fd
--- /dev/null
+++ b/hooks/copilot-cli/subagent-start.sh
@@ -0,0 +1,23 @@
+#!/bin/sh
+# GitHub Copilot CLI SubagentStart hook.
+# Forwards the event JSON to the ai-memory server, fire-and-forget.
+# Walks up from the payload's cwd for a .ai-memory.toml marker file;
+# if found, appends marker query params to the URL so the server
+# applies the declared workspace/project/strategy instead of
+# bucketing by basename(cwd) under the default workspace.
+# At runtime (after `install-hooks --apply`) `_lib.sh` is staged
+# alongside this script. From the source tree it lives one dir up.
+_lib_dir="$(dirname "$0")"
+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."
+. "$_lib_dir/_lib.sh"
+
+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")
+
+printf '%s' "$PAYLOAD" \
+ | ai_memory_post_hook "$SERVER/hook?event=subagent-start&agent=copilot-cli${QS}" >/dev/null 2>&1 || true
+# Acknowledge with an empty JSON object: this hook injects no context.
+printf '{}\n'
+exit 0
diff --git a/hooks/copilot-cli/subagent-stop.ps1 b/hooks/copilot-cli/subagent-stop.ps1
new file mode 100644
index 00000000..30e1f300
--- /dev/null
+++ b/hooks/copilot-cli/subagent-stop.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "subagent-stop" -Agent "copilot-cli"
+exit 0
diff --git a/hooks/copilot-cli/subagent-stop.sh b/hooks/copilot-cli/subagent-stop.sh
new file mode 100755
index 00000000..a4a7c307
--- /dev/null
+++ b/hooks/copilot-cli/subagent-stop.sh
@@ -0,0 +1,23 @@
+#!/bin/sh
+# GitHub Copilot CLI SubagentStop hook.
+# Forwards the event JSON to the ai-memory server, fire-and-forget.
+# Walks up from the payload's cwd for a .ai-memory.toml marker file;
+# if found, appends marker query params to the URL so the server
+# applies the declared workspace/project/strategy instead of
+# bucketing by basename(cwd) under the default workspace.
+# At runtime (after `install-hooks --apply`) `_lib.sh` is staged
+# alongside this script. From the source tree it lives one dir up.
+_lib_dir="$(dirname "$0")"
+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."
+. "$_lib_dir/_lib.sh"
+
+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")
+
+printf '%s' "$PAYLOAD" \
+ | ai_memory_post_hook "$SERVER/hook?event=subagent-stop&agent=copilot-cli${QS}" >/dev/null 2>&1 || true
+# Acknowledge with an empty JSON object: this hook injects no context.
+printf '{}\n'
+exit 0
diff --git a/hooks/copilot-cli/user-prompt-submit.ps1 b/hooks/copilot-cli/user-prompt-submit.ps1
new file mode 100644
index 00000000..42d8f992
--- /dev/null
+++ b/hooks/copilot-cli/user-prompt-submit.ps1
@@ -0,0 +1,3 @@
+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"
+Invoke-AiMemoryHook -Event "user-prompt" -Agent "copilot-cli"
+exit 0
diff --git a/hooks/copilot-cli/user-prompt-submit.sh b/hooks/copilot-cli/user-prompt-submit.sh
new file mode 100755
index 00000000..e831c299
--- /dev/null
+++ b/hooks/copilot-cli/user-prompt-submit.sh
@@ -0,0 +1,23 @@
+#!/bin/sh
+# GitHub Copilot CLI UserPromptSubmit hook.
+# Forwards the event JSON to the ai-memory server, fire-and-forget.
+# Walks up from the payload's cwd for a .ai-memory.toml marker file;
+# if found, appends marker query params to the URL so the server
+# applies the declared workspace/project/strategy instead of
+# bucketing by basename(cwd) under the default workspace.
+# At runtime (after `install-hooks --apply`) `_lib.sh` is staged
+# alongside this script. From the source tree it lives one dir up.
+_lib_dir="$(dirname "$0")"
+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."
+. "$_lib_dir/_lib.sh"
+
+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")
+
+printf '%s' "$PAYLOAD" \
+ | ai_memory_post_hook "$SERVER/hook?event=user-prompt&agent=copilot-cli${QS}" >/dev/null 2>&1 || true
+# Acknowledge with an empty JSON object: this hook injects no context.
+printf '{}\n'
+exit 0