Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(hooks): support external lifecycle capture ownership
Éverton Toffanetto32b320825eee
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9c59817a..ae9b7566 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added+- Added per-execution `AI_MEMORY_CAPTURE_OWNER` context for external lifecycle+ producers. Updated native hooks, script bundles and generated integrations+ suppress capture while preserving supported handoff delivery and MCP recall.+ Documented producer provenance and stable retries through the existing hook+ ingestion API, without changing its schema or standalone defaults. (#821)+### Security- Bumped `rmcp` to 2.x (2.2.0), resolving three MCP transport advisories:GHSA-9pj6-vhgr-3mwh (unauthenticated Streamable-HTTP session-table leak /diff --git a/README.md b/README.mdindex 59e769ef..e40fd2d6 100644--- a/README.md+++ b/README.md@@ -412,6 +412,7 @@ diagram, crate breakdown, schema notes, and invariants.| [`docs/design-decisions.md`](docs/design-decisions.md) | The full v1 spec. || [`docs/managed-harness-contributions.md`](docs/managed-harness-contributions.md) | Protocol and acceptance bar for adding managed resume, transcript import, and startup context delivery to another harness. || [`docs/companion-crates.md`](docs/companion-crates.md) | Boundary and plan for optional companion projects, including the standalone importer at [`companions/ai-memory-importer`](companions/ai-memory-importer). |+| [`docs/external-lifecycle.md`](docs/external-lifecycle.md) | External lifecycle producers: per-execution native capture suppression, preserved handoffs, batch ingestion and stable retry identity. || [`docs/auto-improvement-loop.md`](docs/auto-improvement-loop.md) | Auto-improvement design notes: scheduled review, auto-approval default, manual review opt-in, pending proposal storage, and curator work. |## Licensediff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rsindex d241446b..d7105596 100644--- a/crates/ai-memory-cli/src/commands/hook.rs+++ b/crates/ai-memory-cli/src/commands/hook.rs@@ -54,6 +54,7 @@ const BACKGROUND_DRAIN_BUDGET_ENV: &str = "AI_MEMORY_HOOK_BACKGROUND_DRAIN_BUDGEconst INCREMENTAL_THRESHOLD_ENV: &str = "AI_MEMORY_HOOK_INCREMENTAL_THRESHOLD";const MANAGED_RUN_ENV: &str = "AI_MEMORY_RUN_ID";+const CAPTURE_OWNER_ENV: &str = "AI_MEMORY_CAPTURE_OWNER";/// Backlog size at which `post-tool-use` does a mid-session catch-up drain, so a/// light session pays only a `read_dir`. Override via the env var above.const DEFAULT_INCREMENTAL_THRESHOLD: usize = 32;@@ -508,6 +509,21 @@ where{let agent_kind = AgentKind::from_wire(&args.agent);let hook_event = HookEvent::parse(&args.event);+ // This is inherited execution context, like AI_MEMORY_RUN_ID, rather+ // than server configuration. Hooks deliberately bypass Config::load.+ let external_capture = env_lookup(CAPTURE_OWNER_ENV).is_some_and(|v| !v.trim().is_empty());+ let delivers_context = (hook_event == HookEvent::SessionStart+ && agent_kind.session_start_injects_handoff())+ || (hook_event == HookEvent::UserPrompt && agent_kind.user_prompt_injects_handoff());+ if external_capture && !args.check_capture && !delivers_context {+ // Retiring the fallback session ID is lifecycle housekeeping, not+ // capture. Preserve it even when no event is enqueued.+ if agent_kind == AgentKind::Devin && hook_event == HookEvent::SessionEnd {+ clear_session_id(&resolve_data_dir(data_dir.as_deref()), agent_kind);+ }+ write_success_response(stdout, agent_kind, hook_event)?;+ return Ok(());+ }let (mut payload, mut json) = match parse_hook_payload(payload) {Ok(parsed) => parsed,Err(_) => {@@ -582,7 +598,8 @@ wherelet output = serde_json::json!({"capture_mode": capture_mode,"marker_present": marker_present,- "admits_capture": admits_capture,+ "admits_capture": admits_capture && !external_capture,+ "external_capture": external_capture,"version": protocol.map_or(1, |protocol| protocol.version()),"policy_state": protocol.map_or(PolicyState::Inactive, |protocol| protocol.policy_state()),"tool_family": protocol.map_or(ai_memory_hooks::ToolFamily::Unknown, |protocol| protocol.tool_family()),@@ -672,67 +689,72 @@ where// atomically with the observation row and skips replays whose previous// delivery succeeded but whose response was lost — closing the// conservative-retry duplication vector. Older servers ignore the param.- let ingest_key = uuid::Uuid::new_v4().simple().to_string();- let event_url = format!(- "{base}/hook?event={}&agent={}{}{}&ingest_key={ingest_key}",- args.event, args.agent, hook_qs, capture_qs- );- let entry = hook_spool::entry_for(event_url, payload.clone(), effective_token, oidc_present);- if hook_spool::enqueue(&spool, &entry).is_err() {- eprintln!(- "ai-memory hook warning: failed to spool lifecycle event; capture for this event was skipped"+ if !external_capture {+ let ingest_key = uuid::Uuid::new_v4().simple().to_string();+ let event_url = format!(+ "{base}/hook?event={}&agent={}{}{}&ingest_key={ingest_key}",+ args.event, args.agent, hook_qs, capture_qs);- }- // ZCode is intentionally absent here: it has no SessionEnd and fires Stop- // per turn, so its stored id is cleared by `finalize-session` (or- // overwritten by the next session-start), never by a hook event.- if AgentKind::from_wire(&args.agent) == AgentKind::Devin && args.event == "session-end" {- clear_session_id(&dd, AgentKind::Devin);- }-- // Mid-session catch-up: per-event hooks only enqueue, so a heavy session- // outpaces the boundary-only drain and the spool grows until the next- // boundary. On `post-tool-use`, once the backlog crosses the threshold, do a- // tightly time-boxed drain (budget == per-event timeout, sub-second) so the- // spool stays flat without ever stalling a tool call.- if should_incremental_drain(- &args.event,- hook_spool::spool_len(&spool),- incremental_drain_threshold(),- ) {- let _ = hook_spool::drain_exclusive(- &spool,- &dd,- INCREMENTAL_DRAIN_BUDGET,- INCREMENTAL_DRAIN_BUDGET,- hook_spool::DrainLockWait::NoWait,- )- .await;- }-- // session-start: if this checkout has never had the one-time boot backfill- // attempted, spawn it detached. It self-gates (config opt-out, empty-store- // check) and records the attempt, so this is at most one extra process the- // first time a project is opened after installing hooks — never inline, so- // the SessionStart budget is untouched. Best-effort; a spawn failure must- // not affect session start.- if args.event == "session-start"- && let Ok(trigger_cwd) = std::env::current_dir()- && !super::backfill::sentinel_path(&dd, &trigger_cwd).exists()- {- let _ = hook_drain_process::spawn_backfill(&dd);+ let entry =+ hook_spool::entry_for(event_url, payload.clone(), effective_token, oidc_present);+ if hook_spool::enqueue(&spool, &entry).is_err() {+ eprintln!(+ "ai-memory hook warning: failed to spool lifecycle event; capture for this event was skipped"+ );+ }+ // ZCode is intentionally absent here: it has no SessionEnd and fires Stop+ // per turn, so its stored id is cleared by `finalize-session` (or+ // overwritten by the next session-start), never by a hook event.+ if AgentKind::from_wire(&args.agent) == AgentKind::Devin && args.event == "session-end" {+ clear_session_id(&dd, AgentKind::Devin);+ }++ // Mid-session catch-up: per-event hooks only enqueue, so a heavy session+ // outpaces the boundary-only drain and the spool grows until the next+ // boundary. On `post-tool-use`, once the backlog crosses the threshold, do a+ // tightly time-boxed drain (budget == per-event timeout, sub-second) so the+ // spool stays flat without ever stalling a tool call.+ if should_incremental_drain(+ &args.event,+ hook_spool::spool_len(&spool),+ incremental_drain_threshold(),+ ) {+ let _ = hook_spool::drain_exclusive(+ &spool,+ &dd,+ INCREMENTAL_DRAIN_BUDGET,+ INCREMENTAL_DRAIN_BUDGET,+ hook_spool::DrainLockWait::NoWait,+ )+ .await;+ }++ // session-start: if this checkout has never had the one-time boot backfill+ // attempted, spawn it detached. It self-gates (config opt-out, empty-store+ // check) and records the attempt, so this is at most one extra process the+ // first time a project is opened after installing hooks — never inline, so+ // the SessionStart budget is untouched. Best-effort; a spawn failure must+ // not affect session start.+ if args.event == "session-start"+ && let Ok(trigger_cwd) = std::env::current_dir()+ && !super::backfill::sentinel_path(&dd, &trigger_cwd).exists()+ {+ let _ = hook_drain_process::spawn_backfill(&dd);+ }}// session-start: drain any backlog (e.g. from a previous session that ended// abruptly), then fetch + inject the pending handoff for the resuming agent.if args.event == "session-start" {- let _ = hook_spool::drain_exclusive_within_budget(- &spool,- &dd,- start_drain_budget(),- drain_event_timeout(),- )- .await;+ if !external_capture {+ let _ = hook_spool::drain_exclusive_within_budget(+ &spool,+ &dd,+ start_drain_budget(),+ drain_event_timeout(),+ )+ .await;+ }// Only fetch the handoff for agents that inject the session-start// hook's stdout as context. Grok ignores it, so fetching here would// consume the handoff server-side (the GET is destructive) and then@@ -844,7 +866,8 @@ where// to flush the shared spool. `session-end` remains the primary close path,// but `stop` and `pre-compact` also trigger the helper so delivery does not// rely on the single hook most likely to be cancelled during agent shutdown.- if should_spawn_background_drainer(&args.event)+ if !external_capture+ && should_spawn_background_drainer(&args.event)&& let Err(err) = after_background_drain_event_enqueue(&dd,// The hook's own token, resolved the same way it authenticates@@ -2305,6 +2328,7 @@ mod tests {"admits_capture","capture_mode","disposition",+ "external_capture","extraction_state","marker_present","path_count",diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex d6c6374f..5da3749c 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -188,6 +188,21 @@ pub(crate) fn ts_string_literal(s: &str) -> String {/// repository with no `.ai-memory.toml` marker must emit nothing — mirroring/// the native admit gate in `commands/hook.rs` (`repository_admits_capture`)/// — so the check runs before any disposition logic, for every event kind.+///+/// Ahead of even that marker scan sits the external-ownership gate: when+/// `AI_MEMORY_CAPTURE_OWNER` holds any value that is non-empty after trimming,+/// `capturePolicy` returns `drop` immediately, so a generated consumer never+/// queues, spools, or POSTs a *new* capture event. It mirrors the native gate+/// in `commands/hook.rs` and leaves handoff fetching untouched, which is the+/// whole point: an external producer replaces capture without losing native+/// context delivery.+///+/// Two things it deliberately does not do. It does not suppress the consumer's+/// routing work around the call (`applyMarkerParams` reads the marker before+/// `capturePolicy` is even reached), and it does not erase an existing spool+/// backlog: a consumer that reaches `drainHookQueue` — on dispose, for+/// instance — still kicks off `requestSpoolDrain`, so events spooled before the+/// handover can still be delivered.#[must_use]pub(crate) fn ts_capture_policy_v1(capture_mode: &str) -> String {const TEMPLATE: &str = r##"// capture-policy-v1 (generated; do not fork between adapters)@@ -270,7 +285,15 @@ function captureConfig(cwd: string | undefined): CaptureConfig {}function captureGlob(pattern: string, candidate: string, insensitive: boolean, budget: { work: number }): boolean | undefined { const p = [...pattern]; const c = [...candidate]; const eq = (a: string, b: string) => insensitive && a.charCodeAt(0) < 128 && b.charCodeAt(0) < 128 ? a.toLowerCase() === b.toLowerCase() : a === b; const previous = new Array<boolean>(p.length + 1).fill(false); previous[0] = true; for (let j = 1; j <= p.length; j++) previous[j] = p[j - 1] === "*" && p[j] !== "*" && previous[j - 1]; for (const ch of c) { const current = new Array<boolean>(p.length + 1).fill(false); for (let j = 1; j <= p.length; j++) { if (++budget.work > CAPTURE_MAX_WORK) return undefined; const x = p[j - 1]; current[j] = x === "*" && p[j] === "*" ? false : x === "*" && j >= 2 && p[j - 2] === "*" ? current[j - 2] || previous[j] : x === "*" ? current[j - 1] || (ch !== "/" && previous[j]) : x === "?" ? ch !== "/" && previous[j - 1] : eq(x, ch) && previous[j - 1]; } for (let j = 0; j <= p.length; j++) previous[j] = current[j]; } return previous[p.length]; }function captureTool(payload: Record<string, unknown>): { family: CaptureProtocol["tool_family"]; paths?: string[]; extraction: CaptureProtocol["extraction_state"]; callID?: string } { const name = typeof payload.tool === "string" ? payload.tool.toLowerCase() : ""; const args = payload.args as Record<string, unknown> | undefined; const call = ["tool_use_id","toolUseId","tool_call_id","toolCallId","call_id","callId","callID"].map((k) => payload[k]).find((v): v is string => typeof v === "string" && /^[A-Za-z0-9_.-]{1,128}$/.test(v)); if (["search","grep","glob","find","list","ls","list_files","read_dir"].includes(name)) return { family: "search-list", extraction: "not-applicable", callID: call }; if (["bash","shell","execute","run_command","web_search"].includes(name)) return { family: "non-file", extraction: "extracted", callID: call }; if (!["read","write","edit","apply_patch","notebookedit","notebook_edit","create_file","delete_file","rename_file","move_file","multi_edit","multiedit","replace","replace_all"].includes(name)) return { family: "unknown", extraction: "extracted", callID: call }; const direct = (o: any): string[] | undefined => { if (!o || typeof o !== "object") return undefined; const r: string[] = []; for (const k of ["file_path","filePath","path","absolute_path","AbsolutePath","notebook_path"]) if (k in o) { if (typeof o[k] !== "string") return undefined; r.push(o[k]); } if ("paths" in o) { if (!Array.isArray(o.paths) || o.paths.some((x: unknown) => typeof x !== "string")) return undefined; r.push(...o.paths); } return r.length && r.length <= CAPTURE_MAX_CANDIDATES ? r : undefined; }; let paths = direct(args); if (["multi_edit","multiedit","replace_all"].includes(name)) { const entries = args?.edits ?? args?.replacements; if (!Array.isArray(entries) || !entries.length || entries.length > CAPTURE_MAX_CANDIDATES) paths = undefined; else { paths = paths ?? []; for (const entry of entries) { const more = direct(entry); if (!more || paths.length + more.length > CAPTURE_MAX_CANDIDATES) { paths = undefined; break; } paths.push(...more); } } } if (!paths || paths.some((p) => !p.trim() || [...p].length > CAPTURE_MAX_PATH_CHARS)) return { family: "file", extraction: "missing-or-malformed", callID: call }; return { family: "file", paths, extraction: "extracted", callID: call }; }-function capturePolicy(payload: Record<string, unknown>, cwd: string | undefined): { disposition: CaptureDisposition; protocol?: CaptureProtocol; payload: Record<string, unknown> } { const markerPresent = !!findMarker(cwd); if (CAPTURE_MODE === "allowlist" && !markerPresent) return { disposition: "drop", payload }; const config = captureConfig(cwd); const tool = captureTool(payload); let disposition: CaptureDisposition = "keep"; if (config.state === "invalid" && tool.family === "file") disposition = "metadata-only"; else if (config.state === "active" && tool.family === "search-list") disposition = "drop"; else if (config.state === "active" && tool.family === "file") { if (!tool.paths) disposition = "metadata-only"; else { const candidates = tool.paths.map((p) => captureNormalize(/^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(p) ? p : captureJoin(config.base, p))); if (candidates.some((p) => !p)) disposition = "metadata-only"; else { const budget = { work: 0 }; captureMatch: for (const candidate of candidates as { path: string; windows: boolean }[]) for (const pattern of config.patterns) { if (candidate.windows !== pattern.windows) continue; if (pattern.directory && captureGlob(pattern.directory, candidate.path, pattern.windows, budget)) { disposition = "drop"; break captureMatch; } const match = captureGlob(pattern.path, candidate.path, pattern.windows, budget); if (match === undefined) { disposition = "metadata-only"; break; } if (match) { disposition = "drop"; break captureMatch; } } } } } if (config.state === "inactive") return { disposition, payload }; const protocol: CaptureProtocol = { version: CAPTURE_POLICY_V1, disposition, policy_state: config.state, tool_family: tool.family, path_count: tool.paths?.length ?? 0, extraction_state: tool.extraction }; if (disposition === "metadata-only") { const session = payload.sessionID ?? payload.sessionId ?? payload.session_id; const routing = typeof payload.cwd === "string" ? payload.cwd : cwd; return { disposition, protocol, payload: { ...(typeof session === "string" ? { session_id: session } : {}), ...(typeof routing === "string" ? { cwd: routing } : {}), tool_family: tool.family, tool_name: tool.family, ...(tool.callID ? { tool_call_id: tool.callID } : {}), _ai_memory_capture: protocol } }; } if (disposition === "keep") return { disposition, protocol, payload: { ...payload, _ai_memory_capture: protocol } }; return { disposition, protocol, payload }; }+// An external lifecycle owner (`AI_MEMORY_CAPTURE_OWNER`, any value that is+// non-empty after trimming) takes over capture for this process: the gate runs+// before the capture-policy marker scan, so no disposition work, no marker read+// by this policy, and no queue write, spool write, or capture POST downstream.+// It does not reach the consumer's own routing work (`applyMarkerParams` runs+// earlier in postHook), and context delivery (`fetchHandoff`) is a separate+// path that stays live.+function captureOwnedExternally(): boolean { const owner = typeof process === "undefined" ? undefined : process.env?.AI_MEMORY_CAPTURE_OWNER; return typeof owner === "string" && owner.trim() !== ""; }+function capturePolicy(payload: Record<string, unknown>, cwd: string | undefined): { disposition: CaptureDisposition; protocol?: CaptureProtocol; payload: Record<string, unknown> } { if (captureOwnedExternally()) return { disposition: "drop", payload }; const markerPresent = !!findMarker(cwd); if (CAPTURE_MODE === "allowlist" && !markerPresent) return { disposition: "drop", payload }; const config = captureConfig(cwd); const tool = captureTool(payload); let disposition: CaptureDisposition = "keep"; if (config.state === "invalid" && tool.family === "file") disposition = "metadata-only"; else if (config.state === "active" && tool.family === "search-list") disposition = "drop"; else if (config.state === "active" && tool.family === "file") { if (!tool.paths) disposition = "metadata-only"; else { const candidates = tool.paths.map((p) => captureNormalize(/^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(p) ? p : captureJoin(config.base, p))); if (candidates.some((p) => !p)) disposition = "metadata-only"; else { const budget = { work: 0 }; captureMatch: for (const candidate of candidates as { path: string; windows: boolean }[]) for (const pattern of config.patterns) { if (candidate.windows !== pattern.windows) continue; if (pattern.directory && captureGlob(pattern.directory, candidate.path, pattern.windows, budget)) { disposition = "drop"; break captureMatch; } const match = captureGlob(pattern.path, candidate.path, pattern.windows, budget); if (match === undefined) { disposition = "metadata-only"; break; } if (match) { disposition = "drop"; break captureMatch; } } } } } if (config.state === "inactive") return { disposition, payload }; const protocol: CaptureProtocol = { version: CAPTURE_POLICY_V1, disposition, policy_state: config.state, tool_family: tool.family, path_count: tool.paths?.length ?? 0, extraction_state: tool.extraction }; if (disposition === "metadata-only") { const session = payload.sessionID ?? payload.sessionId ?? payload.session_id; const routing = typeof payload.cwd === "string" ? payload.cwd : cwd; return { disposition, protocol, payload: { ...(typeof session === "string" ? { session_id: session } : {}), ...(typeof routing === "string" ? { cwd: routing } : {}), tool_family: tool.family, tool_name: tool.family, ...(tool.callID ? { tool_call_id: tool.callID } : {}), _ai_memory_capture: protocol } }; } if (disposition === "keep") return { disposition, protocol, payload: { ...payload, _ai_memory_capture: protocol } }; return { disposition, protocol, payload }; }"##;TEMPLATE.replace("__AI_MEMORY_CAPTURE_MODE__", capture_mode)}@@ -2022,6 +2045,25 @@ mod tests {)}+ /// `Some(())` when this machine can execute the emitted TypeScript.+ /// Node is not a build dependency of this project, so a box without it+ /// (or on a Node too old for type stripping) skips the runtime evidence+ /// instead of failing.+ fn node_strip_types_available() -> Option<()> {+ let probe = Command::new("node")+ .args(["--experimental-strip-types", "--version"])+ .output();+ match probe {+ Ok(output) if output.status.success() => Some(()),+ _ => {+ eprintln!(+ "skipping Node-required runtime evidence: node lacks --experimental-strip-types"+ );+ None+ }+ }+ }+#[test]fn bearer_header_is_none_when_no_token() {assert!(bearer_header_value(None).is_none());@@ -2039,21 +2081,9 @@ mod tests {#[test]#[ignore = "manual Node-required generated TypeScript runtime evidence"]fn generated_capture_policy_v1_node_runtime_evidence() {- let strip_types = Command::new("node")- .args(["--experimental-strip-types", "--version"])- .output();- let Ok(strip_types) = strip_types else {- eprintln!(- "skipping Node-required runtime evidence: node lacks --experimental-strip-types"- );+ let Some(()) = node_strip_types_available() else {return;};- if !strip_types.status.success() {- eprintln!(- "skipping Node-required runtime evidence: node lacks --experimental-strip-types"- );- return;- }let temp = tempfile::tempdir().unwrap();let module = temp.path().join("capture-policy-runtime-evidence.ts");@@ -2241,6 +2271,102 @@ check(markedButEmpty.disposition === "keep", "allowlist-marker-present-empty-cap);}+ /// `AI_MEMORY_CAPTURE_OWNER` hands capture to an external producer: the+ /// generated `capturePolicy` must drop before it even looks for a marker.+ /// Executed against the real emitted TypeScript rather than a hand-kept+ /// copy, and cheap enough (three short Node runs, no fixtures) to stay in+ /// the default tier instead of joining the manual evidence test above.+ #[test]+ fn generated_capture_policy_gates_on_external_capture_owner() {+ let Some(()) = node_strip_types_available() else {+ return;+ };+ // `keep()` cancels delete-on-drop: the emitted modules are the+ // evidence, so they stay on disk for inspection after the run.+ let temp = tempfile::tempdir().unwrap().keep();+ eprintln!("capture-owner gate modules retained at {}", temp.display());+ const HARNESS: &str = r#"import { closeSync, mkdirSync, openSync, readFileSync as readMarkerText, readSync, writeFileSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { homedir } from "node:os";++const markerRoot = process.argv[2]!;+const inheritOnly = process.argv[3] === "inherit";+let markerScans = 0;+const repo = join(markerRoot, "repo");+mkdirSync(repo, { recursive: true });+const markerFile = join(repo, ".ai-memory.toml");+writeFileSync(markerFile, '[capture]\nignore_paths = ["secret/**"]\n');+function findMarker(cwd: string | undefined): string | undefined { markerScans++; return cwd === repo ? markerFile : undefined; }+__AI_MEMORY_POLICY__++function fail(label: string): never { throw new Error(`external-owner gate failed: ${label}`); }+function check(ok: unknown, label: string): asserts ok { if (!ok) fail(label); }++function probe(label: string, owned: boolean): void {+ markerScans = 0;+ const payload = { tool: "edit", args: { path: "public/item" } };+ const result = capturePolicy(payload, repo);+ if (owned) {+ check(result.disposition === "drop", `${label} disposition`);+ // Before the capture-policy marker scan: no disk read by the policy, no+ // disposition work, and the payload comes back untouched so nothing+ // downstream can queue it.+ check(markerScans === 0, `${label} marker scan`);+ check(result.protocol === undefined, `${label} protocol`);+ check(result.payload === payload, `${label} payload identity`);+ } else {+ check(result.disposition === "keep", `${label} disposition`);+ check(markerScans > 0, `${label} marker scan`);+ check(result.protocol?.policy_state === "active", `${label} protocol`);+ }+}++if (inheritOnly) {+ // The value really arrived through the process environment, not a mutation+ // this harness made.+ check((process.env.AI_MEMORY_CAPTURE_OWNER ?? "").trim() !== "", "inherited owner missing");+ probe("inherited-owner", true);+} else {+ for (const [value, owned] of [[undefined, false], ["", false], [" \t\n", false], ["orchestrator-a", true], [" orchestrator-a ", true]] as [string | undefined, boolean][]) {+ if (value === undefined) delete process.env.AI_MEMORY_CAPTURE_OWNER;+ else process.env.AI_MEMORY_CAPTURE_OWNER = value;+ probe(`owner=${JSON.stringify(value)}`, owned);+ }+}+"#;++ for (mode, inherit) in [("denylist", false), ("denylist", true), ("allowlist", true)] {+ let module = temp.join(format!(+ "capture-owner-{mode}-{}.ts",+ if inherit { "inherit" } else { "matrix" }+ ));+ fs::write(+ &module,+ HARNESS.replace("__AI_MEMORY_POLICY__", &ts_capture_policy_v1(mode)),+ )+ .unwrap();+ let mut command = Command::new("node");+ command.args([+ "--experimental-strip-types",+ module.to_str().unwrap(),+ temp.to_str().unwrap(),+ if inherit { "inherit" } else { "matrix" },+ ]);+ if inherit {+ command.env("AI_MEMORY_CAPTURE_OWNER", "orchestrator-a");+ } else {+ command.env_remove("AI_MEMORY_CAPTURE_OWNER");+ }+ let output = command.output().unwrap();+ assert!(+ output.status.success(),+ "capture-owner gate evidence failed (mode={mode}, inherit={inherit})\nstdout:\n{}\nstderr:\n{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr),+ );+ }+ }+#[test]fn claude_code_payload_has_all_events() {let root = PathBuf::from("/host/hooks/claude-code");diff --git a/crates/ai-memory-cli/tests/suite/external_capture.rs b/crates/ai-memory-cli/tests/suite/external_capture.rsnew file mode 100644index 00000000..2e0a3091--- /dev/null+++ b/crates/ai-memory-cli/tests/suite/external_capture.rs@@ -0,0 +1,473 @@+//! An external producer may replace capture without replacing native context delivery.++use std::io::Write;+use std::path::{Path, PathBuf};+use std::process::{Output, Stdio};++use serde_json::{Value, json};++use crate::e2e_support::hermetic;++const BIN: &str = env!("CARGO_BIN_EXE_ai-memory");++fn hook(root: &Path, agent: &str, event: &str, owner: Option<&str>, check: bool) -> Output {+ let mut cmd = hermetic(BIN);+ cmd.args(["--data-dir"])+ .arg(root.join("data"))+ .args(["hook", "--agent", agent, "--event", event, "--server-url"])+ .arg(ai_memory_test_support::dead_http_endpoint())+ .env("AI_MEMORY_HOME", root)+ .env("HOME", root)+ .current_dir(root)+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ if let Some(owner) = owner {+ cmd.env("AI_MEMORY_CAPTURE_OWNER", owner);+ }+ if check {+ cmd.arg("--check-capture");+ }+ let mut child = cmd.spawn().expect("spawn hook");+ child+ .stdin+ .take()+ .unwrap()+ .write_all(+ json!({"session_id":"external-owner-test", "cwd":root, "prompt":"capture marker"})+ .to_string()+ .as_bytes(),+ )+ .unwrap();+ let result = child.wait_with_output().unwrap();+ assert!(result.status.success(), "{result:?}");+ result+}++#[test]+fn external_capture_owner_suppresses_only_the_opted_in_process() {+ for owner in [None, Some(""), Some(" \t\n"), Some("orchestrator-a")] {+ let tmp = tempfile::tempdir().unwrap().keep();+ let output = hook(+ tmp.as_path(),+ "claude-code",+ "user-prompt-submit",+ owner,+ false,+ );+ assert_eq!(output.stdout, b"{}\n");+ let spool = tmp.as_path().join("data/hook-spool");+ let entries = std::fs::read_dir(spool)+ .map(|entries| {+ entries+ .flatten()+ .filter(|entry| entry.path().extension().is_some_and(|ext| ext == "json"))+ .count()+ })+ .unwrap_or(0);+ assert_eq!(+ entries,+ usize::from(owner != Some("orchestrator-a")),+ "owner={owner:?}"+ );+ }+}++#[test]+fn external_devin_end_still_clears_native_identity() {+ let root = tempfile::tempdir().unwrap().keep();+ let state = root.join("data/hook-state/devin-session-id");+ std::fs::create_dir_all(state.parent().unwrap()).unwrap();+ std::fs::write(&state, "completed-execution").unwrap();++ hook(&root, "devin", "session-end", Some("orchestrator-a"), true);+ assert!(state.exists(), "inspection must not clear identity");+ hook(&root, "devin", "session-end", Some("orchestrator-a"), false);+ assert!(+ !state.exists(),+ "SessionEnd must retire native fallback identity"+ );+ assert!(!root.join("data/hook-spool").exists());+}++#[test]+fn capture_inspection_reports_external_ownership_without_side_effects() {+ let tmp = tempfile::tempdir().unwrap().keep();+ let output = hook(+ tmp.as_path(),+ "claude-code",+ "user-prompt-submit",+ Some("orchestrator-a"),+ true,+ );+ let report: Value = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(report["external_capture"], true);+ assert_eq!(report["admits_capture"], false);+ assert!(!tmp.as_path().join("data").exists());+}++mod slow {+ use super::*;+ use std::process::Command;+ use std::time::{Duration, Instant};++ use ai_memory_core::SessionId;+ use ai_memory_store::ReaderPool;+ use sha2::{Digest, Sha256};++ use crate::e2e_support::{ServerGuard, free_port};++ const TOKEN: &str = "external-capture-local-test-token";+ const MARKER: &str = "external_capture_handoff_marker";++ struct Fixture {+ _server: ServerGuard,+ reader: ReaderPool,+ root: PathBuf,+ client: reqwest::Client,+ base: String,+ }++ fn command(root: &Path) -> Command {+ let mut cmd = hermetic(BIN);+ for (key, _) in std::env::vars_os() {+ if key.to_string_lossy().starts_with("GIT_") {+ cmd.env_remove(key);+ }+ }+ cmd.env("GIT_CONFIG_NOSYSTEM", "1")+ .env("GIT_CONFIG_GLOBAL", root.join("empty-gitconfig"))+ .env("HOME", root.join("home"))+ .env("USERPROFILE", root.join("home"))+ .env("AI_MEMORY_HOME", root.join("home"))+ .env("AI_MEMORY_DATA_DIR", root.join("data"))+ .env("AI_MEMORY_AUTH_TOKEN", TOKEN)+ .env("AI_MEMORY_EMBEDDING_PROVIDER", "none")+ .env("AI_MEMORY_BACKFILL_ON_START", "false")+ .env("AI_MEMORY_CONSOLIDATE_ON_SESSION_END", "false")+ .env("AI_MEMORY_AUTO_IMPROVE__SCHEDULER__ENABLED", "false")+ .env("RUST_LOG", "off")+ .current_dir(root.join("project"));+ cmd+ }++ impl Fixture {+ async fn start() -> Self {+ let root = tempfile::tempdir().unwrap().keep();+ for dir in ["home", "data", "project"] {+ std::fs::create_dir(root.as_path().join(dir)).unwrap();+ }+ std::fs::write(root.as_path().join("empty-gitconfig"), "").unwrap();+ std::fs::write(+ root.as_path().join("project/.ai-memory.toml"),+ "workspace = \"external-test\"\nproject = \"capture-test\"\n",+ )+ .unwrap();+ let port = free_port();+ let base = format!("http://127.0.0.1:{port}");+ let server = ServerGuard(+ command(root.as_path())+ .args([+ "serve",+ "--transport",+ "http",+ "--bind",+ &format!("127.0.0.1:{port}"),+ "--workspace",+ "external-test",+ "--project",+ "capture-test",+ "--no-watcher",+ ])+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .unwrap(),+ );+ let client = reqwest::Client::builder()+ .timeout(Duration::from_secs(15))+ .build()+ .unwrap();+ let deadline = Instant::now() + Duration::from_secs(30);+ loop {+ if client+ .get(format!("{base}/mcp"))+ .bearer_auth(TOKEN)+ .send()+ .await+ .is_ok()+ {+ break;+ }+ assert!(Instant::now() < deadline, "server readiness timeout");+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ let reader = ReaderPool::new(&root.as_path().join("data/db/memory.sqlite"), 2).unwrap();+ Self {+ _server: server,+ reader,+ root,+ client,+ base,+ }+ }++ fn event(&self, sid: SessionId, producer: &str, event_id: &str, event: &str) -> Value {+ // An adapter-side convention: hash stable identity, never message content.+ let identity = json!([+ "external-capture-v1",+ producer,+ "operator-a",+ "claude-code",+ sid,+ event,+ event_id+ ]);+ let key = format!("{:x}", Sha256::digest(identity.to_string().as_bytes()));+ let mut url = reqwest::Url::parse(&format!("{}/hook", self.base)).unwrap();+ url.query_pairs_mut().extend_pairs([+ ("event", event),+ ("agent", "claude-code"),+ ("workspace", "external-test"),+ ("project", "capture-test"),+ ("extension", producer),+ ("source_event", event),+ ("ingest_key", &key),+ ]);+ json!({"url":url.as_str(), "body":{"session_id":sid, "cwd":self.root.as_path().join("project"), "prompt":MARKER}})+ }++ async fn batch(&self, items: &[Value]) {+ let response = self+ .client+ .post(format!("{}/hook/batch", self.base))+ .bearer_auth(TOKEN)+ .json(items)+ .send()+ .await+ .unwrap();+ assert!(response.status().is_success(), "{}", response.status());+ let ack: Value = response.json().await.unwrap();+ assert_eq!(ack["accepted"], items.len(), "{ack}");+ }++ async fn seed_handoff(&self) {+ let sid = SessionId::new();+ self.batch(&[+ self.event(sid, "orchestrator-a", "start", "session-start"),+ self.event(sid, "orchestrator-a", "prompt", "user-prompt-submit"),+ self.event(sid, "orchestrator-a", "end", "session-end"),+ ])+ .await;+ }++ fn native(&self, sid: SessionId, agent: &str, event: &str) -> String {+ let mut child = command(self.root.as_path())+ .args([+ "hook",+ "--agent",+ agent,+ "--event",+ event,+ "--server-url",+ &self.base,+ "--auth-token",+ TOKEN,+ ])+ .env("AI_MEMORY_CAPTURE_OWNER", "orchestrator-a")+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .unwrap();+ child.stdin.take().unwrap().write_all(+ json!({"session_id":sid,"cwd":self.root.as_path().join("project"),"prompt":"native duplicate"})+ .to_string().as_bytes(),+ ).unwrap();+ let output = child.wait_with_output().unwrap();+ assert!(output.status.success(), "{output:?}");+ assert!(output.stderr.is_empty(), "{output:?}");+ String::from_utf8(output.stdout).unwrap()+ }+ }++ #[tokio::test]+ async fn external_capture_preserves_native_handoffs_and_mcp_recall() {+ let fixture = Fixture::start().await;+ for (agent, event) in [+ ("claude-code", "session-start"),+ ("kimi-code", "user-prompt-submit"),+ ] {+ fixture.seed_handoff().await;+ let receiver = SessionId::new();+ let output = fixture.native(receiver, agent, event);+ assert!(output.contains(MARKER), "handoff was lost: {output}");+ assert!(+ fixture+ .reader+ .observations_for_session(receiver)+ .await+ .unwrap()+ .is_empty()+ );+ assert!(+ !fixture.native(receiver, agent, event).contains(MARKER),+ "handoff was delivered twice"+ );+ fixture.native(receiver, agent, "session-end");+ assert!(!fixture.root.as_path().join("data/hook-spool").exists());+ assert!(!fixture.root.as_path().join("data/backfill-state").exists());+ }+ let response: Value = fixture.client.post(format!("{}/mcp",fixture.base))+ .bearer_auth(TOKEN).header("accept","application/json, text/event-stream")+ .json(&json!({"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"memory_query","arguments":{"query":MARKER,"workspace":"external-test","project":"capture-test"}}}))+ .send().await.unwrap().json().await.unwrap();+ assert!(response.get("error").is_none(), "{response}");+ assert_ne!(+ response.pointer("/result/isError"),+ Some(&Value::Bool(true)),+ "{response}"+ );+ assert!(+ response.to_string().contains(MARKER),+ "MCP did not recall external capture: {response}"+ );+ }++ #[tokio::test]+ async fn external_identities_retry_concurrently_without_collapsing_distinct_events() {+ let fixture = Fixture::start().await;+ let sid = SessionId::new();+ let first = fixture.event(sid, "orchestrator-a", "prompt-1", "user-prompt-submit");+ let unauthorized = fixture+ .client+ .post(format!("{}/hook/batch", fixture.base))+ .json(std::slice::from_ref(&first))+ .send()+ .await+ .unwrap();+ assert_eq!(unauthorized.status(), reqwest::StatusCode::UNAUTHORIZED);+ let retry = [first];+ tokio::join!(fixture.batch(&retry), fixture.batch(&retry));+ fixture+ .batch(&[+ fixture.event(sid, "orchestrator-a", "prompt-2", "user-prompt-submit"),+ fixture.event(sid, "orchestrator-b", "prompt-1", "user-prompt-submit"),+ ])+ .await;+ let observations = fixture.reader.observations_for_session(sid).await.unwrap();+ assert_eq!(observations.len(), 3);+ assert!(+ observations.iter().all(+ |o| o.body == MARKER && o.source_event.as_deref() == Some("user-prompt-submit")+ )+ );+ assert_eq!(+ observations+ .iter()+ .filter(|o| o.extension.as_deref() == Some("orchestrator-b"))+ .count(),+ 1+ );++ // A project-scoped key must not consume an event in another workspace.+ let other_sid = SessionId::new();+ let mut other = retry[0].clone();+ other["body"]["session_id"] = json!(other_sid);+ other["url"] = Value::String(+ other["url"]+ .as_str()+ .unwrap()+ .replace("workspace=external-test", "workspace=other-workspace"),+ );+ fixture.batch(&[other]).await;+ assert_eq!(+ fixture+ .reader+ .observations_for_session(other_sid)+ .await+ .unwrap()+ .len(),+ 1+ );+ let original_scope = fixture+ .reader+ .find_session_scope(sid)+ .await+ .unwrap()+ .unwrap();+ let other_scope = fixture+ .reader+ .find_session_scope(other_sid)+ .await+ .unwrap()+ .unwrap();+ assert_ne!(original_scope.0, other_scope.0);+ assert_ne!(original_scope.1, other_scope.1);+ }++ #[tokio::test]+ async fn documented_batch_example_is_idempotent() {+ let fixture = Fixture::start().await;+ let doc = include_str!("../../../../docs/external-lifecycle.md");+ let example = doc+ .split("```json\n")+ .nth(1)+ .unwrap()+ .split("```")+ .next()+ .unwrap();+ let events: Vec<Value> = serde_json::from_str(example).unwrap();+ fixture.batch(&events).await;+ fixture.batch(&events).await;+ assert_eq!(+ fixture.reader.status_counts().await.unwrap().observations,+ 1+ );+ }++ #[tokio::test]+ async fn fifteen_external_sessions_share_one_server_and_retry_completed_batches() {+ let fixture = Fixture::start().await;+ let mut tasks = tokio::task::JoinSet::new();+ for index in 0..15 {+ let sid = SessionId::new();+ let producer = format!("runtime-{}", index % 3);+ let items = vec![+ fixture.event(sid, &producer, "1", "session-start"),+ fixture.event(sid, &producer, "2", "user-prompt-submit"),+ fixture.event(sid, &producer, "3", "session-end"),+ ];+ let client = fixture.client.clone();+ let endpoint = format!("{}/hook/batch", fixture.base);+ tasks.spawn(async move {+ for _ in 0..2 {+ let response = client+ .post(&endpoint)+ .bearer_auth(TOKEN)+ .json(&items)+ .send()+ .await+ .unwrap();+ assert!(response.status().is_success(), "{}", response.status());+ let ack: Value = response.json().await.unwrap();+ assert_eq!(ack["accepted"], 3, "{ack}");+ }+ sid+ });+ }+ while let Some(result) = tasks.join_next().await {+ let observations = fixture+ .reader+ .observations_for_session(result.unwrap())+ .await+ .unwrap();+ assert_eq!(observations.len(), 3);+ }+ assert_eq!(+ fixture.reader.status_counts().await.unwrap().observations,+ 45+ );+ }+}diff --git a/crates/ai-memory-cli/tests/suite/external_capture_powershell.rs b/crates/ai-memory-cli/tests/suite/external_capture_powershell.rsnew file mode 100644index 00000000..395ccf83--- /dev/null+++ b/crates/ai-memory-cli/tests/suite/external_capture_powershell.rs@@ -0,0 +1,192 @@+//! The PowerShell hook bundle must honour `AI_MEMORY_CAPTURE_OWNER` the same+//! way the POSIX one does: a non-blank owner suppresses the capture POST while+//! the handoff GET still runs and still reaches the agent through stdout.+//!+//! Windows-only. `hooks/lib/ai-memory-hook.ps1` is the shipped helper for every+//! PowerShell-hosted agent, and this is the one CI leg with a PowerShell to run+//! it under. The test dot-sources the REAL helper and shadows nothing but+//! `Invoke-WebRequest`, so the gate, the session/marker query building and the+//! stdout contract under test are the shipped code paths.++#[cfg(windows)]+mod windows_only {+ use std::io::Write as _;+ use std::path::{Path, PathBuf};+ use std::process::Stdio;++ use serde_json::json;++ use crate::e2e_support::hermetic;++ fn repo_root() -> PathBuf {+ Path::new(env!("CARGO_MANIFEST_DIR"))+ .parent()+ .and_then(Path::parent)+ .expect("crate should live under crates/ai-memory-cli")+ .to_path_buf()+ }++ /// Dot-sources the shipped helper, then defines `Invoke-WebRequest` in the+ /// script scope. A function outranks a cmdlet in PowerShell's command+ /// resolution, so every request the helper makes lands here instead of on+ /// the network; nothing else about the helper is replaced.+ const DRIVER: &str = r#"+$ErrorActionPreference = 'Stop'+. $env:AI_MEMORY_TEST_HELPER++function Invoke-WebRequest {+ param(+ [switch] $UseBasicParsing,+ [int] $TimeoutSec,+ [string] $Method = 'Get',+ [string] $Uri,+ $Headers,+ [string] $ContentType,+ $Body+ )+ Add-Content -LiteralPath $env:AI_MEMORY_TEST_LOG -Value ('{0} {1}' -f $Method.ToUpperInvariant(), $Uri)+ if ($Method -eq 'Post') { return $null }+ return [pscustomobject]@{ Content = 'HANDOFF FROM SERVER' }+}++Invoke-AiMemoryHook -Event 'session-start' -Agent 'claude-code' -FetchHandoff+"#;++ struct Run {+ requests: Vec<String>,+ stdout: String,+ }++ impl Run {+ fn methods(&self) -> Vec<&str> {+ self.requests+ .iter()+ .filter_map(|line| line.split_whitespace().next())+ .collect()+ }+ }++ /// Run the helper once under `owner`. `None` leaves the variable unset.+ ///+ /// The sandbox is kept, not dropped: these fixtures are small, recoverable+ /// and worth reading after a CI failure, and nothing here should delete a+ /// tree on its own.+ fn run(owner: Option<&str>) -> Run {+ let tmp = tempfile::tempdir().unwrap().keep();+ let driver = tmp.join("driver.ps1");+ let log = tmp.join("requests.log");+ std::fs::write(&driver, DRIVER).unwrap();+ std::fs::write(&log, "").unwrap();++ // `hermetic` drops every inherited AI_MEMORY_* variable, so only the+ // ones set back below reach the helper.+ let mut command = hermetic(ai_memory_test_support::powershell_exe());+ command+ .args([+ "-NoLogo",+ "-NoProfile",+ "-NonInteractive",+ "-ExecutionPolicy",+ "Bypass",+ "-File",+ ])+ .arg(&driver)+ .env(+ "AI_MEMORY_TEST_HELPER",+ repo_root().join("hooks/lib/ai-memory-hook.ps1"),+ )+ .env("AI_MEMORY_TEST_LOG", &log)+ // Every file the helper may touch (session id, briefed markers)+ // stays in the sandbox, and the marker walk starts and ends there+ // too, so no .ai-memory.toml outside the test can reach it.+ .env("AI_MEMORY_DATA_DIR", &tmp)+ .env("AI_MEMORY_HOME", &tmp)+ .env("HOME", &tmp)+ .env("USERPROFILE", &tmp)+ .current_dir(&tmp)+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ if let Some(owner) = owner {+ command.env("AI_MEMORY_CAPTURE_OWNER", owner);+ }++ let mut child = command.spawn().expect("spawn PowerShell");+ // Read-AiMemoryStdin only reads when stdin is redirected, which a pipe+ // makes true. The payload carries the sandbox as cwd, so the marker+ // walk resolves inside it.+ child+ .stdin+ .take()+ .unwrap()+ .write_all(+ json!({"session_id": "ps-owner-test", "cwd": tmp})+ .to_string()+ .as_bytes(),+ )+ .unwrap();+ let output = child.wait_with_output().unwrap();+ assert!(+ output.status.success(),+ "driver failed for owner={owner:?}: stdout={} stderr={}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );++ Run {+ requests: std::fs::read_to_string(&log)+ .unwrap()+ .lines()+ .map(str::to_owned)+ .filter(|line| !line.trim().is_empty())+ .collect(),+ stdout: String::from_utf8_lossy(&output.stdout).into_owned(),+ }+ }++ #[test]+ fn capture_owner_suppresses_the_post_and_still_delivers_the_handoff() {+ let run = run(Some("orchestrator-a"));+ assert_eq!(+ run.methods(),+ vec!["GET"],+ "an external owner must produce no capture POST: {:?}",+ run.requests+ );+ assert!(+ run.requests[0].contains("/handoff?agent=claude-code"),+ "the handoff GET must still be issued: {:?}",+ run.requests+ );+ assert!(+ run.stdout.contains("HANDOFF FROM SERVER"),+ "the fetched context must still reach the agent: {:?}",+ run.stdout+ );+ }++ #[test]+ fn blank_capture_owner_keeps_capture_on() {+ // An empty value may reach the child as "unset" on Windows; either way+ // the contract is the same, so both spellings assert the same thing.+ for owner in [None, Some(""), Some(" \t ")] {+ let run = run(owner);+ assert_eq!(+ run.methods(),+ vec!["POST", "GET"],+ "owner={owner:?} must not suppress capture: {:?}",+ run.requests+ );+ assert!(+ run.requests[0].contains("/hook?event=session-start&agent=claude-code"),+ "owner={owner:?} POST target: {:?}",+ run.requests+ );+ assert!(+ run.stdout.contains("HANDOFF FROM SERVER"),+ "owner={owner:?} stdout: {:?}",+ run.stdout+ );+ }+ }+}diff --git a/crates/ai-memory-cli/tests/suite/external_capture_ts.rs b/crates/ai-memory-cli/tests/suite/external_capture_ts.rsnew file mode 100644index 00000000..0ac6db37--- /dev/null+++ b/crates/ai-memory-cli/tests/suite/external_capture_ts.rs@@ -0,0 +1,224 @@+//! An external capture owner silences the generated TypeScript integration's+//! transport without silencing its context delivery.+//!+//! The native binary's own gate is covered by `external_capture`, which drives+//! the real CLI. This file covers the other enforcement point: the+//! `capturePolicy` the shared template bakes into every generated+//! JavaScript/TypeScript integration. It renders the real OpenCode plugin+//! through the shipped binary, then runs it in Node against a loopback counter+//! standing in for the server — runtime evidence about the generated *client*+//! (what it sends, queues and spools), not about server behaviour.+//!+//! Scope of the gate, as measured here: no new capture POST, no queue entry,+//! no new spool file. It is not a claim that the client goes quiet altogether.+//! The consumer resolves routing marker params before it ever calls+//! `capturePolicy`, the handoff fetch is a separate path (asserted below), and+//! a spool backlog written before the handover can still drain — dispose calls+//! `requestHookDrain`, and the patched `drainHookQueue` fires+//! `requestSpoolDrain` even with an empty queue. Suppressing new capture is the+//! contract; erasing the backlog is not.+//!+//! Tiered slow: rendering the plugin spawns the CLI and each case spawns Node.+//!+//! Fixtures are retained deliberately. The generated plugin and the harness+//! that drove it are the evidence; nothing here deletes them.++/// Slow tier: three process spawns per case (CLI render plus one Node run).+mod slow_generated_runtime {+ use std::path::{Path, PathBuf};+ use std::process::Command;++ use serde_json::Value;++ use crate::e2e_support::{free_port, hermetic};++ const BIN: &str = env!("CARGO_BIN_EXE_ai-memory");++ /// Node is not a build dependency, so a box without it (or on a Node too+ /// old for type stripping) skips instead of failing.+ fn node_strip_types_available() -> bool {+ match Command::new("node")+ .args(["--experimental-strip-types", "--version"])+ .output()+ {+ Ok(output) if output.status.success() => true,+ _ => {+ eprintln!(+ "skipping generated-plugin runtime test: node lacks --experimental-strip-types"+ );+ false+ }+ }+ }++ /// The plugin exactly as `install-hooks` would write it, minus the three+ /// human-facing comment lines the non-`--apply` render prints first.+ fn render_opencode_plugin(home: &Path, server_url: &str) -> String {+ let output = hermetic(BIN)+ .args(["install-hooks", "--agent", "opencode", "--server-url"])+ .arg(server_url)+ .env("HOME", home)+ .env("USERPROFILE", home)+ .env("AI_MEMORY_HOME", home)+ .current_dir(home)+ .output()+ .expect("render opencode plugin");+ assert!(+ output.status.success(),+ "install-hooks failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ let stdout = String::from_utf8(output.stdout).expect("plugin is utf-8");+ let start = stdout+ .find("// Auto-generated by")+ .expect("generated plugin banner");+ stdout[start..].to_string()+ }++ /// Drives the generated plugin through its public surface: a session+ /// start, a user prompt, the system-prompt transform that fetches a+ /// handoff, and dispose (which posts session-end and flushes the queue).+ /// The loopback server counts what actually leaves the client.+ const HARNESS: &str = r#"import { createServer } from "node:http";+import AiMemoryHooks from "./ai-memory.ts";++const port = Number(process.argv[2]);+const directory = process.argv[3]!;+const events: string[] = [];+let handoffs = 0;+const server = createServer((req, res) => {+ const url = new URL(req.url ?? "/", "http://127.0.0.1");+ req.resume();+ if (url.pathname === "/hook") {+ events.push(url.searchParams.get("event") ?? "?");+ res.writeHead(204);+ res.end();+ return;+ }+ if (url.pathname === "/handoff") {+ handoffs++;+ res.writeHead(200, { "content-type": "text/plain" });+ res.end("HANDOFF_SENTINEL");+ return;+ }+ res.writeHead(404);+ res.end();+});+await new Promise<void>((resolve) => server.listen(port, "127.0.0.1", () => resolve()));++const hooks: any = await (AiMemoryHooks as any)({ directory });+await hooks.event({ event: { type: "session.created", properties: { info: { id: "s1", directory } } } });+await hooks["chat.message"]({ sessionID: "s1" }, { parts: [{ type: "text", text: "PROMPT_SENTINEL" }] });+const transformed: { system: string[] } = { system: [] };+await hooks["experimental.chat.system.transform"]({ sessionID: "s1" }, transformed);+await hooks.dispose();+server.close();+console.log(JSON.stringify({ events, handoffs, system: transformed.system }));+"#;++ /// One plugin run. `hermetic` drops every ambient `AI_MEMORY_*` var, and+ /// `HOME`/`USERPROFILE`/`AI_MEMORY_HOME` point at the fixture, so the+ /// generated client cannot fall back to the developer's config, token+ /// file, or spool. The inherited `GIT_*` state goes too: the plugin shells+ /// out to `git rev-parse` for repo-root routing, and a `GIT_DIR` or+ /// `GIT_CONFIG_*` leaking in from the harness would point it somewhere+ /// outside the fixture. `PATH` and the rest of the environment stay so+ /// Node and git still resolve.+ fn run_plugin(dir: &Path, port: u16, owner: Option<&str>) -> Value {+ let mut command = hermetic("node");+ for (key, _) in std::env::vars_os() {+ if key.to_string_lossy().starts_with("GIT_") {+ command.env_remove(key);+ }+ }+ command+ .args(["--experimental-strip-types", "harness.ts"])+ .arg(port.to_string())+ .arg(dir)+ .current_dir(dir)+ .env("HOME", dir)+ .env("USERPROFILE", dir)+ .env("AI_MEMORY_HOME", dir)+ .env("AI_MEMORY_DATA_DIR", dir.join("data"))+ .env("GIT_CONFIG_GLOBAL", dir.join("absent-gitconfig"))+ .env("GIT_CONFIG_SYSTEM", dir.join("absent-gitconfig"));+ if let Some(owner) = owner {+ command.env("AI_MEMORY_CAPTURE_OWNER", owner);+ }+ let output = command.output().expect("run generated plugin");+ assert!(+ output.status.success(),+ "generated plugin run failed (owner={owner:?})\nstdout:\n{}\nstderr:\n{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr),+ );+ serde_json::from_slice(&output.stdout).expect("harness JSON")+ }++ fn spooled_entries(dir: &Path) -> usize {+ std::fs::read_dir(dir.join("data/hook-spool"))+ .map(|entries| entries.flatten().count())+ .unwrap_or(0)+ }++ fn delivered_events(run: &Value) -> Vec<&str> {+ run["events"]+ .as_array()+ .expect("events array")+ .iter()+ .map(|event| event.as_str().expect("event name"))+ .collect()+ }++ /// Retained fixture root: `keep()` hands back the path and cancels the+ /// delete-on-drop, so the generated plugin stays inspectable after a run.+ fn fixture_root() -> PathBuf {+ let dir = tempfile::tempdir().expect("fixture root").keep();+ eprintln!(+ "generated-plugin runtime fixture retained at {}",+ dir.display()+ );+ dir+ }++ #[test]+ fn generated_plugin_stops_capture_for_an_external_owner_but_still_fetches_context() {+ if !node_strip_types_available() {+ return;+ }+ let dir = fixture_root();+ let port = free_port();+ let plugin = render_opencode_plugin(&dir, &format!("http://127.0.0.1:{port}"));+ std::fs::write(dir.join("ai-memory.ts"), &plugin).unwrap();+ std::fs::write(dir.join("harness.ts"), HARNESS).unwrap();++ let owned = run_plugin(&dir, port, Some("orchestrator-a"));+ assert!(+ delivered_events(&owned).is_empty(),+ "owned run must POST nothing: {owned}"+ );+ assert_eq!(spooled_entries(&dir), 0, "owned run must spool nothing new");+ // Context delivery is a separate path and must survive the handover.+ assert_eq!(owned["handoffs"], 1, "{owned}");+ assert_eq!(owned["system"][0], "HANDOFF_SENTINEL", "{owned}");++ // Controls: unset and whitespace-only are not an owner, so the same+ // plugin and harness must capture normally. Without them the+ // assertions above could pass on a harness that never delivers.+ for (label, owner) in [("unset", None), ("whitespace", Some(" \t\n"))] {+ let captured = run_plugin(&dir, port, owner);+ let events = delivered_events(&captured);+ for expected in ["session-start", "user-prompt", "session-end"] {+ assert!(+ events.contains(&expected),+ "{label}: missing {expected} in {events:?}"+ );+ }+ assert_eq!(captured["handoffs"], 1, "{label}: {captured}");+ assert_eq!(+ captured["system"][0], "HANDOFF_SENTINEL",+ "{label}: {captured}"+ );+ }+ }+}diff --git a/crates/ai-memory-cli/tests/suite/main.rs b/crates/ai-memory-cli/tests/suite/main.rsindex 79e481e8..f98ddeb2 100644--- a/crates/ai-memory-cli/tests/suite/main.rs+++ b/crates/ai-memory-cli/tests/suite/main.rs@@ -12,6 +12,9 @@ mod backfill_failures;mod completions;mod doctor_e2e;mod e2e_support;+mod external_capture;+mod external_capture_powershell;+mod external_capture_ts;mod hook_drain;mod hook_payload;mod marker_scope;diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 0ebaf65f..8cea13da 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -238,6 +238,13 @@ extension seam, not a runtime plugin system: external processors must usethe existing HTTP/MCP APIs and cannot bypass the sanitizer, hookbackpressure, or single-writer SQLite actor.+An external lifecycle producer can set `AI_MEMORY_CAPTURE_OWNER` on the harness+process to suppress its installed native capture while retaining supported+handoff/briefing delivery and MCP. The producer uses `extension`/`source_event`+for provenance and stable, namespaced `ingest_key` values for retries. See the+[external capture contract](external-lifecycle.md) for batching, identity and+the limits of this cooperative process-scoped mode.+Lifecycle bodies have content limits independent of the 10 MiB HTTP requestlimit. User prompts and post-compaction summaries are capped UTF-8-safely at16 KiB; notification and tool excerpts are capped at 2 KB. Nativediff --git a/docs/companion-crates.md b/docs/companion-crates.mdindex 68005d60..ff798208 100644--- a/docs/companion-crates.md+++ b/docs/companion-crates.md@@ -23,6 +23,11 @@ the core workspace.## Integration rules for companions+Orchestrators that own their harness lifecycle can use the+[external capture contract](external-lifecycle.md) to suppress native observation+capture per execution while retaining handoff delivery and MCP retrieval.+Producer provenance and retry identity use the existing hook ingestion fields.+Companion projects may:- call the read-only `/api/v1` endpoints for workspaces, projects, pages,diff --git a/docs/external-lifecycle.md b/docs/external-lifecycle.mdnew file mode 100644index 00000000..7734c248--- /dev/null+++ b/docs/external-lifecycle.md@@ -0,0 +1,186 @@+# External lifecycle capture++An orchestrator that observes its agents can send lifecycle events to one shared+ai-memory server through `/hook/batch`. Framework adapters belong outside core;+the server continues to own storage, retrieval, consolidation and durable memory.++## Choose one capture path before launching++Set `AI_MEMORY_CAPTURE_OWNER` to your producer namespace in the environment of+the harness you launch, for example `example.runtime`. Any non-whitespace value+opts that process and its inheriting children into external capture. Unset,+empty and whitespace-only values preserve normal native capture.++```text+Orchestrator+ |-- launches harness with AI_MEMORY_CAPTURE_OWNER=example.runtime+ |-- records its lifecycle events with stable IDs+ `-- sends those events through POST /hook/batch++Harness+ |-- installed hooks keep delivering supported startup context+ `-- MCP keeps providing recall and deliberate memory writes+```++Updated native hook commands, POSIX/PowerShell hook bundles, and generated+OpenCode/OpenCode 2/OMP/Pi/OpenClaw integrations honor the variable. Reapply+`install-hooks` after upgrading to refresh staged scripts or generated code.+Older installations do not understand this context.++| Responsibility | With external capture |+|---|---|+| Native lifecycle observations | Skipped before spool, queue or POST |+| Native CLI hook drains and SessionStart backfill | Skipped |+| Supported handoff, briefing and inbox-notice delivery | Preserved |+| Native identity used by handoff/session-aware MCP | Preserved |+| MCP recall and deliberate writes | Unchanged |+| Existing repository capture policy | Unchanged; an opted-out repository stays opted out |++Claude Code receives context through SessionStart. Kimi Code receives it through+UserPromptSubmit because it discards SessionStart output. The same existing+delivery paths remain in use. Context delivery may register the receiving session+and claim a handoff; suppressing capture does not make it read-only. Harnesses+without automatic injection can still use `memory_handoff_accept` through MCP.+Do not also claim that handoff in the orchestrator if the hook owns delivery.++This is inherited process context, not server configuration, a security identity,+or a lease. Keep it out of the shared server's environment and global shell+configuration. Standalone launches without it continue to capture normally.+A runtime hosting multiple agents in one process applies the variable to all its+installed ai-memory integrations; it must manage finer capture ownership itself.++`ai-memory hook --check-capture` reports `external_capture: true` and+`admits_capture: false` when this context is active. It performs no ingestion or+handoff delivery. The producer namespace itself is not printed or authenticated.++## Reuse the public event contract++For a live harness, send its actual wire `agent` (such as `claude-code` or `codex`)+and native `session_id`. Use the same session ID, cwd, scope and authenticated+operator as its remaining native integration. The body's session ID takes+precedence over a query parameter. Replacing only the ingestion ID with an+orchestrator's logical agent ID separates it from native handoff/MCP identity.++Use explicit `workspace` and `project` for each event. Preserve canonical+lifecycle names (`session-start`, `user-prompt-submit`, `post-tool-use`,+`session-end`, etc.) and the supported harness payload shape. `session-end`+means the execution ended, not a turn completed. Sessions containing only+unknown events are not substantive sessions for automatic summaries.++Set `extension=<producer-namespace>` and an explicit `source_event=<event-name>`+for provenance. Both are needed to preserve the namespace on recognized events.+`extension` accepts up to 64 ASCII token characters; `source_event` accepts 128.+Letters, digits, `.`, `_`, `-` and `:` are allowed. These fields describe the+source; they do not expand the core event enum or retain arbitrary metadata.++Keep logical agents, parent/child relationships and workflow IDs in adapter-side+state for now. Do not repurpose native `agent_id` fields: some harness payloads+use them as subagent markers. The existing managed-workstream `managed_run`+field also has its own lease, ledger and handoff behavior.++### Stable retry identity++`ingest_key` is an existing project-scoped key, independent of `extension`.+Construct it once from stable event identity and persist it with the event before+delivery. Never hash prompt/tool content to decide whether events are equal.++For example, an adapter using Node can derive a 64-character key as follows:++```javascript+import { createHash } from "node:crypto";++function ingestKey({ producer, actor, agent, sessionId, sourceEvent, eventId }) {+ const identity = JSON.stringify([+ "external-capture-v1", producer, actor, agent,+ sessionId, sourceEvent, eventId,+ ]);+ return createHash("sha256").update(identity, "utf8").digest("hex");+}+```++Here `actor` is a stable adapter-side operator namespace, never a bearer token.+Include the coordinates within which `eventId` is unique. An adapter with+producer-wide unique event IDs may use a smaller tuple. Keep its encoding and+values stable across process restarts and implementation languages.++The same producer/event identity yields the same key on retry. Distinct event+IDs or producer namespaces yield distinct keys even for equal payloads. Reusing+the raw event ID as `ingest_key` under two extensions does **not** namespace it.+Keys accept 1 to 64 ASCII letters, digits, `_` or `-`. Malformed keys fall back+to unkeyed ingestion, so validate them before sending.++The server claims the key and observation in one transaction. A completed replay+is skipped; a pending replay resumes downstream work without inserting another+observation. Keys expire after **30 days**. This is bounded retry protection, not+permanent deduplication or an exactly-once guarantee for every wiki side effect.++### Ordered batches and recovery++A batch uses the existing array of `{url, body}` items:++```json+[+ {+ "url": "/hook?event=user-prompt-submit&agent=claude-code&workspace=team&project=app&extension=example.runtime&source_event=user-prompt-submit&ingest_key=example-runtime-run-17-prompt-4",+ "body": {+ "session_id": "native-session-17",+ "cwd": "/work/app",+ "prompt": "Continue the parser fix."+ }+ }+]+```++Send this JSON to `POST /hook/batch` with the normal bearer authentication. The+URL in each item supplies the event query; the server does not fetch that URL.+The short key above assumes the runtime assigned a producer-wide unique run ID.+Use the tuple recipe when event IDs have narrower scope.++- At most 256 items fit in a batch. Existing body limits and sanitization apply.+- Batch processing happens inline, in array order. There is no global ordering+ across concurrent requests and no all-or-nothing transaction for a batch.+- Prefer `accepted_indices` when present. Otherwise `accepted` is the contiguous+ acknowledged prefix. Preserve every unacknowledged item for retry.+- A rate-limited source can be skipped while other sources advance. Inspect+ acknowledgements even on HTTP 429 or a partial failure; `failed_index` identifies+ a processing failure after earlier skips. An acknowledgement can also mean a+ deliberate policy drop, not a new observation.+- On a timeout or lost response, retry unchanged items and keys. Back off on+ saturation rather than opening an unbounded number of requests.++Maintain a durable producer-side queue if offline/restart recovery matters.+Flush earlier events for a session before sending its terminal event. Serialize+delivery within a session where order matters; different sessions can share the+server concurrently. Late observations and a later terminal event use existing+resumed-session behavior. Stopping a parent does not synthesize endings for its+children; the orchestrator must report those lifecycle transitions.++`POST /hook` remains available, but its `202` response precedes persistence.+Prefer `/hook/batch` when the producer needs an inline processing acknowledgement.++## Boundaries++The variable does not erase or cancel existing spool entries. Explicit+`hook-drain` and other standalone hooks can still deliver that backlog.+Generated integrations also retain their existing queue disposal behavior,+which can drain previously captured events. Choose the capture owner before+the execution's first event; switching midway cannot deduplicate events already+produced by independent paths.++Manual backfill, the importer, `finalize-session` and managed transcript import+through `ai-memory run` retain their existing behavior. Do not combine them as+independent lifecycle producers for the same execution. External capture does+not disable native harness transcript files or other vendors' hooks.++Auth, owner checks, admission rules and sanitization still apply. All items in+one batch share one authenticated identity; separate batches by operator when+representing multiple users. `extension` is self-declared provenance and the+capture variable grants no permissions. ai-memory has a shared single-tenant+wiki with multi-user attribution, not per-project RBAC or producer isolation.+See [multi-user attribution](users.md).++No framework adapter, workflow engine, generic plugin runtime or OpenTelemetry+collector is introduced. A future OpenTelemetry adapter can map conversation+and tool-call identities at the boundary. Keep ingestion producer identity+separate from the model provider and preserve the native session identity needed+by ai-memory's existing integrations.diff --git a/hooks/_lib.sh b/hooks/_lib.shindex fa01573e..74ebd632 100644--- a/hooks/_lib.sh+++ b/hooks/_lib.sh@@ -477,7 +477,25 @@ ai_memory_url_with_ingest_key() {esac}+# AI_MEMORY_CAPTURE_OWNER names an external producer of this session's capture+# events. Non-blank claims ownership; unset, empty and whitespace-only keep+# capture on. The value is only ever tested, never printed or sent.+ai_memory_capture_owned_externally() {+ case "${AI_MEMORY_CAPTURE_OWNER:-}" in+ *[![:space:]]*) return 0 ;;+ *) return 1 ;;+ esac+}+ai_memory_post_hook() {+ # Every shell hook produces its event here, and the spool and piggyback+ # drain hang off the result below, so this one check suppresses all three.+ # Delivery is untouched: an explicit ai_memory_drain_spool still ships the+ # backlog. Stdin is drained so the caller's pipe does not take an EPIPE.+ if ai_memory_capture_owned_externally; then+ cat >/dev/null 2>&1 || true+ return 0+ fi_amurl=$(ai_memory_url_with_ingest_key "$1")_ambody=$(cat)_amhdr=$(ai_memory_auth_header_file || printf '')diff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1index a4fd6848..ca5d176a 100644--- a/hooks/lib/ai-memory-hook.ps1+++ b/hooks/lib/ai-memory-hook.ps1@@ -288,6 +288,14 @@ function Test-AiMemoryAntigravityInitialInvocation {}}+# Parity with `ai_memory_capture_owned_externally` in hooks/_lib.sh:+# AI_MEMORY_CAPTURE_OWNER names an external producer of this session's capture+# events. Non-blank claims ownership; unset, empty and whitespace-only keep+# capture on. The value is only ever tested, never written to output.+function Test-AiMemoryCaptureOwnedExternally {+ return (-not [string]::IsNullOrWhiteSpace($env:AI_MEMORY_CAPTURE_OWNER))+}+function Invoke-AiMemoryHook {param([Parameter(Mandatory = $true)] [string] $Event,@@ -331,17 +339,22 @@ function Invoke-AiMemoryHook {$Headers["Authorization"] = "Bearer $env:AI_MEMORY_AUTH_TOKEN"}- $BodyBytes = [Text.Encoding]::UTF8.GetBytes($Payload)- try {- Invoke-WebRequest `- -UseBasicParsing `- -TimeoutSec 3 `- -Method Post `- -Uri "$Server/hook?event=$Event&agent=$Agent$QS$SessionQS" `- -Headers $Headers `- -ContentType "application/json; charset=utf-8" `- -Body $BodyBytes | Out-Null- } catch {+ # This POST is the only producer on this path (no spool, no drain here).+ # Session identity and the handoff/briefing GET below are delivery, so an+ # external owner leaves them, and the stdout contract, alone.+ if (-not (Test-AiMemoryCaptureOwnedExternally)) {+ $BodyBytes = [Text.Encoding]::UTF8.GetBytes($Payload)+ try {+ Invoke-WebRequest `+ -UseBasicParsing `+ -TimeoutSec 3 `+ -Method Post `+ -Uri "$Server/hook?event=$Event&agent=$Agent$QS$SessionQS" `+ -Headers $Headers `+ -ContentType "application/json; charset=utf-8" `+ -Body $BodyBytes | Out-Null+ } catch {+ }}if ($Agent -eq "devin" -and $Event -eq "session-end") {Clear-AiMemorySessionId -Agent $Agentdiff --git a/tests/hooks/test_lib.sh b/tests/hooks/test_lib.shindex 4a8a4743..b7bace2a 100755--- a/tests/hooks/test_lib.sh+++ b/tests/hooks/test_lib.sh@@ -399,6 +399,116 @@ assert_eq "post_hook spools an undelivered event" "1" \unset AI_MEMORY_DATA_DIR+# --- external capture ownership (AI_MEMORY_CAPTURE_OWNER) -------------+# A wrapper, extension or managed launcher that already produces this+# session's capture events announces itself with AI_MEMORY_CAPTURE_OWNER.+# The bundle must then stop PRODUCING events (no POST, no spool entry, no+# piggyback drain) while still DELIVERING: the synchronous handoff GET keeps+# working, a backlog already on disk stays put, and an explicit drain still+# ships it. Every case below runs the real `ai_memory_post_hook` /+# `ai_memory_get_handoff` / `ai_memory_drain_spool` path with curl stubbed,+# so what is asserted is what the shipped functions do.++# Stub curl: log method + URL, answer 200 to a POST and a body to a GET.+# Only `--data-binary @-` reads the body from stdin. Consuming it for every+# POST would block on an inherited terminal stdin the moment a caller passes+# `@file` or an inline body, which the real curl never touches.+curl() {+ _tm=GET+ _tu=""+ _tdata=""+ while [ "$#" -gt 0 ]; do+ case "$1" in+ -X) shift; [ "$#" -gt 0 ] || break; _tm="$1" ;;+ --data-binary) shift; [ "$#" -gt 0 ] || break; _tdata="$1" ;;+ --data-binary=*) _tdata="${1#--data-binary=}" ;;+ http://* | https://*) _tu="$1" ;;+ esac+ shift+ done+ if [ "$_tdata" = "@-" ]; then+ cat >/dev/null+ fi+ if [ "$_tm" = POST ]; then+ printf 'POST %s\n' "$_tu" >>"$CURL_LOG"+ printf '200'+ else+ printf 'GET %s\n' "$_tu" >>"$CURL_LOG"+ printf 'HANDOFF BODY'+ fi+ return 0+}++# Each case gets its own data dir, so the spool and the curl log start empty+# without anything having to be cleared between cases.+owner_case() {+ AI_MEMORY_DATA_DIR="$TMP/owner-$1"+ export AI_MEMORY_DATA_DIR+ mkdir -p "$AI_MEMORY_DATA_DIR"+ CURL_LOG="$AI_MEMORY_DATA_DIR/curl.log"+ touch "$CURL_LOG"+}+owner_requests() { awk 'END { print NR + 0 }' "$CURL_LOG"; }+owner_posts() { awk '/^POST /{ n++ } END { print n + 0 }' "$CURL_LOG"; }+owner_spooled() { ls "$AI_MEMORY_DATA_DIR/hook-spool/"*.json 2>/dev/null | wc -l | tr -d ' '; }++# 1. Owner set: an event produced now is dropped whole, and the backlog that+# was already queued is neither extended nor drained behind it.+owner_case suppressed+ai_memory_spool_event "http://127.0.0.1:1/hook?event=stop&agent=cursor" '{"e":"backlog"}'+BACKLOG=$(owner_spooled)+assert_eq "owner: backlog is queued before the gate" "1" "$BACKLOG"+AI_MEMORY_CAPTURE_OWNER="external-runner"+export AI_MEMORY_CAPTURE_OWNER+printf '%s' '{"e":"owned"}' \+ | ai_memory_post_hook "http://127.0.0.1:49374/hook?event=post-tool-use&agent=cursor" >/dev/null 2>&1+assert_eq "owner: post_hook sends nothing" "0" "$(owner_requests)"+assert_eq "owner: post_hook spools nothing and drains nothing" "$BACKLOG" "$(owner_spooled)"++# 2. Delivery is untouched: the handoff GET still runs and still returns.+HANDOFF=$(set +e; ai_memory_get_handoff "http://127.0.0.1:49374/handoff?agent=cursor")+assert_eq "owner: handoff GET still delivered" "HANDOFF BODY" "$HANDOFF"+assert_eq "owner: the GET is the only request" "1" "$(owner_requests)"+assert_eq "owner: still no POST" "0" "$(owner_posts)"++# 3. Standalone control: with no owner the same call POSTs as before.+unset AI_MEMORY_CAPTURE_OWNER+owner_case control+printf '%s' '{"e":"control"}' \+ | ai_memory_post_hook "http://127.0.0.1:49374/hook?event=post-tool-use&agent=cursor" >/dev/null 2>&1+assert_eq "no owner: post_hook POSTs" "1" "$(owner_posts)"++# 4. An exported-but-blank variable must not disable capture: empty and+# whitespace-only keep the default behaviour.+AI_MEMORY_CAPTURE_OWNER=""+export AI_MEMORY_CAPTURE_OWNER+owner_case empty+printf '%s' '{"e":"empty"}' \+ | ai_memory_post_hook "http://127.0.0.1:49374/hook?event=post-tool-use&agent=cursor" >/dev/null 2>&1+assert_eq "empty owner: post_hook POSTs" "1" "$(owner_posts)"++AI_MEMORY_CAPTURE_OWNER=$(printf ' \t ')+export AI_MEMORY_CAPTURE_OWNER+owner_case whitespace+printf '%s' '{"e":"blank"}' \+ | ai_memory_post_hook "http://127.0.0.1:49374/hook?event=post-tool-use&agent=cursor" >/dev/null 2>&1+assert_eq "whitespace owner: post_hook POSTs" "1" "$(owner_posts)"++# 5. An EXPLICIT drain is delivery, not production: it must still ship a+# queued event while the owner is set, and retire it on a 2xx.+unset AI_MEMORY_CAPTURE_OWNER+owner_case drain+ai_memory_spool_event "http://127.0.0.1:49374/hook?event=stop&agent=cursor" '{"e":"pending"}'+AI_MEMORY_CAPTURE_OWNER="external-runner"+export AI_MEMORY_CAPTURE_OWNER+ai_memory_drain_spool 64 >/dev/null 2>&1+assert_eq "owner: explicit drain still delivers the backlog" "1" "$(owner_posts)"+assert_eq "owner: delivered entry is retired" "0" "$(owner_spooled)"++unset -f curl+unset AI_MEMORY_CAPTURE_OWNER+unset AI_MEMORY_DATA_DIR+# --- summary ----------------------------------------------------------printf '\n%d passed, %d failed\n' "$PASS" "$FAIL"[ "$FAIL" -eq 0 ]