Skip to content

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

Rust

feat(swival): add first-party Swival CLI MCP and lifecycle hooks (#385)

Matheus C. França5af9a15d4346
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 75fd2f49..c99a65b8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,35 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+- Added first-party Swival CLI support. `AgentKind::Swival` persists sessions
+ under the `swival` wire value (new V48 migration) and never claims startup
+ handoff injection because Swival captures lifecycle-hook stdout without
+ putting it into the model context. `install-hooks --agent swival` renders
+ / merges the single `lifecycle_command` (an `env AI_MEMORY_HOOK_URL=…`
+ prefix plus the shim path, which survives Swival's no-shell
+ `shlex.split` + `subprocess` exec) into `~/.config/swival/config.toml` or a
+ project `swival.toml`; the shim maps `startup`/`exit <base_dir>` positional
+ args to `session-start`/`session-end` hook events and recovers project
+ scope from the cwd marker. `install-mcp --client swival` merges the
+ documented `.swival/mcp.json` HTTP entry, `setup-agent --agent swival`
+ emits the hook command, and `uninstall` strips both. Handoffs are recovered
+ via the MCP `memory_handoff_accept` tool because Swival discards hook
+ stdout ([#385]).
+- Added `ai-memory run swival` managed workstream support. The new
+ `ManagedHarness::Swival` adapter discovers, lists, and checks native
+ sessions against the project-scoped `.swival/HISTORY.md` rollup (or the
+ `--cache-dir` store) under the fixed native id `HISTORY`, injects no
+ resume selector (Swival has none and resumes implicitly by cwd), maps
+ `--yolo` to Swival's own `--files all --commands all`, and passes utility
+ subcommands (`--init-config`, `--logout`, `--list-profiles`, `--version`,
+ `skills`, `--serve`, `--acp`) through untouched. HISTORY.md is an
+ undecodable rolling rollup, so the visible-event ledger comes from
+ lifecycle-hook capture and transcript export fails with an explanatory
+ message (mirroring Antigravity). The server's managed-run allowlist
+ accepts `AgentKind::Swival` explicitly but keeps Swival out of the
+ no-argument automatic pool ([#385]).
+
## [1.25.0] - 2026-08-07
### Added
diff --git a/README.md b/README.md
index ded7c015..8d5a5b48 100644
--- a/README.md
+++ b/README.md
@@ -32,11 +32,12 @@
| 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. |
| Crush | Managed-only | `ai-memory run crush` resumes its project-local session database and supplies portable context through a temporary supported global-context file; no lifecycle-hook installer is provided. |
-| Managed workstreams | Opt-in | `ai-memory run` provides transparent cross-harness continuity for Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, Command Code, both incompatible Kiro CLI engines, OMP, Grok Build CLI, and Antigravity CLI. Direct launches remain unchanged. See [`docs/managed-workstreams.md`](docs/managed-workstreams.md). |
+| Managed workstreams | Opt-in | `ai-memory run` provides transparent cross-harness continuity for Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, Command Code, both incompatible Kiro CLI engines, OMP, Grok Build CLI, Antigravity CLI, and Swival CLI. 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). Only `PreInvocation` with `invocationNum = 0` maps to SessionStart; later model calls cannot consume a next-session handoff. No automatic true session-end hook, so run `ai-memory finalize-session --agent antigravity-cli` after the final turn when you need a summary, handoff, and opt-in SessionEnd consolidation. `ai-memory run antigravity` (aliases `antigravity-cli`, `agy`) adds managed workstream resume via `--conversation`; conversation text is not decoded, so the ledger for this harness comes from hook capture. |
| Grok Build CLI | Supported | MCP config (`install-mcp --client grok` → `$GROK_HOME/config.toml`, default `~/.grok/config.toml`) + lifecycle hooks (`install-hooks --agent grok` → `$GROK_HOME/hooks/ai-memory.json`, default `~/.grok/hooks/ai-memory.json`, Grok-specific hook bundle). Capture works; no hook handoff injection — Grok ignores `SessionStart` stdout, so recover handoffs via MCP `memory_handoff_accept`. `ai-memory run grok` adds managed workstream resume with the context packet delivered natively through `--rules`. Skills root: `.grok/skills` / `$GROK_HOME/skills` (default `~/.grok/skills`). |
+| Swival CLI | Supported | MCP config (`install-mcp --client swival` → project `.swival/mcp.json`, HTTP entry) + lifecycle hooks (`install-hooks --agent swival` → single `lifecycle_command` in `~/.config/swival/config.toml` or a project `swival.toml`; the shim maps Swival's positional `startup`/`exit <base_dir>` hook args to `session-start`/`session-end` events). Capture works; no handoff injection — Swival captures hook stdout but never puts it in the model context, so recover handoffs via MCP `memory_handoff_accept`. `ai-memory run swival` adds managed workstream resume via `--cache-dir` (default `.swival/`); HISTORY.md is not decoded, so the ledger for this harness comes from hook capture. |
| Zero | Supported | `install-mcp --client zero` (native HTTP + bearer in `~/.config/zero/config.json`) + lifecycle hooks via `install-hooks --agent zero --apply` (exec-form native commands in `~/.config/zero/hooks.json`, JSON payload on stdin, no shell). Capture works incl. specialist (subagent) events; no handoff injection — Zero discards `sessionStart` stdout, so recover handoffs via MCP `memory_handoff_accept`. |
| Kimi Code | Supported | MCP config (`url` entry in `~/.kimi-code/mcp.json`) + lifecycle hooks (`[[hooks]]` in `~/.kimi-code/config.toml`, 10 events including subagent start/stop and `PostToolUseFailure` for tool-failure capture); both paths honor `$KIMI_CODE_HOME`. Handoffs inject via `UserPromptSubmit` stdout (Kimi Code discards `SessionStart` hook stdout); `ai-memory run kimi` adds managed workstream resume. |
| Kiro CLI | Supported | MCP config uses `install-mcp --client kiro-cli` (alias `kiro`) and Kiro's Bedrock-compatible schema flavor. `install-hooks --agent kiro-cli` merges v2 hooks into existing agent configs; the explicit `--agent kiro-cli-v3` target writes the incompatible standalone v3 registration. Both preserve unrelated entries, honor `$KIRO_HOME`, enforce capture exclusions, and inject pending handoffs at session start. Kiro has no true SessionEnd hook; use `ai-memory finalize-session --agent kiro-cli`, with `--session-id <uuid>` for concurrent sessions. `ai-memory run kiro` manages v2; add `--v3`, `--mode`, or `--agent-engine v3` for version-safe v3 resume. |
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index e80ce805..e06696d8 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -214,7 +214,7 @@ pub struct RunArgs {
}
/// Harnesses supported by managed workstreams.
-#[derive(Debug, Clone, Copy, clap::ValueEnum)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum RunHarnessChoice {
/// Anthropic Claude Code (`claude`).
#[value(alias = "claude-code")]
@@ -251,6 +251,11 @@ pub enum RunHarnessChoice {
/// Google Antigravity CLI (`agy`).
#[value(name = "antigravity", alias = "antigravity-cli", alias = "agy")]
Antigravity,
+ /// Swival CLI (local-first Python coding agent). Sessions resume
+ /// implicitly from the project `.swival/` store and the visible-event
+ /// ledger comes from lifecycle-hook capture, so `ai-memory run swival`
+ /// launches `swival` with its native arguments passed through.
+ Swival,
}
/// Arguments for `show`.
@@ -1034,6 +1039,13 @@ pub enum AgentChoice {
/// `~/.commandcode/settings.json`.
#[value(alias = "commandcode", alias = "cmdc", alias = "cmd")]
CommandCode,
+ /// Swival CLI (local-first Python coding agent) — lifecycle hooks via
+ /// `lifecycle_command` in `swival.toml` (project) or
+ /// `~/.config/swival/config.toml` (global). NOTE: Swival captures hook
+ /// stdout but never injects it into the model context, so capture works
+ /// but handoff injection does not — recover the prior session's handoff
+ /// via the MCP `memory_handoff_accept` tool.
+ Swival,
}
impl AgentChoice {
@@ -1061,6 +1073,7 @@ impl AgentChoice {
Self::KimiCode => AgentKind::KimiCode,
Self::KiroCli | Self::KiroCliV3 => AgentKind::KiroCli,
Self::CommandCode => AgentKind::CommandCode,
+ Self::Swival => AgentKind::Swival,
}
}
@@ -1171,6 +1184,14 @@ pub enum McpClient {
/// Command Code CLI — `~/.commandcode/mcp.json`.
#[value(alias = "commandcode", alias = "cmdc", alias = "cmd")]
CommandCode,
+ /// Swival CLI — `.swival/mcp.json` in the project root (standard
+ /// `mcpServers` map) or a `[mcp_servers.<name>]` table in
+ /// `swival.toml` / `~/.config/swival/config.toml`. HTTP transport
+ /// against ai-memory's `/mcp` endpoint. Pair with
+ /// `install-hooks --agent swival` for lifecycle capture; Swival
+ /// captures hook stdout but never injects it, so handoffs are
+ /// recovered via MCP `memory_handoff_accept`.
+ Swival,
/// VS Code GitHub Copilot (agent mode) — per-workspace
/// `.vscode/mcp.json`. Copilot's agent mode reads MCP servers
/// from VS Code's own MCP framework (top-level `servers` key),
@@ -2294,6 +2315,48 @@ mod tests {
}
}
+ #[test]
+ fn swival_mcp_and_hook_agents_parse() {
+ let mcp = Cli::try_parse_from([
+ "ai-memory",
+ "install-mcp",
+ "--client",
+ "swival",
+ "--server-url",
+ "http://memory.example:49374",
+ ])
+ .unwrap_or_else(|error| panic!("failed to parse MCP client swival: {error}"));
+ let Command::InstallMcp(args) = mcp.command else {
+ panic!("expected install-mcp for swival");
+ };
+ assert_eq!(args.client, McpClient::Swival);
+
+ let hooks = Cli::try_parse_from([
+ "ai-memory",
+ "install-hooks",
+ "--agent",
+ "swival",
+ "--server-url",
+ "http://memory.example:49374",
+ ])
+ .unwrap_or_else(|error| panic!("failed to parse hook agent swival: {error}"));
+ let Command::InstallHooks(args) = hooks.command else {
+ panic!("expected install-hooks for swival");
+ };
+ assert_eq!(args.agent, AgentChoice::Swival);
+ assert_eq!(args.agent.kind(), ai_memory_core::AgentKind::Swival);
+ }
+
+ #[test]
+ fn run_swival_harness_parses() {
+ let cli = Cli::try_parse_from(["ai-memory", "run", "swival", "--yolo", "refactor auth"])
+ .unwrap_or_else(|error| panic!("failed to parse run swival: {error}"));
+ let Command::Run(args) = cli.command else {
+ panic!("expected run for swival");
+ };
+ assert_eq!(args.harness, Some(RunHarnessChoice::Swival));
+ }
+
#[test]
fn install_hooks_project_strategy_repo_root_parses() {
let cli = Cli::try_parse_from([
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index 332d0d0b..445504a5 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -30,8 +30,9 @@ use crate::commands::render_shared::{
build_antigravity_payload_with_data_dir, build_claude_code_payload_with_data_dir,
build_devin_payload_with_data_dir, build_grok_payload_with_data_dir,
build_kiro_cli_v2_hooks_value, build_kiro_cli_v3_hooks_value, build_profile_payload_for_agent,
- hook_script_for_claude_code, hook_script_for_current_platform, kimi_code_hook_commands,
- local_hook_policy_v1_supported, ts_capture_policy_v1, ts_string_literal,
+ build_swival_lifecycle_command, hook_script_for_claude_code, hook_script_for_current_platform,
+ kimi_code_hook_commands, local_hook_policy_v1_supported, println_swival_handoff_note,
+ ts_capture_policy_v1, ts_string_literal,
};
use crate::config::{Config, DEFAULT_SERVER_URL};
@@ -358,6 +359,7 @@ pub fn run(config: &Config, mut args: InstallHooksArgs) -> Result<()> {
let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
apply_to_kiro_cli_v3_hooks(&hooks_dir, &server_url, auth, &config.data_dir, &args)
}
+ AgentChoice::Swival => apply_to_swival_config(&server_url, auth, &args),
};
}
let strategy = args.project_strategy.and_then(ProjectStrategyArg::baked);
@@ -461,6 +463,7 @@ pub fn run(config: &Config, mut args: InstallHooksArgs) -> Result<()> {
let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
render_kiro_cli_v3(&hooks_dir, &server_url, auth, &config.data_dir, strategy)
}
+ AgentChoice::Swival => render_swival(&server_url, auth, strategy, &args),
}
}
@@ -517,6 +520,7 @@ fn existing_agent_config(args: &InstallHooksArgs) -> Option<String> {
AgentChoice::KimiCode => kimi_code_config_path().ok()?,
AgentChoice::KiroCli => return None,
AgentChoice::KiroCliV3 => kiro_cli_v3_hooks_path().ok()?,
+ AgentChoice::Swival => swival_config_path(args.config_file.as_deref()).ok()?,
}
};
std::fs::read_to_string(path).ok()
@@ -798,6 +802,11 @@ fn infer_installed_mcp_config(agent: AgentChoice) -> Result<Option<InferredMcpCo
"url",
)),
McpClient::ClaudeDesktop => Ok(None),
+ McpClient::Swival => Ok(infer_json_mcp_config(
+ &content,
+ &["mcpServers", "ai-memory"],
+ "url",
+ )),
// MCP-only client: no AgentChoice counterpart routes here.
// Reachable only if a future install_hooks flow targets VS
// Code Copilot directly.
@@ -865,6 +874,7 @@ fn mcp_client_for_agent(agent: AgentChoice) -> Option<McpClient> {
// mcp.json the installer can scrape.
AgentChoice::Pi => None,
AgentChoice::KiroCli | AgentChoice::KiroCliV3 => Some(McpClient::KiroCli),
+ AgentChoice::Swival => Some(McpClient::Swival),
}
}
@@ -4053,6 +4063,104 @@ fn render_zero(
Ok(())
}
+/// `~/.config/swival/config.toml` — Swival's user-level config (issue #385).
+/// Swival merges CLI args over the project `swival.toml` over the global
+/// config, so the global file is the safe default target and a project
+/// `swival.toml` can be targeted with `--config-file`.
+pub(crate) fn swival_config_path(config_file: Option<&Path>) -> anyhow::Result<std::path::PathBuf> {
+ match config_file {
+ Some(p) => Ok(p.to_path_buf()),
+ None => Ok(home_dir()
+ .context("could not locate $HOME for ~/.config/swival/config.toml")?
+ .join(".config")
+ .join("swival")
+ .join("config.toml")),
+ }
+}
+
+/// Print Swival's hook config as a TOML merge (dry-run counterpart of
+/// [`apply_to_swival_config`]).
+fn render_swival(
+ server_url: &str,
+ auth_token: Option<&str>,
+ project_strategy: Option<&str>,
+ args: &InstallHooksArgs,
+) -> Result<()> {
+ let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
+ let script = hooks_dir.join("lifecycle.sh");
+ if !script.exists() {
+ eprintln!(
+ "# warning: {} not present on this filesystem. \
+ If this command is running inside docker against a \
+ host path, you can ignore this; otherwise extract \
+ the scripts first with `ai-memory setup-agent`.",
+ script.display()
+ );
+ }
+ let config_path = swival_config_path(args.config_file.as_deref())?;
+ let command = build_swival_lifecycle_command(&script, server_url, auth_token, project_strategy);
+ println!(
+ "# Swival hook config — merge into {}",
+ config_path.display()
+ );
+ println!("# (a project `swival.toml` overrides this global file;");
+ println!("# pass --config-file to target one explicitly), or re-run");
+ println!("# with --apply to merge it in place.");
+ println!("# Hook script: {}", script.display());
+ println!("# AI-memory server URL: {server_url}");
+ if auth_token.is_some() {
+ println!("# Auth: AI_MEMORY_AUTH_TOKEN embedded in lifecycle_command below.");
+ println!(
+ "# Treat {} as sensitive (chmod 600).",
+ config_path.display()
+ );
+ }
+ println_swival_handoff_note();
+ println!();
+ println!("lifecycle_command = {}", toml_edit::value(command));
+ Ok(())
+}
+
+/// Merge ai-memory's lifecycle hook into Swival's config TOML (issue #385).
+/// Swival has exactly one hook entry — `lifecycle_command` — so this is a
+/// plain key set (no reserved-name ownership dance); other keys in the file
+/// survive untouched.
+fn apply_to_swival_config(
+ server_url: &str,
+ auth_token: Option<&str>,
+ args: &InstallHooksArgs,
+) -> Result<()> {
+ let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
+ let staged = stage_hook_scripts(&hooks_dir, "swival")?;
+ let command_dir = staged_command_dir(&staged, "swival");
+ let strategy = args.project_strategy.and_then(ProjectStrategyArg::baked);
+ let command = build_swival_lifecycle_command(
+ &command_dir.join("lifecycle.sh"),
+ server_url,
+ auth_token,
+ strategy,
+ );
+ let path = swival_config_path(args.config_file.as_deref())?;
+ let outcome = apply_atomic(&path, |existing| {
+ mutate_toml(existing, |doc| {
+ doc["lifecycle_command"] = toml_edit::value(command.clone());
+ Ok(())
+ })
+ })?;
+ println!(
+ "✓ {} {} ({})",
+ outcome.verb(),
+ path.display(),
+ match outcome {
+ ApplyOutcome::Created => "new file",
+ ApplyOutcome::Updated => "backup written next to it",
+ ApplyOutcome::NoOp => "already up to date",
+ }
+ );
+ println_swival_handoff_note();
+ Ok(())
+}
+
fn render_devin(
hooks_dir: &Path,
server_url: &str,
diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rs
index 3b139951..9bd48d5a 100644
--- a/crates/ai-memory-cli/src/commands/install_mcp.rs
+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs
@@ -77,6 +77,7 @@ pub fn run(config: &Config, args: InstallMcpArgs) -> Result<()> {
McpClient::KimiCode => render_kimi_code(&args)?,
McpClient::KiroCli => render_kiro_cli(&args)?,
McpClient::CommandCode => render_command_code(&args)?,
+ McpClient::Swival => render_swival(&args)?,
McpClient::VsCodeCopilot => render_vscode_copilot(&args)?,
McpClient::Zed => render_zed(&args)?,
};
@@ -212,6 +213,12 @@ pub(crate) fn mcp_config_path(client: crate::cli::McpClient) -> Result<PathBuf>
.join("settings")
.join("mcp.json"),
McpClient::CommandCode => home()?.join(".commandcode").join("mcp.json"),
+ // Swival reads the project-scoped `.swival/mcp.json` under the
+ // current base dir by default (its own documented default lookup).
+ McpClient::Swival => std::env::current_dir()
+ .context("could not resolve current dir for .swival/mcp.json default")?
+ .join(".swival")
+ .join("mcp.json"),
// VS Code MCP is workspace-scoped by default: `.vscode/mcp.json`
// at the current workspace root. The user-profile alternative
// lives under VS Code's profile-specific data dir; use VS
@@ -464,7 +471,8 @@ fn json_mcp_location(client: McpClient) -> Option<JsonMcpLocation> {
| McpClient::Devin
| McpClient::KimiCode
| McpClient::KiroCli
- | McpClient::CommandCode => Some(JsonMcpLocation::RootMcpServers),
+ | McpClient::CommandCode
+ | McpClient::Swival => Some(JsonMcpLocation::RootMcpServers),
McpClient::OpenCode => Some(JsonMcpLocation::RootMcp),
// Zero's config.json nests servers under `mcp.servers`, the same
// shape OpenClaw uses.
@@ -691,6 +699,15 @@ fn build_mcp_entry(args: &InstallMcpArgs) -> Result<serde_json::Value> {
entry.insert("headers".into(), json!({"Authorization": b}));
}
}
+ McpClient::Swival => {
+ // Swival .swival/mcp.json entry: `type: "http"` + `url` +
+ // optional headers (documented format).
+ entry.insert("type".into(), json!("http"));
+ entry.insert("url".into(), json!(server_url));
+ if let Some(b) = &bearer {
+ entry.insert("headers".into(), json!({"Authorization": b}));
+ }
+ }
McpClient::VsCodeCopilot => {
// VS Code MCP framework schema: `type: "http"` + `url`,
// headers map for auth. Verified against
@@ -1179,6 +1196,21 @@ fn render_command_code(args: &InstallMcpArgs) -> Result<String> {
))
}
+fn render_swival(args: &InstallMcpArgs) -> Result<String> {
+ Ok(format!(
+ "# Swival CLI — merge into .swival/mcp.json in the project root
+ # (Swival's documented default lookup; project-scoped by design), or
+ # re-run with --apply to merge it in place preserving other servers.
+ # A `[mcp_servers.ai-memory]` table in swival.toml is the TOML
+ # alternative and wins by name when both exist.
+ # Pair with `ai-memory install-hooks --agent swival` for lifecycle
+ # capture; Swival captures hook stdout but never injects it, so
+ # handoffs are recovered via the MCP `memory_handoff_accept` tool.
+ {snippet}\n",
+ snippet = render_json_mcp_fragment(args)?,
+ ))
+}
+
fn render_vscode_copilot(args: &InstallMcpArgs) -> Result<String> {
Ok(format!(
"# VS Code GitHub Copilot (agent mode) — write to one of:\n\
@@ -1612,6 +1644,7 @@ mod tests {
McpClient::KimiCode => render_kimi_code(&args).unwrap(),
McpClient::KiroCli => render_kiro_cli(&args).unwrap(),
McpClient::CommandCode => render_command_code(&args).unwrap(),
+ McpClient::Swival => render_swival(&args).unwrap(),
McpClient::VsCodeCopilot => render_vscode_copilot(&args).unwrap(),
McpClient::Zed => render_zed(&args).unwrap(),
}
@@ -1708,6 +1741,7 @@ mod tests {
McpClient::KimiCode => render_kimi_code(&args).unwrap(),
McpClient::KiroCli => render_kiro_cli(&args).unwrap(),
McpClient::CommandCode => render_command_code(&args).unwrap(),
+ McpClient::Swival => render_swival(&args).unwrap(),
McpClient::VsCodeCopilot => render_vscode_copilot(&args).unwrap(),
McpClient::Zed => render_zed(&args).unwrap(),
}
diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rs
index 51f14a31..a0ea2572 100644
--- a/crates/ai-memory-cli/src/commands/render_shared.rs
+++ b/crates/ai-memory-cli/src/commands/render_shared.rs
@@ -1233,14 +1233,11 @@ fn hook_command(
) -> String {
match context.platform {
HookCommandPlatform::Posix => {
- let mut prefix = format!("AI_MEMORY_HOOK_URL={} ", shell_quote(server_url));
- if let Some(t) = auth_token {
- prefix.push_str(&format!("AI_MEMORY_AUTH_TOKEN={} ", shell_quote(t)));
- }
- if let Some(s) = context.project_strategy {
- prefix.push_str(&format!("AI_MEMORY_PROJECT_STRATEGY={} ", shell_quote(s)));
- }
- format!("{prefix}{}", shell_quote(&script.to_string_lossy()))
+ format!(
+ "{}{}",
+ env_var_prefix(server_url, auth_token, context.project_strategy),
+ shell_quote(&script.to_string_lossy())
+ )
}
HookCommandPlatform::Windows => {
// Hook runners launch this child with redirected streams. Force
@@ -1271,14 +1268,11 @@ fn hook_command(
}
HookCommandPlatform::WindowsBash => {
let bash_path = to_git_bash_path(&script.to_string_lossy());
- let mut inner = format!("AI_MEMORY_HOOK_URL={} ", shell_quote(server_url));
- if let Some(t) = auth_token {
- inner.push_str(&format!("AI_MEMORY_AUTH_TOKEN={} ", shell_quote(t)));
- }
- if let Some(s) = context.project_strategy {
- inner.push_str(&format!("AI_MEMORY_PROJECT_STRATEGY={} ", shell_quote(s)));
- }
- inner.push_str(&shell_quote(&bash_path));
+ let inner = format!(
+ "{}{}",
+ env_var_prefix(server_url, auth_token, context.project_strategy),
+ shell_quote(&bash_path)
+ );
format!("bash -c {}", shell_quote(&inner))
}
HookCommandPlatform::WindowsNative => {
@@ -1469,15 +1463,66 @@ fn to_git_bash_path(path: &str) -> String {
/// command path. Leaves only conservative shell-safe characters unquoted;
/// wraps everything else in single quotes and escapes embedded `'` via
/// `'\''`.
-fn shell_quote(s: &str) -> String {
+pub(crate) fn shell_quote(s: &str) -> String {
if s.chars().all(|c| {
c.is_ascii_alphanumeric()
|| matches!(c, '-' | '_' | '.' | '/' | ':' | '@' | '%' | '+' | '=' | ',')
}) {
- return s.to_string();
+ s.to_string()
+ } else {
+ let escaped = s.replace('\'', "'\\''");
+ format!("'{escaped}'")
}
- let escaped = s.replace('\'', "'\\''");
- format!("'{escaped}'")
+}
+
+/// Build the `AI_MEMORY_HOOK_URL=… [AI_MEMORY_AUTH_TOKEN=…]` env-var prefix
+/// that POSIX hook commands pass the server URL and auth to the shim without
+/// a config file. Shared by the POSIX shell commands, the WindowsBash
+/// bridge, and Swival's no-shell `env`-prefixed lifecycle command (issue
+/// #385).
+fn env_var_prefix(
+ server_url: &str,
+ auth_token: Option<&str>,
+ project_strategy: Option<&str>,
+) -> String {
+ let mut prefix = format!("AI_MEMORY_HOOK_URL={} ", shell_quote(server_url));
+ if let Some(t) = auth_token {
+ prefix.push_str(&format!("AI_MEMORY_AUTH_TOKEN={} ", shell_quote(t)));
+ }
+ if let Some(s) = project_strategy {
+ prefix.push_str(&format!("AI_MEMORY_PROJECT_STRATEGY={} ", shell_quote(s)));
+ }
+ prefix
+}
+
+/// Print Swival's standard stdout-capture note (issue #385): Swival keeps
+/// lifecycle-hook stdout out of the model context, so capture works but
+/// handoff injection does not and handoffs are recovered via MCP.
+pub(crate) fn println_swival_handoff_note() {
+ println!("# NOTE: Swival captures hook stdout but never injects it into the model");
+ println!("# context — capture works, but handoff injection does not. Recover");
+ println!("# a prior session's handoff via the MCP `memory_handoff_accept` tool.");
+}
+
+/// Build Swival's `lifecycle_command` string (issue #385).
+///
+/// Swival invokes the hook as `shlex.split(command) + [event, base_dir]`
+/// with `cwd = base_dir` and its own `SWIVAL_*` env — no shell, no stdin.
+/// The `env VAR=… <script>` prefix survives that exec line because `env`
+/// is a real binary, which is how the hook learns the server URL / auth
+/// token (the `AI_MEMORY_HOOK_URL=… <script>` prefix used by Claude
+/// Code/Grok would be passed to the kernel as the program name and fail).
+pub(crate) fn build_swival_lifecycle_command(
+ script: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
+ project_strategy: Option<&str>,
+) -> String {
+ format!(
+ "env {}{}",
+ env_var_prefix(server_url, auth_token, project_strategy),
+ shell_quote(&script.to_string_lossy())
+ )
}
fn powershell_quote(s: &str) -> String {
@@ -2792,6 +2837,45 @@ $payload = [Console]::In.ReadToEnd()
);
}
+ #[test]
+ fn swival_lifecycle_command_env_prefix_survives_shlex_split() {
+ // `env` is a real binary: the VAR=val prefix survives Python's
+ // shlex.split + subprocess exec (a plain `AI_MEMORY_HOOK_URL=…`
+ // prefix would be passed to exec as the program name and fail).
+ // shell_quote leaves ASCII-safe values unquoted — a URL and plain
+ // path are exec-able as-is; a secret with shell metacharacters
+ // (here `!`) must come back single-quoted.
+ let cmd = build_swival_lifecycle_command(
+ Path::new("/host/hooks/swival/lifecycle.sh"),
+ "http://127.0.0.1:49374",
+ Some("tok!secret"),
+ Some("repo-root"),
+ );
+ assert_eq!(
+ cmd,
+ "env AI_MEMORY_HOOK_URL=http://127.0.0.1:49374 \
+ AI_MEMORY_AUTH_TOKEN='tok!secret' AI_MEMORY_PROJECT_STRATEGY=repo-root \
+ /host/hooks/swival/lifecycle.sh"
+ );
+ // shlex.split strips the single quotes and yields exactly the
+ // `env` + VAR=val + script tokens — pinned by the full-string
+ // equality above; no shell is involved in the exec.
+ }
+
+ #[test]
+ fn swival_lifecycle_command_omits_optional_parts() {
+ let cmd = build_swival_lifecycle_command(
+ Path::new("/x/lifecycle.sh"),
+ "http://127.0.0.1:49374",
+ None,
+ None,
+ );
+ assert_eq!(
+ cmd,
+ "env AI_MEMORY_HOOK_URL=http://127.0.0.1:49374 /x/lifecycle.sh"
+ );
+ }
+
#[test]
fn hook_command_omits_project_strategy_when_none() {
for platform in [
diff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rs
index 372fd23a..149a011c 100644
--- a/crates/ai-memory-cli/src/commands/run.rs
+++ b/crates/ai-memory-cli/src/commands/run.rs
@@ -1355,6 +1355,7 @@ const fn managed_harness(choice: RunHarnessChoice) -> ManagedHarness {
RunHarnessChoice::Kiro => ManagedHarness::Kiro,
RunHarnessChoice::Grok => ManagedHarness::Grok,
RunHarnessChoice::Antigravity => ManagedHarness::Antigravity,
+ RunHarnessChoice::Swival => ManagedHarness::Swival,
}
}
@@ -1379,6 +1380,7 @@ const fn managed_harness_from_agent(agent: AgentKind) -> Option<ManagedHarness>
AgentKind::KiroCli => Some(ManagedHarness::Kiro),
AgentKind::Grok => Some(ManagedHarness::Grok),
AgentKind::AntigravityCli => Some(ManagedHarness::Antigravity),
+ AgentKind::Swival => Some(ManagedHarness::Swival),
_ => None,
}
}
diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rs
index 9860d3c3..7b8b2baf 100644
--- a/crates/ai-memory-cli/src/commands/setup_agent.rs
+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs
@@ -40,7 +40,7 @@ use crate::commands::render_shared::{
ANTIGRAVITY_LIFECYCLE_EVENTS, ANTIGRAVITY_TOOL_EVENTS, CODEX_PROFILE, COMMAND_CODE_PROFILE,
CURSOR_PROFILE, GEMINI_PROFILE, KIMI_CODE_EVENTS, KIRO_CLI_V2_EVENTS, KIRO_CLI_V3_EVENTS,
build_claude_code_payload, build_devin_payload, build_grok_payload,
- hook_script_for_current_platform,
+ build_swival_lifecycle_command, hook_script_for_current_platform, println_swival_handoff_note,
};
use crate::config::{Config, DEFAULT_SERVER_URL};
@@ -159,6 +159,9 @@ pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {
AgentChoice::KiroCliV3 => {
emit_other(&emit_root, agent_sub, &args, &[&KIRO_CLI_V3_EVENTS]);
}
+ // Swival hooks are a single lifecycle_command, not a staged script
+ // bundle — emit_swival prints the TOML directly.
+ AgentChoice::Swival => emit_swival(&emit_root, &args)?,
AgentChoice::OpenCode
| AgentChoice::Pi
| AgentChoice::Omp
@@ -315,6 +318,35 @@ fn emit_grok(emit_root: &Path, args: &SetupAgentArgs) -> Result<()> {
Ok(())
}
+/// Print Swival's lifecycle_command pointing at the staged script (issue #385).
+/// Swival has a single `lifecycle_command` invoked as `<cmd> startup|exit <base_dir>`
+/// with `cwd = base_dir`; like the other setup-agent emitters this renders the
+/// TOML without writing any config file.
+fn emit_swival(emit_root: &Path, args: &SetupAgentArgs) -> Result<()> {
+ let script = emit_root.join("lifecycle.sh");
+ let command =
+ build_swival_lifecycle_command(&script, &args.server_url, args.auth_token.as_deref(), None);
+ println!("# Swival CLI — merge into ~/.config/swival/config.toml");
+ println!("# (or a project swival.toml, which Swival prefers over the global file),");
+ println!("# or re-run `ai-memory install-hooks --agent swival --apply` to merge");
+ println!("# it in place. Swival invokes the hook as:");
+ println!("# <command> startup <base_dir> / <command> exit <base_dir>");
+ println!("# Hook script (must be reachable from the host that runs Swival):");
+ println!("# {}", script.display());
+ println!("# AI-memory server: {}", args.server_url);
+ if args.auth_token.is_some() {
+ println!("# Auth: AI_MEMORY_AUTH_TOKEN embedded in lifecycle_command below.");
+ println!("# Treat ~/.config/swival/config.toml as sensitive (chmod 600).");
+ }
+ println!("# Tip: also run `ai-memory install-mcp --client swival --auth-token <...>`");
+ println!("# to register the MCP endpoint in .swival/mcp.json.");
+ println!();
+ println_swival_handoff_note();
+ println!();
+ println!("lifecycle_command = {}", toml_edit::value(command));
+ Ok(())
+}
+
fn emit_devin(emit_root: &Path, args: &SetupAgentArgs) -> Result<()> {
print!("{}", render_devin_setup_output(emit_root, args)?);
Ok(())
diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rs
index 6b47dc5c..bde0b35d 100644
--- a/crates/ai-memory-cli/src/commands/uninstall.rs
+++ b/crates/ai-memory-cli/src/commands/uninstall.rs
@@ -42,6 +42,8 @@ enum RewriteOp {
ZeroHooksJson,
/// Kimi Code `[[hooks]]` rules inside config.toml.
KimiCodeHooksToml,
+ /// Swival `lifecycle_command` key inside config.toml.
+ SwivalHooksToml,
/// Kiro CLI v2 agent-config hooks with exact generated command signatures.
KiroCliV2HooksJson,
/// Kiro CLI v3 standalone hooks with exact generated names and commands.
@@ -291,6 +293,19 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {
);
}
+ let swival = install_hooks::swival_config_path(None)?;
+ if swival.exists() {
+ let content = std::fs::read_to_string(&swival)
+ .with_context(|| format!("reading {}", swival.display()))?;
+ let removal = strip_swival_lifecycle_command(&content)?;
+ push_rewrite(
+ &mut plan,
+ swival,
+ removal.removed_events,
+ RewriteOp::SwivalHooksToml,
+ );
+ }
+
let plugin = install_hooks::opencode_plugin_path()?;
push_generated_delete(&mut plan, plugin, DeleteKind::OpenCodePlugin);
@@ -524,6 +539,9 @@ fn apply_change(change: &PlannedChange, name: Option<&str>, url: &str) -> anyhow
}
RewriteOp::ZeroHooksJson => strip_zero_hooks(&out)?.new_content,
RewriteOp::KimiCodeHooksToml => strip_kimi_code_hooks(&out)?.new_content,
+ RewriteOp::SwivalHooksToml => {
+ strip_swival_lifecycle_command(&out)?.new_content
+ }
RewriteOp::KiroCliV2HooksJson => strip_kiro_cli_v2_hooks(&out)?.new_content,
RewriteOp::KiroCliV3HooksJson => strip_kiro_cli_v3_hooks(&out)?.new_content,
RewriteOp::McpJson(client) => {
@@ -994,6 +1012,33 @@ fn strip_kimi_code_hooks(content: &str) -> Result<HookRemoval> {
})
}
+/// Remove ai-memory's `lifecycle_command` from a Swival config TOML.
+/// Other keys (inference config, MCP tables, audit settings) survive
+/// untouched. The command is ours when it embeds the lifecycle.sh script
+/// (with or without the `env AI_MEMORY_HOOK_URL=…` prefix) or references
+/// the `ai-memory` binary.
+fn strip_swival_lifecycle_command(content: &str) -> Result<HookRemoval> {
+ let mut removed = Vec::new();
+ let new_content = mutate_toml(content, |doc| {
+ let Some(value) = doc.get("lifecycle_command") else {
+ return Ok(());
+ };
+ let ours = value
+ .as_str()
+ .is_some_and(|cmd| cmd.contains("lifecycle.sh") || hook_command_is_ours(cmd));
+ if !ours {
+ return Ok(());
+ }
+ removed.push("swival.lifecycle_command".to_string());
+ doc.remove("lifecycle_command");
+ Ok(())
+ })?;
+ Ok(HookRemoval {
+ new_content,
+ removed_events: removed,
+ })
+}
+
fn generated_file_is_ours(path: &Path, kind: DeleteKind) -> bool {
let Ok(content) = std::fs::read_to_string(path) else {
return false;
@@ -1080,6 +1125,7 @@ fn mcp_servers_path(client: McpClient) -> Option<&'static [&'static str]> {
| McpClient::KimiCode
| McpClient::KiroCli
| McpClient::CommandCode
+ | McpClient::Swival
| McpClient::Devin => Some(&["mcpServers"]),
McpClient::OpenCode => Some(&["mcp"]),
McpClient::Openclaw | McpClient::Zero => Some(&["mcp", "servers"]),
diff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rs
index a977c02a..2eb2d0be 100644
--- a/crates/ai-memory-core/src/ids.rs
+++ b/crates/ai-memory-core/src/ids.rs
@@ -214,6 +214,8 @@ pub enum AgentKind {
KiroCli,
/// Command Code CLI.
CommandCode,
+ /// Swival CLI (local-first Python coding agent).
+ Swival,
/// Hermes Agent (Nous Research).
Hermes,
/// Anything else (manual capture, future agents).
@@ -226,7 +228,7 @@ impl AgentKind {
/// CHECK constraint accepts every kind (the Zero integration shipped
/// with the enum variant but without the V26 migration and only a
/// live test caught it). Extend together with the enum.
- pub const ALL: [Self; 19] = [
+ pub const ALL: [Self; 20] = [
Self::ClaudeCode,
Self::Codex,
Self::OpenCode,
@@ -244,6 +246,7 @@ impl AgentKind {
Self::KimiCode,
Self::KiroCli,
Self::CommandCode,
+ Self::Swival,
Self::Hermes,
Self::Other,
];
@@ -269,6 +272,7 @@ impl AgentKind {
Self::KimiCode => "kimi-code",
Self::KiroCli => "kiro-cli",
Self::CommandCode => "command-code",
+ Self::Swival => "swival",
Self::Hermes => "hermes",
Self::Other => "other",
}
@@ -297,6 +301,7 @@ impl AgentKind {
"kimi-code" | "kimi" => Self::KimiCode,
"kiro-cli" | "kiro" => Self::KiroCli,
"command-code" | "commandcode" | "cmdc" | "cmd" => Self::CommandCode,
+ "swival" => Self::Swival,
"hermes" | "hermes-agent" => Self::Hermes,
_ => Self::Other,
}
@@ -327,7 +332,13 @@ impl AgentKind {
pub fn session_start_injects_handoff(self) -> bool {
!matches!(
self,
- Self::Crush | Self::Grok | Self::Zero | Self::KimiCode | Self::Hermes | Self::Other
+ Self::Crush
+ | Self::Grok
+ | Self::Zero
+ | Self::KimiCode
+ | Self::Hermes
+ | Self::Swival
+ | Self::Other
)
}
@@ -485,6 +496,28 @@ mod tests {
assert!(!AgentKind::KiroCli.user_prompt_injects_handoff());
}
+ #[test]
+ fn agent_kind_swival_round_trips_without_hook_stdout_handoff() {
+ assert_eq!(AgentKind::Swival.as_str(), "swival");
+ assert_eq!(AgentKind::from_wire("swival"), AgentKind::Swival);
+ // serde uses rename_all = "kebab-case" → "swival".
+ assert_eq!(
+ serde_json::to_string(&AgentKind::Swival).unwrap(),
+ "\"swival\""
+ );
+ assert_eq!(
+ serde_json::from_str::<AgentKind>("\"swival\"").unwrap(),
+ AgentKind::Swival
+ );
+ // Unknown tags still degrade to Other.
+ assert_eq!(AgentKind::from_wire("swival-2"), AgentKind::Other);
+ // Swival captures lifecycle-hook stdout but never injects it into the
+ // model context, so the session-start handoff must be recovered via
+ // the MCP memory_handoff_accept tool instead.
+ assert!(!AgentKind::Swival.session_start_injects_handoff());
+ assert!(!AgentKind::Swival.user_prompt_injects_handoff());
+ }
+
#[test]
fn user_prompt_handoff_injection_is_kimi_only() {
for agent in AgentKind::ALL {
diff --git a/crates/ai-memory-hooks/src/workstream.rs b/crates/ai-memory-hooks/src/workstream.rs
index afbbdfc1..34b02b2d 100644
--- a/crates/ai-memory-hooks/src/workstream.rs
+++ b/crates/ai-memory-hooks/src/workstream.rs
@@ -140,6 +140,7 @@ async fn prepare_run(
| AgentKind::KiroCli
| AgentKind::Grok
| AgentKind::AntigravityCli
+ | AgentKind::Swival
) {
return error(
StatusCode::BAD_REQUEST,
@@ -1155,6 +1156,56 @@ mod tests {
assert_eq!(automatic.status(), StatusCode::BAD_REQUEST);
}
+ #[tokio::test]
+ async fn swival_is_accepted_explicitly_but_not_in_the_automatic_pool() {
+ let temp = TempDir::new().unwrap();
+ let store = Store::open(temp.path()).unwrap();
+ let state = test_state(&store, temp.path());
+
+ let explicit = prepare_run(
+ State(state.clone()),
+ None,
+ Json(PrepareManagedRunRequest {
+ workspace: "default".into(),
+ project: "managed".into(),
+ cwd: "/repo".into(),
+ repo_fingerprint: "repo".into(),
+ worktree_fingerprint: "worktree".into(),
+ agent: AgentKind::Swival,
+ automatic_harness: false,
+ available_agents: Vec::new(),
+ workstream: None,
+ new_workstream: None,
+ lease_owner: "explicit".into(),
+ }),
+ )
+ .await;
+ assert_eq!(explicit.status(), StatusCode::OK);
+ let body = to_bytes(explicit.into_body(), 64 * 1024).await.unwrap();
+ let prepared: PrepareManagedRunResponse = serde_json::from_slice(&body).unwrap();
+ assert_eq!(prepared.resolved_agent, Some(AgentKind::Swival));
+
+ let automatic = prepare_run(
+ State(state),
+ None,
+ Json(PrepareManagedRunRequest {
+ workspace: "default".into(),
+ project: "managed".into(),
+ cwd: "/repo".into(),
+ repo_fingerprint: "repo".into(),
+ worktree_fingerprint: "worktree".into(),
+ agent: AgentKind::Swival,
+ automatic_harness: true,
+ available_agents: vec![AgentKind::Swival],
+ workstream: None,
+ new_workstream: None,
+ lease_owner: "automatic".into(),
+ }),
+ )
+ .await;
+ assert_eq!(automatic.status(), StatusCode::BAD_REQUEST);
+ }
+
#[tokio::test]
async fn grok_run_context_uses_the_direct_delivery_gate() {
let temp = TempDir::new().unwrap();
diff --git a/crates/ai-memory-store/migrations/V48__sessions_swival_agent_kind.sql b/crates/ai-memory-store/migrations/V48__sessions_swival_agent_kind.sql
new file mode 100644
index 00000000..c6a24aa7
--- /dev/null
+++ b/crates/ai-memory-store/migrations/V48__sessions_swival_agent_kind.sql
@@ -0,0 +1,73 @@
+-- Expand sessions.agent_kind CHECK for Swival CLI.
+--
+-- Keep the complete V47 schema, indexes, and scope-pairing triggers while
+-- adding the `swival` wire value.
+
+PRAGMA foreign_keys = OFF;
+
+DROP TRIGGER IF EXISTS auto_improve_scheduler_claims_session_pairing_ai;
+DROP TRIGGER IF EXISTS session_consolidation_jobs_session_pairing_ai;
+
+CREATE TABLE sessions_new (
+ id BLOB PRIMARY KEY NOT NULL,
+ workspace_id BLOB NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
+ project_id BLOB NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
+ agent_kind TEXT NOT NULL CHECK (agent_kind IN ('claude-code','codex','open-code','cursor','gemini-cli','claude-desktop','openclaw','antigravity-cli','omp','pi','crush','grok','zero','devin','kimi-code','kiro-cli','command-code','swival','hermes','other')),
+ cwd TEXT,
+ started_at INTEGER NOT NULL,
+ ended_at INTEGER,
+ summary_page_id BLOB REFERENCES pages(id) ON DELETE SET NULL,
+ ended_observation_count INTEGER NOT NULL DEFAULT 0 CHECK (ended_observation_count >= 0),
+ actor_user TEXT
+);
+
+INSERT INTO sessions_new (
+ id, workspace_id, project_id, agent_kind, cwd, started_at, ended_at,
+ summary_page_id, ended_observation_count, actor_user
+)
+SELECT
+ id, workspace_id, project_id, agent_kind, cwd, started_at, ended_at,
+ summary_page_id, ended_observation_count, actor_user
+FROM sessions;
+
+DROP TABLE sessions;
+
+ALTER TABLE sessions_new RENAME TO sessions;
+
+CREATE INDEX idx_sessions_recent ON sessions(workspace_id, project_id, started_at DESC);
+CREATE INDEX idx_sessions_project ON sessions(project_id);
+CREATE INDEX idx_sessions_started_at ON sessions(started_at DESC);
+CREATE INDEX idx_sessions_scope_ended
+ ON sessions(workspace_id, project_id, ended_at ASC)
+ WHERE ended_at IS NOT NULL;
+CREATE INDEX idx_sessions_open_owner
+ ON sessions(workspace_id, project_id, agent_kind, actor_user)
+ WHERE ended_at IS NULL;
+
+CREATE TRIGGER sessions_ws_proj_pairing_ai
+BEFORE INSERT ON sessions
+FOR EACH ROW
+WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM projects WHERE id = NEW.project_id)
+BEGIN
+ SELECT RAISE(ABORT, 'sessions.workspace_id does not match the project''s workspace');
+END;
+
+CREATE TRIGGER auto_improve_scheduler_claims_session_pairing_ai
+BEFORE INSERT ON auto_improve_scheduler_claims
+FOR EACH ROW
+WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM sessions WHERE id = NEW.session_id)
+ OR NEW.project_id IS NOT (SELECT project_id FROM sessions WHERE id = NEW.session_id)
+BEGIN
+ SELECT RAISE(ABORT, 'auto_improve_scheduler_claims scope does not match the session scope');
+END;
+
+CREATE TRIGGER session_consolidation_jobs_session_pairing_ai
+BEFORE INSERT ON session_consolidation_jobs
+FOR EACH ROW
+WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM sessions WHERE id = NEW.session_id)
+ OR NEW.project_id IS NOT (SELECT project_id FROM sessions WHERE id = NEW.session_id)
+BEGIN
+ SELECT RAISE(ABORT, 'session_consolidation_jobs scope does not match the session scope');
+END;
+
+PRAGMA foreign_keys = ON;
diff --git a/crates/ai-memory-workstream/src/harness.rs b/crates/ai-memory-workstream/src/harness.rs
index 35c5dace..360e27f8 100644
--- a/crates/ai-memory-workstream/src/harness.rs
+++ b/crates/ai-memory-workstream/src/harness.rs
@@ -34,6 +34,8 @@ pub enum ManagedHarness {
Grok,
/// Google Antigravity CLI (`agy`).
Antigravity,
+ /// Swival CLI (local-first Python coding agent).
+ Swival,
}
impl ManagedHarness {
@@ -52,6 +54,7 @@ impl ManagedHarness {
"kiro" | "kiro-cli" => Some(Self::Kiro),
"grok" | "grok-build" => Some(Self::Grok),
"antigravity" | "antigravity-cli" | "agy" => Some(Self::Antigravity),
+ "swival" => Some(Self::Swival),
_ => None,
}
}
@@ -71,6 +74,7 @@ impl ManagedHarness {
Self::Kiro | Self::KiroV3 => AgentKind::KiroCli,
Self::Grok => AgentKind::Grok,
Self::Antigravity => AgentKind::AntigravityCli,
+ Self::Swival => AgentKind::Swival,
}
}
@@ -95,6 +99,7 @@ impl ManagedHarness {
Self::Kiro | Self::KiroV3 => "kiro-cli",
Self::Grok => "grok",
Self::Antigravity => "agy",
+ Self::Swival => "swival",
}
}
@@ -114,6 +119,7 @@ impl ManagedHarness {
Self::KiroV3 => "kiro-v3",
Self::Grok => "grok",
Self::Antigravity => "antigravity",
+ Self::Swival => "swival",
}
}
}
@@ -201,6 +207,9 @@ pub fn build_launch_plan(
let session_dir = match harness {
ManagedHarness::Pi | ManagedHarness::Omp => flag_path(&args, &["--session-dir"]),
ManagedHarness::Crush => flag_path(&args, &["--data-dir", "-D"]),
+ // `--cache-dir` relocates the whole `.swival` store (HISTORY.md,
+ // continue.md, memory/, cache.db), so it is the session root.
+ ManagedHarness::Swival => flag_path(&args, &["--cache-dir"]),
_ => None,
}
.or_else(|| environment_session_dir(harness));
@@ -330,6 +339,10 @@ pub fn build_launch_plan(
expected = Some(id.to_string());
}
}
+ // Swival resumes implicitly from `.swival/HISTORY.md` + continue.md
+ // in the project directory and exposes no session selector, so
+ // nothing is injected; fresh sessions are discovered post-exit.
+ ManagedHarness::Swival => {}
}
}
@@ -365,6 +378,8 @@ pub fn apply_yolo(harness: ManagedHarness, args: &mut Vec<OsString>) {
ManagedHarness::KiroV3 => None,
ManagedHarness::Grok => Some("--yolo"),
ManagedHarness::Antigravity => Some("--dangerously-skip-permissions"),
+ // Swival's own shorthand for `--files all --commands all`.
+ ManagedHarness::Swival => Some("--yolo"),
};
if let Some(flag) = flag {
// Kimi's `--yolo` has hidden aliases (`--yes`, `--auto-approve`) and
@@ -413,6 +428,11 @@ fn noninteractive_invocation(harness: ManagedHarness, args: &[OsString]) -> bool
// / `-i` is NOT: it seeds a prompt and then keeps the session open, so
// it stays adoptable.
ManagedHarness::Antigravity => has_flag(args, &["--print", "-p", "--prompt"]),
+ // A positional TASK (or reviewer/stdin mode) makes Swival run
+ // one-shot; only a request-free invocation keeps the interactive
+ // REPL. Flag values are indistinguishable from a task, so any
+ // argument fails closed toward the noninteractive side.
+ ManagedHarness::Swival => !args.is_empty(),
}
}
@@ -434,6 +454,20 @@ fn launch_mode(harness: ManagedHarness, args: &[OsString]) -> LaunchMode {
if harness == ManagedHarness::CommandCode && has_flag(args, &["--list-models", "--ide-setup"]) {
return LaunchMode::Passthrough;
}
+ if harness == ManagedHarness::Swival
+ && has_flag(
+ args,
+ &[
+ "--init-config",
+ "--logout",
+ "--list-profiles",
+ "--serve",
+ "--acp",
+ ],
+ )
+ {
+ return LaunchMode::Passthrough;
+ }
if matches!(harness, ManagedHarness::Kiro | ManagedHarness::KiroV3) {
// An unknown non-v2 engine remains passthrough rather than being
// assigned to either incompatible adapter. Headless runs and one-shot
@@ -666,6 +700,7 @@ fn launch_mode(harness: ManagedHarness, args: &[OsString]) -> LaunchMode {
"update",
]
.as_slice(),
+ ManagedHarness::Swival => ["skills"].as_slice(),
};
let first = if matches!(harness, ManagedHarness::Kiro | ManagedHarness::KiroV3) {
kiro_root_subcommand(args)
@@ -761,6 +796,9 @@ pub fn has_native_session_selector(harness: ManagedHarness, args: &[OsString]) -
// naming one; that is still an explicit user choice, so nothing may be
// injected over it.
ManagedHarness::Antigravity => has_flag(args, &["--conversation", "--continue", "-c"]),
+ // Swival exposes no resume/continue selector; it resumes implicitly
+ // from the project's `.swival/` store by cwd.
+ ManagedHarness::Swival => false,
}
}
@@ -793,6 +831,7 @@ fn explicit_session_id(harness: ManagedHarness, args: &[OsString]) -> Option<Str
// A bare `--continue` names no conversation: the id is only known
// after the fact, from the conversation store.
ManagedHarness::Antigravity => flag_value(args, &["--conversation"]),
+ ManagedHarness::Swival => None,
}
}
@@ -905,6 +944,9 @@ fn environment_session_dir_with(
ManagedHarness::Grok => value("GROK_HOME").map(|dir| dir.join("sessions")),
// `agy` exposes no environment override for its conversation store.
ManagedHarness::Antigravity => None,
+ // Swival's store is project-scoped under `.swival/` (the `--cache-dir`
+ // flag is the only relocation knob); no environment override exists.
+ ManagedHarness::Swival => None,
}
}
@@ -1809,6 +1851,112 @@ mod tests {
);
}
+ #[test]
+ fn swival_names_parse_to_one_variant() {
+ assert_eq!(
+ ManagedHarness::from_name("swival"),
+ Some(ManagedHarness::Swival)
+ );
+ assert_eq!(ManagedHarness::Swival.executable(), "swival");
+ assert_eq!(ManagedHarness::Swival.as_str(), "swival");
+ assert_eq!(ManagedHarness::Swival.agent_kind(), AgentKind::Swival);
+ }
+
+ /// Swival resumes implicitly from `.swival/` by cwd and exposes no
+ /// session selector, so neither a fresh nor a linked launch may rewrite
+ /// argv or claim an expected session id.
+ #[test]
+ fn swival_launch_never_injects_a_selector() {
+ for (linked, native) in [
+ (
+ None,
+ vec![OsString::from("--profile"), OsString::from("default")],
+ ),
+ (
+ Some("HISTORY"),
+ vec![OsString::from("--model"), OsString::from("code-35b")],
+ ),
+ ] {
+ let plan =
+ build_launch_plan(ManagedHarness::Swival, None, native.clone(), linked).unwrap();
+ assert_eq!(plan.args, native, "{native:?} must stay byte-identical");
+ assert_eq!(plan.expected_session_id, None);
+ assert_eq!(plan.mode, LaunchMode::Session);
+ assert_eq!(plan.session_dir, None);
+ }
+ }
+
+ #[test]
+ fn swival_cache_dir_flag_relocates_the_session_store() {
+ let plan = build_launch_plan(
+ ManagedHarness::Swival,
+ None,
+ vec![
+ OsString::from("--cache-dir"),
+ OsString::from("/stores/swival"),
+ ],
+ None,
+ )
+ .unwrap();
+ assert_eq!(
+ plan.session_dir.as_deref(),
+ Some(std::path::Path::new("/stores/swival"))
+ );
+ }
+
+ #[test]
+ fn swival_yolo_maps_to_its_own_flag() {
+ let mut args = Vec::new();
+ apply_yolo(ManagedHarness::Swival, &mut args);
+ assert_eq!(strings(&args), ["--yolo"]);
+ // The user's own `--yolo` (or its `--files all` expansion) is not
+ // duplicated.
+ let mut explicit = vec![OsString::from("--yolo")];
+ apply_yolo(ManagedHarness::Swival, &mut explicit);
+ assert_eq!(strings(&explicit), ["--yolo"]);
+ }
+
+ #[test]
+ fn swival_utility_subcommands_are_passthrough() {
+ for native in [
+ vec![OsString::from("--init-config")],
+ vec![OsString::from("--logout")],
+ vec![OsString::from("--list-profiles")],
+ vec![OsString::from("--serve")],
+ vec![OsString::from("--acp")],
+ vec![OsString::from("skills"), OsString::from("list")],
+ vec![OsString::from("--version")],
+ ] {
+ assert_eq!(
+ build_launch_plan(ManagedHarness::Swival, None, native.clone(), None)
+ .unwrap()
+ .mode,
+ LaunchMode::Passthrough,
+ "{native:?} must be passthrough"
+ );
+ }
+ }
+
+ #[test]
+ fn swival_oneshot_task_is_noninteractive_but_session_bearing() {
+ // A positional TASK runs one-shot, so the adoption prompt must not
+ // appear, yet the run is still a session (not a utility).
+ let plan = build_launch_plan(
+ ManagedHarness::Swival,
+ None,
+ vec![OsString::from("refactor auth")],
+ None,
+ )
+ .unwrap();
+ assert_eq!(plan.mode, LaunchMode::Session);
+ assert!(!allows_native_session_adoption(
+ ManagedHarness::Swival,
+ &plan.args
+ ));
+ // A request-free launch keeps the interactive REPL and is adoptable.
+ assert!(allows_native_session_adoption(ManagedHarness::Swival, &[]));
+ }
+
#[test]
fn antigravity_explicit_selector_always_wins() {
for native in [
diff --git a/crates/ai-memory-workstream/src/transcript.rs b/crates/ai-memory-workstream/src/transcript.rs
index 7ec2732b..ee6482a1 100644
--- a/crates/ai-memory-workstream/src/transcript.rs
+++ b/crates/ai-memory-workstream/src/transcript.rs
@@ -130,6 +130,15 @@ pub async fn export_transcript(
"antigravity conversations expose no decodable transcript; this session's events come from hook capture"
));
}
+ if harness == ManagedHarness::Swival {
+ // `.swival/HISTORY.md` is a human-readable session rollup, not a
+ // structured event log, and its shape is not versioned. The
+ // visible-event ledger for this harness comes from lifecycle-hook
+ // capture instead; only session identity is read from the store.
+ return Err(anyhow!(
+ "swival HISTORY.md exposes no decodable transcript; this session's events come from hook capture"
+ ));
+ }
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)
@@ -150,6 +159,9 @@ pub async fn discover_native_session(
if harness == ManagedHarness::Crush {
return discover_crush(cwd, session_dir, started_at);
}
+ if harness == ManagedHarness::Swival {
+ return discover_swival(cwd, session_dir, started_at);
+ }
let mut candidates = collect_session_files(harness, home, session_dir)?;
candidates.sort_by(|left, right| {
modified(right)
@@ -188,6 +200,9 @@ pub async fn list_native_sessions(
if harness == ManagedHarness::Crush {
return list_crush_sessions(cwd, session_dir, limit);
}
+ if harness == ManagedHarness::Swival {
+ return list_swival_sessions(cwd, session_dir, limit);
+ }
let mut files = collect_session_files(harness, home, session_dir)?;
files.sort_by(|left, right| {
@@ -240,6 +255,9 @@ pub fn native_session_exists(
if harness == ManagedHarness::Crush {
return Ok(crush_updated(cwd, session_dir, native_session_id)?.is_some());
}
+ if harness == ManagedHarness::Swival {
+ return Ok(swival_updated(cwd, session_dir, native_session_id)?.is_some());
+ }
Ok(locate_session_file(harness, home, cwd, session_dir, native_session_id)?.is_some())
}
@@ -281,6 +299,11 @@ pub async fn wait_for_transcript_flush(
session_dir: Option<&Path>,
native_session_id: &str,
) -> Result<()> {
+ if harness == ManagedHarness::Swival {
+ // HISTORY.md is never decoded, so there is no buffered transcript to
+ // settle before the ledger import (which comes from hook capture).
+ return Ok(());
+ }
let mut previous = None;
for _ in 0..10 {
let current = if harness == ManagedHarness::OpenCode {
@@ -440,7 +463,10 @@ fn export_jsonl(
&mut events,
&mut losses,
),
- ManagedHarness::OpenCode | ManagedHarness::Crush | ManagedHarness::Antigravity => {
+ ManagedHarness::OpenCode
+ | ManagedHarness::Crush
+ | ManagedHarness::Antigravity
+ | ManagedHarness::Swival => {
return Err(anyhow!(
"{} transcripts must use their SQLite adapter",
harness.as_str()
@@ -2411,7 +2437,8 @@ fn session_header(harness: ManagedHarness, path: &Path) -> Result<Option<(String
| ManagedHarness::Kiro
| ManagedHarness::KiroV3
| ManagedHarness::Grok
- | ManagedHarness::Antigravity => (None, None),
+ | ManagedHarness::Antigravity
+ | ManagedHarness::Swival => (None, None),
};
if let (Some(id), Some(cwd)) = (id, cwd) {
return Ok(Some((id.to_string(), PathBuf::from(cwd))));
@@ -2880,6 +2907,70 @@ fn crush_db(cwd: &Path, session_dir: Option<&Path>) -> PathBuf {
session_dir.unwrap_or(&cwd.join(".crush")).join("crush.db")
}
+/// Resolve Swival's per-project store root: `--cache-dir` when given, else
+/// `cwd/.swival`. All session state (HISTORY.md, continue.md, memory/,
+/// cache.db, mcp.json) lives under this one directory.
+fn swival_root(cwd: &Path, session_dir: Option<&Path>) -> PathBuf {
+ session_dir.unwrap_or(&cwd.join(".swival")).to_path_buf()
+}
+
+/// The session rollup file. The fixed `HISTORY` stem doubles as the native
+/// session id: Swival keeps exactly one current rollup per checkout.
+fn swival_history_path(cwd: &Path, session_dir: Option<&Path>) -> PathBuf {
+ swival_root(cwd, session_dir).join("HISTORY.md")
+}
+
+fn discover_swival(
+ cwd: &Path,
+ session_dir: Option<&Path>,
+ started_at: SystemTime,
+) -> Result<Option<String>> {
+ Ok(list_swival_sessions(cwd, session_dir, 1)?
+ .into_iter()
+ .find(|candidate| candidate.updated_at + Duration::from_secs(2) >= started_at)
+ .map(|candidate| candidate.native_session_id))
+}
+
+fn list_swival_sessions(
+ cwd: &Path,
+ session_dir: Option<&Path>,
+ limit: usize,
+) -> Result<Vec<NativeSessionCandidate>> {
+ if limit == 0 {
+ return Ok(Vec::new());
+ }
+ let history = swival_history_path(cwd, session_dir);
+ if !history.is_file() {
+ return Ok(Vec::new());
+ }
+ let Some(updated_at) = modified(&history) else {
+ return Ok(Vec::new());
+ };
+ Ok(vec![NativeSessionCandidate {
+ native_session_id: "HISTORY".to_owned(),
+ updated_at,
+ }])
+}
+
+fn swival_updated(
+ cwd: &Path,
+ session_dir: Option<&Path>,
+ native_session_id: &str,
+) -> Result<Option<i64>> {
+ if native_session_id != "HISTORY" {
+ return Ok(None);
+ }
+ let history = swival_history_path(cwd, session_dir);
+ if !history.is_file() {
+ return Ok(None);
+ }
+ Ok(modified(&history).map(|time| {
+ time.duration_since(UNIX_EPOCH)
+ .ok()
+ .map_or(0, |duration| duration.as_millis() as i64)
+ }))
+}
+
fn native_timestamp(value: i64) -> Option<SystemTime> {
let value = u64::try_from(value).ok()?;
if value < 100_000_000_000 {
@@ -2933,6 +3024,10 @@ fn session_root(harness: ManagedHarness, home: &Path, override_dir: Option<&Path
ManagedHarness::KiroV3 => home.join(".kiro/sessions"),
ManagedHarness::Grok => home.join(".grok/sessions"),
ManagedHarness::Antigravity => home.join(".gemini/antigravity-cli/conversations"),
+ // Swival's store is project-scoped (`.swival/` under the checkout),
+ // so every public entry point resolves it from `cwd` and this arm is
+ // unreachable; kept for match exhaustiveness.
+ ManagedHarness::Swival => home.join(".swival"),
}
}
@@ -3157,7 +3252,8 @@ mod tests {
| ManagedHarness::Kiro
| ManagedHarness::KiroV3
| ManagedHarness::Grok
- | ManagedHarness::Antigravity => {
+ | ManagedHarness::Antigravity
+ | ManagedHarness::Swival => {
unreachable!()
}
},
@@ -4587,6 +4683,88 @@ mod tests {
assert!(error.contains("hook capture"), "{error}");
}
+ /// Swival's store is project-scoped (`.swival/` under the checkout) and
+ /// the rollup stem doubles as the native session id. Discovery, listing,
+ /// and existence all read the same HISTORY.md file.
+ #[tokio::test]
+ async fn swival_lists_and_resolves_its_project_history_rollup() {
+ let temp = tempfile::TempDir::new().unwrap();
+ let cwd = temp.path().join("checkout");
+ fs::create_dir_all(cwd.join(".swival")).unwrap();
+ fs::write(cwd.join(".swival/HISTORY.md"), "# Session\n").unwrap();
+
+ let sessions = list_native_sessions(ManagedHarness::Swival, temp.path(), &cwd, None, 8)
+ .await
+ .unwrap();
+ assert_eq!(sessions.len(), 1);
+ assert_eq!(sessions[0].native_session_id, "HISTORY");
+ assert!(
+ native_session_exists(ManagedHarness::Swival, temp.path(), &cwd, None, "HISTORY")
+ .unwrap()
+ );
+ assert!(
+ !native_session_exists(ManagedHarness::Swival, temp.path(), &cwd, None, "OTHER")
+ .unwrap()
+ );
+ // Other checkouts stay invisible — the store is resolved from cwd.
+ let elsewhere = temp.path().join("elsewhere");
+ fs::create_dir_all(elsewhere.join(".swival")).unwrap();
+ fs::write(elsewhere.join(".swival/HISTORY.md"), "# Session\n").unwrap();
+ let none = list_native_sessions(ManagedHarness::Swival, temp.path(), &elsewhere, None, 8)
+ .await
+ .unwrap();
+ assert_eq!(none.len(), 1);
+ assert_eq!(none[0].native_session_id, "HISTORY");
+ }
+
+ #[tokio::test]
+ async fn swival_missing_store_lists_nothing() {
+ let temp = tempfile::TempDir::new().unwrap();
+ let cwd = temp.path().join("checkout");
+ fs::create_dir_all(&cwd).unwrap();
+ let sessions = list_native_sessions(ManagedHarness::Swival, temp.path(), &cwd, None, 8)
+ .await
+ .unwrap();
+ assert!(sessions.is_empty());
+ assert!(
+ !native_session_exists(ManagedHarness::Swival, temp.path(), &cwd, None, "HISTORY")
+ .unwrap()
+ );
+ }
+
+ #[tokio::test]
+ async fn swival_discover_requires_a_freshly_touched_rollup() {
+ let temp = tempfile::TempDir::new().unwrap();
+ let cwd = temp.path().join("checkout");
+ fs::create_dir_all(cwd.join(".swival")).unwrap();
+ fs::write(cwd.join(".swival/HISTORY.md"), "# Session\n").unwrap();
+ let started = SystemTime::now();
+ let discovered =
+ discover_native_session(ManagedHarness::Swival, temp.path(), &cwd, None, started)
+ .await
+ .unwrap();
+ assert_eq!(discovered.as_deref(), Some("HISTORY"));
+ }
+
+ /// The rollup is not versioned, so the ledger for this harness comes from
+ /// hook capture. The failure has to say so.
+ #[tokio::test]
+ async fn swival_transcript_export_explains_why_it_is_unavailable() {
+ let temp = tempfile::TempDir::new().unwrap();
+ let error = export_transcript(
+ ManagedHarness::Swival,
+ temp.path(),
+ temp.path(),
+ None,
+ "HISTORY",
+ None,
+ )
+ .await
+ .unwrap_err()
+ .to_string();
+ assert!(error.contains("hook capture"), "{error}");
+ }
+
const KIRO_SESSION_A: &str = "3f6d1c2a-0000-4000-8000-000000000aaa";
const KIRO_SESSION_B: &str = "3f6d1c2a-0000-4000-8000-000000000bbb";
const KIRO_V3_SESSION: &str = "sess_c3774f9d-269e-40d1-aa02-2bb0c0817b4e";
diff --git a/docs/install.md b/docs/install.md
index 188dd24f..6690fe6a 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -9,7 +9,7 @@ path (docker + Claude Code). This page covers everything else:
- [Arch Linux native packages (AUR)](#arch-linux-native-packages-aur)
(systemd system service or user service)
- [Configuring other agent CLIs](#configuring-other-agent-clis)
- (Codex, Command Code, Devin CLI, OpenCode, OMP, Pi, Cursor, Claude Desktop, Gemini CLI, Antigravity CLI, Grok Build CLI, Zero, Kimi Code, Kiro CLI, OpenClaw, VS Code Copilot, Zed)
+ (Codex, Command Code, Devin CLI, OpenCode, OMP, Pi, Cursor, Claude Desktop, Gemini CLI, Antigravity CLI, Grok Build CLI, Zero, Kimi Code, Kiro CLI, OpenClaw, Swival CLI, VS Code Copilot, Zed)
- [Installing hooks without docker](#installing-hooks-without-docker)
(curl-based installer)
- [Running ai-memory without docker](#running-ai-memory-without-docker)
@@ -1053,20 +1053,35 @@ docker run --rm akitaonrails/ai-memory:latest \
docker run --rm akitaonrails/ai-memory:latest \
install-mcp --client zed --auth-token "$TOKEN" \
--server-url "http://homelab:49374/mcp"
+
+docker run --rm akitaonrails/ai-memory:latest \
+ install-mcp --client swival --auth-token "$TOKEN" \
+ --server-url "http://homelab:49374/mcp"
+
+docker run --rm akitaonrails/ai-memory:latest \
+ install-hooks --agent swival --auth-token "$TOKEN" \
+ --server-url "http://homelab:49374"
```
-Cursor, Gemini CLI, Antigravity CLI, Grok Build CLI, Kiro CLI, Command Code, and OpenClaw support both
+Cursor, Gemini CLI, Antigravity CLI, Grok Build CLI, Kiro CLI, Command Code, OpenClaw, and Swival support both
`install-mcp` and `install-hooks`. Grok's `install-mcp --client grok` writes
`$GROK_HOME/config.toml` (default `~/.grok/config.toml`); its hooks live under
`$GROK_HOME/hooks` (default `~/.grok/hooks`). `install-hooks --agent grok`
captures lifecycle events.
+`install-mcp --client swival` merges `.swival/mcp.json` in the current
+directory (Swival's documented default lookup); `install-hooks --agent swival`
+merges the single `lifecycle_command` into `~/.config/swival/config.toml` (or
+a project `swival.toml` via `--config-file`). Swival runs only
+`startup`/`exit` lifecycle events with positional args and no shell, so the
+installed command prefixes `env AI_MEMORY_HOOK_URL=…`.
Grok ignores `SessionStart` stdout, so handoffs must be accepted through MCP with
`memory_handoff_accept` when resuming. Claude Desktop, VS Code Copilot, and Zed
are MCP-only here, so you'll need to nudge the model to call
`memory_query` / `memory_handoff_accept` itself.
For clients with `install-hooks` support, the capture path handles
handoff injection at session start or the client's closest equivalent, except
-for Grok's (and Zero's) no-stdout SessionStart behavior (Antigravity CLI uses `PreInvocation`).
+for Grok's (and Zero's, and Swival's) no-stdout SessionStart behavior
+(Antigravity CLI uses `PreInvocation`).
---
@@ -1104,7 +1119,7 @@ docker run --rm akitaonrails/ai-memory:latest \
```
The curl script installer supports
-`--agent claude-code|codex|cursor|gemini-cli|antigravity-cli|grok|opencode|openclaw|omp|oh-my-pi|pi`
+`--agent claude-code|codex|cursor|gemini-cli|antigravity-cli|grok|opencode|openclaw|omp|oh-my-pi|pi|swival`
and `--to <dir>`; `--help` prints the full flag list. OpenCode,
OpenClaw, OMP / Oh My Pi, and Pi do not need script extraction because
`install-hooks` generates TypeScript plugin/extension files for them
diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.md
index 9c442d5b..431ea491 100644
--- a/docs/managed-workstreams.md
+++ b/docs/managed-workstreams.md
@@ -2,7 +2,7 @@
`ai-memory run` is an opt-in launcher that lets one logical coding session move
between Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, Command Code, Kiro
-CLI v2/v3, OMP, Grok Build CLI, and Antigravity CLI. Direct agent launches
+CLI v2/v3, OMP, Grok Build CLI, Antigravity CLI, and Swival CLI. 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.
@@ -42,7 +42,7 @@ file, and the current checkout remain authoritative.
ai-memory run [--workspace NAME] [--project NAME]
[--workstream NAME | --new NAME] [--executable PATH]
[--yolo] [--fresh]
- [claude|codex|opencode|pi|crush|omp|kimi|command-code|kiro|grok|antigravity]
+ [claude|codex|opencode|pi|crush|omp|kimi|command-code|kiro|grok|antigravity|swival]
[native arguments...]
```
@@ -130,7 +130,7 @@ takes precedence: ai-memory resumes the most recently linked harness that still
has a usable local session. It never chooses a newer but obsolete session from
another harness merely because that file has a later timestamp. Kiro's v2 and
v3 candidates share one server agent identity, but the selected native engine
-flavor remains exact. OMP, Grok, and Antigravity remain available explicitly
+flavor remains exact. OMP, Grok, Antigravity, and Swival remain available explicitly
but are not in the automatic pool.
Bare mode accepts wrapper options but not harness-native arguments or
@@ -238,6 +238,7 @@ is labelled completed evidence and must never be replayed as a pending call.
| OMP | native default creation | `--resume=<id>` | `~/.omp/agent/sessions/**/*.jsonl` |
| Grok Build CLI | generated `--session-id` | `--resume <id>` | `$GROK_HOME/sessions/*/*/chat_history.jsonl` |
| Antigravity CLI | native default creation | `--conversation <id>` | `~/.gemini/antigravity-cli/conversations/<id>.db` metadata plus lifecycle-hook capture |
+| Swival CLI | native default creation | none (resumes implicitly by cwd) | `<checkout>/.swival/HISTORY.md` (or `--cache-dir`) metadata plus lifecycle-hook capture |
Command Code v3 transcripts are self-describing and append-only. The adapter
requires the UUID filename, header id, and canonical header `cwd` to agree
@@ -276,8 +277,9 @@ the harness's native dangerous mode. The translation is Claude Code
`--dangerously-bypass-approvals-and-sandbox`, OpenCode `--auto`, Pi `--approve`,
Crush `--yolo`, Kimi Code `--yolo`, Command Code `--yolo`, Kiro CLI v2
`--trust-all-tools`, Grok Build CLI `--yolo` (equivalent to its
-`--always-approve` option), and Antigravity CLI
-`--dangerously-skip-permissions`. Kiro v3 replaced the trust-all flag with
+`--always-approve` option), Antigravity CLI
+`--dangerously-skip-permissions`, and Swival CLI `--yolo`
+(its own shorthand for `--files all --commands all`). Kiro v3 replaced the trust-all flag with
`permissions.yaml`, so ai-memory prints a notice and adds no unverified flag.
OMP currently needs no added flag. ai-memory does not add a duplicate when the
translated native flag is already present.
@@ -405,6 +407,22 @@ fails with a message saying so. The managed launcher accepts `antigravity`,
Antigravity CLI v1.1.7. Antigravity is not part of the no-argument
auto-detection set; name it explicitly.
+Swival keeps its whole store in `<checkout>/.swival/` (relocatable with
+`--cache-dir`), and the fixed rollup stem `HISTORY.md` doubles as the native
+session id. Discovery and listing therefore read one file under the current
+checkout, and other checkouts never leak into the chooser. Swival accepts no
+caller-chosen id and has no resume selector, so a fresh launch injects nothing
+and the session is linked by the hooks or discovered after exit. `--yolo` maps
+to Swival's own `--files all --commands all` shorthand, and utility invocations
+(`--init-config`, `--logout`, `--list-profiles`, `--version`, `skills`,
+`--serve`, `--acp`) pass through untouched. HISTORY.md is a rolling
+transcript-free rollup, so ai-memory does not decode conversation text: the
+visible-event ledger for this harness comes from lifecycle-hook capture, and
+transcript export fails with a message saying so. A positional task makes the
+launch non-interactive; an empty invocation starts Swival's REPL. The managed
+launcher accepts `swival`. Swival is not part of the no-argument
+auto-detection set; name it explicitly.
+
Crush needs no ai-memory hook installation for managed mode. The launcher reads
its one-time context from the server, copies the existing global Crush JSON into
a private temporary directory, appends an ephemeral context path, and points the
diff --git a/docs/mcp-install.md b/docs/mcp-install.md
index c493f264..3648a91c 100644
--- a/docs/mcp-install.md
+++ b/docs/mcp-install.md
@@ -601,6 +601,50 @@ capture and session-end handoff *creation* work, but handoff *injection*
does not — ask Zero to call `memory_handoff_accept` at the start of a
resumed session.
+## Swival CLI
+
+**Status:** ✅ MCP supported. ✅ Lifecycle hooks supported via
+`ai-memory install-hooks --agent swival --apply`. ❌ No automatic handoff
+injection (Swival captures hook stdout but never puts it in the model
+context — same policy as Zero/Grok; recover handoffs through
+`memory_handoff_accept`).
+
+**Config file:** Swival reads the project-scoped `.swival/mcp.json` by
+default (its own documented default lookup), so `install-mcp --client
+swival --apply` merges under that path in the current directory. The TOML
+alternative is a `[mcp_servers.ai-memory]` table in `swival.toml` or
+`~/.config/swival/config.toml`, which wins by name when both exist — pass
+`--config-file` to target it explicitly.
+
+```bash
+ai-memory install-mcp --client swival --apply --server-url "http://homelab:49374/mcp" --auth-token "$TOKEN"
+```
+
+which merges into `.swival/mcp.json`:
+
+```json
+{
+ "mcpServers": {
+ "ai-memory": {
+ "type": "http",
+ "url": "http://homelab:49374/mcp",
+ "headers": { "Authorization": "Bearer <token>" }
+ }
+ }
+}
+```
+
+Lifecycle capture is a single hook: `ai-memory install-hooks --agent swival
+--apply` merges `lifecycle_command` into `~/.config/swival/config.toml` (or
+a project `swival.toml` via `--config-file`). Swival runs the command as
+`<command> startup <base_dir>` / `<command> exit <base_dir>` with
+`cwd = base_dir` and `SWIVAL_*` env — the installed command prefixes an
+`env AI_MEMORY_HOOK_URL=…` so the shim can post the server without a shell.
+Only `startup`/`exit` events exist (no tool/prompt/compaction hooks), and
+Swival discards hook stdout, so handoffs must be recovered explicitly:
+ask the model to call `memory_handoff_accept` after a resumed session
+starts.
+
## Grok Build CLI
**Status:** ✅ MCP supported. ✅ Lifecycle hooks supported via
@@ -1091,8 +1135,8 @@ that *starts* the next one - to play nicely with ai-memory:
| Side | What's needed | Covered by |
|---|---|---|
-| **Ending side** | The agent must create a handoff through a true session-end hook, the manual finalizer, or `memory_handoff_begin`. | Built-in automatically for Claude Code, Devin CLI, Cursor, Gemini CLI, Grok Build CLI, Zero, Kimi Code, OpenClaw, OpenCode, and OMP. Codex, Antigravity CLI, both Kiro CLI engines, and Command Code have no reliable true session-end event; run `ai-memory finalize-session` with the corresponding `--agent` after the final turn. |
-| **Starting side** | Either (a) the session-start/plugin path injects the handoff via `/handoff`, OR (b) the model proactively calls `memory_handoff_accept` on first turn. | (a) is built-in for Claude Code / Codex / Devin CLI / Cursor / Gemini CLI / Antigravity CLI / Kimi Code / both Kiro CLI engines / Command Code / OpenClaw / OpenCode / OMP. It requires a client that consumes startup-hook stdout or an equivalent context-injection result. Grok and Zero are explicitly excluded because they discard SessionStart stdout; use (b). (b) works for any MCP-capable client if you nudge the model - see [the managed routing package](usage.md#install-the-routing-snippet-and-agent-skills). |
+| **Ending side** | The agent must create a handoff through a true session-end hook, the manual finalizer, or `memory_handoff_begin`. | Built-in automatically for Claude Code, Devin CLI, Cursor, Gemini CLI, Grok Build CLI, Zero, Kimi Code, OpenClaw, OpenCode, Swival CLI, and OMP. Codex, Antigravity CLI, both Kiro CLI engines, and Command Code have no reliable true session-end event; run `ai-memory finalize-session` with the corresponding `--agent` after the final turn. |
+| **Starting side** | Either (a) the session-start/plugin path injects the handoff via `/handoff`, OR (b) the model proactively calls `memory_handoff_accept` on first turn. | (a) is built-in for Claude Code / Codex / Devin CLI / Cursor / Gemini CLI / Antigravity CLI / Kimi Code / both Kiro CLI engines / Command Code / OpenClaw / OpenCode / OMP. It requires a client that consumes startup-hook stdout or an equivalent context-injection result. Grok, Zero, and Swival are explicitly excluded because they discard (or never inject) SessionStart stdout; use (b). (b) works for any MCP-capable client if you nudge the model - see [the managed routing package](usage.md#install-the-routing-snippet-and-agent-skills). |
OpenCode uses its official `session.deleted` plugin event for true session-end
delivery. Its generated plugin also sends a deduped best-effort close for any
diff --git a/hooks/swival/lifecycle.sh b/hooks/swival/lifecycle.sh
new file mode 100755
index 00000000..555b4ee4
--- /dev/null
+++ b/hooks/swival/lifecycle.sh
@@ -0,0 +1,37 @@
+#!/bin/sh
+# Swival lifecycle hook (issue #385).
+#
+# Swival invokes `lifecycle_command` as positional args —
+# <command> startup <base_dir>
+# <command> exit <base_dir>
+# — with the base_dir as cwd and SWIVAL_* env vars (SWIVAL_HOOK_EVENT,
+# SWIVAL_BASE_DIR, ...). There is NO stdin payload.
+#
+# Swival captures hook stdout but never injects it into the model context,
+# so this script only records the event. It never fetches /handoff:
+# accepting a handoff is destructive and Swival would discard the output.
+# Recover the prior session's handoff via the MCP memory_handoff_accept tool.
+_lib_dir="$(dirname "$0")"
+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."
+. "$_lib_dir/_lib.sh"
+
+event="$1"
+base_dir="$2"
+[ -n "$event" ] || exit 0
+[ -n "$base_dir" ] || exit 0
+
+SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"
+QS=$(ai_memory_marker_qs "$base_dir")
+
+case "$event" in
+ startup)
+ printf '{}' \
+ | ai_memory_post_hook "$SERVER/hook?event=session-start&agent=swival${QS}" >/dev/null 2>&1 || true
+ ;;
+ exit)
+ printf '{}' \
+ | ai_memory_post_hook "$SERVER/hook?event=session-end&agent=swival${QS}" >/dev/null 2>&1 || true
+ ;;
+esac
+printf '{}\n'
+exit 0
diff --git a/tests/hooks/test_lib.sh b/tests/hooks/test_lib.sh
index f1c6afda..b285906b 100755
--- a/tests/hooks/test_lib.sh
+++ b/tests/hooks/test_lib.sh
@@ -144,6 +144,29 @@ PS_ANTIGRAVITY_STATIC=$(grep -q 'function Test-AiMemoryAntigravityInitialInvocat
&& printf 'ok' || printf 'missing')
assert_eq "powershell antigravity hook has invocation guard" "ok" "$PS_ANTIGRAVITY_STATIC"
+# --- swival lifecycle shim (issue #385) --------------------------------
+# Swival invokes `lifecycle_command startup|exit <base_dir>` with cwd =
+# base_dir and no stdin; the shim maps those positional args to hook events,
+# resolves marker scope from base_dir, and MUST never fetch /handoff (Swival
+# discards hook stdout, so accepting would throw the context away).
+rm -f "$FAKE_CURL_LOG"
+SW_OUTPUT=$(PATH="$FAKE_CURL_BIN:$PATH" AI_MEMORY_CURL_LOG="$FAKE_CURL_LOG" \
+ AI_MEMORY_HOOK_URL='http://memory.test' sh hooks/swival/lifecycle.sh startup "$TMP/a/b/c")
+assert_eq "swival startup returns empty hook output" "{}" "$SW_OUTPUT"
+assert_eq "swival startup posts session-start without fetching handoff" "1" \
+ "$(wc -l <"$FAKE_CURL_LOG" | tr -d ' ')"
+assert_eq "swival startup posts session-start event" "yes" \
+ "$(grep -q 'hook?event=session-start&agent=swival&cwd=' "$FAKE_CURL_LOG" && printf 'yes' || printf 'no')"
+assert_eq "swival startup never fetches handoff" "no" \
+ "$(grep -q '/handoff' "$FAKE_CURL_LOG" && printf 'yes' || printf 'no')"
+
+rm -f "$FAKE_CURL_LOG"
+SW_EXIT=$(PATH="$FAKE_CURL_BIN:$PATH" AI_MEMORY_CURL_LOG="$FAKE_CURL_LOG" \
+ AI_MEMORY_HOOK_URL='http://memory.test' sh hooks/swival/lifecycle.sh exit "$TMP/a/b/c")
+assert_eq "swival exit returns empty hook output" "{}" "$SW_EXIT"
+assert_eq "swival exit posts session-end event" "yes" \
+ "$(grep -q 'hook?event=session-end&agent=swival&cwd=' "$FAKE_CURL_LOG" && printf 'yes' || printf 'no')"
+
# --- json_string -------------------------------------------------------
JSON_INPUT='quoted "thing" \ path
next line'