How the `ai-memory run` Command Manages Workstreams: A Deep Dive into the 11-Phase Lifecycle
The ai-memory run command orchestrates an 11-phase managed workstream lifecycle that ties native harness processes to server-side records, handling everything from repository fingerprinting to transcript import.
The ai-memory run command in the akitaonrails/ai-memory repository implements a sophisticated workstream management system that bridges local AI agent processes with persistent server-side state. This managed approach ensures that every native session is tracked, linked, and synchronized with the cloud workstream, enabling features like automatic transcript import and heartbeat monitoring.
Phase 1: Repository Context and Harness Selection
Repository Inspection and Fingerprinting
The lifecycle begins with repository discovery. In crates/ai-memory-cli/src/commands/run.rs, the inspect_repository function (line 87) determines the checkout path and calculates a repository fingerprint. Simultaneously, native_home (lines 30-31) locates where native harness sessions are stored locally. These values establish the foundation for linking local activity to the correct workstream context.
Automatic Harness Detection
When users omit the --harness flag, the CLI performs automatic discovery. The list_auto_sessions function (lines 24-53) scans for checkout-local sessions across all supported harnesses defined in AUTO_HARNESSES. It then filters these through filter_usable_auto_sessions (lines 82-97) to exclude any harnesses whose executables are not present on the system PATH.
Phase 2: Server Preparation and Session Adoption
Preparing the Managed Run
With harness selection complete, the CLI initiates server-side workstream creation. The prepare_managed_run function (lines 64-66) constructs a PrepareManagedRunRequest containing the workspace fingerprint, repository details, selected agent, and available agents for auto-selection. This request hits the /workstream/runs endpoint. The implementation includes retry logic via prepare_managed_run_with_retry (lines 77-99) to handle transient network failures. The server responds with a PrepareManagedRunResponse containing the critical run_id, workstream_id, and optionally a pre-linked native session ID.
Native Session Adoption
If the workstream lacks a linked session and the harness supports adoption, the CLI attempts to reuse existing local sessions. The auto_candidates logic (lines 101-118) identifies potential sessions, while choose_native_session_interactive (lines 38-71) provides an interactive picker when multiple candidates exist. This prevents unnecessary session creation when valid local contexts are already available.
Phase 3: Launch Plan Construction and Process Spawning
Building the Launch Plan
Before execution, the CLI constructs a LaunchPlan that determines execution mode. The build_preflighted_launch_plan function (lines 78-89) in run.rs delegates to build_launch_plan (located in crates/ai-memory-workstream/src/lib.rs) to resolve Session versus Passthrough mode, handle special flags like --yolo and --fresh, and determine the executable path and arguments.
Linking and Spawning
For session-mode runs, the CLI notifies the server of the native session association via post_json_no_content (lines 46-60) sending a LinkManagedRunRequest. The process spawns with three critical environment variables injected:
AI_MEMORY_RUN_IDAI_MEMORY_WORKSTREAM_IDAI_MEMORY_HOOK_URL
These variables enable the harness to send hook events back to the server. The spawn logic resides in the command construction block (lines 97-108).
Phase 4: Runtime Monitoring
Heartbeat Maintenance
While the native process executes, a background task maintains the workstream lease. The send_managed_heartbeat and send_managed_heartbeat_with_timeout functions (lines 53-88) periodically post to /heartbeat. The system tolerates server unreachable conditions, entering a quiet retry mode after configurable consecutive failures to prevent log spam while ensuring eventual consistency.
Phase 5: Termination and Transcript Import
Process Completion Handling
When the child process exits, the CLI resolves the final state. The resolve_native_session_after_run function (lines 105-121) collects the exit code, fetches pending server status, and discovers any newly created native session IDs that weren't known at launch.
Transcript Import and Finalization
The final phase exports and uploads the execution transcript. The import_batches function (lines 93-122) exports the native transcript via export_transcript, splits events into size-bounded chunks, and posts them to /finish. If the harness provides a context packet (such as Grok or Crush), it is delivered before the first batch via finish_with_retry (lines 146-161). Finally, the heartbeat task aborts and the CLI returns the native process exit code (lines 144-145).
Key Source Files and Architecture
The workstream management logic spans four primary crates:
crates/ai-memory-cli/src/commands/run.rs: Contains the mainrunfunction (line 78) andrun_fromhelper orchestrating the entire lifecycle.crates/ai-memory-workstream/src/lib.rs: DefinesLaunchPlan,ManagedHarness, and helper functions likebuild_launch_plananddiscover_native_session.crates/ai-memory-cli/src/cli.rs: DefinesRunArgsandRunHarnessChoicestructures that parse command-line inputs.crates/ai-memory-core/src/lib.rs: Houses the protocol definitions includingPrepareManagedRunRequest,FinishManagedRunRequest, and related response structs.
Practical Usage Examples
# Run a Codex session, creating a new workstream called "experiment"
ai-memory run codex --workstream experiment --fresh
# Run a Kiro CLI session, automatically selecting the newest checkout-local session
ai-memory run kiro
# Run a native executable not on PATH with explicit harness specification
ai-memory run --executable /usr/local/bin/custom-agent claude --fresh
Summary
- The
ai-memory runcommand implements an 11-phase workstream management lifecycle that ensures server-side consistency with local execution. - Repository fingerprinting via
inspect_repositoryand automatic harness selection vialist_auto_sessionsprovide zero-configuration operation. - Server coordination uses
PrepareManagedRunRequestandLinkManagedRunRequestto establish the relationship between native processes and workstream records. - Runtime reliability is maintained through environment variable injection (
AI_MEMORY_RUN_ID,AI_MEMORY_WORKSTREAM_ID,AI_MEMORY_HOOK_URL) and robust heartbeat mechanisms. - Execution artifacts are captured through
export_transcriptand imported via batchedfinishrequests, preserving complete session history.
Frequently Asked Questions
How does ai-memory run handle network interruptions during execution?
The heartbeat implementation in send_managed_heartbeat_with_retry (lines 53-88) tolerates transient failures by entering a quiet retry mode after a configurable number of consecutive misses. The native process continues running independently, and the CLI attempts to reconcile state once connectivity returns, ensuring workstream management remains resilient to network partitions.
What happens if I don't specify a harness when running the command?
If the --harness flag is omitted, the CLI executes automatic discovery via list_auto_sessions (lines 24-53) and filter_usable_auto_sessions (lines 82-97). It scans for checkout-local sessions of all supported harnesses and filters for executables present on PATH. This allows ai-memory run to intelligently select the appropriate agent without explicit configuration.
Can I reuse an existing local session instead of creating a new one?
Yes. If the workstream has no linked session and the harness supports adoption, the CLI evaluates auto_candidates (lines 101-118) to identify reusable sessions. When multiple candidates exist, choose_native_session_interactive (lines 38-71) prompts for selection. This adoption logic prevents unnecessary session proliferation while maintaining accurate workstream tracking.
Where is the server communication logic defined?
The request/response structures used for server communication—such as PrepareManagedRunRequest, LinkManagedRunRequest, and FinishManagedRunRequest—are defined in crates/ai-memory-core/src/lib.rs. The CLI uses these structs to communicate with endpoints like /workstream/runs, /heartbeat, and /finish throughout the managed run lifecycle.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →