Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(cli): harden project-first managed launches
AkitaOnRailsb75699f2b3ee
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 38df662f..bc974578 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Added+- Added `ai-memory show`, a project-first managed launcher that joins private+ client-local checkout links with public server project metadata and a bounded+ local scan, then launches an installed harness without changing the parent+ process directory. It supports discovery-only `--json`, stages new projects+ atomically with routing and Agent Skills, keeps remote-server filesystem paths+ private, refreshes links after successful managed prepares and CLI+ rename/move operations, and runs host-side through the Docker wrapper (#342).- Hook ingestion now recognizes Hermes Agent as a concrete session kind andunderstands its documented shell-hook `tool_name` / `tool_input` envelopefor bounded tool-family titles and capture exclusions. Migration V44 expandsdiff --git a/Cargo.lock b/Cargo.lockindex 40400ebf..c663d0e0 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -654,6 +654,15 @@ version = "1.0.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"+[[package]]+name = "convert_case"+version = "0.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9"+dependencies = [+ "unicode-segmentation",+]+[[package]]name = "core-foundation-sys"version = "0.8.7"@@ -723,15 +732,17 @@ checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"[[package]]name = "crossterm"-version = "0.28.1"+version = "0.29.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6"+checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b"dependencies = ["bitflags","crossterm_winapi",+ "derive_more",+ "document-features","mio","parking_lot",- "rustix 0.38.44",+ "rustix","signal-hook","signal-hook-mio","winapi",@@ -817,6 +828,28 @@ dependencies = ["powerfmt",]+[[package]]+name = "derive_more"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"+dependencies = [+ "derive_more-impl",+]++[[package]]+name = "derive_more-impl"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"+dependencies = [+ "convert_case",+ "proc-macro2",+ "quote",+ "rustc_version",+ "syn",+]+[[package]]name = "digest"version = "0.10.7"@@ -859,6 +892,15 @@ dependencies = ["syn",]+[[package]]+name = "document-features"+version = "0.2.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61"+dependencies = [+ "litrs",+]+[[package]]name = "dyn-clone"version = "1.0.20"@@ -1685,12 +1727,6 @@ dependencies = ["vcpkg",]-[[package]]-name = "linux-raw-sys"-version = "0.4.15"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"-[[package]]name = "linux-raw-sys"version = "0.12.1"@@ -1703,6 +1739,12 @@ version = "0.8.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"+[[package]]+name = "litrs"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092"+[[package]]name = "lock_api"version = "0.4.14"@@ -2469,16 +2511,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe"[[package]]-name = "rustix"-version = "0.38.44"+name = "rustc_version"+version = "0.4.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"dependencies = [- "bitflags",- "errno",- "libc",- "linux-raw-sys 0.4.15",- "windows-sys 0.52.0",+ "semver",][[package]]@@ -2490,7 +2528,7 @@ dependencies = ["bitflags","errno","libc",- "linux-raw-sys 0.12.1",+ "linux-raw-sys","windows-sys 0.61.2",]@@ -2897,7 +2935,7 @@ dependencies = ["fastrand","getrandom 0.4.2","once_cell",- "rustix 1.1.4",+ "rustix","windows-sys 0.61.2",]@@ -3286,6 +3324,12 @@ version = "1.0.24"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"+[[package]]+name = "unicode-segmentation"+version = "1.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"+[[package]]name = "unicode-xid"version = "0.2.6"@@ -3997,7 +4041,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"dependencies = ["libc",- "rustix 1.1.4",+ "rustix",][[package]]diff --git a/Cargo.toml b/Cargo.tomlindex cfe8e1f5..41716941 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -80,7 +80,7 @@ clap_complete = "4"# and only styles text, it cannot read arrow keys. crossterm is the portable# option that keeps one code path across Linux, macOS, and Windows consoles# instead of a `#[cfg]` split over termios and the Win32 console API.-crossterm = "0.28"+crossterm = "0.29"dirs = "5"# Format-preserving TOML editor for install-mcp --apply against# Codex's config.toml. Plain `toml` round-trips destroy comments;diff --git a/README.md b/README.mdindex 45486e44..0e0d8d1d 100644--- a/README.md+++ b/README.md@@ -185,38 +185,39 @@ priors are at the [bottom](#influences-and-prior-art).ai-memory run --fresh codex```-- **"Pick the project instead of remembering where it lives."** Project scope- comes from the working directory, so launching from a parent directory that- holds many checkouts resolves all of them into that parent's basename. Start- from the menu instead, from anywhere:+- **"Pick the project instead of remembering where it lives."** Start from a+ directory containing your checkouts and choose the checkout before the+ managed harness:```bashai-memory show++ # Machine-readable discovery without launching anything.+ ai-memory show --json```- The menu merges two sources: projects ai-memory already tracks (newest- activity first, with page counts) and a fast depth-1 scan of the current- directory for anything carrying a project marker (`.git`, `Cargo.toml`,- `package.json`, `go.mod`, `pyproject.toml`, and friends). Dependency and build- directories are skipped. So running it from a folder full of checkouts works- on day one, before ai-memory has seen any of them — pick one, pick a harness,- and it enters that directory and hands off to `ai-memory run`.+ Each successful `ai-memory run` saves a client-local checkout link keyed by+ the configured server plus workspace/project. `show` joins those links with+ the server's public activity and page-count metadata. A fast, bounded depth-1+ scan of the current directory also finds new checkouts carrying a project+ marker (`.git`, `Cargo.toml`, `package.json`, `go.mod`, `pyproject.toml`, and+ friends), while skipping dependency and build directories. The server never+ exposes a checkout path, so two client machines can safely use different+ local paths for the same project on a remote homeserver.The list always leads with **`+ New project`**: type a name and ai-memory- creates the directory, pins the workspace and project in a `.ai-memory.toml`- marker, and installs the routing block and managed Agent Skills into the- instruction file the agent you picked actually reads — then launches it there.- So a brand-new project starts with its memory context already wired, without a- `mkdir` / `install-instructions` detour.+ validates a portable directory name, stages the new checkout privately, pins+ its workspace and project in `.ai-memory.toml`, and installs the routing block+ and managed Agent Skills for the chosen agent. The final directory appears+ only after every setup step succeeds, then `show` launches from it.The harness menu only offers agents actually installed on the host, using thesame `PATH` lookup `run` enforces at launch.- `--no-scan` restricts the list to tracked projects; `--workspace` narrows that- half; `--yolo`, `--fresh`, and any trailing native arguments are forwarded- unchanged. With output redirected it prints the same candidates as- tab-separated lines instead of drawing a menu, so `ai-memory show | grep …`- works; launching from a script stays the job of `ai-memory run <harness>`.+ `--no-scan` uses only saved links; `--workspace` filters both sources;+ `--yolo`, `--fresh`, and trailing native arguments are forwarded unchanged.+ Non-terminal use must pass `--json`; JSON mode is discovery-only and never+ launches a harness.The first explicit run can offer an existing session from this exact checkoutor start a new one. Switching harnesses starts or resumes the native session@@ -539,10 +540,10 @@ one matching entry.MCP/hooks. Explicit `--server-url` flags still work, but are no longerrequired when the env vars are set. Any non-loopback server should usebearer auth.-- **Managed-run wrapper:** `ai-memory run` must be intercepted by the current- host wrapper so the native harness and its session store remain accessible.- An old wrapper may pass `run` into Docker and fail with `No such file or- directory` for `codex`, `claude`, or another host executable. Run+- **Managed-launch wrapper:** `ai-memory run` and `ai-memory show` must be+ intercepted by the current host wrapper so local checkouts, native harnesses,+ and session stores remain accessible. An old wrapper may pass either command+ into Docker and fail to find a checkout or host executable. Run`ai-memory upgrade` on the agent machine to refresh it. The host-native runnerinherits `AI_MEMORY_SERVER_URL`, `AI_MEMORY_AUTH_TOKEN`, and the host `PATH`.- **Upgrades:** for Docker-wrapper installs, run `ai-memory upgrade` on eachdiff --git a/bin/ai-memory b/bin/ai-memoryindex 3b69e8e0..23328a09 100755--- a/bin/ai-memory+++ b/bin/ai-memory@@ -10,6 +10,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.+# ai-memory show ... Use that client for host project/harness discovery.## Env overrides:# AI_MEMORY_IMAGE docker image (default: akitaonrails/ai-memory:latest)@@ -22,7 +23,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)+# AI_MEMORY_NATIVE_BIN native ai-memory binary used for `run`/`show` (optional)# AI_MEMORY_WRAPPER_URL wrapper release asset override (optional; its# .sha256 companion is required)# AI_MEMORY_WRAPPER_SHA256_URL wrapper checksum URL override (optional)@@ -223,10 +224,10 @@ cmd_upgrade() {touch "${VERSION_CHECK_FILE}"}-# `ai-memory run` must execute on the host: native harnesses and their-# native transcript stores are host resources, not contents of the helper+# `ai-memory run` and `show` must execute on the host: checkouts, harnesses,+# and 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() {+native_host_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@@ -242,7 +243,7 @@ native_run_binary() {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+ echo "install the native release binary to use ai-memory run/show" >&2return 1;;esac@@ -250,7 +251,7 @@ native_run_binary() {x86_64 | amd64) arch="x86_64" ;;aarch64 | arm64) arch="aarch64" ;;*)- echo "ai-memory: no managed-run release binary is published for $(uname -m)" >&2+ echo "ai-memory: no host-launch release binary is published for $(uname -m)" >&2return 1;;esac@@ -279,13 +280,13 @@ native_run_binary() {if [ "${need_refresh}" -eq 1 ]; thencommand -v curl >/dev/null 2>&1 || {- echo "ai-memory: curl is required to install the native managed-run client" >&2+ echo "ai-memory: curl is required to install the native host-launch client" >&2return 1}tmp="${native_dir}/.install-$$"rm -rf "${tmp}"mkdir -p "${tmp}"- echo "ai-memory: installing checksum-verified native managed-run client (${artifact})" >&2+ echo "ai-memory: installing checksum-verified native host-launch client (${artifact})" >&2curl -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@@ -294,7 +295,7 @@ native_run_binary() {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+ echo "ai-memory: native host-launch client checksum mismatch" >&2rm -rf "${tmp}"return 1}@@ -317,10 +318,11 @@ case "${1:-}" incmd_upgradeexit 0;;- run)+ run | show)+ NATIVE_HOST_COMMAND=$1shift- NATIVE_RUN_BIN=$(native_run_binary)- exec "${NATIVE_RUN_BIN}" run "$@"+ NATIVE_HOST_BIN=$(native_host_binary)+ exec "${NATIVE_HOST_BIN}" "${NATIVE_HOST_COMMAND}" "$@";;esacdiff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 985c6964..e8f1b753 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -37,8 +37,8 @@ pub enum Command {/// Native arguments are forwarded except exact wrapper flags such as/// `--yolo` and `--fresh`.Run(RunArgs),- /// Pick a known project and harness from an interactive menu, then launch- /// it there. Removes the `cd` step `run` requires.+ /// Pick a local project and installed harness, then launch from that+ /// checkout. Removes the `cd` step `run` requires.Show(ShowArgs),/// Search the complete visible event ledger for a managed workstream.WorkstreamSearch(WorkstreamSearchArgs),@@ -242,13 +242,16 @@ pub enum RunHarnessChoice {/// Arguments for `show`.#[derive(Debug, Args)]pub struct ShowArgs {- /// Only list projects from this workspace. Defaults to every workspace.+ /// Only list local projects resolving to this workspace.#[arg(long)]pub workspace: Option<String>,- /// List only projects the server already tracks, skipping the depth-1- /// scan of the current directory for untracked project directories.+ /// Use saved local checkout links only; skip the depth-1 directory scan.#[arg(long)]pub no_scan: bool,+ /// Print structured project and harness choices instead of opening menus.+ /// Required when stdin or stdout is not a terminal.+ #[arg(long)]+ pub json: bool,/// Disable native permission prompts using the selected harness's/// equivalent dangerous-mode option. Forwarded to `run`.#[arg(long)]@@ -1703,6 +1706,36 @@ mod tests {);}+ #[test]+ fn show_parses_listing_and_launch_flags_without_consuming_native_args() {+ let listing = Cli::try_parse_from(["ai-memory", "show", "--json", "--no-scan"])+ .expect("show listing parses");+ let Command::Show(listing) = listing.command else {+ panic!("expected show command");+ };+ assert!(listing.json);+ assert!(listing.no_scan);++ let launch = Cli::try_parse_from([+ "ai-memory",+ "show",+ "--workspace",+ "team",+ "--yolo",+ "--fresh",+ "--model",+ "fast",+ ])+ .expect("show launch parses");+ let Command::Show(launch) = launch.command else {+ panic!("expected show command");+ };+ assert_eq!(launch.workspace.as_deref(), Some("team"));+ assert!(launch.yolo);+ assert!(launch.fresh);+ assert_eq!(launch.native_args, ["--model", "fast"]);+ }+#[test]fn claude_session_aware_mcp_flag_parses() {let cli = Cli::try_parse_from([diff --git a/crates/ai-memory-cli/src/commands/install_instructions.rs b/crates/ai-memory-cli/src/commands/install_instructions.rsindex 9ac6f509..7c30c44b 100644--- a/crates/ai-memory-cli/src/commands/install_instructions.rs+++ b/crates/ai-memory-cli/src/commands/install_instructions.rs@@ -40,6 +40,14 @@ const LEGACY_ORPHAN_TAIL_CRLF: &str =/// Returns an error if the target path can't be written or if the/// existing file isn't valid UTF-8.pub fn run(_config: &Config, args: InstallInstructionsArgs) -> Result<()> {+ run_inner(args, true)+}++pub(super) fn run_quiet(args: InstallInstructionsArgs) -> Result<()> {+ run_inner(args, false)+}++fn run_inner(args: InstallInstructionsArgs, report: bool) -> Result<()> {let block = full_block();let targets = resolve_targets(args.target.as_ref())?;let skill_args = if args.no_skills {@@ -66,21 +74,27 @@ pub fn run(_config: &Config, args: InstallInstructionsArgs) -> Result<()> {let outcome = apply_atomic(target, |existing| {Ok(merge_instructions_block(existing, &block))})?;- println!(- "✓ {} {} ({})",- outcome.verb(),- target.display(),- match outcome {- ApplyOutcome::Created => "new file",- ApplyOutcome::Updated => "backup written next to it",- ApplyOutcome::NoOp => "already up to date",- }- );+ if report {+ println!(+ "✓ {} {} ({})",+ outcome.verb(),+ target.display(),+ match outcome {+ ApplyOutcome::Created => "new file",+ ApplyOutcome::Updated => "backup written next to it",+ ApplyOutcome::NoOp => "already up to date",+ }+ );+ }}}if let Some(prepared_skills) = prepared_skills {- install_skills::run_prepared(prepared_skills)?;+ if report {+ install_skills::run_prepared(prepared_skills)?;+ } else {+ install_skills::run_prepared_quiet(prepared_skills)?;+ }}Ok(())diff --git a/crates/ai-memory-cli/src/commands/install_skills.rs b/crates/ai-memory-cli/src/commands/install_skills.rsindex 4e3a3b6e..4a4ca260 100644--- a/crates/ai-memory-cli/src/commands/install_skills.rs+++ b/crates/ai-memory-cli/src/commands/install_skills.rs@@ -69,6 +69,11 @@ pub(super) fn run_prepared(prepared: PreparedInstall) -> Result<()> {Ok(())}+pub(super) fn run_prepared_quiet(prepared: PreparedInstall) -> Result<()> {+ let _ = apply_prepared_install(prepared)?;+ Ok(())+}+fn print_reports(reports: Vec<InstallReport>) {for report in reports {println!(diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rsindex 99de398a..d52fdb35 100644--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@ -37,6 +37,7 @@ pub mod move_project;pub mod openclaw_plugin;pub mod path_util;pub mod pending_writes;+pub mod project_registry;pub mod purge_project;pub mod read_page;pub mod reindex;@@ -149,6 +150,51 @@ pub(crate) fn resolve_scope(Ok((workspace, project))}+/// Resolve `(workspace, project)` for an explicit local directory without+/// changing the process working directory or consulting wrapper cwd overrides.+///+/// The policy matches [`resolve_scope`]: a marker may pin either half, an+/// unpinned project under a marker follows that marker's strategy, and a tree+/// without a scope marker falls back to the main repository root.+pub(crate) fn resolve_scope_for_path(+ config: &Config,+ cwd: &std::path::Path,+) -> Result<(String, String)> {+ let cwd = cwd+ .canonicalize()+ .with_context(|| format!("canonicalizing project candidate {}", cwd.display()))?;+ let identity = cwd.to_string_lossy().into_owned();+ let marker = crate::marker::read_scope(&identity, &config.runtime_env);+ let workspace = marker+ .as_ref()+ .and_then(|scope| scope.workspace.clone())+ .unwrap_or_else(|| crate::config::DEFAULT_WORKSPACE.to_string());+ let project = match marker.as_ref() {+ Some(scope) => scope+ .project+ .clone()+ .or_else(|| {+ if scope.is_repo_root() {+ crate::marker::repo_root_project(&identity)+ } else {+ ai_memory_consolidate::derive_project_name(+ &cwd,+ ai_memory_consolidate::ProjectNameStrategy::Basename,+ )+ .map(|(name, _)| name)+ }+ })+ .ok_or_else(|| anyhow!("could not derive project name from {}", cwd.display()))?,+ None => ai_memory_consolidate::derive_project_name(+ &cwd,+ ai_memory_consolidate::ProjectNameStrategy::MainRepoRoot,+ )+ .map(|(name, _)| name)+ .ok_or_else(|| anyhow!("could not derive project name from {}", cwd.display()))?,+ };+ Ok((workspace, project))+}+/// Resolve only the workspace half, for the one command whose project half is/// deliberately absent (`embed --force` fans out across every project in the/// workspace). Resolving the pair there would make the command fail on the@@ -409,6 +455,50 @@ mod tests {);}+ #[test]+ fn explicit_path_scope_matches_marker_and_non_repo_fallback_policy() {+ let tmp = tempfile::TempDir::new().unwrap();+ let workspace_tree = tmp.path().join("workspace-tree");+ let workspace_child = workspace_tree.join("child");+ std::fs::create_dir_all(&workspace_child).unwrap();+ std::fs::write(+ workspace_tree.join(".ai-memory.toml"),+ "workspace = \"acme\"\n",+ )+ .unwrap();++ let pinned = tmp.path().join("pinned-checkout");+ std::fs::create_dir(&pinned).unwrap();+ std::fs::write(+ pinned.join(".ai-memory.toml"),+ "project = \"shared-project\"\n",+ )+ .unwrap();++ let plain = tmp.path().join("plain-checkout");+ std::fs::create_dir(&plain).unwrap();+ let config = Config::default();++ assert_eq!(+ resolve_scope_for_path(&config, &workspace_child).unwrap(),+ ("acme".to_owned(), "child".to_owned())+ );+ assert_eq!(+ resolve_scope_for_path(&config, &pinned).unwrap(),+ (+ crate::config::DEFAULT_WORKSPACE.to_owned(),+ "shared-project".to_owned()+ )+ );+ assert_eq!(+ resolve_scope_for_path(&config, &plain).unwrap(),+ (+ crate::config::DEFAULT_WORKSPACE.to_owned(),+ "plain-checkout".to_owned()+ )+ );+ }+#[test]fn workspace_only_marker_uses_linked_worktree_directory_name() {let tmp = tempfile::TempDir::new().unwrap();diff --git a/crates/ai-memory-cli/src/commands/move_project.rs b/crates/ai-memory-cli/src/commands/move_project.rsindex 71058cd9..7435b935 100644--- a/crates/ai-memory-cli/src/commands/move_project.rs+++ b/crates/ai-memory-cli/src/commands/move_project.rs@@ -74,6 +74,21 @@ pub async fn run(config: &Config, args: MoveProjectArgs) -> Result<()> {let moved_via = report["moved_via"].as_str().unwrap_or("");let skipped_count = report["pages_skipped"].as_array().map_or(0, |s| s.len());+ if (moved_via == "true-move" || purged)+ && let Err(error) = super::project_registry::rekey_scope(+ config,+ &endpoint,+ &from_workspace,+ &project,+ &args.to_workspace,+ &project,+ )+ {+ eprintln!(+ "ai-memory: project moved, but the client-local checkout link could not be updated ({error:#})"+ );+ }+if moved_via == "true-move" {// Lossless: re-stamped in place, nothing copied or purged.println!(diff --git a/crates/ai-memory-cli/src/commands/project_registry.rs b/crates/ai-memory-cli/src/commands/project_registry.rsnew file mode 100644index 00000000..e80ea7f1--- /dev/null+++ b/crates/ai-memory-cli/src/commands/project_registry.rs@@ -0,0 +1,398 @@+//! Client-local checkout links for project-first managed launches.+//!+//! Server project rows intentionally do not expose `repo_path`: that path+//! belongs to the server host and can disclose private filesystem layout. A+//! client records the checkout it successfully used, keyed by the normalized+//! server identity plus `(workspace, project)`, so two machines may map the+//! same remote scope to different local directories.++use std::collections::HashSet;+use std::fs::{self, File, OpenOptions};+use std::path::{Path, PathBuf};++use anyhow::{Context, Result, bail};+use fs2::FileExt as _;+use serde::{Deserialize, Serialize};++use crate::config::Config;+use crate::http_client::ServerEndpoint;++const REGISTRY_VERSION: u32 = 1;+const MAX_REGISTRY_BYTES: u64 = 4 * 1024 * 1024;+const MAX_LINKS: usize = 10_000;+const REGISTRY_FILE: &str = "client-projects.json";+const REGISTRY_LOCK_FILE: &str = "client-projects.lock";++/// One server-scoped local checkout link.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub(super) struct ProjectLink {+ /// Normalized server origin and mount path, without credentials.+ pub(super) server: String,+ /// Remote workspace name.+ pub(super) workspace: String,+ /// Remote project name.+ pub(super) project: String,+ /// Canonical absolute path on this client.+ pub(super) path: PathBuf,+ /// Last successful managed prepare that refreshed this link.+ pub(super) linked_at: String,+}++#[derive(Debug, Serialize, Deserialize)]+struct ProjectRegistry {+ version: u32,+ links: Vec<ProjectLink>,+}++impl Default for ProjectRegistry {+ fn default() -> Self {+ Self {+ version: REGISTRY_VERSION,+ links: Vec::new(),+ }+ }+}++/// Return links belonging to the configured server.+pub(super) fn links_for_server(+ config: &Config,+ endpoint: &ServerEndpoint,+) -> Result<Vec<ProjectLink>> {+ let server = endpoint.identity();+ Ok(load_registry(®istry_path(config))?+ .links+ .into_iter()+ .filter(|link| link.server == server)+ .collect())+}++/// Record the checkout only after the server accepted a managed run prepare.+///+/// The path is canonicalized before persistence. A later picker rejects a+/// path whose canonical form has changed, which catches a removed checkout+/// replaced by a symlink before any harness is launched.+pub(super) fn record_prepared_checkout(+ config: &Config,+ endpoint: &ServerEndpoint,+ workspace: &str,+ project: &str,+ path: &Path,+) -> Result<()> {+ let canonical = path+ .canonicalize()+ .with_context(|| format!("canonicalizing checkout {}", path.display()))?;+ if !canonical.is_dir() {+ bail!("checkout is not a directory: {}", canonical.display());+ }+ let server = endpoint.identity();+ update_registry(config, |registry| {+ registry.links.retain(|link| {+ !(link.server == server && link.workspace == workspace && link.project == project)+ });+ registry.links.push(ProjectLink {+ server,+ workspace: workspace.to_owned(),+ project: project.to_owned(),+ path: canonical,+ linked_at: jiff::Timestamp::now().to_string(),+ });+ Ok(true)+ })+}++/// Move a local link after a successful server-side project rename or move.+///+/// If the destination already has a link, it wins. That is the safe behavior+/// for a copy-and-purge merge into an existing project: the destination's+/// established checkout must not be silently replaced by the source path.+pub(super) fn rekey_scope(+ config: &Config,+ endpoint: &ServerEndpoint,+ from_workspace: &str,+ from_project: &str,+ to_workspace: &str,+ to_project: &str,+) -> Result<()> {+ let server = endpoint.identity();+ update_registry(config, |registry| {+ let Some(source_index) = registry.links.iter().position(|link| {+ link.server == server+ && link.workspace == from_workspace+ && link.project == from_project+ }) else {+ return Ok(false);+ };+ let mut source = registry.links.remove(source_index);+ let destination_exists = registry.links.iter().any(|link| {+ link.server == server && link.workspace == to_workspace && link.project == to_project+ });+ if !destination_exists {+ source.workspace = to_workspace.to_owned();+ source.project = to_project.to_owned();+ source.linked_at = jiff::Timestamp::now().to_string();+ registry.links.push(source);+ }+ Ok(true)+ })+}++fn registry_path(config: &Config) -> PathBuf {+ config.data_dir.join(REGISTRY_FILE)+}++fn lock_path(config: &Config) -> PathBuf {+ config.data_dir.join(REGISTRY_LOCK_FILE)+}++fn update_registry(+ config: &Config,+ mutate: impl FnOnce(&mut ProjectRegistry) -> Result<bool>,+) -> Result<()> {+ fs::create_dir_all(&config.data_dir).with_context(|| {+ format!(+ "creating client data directory {}",+ config.data_dir.display()+ )+ })?;+ let lock = open_private_lock(&lock_path(config))?;+ lock.lock_exclusive()+ .context("locking client project registry")?;++ let path = registry_path(config);+ let mut registry = load_registry(&path)?;+ if mutate(&mut registry)? {+ if registry.links.len() > MAX_LINKS {+ bail!("client project registry exceeds {MAX_LINKS} links");+ }+ let mut rendered =+ serde_json::to_vec_pretty(®istry).context("serializing client project registry")?;+ rendered.push(b'\n');+ refuse_symlink(&path)?;+ ai_memory_wiki::write_atomic(&path, &rendered)+ .with_context(|| format!("writing client project registry {}", path.display()))?;+ make_private(&path)?;+ }+ Ok(())+}++fn load_registry(path: &Path) -> Result<ProjectRegistry> {+ refuse_symlink(path)?;+ let metadata = match fs::metadata(path) {+ Ok(metadata) => metadata,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {+ return Ok(ProjectRegistry::default());+ }+ Err(error) => return Err(error).with_context(|| format!("inspecting {}", path.display())),+ };+ if metadata.len() > MAX_REGISTRY_BYTES {+ bail!(+ "client project registry {} exceeds the {} byte limit",+ path.display(),+ MAX_REGISTRY_BYTES+ );+ }+ let bytes = fs::read(path).with_context(|| format!("reading {}", path.display()))?;+ let registry: ProjectRegistry = serde_json::from_slice(&bytes).with_context(|| {+ format!(+ "parsing {}; refusing to overwrite malformed client state",+ path.display()+ )+ })?;+ if registry.version != REGISTRY_VERSION {+ bail!(+ "unsupported client project registry version {} in {} (expected {})",+ registry.version,+ path.display(),+ REGISTRY_VERSION+ );+ }+ if registry.links.len() > MAX_LINKS {+ bail!("client project registry exceeds {MAX_LINKS} links");+ }+ let mut keys = HashSet::with_capacity(registry.links.len());+ for link in ®istry.links {+ if !keys.insert((&link.server, &link.workspace, &link.project)) {+ bail!(+ "duplicate client project registry key for {}/{}/{} in {}",+ link.server,+ link.workspace,+ link.project,+ path.display()+ );+ }+ }+ Ok(registry)+}++fn open_private_lock(path: &Path) -> Result<File> {+ refuse_symlink(path)?;+ let mut options = OpenOptions::new();+ options.create(true).read(true).write(true);+ #[cfg(unix)]+ {+ use std::os::unix::fs::OpenOptionsExt as _;+ options.mode(0o600);+ }+ options+ .open(path)+ .with_context(|| format!("opening client project registry lock {}", path.display()))+}++fn refuse_symlink(path: &Path) -> Result<()> {+ match fs::symlink_metadata(path) {+ Ok(metadata) if metadata.file_type().is_symlink() => {+ bail!(+ "refusing client project registry symlink {}",+ path.display()+ )+ }+ Ok(_) => Ok(()),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),+ Err(error) => Err(error).with_context(|| format!("inspecting {}", path.display())),+ }+}++#[cfg(unix)]+fn make_private(path: &Path) -> Result<()> {+ use std::os::unix::fs::PermissionsExt as _;+ fs::set_permissions(path, fs::Permissions::from_mode(0o600))+ .with_context(|| format!("restricting permissions on {}", path.display()))+}++#[cfg(not(unix))]+fn make_private(_path: &Path) -> Result<()> {+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ fn config_at(path: &Path) -> Config {+ Config {+ data_dir: path.to_path_buf(),+ ..Config::default()+ }+ }++ fn endpoint(url: &str) -> ServerEndpoint {+ ServerEndpoint::from_pair(Some(url.to_owned()), None)+ }++ #[test]+ fn links_are_isolated_by_server_and_scope() {+ let tmp = tempfile::TempDir::new().unwrap();+ let checkout = tmp.path().join("checkout");+ fs::create_dir(&checkout).unwrap();+ let config = config_at(&tmp.path().join("data"));+ let first = endpoint("http://memory-one:49374/root/");+ let second = endpoint("http://memory-two:49374");++ record_prepared_checkout(&config, &first, "default", "app", &checkout).unwrap();++ let links = links_for_server(&config, &first).unwrap();+ assert_eq!(links.len(), 1);+ assert_eq!(links[0].path, checkout.canonicalize().unwrap());+ assert!(links_for_server(&config, &second).unwrap().is_empty());+ }++ #[test]+ fn recording_the_same_key_replaces_only_that_link() {+ let tmp = tempfile::TempDir::new().unwrap();+ let first_path = tmp.path().join("first");+ let second_path = tmp.path().join("second");+ let other_path = tmp.path().join("other");+ for path in [&first_path, &second_path, &other_path] {+ fs::create_dir(path).unwrap();+ }+ let config = config_at(&tmp.path().join("data"));+ let endpoint = endpoint("http://memory:49374");++ record_prepared_checkout(&config, &endpoint, "default", "app", &first_path).unwrap();+ record_prepared_checkout(&config, &endpoint, "default", "other", &other_path).unwrap();+ record_prepared_checkout(&config, &endpoint, "default", "app", &second_path).unwrap();++ let links = links_for_server(&config, &endpoint).unwrap();+ assert_eq!(links.len(), 2);+ assert!(links.iter().any(|link| {+ link.project == "app" && link.path == second_path.canonicalize().unwrap()+ }));+ assert!(links.iter().any(|link| link.project == "other"));+ }++ #[test]+ fn malformed_registry_is_not_overwritten() {+ let tmp = tempfile::TempDir::new().unwrap();+ let data = tmp.path().join("data");+ let checkout = tmp.path().join("checkout");+ fs::create_dir_all(&data).unwrap();+ fs::create_dir(&checkout).unwrap();+ let path = data.join(REGISTRY_FILE);+ fs::write(&path, b"not json").unwrap();+ let config = config_at(&data);++ assert!(+ record_prepared_checkout(+ &config,+ &endpoint("http://memory:49374"),+ "default",+ "app",+ &checkout,+ )+ .is_err()+ );+ assert_eq!(fs::read(&path).unwrap(), b"not json");+ }++ #[test]+ fn duplicate_scope_keys_are_rejected_without_overwriting() {+ let tmp = tempfile::TempDir::new().unwrap();+ let data = tmp.path().join("data");+ let checkout = tmp.path().join("checkout");+ fs::create_dir_all(&data).unwrap();+ fs::create_dir(&checkout).unwrap();+ let path = data.join(REGISTRY_FILE);+ let duplicate = br#"{+ "version": 1,+ "links": [+ {"server":"http://memory:49374","workspace":"default","project":"app","path":"/one","linked_at":"2026-01-01T00:00:00Z"},+ {"server":"http://memory:49374","workspace":"default","project":"app","path":"/two","linked_at":"2026-01-02T00:00:00Z"}+ ]+}+"#;+ fs::write(&path, duplicate).unwrap();+ let config = config_at(&data);++ assert!(links_for_server(&config, &endpoint("http://memory:49374")).is_err());+ assert!(+ record_prepared_checkout(+ &config,+ &endpoint("http://memory:49374"),+ "default",+ "app",+ &checkout,+ )+ .is_err()+ );+ assert_eq!(fs::read(&path).unwrap(), duplicate);+ }++ #[test]+ fn rekey_preserves_an_existing_destination_link() {+ let tmp = tempfile::TempDir::new().unwrap();+ let source = tmp.path().join("source");+ let destination = tmp.path().join("destination");+ fs::create_dir(&source).unwrap();+ fs::create_dir(&destination).unwrap();+ let config = config_at(&tmp.path().join("data"));+ let endpoint = endpoint("http://memory:49374");+ record_prepared_checkout(&config, &endpoint, "from", "app", &source).unwrap();+ record_prepared_checkout(&config, &endpoint, "to", "app", &destination).unwrap();++ rekey_scope(&config, &endpoint, "from", "app", "to", "app").unwrap();++ let links = links_for_server(&config, &endpoint).unwrap();+ assert_eq!(links.len(), 1);+ assert_eq!(links[0].path, destination.canonicalize().unwrap());+ }+}diff --git a/crates/ai-memory-cli/src/commands/rename_project.rs b/crates/ai-memory-cli/src/commands/rename_project.rsindex 6824c74d..f98dc24d 100644--- a/crates/ai-memory-cli/src/commands/rename_project.rs+++ b/crates/ai-memory-cli/src/commands/rename_project.rs@@ -29,6 +29,13 @@ pub async fn run(config: &Config, args: RenameProjectArgs) -> Result<()> {});let summary: serde_json::Value = post_json(&endpoint, "/admin/rename-project", &body).await?;let pages = summary["pages"].as_u64().unwrap_or(0);+ if let Err(error) = super::project_registry::rekey_scope(+ config, &endpoint, &workspace, &from, &workspace, &args.to,+ ) {+ eprintln!(+ "ai-memory: project renamed, but the client-local checkout link could not be updated ({error:#})"+ );+ }println!("Renamed {}/{} → {}/{} ({} pages now under the new name).",workspace, from, workspace, args.to, pagesdiff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rsindex f4f23d71..11b18481 100644--- a/crates/ai-memory-cli/src/commands/run.rs+++ b/crates/ai-memory-cli/src/commands/run.rs@@ -73,7 +73,13 @@ impl HeartbeatHealth {/// Run one native harness and return its exact process exit code.pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {let cwd = std::env::current_dir().context("getting managed run working directory")?;- let repository = inspect_repository(&cwd)?;+ run_from(config, args, &cwd).await+}++/// Run one native harness from an explicit checkout without changing the+/// parent process's working directory.+pub(super) async fn run_from(config: &Config, args: RunArgs, cwd: &Path) -> Result<i32> {+ let repository = inspect_repository(cwd)?;let home = native_home(config).context("locating native harness session storage")?;let automatic_harness = args.harness.is_none();let mut native_args = args.native_args;@@ -116,8 +122,8 @@ pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {let may_adopt_native_session = args.new_workstream.is_none() && !force_fresh;let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;let prepare = PrepareManagedRunRequest {- workspace,- project,+ workspace: workspace.clone(),+ project: project.clone(),cwd: repository.cwd.to_string_lossy().into_owned(),repo_fingerprint: repository.repo_fingerprint,worktree_fingerprint: repository.worktree_fingerprint,@@ -143,6 +149,17 @@ pub async fn run(config: &Config, args: RunArgs) -> Result<i32> {return Err(error);}};+ if let Err(error) = super::project_registry::record_prepared_checkout(+ config,+ &endpoint,+ &workspace,+ &project,+ &repository.cwd,+ ) {+ eprintln!(+ "ai-memory: could not refresh the client-local project link ({error:#}); continuing the managed run"+ );+ }let run_path = format!("/workstream/runs/{}", prepared.run_id);macro_rules! acquired_try {($result:expr) => {diff --git a/crates/ai-memory-cli/src/commands/show.rs b/crates/ai-memory-cli/src/commands/show.rsindex aaaebee4..7709959d 100644--- a/crates/ai-memory-cli/src/commands/show.rs+++ b/crates/ai-memory-cli/src/commands/show.rs@@ -1,59 +1,28 @@-//! `ai-memory show` — pick a project and a harness, then launch it.+//! `ai-memory show` project and managed-harness picker.//!-//! Thin HTTP client for the listing half: calls `GET /api/v1/projects` and-//! renders the rows the server already aggregates. The launch half delegates-//! to [`crate::commands::run`] so managed workstreams, handoff delivery, and-//! native-argument forwarding keep exactly one implementation.-//!-//! The picker exists because project scope is resolved from the working-//! directory. Opening an agent from a parent directory that holds many-//! checkouts resolves every one of them to that parent's basename, so the-//! sessions pile into a single scope. Choosing the project first and entering-//! its recorded `repo_path` makes the scope explicit before the agent starts.+//! Remote project metadata is joined with a client-local checkout registry.+//! The server never sends host filesystem paths, and each client may map the+//! same remote scope to a different local checkout.-use std::io::{IsTerminal, Write};+use std::collections::HashMap;+use std::io::{IsTerminal as _, Write as _};use std::path::{Path, PathBuf};-use std::time::SystemTime;+use std::time::{SystemTime, UNIX_EPOCH};use anyhow::{Context, Result, bail};-use clap::ValueEnum;+use clap::ValueEnum as _;use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};-use crossterm::style::Stylize;+use crossterm::style::Stylize as _;use crossterm::{cursor, execute, terminal};-use serde::Deserialize;+use serde::{Deserialize, Serialize};-use crate::cli::{InstallInstructionsArgs, RunArgs, RunHarnessChoice, ShowArgs};-use crate::commands::apply_shared::apply_atomic;-use crate::commands::install_instructions;-use crate::config::Config;+use crate::cli::{+ InstallInstructionsArgs, InstallSkillsAgent, RunArgs, RunHarnessChoice, ShowArgs,+};+use crate::commands::{install_instructions, project_registry};+use crate::config::{Config, DEFAULT_WORKSPACE};use crate::http_client::{ServerEndpoint, get_json};-/// Server-shaped row. Mirrors `ai_memory_store::ProjectSummary`.-#[derive(Debug, Deserialize)]-struct ProjectRow {- /// Workspace the project belongs to.- workspace_name: String,- /// Project name within the workspace.- project_name: String,- /// Number of `is_latest = 1` pages.- page_count: u64,- /// ISO-8601 timestamp of the newest page update, when any page exists.- last_updated: Option<String>,- /// Absolute checkout path, when one was recorded.- repo_path: Option<String>,-}--/// One selectable line: what the user reads, plus the dimmed trailer.-struct Choice {- /// Primary label, rendered at full brightness.- label: String,- /// Secondary detail, rendered dim. Empty renders nothing.- detail: String,-}--/// Directory entries that mark a subdirectory as a project worth offering.-/// Matched by name, so recognising a candidate costs one `exists()` per marker-/// and never a directory walk.const PROJECT_MARKERS: [&str; 12] = [".git",".ai-memory.toml",@@ -68,16 +37,6 @@ const PROJECT_MARKERS: [&str; 12] = ["docker-compose.yml","compose.yml",];--/// Label of the always-present first entry that creates a project.-const NEW_PROJECT_LABEL: &str = "+ New project";--/// Workspace a created project is filed under when `--workspace` is absent.-/// Matches the scope resolver's own default, so a project created here lands-/// where a project created by the lifecycle hooks would.-const DEFAULT_WORKSPACE: &str = "default";--/// Directory names that hold dependencies or build output, never projects.const SKIPPED_DIRS: [&str; 8] = ["node_modules","target",@@ -88,129 +47,136 @@ const SKIPPED_DIRS: [&str; 8] = [".venv","__pycache__",];+const MAX_SCAN_ENTRIES: usize = 4096;+const NEW_PROJECT_LABEL: &str = "+ New project";++#[derive(Debug, Clone, Deserialize)]+struct ProjectRow {+ workspace_name: String,+ project_name: String,+ page_count: u64,+ last_updated: Option<String>,+}-/// One launchable entry: a project the server already tracks, or a directory-/// the scan just found.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum CandidateSource {+ Registry,+ Scan,+}++impl CandidateSource {+ const fn as_str(self) -> &'static str {+ match self {+ Self::Registry => "registry",+ Self::Scan => "scan",+ }+ }+}++#[derive(Debug, Clone)]struct Candidate {- /// Workspace name when the server already tracks this checkout. `None`- /// for a scanned directory, which lets `run` derive the scope from the- /// checkout itself exactly as the lifecycle hooks would.- workspace: Option<String>,- /// Project name: the server's for tracked rows, the directory name for- /// scanned ones.+ workspace: String,project: String,- /// Directory to enter before launching.path: PathBuf,- /// Dimmed trailer shown next to the label.+ source: CandidateSource,+ page_count: Option<u64>,+ last_updated: Option<String>,+ activity_us: Option<i64>,+}++impl Candidate {+ fn label(&self) -> String {+ terminal_text(&format!("{}/{}", self.workspace, self.project))+ }++ fn detail(&self) -> String {+ let path = terminal_text(&self.path.to_string_lossy());+ match self.page_count {+ Some(count) => format!(+ "{} | {count} page{} | {path}",+ humanize_age(self.last_updated.as_deref()),+ if count == 1 { "" } else { "s" }+ ),+ None => format!("local only | {path}"),+ }+ }+}++struct Choice {+ label: String,detail: String,}-/// Run the `show` subcommand.-///-/// # Errors-/// Returns an error if nothing launchable is found, stdin/stdout is not a-/// terminal, or the delegated launch fails. Returns the launched harness's-/// exit code.+#[derive(Serialize)]+struct JsonProject {+ workspace: String,+ project: String,+ path: String,+ source: &'static str,+ tracked: bool,+ page_count: Option<u64>,+ last_updated: Option<String>,+}++#[derive(Serialize)]+struct JsonOutput {+ server: String,+ projects: Vec<JsonProject>,+ harnesses: Vec<String>,+}++/// Pick a local checkout and harness, then delegate to managed `run`.pub async fn run(config: &Config, args: ShowArgs) -> Result<i32> {- let mut candidates = tracked_projects(config, args.workspace.as_deref()).await;-- // The scan is what makes the picker useful on a machine where ai-memory- // has not run yet: without it the menu stays empty until every project has- // been opened once the long way, which is the very step this command- // exists to remove.- if !args.no_scan {- let root = std::env::current_dir().context("reading the current directory")?;- let mut seen: Vec<PathBuf> = candidates.iter().map(|c| normalize(&c.path)).collect();- for path in scan_for_projects(&root) {- let key = normalize(&path);- if seen.contains(&key) {- continue;- }- let Some(project) = directory_name(&path) else {- continue;- };- seen.push(key);- candidates.push(Candidate {- workspace: None,- project,- path,- detail: "not tracked yet".to_string(),- });- }+ if args.json && (args.yolo || args.fresh || !args.native_args.is_empty()) {+ bail!("--json only lists launch options; do not combine it with launch arguments");}+ let root = std::env::current_dir()+ .context("reading the current directory")?+ .canonicalize()+ .context("canonicalizing the current directory")?;+ let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;+ let candidates = collect_candidates(+ config,+ &endpoint,+ &root,+ args.workspace.as_deref(),+ !args.no_scan,+ )+ .await;+ let harnesses = available_harnesses();- // Redirected output means nobody is there to press a key. Printing what- // the menu would have offered is more useful than refusing: it makes the- // list greppable, and `show` still answers "which projects can I launch?".- // Creating a project needs a name nobody can type here, so that entry is- // interactive-only and the printed list stays exactly the launchable set.- if !std::io::stdout().is_terminal() || !std::io::stdin().is_terminal() {- if candidates.is_empty() {- bail!(- "nothing to launch: the server tracks no project with a \- checkout path, and no project directory was found under {}. \- Run `ai-memory show` on a terminal to create one, or use \- `ai-memory run <harness>` directly",- std::env::current_dir()- .map(|p| p.display().to_string())- .unwrap_or_else(|_| "the current directory".to_string())- );- }- // Projects on stdout so the list stays greppable; the harness summary- // on stderr so it never contaminates a pipeline.- let detected: Vec<String> = RunHarnessChoice::value_variants()- .iter()- .filter(|choice| crate::commands::run::harness_available(**choice))- .map(|choice| harness_name(*choice))- .collect();- eprintln!(- "ai-memory: harnesses found in PATH: {}",- if detected.is_empty() {- "none".to_string()- } else {- detected.join(", ")- }- );- for candidate in &candidates {- println!(- "{}\t{}\t{}",- match &candidate.workspace {- Some(workspace) => format!("{workspace}/{}", candidate.project),- None => candidate.project.clone(),- },- candidate.path.display(),- candidate.detail- );- }+ if args.json {+ print_json(&endpoint, &candidates, &harnesses)?;return Ok(0);}+ if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() {+ bail!(+ "`ai-memory show` needs a terminal; use `ai-memory show --json` to list choices in scripts"+ );+ }+ if harnesses.is_empty() {+ bail!(+ "no supported managed harness was found in PATH (looked for: {})",+ RunHarnessChoice::value_variants()+ .iter()+ .map(|choice| harness_name(*choice))+ .collect::<Vec<_>>()+ .join(", ")+ );+ }- banner()?;-- // Creating a project leads the list because an empty machine has nothing- // else to offer, and because the alternative — leave the menu, `mkdir`,- // write a marker by hand, come back — is the same detour this command- // exists to remove.let mut project_choices = vec![Choice {- label: NEW_PROJECT_LABEL.to_string(),- detail: "create the directory and its agent context files".to_string(),+ label: NEW_PROJECT_LABEL.to_owned(),+ detail: "create a directory and install its agent context".to_owned(),}];- project_choices.extend(candidates.iter().map(|c| Choice {- label: match &c.workspace {- Some(workspace) => format!("{workspace}/{}", c.project),- None => c.project.clone(),- },- detail: c.detail.clone(),+ project_choices.extend(candidates.iter().map(|candidate| Choice {+ label: candidate.label(),+ detail: candidate.detail(),}));- let Some(picked) = select("Project", &project_choices)? else {+ let Some(project_index) = select("Project", &project_choices)? else {return Ok(0);};-- // Ask for the name before the harness question: the answer decides which- // directory the rest of the flow is about, and a name rejected after the- // harness pick would throw that pick away.- let root = std::env::current_dir().context("reading the current directory")?;- let new_project = if picked == 0 {+ let new_project = if project_index == 0 {let Some(name) = prompt_project_name(&root)? else {return Ok(0);};@@ -219,98 +185,41 @@ pub async fn run(config: &Config, args: ShowArgs) -> Result<i32> {None};- // Offering a harness that is not installed only moves the failure one step- // later, after the user has already committed to a project. Ask the same- // question `run` would ask at launch, and ask it before the menu.- let harnesses: Vec<RunHarnessChoice> = RunHarnessChoice::value_variants()+ let harness_choices = harnesses.iter()- .copied()- .filter(|choice| crate::commands::run::harness_available(*choice))- .collect();- if harnesses.is_empty() {- bail!(- "no supported agent harness was found in PATH (looked for: {}). \- Install one, or use `ai-memory run <harness> --executable <path>` \- for a harness installed somewhere else",- RunHarnessChoice::value_variants()- .iter()- .map(|h| harness_name(*h))- .collect::<Vec<_>>()- .join(", ")- );- }- let harness_choices: Vec<Choice> = harnesses- .iter()- .map(|h| Choice {- label: harness_name(*h),+ .map(|choice| Choice {+ label: harness_name(*choice),detail: String::new(),})- .collect();- let Some(picked_harness) = select(- &format!(- "Agent · {}",- new_project- .as_deref()- .unwrap_or(&project_choices[picked].label)- ),- &harness_choices,- )?- else {+ .collect::<Vec<_>>();+ let project_label = new_project+ .as_deref()+ .map(terminal_text)+ .unwrap_or_else(|| project_choices[project_index].label.clone());+ let Some(harness_index) = select(&format!("Agent | {project_label}"), &harness_choices)? else {return Ok(0);};- let harness = harnesses[picked_harness];-- // A created project pins nothing here: the marker written below already- // declares both scope halves, so letting `run` read it keeps one source of- // truth — the same one the lifecycle hooks will read on every later- // session, whether or not it was launched from this menu.- let (target, workspace, project) = match &new_project {- Some(name) => {- let workspace = args.workspace.as_deref().unwrap_or(DEFAULT_WORKSPACE);- (create_project(&root, name, workspace)?, None, None)- }- None => {- let chosen = &candidates[picked - 1];- if !chosen.path.is_dir() {- bail!(- "project {} records checkout {}, which no longer exists. \- Move it back, or launch from the new location once so the \- path is re-recorded",- chosen.project,- chosen.path.display()- );- }- // A tracked row pins both scope halves, so a marker in the target- // tree cannot retarget a launch the listing already resolved. A- // scanned directory deliberately passes neither: `run` then derives- // the scope from the checkout, honouring its `.ai-memory.toml`, and- // the first session lands in the same scope the hooks would have- // chosen on their own.- (- chosen.path.clone(),- chosen.workspace.clone(),- chosen.workspace.as_ref().map(|_| chosen.project.clone()),- )- }- };-- // Entering the checkout is what makes every cwd-derived resolution inside- // `run` (marker discovery, hook scope, transcript adoption) agree with the- // project the user just picked.- std::env::set_current_dir(&target).with_context(|| format!("entering {}", target.display()))?;+ let harness = harnesses[harness_index];- // After the `cd`, because project-scoped skills resolve their root from the- // working directory: installing from the parent would drop the skills next- // to the sibling checkouts instead of inside the new project.- if new_project.is_some() {- install_context_files(config, harness, &target)?;- }+ let (target, workspace, project) = if let Some(name) = new_project {+ let workspace = args.workspace.as_deref().unwrap_or(DEFAULT_WORKSPACE);+ let target = create_project(&root, &name, workspace, harness)?;+ (target, workspace.to_owned(), name)+ } else {+ let candidate = &candidates[project_index - 1];+ let target = revalidate_candidate(config, candidate)?;+ (+ target,+ candidate.workspace.clone(),+ candidate.project.clone(),+ )+ };- crate::commands::run::run(+ crate::commands::run::run_from(config,RunArgs {- workspace,- project,+ workspace: Some(workspace),+ project: Some(project),workstream: None,new_workstream: None,executable: None,@@ -319,155 +228,231 @@ pub async fn run(config: &Config, args: ShowArgs) -> Result<i32> {harness: Some(harness),native_args: args.native_args,},+ &target,).await}-/// Whether `name` is accepted by the server's workspace/project rule-/// (`^[a-z0-9][a-z0-9._-]*$`).-///-/// Checked here rather than at launch because a name the server rejects fails-/// inside the lifecycle hooks, as a warning on a session that already started —-/// long after the directory carrying that name exists on disk.-fn valid_scope_name(name: &str) -> bool {- let mut chars = name.chars();- let Some(first) = chars.next() else {- return false;+async fn collect_candidates(+ config: &Config,+ endpoint: &ServerEndpoint,+ root: &Path,+ workspace_filter: Option<&str>,+ scan: bool,+) -> Vec<Candidate> {+ let query = workspace_filter+ .filter(|value| !value.is_empty())+ .map_or_else(Vec::new, |workspace| vec![("workspace", workspace)]);+ let rows: Option<Vec<ProjectRow>> = match get_json(endpoint, "/api/v1/projects", &query).await {+ Ok(rows) => Some(rows),+ Err(error) => {+ eprintln!(+ "ai-memory: server project listing unavailable ({}); using client-local links and scan results",+ terminal_text(&format!("{error:#}"))+ );+ None+ }};- if !(first.is_ascii_lowercase() || first.is_ascii_digit()) {- return false;+ let stats = rows.as_ref().map(|rows| {+ rows.iter()+ .cloned()+ .map(|row| ((row.workspace_name.clone(), row.project_name.clone()), row))+ .collect::<HashMap<_, _>>()+ });++ let links = match project_registry::links_for_server(config, endpoint) {+ Ok(links) => links,+ Err(error) => {+ eprintln!(+ "ai-memory: client project registry unavailable ({}); using scan results",+ terminal_text(&format!("{error:#}"))+ );+ Vec::new()+ }+ };+ let mut candidates = Vec::new();+ let mut stale_warnings = 0usize;+ for link in links {+ if workspace_filter.is_some_and(|filter| filter != link.workspace) {+ continue;+ }+ let key = (link.workspace.clone(), link.project.clone());+ if stats+ .as_ref()+ .is_some_and(|known| !known.contains_key(&key))+ {+ continue;+ }+ let path = match validate_registered_path(&link.path) {+ Ok(path) => path,+ Err(error) => {+ if stale_warnings < 3 {+ eprintln!(+ "ai-memory: ignored stale client project link {}/{} ({})",+ terminal_text(&link.workspace),+ terminal_text(&link.project),+ terminal_text(&format!("{error:#}"))+ );+ }+ stale_warnings += 1;+ continue;+ }+ };+ let row = stats.as_ref().and_then(|known| known.get(&key));+ push_candidate(+ &mut candidates,+ candidate_from(+ path,+ link.workspace,+ link.project,+ CandidateSource::Registry,+ row,+ Some(&link.linked_at),+ ),+ );+ }+ if stale_warnings > 3 {+ eprintln!(+ "ai-memory: ignored {} additional stale client project links",+ stale_warnings - 3+ );}- chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '-' | '_'))-}-/// Marker contents pinning both scope halves for a freshly created project.-///-/// Both keys are written even though `project` defaults to the directory-/// basename: the default follows the directory, so a later rename or a-/// `cd` into a subdirectory would silently fork the memory into a second-/// project. Pinning them means the scope survives both.-fn marker_body(workspace: &str, project: &str) -> String {- format!(- "# Created by `ai-memory show`. Declares the scope every wiki page,\n\- # observation, and handoff from this directory is filed under.\n\- # Both keys are pinned on purpose: the defaults follow the directory\n\- # name, so renaming or working from a subdirectory would otherwise\n\- # start a second, empty project. See docs/marker-file.md.\n\- workspace = \"{workspace}\"\n\- project = \"{project}\"\n"- )+ if scan {+ for path in scan_for_projects(root) {+ let Ok((workspace, project)) = super::resolve_scope_for_path(config, &path) else {+ continue;+ };+ if workspace_filter.is_some_and(|filter| filter != workspace) {+ continue;+ }+ let key = (workspace.clone(), project.clone());+ let row = stats.as_ref().and_then(|known| known.get(&key));+ push_candidate(+ &mut candidates,+ candidate_from(path, workspace, project, CandidateSource::Scan, row, None),+ );+ }+ }+ candidates.sort_by(|left, right| {+ right+ .activity_us+ .cmp(&left.activity_us)+ .then_with(|| left.workspace.cmp(&right.workspace))+ .then_with(|| left.project.cmp(&right.project))+ .then_with(|| left.path.cmp(&right.path))+ });+ candidates}-/// Instruction file the routing block belongs in for `harness`.-///-/// Claude Code reads `CLAUDE.md`; every other supported harness converged on-/// `AGENTS.md`. Writing the one the chosen agent actually reads is what makes-/// the block take effect on the very first session.-const fn instruction_file(harness: RunHarnessChoice) -> &'static str {- match harness {- RunHarnessChoice::Claude => "CLAUDE.md",- _ => "AGENTS.md",+fn candidate_from(+ path: PathBuf,+ workspace: String,+ project: String,+ source: CandidateSource,+ row: Option<&ProjectRow>,+ local_activity: Option<&str>,+) -> Candidate {+ Candidate {+ workspace,+ project,+ activity_us: row+ .and_then(|row| timestamp_us(row.last_updated.as_deref()))+ .or_else(|| timestamp_us(local_activity))+ .or_else(|| directory_modified_us(&path)),+ page_count: row.map(|row| row.page_count),+ last_updated: row.and_then(|row| row.last_updated.clone()),+ path,+ source,}}-/// Create `name` under `parent` with its scope marker.-///-/// # Errors-/// Returns an error when the directory already exists or cannot be created,-/// or when the marker cannot be written.-fn create_project(parent: &Path, name: &str, workspace: &str) -> Result<PathBuf> {- // Both halves land inside a quoted TOML string, so an unchecked value can- // close the quote and append keys of its own. The name comes from the- // prompt, which already rejects it; `--workspace` reaches here verbatim and- // is checked at the same boundary, before anything is written.- for (label, value) in [("project name", name), ("workspace", workspace)] {- if !valid_scope_name(value) {- bail!(- "invalid {label} {value:?}: lowercase letters, digits, dot, dash and underscore only, starting with a letter or digit"- );+fn push_candidate(candidates: &mut Vec<Candidate>, candidate: Candidate) {+ if let Some(existing) = candidates+ .iter_mut()+ .find(|existing| existing.path == candidate.path)+ {+ if existing.page_count.is_none() && candidate.page_count.is_some() {+ existing.page_count = candidate.page_count;+ existing.last_updated = candidate.last_updated;+ existing.activity_us = candidate.activity_us;}+ return;}- let path = parent.join(name);- // `create_dir` rather than `create_dir_all`: it fails when the directory- // already exists, which is the check that keeps a mistyped name from- // adopting an unrelated tree between the prompt's look and this write.- std::fs::create_dir(&path)- .with_context(|| format!("creating project directory {}", path.display()))?;- apply_atomic(&path.join(".ai-memory.toml"), |_| {- Ok(marker_body(workspace, name))- })- .with_context(|| format!("writing the scope marker in {}", path.display()))?;- println!("✓ created {}", path.display());- Ok(path)+ candidates.push(candidate);}-/// Write the agent context files into the new project: the routing block in-/// the instruction file the chosen harness reads, plus the managed ai-memory-/// Agent Skills that block refers to.-///-/// Delegates to `install-instructions` so a project created here is byte-for--/// byte what `ai-memory install-instructions` produces, and stays that way as-/// the snippet evolves.-///-/// # Errors-/// Propagates instruction/skill installation failures.-fn install_context_files(config: &Config, harness: RunHarnessChoice, path: &Path) -> Result<()> {- install_instructions::run(- config,- InstallInstructionsArgs {- target: Some(path.join(instruction_file(harness))),- print: false,- no_skills: false,- skills_scope: None,- skills_agent: None,- skills_target_dir: None,- skills_force: false,- },- )+fn print_json(+ endpoint: &ServerEndpoint,+ candidates: &[Candidate],+ harnesses: &[RunHarnessChoice],+) -> Result<()> {+ let output = JsonOutput {+ server: endpoint.identity(),+ projects: candidates+ .iter()+ .map(|candidate| JsonProject {+ workspace: candidate.workspace.clone(),+ project: candidate.project.clone(),+ path: candidate.path.to_string_lossy().into_owned(),+ source: candidate.source.as_str(),+ tracked: candidate.page_count.is_some(),+ page_count: candidate.page_count,+ last_updated: candidate.last_updated.clone(),+ })+ .collect(),+ harnesses: harnesses+ .iter()+ .map(|choice| harness_name(*choice))+ .collect(),+ };+ let stdout = std::io::stdout();+ let mut out = stdout.lock();+ serde_json::to_writer_pretty(&mut out, &output).context("rendering project list JSON")?;+ writeln!(out)?;+ Ok(())}-/// Projects the server already tracks, newest activity first.-///-/// A listing failure is reported and treated as empty rather than fatal: the-/// scan alone still produces a usable menu, and a first run on a machine whose-/// server is not up yet is exactly when the picker is most useful.-async fn tracked_projects(config: &Config, workspace: Option<&str>) -> Vec<Candidate> {- let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;- let query: Vec<(&str, &str)> = match workspace {- Some(workspace) if !workspace.is_empty() => vec![("workspace", workspace)],- _ => Vec::new(),- };- let rows: Vec<ProjectRow> = match get_json(&endpoint, "/api/v1/projects", &query).await {- Ok(rows) => rows,- Err(error) => {- eprintln!("ai-memory: listing tracked projects failed ({error:#}); showing scan only");- return Vec::new();- }- };- rows.into_iter()- .filter_map(|row| {- // A row without `repo_path` has no directory to enter — it was- // created by explicit scope arguments, or its checkout moved.- let path = row.repo_path.filter(|p| !p.is_empty())?;- Some(Candidate {- detail: format!(- "{} · {} page{}",- humanize_age(row.last_updated.as_deref()),- row.page_count,- if row.page_count == 1 { "" } else { "s" }- ),- workspace: Some(row.workspace_name),- project: row.project_name,- path: PathBuf::from(path),- })- })+fn available_harnesses() -> Vec<RunHarnessChoice> {+ RunHarnessChoice::value_variants()+ .iter()+ .copied()+ .filter(|choice| crate::commands::run::harness_available(*choice)).collect()}-/// Immediate subdirectories of `root` that look like projects, plus `root`-/// itself when it is one. Depth 1 only — deep trees are what make a scan slow-/// enough to be noticed, and a workspace directory holds its checkouts flat.-fn scan_for_projects(root: &std::path::Path) -> Vec<PathBuf> {+fn validate_registered_path(path: &Path) -> Result<PathBuf> {+ if !path.is_absolute() {+ bail!("stored checkout path is not absolute");+ }+ let canonical = path+ .canonicalize()+ .with_context(|| format!("checkout {} no longer resolves", path.display()))?;+ if canonical != path {+ bail!("checkout path now resolves somewhere else");+ }+ if !canonical.is_dir() {+ bail!("checkout path is not a directory");+ }+ Ok(canonical)+}++fn revalidate_candidate(config: &Config, candidate: &Candidate) -> Result<PathBuf> {+ let path = validate_registered_path(&candidate.path)?;+ let (workspace, project) = super::resolve_scope_for_path(config, &path)?;+ if workspace != candidate.workspace || project != candidate.project {+ bail!(+ "checkout scope changed after it was listed: expected {}/{}, found {}/{}; rerun `ai-memory show`",+ terminal_text(&candidate.workspace),+ terminal_text(&candidate.project),+ terminal_text(&workspace),+ terminal_text(&project)+ );+ }+ Ok(path)+}++fn scan_for_projects(root: &Path) -> Vec<PathBuf> {let mut found = Vec::new();if is_project_dir(root) {found.push(root.to_path_buf());@@ -475,176 +460,216 @@ fn scan_for_projects(root: &std::path::Path) -> Vec<PathBuf> {let Ok(entries) = std::fs::read_dir(root) else {return found;};- for entry in entries.flatten() {+ for entry in entries.take(MAX_SCAN_ENTRIES).flatten() {let path = entry.path();- let Some(name) = path.file_name().and_then(|n| n.to_str()) else {+ let Some(name) = path.file_name().and_then(|name| name.to_str()) else {continue;};- // Dot-directories are configuration and caches; the skip list covers- // dependency and build trees that can each hold thousands of entries.if name.starts_with('.') || SKIPPED_DIRS.contains(&name) {continue;}- if entry.file_type().is_ok_and(|t| t.is_dir()) && is_project_dir(&path) {- found.push(path);+ if entry.file_type().is_ok_and(|kind| kind.is_dir())+ && is_project_dir(&path)+ && let Ok(canonical) = path.canonicalize()+ {+ found.push(canonical);}}- sort_by_recency(&mut found, directory_modified);+ found.sort_by(|left, right| {+ directory_modified_us(right)+ .cmp(&directory_modified_us(left))+ .then_with(|| left.cmp(right))+ });found}-/// Newest first, then by path.-///-/// The tracked half of the menu is ordered by activity, and the scanned half-/// used to be alphabetical — which buried the project you just created under-/// every checkout whose name sorts earlier. Both halves now answer the same-/// question: what did I touch most recently? Directories whose timestamp-/// cannot be read sort last rather than to the top, and the path tiebreak-/// keeps the order stable when timestamps match.-fn sort_by_recency(paths: &mut [PathBuf], at: impl Fn(&Path) -> Option<SystemTime>) {- paths.sort_by(|left, right| at(right).cmp(&at(left)).then_with(|| left.cmp(right)));+fn is_project_dir(path: &Path) -> bool {+ PROJECT_MARKERS+ .iter()+ .any(|marker| path.join(marker).exists())}-/// Directory mtime, or `None` when the filesystem will not report one.-fn directory_modified(path: &Path) -> Option<SystemTime> {+fn directory_modified_us(path: &Path) -> Option<i64> {std::fs::metadata(path)- .and_then(|meta| meta.modified())+ .and_then(|metadata| metadata.modified()).ok()+ .and_then(system_time_us)}-/// Whether a directory carries any recognised project marker.-fn is_project_dir(path: &std::path::Path) -> bool {- PROJECT_MARKERS- .iter()- .any(|marker| path.join(marker).exists())+fn system_time_us(time: SystemTime) -> Option<i64> {+ let micros = time.duration_since(UNIX_EPOCH).ok()?.as_micros();+ i64::try_from(micros).ok()+}++fn timestamp_us(raw: Option<&str>) -> Option<i64> {+ raw?.parse::<jiff::Timestamp>()+ .ok()+ .map(|ts| ts.as_microsecond())+}++fn portable_component(value: &str) -> bool {+ let mut chars = value.chars();+ let Some(first) = chars.next() else {+ return false;+ };+ (first.is_ascii_lowercase() || first.is_ascii_digit())+ && chars.all(|character| {+ character.is_ascii_lowercase()+ || character.is_ascii_digit()+ || matches!(character, '.' | '-' | '_')+ })}-/// Canonical form for duplicate detection, falling back to the path as given-/// when the filesystem cannot resolve it.-fn normalize(path: &std::path::Path) -> PathBuf {- std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())+fn marker_body(workspace: &str, project: &str) -> String {+ let mut document = toml_edit::DocumentMut::new();+ document["workspace"] = toml_edit::value(workspace);+ document["project"] = toml_edit::value(project);+ format!(+ "# Created by `ai-memory show`. Both scope names are pinned so moving\n\+ # into a subdirectory or renaming this checkout does not fork memory.\n\+ {document}"+ )}-/// Directory name as a project name, or `None` for a path without one.-fn directory_name(path: &std::path::Path) -> Option<String> {- path.file_name()- .and_then(|n| n.to_str())- .filter(|n| !n.is_empty())- .map(ToString::to_string)+fn create_project(+ parent: &Path,+ name: &str,+ workspace: &str,+ harness: RunHarnessChoice,+) -> Result<PathBuf> {+ create_project_with_initializer(parent, name, workspace, |staging| {+ install_context_files(harness, staging)+ })}-/// Print the start-up banner.-///-/// # Errors-/// Returns an error if stdout cannot be written or flushed.-fn banner() -> Result<()> {- let mut out = std::io::stdout();- let art = [- r" _ _ __ ___ ___ _ __ ___ ___ _ __ _ _ ",- r" __ _ (_) | '_ ` _ \ / _ \ '_ ` _ \ / _ \| '__| | | |",- r" / _` || |_____ | | | | | | __/ | | | | | (_) | | | |_| |",- r" \__,_||_| |_| |_| |_|\___|_| |_| |_|\___/|_| \__, |",- r" |___/ ",- ];- writeln!(out)?;- for line in art {- writeln!(out, "{}", line.green().bold())?;+fn create_project_with_initializer(+ parent: &Path,+ name: &str,+ workspace: &str,+ initialize: impl FnOnce(&Path) -> Result<()>,+) -> Result<PathBuf> {+ if !portable_component(name) {+ bail!(+ "invalid project name {name:?}: use lowercase ASCII letters, digits, dot, dash, or underscore, starting with a letter or digit"+ );}- writeln!(- out,- "{}",- " long-term memory for AI coding agents".dark_green()- )?;- writeln!(- out,- "{}",- " by Fabio Akita · github.com/akitaonrails/ai-memory".dark_green()- )?;- writeln!(out)?;- out.flush()?;- Ok(())+ let target = parent.join(name);+ if target.exists() {+ bail!("project directory already exists: {}", target.display());+ }+ let staging = tempfile::Builder::new()+ .prefix(".ai-memory-project-")+ .tempdir_in(parent)+ .with_context(|| format!("creating a staging directory in {}", parent.display()))?;+ ai_memory_wiki::write_atomic(+ &staging.path().join(".ai-memory.toml"),+ marker_body(workspace, name).as_bytes(),+ )+ .context("writing the staged project marker")?;+ initialize(staging.path())?;+ if target.exists() {+ bail!(+ "project directory appeared while it was being prepared: {}",+ target.display()+ );+ }+ std::fs::rename(staging.path(), &target)+ .with_context(|| format!("publishing new project {}", target.display()))?;+ let target = target+ .canonicalize()+ .with_context(|| format!("canonicalizing new project {}", target.display()))?;+ println!("created {}", target.display());+ Ok(target)+}++fn install_context_files(harness: RunHarnessChoice, path: &Path) -> Result<()> {+ let (instruction, agent, skill_root) = match harness {+ RunHarnessChoice::Claude => (+ "CLAUDE.md",+ InstallSkillsAgent::ClaudeCode,+ path.join(".claude/skills"),+ ),+ _ => (+ "AGENTS.md",+ InstallSkillsAgent::Agents,+ path.join(".agents/skills"),+ ),+ };+ install_instructions::run_quiet(InstallInstructionsArgs {+ target: Some(path.join(instruction)),+ print: false,+ no_skills: false,+ skills_scope: None,+ skills_agent: Some(agent),+ skills_target_dir: Some(skill_root),+ skills_force: false,+ })}-/// Human-readable age of an ISO-8601 timestamp.fn humanize_age(timestamp: Option<&str>) -> String {let Some(raw) = timestamp else {- return "no pages yet".to_string();+ return "no pages yet".to_owned();};let Ok(then) = raw.parse::<jiff::Timestamp>() else {- return raw.to_string();+ return "unknown activity".to_owned();};let seconds = (jiff::Timestamp::now() - then).get_seconds();if seconds < 0 {- return "just now".to_string();+ return "just now".to_owned();}let (value, unit) = match seconds {- s if s < 60 => return "just now".to_string(),- s if s < 3_600 => (s / 60, "minute"),- s if s < 86_400 => (s / 3_600, "hour"),- s if s < 2_592_000 => (s / 86_400, "day"),- s => (s / 2_592_000, "month"),+ value if value < 60 => return "just now".to_owned(),+ value if value < 3_600 => (value / 60, "minute"),+ value if value < 86_400 => (value / 3_600, "hour"),+ value if value < 2_592_000 => (value / 86_400, "day"),+ value => (value / 2_592_000, "month"),};format!("{value} {unit}{} ago", if value == 1 { "" } else { "s" })}-/// Display name for a harness variant, taken from the same clap metadata the-/// parser accepts, so the menu can never drift from the CLI surface.fn harness_name(harness: RunHarnessChoice) -> String {harness.to_possible_value()- .map_or_else(|| "unknown".to_string(), |v| v.get_name().to_string())+ .map_or_else(|| "unknown".to_owned(), |value| value.get_name().to_owned())+}++fn terminal_text(text: &str) -> String {+ text.chars()+ .map(|character| {+ if character.is_control() {+ '?'+ } else {+ character+ }+ })+ .collect()}-/// Restores raw mode and cursor visibility even when the caller bails early.struct TerminalGuard;impl Drop for TerminalGuard {fn drop(&mut self) {- // Best-effort: the process is already unwinding or finishing, and a- // failed restore must not mask the original error.let _ = terminal::disable_raw_mode();let _ = execute!(std::io::stdout(), cursor::Show);}}-/// Draw an arrow-key menu and return the chosen index, or `None` when the-/// user cancels with `Esc`, `q`, or `Ctrl-C`.-///-/// # Errors-/// Returns an error when stdout/stdin is not a terminal, or when raw mode-/// cannot be entered.fn select(title: &str, choices: &[Choice]) -> Result<Option<usize>> {if choices.is_empty() {bail!("nothing to choose from");}- if !std::io::stdout().is_terminal() || !std::io::stdin().is_terminal() {- bail!(- "`ai-memory show` needs an interactive terminal. Use \- `ai-memory run <harness>` from the project directory in scripts \- and pipelines"- );- }-terminal::enable_raw_mode().context("entering raw mode")?;let _guard = TerminalGuard;execute!(std::io::stdout(), cursor::Hide)?;-- // Windows reports a release event for every press. The previous menu's- // Enter release is still queued when this one opens, and reading it here- // would select the first entry before the user sees the list. Discard- // whatever is already pending before taking input.while event::poll(std::time::Duration::from_millis(0))? {let _ = event::read()?;}- let mut cursor_at = 0usize;+ let mut selected = 0usize;let mut offset = 0usize;let mut drawn = 0u16;loop {- drawn = draw(title, choices, cursor_at, &mut offset, drawn)?;- // Only key presses matter. Releases and repeats are what made every- // arrow move two entries on Windows; resize and mouse events fall- // through and redraw on the next iteration.+ drawn = draw(title, choices, selected, &mut offset, drawn)?;let Event::Key(KeyEvent {code,modifiers,@@ -656,20 +681,18 @@ fn select(title: &str, choices: &[Choice]) -> Result<Option<usize>> {};match code {KeyCode::Up | KeyCode::Char('k') => {- cursor_at = cursor_at.checked_sub(1).unwrap_or(choices.len() - 1);- }- KeyCode::Down | KeyCode::Char('j') => {- cursor_at = (cursor_at + 1) % choices.len();+ selected = selected.checked_sub(1).unwrap_or(choices.len() - 1);}- KeyCode::Home => cursor_at = 0,- KeyCode::End => cursor_at = choices.len() - 1,- KeyCode::PageUp => cursor_at = cursor_at.saturating_sub(viewport_rows()),+ KeyCode::Down | KeyCode::Char('j') => selected = (selected + 1) % choices.len(),+ KeyCode::Home => selected = 0,+ KeyCode::End => selected = choices.len() - 1,+ KeyCode::PageUp => selected = selected.saturating_sub(viewport_rows()),KeyCode::PageDown => {- cursor_at = (cursor_at + viewport_rows()).min(choices.len() - 1);+ selected = (selected + viewport_rows()).min(choices.len() - 1);}KeyCode::Enter => {clear(drawn)?;- return Ok(Some(cursor_at));+ return Ok(Some(selected));}KeyCode::Esc | KeyCode::Char('q') => {clear(drawn)?;@@ -684,17 +707,6 @@ fn select(title: &str, choices: &[Choice]) -> Result<Option<usize>> {}}-/// Ask for the new project's name, returning `None` when the user cancels-/// with `Esc` or `Ctrl-C`.-///-/// Rejections are shown in place and leave the typed text alone: the name is-/// validated against the same rule the server enforces, and against `parent`,-/// so every reason the creation could fail is answered while it can still be-/// corrected by typing.-///-/// # Errors-/// Returns an error when raw mode cannot be entered or the terminal cannot be-/// written.fn prompt_project_name(parent: &Path) -> Result<Option<String>> {terminal::enable_raw_mode().context("entering raw mode")?;let _guard = TerminalGuard;@@ -704,7 +716,7 @@ fn prompt_project_name(parent: &Path) -> Result<Option<String>> {}let mut name = String::new();- let mut problem: Option<String> = None;+ let mut problem = None;let mut drawn = 0u16;loop {drawn = draw_prompt("New project name", &name, problem.as_deref(), drawn)?;@@ -737,11 +749,8 @@ fn prompt_project_name(parent: &Path) -> Result<Option<String>> {return Ok(Some(name));}}- // Control-modified keys are shortcuts, not text. Everything the- // rule rejects is still accepted into the buffer so the reason- // shows up under the line the user is looking at.- KeyCode::Char(c) if !modifiers.contains(KeyModifiers::CONTROL) => {- name.push(c);+ KeyCode::Char(character) if !modifiers.contains(KeyModifiers::CONTROL) => {+ name.push(character);problem = None;}_ => {}@@ -749,17 +758,12 @@ fn prompt_project_name(parent: &Path) -> Result<Option<String>> {}}-/// Why `name` cannot be created under `parent`, or `None` when it can.fn rejection(parent: &Path, name: &str) -> Option<String> {if name.is_empty() {- return Some("type a name".to_string());+ return Some("type a name".to_owned());}- if !valid_scope_name(name) {- return Some(- "lowercase letters, digits, dot, dash and underscore only, \- starting with a letter or digit"- .to_string(),- );+ if !portable_component(name) {+ return Some("use lowercase letters, digits, dot, dash, or underscore".to_owned());}if parent.join(name).exists() {return Some(format!("{name} already exists here"));@@ -767,113 +771,102 @@ fn rejection(parent: &Path, name: &str) -> Option<String> {None}-/// Render the name prompt in place and return how many lines it occupies.fn draw_prompt(title: &str, name: &str, problem: Option<&str>, previous: u16) -> Result<u16> {- let (cols, _) = terminal::size().unwrap_or((80, 24));- let width = usize::from(cols.max(20)).saturating_sub(1);-+ let (columns, _) = terminal::size().unwrap_or((80, 24));+ let width = usize::from(columns.max(20)).saturating_sub(1);let mut out = std::io::stdout();if previous > 0 {execute!(out, cursor::MoveUp(previous))?;}write!(out, "\r")?;execute!(out, terminal::Clear(terminal::ClearType::FromCursorDown))?;- write!(out, " {}\r\n", truncate(title, width).green().bold())?;- // A block stands in for the cursor, which stays hidden so the redraw- // cannot leave it parked on a line it already erased.+ write!(+ out,+ " {}\r\n",+ truncate(&terminal_text(title), width).green().bold()+ )?;write!(out," > {}{}\r\n",- truncate(name, width.saturating_sub(5)).as_str().bold(),- "▏".green()+ truncate(&terminal_text(name), width.saturating_sub(5))+ .as_str()+ .bold(),+ "|".green())?;- let footer = match problem {- Some(problem) => format!(" {problem}"),- None => " enter create · esc cancel".to_string(),- };+ let footer = problem+ .map(|problem| format!(" {}", terminal_text(problem)))+ .unwrap_or_else(|| " enter create | esc cancel".to_owned());let footer = truncate(&footer, width);- match problem {- Some(_) => write!(out, "{}\r\n", footer.as_str().red())?,- None => write!(out, "{}\r\n", footer.as_str().dark_grey())?,+ if problem.is_some() {+ write!(out, "{}\r\n", footer.as_str().red())?;+ } else {+ write!(out, "{}\r\n", footer.as_str().dark_grey())?;}out.flush()?;-Ok(3)}-/// How many entries fit on screen at once.-///-/// The redraw walks the cursor back up over the block it just printed, which-/// only lands on the right line while the whole block fits in the window. A-/// list taller than the terminal scrolls the top away and every later redraw-/// then targets the wrong row — which is what made a long project list flash-/// and disappear.fn viewport_rows() -> usize {let (_, rows) = terminal::size().unwrap_or((80, 24));- // Title, hint, and one row of slack for the line the cursor rests on.usize::from(rows).saturating_sub(3).max(3)}-/// First visible entry that keeps `cursor_at` inside a `viewport`-tall window,-/// moving `current` as little as possible so the list does not jump around-/// while the cursor travels within the window.-fn scroll_offset(cursor_at: usize, total: usize, viewport: usize, current: usize) -> usize {+fn scroll_offset(selected: usize, total: usize, viewport: usize, current: usize) -> usize {let mut offset = current;- if cursor_at < offset {- offset = cursor_at;- } else if cursor_at >= offset + viewport {- offset = cursor_at + 1 - viewport;+ if selected < offset {+ offset = selected;+ } else if selected >= offset + viewport {+ offset = selected + 1 - viewport;}offset.min(total.saturating_sub(viewport))}-/// Shorten to `width` characters, marking the cut with an ellipsis. Keeps each-/// rendered line inside the terminal so nothing wraps onto a second row and-/// desynchronises the redraw's line count.fn truncate(text: &str, width: usize) -> String {if width == 0 {return String::new();}if text.chars().count() <= width {- return text.to_string();+ return text.to_owned();}- let mut out: String = text.chars().take(width.saturating_sub(1)).collect();- out.push('…');- out+ let mut output = text+ .chars()+ .take(width.saturating_sub(1))+ .collect::<String>();+ output.push('…');+ output}-/// Render the menu in place and return how many lines it occupies.-///-/// `offset` is the first visible entry, carried between draws so the window-/// only moves when the cursor would leave it.fn draw(title: &str,choices: &[Choice],- cursor_at: usize,+ selected: usize,offset: &mut usize,previous: u16,) -> Result<u16> {- let (cols, _) = terminal::size().unwrap_or((80, 24));- let width = usize::from(cols.max(20)).saturating_sub(1);+ let (columns, _) = terminal::size().unwrap_or((80, 24));+ let width = usize::from(columns.max(20)).saturating_sub(1);let viewport = viewport_rows().min(choices.len());-- *offset = scroll_offset(cursor_at, choices.len(), viewport, *offset);+ *offset = scroll_offset(selected, choices.len(), viewport, *offset);let mut out = std::io::stdout();if previous > 0 {execute!(out, cursor::MoveUp(previous))?;}- // Raw mode disables the implicit carriage return, so every line needs an- // explicit `\r`.write!(out, "\r")?;execute!(out, terminal::Clear(terminal::ClearType::FromCursorDown))?;- write!(out, " {}\r\n", truncate(title, width).green().bold())?;-+ write!(+ out,+ " {}\r\n",+ truncate(&terminal_text(title), width).green().bold()+ )?;for (index, choice) in choices.iter().enumerate().skip(*offset).take(viewport) {- let marker = if index == cursor_at { " > " } else { " " };- let label = truncate(&choice.label, width.saturating_sub(marker.len()));+ let marker = if index == selected { " > " } else { " " };+ let label = truncate(+ &terminal_text(&choice.label),+ width.saturating_sub(marker.len()),+ );let used = marker.len() + label.chars().count();- if index == cursor_at {+ if index == selected {write!(out,"{}{}",@@ -884,31 +877,27 @@ fn draw(write!(out, "{marker}{}", label.as_str().reset())?;}if !choice.detail.is_empty() && used + 2 < width {- let detail = truncate(&choice.detail, width - used - 2);+ let detail = truncate(&terminal_text(&choice.detail), width - used - 2);write!(out, " {}", detail.as_str().dark_grey())?;}write!(out, "\r\n")?;}-let hint = if choices.len() > viewport {format!(- " ↑/↓ move · pgup/pgdn page · enter select · esc cancel [{}/{}]",- cursor_at + 1,+ " up/down move | pgup/pgdn page | enter select | esc cancel [{}/{}]",+ selected + 1,choices.len())} else {- " ↑/↓ move · enter select · esc cancel".to_string()+ " up/down move | enter select | esc cancel".to_owned()};write!(out, "{}\r\n", truncate(&hint, width).dark_grey())?;out.flush()?;-- // title + visible entries + hintOk(u16::try_from(viewport).unwrap_or(u16::MAX).saturating_add(2))}-/// Erase the menu block so the launched agent starts on a clean screen.fn clear(drawn: u16) -> Result<()> {let mut out = std::io::stdout();if drawn > 0 {@@ -923,331 +912,175 @@ fn clear(drawn: u16) -> Result<()> {mod tests {use super::*;- #[test]- fn humanize_age_reports_missing_pages() {- assert_eq!(humanize_age(None), "no pages yet");- }-- #[test]- fn humanize_age_passes_through_unparseable_timestamps() {- assert_eq!(humanize_age(Some("not-a-timestamp")), "not-a-timestamp");- }-- #[test]- fn humanize_age_singularises_and_pluralises() {- let two_days = jiff::Timestamp::now() - std::time::Duration::from_secs(2 * 86_400);- assert_eq!(humanize_age(Some(&two_days.to_string())), "2 days ago");-- let one_hour = jiff::Timestamp::now() - std::time::Duration::from_secs(3_600);- assert_eq!(humanize_age(Some(&one_hour.to_string())), "1 hour ago");- }-- /// A clock skew that puts a page in the future must not underflow into a- /// nonsensical age.- #[test]- fn humanize_age_clamps_future_timestamps() {- let ahead = jiff::Timestamp::now() + std::time::Duration::from_secs(600);- assert_eq!(humanize_age(Some(&ahead.to_string())), "just now");- }-- /// The menu labels come from clap's own metadata, so every harness the- /// parser accepts can be named by the picker.- #[test]- fn harness_names_cover_every_parser_variant() {- for harness in RunHarnessChoice::value_variants() {- assert_ne!(harness_name(*harness), "unknown");+ fn config_at(path: &Path) -> Config {+ Config {+ data_dir: path.to_path_buf(),+ ..Config::default()}}- /// Availability must not panic or depend on the working directory: the- /// picker calls it for every variant before drawing the menu, from- /// whatever directory the user happened to be in.- #[test]- fn availability_is_answerable_for_every_variant() {- let tmp = tempfile::TempDir::new().unwrap();- let restore = std::env::current_dir().unwrap();- std::env::set_current_dir(tmp.path()).unwrap();-- let answers: Vec<bool> = RunHarnessChoice::value_variants()- .iter()- .map(|h| crate::commands::run::harness_available(*h))- .collect();-- std::env::set_current_dir(restore).unwrap();- assert_eq!(answers.len(), RunHarnessChoice::value_variants().len());+ fn make_project(root: &Path, name: &str, marker: &str) -> PathBuf {+ let path = root.join(name);+ std::fs::create_dir_all(&path).unwrap();+ std::fs::write(path.join(marker), b"").unwrap();+ path.canonicalize().unwrap()}#[test]- fn selecting_from_an_empty_list_is_an_error() {- assert!(select("empty", &[]).is_err());+ fn terminal_text_removes_control_sequences() {+ assert_eq!(terminal_text("safe\n\u{1b}[31mname\r"), "safe??[31mname?");}- /// The redraw walks back up over exactly the block it printed, so the- /// window must never expose more entries than fit — a taller block scrolls- /// the top away and every later redraw targets the wrong row.#[test]- fn scroll_offset_keeps_the_cursor_inside_the_window() {- // Cursor within the current window leaves it untouched.- assert_eq!(scroll_offset(2, 24, 5, 0), 0);- // Falling off the bottom scrolls by the minimum.- assert_eq!(scroll_offset(5, 24, 5, 0), 1);- assert_eq!(scroll_offset(6, 24, 5, 1), 2);- // Falling off the top scrolls back up to the cursor.- assert_eq!(scroll_offset(3, 24, 5, 7), 3);- // The window never runs past the end of the list.- assert_eq!(scroll_offset(23, 24, 5, 22), 19);+ fn invalid_server_timestamp_is_not_echoed_to_the_terminal() {+ assert_eq!(humanize_age(Some("\u{1b}[31m")), "unknown activity");}#[test]- fn scroll_offset_is_zero_when_everything_fits() {- for cursor in 0..5 {- assert_eq!(scroll_offset(cursor, 5, 10, 0), 0);- }- }+ fn registry_activity_orders_projects_when_server_metadata_is_unavailable() {+ let timestamp = "2026-08-01T12:00:00Z";+ let candidate = candidate_from(+ PathBuf::from("/missing-is-fine-for-this-pure-test"),+ "default".to_owned(),+ "app".to_owned(),+ CandidateSource::Registry,+ None,+ Some(timestamp),+ );- #[test]- fn truncate_marks_the_cut_and_respects_the_width() {- assert_eq!(truncate("short", 10), "short");- assert_eq!(truncate("exactfit", 8), "exactfit");- assert_eq!(truncate("truncate-me", 5), "trun…");- assert_eq!(truncate("anything", 0), "");+ assert_eq!(candidate.activity_us, timestamp_us(Some(timestamp)));}- /// A wrapped line would occupy two rows and desynchronise the line count- /// the redraw walks back over, so nothing may exceed the given width.#[test]- fn truncate_never_exceeds_the_requested_width() {- for width in 0..12 {- assert!(- truncate("a considerably longer label", width)- .chars()- .count()- <= width- );+ fn portable_project_components_reject_injection_and_traversal() {+ for valid in ["ai-memory", "app2", "my_project", "web.api"] {+ assert!(portable_component(valid));}- }-- /// Create `dir` and drop `marker` inside it when one is given.- fn make_dir(root: &std::path::Path, name: &str, marker: Option<&str>) -> PathBuf {- let dir = root.join(name);- std::fs::create_dir_all(&dir).unwrap();- if let Some(marker) = marker {- std::fs::write(dir.join(marker), "").unwrap();+ for invalid in ["", "../other", "Upper", "with space", "x\nproject", "x\""] {+ assert!(!portable_component(invalid));}- dir}#[test]- fn scan_finds_marked_subdirectories_and_ignores_plain_ones() {+ fn scan_is_depth_one_and_skips_build_directories() {let tmp = tempfile::TempDir::new().unwrap();- make_dir(tmp.path(), "with-git", Some(".git"));- make_dir(tmp.path(), "with-cargo", Some("Cargo.toml"));- make_dir(tmp.path(), "just-a-folder", None);-- let found = scan_for_projects(tmp.path());- let names: Vec<String> = found.iter().filter_map(|p| directory_name(p)).collect();-- assert!(names.contains(&"with-git".to_string()));- assert!(names.contains(&"with-cargo".to_string()));- assert!(- !names.contains(&"just-a-folder".to_string()),- "a directory with no marker is not a project"- );- }-- /// Dependency and build trees can hold thousands of entries and are never- /// projects; descending into them is what would make the scan noticeable.- #[test]- fn scan_skips_dependency_build_and_dot_directories() {- let tmp = tempfile::TempDir::new().unwrap();- make_dir(tmp.path(), "node_modules", Some("package.json"));- make_dir(tmp.path(), "target", Some("Cargo.toml"));- make_dir(tmp.path(), ".cache", Some("package.json"));+ let project = make_project(tmp.path(), "app", "Cargo.toml");+ let nested = tmp.path().join("plain/nested");+ std::fs::create_dir_all(&nested).unwrap();+ std::fs::write(nested.join("go.mod"), b"").unwrap();+ make_project(tmp.path(), "target", "Cargo.toml");- assert!(scan_for_projects(tmp.path()).is_empty());+ assert_eq!(scan_for_projects(tmp.path()), vec![project]);}- /// Running the picker from inside a single checkout should still offer- /// that checkout, not just its children.#[test]- fn scan_includes_the_root_when_the_root_is_itself_a_project() {+ fn failed_project_initialization_rolls_back_the_staging_directory() {let tmp = tempfile::TempDir::new().unwrap();- std::fs::write(tmp.path().join("go.mod"), "").unwrap();-- let found = scan_for_projects(tmp.path());-- assert_eq!(found.len(), 1);- assert_eq!(normalize(&found[0]), normalize(tmp.path()));- }-- #[test]- fn scan_of_an_unreadable_root_is_empty_rather_than_an_error() {- let missing = std::path::Path::new("definitely-not-a-real-directory-xyz");- assert!(scan_for_projects(missing).is_empty());- }+ let result = create_project_with_initializer(tmp.path(), "app", "default", |_path| {+ bail!("synthetic failure")+ });- /// The rule the server enforces at `get_or_create_project`. A name that- /// passes here and fails there would only surface as a hook warning on a- /// session that already started.- #[test]- fn scope_names_follow_the_server_rule() {- for ok in ["ai-memory", "app2", "my_project", "a", "web.api", "0day"] {- assert!(valid_scope_name(ok), "{ok} should be accepted");- }- for bad in [- "",- "-leading-dash",- ".dotfile",- "_underscore",- "UpperCase",- "with space",- "acentuação",- "sub/dir",- ] {- assert!(!valid_scope_name(bad), "{bad} should be rejected");- }+ assert!(result.is_err());+ assert!(!tmp.path().join("app").exists());+ assert!(std::fs::read_dir(tmp.path()).unwrap().all(|entry| {+ !entry+ .unwrap()+ .file_name()+ .to_string_lossy()+ .starts_with(".ai-memory-project-")+ }));}- /// Every reason creation could fail is answered while the name can still- /// be corrected by typing.#[test]- fn rejection_explains_empty_invalid_and_taken_names() {+ fn created_project_is_published_only_after_initialization() {let tmp = tempfile::TempDir::new().unwrap();- make_dir(tmp.path(), "taken", None);-- assert_eq!(rejection(tmp.path(), "").as_deref(), Some("type a name"));- assert!(- rejection(tmp.path(), "Bad Name").is_some_and(|p| p.contains("lowercase")),- "an invalid name names the rule"- );- assert!(- rejection(tmp.path(), "taken").is_some_and(|p| p.contains("already exists")),- "an occupied directory is refused before it can be adopted"- );- assert_eq!(rejection(tmp.path(), "brand-new"), None);- }+ let path = create_project_with_initializer(tmp.path(), "app", "default", |staging| {+ assert!(!tmp.path().join("app").exists());+ std::fs::write(staging.join("AGENTS.md"), b"ready")?;+ Ok(())+ })+ .unwrap();- /// Both scope halves are pinned so a rename or a subdirectory `cd` cannot- /// fork the memory into a second, empty project.- #[test]- fn created_marker_pins_both_scope_halves() {- let body = marker_body("acme", "portal");- assert!(body.contains("workspace = \"acme\""));- assert!(body.contains("project = \"portal\""));+ assert_eq!(std::fs::read(path.join("AGENTS.md")).unwrap(), b"ready");+ let marker = std::fs::read_to_string(path.join(".ai-memory.toml")).unwrap();+ assert!(marker.contains("workspace = \"default\""));+ assert!(marker.contains("project = \"app\""));}#[test]- fn creating_a_project_writes_the_directory_and_its_marker() {+ fn marker_encoding_preserves_an_existing_nonportable_workspace_name() {let tmp = tempfile::TempDir::new().unwrap();+ let path =+ create_project_with_initializer(tmp.path(), "app", "Team \"One\"", |_staging| Ok(()))+ .unwrap();- let path = create_project(tmp.path(), "fresh", "default").unwrap();-- assert!(path.is_dir());let marker = std::fs::read_to_string(path.join(".ai-memory.toml")).unwrap();- assert!(marker.contains("project = \"fresh\""));- // The marker is itself a recognised marker, so the project shows up in- // the scan on the next run even before the server has tracked it.- assert!(is_project_dir(&path));+ let document = marker.parse::<toml_edit::DocumentMut>().unwrap();+ assert_eq!(document["workspace"].as_str(), Some("Team \"One\""));}- /// An existing directory must not be adopted: it can hold an unrelated- /// project whose own marker the creation would overwrite.#[test]- fn creating_over_an_existing_directory_fails() {+ fn candidate_is_rejected_when_its_scope_changes_after_listing() {let tmp = tempfile::TempDir::new().unwrap();- make_dir(tmp.path(), "occupied", Some("Cargo.toml"));+ let path = make_project(tmp.path(), "app", ".ai-memory.toml");+ std::fs::write(+ path.join(".ai-memory.toml"),+ b"workspace = \"one\"\nproject = \"app\"\n",+ )+ .unwrap();+ let candidate = Candidate {+ workspace: "one".to_owned(),+ project: "app".to_owned(),+ path: path.clone(),+ source: CandidateSource::Scan,+ page_count: None,+ last_updated: None,+ activity_us: None,+ };+ std::fs::write(+ path.join(".ai-memory.toml"),+ b"workspace = \"two\"\nproject = \"app\"\n",+ )+ .unwrap();- assert!(create_project(tmp.path(), "occupied", "default").is_err());+ assert!(revalidate_candidate(&config_at(tmp.path()), &candidate).is_err());}- /// The routing block only takes effect in the file the chosen agent reads.+ #[cfg(unix)]#[test]- fn instruction_file_matches_the_harness_convention() {- assert_eq!(instruction_file(RunHarnessChoice::Claude), "CLAUDE.md");- for other in RunHarnessChoice::value_variants()- .iter()- .filter(|h| !matches!(h, RunHarnessChoice::Claude))- {- assert_eq!(instruction_file(*other), "AGENTS.md");- }- }+ fn registered_path_rejects_a_checkout_replaced_by_a_symlink() {+ use std::os::unix::fs::symlink;- /// `--workspace` reaches the marker verbatim, so an unvalidated value can- /// close the TOML string and append keys of its own. The name typed into- /// the prompt is checked; this argument must be held to the same rule.- #[test]- fn workspace_names_are_validated_before_reaching_the_marker() {let tmp = tempfile::TempDir::new().unwrap();-- let injected = "default\"-project = \"hijacked";- let error = create_project(tmp.path(), "victim", injected).unwrap_err();-- assert!(- error.to_string().contains("workspace"),- "the failure must name the offending argument: {error}"- );- assert!(- !tmp.path().join("victim").exists(),- "nothing may be created when the scope is invalid"- );+ let checkout = tmp.path().join("checkout");+ let other = tmp.path().join("other");+ std::fs::create_dir(&checkout).unwrap();+ std::fs::create_dir(&other).unwrap();+ let stored = checkout.canonicalize().unwrap();+ std::fs::remove_dir(&checkout).unwrap();+ symlink(&other, &checkout).unwrap();++ assert!(validate_registered_path(&stored).is_err());}- /// The project you just created has to be near the top: alphabetical order- /// buried it under every checkout whose name sorts earlier, which is the- /// one case the picker exists to serve.#[test]- fn scanned_projects_are_ordered_newest_first() {- let base = SystemTime::UNIX_EPOCH;- let mut paths: Vec<PathBuf> = ["alpha", "personal", "zulu", "unreadable"]- .iter()- .map(PathBuf::from)- .collect();-- sort_by_recency(&mut paths, |path| {- match path.to_str().unwrap() {- "alpha" => Some(base + std::time::Duration::from_secs(10)),- "personal" => Some(base + std::time::Duration::from_secs(90)),- "zulu" => Some(base + std::time::Duration::from_secs(50)),- // A directory whose timestamp cannot be read must not win the- // top slot by default.- _ => None,- }- });-- assert_eq!(- paths- .iter()- .map(|p| p.to_str().unwrap())- .collect::<Vec<_>>(),- ["personal", "zulu", "alpha", "unreadable"]- );- }-- /// Equal timestamps must not reorder between runs.- #[test]- fn equal_timestamps_fall_back_to_a_stable_path_order() {- let mut paths: Vec<PathBuf> = ["b", "c", "a"].iter().map(PathBuf::from).collect();- sort_by_recency(&mut paths, |_| Some(SystemTime::UNIX_EPOCH));- assert_eq!(- paths- .iter()- .map(|p| p.to_str().unwrap())- .collect::<Vec<_>>(),- ["a", "b", "c"]- );+ fn scroll_and_truncation_stay_inside_the_viewport() {+ assert_eq!(scroll_offset(5, 24, 5, 0), 1);+ assert_eq!(scroll_offset(23, 24, 5, 22), 19);+ for width in 0..12 {+ assert!(+ truncate("a considerably longer label", width)+ .chars()+ .count()+ <= width+ );+ }}- /// The same checkout reached by two spellings must dedupe, otherwise a- /// tracked project would also appear as an untracked scan hit.#[test]- fn normalize_matches_equivalent_paths() {- let tmp = tempfile::TempDir::new().unwrap();- let nested = tmp.path().join("child");- std::fs::create_dir_all(&nested).unwrap();-- let indirect = tmp.path().join("child").join("..").join("child");-- assert_eq!(normalize(&nested), normalize(&indirect));+ fn harness_names_cover_every_parser_variant() {+ for harness in RunHarnessChoice::value_variants() {+ assert_ne!(harness_name(*harness), "unknown");+ }}}diff --git a/crates/ai-memory-cli/src/http_client.rs b/crates/ai-memory-cli/src/http_client.rsindex ab0d3592..fd3d445c 100644--- a/crates/ai-memory-cli/src/http_client.rs+++ b/crates/ai-memory-cli/src/http_client.rs@@ -160,6 +160,21 @@ impl ServerEndpoint {format!("{}{}{path}", self.url, self.base_path)}+ /// Stable, credential-free identity for client-local state tied to this+ /// server. The normalized mount path is part of the identity; bearer+ /// material deliberately is not.+ pub(crate) fn identity(&self) -> String {+ let raw = format!("{}{}", self.url.trim_end_matches('/'), self.base_path);+ let Ok(mut parsed) = reqwest::Url::parse(&raw) else {+ return "<invalid-server-url>".to_owned();+ };+ let _ = parsed.set_username("");+ let _ = parsed.set_password(None);+ parsed.set_query(None);+ parsed.set_fragment(None);+ parsed.as_str().trim_end_matches('/').to_owned()+ }+/// Apply auth header to a `reqwest::RequestBuilder` if a token is set.pub(crate) fn authenticate(&self, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder {match &self.auth_token {@@ -448,6 +463,22 @@ mod tests {assert_eq!(ep.auth_token.as_deref(), Some("secret"));}+ #[test]+ fn client_state_identity_normalizes_mounts_and_never_contains_credentials() {+ let first = ServerEndpoint::from_pair(+ Some("http://alice:[email protected]:49374/wiki/".to_owned()),+ None,+ );+ let second = ServerEndpoint::from_pair(+ Some("http://memory.example:49374/wiki".to_owned()),+ Some("bearer-secret".to_owned()),+ );++ assert_eq!(first.identity(), second.identity());+ assert!(!first.identity().contains("alice"));+ assert!(!first.identity().contains("secret"));+ }+// ----------------------------------------------------------------// Base-path awareness — graduated from the Docker live exploration of// the CLI-client-under-AI_MEMORY_BASE_PATH bug. The server nests everydiff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex f685ba97..999d86d1 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -769,10 +769,6 @@ pub struct ProjectSummary {/// ISO-8601 timestamp of the newest `updated_at`, or `None` when/// the project has no pages yet.pub last_updated: Option<String>,- /// Absolute checkout path recorded for cwd matching, or `None` when the- /// project was created without one (the `scratch` fallback, explicit- /// scope creation, or a checkout that has since moved).- pub repo_path: Option<String>,}/// One workspace scope with the id + name needed to write its@@ -4475,8 +4471,7 @@ impl ReaderPool {"SELECT w.name AS workspace_name, \p.name AS project_name, \COUNT(pg.id) AS page_count, \- MAX(pg.updated_at) AS last_updated_us, \- p.repo_path AS repo_path \+ MAX(pg.updated_at) AS last_updated_us \FROM workspaces w \JOIN projects p ON p.workspace_id = w.id \LEFT JOIN pages pg ON pg.project_id = p.id AND pg.is_latest = 1 \@@ -4489,18 +4484,11 @@ impl ReaderPool {let project_name: String = row.get(1)?;let page_count: i64 = row.get(2)?;let last_updated_us: Option<i64> = row.get(3)?;- let repo_path: Option<String> = row.get(4)?;- Ok((- workspace_name,- project_name,- page_count,- last_updated_us,- repo_path,- ))+ Ok((workspace_name, project_name, page_count, last_updated_us))})?;let mut out = Vec::new();for r in rows {- let (workspace_name, project_name, page_count, last_updated_us, repo_path) = r?;+ let (workspace_name, project_name, page_count, last_updated_us) = r?;let last_updated = last_updated_us.and_then(|us| jiff::Timestamp::from_microsecond(us).ok()).map(|ts| ts.to_string());@@ -4509,7 +4497,6 @@ impl ReaderPool {project_name,page_count: u64::try_from(page_count).unwrap_or(0),last_updated,- repo_path,});}Ok(out)diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 04abfd80..a60e2f5f 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -245,6 +245,10 @@ separately gated Claude Code assistant/Stop excerpt remains capped at 2 KB.* `<data_dir>/logs/` - rolling daily `tracing` output.* `<data_dir>/models/` - reserved for bundled embedding models(M9.5+, when local `ort` lands).+* `<data_dir>/client-projects.json` - private, client-local checkout links for+ `ai-memory show`, keyed by credential-free server identity plus workspace and+ project. It is not part of the SQLite/wiki source of truth, and no server API+ exposes host paths.**Schema (current head):**diff --git a/docs/install.md b/docs/install.mdindex 9d71940a..b682248c 100644--- a/docs/install.md+++ b/docs/install.md@@ -1258,6 +1258,7 @@ docker run --rm akitaonrails/ai-memory:latest --help # full subcommand tree|---|---|---|| `serve` | `docker compose up -d` (already done) | Run the HTTP MCP server || `run [harness] [args...]` | host wrapper or native binary | Opt into one managed cross-harness workstream; omit the harness to resume the newest usable local session, or name Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, OMP, Grok Build CLI, or Antigravity CLI explicitly; exact `--yolo` and `--fresh` flags are wrapper-owned and other native arguments pass through |+| `show [--json]` | host wrapper or native binary | Choose a client-local checkout and installed managed harness, or return structured discovery data without launching; remote servers never provide checkout paths || `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 FTS5 search + bounded source authority; use MCP `memory_query` for entity/graph/vector RRF |@@ -1521,12 +1522,13 @@ warns that relabeling system directories such as `/home` can make the hostinoperable. Docker documents `label=disable` in the[`docker run` security options](https://docs.docker.com/reference/cli/docker/container/run/#security-opt).-`ai-memory run` is the exception: the current wrapper intercepts it and starts a-cached checksum-verified native client on the host, where harness executables-and session stores exist. It preserves an explicit remote-`AI_MEMORY_SERVER_URL`. If `run` logs `data_dir=/data` and then cannot find-`codex`, `claude`, or another harness executable, refresh the stale wrapper with-`ai-memory upgrade` on that client machine.+`ai-memory run` and `ai-memory show` are the exceptions: the current wrapper+intercepts them and starts a cached checksum-verified native client on the host,+where local checkouts, harness executables, and session stores exist. It+preserves an explicit remote `AI_MEMORY_SERVER_URL`. If either command logs+`data_dir=/data`, cannot find a checkout, or cannot find `codex`, `claude`, or+another host executable, refresh the stale wrapper with `ai-memory upgrade` on+that client machine.### Docker compose alternativediff --git a/docs/lifecycle-ops.md b/docs/lifecycle-ops.mdindex 393f8e99..2dd6ee20 100644--- a/docs/lifecycle-ops.md+++ b/docs/lifecycle-ops.md@@ -149,6 +149,10 @@ This command also does not rename a source checkout or rewrite any native agentsession locator. See [managed workstream renamebehavior](managed-workstreams.md#project-and-directory-renames) beforephysically renaming a checkout that has native sessions.+After a successful CLI rename, the client also rekeys its local `show` checkout+link. A direct `/admin/rename-project` request cannot update other machines'+client registries; the next successful managed `run` from a checkout refreshes+its link.Failure modes:@@ -243,6 +247,11 @@ a low-level re-stamp:through `workstream_id`; `page_embeddings` and `links` remain attachedthrough `page_id`, so none of those rows need a direct re-stamp.+After a successful CLI true move, or a completed copy-purge move, the client+rekeys its local `show` checkout link. Existing destination links win during a+merge. Direct admin API callers leave client-local registries untouched; a+later successful managed `run` repairs the relevant link.+Ordering is **rename-FIRST, SQL-commit-LAST**, so the **DB is never ahead ofdisk**: a rename failure touches nothing; a crash between the two steps leavesat most an orphan dir at the destination with the DB still wholly at the sourcediff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.mdindex e1f1c23e..70bcb8da 100644--- a/docs/managed-workstreams.md+++ b/docs/managed-workstreams.md@@ -46,6 +46,44 @@ and worktree, creating one named `default` on first use. `--new NAME` starts anindependent line of work; `--workstream NAME` returns to one. These are optionalbranching controls, not harness-switch controls.+## Project-first launcher++`ai-memory show` reverses the usual `cd` then `run` flow: choose a local+checkout, choose an installed managed harness, and launch from that checkout.++```bash+cd ~/Projects+ai-memory show++# Structured discovery only; never launches a harness.+ai-memory show --json+ai-memory show --json --no-scan+```++A successful managed prepare refreshes `<data_dir>/client-projects.json`, a+private client-local registry keyed by a normalized, credential-free server URL+and `(workspace, project)`. The server's `/api/v1/projects` response supplies+only project metadata; it never exposes or chooses a server-host checkout path.+This lets a laptop and desktop map the same remote homeserver project to+different local directories without syncing path precedence or conflicts.++By default the picker combines valid saved links with a bounded depth-1 scan of+the current directory. The scan recognizes common project markers, ignores+symlinks plus dependency/build directories, and resolves each candidate through+the same marker and repository rules as `run`. `--no-scan` uses saved links+only, while `--workspace NAME` filters both sources. Stale, retargeted, or+scope-mismatched links are skipped and a successful later `run` repairs the+entry. If the server is temporarily unavailable, saved links and scan results+remain selectable, but managed `run` still fails closed if it cannot prepare a+workstream before launching the agent.++Interactive mode begins with `+ New project`. The launcher accepts a portable+lowercase ASCII directory name, builds the marker, instruction routing, and+Agent Skills in a hidden staging directory, and renames it into place only when+all setup succeeds. `--yolo`, `--fresh`, and trailing native arguments apply to+the selected harness. Non-terminal callers must use `--json`; JSON cannot be+combined with launch arguments.+## Automatic harness selectionWith no harness name, `ai-memory run` inspects checkout-local sessions for@@ -282,14 +320,15 @@ only after the child starts, so a spawn failure cannot lose the packet. Theoriginal config is not modified. ai-memory opens the project database read-only;the launched Crush process continues its normal native session writes.-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+The Linux/macOS Docker shell wrapper cannot inspect host projects or execute a+host agent from inside its helper container. For `run` and `show`, it downloads+the matching native release into`~/.cache/ai-memory/native-runner`, verifies the published SHA-256 checksum, andexecutes that host client. Set `AI_MEMORY_NATIVE_BIN=/path/to/ai-memory` to use aspecific native build. Native package, release, and source installs need noshim. On native Windows, use the published `ai-memory.exe` or a source build.-The wrapper intercepts `run` before Docker and preserves the host `PATH`,+The wrapper intercepts both commands before Docker and preserves the host `PATH`,`AI_MEMORY_SERVER_URL`, and authentication environment. The native client'sstartup log shows `server_url` as well as its local config paths; `data_dir` and`bind` describe local defaults and do not override a configured remote server.diff --git a/scripts/check-native-packaging.sh b/scripts/check-native-packaging.shindex 05cf9c3a..5992d9b9 100755--- a/scripts/check-native-packaging.sh+++ b/scripts/check-native-packaging.sh@@ -61,6 +61,7 @@ main() {bash -n packaging/aur/PKGBUILDbash -n packaging/aur/PKGBUILD-binbash -n packaging/aur/ai-memory.install+ bash -n bin/ai-memorybash -n scripts/test-native-arch-systemd-distrobox.shif command -v makepkg >/dev/null 2>&1 && [ "$(id -u)" != "0" ]; then@@ -79,6 +80,23 @@ main() {}trap cleanup EXIT+ log "Checking host-launch wrapper routing"+ local fake_docker fake_native wrapper_log+ fake_docker="${TMP_ROOT}/forbidden-docker"+ fake_native="${TMP_ROOT}/fake-ai-memory"+ wrapper_log="${TMP_ROOT}/wrapper.log"+ printf '%s\n' '#!/usr/bin/env bash' 'exit 97' >"${fake_docker}"+ printf '%s\n' '#!/usr/bin/env bash' 'printf '\''%s\n'\'' "$*" >>"${AI_MEMORY_WRAPPER_TEST_LOG}"' >"${fake_native}"+ chmod 0755 "${fake_docker}" "${fake_native}"+ AI_MEMORY_DOCKER="${fake_docker}" AI_MEMORY_NATIVE_BIN="${fake_native}" \+ AI_MEMORY_WRAPPER_TEST_LOG="${wrapper_log}" \+ bin/ai-memory run codex --yolo+ AI_MEMORY_DOCKER="${fake_docker}" AI_MEMORY_NATIVE_BIN="${fake_native}" \+ AI_MEMORY_WRAPPER_TEST_LOG="${wrapper_log}" \+ bin/ai-memory show --json --no-scan+ assert_contains "${wrapper_log}" "run codex --yolo"+ assert_contains "${wrapper_log}" "show --json --no-scan"+log "Creating temporary alternate root"mkdir -p \"${TMP_ROOT}/etc" \