# Aiki CLI — Orientation Primer

## 1. What is Aiki?

Aiki is an AI-native task tracking and agent orchestration CLI written in Rust. It acts as a disciplined layer between your repository and your AI coding assistants — Claude Code, Cursor, Codex, and Zed — turning free-form AI edits into a structured, auditable workflow.

At its core, Aiki answers a fundamental question that every team adopting AI coding tools eventually asks: *Who changed what, when, and why — and did anyone actually check?* Without structure, AI edits blur into a stream of undifferentiated changes with no ownership, no review trail, and no clear way to revisit or undo discrete pieces of work. Aiki gives every AI action a task identity, a history, and a quality gate.

Aiki is experimental (v0.1.0) and under active development. Install via Homebrew: `brew tap aiki-sh/tap && brew install aiki`.

## 2. What Can Aiki Do?

- **Task tracking**: Every AI action maps to a task with a unique 32-character ID. Start a task, watch it progress, close it with confidence scoring and a summary. Tasks persist across sessions, agents, and context resets — they live in JJ change history, not in memory.

- **Structured SDLC**: A four-phase software development loop — `aiki plan`, `aiki build`, `aiki review`, `aiki fix` — that takes a natural-language plan to running, reviewed code. Build decomposes the plan into subtasks and runs them in parallel lanes; review evaluates the output; fix auto-remediates issues until the code is clean.

- **Session isolation**: Every AI agent session gets its own isolated Jujutsu (JJ) workspace. Multiple agents can work concurrently on the same repo without stepping on each other. When a session ends, its changes are atomically absorbed (rebased) back into the main workspace.

- **Event-driven hooks**: A YAML-based flow system fires at every significant point in the agent lifecycle — session start, turn start/end, file changes, shell commands, web requests, and more. Hooks can inject context into agent prompts, block dangerous operations, run shell commands, or send autoreplies.

- **Plugin system**: Reusable behaviors are packaged as GitHub repos (a `plugin.yaml` + `hooks.yaml` + task templates). Plugins are auto-fetched on first use and compose via `include:`, `before:`, `after:`, and `hook:` directives.

- **Multi-agent handoffs**: Tasks persist across agent boundaries. Claude can start a task, Codex can review it, and Cursor can fix it — all referencing the same task ID.

## 3. What Is Aiki Made Of?

Aiki is a single Rust binary (`aiki`) built from a unified crate at `src/`. Its major modules are:

- **`src/commands/`** — One file per CLI command: `plan`, `build`, `review`, `fix`, `loop_cmd`, `decompose`, `task`, `session`, `init`, `doctor`, `plugin`, `run`, `resolve`, `epic`, `blame`, `authors`, and more. Each command module defines its CLI arguments (via `clap`) and implements the command logic.

- **`src/editors/`** — Editor-specific integrations: `claude_code/`, `cursor/`, `codex/`, `acp/`, and `zed`. Each handles the protocol details for its target AI agent, including session tracking, event translation, and (for Codex) sandbox configuration.

- **`src/repos/`** — Repository detection (`detector.rs`), initialization state machine (`init_state.rs`), and repo identity (`id.rs`). Determines whether Aiki is enabled for the current repo and user.

- **`src/expressions/`** — A Rhai (embedded scripting language) expression evaluator used by the hooks system for conditional logic, variable binding, and template interpolation in YAML flow definitions.

- **`src/tools.rs`** — Tool call handling for AI agent interactions.

- **`src/instructions.rs`** — Context injection engine that builds the CLAUDE.md / AGENTS.md style instructions Aiki injects into each agent session.

## 4. How the SDLC Pipeline Works

The flagship workflow is a closed feedback loop of four commands:

**Plan** (`aiki plan path/to/plan.md`): You and an AI agent collaborate interactively on a specification. The output is a markdown plan file in `ops/now/` that describes what to build, requirements, and implementation approach.

**Build** (`aiki build path/to/plan.md`): Reads the plan and runs a three-stage pipeline:
1. `plan` — Creates an epic task from the plan file.
2. `decompose` — Reads the epic and creates numbered subtasks, each with detailed instructions and dependency links. Dependency links form the execution graph (a directed acyclic graph of `depends-on` and `needs-context` edges).
3. `loop` — Orchestrates subtask execution: derives parallel lanes from the DAG, runs independent lanes concurrently (one agent per lane), and waits for completion. A real-time status screen shows progress, agent activity, and timing.

**Review** (`aiki review <task-id>`): Evaluates the code changes against structured criteria. Issues are tracked as review comments with severity levels (high/medium/low) and file locations. Review auto-assigns a different agent than the one that wrote the code.

**Fix** (`aiki fix <review-id>`): Reads issues from a review, runs them through a `fix → decompose → loop` pipeline, then re-reviews until the code is clean (up to 10 iterations by default).

The full pipeline can be triggered in one command: `aiki build path/to/plan.md --fix`.

## 5. How Session Isolation Works

The most technically sophisticated part of Aiki is its session isolation system, implemented in `src/editors/` and documented in `docs/session-isolation.md`.

When any AI agent session starts, Aiki creates an isolated Jujutsu (JJ) workspace for that session under `/tmp/aiki/{repo-id}/{session-uuid}/`. The workspace shares the same underlying JJ repository store (`.jj/repo`) but has its own working copy. The agent is instructed to `cd` into this workspace and do all its work there.

At the end of each agent turn, Aiki runs a **two-phase absorption**:
1. **Phase 1**: Rebase the workspace's changes (`jj rebase -b {ws_head} -d @-`) onto the current parent of the main working copy, using `-b` (branch) to avoid cascading rewrites to sibling workspaces.
2. **Phase 2**: Rebase the main working copy (`jj rebase -s @ -d {ws_head}`) onto the workspace's head, advancing the main workspace forward.

A file-based lock (`/tmp/aiki/{repo-id}/.absorb.lock`) serializes concurrent absorptions so each one builds on the last. After absorption, the filesystem is synced with `jj workspace update-stale`. If conflicts arise, Aiki emits an autoreply asking the agent to resolve them.

**Why unconditional isolation?** Every session always gets a workspace regardless of how many sessions are active. This eliminates the race condition where a second session could start before the first creates its workspace.

## 6. The Hooks System

Aiki's behavior is driven by **flows** — YAML files that declare handlers for events. The default bundled flow (`aiki/default`) includes the core provenance flow.

**Events** fire at: `session.started/resumed/ended`, `turn.started/completed`, `change.permission_asked/completed`, `read.permission_asked/completed`, `shell.permission_asked/completed`, `web.permission_asked/completed`, `mcp.permission_asked/completed`, `commit.message_started`, `repo.changed`, `task.started/closed`, and `workflow.started/completed/step.started/completed`.

**Actions** in handlers include: `shell` (run a command), `jj` (run a JJ command), `context` (inject text into agent prompts), `autoreply` (send a follow-up message to the agent), `commit_message` (modify commit messages), `log`, `let` (bind a variable), `call` (call a Rust native function), `hook` (invoke another plugin), `task.run` (spawn an agent), `review`, `stop`, `block` (exit code 2 to block the editor operation), and `session.end`.

## 7. The Plugin System

Plugins are GitHub repos with a `plugin.yaml` manifest, an optional `hooks.yaml`, and optional `tasks/` directory of markdown task templates. Plugins are referenced as `namespace/name` (e.g., `somecorp/safety-guard`) and auto-fetched from GitHub on first use.

Templates use `{{variable}}` interpolation and `{{> partial}}` includes. Task templates define the structure and content of plans, reviews, and fix tasks.

The `aiki` namespace (`aiki-sh` on GitHub) is reserved for first-party plugins. First-party plugins can be referenced as bare names: `herdr` resolves to `aiki-sh/aiki-plugin-herdr`.

## 8. How to Install and Use Aiki End-to-End

**Install:**
```bash
brew tap aiki-sh/tap
brew install aiki
aiki --version
```

**Initialize a repo:**
```bash
cd your-project
aiki init
```
This configures editor integrations for Claude Code, Cursor, Codex, and Zed.

**Chat mode (simplest — just add traceability to normal AI usage):**
```bash
# Open your AI editor (Claude Code, Cursor, etc.)
# Ask the AI to make a change
# Aiki automatically hooks in, starts a task, tracks the change
aiki task show <task-id>     # See the task while agent works
aiki task diff <task-id>     # See exact code changes
```

**Headless SDLC workflow:**
```bash
# 1. Plan
aiki plan ops/now/my-feature.md "Add webhook support"

# 2. Build (with automatic review and fix)
aiki build ops/now/my-feature.md --fix

# 3. Review manually
aiki review <task-id>

# 4. Fix issues
aiki fix <review-id>
```

**Verify health:**
```bash
aiki doctor    # Diagnose setup issues
```

## 9. Honest Limits

- Aiki is v0.1.0 and explicitly **experimental**. The API and behavior are under active development.
- Session isolation requires Jujutsu (JJ) — it does not work with plain Git repos.
- There is a known P0 bug: concurrent absorptions can strand commits on side branches in some edge cases.
- The concurrent-agent workflow assumes agents respect the workspace path injected by Aiki; sandboxed agents (e.g., Codex `--full-auto`) need special `--add-dir` flags for the JJ store.
- Aiki does not replace your AI tools — it wraps them. You still need Claude Code, Codex, or Cursor installed.
