Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat: add managed cross-harness workstreams
AkitaOnRails5c4469df135d
diff --git a/AGENTS.md b/AGENTS.mdindex 9c55d453..6785f7ee 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -18,10 +18,11 @@ forward the real agent session id automatically; pass explicit`workspace` + `project` / `scopes`, or use a session-aware bridge thatforwards the lifecycle-hook session id on MCP calls.-**Lifecycle hooks already capture every prompt and tool call-automatically.** Do not manually write routine notes. Only write durable-memory when the user explicitly asks to remember or annotate something-permanently.+**Lifecycle hooks already capture sanitized, bounded prompt and tool-lifecycle+observations automatically.** They are not complete native transcripts;+managed `ai-memory run` launches add the portable visible-event ledger. Do not+manually write routine notes. Only write durable memory when the user explicitly asks+to remember or annotate something permanently.### Use the installed ai-memory Agent Skillsdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 312ab7c4..727b10e8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added+- Optional managed cross-harness workstreams via `ai-memory run` for Claude+ Code, Codex, OpenCode, Pi, and OMP. Direct harness launches retain the legacy+ hook/handoff behavior. Managed launches transparently create or resume one+ native session per harness, pass all harness argv through without a `--`+ separator, inject unseen portable context at SessionStart, import visible+ native transcript tails through read-only adapters, and record non-mutating+ repository checkpoints. A lease prevents concurrent writers; deterministic+ event ids, incremental cursors, immutable sanitized JSONL segments, and+ batched idempotent imports make retry and crash recovery explicit. Hidden+ reasoning and private provider records are excluded with loss annotations.+ `ai-memory workstream-search` searches history older than the bounded startup+ packet. The Linux/macOS Docker wrapper uses a checksum-verified cached native+ client for `run` so host agent executables and transcript stores remain+ accessible. A separate opt-in local acceptance runner validates real+ cross-harness delivery and native resume without adding credentialed model+ calls to CI. Generated OpenCode/Pi/OMP integrations reserve managed context+ acknowledgement for their model-visible injection path; OpenCode caches the+ packet per native session so auxiliary model requests cannot consume it+ before the main coding turn. Pi/OMP native `--session-dir` overrides are+ honored by the importer, as are native store environment overrides for all+ five adapters. This includes complete atomic-write temp transcripts left by+ a Pi-family process that exits before its final rename.+### Changed- Configuring the hosted `anthropic` or `openai` provider without an explicitmodel now selects the documented recommended defaults, `claude-haiku-4-5`diff --git a/Cargo.lock b/Cargo.lockindex 36a050a7..4f175bf6 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -41,6 +41,7 @@ dependencies = ["ai-memory-store","ai-memory-web","ai-memory-wiki",+ "ai-memory-workstream","anyhow","axum","base64",@@ -145,6 +146,7 @@ dependencies = ["serde","serde_json","serde_urlencoded",+ "sha2","tempfile","thiserror 2.0.18","tokio",@@ -278,6 +280,21 @@ dependencies = ["winapi-util",]+[[package]]+name = "ai-memory-workstream"+version = "1.15.0"+dependencies = [+ "ai-memory-core",+ "anyhow",+ "rusqlite",+ "serde",+ "serde_json",+ "sha2",+ "tempfile",+ "tokio",+ "uuid",+]+[[package]]name = "android_system_properties"version = "0.1.5"diff --git a/Cargo.toml b/Cargo.tomlindex 63f2af11..c7e11e2a 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -10,6 +10,7 @@ members = ["crates/ai-memory-consolidate","crates/ai-memory-web","crates/ai-memory-cli",+ "crates/ai-memory-workstream",# Live A/B harness — not part of the shipped binary, but in# the workspace so it shares deps + builds with the rest."evals",@@ -33,6 +34,7 @@ ai-memory-hooks = { path = "crates/ai-memory-hooks", version = "1.15.0" }ai-memory-llm = { path = "crates/ai-memory-llm", version = "1.15.0" }ai-memory-consolidate = { path = "crates/ai-memory-consolidate", version = "1.15.0" }ai-memory-web = { path = "crates/ai-memory-web", version = "1.15.0" }+ai-memory-workstream = { path = "crates/ai-memory-workstream", version = "1.15.0" }# (Workspace shared deps follow below)diff --git a/README.md b/README.mdindex e5799885..b7256d4b 100644--- a/README.md+++ b/README.md@@ -30,6 +30,7 @@| Gemini CLI | Supported | MCP config + lifecycle hooks. || Oh My Pi / OMP | Supported | Use `--client omp` / `--agent omp` (or `oh-my-pi`) for native `.omp` MCP config + TypeScript extension; generated extension enforces capture exclusions. || Pi | Supported | Generated `~/.pi/agent/extensions/ai-memory.ts` extension provides lifecycle capture and an HTTP MCP bridge; generated extension enforces capture exclusions. |+| Managed workstreams | Opt-in | `ai-memory run` provides transparent cross-harness continuity for Claude Code, Codex, OpenCode, Pi, and OMP. Direct launches remain unchanged. See [`docs/managed-workstreams.md`](docs/managed-workstreams.md). || Claude Desktop | MCP-only | Uses `mcp-remote`; no lifecycle hooks. || OpenClaw | Supported | MCP config + native plugin lifecycle hooks; generated plugin enforces capture exclusions. || Antigravity CLI | Supported | MCP config (`serverUrl`) + lifecycle hooks (`agy` alias). |@@ -43,12 +44,12 @@## What it is-LLM coding agents lose all context when a session ends. ai-memory-gives them a shared, persistent wiki: every prompt, tool call, and-decision is captured automatically; when a session ends, the relevant-pages get rewritten as a coherent narrative; when the next agent-starts (Claude Code, Codex, OpenCode, …) it sees a handoff with-"where you left off" already prepended.+LLM coding agents lose context when a session ends. ai-memory gives them a+shared, persistent wiki compiled from sanitized lifecycle observations. When a+session ends, relevant observations become a coherent summary; the next agent+receives a bounded handoff. Optional `ai-memory run` launches add a portable+visible-event ledger and native per-harness resume for higher-fidelity+cross-harness continuity.The wiki is plain markdown in a git repo - `grep`-able, openable inObsidian, backed up with `rsync`. No vector database to babysit, no@@ -58,8 +59,13 @@ priors are at the [bottom](#influences-and-prior-art).## Key features-- **Zero-friction capture.** Lifecycle hooks fire-and-forget every- prompt + tool call + session boundary. You never type `write_note`.+- **Zero-friction lifecycle capture.** Hooks fire-and-forget bounded,+ sanitized prompt, tool-lifecycle, and session-boundary observations. Direct+ launches keep this lightweight path; it is not a complete native transcript.+- **Opt-in managed workstreams.** `ai-memory run claude`, then `ai-memory run+ codex --yolo`, transparently resumes one logical workstream with native+ per-harness sessions, a portable visible-event ledger, and full-ledger search.+ Native arguments pass through unchanged; direct agent commands are unaffected.- **Per-repository capture exclusions.** A nearest-marker `[capture]``ignore_paths` policy drops matching recognized file-tool events before theyreach the local spool or server. See [the capture policy reference](docs/marker-file.md#capture-exclusions).@@ -605,7 +611,7 @@ One Rust binary runs an MCP/HTTP server and owns one data directory:```text<data_dir>/├── wiki/ # markdown source of truth, git-versioned-├── raw/ # immutable session log archive+├── raw/ # immutable sanitized managed-workstream transcript segments├── db/ # SQLite indexes, including FTS5 and embeddings├── models/ # reserved for local embedding models└── logs/ # rolling tracing output@@ -625,6 +631,7 @@ diagram, crate breakdown, schema notes, and invariants.|---|---|| [`docs/install.md`](docs/install.md) | **Installation cookbook.** Every agent CLI, every alternative (curl, source build, no-docker, no-auth), and the server-on-a-different-machine (homelab/LAN) walkthrough. Read after the Quick start if your setup doesn't match the happy path. || [`docs/usage.md`](docs/usage.md) | Handoffs, proactive memory queries, slim routing snippet + managed Agent Skills, migration from other memory tools, web UI, raw-wiki inspection, and rules-vs-facts workflow. |+| [`docs/managed-workstreams.md`](docs/managed-workstreams.md) | Optional `ai-memory run` continuity across Claude Code, Codex, OpenCode, Pi, and OMP: transparent native resume, argument forwarding, ledger search, privacy, and recovery. || [`docs/marker-file.md`](docs/marker-file.md) | `.ai-memory.toml` workspace/project routing for multi-client trees, mono-repos, worktrees, and work/personal separation. || [`docs/auto-scope.md`](docs/auto-scope.md) | `[auto_scope]` modes for shared servers: default single-slot routing, session-aware isolation, and multi-user `per_actor` behavior. || [`docs/macos.md`](docs/macos.md) | macOS install paths: native release binary (recommended), source build, the Docker wrapper, hook-platform notes, and current macOS limitations. |diff --git a/bin/ai-memory b/bin/ai-memoryindex 3806b448..d46ff799 100755--- a/bin/ai-memory+++ b/bin/ai-memory@@ -9,6 +9,7 @@## Special wrapper-only subcommands (not forwarded to the binary):# ai-memory upgrade Pull the latest image + remind to re-stage hooks.+# ai-memory run ... Use a cached native client so it can exec host agents.## Env overrides:# AI_MEMORY_IMAGE docker image (default: akitaonrails/ai-memory:latest)@@ -21,6 +22,7 @@# COPILOT_GITHUB_TOKEN GitHub token for AI_MEMORY_LLM_PROVIDER=copilot# AI_MEMORY_NO_TTY=1 force non-interactive even on a real tty# AI_MEMORY_NO_VERSION_CHECK=1 skip the once-per-day update check+# AI_MEMORY_NATIVE_BIN native ai-memory binary used for `run` (optional)set -euo pipefailIMAGE="${AI_MEMORY_IMAGE:-akitaonrails/ai-memory:latest}"@@ -109,6 +111,7 @@ cmd_upgrade() {fiecho "→ pulling ${IMAGE}""${DOCKER}" pull "${IMAGE}"+ rm -f "${CACHE_DIR}/native-runner/last-check"local found_agents=()if [ -d "${HOOKS_STAGE_DIR}" ]; then@@ -194,6 +197,92 @@ cmd_upgrade() {touch "${VERSION_CHECK_FILE}"}+# `ai-memory run` must execute on the host: Claude/Codex/OpenCode and their+# native transcript stores are host resources, not contents of the helper+# container. Keep a checksum-verified release client beside the wrapper cache.+native_run_binary() {+ if [ -n "${AI_MEMORY_NATIVE_BIN:-}" ]; then+ [ -x "${AI_MEMORY_NATIVE_BIN}" ] || {+ echo "ai-memory: AI_MEMORY_NATIVE_BIN is not executable: ${AI_MEMORY_NATIVE_BIN}" >&2+ return 1+ }+ printf '%s\n' "${AI_MEMORY_NATIVE_BIN}"+ return 0+ fi++ local os arch artifact base native_dir binary archive check_file need_refresh remote_sum local_sum tmp+ case "$(uname -s 2>/dev/null || true)" in+ Linux) os="linux" ;;+ Darwin) os="macos" ;;+ *)+ echo "ai-memory: the Docker wrapper cannot provide managed host launches on this OS" >&2+ echo "install the native release binary and run: ai-memory run <harness> ..." >&2+ return 1+ ;;+ esac+ case "$(uname -m 2>/dev/null || true)" in+ x86_64 | amd64) arch="x86_64" ;;+ aarch64 | arm64) arch="aarch64" ;;+ *)+ echo "ai-memory: no managed-run release binary is published for $(uname -m)" >&2+ return 1+ ;;+ esac+ artifact="ai-memory-${os}-${arch}"+ base="https://github.com/akitaonrails/ai-memory/releases/latest/download/${artifact}.tar.gz"+ native_dir="${CACHE_DIR}/native-runner"+ binary="${native_dir}/ai-memory"+ archive="${native_dir}/${artifact}.tar.gz"+ check_file="${native_dir}/last-check"+ mkdir -p "${native_dir}"++ need_refresh=0+ [ -x "${binary}" ] && [ -f "${archive}" ] || need_refresh=1+ if [ "${need_refresh}" -eq 0 ] && { [ ! -f "${check_file}" ] || [ -n "$(find "${check_file}" -mtime +0 2>/dev/null)" ]; }; then+ remote_sum=$(curl -fsSL "${base}.sha256" 2>/dev/null | awk 'NR == 1 { print $1 }' || true)+ if command -v sha256sum >/dev/null 2>&1; then+ local_sum=$(sha256sum "${archive}" | awk '{ print $1 }')+ else+ local_sum=$(shasum -a 256 "${archive}" | awk '{ print $1 }')+ fi+ if [ -n "${remote_sum}" ] && [ "${remote_sum}" != "${local_sum}" ]; then+ need_refresh=1+ fi+ touch "${check_file}"+ fi++ if [ "${need_refresh}" -eq 1 ]; then+ command -v curl >/dev/null 2>&1 || {+ echo "ai-memory: curl is required to install the native managed-run client" >&2+ return 1+ }+ tmp="${native_dir}/.install-$$"+ rm -rf "${tmp}"+ mkdir -p "${tmp}"+ echo "ai-memory: installing checksum-verified native managed-run client (${artifact})" >&2+ curl -fsSL "${base}" -o "${tmp}/${artifact}.tar.gz"+ curl -fsSL "${base}.sha256" -o "${tmp}/${artifact}.tar.gz.sha256"+ if command -v sha256sum >/dev/null 2>&1; then+ (cd "${tmp}" && sha256sum -c "${artifact}.tar.gz.sha256" >/dev/null)+ else+ remote_sum=$(awk 'NR == 1 { print $1 }' "${tmp}/${artifact}.tar.gz.sha256")+ local_sum=$(shasum -a 256 "${tmp}/${artifact}.tar.gz" | awk '{ print $1 }')+ [ "${remote_sum}" = "${local_sum}" ] || {+ echo "ai-memory: native managed-run client checksum mismatch" >&2+ rm -rf "${tmp}"+ return 1+ }+ fi+ tar -xzf "${tmp}/${artifact}.tar.gz" -C "${tmp}"+ [ -x "${tmp}/ai-memory" ] || chmod +x "${tmp}/ai-memory"+ mv "${tmp}/${artifact}.tar.gz" "${archive}"+ mv "${tmp}/ai-memory" "${binary}"+ rm -rf "${tmp}"+ touch "${check_file}"+ fi+ printf '%s\n' "${binary}"+}+# ---- intercept wrapper-only subcommands ----------------------------------case "${1:-}" in@@ -202,6 +291,10 @@ case "${1:-}" incmd_upgradeexit 0;;+ run)+ NATIVE_RUN_BIN=$(native_run_binary)+ exec "${NATIVE_RUN_BIN}" "$@"+ ;;esac# ---- normal pass-through to the binary inside docker ---------------------@@ -233,6 +326,7 @@ for var in \AI_MEMORY_EMBEDDING_BASE_URL \AI_MEMORY_EMBEDDING_DIM \AI_MEMORY_ALLOWED_HOSTS \+ AI_MEMORY_WORKSTREAM_ID \AI_MEMORY_HOOK_PLATFORM \AI_MEMORY_HOOKS_HOST_ROOT \ANTHROPIC_API_KEY \diff --git a/crates/ai-memory-cli/Cargo.toml b/crates/ai-memory-cli/Cargo.tomlindex c269c047..78502b29 100644--- a/crates/ai-memory-cli/Cargo.toml+++ b/crates/ai-memory-cli/Cargo.toml@@ -20,6 +20,7 @@ ai-memory-llm.workspace = trueai-memory-mcp.workspace = trueai-memory-store.workspace = trueai-memory-web.workspace = true+ai-memory-workstream.workspace = trueai-memory-wiki.workspace = truereqwest.workspace = truesecrecy.workspace = truediff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 9e006b5b..0f5791fd 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -1,5 +1,6 @@//! Command-line interface definition (clap derive).+use std::ffi::OsString;use std::path::PathBuf;use clap::{Args, Parser, Subcommand};@@ -31,6 +32,11 @@ pub enum Command {Init(InitArgs),/// Print runtime status (counts, paths, version).Status(StatusArgs),+ /// Launch an agent in an opt-in, cross-harness managed workstream.+ /// Every argument after the harness name is forwarded unchanged.+ Run(RunArgs),+ /// Search the complete visible event ledger for a managed workstream.+ WorkstreamSearch(WorkstreamSearchArgs),/// Audit the store for likely cross-project contamination (read-only,/// SQL-only). Flags sessions whose cwd resolves to a different project and/// observations whose project disagrees with their session.@@ -154,6 +160,70 @@ pub enum Command {User(UserArgs),}+/// Arguments for `run`. Wrapper-owned flags must precede `harness`; the+/// trailing native argv is deliberately opaque to clap.+#[derive(Debug, Args)]+#[command(trailing_var_arg = true)]+pub struct RunArgs {+ /// Workspace containing the managed workstream.+ #[arg(long, default_value = "default")]+ pub workspace: String,+ /// Project override. Defaults to the current repository project.+ #[arg(long)]+ pub project: Option<String>,+ /// Select an existing named workstream instead of the current one.+ #[arg(long, conflicts_with = "new_workstream")]+ pub workstream: Option<String>,+ /// Create and select a fresh named workstream.+ #[arg(long = "new", conflicts_with = "workstream")]+ pub new_workstream: Option<String>,+ /// Override the native harness executable path.+ #[arg(long)]+ pub executable: Option<PathBuf>,+ /// Agent harness to launch.+ #[arg(value_enum)]+ pub harness: RunHarnessChoice,+ /// Native harness arguments, forwarded byte-for-byte and in order.+ #[arg(allow_hyphen_values = true, trailing_var_arg = true)]+ pub native_args: Vec<OsString>,+}++/// Harnesses supported by managed workstreams.+#[derive(Debug, Clone, Copy, clap::ValueEnum)]+pub enum RunHarnessChoice {+ /// Anthropic Claude Code (`claude`).+ #[value(alias = "claude-code")]+ Claude,+ /// OpenAI Codex CLI.+ Codex,+ /// OpenCode.+ #[value(name = "opencode", alias = "open-code")]+ OpenCode,+ /// Pi coding agent.+ Pi,+ /// Oh My Pi.+ #[value(alias = "oh-my-pi")]+ Omp,+}++/// Arguments for `workstream-search`.+#[derive(Debug, Args)]+pub struct WorkstreamSearchArgs {+ /// Natural-language or FTS query. Omit to show the newest events.+ #[arg(default_value = "")]+ pub query: String,+ /// Workstream to search. Managed child processes receive this through the+ /// environment, so agents normally do not need to pass it.+ #[arg(long, env = "AI_MEMORY_WORKSTREAM_ID")]+ pub workstream_id: ai_memory_core::WorkstreamId,+ /// Maximum events to return.+ #[arg(long, default_value_t = 20, value_parser = clap::value_parser!(u8).range(1..=100))]+ pub limit: u8,+ /// Emit JSON instead of readable event blocks.+ #[arg(long)]+ pub json: bool,+}+/// Arguments for `user`.#[derive(Debug, Args)]pub struct UserArgs {diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rsindex e7870571..e8c746d7 100644--- a/crates/ai-memory-cli/src/commands/hook.rs+++ b/crates/ai-memory-cli/src/commands/hook.rs@@ -16,7 +16,7 @@ use std::io::Read;use std::path::{Path, PathBuf};use std::time::Duration;-use ai_memory_core::{AgentKind, SessionId};+use ai_memory_core::{AgentKind, ManagedRunId, SessionId};use ai_memory_hooks::capture_policy::metadata_only_body;use ai_memory_hooks::{CaptureDisposition, PolicyState};use ai_memory_llm::OidcToken;@@ -48,6 +48,7 @@ const START_BUDGET_ENV: &str = "AI_MEMORY_HOOK_START_BUDGET_MINUTES";const BACKGROUND_DRAIN_BUDGET_ENV: &str = "AI_MEMORY_HOOK_BACKGROUND_DRAIN_BUDGET_MINUTES";const INCREMENTAL_THRESHOLD_ENV: &str = "AI_MEMORY_HOOK_INCREMENTAL_THRESHOLD";+const MANAGED_RUN_ENV: &str = "AI_MEMORY_RUN_ID";/// 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;@@ -253,6 +254,18 @@ fn env_lookup(name: &str) -> Option<String> {std::env::var(name).ok()}+fn managed_run_query_suffix_with(mut env_lookup: impl FnMut(&str) -> Option<String>) -> String {+ env_lookup(MANAGED_RUN_ENV)+ .filter(|value| value.parse::<ManagedRunId>().is_ok())+ .map_or_else(String::new, |value| {+ format!("&managed_run={}", url_encode(&value))+ })+}++fn managed_run_query_suffix() -> String {+ managed_run_query_suffix_with(env_lookup)+}+/// Read a positive-integer minute override from `name`, falling back to the/// built-in short default for missing / empty / non-numeric / zero values. Clamp/// large values so a typo cannot block a hook boundary for hours or days.@@ -376,7 +389,8 @@ wherelet dd = resolve_data_dir(data_dir.as_deref());let spool = hook_spool::spool_dir(&dd);let session_qs = session_id_query_suffix(&dd, &args.agent, &args.event, &json);- let hook_qs = format!("{qs}{session_qs}");+ let managed_qs = managed_run_query_suffix();+ let hook_qs = format!("{qs}{session_qs}{managed_qs}");// Spool THIS event — an instant local write, never the network. The auth// mode is decided without a round-trip: an explicit `--auth-token` is@@ -444,7 +458,15 @@ whereif AgentKind::from_wire(&args.agent).session_start_injects_handoff() {let client = build_client();let bearer = hook_spool::resolve_bearer(&client, &dd, args.auth_token.as_deref()).await;- let handoff_url = format!("{base}/handoff?agent={}{qs}", args.agent);+ let native_session_qs = canonical_session_id+ .as_deref()+ .map_or_else(String::new, |session_id| {+ format!("&session_id={}", url_encode(session_id))+ });+ let handoff_url = format!(+ "{base}/handoff?agent={}{qs}{managed_qs}{native_session_qs}",+ args.agent+ );if let Some(handoff) =get_handoff(&client, &handoff_url, bearer.as_deref(), handoff_timeout()).await{diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 958e66eb..8dca4ff0 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -1514,6 +1514,8 @@ fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {return format!("{TS_TOML_FLAG}\n{}",r#"function applyMarkerParams(url: URL, cwd: string | undefined): void {+ const managedRun = process.env.AI_MEMORY_RUN_ID;+ if (managedRun) url.searchParams.set("managed_run", managedRun);const marker = findMarker(cwd);if (!marker || !cwd) return;url.searchParams.set("cwd", cwd);@@ -1543,6 +1545,8 @@ fn ts_apply_marker_params(default_strategy: Option<&str>) -> String {);};let body = r#"function applyMarkerParams(url: URL, cwd: string | undefined): void {+ const managedRun = process.env.AI_MEMORY_RUN_ID;+ if (managedRun) url.searchParams.set("managed_run", managedRun);if (!cwd) return;url.searchParams.set("cwd", cwd);let workspace: string | undefined;@@ -1788,7 +1792,7 @@ function textFromParts(parts: unknown): string {{const sessionCwds = new Map<string, string>();const startedSessions = new Set<string>();-const handoffChecked = new Set<string>();+const handoffFetches = new Map<string, Promise<string | undefined>>();const preCompactLast = new Map<string, number>();function cwdFor(id: string | undefined, directory: string): string {{@@ -1803,7 +1807,12 @@ function startSession(id: string | undefined, cwd: string, extra: Record<string,if (!id || startedSessions.has(id)) return;startedSessions.add(id);rememberCwd(id, cwd);- postHook("session-start", {{ sessionID: id, cwd, ...extra }});+ // Generated integrations inject through fetchHandoff below. In managed mode+ // a queued SessionStart response is not model-visible and must not consume+ // the workstream context before that synchronous fetch receives it.+ if (!process.env.AI_MEMORY_RUN_ID) {{+ postHook("session-start", {{ sessionID: id, cwd, ...extra }});+ }}}}function endSession(id: string | undefined, directory: string, cwd?: string): void {{@@ -1811,7 +1820,7 @@ function endSession(id: string | undefined, directory: string, cwd?: string): voconst resolvedCwd = cwd || cwdFor(id, directory);postHook("session-end", {{ sessionID: id, cwd: resolvedCwd }});sessionCwds.delete(id);- handoffChecked.delete(id);+ handoffFetches.delete(id);preCompactLast.delete(id);}}@@ -1839,10 +1848,11 @@ function postHook(event: string, payload: Record<string, unknown>): void {{}}}}-async function fetchHandoff(cwd: string): Promise<string | undefined> {{+async function fetchHandoff(cwd: string, id: string | undefined): Promise<string | undefined> {{const url = new URL(`${{SERVER}}/handoff`);url.searchParams.set("agent", AGENT);url.searchParams.set("cwd", cwd);+ if (id) url.searchParams.set("session_id", id);applyMarkerParams(url, cwd);try {{const response = await fetch(url, {{@@ -1935,10 +1945,14 @@ export const AiMemoryHooks: Plugin = async ({{ directory }}) => {{}},"experimental.chat.system.transform": async (input, output) => {{const id = sessionID(input);- if (!id || handoffChecked.has(id)) return;- handoffChecked.add(id);+ if (!id) return;startSession(id, cwdFor(id, directory));- const handoff = await fetchHandoff(cwdFor(id, directory));+ let pending = handoffFetches.get(id);+ if (!pending) {{+ pending = fetchHandoff(cwdFor(id, directory), id);+ handoffFetches.set(id, pending);+ }}+ const handoff = await pending;if (handoff) (output as any).system.push(handoff);}},}};@@ -2371,7 +2385,12 @@ function startSession(ctx: any, extra: Record<string, unknown> = {{}}): void {{const id = sessionID(ctx);if (!id || startedSessions.has(id)) return;startedSessions.add(id);- postHook("session-start", {{ ...sessionPayload(ctx), ...extra }});+ // Generated integrations inject through fetchHandoff below. In managed mode+ // a queued SessionStart response is not model-visible and must not consume+ // the workstream context before that synchronous fetch receives it.+ if (!process.env.AI_MEMORY_RUN_ID) {{+ postHook("session-start", {{ ...sessionPayload(ctx), ...extra }});+ }}}}function postPreCompact(ctx: any): void {{@@ -2398,10 +2417,11 @@ function postHook(event: string, payload: Record<string, unknown>): void {{}}}}-async function fetchHandoff(cwd: string): Promise<string | undefined> {{+async function fetchHandoff(cwd: string, id: string | undefined): Promise<string | undefined> {{const url = new URL(`${{SERVER}}/handoff`);url.searchParams.set("agent", AGENT);url.searchParams.set("cwd", cwd);+ if (id) url.searchParams.set("session_id", id);applyMarkerParams(url, cwd);try {{const response = await fetch(url, {{@@ -2431,7 +2451,7 @@ export default function AiMemoryExtension(api: any): void {{const id = sessionID(ctx);if (!id || handoffChecked.has(id)) return;handoffChecked.add(id);- const handoff = await fetchHandoff(ctx?.cwd ?? "");+ const handoff = await fetchHandoff(ctx?.cwd ?? "", id);if (!handoff) return;return {{message: {{@@ -4213,6 +4233,7 @@ model = "gpt-5"assert!(generated.contains("const CAPTURE_POLICY_V1 = 1;"));assert!(generated.contains("const CAPTURE_MARKER_MAX_BYTES = 64 * 1024;"));assert!(generated.contains("async function fetchHandoff"));+ assert!(generated.contains("if (!process.env.AI_MEMORY_RUN_ID) {"));assert!(generated.contains("const response = await fetch(url, {"));assert!(generated.contains("signal: timeoutSignal(1000)"));assert!(!generated.contains("signal: timeoutSignal(500)"));@@ -4230,6 +4251,11 @@ model = "gpt-5"assert!(plugin.contains(r#""experimental.chat.system.transform": async"#));assert!(plugin.contains("export default AiMemoryHooks"));assert!(plugin.contains("const startedSessions = new Set<string>();"));+ assert!(+ plugin+ .contains("const handoffFetches = new Map<string, Promise<string | undefined>>();")+ );+ assert!(!plugin.contains("handoffChecked"));assert!(plugin.contains("function startSession"));assert!(plugin.contains("function endSession"));assert!(plugin.contains("fetchHandoff"));@@ -4267,7 +4293,7 @@ model = "gpt-5");assert!(plugin.contains("!startedSessions.delete(id)"));assert!(plugin.contains("sessionCwds.delete(id);"));- assert!(plugin.contains("handoffChecked.delete(id);"));+ assert!(plugin.contains("handoffFetches.delete(id);"));assert!(plugin.contains("preCompactLast.delete(id);"));assert!(plugin.contains("postHook(\"user-prompt\""));assert!(plugin.contains("Bearer ${TOKEN}"));@@ -4356,6 +4382,7 @@ model = "gpt-5"assert!(extension.contains("postHook(\"session-start\""));assert!(extension.contains("postHook(\"user-prompt\""));assert!(extension.contains("fetchHandoff"));+ assert!(extension.contains("if (!process.env.AI_MEMORY_RUN_ID) {"));assert!(extension.contains("function applyMarkerParams"));assert!(extension.contains("readFileSync(marker, \"utf8\")"));assert!(extension.contains("text.split(/\\r?\\n/)"));diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rsindex 09a6ad0c..f863b5c8 100644--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@ -44,12 +44,14 @@ pub mod reorg;pub mod reset;pub mod restore;pub mod restore_page;+pub mod run;pub mod search;pub mod serve;pub mod setup_agent;pub mod status;pub mod uninstall;pub mod user;+pub mod workstream_search;pub mod write_page;/// Resolve the effective project name for a client command.diff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rsnew file mode 100644index 00000000..a64c4aea--- /dev/null+++ b/crates/ai-memory-cli/src/commands/run.rs@@ -0,0 +1,382 @@+//! Opt-in managed cross-harness launcher.++use std::path::PathBuf;+use std::process::Stdio;+use std::time::{Duration, SystemTime};++use ai_memory_core::{+ FinishManagedRunRequest, FinishManagedRunResponse, LinkManagedRunRequest, ManagedRunStatus,+ PrepareManagedRunRequest, PrepareManagedRunResponse,+};+use ai_memory_workstream::{+ ExportedTranscript, ManagedHarness, build_launch_plan, discover_native_session,+ export_transcript, inspect_repository, wait_for_transcript_flush,+};+use anyhow::{Context as _, Result, anyhow};+use tokio::process::Command;++use crate::cli::{RunArgs, RunHarnessChoice};+use crate::commands::{path_util, resolve_project_name};+use crate::config::Config;+use crate::http_client::{ServerEndpoint, get_json, post_empty, post_json, post_json_no_content};++const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(30);+const IMPORT_BATCH_EVENTS: usize = 400;+const IMPORT_BATCH_BYTES: usize = 1024 * 1024;++/// Run one native harness and return its exact process exit code.+pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {+ let harness = managed_harness(args.harness);+ let cwd = std::env::current_dir().context("getting managed run working directory")?;+ let repository = inspect_repository(&cwd)?;+ let project = resolve_project_name(config, args.project.as_deref())?;+ let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;+ let prepare = PrepareManagedRunRequest {+ workspace: args.workspace,+ project,+ cwd: repository.cwd.to_string_lossy().into_owned(),+ repo_fingerprint: repository.repo_fingerprint,+ worktree_fingerprint: repository.worktree_fingerprint,+ agent: harness.agent_kind(),+ workstream: args.workstream,+ new_workstream: args.new_workstream,+ lease_owner: lease_owner(),+ };+ let prepared: PrepareManagedRunResponse = post_json(&endpoint, "/workstream/runs", &prepare)+ .await+ .context("opening managed workstream; the agent was not started")?;+ let plan = build_launch_plan(+ harness,+ args.executable.map(PathBuf::into_os_string),+ args.native_args,+ prepared.native_session_id.as_deref(),+ )?;+ let run_path = format!("/workstream/runs/{}", prepared.run_id);+ if let Some(native_session_id) = &plan.expected_session_id {+ post_json_no_content(+ &endpoint,+ &format!("{run_path}/link"),+ &LinkManagedRunRequest {+ native_session_id: native_session_id.clone(),+ },+ )+ .await+ .context("linking the managed native session; the agent was not started")?;+ }++ let started_at = SystemTime::now();+ let child = Command::new(&plan.program)+ .args(&plan.args)+ .current_dir(&repository.cwd)+ .env("AI_MEMORY_RUN_ID", prepared.run_id.to_string())+ .env(+ "AI_MEMORY_WORKSTREAM_ID",+ prepared.workstream_id.to_string(),+ )+ .env("AI_MEMORY_HOOK_URL", endpoint.build_url(""))+ .stdin(Stdio::inherit())+ .stdout(Stdio::inherit())+ .stderr(Stdio::inherit())+ .spawn();++ let mut child = match child {+ Ok(child) => child,+ Err(spawn_error) => {+ let spawn_message = spawn_error.to_string();+ let request = FinishManagedRunRequest {+ native_session_id: plan.expected_session_id,+ source_cursor: prepared.source_cursor,+ events: Vec::new(),+ complete: true,+ checkpoint: repository.checkpoint,+ losses: vec![format!(+ "native process could not be started: {spawn_message}"+ )],+ exit_code: None,+ };+ let _ = finish_with_retry(&endpoint, &run_path, &request).await;+ return Err(anyhow!(spawn_message)).context(format!(+ "starting managed {} executable {}",+ harness.as_str(),+ plan.program.to_string_lossy()+ ));+ }+ };++ let mut heartbeat = tokio::time::interval(HEARTBEAT_INTERVAL);+ heartbeat.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);+ heartbeat.tick().await;+ let status = loop {+ tokio::select! {+ result = child.wait() => break result.context("waiting for managed harness")?,+ _ = heartbeat.tick() => {+ if let Err(error) = post_empty(&endpoint, &format!("{run_path}/heartbeat")).await {+ eprintln!("ai-memory: managed workstream heartbeat failed: {error}");+ }+ }+ }+ };+ let exit_code = status.code().unwrap_or(1);++ let server_status = get_json::<ManagedRunStatus>(&endpoint, &run_path, &[])+ .await+ .ok();+ let home = config+ .home_dir+ .as_deref()+ .map(PathBuf::from)+ .or_else(path_util::home_dir)+ .context("locating the home directory for native transcript import")?;+ let discovered_session = if plan.expected_session_id.is_none() {+ discover_native_session(+ harness,+ &home,+ &repository.cwd,+ plan.session_dir.as_deref(),+ started_at,+ )+ .await?+ } else {+ None+ };+ let native_session_id = plan+ .expected_session_id+ .clone()+ .or(discovered_session)+ .or_else(|| {+ server_status+ .as_ref()+ .and_then(|status| status.native_session_id.clone())+ });+ let source_cursor = if native_session_id.as_deref() == prepared.native_session_id.as_deref() {+ prepared.source_cursor.as_deref()+ } else {+ None+ };+ let transcript = export_after_flush(+ harness,+ &home,+ &repository.cwd,+ plan.session_dir.as_deref(),+ native_session_id.as_deref(),+ source_cursor,+ )+ .await;+ let checkpoint = inspect_repository(&repository.cwd)+ .map(|identity| identity.checkpoint)+ .unwrap_or(repository.checkpoint);+ let imported = import_batches(+ &endpoint,+ &run_path,+ transcript,+ checkpoint,+ Some(exit_code),+ )+ .await?;++ if prepared.sync_through > prepared.sync_after+ && !server_status.is_some_and(|status| status.context_delivered)+ {+ eprintln!(+ "ai-memory: this harness did not acknowledge its managed context packet; refresh its ai-memory hooks before the next run"+ );+ }+ eprintln!(+ "ai-memory: workstream '{}' saved {imported} new event(s)",+ prepared.workstream_name+ );+ Ok(exit_code)+}++async fn export_after_flush(+ harness: ManagedHarness,+ home: &std::path::Path,+ cwd: &std::path::Path,+ session_dir: Option<&std::path::Path>,+ native_session_id: Option<&str>,+ source_cursor: Option<&str>,+) -> ExportedTranscript {+ let Some(native_session_id) = native_session_id else {+ return ExportedTranscript {+ losses: vec![+ "native session id could not be discovered; transcript was not imported".into(),+ ],+ ..ExportedTranscript::default()+ };+ };+ if let Err(error) =+ wait_for_transcript_flush(harness, home, cwd, session_dir, native_session_id).await+ {+ eprintln!("ai-memory: transcript flush check failed: {error}");+ }+ match export_transcript(+ harness,+ home,+ cwd,+ session_dir,+ native_session_id,+ source_cursor,+ )+ .await+ {+ Ok(export) => export,+ Err(error) => ExportedTranscript {+ native_session_id: native_session_id.to_string(),+ source_cursor: source_cursor.map(str::to_string),+ losses: vec![format!("native transcript import failed: {error}")],+ events: Vec::new(),+ },+ }+}++async fn import_batches(+ endpoint: &ServerEndpoint,+ run_path: &str,+ transcript: ExportedTranscript,+ checkpoint: ai_memory_core::WorkstreamCheckpoint,+ exit_code: Option<i32>,+) -> Result<usize> {+ let mut imported = 0;+ let mut batches = event_batches(transcript.events).into_iter().peekable();+ while let Some(batch) = batches.next() {+ let complete = batches.peek().is_none();+ let request = FinishManagedRunRequest {+ native_session_id: nonempty_session(&transcript.native_session_id),+ source_cursor: complete.then(|| transcript.source_cursor.clone()).flatten(),+ events: batch,+ complete,+ checkpoint: checkpoint.clone(),+ losses: if complete {+ transcript.losses.clone()+ } else {+ Vec::new()+ },+ exit_code: complete.then_some(exit_code).flatten(),+ };+ imported += finish_with_retry(endpoint, run_path, &request)+ .await?+ .imported_events;+ }+ Ok(imported)+}++fn event_batches(+ events: Vec<ai_memory_core::NewWorkstreamEvent>,+) -> Vec<Vec<ai_memory_core::NewWorkstreamEvent>> {+ let mut batches = Vec::new();+ let mut batch = Vec::new();+ let mut bytes = 0_usize;+ for event in events {+ let event_bytes = serde_json::to_vec(&event).map_or(IMPORT_BATCH_BYTES, |raw| raw.len());+ if !batch.is_empty()+ && (batch.len() >= IMPORT_BATCH_EVENTS+ || bytes.saturating_add(event_bytes) > IMPORT_BATCH_BYTES)+ {+ batches.push(std::mem::take(&mut batch));+ bytes = 0;+ }+ bytes = bytes.saturating_add(event_bytes);+ batch.push(event);+ }+ batches.push(batch);+ batches+}++async fn finish_with_retry(+ endpoint: &ServerEndpoint,+ run_path: &str,+ request: &FinishManagedRunRequest,+) -> Result<FinishManagedRunResponse> {+ let path = format!("{run_path}/finish");+ let mut last_error = None;+ for attempt in 0..3 {+ match post_json(endpoint, &path, request).await {+ Ok(response) => return Ok(response),+ Err(error) => last_error = Some(error),+ }+ tokio::time::sleep(Duration::from_millis(250 * (attempt + 1))).await;+ }+ Err(last_error.unwrap_or_else(|| anyhow!("managed finish failed")))+ .context("persisting the managed transcript; the native process has already exited")+}++fn nonempty_session(value: &str) -> Option<String> {+ (!value.is_empty()).then(|| value.to_string())+}++fn lease_owner() -> String {+ let host = std::env::var("HOSTNAME").unwrap_or_else(|_| "localhost".to_string());+ format!("{host}:{}", std::process::id())+}++const fn managed_harness(choice: RunHarnessChoice) -> ManagedHarness {+ match choice {+ RunHarnessChoice::Claude => ManagedHarness::Claude,+ RunHarnessChoice::Codex => ManagedHarness::Codex,+ RunHarnessChoice::OpenCode => ManagedHarness::OpenCode,+ RunHarnessChoice::Pi => ManagedHarness::Pi,+ RunHarnessChoice::Omp => ManagedHarness::Omp,+ }+}++#[cfg(test)]+mod tests {+ use std::ffi::{OsStr, OsString};++ use clap::Parser as _;++ use crate::cli::{Cli, Command as CliCommand};++ #[test]+ fn native_arguments_do_not_require_separator_and_remain_opaque() {+ let cli = Cli::try_parse_from([+ OsStr::new("ai-memory"),+ OsStr::new("run"),+ OsStr::new("--project"),+ OsStr::new("memory"),+ OsStr::new("codex"),+ OsStr::new("--yolo"),+ OsStr::new("-m"),+ OsStr::new("gpt-5"),+ OsStr::new("continue here"),+ ])+ .unwrap();+ let CliCommand::Run(args) = cli.command else {+ panic!("expected run command");+ };+ assert_eq!(args.project.as_deref(), Some("memory"));+ assert_eq!(+ args.native_args,+ ["--yolo", "-m", "gpt-5", "continue here"]+ .map(OsString::from)+ .to_vec()+ );+ }++ #[test]+ fn opencode_name_and_native_flags_parse_without_separator() {+ let cli = Cli::try_parse_from([+ OsStr::new("ai-memory"),+ OsStr::new("run"),+ OsStr::new("opencode"),+ OsStr::new("run"),+ OsStr::new("--model"),+ OsStr::new("provider/model"),+ OsStr::new("continue here"),+ ])+ .unwrap();+ let CliCommand::Run(args) = cli.command else {+ panic!("expected run command");+ };+ assert!(matches!(+ args.harness,+ crate::cli::RunHarnessChoice::OpenCode+ ));+ assert_eq!(+ args.native_args,+ ["run", "--model", "provider/model", "continue here"]+ .map(OsString::from)+ .to_vec()+ );+ }+}diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex 02995fcd..8f312347 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -13,7 +13,8 @@ use ai_memory_core::{ActiveProject, ActorContext, PagePath, ProjectId, Sanitizer, SessionId, WorkspaceId,};use ai_memory_hooks::{- DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT, HookState, ProjectCacheStore, hook_router,+ DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT, HookState, ProjectCacheStore, WorkstreamState, hook_router,+ workstream_router,};use ai_memory_llm::{Embedder, LlmProvider, ProviderHealth, build_embedder, build_provider};use ai_memory_mcp::{AdminState, AiMemoryServer, ScopeInvalidation, admin_router};@@ -410,6 +411,12 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {)),home_dir: config.home_dir.clone(),});+ let workstreams = workstream_router(WorkstreamState {+ writer: store.writer.clone(),+ reader: store.reader.clone(),+ sanitizer: sanitizer.clone(),+ data_dir: config.data_dir.clone(),+ });let admin = admin_router(AdminState {writer: store.writer.clone(),reader: store.reader.clone(),@@ -472,6 +479,7 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {let router = axum::Router::new().nest_service("/mcp", mcp_service).merge(hooks)+ .merge(workstreams).layer(DefaultBodyLimit::max(MAX_BODY_BYTES)).merge(admin.layer(DefaultBodyLimit::max(BOOTSTRAP_MAX_BODY_BYTES)));let base_path = normalize_prefix(&args.base_path);diff --git a/crates/ai-memory-cli/src/commands/workstream_search.rs b/crates/ai-memory-cli/src/commands/workstream_search.rsnew file mode 100644index 00000000..25e7cad7--- /dev/null+++ b/crates/ai-memory-cli/src/commands/workstream_search.rs@@ -0,0 +1,40 @@+//! Explicit retrieval for history older than a managed startup packet.++use ai_memory_core::WorkstreamEvent;+use anyhow::Result;++use crate::cli::WorkstreamSearchArgs;+use crate::config::Config;+use crate::http_client::{ServerEndpoint, get_json};++/// Search or tail one portable managed-workstream ledger.+pub async fn run(config: &Config, args: WorkstreamSearchArgs) -> Result<()> {+ let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;+ let path = format!("/workstream/{}/events", args.workstream_id);+ let limit = args.limit.to_string();+ let events: Vec<WorkstreamEvent> = get_json(+ &endpoint,+ &path,+ &[("q", args.query.as_str()), ("limit", limit.as_str())],+ )+ .await?;+ if args.json {+ println!("{}", serde_json::to_string_pretty(&events)?);+ return Ok(());+ }+ if events.is_empty() {+ println!("No matching managed-workstream events.");+ return Ok(());+ }+ for event in events {+ let role = event.role.as_deref().unwrap_or(event.kind.as_str());+ println!(+ "## Event {} | {} | {}\n{}\n",+ event.sequence,+ event.agent.as_str(),+ role,+ event.content+ );+ }+ Ok(())+}diff --git a/crates/ai-memory-cli/src/http_client.rs b/crates/ai-memory-cli/src/http_client.rsindex bc110f86..0d2e984d 100644--- a/crates/ai-memory-cli/src/http_client.rs+++ b/crates/ai-memory-cli/src/http_client.rs@@ -200,6 +200,44 @@ pub async fn post_json<B: Serialize, T: DeserializeOwned>(post_json_with_query(endpoint, path, &[], body).await}+/// POST JSON and require a successful response without decoding its body.+pub async fn post_json_no_content<B: Serialize>(+ endpoint: &ServerEndpoint,+ path: &str,+ body: &B,+) -> Result<()> {+ let client = reqwest::Client::new();+ let url = endpoint.build_url(path);+ let req = endpoint.authenticate(client.post(&url).json(body));+ let resp = req+ .send()+ .await+ .map_err(|e| augment_connect_error(e, endpoint, &url))?;+ let status = resp.status();+ if !status.is_success() {+ let body = resp.text().await.unwrap_or_default();+ bail!("server returned {status}: {body}");+ }+ Ok(())+}++/// POST an empty body and require a successful response.+pub async fn post_empty(endpoint: &ServerEndpoint, path: &str) -> Result<()> {+ let client = reqwest::Client::new();+ let url = endpoint.build_url(path);+ let req = endpoint.authenticate(client.post(&url));+ let resp = req+ .send()+ .await+ .map_err(|e| augment_connect_error(e, endpoint, &url))?;+ let status = resp.status();+ if !status.is_success() {+ let body = resp.text().await.unwrap_or_default();+ bail!("server returned {status}: {body}");+ }+ Ok(())+}+/// POST JSON body to `<endpoint>{path}` with URL-encoded query params.////// # Errorsdiff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rsindex 045c1d3e..9d6ccadf 100644--- a/crates/ai-memory-cli/src/main.rs+++ b/crates/ai-memory-cli/src/main.rs@@ -67,6 +67,14 @@ async fn main() -> Result<()> {match command {Command::Init(args) => commands::init::run(&config, args, config_path.as_deref()),Command::Status(args) => commands::status::run(&config, args).await,+ Command::Run(args) => {+ let exit_code = commands::run::run(&config, args).await?;+ if exit_code != 0 {+ std::process::exit(exit_code);+ }+ Ok(())+ }+ Command::WorkstreamSearch(args) => commands::workstream_search::run(&config, args).await,Command::AuditContamination(args) => {commands::audit_contamination::run(&config, args).await}diff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rsindex 274694bd..b8a3d150 100644--- a/crates/ai-memory-core/src/ids.rs+++ b/crates/ai-memory-core/src/ids.rs@@ -83,6 +83,8 @@ id_newtype!(pub SessionId, "Identifier for a single agent run.");id_newtype!(pub ObservationId, "Identifier for a single observation captured during a session.");id_newtype!(pub PageId, "Identifier for a single wiki page version.");id_newtype!(pub HandoffId, "Identifier for a cross-agent handoff record.");+id_newtype!(pub WorkstreamId, "Identifier for a managed cross-harness workstream.");+id_newtype!(pub ManagedRunId, "Identifier for one `ai-memory run` invocation.");id_newtype!(pub UserId, "Identifier for a registered user (multi-user attribution; see [`crate::actor`]).");id_newtype!(pub AutoImproveRunId, "Identifier for one auto-improvement review run.");id_newtype!(pub AutoImproveProposalId, "Identifier for one staged auto-improvement proposal.");diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rsindex c1430712..27a25703 100644--- a/crates/ai-memory-core/src/lib.rs+++ b/crates/ai-memory-core/src/lib.rs@@ -16,6 +16,7 @@ pub mod routing_skills;pub mod routing_snippet;pub mod sanitize;pub mod user;+mod workstream;/// Default workspace name used by the single-workspace v1 flow.pub const DEFAULT_WORKSPACE_NAME: &str = "default";@@ -40,11 +41,16 @@ pub use actor::{ActorContext, AuthLevel, AuthzError, Capability};pub use error::{MemoryError, MemoryResult};pub use handoff::{Handoff, HandoffState, NewHandoff};pub use ids::{- AgentKind, AutoImproveProposalId, AutoImproveRunId, HandoffId, ObservationId, PageId, PagePath,- ProjectId, SessionId, UserId, WorkspaceId,+ AgentKind, AutoImproveProposalId, AutoImproveRunId, HandoffId, ManagedRunId, ObservationId,+ PageId, PagePath, ProjectId, SessionId, UserId, WorkspaceId, WorkstreamId,};pub use observation::{NewObservation, NewSession, Observation, ObservationKind};pub use page::{LinkTarget, NewPage, Page, Tier};pub use routing_snippet::{MARKER_END, MARKER_START, SNIPPET_BODY, find_marker_line, full_block};pub use sanitize::{SanitizeConfig, Sanitized, Sanitizer};pub use user::{MAX_EMAIL_LEN, MAX_USERNAME_LEN, NewUser, User, validate_email, validate_username};+pub use workstream::{+ FinishManagedRunRequest, FinishManagedRunResponse, LinkManagedRunRequest, ManagedRunStatus,+ NewWorkstreamEvent, PrepareManagedRunRequest, PrepareManagedRunResponse, WorkstreamCheckpoint,+ WorkstreamEvent, WorkstreamEventKind,+};diff --git a/crates/ai-memory-core/src/routing_snippet.rs b/crates/ai-memory-core/src/routing_snippet.rsindex 0c02fe62..fa4e6f36 100644--- a/crates/ai-memory-core/src/routing_snippet.rs+++ b/crates/ai-memory-core/src/routing_snippet.rs@@ -46,10 +46,11 @@ forward the real agent session id automatically; pass explicit`workspace` + `project` / `scopes`, or use a session-aware bridge thatforwards the lifecycle-hook session id on MCP calls.-**Lifecycle hooks already capture every prompt and tool call-automatically.** Do not manually write routine notes. Only write durable-memory when the user explicitly asks to remember or annotate something-permanently.+**Lifecycle hooks already capture sanitized, bounded prompt and tool-lifecycle+observations automatically.** They are not complete native transcripts;+managed `ai-memory run` launches add the portable visible-event ledger. Do not+manually write routine notes. Only write durable memory when the user explicitly asks+to remember or annotate something permanently.### Use the installed ai-memory Agent Skillsdiff --git a/crates/ai-memory-core/src/workstream.rs b/crates/ai-memory-core/src/workstream.rsnew file mode 100644index 00000000..59d64245--- /dev/null+++ b/crates/ai-memory-core/src/workstream.rs@@ -0,0 +1,238 @@+//! Managed cross-harness workstream wire types.+//!+//! A workstream is the portable, append-only history shared by native harness+//! sessions launched through `ai-memory run`. Direct harness launches never+//! create or consume these records.++use serde::{Deserialize, Serialize};++use crate::{AgentKind, ManagedRunId, WorkstreamId};++/// Semantic event families preserved in the portable workstream ledger.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum WorkstreamEventKind {+ /// User, assistant, developer, system, or tool-authored message.+ Message,+ /// A historical tool invocation. It must never be replayed as pending.+ ToolCall,+ /// Completed or failed historical tool output.+ ToolResult,+ /// Native context compaction or summary boundary.+ Compaction,+ /// Repository state observed at a managed-run boundary.+ Checkpoint,+ /// Importer loss, redaction, or recovery note.+ Annotation,+}++impl WorkstreamEventKind {+ /// Canonical SQLite/wire representation.+ #[must_use]+ pub const fn as_str(self) -> &'static str {+ match self {+ Self::Message => "message",+ Self::ToolCall => "tool_call",+ Self::ToolResult => "tool_result",+ Self::Compaction => "compaction",+ Self::Checkpoint => "checkpoint",+ Self::Annotation => "annotation",+ }+ }+}++impl std::str::FromStr for WorkstreamEventKind {+ type Err = crate::MemoryError;++ fn from_str(value: &str) -> Result<Self, Self::Err> {+ match value {+ "message" => Ok(Self::Message),+ "tool_call" => Ok(Self::ToolCall),+ "tool_result" => Ok(Self::ToolResult),+ "compaction" => Ok(Self::Compaction),+ "checkpoint" => Ok(Self::Checkpoint),+ "annotation" => Ok(Self::Annotation),+ other => Err(crate::MemoryError::MalformedRecord(format!(+ "unknown workstream event kind: {other}"+ ))),+ }+ }+}++/// One normalized event uploaded from a native harness transcript.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct NewWorkstreamEvent {+ /// Stable, source-derived identifier used to make retries idempotent.+ pub event_id: String,+ /// Harness that produced this event.+ pub agent: AgentKind,+ /// Native session that produced this event.+ pub native_session_id: String,+ /// Native record/block identifier when one exists.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub source_record_id: Option<String>,+ /// Semantic event family.+ pub kind: WorkstreamEventKind,+ /// Message role (`user`, `assistant`, `tool`, etc.) when applicable.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub role: Option<String>,+ /// Sanitized, human-readable event content.+ pub content: String,+ /// Source timestamp as RFC 3339 when available.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub occurred_at: Option<String>,+ /// Adapter-specific, allow-listed metadata. Never contains credentials or+ /// opaque provider reasoning.+ #[serde(default)]+ pub metadata: serde_json::Value,+}++/// Repository state captured without mutating the checkout.+#[derive(Debug, Clone, Default, Serialize, Deserialize)]+pub struct WorkstreamCheckpoint {+ /// Current Git commit, when inside a repository.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub head: Option<String>,+ /// Current branch or detached-HEAD marker.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub branch: Option<String>,+ /// Stable hash of the porcelain status output.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub dirty_hash: Option<String>,+ /// Changed and untracked paths, bounded by the local adapter.+ #[serde(default)]+ pub changed_paths: Vec<String>,+}++/// Request to open a lease-backed managed harness invocation.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct PrepareManagedRunRequest {+ /// Workspace name resolved by the host CLI.+ pub workspace: String,+ /// Project name resolved by the host CLI.+ pub project: String,+ /// Canonical host working directory.+ pub cwd: String,+ /// Stable repository identity hash.+ pub repo_fingerprint: String,+ /// Stable worktree identity hash (distinct across linked worktrees).+ pub worktree_fingerprint: String,+ /// Harness being launched.+ pub agent: AgentKind,+ /// Select an existing named workstream instead of the current selection.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub workstream: Option<String>,+ /// Create and select a fresh named workstream.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub new_workstream: Option<String>,+ /// Diagnostic owner label (host and process id), not an authorization key.+ pub lease_owner: String,+}++/// Result of preparing a managed invocation.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct PrepareManagedRunResponse {+ /// Selected logical workstream.+ pub workstream_id: WorkstreamId,+ /// Human-readable workstream name.+ pub workstream_name: String,+ /// Lease/run identifier exported to the child process.+ pub run_id: ManagedRunId,+ /// Previously linked native session for this harness, if any.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub native_session_id: Option<String>,+ /// Adapter cursor from the last successful source import.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub source_cursor: Option<String>,+ /// First portable sequence not yet delivered to this native session.+ pub sync_after: i64,+ /// Portable high-water mark assigned to this launch.+ pub sync_through: i64,+}++/// Bind the actual native session selected or created by a managed launch.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct LinkManagedRunRequest {+ /// Harness-native session identifier.+ pub native_session_id: String,+}++/// Import and close request sent after the managed child exits.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct FinishManagedRunRequest {+ /// Native session observed by hooks or transcript discovery.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub native_session_id: Option<String>,+ /// Adapter-specific cursor after reading the transcript.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub source_cursor: Option<String>,+ /// Normalized unseen source events.+ #[serde(default)]+ pub events: Vec<NewWorkstreamEvent>,+ /// Whether this is the final import batch. Non-final batches keep the+ /// lease open and do not advance the durable source cursor.+ #[serde(default = "default_true")]+ pub complete: bool,+ /// Non-mutating repository checkpoint at child exit.+ pub checkpoint: WorkstreamCheckpoint,+ /// Explicit extraction/redaction losses.+ #[serde(default)]+ pub losses: Vec<String>,+ /// Native process exit code; absent when terminated by a signal.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub exit_code: Option<i32>,+}++const fn default_true() -> bool {+ true+}++/// Result of an idempotent managed-run finish.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct FinishManagedRunResponse {+ /// Number of new portable events inserted; duplicates are excluded.+ pub imported_events: usize,+ /// Current portable high-water mark.+ pub latest_sequence: i64,+}++/// Managed-run state returned to the host wrapper for transcript discovery.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ManagedRunStatus {+ /// Run identifier.+ pub run_id: ManagedRunId,+ /// Owning workstream.+ pub workstream_id: WorkstreamId,+ /// Harness being run.+ pub agent: AgentKind,+ /// Native session linked by SessionStart, if observed.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub native_session_id: Option<String>,+ /// Whether the SessionStart context packet was returned successfully.+ pub context_delivered: bool,+ /// Current run state (`active`, `finished`, or `expired`).+ pub state: String,+}++/// Stored workstream event returned by history reads.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct WorkstreamEvent {+ /// Portable monotonic sequence within the workstream.+ pub sequence: i64,+ /// Stable source-derived event identifier.+ pub event_id: String,+ /// Source harness.+ pub agent: AgentKind,+ /// Source native session.+ pub native_session_id: String,+ /// Semantic event family.+ pub kind: WorkstreamEventKind,+ /// Optional message role.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub role: Option<String>,+ /// Sanitized event content.+ pub content: String,+ /// Source timestamp when available.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub occurred_at: Option<String>,+}diff --git a/crates/ai-memory-hooks/Cargo.toml b/crates/ai-memory-hooks/Cargo.tomlindex 9b4092fd..d91bf654 100644--- a/crates/ai-memory-hooks/Cargo.toml+++ b/crates/ai-memory-hooks/Cargo.toml@@ -26,6 +26,7 @@ jiff.workspace = trueuuid.workspace = trueaxum.workspace = trueregex.workspace = true+sha2.workspace = true[dev-dependencies]tempfile.workspace = truediff --git a/crates/ai-memory-hooks/src/lib.rs b/crates/ai-memory-hooks/src/lib.rsindex 69021b26..ff4a31de 100644--- a/crates/ai-memory-hooks/src/lib.rs+++ b/crates/ai-memory-hooks/src/lib.rs@@ -26,6 +26,7 @@ pub mod log;pub mod payload;pub mod router;pub mod synth;+pub mod workstream;// Re-export the sanitizer types from core so callers that grew up// pointing at this crate's `sanitize` module keep working.@@ -41,3 +42,4 @@ pub use router::{hook_router,};pub use synth::synthesize_session_page;+pub use workstream::{WorkstreamState, workstream_router};diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rsindex 4dd16c11..3ea81839 100644--- a/crates/ai-memory-hooks/src/payload.rs+++ b/crates/ai-memory-hooks/src/payload.rs@@ -55,6 +55,9 @@ pub struct HookQuery {/// instead of just the current one — the meta-repo case (e.g. `ai-memory`/// needing to see `ai-memory-ops` / `infra` without passing `global=true`).pub default_global: Option<String>,+ /// Invocation-scoped `ai-memory run` lease. Absent for every direct+ /// harness launch, preserving legacy capture and handoff behavior.+ pub managed_run: Option<String>,}/// Coalesced view of an incoming hook event after light parsing of the@@ -90,6 +93,8 @@ pub struct HookEnvelope {/// router publishes it on the actor's `ActiveProject` so default-scoped/// read tools broaden to a global search.pub recall_default_global_requested: bool,+ /// Invocation-scoped managed-run id forwarded by the host hook.+ pub managed_run: Option<String>,/// Optional third-party extension namespace.pub extension: Option<String>,/// Optional source event name from the extension vocabulary.@@ -319,6 +324,7 @@ impl HookEnvelope {let project_strategy = ProjectStrategy::parse(query.project_strategy.as_deref());let drop_subagent_requested = query_flag_truthy(query.drop_subagent.as_deref());let recall_default_global_requested = query_flag_truthy(query.default_global.as_deref());+ let managed_run = query.managed_run.filter(|value| !value.trim().is_empty());let extension = normalize_extension_name(query.extension.as_deref());let source_event = extension.as_ref().and_then(|_| {let raw_source = query@@ -375,6 +381,7 @@ impl HookEnvelope {project_strategy,drop_subagent_requested,recall_default_global_requested,+ managed_run,extension,source_event,title_hint,diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex 91870f8c..2c161e12 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -14,9 +14,9 @@ use std::sync::Arc;use ai_memory_consolidate::Consolidator;use ai_memory_core::{- ActiveProject, ActorKey, AgentKind, DEFAULT_WORKSPACE_NAME, Handoff, NewHandoff,+ ActiveProject, ActorKey, AgentKind, DEFAULT_WORKSPACE_NAME, Handoff, ManagedRunId, NewHandoff,NewObservation, NewSession, ObservationKind, ProjectId, Sanitized, Sanitizer, SessionId,- WorkspaceId,+ WorkspaceId, WorkstreamEvent, WorkstreamEventKind,};use ai_memory_store::WriterHandle;use ai_memory_wiki::Wiki;@@ -979,6 +979,11 @@ pub struct HandoffQuery {/// [`BRIEF_BUDGET_MIN`], [`BRIEF_BUDGET_MAX`]; defaults to/// [`BRIEF_BUDGET_DEFAULT`] when absent or unparsable.pub briefing_budget: Option<String>,+ /// Invocation-scoped managed run. When present, workstream delta delivery+ /// replaces (and never consumes) the legacy single-use handoff.+ pub managed_run: Option<String>,+ /// Native session identifier observed in the SessionStart payload.+ pub session_id: Option<String>,}/// Synchronous endpoint used by `session-start.sh` to discover any@@ -1014,6 +1019,46 @@ async fn fetch_and_accept_handoff(actor_user: Option<String>,) -> anyhow::Result<Option<String>> {let agent = query.agent.as_deref().map_or(AgentKind::Other, parse_agent);+ if let Some(raw_run_id) = query.managed_run.as_deref() {+ let Ok(run_id) = ManagedRunId::from_str(raw_run_id) else {+ warn!(managed_run = %raw_run_id, "invalid managed run id on SessionStart");+ return Ok(None);+ };+ if let Some(native_session_id) = query+ .session_id+ .as_deref()+ .filter(|value| !value.trim().is_empty())+ {+ let _ = state+ .writer+ .link_managed_run_session(run_id, agent, native_session_id)+ .await?;+ }+ let Some(context) = state.reader.managed_run_context(run_id, 256).await? else {+ warn!(managed_run = %run_id, "managed SessionStart has no active run");+ return Ok(None);+ };+ if context.agent != agent {+ warn!(+ managed_run = %run_id,+ expected = %context.agent.as_str(),+ actual = %agent.as_str(),+ "managed SessionStart agent mismatch"+ );+ return Ok(None);+ }+ if context.context_delivered {+ return Ok(None);+ }+ let rendered = render_managed_context(+ &context.events,+ &context.workstream_name,+ context.workstream_id,+ context.sync_after,+ );+ let _ = state.writer.accept_managed_run_context(run_id).await?;+ return Ok(rendered);+ }// `/handoff` has no session_id in the request — `per_session` mode// therefore falls back to the single slot (graceful degradation),// while `per_actor` keys by `user` alone.@@ -1235,6 +1280,79 @@ fn render_handoff_markdown(h: &Handoff) -> String {buf}+fn render_managed_context(+ events: &[WorkstreamEvent],+ workstream_name: &str,+ workstream_id: ai_memory_core::WorkstreamId,+ sync_after: i64,+) -> Option<String> {+ const MAX_PACKET_CHARS: usize = 30_000;+ const MAX_EVENT_CHARS: usize = 6_000;+ if events.is_empty() {+ return None;+ }++ fn cap_chars(value: &str, max: usize) -> String {+ if value.chars().count() <= max {+ return value.to_string();+ }+ let mut out: String = value.chars().take(max.saturating_sub(1)).collect();+ out.push('…');+ out+ }++ let mut selected = Vec::new();+ let mut used = 0_usize;+ let mut first_sequence = 0_i64;+ for event in events.iter().rev() {+ let role = event.role.as_deref().unwrap_or(match event.kind {+ WorkstreamEventKind::ToolCall => "historical tool call (completed evidence)",+ WorkstreamEventKind::ToolResult => "historical tool result (completed evidence)",+ WorkstreamEventKind::Checkpoint => "repository checkpoint",+ WorkstreamEventKind::Compaction => "native compaction",+ WorkstreamEventKind::Annotation => "import note",+ WorkstreamEventKind::Message => "message",+ });+ let content = cap_chars(&event.content, MAX_EVENT_CHARS);+ let block = format!(+ "### {} · {} · event {}\n{}\n",+ event.agent.as_str(),+ role,+ event.sequence,+ content+ );+ let block_chars = block.chars().count();+ if !selected.is_empty() && used.saturating_add(block_chars) > MAX_PACKET_CHARS {+ break;+ }+ used = used.saturating_add(block_chars);+ first_sequence = event.sequence;+ selected.push(block);+ }+ selected.reverse();+ let last_sequence = events.last().map_or(0, |event| event.sequence);+ let omitted = first_sequence > sync_after.saturating_add(1);++ let mut rendered = format!(+ "> **ai-memory managed workstream: {workstream_name}**\n> Portable events {first_sequence} through {last_sequence}. Foreign tool calls/results below are completed historical evidence; do not replay them as pending actions. The latest repository checkpoint is authoritative over older native-session assumptions.\n\n"+ );+ if omitted {+ rendered.push_str(+ "> Older unseen events did not fit the startup budget. Search the complete visible ledger with `ai-memory workstream-search --workstream-id "+ );+ rendered.push_str(&workstream_id.to_string());+ rendered.push_str(" \"<query>\"`.\n\n");+ }+ for block in selected {+ rendered.push_str(&block);+ rendered.push('\n');+ }+ rendered.push_str(+ "Continue this logical workstream from the current checkout state. Preserve source-harness provenance when relying on historical evidence. If an older detail is missing, search the visible ledger with `ai-memory workstream-search \"<query>\"`; this managed process already carries the workstream id.\n",+ );+ Some(rendered)+}+/// Build the `project_cache` key from the resolved cwd, overrides, and/// project strategy. Shared by `resolve_project_ids` (insert/lookup) and/// `process` (eviction on the stale-cache retry) so the two always agree on@@ -1759,6 +1877,30 @@ async fn process(.await?;}+ // `AI_MEMORY_RUN_ID` is invocation-scoped. A valid active run links the+ // native session and switches only this hook invocation to managed+ // workstream semantics; direct harness launches keep the legacy path.+ let managed = env.managed_run.is_some();+ let managed_run = env.managed_run.as_deref().and_then(|raw| {+ ManagedRunId::from_str(raw)+ .map_err(|error| {+ warn!(managed_run = %raw, error = %error, "invalid managed run id on hook event");+ error+ })+ .ok()+ });+ if let Some(run_id) = managed_run+ && let Some(native_session_id) = env+ .session_id+ .as_deref()+ .filter(|value| !value.trim().is_empty())+ {+ let _ = state+ .writer+ .link_managed_run_session(run_id, env.agent, native_session_id)+ .await?;+ }+// Persist the observation row.let kind = env.event.to_observation_kind();let title = env@@ -1838,15 +1980,19 @@ async fn process(}).await?;state.writer.end_session(session_id, Some(page_id)).await?;- let handoff = build_auto_handoff(- ws,- proj,- env.agent,- session_id,- env.cwd.clone(),- &observations,- );- let handoff_id = state.writer.insert_handoff(handoff).await?;+ let handoff_id = if managed {+ None+ } else {+ let handoff = build_auto_handoff(+ ws,+ proj,+ env.agent,+ session_id,+ env.cwd.clone(),+ &observations,+ );+ Some(state.writer.insert_handoff(handoff).await?)+ };// Opt-in (AI_MEMORY_CONSOLIDATE_ON_SESSION_END): additionally run LLM// consolidation so the session's knowledge is compiled into topical// pages, not just the heuristic session record. The heuristic page@@ -1888,12 +2034,21 @@ async fn process(Ok(None) => debug!("wiki clean; no auto-commit"),Err(e) => warn!(error = %e, "auto-commit failed"),}- info!(- session = %session_id,- page = %new_page.path,- handoff = %handoff_id,- "session ended; summary page + open handoff created",- );+ if let Some(handoff_id) = handoff_id {+ info!(+ session = %session_id,+ page = %new_page.path,+ handoff = %handoff_id,+ "session ended; summary page + open handoff created",+ );+ } else {+ info!(+ session = %session_id,+ page = %new_page.path,+ managed_run = ?managed_run,+ "managed session ended; summary page written without duplicate legacy handoff",+ );+ }}Ok(())@@ -2159,6 +2314,26 @@ mod tests {}}+ #[test]+ fn managed_context_labels_completed_tools_and_discloses_omitted_history() {+ let events = vec![WorkstreamEvent {+ sequence: 300,+ event_id: "tool-300".into(),+ agent: AgentKind::Codex,+ native_session_id: "native".into(),+ kind: WorkstreamEventKind::ToolCall,+ role: None,+ content: "cargo test".into(),+ occurred_at: None,+ }];+ let rendered =+ render_managed_context(&events, "default", ai_memory_core::WorkstreamId::new(), 0)+ .unwrap();+ assert!(rendered.contains("historical tool call (completed evidence)"));+ assert!(rendered.contains("Older unseen events did not fit"));+ assert!(rendered.contains("workstream-search"));+ }+#[cfg(not(windows))]fn init_repo_with_commit(path: &std::path::Path) -> git2::Repository {std::fs::create_dir_all(path).unwrap();@@ -4519,6 +4694,69 @@ mod tests {);}+ #[tokio::test]+ async fn managed_marker_never_falls_back_to_a_legacy_handoff() {+ let tmp = TempDir::new().unwrap();+ let state = make_state(&tmp).await;+ let run_id = ManagedRunId::new().to_string();+ let managed_session = SessionId::new();+ for event in ["session-start", "session-end"] {+ let envelope = HookEnvelope::from_query_and_body(+ HookQuery {+ event: event.into(),+ agent: Some("codex".into()),+ cwd: Some(tmp.path().to_string_lossy().into_owned()),+ workspace: Some("default".into()),+ project: Some("scratch".into()),+ managed_run: Some(run_id.clone()),+ ..Default::default()+ },+ serde_json::json!({+ "session_id": managed_session.to_string(),+ "cwd": tmp.path(),+ }),+ );+ process(&state, envelope, None).await.unwrap();+ }+ assert!(+ state+ .reader+ .latest_open_handoff(state.workspace_id, state.project_id, None)+ .await+ .unwrap()+ .is_none(),+ "a stale or invalid managed lease must not create a duplicate legacy handoff"+ );++ let direct_session = SessionId::new();+ for event in ["session-start", "session-end"] {+ let envelope = HookEnvelope::from_query_and_body(+ HookQuery {+ event: event.into(),+ agent: Some("codex".into()),+ cwd: Some(tmp.path().to_string_lossy().into_owned()),+ workspace: Some("default".into()),+ project: Some("scratch".into()),+ ..Default::default()+ },+ serde_json::json!({+ "session_id": direct_session.to_string(),+ "cwd": tmp.path(),+ }),+ );+ process(&state, envelope, None).await.unwrap();+ }+ assert!(+ state+ .reader+ .latest_open_handoff(state.workspace_id, state.project_id, None)+ .await+ .unwrap()+ .is_some(),+ "direct launches must retain the legacy SessionEnd handoff behavior"+ );+ }+#[tokio::test]async fn already_ended_session_end_does_not_create_summary_or_handoff() {let tmp = TempDir::new().unwrap();@@ -4889,6 +5127,8 @@ mod tests {project_strategy: None,briefing: None,briefing_budget: None,+ managed_run: None,+ session_id: None,},None,)@@ -4962,6 +5202,8 @@ mod tests {project_strategy: None,briefing: briefing.map(str::to_owned),briefing_budget: None,+ managed_run: None,+ session_id: None,};// Non-truthy opt-in: no handoff pending, nothing to inject.@@ -5122,6 +5364,8 @@ mod tests {project_strategy: None,briefing: None,briefing_budget: None,+ managed_run: None,+ session_id: None,},None,)diff --git a/crates/ai-memory-hooks/src/workstream.rs b/crates/ai-memory-hooks/src/workstream.rsnew file mode 100644index 00000000..45ce6471--- /dev/null+++ b/crates/ai-memory-hooks/src/workstream.rs@@ -0,0 +1,605 @@+//! Authenticated HTTP ingress for optional managed workstreams.++use std::fmt::Write as _;+use std::path::{Path, PathBuf};+use std::str::FromStr as _;++use ai_memory_core::{+ AgentKind, AuthLevel, Capability, FinishManagedRunRequest, FinishManagedRunResponse,+ LinkManagedRunRequest, ManagedRunId, ManagedRunStatus, NewWorkstreamEvent,+ PrepareManagedRunRequest, PrepareManagedRunResponse, Sanitizer, WorkstreamEventKind,+ WorkstreamId,+};+use ai_memory_store::{+ FinishWorkstreamRun, PrepareWorkstreamRun, ReaderPool, StoreError, WorkstreamSelection,+ WriterHandle, create_explicit_scope,+};+use axum::extract::{Path as AxumPath, Query, State};+use axum::http::StatusCode;+use axum::response::{IntoResponse, Response};+use axum::routing::{get, post};+use axum::{Extension, Json, Router};+use serde::{Deserialize, Serialize};+use sha2::{Digest as _, Sha256};+use tracing::warn;++const MAX_EVENTS_PER_FINISH: usize = 4_096;+const MAX_EVENT_CONTENT_BYTES: usize = 64 * 1024;+const MAX_EVENT_ID_BYTES: usize = 512;+const MAX_NATIVE_SESSION_ID_BYTES: usize = 512;+const MAX_METADATA_BYTES: usize = 16 * 1024;+const MAX_NAME_BYTES: usize = 256;+const MAX_CWD_BYTES: usize = 16 * 1024;++/// State shared by the managed-workstream HTTP endpoints.+#[derive(Clone)]+pub struct WorkstreamState {+ /// Single-writer store actor.+ pub writer: WriterHandle,+ /// Read pool for status and packet assembly.+ pub reader: ReaderPool,+ /// Privacy scrubber applied before raw or indexed persistence.+ pub sanitizer: Sanitizer,+ /// ai-memory data root containing `raw/workstreams`.+ pub data_dir: PathBuf,+}++/// Build the host-wrapper API. It is mounted beside `/hook` and therefore+/// receives the same bearer-auth middleware as MCP and hook ingress.+pub fn workstream_router(state: WorkstreamState) -> Router {+ Router::new()+ .route("/workstream/runs", post(prepare_run))+ .route("/workstream/runs/{run_id}", get(run_status))+ .route("/workstream/runs/{run_id}/heartbeat", post(heartbeat_run))+ .route("/workstream/runs/{run_id}/link", post(link_run))+ .route("/workstream/runs/{run_id}/finish", post(finish_run))+ .route("/workstream/{workstream_id}/events", get(search_events))+ .with_state(state)+}++#[derive(Debug, Serialize)]+struct ApiError {+ error: String,+}++type ApiFailure = (StatusCode, Json<ApiError>);++fn api_failure(status: StatusCode, message: impl Into<String>) -> ApiFailure {+ (+ status,+ Json(ApiError {+ error: message.into(),+ }),+ )+}++fn error(status: StatusCode, message: impl Into<String>) -> Response {+ api_failure(status, message).into_response()+}++fn authorize(+ level: Option<Extension<AuthLevel>>,+ capability: Capability,+) -> Result<(), ApiFailure> {+ let level = level.map_or(AuthLevel::Anonymous, |Extension(level)| level);+ level.authorize(capability, true).map_err(|failure| {+ let status = if failure.is_authentication_required() {+ StatusCode::UNAUTHORIZED+ } else {+ StatusCode::FORBIDDEN+ };+ api_failure(status, failure.message())+ })+}++async fn prepare_run(+ State(state): State<WorkstreamState>,+ level: Option<Extension<AuthLevel>>,+ Json(request): Json<PrepareManagedRunRequest>,+) -> Response {+ if let Err(response) = authorize(level, Capability::NormalWrite) {+ return response.into_response();+ }+ if request.workspace.trim().is_empty()+ || request.project.trim().is_empty()+ || request.cwd.trim().is_empty()+ || request.repo_fingerprint.trim().is_empty()+ || request.worktree_fingerprint.trim().is_empty()+ || request.lease_owner.trim().is_empty()+ {+ return error(+ StatusCode::BAD_REQUEST,+ "managed run fields cannot be empty",+ );+ }+ if request.cwd.len() > MAX_CWD_BYTES {+ return error(StatusCode::BAD_REQUEST, "managed run cwd is too long");+ }+ if request.workstream.is_some() && request.new_workstream.is_some() {+ return error(+ StatusCode::BAD_REQUEST,+ "workstream and new_workstream are mutually exclusive",+ );+ }+ if !matches!(+ request.agent,+ AgentKind::ClaudeCode+ | AgentKind::Codex+ | AgentKind::OpenCode+ | AgentKind::Pi+ | AgentKind::Omp+ ) {+ return error(+ StatusCode::BAD_REQUEST,+ "managed run requires a supported command-line harness",+ );+ }+ for (label, value) in [+ ("workspace", request.workspace.as_str()),+ ("project", request.project.as_str()),+ ("repo_fingerprint", request.repo_fingerprint.as_str()),+ (+ "worktree_fingerprint",+ request.worktree_fingerprint.as_str(),+ ),+ ("lease_owner", request.lease_owner.as_str()),+ ] {+ if value.len() > MAX_NAME_BYTES {+ return error(StatusCode::BAD_REQUEST, format!("{label} is too long"));+ }+ }+ let scope = match create_explicit_scope(+ &state.writer,+ request.workspace.trim(),+ request.project.trim(),+ )+ .await+ {+ Ok(scope) => scope,+ Err(failure) => return error(StatusCode::BAD_REQUEST, failure.to_string()),+ };+ let selection = match (request.workstream, request.new_workstream) {+ (Some(name), None) => WorkstreamSelection::Named(name.trim().to_string()),+ (None, Some(name)) => WorkstreamSelection::New(name.trim().to_string()),+ (None, None) => WorkstreamSelection::Current,+ (Some(_), Some(_)) => {+ return error(+ StatusCode::BAD_REQUEST,+ "workstream and new_workstream are mutually exclusive",+ );+ }+ };+ let prepared = state+ .writer+ .prepare_workstream_run(PrepareWorkstreamRun {+ workspace_id: scope.workspace_id,+ project_id: scope.project_id,+ repo_fingerprint: request.repo_fingerprint,+ worktree_fingerprint: request.worktree_fingerprint,+ cwd: request.cwd,+ agent: request.agent,+ selection,+ lease_owner: request.lease_owner,+ })+ .await;+ match prepared {+ Ok(prepared) => Json(PrepareManagedRunResponse {+ workstream_id: prepared.workstream_id,+ workstream_name: prepared.workstream_name,+ run_id: prepared.run_id,+ native_session_id: prepared.native_session_id,+ source_cursor: prepared.source_cursor,+ sync_after: prepared.sync_after,+ sync_through: prepared.sync_through,+ })+ .into_response(),+ Err(failure) => store_error_response(failure),+ }+}++async fn run_status(+ State(state): State<WorkstreamState>,+ level: Option<Extension<AuthLevel>>,+ AxumPath(raw_run_id): AxumPath<String>,+) -> Response {+ if let Err(response) = authorize(level, Capability::NormalRead) {+ return response.into_response();+ }+ let run_id = match parse_run_id(&raw_run_id) {+ Ok(id) => id,+ Err(response) => return response.into_response(),+ };+ match state.reader.managed_run_status(run_id).await {+ Ok(Some(status)) => Json(ManagedRunStatus {+ run_id: status.run_id,+ workstream_id: status.workstream_id,+ agent: status.agent,+ native_session_id: status.native_session_id,+ context_delivered: status.context_delivered,+ state: status.state,+ })+ .into_response(),+ Ok(None) => error(StatusCode::NOT_FOUND, "managed run not found"),+ Err(failure) => error(StatusCode::INTERNAL_SERVER_ERROR, failure.to_string()),+ }+}++async fn heartbeat_run(+ State(state): State<WorkstreamState>,+ level: Option<Extension<AuthLevel>>,+ AxumPath(raw_run_id): AxumPath<String>,+) -> Response {+ if let Err(response) = authorize(level, Capability::NormalWrite) {+ return response.into_response();+ }+ let run_id = match parse_run_id(&raw_run_id) {+ Ok(id) => id,+ Err(response) => return response.into_response(),+ };+ match state.writer.heartbeat_managed_run(run_id).await {+ Ok(true) => StatusCode::NO_CONTENT.into_response(),+ Ok(false) => error(StatusCode::CONFLICT, "managed run lease is not active"),+ Err(failure) => store_error_response(failure),+ }+}++#[derive(Debug, Default, Deserialize)]+struct EventQuery {+ #[serde(default)]+ q: String,+ #[serde(default = "default_event_limit")]+ limit: usize,+}++const fn default_event_limit() -> usize {+ 20+}++async fn search_events(+ State(state): State<WorkstreamState>,+ level: Option<Extension<AuthLevel>>,+ AxumPath(raw_workstream_id): AxumPath<String>,+ Query(query): Query<EventQuery>,+) -> Response {+ if let Err(response) = authorize(level, Capability::NormalRead) {+ return response.into_response();+ }+ let workstream_id = match WorkstreamId::from_str(&raw_workstream_id) {+ Ok(id) => id,+ Err(_) => return error(StatusCode::BAD_REQUEST, "invalid workstream id"),+ };+ match state+ .reader+ .search_workstream_events(workstream_id, query.q, query.limit.clamp(1, 100))+ .await+ {+ Ok(events) => Json(events).into_response(),+ Err(failure) => error(StatusCode::INTERNAL_SERVER_ERROR, failure.to_string()),+ }+}++async fn link_run(+ State(state): State<WorkstreamState>,+ level: Option<Extension<AuthLevel>>,+ AxumPath(raw_run_id): AxumPath<String>,+ Json(request): Json<LinkManagedRunRequest>,+) -> Response {+ if let Err(response) = authorize(level, Capability::NormalWrite) {+ return response.into_response();+ }+ let run_id = match parse_run_id(&raw_run_id) {+ Ok(id) => id,+ Err(response) => return response.into_response(),+ };+ if request.native_session_id.trim().is_empty()+ || request.native_session_id.len() > MAX_NATIVE_SESSION_ID_BYTES+ {+ return error(StatusCode::BAD_REQUEST, "invalid native session id");+ }+ let status = match state.reader.managed_run_status(run_id).await {+ Ok(Some(status)) => status,+ Ok(None) => return error(StatusCode::NOT_FOUND, "managed run not found"),+ Err(failure) => return error(StatusCode::INTERNAL_SERVER_ERROR, failure.to_string()),+ };+ if status.state != "active" {+ return error(StatusCode::CONFLICT, "managed run is not active");+ }+ match state+ .writer+ .link_managed_run_session(run_id, status.agent, request.native_session_id)+ .await+ {+ Ok(true) => StatusCode::NO_CONTENT.into_response(),+ Ok(false) => error(StatusCode::CONFLICT, "managed run is not active"),+ Err(failure) => store_error_response(failure),+ }+}++async fn finish_run(+ State(state): State<WorkstreamState>,+ level: Option<Extension<AuthLevel>>,+ AxumPath(raw_run_id): AxumPath<String>,+ Json(mut request): Json<FinishManagedRunRequest>,+) -> Response {+ if let Err(response) = authorize(level, Capability::NormalWrite) {+ return response.into_response();+ }+ let run_id = match parse_run_id(&raw_run_id) {+ Ok(id) => id,+ Err(response) => return response.into_response(),+ };+ if request.events.len() > MAX_EVENTS_PER_FINISH {+ return error(+ StatusCode::PAYLOAD_TOO_LARGE,+ format!("at most {MAX_EVENTS_PER_FINISH} events are accepted per finish"),+ );+ }+ if request+ .native_session_id+ .as_deref()+ .is_some_and(|id| id.trim().is_empty() || id.len() > MAX_NATIVE_SESSION_ID_BYTES)+ {+ return error(StatusCode::BAD_REQUEST, "invalid native session id");+ }+ let status = match state.reader.managed_run_status(run_id).await {+ Ok(Some(status)) => status,+ Ok(None) => return error(StatusCode::NOT_FOUND, "managed run not found"),+ Err(failure) => return error(StatusCode::INTERNAL_SERVER_ERROR, failure.to_string()),+ };+ if status.state == "finished" {+ return match state+ .writer+ .finish_workstream_run(FinishWorkstreamRun {+ run_id,+ native_session_id: None,+ source_cursor: None,+ events: Vec::new(),+ complete: true,+ segment_path: None,+ exit_code: None,+ })+ .await+ {+ Ok(result) => Json(FinishManagedRunResponse {+ imported_events: 0,+ latest_sequence: result.latest_sequence,+ })+ .into_response(),+ Err(failure) => store_error_response(failure),+ };+ }+ if status.state != "active" {+ return error(StatusCode::CONFLICT, "managed run is not active");+ }+ let native_session_id = request+ .native_session_id+ .clone()+ .or(status.native_session_id.clone())+ .unwrap_or_else(|| format!("unresolved:{run_id}"));+ if let Err(message) = sanitize_events(+ &state.sanitizer,+ status.agent,+ &native_session_id,+ &mut request.events,+ ) {+ return error(StatusCode::BAD_REQUEST, message);+ }+ if request.complete {+ append_boundary_events(+ &state.sanitizer,+ run_id,+ status.agent,+ &native_session_id,+ &mut request,+ );+ }+ let segment_path = match write_segment(+ &state.data_dir,+ status.workstream_id,+ run_id,+ &request.events,+ ) {+ Ok(path) => path,+ Err(failure) => {+ warn!(error = %failure, run = %run_id, "managed transcript segment write failed");+ return error(StatusCode::INTERNAL_SERVER_ERROR, failure.to_string());+ }+ };+ let input = FinishWorkstreamRun {+ run_id,+ native_session_id: request.native_session_id.or(status.native_session_id),+ source_cursor: request.source_cursor,+ events: request.events,+ complete: request.complete,+ segment_path: Some(segment_path),+ exit_code: request.exit_code,+ };+ match state.writer.finish_workstream_run(input).await {+ Ok(result) => Json(FinishManagedRunResponse {+ imported_events: result.imported_events,+ latest_sequence: result.latest_sequence,+ })+ .into_response(),+ Err(failure) => store_error_response(failure),+ }+}++fn parse_run_id(raw: &str) -> Result<ManagedRunId, ApiFailure> {+ ManagedRunId::from_str(raw).map_err(|_| api_failure(StatusCode::BAD_REQUEST, "invalid run id"))+}++fn store_error_response(failure: StoreError) -> Response {+ let status = match failure {+ StoreError::WorkstreamBusy(_) | StoreError::Duplicate(_) => StatusCode::CONFLICT,+ StoreError::NotFound(_) => StatusCode::NOT_FOUND,+ StoreError::InvalidState(_) => StatusCode::BAD_REQUEST,+ _ => StatusCode::INTERNAL_SERVER_ERROR,+ };+ error(status, failure.to_string())+}++fn sanitize_events(+ sanitizer: &Sanitizer,+ expected_agent: AgentKind,+ expected_session: &str,+ events: &mut [NewWorkstreamEvent],+) -> Result<(), String> {+ for event in events {+ if event.agent != expected_agent {+ return Err(format!(+ "event {} agent does not match managed run",+ event.event_id+ ));+ }+ if event.native_session_id != expected_session {+ return Err(format!(+ "event {} native session does not match managed run",+ event.event_id+ ));+ }+ if event.event_id.trim().is_empty() || event.event_id.len() > MAX_EVENT_ID_BYTES {+ return Err("invalid workstream event id".to_string());+ }+ if event.content.len() > MAX_EVENT_CONTENT_BYTES {+ let mut end = MAX_EVENT_CONTENT_BYTES;+ while !event.content.is_char_boundary(end) {+ end -= 1;+ }+ event.content.truncate(end);+ event.content.push_str("\n[truncated by ai-memory]");+ }+ event.content = sanitizer.scrub(&event.content);+ if let Some(role) = &event.role+ && (role.len() > 32+ || !role+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-')))+ {+ return Err("invalid workstream message role".to_string());+ }+ let raw_metadata = serde_json::to_string(&event.metadata).map_err(|e| e.to_string())?;+ if raw_metadata.len() > MAX_METADATA_BYTES {+ event.metadata = serde_json::json!({ "truncated": true });+ } else {+ let scrubbed = sanitizer.scrub(&raw_metadata);+ event.metadata = serde_json::from_str(&scrubbed)+ .unwrap_or_else(|_| serde_json::json!({ "redacted": true }));+ }+ }+ Ok(())+}++fn append_boundary_events(+ sanitizer: &Sanitizer,+ run_id: ManagedRunId,+ agent: AgentKind,+ native_session_id: &str,+ request: &mut FinishManagedRunRequest,+) {+ let mut checkpoint = String::new();+ if let Some(head) = &request.checkpoint.head {+ let _ = writeln!(checkpoint, "HEAD: {head}");+ }+ if let Some(branch) = &request.checkpoint.branch {+ let _ = writeln!(checkpoint, "Branch: {branch}");+ }+ if let Some(dirty_hash) = &request.checkpoint.dirty_hash {+ let _ = writeln!(checkpoint, "Dirty-state hash: {dirty_hash}");+ }+ if !request.checkpoint.changed_paths.is_empty() {+ checkpoint.push_str("Changed paths:\n");+ for path in &request.checkpoint.changed_paths {+ let _ = writeln!(checkpoint, "- {path}");+ }+ }+ if checkpoint.is_empty() {+ checkpoint.push_str("No Git repository checkpoint was available.");+ }+ truncate_owned(&mut checkpoint, MAX_EVENT_CONTENT_BYTES);+ request.events.push(NewWorkstreamEvent {+ event_id: format!("managed-run:{run_id}:checkpoint"),+ agent,+ native_session_id: native_session_id.to_string(),+ source_record_id: None,+ kind: WorkstreamEventKind::Checkpoint,+ role: None,+ content: sanitizer.scrub(&checkpoint),+ occurred_at: None,+ metadata: serde_json::json!({ "exit_code": request.exit_code }),+ });+ if !request.losses.is_empty() {+ let mut content = String::from("Transcript extraction losses:\n");+ for loss in &request.losses {+ let _ = writeln!(content, "- {loss}");+ }+ truncate_owned(&mut content, MAX_EVENT_CONTENT_BYTES);+ request.events.push(NewWorkstreamEvent {+ event_id: format!("managed-run:{run_id}:losses"),+ agent,+ native_session_id: native_session_id.to_string(),+ source_record_id: None,+ kind: WorkstreamEventKind::Annotation,+ role: None,+ content: sanitizer.scrub(&content),+ occurred_at: None,+ metadata: serde_json::json!({ "loss_count": request.losses.len() }),+ });+ }+}++fn write_segment(+ data_dir: &Path,+ workstream_id: ai_memory_core::WorkstreamId,+ run_id: ManagedRunId,+ events: &[NewWorkstreamEvent],+) -> std::io::Result<String> {+ let mut bytes = Vec::new();+ for event in events {+ serde_json::to_writer(&mut bytes, event).map_err(std::io::Error::other)?;+ bytes.push(b'\n');+ }+ let digest = Sha256::digest(&bytes);+ let digest_hex = format!("{digest:x}");+ let relative = PathBuf::from("workstreams")+ .join(workstream_id.to_string())+ .join("segments")+ .join(format!("{run_id}-{}.jsonl", &digest_hex[..16]));+ let target = data_dir.join("raw").join(&relative);+ let parent = target+ .parent()+ .ok_or_else(|| std::io::Error::other("managed segment has no parent"))?;+ std::fs::create_dir_all(parent)?;+ if target.exists() {+ return Ok(relative.to_string_lossy().replace('\\', "/"));+ }+ let temp = parent.join(format!(".{run_id}-{}.tmp", ManagedRunId::new()));+ {+ use std::io::Write as _;+ let mut file = std::fs::OpenOptions::new()+ .write(true)+ .create_new(true)+ .open(&temp)?;+ file.write_all(&bytes)?;+ file.sync_all()?;+ }+ if let Err(failure) = std::fs::rename(&temp, &target) {+ let target_won_race = target.exists();+ let _ = std::fs::remove_file(&temp);+ if !target_won_race {+ return Err(failure);+ }+ }+ Ok(relative.to_string_lossy().replace('\\', "/"))+}++fn truncate_owned(value: &mut String, max: usize) {+ if value.len() <= max {+ return;+ }+ let mut end = max;+ while !value.is_char_boundary(end) {+ end -= 1;+ }+ value.truncate(end);+ value.push_str("\n[truncated by ai-memory]");+}diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 1a580125..94eaf677 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -167,8 +167,10 @@ cannot forward the real agent session id automatically; pass explicit \`workspace` + `project` / `scopes`, or use a session-aware bridge that \forwards the lifecycle-hook session id on MCP calls.\n\\n\-Lifecycle hooks already capture every prompt + tool call automatically \-— you do NOT need to write routine notes by hand. When the user \+Lifecycle hooks already capture sanitized, bounded prompt and tool-lifecycle \+observations automatically. They are not complete native transcripts; managed \+`ai-memory run` launches add the portable visible-event ledger. You do NOT \+need to write routine notes by hand. When the user \explicitly asks to remember a permanent annotation/fact/rule, write a \durable wiki page; do not use a handoff for that. Use these tools when \the conversation calls for them:\n\diff --git a/crates/ai-memory-store/migrations/V31__managed_workstreams.sql b/crates/ai-memory-store/migrations/V31__managed_workstreams.sqlnew file mode 100644index 00000000..7c2722ee--- /dev/null+++ b/crates/ai-memory-store/migrations/V31__managed_workstreams.sql@@ -0,0 +1,116 @@+-- Optional `ai-memory run` workstreams. Direct harness launches continue to+-- use sessions/observations/handoffs and never touch these tables.++CREATE TABLE workstreams (+ 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,+ repo_fingerprint TEXT NOT NULL,+ worktree_fingerprint TEXT NOT NULL,+ name TEXT NOT NULL,+ cwd TEXT NOT NULL,+ created_at INTEGER NOT NULL,+ selected_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ UNIQUE (workspace_id, project_id, repo_fingerprint, worktree_fingerprint, name)+);++CREATE TRIGGER workstreams_ws_proj_pairing_ai+BEFORE INSERT ON workstreams+FOR EACH ROW+WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM projects WHERE id = NEW.project_id)+BEGIN+ SELECT RAISE(ABORT, 'workstreams.workspace_id does not match the project''s workspace');+END;++CREATE INDEX idx_workstreams_selected+ ON workstreams(workspace_id, project_id, repo_fingerprint, worktree_fingerprint, selected_at DESC);++CREATE TABLE workstream_native_sessions (+ workstream_id BLOB NOT NULL REFERENCES workstreams(id) ON DELETE CASCADE,+ agent_kind TEXT NOT NULL,+ native_session_id TEXT NOT NULL,+ is_current INTEGER NOT NULL DEFAULT 1 CHECK (is_current IN (0, 1)),+ source_cursor TEXT,+ delivery_cursor INTEGER NOT NULL DEFAULT 0,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ PRIMARY KEY (workstream_id, agent_kind, native_session_id)+);++CREATE UNIQUE INDEX idx_workstream_native_current+ ON workstream_native_sessions(workstream_id, agent_kind)+ WHERE is_current = 1;++CREATE TABLE managed_runs (+ id BLOB PRIMARY KEY NOT NULL,+ workstream_id BLOB NOT NULL REFERENCES workstreams(id) ON DELETE CASCADE,+ agent_kind TEXT NOT NULL,+ lease_owner TEXT NOT NULL,+ native_session_id TEXT,+ state TEXT NOT NULL CHECK (state IN ('active', 'finished', 'expired')),+ sync_after INTEGER NOT NULL DEFAULT 0,+ sync_through INTEGER NOT NULL DEFAULT 0,+ context_delivered INTEGER NOT NULL DEFAULT 0 CHECK (context_delivered IN (0, 1)),+ lease_expires_at INTEGER NOT NULL,+ started_at INTEGER NOT NULL,+ ended_at INTEGER,+ exit_code INTEGER+);++CREATE UNIQUE INDEX idx_managed_runs_one_active+ ON managed_runs(workstream_id)+ WHERE state = 'active';++CREATE INDEX idx_managed_runs_lease+ ON managed_runs(state, lease_expires_at);++CREATE TABLE workstream_events (+ workstream_id BLOB NOT NULL REFERENCES workstreams(id) ON DELETE CASCADE,+ sequence INTEGER NOT NULL,+ event_id TEXT NOT NULL,+ agent_kind TEXT NOT NULL,+ native_session_id TEXT NOT NULL,+ source_record_id TEXT,+ kind TEXT NOT NULL CHECK (kind IN (+ 'message', 'tool_call', 'tool_result',+ 'compaction', 'checkpoint', 'annotation'+ )),+ role TEXT,+ content TEXT NOT NULL,+ occurred_at TEXT,+ metadata_json TEXT NOT NULL DEFAULT '{}',+ segment_path TEXT,+ created_at INTEGER NOT NULL,+ PRIMARY KEY (workstream_id, sequence),+ UNIQUE (workstream_id, event_id)+);++CREATE INDEX idx_workstream_events_recent+ ON workstream_events(workstream_id, sequence DESC);++CREATE VIRTUAL TABLE workstream_events_fts USING fts5(+ content,+ role UNINDEXED,+ agent_kind UNINDEXED,+ content='workstream_events',+ content_rowid='rowid',+ tokenize='unicode61 remove_diacritics 2'+);++CREATE TRIGGER workstream_events_fts_ai AFTER INSERT ON workstream_events BEGIN+ INSERT INTO workstream_events_fts(rowid, content, role, agent_kind)+ VALUES (new.rowid, new.content, new.role, new.agent_kind);+END;++CREATE TRIGGER workstream_events_fts_ad AFTER DELETE ON workstream_events BEGIN+ INSERT INTO workstream_events_fts(workstream_events_fts, rowid, content, role, agent_kind)+ VALUES ('delete', old.rowid, old.content, old.role, old.agent_kind);+END;++CREATE TRIGGER workstream_events_fts_au AFTER UPDATE ON workstream_events BEGIN+ INSERT INTO workstream_events_fts(workstream_events_fts, rowid, content, role, agent_kind)+ VALUES ('delete', old.rowid, old.content, old.role, old.agent_kind);+ INSERT INTO workstream_events_fts(rowid, content, role, agent_kind)+ VALUES (new.rowid, new.content, new.role, new.agent_kind);+END;diff --git a/crates/ai-memory-store/src/error.rs b/crates/ai-memory-store/src/error.rsindex 3965ab89..9b643d07 100644--- a/crates/ai-memory-store/src/error.rs+++ b/crates/ai-memory-store/src/error.rs@@ -111,4 +111,8 @@ pub enum StoreError {/// A requested state transition is not allowed.#[error("invalid state: {0}")]InvalidState(String),++ /// A live `ai-memory run` lease already owns the selected workstream.+ #[error("workstream is already active: {0}")]+ WorkstreamBusy(String),}diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex aac0d1df..0bd1b827 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -22,6 +22,7 @@ mod ops;mod reader;mod scope;pub mod users;+mod workstream;mod writer;pub use fts_query::prepare_fts5_query;@@ -52,6 +53,10 @@ pub use scope::{lookup_global_scope, resolve_many_existing_scopes,};pub use users::{TOKEN_HASH_LEN, TOKEN_RAW_LEN, TokenPepper, generate_token, hash_token};+pub use workstream::{+ FinishWorkstreamRun, FinishedWorkstreamRun, ManagedRunContext, PrepareWorkstreamRun,+ PreparedWorkstreamRun, StoredManagedRunStatus, WorkstreamSelection,+};pub use writer::WriterHandle;/// Filename used inside the data dir's `db/` subdirectory.@@ -114,8 +119,9 @@ impl Store {mod tests {use super::*;use ai_memory_core::{- ActorContext, AgentKind, LinkTarget, NewObservation, NewPage, NewSession, ObservationId,- ObservationKind, PageId, PagePath, ProjectId, SessionId, Tier, UserId, WorkspaceId,+ ActorContext, AgentKind, LinkTarget, NewObservation, NewPage, NewSession,+ NewWorkstreamEvent, ObservationId, ObservationKind, PageId, PagePath, ProjectId, SessionId,+ Tier, UserId, WorkspaceId, WorkstreamEventKind,};use rusqlite::{Connection, params};use sha2::{Digest, Sha256};@@ -3288,4 +3294,286 @@ mod tests {.unwrap();assert!(mismatch.is_empty());}++ #[tokio::test]+ async fn managed_workstream_batches_are_idempotent_and_release_the_lease() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let project = store+ .writer+ .get_or_create_project(ws, "managed", None)+ .await+ .unwrap();+ let prepare = PrepareWorkstreamRun {+ workspace_id: ws,+ project_id: project,+ repo_fingerprint: "repo".into(),+ worktree_fingerprint: "worktree".into(),+ cwd: "/repo".into(),+ agent: AgentKind::Codex,+ selection: WorkstreamSelection::Current,+ lease_owner: "test:1".into(),+ };+ let run = store+ .writer+ .prepare_workstream_run(prepare.clone())+ .await+ .unwrap();+ let busy = store+ .writer+ .prepare_workstream_run(prepare.clone())+ .await+ .unwrap_err();+ assert!(matches!(busy, StoreError::WorkstreamBusy(_)));+ assert!(+ store+ .writer+ .link_managed_run_session(run.run_id, AgentKind::Codex, "native-1")+ .await+ .unwrap()+ );++ let event = NewWorkstreamEvent {+ event_id: "event-1".into(),+ agent: AgentKind::Codex,+ native_session_id: "native-1".into(),+ source_record_id: Some("record-1".into()),+ kind: WorkstreamEventKind::Message,+ role: Some("assistant".into()),+ content: "portable context".into(),+ occurred_at: None,+ metadata: serde_json::json!({}),+ };+ let partial = FinishWorkstreamRun {+ run_id: run.run_id,+ native_session_id: Some("native-1".into()),+ source_cursor: None,+ events: vec![event.clone()],+ complete: false,+ segment_path: Some("segment-1.jsonl".into()),+ exit_code: None,+ };+ assert_eq!(+ store+ .writer+ .finish_workstream_run(partial.clone())+ .await+ .unwrap()+ .imported_events,+ 1+ );+ assert_eq!(+ store+ .writer+ .finish_workstream_run(partial)+ .await+ .unwrap()+ .imported_events,+ 0+ );+ assert_eq!(+ store+ .reader+ .managed_run_status(run.run_id)+ .await+ .unwrap()+ .unwrap()+ .state,+ "active"+ );++ let finished = store+ .writer+ .finish_workstream_run(FinishWorkstreamRun {+ run_id: run.run_id,+ native_session_id: Some("native-1".into()),+ source_cursor: Some("cursor-1".into()),+ events: vec![event],+ complete: true,+ segment_path: Some("segment-final.jsonl".into()),+ exit_code: Some(0),+ })+ .await+ .unwrap();+ assert_eq!(finished.imported_events, 0);+ let search = store+ .reader+ .search_workstream_events(run.workstream_id, "portable".into(), 10)+ .await+ .unwrap();+ assert_eq!(search.len(), 1);+ assert_eq!(search[0].event_id, "event-1");+ let next = store+ .writer+ .prepare_workstream_run(prepare.clone())+ .await+ .unwrap();+ assert_eq!(next.workstream_id, run.workstream_id);+ assert_eq!(next.native_session_id.as_deref(), Some("native-1"));+ assert_eq!(next.source_cursor.as_deref(), Some("cursor-1"));+ assert_eq!(next.sync_through, 1);+ assert!(+ store+ .writer+ .link_managed_run_session(next.run_id, AgentKind::Codex, "native-2")+ .await+ .unwrap()+ );+ let fresh_context = store+ .reader+ .managed_run_context(next.run_id, 256)+ .await+ .unwrap()+ .unwrap();+ assert_eq!(fresh_context.sync_after, 0);+ assert_eq!(fresh_context.events.len(), 1);+ assert!(+ store+ .writer+ .accept_managed_run_context(next.run_id)+ .await+ .unwrap()+ );+ assert!(+ !store+ .writer+ .link_managed_run_session(next.run_id, AgentKind::Codex, "native-3")+ .await+ .unwrap(),+ "a delivered run must not be rebound by a nested same-agent process"+ );+ store+ .writer+ .finish_workstream_run(FinishWorkstreamRun {+ run_id: next.run_id,+ native_session_id: Some("native-2".into()),+ source_cursor: Some("cursor-2".into()),+ events: Vec::new(),+ complete: true,+ segment_path: Some("segment-native-2.jsonl".into()),+ exit_code: Some(0),+ })+ .await+ .unwrap();+ let retry = store+ .writer+ .prepare_workstream_run(prepare.clone())+ .await+ .unwrap();+ assert_eq!(retry.native_session_id.as_deref(), Some("native-2"));+ assert_eq!(+ retry.sync_after, 1,+ "delivered context must stay acknowledged"+ );+ assert_eq!(retry.sync_through, 1);+ assert!(+ store+ .writer+ .link_managed_run_session(retry.run_id, AgentKind::Codex, "native-3")+ .await+ .unwrap()+ );+ store+ .writer+ .finish_workstream_run(FinishWorkstreamRun {+ run_id: retry.run_id,+ native_session_id: Some("native-3".into()),+ source_cursor: Some("cursor-3".into()),+ events: Vec::new(),+ complete: true,+ segment_path: Some("segment-native-3.jsonl".into()),+ exit_code: Some(0),+ })+ .await+ .unwrap();+ let undelivered = store.writer.prepare_workstream_run(prepare).await.unwrap();+ assert_eq!(undelivered.native_session_id.as_deref(), Some("native-3"));+ assert_eq!(+ undelivered.sync_after, 0,+ "undelivered context must be retried"+ );+ assert_eq!(undelivered.sync_through, 1);+ }++ #[tokio::test]+ async fn managed_workstreams_are_isolated_across_workspaces() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let mut runs = Vec::new();++ for (workspace_name, content) in [+ ("workspace-a", "only visible in workspace a"),+ ("workspace-b", "only visible in workspace b"),+ ] {+ let workspace = store+ .writer+ .get_or_create_workspace(workspace_name)+ .await+ .unwrap();+ let project = store+ .writer+ .get_or_create_project(workspace, "shared-name", None)+ .await+ .unwrap();+ let run = store+ .writer+ .prepare_workstream_run(PrepareWorkstreamRun {+ workspace_id: workspace,+ project_id: project,+ repo_fingerprint: "same-repository".into(),+ worktree_fingerprint: "same-worktree".into(),+ cwd: "/same/path".into(),+ agent: AgentKind::Codex,+ selection: WorkstreamSelection::Current,+ lease_owner: workspace_name.into(),+ })+ .await+ .unwrap();+ store+ .writer+ .finish_workstream_run(FinishWorkstreamRun {+ run_id: run.run_id,+ native_session_id: Some(format!("native-{workspace_name}")),+ source_cursor: Some("cursor".into()),+ events: vec![NewWorkstreamEvent {+ event_id: "same-native-event-id".into(),+ agent: AgentKind::Codex,+ native_session_id: format!("native-{workspace_name}"),+ source_record_id: None,+ kind: WorkstreamEventKind::Message,+ role: Some("assistant".into()),+ content: content.into(),+ occurred_at: None,+ metadata: serde_json::json!({}),+ }],+ complete: true,+ segment_path: None,+ exit_code: Some(0),+ })+ .await+ .unwrap();+ runs.push(run);+ }++ assert_ne!(runs[0].workstream_id, runs[1].workstream_id);+ let first = store+ .reader+ .search_workstream_events(runs[0].workstream_id, "visible".into(), 10)+ .await+ .unwrap();+ let second = store+ .reader+ .search_workstream_events(runs[1].workstream_id, "visible".into(), 10)+ .await+ .unwrap();+ assert_eq!(first.len(), 1);+ assert_eq!(first[0].content, "only visible in workspace a");+ assert_eq!(second.len(), 1);+ assert_eq!(second[0].content, "only visible in workspace b");+ }}diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex 5aee0304..ad6af2d8 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -12,8 +12,8 @@ use std::sync::Arc;use ai_memory_core::{AgentKind, AutoImproveProposalId, AutoImproveRunId, Handoff, HandoffId, HandoffState,- Observation, ObservationId, ObservationKind, PageId, PagePath, ProjectId, SessionId, User,- UserId, WorkspaceId,+ ManagedRunId, Observation, ObservationId, ObservationKind, PageId, PagePath, ProjectId,+ SessionId, User, UserId, WorkspaceId, WorkstreamEvent, WorkstreamId,};use jiff::Timestamp;use parking_lot::Mutex;@@ -34,6 +34,7 @@ use crate::error::{StoreError, StoreResult};use crate::fts_query::prepare_fts5_query;use crate::maintenance::MaintenanceJob;use crate::users::TOKEN_HASH_LEN;+use crate::workstream::{ManagedRunContext, StoredManagedRunStatus};fn page_kind_expr(path_column: &str, frontmatter_column: &str) -> String {format!(@@ -685,6 +686,39 @@ impl ReaderPool {.map_err(|e| StoreError::PoolPanic(e.to_string()))?}+ /// Return the current state of one `ai-memory run` invocation.+ pub async fn managed_run_status(+ &self,+ run_id: ManagedRunId,+ ) -> StoreResult<Option<StoredManagedRunStatus>> {+ self.with_conn(move |conn| crate::workstream::run_status(conn, run_id))+ .await+ }++ /// Return the unseen portable range assigned to a managed SessionStart.+ pub async fn managed_run_context(+ &self,+ run_id: ManagedRunId,+ max_events: usize,+ ) -> StoreResult<Option<ManagedRunContext>> {+ self.with_conn(move |conn| crate::workstream::run_context(conn, run_id, max_events))+ .await+ }++ /// Search visible events in one managed workstream, or return its newest+ /// events when `query` is empty.+ pub async fn search_workstream_events(+ &self,+ workstream_id: WorkstreamId,+ query: String,+ limit: usize,+ ) -> StoreResult<Vec<WorkstreamEvent>> {+ self.with_conn(move |conn| {+ crate::workstream::search_events(conn, workstream_id, &query, limit)+ })+ .await+ }+/// Run a full-text search against the FTS5 index and return the top/// matches, limited to `is_latest = 1` rows.///diff --git a/crates/ai-memory-store/src/workstream.rs b/crates/ai-memory-store/src/workstream.rsnew file mode 100644index 00000000..aa137aa8--- /dev/null+++ b/crates/ai-memory-store/src/workstream.rs@@ -0,0 +1,869 @@+//! Store operations for optional `ai-memory run` workstreams.++use std::str::FromStr as _;++use ai_memory_core::{+ AgentKind, ManagedRunId, NewWorkstreamEvent, ProjectId, WorkspaceId, WorkstreamEvent,+ WorkstreamEventKind, WorkstreamId,+};+use jiff::Timestamp;+use rusqlite::{Connection, OptionalExtension as _, Transaction, params};++use crate::{StoreError, StoreResult};++const LEASE_MICROS: i64 = 90 * 1_000_000;+const MAX_WORKSTREAM_NAME_CHARS: usize = 128;++/// How a prepare request chooses the workstream for a repository/worktree.+#[derive(Debug, Clone)]+pub enum WorkstreamSelection {+ /// Continue the most recently selected workstream, creating `default` when+ /// the worktree has never used managed mode.+ Current,+ /// Select an existing named workstream.+ Named(String),+ /// Create and select a fresh named workstream.+ New(String),+}++/// Store-level input for opening a managed run.+#[derive(Debug, Clone)]+pub struct PrepareWorkstreamRun {+ /// Resolved workspace.+ pub workspace_id: WorkspaceId,+ /// Resolved project.+ pub project_id: ProjectId,+ /// Repository identity hash.+ pub repo_fingerprint: String,+ /// Worktree identity hash.+ pub worktree_fingerprint: String,+ /// Host working directory.+ pub cwd: String,+ /// Harness being launched.+ pub agent: AgentKind,+ /// Workstream selection behavior.+ pub selection: WorkstreamSelection,+ /// Diagnostic lease owner.+ pub lease_owner: String,+}++/// Store-level result for a prepared managed run.+#[derive(Debug, Clone)]+pub struct PreparedWorkstreamRun {+ /// Selected workstream.+ pub workstream_id: WorkstreamId,+ /// Selected name.+ pub workstream_name: String,+ /// New invocation/lease id.+ pub run_id: ManagedRunId,+ /// Current native session for the requested harness.+ pub native_session_id: Option<String>,+ /// Last adapter cursor for that native session.+ pub source_cursor: Option<String>,+ /// Last sequence already delivered to that native session.+ pub sync_after: i64,+ /// Workstream high-water mark assigned to the launch.+ pub sync_through: i64,+}++/// Store-level finish input after the raw segment has been made durable.+#[derive(Debug, Clone)]+pub struct FinishWorkstreamRun {+ /// Managed invocation.+ pub run_id: ManagedRunId,+ /// Actual native session, when observed.+ pub native_session_id: Option<String>,+ /// Adapter cursor after export.+ pub source_cursor: Option<String>,+ /// Sanitized normalized events.+ pub events: Vec<NewWorkstreamEvent>,+ /// Close the run and advance its source cursor after this batch.+ pub complete: bool,+ /// Relative immutable raw-segment path.+ pub segment_path: Option<String>,+ /// Child exit code when available.+ pub exit_code: Option<i32>,+}++/// Result of an idempotent finish operation.+#[derive(Debug, Clone, Copy)]+pub struct FinishedWorkstreamRun {+ /// Number of newly indexed events.+ pub imported_events: usize,+ /// Current workstream high-water mark.+ pub latest_sequence: i64,+}++/// State needed to render the SessionStart synchronization packet.+#[derive(Debug, Clone)]+pub struct ManagedRunContext {+ /// Invocation id.+ pub run_id: ManagedRunId,+ /// Workstream id.+ pub workstream_id: WorkstreamId,+ /// Human-readable workstream name.+ pub workstream_name: String,+ /// Harness being launched.+ pub agent: AgentKind,+ /// Linked native session when SessionStart has already reported it.+ pub native_session_id: Option<String>,+ /// Lower delivery cursor.+ pub sync_after: i64,+ /// Assigned high-water mark.+ pub sync_through: i64,+ /// Whether context has already been returned for this invocation.+ pub context_delivered: bool,+ /// Repository checkpoint recorded by the latest event, if any.+ pub events: Vec<WorkstreamEvent>,+}++/// Lightweight status used by the host wrapper after the child exits.+#[derive(Debug, Clone)]+pub struct StoredManagedRunStatus {+ /// Invocation id.+ pub run_id: ManagedRunId,+ /// Workstream id.+ pub workstream_id: WorkstreamId,+ /// Harness.+ pub agent: AgentKind,+ /// Native session observed by hooks.+ pub native_session_id: Option<String>,+ /// SessionStart delivery acknowledgement.+ pub context_delivered: bool,+ /// State string.+ pub state: String,+}++struct FinishRunRow {+ workstream: Vec<u8>,+ agent_wire: String,+ linked_session: Option<String>,+ state: String,+ sync_after: i64,+ sync_through: i64,+ context_delivered: bool,+}++struct LinkRunRow {+ workstream: Vec<u8>,+ agent: String,+ native_session: Option<String>,+ sync_through: i64,+ context_delivered: bool,+}++/// Atomically select a workstream, expire stale leases, and open one run.+pub(crate) fn prepare_run(+ conn: &mut Connection,+ input: &PrepareWorkstreamRun,+) -> StoreResult<PreparedWorkstreamRun> {+ let now = Timestamp::now().as_microsecond();+ let tx = conn.transaction()?;+ tx.execute(+ "UPDATE managed_runs SET state = 'expired', ended_at = ?1 \+ WHERE state = 'active' AND lease_expires_at <= ?1",+ params![now],+ )?;++ let (workstream_id, workstream_name) = select_workstream(&tx, input, now)?;+ let busy: Option<(String, i64)> = tx+ .query_row(+ "SELECT lease_owner, lease_expires_at FROM managed_runs \+ WHERE workstream_id = ?1 AND state = 'active'",+ params![workstream_id.as_bytes()],+ |row| Ok((row.get(0)?, row.get(1)?)),+ )+ .optional()?;+ if let Some((owner, expires)) = busy {+ return Err(StoreError::WorkstreamBusy(format!(+ "owned by {owner} until {}",+ Timestamp::from_microsecond(expires)+ .map(|t| t.to_string())+ .unwrap_or_else(|_| expires.to_string())+ )));+ }++ let latest_sequence: i64 = tx.query_row(+ "SELECT COALESCE(MAX(sequence), 0) FROM workstream_events WHERE workstream_id = ?1",+ params![workstream_id.as_bytes()],+ |row| row.get(0),+ )?;+ let native: Option<(String, Option<String>, i64)> = tx+ .query_row(+ "SELECT native_session_id, source_cursor, delivery_cursor \+ FROM workstream_native_sessions \+ WHERE workstream_id = ?1 AND agent_kind = ?2 AND is_current = 1",+ params![workstream_id.as_bytes(), input.agent.as_str()],+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),+ )+ .optional()?;+ let (native_session_id, source_cursor, sync_after) = native+ .map_or((None, None, 0), |(session, cursor, delivery)| {+ (Some(session), cursor, delivery)+ });++ let run_id = ManagedRunId::new();+ tx.execute(+ "INSERT INTO managed_runs( \+ id, workstream_id, agent_kind, lease_owner, native_session_id, state, \+ sync_after, sync_through, context_delivered, lease_expires_at, started_at \+ ) VALUES (?1, ?2, ?3, ?4, ?5, 'active', ?6, ?7, 0, ?8, ?9)",+ params![+ run_id.as_bytes(),+ workstream_id.as_bytes(),+ input.agent.as_str(),+ input.lease_owner,+ native_session_id,+ sync_after,+ latest_sequence,+ now + LEASE_MICROS,+ now,+ ],+ )?;+ tx.execute(+ "UPDATE workstreams SET selected_at = ?1, updated_at = ?1, cwd = ?2 WHERE id = ?3",+ params![now, input.cwd, workstream_id.as_bytes()],+ )?;+ tx.commit()?;++ Ok(PreparedWorkstreamRun {+ workstream_id,+ workstream_name,+ run_id,+ native_session_id,+ source_cursor,+ sync_after,+ sync_through: latest_sequence,+ })+}++fn select_workstream(+ tx: &Transaction<'_>,+ input: &PrepareWorkstreamRun,+ now: i64,+) -> StoreResult<(WorkstreamId, String)> {+ match &input.selection {+ WorkstreamSelection::New(name) => {+ validate_workstream_name(name)?;+ let exists: bool = tx.query_row(+ "SELECT EXISTS(SELECT 1 FROM workstreams \+ WHERE workspace_id = ?1 AND project_id = ?2 \+ AND repo_fingerprint = ?3 AND worktree_fingerprint = ?4 AND name = ?5)",+ params![+ input.workspace_id.as_bytes(),+ input.project_id.as_bytes(),+ input.repo_fingerprint,+ input.worktree_fingerprint,+ name,+ ],+ |row| row.get(0),+ )?;+ if exists {+ return Err(StoreError::Duplicate(format!(+ "workstream '{name}' already exists; select it with --workstream"+ )));+ }+ insert_workstream(tx, input, name, now)+ }+ WorkstreamSelection::Named(name) => {+ validate_workstream_name(name)?;+ find_named_workstream(tx, input, name)?+ .ok_or_else(|| StoreError::NotFound(format!("managed workstream '{name}'")))+ }+ WorkstreamSelection::Current => {+ let current = tx+ .query_row(+ "SELECT id, name FROM workstreams \+ WHERE workspace_id = ?1 AND project_id = ?2 \+ AND repo_fingerprint = ?3 AND worktree_fingerprint = ?4 \+ ORDER BY selected_at DESC LIMIT 1",+ params![+ input.workspace_id.as_bytes(),+ input.project_id.as_bytes(),+ input.repo_fingerprint,+ input.worktree_fingerprint,+ ],+ |row| {+ let id: Vec<u8> = row.get(0)?;+ let name: String = row.get(1)?;+ Ok((id, name))+ },+ )+ .optional()?;+ match current {+ Some((id, name)) => Ok((WorkstreamId::from_slice(&id)?, name)),+ None => insert_workstream(tx, input, "default", now),+ }+ }+ }+}++fn find_named_workstream(+ tx: &Transaction<'_>,+ input: &PrepareWorkstreamRun,+ name: &str,+) -> StoreResult<Option<(WorkstreamId, String)>> {+ let row = tx+ .query_row(+ "SELECT id, name FROM workstreams \+ WHERE workspace_id = ?1 AND project_id = ?2 \+ AND repo_fingerprint = ?3 AND worktree_fingerprint = ?4 AND name = ?5",+ params![+ input.workspace_id.as_bytes(),+ input.project_id.as_bytes(),+ input.repo_fingerprint,+ input.worktree_fingerprint,+ name,+ ],+ |row| Ok((row.get::<_, Vec<u8>>(0)?, row.get::<_, String>(1)?)),+ )+ .optional()?;+ row.map(|(id, name)| Ok((WorkstreamId::from_slice(&id)?, name)))+ .transpose()+}++fn insert_workstream(+ tx: &Transaction<'_>,+ input: &PrepareWorkstreamRun,+ name: &str,+ now: i64,+) -> StoreResult<(WorkstreamId, String)> {+ let id = WorkstreamId::new();+ tx.execute(+ "INSERT INTO workstreams( \+ id, workspace_id, project_id, repo_fingerprint, worktree_fingerprint, \+ name, cwd, created_at, selected_at, updated_at \+ ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?8, ?8)",+ params![+ id.as_bytes(),+ input.workspace_id.as_bytes(),+ input.project_id.as_bytes(),+ input.repo_fingerprint,+ input.worktree_fingerprint,+ name,+ input.cwd,+ now,+ ],+ )?;+ Ok((id, name.to_string()))+}++fn validate_workstream_name(name: &str) -> StoreResult<()> {+ let trimmed = name.trim();+ if trimmed.is_empty()+ || trimmed.chars().count() > MAX_WORKSTREAM_NAME_CHARS+ || trimmed.chars().any(char::is_control)+ || trimmed.contains(['/', '\\'])+ {+ return Err(StoreError::InvalidState(format!(+ "invalid workstream name '{name}'"+ )));+ }+ Ok(())+}++/// Extend the lease for a live managed run.+pub(crate) fn heartbeat(conn: &mut Connection, run_id: ManagedRunId) -> StoreResult<bool> {+ let now = Timestamp::now().as_microsecond();+ let changed = conn.execute(+ "UPDATE managed_runs SET lease_expires_at = ?1 \+ WHERE id = ?2 AND state = 'active' AND lease_expires_at > ?3",+ params![now + LEASE_MICROS, run_id.as_bytes(), now],+ )?;+ Ok(changed > 0)+}++/// Link the native session reported by a managed child hook.+pub(crate) fn link_native_session(+ conn: &mut Connection,+ run_id: ManagedRunId,+ agent: AgentKind,+ native_session_id: &str,+) -> StoreResult<bool> {+ if native_session_id.trim().is_empty() {+ return Ok(false);+ }+ let now = Timestamp::now().as_microsecond();+ let tx = conn.transaction()?;+ let run: Option<LinkRunRow> = tx+ .query_row(+ "SELECT workstream_id, agent_kind, native_session_id, sync_through, context_delivered \+ FROM managed_runs WHERE id = ?1 AND state = 'active'",+ params![run_id.as_bytes()],+ |row| {+ Ok(LinkRunRow {+ workstream: row.get(0)?,+ agent: row.get(1)?,+ native_session: row.get(2)?,+ sync_through: row.get(3)?,+ context_delivered: row.get(4)?,+ })+ },+ )+ .optional()?;+ let Some(run) = run else {+ return Ok(false);+ };+ if run.agent != agent.as_str() {+ return Ok(false);+ }+ if run.context_delivered+ && run+ .native_session+ .as_deref()+ .is_some_and(|linked| linked != native_session_id)+ {+ return Ok(false);+ }+ let workstream = run.workstream;+ let sync_through = run.sync_through;+ let delivered = run.context_delivered;+ tx.execute(+ "UPDATE workstream_native_sessions SET is_current = 0, updated_at = ?1 \+ WHERE workstream_id = ?2 AND agent_kind = ?3 AND native_session_id <> ?4",+ params![now, workstream, agent.as_str(), native_session_id],+ )?;+ let prior_delivery = tx+ .query_row(+ "SELECT delivery_cursor FROM workstream_native_sessions \+ WHERE workstream_id = ?1 AND agent_kind = ?2 AND native_session_id = ?3",+ params![workstream, agent.as_str(), native_session_id],+ |row| row.get::<_, i64>(0),+ )+ .optional()?;+ let initial_delivery = prior_delivery.unwrap_or(if delivered { sync_through } else { 0 });+ tx.execute(+ "INSERT INTO workstream_native_sessions( \+ workstream_id, agent_kind, native_session_id, is_current, delivery_cursor, \+ created_at, updated_at \+ ) VALUES (?1, ?2, ?3, 1, ?4, ?5, ?5) \+ ON CONFLICT(workstream_id, agent_kind, native_session_id) DO UPDATE SET \+ is_current = 1, \+ delivery_cursor = MAX(workstream_native_sessions.delivery_cursor, excluded.delivery_cursor), \+ updated_at = excluded.updated_at",+ params![+ workstream,+ agent.as_str(),+ native_session_id,+ initial_delivery,+ now,+ ],+ )?;+ tx.execute(+ "UPDATE managed_runs SET native_session_id = ?1, sync_after = ?2 WHERE id = ?3",+ params![native_session_id, initial_delivery, run_id.as_bytes()],+ )?;+ tx.commit()?;+ Ok(true)+}++/// Mark the assigned synchronization packet delivered to SessionStart.+pub(crate) fn accept_context(conn: &mut Connection, run_id: ManagedRunId) -> StoreResult<bool> {+ let now = Timestamp::now().as_microsecond();+ let tx = conn.transaction()?;+ let run: Option<(Vec<u8>, String, Option<String>, i64)> = tx+ .query_row(+ "SELECT workstream_id, agent_kind, native_session_id, sync_through \+ FROM managed_runs WHERE id = ?1 AND state = 'active'",+ params![run_id.as_bytes()],+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),+ )+ .optional()?;+ let Some((workstream, agent, native_session, sync_through)) = run else {+ return Ok(false);+ };+ tx.execute(+ "UPDATE managed_runs SET context_delivered = 1, lease_expires_at = ?1 WHERE id = ?2",+ params![now + LEASE_MICROS, run_id.as_bytes()],+ )?;+ if let Some(native_session) = native_session {+ tx.execute(+ "UPDATE workstream_native_sessions \+ SET delivery_cursor = MAX(delivery_cursor, ?1), updated_at = ?2 \+ WHERE workstream_id = ?3 AND agent_kind = ?4 \+ AND native_session_id = ?5",+ params![sync_through, now, workstream, agent, native_session],+ )?;+ }+ tx.commit()?;+ Ok(true)+}++/// Index one immutable source segment and close the run atomically.+pub(crate) fn finish_run(+ conn: &mut Connection,+ input: &FinishWorkstreamRun,+) -> StoreResult<FinishedWorkstreamRun> {+ let now = Timestamp::now().as_microsecond();+ let tx = conn.transaction()?;+ let run: Option<FinishRunRow> = tx+ .query_row(+ "SELECT workstream_id, agent_kind, native_session_id, state, \+ sync_after, sync_through, context_delivered \+ FROM managed_runs WHERE id = ?1",+ params![input.run_id.as_bytes()],+ |row| {+ Ok(FinishRunRow {+ workstream: row.get(0)?,+ agent_wire: row.get(1)?,+ linked_session: row.get(2)?,+ state: row.get(3)?,+ sync_after: row.get(4)?,+ sync_through: row.get(5)?,+ context_delivered: row.get(6)?,+ })+ },+ )+ .optional()?;+ let Some(run) = run else {+ return Err(StoreError::NotFound(format!(+ "managed run {}",+ input.run_id+ )));+ };+ let FinishRunRow {+ workstream,+ agent_wire,+ linked_session,+ state,+ sync_after,+ sync_through,+ context_delivered,+ } = run;+ let latest_before: i64 = tx.query_row(+ "SELECT COALESCE(MAX(sequence), 0) FROM workstream_events WHERE workstream_id = ?1",+ params![workstream],+ |row| row.get(0),+ )?;+ if state == "finished" {+ return Ok(FinishedWorkstreamRun {+ imported_events: 0,+ latest_sequence: latest_before,+ });+ }+ if state != "active" {+ return Err(StoreError::InvalidState(format!(+ "managed run {} is {state}",+ input.run_id+ )));+ }+ let agent = AgentKind::from_wire(&agent_wire);+ let native_session = input+ .native_session_id+ .as_deref()+ .or(linked_session.as_deref());++ let mut latest = latest_before;+ let mut imported = 0_usize;+ for event in &input.events {+ if event.agent != agent {+ return Err(StoreError::InvalidState(format!(+ "event {} belongs to {}, managed run expects {}",+ event.event_id,+ event.agent.as_str(),+ agent.as_str()+ )));+ }+ if let Some(native_session) = native_session+ && event.native_session_id != native_session+ {+ return Err(StoreError::InvalidState(format!(+ "event {} belongs to native session {}, managed run expects {native_session}",+ event.event_id, event.native_session_id+ )));+ }+ let exists: bool = tx.query_row(+ "SELECT EXISTS(SELECT 1 FROM workstream_events \+ WHERE workstream_id = ?1 AND event_id = ?2)",+ params![workstream, event.event_id],+ |row| row.get(0),+ )?;+ if exists {+ continue;+ }+ latest += 1;+ tx.execute(+ "INSERT INTO workstream_events( \+ workstream_id, sequence, event_id, agent_kind, native_session_id, \+ source_record_id, kind, role, content, occurred_at, metadata_json, \+ segment_path, created_at \+ ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)",+ params![+ workstream,+ latest,+ event.event_id,+ event.agent.as_str(),+ event.native_session_id,+ event.source_record_id,+ event.kind.as_str(),+ event.role,+ event.content,+ event.occurred_at,+ serde_json::to_string(&event.metadata)?,+ input.segment_path,+ now,+ ],+ )?;+ imported += 1;+ }++ let known_through = if context_delivered || sync_after >= sync_through {+ latest+ } else {+ 0+ };+ if input.complete+ && let Some(native_session) = native_session+ {+ tx.execute(+ "UPDATE workstream_native_sessions SET is_current = 0, updated_at = ?1 \+ WHERE workstream_id = ?2 AND agent_kind = ?3 AND native_session_id <> ?4",+ params![now, workstream, agent.as_str(), native_session],+ )?;+ tx.execute(+ "INSERT INTO workstream_native_sessions( \+ workstream_id, agent_kind, native_session_id, is_current, source_cursor, \+ delivery_cursor, created_at, updated_at \+ ) VALUES (?1, ?2, ?3, 1, ?4, ?5, ?6, ?6) \+ ON CONFLICT(workstream_id, agent_kind, native_session_id) DO UPDATE SET \+ is_current = 1, source_cursor = excluded.source_cursor, \+ delivery_cursor = MAX(workstream_native_sessions.delivery_cursor, excluded.delivery_cursor), \+ updated_at = excluded.updated_at",+ params![+ workstream,+ agent.as_str(),+ native_session,+ input.source_cursor,+ known_through,+ now,+ ],+ )?;+ }+ if input.complete {+ tx.execute(+ "UPDATE managed_runs SET state = 'finished', native_session_id = COALESCE(?1, native_session_id), \+ ended_at = ?2, lease_expires_at = ?2, exit_code = ?3 WHERE id = ?4",+ params![+ native_session,+ now,+ input.exit_code,+ input.run_id.as_bytes()+ ],+ )?;+ } else {+ tx.execute(+ "UPDATE managed_runs SET native_session_id = COALESCE(?1, native_session_id), \+ lease_expires_at = ?2 WHERE id = ?3",+ params![native_session, now + LEASE_MICROS, input.run_id.as_bytes()],+ )?;+ }+ tx.execute(+ "UPDATE workstreams SET updated_at = ?1 WHERE id = ?2",+ params![now, workstream],+ )?;+ tx.commit()?;+ Ok(FinishedWorkstreamRun {+ imported_events: imported,+ latest_sequence: latest,+ })+}++/// Reader-side managed-run status.+pub(crate) fn run_status(+ conn: &Connection,+ run_id: ManagedRunId,+) -> StoreResult<Option<StoredManagedRunStatus>> {+ let row = conn+ .query_row(+ "SELECT workstream_id, agent_kind, native_session_id, context_delivered, state \+ FROM managed_runs WHERE id = ?1",+ params![run_id.as_bytes()],+ |row| {+ Ok((+ row.get::<_, Vec<u8>>(0)?,+ row.get::<_, String>(1)?,+ row.get::<_, Option<String>>(2)?,+ row.get::<_, bool>(3)?,+ row.get::<_, String>(4)?,+ ))+ },+ )+ .optional()?;+ row.map(+ |(workstream, agent, native_session_id, context_delivered, state)| {+ Ok(StoredManagedRunStatus {+ run_id,+ workstream_id: WorkstreamId::from_slice(&workstream)?,+ agent: AgentKind::from_wire(&agent),+ native_session_id,+ context_delivered,+ state,+ })+ },+ )+ .transpose()+}++/// Reader-side context range assigned to one managed run.+pub(crate) fn run_context(+ conn: &Connection,+ run_id: ManagedRunId,+ max_events: usize,+) -> StoreResult<Option<ManagedRunContext>> {+ let row = conn+ .query_row(+ "SELECT mr.workstream_id, w.name, mr.agent_kind, mr.native_session_id, \+ mr.sync_after, mr.sync_through, mr.context_delivered \+ FROM managed_runs mr JOIN workstreams w ON w.id = mr.workstream_id \+ WHERE mr.id = ?1 AND mr.state = 'active'",+ params![run_id.as_bytes()],+ |row| {+ Ok((+ row.get::<_, Vec<u8>>(0)?,+ row.get::<_, String>(1)?,+ row.get::<_, String>(2)?,+ row.get::<_, Option<String>>(3)?,+ row.get::<_, i64>(4)?,+ row.get::<_, i64>(5)?,+ row.get::<_, bool>(6)?,+ ))+ },+ )+ .optional()?;+ let Some((workstream, name, agent, native, after, through, delivered)) = row else {+ return Ok(None);+ };+ let workstream_id = WorkstreamId::from_slice(&workstream)?;+ let mut stmt = conn.prepare(+ "SELECT sequence, event_id, agent_kind, native_session_id, kind, role, content, occurred_at \+ FROM workstream_events \+ WHERE workstream_id = ?1 AND sequence > ?2 AND sequence <= ?3 \+ ORDER BY sequence DESC LIMIT ?4",+ )?;+ let rows = stmt.query_map(+ params![+ workstream,+ after,+ through,+ i64::try_from(max_events).unwrap_or(i64::MAX)+ ],+ |row| {+ Ok((+ row.get::<_, i64>(0)?,+ row.get::<_, String>(1)?,+ row.get::<_, String>(2)?,+ row.get::<_, String>(3)?,+ row.get::<_, String>(4)?,+ row.get::<_, Option<String>>(5)?,+ row.get::<_, String>(6)?,+ row.get::<_, Option<String>>(7)?,+ ))+ },+ )?;+ let mut events = Vec::new();+ for row in rows {+ let (sequence, event_id, agent, native_session_id, kind, role, content, occurred_at) = row?;+ events.push(WorkstreamEvent {+ sequence,+ event_id,+ agent: AgentKind::from_wire(&agent),+ native_session_id,+ kind: WorkstreamEventKind::from_str(&kind)?,+ role,+ content,+ occurred_at,+ });+ }+ events.reverse();+ Ok(Some(ManagedRunContext {+ run_id,+ workstream_id,+ workstream_name: name,+ agent: AgentKind::from_wire(&agent),+ native_session_id: native,+ sync_after: after,+ sync_through: through,+ context_delivered: delivered,+ events,+ }))+}++/// Search or tail the portable ledger for explicit managed-session recovery.+pub(crate) fn search_events(+ conn: &Connection,+ workstream_id: WorkstreamId,+ query: &str,+ limit: usize,+) -> StoreResult<Vec<WorkstreamEvent>> {+ let limit = i64::try_from(limit.clamp(1, 100)).unwrap_or(100);+ let free_text = query+ .replace("title:", "")+ .replace("body:", "")+ .replace("content:", "");+ let fts_query = crate::prepare_fts5_query(&free_text);+ let sql = if fts_query.is_empty() {+ "SELECT sequence, event_id, agent_kind, native_session_id, kind, role, content, occurred_at \+ FROM workstream_events WHERE workstream_id = ?1 ORDER BY sequence DESC LIMIT ?2"+ } else {+ "SELECT e.sequence, e.event_id, e.agent_kind, e.native_session_id, e.kind, \+ e.role, e.content, e.occurred_at \+ FROM workstream_events_fts f \+ JOIN workstream_events e ON e.rowid = f.rowid \+ WHERE workstream_events_fts MATCH ?2 AND e.workstream_id = ?1 \+ ORDER BY f.rank LIMIT ?3"+ };+ let mut statement = conn.prepare(sql)?;+ let read_row = |row: &rusqlite::Row<'_>| {+ Ok((+ row.get::<_, i64>(0)?,+ row.get::<_, String>(1)?,+ row.get::<_, String>(2)?,+ row.get::<_, String>(3)?,+ row.get::<_, String>(4)?,+ row.get::<_, Option<String>>(5)?,+ row.get::<_, String>(6)?,+ row.get::<_, Option<String>>(7)?,+ ))+ };+ let mut events = Vec::new();+ if fts_query.is_empty() {+ let rows = statement.query_map(params![workstream_id.as_bytes(), limit], read_row)?;+ for row in rows {+ events.push(stored_event(row?)?);+ }+ } else {+ let rows = statement.query_map(+ params![workstream_id.as_bytes(), fts_query, limit],+ read_row,+ )?;+ for row in rows {+ events.push(stored_event(row?)?);+ }+ }+ Ok(events)+}++fn stored_event(+ row: (+ i64,+ String,+ String,+ String,+ String,+ Option<String>,+ String,+ Option<String>,+ ),+) -> StoreResult<WorkstreamEvent> {+ let (sequence, event_id, agent, native_session_id, kind, role, content, occurred_at) = row;+ Ok(WorkstreamEvent {+ sequence,+ event_id,+ agent: AgentKind::from_wire(&agent),+ native_session_id,+ kind: WorkstreamEventKind::from_str(&kind)?,+ role,+ content,+ occurred_at,+ })+}diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rsindex b0543f1a..986c7790 100644--- a/crates/ai-memory-store/src/writer.rs+++ b/crates/ai-memory-store/src/writer.rs@@ -11,8 +11,8 @@ use std::sync::{Arc, Mutex};use std::thread::{self, JoinHandle};use ai_memory_core::{- AgentKind, HandoffId, NewHandoff, NewObservation, NewPage, NewSession, NewUser, ObservationId,- PageId, PagePath, ProjectId, SessionId, UserId, WorkspaceId,+ AgentKind, HandoffId, ManagedRunId, NewHandoff, NewObservation, NewPage, NewSession, NewUser,+ ObservationId, PageId, PagePath, ProjectId, SessionId, UserId, WorkspaceId,};use rusqlite::Connection;use tokio::sync::{mpsc, oneshot};@@ -26,6 +26,9 @@ use crate::ops::{self, DeleteWorkspaceSummary, EmbeddingWrite, MoveSummary, PurgeSummary, ReorgSummary,};use crate::users::{self, TOKEN_HASH_LEN};+use crate::workstream::{+ FinishWorkstreamRun, FinishedWorkstreamRun, PrepareWorkstreamRun, PreparedWorkstreamRun,+};/// Commands accepted by the writer thread.pub(crate) enum WriteCmd {@@ -258,6 +261,28 @@ pub(crate) enum WriteCmd {job: crate::maintenance::MaintenanceJob,reply: oneshot::Sender<StoreResult<()>>,},+ PrepareWorkstreamRun {+ input: PrepareWorkstreamRun,+ reply: oneshot::Sender<StoreResult<PreparedWorkstreamRun>>,+ },+ HeartbeatManagedRun {+ run_id: ManagedRunId,+ reply: oneshot::Sender<StoreResult<bool>>,+ },+ LinkManagedRunSession {+ run_id: ManagedRunId,+ agent: AgentKind,+ native_session_id: String,+ reply: oneshot::Sender<StoreResult<bool>>,+ },+ AcceptManagedRunContext {+ run_id: ManagedRunId,+ reply: oneshot::Sender<StoreResult<bool>>,+ },+ FinishWorkstreamRun {+ input: FinishWorkstreamRun,+ reply: oneshot::Sender<StoreResult<FinishedWorkstreamRun>>,+ },Shutdown,}@@ -1028,6 +1053,62 @@ impl WriterHandle {rx.await.map_err(|_| StoreError::WriterClosed)?}+ /// Select a workstream and open its single active managed-run lease.+ pub async fn prepare_workstream_run(+ &self,+ input: PrepareWorkstreamRun,+ ) -> StoreResult<PreparedWorkstreamRun> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::PrepareWorkstreamRun { input, reply: tx })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }++ /// Extend a managed-run lease. Returns false for missing/stale runs.+ pub async fn heartbeat_managed_run(&self, run_id: ManagedRunId) -> StoreResult<bool> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::HeartbeatManagedRun { run_id, reply: tx })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }++ /// Attach the harness-native session observed by a managed SessionStart.+ pub async fn link_managed_run_session(+ &self,+ run_id: ManagedRunId,+ agent: AgentKind,+ native_session_id: impl Into<String>,+ ) -> StoreResult<bool> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::LinkManagedRunSession {+ run_id,+ agent,+ native_session_id: native_session_id.into(),+ reply: tx,+ })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }++ /// Acknowledge successful SessionStart delivery for a managed run.+ pub async fn accept_managed_run_context(&self, run_id: ManagedRunId) -> StoreResult<bool> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::AcceptManagedRunContext { run_id, reply: tx })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }++ /// Index an immutable transcript segment and release the run lease.+ pub async fn finish_workstream_run(+ &self,+ input: FinishWorkstreamRun,+ ) -> StoreResult<FinishedWorkstreamRun> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::FinishWorkstreamRun { input, reply: tx })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }+async fn send(&self, cmd: WriteCmd) -> StoreResult<()> {self.inner.tx@@ -1383,6 +1464,36 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {let result = crate::maintenance::record_success(&conn, job);send_or_warn(reply, result, "record_maintenance_job_success");}+ WriteCmd::PrepareWorkstreamRun { input, reply } => {+ let result = crate::workstream::prepare_run(&mut conn, &input);+ send_or_warn(reply, result, "prepare_workstream_run");+ }+ WriteCmd::HeartbeatManagedRun { run_id, reply } => {+ let result = crate::workstream::heartbeat(&mut conn, run_id);+ send_or_warn(reply, result, "heartbeat_managed_run");+ }+ WriteCmd::LinkManagedRunSession {+ run_id,+ agent,+ native_session_id,+ reply,+ } => {+ let result = crate::workstream::link_native_session(+ &mut conn,+ run_id,+ agent,+ &native_session_id,+ );+ send_or_warn(reply, result, "link_managed_run_session");+ }+ WriteCmd::AcceptManagedRunContext { run_id, reply } => {+ let result = crate::workstream::accept_context(&mut conn, run_id);+ send_or_warn(reply, result, "accept_managed_run_context");+ }+ WriteCmd::FinishWorkstreamRun { input, reply } => {+ let result = crate::workstream::finish_run(&mut conn, &input);+ send_or_warn(reply, result, "finish_workstream_run");+ }}}tracing::debug!("writer thread exiting cleanly");diff --git a/crates/ai-memory-workstream/Cargo.toml b/crates/ai-memory-workstream/Cargo.tomlnew file mode 100644index 00000000..8244c01e--- /dev/null+++ b/crates/ai-memory-workstream/Cargo.toml@@ -0,0 +1,25 @@+[package]+name = "ai-memory-workstream"+version.workspace = true+edition.workspace = true+rust-version.workspace = true+license.workspace = true+repository.workspace = true+authors.workspace = true+description = "Read-only native harness adapters and managed launch planning for ai-memory."++[dependencies]+ai-memory-core.workspace = true+anyhow.workspace = true+serde.workspace = true+serde_json.workspace = true+sha2.workspace = true+rusqlite.workspace = true+tokio.workspace = true+uuid.workspace = true++[dev-dependencies]+tempfile.workspace = true++[lints]+workspace = truediff --git a/crates/ai-memory-workstream/src/harness.rs b/crates/ai-memory-workstream/src/harness.rsnew file mode 100644index 00000000..0719c3f9--- /dev/null+++ b/crates/ai-memory-workstream/src/harness.rs@@ -0,0 +1,668 @@+//! Native command planning without filtering harness arguments.++use std::ffi::OsString;+use std::path::PathBuf;++use ai_memory_core::AgentKind;+use anyhow::Result;+use uuid::Uuid;++/// Harnesses with native-session and transcript adapters.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ManagedHarness {+ /// Anthropic Claude Code.+ Claude,+ /// OpenAI Codex CLI.+ Codex,+ /// OpenCode.+ OpenCode,+ /// Pi coding agent.+ Pi,+ /// Oh My Pi.+ Omp,+}++impl ManagedHarness {+ /// Parse the user-facing command name.+ #[must_use]+ pub fn from_name(value: &str) -> Option<Self> {+ match value {+ "claude" | "claude-code" => Some(Self::Claude),+ "codex" => Some(Self::Codex),+ "opencode" | "open-code" => Some(Self::OpenCode),+ "pi" => Some(Self::Pi),+ "omp" | "oh-my-pi" => Some(Self::Omp),+ _ => None,+ }+ }++ /// Core agent kind used on the wire and in storage.+ #[must_use]+ pub const fn agent_kind(self) -> AgentKind {+ match self {+ Self::Claude => AgentKind::ClaudeCode,+ Self::Codex => AgentKind::Codex,+ Self::OpenCode => AgentKind::OpenCode,+ Self::Pi => AgentKind::Pi,+ Self::Omp => AgentKind::Omp,+ }+ }++ /// Default executable resolved through `PATH`.+ #[must_use]+ pub const fn executable(self) -> &'static str {+ match self {+ Self::Claude => "claude",+ Self::Codex => "codex",+ Self::OpenCode => "opencode",+ Self::Pi => "pi",+ Self::Omp => "omp",+ }+ }++ /// Stable user-facing name.+ #[must_use]+ pub const fn as_str(self) -> &'static str {+ match self {+ Self::Claude => "claude",+ Self::Codex => "codex",+ Self::OpenCode => "opencode",+ Self::Pi => "pi",+ Self::Omp => "omp",+ }+ }+}++/// Whether the planned native invocation participates in session continuity.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum LaunchMode {+ /// Interactive or persisted native session.+ Session,+ /// Native utility/subcommand or explicitly ephemeral invocation. Arguments+ /// are still passed through and repository state is still checkpointed.+ Passthrough,+}++/// Fully constructed native process invocation.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct LaunchPlan {+ /// Executable name/path.+ pub program: OsString,+ /// Native argument vector. User arguments retain byte/order identity.+ pub args: Vec<OsString>,+ /// Session id known before launch (generated, linked, or explicit).+ pub expected_session_id: Option<String>,+ /// Native transcript root resolved from explicit arguments or environment.+ pub session_dir: Option<PathBuf>,+ /// Session-bearing versus utility invocation.+ pub mode: LaunchMode,+}++/// Build the transparent resume/create command for one harness.+///+/// User arguments are never validated or rewritten. Adapter-owned session+/// selectors are inserted only when the invocation is session-bearing and the+/// user did not provide an explicit native selector.+pub fn build_launch_plan(+ harness: ManagedHarness,+ executable: Option<OsString>,+ native_args: Vec<OsString>,+ linked_session_id: Option<&str>,+) -> Result<LaunchPlan> {+ let program = executable.unwrap_or_else(|| OsString::from(harness.executable()));+ let mut args = native_args;+ let session_dir = match harness {+ ManagedHarness::Pi | ManagedHarness::Omp => flag_path(&args, &["--session-dir"]),+ _ => None,+ }+ .or_else(|| environment_session_dir(harness));+ let mut expected = explicit_session_id(harness, &args);+ let mode = launch_mode(harness, &args);+ if mode == LaunchMode::Session && !has_explicit_session_selector(harness, &args) {+ match harness {+ ManagedHarness::Claude => {+ let id = linked_session_id+ .map(str::to_owned)+ .unwrap_or_else(|| Uuid::new_v4().to_string());+ if linked_session_id.is_some() {+ args.extend([OsString::from("--resume"), OsString::from(&id)]);+ } else {+ args.extend([OsString::from("--session-id"), OsString::from(&id)]);+ }+ expected = Some(id);+ }+ ManagedHarness::Codex => {+ if let Some(id) = linked_session_id {+ let noninteractive = first_arg_is(&args, "exec");+ let mut resumed = if noninteractive {+ vec![+ OsString::from("exec"),+ OsString::from("resume"),+ OsString::from(id),+ ]+ } else {+ vec![OsString::from("resume"), OsString::from(id)]+ };+ resumed.extend(args.into_iter().skip(usize::from(noninteractive)));+ args = resumed;+ expected = Some(id.to_string());+ }+ }+ ManagedHarness::OpenCode => {+ if let Some(id) = linked_session_id {+ if first_arg_is(&args, "run") {+ args.insert(1, OsString::from(id));+ args.insert(1, OsString::from("--session"));+ } else {+ args.insert(0, OsString::from(id));+ args.insert(0, OsString::from("--session"));+ }+ expected = Some(id.to_string());+ }+ }+ ManagedHarness::Pi => {+ let id = linked_session_id+ .map(str::to_owned)+ .unwrap_or_else(|| Uuid::new_v4().to_string());+ let selector = if linked_session_id.is_some() {+ "--session"+ } else {+ "--session-id"+ };+ args.extend([OsString::from(selector), OsString::from(&id)]);+ expected = Some(id);+ }+ ManagedHarness::Omp => {+ if let Some(id) = linked_session_id {+ args.push(OsString::from(format!("--resume={id}")));+ expected = Some(id.to_string());+ }+ }+ }+ }++ Ok(LaunchPlan {+ program,+ args,+ expected_session_id: expected,+ session_dir,+ mode,+ })+}++fn launch_mode(harness: ManagedHarness, args: &[OsString]) -> LaunchMode {+ if has_flag(args, &["--help", "-h", "--version", "-v"])+ || has_flag(args, &["--no-session", "--no-session-persistence"])+ {+ return LaunchMode::Passthrough;+ }+ if harness == ManagedHarness::Codex+ && first_arg_is(args, "exec")+ && args+ .get(1)+ .and_then(|arg| arg.to_str())+ .is_some_and(|command| matches!(command, "review" | "help"))+ {+ return LaunchMode::Passthrough;+ }+ let utility = match harness {+ ManagedHarness::Claude => [+ "agents",+ "auth",+ "auto-mode",+ "doctor",+ "install",+ "mcp",+ "plugin",+ "plugins",+ "project",+ "setup-token",+ "ultrareview",+ "update",+ "upgrade",+ ]+ .as_slice(),+ ManagedHarness::Codex => [+ "review",+ "login",+ "logout",+ "mcp",+ "plugin",+ "mcp-server",+ "app-server",+ "remote-control",+ "completion",+ "update",+ "doctor",+ "sandbox",+ "debug",+ "apply",+ "archive",+ "delete",+ "unarchive",+ "cloud",+ "exec-server",+ "features",+ "help",+ ]+ .as_slice(),+ ManagedHarness::OpenCode => [+ "completion",+ "acp",+ "mcp",+ "attach",+ "debug",+ "providers",+ "agent",+ "upgrade",+ "uninstall",+ "serve",+ "web",+ "models",+ "stats",+ "export",+ "import",+ "github",+ "pr",+ "session",+ "plugin",+ "db",+ ]+ .as_slice(),+ ManagedHarness::Pi => {+ ["install", "remove", "uninstall", "update", "list", "config"].as_slice()+ }+ ManagedHarness::Omp => [+ "acp",+ "agents",+ "auth-broker",+ "auth-gateway",+ "commit",+ "config",+ "grep",+ "grievances",+ "plugin",+ "read",+ "search",+ "setup",+ "shell",+ "ssh",+ "stats",+ "update",+ "worktree",+ ]+ .as_slice(),+ };+ let first = args.first().and_then(|arg| arg.to_str());+ if first.is_some_and(|value| utility.contains(&value)) {+ LaunchMode::Passthrough+ } else {+ LaunchMode::Session+ }+}++fn has_explicit_session_selector(harness: ManagedHarness, args: &[OsString]) -> bool {+ match harness {+ ManagedHarness::Claude => has_flag(+ args,+ &["--resume", "-r", "--continue", "-c", "--session-id"],+ ),+ ManagedHarness::Codex => {+ first_arg_is(args, "resume")+ || first_arg_is(args, "fork")+ || args.first().and_then(|arg| arg.to_str()) == Some("exec")+ && args.get(1).and_then(|arg| arg.to_str()) == Some("resume")+ }+ ManagedHarness::OpenCode => {+ has_flag(args, &["--session", "-s", "--continue", "-c", "--fork"])+ }+ ManagedHarness::Pi => has_flag(+ args,+ &[+ "--session",+ "--session-id",+ "--continue",+ "-c",+ "--resume",+ "-r",+ "--fork",+ ],+ ),+ ManagedHarness::Omp => has_flag(args, &["--resume", "-r", "--continue", "-c"]),+ }+}++fn explicit_session_id(harness: ManagedHarness, args: &[OsString]) -> Option<String> {+ match harness {+ ManagedHarness::Claude => flag_value(args, &["--resume", "-r", "--session-id"]),+ ManagedHarness::Codex => {+ if first_arg_is(args, "exec")+ && args.get(1).and_then(|arg| arg.to_str()) == Some("resume")+ {+ args.get(2)+ .and_then(|value| value.to_str())+ .filter(|value| !value.starts_with('-'))+ .map(str::to_owned)+ } else {+ positional_after_command(args, &["resume"])+ }+ }+ ManagedHarness::OpenCode => flag_value(args, &["--session", "-s"]),+ ManagedHarness::Pi => flag_value(args, &["--session", "--session-id"]),+ ManagedHarness::Omp => flag_value(args, &["--resume", "-r"]),+ }+}++fn first_arg_is(args: &[OsString], expected: &str) -> bool {+ args.first().and_then(|value| value.to_str()) == Some(expected)+}++fn has_flag(args: &[OsString], names: &[&str]) -> bool {+ args.iter().any(|arg| {+ let Some(value) = arg.to_str() else {+ return false;+ };+ names+ .iter()+ .any(|name| value == *name || value.starts_with(&format!("{name}=")))+ })+}++fn flag_value(args: &[OsString], names: &[&str]) -> Option<String> {+ for (index, arg) in args.iter().enumerate() {+ let value = arg.to_str()?;+ for name in names {+ if value == *name {+ return args+ .get(index + 1)+ .and_then(|next| next.to_str())+ .filter(|next| !next.starts_with('-'))+ .map(str::to_owned);+ }+ if let Some(found) = value.strip_prefix(&format!("{name}="))+ && !found.is_empty()+ {+ return Some(found.to_string());+ }+ }+ }+ None+}++fn flag_path(args: &[OsString], names: &[&str]) -> Option<PathBuf> {+ for (index, arg) in args.iter().enumerate() {+ if names.iter().any(|name| arg == *name) {+ return args.get(index + 1).map(PathBuf::from);+ }+ let Some(value) = arg.to_str() else {+ continue;+ };+ for name in names {+ if let Some(found) = value.strip_prefix(&format!("{name}="))+ && !found.is_empty()+ {+ return Some(PathBuf::from(found));+ }+ }+ }+ None+}++fn environment_session_dir(harness: ManagedHarness) -> Option<PathBuf> {+ environment_session_dir_with(harness, |name| std::env::var_os(name))+}++fn environment_session_dir_with(+ harness: ManagedHarness,+ get: impl Fn(&str) -> Option<OsString>,+) -> Option<PathBuf> {+ let value = |name| {+ get(name)+ .filter(|value| !value.is_empty())+ .map(PathBuf::from)+ };+ match harness {+ ManagedHarness::Claude => value("CLAUDE_CONFIG_DIR").map(|dir| dir.join("projects")),+ ManagedHarness::Codex => value("CODEX_HOME").map(|dir| dir.join("sessions")),+ ManagedHarness::OpenCode => value("XDG_DATA_HOME").map(|dir| dir.join("opencode")),+ ManagedHarness::Pi => value("PI_CODING_AGENT_SESSION_DIR")+ .or_else(|| value("PI_CODING_AGENT_DIR").map(|dir| dir.join("sessions"))),+ ManagedHarness::Omp => value("PI_CODING_AGENT_DIR").map(|dir| dir.join("sessions")),+ }+}++fn positional_after_command(args: &[OsString], commands: &[&str]) -> Option<String> {+ let command = args.first()?.to_str()?;+ if !commands.contains(&command) {+ return None;+ }+ args.get(1)+ .and_then(|value| value.to_str())+ .filter(|value| !value.starts_with('-'))+ .map(str::to_owned)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn strings(args: &[OsString]) -> Vec<String> {+ args.iter()+ .map(|value| value.to_string_lossy().into_owned())+ .collect()+ }++ #[test]+ fn claude_generates_then_resumes_native_session() {+ let fresh = build_launch_plan(ManagedHarness::Claude, None, vec![], None).unwrap();+ let id = fresh.expected_session_id.clone().unwrap();+ assert_eq!(strings(&fresh.args), ["--session-id", id.as_str()]);++ let resumed = build_launch_plan(+ ManagedHarness::Claude,+ None,+ vec![OsString::from("--model"), OsString::from("opus")],+ Some(&id),+ )+ .unwrap();+ assert_eq!(+ strings(&resumed.args),+ ["--model", "opus", "--resume", id.as_str()]+ );+ }++ #[test]+ fn codex_resume_preserves_all_user_arguments_in_order() {+ let native = vec![+ OsString::from("--yolo"),+ OsString::from("-m"),+ OsString::from("gpt-5"),+ OsString::from("continue here"),+ ];+ let plan =+ build_launch_plan(ManagedHarness::Codex, None, native, Some("codex-id")).unwrap();+ assert_eq!(+ strings(&plan.args),+ [+ "resume",+ "codex-id",+ "--yolo",+ "-m",+ "gpt-5",+ "continue here"+ ]+ );+ }++ #[test]+ fn codex_exec_resume_uses_native_noninteractive_subcommand() {+ let native = vec![+ OsString::from("exec"),+ OsString::from("--json"),+ OsString::from("continue here"),+ ];+ let plan =+ build_launch_plan(ManagedHarness::Codex, None, native, Some("codex-id")).unwrap();+ assert_eq!(+ strings(&plan.args),+ ["exec", "resume", "codex-id", "--json", "continue here"]+ );+ assert_eq!(plan.mode, LaunchMode::Session);+ }++ #[test]+ fn explicit_codex_exec_resume_wins() {+ let native = vec![+ OsString::from("exec"),+ OsString::from("resume"),+ OsString::from("chosen"),+ OsString::from("continue here"),+ ];+ let plan = build_launch_plan(ManagedHarness::Codex, None, native, Some("linked")).unwrap();+ assert_eq!(+ strings(&plan.args),+ ["exec", "resume", "chosen", "continue here"]+ );+ assert_eq!(plan.expected_session_id.as_deref(), Some("chosen"));+ }++ #[test]+ fn explicit_native_selector_wins() {+ let plan = build_launch_plan(+ ManagedHarness::OpenCode,+ None,+ vec![OsString::from("--session=chosen"), OsString::from("--auto")],+ Some("linked"),+ )+ .unwrap();+ assert_eq!(strings(&plan.args), ["--session=chosen", "--auto"]);+ assert_eq!(plan.expected_session_id.as_deref(), Some("chosen"));+ }++ #[test]+ fn opencode_resume_places_selector_after_run_subcommand() {+ let plan = build_launch_plan(+ ManagedHarness::OpenCode,+ None,+ vec![OsString::from("run"), OsString::from("continue here")],+ Some("open-code-id"),+ )+ .unwrap();+ assert_eq!(+ strings(&plan.args),+ ["run", "--session", "open-code-id", "continue here"]+ );+ assert_eq!(plan.expected_session_id.as_deref(), Some("open-code-id"));+ }++ #[test]+ fn pi_generates_then_resumes_native_session() {+ let fresh = build_launch_plan(+ ManagedHarness::Pi,+ None,+ vec![OsString::from("continue here")],+ None,+ )+ .unwrap();+ let id = fresh.expected_session_id.clone().unwrap();+ assert_eq!(+ strings(&fresh.args),+ ["continue here", "--session-id", id.as_str()]+ );++ let resumed = build_launch_plan(+ ManagedHarness::Pi,+ None,+ vec![OsString::from("continue here")],+ Some(&id),+ )+ .unwrap();+ assert_eq!(+ strings(&resumed.args),+ ["continue here", "--session", id.as_str()]+ );+ }++ #[test]+ fn omp_resume_uses_equals_form_without_reordering_native_args() {+ let plan = build_launch_plan(+ ManagedHarness::Omp,+ None,+ vec![OsString::from("--yolo"), OsString::from("continue here")],+ Some("omp-id"),+ )+ .unwrap();+ assert_eq!(+ strings(&plan.args),+ ["--yolo", "continue here", "--resume=omp-id"]+ );+ assert_eq!(plan.expected_session_id.as_deref(), Some("omp-id"));+ }++ #[test]+ fn pi_family_session_directory_is_observed_without_changing_native_argv() {+ let pi_args = vec![+ OsString::from("--session-dir"),+ OsString::from("/tmp/pi sessions"),+ OsString::from("continue here"),+ ];+ let pi = build_launch_plan(ManagedHarness::Pi, None, pi_args.clone(), None).unwrap();+ assert_eq!(+ pi.session_dir.as_deref(),+ Some(std::path::Path::new("/tmp/pi sessions"))+ );+ assert_eq!(&pi.args[..pi_args.len()], pi_args);++ let omp = build_launch_plan(+ ManagedHarness::Omp,+ None,+ vec![OsString::from("--session-dir=/tmp/omp")],+ None,+ )+ .unwrap();+ assert_eq!(+ omp.session_dir.as_deref(),+ Some(std::path::Path::new("/tmp/omp"))+ );+ }++ #[test]+ fn native_store_environment_overrides_match_harness_layouts() {+ let get = |name: &str| match name {+ "CLAUDE_CONFIG_DIR" => Some(OsString::from("/stores/claude")),+ "CODEX_HOME" => Some(OsString::from("/stores/codex")),+ "XDG_DATA_HOME" => Some(OsString::from("/stores/xdg")),+ "PI_CODING_AGENT_DIR" => Some(OsString::from("/stores/pi-family")),+ _ => None,+ };+ assert_eq!(+ environment_session_dir_with(ManagedHarness::Claude, get).as_deref(),+ Some(std::path::Path::new("/stores/claude/projects"))+ );+ assert_eq!(+ environment_session_dir_with(ManagedHarness::Codex, get).as_deref(),+ Some(std::path::Path::new("/stores/codex/sessions"))+ );+ assert_eq!(+ environment_session_dir_with(ManagedHarness::OpenCode, get).as_deref(),+ Some(std::path::Path::new("/stores/xdg/opencode"))+ );+ assert_eq!(+ environment_session_dir_with(ManagedHarness::Omp, get).as_deref(),+ Some(std::path::Path::new("/stores/pi-family/sessions"))+ );+ }++ #[test]+ fn utility_subcommands_are_passed_through_without_resume_flags() {+ let plan = build_launch_plan(+ ManagedHarness::Codex,+ None,+ vec![OsString::from("doctor")],+ Some("linked"),+ )+ .unwrap();+ assert_eq!(plan.mode, LaunchMode::Passthrough);+ assert_eq!(strings(&plan.args), ["doctor"]);+ }+}diff --git a/crates/ai-memory-workstream/src/lib.rs b/crates/ai-memory-workstream/src/lib.rsnew file mode 100644index 00000000..c4eed954--- /dev/null+++ b/crates/ai-memory-workstream/src/lib.rs@@ -0,0 +1,11 @@+//! Read-only native harness adapters used by `ai-memory run`.++mod harness;+mod repository;+mod transcript;++pub use harness::{LaunchMode, LaunchPlan, ManagedHarness, build_launch_plan};+pub use repository::{RepositoryIdentity, inspect_repository};+pub use transcript::{+ ExportedTranscript, discover_native_session, export_transcript, wait_for_transcript_flush,+};diff --git a/crates/ai-memory-workstream/src/repository.rs b/crates/ai-memory-workstream/src/repository.rsnew file mode 100644index 00000000..c1108238--- /dev/null+++ b/crates/ai-memory-workstream/src/repository.rs@@ -0,0 +1,153 @@+//! Repository/worktree identity and non-mutating boundary checkpoints.++use std::path::{Path, PathBuf};+use std::process::Command;++use ai_memory_core::WorkstreamCheckpoint;+use anyhow::{Context as _, Result};+use sha2::{Digest as _, Sha256};++/// Stable identity used to select a workstream without relying only on CWD.+#[derive(Debug, Clone)]+pub struct RepositoryIdentity {+ /// Canonical host cwd.+ pub cwd: PathBuf,+ /// Repository identity hash shared by linked worktrees.+ pub repo_fingerprint: String,+ /// Worktree-specific identity hash.+ pub worktree_fingerprint: String,+ /// Current non-mutating Git checkpoint.+ pub checkpoint: WorkstreamCheckpoint,+}++/// Inspect the current checkout without committing, stashing, resetting, or+/// otherwise changing it.+pub fn inspect_repository(cwd: &Path) -> Result<RepositoryIdentity> {+ let canonical = cwd+ .canonicalize()+ .with_context(|| format!("canonicalizing managed run cwd {}", cwd.display()))?;+ let git_root = git(&canonical, &["rev-parse", "--show-toplevel"]);+ let common_dir = git(+ &canonical,+ &["rev-parse", "--path-format=absolute", "--git-common-dir"],+ );+ let git_dir = git(+ &canonical,+ &["rev-parse", "--path-format=absolute", "--git-dir"],+ );+ let remotes = git(&canonical, &["remote", "get-url", "--all", "origin"]);++ let repo_seed = match (&git_root, &common_dir, &remotes) {+ (_, _, Some(remotes)) if !remotes.trim().is_empty() => format!("git-remotes\n{remotes}"),+ (_, Some(common), _) => format!("git-common\n{common}"),+ (Some(root), _, _) => format!("git-root\n{root}"),+ _ => format!("directory\n{}", canonical.display()),+ };+ let worktree_seed = match (&git_dir, &git_root) {+ (Some(git_dir), _) => format!("{}\ngit-dir\n{git_dir}", sha256(&repo_seed)),+ (_, Some(root)) => format!("{}\nroot\n{root}", sha256(&repo_seed)),+ _ => format!("{}\ncwd\n{}", sha256(&repo_seed), canonical.display()),+ };+ Ok(RepositoryIdentity {+ cwd: canonical.clone(),+ repo_fingerprint: sha256(&repo_seed),+ worktree_fingerprint: sha256(&worktree_seed),+ checkpoint: checkpoint(&canonical),+ })+}++fn checkpoint(cwd: &Path) -> WorkstreamCheckpoint {+ let status = git_bytes(cwd, &["status", "--porcelain=v1", "-z"]);+ let changed_paths = status+ .as_deref()+ .map(parse_status_paths)+ .unwrap_or_default();+ WorkstreamCheckpoint {+ head: git(cwd, &["rev-parse", "HEAD"]),+ branch: git(cwd, &["branch", "--show-current"]).map(|branch| {+ if branch.is_empty() {+ "(detached HEAD)".to_string()+ } else {+ branch+ }+ }),+ dirty_hash: status+ .as_deref()+ .and_then(|bytes| (!bytes.is_empty()).then(|| format!("{:x}", Sha256::digest(bytes)))),+ changed_paths,+ }+}++fn git(cwd: &Path, args: &[&str]) -> Option<String> {+ let output = git_bytes(cwd, args)?;+ String::from_utf8(output)+ .ok()+ .map(|value| value.trim().to_string())+}++fn git_bytes(cwd: &Path, args: &[&str]) -> Option<Vec<u8>> {+ let output = Command::new("git")+ .arg("-C")+ .arg(cwd)+ .args(args)+ .output()+ .ok()?;+ output.status.success().then_some(output.stdout)+}++fn parse_status_paths(status: &[u8]) -> Vec<String> {+ let mut entries = status.split(|byte| *byte == 0).peekable();+ let mut paths = Vec::new();+ while let Some(entry) = entries.next() {+ if entry.len() <= 3 {+ continue;+ }+ if let Ok(path) = String::from_utf8(entry[3..].to_vec()) {+ paths.push(path);+ }+ if entry[..2]+ .iter()+ .any(|status| matches!(*status, b'R' | b'C'))+ && let Some(old_path) = entries.next()+ && let Ok(path) = String::from_utf8(old_path.to_vec())+ {+ paths.push(path);+ }+ if paths.len() >= 256 {+ break;+ }+ }+ paths.truncate(256);+ paths+}++fn sha256(value: &str) -> String {+ format!("{:x}", Sha256::digest(value.as_bytes()))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn non_git_directory_has_stable_distinct_fingerprints() {+ let temp = tempfile::tempdir().unwrap();+ let first = inspect_repository(temp.path()).unwrap();+ let second = inspect_repository(temp.path()).unwrap();+ assert_eq!(first.repo_fingerprint, second.repo_fingerprint);+ assert_eq!(first.worktree_fingerprint, second.worktree_fingerprint);+ assert_eq!(first.repo_fingerprint.len(), 64);+ }++ #[test]+ fn status_parser_handles_spaces_without_shell_splitting() {+ let paths = parse_status_paths(b" M path with spaces.rs\0?? new.txt\0");+ assert_eq!(paths, ["path with spaces.rs", "new.txt"]);+ }++ #[test]+ fn status_parser_preserves_both_rename_paths() {+ let paths = parse_status_paths(b"R new name.rs\0old name.rs\0");+ assert_eq!(paths, ["new name.rs", "old name.rs"]);+ }+}diff --git a/crates/ai-memory-workstream/src/transcript.rs b/crates/ai-memory-workstream/src/transcript.rsnew file mode 100644index 00000000..919ef9ec--- /dev/null+++ b/crates/ai-memory-workstream/src/transcript.rs@@ -0,0 +1,1259 @@+//! Incremental, read-only extraction from native harness session stores.++use std::fs::{self, File};+use std::io::{BufRead as _, BufReader, Seek as _, SeekFrom};+use std::path::{Path, PathBuf};+use std::time::{Duration, SystemTime, UNIX_EPOCH};++use ai_memory_core::{AgentKind, NewWorkstreamEvent, WorkstreamEventKind};+use anyhow::{Context as _, Result, anyhow};+use rusqlite::{Connection, OpenFlags, params};+use serde::{Deserialize, Serialize};+use serde_json::{Value, json};+use sha2::{Digest as _, Sha256};++use crate::ManagedHarness;++const MAX_SCAN_FILES: usize = 50_000;+const MAX_EVENT_BYTES: usize = 128 * 1024;++/// Incremental transcript export produced after a managed child exits.+#[derive(Debug, Clone, Default)]+pub struct ExportedTranscript {+ /// Native session that was read.+ pub native_session_id: String,+ /// Opaque adapter cursor persisted only for the next local read.+ pub source_cursor: Option<String>,+ /// Portable visible events after the incoming cursor.+ pub events: Vec<NewWorkstreamEvent>,+ /// Explicit records of private, malformed, or unsupported source data.+ pub losses: Vec<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+struct FileCursor {+ path: String,+ offset: u64,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+struct OpenCodeCursor {+ updated: i64,+ id: String,+}++/// Export unseen visible transcript records for one native session.+pub async fn export_transcript(+ harness: ManagedHarness,+ home: &Path,+ cwd: &Path,+ session_dir: Option<&Path>,+ native_session_id: &str,+ source_cursor: Option<&str>,+) -> Result<ExportedTranscript> {+ if harness == ManagedHarness::OpenCode {+ return export_opencode(home, session_dir, native_session_id, source_cursor);+ }+ let path = locate_session_file(harness, home, cwd, session_dir, native_session_id)?+ .ok_or_else(|| anyhow!("native transcript for {native_session_id} was not found"))?;+ export_jsonl(harness, &path, native_session_id, source_cursor)+}++/// Discover a session created after `started_at` when the harness could not be+/// assigned an id before launch and SessionStart did not link one.+pub async fn discover_native_session(+ harness: ManagedHarness,+ home: &Path,+ cwd: &Path,+ session_dir: Option<&Path>,+ started_at: SystemTime,+) -> Result<Option<String>> {+ if harness == ManagedHarness::OpenCode {+ return discover_opencode(home, session_dir, cwd, started_at);+ }+ let root = session_root(harness, home, session_dir);+ let mut candidates = collect_files(&root, |path| transcript_file(harness, path))?;+ candidates.sort_by_key(modified);+ candidates.reverse();+ for path in candidates.into_iter().take(512) {+ if modified(&path).is_some_and(|time| time + Duration::from_secs(2) < started_at) {+ break;+ }+ if let Some((id, record_cwd)) = session_header(harness, &path)?+ && same_path(&record_cwd, cwd)+ {+ return Ok(Some(id));+ }+ }+ Ok(None)+}++/// Wait briefly for buffered transcript writers to settle before importing.+pub async fn wait_for_transcript_flush(+ harness: ManagedHarness,+ home: &Path,+ cwd: &Path,+ session_dir: Option<&Path>,+ native_session_id: &str,+) -> Result<()> {+ let mut previous = None;+ for _ in 0..10 {+ let current = if harness == ManagedHarness::OpenCode {+ opencode_updated(home, session_dir, native_session_id)?.map(|value| value.to_string())+ } else {+ locate_session_file(harness, home, cwd, session_dir, native_session_id)?.and_then(+ |path| {+ fs::metadata(&path)+ .ok()+ .map(|metadata| format!("{}:{}", path.display(), metadata.len()))+ },+ )+ };+ if current.is_some() && current == previous {+ return Ok(());+ }+ previous = current;+ tokio::time::sleep(Duration::from_millis(200)).await;+ }+ Ok(())+}++fn export_jsonl(+ harness: ManagedHarness,+ path: &Path,+ native_session_id: &str,+ source_cursor: Option<&str>,+) -> Result<ExportedTranscript> {+ let cursor = source_cursor+ .and_then(|raw| serde_json::from_str::<FileCursor>(raw).ok())+ .filter(|cursor| Path::new(&cursor.path) == path);+ let mut file = File::open(path)+ .with_context(|| format!("opening native transcript {}", path.display()))?;+ let len = file.metadata()?.len();+ let start = cursor.map_or(0, |cursor| cursor.offset.min(len));+ file.seek(SeekFrom::Start(start))?;+ let mut reader = BufReader::new(file);+ let mut offset = start;+ let mut committed_offset = start;+ let mut line = Vec::new();+ let mut events = Vec::new();+ let mut losses = Vec::new();+ loop {+ line.clear();+ let read = reader.read_until(b'\n', &mut line)?;+ if read == 0 {+ break;+ }+ offset += read as u64;+ if !line.ends_with(b"\n") {+ break;+ }+ committed_offset = offset;+ let value: Value = match serde_json::from_slice(&line) {+ Ok(value) => value,+ Err(_) => {+ losses.push(format!(+ "malformed JSONL record at byte {}",+ offset - read as u64+ ));+ continue;+ }+ };+ let record_id =+ source_id(&value).unwrap_or_else(|| format!("byte-{}", offset - read as u64));+ match harness {+ ManagedHarness::Claude => parse_claude(+ &value,+ native_session_id,+ &record_id,+ &mut events,+ &mut losses,+ ),+ ManagedHarness::Codex => parse_codex(+ &value,+ native_session_id,+ &record_id,+ &mut events,+ &mut losses,+ ),+ ManagedHarness::Pi | ManagedHarness::Omp => parse_pi_family(+ harness.agent_kind(),+ &value,+ native_session_id,+ &record_id,+ &mut events,+ &mut losses,+ ),+ ManagedHarness::OpenCode => unreachable!("OpenCode uses its SQLite adapter"),+ }+ }+ Ok(ExportedTranscript {+ native_session_id: native_session_id.to_string(),+ source_cursor: Some(serde_json::to_string(&FileCursor {+ path: path.to_string_lossy().into_owned(),+ offset: committed_offset,+ })?),+ events,+ losses: deduplicate_losses(losses),+ })+}++fn parse_claude(+ value: &Value,+ session: &str,+ record_id: &str,+ events: &mut Vec<NewWorkstreamEvent>,+ losses: &mut Vec<String>,+) {+ if value.get("isMeta").and_then(Value::as_bool) == Some(true) {+ losses.push("Claude synthetic/meta records were intentionally excluded".into());+ return;+ }+ let record_type = value+ .get("type")+ .and_then(Value::as_str)+ .unwrap_or_default();+ let compact_boundary = record_type == "system"+ && value.get("subtype").and_then(Value::as_str) == Some("compact_boundary");+ if compact_boundary || matches!(record_type, "summary" | "compact" | "compaction") {+ if let Some(text) = first_string(value, &["summary", "content", "text"]) {+ push_event(+ events,+ AgentKind::ClaudeCode,+ session,+ record_id,+ 0,+ WorkstreamEventKind::Compaction,+ Some("assistant"),+ text,+ timestamp(value),+ json!({}),+ );+ }+ return;+ }+ if !matches!(record_type, "user" | "assistant") {+ return;+ }+ let message = value.get("message").unwrap_or(value);+ let role = message+ .get("role")+ .and_then(Value::as_str)+ .unwrap_or(record_type);+ if !matches!(role, "user" | "assistant") {+ losses.push("Claude non-conversation message records were intentionally excluded".into());+ return;+ }+ parse_content_blocks(+ AgentKind::ClaudeCode,+ session,+ record_id,+ role,+ message.get("content"),+ timestamp(value),+ events,+ losses,+ );+}++fn parse_codex(+ value: &Value,+ session: &str,+ record_id: &str,+ events: &mut Vec<NewWorkstreamEvent>,+ losses: &mut Vec<String>,+) {+ let record_type = value.get("type").and_then(Value::as_str);+ let payload = value.get("payload").unwrap_or(&Value::Null);+ if record_type == Some("compacted") {+ if let Some(summary) = first_string(payload, &["message", "summary", "content", "text"]) {+ push_event(+ events,+ AgentKind::Codex,+ session,+ record_id,+ 0,+ WorkstreamEventKind::Compaction,+ Some("assistant"),+ summary,+ timestamp(value),+ json!({}),+ );+ }+ return;+ }+ if record_type != Some("response_item") {+ return;+ }+ let item_type = payload+ .get("type")+ .and_then(Value::as_str)+ .unwrap_or_default();+ match item_type {+ "message" => {+ let role = payload+ .get("role")+ .and_then(Value::as_str)+ .unwrap_or_default();+ if !matches!(role, "user" | "assistant") {+ return;+ }+ parse_content_blocks(+ AgentKind::Codex,+ session,+ record_id,+ role,+ payload.get("content"),+ timestamp(value),+ events,+ losses,+ );+ }+ "function_call" | "custom_tool_call" | "tool_call" => {+ let name = first_string(payload, &["name", "tool"]).unwrap_or("tool");+ let body = first_string(payload, &["arguments", "input", "text"]).unwrap_or("");+ push_event(+ events,+ AgentKind::Codex,+ session,+ record_id,+ 0,+ WorkstreamEventKind::ToolCall,+ Some("assistant"),+ &format!("{name}: {body}"),+ timestamp(value),+ json!({"tool": name}),+ );+ }+ "function_call_output" | "custom_tool_call_output" | "tool_result" => {+ let body = first_string(payload, &["output", "content", "text"]).unwrap_or("");+ push_event(+ events,+ AgentKind::Codex,+ session,+ record_id,+ 0,+ WorkstreamEventKind::ToolResult,+ Some("tool"),+ body,+ timestamp(value),+ json!({}),+ );+ }+ "web_search_call" => {+ let action = payload.get("action").map(compact_json).unwrap_or_default();+ push_event(+ events,+ AgentKind::Codex,+ session,+ record_id,+ 0,+ WorkstreamEventKind::ToolCall,+ Some("assistant"),+ &format!("web_search: {action}"),+ timestamp(value),+ json!({"tool": "web_search", "status": payload.get("status").and_then(Value::as_str)}),+ );+ }+ "compacted" | "compaction" => {+ let body = first_string(payload, &["summary", "content", "text"]).unwrap_or("");+ push_event(+ events,+ AgentKind::Codex,+ session,+ record_id,+ 0,+ WorkstreamEventKind::Compaction,+ Some("assistant"),+ body,+ timestamp(value),+ json!({}),+ );+ }+ "reasoning" => losses.push("Codex hidden reasoning was intentionally excluded".into()),+ _ => {}+ }+}++fn parse_pi_family(+ agent: AgentKind,+ value: &Value,+ session: &str,+ record_id: &str,+ events: &mut Vec<NewWorkstreamEvent>,+ losses: &mut Vec<String>,+) {+ let record_type = value+ .get("type")+ .and_then(Value::as_str)+ .unwrap_or_default();+ match record_type {+ "message" => {+ let message = value.get("message").unwrap_or(value);+ let role = message+ .get("role")+ .and_then(Value::as_str)+ .unwrap_or("assistant");+ match role {+ "user" | "assistant" => parse_content_blocks(+ agent,+ session,+ record_id,+ role,+ message.get("content"),+ timestamp(value),+ events,+ losses,+ ),+ "tool" | "toolResult" | "tool_result" => {+ let body = message.get("content").map(value_text).unwrap_or_default();+ let tool = first_string(message, &["toolName", "tool", "name"]);+ push_event(+ events,+ agent,+ session,+ record_id,+ 0,+ WorkstreamEventKind::ToolResult,+ Some("tool"),+ &body,+ timestamp(value),+ json!({+ "tool": tool,+ "is_error": message.get("isError").or_else(|| message.get("is_error")).and_then(Value::as_bool).unwrap_or(false)+ }),+ );+ }+ _ => losses.push(format!(+ "{} non-conversation message records were intentionally excluded",+ agent.as_str()+ )),+ }+ }+ "compaction" | "compact" | "summary" => {+ let body = first_string(value, &["summary", "content", "text"]).unwrap_or("");+ push_event(+ events,+ agent,+ session,+ record_id,+ 0,+ WorkstreamEventKind::Compaction,+ Some("assistant"),+ body,+ timestamp(value),+ json!({}),+ );+ }+ _ => {}+ }+}++#[allow(clippy::too_many_arguments)]+fn parse_content_blocks(+ agent: AgentKind,+ session: &str,+ record_id: &str,+ role: &str,+ content: Option<&Value>,+ occurred_at: Option<String>,+ events: &mut Vec<NewWorkstreamEvent>,+ losses: &mut Vec<String>,+) {+ let Some(content) = content else { return };+ let blocks: Vec<&Value> = content+ .as_array()+ .map_or_else(|| vec![content], |items| items.iter().collect());+ for (index, block) in blocks.into_iter().enumerate() {+ if let Some(text) = block.as_str() {+ if codex_synthetic_context(agent, role, text) {+ continue;+ }+ push_event(+ events,+ agent,+ session,+ record_id,+ index,+ WorkstreamEventKind::Message,+ Some(role),+ text,+ occurred_at.clone(),+ json!({}),+ );+ continue;+ }+ let block_type = block+ .get("type")+ .and_then(Value::as_str)+ .unwrap_or_default();+ match block_type {+ "text" | "input_text" | "output_text" => {+ if let Some(text) = first_string(block, &["text", "content"]) {+ if codex_synthetic_context(agent, role, text) {+ continue;+ }+ push_event(+ events,+ agent,+ session,+ record_id,+ index,+ WorkstreamEventKind::Message,+ Some(role),+ text,+ occurred_at.clone(),+ json!({}),+ );+ }+ }+ "tool_use" | "toolCall" | "tool_call" => {+ let name = first_string(block, &["name", "toolName", "tool"]).unwrap_or("tool");+ let input = block+ .get("input")+ .or_else(|| block.get("arguments"))+ .map(compact_json)+ .unwrap_or_default();+ push_event(+ events,+ agent,+ session,+ record_id,+ index,+ WorkstreamEventKind::ToolCall,+ Some("assistant"),+ &format!("{name}: {input}"),+ occurred_at.clone(),+ json!({"tool": name}),+ );+ }+ "tool_result" | "toolResult" => {+ let body = block.get("content").map(value_text).unwrap_or_default();+ push_event(+ events,+ agent,+ session,+ record_id,+ index,+ WorkstreamEventKind::ToolResult,+ Some("tool"),+ &body,+ occurred_at.clone(),+ json!({"is_error": block.get("is_error").and_then(Value::as_bool).unwrap_or(false)}),+ );+ }+ "thinking" | "reasoning" | "redacted_thinking" => {+ losses.push(format!(+ "{} hidden reasoning was intentionally excluded",+ agent.as_str()+ ));+ }+ _ => {}+ }+ }+}++fn codex_synthetic_context(agent: AgentKind, role: &str, text: &str) -> bool {+ if role != "user" {+ return false;+ }+ let trimmed = text.trim_start();+ match agent {+ AgentKind::Codex => {+ trimmed.starts_with("# AGENTS.md instructions for ")+ || trimmed.starts_with("<environment_context>")+ || trimmed.starts_with("<permissions instructions>")+ || trimmed.starts_with("<INSTRUCTIONS>")+ }+ AgentKind::ClaudeCode => trimmed.starts_with("<system-reminder>"),+ _ => false,+ }+}++fn export_opencode(+ home: &Path,+ session_dir: Option<&Path>,+ session: &str,+ source_cursor: Option<&str>,+) -> Result<ExportedTranscript> {+ let db = opencode_db(home, session_dir);+ let connection = Connection::open_with_flags(+ &db,+ OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,+ )+ .with_context(|| {+ format!(+ "opening OpenCode session database {} read-only",+ db.display()+ )+ })?;+ let cursor = source_cursor+ .and_then(|raw| serde_json::from_str::<OpenCodeCursor>(raw).ok())+ .unwrap_or_default();+ let mut statement = connection.prepare(+ "SELECT p.id, p.time_updated, m.data, p.data+ FROM part p JOIN message m ON m.id = p.message_id+ WHERE p.session_id = ?1 AND (p.time_updated > ?2 OR (p.time_updated = ?2 AND p.id > ?3))+ ORDER BY p.time_updated, p.id",+ )?;+ let rows = statement.query_map(params![session, cursor.updated, cursor.id], |row| {+ Ok((+ row.get::<_, String>(0)?,+ row.get::<_, i64>(1)?,+ row.get::<_, String>(2)?,+ row.get::<_, String>(3)?,+ ))+ })?;+ let mut events = Vec::new();+ let mut losses = Vec::new();+ let mut next_cursor = cursor;+ for row in rows {+ let (id, updated, message_raw, part_raw) = row?;+ next_cursor = OpenCodeCursor {+ updated,+ id: id.clone(),+ };+ let Ok(message) = serde_json::from_str::<Value>(&message_raw) else {+ losses.push(format!("malformed OpenCode message for part {id}"));+ continue;+ };+ let Ok(part) = serde_json::from_str::<Value>(&part_raw) else {+ losses.push(format!("malformed OpenCode part {id}"));+ continue;+ };+ parse_opencode(&message, &part, session, &id, &mut events, &mut losses);+ }+ Ok(ExportedTranscript {+ native_session_id: session.to_string(),+ source_cursor: Some(serde_json::to_string(&next_cursor)?),+ events,+ losses: deduplicate_losses(losses),+ })+}++fn parse_opencode(+ message: &Value,+ part: &Value,+ session: &str,+ id: &str,+ events: &mut Vec<NewWorkstreamEvent>,+ losses: &mut Vec<String>,+) {+ let role = message+ .get("role")+ .and_then(Value::as_str)+ .unwrap_or("assistant");+ let kind = part.get("type").and_then(Value::as_str).unwrap_or_default();+ match kind {+ "text" => {+ if !matches!(role, "user" | "assistant") {+ losses.push(+ "OpenCode non-conversation message records were intentionally excluded".into(),+ );+ return;+ }+ if let Some(text) = first_string(part, &["text", "content"]) {+ push_event(+ events,+ AgentKind::OpenCode,+ session,+ id,+ 0,+ WorkstreamEventKind::Message,+ Some(role),+ text,+ None,+ json!({}),+ );+ }+ }+ "tool" => {+ let name = first_string(part, &["tool", "name"]).unwrap_or("tool");+ let state = part.get("state").unwrap_or(&Value::Null);+ let input = state.get("input").map(compact_json).unwrap_or_default();+ push_event(+ events,+ AgentKind::OpenCode,+ session,+ id,+ 0,+ WorkstreamEventKind::ToolCall,+ Some("assistant"),+ &format!("{name}: {input}"),+ None,+ json!({"tool": name}),+ );+ if let Some(output) = state+ .get("output")+ .map(value_text)+ .filter(|value| !value.is_empty())+ {+ push_event(+ events,+ AgentKind::OpenCode,+ session,+ id,+ 1,+ WorkstreamEventKind::ToolResult,+ Some("tool"),+ &output,+ None,+ json!({"status": state.get("status").and_then(Value::as_str)}),+ );+ }+ }+ "compaction" => {+ let body = first_string(part, &["summary", "text", "content"]).unwrap_or("");+ push_event(+ events,+ AgentKind::OpenCode,+ session,+ id,+ 0,+ WorkstreamEventKind::Compaction,+ Some("assistant"),+ body,+ None,+ json!({}),+ );+ }+ "reasoning" => losses.push("OpenCode hidden reasoning was intentionally excluded".into()),+ _ => {}+ }+}++#[allow(clippy::too_many_arguments)]+fn push_event(+ events: &mut Vec<NewWorkstreamEvent>,+ agent: AgentKind,+ session: &str,+ record_id: &str,+ block: usize,+ kind: WorkstreamEventKind,+ role: Option<&str>,+ content: &str,+ occurred_at: Option<String>,+ metadata: Value,+) {+ if content.trim().is_empty() {+ return;+ }+ let content = truncate_utf8(content, MAX_EVENT_BYTES);+ let seed = format!(+ "{}\0{session}\0{record_id}\0{block}\0{}\0{content}",+ agent.as_str(),+ kind.as_str()+ );+ events.push(NewWorkstreamEvent {+ event_id: format!("native:{:x}", Sha256::digest(seed.as_bytes())),+ agent,+ native_session_id: session.to_string(),+ source_record_id: Some(record_id.to_string()),+ kind,+ role: role.map(str::to_string),+ content: content.to_string(),+ occurred_at,+ metadata,+ });+}++fn locate_session_file(+ harness: ManagedHarness,+ home: &Path,+ cwd: &Path,+ session_dir: Option<&Path>,+ id: &str,+) -> Result<Option<PathBuf>> {+ let root = session_root(harness, home, session_dir);+ if harness == ManagedHarness::Claude {+ let encoded = cwd.to_string_lossy().replace('/', "-");+ let exact = root.join(encoded).join(format!("{id}.jsonl"));+ if exact.is_file() {+ return Ok(Some(exact));+ }+ }+ let mut files = collect_files(&root, |path| transcript_file(harness, path))?;+ files.sort_by_key(|path| temporary_transcript(path));+ for path in &files {+ if path.to_string_lossy().contains(id) {+ return Ok(Some(path.clone()));+ }+ }+ for path in files.into_iter().take(2_000) {+ if session_header(harness, &path)?.is_some_and(|(found, _)| found == id) {+ return Ok(Some(path));+ }+ }+ Ok(None)+}++fn transcript_file(harness: ManagedHarness, path: &Path) -> bool {+ path.extension().is_some_and(|ext| ext == "jsonl")+ || matches!(harness, ManagedHarness::Pi | ManagedHarness::Omp) && temporary_transcript(path)+}++fn temporary_transcript(path: &Path) -> bool {+ path.extension().is_some_and(|ext| ext == "tmp")+ && path+ .file_name()+ .and_then(|name| name.to_str())+ .is_some_and(|name| name.contains(".jsonl."))+}++fn session_header(harness: ManagedHarness, path: &Path) -> Result<Option<(String, PathBuf)>> {+ let mut reader = BufReader::new(File::open(path)?);+ let mut line = String::new();+ for _ in 0..64 {+ line.clear();+ if reader.read_line(&mut line)? == 0 {+ break;+ }+ let Ok(value) = serde_json::from_str::<Value>(&line) else {+ continue;+ };+ let (id, cwd) = match harness {+ ManagedHarness::Claude => (+ value.get("sessionId").and_then(Value::as_str),+ value.get("cwd").and_then(Value::as_str),+ ),+ ManagedHarness::Codex => {+ let payload = value.get("payload").unwrap_or(&Value::Null);+ (+ payload.get("id").and_then(Value::as_str),+ payload.get("cwd").and_then(Value::as_str),+ )+ }+ ManagedHarness::Pi | ManagedHarness::Omp => (+ value.get("id").and_then(Value::as_str),+ value.get("cwd").and_then(Value::as_str),+ ),+ ManagedHarness::OpenCode => (None, None),+ };+ if let (Some(id), Some(cwd)) = (id, cwd) {+ return Ok(Some((id.to_string(), PathBuf::from(cwd))));+ }+ }+ Ok(None)+}++fn discover_opencode(+ home: &Path,+ session_dir: Option<&Path>,+ cwd: &Path,+ started_at: SystemTime,+) -> Result<Option<String>> {+ let db = opencode_db(home, session_dir);+ if !db.is_file() {+ return Ok(None);+ }+ let connection = Connection::open_with_flags(+ &db,+ OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,+ )?;+ let since = started_at+ .duration_since(UNIX_EPOCH)+ .unwrap_or_default()+ .as_millis() as i64;+ let mut statement = connection.prepare(+ "SELECT id FROM session WHERE directory = ?1 AND time_updated >= ?2 ORDER BY time_updated DESC LIMIT 1",+ )?;+ match statement.query_row(params![cwd.to_string_lossy(), since], |row| row.get(0)) {+ Ok(id) => Ok(Some(id)),+ Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),+ Err(error) => Err(error.into()),+ }+}++fn opencode_updated(home: &Path, session_dir: Option<&Path>, session: &str) -> Result<Option<i64>> {+ let db = opencode_db(home, session_dir);+ if !db.is_file() {+ return Ok(None);+ }+ let connection = Connection::open_with_flags(+ &db,+ OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,+ )?;+ match connection.query_row(+ "SELECT time_updated FROM session WHERE id = ?1",+ [session],+ |row| row.get(0),+ ) {+ Ok(value) => Ok(Some(value)),+ Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),+ Err(error) => Err(error.into()),+ }+}++fn opencode_db(home: &Path, session_dir: Option<&Path>) -> PathBuf {+ session_dir.map_or_else(+ || home.join(".local/share/opencode/opencode.db"),+ |dir| dir.join("opencode.db"),+ )+}++fn session_root(harness: ManagedHarness, home: &Path, override_dir: Option<&Path>) -> PathBuf {+ if let Some(override_dir) = override_dir {+ return override_dir.to_path_buf();+ }+ match harness {+ ManagedHarness::Claude => home.join(".claude/projects"),+ ManagedHarness::Codex => home.join(".codex/sessions"),+ ManagedHarness::OpenCode => home.join(".local/share/opencode"),+ ManagedHarness::Pi => home.join(".pi/agent/sessions"),+ ManagedHarness::Omp => home.join(".omp/agent/sessions"),+ }+}++fn collect_files(root: &Path, predicate: impl Fn(&Path) -> bool + Copy) -> Result<Vec<PathBuf>> {+ if !root.is_dir() {+ return Ok(Vec::new());+ }+ let mut pending = vec![root.to_path_buf()];+ let mut files = Vec::new();+ while let Some(directory) = pending.pop() {+ for entry in+ fs::read_dir(&directory).with_context(|| format!("reading {}", directory.display()))?+ {+ let entry = entry?;+ let path = entry.path();+ let file_type = entry.file_type()?;+ if file_type.is_dir() {+ pending.push(path)+ } else if file_type.is_file() && predicate(&path) {+ files.push(path);+ if files.len() >= MAX_SCAN_FILES {+ return Ok(files);+ }+ }+ }+ }+ Ok(files)+}++fn source_id(value: &Value) -> Option<String> {+ for key in ["uuid", "id", "messageId", "call_id", "callId"] {+ if let Some(id) = value.get(key).and_then(Value::as_str) {+ return Some(id.to_string());+ }+ }+ value.get("payload").and_then(|payload| {+ ["id", "call_id", "callId"]+ .into_iter()+ .find_map(|key| payload.get(key).and_then(Value::as_str).map(str::to_string))+ })+}++fn timestamp(value: &Value) -> Option<String> {+ value+ .get("timestamp")+ .and_then(Value::as_str)+ .map(str::to_string)+}++fn first_string<'a>(value: &'a Value, keys: &[&str]) -> Option<&'a str> {+ keys.iter()+ .find_map(|key| value.get(*key).and_then(Value::as_str))+}++fn value_text(value: &Value) -> String {+ match value {+ Value::String(text) => text.clone(),+ Value::Array(items) => items+ .iter()+ .map(value_text)+ .filter(|text| !text.is_empty())+ .collect::<Vec<_>>()+ .join("\n"),+ Value::Object(_) => first_string(value, &["text", "content", "output"])+ .map_or_else(|| compact_json(value), str::to_string),+ Value::Null => String::new(),+ _ => value.to_string(),+ }+}++fn compact_json(value: &Value) -> String {+ serde_json::to_string(value).unwrap_or_default()+}++fn truncate_utf8(value: &str, max: usize) -> &str {+ if value.len() <= max {+ return value;+ }+ let mut end = max;+ while !value.is_char_boundary(end) {+ end -= 1+ }+ &value[..end]+}++fn modified(path: &PathBuf) -> Option<SystemTime> {+ fs::metadata(path).ok()?.modified().ok()+}++fn same_path(left: &Path, right: &Path) -> bool {+ left.canonicalize().ok() == right.canonicalize().ok()+}++fn deduplicate_losses(losses: Vec<String>) -> Vec<String> {+ let mut output = Vec::new();+ for loss in losses {+ if !output.contains(&loss) {+ output.push(loss)+ }+ }+ output+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn incomplete_final_jsonl_record_does_not_advance_cursor() {+ let temp = tempfile::tempdir().unwrap();+ let path = temp.path().join("session.jsonl");+ fs::write(&path, b"{\"type\":\"message\",\"id\":\"one\",\"message\":{\"role\":\"user\",\"content\":\"hello\"}}\n{\"type\":").unwrap();+ let export = export_jsonl(ManagedHarness::Pi, &path, "session", None).unwrap();+ let cursor: FileCursor =+ serde_json::from_str(export.source_cursor.as_deref().unwrap()).unwrap();+ assert_eq!(cursor.offset, 74);+ assert_eq!(export.events.len(), 1);+ }++ #[test]+ fn omp_adapter_reads_complete_atomic_write_temp_transcript() {+ let temp = tempfile::tempdir().unwrap();+ let session = "019f80c5-0148-7000-82d5-9a3c4c9b9be3";+ let path = temp+ .path()+ .join(format!(".session_{session}.jsonl.nonce.tmp"));+ std::fs::write(+ &path,+ format!("{{\"type\":\"session\",\"id\":\"{session}\",\"cwd\":\"/repo\"}}\n"),+ )+ .unwrap();++ let found = locate_session_file(+ ManagedHarness::Omp,+ temp.path(),+ Path::new("/repo"),+ Some(temp.path()),+ session,+ )+ .unwrap();++ assert_eq!(found.as_deref(), Some(path.as_path()));+ }++ #[test]+ fn claude_adapter_excludes_thinking_and_keeps_tools() {+ let value = json!({"type":"assistant","uuid":"record","timestamp":"2026-01-01T00:00:00Z","message":{"role":"assistant","content":[+ {"type":"thinking","thinking":"private"},+ {"type":"tool_use","name":"Read","input":{"file":"README.md"}},+ {"type":"text","text":"Done"}+ ]}});+ let mut events = Vec::new();+ let mut losses = Vec::new();+ parse_claude(&value, "session", "record", &mut events, &mut losses);+ assert_eq!(events.len(), 2);+ assert_eq!(events[0].kind, WorkstreamEventKind::ToolCall);+ assert_eq!(events[1].content, "Done");+ assert_eq!(losses.len(), 1);+ }++ #[test]+ fn claude_adapter_keeps_compaction_and_excludes_meta_records() {+ let compact = json!({+ "type":"system",+ "subtype":"compact_boundary",+ "uuid":"compact",+ "content":"portable compact summary",+ "isMeta":false+ });+ let meta = json!({+ "type":"user",+ "uuid":"meta",+ "isMeta":true,+ "message":{"role":"user","content":"private harness metadata"}+ });+ let mut events = Vec::new();+ let mut losses = Vec::new();+ parse_claude(&compact, "session", "compact", &mut events, &mut losses);+ parse_claude(&meta, "session", "meta", &mut events, &mut losses);+ assert_eq!(events.len(), 1);+ assert_eq!(events[0].kind, WorkstreamEventKind::Compaction);+ assert_eq!(events[0].content, "portable compact summary");+ assert_eq!(+ losses,+ ["Claude synthetic/meta records were intentionally excluded"]+ );+ }++ #[test]+ fn event_ids_are_stable() {+ let mut first = Vec::new();+ let mut second = Vec::new();+ push_event(+ &mut first,+ AgentKind::Codex,+ "s",+ "r",+ 0,+ WorkstreamEventKind::Message,+ Some("user"),+ "hello",+ None,+ json!({}),+ );+ push_event(+ &mut second,+ AgentKind::Codex,+ "s",+ "r",+ 0,+ WorkstreamEventKind::Message,+ Some("user"),+ "hello",+ None,+ json!({}),+ );+ assert_eq!(first[0].event_id, second[0].event_id);+ }++ #[test]+ fn codex_adapter_excludes_reloaded_harness_context() {+ let value = json!({"type":"response_item","payload":{"type":"message","role":"user","content":[+ {"type":"input_text","text":"# AGENTS.md instructions for /repo\n<INSTRUCTIONS>private</INSTRUCTIONS>"},+ {"type":"input_text","text":"actual request"}+ ]}});+ let mut events = Vec::new();+ let mut losses = Vec::new();+ parse_codex(&value, "session", "record", &mut events, &mut losses);+ assert_eq!(events.len(), 1);+ assert_eq!(events[0].content, "actual request");+ }++ #[test]+ fn codex_adapter_keeps_current_top_level_compaction_shape() {+ let value = json!({+ "type":"compacted",+ "timestamp":"2026-01-01T00:00:00Z",+ "payload":{"message":"portable compact summary","replacement_history":[]}+ });+ let mut events = Vec::new();+ let mut losses = Vec::new();+ parse_codex(&value, "session", "record", &mut events, &mut losses);+ assert_eq!(events.len(), 1);+ assert_eq!(events[0].kind, WorkstreamEventKind::Compaction);+ assert_eq!(events[0].content, "portable compact summary");+ }++ #[test]+ fn message_adapters_exclude_non_conversation_roles() {+ let claude = json!({+ "type":"user",+ "message":{"role":"system","content":"private Claude instructions"}+ });+ let opencode_message = json!({"role":"system"});+ let opencode_part = json!({"type":"text","text":"private OpenCode instructions"});+ let pi = json!({+ "type":"message",+ "message":{"role":"system","content":"private Pi instructions"}+ });+ let mut events = Vec::new();+ let mut losses = Vec::new();++ parse_claude(&claude, "session", "claude", &mut events, &mut losses);+ parse_opencode(+ &opencode_message,+ &opencode_part,+ "session",+ "opencode",+ &mut events,+ &mut losses,+ );+ parse_pi_family(+ AgentKind::Pi,+ &pi,+ "session",+ "pi",+ &mut events,+ &mut losses,+ );++ assert!(events.is_empty());+ assert_eq!(losses.len(), 3);+ }++ #[test]+ fn pi_family_adapter_normalizes_tool_result_messages() {+ let value = json!({+ "type":"message",+ "timestamp":"2026-01-01T00:00:00Z",+ "message":{+ "role":"toolResult",+ "toolName":"read",+ "isError":false,+ "content":[{"type":"text","text":"file contents"}]+ }+ });+ let mut events = Vec::new();+ let mut losses = Vec::new();+ parse_pi_family(+ AgentKind::Omp,+ &value,+ "session",+ "record",+ &mut events,+ &mut losses,+ );++ assert!(losses.is_empty());+ assert_eq!(events.len(), 1);+ assert_eq!(events[0].kind, WorkstreamEventKind::ToolResult);+ assert_eq!(events[0].role.as_deref(), Some("tool"));+ assert!(events[0].content.contains("file contents"));+ assert_eq!(events[0].metadata["tool"], "read");+ }++ #[test]+ fn opencode_adapter_reads_sqlite_incrementally_without_writing_it() {+ let home = tempfile::tempdir().unwrap();+ let db = opencode_db(home.path(), None);+ fs::create_dir_all(db.parent().unwrap()).unwrap();+ let connection = Connection::open(&db).unwrap();+ connection+ .execute_batch(+ "CREATE TABLE message(id TEXT PRIMARY KEY, session_id TEXT, data TEXT);\n\+ CREATE TABLE part(id TEXT PRIMARY KEY, message_id TEXT, session_id TEXT, \+ time_updated INTEGER, data TEXT);",+ )+ .unwrap();+ connection+ .execute(+ "INSERT INTO message VALUES ('m1', 's1', ?1)",+ [json!({"role":"user"}).to_string()],+ )+ .unwrap();+ connection+ .execute(+ "INSERT INTO part VALUES ('p1', 'm1', 's1', 1, ?1)",+ [json!({"type":"text","text":"first"}).to_string()],+ )+ .unwrap();++ let first = export_opencode(home.path(), None, "s1", None).unwrap();+ assert_eq!(first.events.len(), 1);+ assert_eq!(first.events[0].content, "first");+ connection+ .execute(+ "INSERT INTO part VALUES ('p2', 'm1', 's1', 2, ?1)",+ [json!({"type":"text","text":"second"}).to_string()],+ )+ .unwrap();+ let second =+ export_opencode(home.path(), None, "s1", first.source_cursor.as_deref()).unwrap();+ assert_eq!(second.events.len(), 1);+ assert_eq!(second.events[0].content, "second");+ }+}diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex af6aedd8..35e7aeec 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -27,7 +27,8 @@ markdown stays the source of truth.Solid arrows are request, read, and write paths. Dashed arrows arebackground reconciliation or provider-backed maintenance. The core invariant isunchanged: the markdown wiki is the source of truth, and SQLite is the derived-index for search, sessions, observations, handoffs, audit, and embeddings.+index for search, sessions, observations, handoffs, audit, embeddings, and the+optional managed-workstream continuity ledger.Auto-improvement sits on the provider-backed maintenance side: the serverschedules reviews for newly completed sessions in every project, recordsvalidated proposals in the pending-writes audit trail, and auto-approves them@@ -101,6 +102,17 @@ from hook paths.backup API so the source stays writable; `ai-memory restore`reverses. Or: `git push` the wiki dir + `rsync` the data dir.+**Optional managed-workstream loop:** `ai-memory run` opens a lease for the+current repository/worktree workstream, uses a harness adapter to create or+resume that harness's native session, and marks lifecycle calls with an+invocation-scoped run id. SessionStart injects an unseen bounded event range;+the host imports the native transcript tail and a Git checkpoint when the child+exits. Native stores are read-only. Raw sanitized JSONL segments are immutable,+while SQLite supplies monotonic sequences, FTS, native source/delivery cursors,+and idempotent retry state. A full-ledger `workstream-search` path complements+the bounded startup packet. See [Managed cross-harness+workstreams](managed-workstreams.md).+## Hook event vocabularyThe core observation vocabulary is a closed set of agent lifecycle@@ -141,8 +153,9 @@ backpressure, or single-writer SQLite actor.* `<data_dir>/db/memory.sqlite` - derived index. WAL mode. Onewriter actor owns the writer `Connection`; reads go through acloneable read-only pool.-* `<data_dir>/raw/` - reserved for raw session log archives; current raw- fallback recall searches the durable `observations` table via FTS5.+* `<data_dir>/raw/` - immutable sanitized managed-workstream JSONL segments.+ Legacy raw fallback recall searches the durable `observations` table via+ FTS5; lifecycle HookEnvelope JSON is not a complete transcript archive.* `<data_dir>/logs/` - rolling daily `tracing` output.* `<data_dir>/models/` - reserved for bundled embedding models(M9.5+, when local `ort` lands).@@ -154,8 +167,10 @@ backpressure, or single-writer SQLite actor.| `workspaces`, `projects` | Top of the 3-tuple identity coordinate. || `pages` | Versioned wiki pages with `is_latest` + `supersedes` chain. M8 columns: `last_accessed_at`, `access_count`, `superseded_at`. M9 cols: `embedding_provider`, `embedding_model`, `embedding_dim`. || `pages_fts` | FTS5 virtual table over `(title, body)`, auto-synced by triggers. |-| `sessions`, `observations` | Hook capture, full audit log. |+| `sessions`, `observations` | Sanitized, bounded lifecycle-hook projections. They are an operational audit trail, not a complete native transcript. || `observations_fts` | FTS5 virtual table over raw observation `(title, body)`, used only as bounded fallback. |+| `workstreams`, `managed_runs`, `workstream_native_sessions` | Optional lease state plus per-harness native source and delivery cursors for `ai-memory run`. |+| `workstream_events`, `workstream_events_fts` | Append-only normalized visible transcript events and full-text search; immutable sanitized source batches also live under `raw/workstreams/`. || `links` | Wikilink / markdown cross-references. `to_page_id` (a global PageId) is nullable for unresolved forward links. `to_workspace` / `to_project` carry a cross-project scope (NULL = the source page's own project). || `handoffs` | Typed cross-agent handoff records (open / accepted / expired). || `page_embeddings` | Optional vector rows for latest pages, with `(provider, model, dim)` denormalised so hybrid search can ignore stale vectors after an embedding config change and report missing-embedding diagnostics. |@@ -218,6 +233,7 @@ crates/├── ai-memory-hooks/ payload schemas, sanitiser, /hook ingress.├── ai-memory-llm/ provider auth boundary + LlmProvider / Embedder traits.├── ai-memory-consolidate/ Karpathy ingest / lint / sweep / auto-improve pipeline.+├── ai-memory-workstream/ read-only native transcript + launch adapters.└── ai-memory-cli/ `ai-memory` binary entry point + thin HTTP subcommands.```diff --git a/docs/design-decisions.md b/docs/design-decisions.mdindex 7e06fa93..a3aff4a0 100644--- a/docs/design-decisions.md+++ b/docs/design-decisions.md@@ -11,7 +11,7 @@A self-contained Rust binary that:1. Runs as an **MCP server** (stdio + HTTP/SSE) for coding-agent CLIs (Claude Code, OpenAI Codex, Cursor, Gemini CLI, Antigravity CLI, OpenClaw, OpenCode, OMP, and MCP-capable clients).-2. Captures the agent's session **automatically** - no `write_note` ceremony - via hook scripts or generated extensions that the agent CLIs invoke (Claude Code / Codex / Cursor / Gemini CLI / Antigravity CLI lifecycle hooks, OpenClaw / OpenCode / OMP TypeScript integrations). Optional transcript-tail fallback for agents without hook APIs.+2. Captures sanitized, bounded lifecycle observations **automatically** - no `write_note` ceremony - via hook scripts or generated extensions that agent CLIs invoke. Optional `ai-memory run` workstreams additionally read visible native transcript tails through host-side, read-only adapters.3. Maintains a **Karpathy-style wiki**: incrementally-compiled markdown pages with cross-links, supersession, an `index.md` and a `log.md`.4. Serves retrieval via the MCP `tools/list` to coding agents: a handful of *narrow* tools, not 50.5. Ships a **Docker image** (`docker run -v ai-memory-data:/data -p 49374:49374 ai-memory`) so it can move between desktop and homelab.@@ -239,9 +239,11 @@ Project resolution chain: explicit param → server's default → cwd-based heur- **Self-healing**: startup checks (`memory_diagnose`): vector dim/provider drift, FTS index corruption, orphan pages, broken links, zombie sessions. `memory_heal` auto-fixes the safe subset.- **Logging**: structured `tracing` with rotating files, capped at N MB. No feedback loops (agentmemory #519).-## 13. What we are explicitly NOT doing in v1+## 13. Original v1 exclusions (historical)-To stay scoped:+The initial scope excluded the following. Some, including multi-user auth, the+web UI, and managed Agent Skills, shipped after v1; this list is retained as the+historical decision boundary rather than a current support matrix.- No multi-tenant auth/RBAC (single-user homelab).- No web UI / dashboard (use `sqlite3` + `glow`/Obsidian).@@ -277,3 +279,31 @@ Top-line rules carved into the codebase:18. LLM has off by default; opt-in via env (agentmemory #138/#143).19. `cargo deny` for transitive license audits (cognee #2807 - FastEmbed removed for license).20. Pin upstream native deps; ship a lockfile (agentmemory #555/#540).++## 15. Managed workstreams use a portable ledger, not native format conversion++Managed cross-harness continuity is explicitly opt-in through `ai-memory run`.+Direct Claude Code, Codex, OpenCode, Pi, and OMP launches retain the existing+hook and single-use handoff behavior. There is no process-global mode or manual+harness switch: the wrapper selects the current repository/worktree workstream+and each adapter applies that harness's native create/resume syntax.++One logical workstream owns one native session per harness plus an append-only+portable event ledger. We rejected converting a Claude transcript into a fake+Codex rollout (and the inverse): native stores include private, versioned state,+provider-specific records, and integrity assumptions that ai-memory does not+own. Adapters therefore read native stores without modifying them, normalize+only visible messages/completed tools/compaction boundaries, and keep source+and delivery cursors separately. Hidden reasoning and provider-private records+are excluded explicitly.++A renewable single-writer lease resolves precedence and concurrency instead of+attempting bidirectional file synchronization. SessionStart receives a bounded+unseen delta; the full visible ledger stays searchable. Repository checkpoints+are evidence at run boundaries and never commit, stash, reset, or otherwise+mutate the checkout. The markdown wiki remains the durable knowledge surface;+the managed ledger is an operational continuity substrate.++This design follows the harness-format and session-portability experiments in+the companion `ai-babel` research project: semantic continuity is portable,+while exact native context is preserved by resuming that harness's own session.diff --git a/docs/install.md b/docs/install.mdindex 3e891161..2d24e00f 100644--- a/docs/install.md+++ b/docs/install.md@@ -14,6 +14,8 @@ path (docker + Claude Code). This page covers everything else:(curl-based installer)- [Running ai-memory without docker](#running-ai-memory-without-docker)(cargo install, building from source)+- [Managed cross-harness workstreams](managed-workstreams.md)+ (`ai-memory run`, transparent native resume, and argument forwarding)- [LLM provider tiers + self-hosted Ollama](#llm-provider-tiers)- [Subcommand reference](#subcommand-reference)- [Managed routing snippets and Agent Skills](#managed-routing-snippets-and-agent-skills)@@ -1092,6 +1094,8 @@ docker run --rm akitaonrails/ai-memory:latest --help # full subcommand tree| Subcommand | Pattern | What it does ||---|---|---|| `serve` | `docker compose up -d` (already done) | Run the HTTP MCP server |+| `run <harness> [args...]` | host wrapper or native binary | Opt into one managed cross-harness workstream; all arguments after the harness name go to the harness unchanged |+| `workstream-search [query]` | managed child or thin HTTP client | Search the complete visible managed-workstream ledger; the managed child receives its workstream id automatically || `status` | `docker exec` | Counts, paths, derived-index diagnostics, and passive LLM/embedding provider health || `search "<query>"` | `docker exec` | Wiki search with FTS5 + graph/vector RRF || `write-page` | `docker exec` | Manual page write (atomic + indexed) |diff --git a/docs/lifecycle-ops.md b/docs/lifecycle-ops.mdindex 62d5462a..0debd310 100644--- a/docs/lifecycle-ops.md+++ b/docs/lifecycle-ops.md@@ -281,7 +281,7 @@ supersession chain (the real page history lives in the wiki's gitmirror). The `true-move` path has no such loss.> **Operational caveat — moving the project the current session writes-> to.** Lifecycle hooks stamp an observation on every tool call into the+> to.** Lifecycle hooks stamp a bounded observation on every supported tool-lifecycle event into the> session's project. If you move that very project mid-session, the next> hook re-creates the source (`scratch`-style) under the old workspace.> Before moving a live project, point the repo's `.ai-memory.toml` at thediff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.mdnew file mode 100644index 00000000..3107c565--- /dev/null+++ b/docs/managed-workstreams.md@@ -0,0 +1,149 @@+# Managed cross-harness workstreams++`ai-memory run` is an opt-in launcher that lets one logical coding session move+between Claude Code, Codex, OpenCode, Pi, and OMP. Direct agent launches keep+their existing ai-memory behavior. There is no global mode toggle and no+`switch` command: using `run` selects the current workstream and transparently+creates or resumes the correct native session for the requested harness.++```bash+cd /path/to/project++ai-memory run claude+# quit Claude Code, then continue the same logical workstream in Codex+ai-memory run codex --yolo+# return to Claude Code later; ai-memory supplies Claude's native --resume+ai-memory run claude --model opus+```++Everything after the harness name is native argv. No `--` separator is needed,+and ai-memory does not maintain a second copy of each harness's option schema.+Wrapper options must come first:++```text+ai-memory run [--workspace NAME] [--project NAME]+ [--workstream NAME | --new NAME] [--executable PATH]+ <claude|codex|opencode|pi|omp> [native arguments...]+```++The default is the most recently selected workstream for the current repository+and worktree, creating one named `default` on first use. `--new NAME` starts an+independent line of work; `--workstream NAME` returns to one. These are optional+branching controls, not harness-switch controls.++## What happens on each run++1. The host client resolves the normal workspace/project scope and a stable+ repository plus worktree fingerprint. It opens a 90-second renewable lease.+ One writer may own a workstream at a time, so two terminals cannot silently+ race its native-session pointers or delivery cursors.+2. The harness adapter passes every native argument through in order and adds a+ native create/resume selector only when the user did not supply one.+3. `AI_MEMORY_RUN_ID` marks lifecycle hooks as managed. SessionStart links the+ actual native session and injects only the portable events that session has+ not seen. Direct launches do not set this variable and continue to use the+ existing single-use handoff path.+4. When the child exits, ai-memory reads the native transcript store without+ modifying it. Visible user/assistant messages, completed tool calls/results,+ compaction summaries, and a non-mutating Git checkpoint enter an append-only+ workstream ledger. Hidden reasoning and unsupported/private records are+ excluded and recorded as extraction-loss annotations.+5. Imports use deterministic event ids, incremental source cursors, immutable+ sanitized JSONL segments, and bounded batches. A retry cannot duplicate+ history. The native process's exit code is preserved.++The next harness receives a bounded recent delta because no agent context window+can safely absorb an unbounded transcript. The complete visible ledger remains+searchable from inside a managed agent process:++```bash+ai-memory workstream-search "scope resolver decision"+ai-memory workstream-search --limit 50 --json "failed migration"+```++`AI_MEMORY_WORKSTREAM_ID` supplies the id automatically inside the child. From+another shell, pass `--workstream-id <uuid>` explicitly. Search results preserve+the source harness, role, event sequence, and content. Historical tool activity+is labelled completed evidence and must never be replayed as a pending call.++## Native adapter behavior++| Harness | Fresh native session | Returning native session | Read-only source |+|---|---|---|---|+| Claude Code | generated `--session-id` | `--resume <id>` | `~/.claude/projects/**/*.jsonl` |+| Codex | native default creation | `resume <id>` | `~/.codex/sessions/**/rollout-*.jsonl` |+| OpenCode | native default creation | `--session <id>` | `~/.local/share/opencode/opencode.db` opened read-only |+| Pi | generated `--session-id` | `--session <id>` | `~/.pi/agent/sessions/**/*.jsonl` |+| OMP | native default creation | `--resume=<id>` | `~/.omp/agent/sessions/**/*.jsonl` |++An explicit native selector such as Claude's `--resume`, OpenCode's `--session`,+or Codex's `resume` wins. ai-memory links the selected native session and resets+an unrelated adapter cursor rather than assuming it belongs to the old session.+Pi and OMP `--session-dir` values are passed through unchanged and used as the+read-only import root. Native store environment overrides are also honored:+`CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `XDG_DATA_HOME`,+`PI_CODING_AGENT_SESSION_DIR`, and `PI_CODING_AGENT_DIR`. The Pi-family adapter+also recognizes a complete `.jsonl.<nonce>.tmp` atomic-write file when a native+process exits before renaming it; incomplete final JSONL records are never+imported. Help, version, and known utility subcommands pass through without+session flags.++## Installation and recovery++Managed runs need current ai-memory lifecycle hooks so SessionStart can receive+the portable delta. Refresh them after upgrading:++```bash+ai-memory install-hooks --agent claude-code --apply+ai-memory install-hooks --agent codex --apply+ai-memory install-hooks --agent opencode --apply+ai-memory install-hooks --agent pi --apply+ai-memory install-hooks --agent omp --apply+```++The Linux/macOS Docker shell wrapper cannot execute a host agent from inside its+helper container. For `run` only, it downloads the matching native release into+`~/.cache/ai-memory/native-runner`, verifies the published SHA-256 checksum, and+executes that host client. Set `AI_MEMORY_NATIVE_BIN=/path/to/ai-memory` to use a+specific native build. Native package, release, and source installs need no+shim. On native Windows, use the published `ai-memory.exe` or a source build.++If a client is killed before final import, its lease expires. A later managed+run starts from the last committed adapter cursor, so already linked native+sessions can import the missing tail without duplicating earlier events. A+server or authentication failure before process launch is fatal; ai-memory does+not silently start an unmanaged agent.++## Privacy and storage boundaries++Managed mode does not write to Claude, Codex, OpenCode, Pi, or OMP private+stores. Adapters read only documented/observed local session formats. Provider+credentials, encrypted content, system/developer prompt records, and hidden+reasoning are not copied. The server sanitizer runs before both the SQLite FTS+ledger and immutable files under+`<data_dir>/raw/workstreams/<workstream-id>/segments/` are written.++The ledger is an operational continuity substrate, not a replacement for the+markdown wiki. Durable decisions, rules, procedures, and project facts still+belong in wiki pages through consolidation or explicit durable writes.++## Manual acceptance++The opt-in acceptance runner exercises wrapper edge cases and then orchestrates+the locally installed Claude, Codex, OpenCode, Pi, and OMP CLIs through one real+workstream:++```bash+scripts/managed-workstream-acceptance.sh+```++It is deliberately separate from CI because it uses local harness credentials+and model calls. Hook configs, native session stores, the ai-memory server, and+the Git fixture are isolated under a temporary directory. Claude, Codex, and+OpenCode receive only copied authentication material; OMP receives a temporary+agent directory with read-consistent credential/model database backups and+copied settings. Native session creation, read-only extraction, cross-harness+injection, and returning resume paths are all exercised. Set+`AI_MEMORY_ACCEPTANCE_HARNESSES="claude codex"` to select+a subset, `AI_MEMORY_ACCEPTANCE_DETERMINISTIC_ONLY=1` to skip model calls, or+`AI_MEMORY_ACCEPTANCE_KEEP=1` to retain all temporary logs and data.diff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex 50879739..4aca26da 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -47,7 +47,7 @@ endpoint. The trade-off:| | What you get | What you don't get ||---|---|---|| **MCP only** | LLM can query the wiki, accept handoffs, run memory_consolidate, and run `memory_auto_improve` learning reviews | No automatic session-end summaries; no auto-handoff at session boundaries |-| **MCP + hooks** | All of the above *plus* every prompt/tool-call captured automatically; handoffs surface at SessionStart with no human prompting **only when the client consumes startup-hook output or an equivalent context-injection result** | Grok and Zero discard SessionStart stdout; ask them to call `memory_handoff_accept` when resuming. |+| **MCP + hooks** | All of the above *plus* bounded sanitized prompt/tool-lifecycle observations captured automatically; handoffs surface at SessionStart with no human prompting **only when the client consumes startup-hook output or an equivalent context-injection result** | Hook observations are not complete native transcripts. Grok and Zero discard SessionStart stdout; ask them to call `memory_handoff_accept` when resuming. |For MCP-only use, you can still cover the session-boundary gap by askingthe LLM to call `memory_handoff_begin` manually before quitting.diff --git a/hooks/_lib.sh b/hooks/_lib.shindex b16129a6..78159a07 100644--- a/hooks/_lib.sh+++ b/hooks/_lib.sh@@ -67,6 +67,27 @@ ai_memory_extract_cwd() {ai_memory_json_unescape_path "$raw"}+# Extract a harness-native session id from the common hook payload spellings.+# Like the cwd fallback above this intentionally handles top-level JSON strings+# only; native `ai-memory hook` uses a real JSON parser.+ai_memory_extract_session_id() {+ payload="${1:-$(cat)}"+ for key in session_id sessionId sessionID session conversationId; do+ rest=${payload#*\"$key\"}+ if [ "$rest" != "$payload" ]; then+ printf '%s' "$rest" \+ | sed -n -E 's/^[[:space:]]*:[[:space:]]*"([^"]*)".*/\1/p' \+ | head -n 1+ return 0+ fi+ done+}++ai_memory_managed_qs() {+ [ -n "${AI_MEMORY_RUN_ID:-}" ] || return 0+ printf '&managed_run=%s' "$(ai_memory_url_encode "$AI_MEMORY_RUN_ID")"+}+# Resolve cwd for agents whose native hook payload omits it. Payload wins,# then Devin's project env var, then the hook process cwd.ai_memory_resolve_cwd() {@@ -142,7 +163,10 @@ ai_memory_repo_root_project() {# as the prior hook events even when no marker file exists.ai_memory_marker_qs() {cwd="$1"- [ -z "$cwd" ] && return 0+ if [ -z "$cwd" ]; then+ ai_memory_managed_qs+ return 0+ fiqs="&cwd=$(ai_memory_url_encode "$cwd")"ws=""pr=""@@ -178,6 +202,7 @@ ai_memory_marker_qs() {# Per-project drop_subagent_captures opt-in: forward to the server, which# interprets truthiness (1/true/...) and scopes the drop to this project.[ -n "$ds" ] && qs="${qs}&drop_subagent=$(ai_memory_url_encode "$ds")"+ qs="${qs}$(ai_memory_managed_qs)"printf '%s' "$qs"}diff --git a/hooks/claude-code/session-start.sh b/hooks/claude-code/session-start.shindex 65de120a..1ec0b3f8 100755--- a/hooks/claude-code/session-start.sh+++ b/hooks/claude-code/session-start.sh@@ -20,6 +20,9 @@ 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")+SESSION_ID=$(ai_memory_extract_session_id "$PAYLOAD")+SESSION_QS=""+[ -n "$SESSION_ID" ] && SESSION_QS="&session_id=$(ai_memory_url_encode "$SESSION_ID")"printf '%s' "$PAYLOAD" \| ai_memory_post_hook "$SERVER/hook?event=session-start&agent=claude-code${QS}" >/dev/null 2>&1 || true@@ -30,7 +33,7 @@ printf '%s' "$PAYLOAD" \# does not start with "{", so Claude Code logs every session start as# "Hook output does not start with {, treating as plain text". JSON# injects the same handoff with a clean debug log; no handoff -> "{}".-HANDOFF=$(ai_memory_get_handoff "$SERVER/handoff?agent=claude-code${QS}" 2>/dev/null || true)+HANDOFF=$(ai_memory_get_handoff "$SERVER/handoff?agent=claude-code${QS}${SESSION_QS}" 2>/dev/null || true)if [ -n "$HANDOFF" ]; thenprintf '{"hookSpecificOutput":{"hookEventName":"SessionStart","additionalContext":%s}}\n' \"$(printf '%s' "$HANDOFF" | ai_memory_json_string)"diff --git a/hooks/codex/session-start.sh b/hooks/codex/session-start.shindex 4f8687e5..37ccb4cc 100755--- a/hooks/codex/session-start.sh+++ b/hooks/codex/session-start.sh@@ -14,8 +14,11 @@ 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")+SESSION_ID=$(ai_memory_extract_session_id "$PAYLOAD")+SESSION_QS=""+[ -n "$SESSION_ID" ] && SESSION_QS="&session_id=$(ai_memory_url_encode "$SESSION_ID")"printf '%s' "$PAYLOAD" \| ai_memory_post_hook "$SERVER/hook?event=session-start&agent=codex${QS}" >/dev/null 2>&1 || true-ai_memory_get_handoff "$SERVER/handoff?agent=codex${QS}" 2>/dev/null || true+ai_memory_get_handoff "$SERVER/handoff?agent=codex${QS}${SESSION_QS}" 2>/dev/null || trueexit 0diff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1index d50a026b..7b6f2bfb 100644--- a/hooks/lib/ai-memory-hook.ps1+++ b/hooks/lib/ai-memory-hook.ps1@@ -189,6 +189,9 @@ function Invoke-AiMemoryHook {$Payload = Read-AiMemoryStdin$Cwd = Resolve-AiMemoryCwd -Payload $Payload -Agent $Agent$QS = Get-AiMemoryMarkerQuery -Cwd $Cwd+ if ($env:AI_MEMORY_RUN_ID) {+ $QS += "&managed_run=$([Uri]::EscapeDataString($env:AI_MEMORY_RUN_ID))"+ }$SessionQS = ""if ($Agent -eq "devin") {$SessionQS = Get-AiMemorySessionIdQuery -Agent $Agent -Event $Event@@ -215,11 +218,26 @@ function Invoke-AiMemoryHook {}if ($FetchHandoff) {+ $NativeSessionQS = ""+ try {+ $ParsedPayload = $Payload | ConvertFrom-Json+ $NativeSessionId = @(+ $ParsedPayload.session_id,+ $ParsedPayload.sessionId,+ $ParsedPayload.sessionID,+ $ParsedPayload.session,+ $ParsedPayload.conversationId+ ) | Where-Object { $_ } | Select-Object -First 1+ if ($NativeSessionId) {+ $NativeSessionQS = "&session_id=$([Uri]::EscapeDataString([string]$NativeSessionId))"+ }+ } catch {+ }try {$Response = Invoke-WebRequest `-UseBasicParsing `-TimeoutSec 2 `- -Uri "$Server/handoff?agent=$Agent$QS" `+ -Uri "$Server/handoff?agent=$Agent$QS$NativeSessionQS" `-Headers $Headersif ($null -ne $Response -and $Response.Content) {if ($AntigravityPreInvocationOutput) {diff --git a/hooks/opencode/session-start.sh b/hooks/opencode/session-start.shindex cf9af906..98420f98 100755--- a/hooks/opencode/session-start.sh+++ b/hooks/opencode/session-start.sh@@ -14,8 +14,11 @@ 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")+SESSION_ID=$(ai_memory_extract_session_id "$PAYLOAD")+SESSION_QS=""+[ -n "$SESSION_ID" ] && SESSION_QS="&session_id=$(ai_memory_url_encode "$SESSION_ID")"printf '%s' "$PAYLOAD" \| ai_memory_post_hook "$SERVER/hook?event=session-start&agent=open-code${QS}" >/dev/null 2>&1 || true-ai_memory_get_handoff "$SERVER/handoff?agent=open-code${QS}" 2>/dev/null || true+ai_memory_get_handoff "$SERVER/handoff?agent=open-code${QS}${SESSION_QS}" 2>/dev/null || trueexit 0diff --git a/scripts/managed-workstream-acceptance.sh b/scripts/managed-workstream-acceptance.shnew file mode 100755index 00000000..8c693993--- /dev/null+++ b/scripts/managed-workstream-acceptance.sh@@ -0,0 +1,406 @@+#!/usr/bin/env bash+# Manual, opt-in acceptance test for managed cross-harness workstreams.+# This is intentionally not called by CI: the real-harness phase uses the+# operator's installed CLIs, credentials, model defaults, and native stores.+set -euo pipefail++ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)+BIN=${AI_MEMORY_ACCEPTANCE_BIN:-"$ROOT/target/debug/ai-memory"}+KEEP=${AI_MEMORY_ACCEPTANCE_KEEP:-0}+DETERMINISTIC_ONLY=${AI_MEMORY_ACCEPTANCE_DETERMINISTIC_ONLY:-0}+HARNESS_WORDS=${AI_MEMORY_ACCEPTANCE_HARNESSES:-"claude codex opencode pi omp"}+TMP=$(mktemp -d "${TMPDIR:-/tmp}/ai-memory-workstream-acceptance.XXXXXX")+DATA="$TMP/data"+REPO="$TMP/repo"+CONFIG="$TMP/config"+LOGS="$TMP/logs"+SERVER_PID=""++cleanup() {+ local code=$?+ if [ -n "$SERVER_PID" ]; then+ kill "$SERVER_PID" 2>/dev/null || true+ wait "$SERVER_PID" 2>/dev/null || true+ fi+ if [ "$KEEP" = 1 ] || [ "$code" -ne 0 ]; then+ printf 'acceptance artifacts retained at %s\n' "$TMP" >&2+ else+ rm -rf "$TMP"+ fi+}+trap cleanup EXIT INT TERM++for command in cargo curl diff git jq sqlite3; do+ command -v "$command" >/dev/null 2>&1 || {+ printf 'missing required command: %s\n' "$command" >&2+ exit 1+ }+done++if [ ! -x "$BIN" ] || [ "${AI_MEMORY_ACCEPTANCE_REBUILD:-1}" = 1 ]; then+ (cd "$ROOT" && TAILWIND_SKIP=1 cargo build -p ai-memory-cli)+fi++mkdir -p "$DATA" "$REPO" "$CONFIG" "$LOGS"+git -C "$REPO" init -q+git -C "$REPO" config user.name "ai-memory acceptance"+git -C "$REPO" config user.email "acceptance@localhost"+printf '# Managed workstream acceptance\n' >"$REPO/README.md"+git -C "$REPO" add README.md+git -C "$REPO" commit -qm "acceptance fixture"++TOKEN="managed-acceptance-$(date +%s)-$$"+PORT=${AI_MEMORY_ACCEPTANCE_PORT:-$((52000 + ($$ % 10000)))}+for _ in $(seq 1 50); do+ if ! curl -sS --max-time 0.1 "http://127.0.0.1:$PORT/" >/dev/null 2>&1; then+ break+ fi+ PORT=$((PORT + 1))+done+URL="http://127.0.0.1:$PORT"+export AI_MEMORY_SERVER_URL="$URL"+export AI_MEMORY_AUTH_TOKEN="$TOKEN"+export AI_MEMORY_NO_VERSION_CHECK=1++"$BIN" --data-dir "$DATA" serve \+ --transport http \+ --bind "127.0.0.1:$PORT" \+ --no-watcher >"$LOGS/server.log" 2>&1 &+SERVER_PID=$!+for _ in $(seq 1 100); do+ status=$(curl -sS --max-time 0.2 -o /dev/null -w '%{http_code}' \+ -H "Authorization: Bearer $TOKEN" \+ "$URL/workstream/not-a-uuid/events" 2>/dev/null || true)+ [ "$status" = 400 ] && break+ if ! kill -0 "$SERVER_PID" 2>/dev/null; then+ printf 'ai-memory server exited during startup\n' >&2+ tail -80 "$LOGS/server.log" >&2+ exit 1+ fi+ sleep 0.1+done+[ "${status:-}" = 400 ] || {+ printf 'ai-memory server did not become ready at %s\n' "$URL" >&2+ tail -80 "$LOGS/server.log" >&2+ exit 1+}++FAKE="$TMP/fake-harness.sh"+cat >"$FAKE" <<'EOF'+#!/usr/bin/env bash+set -euo pipefail+case "${AI_MEMORY_ACCEPTANCE_FAKE_MODE:-argv}" in+ argv)+ printf '%s\n' "$@" >"$AI_MEMORY_ACCEPTANCE_ARGV_LOG"+ ;;+ exit)+ exit "${AI_MEMORY_ACCEPTANCE_EXIT_CODE:-23}"+ ;;+ lease)+ : >"$AI_MEMORY_ACCEPTANCE_STARTED"+ sleep "${AI_MEMORY_ACCEPTANCE_SLEEP:-3}"+ ;;+esac+EOF+chmod +x "$FAKE"++printf 'running deterministic wrapper edge checks\n'+(+ cd "$REPO"+ AI_MEMORY_ACCEPTANCE_FAKE_MODE=argv \+ AI_MEMORY_ACCEPTANCE_ARGV_LOG="$TMP/argv.log" \+ "$BIN" --data-dir "$DATA" run --new edge-argv --executable "$FAKE" \+ codex --yolo -m gpt-5 "prompt words" >"$LOGS/edge-argv.log" 2>&1+)+diff -u <(printf '%s\n' --yolo -m gpt-5 "prompt words") "$TMP/argv.log"++set +e+(+ cd "$REPO"+ AI_MEMORY_ACCEPTANCE_FAKE_MODE=exit AI_MEMORY_ACCEPTANCE_EXIT_CODE=23 \+ "$BIN" --data-dir "$DATA" run --new edge-exit --executable "$FAKE" \+ codex >"$LOGS/edge-exit.log" 2>&1+)+exit_code=$?+set -e+[ "$exit_code" -eq 23 ] || {+ printf 'managed child exit code was %s, expected 23\n' "$exit_code" >&2+ exit 1+}++(+ cd "$REPO"+ AI_MEMORY_ACCEPTANCE_FAKE_MODE=lease \+ AI_MEMORY_ACCEPTANCE_STARTED="$TMP/lease-started" \+ "$BIN" --data-dir "$DATA" run --new edge-lease --executable "$FAKE" \+ codex >"$LOGS/edge-lease-owner.log" 2>&1+) &+lease_pid=$!+for _ in $(seq 1 100); do+ [ -f "$TMP/lease-started" ] && break+ sleep 0.05+done+[ -f "$TMP/lease-started" ] || {+ printf 'lease owner did not start\n' >&2+ exit 1+}+set +e+(+ cd "$REPO"+ AI_MEMORY_ACCEPTANCE_FAKE_MODE=argv \+ AI_MEMORY_ACCEPTANCE_ARGV_LOG="$TMP/lease-contender-argv.log" \+ "$BIN" --data-dir "$DATA" run --workstream edge-lease --executable "$FAKE" \+ codex >"$LOGS/edge-lease-contender.log" 2>&1+)+lease_code=$?+set -e+[ "$lease_code" -ne 0 ] || {+ printf 'a concurrent managed writer unexpectedly acquired the lease\n' >&2+ exit 1+}+wait "$lease_pid"++if [ "$DETERMINISTIC_ONLY" = 1 ]; then+ printf 'deterministic managed-workstream acceptance passed\n'+ exit 0+fi++read -r -a requested_harnesses <<<"$HARNESS_WORDS"+harnesses=()+for harness in "${requested_harnesses[@]}"; do+ if command -v "$harness" >/dev/null 2>&1; then+ harnesses+=("$harness")+ else+ printf 'skipping unavailable harness: %s\n' "$harness" >&2+ fi+done+[ "${#harnesses[@]}" -ge 2 ] || {+ printf 'real acceptance needs at least two installed harnesses\n' >&2+ exit 1+}++CLAUDE_CONFIG_HOME="$CONFIG/claude"+CLAUDE_SETTINGS="$CLAUDE_CONFIG_HOME/settings.json"+CODEX_ACCEPTANCE_HOME="$CONFIG/codex-home"+CODEX_HOOKS="$CODEX_ACCEPTANCE_HOME/.codex/hooks.json"+OPENCODE_CONFIG_HOME="$CONFIG/opencode-xdg"+OPENCODE_PLUGIN="$OPENCODE_CONFIG_HOME/opencode/plugins/ai-memory.ts"+OPENCODE_DATA_HOME="$CONFIG/opencode-xdg-data"+PI_EXTENSION="$CONFIG/pi/ai-memory.ts"+OMP_EXTENSION="$CONFIG/omp/ai-memory.ts"+OMP_AGENT_DIR="$CONFIG/omp/agent"+mkdir -p "$(dirname "$CLAUDE_SETTINGS")" "$(dirname "$CODEX_HOOKS")" \+ "$(dirname "$OPENCODE_PLUGIN")" "$(dirname "$PI_EXTENSION")" \+ "$(dirname "$OMP_EXTENSION")" "$OMP_AGENT_DIR" "$OPENCODE_DATA_HOME/opencode"++# Redirect native transcript stores into the fixture while reusing only the+# minimum authentication material required for real model calls.+if [ -f "$HOME/.claude/.credentials.json" ]; then+ cp "$HOME/.claude/.credentials.json" "$CLAUDE_CONFIG_HOME/.credentials.json"+fi+if [ -f "$HOME/.local/share/opencode/auth.json" ]; then+ cp "$HOME/.local/share/opencode/auth.json" "$OPENCODE_DATA_HOME/opencode/auth.json"+fi++# Codex only discovers hooks below its home. Use a temporary home so the+# acceptance config cannot modify or depend on the operator's trusted hooks.+if [ -f "$HOME/.codex/auth.json" ]; then+ cp "$HOME/.codex/auth.json" "$CODEX_ACCEPTANCE_HOME/.codex/auth.json"+fi++# OMP's installed release drops explicit extension paths when+# --no-extensions is set. Isolate discovery with a temporary agent directory+# and copy only settings plus consistent credential/model database backups.+for database in agent.db models.db; do+ if [ -f "$HOME/.omp/agent/$database" ]; then+ sqlite3 "$HOME/.omp/agent/$database" ".backup '$OMP_AGENT_DIR/$database'"+ fi+done+for config_name in auth.json config.yml models-store.json settings.json; do+ if [ -f "$HOME/.omp/agent/$config_name" ]; then+ cp "$HOME/.omp/agent/$config_name" "$OMP_AGENT_DIR/$config_name"+ fi+done++# Preserve OpenCode's provider/model preferences while loading only the+# acceptance plugin from the isolated XDG config root.+for config_name in opencode.json opencode.jsonc tui.json; do+ if [ -f "$HOME/.config/opencode/$config_name" ]; then+ cp "$HOME/.config/opencode/$config_name" \+ "$OPENCODE_CONFIG_HOME/opencode/$config_name"+ fi+done++install_hook() {+ local agent=$1+ local target=$2+ local -a command=(+ "$BIN" --data-dir "$DATA" install-hooks --apply+ --agent "$agent" --server-url "$URL" --auth-token "$TOKEN"+ --config-file "$target"+ )+ case "$agent" in+ claude-code | codex)+ command+=(--hooks-dir "$ROOT/hooks")+ ;;+ esac+ XDG_DATA_HOME="$TMP/xdg-data" "${command[@]}" \+ >"$LOGS/install-$agent.log" 2>&1+}++install_hook claude-code "$CLAUDE_SETTINGS"+install_hook codex "$CODEX_HOOKS"+install_hook opencode "$OPENCODE_PLUGIN"+install_hook pi "$PI_EXTENSION"+install_hook omp "$OMP_EXTENSION"++uuid_from_hex() {+ local hex=$1+ printf '%s-%s-%s-%s-%s\n' \+ "${hex:0:8}" "${hex:8:4}" "${hex:12:4}" "${hex:16:4}" "${hex:20:12}"+}++workstream_id() {+ local name=$1+ local hex+ hex=$(sqlite3 "$DATA/db/memory.sqlite" \+ "SELECT lower(hex(id)) FROM workstreams WHERE name = '$name' ORDER BY selected_at DESC LIMIT 1;")+ [ "${#hex}" -eq 32 ] || return 1+ uuid_from_hex "$hex"+}++agent_wire_name() {+ case "$1" in+ claude) printf 'claude-code\n' ;;+ opencode) printf 'open-code\n' ;;+ *) printf '%s\n' "$1" ;;+ esac+}++uppercase() {+ printf '%s' "$1" | tr '[:lower:]' '[:upper:]'+}++run_harness() {+ local harness=$1+ local current=$2+ local previous=$3+ local first_run=$4+ local log="$LOGS/real-$harness-$current.log"+ local prompt+ local expected_agent+ local -a wrapper_args native_args+ expected_agent=$(agent_wire_name "$harness")+ if [ -z "$previous" ]; then+ prompt="Do not use tools. Reply with exactly: $current"+ else+ prompt="Do not use tools. From the injected ai-memory managed-workstream context, identify the most recent assistant sentinel beginning with AMWS-. Reply on one line with that prior sentinel, then $current."+ fi+ if [ "$first_run" = 1 ]; then+ wrapper_args=(--new "$WORKSTREAM_NAME")+ else+ wrapper_args=(--workstream "$WORKSTREAM_NAME")+ fi+ case "$harness" in+ claude)+ native_args=(-p --settings "$CLAUDE_SETTINGS" --model "${AI_MEMORY_ACCEPTANCE_CLAUDE_MODEL:-haiku}" --permission-mode plan "$prompt")+ ;;+ codex)+ native_args=(exec -c 'sandbox_mode="read-only"' --dangerously-bypass-hook-trust --json "$prompt")+ if [ -n "${AI_MEMORY_ACCEPTANCE_CODEX_MODEL:-}" ]; then+ native_args=(exec -c 'sandbox_mode="read-only"' --dangerously-bypass-hook-trust --json --model "$AI_MEMORY_ACCEPTANCE_CODEX_MODEL" "$prompt")+ fi+ ;;+ opencode)+ native_args=(run --format json --auto "$prompt")+ [ -z "${AI_MEMORY_ACCEPTANCE_OPENCODE_MODEL:-}" ] || native_args=(run --format json --auto --model "$AI_MEMORY_ACCEPTANCE_OPENCODE_MODEL" "$prompt")+ ;;+ pi)+ native_args=(-p --no-tools --no-extensions --extension "$PI_EXTENSION" --session-dir "$CONFIG/pi/sessions" "$prompt")+ [ -z "${AI_MEMORY_ACCEPTANCE_PI_MODEL:-}" ] || native_args=(-p --no-tools --no-extensions --extension "$PI_EXTENSION" --session-dir "$CONFIG/pi/sessions" --model "$AI_MEMORY_ACCEPTANCE_PI_MODEL" "$prompt")+ ;;+ omp)+ native_args=(-p --no-tools --extension "$OMP_EXTENSION" --session-dir "$CONFIG/omp/sessions" "$prompt")+ [ -z "${AI_MEMORY_ACCEPTANCE_OMP_MODEL:-}" ] || native_args=(-p --no-tools --extension "$OMP_EXTENSION" --session-dir "$CONFIG/omp/sessions" --model "$AI_MEMORY_ACCEPTANCE_OMP_MODEL" "$prompt")+ ;;+ *)+ printf 'unsupported acceptance harness: %s\n' "$harness" >&2+ return 1+ ;;+ esac++ printf 'running real harness: %s\n' "$harness" >&2+ if [ "$harness" = claude ]; then+ (cd "$REPO" && CLAUDE_CONFIG_DIR="$CLAUDE_CONFIG_HOME" \+ "$BIN" --data-dir "$DATA" run "${wrapper_args[@]}" "$harness" "${native_args[@]}") \+ >"$log" 2>&1+ elif [ "$harness" = codex ]; then+ (cd "$REPO" && HOME="$CODEX_ACCEPTANCE_HOME" \+ CODEX_HOME="$CODEX_ACCEPTANCE_HOME/.codex" \+ "$BIN" --data-dir "$DATA" run "${wrapper_args[@]}" "$harness" "${native_args[@]}") \+ >"$log" 2>&1+ elif [ "$harness" = opencode ]; then+ (cd "$REPO" && XDG_CONFIG_HOME="$OPENCODE_CONFIG_HOME" \+ XDG_DATA_HOME="$OPENCODE_DATA_HOME" \+ "$BIN" --data-dir "$DATA" run "${wrapper_args[@]}" "$harness" "${native_args[@]}") \+ >"$log" 2>&1+ elif [ "$harness" = omp ]; then+ (cd "$REPO" && PI_CODING_AGENT_DIR="$OMP_AGENT_DIR" \+ "$BIN" --data-dir "$DATA" run "${wrapper_args[@]}" "$harness" "${native_args[@]}") \+ >"$log" 2>&1+ else+ (cd "$REPO" && "$BIN" --data-dir "$DATA" run \+ "${wrapper_args[@]}" "$harness" "${native_args[@]}") >"$log" 2>&1+ fi++ local id results event native_id+ id=$(workstream_id "$WORKSTREAM_NAME")+ results=$("$BIN" --data-dir "$DATA" workstream-search \+ --workstream-id "$id" --limit 100 --json "$current")+ event=$(jq -c --arg agent "$expected_agent" --arg current "$current" \+ '[.[] | select(.agent == $agent and .role == "assistant" and (.content | contains($current)))] | last // empty' \+ <<<"$results")+ [ -n "$event" ] || {+ printf '%s did not persist an assistant event containing %s\n' "$harness" "$current" >&2+ tail -120 "$log" >&2+ return 1+ }+ if [ -n "$previous" ] && ! jq -e --arg previous "$previous" \+ '.content | contains($previous)' <<<"$event" >/dev/null; then+ printf '%s did not demonstrate receipt of prior sentinel %s\n' "$harness" "$previous" >&2+ jq -r '.content' <<<"$event" >&2+ return 1+ fi+ native_id=$(jq -r '.native_session_id' <<<"$event")+ printf '%s\n' "$native_id"+}++WORKSTREAM_NAME="native-acceptance-$(date +%s)-$$"+RUN_TAG="$(date +%s)-$$"+previous=""+first_harness=${harnesses[0]}+first_native=""+index=0+for harness in "${harnesses[@]}"; do+ current="AMWS-$RUN_TAG-$(uppercase "$harness")"+ first_run=0+ [ "$index" -ne 0 ] || first_run=1+ native_id=$(run_harness "$harness" "$current" "$previous" "$first_run")+ if [ "$index" -eq 0 ]; then+ first_native=$native_id+ fi+ previous=$current+ index=$((index + 1))+done++return_sentinel="AMWS-$RUN_TAG-$(uppercase "$first_harness")-RETURN"+returned_native=$(run_harness "$first_harness" "$return_sentinel" "$previous" 0)+[ "$returned_native" = "$first_native" ] || {+ printf '%s resumed native session %s, expected %s\n' \+ "$first_harness" "$returned_native" "$first_native" >&2+ exit 1+}++printf 'real managed-workstream acceptance passed: %s\n' "${harnesses[*]}"+printf 'returned to %s native session %s\n' "$first_harness" "$first_native"+printf 'native harness session stores and resume paths were exercised\n'