# ActDim Along (v4.9.0) - Full Documentation Context

> [![Tests](https://github.com/actdim/along/actions/workflows/tests.yml/badge.svg)](https://github.com/actdim/along/actions/workflows/tests.yml) - Python 3.10-3.13 on Linux and Windows.

---

## Document: README.md (Overview)

# ActDim Along (v4.9.0)

[![Tests](https://github.com/actdim/along/actions/workflows/tests.yml/badge.svg)](https://github.com/actdim/along/actions/workflows/tests.yml) - Python 3.10-3.13 on Linux and Windows.

ActDim Along is a provider-agnostic context and memory protocol for AI coding agents (`ALONG-PROTOCOL v4.9.0`) that provides persistent in-repo task tracking, an evergreen architecture wiki, and mechanical quality gates across Claude Code, Google Antigravity, OpenAI Codex, and OpenCode.

---

## Quickstart & Installation

Install Along across all supported AI providers with a single command:

### Windows (PowerShell)
```powershell
powershell -NoProfile -ExecutionPolicy Bypass -Command "irm https://raw.githubusercontent.com/actdim/along/main/install.ps1 | iex"
```

### Linux / macOS (Bash)
```bash
curl -fsSL https://raw.githubusercontent.com/actdim/along/main/install.sh | bash
```

The installer bootstraps the repository into `~/.cache/actdim-along/repo` (via shallow `git clone` or archive fallback) and configures skills across Claude Code, OpenAI Codex, Google Antigravity, and OpenCode.

### Python Package Installation (Core vs. Extras)

Along is distributed on PyPI as `actdim-along`. Install Along Core with minimal dependencies or include modular extras:

```bash
# Core only: minimal runtime dependency (ruamel.yaml>=0.18; telemetry is built-in stdlib)
pip install actdim-along

# Web Dashboard: FastAPI, Uvicorn, Pydantic, and Rich
pip install actdim-along[dash]

# Full suite: install all optional extras
pip install actdim-along[all]
```

#### Manual / Local Checkout Installation
If you prefer to clone the repository manually or are developing Along:
```powershell
git clone https://github.com/actdim/along.git
cd along
powershell -NoProfile -ExecutionPolicy Bypass -File install.ps1 -Target all # Windows
bash install.sh --target=all                                               # Linux / macOS
```

An install records what it wrote in `~/.along/install-manifest.json`: it never deletes a
directory it does not own, so rules you wrote yourself survive every re-install, and
`install.ps1 -Uninstall` / `./install.sh --uninstall` removes exactly that record and
nothing else. See [Setup, Installation & Workflows](./docs/topic--setup-and-workflow.md).

---

## Why Along?

AI coding agents encounter several recurring failure modes across extended sessions:
- **Context Loss**: Agents forget past architectural choices, re-invent rejected patterns, and drop active tasks across sessions.
- **Context Bloat**: Ingesting entire files or directories into prompts consumes large token budgets per turn.
- **Multi-Branch Concurrency**: Parallel agents modify shared documentation, status boards, or lock files, causing git merge conflicts.
- **Unanchored Modifications**: Without explicit issue anchoring and pre-commit checks, agents can make unintended modifications that bypass test suites.
- **Toolchain Inconsistencies**: Differing build tools, test frameworks, and command flags can produce verbose context logs or invalid invocations.
- **Workspace Pollution**: Running parallel or autonomous agents directly in developer working directories can conflict with uncommitted working tree edits.
- **Prompt Instruction Decay**: Natural language guidelines in static prompts can lose effectiveness as context length grows.

Along addresses these challenges through a dual-tier structure: an evergreen architecture wiki (`docs/`) for system design consensus, and a machine-readable governance layer (`.along/`) for task tracking, decision records, and session history. Agents track issues in a dependency graph, search project knowledge via bounded snippet retrieval, and verify changes through declarative quality gates.

---

## Core Value Proposition

| Pillar | How Along Delivers It |
| :--- | :--- |
| **Zero-Vector In-Repo Intelligence** | Fast TF-IDF multi-scope retrieval engine (`along-kb-search`) unifying docs, ADR constraints, active issues, and session logs into word-boundary aligned snippets (<= 150 words), avoiding full-file context ingestion and significantly reducing exploration prompt tokens without external vector DBs or daemon processes (see [benchmarks](scripts/bench_kb_search.py)). |
| **Dual-Tier Memory Architecture** | Clean architectural separation: Evergreen LLM-Wiki (`docs/`) with AST code symbol grounding and SHA-256 drift detection vs. Living Transactional Governance (`.along/`) with DAG issues, immutable session history, and atomic projections. |
| **Persistent In-Repo Memory** | Durable, git-tracked memory (`.along/`): DAG issues (spikes and `risk`-tagged blockers included), append-only ADR logs, milestones, and session records that travel with the codebase. |
| **Autonomous Multi-Agent Teams** | Sequential living-plan state machine (`along-team`): Supervisor -> Scout -> Architect -> Implementer -> Reviewer with session blackboards, retry limits, and single-agent degradation. |
| **Runtime Worktree Workspace Isolation** | Ephemeral Git worktree isolation (`along worktree`, `/along-team --worktree`) satisfying the 3-part Environment Readiness Contract: NTFS junctions / symlinks for dependencies (`node_modules`, `.venv`), `.env` configuration copying, real-time session blackboard sharing, and Windows file lock resilient teardown. |
| **Runtime Mechanical Prose Enforcement** | Active agent lifecycle interception (`PreToolUse`, `Stop`) turning markdown guidelines into hard runtime errors across Claude Code, Antigravity, and Codex, with machine-checked bi-directional traceability (`along hook verify`). |
| **Token-Efficient LLM-Wiki (`docs/`)** | Modular knowledge base with in-place source provenance, SHA-256 drift detection, deterministic `llms.txt` compilation, and targeted snippet search (`along-kb-search`) avoiding full-file context ingestion. |
| **Stack-Agnostic Lifecycle & Polyglot Hooks** | Unified agent execution contract (`/along-build`, `/along-test`, `/along-dev`, `/along-version-bump`, `/along-dep-scan`) with zero-config stack auto-detection and polyglot repository hooks (`.along/scripts/` in Python, Bash, PowerShell, Batch). |
| **Zero-Conflict Git Concurrency** | Single Source of Truth (SSOT) atomic files vs compiled projections (`ISSUES.md`, `INDEX.md`), union merges (`merge=union`), and decentralized date-slug ADRs that avoid collisions in parallel branches. |
| **Engineering Provenance & Dual-Track UI** | Living plans, fix loops, and verification gates are permanently recorded in session logs while projecting interactive visual review cards in IDEs (Antigravity). |
| **Strict Data Safety & Verification Gates** | Hermetic engines (`alongkit`) with transactional byte-exact rollbacks, strict front-matter preservation (`ruamel.yaml`), and zero-unintended-deletions invariant. |
| **Declarative Runtime Gates & Traceability** | Mechanical agent lifecycle interception (`PreToolUse`, `Stop`) enforcing declarative runtime gates in `default_gates.yaml` (32 protocol invariants enforced across runtime hooks, git hooks, and CI), backed by machine-checked bi-directional traceability (`along hook verify`). In runtimes with Along hooks installed, violations trigger immediate tool-level interception; git and CI gates provide universal baseline enforcement everywhere. |
| **Nearest Context Boundary** | Monorepos, microservices, and Git submodules maintain isolated localized memory, preventing root workspace pollution. |

---

### Dual-Tier Memory Architecture: Evergreen Wiki vs. Living Governance

Along divides repository intelligence into two specialized, complementary tiers to keep agent context scalable and predictable:

```mermaid
flowchart TD
    subgraph Tier1["Tier 1: Evergreen Architecture Wiki (docs/)"]
        WIKI["Curated Knowledge Base (docs/topic--*.md)"]
        AST["AST Code Symbol Grounding (zero ghost symbols)"]
        PROV["Source Provenance (SHA-256 drift gate)"]
        LLMS["Deterministic llms.txt & llms-full.txt"]
    end

    subgraph Tier2["Tier 2: Living Governance Memory (.along/)"]
        ISSUES["Machine-Parseable DAG Issues (open -> done)"]
        ADRS["Decentralized ADRs & CONSTRAINTS.md"]
        SESSIONS["Immutable Session Logs & Engineering Provenance"]
        PROJ["Auto-Compiled Projections (ISSUES.md)"]
    end

    subgraph Retrieval["Zero-Vector In-Repo Retrieval Engine (along kb-search)"]
        SEARCH["Fast TF-IDF Multi-Scope Search"]
        SNIPPETS["Targeted Bounded Snippets (<= 150 Words)"]
        SAVINGS["Bounded Snippets (<= 150 Words) vs Full-File Ingestion"]
    end

    WIKI --- SEARCH
    ISSUES --- SEARCH
    ADRS --- SEARCH
    SESSIONS --- SEARCH
    SEARCH --> SNIPPETS --> SAVINGS
```

- **Tier 1: Evergreen Architecture Wiki (`docs/`)**:
  - **Purpose**: Curated, cumulative knowledge base representing the current factual state of system design.
  - **Mechanisms**: In-place source provenance (`sources: [{path, hash}]`), AST code symbol verification to prevent hallucinated interfaces, and deterministic compilation into `docs/INDEX.md` and `llms.txt`.
  - **Lifecycle**: Evolves with the codebase. Never transactional; updated only when public contracts, workflows, or architecture change.
- **Tier 2: Living Governance Memory (`.along/`)**:
  - **Purpose**: Transactional project memory, active task execution state, and historical audit trails.
  - **Mechanisms**: Machine-parseable DAG issues with lifecycle states, modular ADRs (`ADR-YYYY-MM-DD--<slug>.md`), compiled constraints projection (`CONSTRAINTS.md`), and append-only session history.
  - **Lifecycle**: Transactional and stateful. Closed issues and session logs are permanent and immutable.
- **Unified Retrieval Engine (`along kb-search`)**:
  - Unifies both tiers in a single fast local query without vector embeddings, cloud dependencies, or background daemon processes.
  - Returns word-boundary aligned snippets (< 150 tokens) directly to agent prompts, avoiding full-file context ingestion (measured in [scripts/bench_kb_search.py](scripts/bench_kb_search.py)).

### Along Core vs. Modular Extras Architecture

Along enforces a strict minimal-core architecture:
- **Along Core (`actdim-along`)**: In-repo memory (`.along/`), entity lifecycle (`ISSUES/`, `DECISIONS/`, `MILESTONES/`), projections (`ISSUES.md`, `CONSTRAINTS.md`, `docs/INDEX.md`), bounded snippet retrieval (`along kb-search`), standard lifecycle contracts (`build`, `test`, `dev`, `commit`, `wrap`), mechanical safety gates, and stdlib telemetry (tracer, redactor, spool, OTLP/HTTP JSON exporter). Core runtime dependencies remain strictly minimal (`ruamel.yaml>=0.18`).
- **Modular Extras**:
  - `actdim-along[dash]`: Web dashboard UI, Cytoscape DAG visualization, and OpenAPI analytics server.
  - `actdim-along[all]`: Stable alias for optional extras (`[dash]`).
  - Optional protocol modules (`along-team`, git worktree sandboxing, `code-review-graph` AST tools, `along-dep-scan`) operate on-demand with zero extra package dependencies.
- **Protocol Versioning**: Protocol specification version (`ALONG-PROTOCOL vX.Y.Z`) changes strictly on format or schema updates. Tooling enhancements release as minors; breaking format changes are batched into rare majors with migration automation (`along migrate`).

---

## Using Along in Your Projects? (Drop-In Blurb)

Add this badge and blurb to the `README.md` of any repository powered by Along:

````markdown
### AI Development: Powered by [ActDim Along](https://github.com/actdim/along)

This repository follows the **ActDim Along Protocol** for AI agent context, persistent memory, and autonomous workflows:
- **Dual-Tier Memory**: Evergreen LLM-Wiki in `docs/` and living governance memory in `.along/` survive across all AI sessions.
- **Zero-Vector Unified Retrieval**: Fast local snippet search across architecture, decisions, and issues returning bounded snippets (< 150 tokens) without full-file ingestion or external database dependencies.
- **Runtime Worktree Isolation**: Autonomous agent tasks execute in isolated Git worktrees with automatic dependency linking, preserving clean developer checkouts.
- **Mechanical Quality Gates**: Protocol rules, clean typography, and issue bindings are mechanically enforced before tools execute in runtimes that load Along's hooks (Claude Code, Antigravity, Codex); elsewhere they are advisory. The portable baseline for every committer is the CI job `along gates check --ci` plus opt-in git hooks (`along hooks install --git`).
- **Standardized Lifecycle Contract**: Unified commands for build, test, dev, release, and dependency discovery via pluggable `.along/scripts/` hooks.
- **Provider-Agnostic**: Compatible out of the box with **Claude Code**, **Google Antigravity**, **OpenAI Codex**, and **OpenCode**.
````

---

## Knowledge Base & Architecture Index

The repository's complete technical specification is maintained as a living LLM-Wiki in [`docs/`](./docs/INDEX.md):

| Topic | Description | Link |
| :--- | :--- | :--- |
| **System Architecture** | Provider flow, context boundaries, code intelligence, and bridge layers. | [System Architecture & Flow](./docs/topic--architecture.md) |
| **CLI Command Reference** | Unified console command dictionary, subcommands, flags, and exit codes. | [Along CLI Command Reference](./docs/topic--cli-reference.md) |
| **Domain Model & Entities** | Machine-parseable schemas for Issues, ADRs, Milestones, and Sessions. | [Domain Model & Entity Ecosystem](./docs/topic--domain-model.md) |
| **Setup & Workflows** | Installation matrix, repository onboarding, and session lifecycle. | [Setup, Installation & Workflows](./docs/topic--setup-and-workflow.md) |
| **LLM-Wiki Architecture** | Andrej Karpathy paradigm, source isolation, and token efficiency. | [LLM-Wiki Architecture & Paradigm](./docs/topic--llm-wiki-architecture.md) |
| **Runtime Hooks & Gates** | Agent lifecycle interception harness across Antigravity, Claude, and Codex, plus the runtime capability matrix: where gates are mechanical and where (Claude Cowork, Cursor, OpenCode) they are advisory. | [Runtime Lifecycle Hooks & Mechanical Gates](./docs/topic--runtime-hooks-and-gates.md) |
| **Declarative Gates & Traceability** | Extensible YAML gate engine and bi-directional machine-checked matrix. | [Declarative Gate Engine & Traceability Matrix](./docs/topic--declarative-gates-and-traceability.md) |

## Automation Skills Reference (Grouped by Workflow Phase)

Along provides **21 singular automation skills** structured across 6 core lifecycle phases:

### 1. Bootstrap & Repository Protocol Management
| Skill / Command | Purpose |
| :--- | :--- |
| **`along-init`** (`/along-init`) | Scaffold/refresh `AGENTS.md` + `CLAUDE.md` + `.along/` in a folder via the deterministic `along init` engine; a root `VISION.md` moves into `.along/`. |
| **`along-update`** (`/along-update`) | One-liner update of repository context, protocol, and global skills from GitHub. |
| **`along-version-bump`** (`/along-version-bump`) | Multi-stack version bump and release orchestrator (Node, Python, Rust, .NET). |

### 2. Orchestration, Planning & Multi-Agent Teams
| Skill / Command | Purpose |
| :--- | :--- |
| **`along-team`** (`/along-team`) | Sequential multi-agent autonomous development engine and living plan. |
| **`along start`** | Atomically claim issue, initialize session blackboard, and provision worktree. |
| **`along issue`** | Create, update (fuzzy milestones, priority), show, and close issues. |
| **`along milestone`** | Synchronize bidirectional target issues, calculate progress %, and show status. |
| **`along-issue-sync`** (`/along-issue-sync`) | Reconcile active issue board projection (`ISSUES.md`) with atomic issue files. |
| **`along-decision-sync`** (`/along-decision-sync`) | Record ADRs into append-only `.along/DECISIONS.md` and compile active `.along/CONSTRAINTS.md`. |

### 3. Development & Lifecycle Execution Runners
| Skill / Command | Purpose |
| :--- | :--- |
| **`along-build`** (`/along-build`) | Project build lifecycle hook via `.along/scripts/build.py` or auto-detected runner. |
| **`along-test`** (`/along-test`) | Automated test suite with quiet flags via `.along/scripts/test.py` or runner. |
| **`along-dev`** (`/along-dev`) | Local development/debugging server via `.along/scripts/dev.py` or runner. |

### 4. Quality Gates, Code Graph & Commit Integrity
| Skill / Command | Purpose |
| :--- | :--- |
| **`along-commit`** (`/along-commit`) | Smart ASCII-clean Conventional Committer linked to active `.along/` issue. |
| **`along hook verify`** (`along hook`) | Verify bi-directional traceability between prose badges and YAML gates, and print which layer (runtime, git, ci) enforces each gate. |
| **`along gates check`** | Commit-time gates outside agent runtimes: `--hook pre-commit` / `--hook commit-msg` (opt-in via `along hooks install --git`) or `--ci` over a commit range. |
| **`along git setup`** | Register merge drivers for projections and entity front-matter (`along git sync` after a merge). |
| **`along-graph-check`** (`/along-graph-check`) | Preflight health check and verification for `code-review-graph` AST engine. |
| **`along-graph-sync`** (`/along-graph-sync`) | Build or incrementally update `code-review-graph` AST code intelligence database. |
| **`along-graph-impact`** (`/along-graph-impact`) | Determine blast radius, affected flows, and candidate tests for changed symbols or files. |
| **`along-graph-arch`** (`/along-graph-arch`) | Architectural overview, community structure, coupling hotspots, and bridge nodes. |
| **`along-dep-scan`** (`/along-dep-scan`) | Scan declared dependencies for AI instructions into `docs/topic--dependencies.md`. |
| **`along context-budget`** (`along budget`) | Context budget measurement and regression gate (`--check`, `--json`). |

### 5. Knowledge Base & LLM-Wiki Intelligence
| Skill / Command | Purpose |
| :--- | :--- |
| **`along-kb-sync`** (`/along-kb-sync`) | Idempotent LLM-Wiki Knowledge Base compiler, AST symbol grounding, and link integrity gate in `docs/`. |
| **`along-kb-search`** (`/along-kb-search`) | Zero-vector local multi-scope snippet search across `docs/`, ADRs, issues, and session logs (< 150 tokens/match). |

### 6. Visual Analytics, History & Diagnostics
| Skill / Command | Purpose |
| :--- | :--- |
| **`along-dash`** (`/along-dash`) | Launch executive dashboard (Web UI, CLI, Cytoscape DAG, HTML export). |
| **`along-history-sync`** (`/along-history-sync`) | Reconstruct `.along/` milestones, issues, and sessions from Git commits. |
| **`along-feedback`** (`/along-feedback`) | System self-diagnostics, incident logging, and feedback dispatch. |
| **`along-wrap`** (`/along-wrap`) | Unified end-of-stage wrap: verification checklist, session log, issues, history. |

---

## License

MIT License. See [LICENSE](./LICENSE) for details.

---

## Document: AGENTS.md (Agent Conventions & Protocol)

<!-- BEGIN ALONG-PROTOCOL root (managed by along-init - do not edit by hand) -->
# ALONG-PROTOCOL v4.9.0

This repo carries its own agent context, provider-agnostically. Follow it every session, whatever tool you are. This is the core; procedures (completion checklist, doc routing, merges, along-team, tool-use rules) live in `.along/PROTOCOL.md` - pull the section you need via `/along-kb-search`. A gate's error message carries its detail.

## Where state lives
- **Nearest wins**: any folder may carry `AGENTS.md` + `.along/`; use NEAREST for your working area: nearest `.along/` > parent `.along/` > global config. A nested `.git` or `along init` makes a subproject.
- **Read at session start** (not auto-loaded): `.along/ISSUES.md`, `.along/CONSTRAINTS.md`, your issue `.along/ISSUES/<type>--<slug>.md`; when relevant `.along/VISION.md`, `.along/GLOSSARY.md`. They reflect the state WHEN WRITTEN - verify named files/APIs/flags against the code.
- **Entities**: issues (`feat|bug|debt|task|docs|spike`), ADRs (`.along/DECISIONS/`, never edited - superseded), milestones, sessions. Keys `<type>--<slug>`, referenced by key, never by path; schemas in `docs/topic--domain-model.md`. Create them from intent unprompted (build/fix -> issue, blocked -> issue tagged `risk`, compare -> `spike` issue, release -> milestone).
- **Projections** (`ISSUES.md`, `DECISIONS.md`, `CONSTRAINTS.md`, `docs/INDEX.md`) are compiled: on conflict take either side and re-run the sync.
- **Authority & Discovery**: Entity location and plan approval come from the CLI (`along issue find <slug>`, `along plan status`) or issue front matter (`plan_status`). Projections are compiled overviews and may lag or omit subproject details. Before reporting an entity as missing, search all nested contexts with `along issue find <slug>`.

## Anchor work to an issue
1. Find or create the issue with `status: in-progress`; `along start <slug>` binds this session.
2. Source edits unlock after the user approves the plan (`EnterPlanMode` -> `ExitPlanMode`, or `along plan approve --plan-file <path>` after their explicit yes). Questions get read-only answers.
3. Commit via `/along-commit`: bound to the slug, no AI `Co-Authored-By:` trailers.
4. Finish with the completion checklist, ending in `along wrap <slug> --summary "..." (--decisions <ADR...> | --no-decisions)`.

## Gates
Runtime hooks enforce these where installed; elsewhere (`along doctor` shows the level) self-apply every one and use the `along` CLI instead of raw tools.
- [gate: require-active-issue] [gate: require-plan-approval] - no source edit without an in-progress issue and an approved plan.
- [gate: subproject-boundary] - a subproject's entities go in ITS `.along/`; cross-subproject work needs an issue in each, or a root umbrella with `parent:` children.
- [gate: workspace-containment] - read/write inside the workspace (plus temp); other roots need `allowed_roots`; never credential stores.
- [gate: projection-protection] - never hand-edit or hand-merge projections.
- [gate: commit-issue-binding] - every commit names the active issue.
- [gate: issue-lifecycle] [gate: entity-reference-integrity] [gate: entity-deletion-protection] - close via `along wrap` / `along issue done`; rename or supersede, never delete a referenced entity.
- [gate: doc-manual-lock] - `write_policy: manual` docs change only under a `docs--<slug>` issue.
- [gate: rule-pack-protection] - never edit `.along/rules/**/*.md` (`along rules attach` owns them).
- [gate: doc-routing-compliance] - ADR vs `README.md` vs `docs/topic--*.md` routing tree.
- [gate: untracked-exports] - dashboards and `.along/diagnostics/` stay out of Git.
- [gate: cli_safety] - file content via file tools, never heredocs or `python -c`; no global installs.
- [gate: team-step-active] [gate: team-reviews-before-stop] - an `along-team` blackboard holds you to its step loop.
- [gate: test_before_stop] [gate: wrap_before_stop] [gate: projection_sync_before_stop] - before stopping: tests (per the approved verify policy) run after your last edit, session wrapped, projections synced.
- [gate: unresolved_gate_denial] - a denied tool call is redone within the gate's rules or told to the user (`along gates ack`), never dropped silently; closing waits for their reply.
- Commit-time (`along lint`, pre-commit + CI): ASCII typography, fence languages, relative links, no `docs/` -> `.along/` links, Windows-safe names, no secrets, no stubs.
- Bypass is the user's call: `-n`, `--force-reason`, `scratch fallback` need `--reason` after their reply; recorded in `along gates stats`.

## Judgment rules
- Ground facts in code, `README.md` and `docs/`; no generic placeholders. Query `/along-kb-search` before reading whole docs; update affected `docs/topic--*.md` after non-trivial changes.
- Use `/along-test`, `/along-build`, `/along-dev` before raw commands, with quiet flags. Review your diff and blast radius (`along graph-impact`).
- Never delete or truncate docs, comments or code unless told; no stubs; check `git diff --stat` after batch edits. Verify written files parse. Tests stay hermetic.
- Stay in scope: failures your issue did not cause (red at HEAD, untouched code) are reported and filed as an issue, never fixed under this one; never edit tests or fixtures to make them pass unless the issue is about them; bypass (`-n --reason`) only after the user's reply.
- Scope > 3 files, crossing subsystems or refactoring core engines: route to `along-team`; plans MUST declare `Execution Mode: Direct` or `Role-Based`.
- Treat the `along` CLI as a black box (`along <cmd> --help`, no engine source outside the Along repo); report its errors verbatim.
<!-- END ALONG-PROTOCOL -->

## Project specifics

<!-- BEGIN ALONG-RULES -->
See the following engineering guidelines:
- `[languages/python.md](.along/rules/languages/python.md)`
- `[languages/typescript.md](.along/rules/languages/typescript.md)`
- `[platforms/web.md](.along/rules/platforms/web.md)`
<!-- END ALONG-RULES -->

This repository is **ActDim Along** (`actdim-along`) - the provider-agnostic agent-context protocol and skills suite.

- **Skills Source**: `skills/` (`along-init`, `along-update`, `along-dash`, `along-wrap`, `along-commit`, `along-build`, `along-test`, `along-dev`, `along-team`, `along-kb-sync`, `along-kb-search`, `along-issue-sync`, `along-decision-sync`, `along-history-sync`, `along-graph-check`, `along-graph-sync`, `along-graph-impact`, `along-graph-arch`, `along-dep-scan`, `along-version-bump`, `along-feedback`).
- **Engines**: `scripts/` (one per skill) on shared `scripts/alongkit/` package. Helpers live there only (`tests/test_alongkit.py` checks). Runtime dep: `ruamel.yaml`.
- **Typography**: `along sanitize [--write]`; `/along-commit` and `/along-version-bump` abort on it (`--fix-typography` rewrites). Scope: `.md .py .sh .ps1 .bat`.
- **Release**: `/along-version-bump`: pre-mutation gates, rollback via `alongkit.transaction.FileTransaction`.
- **Migration**: `migrate_protocol.py` keeps destinations, union-merges append-only files, backs up to `.along/.migration-backup/`.
- **Install**: `install.ps1 -Target all` / `install.bat` (Windows), `bash install.sh` (Unix); `-Uninstall` / `--uninstall`; manifest `~/.along/install-manifest.json`.
- **Lifecycle**: Tests: `python .along/scripts/test.py`. Dev: `npm run dev`. Build: `npm run build`.
- **Frontend** (`packages/dashboard-ui/`): Internal dashboard. Governed exclusively by `@actdim/ui-core` (`packages/dashboard-ui/node_modules/@actdim/ui-core/docs/INDEX.md`). Application-specific architecture: `[packages/dashboard-ui/docs/topic--architecture.md](./packages/dashboard-ui/docs/topic--architecture.md)`. NSwag client via `@actdim/msgmesh/adapters`, 100% typed (zero `any`/`as`).

---

## Document: docs/topic--agent-run-protocol.md (Agent Run Protocol (ARP/AEP) & OpenTelemetry Engine)

# Agent Run Protocol (ARP/AEP) & OpenTelemetry Engine

## 1. System Topology & Architecture Overview

The Along Agent Run Protocol (ARP), also referred to as the Agent Execution Protocol (AEP), defines a standardized observability, telemetry, and execution tracking engine for autonomous agent workflows. Modern AI agent operations execute non-deterministic cycles of LLM inference, multi-step chain reasoning, external tool usage, and subprocess execution. Without rigorous runtime tracing, debugging multi-agent swarms, identifying token bottlenecks, and investigating protocol violations becomes intractable.

The ARP engine bridges semantic OpenInference standards and OpenTelemetry (OTel) GenAI semantic conventions into Along. It provides real-time, vendor-neutral telemetry with local disk buffering and offline survivability, implemented entirely within Along Core using only the Python standard library (no third-party OpenTelemetry SDK dependencies required).

```text
+-----------------------------------------------------------------------------------+
|                            Along Agent Runtime (Harness)                          |
|                                                                                   |
|  +-----------------------------------------------------------------------------+  |
|  |                        Root Span: SpanKind.AGENT                            |  |
|  |    along.run.id, along.issue.slug, along.agent.name, along.observability    |  |
|  +-----------------------------------------------------------------------------+  |
|          |                                              |                         |
|          v                                              v                         |
|  +-----------------------------+              +--------------------------------+  |
|  |    SpanKind.CHAIN (Step)    |              |     SpanKind.TOOL (Execution)  |  |
|  |   turn_seq, phase, retries  |              |    tool.name, process.cmd      |  |
|  +-----------------------------+              +--------------------------------+  |
|          |                                              |                         |
|          v                                              v                         |
|  +-----------------------------+              +--------------------------------+  |
|  |     SpanKind.LLM (Model)    |              |    Subprocess: run_capture     |  |
|  |   gen_ai.usage, prompt/resp |              |   pid, exit_code, stdout/err   |  |
|  +-----------------------------+              +--------------------------------+  |
+-----------------------------------------------------------------------------------+
                                         |
                       +-----------------+-----------------+
                       |                                   |
                       v                                   v
        +-----------------------------+     +-----------------------------+
        |     Sensitive Data Scrub    |     |      Payload Offloading     |
        |        class Redactor       |     |   class ArtifactOffloader   |
        |  API keys, tokens, paths    |     |   >10 KB or >50 lines to    |
        +-----------------------------+     |  .along/artifacts/<run_id>/ |
                       |                    +-----------------------------+
                       +-----------------+-----------------+
                                         |
                                         v
                         +-------------------------------+
                         |     Export & Failover Engine  |
                         |      class OTLPExporter       |
                         +-------------------------------+
                                         |
                    +--------------------+--------------------+
                    | (HTTP 2xx Success)                      | (Connection Error / Timeout)
                    v                                         v
     +-----------------------------+          +-----------------------------------+
     |   OTel / OTLP Collector     |          |  Local Write-Ahead Log (WAL)      |
     |   http://localhost:4318     |          |  class Spooler                    |
     |   /v1/traces                |          |  .along/telemetry/spool/<run>.wal |
     +-----------------------------+          +-----------------------------------+
                                                              |
                                                              | along telemetry flush
                                                              v
                                              +-----------------------------------+
                                              | Flushed to Collector on Reconnect |
                                              +-----------------------------------+
```

Telemetry is instrumented non-intrusively across the core Along architecture:
- Session Blackboards and Agent Lifecycle: Tracks execution turns, plan revisions, and autonomous task completions.
- Subprocess Execution via `run_capture`: Captures terminal process invocations, exit codes, process IDs, and outputs.
- Declarative Gate Enforcements: Hooks report gate validations directly into active spans.
- Offline-First Durability: Telemetry never disrupts agent runs if the network is absent or the OTel collector is offline.

---

## 2. Core Components & Span Hierarchy

The telemetry architecture centers on six core modules under `scripts/alongkit/telemetry/`:

### 2.1 Span Taxonomy & Semantic Hierarchy (`SpanKind`)
The engine categorizes execution scopes into four distinct `SpanKind` classifications:
1. `SpanKind.AGENT`: The root span representing the end-to-end agent run. Carries run metadata including `along.run.id`, `along.issue.slug`, `along.agent.name`, and `along.observability.level`.
2. `SpanKind.CHAIN`: Represents sequential reasoning chains, workflow steps, or multi-turn loops. Carries turn sequences (`along.turn.seq`), step titles (`along.turn.title`), phases (`along.turn.phase`), and retry counters (`along.turn.retries`).
3. `SpanKind.TOOL`: Encompasses external tool executions, file system operations, and shell executions. Carries `tool.name`, `tool.parameters`, and process execution details.
4. `SpanKind.LLM`: Encapsulates prompt evaluations, model inference calls, and token generation. Carries OpenInference model metadata (`llm.model_name`), standard OTel GenAI system identifiers (`gen_ai.system`), and token usage counters (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`).

### 2.2 Trace Coordinator (`Tracer`)
`Tracer` coordinates trace context across nested execution scopes. It manages:
- 128-bit W3C-compliant Trace IDs (`trace_id` as a 32-character hexadecimal string) and 64-bit Span IDs (`span_id` as a 16-character hexadecimal string).
- Stack-based active span scoping via `start_span(...)`, context managers, and `end_span(...)`.
- Automatic linkage of child spans to their `parent_span_id`.
- Global ambient registration via `Tracer.set_active(tracer)` and `Tracer.get_active()`, allowing detached subroutines such as subprocess execution to attach telemetry to active turns without manual dependency plumbing.

### 2.3 Secret Redactor (`Redactor`)
Prior to buffering or exporting any span attributes, span events, or payload text, `Redactor` scrubs confidential credentials:
- Private Cryptographic Keys: Scans for PEM blocks (`-----BEGIN RSA/EC/OPENSSH/DSA PRIVATE KEY-----`) and replaces them with `[REDACTED_PRIVATE_KEY]`.
- Anthropic API Keys: Detects `sk-ant-(api03-)?...` keys and replaces them with `sk-ant-[REDACTED]`.
- OpenAI API Keys: Detects `sk-...` and `sk-proj-...` keys and replaces them with `sk-[REDACTED]`.
- GitHub Access Tokens: Detects `ghp_`, `gho_`, `ghu_`, `ghs_`, `ghr_`, and fine-grained `github_pat_` tokens, replacing them with `[REDACTED_GITHUB_TOKEN]`.
- AWS Access Keys: Detects `AKIA...` and `ASIA...` 20-character keys, replacing them with `[REDACTED_AWS_KEY]`.
- Bearer Authorization Headers: Detects `Bearer <token>` HTTP headers and masks values.
- Generic Password & Secret Assignments: Matches `api_key = "..."`, `password: "..."`, and `client_secret: "..."`, masking the literal values.
- Home Directory Paths: Normalizes absolute user directory paths across Windows (`C:\Users\<user>`), macOS (`/Users/<user>`), and Linux (`/home/<user>`) to prevent leaking local developer usernames.

### 2.4 Artifact Offloader (`ArtifactOffloader`)
Large terminal outputs, build logs, and multi-megabyte tool payloads degrade OTel collector performance and exceed message limits. The `ArtifactOffloader` applies deterministic size threshold rules:
- Offload Trigger: Any text payload exceeding 10 KB (10,240 bytes) OR exceeding 50 lines of text.
- Storage Location: Persisted atomically under `.along/artifacts/<run_id>/<sha256>.<ext>`.
- Truncated Inline Preview: The span attribute retains a 20-line, 1,000-character preview ending with an explicit reference marker: `... [Output offloaded to .along/artifacts/<run_id>/<sha256>.<ext> (<bytes> bytes, <lines> lines)]`.
- Metadata Annotation: Generates an `ArtifactRef` data structure recording the file path, SHA-256 digest, exact byte count, line count, and MIME type.
- Distilled Observations: When a command runs through `proc.run_capture(distill=True)`, `Tracer.record_command_result(observation=...)` sets the span output to the distilled observation (`alongkit.distill`, at most 50 lines / 2 KB) and force-offloads the raw stdout and stderr to the artifact whatever their size (`maybe_offload(force=True)`). The active execution span stays small, and the raw text remains reachable through `along.artifact.ref`.

### 2.5 Fail-Open Write-Ahead Log Spooler (`Spooler`)
If network export fails or the OTel collector endpoint is unreachable, the engine never crashes or interrupts agent workflows:
- Disk WAL Spool: Records spans immediately as newline-delimited JSON (JSON lines) into `.along/telemetry/spool/<run_id>.wal`.
- Durability: Flushes and executes `os.fsync` after writing each span line.
- Re-read & Clearance: Supports atomic extraction (`read_spool()`) and safe deletion (`clear()`) once exported.

### 2.6 OTLP Exporter (`OTLPExporter`)
`OTLPExporter` formats spans into the official OpenTelemetry `v1/traces` JSON schema via `build_otlp_payload(...)` and transmits batches via HTTP POST:
- Default Endpoint: `http://localhost:4318/v1/traces`.
- Fallback & Spooling: If an HTTP connection error or timeout occurs, `OTLPExporter` automatically offloads the failed batch to the local `Spooler`.
- Deferred Flushing: Provides `flush_spool(...)` to replay stored WAL records once connectivity resumes.

---

## 3. Data Flow & Telemetry Execution Workflows

Telemetry generation flows hierarchically throughout an agent session:

```text
Agent Harness           Tracer / Stack             Redactor / Offloader         OTLP / Spooler
     |                         |                            |                          |
     |--- start_run() -------->|                            |                          |
     |                         |-- create AGENT span ------>|                          |
     |                         |<-- sanitized root span ----|                          |
     |                         |                                                       |
     |--- step / turn -------->|                                                       |
     |                         |-- create CHAIN span ------>|                          |
     |                         |<-- sanitized turn span ----|                          |
     |                         |                                                       |
     |--- run_capture(cmd) --->|                                                       |
     |        |                |-- create TOOL span ------->|                          |
     |        v                |                            |-- maybe_offload() ------>| (if >10KB / >50 lines)
     |    subprocess.Popen     |                            |   write to .along/art..  |
     |    proc.communicate()   |                            |<-- preview + ArtifactRef |
     |        |                |-- record_command_result -->|                          |
     |        |                |                            |-- sanitize_text() ------>|
     |        |<---------------|                            |<-- clean stdout/stderr --|
     |                         |                                                       |
     |--- end_span() --------->|                                                       |
     |                         |-- buffer span -------------+                          |
     |                         |                            |                          |
     |--- end_run() ---------->|                            |                          |
     |                         |-- flush_buffered_spans --->+------------------------->|
     |                         |                                                       |-- HTTP POST to OTLP
     |                         |                                                       |   (on fail: write WAL)
```

### 3.1 Subprocess Telemetry Integration (`proc.run_capture`)
All text-capturing subprocess calls in Along execute via `alongkit.proc.run_capture`. Telemetry is linked automatically:
1. Active Tracer Discovery: When `run_capture` is invoked, it queries `Tracer.get_active()`. If an active tracer and span exist, subprocess execution attaches directly to that span context.
2. Timeouts: `run_capture` does not judge commands (there is no circuit breaker, `debt--gate-simplification`). A process that exceeds its `timeout` is reported as a failed result (`timed out after <n>s`); runner timeouts handle hangs.
3. Execution Metrics: On process completion, `run_capture` captures process ID (`process.pid`), complete command line (`process.command_line`), and process return code (`process.exit.code`).
4. Output Scrubbing & Offloading: The command stdout and stderr are scrubbed through `Redactor.sanitize_text(...)`. If the output exceeds 10 KB or 50 lines, `ArtifactOffloader` saves the raw stream to `.along/artifacts/<run_id>/` and returns a truncated preview with the artifact digest.

---

## 4. Invariants, Failure Modes & Redaction Guarantees

The telemetry subsystem adheres to four non-negotiable architectural guarantees:

### 4.1 Fail-Open Telemetry Invariance
Telemetry is strictly auxiliary. An agent run MUST NEVER fail due to telemetry network failures, collector downtime, disk serialization errors, or OTel schema changes:
- Network Outages: When HTTP requests to the collector fail or time out, spans are routed to `.along/telemetry/spool/<run_id>.wal`.
- Spool Failures: If disk write permissions fail, exceptions are suppressed, and the primary agent execution proceeds unaffected.
- Zero Execution Blocking: Telemetry calls utilize non-blocking routines or strict timeouts (default exporter timeout: 3.0s, connectivity probe timeout: 1.5s).

### 4.2 Credential Redaction Invariance
Under no circumstances may plaintext API tokens or developer credentials appear in exported OTel payloads, local WAL logs, or offloaded artifacts. Redaction rules are evaluated in deterministic precedence (e.g. `sk-ant-` evaluated before generic `sk-` tokens) to ensure complete masking.

### 4.3 Clean ASCII Storage Standard
All emitted JSON files, WAL records, artifacts, and documentation follow strict Clean ASCII encoding:
- Prohibited Characters: Unicode em-dashes, typographic curly quotes, unicode ellipses, non-breaking spaces, and BOM markers are strictly barred.
- Deterministic Serialization: `json.dumps(..., ensure_ascii=True)` guarantees transport compatibility across heterogeneous platforms and terminals.

### 4.4 Idempotent Spool Flushes
Flushing buffered WAL logs is atomic:
- Span payloads are transmitted to the OTLP collector.
- Upon receiving HTTP 2xx confirmation from the endpoint, the corresponding `.wal` files are cleared.
- If export fails, the WAL files remain intact on disk, allowing subsequent retry via `along telemetry flush`.

---

## 5. CLI Reference & Telemetry Administration

Along provides dedicated administrative CLI subcommands under `along telemetry`:

### 5.1 Telemetry Status (`along telemetry status`)
Inspects the local telemetry buffer, pending WAL spool files, and collector connectivity:

```bash
along telemetry status [--json] [--endpoint <url>]
```

Parameters and behavior:
- `--json`: Emits structured machine-readable JSON containing `wal_count`, `total_bytes`, `endpoint`, `connected`, `endpoint_status`, and `wal_files`.
- `--endpoint <url>`: Overrides the target OTLP endpoint to test (defaults to `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`, `ALONG_TELEMETRY_ENDPOINT`, `OTEL_EXPORTER_OTLP_ENDPOINT`, or `http://localhost:4318/v1/traces`).
- Connectivity Probe: Sends an empty OTLP test payload with a fast 1.5s timeout. Reports connection status without blocking.

Terminal output example:
```text
Along Telemetry Status:
  Endpoint:      http://localhost:4318/v1/traces [unreachable (timed out)]
  Spool Dir:     /path/to/repo/.along/telemetry/spool
  Pending WALs:  2 file(s)
  Spooled Size:  4820 bytes
  WAL Files:
    - 372d529afe5e4c5392e396b08d799b5a.wal (2410 bytes)
    - 8a91b2c3d4e5f60718293a4b5c6d7e8f.wal (2410 bytes)
```

JSON output example:
```json
{
  "wal_count": 2,
  "total_bytes": 4820,
  "endpoint": "http://localhost:4318/v1/traces",
  "connected": false,
  "endpoint_status": "timed out",
  "spool_dir": "/path/to/repo/.along/telemetry/spool",
  "wal_files": [
    {
      "name": "372d529afe5e4c5392e396b08d799b5a.wal",
      "size_bytes": 2410
    },
    {
      "name": "8a91b2c3d4e5f60718293a4b5c6d7e8f.wal",
      "size_bytes": 2410
    }
  ]
}
```

### 5.2 Telemetry Flush (`along telemetry flush`)
Replays and exports all spooled spans to the active OTLP collector:

```bash
along telemetry flush [--endpoint <url>]
```

Parameters and behavior:
- `--endpoint <url>`: Overrides the target endpoint.
- Reads all `.wal` files under `.along/telemetry/spool/`.
- Transmits spans via `OTLPExporter(endpoint=...)`.
- On HTTP 2xx success: Clears the flushed `.wal` files and prints the total number of flushed spans.
- On network failure: Retains the WAL files on disk, reports the error to `stderr`, and exits with code 1.

## 6. Agent Runtime Runners & Antigravity Supervisor

Along provides supervised process launchers for native AI agent environments under `alongkit.runner`.

### 6.1 Antigravity Runtime Runner (`along run antigravity`)

The Antigravity runner (`alongkit.runner.antigravity.AntigravityRunner`) supervises Google Antigravity processes, enforcing workspace containment, active issue binding, and dual-channel telemetry.

```bash
along run antigravity [--dry-run] [-i|--issue <slug>] [--run-id <id>] [-e|--endpoint <url>] [-b|--binary <path>] [-- <agent-args...>]
along run agy [--dry-run] [-i|--issue <slug>] [--run-id <id>] [-e|--endpoint <url>] [-b|--binary <path>] [-- <agent-args...>]
```

#### Dual-Channel Observability Model
1. **Hook Channel (`antigravity_hook`)**: The lifecycle gate hook (`along_hook.py --runtime antigravity`) intercepts `PreToolUse` and `PostToolUse` events from the Antigravity IDE, recording structured tool spans with parameter verification, execution duration, and exit codes.
2. **Stream Channel (`stdout_stream`)**: The `ChunkedStreamSupervisor` captures child process stdout and stderr in binary mode, chunking output at 200 ms or 64 KB boundaries into `SpanEvent` records, while simultaneously teeing to the console and persisting logs to `.along/artifacts/<run_id>/stdout.log` and `stderr.log`.

#### Environment Variable Contract
When spawning the Antigravity runtime, the supervisor injects the following context variables:
- `ALONG_RUN_ID`: Unique hexadecimal run ID (32 chars) linking all spans and artifacts.
- `ALONG_ISSUE_SLUG`: Active issue key bound to the session (enforces `require-active-issue` gate).
- `ALONG_REPO_ROOT`: Absolute path to repository root, enforcing workspace containment.
- `ALONG_OBSERVABILITY_LEVEL`: Set to `complete` for full dual-channel tracing.
- `ALONG_OBSERVABILITY_SOURCES`: Set to `antigravity_hook,stdout_stream`.
- `ALONG_OTEL_ENDPOINT`: Optional OTLP trace collector endpoint.
- `PYTHONIOENCODING`: Forced to `utf-8`.
- `PYTHONUTF8`: Forced to `1`.

Note: Google Antigravity is a desktop IDE environment and is available only through `along run antigravity` / `along run agy`. It is not offered as a headless orchestrator runtime.

### 6.2 Headless Agent CLI Runtime Adapters

Headless CLI runners (`alongkit.runner`) provide non-interactive process supervision for autonomous agent workflows across Claude Code, OpenAI Codex, OpenCode, and generic CLI workers.

#### Verified CLI Contracts and Fixtures
Each adapter's command-line interface is bound to a verified CLI release with `--help` and sample output fixtures stored in `tests/fixtures/runtimes/<tool>/<version>/`:
- **Claude Code (`ClaudeCodeRunner`, runtime: `claude`, `claude-code`)**: Verified against version `2.1.228`.
  - Command: `claude -p --output-format json --no-session-persistence [--model <model>] [--dangerously-skip-permissions]`
  - Output: Single JSON object (`type`, `subtype`, `is_error`, `result`, `total_cost_usd`, `usage`).
- **OpenAI Codex (`CodexRunner`, runtime: `codex`)**: Verified against version `0.158.0`.
  - Command: `codex exec --json --color never -C <repo_root> [-m <model>] [--sandbox workspace-write] -`
  - Output: Streaming JSONL events (`thread.started`, `turn.started`, `item.completed`, `turn.completed`).
- **OpenCode (`OpenCodeRunner`, runtime: `opencode`)**: Verified against version `1.18.32`.
  - Command: `opencode run --format json --dir <repo_root> [-m <model>] [--auto]`
  - Output: Streaming JSONL events (`step_start`, `text`, `tool_use`, `step_finish`).
- **Generic CLI (`GenericCliRunner`, runtime: `generic`)**: Executes custom binaries or commands, buffering line output.

#### Brief Delivery via Stdin
To protect against OS command-line argument limits (such as the 8191-character limit on Windows `cmd.exe` shims) and argument re-parsing issues, prompt briefs are passed exclusively via standard input (`stdin`). Standard input is closed (`DEVNULL`) when unused.

#### Allowlisted Process Environment
To prevent leakage of host secrets (such as Telegram bot tokens, global keys, or credentials belonging to other providers), child processes receive an allowlisted environment only:
- Core environment: `PATH`, `PATHEXT`, `HOME`, `USERPROFILE`, `LOCALAPPDATA`, `APPDATA`, `TEMP`, `TMP`, locale (`LANG`, `LC_*`).
- Runtime-specific keys:
  - Claude: `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_BASE_URL`, `CLAUDE_CONFIG_DIR`, `CLAUDE_CODE_*`.
  - Codex: `OPENAI_API_KEY`, `OPENAI_BASE_URL`, `CODEX_HOME`.
  - OpenCode: `OPENAI_API_KEY`, `OPENAI_BASE_URL`, `OPENCODE_*`.
- Explicit passthrough: Configured via `env_passthrough: [VAR_NAME, ...]`.

#### Process-Tree Termination
Subprocess execution uses new process groups (`CREATE_NEW_PROCESS_GROUP` on Windows, `start_new_session=True` on POSIX). On execution timeout:
- Windows: Terminates entire process trees via `taskkill /PID <pid> /T /F`, preventing orphaned tool processes or lingering npm `.cmd` shims.
- POSIX: Signals process groups via `os.killpg(pgid, signal.SIGTERM)` followed by `SIGKILL` after a grace deadline.

---

## Document: docs/topic--architecture.md (System Architecture & Flow)

# System Architecture & Flow

ActDim Along (`actdim-along`) is a provider-agnostic agent-context, project memory, and documentation protocol designed to give software repositories a persistent, durable, token-efficient, and human-readable context layer.

---

## 1. System Topology & Architecture

Along operates as a modular, three-layer architecture spanning host AI agent runtimes, repository-native persistent memory, and integrated execution tooling:

```mermaid
flowchart TD
    subgraph HostAgents["Host AI Agent Runtimes"]
        CC["Claude Code (~/.claude)"]
        CX["Codex (~/.codex)"]
        OC["OpenCode (~/.config/opencode)"]
        AG["Antigravity (~/.gemini/config)"]
    end

    subgraph MemoryLayer["Repository Persistent Memory (.along/ & docs/)"]
        AGENTS["AGENTS.md (Root Protocol & Conventions)"]
        ALONG_DIR[".along/ (Living Project State: ISSUES, DECISIONS, SESSIONS)"]
        DOCS["docs/ (Compiled LLM-Wiki Knowledge Base)"]
        EXPORTS["llms.txt & llms-full.txt (.well-known/ or root)"]
    end

    subgraph MultiAgentEngine["Multi-Agent Orchestration & Execution"]
        TEAM["Sequential State Machine (/along-team)"]
        BLACKBOARD[".along/.session/<slug>/ (Ephemeral Blackboard)"]
        LIFECYCLE["Lifecycle Suite (build, test, dev, commit, wrap)"]
    end

    subgraph ToolingAndAST["Tooling & Code Intelligence"]
        CRG["along graph-* CLI (code-review-graph AST Engine)"]
        WIKI_SEARCH["along-kb-search (Fast Multi-Scope Retrieval)"]
        DASH["FastAPI Dashboard + Cytoscape DAG (/along-dash)"]
    end

    CC --> AGENTS
    CX --> AGENTS
    OC --> AGENTS
    AG --> AGENTS

    AGENTS --> ALONG_DIR
    AGENTS --> DOCS
    DOCS --> EXPORTS
    ALONG_DIR --> TEAM
    TEAM --> BLACKBOARD
    TEAM --> LIFECYCLE
    LIFECYCLE --> CRG
    DOCS --> WIKI_SEARCH
    ALONG_DIR --> DASH
```

---

## 2. Provider Compatibility & Discovery Paths

Along avoids vendor lock-in by utilizing standard agent discovery paths without requiring custom binary daemons:

| Host Agent | Discovery & Context Entry Point | Skills Installation Target | Execution Mechanism |
| :--- | :--- | :--- | :--- |
| **Claude Code** | Reads `CLAUDE.md`, which references `@AGENTS.md`. | `~/.claude/skills/along-*/` | Direct slash commands (`/along-*`) and CLI tools. |
| **Codex** | Reads `AGENTS.md` natively on session initialization. | `~/.codex/skills/along-*/` | Native skill execution and prompt injection. |
| **OpenCode** | Reads `AGENTS.md` and `CLAUDE.md` natively. | `~/.config/opencode/commands/along-*.md` | Flat markdown command declarations. |
| **Google Antigravity** | Reads `AGENTS.md` (or `GEMINI.md`) natively. | `~/.gemini/config/skills/along-*/` | Slash commands, `/goal` autonomy, and CLI tools. |

---

## 3. Nearest Context Boundary & Subproject Localization

### Subproject Boundary Definition (ADR-2026-10-06)

Following [ADR-2026-10-06](./decisions/ADR-2026-10-06--subproject-boundary-is-git-or-explicit-init.md), a subproject context boundary is strictly determined by one of two conditions:
1. **A nested Git boundary**: A directory containing its own `.git` (Git submodule, nested clone, or worktree).
2. **An explicit user initialization**: A directory where the user explicitly executed `along init`.

Package manifests alone (`package.json`, `Cargo.toml`, `*.csproj`, `pyproject.toml`) do **not** establish a subproject boundary. In a monorepo workspace (e.g. `pnpm-workspace.yaml`, Cargo `[workspace]`, or npm workspaces), all package folders (`packages/*`) belong to the root Along context unless explicitly initialized.

### Monorepo Workspaces vs Git Submodules

Understanding the architectural distinction between Monorepo Workspaces and Git Submodules is essential for proper change management and release orchestration:

| Architectural Dimension | Monorepo Workspaces (`packages/*`) | Git Submodules (`.gitmodules`) |
| :--- | :--- | :--- |
| **Git Repositories** | Single shared `.git` repository. | Multiple distinct `.git` repositories with independent remotes. |
| **Commit Atomicity** | Atomic: A single Git commit can span changes across multiple packages. | Fragmented: Each submodule requires its own independent Git commit; the root records only a commit pointer (SHA). |
| **Context Ownership** | Root `.along/` manages issues and history across packages. | Nearest `.along/`: Each submodule maintains its own isolated `.along/` memory. |
| **Release Flow** | Single release run: `along bump` updates all package manifests in one commit. | Multi-stage orchestration: Submodules must be tested, committed, and pushed to origin before root can update their pointers. |

### Anti-Root Pollution Rule

When true subprojects exist (submodules with independent `.git` or explicit subprojects):
1. **Nearest `.along/` Boundary**: Agents MUST evaluate and write entities (`ISSUES/`, `SESSIONS/`, `DECISIONS.md`, `HISTORY.md`) to the **NEAREST** `.along/` corresponding to the modified files.
2. **Submodule Isolation**: When fixing a defect or adding a feature inside a Git submodule, the issue ticket, ADR, session log, and history line are recorded directly in that submodule's `.along/`.
3. **Parent Orchestration**: The workspace root `.along/` is reserved strictly for whole-solution orchestration, integration tasks, and cross-package architectural ADRs. Parent issues reference subproject issues via canonical keys (e.g. `[pkg-auth:feat--token-refresh]`), never by copying internal history.

---

## 4. Multi-Branch Concurrency & Git File Model

Collaborative software development requires parallel feature branches without merge conflicts on tracking files. Along solves this through a formal distinction between SSOT entities and derived projections:

### Single Source of Truth (SSOT) vs Derived Projections

```mermaid
flowchart LR
    subgraph SSOT["Single Source of Truth (Atomic Files)"]
        I["Atomic Issue Files (.along/ISSUES/<type>--<slug>.md)"]
        S["Session Journals (.along/SESSIONS/<YYYY>/<date>--<slug>.md)"]
        T["Knowledge Base Topics (docs/topic--<slug>.md)"]
    end

    subgraph Projections["Compiled Projections (Derived Views)"]
        IB["Active Issue Board (.along/ISSUES.md)"]
        KI["Knowledge Index (docs/INDEX.md)"]
    end

    I -->|along-issue-sync| IB
    T -->|along-kb-sync| KI
```

1. **Atomic SSOT Files**: Each issue (`.along/ISSUES/<type>--<slug>.md`) and session journal (`.along/SESSIONS/<YYYY>/<date>--<slug>.md`) is an isolated Markdown file with YAML front-matter. Parallel branches create distinct files, resulting in zero Git merge collisions.
2. **Derived Projections & Export Artifacts**: `.along/ISSUES.md` and `docs/INDEX.md` are dynamically compiled views tracked in Git as entry points. Under the **Zero-Manual-Merge Rule**, developers and agents never resolve Git conflicts in projection files manually: accept either version and run `/along-issue-sync` or `/along-kb-sync` to recompile cleanly from source. `along git setup` automates this with custom merge drivers: projections merge as "ours" and `along git sync` recompiles them, and entity files get a 3-way front-matter merge (see [CLI Reference](./topic--cli-reference.md)). Generated dashboards (`.along/dashboard.html`, `.along/DASHBOARD.md`) are untracked export artifacts kept out of Git via `.gitignore`.
3. **Append-Only Linear Merge Driver**: `.along/HISTORY.md` and `.along/DECISIONS.md` are append-only. `.gitattributes` configures `merge=union` for these files, enabling Git to automatically combine appended entries from concurrent branches without conflicts.

---

## 5. Engine Implementation Layer (`scripts/` and `scripts/alongkit/`)

The eighteen skills are thin: every one of them dispatches to a Python engine in `scripts/`.
Those engines share one implementation package, `scripts/alongkit/`, introduced in v3.0.0.

Before it existed, the engines were twelve standalone programs with no shared module.
`find_repo_root` had five divergent copies that disagreed on what a repository root is,
front-matter parsing had four, and `subprocess.run` was called at 25+ sites with no shared
convention, which is how one encoding defect reached every engine at once. The demonstrated
cost is recorded in `[bug--adr-retrieval-blind-to-slug-headers]`: the ADR header format
changed in v2.2.0, was updated where ADRs are written and validated, and was missed in the
reader, so ADR search returned zero results in every released version.

| Module | Owns |
| :--- | :--- |
| `alongkit/repo.py` | The installation definition (`is_installed`: Along state, never an `AGENTS.md`), root discovery (installation or `.git`), nearest `.along/` discovery, package doc roots, engine resolution, directory walking and the shared ignore set. |
| `alongkit/frontmatter.py` | The single YAML front-matter reader and writer (`ruamel.yaml`, round-trip). |
| `alongkit/commands/` | Modular command handlers for the CLI router (doctor, lifecycle, gates, ops, telemetry, session, issue). |
| `alongkit/entities/` | Modular entity subsystem (vocabulary, decisions, projections, query, mutation, validation) with backward-compatible `alongkit.entities` facade. |
| `alongkit/proc.py` | Subprocess execution with UTF-8 fixed on both sides of the pipe. |
| `alongkit/markdown.py` | Link parsing, fenced-code tracking, GitHub heading anchors, and link resolution. |
| `alongkit/typography.py` | The forbidden-character table, shared with the quality gate. |
| `alongkit/sanitizer.py` | Which files that table governs, strict reads, the modes, and the JSON report. |
| `alongkit/gates.py` | Pre-commit and pre-release test, typography, and Markdown link gates. |
| `alongkit/transaction.py` | Snapshot and byte-exact rollback around a multi-file mutation. |
| `alongkit/migration.py` | Collision policy, on-disk backup, and the dry-run plan behind the migration engine. |
| `alongkit/semver.py` | Version parsing, increments, comparison. |
| `alongkit/version.py` | The protocol version constant, declared exactly once. |
| `alongkit/bootstrap.py` | Dependency resolution for a directly invoked engine. |
| `alongkit/cli.py` | The `along` console entry point, which delegates to the `along_exec.py` router. |

### Front-matter and the runtime dependency

Front-matter is YAML because tools that are not Along read it: GitHub, static site
generators, `gray-matter`. The engines therefore use a real YAML implementation rather than
a bespoke parser. `ruamel.yaml` is chosen over `pyyaml` because round-trip mode preserves
comments, key order, and quoting style, which is what makes editing a file the user owns
safe. Reads are strict and refuse a block they cannot understand; edits name individual
keys and leave every other line byte-identical.

See [ADR-2026-09-01--frontmatter-on-ruamel-yaml](./decisions/ADR-2026-09-01--frontmatter-on-ruamel-yaml.md) and
[ADR-2026-09-01--shared-engine-package](./decisions/ADR-2026-09-01--shared-engine-package.md).

### The typography rule: what it governs, and who may rewrite

Two modules, deliberately split. `alongkit/typography.py` is the character table and a
pure string transformation; it never opens a file. `alongkit/sanitizer.py` owns every
decision that touches a user's disk.

| Question | Answer |
| :--- | :--- |
| Which files? | `.md`, `.py`, `.sh`, `.ps1`, `.bat`. Data files (`.json`, `.yaml`, `.yml`, `.toml`) only with `--include-data`. Localized resource directories (`locales/`, `i18n/`, `translations/`, ...) never. |
| Which directories? | All of them, hidden included, so a byte order mark in `.along/**` is finally visible. Excludable per repository with `.alongsanitizeignore` or `--exclude`. |
| Who may write? | Only an explicit `--write` (standalone) or `--fix-typography` (commit, release). The gates verify and abort. |
| What about a file that is not UTF-8? | Skipped, reported by path with the decode reason, left byte-identical. Never decoded lossily and rewritten. |
| What about line endings? | Preserved verbatim. Nothing parses `.gitattributes`, because preserving what a file already uses cannot contradict it. |
| What do callers consume? | `sanitizer.Report` (`--json` on stdout, human output on stderr), never printed text. |

The previous implementation did the opposite of each row and ran that way unattended
before every commit and every release. See
[ADR-2026-09-01--typography-rule-scope](./decisions/ADR-2026-09-01--typography-rule-scope.md).

### Gates precede mutations, and mutations roll back

A gate that reports after the fact is not a gate. The release engine used to bump the
version, rewrite the tree with the sanitizer, flip the milestone to `completed`, and
regenerate the dashboard, and only then run the tests - and only when `--commit` was
passed. When they failed it printed "Release aborted" and exited over a tree that was
already half-released, with nothing to undo it.

Two rules follow, and `[bug--release-engine-mutates-before-tests-and-reinstalls-globals]`
records what each of them cost:

1. **Every gate runs on the untouched tree, unconditionally.** Tests, the typography check,
   and the Markdown link check all run before the first byte is written, whatever flags the
   invocation carries. `--no-verify` is the single documented way past them.
2. **Every mutation is recorded.** `alongkit/transaction.py` snapshots a file's exact bytes
   (or its absence) before anything writes to it. On failure the transaction restores each
   one and names it; a mutation it cannot undo - a project's own
   `.along/scripts/bump_version.py` writing paths the engine cannot see - is reported
   rather than assumed away. The transaction closes at the git commit, past which a
   rollback would destroy committed work instead of repairing anything.

The release also stages only the paths it wrote, rather than `git add -A`, and touches no
machine-global state: it used to finish by running `install.ps1 -Target all`, which then
deleted and recreated `~/.claude/rules`. Installing no longer deletes that directory
either; see the next section.

### An installer never deletes what it did not write

Both installers copied their artifacts over a destination they had just removed
(`Remove-Item -Recurse -Force ~/.claude/rules`), which took the user's own rule files with
it on every run. The delete existed to stop superseded files accumulating, so it is
replaced by knowledge rather than by force: `install_manifest.py` records every path an
install wrote into `~/.along/install-manifest.json`, and the next run removes, by name,
only the files the previous install wrote and this one no longer ships. The same record is
what `-Uninstall` / `--uninstall` reads.

The layout itself is described once, in `alongkit.install.planned_files`, and both
installers are measured against it end to end, so `install.sh` cannot again ship without
the rule packs the way it did for months. Code intelligence tools (`code-review-graph`)
execute directly via CLI (`along graph-*`), bypassing stdio IPC serialization overhead
and IDE authorization dialogs, while legacy MCP registration is decoupled and managed
via `configure_mcp.py --clean`.

### A migration merges; it does not choose a winner

The same failure in a different shape. The migration engine moved legacy `.agents/`
content onto `.along/` by deleting the destination first, so a repository that held both -
a partial migration, or two branches migrating separately - lost the newer `DECISIONS.md`
and `HISTORY.md`. Both are append-only by protocol, so nothing could bring them back.

`alongkit/migration.py` makes the destination untouchable. On a collision the file class
decides: append-only files are union-merged the way `.gitattributes` already merges them
across branches, derived projections keep the destination and drop the legacy copy for
recompilation, and anything else keeps the destination with the legacy copy preserved
beside it as `<name>.legacy.md`. Before the first change the state directories are copied
to `.along/.migration-backup/<timestamp>/` (machine-local state excluded, newest 5 snapshots
kept), and the copy ignores itself so it never enters history.

Where the release engine needs an in-memory transaction - undo everything, the tests
failed - a migration needs the opposite: a durable copy that outlives the process, because
it is meant to be run, inspected, and re-run. What the two share is the rule that produced
both defects: an operation that writes before it is sure, and cannot be undone, has no
business being unattended. Which is why the migration is a dry run for every caller that
is not a human at a terminal, and why installing no longer migrates at all. See
[ADR-2026-09-01--migration-never-deletes-a-destination](./decisions/ADR-2026-09-01--migration-never-deletes-a-destination.md).

### Three invocation paths, one package

```mermaid
flowchart TD
    A["along <subcommand> (console script)"] --> R["along_exec.py (router)"]
    B["python scripts/along_exec.py (source checkout)"] --> R
    C["python ~/.along/bin/along_exec.py (global file copy)"] --> R
    R --> K["alongkit (shared implementation)"]
    K --> D{"ruamel.yaml importable?"}
    D -->|Yes| E["Run"]
    D -->|No| F["alongkit.bootstrap re-executes under `uv run`"]
    F --> E
```

Python places the running script's own directory on `sys.path`, and the installers copy
`alongkit/` next to the engines, so `from alongkit import ...` resolves in a flat
`~/.along/bin/` install with no path manipulation and no package install. When the
interpreter lacks `ruamel.yaml`, `alongkit.bootstrap` re-executes the engine under
`uv run` once; if `uv` is absent it exits with an actionable message rather than a
traceback. For the comprehensive reference of console subcommands, options, and exit codes, see [Along CLI Command Reference](./topic--cli-reference.md).

### Structural guards

Two tests keep the duplication from growing back
([tests/test_alongkit.py](../tests/test_alongkit.py)):

- no name may be defined at module level in two different engines;
- no engine may redefine a name the shared package already owns.

A third asserts that an engine still runs from a flat directory copy, and a fourth that
both installers carry the package.

A fifth structural gate enforces clean exception handling (`alongkit.gates.exception_handling_gate`),
verifying via AST analysis that zero bare `except:` or swallowed generic `except Exception: pass`
clauses exist across `scripts/` and `dashboard/`. Internal engine errors and skipped entity files
are systematically reported and recorded through centralized telemetry in `alongkit.diagnostics`
(`try_record_incident`). See [ADR-2026-09-09--error-handling-and-failure-visibility](./decisions/ADR-2026-09-09--error-handling-and-failure-visibility.md).

Two more guard the suite itself
([tests/test_zz_hermetic_suite.py](../tests/test_zz_hermetic_suite.py)): the working tree
must be byte-identical before and after a run, and no test may build an engine command
line whose target is the repository root. Engines write, so a test that passes the real
root can rewrite project memory mid-session; fixtures come from
[tests/hermetic.py](../tests/hermetic.py). See
[Writing Tests: the Hermetic Rule](./topic--setup-and-workflow.md).

---
## 6. End-to-End Human & Developer Workflow

The lifecycle of a task in Along follows a structured, low-friction flow designed to eliminate administrative burden for the developer:

```mermaid
sequenceDiagram
    autonumber
    actor Human as Developer / User
    participant Agent as Host AI Agent
    participant Memory as .along/ ISSUES & Blackboard
    participant Team as Multi-Agent Engine (along-team)
    participant Verify as Reviewer & Code Graph CLI
    participant Commit as along-commit & along-wrap

    Human->>Agent: "Implement JWT refresh token rotation"
    Note over Agent: Intent Heuristics Auto-Detects New Feature
    Agent->>Memory: Auto-create .along/ISSUES/feat--jwt-refresh-token.md
    Agent->>Team: Launch /along-team (Adaptive Sizing)
    Team->>Team: Scout (Research) -> Architect (Living Plan)
    loop Each Step in Living Plan
        Team->>Team: Implementer executes isolated code edits
        Team->>Verify: Reviewer runs tests, checks diff & blast radius
        Verify-->>Team: PASS / Feedback Loop
    end
    Agent->>Commit: /along-commit (ASCII Cleanliness + Conventional Commit)
    Agent->>Commit: /along-wrap (Session log, move to done/, update ISSUES.md)
    Agent-->>Human: Present concise executive summary
```

1. **Intent Recognition (Zero-Friction Tracking)**: Natural developer prompts ("Build feature X", "Fix bug Y", "Investigate library Z") automatically trigger the creation of typed issues (`feat`, `bug`, `spike`; a blocker is an issue tagged `risk`) in `.along/ISSUES/` without requiring manual file management.
2. **Mandatory Issue Anchoring**: All non-trivial code modifications must bind to an active issue in `.along/ISSUES/` with `status: in-progress`.
3. **Autonomous Execution**: The agent executes the task via `/along-team` or direct fast-path.
4. **Verification Gate**: Automated tests, file integrity audits, and AST blast radius checks are executed before finalizing changes.
5. **Issue-Linked Commits**: `/along-commit` checks typography (clean ASCII) and formats Conventional Commits linked directly to the issue slug.
6. **Session Wrap-Up**: `/along-wrap` moves finished issues to `.along/ISSUES/done/`, reconciles `ISSUES.md`, records `.along/SESSIONS/`, and appends to `HISTORY.md`.

---

## 7. Deep Architectural Rationale: Multi-Agent State Machine vs Single-Agent Linear Execution

A core architectural decision in Along is the deployment of a **Sequential Multi-Agent State Machine** (`/along-team`) instead of unconstrained single-agent linear execution.

### Why Single-Agent Linear Execution Fails on Complex Tasks

When a single LLM agent attempts to research, plan, write code, run tests, and review its own output in a single continuous conversation context, it inevitably succembers to three fundamental failure modes:

1. **Prompt Pollution & Context Saturation**:
   - Running terminal searches, directory listings, and build outputs dumps thousands of raw tokens into the context window.
   - By the time the agent reaches the implementation phase, the prompt is saturated with irrelevant tool noise, degrading the model's reasoning capabilities and causing context truncation.
2. **Author Bias & Hallucinated Test Passes**:
   - The same agent instance that wrote the code has severe confirmation bias. When verifying its own changes, it routinely overlooks edge cases, ignores unhandled exceptions, and accepts superficial test runs.
3. **Plan Drift on AST/Build Errors**:
   - When encountering a compilation or runtime error, a single linear agent tends to make hasty, localized patches without reassessing the overarching system architecture, leading to architectural debt.

### The Multi-Agent Sequential State Machine Solution

Along replaces unstructured chat swarms and single-agent linear loops with a deterministic **5-Phase State Machine**:

```mermaid
flowchart TD
    TASK["Developer Task / Goal"] --> ANALYZE["Phase 0: Analyze (Supervisor)"]
    ANALYZE -->|S-Size: 1-2 files| FASTPATH["Direct Single-Agent Fast-Path"]
    ANALYZE -->|M / L / XL-Size| SCOUT["Phase 1: Research Scout (research)"]
    
    SCOUT --> ARCHITECT["Phase 2: Architect (Living Plan)"]
    
    subgraph StepLoop["Step Execution Loop (Steps 1..N)"]
        WORKER["Phase 3: Implementer (self)"]
        REVIEWER["Phase 4: Gatekeeper Reviewer (self)"]
        REASSESS["Phase 5: Reassess & Living Plan Update"]
        
        WORKER --> REVIEWER
        REVIEWER -->|FAIL: Retries <= 2| WORKER
        REVIEWER -->|PASS| REASSESS
    end
    
    ARCHITECT --> StepLoop
    REASSESS -->|More Steps| StepLoop
    REASSESS -->|All Steps Complete| WRAP["Phase 7: Wrap-up (/along-wrap)"]
    FASTPATH --> WRAP
```

### Adaptive Complexity Routing (T-Shirt Sizing)

Multi-agent execution introduces context switching overhead. Therefore, Along enforces strict **Adaptive Complexity Routing**:

- **`S-Size` Tasks (1-2 files, clear scope, minor bug/tweak)**:
  - *Strategy*: **Fast-Path Single-Agent Execution**. Subagents are **NOT** spawned. The primary agent directly applies edits, runs tests, and completes the task, preserving token budget.
- **`M-Size` Tasks (3-5 files, isolated module/route)**:
  - *Strategy*: **Fast Loop** (Scout -> Worker -> Reviewer) in a single linear pass.
- **`L / XL-Size` Tasks (Cross-module refactorings, protocol changes, new subsystems)**:
  - *Strategy*: **Full State Machine** with dynamic Living Plan, step-by-step worker subagents, independent gatekeeper review, and reassess cycles.

### The 5 Specialized Roles & Strict Contracts

Along establishes 5 clearly separated functional roles:

1. **Supervisor (Lead Orchestrator)**:
   - *Responsibility*: Requirement extraction (`REQ-1`, `REQ-2`), acceptance criteria enforcement, task sizing, and gatekeeping. Runs in parent context; never writes low-level code directly in L/XL tasks.
   - *Context Pruning Rule*: The Supervisor strictly strips raw search logs and tool output from the Scout, passing only distilled facts (target files, constraints, AST symbols) to the Implementer.
2. **Researcher (Scout)**:
   - *Responsibility*: Read-only discovery. Maps existing code patterns, dependencies, and potential risks without touching file contents (`TypeName: "research"`, `enable_write_tools: false`).
3. **Architect**:
   - *Responsibility*: Executes Public Surface Discovery (searching for all mirrors across `README.md`, `AGENTS.md`, `docs/`) and converts scout findings into a concrete **Living Plan** composed of 2 to 5 verifiable steps mapped directly to `REQ-N`.
4. **Implementer (Worker)**:
   - *Responsibility*: Executes the specific step in an isolated context (`TypeName: "self"`, `Workspace: "branch"` or `"inherit"`). Focuses exclusively on the assigned step without worrying about global orchestration.
5. **Reviewer (Gatekeeper: Tester + Critic + Judge)**:
   - *Responsibility*: Evaluates the implementer's changes in an isolated context against the mandatory **6-Point Verification Rubric**:
     1. *Zero-Byte & File Integrity Gate*: `git status -u` check ensuring `size > 0` and zero empty placeholders.
     2. *Automated Test Suite*: Runs `/along-test` ensuring zero failures and increased test coverage.
     3. *Diff & Scope Audit*: Verifies that only requested files were touched without unintended edits.
     4. *Requirement Coverage Gate*: Verifies 100% satisfaction of every `REQ-N` from the initial user prompt.
     5. *AST Blast Radius & ADR Compliance*: Verifies downstream callers and checks conformance with `.along/DECISIONS.md`.
     6. *Documentation & Public Surface Parity*: Ensures both internal `docs/topic--*.md` and public entry points (`README.md`, `AGENTS.md`) reflect modifications without drift.
     7. *Clean ASCII & Typography*: Validates clean UTF-8 without forbidden typographic characters.

---

## 8. Ephemeral Session Blackboard Memory

To prevent multi-agent coordination data from leaking across sessions or cluttering the git history, Along establishes an **Ephemeral Session Blackboard**:

- **Location**: `.along/.session/<issue-slug>/` (automatically excluded in `.gitignore`).
- **Artifacts**:
  - `state.json`: Phase, approval, execution mode (`direct` / `role-based`), steps and retry counters.
  - `plan.md`: The approved Living Plan; later plans are appended as `## Revision N`.
  - `research.md`: Scout findings (symbols, constraints, patterns).
  - `execution_trace.md`: Edits, test runs with results, gate denials, approvals, phase and step changes (written by the hooks and Along commands).
  - `reviews/step-N.md`: Reviewer reports and verdicts per step.
- **Lifecycle**:
  1. *Allocated*: `along start` (direct) or `along scratch init` (role-based).
  2. *Updated*: Plan capture at approval, trace by the hooks, step state by `along scratch update`.
  3. *Archived*: `along wrap`, `along scratch purge`, `along issue done` and `along session gc` (unbound blackboards of closed issues) write the Blackboard Record into `.along/SESSIONS/<YYYY>/<date>--<slug>.md` (append-only once committed); attributed paths go to its `files:` front matter, the plan itself is not copied.
  4. *Purged*: Deleted only after the record is committed.

See [Session Lifecycle](./topic--session-lifecycle.md).

---

## 9. Historical Analysis: Documentation Truncation Incident & Prevention

During the transition to the LLM-Wiki architecture in commit `5bab25dc5b3e57c0e83b23f47b7ce221773a6e90` (2026-08-30), an automated file renaming routine accidentally replaced populated documentation files (`01-architecture.md`, `02-domain-model.md`, `03-setup-and-workflow.md`) with 13-line placeholder templates. Subsequent feature PRs updated internal skill instructions while failing to backfill the public `docs/` Knowledge Base.

### Institutionalized Quality Gates

To guarantee that documentation remains synchronized with code and is never silently truncated:
1. **Mandatory Post-Batch & Destructive Operation Audit Gate**: After executing any batch replacement, migration script, refactoring tool, or multi-file rewrite, agents MUST immediately run `git diff --stat` to verify that net line counts and file sizes align with expectations. Any unexpected net reduction in file size or line count must be inspected in detail before proceeding.
2. **Anti-Stub & Size Regression Invariant**: Automated test suite (`test_21_docs_articles_not_empty_placeholders`) and Reviewer rubrics reject any file modification that reduces substantial documentation or code to empty placeholder stubs or skeleton templates.
3. **Documentation Blast Radius Gate**: Mandatory in `/along-wrap` and `AGENTS.md`. Whenever public interfaces, commands, or system architectures change, the affected `docs/topic--*.md` articles MUST be updated before closing an issue.
4. **Link Integrity Gate (`along-kb-sync --strict`)**: Verifies that all cross-references across `docs/`, `README.md`, and `.along/` resolve to valid physical files.

---

## 10. Lifecycle & Polyglot Hook Architecture (`alongkit.lifecycle`)

Along decouples AI agent operational intent from underlying repository toolchains through the **Contract-First Lifecycle Hook Architecture**:

```mermaid
flowchart TD
    AGENT["AI Coding Agent (/along-test, /along-build, /along-dev)"]
    ROUTER["along_exec.py Dispatcher"]
    SUB_CHECK{"Subproject Hook exists? (packages/*/.along/scripts/)"}
    ROOT_CHECK{"Root Hook exists? (.along/scripts/)"}
    INTERPRETER["alongkit.lifecycle.build_interpreter_cmd()"]
    RUN_EXEC["Safe Process Execution (shell=False, argv list)"]
    AUTODETECT["Stack Detector (Node, Rust, .NET, Python, Go)"]
    SYNTHESIZE["Synthesize .along/scripts/<action>.py"]

    AGENT --> ROUTER
    ROUTER --> SUB_CHECK
    SUB_CHECK -->|Yes| INTERPRETER
    SUB_CHECK -->|No| ROOT_CHECK
    ROOT_CHECK -->|Yes| INTERPRETER
    ROOT_CHECK -->|No| AUTODETECT
    AUTODETECT -->|Known Stack| SYNTHESIZE
    SYNTHESIZE --> INTERPRETER
    AUTODETECT -->|Unknown Stack| UNCONFIG["Generate Unconfigured Template"]
    INTERPRETER --> RUN_EXEC
```

### Architectural Principles

1. **Stack-Agnostic Interface**: AI agents interact exclusively with standardized verbs (`/along-build`, `/along-test`, `/along-dev`, `/along-version-bump`, `/along-dep-scan`). The agent never needs custom prompt tuning for different languages.
2. **Polyglot Interpreter Selection**:
   - `.py`: Executed via `sys.executable`.
   - `.sh`: Executed via `bash` binary.
   - `.ps1`: Executed via `pwsh` or `powershell` with `-NoProfile -File`.
   - `.bat` / `.cmd`: Executed via `cmd.exe /c`.
   - Native binaries: Executed directly.
3. **Safe Execution without Shell Injection**: All lifecycle commands avoid `shell=True`. Arguments are pre-split or passed as discrete argv lists, preserving spaces and special characters.
4. **Nearest-Boundary Monorepo Localization**: In modular codebases and Git submodules, the dispatcher locates the nearest `.along/scripts/` hook before falling back to workspace root.
5. **Non-Destructive Auto-Synthesis**: When hooks are absent, Along analyzes project manifests (`package.json`, `Cargo.toml`, `*.csproj`, `pyproject.toml`, `go.mod`), injects quiet flags (`-q`, `-v q`; never `--silent` for `npm test`, since the test gate counts executed tests from the runner summary), and synthesizes an executable `.along/scripts/<action>.py` hook marked with `# Status: verified`.

---

## Document: docs/topic--autonomous-environment.md (Autonomous Environment Architecture & Docker Isolation)

# Autonomous Environment Architecture & Docker Isolation

Comprehensive operational guide and architecture specification for isolated autonomous agent execution environments using Docker and Along Protocol.

---

## 1. Architectural Motivation & Threat Model

When executing autonomous AI agents without human confirmation on remote servers or VPS instances, host environments face substantial operational risks:
- Unbounded Command Execution: Arbitrary commands (e.g. bash scripts, package installers, build hooks) executed by agents cannot be verified as safe purely from static command text.
- Runtime Sandbox Asymmetry: Proprietary sandbox mechanisms (such as Claude Code bubblewrap sandboxes) cover only a single runtime, leaving other tools (OpenCode, Codex, custom scripts) uncontained.
- Host Contamination: Accidental file deletion, port conflicts, host credential leaks, or runaway background processes can disrupt server integrity.

As codified in [ADR-2026-10-17--docker-isolation-now-gvisor-later](./decisions/ADR-2026-10-17--docker-isolation-now-gvisor-later.md), Along adopts a container-based isolation model:
- The VPS acts as the outer, disposable physical boundary.
- Inside the host, each project environment maps strictly to one dedicated Docker container and one isolated host filesystem directory.
- Container boundaries enforce non-root user execution, strict volume boundaries, and an egress firewall allowlist.

---

## 2. Environment Architecture & Isolation Model

Each environment managed by `along env` adheres to an explicit isolation invariant:

```text
Host / VPS (/srv/along/envs/<name>/)
├── env.yaml        (Declarative settings, under 20 lines)
├── secrets.env     (API keys, git token, telegram credentials)
└── compose.yaml    (Deterministic docker compose specification)
        │
        ▼
Container Boundary (along-<name>)
├── Non-Root User: along (UID 1000, GID 1000 via setpriv)
├── Egress Allowlist Firewall (iptables + ipset: model APIs, GitHub, PyPI, npm)
└── Isolated Named Volumes:
    ├── repo          -> /workspace (Only writable project tree)
    ├── claude_auth   -> /home/along/.claude
    ├── opencode_auth -> /home/along/.opencode
    └── cache         -> /home/along/.cache
```

### Persistent State Invariant
All authentication tokens, agent login sessions, and Git repository clones are stored strictly inside named Docker volumes. Consequently:
- Stopping an environment with `along env down` preserves all agent login state and work in progress.
- Starting the environment again with `along env up` instantly restores operational readiness without re-authentication.

### Future Hardening: gVisor Runtime
The `env.yaml` schema includes an optional `gvisor: true` switch. When enabled on hosts with `runsc` installed, the generated `compose.yaml` appends `runtime: runsc` to provide kernel-level virtualization and protection against container escape vulnerabilities.

---

## 3. Directory Layout & Configuration Files

By default on Linux systems, environments are provisioned under `/srv/along/envs/<name>/` (configurable via `--dir` or the `ALONG_ENVS_DIR` environment variable).
Environment names are validated against `^[a-z0-9][a-z0-9_-]{0,62}$` to prevent directory traversal (`../`) and ensure container name safety.

### 3.1 env.yaml
Declarative environment descriptor serialized using ruamel round-trip mode and designed to stay strictly under 20 lines:

```yaml
name: myproj
repo: "https://github.com/actdim/along.git"
branch: "main"
runtimes:
  - claude-code
  - opencode
telegram_chat_id: ""
egress_allowlist: []
gvisor: false
image: "actdim/along-autonomous:latest"
```

### 3.2 secrets.env
Uncommitted secrets file with restricted filesystem permissions (`chmod 0600` on POSIX):

```env
# Model API Keys (scoped keys with spend limits recommended)
ANTHROPIC_API_KEY=sk-ant-...
OPENAI_API_KEY=sk-...
GEMINI_API_KEY=AIza...

# Git Repository Credentials (fine-grained repo-scoped token)
GITHUB_TOKEN=ghp_...

# Telegram Alerts & Interventions
TELEGRAM_BOT_TOKEN=123456:ABC-DEF...
TELEGRAM_CHAT_ID=-100123456789

# Autonomous Execution Mode & Self-Approval
ALONG_AUTONOMOUS=1
ALONG_ARCHITECT_SELF_APPROVAL=0  # Set to 1 to allow orchestrator architect self-approval without operator plan approval
```

### 3.3 compose.yaml
Deterministically synthesized compose specification created by `along env up` or `along env update`:

```yaml
# Generated by Along (along env) - do not edit by hand
services:
  runner:
    image: actdim/along-autonomous:latest
    container_name: along-myproj
    init: true
    restart: unless-stopped
    security_opt:
      - no-new-privileges:true
    sysctls:
      net.ipv6.conf.all.disable_ipv6: 1
    cap_add:
      - NET_ADMIN
    env_file:
      - secrets.env
    environment:
      ALONG_ENV_NAME: myproj
      ALONG_AUTONOMOUS: "1"
      ALONG_REPO_URL: "https://github.com/actdim/along.git"
      ALONG_REPO_BRANCH: "main"
      ALONG_RUNTIMES: "claude-code,opencode"
    volumes:
      - repo:/workspace
      - claude_auth:/home/along/.claude
      - opencode_auth:/home/along/.opencode
      - cache:/home/along/.cache

volumes:
  repo:
  claude_auth:
  opencode_auth:
  cache:
```

---

## 4. Docker Assets & Container Hardening

The autonomous runtime container is built from a single unified `docker/Dockerfile`:
- Base System: Ubuntu 24.04 LTS (Noble Numbat).
- Non-Root User: Replaces default `ubuntu` UID/GID 1000 user (`userdel --remove ubuntu`) and provisions user `along` (UID 1000, GID 1000).
- Privilege Separation: `sudo` is completely removed from the image and no sudoers files exist. The container entrypoint starts as root to initialize networking, then drops privileges permanently to UID 1000 via `setpriv --reuid=1000 --regid=1000 --init-groups --no-new-privs`.
- Runtimes: Node.js 20 LTS, Python 3.12, Along Protocol toolchain, `ipset`.
- Agent Tooling: Claude Code (`@anthropic-ai/claude-code`) and OpenCode (`opencode-ai`).

---

## 5. Egress Firewall & Network Allowlist

Container network egress is strictly regulated at container startup by `docker/init-firewall.sh`:
- Fail-Closed Architecture: The container entrypoint enforces root firewall application before any agent processes start. If the firewall fails or NET_ADMIN capability is missing, the container exits immediately with an error, preventing open fallback. The firewall can only be bypassed with explicit `ALONG_FIREWALL=off`.
- Preserved Docker DNS: The `nat` table is never modified, preserving Docker's embedded DNS (127.0.0.11) DNAT rules in `DOCKER_OUTPUT` and `DOCKER_POSTROUTING`.
- Nameserver Scoping: Outbound DNS traffic on port 53 (UDP/TCP) is permitted exclusively to nameservers configured in `/etc/resolv.conf` (or `ALONG_RESOLV_CONF`). Generic outbound queries to arbitrary destinations (e.g. 1.1.1.1, 8.8.8.8) are blocked to prevent DNS tunnelling.
- IPv6 Traffic Blocking: IPv6 INPUT, FORWARD, and OUTPUT chains are set to default DROP policy with fast ICMP rejection.
- Dynamic IP Refresh: An in-container background daemon periodically resolves allowlisted hosts and swaps the active `along-allow` ipset table every `ALONG_FIREWALL_REFRESH` seconds (default: 300 s).
- Mandatory Endpoints:
  - `api.anthropic.com` (Anthropic Claude API)
  - `api.openai.com` (OpenAI API)
  - `generativelanguage.googleapis.com` (Google Gemini API)
  - `github.com` (Git repository clone and push via HTTPS and SSH)
  - `pypi.org` and `files.pythonhosted.org` (Python package installation)
  - `registry.npmjs.org` (Node.js package installation)
  - `api.telegram.org` (Telegram alerts and long-polling supervisor gateway)

Custom host additions can be specified in `env.yaml` under `egress_allowlist` and are injected into the firewall via root-owned file `/run/along/egress.list`.

---

## 6. CLI Command Reference

The `along env` toolchain provides six operational subcommands:

### along env up
Create and start an isolated Docker environment:
```bash
along env up myproj --repo https://github.com/actdim/along.git --branch main
```
Flags:
- `<name>`: Environment name (required, must match `^[a-z0-9][a-z0-9_-]{0,62}$`).
- `--repo <url>`: Target Git repository clone URL.
- `--branch <branch>`: Target branch (default: `main`).
- `--dir <path>`: Base environments directory or custom environment path.

When docker or compose fails, `along env up` exits with non-zero exit code 1.

### along env down
Stop running container while keeping persistent volumes intact:
```bash
along env down myproj
```
When docker stop or compose down fails, `along env down` exits with non-zero exit code 1.

### along env status
Display environment details or list all configured environments:
```bash
# Show summary of a specific environment
along env status myproj

# Show machine-readable JSON status
along env status myproj --json

# List all configured environments on host
along env status
```

### along env logs
View or stream live logs from the runner container:
```bash
# Follow logs
along env logs myproj -f

# View last 50 lines
along env logs myproj --tail 50
```

### along env shell
Launch an interactive bash session inside the isolated container as non-root user `along`:
```bash
along env shell myproj
```

### along env update
Pull latest container image and restart the runner container (without unnecessary `--build` rebuilds):
```bash
along env update myproj
```
When docker pull or compose up fails, `along env update` reports the error and exits with non-zero exit code 1.

### Runner daemon (`along daemon`)

`along daemon start` (background) or `--foreground` (systemd: `docker/along-runner.service`) polls the
Telegram Bot API and runs `/task <slug>` through the orchestrator. Runtime files live in
`.along/.daemon/` (git-ignored):

- `daemon.pid`: PID on line 1 and the process start-time token on line 2, created exclusively. `status`
  and `stop` act only on the process that wrote it; a live PID with another or no token (PID reuse, or a
  file from an older version) is reported as `stale-pid` and never signalled.
- `daemon.json`: status, current task and `telegram_offset`, saved before each update runs, so a restart
  never runs an accepted command again.
- `daemon.log`: rotated to `daemon.log.1` above 5 MB.

#### Telegram Configuration & Precedence

Telegram settings are resolved uniformly via `alongkit.telegram` across daemon and feedback tools. Configuration merges through strict precedence (lower to higher priority, higher overwrites):
1. **Global Configuration**: `~/.along/config.json` (`transports.telegram` or `daemon` section).
2. **Local Repository Configuration**: `.along/config.json` (`transports.telegram` or `daemon` section).
3. **Environment Variables**:
   - Bot Token: `ALONG_TELEGRAM_BOT_TOKEN` or `TELEGRAM_BOT_TOKEN`.
   - Primary Chat ID: `ALONG_TELEGRAM_CHAT_ID` or `TELEGRAM_CHAT_ID`.
   - Allowed Chats: `ALONG_TELEGRAM_ALLOWED_CHATS` or `TELEGRAM_ALLOWED_CHATS` (comma-separated chat IDs).

Tasks run on a worker thread: `/status` answers during a run, a second `/task` gets "Runner busy", and on
SIGTERM the daemon stops polling and waits up to 20 s for the task. Commands older than
`max_command_age` (default 600 s; `daemon.max_command_age` in `.along/config.json` or
`ALONG_DAEMON_MAX_COMMAND_AGE`) are ignored with a reply. Transient poll errors back off
exponentially with jitter up to 300 s, resetting on success. HTTP 429 honors `retry_after`. HTTP 409
Conflict is retried within `conflict_window` (default 60 s; `daemon.conflict_window` in `.along/config.json`
or `ALONG_DAEMON_CONFLICT_WINDOW`); if it outlasts the window, the daemon notifies allowed chats and exits
with code 78. A rejected bot token (HTTP 401/404) exits with code 78 immediately. The systemd unit's
`RestartPreventExitStatus=78` prevents automatic restart on permanent configuration or conflict errors.
With `--worktree`, a clean worktree is removed but its `along/<slug>` branch is kept and named in the
reply; a worktree with uncommitted changes is kept whole.

Architect self-approval: Multi-agent orchestration requires human operator plan approval by default. When running headless in an autonomous environment without human operators, setting `ALONG_ARCHITECT_SELF_APPROVAL=1` enables the architect phase to self-approve the living plan and transition directly to the implementer phase. If unset or `0`, the orchestrator marks `plan_status: needs-approval`, updates session state to `needs-input`, and halts for external review.

---

## 7. Accepted Operational Risks

1. Model API Key Exposure: Agents executing inside the container have access to model keys injected via `secrets.env`. Operators should use per-VPS keys with strict budget limits.
2. Fine-Grained Git Permissions: Git credentials are handled via the ephemeral credential helper (`/usr/local/bin/git-credential-along`), ensuring tokens are supplied in-memory and never written to `/workspace/.git/config`.
3. DNS Tunnelling Through Docker Resolver: While outbound port 53 is restricted to the Docker embedded resolver (127.0.0.11), queries forwarded upstream could theoretically be abused for low-bandwidth DNS data exfiltration. Operators requiring air-gapped isolation should use explicit private upstream resolvers.
4. Telegram Bot Token: In the MVP, supervisor notifications share the environment credentials. Future milestones separate orchestrator and worker containers.

---

## Document: docs/topic--cli-reference.md (Along CLI Command Reference)

# Along CLI Command Reference

This document provides the canonical command-line interface reference for the `along` toolchain.

The Along CLI acts as the unified command router for human developers, terminal scripts, CI/CD pipelines, and autonomous AI agents. It guarantees identical execution semantics whether invoked as a globally installed console script, via Python directly in a repository checkout, or through a shared global installation.

---

## 1. Invocation Architecture & Paths

The CLI is routed through `scripts/along_exec.py` backed by the shared `alongkit` engine library. It automatically ensures runtime dependencies (such as `ruamel.yaml`) via `uv run` fallback if they are missing in the active interpreter.

```text
Invocation Paths:
  1. Canonical Console Script:   along <command> [subcommand] [options...]
  2. Local Repository Checkout: python scripts/along_exec.py <command> [subcommand] [options...]
  3. Global User Installation:   python ~/.along/bin/along_exec.py <command> [subcommand] [options...]
```

### In-Band vs Out-of-Band Execution

- **In-Band (Inside Agent Session)**: Standard day-to-day workflow driven by the agent using specialized skills (`/along-test`, `/along-wrap`, `/along-kb-sync`).
- **Out-of-Band (External OS Terminal CLI)**: Direct command execution by the developer or bootstrap scripts via `along <command>` (e.g. `along update`, `along doctor`). Essential for initial bootstrapping, protocol upgrades, and disaster recovery when runtime lifecycle hooks are in a broken state.

General help and command listing are accessible via:
```bash
along --help
along <command> --help
along <command> <subcommand> --help
```

For the entity and repository commands (section 3), `-h` / `--help` anywhere after the
subcommand, before a `--` separator, prints the usage for that subcommand, exits 0 and writes
nothing. `run`, `kb`, `graph`, the tool engines and the lifecycle hooks pass `--help` on to the
command they run. Entity names that start with `-` are rejected with exit code 2.

---

## 2. Project Lifecycle Hooks

Lifecycle commands provide a uniform execution contract across any programming language or build stack. They execute repository-specific hooks in `.along/scripts/` when present, or automatically detect the underlying project runner.

### `along build`
Executes the project build lifecycle hook.
- **Engine Script**: `.along/scripts/build.py`
- **Auto-Detection Fallback**: Detects `package.json` (`npm run build`), `Cargo.toml` (`cargo build`), `.csproj`/`.sln` (`dotnet build`), `pyproject.toml`/`setup.py` (`python -m build`).
- **Synthesis**: If no build script exists, automatically synthesizes a verified or unconfigured template in `.along/scripts/build.py`. An unconfigured template exits `0` with a `[Warning]` that nothing was verified, and the wrap / commit quality gates report "tests are not configured" instead of a pass.
- **Usage**:
  ```bash
  along build [args...]
  ```

### `along test`
Executes automated test suites using quiet, token-efficient flags.
- **Engine Script**: `.along/scripts/test.py`
- **Auto-Detection Fallback**: Detects `pytest` (`pytest -q`), `npm` (`npm test`, only when `package.json` has a `test` script; no `--silent` is added), `dotnet` (`dotnet test <solution or test project> -v q`, only with a `*.sln` / `*.slnx` or a test project referencing `Microsoft.NET.Test.Sdk` / `<IsTestProject>`; a library project alone detects nothing), `cargo` (`cargo test -q`).
- **Enclosing hook**: a nested context without its own hook runs the nearest enclosing context's hook of the same git repository instead of synthesizing one; a folder with only an `AGENTS.md` uses the enclosing context.
- **No tests is not a pass**: when the runner output shows zero executed tests (`Ran 0 tests`, `no tests ran`, `Total tests: 0`, `No test is available`, `No test files found`, ...), `along test` prints `FAIL: ... executed no tests` and exits `5`, and the run is not recorded green. Output that says nothing about test counts is judged by the exit code alone. Executed-test counting strips ANSI colour codes first, and `npm test` resolves to the `package.json` `test` script for runner detection.
- **Test policy & scoping flags**:
  - By default, `along test` runs under the effective verify policy of the bound issue (approved plan snapshot > repository config).
  - `--full`: Forces running the full test suite.
  - `--affected`: Runs tests targeting attributed files in the active session.
  - `--scope <name>`: Runs a named test scope declared in `.along/config.json` under `verify.scopes`.
  - Flags are consumed by Along and stripped from the hook's argv. Environment variables `ALONG_TEST_MODE`, `ALONG_TEST_SCOPE`, and `ALONG_ATTRIBUTED_FILES` are passed to `.along/scripts/test.py`.
  - The repository `verify` block of `.along/config.json` (`{"tests": "required" | "none", "reason": "", "tracked_by": "", "checks": []}`) sets the repository default. `required`: tests must actually run. `none`: requires `reason` and `tracked_by` issue key. See [Setup and Workflow](./topic--setup-and-workflow.md).
- **Distilled Output** (`along test`, `along build`): When stdout is not a terminal (an agent or a pipe reads it), the output is distilled by `alongkit.distill`. A pass becomes `PASS: <cmd> completed successfully (code 0, <s>s)` plus the runner summary (`Ran N tests`, `OK`). A failure keeps the failure blocks: tracebacks, unittest `FAIL:` / `ERROR:` sections, pytest `E` lines, compiler `error:` lines, panics. Resolver chatter, deprecation notices, progress redraws and passing-test lines are dropped. The result is capped at 50 lines / 2 KB, with the runner summary always kept. The raw output is written to `.along/artifacts/lifecycle/<action>.log` (gitignored, overwritten per run). In a terminal the output streams as before.
  - `--raw` streams the full output, `--distill` forces distillation. Both flags are consumed by Along and not passed on; `--verbose` is left alone because pytest and cargo use it. `ALONG_OUTPUT=raw|distill` sets the mode for a whole session. `along dev` / `along debug` always stream.
- **Usage**:
  ```bash
  along test [args...]
  along test --raw -q
  ```

### `along dev`
Launches the local development server or watcher.
- **Engine Script**: `.along/scripts/dev.py`
- **Auto-Detection Fallback**: Detects `npm run dev`, `cargo run`, `dotnet run`, or `python main.py`.
- **Usage**:
  ```bash
  along dev [args...]
  ```

### `along dev-env`
Initializes local developer virtual environment (`scripts/alongkit/devenv.py`).
- Provisions `.venv` in the repository root using `uv` (with `venv` fallback) and installs `alongkit` in editable mode (`pip install -e .`).
- **Options**:
  - `--reinstall`: Forces removal and clean recreation of the existing `.venv` environment.
- **Usage**:
  ```bash
  along dev-env
  along dev-env --reinstall
  ```

### `along debug`
Executes project debugging or diagnostics profile.
- **Engine Script**: `.along/scripts/debug.py`
- **Usage**:
  ```bash
  along debug [args...]
  ```

---

## 3. Entity & Repository Management

Entity commands manage the durable in-repo memory stored inside `.along/` (issues, decisions, sessions, scratchpads, and isolated worktrees).

They work inside an Along installation only: the nearest folder (from the current directory upward) whose `.along/` holds Along state. A folder with only an `AGENTS.md` (a folder guide) or a stateless `.along/` is passed by, so a command run in a package folder writes to the installation above it. Outside any installation `issue`, `start`, `session`, `plan`, `decision`, `milestone`, `scratch`, `worktree`, `wrap` and `commit` exit `2` with "Along is not installed"; only `along init` creates an installation, and `along test|build|dev` there run the detected command without writing a hook.

### `along status`
Displays an instant terminal summary of repository health, active in-flight issues, and recent completed sessions, plus the test policy line (e.g. `tests: required (default)` or `tests: none - <reason> (<tracked_by>)`).
- **Usage**:
  ```bash
  along status
  ```

### `along doctor`
Validates repository compliance with the Along protocol. Audits `.along/` directory layout, `.gitattributes` merge drivers, and ADR header formatting.
- **Runtime section**: names the runtime (`claude-code`, `cowork`, `antigravity`, `codex`, ...), the gate enforcement level (`mechanical` only when Along hooks are registered for that runtime, otherwise `advisory`), the Python floor (3.10), a stale `.git/index.lock`, and a cross-OS or VM-mounted repository (worktrees unsafe). See the capability matrix in [Runtime Lifecycle Hooks & Mechanical Gates](./topic--runtime-hooks-and-gates.md).
- **Vision & root notes**: warns about a root `VISION.md` next to `.along/`, an unresolved `along:imported-vision needs-restructure` section in `.along/VISION.md`, and root notes (`ROADMAP.md`, `ARCHITECTURE.md`, `SPEC.md`, `TODO.md`, `DESIGN.md`) that the agent must route into the Knowledge Base.
- **Tracked diagnostics**: warns when files under any `.along/diagnostics/` are still tracked in git (committed before the directory ignored itself) and names `along migrate --apply` (or `git rm --cached`) as the fix.
- **Nested installs**: warns about nested `.along/` contexts that sit in no nested git repository (possibly created per manifest folder by older versions) and lists them. It changes nothing: consolidating them into the root is a manual per-repository task. A deliberate nested context is silenced with `"subproject": {"intentional": true}` in its `.along/config.json`. See ADR `subproject-boundary-is-git-or-explicit-init`.
- **Sessions**: warns about orphan blackboards (no session bound, issue closed or missing; fix with `along session gc` or `along scratch purge <slug>`), session bindings older than 72 h or without a blackboard (`along session gc`), and issues in progress with no session bound. See [Parallel Sessions](./topic--parallel-sessions.md).
- **Verification & gates**: prints the test policy line (`Verify: tests: ...`, see `along test`; `tests: none` is a warning, an invalid policy such as a missing `reason` / `tracked_by` an error), active gate strictness profile (`strict`, `standard`, `light`), warns about gates shadowed by repository config and names the most-bypassed gates (see `along gates stats`).
- **Options**:
  - `entities`, `--entities`: Performs deep validation of the entity DAG graph, verifying parent/child relationships, `blocked_by` dependencies, and detecting circular references. References resolve against the current `.along/`, every enclosing `.along/` up to the outermost context below home (crossing nested git / submodule boundaries), every nested subproject `.along/` below it, and every sibling `.along/` of the same git repository (nested git repositories and dependency/build dirs are not entered). Schema findings on archived issues (`.along/ISSUES/done/`) are warnings.
  - `entities --fix`, `--entities --fix`: Removes `milestone` fields of issues and session logs that resolve to no milestone, lists the changed files, then validates.
  - `issues`, `--issues`: Validates issue entity quality across `.along/ISSUES/`, detecting boilerplate placeholders, unfilled scaffold stubs, and incomplete criteria.
  - `docs`, `--docs`: Validates documentation quality across `docs/` and detects abandoned zombie stubs.
- **Usage**:
  ```bash
  along doctor
  along doctor --entities
  along doctor --issues
  along doctor --docs
  along doctor --entities --fix
  ```

### `along issue`
Manages atomic issue files in `.along/ISSUES/` and recompiles the active board projection (`.along/ISSUES.md`).
- **Subcommands**:
  - `along issue create <type> <slug> --title "Title" [options...]`: Creates a new issue file. Valid types: `feat`, `bug`, `debt`, `task`, `docs`, `spike`. A `spike` is scaffolded with an `## Outcome` section, filled before it is closed as `done`. A risk or blocker is an ordinary issue (usually `debt`) tagged `risk` with a `## Mitigation` section.
    - Options: `--priority {high,medium,low,critical}`, `--tags "t1,t2"`, `--agent <name>`, `--milestone <name>`, `--verify-tests {required,affected,scoped,none}`, `--verify-scope <name>`, `--verify-reason "<text>"`, `--verify-tracked-by <key>`, `--verify-checks <c1,c2>`.
  - `along issue update <slug> [options...]` (alias: `along issue edit`): Updates frontmatter metadata of an existing issue, preserving YAML comments and ordering.
    - Options:
      - `--milestone <name>`, `-m <name>`: Assigns or reassigns issue to a milestone. Supports fuzzy matching (exact slug, version prefix such as `v4.0` or `4.0`, or unambiguous substring). Use `"none"`, `"null"`, or `""` to unassign. Automatically triggers bidirectional milestone synchronization.
      - `--priority <p>`, `-p <p>`: Updates priority (`critical`, `high`, `medium`, `low`).
      - `--status <s>`, `-s <s>`: Updates status (`open`, `in-progress`, `blocked`, `done`, `superseded`, `cancelled`, `duplicate`).
      - `--tags <t1,t2>`: Replaces tags with a comma-separated list.
      - `--title <title>`, `-t <title>`: Updates the issue title in frontmatter.
      - `--verify-tests {required,affected,scoped,none}`, `--verify-scope <name>`, `--verify-reason "<text>"`, `--verify-tracked-by <key>`, `--verify-checks <c1,c2>`, `--verify-clear`: Updates or clears the issue verify policy block.
    - Side-effects: Automatically recompiles `.along/ISSUES.md` board projection and synchronizes affected milestones.
  - `along issue show <slug> [--json]` (alias: `along issue get`): Displays detailed summary of an issue, including frontmatter metadata, priority, status, milestone, body excerpt, `verify` (frontmatter block) and `verify_effective` (effective policy description).
    - Options: `--json` outputs structured JSON payload.
  - `along issue done <slug> [options...]`: Marks the issue as completed, records `completed: YYYY-MM-DD`, and moves the file into `.along/ISSUES/done/`. In the same transaction the issue's blackboard (if any) is archived into today's session log `.along/SESSIONS/<YYYY>/<date>--<slug>.md` and, with status `done`, the key is added to its `issues_completed` (the log is created without a blackboard too); the blackboard is purged after the commit. See [Session Lifecycle](./topic--session-lifecycle.md).
    - Options: `--status {done,superseded,cancelled,duplicate}`, `--superseded-by <slug>`, `--duplicate-of <slug>`, `--force-reason "..."`.
    - Closing as `done` / `superseded` refuses while the blackboard holds gate denials that are open or acknowledged without a user reply since (see `along gates denials`); `--force-reason` passes under the bypass rules (the refusal first, then the user's reply) and is recorded. `cancelled` / `duplicate` are not held. [feat--anti-silent-fallback-gate]
  - `along issue reopen <slug>`: Moves a closed issue from `.along/ISSUES/done/` back to `.along/ISSUES/`, sets `status: open`, removes `completed` / `superseded_by` / `duplicate_of`, restores sibling links and recompiles `.along/ISSUES.md` (one transaction). Session logs that list it as completed stay as they are. Resume with `along start <slug>`.
  - `along issue sync`: Recompiles `.along/ISSUES.md` deterministically from atomic files in `.along/ISSUES/` and `.along/ISSUES/done/`, then runs the entity reference integrity gate (`validate_entities`): dangling references or schema / enum violations that are absent at `HEAD` exit `1` in `enforce` mode and only warn in `shadow` mode; problems already present at `HEAD` are printed as a warning and never fail it. A `parent` found in an enclosing context is printed as `<key>: parent <parent> (found in <ctx>)`.
  - `along issue list`: Lists all active in-progress and open issues in the terminal.
  - `along issue rename <old-key> <new-key>`: Renames an issue (type and/or slug; a bare slug keeps the type). Rewrites the file name and `slug`/`type`, then every inbound reference in the nearest `.along/`: `related`, `blocked_by`, `parent`, `superseded_by`, `duplicate_of` in issues and ADRs, milestone `target_issues`, and session `issues_advanced` / `issues_completed`.
  - `along issue cancel <slug>`: Same as `along issue done <slug> --status cancelled`.
  - `along issue delete <slug>`: Removes an issue created by mistake: strips it from `related` / `blocked_by` lists and milestone `target_issues`, deletes the file and recompiles milestones and the board. Refused when a session log, a `parent` / `superseded_by` / `duplicate_of` reference or a commit message names it; cancel or supersede such an issue instead.
  - `along issue supersede <old-key> --by <new-key>`: Closes the old issue as `superseded` with `superseded_by: <new-key>` and moves it to `done/` (the file is kept, so session history stays valid). Dependency fields of other entities (`related`, `blocked_by`, `parent`, ...) are rewritten to the successor; session logs are left as they are.
  - `along issue create ... --milestone <m>` and `along issue update --milestone <m>` keep the milestone `target_issues` in sync (added on assignment, removed from the previous milestone on reassignment).
- **Usage**:
  ```bash
  along issue create feat token-refresh --title "Add OAuth token refresh" --priority high
  along issue update token-refresh --priority critical --tags "auth,security" --milestone v4.0.0
  along issue show token-refresh
  along issue list
  along issue done token-refresh
  along issue rename feat--token-refresh feat--oauth-token-refresh
  along issue supersede feat--oauth-token-refresh --by feat--session-auth-rework
  along issue sync
  ```

### `along start`
Atomically marks an issue as `in-progress`, updates `updated: YYYY-MM-DD`, recompiles the active board projection (`.along/ISSUES.md`), initializes the session blackboard (`.along/.session/<slug>/`) and binds this agent session to the issue (`.along/.session/bindings/<runtime>--<session_id>.json`). Starting is refused if the issue is already closed in `done/` (reopen first with `along issue reopen <slug>`) or if the issue file contains unfilled scaffold placeholders or lacks concrete acceptance criteria.
- **Clean Start Guard**: Hard-blocks starting when uncommitted changes from previously wrapped issues remain in the working tree (advising `along commit -i <slug>` or `along session close`), or when other in-progress issues have uncommitted changes (suggesting `along start <slug> --worktree` to avoid dirtying the shared checkout). Override with `--allow-dirty`.
- **Options**:
  - `--profile <strict|standard|light>`: Sets the gate strictness profile for this session.
  - `--allow-dirty`: Bypasses the Clean Start Guard to proceed despite uncommitted working tree changes.
  - `--approved`: Mark the plan approved at once (scripted and runner use only). Held to the same check as `along plan approve`: refused when the plan changed after the user's last message.
  - A plan approved ahead (ticket `plan_status: approved` with an approval logged by `along plan approve` on this machine) is used as is: the session starts in `execution` with "Using the approved plan in .along/ISSUES/<key>/plan.md" and no further approval. `approved` without a logged approval here (approved elsewhere, or written by hand) leaves the session in `planning` with a note to show the plan and ask; `needs-rework` does the same.
  - `--worktree`: Enforces git worktree workspace isolation. Verifies environment readiness, provisions an isolated worktree at `.along/worktrees/<slug>` on branch `along/<slug>`, links heavy dependencies (`node_modules`, `.venv`) via NTFS junctions on Windows or symlinks on POSIX, copies untracked configuration (`.env*`), and points agent execution to the worktree path.
  - `--allow-root <path>` (repeatable): Adds `path` to the issue's `allowed_roots` frontmatter: extra read-only roots for `[gate: workspace-containment]` (for example a sibling contracts repository).
  - `--write-scope <path>` (repeatable): Adds `path` to the issue's `write_scope` frontmatter: once set, workspace writes are limited to these subfolders plus `.along/`.
- **Usage**:
  ```bash
  along start token-refresh
  along start token-refresh --worktree
  along start token-refresh --profile light
  along start token-refresh --allow-root ../contracts --write-scope packages/auth
  along start token-refresh --allow-dirty
  ```

### `along milestone`
Tracks progress across high-level milestones and sprints in `.along/MILESTONES/`. Provides bidirectional synchronization with issues and dynamic progress tracking.
- **Subcommands**:
  - `along milestone sync [<slug>]`: Scans all active and completed issues in `.along/ISSUES/`, discovers issues declaring `milestone: <slug>`, dynamically updates `target_issues: [...]` in milestone frontmatter, recalculates `progress_pct = round(100 * done_count / total)`, and automatically transitions status to `completed` when all target issues are closed. An explicit `target_issues` entry stays as long as its issue exists and names no other milestone. If `<slug>` is omitted, synchronizes all milestones in `.along/MILESTONES/` except `completed` ones, which change only when named.
  - `along milestone list [--status <status>] [--json]`: Lists all milestones with progress statistics, completion percentages, and target issue counts.
    - Options: `--status` filters by status (`open`, `in-progress`, `completed`), `--json` outputs machine-readable JSON array.
  - `along milestone show <slug> [--json]`: Displays detailed milestone status, due date, progress percentage, and checklist of all target issues with individual completion states. Supports fuzzy query resolution (exact slug, version prefix such as `4.0`, or substring).
    - Options: `--json` emits structured JSON payload.
  - `along milestone create <slug> --title "Title" [--due YYYY-MM-DD]`: Creates `.along/MILESTONES/<slug>.md` with standard front-matter (`status: open`, empty `target_issues`, `progress_pct: 0`). Refuses to overwrite an existing file and rejects a slug whose version collides with an existing milestone.
- **Usage**:
  ```bash
  along milestone create v5.5.0-priority-aware-planning --title "v5.5.0: Priority-Aware Planning" --due 2027-09-30
  along milestone sync
  along milestone list --status in-progress
  along milestone show v4.0.0-runtime-gates-and-worktree-isolation
  along milestone show 4.0
  ```

### `along session`
Manages session logs in `.along/SESSIONS/` and records engineering provenance.
- **Subcommands**:
  - `along session create <slug> --summary "Summary" [options...]`: Initializes a new session log.
    - Options: `--issues "slug1,slug2"`, `--decisions "ADR-slug"`, `--agent <name>`, `--milestone <name>`, `--commit <sha>`.
    - Front-matter is emitted through `ruamel.yaml`; `branch` and `commit` come from git (omitted outside a repository). Named issues are filed by their status: closed ones under `issues_completed`, the rest under `issues_advanced` (canonical keys); `## Work Completed` lists each with its title and status. The body records test evidence when a passing `along test` run was recorded for the current working tree (in this context or an enclosing one) or the runtime hooks recorded a run after the last edit. The `HISTORY.md` line is written through the same one-line-per-slug writer as `along wrap`.
  - `along session wrap <slug> [options...]`: Same as `along wrap` (see below), including the required `--decisions` / `--no-decisions` answer.
    - Options: `--status {done,superseded,cancelled,duplicate}`, `--summary "Summary"`, `--decisions "ADR-a,ADR-b"` or `--no-decisions`, `--force-reason "..."`, `--dry-run`, `-n`.
  - `along session bindings`: Lists agent-session bindings (session key, issue, approval, last update).
  - `along session gc [--dry-run]`: Removes bindings older than 72 hours or pointing at a purged blackboard. Also archives (into the session log) and removes unbound blackboards whose issue is already closed; blackboards of missing issues are only reported.
  - `along session list [--json]`: Readiness of every issue in progress, every bound issue and every blackboard: sessions and their last event, attributed files (exclusive / shared with which issues, still uncommitted), last edit vs last test run, acceptance criteria ticked / total, plan recorded, verdict `ready` / `blocked` with reasons; for the repository: uncommitted changes grouped by wrapped issue, truly unattributed and staged paths, a merge / rebase in progress, conflict markers.
  - `along session close <slug>... | --ready [--dry-run] [--push]`: Closes out finished work in one step. Needs the user's approval recorded with `along plan approve --closeout` in this session. Refuses during a merge / rebase / cherry-pick, with conflicts or with staged files. Plans the commits first, runs the tests once (nothing is touched when they fail), wraps each issue, then commits by attribution: one commit per issue (its files, issue move, session log), one combined commit per set of issues sharing files (all refs), the projections last. Files also attributed to an issue not closed now are held back; unattributed changes are never committed. Also supports already wrapped done issues (`along session close <done-slug>`), reading attributed files from their session log (`files:` front matter, or the legacy `### Attributed Files` table) and committing them without re-wrapping. `--push` pushes once at the end. Idempotent: a re-run (`along session close`) resumes from `.along/.session/.closeout.json`. Issues that are not ready are listed and left untouched.
- **Usage**:
  ```bash
  along session list
  along plan approve --closeout --ready
  along session close --ready --push
  along session create token-refresh --summary "Implementing OAuth token refresh logic"
  along session wrap token-refresh --status done --no-decisions --summary "Completed implementation and hermetic tests"
  along session gc --dry-run
  ```

### `along plan`
Plan approval for this agent session ([gate: require-plan-approval]).
- **Subcommands**:
  - `along plan approve [<slug>] [--plan-file <path>]`: Records the user's approval of the presented plan for the bound issue (or for the next `along start` when none is bound). Run it only after the user's explicit yes; in Claude Code accepting a plan via `ExitPlanMode` records it automatically, plan text included. `--plan-file` writes the approved plan into the issue's plan, `.along/ISSUES/<key>/plan.md` (committed with the ticket; the scaffold becomes `## Revision 1`, later plans are appended as `## Revision N`); a blackboard without an issue keeps its own `plan.md`. With an issue, approval is refused (exit 2) while the plan is still the scaffold. Every approval also sets the ticket's `plan_status: approved` and appends an approval event to `.along/.session/plan-approvals.jsonl`. **Before `along start`** (no blackboard yet) it approves ahead: the plan comes from `--plan-file`, from this session's `ExitPlanMode` acceptance made before any issue was bound, or from the existing `.along/ISSUES/<key>/plan.md`; the issue is not started and no blackboard is created; the next `along start <slug>` runs the plan without asking again. Where the runtime records user messages (Claude Code `UserPromptSubmit` hook), approval is also refused when the plan file changed after the user's last message ("plan changed after the user's last message; show it and wait for a reply"); with no recorded message it passes as `approved_via: cli-unverified`. The binding records `approved_via` (`exit-plan-mode` | `cli` | `cli-unverified`), `approved_at` and `plan_sha256`.
  - `along plan revise <slug> --plan-file <path> --reason "..."`: Appends a correction made during the work as the plan's next revision, with a `Reason:` line. The status stays as it is; corrections within the ticket's requirements need no new approval.
  - `along plan rework <slug> --reason "..."`: The plan cannot be followed within the ticket: sets `plan_status: needs-rework`, appends a `## Rework requested` note to the plan, logs it, and returns a started session to `planning` unapproved. Then stop and ask the user.
  - `along plan status [<slug>]`: Also prints the issue plan's state (`approved (ready; confirmed on this machine)`, `approved in the ticket, not confirmed on this machine`, `needs-approval`, `needs-rework`, or `none`) and its path.
  - `along plan approve --closeout <slug>... | --closeout --ready`: Records the user's approval to close these issues out (`--ready`: every issue `along session list` shows ready) in this session's binding; works from a fresh session. `along session close` of those issues passes with it; the closeout consumes it; it lapses after 72 h. Run it only after the user's explicit yes.
  - `along plan status`: Prints the session key, the resolved issue (`binding`, `single`, `ambiguous`, `elsewhere`, `none`), the phase and the approval.
- **Usage**:
  ```bash
  along plan status
  along plan approve token-refresh --plan-file plan.md
  ```

### `along decision`
Manages Architectural Decision Records (ADRs) and architectural constraints.
- **Subcommands**:
  - `along decision create <slug> --title "Title" --context "Why" --decision "What" --consequences "Tradeoffs"`: Creates a decentralized ADR in `.along/DECISIONS/ADR-YYYY-MM-DD--<slug>.md` and mirrors to `docs/decisions/`.
  - `along decision sync`: Recompiles the lean projection board `.along/DECISIONS.md` and active architectural constraints in `.along/CONSTRAINTS.md`.
- **Usage**:
  ```bash
  along decision create jwt-auth --title "Adopt JWT for API Auth" --context "Need stateless tokens" --decision "Use RS256 JWTs" --consequences "Key rotation required"
  along decision sync
  ```

### `along scratch`
Manages ephemeral multi-agent session blackboard memory (`.along/.session/<slug>/`) used by `along-team`.
- **Subcommands**:
  - `along scratch init <slug> [--title "Title"] [--steps N] [--restart] [--mode direct]`: Initializes session scratchpad directory, `state.json`, and `plan.md`. The blackboard is `role-based` (held to the along-team step loop by `[gate: team-step-active]` and `[gate: team-reviews-before-stop]`) unless `--mode direct` is given.
  - `along scratch state <slug> [--json]`: Displays current step progress, status, and retry counters.
  - `along scratch patch <slug> <json-delta> [--file <path>] [--show]`: Atomically updates structured working memory in `blackboard.json` using the deterministic merge operator ($\Sigma_{t+1} = \Sigma_t \oplus \Delta \Sigma_t$) with null-deletion semantics (passing `null` deletes the key). Supports `active_hypotheses`, `discovered_symbols`, `touched_files` (deduplicated), `open_defects`, and `custom` nested dicts.
  - `along scratch phase <slug> <inquiry|planning|execution> [--approve]`: Sets the session phase; `--approve` also marks the plan as approved.
  - `along scratch approve <slug>` (alias: `plan-approve`): Grants plan approval and moves the session to the `execution` phase. Refused while `plan.md` is the scaffold.
  - `along scratch update <slug> [--step N] [--step-status {pending,in-progress,passed,failed}] [--inc-retry] [--status {in-progress,completed,failed}]`: Updates execution state.
  - `along scratch fallback <slug> --reason "..."`: Switches the blackboard to single-agent (`direct`) execution and records the reason in `execution_trace.md`. A bypass: where user messages are recorded, a team-step gate must have failed in this session and the user must have replied after that failure.
  - `approve`, `phase --approve` and `update --approve` follow the `along plan approve` check (refused when the plan changed after the user's last message).
  - `along scratch purge <slug> [--force --reason "..."]`: Archives the blackboard into today's session log of the issue, then deletes it and the bindings to it (direct blackboards included). Refuses (exit 2) while a role-based blackboard has steps that are not `passed` or passed steps without `reviews/step-N.md`, unless forced with a reason; the reason is written into the record and the trace. `--force` is a bypass held to the same rules as `fallback`.
- **Usage**:
  ```bash
  along scratch init token-refresh --title "Token Refresh Step Loop" --steps 4
  along scratch state token-refresh
  along scratch patch token-refresh '{"active_hypotheses": {"H1": "valid"}}' --show
  along scratch update token-refresh --step 1 --step-status in-progress
  along scratch update token-refresh --step 1 --step-status passed
  along scratch fallback token-refresh --reason "single file change, no parallel roles"
  along scratch purge token-refresh
  ```

### `along worktree`
Manages runtime Git worktree workspace isolation for parallel or multi-agent execution, enforcing the 3-part Environment Readiness Contract.
- **Subcommands**:
  - `along worktree create <slug> [--branch <name>] [--base-ref <ref>]`: Provisions an isolated worktree at `.along/worktrees/<slug>`, links heavy dependencies (`node_modules`, `.venv`) via NTFS directory junctions on Windows (`mklink /J`) or symlinks on POSIX, copies untracked `.env*` files, and shares the session blackboard.
  - `along worktree remove <slug> [--force] [--keep-branch]`: Safely unlinks dependency junctions (`os.rmdir`) without touching parent files, resets CWD, and prunes the worktree with an exponential backoff loop for Windows file handle lock resilience.
  - `along worktree merge <slug> [--squash]`: Merges changes from the worktree branch into the primary working branch.
  - `along worktree list [--json]`: Lists active worktrees, branches, and linked dependencies.
  - `along worktree status [--json]`: Displays environment readiness and filesystem capability matrix.
  - `along worktree gc`: Prunes orphaned worktrees and purges deferred trash directories (`.along/worktrees/.trash_*`).
- **Usage**:
  ```bash
  along worktree create worker-auth --branch feature/auth
  along worktree list
  along worktree merge worker-auth --squash
  along worktree remove worker-auth --force
  along worktree gc
  ```

### `along git`
Registers Along's custom git merge drivers so concurrent branches merge projections and entity files without conflict markers. Drivers live in the local `.git/config` (per clone, never tracked); the file bindings live in a managed block of the tracked `.gitattributes`. No git hooks are installed. `along update` runs `setup` on the root context automatically.
- **Drivers**:
  - `along-projection` (`**/.along/ISSUES.md`, `**/.along/CONSTRAINTS.md`, `**/docs/INDEX.md`, plus `**/.along/DECISIONS.md` when modular `.along/DECISIONS/` exists): keeps "ours", exits 0, and records the path in `$GIT_DIR/along-projection-resync`. Git runs drivers before the merged entity files reach the working tree, so recompiling inside the driver would only rebuild the pre-merge board. A file that is not an Along projection falls back to a standard 3-way merge.
  - `along-frontmatter` (`**/.along/ISSUES/**/*.md`, `**/.along/DECISIONS/**/*.md`): 3-way YAML merge. A key changed on one side takes that side; if both sides changed it, lists get a 3-way set merge, `status` takes the most advanced lifecycle state, `updated`/`completed` take the later date, and other scalars take the side with the newer `updated` (ours on a tie). Bodies merge through `git merge-file`; overlapping body edits still leave conflict markers and a non-zero exit.
- **Subcommands**:
  - `along git setup [--uninstall] [--dry-run]`: Idempotently writes `merge.along-projection.*` / `merge.along-frontmatter.*` (absolute paths to the interpreter and `along_merge_driver.py`) and refreshes the `.gitattributes` block. `--uninstall` removes both.
  - `along git status [--json]`: Reports driver registration, the `.gitattributes` bindings, and projections awaiting a resync. `along doctor` reports the same.
  - `along git sync`: Recompiles `ISSUES.md`, `DECISIONS.md`, `CONSTRAINTS.md` (root and subprojects named in the marker) and `docs/INDEX.md`, then clears the marker. Run it after a merge.
- **Usage**:
  ```bash
  along git setup
  git merge feature/x
  along git sync
  ```

### `along rules`
Attaches engineering guidelines and rule packs to the project.
- **Subcommands**:
  - `along rules attach`: Automatically inspects repository dependencies and project manifests, attaching appropriate language and platform rule packs into `.along/rules/`. A pack whose body differs from its managed header hash is kept (`--on-conflict preserve|diff|overwrite`); an obsolete pack is pruned only when it is unmodified (a headerless legacy pack must match the current template).
  - `along rules status [--json]`, `along rules diff <rule>`, `along rules restore [<rule>]`: audit, diff and restore packs against the Along templates (restore backs up to `.along/.migration-backup/`).
- Agents never edit `.along/rules/**/*.md` directly: [gate: rule-pack-protection] denies file-tool writes at runtime and `along gates check` flags an edited pack (including shell edits) by its header hash.
- **Usage**:
  ```bash
  along rules attach
  along rules status
  along rules restore platforms/web.md
  ```

### `along budget` (alias `along context-budget`)
Audits repository token footprint and context budgets against protocol limits.
- **Options**:
  - `--check`: Exits with status code 1 if any measured file exceeds configured budget thresholds (e.g. `AGENTS.md` exceeding 7 KB).
  - `--json`: Outputs structured JSON report for CI/CD gates.
- **AGENTS.md limits**: `agents_md_bytes` (7168) measures `AGENTS.md` without its "Project specifics" section (the managed core; procedure lives in `.along/PROTOCOL.md`); `project_specifics_bytes` (4096) is a soft limit on that section that only warns, with the hint to move details into `docs/topic--*.md`. Both are overridable in the `budget` block of `.along/config.json`.
- **Usage**:
  ```bash
  along budget
  along budget --check
  along budget --json
  ```

### `along patch`
Executes deterministic Python AST code modifications without LLM syntax corruption.
- **Subcommands**:
  - `along patch replace-func <target_file> <function_name> <replacement_code_file>`: Replaces an existing Python function definition in `<target_file>` with code from `<replacement_code_file>`, preserving comments, formatting, and surrounding file contents.
- **Usage**:
  ```bash
  along patch replace-func scripts/engine.py validate_token scratch/new_validate.py
  ```

---

## 4. Protocol Tool Engines

Protocol tools provide specialized repository maintenance, release management, and intelligence operations.

### `along wrap`
Transactional end-of-stage wrap engine.
- Validates quality gates, inspects git diffs, updates active issue status, moves files to `done/`, writes session logs, recompiles projections, appends to `HISTORY.md`, and atomically commits wrapped work.
- **Check-then-write**: every check (team steps, plan, completion of `- [ ]` checklist items in issue Acceptance Criteria and living plan, tests, zero-byte audit, entity graph) runs before the first write; a failed wrap leaves the tree unchanged. KB sync runs after the transaction commits and only warns on failure.
- **Atomic auto-commit**: Automatically commits attributed files, issue status change, session log, and updated projections in a single atomic commit linked to the issue slug. `.along/PROTOCOL.md` and any `AGENTS.md` changed only inside its managed blocks (engine refreshes) are included too. Pass `--no-commit` to keep changes staged/unstaged on disk.
- **Options**:
  - `-s, --status <status>`: Closing status (`done`, `superseded`, `cancelled`, `duplicate`). Default: `done`.
  - `-m, --summary "<text>"`: One-line summary for `.along/HISTORY.md` index (falls back to issue title if omitted).
  - `--no-commit`: Skip automatic git commit of attributed and wrap metadata files.
  - `--dry-run`: Simulate wrap-up operations without writing or moving files.
  - `-n, --no-verify --reason "<text>"`: Skip pre-flight automated tests (`--force-reason` also serves as the reason). A recorded bypass, see [Runtime Lifecycle Hooks & Mechanical Gates](./topic--runtime-hooks-and-gates.md).
  - `-a, --agent "<name>"`: Explicit agent name.
  - `-d, --decisions "ADR-a,ADR-b"` or `--no-decisions` (one is required): The answer to "were architectural decisions made?". The session log for today is written or extended with `issues_completed: [<type>--<slug>]`, the decisions, the attributed paths as the front-matter list `files:`, and the blackboard record (step table, research, execution trace, notes, reviews; the plan is not copied). A second record of the same issue on the same day is appended as `## Blackboard Record (<n>, <ts>)`. The blackboard is purged only after the wrap transaction committed.
  - `--force-reason "<text>"`: Wrap past open steps, uncompleted checklist items, or a scaffold plan (refused otherwise, exit 2); it also passes the entity-reference-integrity gate. The reason is recorded in the trace and the session log; when a check is actually forced it is a recorded bypass.
- **Uncommitted work warning**: when `--no-commit` is used and files attributed to the issue remain uncommitted after wrap, warns with the list of paths and emits the exact `along commit -i <slug> --paths ...` command.
- **Completion token**: the purge removes the session's binding; when this session had an approved plan for the slug, it keeps a completion token so a manual `along commit -i <slug>` passes the plan gate without a new approval (see `along commit`).
- **Usage**:
  ```bash
  along wrap <slug> --no-decisions -m "Summary of work"
  along wrap <slug> --decisions ADR-2026-10-01--session-bindings -m "Summary of work"
  along wrap <slug> --no-commit --no-decisions -m "Summary of work"
  along wrap <slug> -s superseded --no-decisions
  ```

### `along kb-sync` (alias `along kb sync`)
Idempotent compiler and integrity gate for the living LLM-Wiki in `docs/`.
- Validates SHA-256 provenance against source files, recompiles `docs/INDEX.md`, updates `llms.txt` and `llms-full.txt`, rewrites legacy `.along/KB/` links, and enforces link integrity.
- **Options**:
  - `--strict`: Fails with non-zero exit code on broken relative links or missing targets.
  - `--crosslink-check`: Audits documentation for unlinked topic concepts.
  - `--crosslink-apply`: Automatically applies deterministic markdown cross-links.
  - `--strict-sections`: Enforces Section Taxonomy Contracts across standard topic files.
  - `--dry-run`: Reports planned modifications without writing to disk.
- **Usage**:
  ```bash
  along kb-sync
  along kb-sync --strict
  along kb-sync --crosslink-check
  ```

### `along kb-search` (alias `along kb search`)
Targeted snippet retrieval engine across `docs/` and `.along/` living memory.
- Uses token-based Inverse Document Frequency (IDF) scoring to extract relevant headings and paragraphs, minimizing prompt token consumption.
- **Options**:
  - `--category <cat>`: Filters by category (`all`, `kb`, `issue`, `decision`, `milestone`, `session`). Spikes are indexed as issues.
  - `--any`: Matches any query token (OR match).
  - `--prefix`: Enables prefix matching.
  - `--stats`: Outputs query timing and corpus indexing statistics.
- **Usage**:
  ```bash
  along kb-search "worktree readiness contract"
  along kb-search "token refresh" --category issue
  ```

### `along dep-scan`
Hierarchical dependency discovery and AI instruction scanner.
- Traverses multi-project repositories (npm, pip, cargo, nuget, go), parses dependencies, discovers vendor AI instruction files, and updates `docs/topic--dependencies.md`.
- **Options**:
  - `--json`: Emits raw JSON discovery data.
- **Usage**:
  ```bash
  along dep-scan
  along dep-scan --json
  ```

### `along history-sync`
Git commit history reconciliation engine.
- Reconstructs `.along/` milestones, issues, and session logs from existing Git commit history, tags, and PR references.
- **Usage**:
  ```bash
  along history-sync
  ```

### `along commit`
Conventional Commits generator with active issue binding and typography validation.
- Automatically checks modified files for forbidden non-ASCII typography, binds commit messages to the active `.along/` issue slug, and creates clean Git commits.
- **Options**:
  - `-i <slug>`: Explicitly specifies target issue slug (otherwise auto-detected from active issue).
  - `-m "<message>"`: Commit message body.
  - `--fix-typography`: Automatically rewrites non-ASCII typography violations before committing.
  - `-n, --no-verify --reason "<text>"`: Skips the pre-commit gates. A recorded bypass: the commit carries an `Along-Bypass: <gate>; <verified|unverified>; <reason>` trailer.
  - `-a, --all` / `--paths <file>...`: Stage the whole tree / only these paths. Prefer `--paths` when other sessions have uncommitted work in the tree.
  - `-p, --push`: Push after the commit.
- **Plan gate**: commits (`along commit`, `git commit`) are not held by `require_plan_approval`; it judges file-tool targets and, at turn end, the files the turn changed (see [Runtime Hooks & Gates](./topic--runtime-hooks-and-gates.md)).
- **Test reuse**: the pre-commit test gate (also of `along wrap` and `along bump`) skips the suite when a recorded green run on the same working tree covers the effective verify policy (full covers all; scoped/affected cover matching mode and scope). Partial runs never satisfy full. Runs are kept in `.along/diagnostics/test_runs.json`.
- **Docs-only skip**: `along commit` skips the test gate when the change touches only `*.md`, `docs/**`, `.along/**` (not `.along/scripts/`), `llms*.txt` or a version-only `package.json` change.
- **Usage**:
  ```bash
  along commit -i token-refresh -m "feat(auth): implement refresh token rotation"
  along commit -i token-refresh -m "fix(auth): handle expired token" --fix-typography
  ```

### `along version-bump` (alias `along bump`)
Multi-stack project version incrementer and release packager.
- Checks pre-release quality gates, updates package manifests (`package.json`, `pyproject.toml`, `Cargo.toml`), updates `CHANGELOG.md`, creates annotated Git release tags, and generates release commits with transactional rollback on test failure.
- **Options**:
  - `patch` | `minor` | `major` | `<version>`: Version increment level (default: `patch`).
  - `-c`, `--commit`: Automatically creates release commit.
  - `-p`, `--push`: Pushes release commit and tag to remote.
  - `--fix-typography`: Automatically repairs typography before releasing.
  - `-n`, `--no-verify --reason "<text>"`: Bypasses pre-mutation quality gates (a recorded bypass; the reason is required).
  - `--carry-over <milestone>`: Moves still-open issues of the released milestone to `<milestone>` (issue `milestone` field and both `target_issues` lists) instead of aborting.
- **Milestone reconciliation**: The milestone whose slug names the new version is set to `completed` only when all its issues (by `milestone` field or `target_issues`) are closed (`done`, `superseded`, `cancelled`, `duplicate`). Otherwise the release aborts inside the transaction and lists the open issues. `progress_pct` is closed / total.
- **Usage**:
  ```bash
  along bump patch
  along bump minor --carry-over v4.6.0-next-release
  along bump minor --commit
  ```

### `along init`
Deterministic scaffolder behind `/along-init` (`scripts/along_init.py`). Idempotent; existing state is never overwritten.
- **AGENTS.md**: FULL protocol block at an architecture root; a short REF block (`ref=<relpath>`) in a nested folder whose ancestor inside the same git working tree carries the FULL block. A git repository or submodule root always gets FULL. A hand-written file without markers gets the block on top and keeps its text under `## Project specifics`.
- **Files**: `CLAUDE.md` import line, `.gitattributes` merge lines, `.along/` skeleton (`ISSUES.md`, `ISSUES/done/`, `DECISIONS/`, `GLOSSARY.md`, `HISTORY.md`, `SESSIONS/<YYYY>/`), `docs/INDEX.md`. A nested context that gets a REF block creates no `GLOSSARY.md` and no `VISION.md` skeleton; they are created on first use.
- **VISION**: a root `VISION.md` ends up only in `.along/VISION.md` (moved, deduplicated, or merged under an `along:imported-vision needs-restructure` marker); links to it are repointed (public files -> `docs/INDEX.md`). Otherwise a skeleton with `## Scope`, `## Non-goals`, `## Roadmap` is created (FULL contexts only).
- **Pipeline**: `along rules attach`, `along git setup` (git roots), `along hook install --runtime all`, `along migrate --apply`.
- **Report**: CREATED / UPDATED / UNTOUCHED files, VISION outcome, repointed links, `AGENT ACTIONS` (imported VISION section, root notes `ROADMAP.md` / `ARCHITECTURE.md` / `SPEC.md` / `TODO.md` / `DESIGN.md`, adopted hand-written `AGENTS.md`) and, when `.along/` already existed, `RE-RUN QUESTIONS` for the user.
- **Options**: `--dry-run`, `--json`, `--profile <strict|standard|light>`, `--no-rules`, `--no-git`, `--no-hooks`, `--no-migrate`.
- **Usage**:
  ```bash
  along init --dry-run
  along init
  along init --profile light
  along init packages/lib --no-hooks
  ```

### `along update`
Self-update engine for the Along protocol and skills suite.
- Refreshes the managed protocol block in every context with the same rules as `along init` (FULL/REF, hand-written adoption) and runs the migration, whose heal passes (Step 13: root `VISION.md`; Step 16: legacy risk, spike and checklist records) run even on an up-to-date repository.
- Reconciles local repository files, managed protocol blocks, and global user skills (`~/.claude/`, `~/.gemini/`, `~/.codex/`) against the latest upstream release from GitHub.
- Automatically scaffolds and reconciles global runtime lifecycle hooks in user home configurations (`~/.gemini/config/hooks.json`, `~/.claude/settings.json`, and `~/.codex/hooks.json`) and recursively purges legacy local hooks and workaround scripts from consumer repositories.
- Performs pre-flight hook cleanup and per-context exception isolation so that corrupt or locked files in one subproject do not abort the update for remaining contexts.
- Refreshes existing contexts only: it never creates a context and never offers a package-manifest folder for `along init` (a manifest is not a subproject). Nested git repositories without a context are listed as a note.
- **Out-of-Band Recovery**: If an agent session is ever locked due to a broken hook configuration (chicken-and-egg problem), running `along update` from an external OS terminal bypasses agent interception, cleans up broken local hooks, and restores the environment.
- **Options**:
  - `--check-only`: Only inspect versions without making modifications.
  - `--dry-run`: Simulate updates, migrations, and hook installations without writing files.
  - `--force`: Force reinstallation even if versions match.
  - `--local-only`: Skip remote GitHub check and use local installation.
  - `--no-hooks`: Skip automatic reconciliation of runtime lifecycle hooks.
  - `--kb-sync`, `--dep-scan`, `--history-sync`, `--all-sync`: Post-update sync triggers.
- **Usage**:
  ```bash
  along update
  along update --dry-run
  along update --no-hooks
  ```

### `along dash` (alias `along dashboard`)
Launches the Along executive dashboard service.
- Provides interactive web UI (FastAPI + MobX), Cytoscape DAG dependency graph, OpenAPI Swagger interface, and static HTML reporting.
- **Options**:
  - `-w`, `--web`: Starts local web server on port 8000.
  - `-c`, `--cli`: Displays terminal summary table.
  - `-e`, `--export`: Generates standalone static HTML report.
- **Usage**:
  ```bash
  along dash --web
  along dash --cli
  ```

### `along migrate`
Protocol migration engine.
- Migrates legacy directory structures (`.agents/` to `.along/`, monolithic `DECISIONS.md` to modular ADRs), updates front-matter schemas, and preserves destination backups in `.along/.migration-backup/`.
- **Options**:
  - `--apply`: Applies planned migration operations (default is safe dry-run plan output).
- **Usage**:
  ```bash
  along migrate
  along migrate --apply
  ```

### `along sanitize` (alias `along typography`)
Typography inspection and ASCII enforcement utility.
- Scans documentation, scripts, and code files for forbidden unicode characters (em-dash, en-dash, curly quotes, guillemets, unicode ellipsis, non-breaking spaces) and reports line-by-line violations.
- **Options**:
  - `--dry-run`: Reports findings and exits with code 0 without modifying files.
  - `--write`: Applies clean ASCII replacements in-place.
  - `--json`: Emits structured JSON findings for CI automation.
  - `--include-data`: Also scans `.json`, `.yaml`, `.yml`, and `.toml` files.
  - `--exclude '<glob>'`: Skips paths matching specified glob pattern.
- **Usage**:
  ```bash
  along sanitize
  along sanitize --write
  along sanitize --check
  ```

### `along feedback` (aliases `diagnostics`, `telemetry`)
System diagnostics and incident dispatch engine.
- Gathers sanitized incident traces from `~/.along/diagnostics/` and exports or dispatches reports via GitHub Pull Request, Telegram bot, Webhook, or local export.
- **Subcommands**:
  - `list`: Lists unresolved diagnostic incidents (`--all` includes resolved).
  - `show <id>`: Shows full details of an incident.
  - `record --component <name> --error <msg>`: Records an incident manually.
  - `report`: Generates markdown diagnostics report (`--output <path>` saves to file).
  - `send`: Dispatches report or feedback note (`--channel {all,telegram,webhook,file,github}`, `--title <title>`, `--body-file <path>`, `--yes`, `--dry-run`).
  - `clear`: Purges diagnostic incident logs (`--all` purges resolved too).
  - `config`: Manages feedback transport configuration (`show`, `init`, `path`).
- **Usage**:
  ```bash
  along feedback list
  along feedback send --dry-run
  along feedback send --channel github --title "Feedback Title" --body-file feedback.md --yes
  ```

### `along graph-check`
Preflight verification for `code-review-graph` AST engine.
- Verifies graph indexing status, validates `.code-review-graph-ignore` configuration to prevent repository bloat, and checks tool accessibility.
- **Usage**:
  ```bash
  along graph-check
  along graph-check --json
  ```

### `along graph-sync` (alias `along graph-build`)
Code intelligence AST knowledge graph synchronization engine.
- Runs incremental AST update (default) or full rebuild (`--full`) via pinned `code-review-graph`.
- Automatically creates or repairs `.code-review-graph-ignore` with standard exclusions (`node_modules/`, `dist/`, `.venv/`, etc.) before indexing.
- **Usage**:
  ```bash
  along graph-sync              # Incremental update (changed files only)
  along graph-sync --full       # Full graph rebuild from scratch
  along graph-sync --status     # Show current graph statistics
  along graph-build             # Alias for graph-sync
  ```

### `along graph-impact`
Semantic blast radius and affected execution flow analyzer.
- Traces direct callers, callees, and importers using `code-review-graph` AST queries with automatic fallback to static search.
- Automatically maps impacted symbols to candidate tests and affected documentation articles in `docs/topic--*.md`.
- **Options**:
  - `TARGET`: Symbol name or file path (auto-detects changes from git if omitted).
  - `--base REF`: Git base ref for change detection (default: `HEAD~1`).
  - `--max-depth N`: Traversal depth in the call hierarchy (default: `2`).
  - `--json`: Output machine-readable JSON report.
  - `--optional`: Treat offline AST engine state as non-fatal warning.
- **Usage**:
  ```bash
  along graph-impact                          # Auto-detect changed files from git
  along graph-impact scripts/along_exec.py    # Target specific file
  along graph-impact my_symbol --max-depth 3  # Trace symbol callers up to 3 hops
  along graph-impact --json                   # Output machine-readable JSON report
  ```

### `along graph-arch`
Architectural intelligence, community clustering, and coupling hotspot analyzer.
- Analyzes repository modular structure, cohesion-based functional communities, hub hotspots, and critical bridge nodes.
- **Options**:
  - `--detail-level {standard,minimal}`: Output detail level (default: `standard`).
  - `--top-hubs N`: Maximum number of hub nodes to display (default: `5`).
  - `--top-bridges N`: Maximum number of bridge nodes to display (default: `5`).
  - `--json`: Output machine-readable JSON report.
- **Usage**:
  ```bash
  along graph-arch
  along graph-arch --detail-level minimal
  along graph-arch --json
  ```

### `along hook` (alias `along hooks`)
Runtime lifecycle hook interceptor and declarative gate evaluation harness.
- **Subcommands**:
  - `along hook eval <event> [--runtime {antigravity,claude,codex,generic}]`: Evaluates declarative gates against an incoming event payload passed via stdin or argument.
  - `along hook install [--runtime {antigravity,claude,codex,all}]`: Scaffolds or updates runtime hook configuration manifests (`.agents/hooks.json`, `.claude/settings.json`, `.codex/hooks.json`).
  - `along hook attribution [--runtime {claude,cursor,all}] [--claude-home DIR] [--cursor-home DIR] [--dry-run]`: Turns off AI commit attribution (`Co-Authored-By:` trailers) in existing runtime homes: `attribution.commit = ""` + `includeCoAuthoredBy = false` in Claude Code `settings.json`, `attribution.attributeCommitsToAgent = false` in Cursor `cli-config.json`. Writes no hooks. Also run by the installers and every `/along-update`.
  - `along hook install --git [--uninstall] [--dry-run]`: Opt-in, never run by init/update. Writes `pre-commit` and `commit-msg` shims into the repository's hooks directory that run `along gates check --hook <name>`. A foreign hook already there is kept as `<hook>.pre-along` and run first (restored on `--uninstall`); with `core.hooksPath` set (husky, lefthook) nothing is written and the commands to add to the manager are printed.
  - `along hook verify [--strict]`: Audits bi-directional traceability between prose badges (`[gate: <id>]`) across documentation/skills and declarative YAML gate rules in `default_gates.yaml`, and prints the enforcement matrix (`runtime` / `git` / `ci` per gate).
- **Usage**:
  ```bash
  along hook verify --strict
  along hook install --runtime all
  along hooks install --git
  ```

### `along gates`
Runs the commit-time gate subset (catalogue entries with `git` or `ci` in `enforcement`) outside agent runtimes. Read-only: projection freshness is checked by recompiling in a temp snapshot. Exit `0` clean, `1` violations, `2` usage error.
- **Subcommands**:
  - `along gates check`: Staged changes (same as `--hook pre-commit`).
  - `along gates check --hook pre-commit`: Added lines of the staged diff (typography in `.md`/`.py`/`.sh`/`.ps1`/`.bat`, conflict markers, anti-stub) and freshness of staged `.along/` boards (`ISSUES.md`, `DECISIONS.md`, `CONSTRAINTS.md`). Only added lines count, so existing debt elsewhere never blocks a commit.
  - `along gates check --hook commit-msg <file>`: Issue binding and AI co-author trailers in the message.
  - `along gates check --ci [--range R] [--no-links] [--json]`: Every non-merge commit message in the range, the range diff, projection freshness of the checkout, and link integrity (`along kb-sync --check`). The range defaults to `origin/$GITHUB_BASE_REF...HEAD` for PRs, `$ALONG_CI_BEFORE..HEAD` for pushes, else `HEAD^..HEAD`. Used by `.github/workflows/tests.yml`.
  - `along gates stats [--since YYYY-MM-DD]`: Per-gate blocked / warned / bypassed counts aggregated from `.along/diagnostics/hooks_audit.jsonl` (shadow-mode records, `decision: "warn"`, count as warnings; `decision: bypass` entries as bypasses), then "Repeated blocks": identical (gate, target) blocks >= 3 in one conversation, a loop indicator. Each audit entry ends with `target` (the judged command or file path, redacted, at most 200 chars); entries without it fall back to the reason. Read-only.
  - `along gates denials [--slug SLUG] [--json]`: Gate denials of the bound issue (or `--slug`) from its event ledger, as well as Stop denials from the session activity trace: `open`, `resolved (retry)` (the same command or path later went through; a write counts once it succeeded), `resolved (approve)` (a `denial: procedural` gate - `require_plan_approval`, `require_active_issue` - after the plan approval), or `acked` (verified once the user replied after the ack). Operates even without active session binding by inspecting recent session activity traces. Read-only. [feat--anti-silent-fallback-gate]
  - `along gates ack (ID... | --all) --note "..." [--slug SLUG]`: Records that the user was told what a denied tool call left undone (`ack` ledger event plus a trace line). Acknowledges PreToolUse ledger denials and Stop-time activity trace denials alike, even after session unbinding or wrap. Releases [gate: unresolved_gate_denial] at turn end; `along wrap`, `along issue done` and `along session close` accept it once the user has replied after it. Exit `2` without `--note` or with an unknown id.
- **Usage**:
  ```bash
  along gates check --ci --range origin/main...HEAD
  along gates stats --since 2026-10-01
  along gates denials
  along gates ack d-1a2b3c --note "force push not done: held by the gate, left to the user"
  ```

### `along lint`
Alias of `along gates check`: runs the commit-time checks on demand (typography, anti-stub, AI co-author trailers, code fence languages, portable links, stable entry point, Windows-safe filenames, tracked secrets). The same checks run in pre-commit / commit-msg hooks and CI, not while the agent works. Takes the same options as `along gates check`.
- **Usage**:
  ```bash
  along lint
  along lint --ci --range origin/main...HEAD
  ```

### `along run`
Executes an agent runtime supervisor or runs a shell command behind the Along runtime lifecycle hook and declarative gate pipeline.

#### 1. Agent Runtime Runner
Supervises an autonomous agent runtime (such as Google Antigravity), enforcing workspace containment, active issue binding, and dual-channel OpenTelemetry tracing:

```bash
along run antigravity [--dry-run] [-i|--issue <slug>] [--run-id <id>] [-e|--endpoint <url>] [-b|--binary <path>] [-- <agent-args...>]
along run agy [--dry-run] [-i|--issue <slug>] [--run-id <id>] [-e|--endpoint <url>] [-b|--binary <path>] [-- <agent-args...>]
```

Parameters:
- `--dry-run`, `-n`: Preview configured environment variables, resolved binary, and active issue binding without spawning the process.
- `-i`, `--issue <slug>`: Bind the run to an explicit active issue (defaults to the currently in-progress issue in `.along/ISSUES/`).
- `--run-id <id>`: Set an explicit 32-character run ID for telemetry grouping.
- `-e`, `--endpoint <url>`: Target OpenTelemetry OTLP/HTTP traces endpoint.
- `-b`, `--binary <path>`: Explicit path to the Antigravity binary executable.

#### 2. Lifecycle Command Proxy
Intercepts shell commands, evaluating the `PreToolUse` shell gates (`cli_safety` warnings, `destructive_command`, commit gates) before executing:

```bash
along run pytest -q
along run npm test
```

### `along orchestrate`
Cross-runtime multi-agent supervisor orchestrator for tiered model workflows. Executes sequential multi-agent loops across heterogeneous CLI runtimes (claude, claude-code, codex, opencode, generic).

- **Usage**:
  ```bash
  along orchestrate <slug> [options]
  ```
- **Options**:
  - `--dry-run`: Preview prompt payloads and simulated runs without launching processes.
  - `--max-retries <N>`: Maximum retry attempts per step (default: 3).
  - `--timeout <sec>`: Process timeout per role execution in seconds.
  - `--scout <runtime>`: Runtime adapter for scout role (choices: claude, claude-code, codex, opencode, generic).
  - `--architect <runtime>`: Runtime adapter for architect role.
  - `--implementer <runtime>`: Runtime adapter for implementer role.
  - `--reviewer <runtime>`: Runtime adapter for reviewer role.
  - `--model <model>`: Default model override across roles.
  - `--skip-scout`: Skip scout research phase.
  - `--skip-architect`: Skip architect living plan phase.
  - `--force`: Force claim acquisition or execution restart.
  - `--json`: Output execution results as JSON.

### `along resolve`
Semantic and test-gated conflict auto-resolution engine for documentation and source code (`feat--docs-semantic-conflict-resolution`, `feat--test-gated-code-merge-pipeline`).
- **Documentation mode (`--docs`, default)**:
  - Detects unmerged markdown files (`UU`, `AA`, `UD`, `DU` in `docs/**/*.md`, `README.md`, `AGENTS.md`) and reconciles structural conflicts outside fenced code blocks.
  - Non-overlapping headings/sections combined in deterministic order.
  - Task checklists (`- [ ]`, `- [x]`) merged via set-union with `[x]` completion priority; table rows deduplicated.
  - Recompiles the Knowledge Base via `along kb sync` after successful resolution.
- **Source code mode (`--code`)**:
  - Detects unmerged source code files, reconciling non-overlapping imports, functions, classes, and methods.
  - Enforces test-gated verification: executes the project test suite (`along test`) immediately after code resolution. If tests fail, `FileTransaction` restores all original conflict markers and exits with code 1.
- **Options**:
  - `--docs`: Target unmerged documentation files across `docs/` and root markdown (default).
  - `--code`: Resolve unmerged source code files with test-gated verification.
  - `--no-tests`: Skip running test runner during code conflict resolution verification.
  - `--check`, `--dry-run`: Test resolution and report outcomes without writing changes to disk.
  - `--strict`: Fail with exit code 1 if any conflict cannot be cleanly resolved or broken links remain.
  - `--no-kb-sync`: Skip post-merge `along kb sync` execution.
  - `files`: Optional explicit file paths to resolve.
- **Usage**:
  ```bash
  along resolve --docs
  along resolve --code
  along resolve --check
  along resolve --strict docs/topic--architecture.md
  ```

### `along conflict-check` (alias `along conflictcheck`)
Predicts git merge conflict risks and AST symbol collisions between `HEAD` and a target branch before merging (`scripts/along_conflict_check.py`).
- Analyzes the common merge-base ancestor between branches.
- Detects overlapping modified files across branches.
- Identifies colliding AST symbols across function and class definitions.
- Classifies risk level (`CLEAN`, `LOW`, `MEDIUM`, `HIGH`, `UNKNOWN`) and exits with code 1 on `HIGH` or `UNKNOWN` risk.
- **Options**:
  - `branch`: Target branch to compare against HEAD.
  - `--json`: Output report in structured JSON format.
- **Usage**:
  ```bash
  along conflict-check origin/main
  along conflict-check feature-branch --json
  ```

### `along brief`
Compile compact, role-specific handoff context for an issue (`scripts/alongkit/commands/brief.py`).
- Assembles deterministic context prompt for `architect`, `implementer`, or `reviewer`.
- Validates issue existence, required issue slug, and role parameter.
- Usage errors (missing issue slug, missing role, or invalid role) exit with code 2.
- **Options**:
  - `<slug>`: Target issue slug (required).
  - `--role <architect|implementer|reviewer>`: Target role for prompt brief compilation (required).
- **Usage**:
  ```bash
  along brief my-feature --role implementer
  along brief my-feature --role reviewer
  ```

---

## 5. Exit Codes and CI/CD Automation

All Along CLI commands adhere to standard POSIX process exit code conventions:

| Exit Code | Meaning | Example Scenarios |
| :--- | :--- | :--- |
| `0` | Success | Operation completed cleanly; all gates passed. |
| `1` | General Failure / Gate Denial | Syntax error, broken link (`kb-sync --strict`), forbidden typography (`sanitize`), failed test. |
| `2` | Usage / CLI Argument Error / Agent Denial | Missing or invalid CLI arguments (e.g. invalid role in `along brief`), entity names starting with `-`, or OpenAI Codex hook denial. |


For automated CI/CD validation pipelines, run the following sequence to enforce total repository integrity:

```bash
# 1. Verify gate traceability
along hook verify --strict

# 2. Check typography cleanliness
along sanitize

# 3. Check link integrity and taxonomy
along kb-sync --strict --strict-sections

# 4. Check context budget
along budget --check

# 5. Run hermetic tests
along test
```

---

## Document: docs/topic--declarative-gates-and-traceability.md (Declarative Gate Engine & Protocol Traceability Matrix)

# Declarative Gate Engine & Protocol Traceability Matrix

## 1. System Topology & Overview

Natural language guidelines and prose instructions in `AGENTS.md` and `skills/*/SKILL.md` are vulnerable to context truncation and probabilistic LLM compliance degradation. While runtime hooks provide interception at the agent harness boundary, hardcoded Python gates create maintenance overhead and opacity: agents and developers cannot easily inspect which prose instructions correspond to active enforcement logic.

The Along Declarative Gate Engine and Bi-Directional Traceability Matrix bridges this gap. It replaces opaque programmatic gates with an extensible, metadata-driven YAML gate catalogue (`scripts/alongkit/hooks/default_gates.yaml` and repository-level `.along/rules/gates.yaml`), paired with explicit inline prose badges (`[gate: <id>]`) embedded across protocol specifications and skill manifests.

```text
+-------------------------------------------------------------------------+
|                  Prose Specifications & Skill Manifests                 |
|  AGENTS.md, skills/along-init/protocol.md, skills/along-commit/SKILL.md |
|  Embedded Badges: [gate: <id>] (e.g. [gate: commit_issue_binding])      |
+-------------------------------------------------------------------------+
                                    |
                    Machine-Checked Bi-Directional Audit
                    (along hook verify / traceability.py)
                                    v
+-------------------------------------------------------------------------+
|                   Declarative Gate Engine Catalogue                     |
|  scripts/alongkit/hooks/default_gates.yaml                              |
|  .along/rules/gates.yaml (repository overrides)                         |
+-------------------------------------------------------------------------+
       |                                                    |
       v (Regex/Match rules)                                v (Stateful predicates)
+----------------------------+             +------------------------------+
| Declarative Content Gates  |             | Stateful Predicates Engine   |
| - anti_stub_injection (git)|             | - require_active_issue       |
| - cli_safety (warn)        |             | - require_plan_approval      |
| - projection_protection    |             | - destructive_command        |
| - typography (git)         |             | - test_before_stop           |
| - commit_issue_binding     |             | - wrap_before_stop           |
| - commit_no_conflict_marker|             | - subproject_boundary        |
+----------------------------+             +------------------------------+
               \                                         /
                v                                       v
+-------------------------------------------------------------------------+
|                         Runtime Hook Execution                          |
|         Universal Dispatcher: scripts/along_hook.py                     |
|         Runtimes: Antigravity, Claude Code, OpenAI Codex                |
+-------------------------------------------------------------------------+
```

---

## 2. Core Components & Engine Implementation

### 2.1 Declarative Schema & Gate Catalogue (`default_gates.yaml`)

Gates are declared in YAML format with standard schema fields:
- `id`: Canonical identifier matching prose badges (e.g., `commit_issue_binding`).
- `description`: Human-readable summary of the invariant.
- `event`: Lifecycle trigger event (`PreToolUse`, `PostToolUse`, `Stop`), or a list of them (`require_plan_approval` uses `[PreToolUse, Stop]`). Gates with `enforcement: [git, ci]` declare no event.
- `decision`: Action on match (`deny`, `ask`, `force_ask`).
- `target_tools`: List of tools intercepted (e.g., `run_command`, `write_to_file`).
- `match_type`: Evaluation strategy (`regex`, `predicate`, `composite`).
- `patterns`: Regex patterns for argument matching (for `regex` matchers).
- `predicate`: Name of python predicate handler in `alongkit.hooks.predicates`.
- `remediation`: Explicit remediation message returned to the agent on violation.
- `enforcement`: Layers that enforce the gate, any of `runtime` (agent hooks, the default), `git` (opt-in `along hooks install --git`), `ci` (`along gates check --ci`). An unknown layer is a schema error. `alongkit.gitgates` reads its patterns (issue binding, anti-stub) from the same entries, so the layers cannot disagree. `along hook verify` prints the resulting matrix.

The catalogue defines 33 gates; the ones below are described here (the team, doc-lock, entity-deletion, session-record and bounded-prompt gates are covered in [Runtime Hooks & Gates](./topic--runtime-hooks-and-gates.md)). Commit-time content checks (`typography`, `anti_stub_injection`, `commit_no_ai_coauthor`, plus 17-23) run at pre-commit / commit-msg / CI and on demand through `along lint` (alias of `along gates check`):
1. `commit_issue_binding`: Intercepts `git commit` to require issue binding: `[<type>--<slug>]` or `(refs #<slug>)`, the form `/along-commit` appends. In git/CI mode, subjects starting with `release: `, `Merge `, `Revert "`, `fixup! `, `squash! ` are exempt.
2. `commit_no_conflict_markers`: Intercepts `git commit` and inspects the lines the commit would add (`git diff --cached`, or `git diff HEAD` for `commit -a`) for unresolved merge conflict markers at line start (`<<<<<<< `, `=======`, `>>>>>>> `). The commit message itself is not inspected, so a Markdown rule of `=======` in a message is allowed. No file class is exempt: `merge=union` files never receive markers from git, so a marker there is a real conflict too.
3. `anti_stub_injection` (`enforcement: [git, ci]`): Forbids stub markers and lazy truncation skeletons on added lines at commit time.
4. `cli_safety`: Warns (every profile) on shell commands with heredocs (`<<EOF`), inline python file writers, and global installs. Recursive deletes and history rewrites belong to `destructive_command` (13).
5. `projection_protection`: Intercepts file writes to derived projections (`.along/ISSUES.md`, `docs/INDEX.md`, `DECISIONS.md`).
6. `typography` (`enforcement: [git, ci]`): Enforces ASCII typography at commit time (no em-dashes, curly quotes, guillemets, ellipsis glyphs, or NBSP); no runtime hook.
7. `require_active_issue`: Stateful predicate requiring an active `in-progress` issue in `.along/ISSUES/` bound to the current session. It never fires on Along state under any `.along/` (except `.along/scripts/`, which is code). Its `exclude_paths` (`docs/**`, `CHANGELOG.md`) match relative to the context owning the file, so a subproject's own state and docs pass like the root's. A session bound to a subproject issue may also edit inside that issue's `write_scope` / `allowed_roots` (`along start --write-scope/--allow-root`, relative to the issue's context).
8. `test_before_stop`: Intercepts session termination (`Stop`) to ensure `/along-test` or test suites ran cleanly if code was modified. Passes immediately when the working tree matches a recorded green run (`alongkit.testruns`) covering the effective verify policy (full covers all; scoped/affected require matching mode and scope). If tests ran but did not cover the approved verify policy, the gate remains armed and states the mismatch. Documentation edits re-arm it only with the option `count_docs: true`, where doc-only edits can be satisfied by scoped tests declared under `doc_tests: [...]` (`along test --doc`). Built-in test-inert paths (`.vscode/**`, `.idea/**`, `*.code-workspace`, `.editorconfig`, `.claude/**`, `.codex/**`, `.cursor/**`) and patterns declared under `ignore_paths` do not arm the gate. On rejection, the gate message lists the modified source files.
9. `wrap_before_stop`: Intercepts session termination (`Stop`) to ensure a session log exists if an issue was marked done.
10. `projection_sync_before_stop`: At session termination (`Stop`) recompiles a stale `ISSUES.md` itself (content compared with the compiled board); it never blocks.
11. `subproject_boundary`: Enforces context localization for subprojects with their own `.along/`, preventing subproject entities from leaking to workspace root `.along/`. A folder with only a package manifest is not a subproject.
12. `worktree_env_readiness`: Verifies dependency junctions and environment config propagation before worktree tool execution.
13. `destructive_command` (`alongkit.hooks.deletion`): Holds only explicit recursive deletes (`rm -r`, `Remove-Item -Recurse`, `del /s`, `rd /s`, ...), `git clean -f`, `git reset --hard` and `git push --force` when the target is empty, unexpandable, outside the repository, the repository itself, or holds uncommitted work (`git reset --hard`: modified tracked files; `git clean -f`: its dry run removes something; `git push --force`: always). ASK in interactive sessions, DENY in autonomous ones (`ALONG_AUTONOMOUS=1`, Claude Code `bypassPermissions`).
14. `require_plan_approval` (`event: [PreToolUse, Stop]`): Without an approved plan, holds a file-tool write to a repository file (not a planning or session artifact) before it runs, and at `Stop` the files the turn changed according to `git status` (baseline taken at the user's message, `alongkit.hooks.turnstate`), outside Along state and planning artifacts. Shell commands are never checked before they run; commits are not held.
15. `commit_no_ai_coauthor` (`enforcement: [git, ci]`): Rejects at commit time (commit-msg hook, CI, `along lint`) a message carrying a `Co-Authored-By:` trailer that names an AI agent. Human co-authors pass. Opt-out: `.along/config.json` `commits.allow_ai_coauthor: true`. See [Runtime Hooks & Gates](./topic--runtime-hooks-and-gates.md).
16. `workspace_containment`: Keeps file, search and shell `Cwd` paths inside the workspace (`alongkit.hooks.containment`). Paths are canonicalized with `os.path.realpath`, so `..` and symlinks cannot escape. Writes are allowed in the workspace (limited to `write_scope` plus `.along/` when declared), the system temp dir, the runtime brain dir of the current conversation, `~/.claude/projects/` and the Claude Code plan dir `~/.claude/plans/`. Reads are also allowed in declared `allowed_roots`, a worktree's main checkout, and the read-only global dirs `~/.gemini`, `~/.claude`, `~/.codex`, `~/.along`. Credential stores (`~/.ssh`, `~/.aws`, ...) are never accessible. A write outside scope is denied. A read outside scope returns `ask` in interactive mode and `deny` in autonomous mode (Claude Code `bypassPermissions`, `ALONG_AUTONOMOUS=1`, or `on_violation: deny`). Runtimes without an ask channel receive `deny` (the engine converts `ask` for every runtime except Antigravity). Scopes come from the gate options, the in-progress issue frontmatter (`allowed_roots`, `write_scope`) and `along start --allow-root/--write-scope`. The workspace is the session's project: when the runtime names it (Claude Code `CLAUDE_PROJECT_DIR`) and the shell cwd lies inside it, a `cd` into a nested `.along/` context does not narrow the scope (`repo.find_session_root`); relative paths still resolve against the shell cwd.

Repository-state gates (17-23) declare `enforcement: [git, ci]` and no runtime layer, so the runtime pipeline skips them. `along gates check` runs their `alongkit.repochecks` handlers over the staged blobs (pre-commit) or every tracked file (`--ci`). A line containing `along: allow-<gate-id>` is exempt (for fixtures), and `exclude_paths` (fnmatch globs) exempts whole files:

17. `windows_safe_filenames`: No `<>:"|?*`, control characters, trailing dot/space or reserved device names (`CON`, `NUL`, `COM1`, ...) in any path component.
18. `untracked_exports`: `.along/dashboard.html`, `.along/DASHBOARD.md` and per-machine `.along/diagnostics/` files (any context depth) are never tracked. Untracking (`git rm --cached`) passes; migration Step 14 untracks diagnostics committed before the directory ignored itself, and `along doctor` reports any that remain.
19. `code_fence_language`: Every opening Markdown code fence names a language (`text` for plain output).
20. `portable_links`: Markdown link targets use no `file://` scheme and no backslashes. Inline code and fenced blocks are ignored.
21. `stable_entry_point`: Files in `scope` (default `README.md`, `docs/*`) never link into `.along/`.
22. `issue_lifecycle`: Closed issues (`done`, `cancelled`, `superseded`, ...) live in `.along/ISSUES/done/`; open, in-progress or blocked ones never do.
23. `no_tracked_secrets`: No private key headers or well-known token shapes (AWS, GitHub, Anthropic, OpenAI, Slack, Google).

The entity graph gate spans all three layers:

24. `entity_reference_integrity`: `alongkit.entities.validate_entities` finds no dangling reference (`related`, `blocked_by`, `parent`, `superseded_by`, `duplicate_of`, `milestone`, `target_issues`, session `issues_*`) and no schema or enum violation. References resolve in the nearest `.along/`, in enclosing contexts up to the git root, in nested subproject contexts below it (`descendant_entity_keys`) and in sibling contexts of the same git repository (`sibling_entity_keys`); nested git repositories are not entered. Schema findings on archived issues are warnings. Runtime: a `Stop` predicate once git reports a changed entity file; `along wrap` (rolls back) and `along issue sync` (exit `1`) call `alongkit.gates.entity_integrity_gate`, which only warns in `shadow` mode. All three block only problems absent at `HEAD` (`gitgates.baseline_entity_problems`); pre-existing ones are printed as a warning. Git/CI: `along gates check` and `along commit` validate a snapshot of the staged (or checked-out) `.along/` against HEAD (or the range base) and block only problems the change introduces; pre-existing ones are printed as a notice. Renaming or retiring a referenced issue goes through `along issue rename` / `along issue supersede`, which rewrite the inbound references.

The managed rule pack gate also spans all three layers:

25. `rule_pack_protection`: Managed rule packs (`.along/rules/**/*.md` in any `.along/`) belong to `along rules attach`. Runtime: denies file-tool writes to them (shell edits are caught at commit by the header hash check below); `.along/rules/gates.yaml` stays editable. Git/CI: `alongkit.gitgates.check_rule_packs` runs `repochecks.check_rule_pack_integrity` over staged (or tracked) rule packs, which must carry the managed header with a body matching its `sha256`. The gate's catalogue rule is the runtime predicate, so the repository-state loop does not run it. Project guidelines go to `docs/topic--<slug>.md` or `AGENTS.md` "Project specifics"; `along rules restore` reverts a pack.

26. `wrapped_work_uncommitted` [gate: wrapped_work_uncommitted]: Intercepts session termination (`Stop`) to warn when the active session wrapped an issue but attributed files remain uncommitted on disk. Non-blocking: runs in `shadow` mode by default, emitting guidance on committing attributed files.

27. `doc_routing_compliance` [gate: doc-routing-compliance]: Enforces the Along Documentation Routing Tree. `README.md` must remain a high-level overview (no deep code fences >50 lines, no coding convention or technical reference sections >50 lines, no overall bloat >300 lines with technical reference content). `AGENTS.md` must not treat `README.md` as the conventions source of truth instead of `docs/topic--<slug>.md` or `docs/INDEX.md`. Enforced across runtime (`PreToolUse`), git `pre-commit`, and `--ci`.

Gate options: keys of a gate entry other than the definition keys (`id`, `title`, `description`, `event`, `tools`, `match_args`, `rule(s)`, `enforcement`, `enabled`) are passed to predicate handlers as `options=`. A `.along/rules/gates.yaml` entry whose `id` names a built-in gate is merged into it: keys it sets win and the rest is inherited, so an entry can just add options or set `enabled: false`:

```yaml
gates:
  - id: workspace_containment
    allowed_roots: ["../contracts", "../shared-lib"]
    write_scope: ["packages/auth"]
    on_violation: deny      # auto (default) | ask | deny
  - id: require_plan_approval
    enforce_unbound: true   # also hold sessions not bound to an issue (default false)
  - id: test_before_stop
    enforce_unbound: true
    ignore_paths: ["build/**", "dist/**"]  # additional test-inert paths (globs)
```

`enforce_unbound` (`require_plan_approval`, `test_before_stop`): by default these gates hold only agent sessions bound to an issue (`along start <slug>`); unbound sessions fail open. Set it to `true` to hold every session.


### 2.2 Stateful Predicate Handlers (`alongkit.hooks.predicates`)

While regex gates evaluate single tool calls in isolation, complex invariants require session state:
- `record_tool_activity()`: Records executed commands and modified paths into `.along/diagnostics/activity_trace.jsonl`.
- `load_activity_trace()`: Reconstructs session tool call history to evaluate post-conditions.
- Predicate functions (`check_require_active_issue`, `check_test_before_stop`, `check_wrap_before_stop`, `check_uncommitted_wrap_before_stop`, `check_projection_sync_before_stop`, `check_subproject_boundary`, `check_mutation_authorization`, `check_destructive_command`) return a violation message string or `None`.

### 2.3 Bi-Directional Traceability Scanner (`alongkit.hooks.traceability`)

The traceability engine guarantees zero drift between written instructions and active enforcement:
- `scan_prose_anchors()`: Parses Markdown files across `AGENTS.md` and `skills/*/SKILL.md` using regex `r"\[gate:\s*([a-zA-Z0-9_-]+)\]"`.
- `audit_traceability()`: Correlates prose anchors against active gates loaded from YAML.
  - Reports missing anchors (gates defined in YAML with no prose badge).
  - Reports dangling badges (badges in prose with no corresponding YAML gate).
  - Returns boolean pass/fail status.
- CLI verification: `along hook verify` (or `python scripts/along_hook.py verify`) runs the audit and outputs a structured matrix report.

---

## 3. Data Flow & Execution Workflow

### 3.1 Declarative Gate Evaluation Flow

```text
[Tool Invocation Event]
          |
          v
[Declarative Engine: load_gates()]
  Reads: scripts/alongkit/hooks/default_gates.yaml
  Reads: .along/rules/gates.yaml (if present)
          |
          v
[Filter Gates by event_type and target_tools]
          |
   +------+------+
   |             |
(Regex)     (Predicate)
   |             |
   |             +--> [Execute alongkit.hooks.predicates]
   |                  Reads repository state & activity trace
   v                  Returns violation string or None
[Regex Match on Args]    |
   |                     |
   +----------+----------+
              |
         (Violation?)
          /        \
        YES         NO
         |           |
         v           v
    [GateResult:   [GateResult:
     DENY]          ALLOW]
```

### 3.2 Machine-Checked Traceability Verification Flow

```text
[Developer / Agent invokes: along hook verify]
                       |
                       v
         [audit_traceability(repo_root)]
          /                           \
         v                             v
[Parse Prose Badges]          [Load Declarative Gates]
AGENTS.md, skills/*/SKILL.md   default_gates.yaml + gates.yaml
         \                             /
          v                           v
         [Cross-Reference Badges <-> Gate IDs]
                       |
        +--------------+--------------+
        |                             |
 (Clean 1:1 Match)             (Drift Detected)
        |                             |
        v                             v
[Verdict: PASSED]             [Verdict: FAILED]
Exit Code: 0                  Exit Code: 1 (lists missing/dangling)
```

---

## 4. Invariants & Failure Modes

1. **Strict Bi-Directional Traceability Invariant**:
   - Every active gate in `default_gates.yaml` MUST have at least one corresponding `[gate: <id>]` badge in prose documentation (`AGENTS.md` or `skills/`).
   - Every `[gate: <id>]` badge in documentation MUST map to an active gate in the catalogue.
   - `along hook verify` MUST exit with code 0 in CI and local test suites (`tests/test_gates_traceability.py`).
2. **Deterministic Isolation**:
   - Predicate handlers and file parsers use narrow exception handling `(OSError, UnicodeDecodeError, ValueError)`. Generic exceptions (`except Exception:`) and unhandled crashes are forbidden.
3. **Repository Extensibility**:
   - Projects can extend or override default gates by adding `.along/rules/gates.yaml`.
   - Repository-specific gates are merged with `default_gates.yaml`, allowing local project rules to participate in declarative verification.
4. **Hermetic Test Guarantees**:
   - All tests for declarative gate loading, predicate evaluation, and traceability verification run strictly within throwaway temporary directories (`tempfile.mkdtemp()`).

---

## Document: docs/topic--dependencies.md (Dependencies & Submodules AI Documentation and Rules)

# Dependencies & Submodules AI Documentation and Rules

> [!NOTE]
> This document maintains a unified registry of internal subprojects, submodules, and external dependencies.
> Consult linked guidelines when developing, refactoring, or integrating components across the repository.

## Internal Subprojects, Modules & Submodules

| Subproject / Module | Path | Ecosystems | AI Documentation & Context |
| :--- | :--- | :--- | :--- |
| **`@along/dashboard-ui`** | `packages/dashboard-ui` | `npm` | [AGENTS.md](../packages/dashboard-ui/AGENTS.md) <br> [llms-full.txt](../packages/dashboard-ui/llms-full.txt) <br> [llms.txt](../packages/dashboard-ui/llms.txt) <br> [docs/](../packages/dashboard-ui/docs) |

## Internal Monorepo Dependency Graph

No internal monorepo package inter-dependencies detected.

## Declared External Dependencies with AI Guidelines

| Package | Scope / Project | Ecosystem | Version | AI Guidelines / Instructions |
| :--- | :--- | :--- | :--- | :--- |
| **`@actdim/dynstruct`** | `packages/dashboard-ui` | `npm` | `1.12.2` | [AGENTS.md](../packages/dashboard-ui/node_modules/.pnpm/@actdim+dynstruct@1.12.2_@a_9cc227333c0ecf4368f7602292dd8c27/node_modules/@actdim/dynstruct/AGENTS.md) <br> [CLAUDE.md](../packages/dashboard-ui/node_modules/.pnpm/@actdim+dynstruct@1.12.2_@a_9cc227333c0ecf4368f7602292dd8c27/node_modules/@actdim/dynstruct/CLAUDE.md) <br> [llms-full.txt](../packages/dashboard-ui/node_modules/.pnpm/@actdim+dynstruct@1.12.2_@a_9cc227333c0ecf4368f7602292dd8c27/node_modules/@actdim/dynstruct/llms-full.txt) <br> [llms.txt](../packages/dashboard-ui/node_modules/.pnpm/@actdim+dynstruct@1.12.2_@a_9cc227333c0ecf4368f7602292dd8c27/node_modules/@actdim/dynstruct/llms.txt) <br> [docs/](../packages/dashboard-ui/node_modules/@actdim/dynstruct/docs) <br> manifest metadata (`ai`) |
| **`@actdim/dynstruct-mui`** | `packages/dashboard-ui` | `npm` | `1.12.2` | [AGENTS.md](../packages/dashboard-ui/node_modules/.pnpm/@actdim+dynstruct-mui@1.12._dbfecc25c230812454a35b7fc03c90af/node_modules/@actdim/dynstruct-mui/AGENTS.md) <br> [CLAUDE.md](../packages/dashboard-ui/node_modules/.pnpm/@actdim+dynstruct-mui@1.12._dbfecc25c230812454a35b7fc03c90af/node_modules/@actdim/dynstruct-mui/CLAUDE.md) <br> [llms-full.txt](../packages/dashboard-ui/node_modules/.pnpm/@actdim+dynstruct-mui@1.12._dbfecc25c230812454a35b7fc03c90af/node_modules/@actdim/dynstruct-mui/llms-full.txt) <br> [llms.txt](../packages/dashboard-ui/node_modules/.pnpm/@actdim+dynstruct-mui@1.12._dbfecc25c230812454a35b7fc03c90af/node_modules/@actdim/dynstruct-mui/llms.txt) <br> [docs/](../packages/dashboard-ui/node_modules/@actdim/dynstruct-mui/docs) <br> manifest metadata (`ai`) |
| **`@actdim/msgmesh`** | `packages/dashboard-ui` | `npm` | `1.12.2` | [AGENTS.md](../packages/dashboard-ui/node_modules/.pnpm/@actdim+msgmesh@1.12.2_@act_ada671f90b40be71a7baed66a398f37c/node_modules/@actdim/msgmesh/AGENTS.md) <br> [CLAUDE.md](../packages/dashboard-ui/node_modules/.pnpm/@actdim+msgmesh@1.12.2_@act_ada671f90b40be71a7baed66a398f37c/node_modules/@actdim/msgmesh/CLAUDE.md) <br> [llms-full.txt](../packages/dashboard-ui/node_modules/.pnpm/@actdim+msgmesh@1.12.2_@act_ada671f90b40be71a7baed66a398f37c/node_modules/@actdim/msgmesh/llms-full.txt) <br> [llms.txt](../packages/dashboard-ui/node_modules/.pnpm/@actdim+msgmesh@1.12.2_@act_ada671f90b40be71a7baed66a398f37c/node_modules/@actdim/msgmesh/llms.txt) <br> [docs/](../packages/dashboard-ui/node_modules/@actdim/msgmesh/docs) <br> manifest metadata (`ai`) |
| **`@actdim/ui-core`** | `packages/dashboard-ui` | `npm` | `1.12.2` | [AGENTS.md](../packages/dashboard-ui/node_modules/.pnpm/@actdim+ui-core@1.12.2_cf596066e6c8cf207f71129b8d105d17/node_modules/@actdim/ui-core/AGENTS.md) <br> [CLAUDE.md](../packages/dashboard-ui/node_modules/.pnpm/@actdim+ui-core@1.12.2_cf596066e6c8cf207f71129b8d105d17/node_modules/@actdim/ui-core/CLAUDE.md) <br> [llms-full.txt](../packages/dashboard-ui/node_modules/.pnpm/@actdim+ui-core@1.12.2_cf596066e6c8cf207f71129b8d105d17/node_modules/@actdim/ui-core/llms-full.txt) <br> [llms.txt](../packages/dashboard-ui/node_modules/.pnpm/@actdim+ui-core@1.12.2_cf596066e6c8cf207f71129b8d105d17/node_modules/@actdim/ui-core/llms.txt) <br> [docs/](../packages/dashboard-ui/node_modules/@actdim/ui-core/docs) <br> manifest metadata (`ai`) |
| **`@actdim/utico`** | `packages/dashboard-ui` | `npm` | `1.12.2` | [AGENTS.md](../packages/dashboard-ui/node_modules/.pnpm/@actdim+utico@1.12.2_dexie@4.4.5_luxon@3.7.2_uuid@13.0.2/node_modules/@actdim/utico/AGENTS.md) <br> [CLAUDE.md](../packages/dashboard-ui/node_modules/.pnpm/@actdim+utico@1.12.2_dexie@4.4.5_luxon@3.7.2_uuid@13.0.2/node_modules/@actdim/utico/CLAUDE.md) <br> [llms-full.txt](../packages/dashboard-ui/node_modules/.pnpm/@actdim+utico@1.12.2_dexie@4.4.5_luxon@3.7.2_uuid@13.0.2/node_modules/@actdim/utico/llms-full.txt) <br> [llms.txt](../packages/dashboard-ui/node_modules/.pnpm/@actdim+utico@1.12.2_dexie@4.4.5_luxon@3.7.2_uuid@13.0.2/node_modules/@actdim/utico/llms.txt) <br> [docs/](../packages/dashboard-ui/node_modules/@actdim/utico/docs) <br> manifest metadata (`ai`) |
| **`@mui/material`** | `packages/dashboard-ui` | `npm` | `9.5.0` | [docs/](../packages/dashboard-ui/node_modules/@mui/material/docs) |
| **`cytoscape`** | `packages/dashboard-ui` | `npm` | `3.34.2` | [AGENTS.md](../packages/dashboard-ui/node_modules/.pnpm/cytoscape@3.34.2/node_modules/cytoscape/AGENTS.md) |
| **`react-router`** | `packages/dashboard-ui` | `npm` | `7.18.2` | [docs/](../packages/dashboard-ui/node_modules/react-router/docs) |

## Transitive Dependency Guidelines & Invariants

No exported invariants detected across repository dependencies.

## Custom Project Dependency Hooks (`.along/scripts/dep_scan.py`)

While Along natively auto-discovers dependencies across Node.js (`package.json`), Python (`pyproject.toml`, `requirements*.txt`), .NET NuGet (`*.csproj`), Rust (`Cargo.toml`), and Go (`go.mod`), repositories using other ecosystems or internal package managers can supply a custom discovery hook:

- **Hook Path**: `.along/scripts/dep_scan.py` (or `scan_deps.py`).
- **Invocation**: `/along-dep-scan` or `along dep-scan` executes the script passing `--json` with working directory set to the project root.
- **Output Schema**: The script must write a JSON list to stdout:
  ```json
  [
    {
      "package": "custom-package",
      "ecosystem": "hex",
      "version": "1.0.0",
      "files": [
        {
          "filename": "AGENTS.md",
          "path": "deps/custom-package/AGENTS.md"
        }
      ]
    }
  ]
  ```
- **Monorepo Localization**: In multi-package repositories or submodules, subproject-specific hooks placed in `packages/<subproject>/.along/scripts/dep_scan.py` are executed automatically when scanning that subproject.

## Usage in Agent Sessions
When working on features involving any of the modules or external libraries above:
1. **Internal Submodules**: Follow conventions in the nearest `AGENTS.md` or subproject `docs/`.
2. **Third-Party Libraries**: Read the linked instruction files directly for framework-specific patterns and best practices.

---

## Document: docs/topic--domain-model.md (Domain Model & Entity Ecosystem)

# Domain Model & Entity Ecosystem

Along models repository memory, project tracking, and documentation as a strongly-typed, schema-validated **Directed Acyclic Graph (DAG)** of Markdown entities with YAML front-matter (`protocol: along`).

---

## 1. Entity Ecosystem Architecture

The entity ecosystem provides a structured data layer that is simultaneously human-readable in plain Markdown, machine-parsable by local scripts and dashboards, and token-efficient for AI agents:

```mermaid
flowchart TD
    subgraph PlanningAndEpics["Planning & Target Scope"]
        MILESTONE["Milestones (.along/MILESTONES/)"]
    end

    subgraph CoreUnitsOfWork["Core Units of Work"]
        ISSUE["Issues (.along/ISSUES/<type>--<slug>.md), incl. spike and risk-tagged issues"]
        DONE_ISSUE["Completed Issues (.along/ISSUES/done/)"]
    end

    subgraph GovernanceAndQuality["Governance & Architecture"]
        ADR["Decisions / ADRs (.along/DECISIONS/)"]
    end

    subgraph LivingMemory["Living Memory & Journals"]
        SESSION["Session Logs (.along/SESSIONS/<YYYY>/)"]
        HISTORY["History Chronicle (.along/HISTORY.md)"]
        KB["Knowledge Base (docs/topic--*.md)"]
    end

    MILESTONE -->|targets| ISSUE
    ISSUE -->|spike yields| ADR
    ISSUE -->|moves to done/| DONE_ISSUE
    ISSUE -->|advances| SESSION
    ADR -->|governs| ISSUE
    SESSION -->|wrap appends one line| HISTORY
    ISSUE -->|documents in| KB
```

---

## 2. Granular Entity Taxonomy & Schemas

Along defines 6 entity types, each fulfilling a specific role in repository memory and lifecycle management. Risks, spikes and checklists are no longer separate entities: a risk or blocker is an issue tagged `risk`, a spike is a `spike` issue, and the completion checklist lives in `AGENTS.md` and is printed by `along wrap` ([debt--entity-model-slimming]; `along update` converts old `RISKS/`, `SPIKES/` and `CHECKLISTS/` folders through migration Step 16, see [Migrations](./topic--migrations.md)).

### 1. Issues (`.along/ISSUES/<type>--<slug>.md`)
Atomic units of engineering work. Along categorizes issues into **6 types**:

| Issue Type | Purpose & Scope | Example Slug |
| :--- | :--- | :--- |
| **`feat`** | New functional capabilities, user-facing features, API endpoints, or skills. | `feat--jwt-token-refresh` |
| **`bug`** | Defect repairs, regression fixes, edge-case remediation, or error recovery. | `bug--windows-path-escaping` |
| **`debt`** | Technical debt payoff, code refactoring, performance optimization, or dead code elimination. | `debt--dynstruct-migration` |
| **`task`** | Routine chores, infrastructure setup, CI/CD configuration, or dependency updates. | `task--setup-vitest-runner` |
| **`docs`** | Knowledge base authoring, architectural specifications, or developer workflow guides. | `docs--skills-architecture-overhaul` |
| **`spike`** | Timeboxed experiment, benchmark or library evaluation before an architectural commitment. Carries an `## Outcome` section; a concluded spike is closed as `done` and its result usually becomes an ADR (`related:`). | `spike--duckdb-vs-sqlite` |

A **risk or blocker** (rate limit, external dependency, upstream defect) is an ordinary issue, usually `debt`, tagged `risk`, with a `## Mitigation` section; the issue it blocks lists it in `blocked_by`.

#### YAML Front-Matter Schema:
```yaml
---
protocol: along
protocol_version: "3.9.4"
slug: jwt-token-refresh
type: feat
status: in-progress
priority: high
created: 2026-09-01
updated: 2026-09-01
completed: null
agent: antigravity
tags: [auth, security, tokens]
milestone: v2.3.0-security
blocked_by: [feat--db-schema-migrations]
related: [debt--token-revocation-latency]
parent: feat--identity-platform
superseded_by: null
duplicate_of: null
plan_status: approved           # optional: needs-approval | approved | needs-rework
---

# Issue Title

Detailed problem statement, constraints, and verifiable acceptance criteria.

## Acceptance Criteria
- [ ] Implement refresh token rotation endpoint.
- [ ] Add 100% test coverage for expired tokens.
- [ ] Update docs/topic--architecture.md.
```

#### Lifecycle States:
- **`open`**: Backlog item, not currently being executed.
- **`in-progress`**: Actively being developed by an agent or human. Initiated atomically via `along start <slug> [--worktree]`. Non-trivial code edits require an active issue.
- **`blocked`**: Waiting on an external dependency (`blocked_by`), API key, or a `risk`-tagged issue.
- **`done`**: Delivered terminal state. Fully implemented, verified by tests and code review. Closed via `along issue done <slug>` or `/along-wrap`. Mandatory field `completed: YYYY-MM-DD` is set, and the file is moved to `.along/ISSUES/done/<type>--<slug>.md`. Only `done` issues count towards milestone and sprint completion metrics.
- **`superseded`**: Non-delivered terminal state. Replaced by another issue or architectural decision. Closed via `along issue supersede <old-key> --by <new-key>` (rewrites inbound references) or `along issue done <slug> --status superseded --superseded-by <slug>`. Mandatory field `completed: YYYY-MM-DD` is set, `superseded_by: <target-slug>` references the replacement entity, and the file is moved to `.along/ISSUES/done/`.
- **`cancelled`**: Non-delivered terminal state. Abandoned or intentionally dropped requirements. Closed via `along issue done <slug> --status cancelled`. Mandatory field `completed: YYYY-MM-DD` is set, and the file is moved to `.along/ISSUES/done/`.
- **`duplicate`**: Non-delivered terminal state. Redundant issue covered by another entity. Closed via `along issue done <slug> --status duplicate --duplicate-of <slug>`. Mandatory field `completed: YYYY-MM-DD` is set, `duplicate_of: <primary-slug>` references the primary entity, and the file is moved to `.along/ISSUES/done/`.

#### Issue Plan (`.along/ISSUES/<type>--<slug>/plan.md`):
The ticket says what and why; the plan says how. An issue's plan lives in the folder named after its ticket, is committed with it, and moves with it (`along wrap`, `along issue done`, `reopen`, `rename`, `supersede`; `delete` removes it). It is one living file: the approved baseline as `## Revision 1`, then each correction made during the work as the next revision with a `Reason:` line, and `## Rework requested` notes. Session blackboards and `along-team` read and write this file (`session.plan_path`); a blackboard without an issue keeps its own `plan.md`.

`plan_status` in the ticket front-matter records where the plan stands:
- **`needs-approval`**: written, waiting for the user's yes (set by the agent).
- **`approved`**: ready to run. Set only by `along plan approve` after the user's explicit yes, which also appends an approval event to the machine-local `.along/.session/plan-approvals.jsonl`. `along start` and the orchestrator trust `approved` only with such an event on this machine; otherwise they ask the user again. File-tool edits that set `approved` are denied by `require-plan-approval`.
- **`needs-rework`**: the plan cannot be followed within the ticket (`along plan rework <slug> --reason "..."`); the user decides how to proceed.
- absent: no plan yet.

The board (`.along/ISSUES.md`) shows `plan ready`, `plan: needs approval` or `plan: needs rework` after the entry. See `.along/PROTOCOL.md` "Issue Plans & Approving Ahead" for the flow.

#### Quality Gates & Anti-Stub Validation (`validate_issue_completion`):
To prevent empty scaffolding or hallucinated completions from degrading project memory:
- **Mandatory Sections**: Every issue must declare `## Problem`, `## Requirements`, and `## Acceptance Criteria`.
- **Anti-Stub Invariance**: Issues containing template placeholder text (such as `"Describe the feature..."` or `"Task requirement 1"`) or lacking concrete criteria are blocked by `along start` and `along plan approve`.
- **Completion Validation**: Transitioning an issue to `done` (`along wrap` or `along issue done <slug>`) executes `validate_issue_completion`:
  - Refuses issues with unfilled scaffold placeholders;
  - Requires mandatory `## Acceptance Criteria` with at least one completed checklist item (`- [x]`);
  - Requires all checklist items to be checked (`- [x]`); any remaining `- [ ]` checklist item aborts wrap unless explicitly overridden with `--force-reason`.
- **Audit Tooling**: Run `along doctor issues` (or `along doctor --issues`) to audit all `.along/ISSUES/` files for template stubs or uncompleted criteria.

---

### 2. Architectural Decision Records (ADRs) (`.along/DECISIONS/` & Projections)
Dual-layer architecture: modular records in `.along/DECISIONS/ADR-YYYY-MM-DD--<slug>.md` paired with compiled `.along/DECISIONS.md` (compact summary board) and `.along/CONSTRAINTS.md` (active constraints) projections, alongside `docs/decisions/` for MkDocs search and publishing.

#### Why Modular File-Per-ADR with Compiled Projections?
- **Bounded Session-Start Context**: Agents read only active architectural rules in `.along/CONSTRAINTS.md` at session start, keeping session-start reads bounded.
- **Git Branch Isolation**: Storing ADRs in distinct files (`.along/DECISIONS/ADR-YYYY-MM-DD--<slug>.md`) eliminates git merge collisions entirely.
- **Search & MkDocs Integration**: Each ADR is published to `docs/decisions/`, making decisions fully searchable in the static documentation site.
- **Legacy Compatibility**: Repositories using single-file append-only `DECISIONS.md` continue to work seamlessly.

#### Schema & Entry Format:
```markdown
---
title: "Session-Scoped Blackboard Memory"
date: 2026-08-31
status: accepted # or: superseded
superseded_by: <target-slug> # optional
type: decision
slug: session-scoped-blackboard-memory
tags:
  - architecture
  - memory
---

# ADR-2026-08-31--session-scoped-blackboard-memory - Session-Scoped Blackboard Memory

- Date: 2026-08-31
- Status: accepted (or: superseded by ADR-YYYY-MM-DD--<slug>)
- Context: In-flight multi-agent coordination data cluttered conversation context.
- Decision: Introduce .along/.session/<slug>/ with automated GC during /along-wrap.
- Consequences: Eliminates state leakage; guarantees clean repository hygiene.
```

---

### 3. Milestones & Sprints (`.along/MILESTONES/<slug>.md`)
Group multiple issues into structured release targets, sprints, or major project stages.

#### Schema:
```yaml
---
protocol: along
protocol_version: "3.9.4"
slug: v2.3.0-security
title: Security & Authentication Hardening
status: in-progress
due_date: 2026-09-15
created: 2026-09-01
target_issues:
  - feat--jwt-token-refresh
  - bug--auth-header-leak
  - debt--crypto-upgrade
progress_pct: 33
---
```

#### Milestone Synchronization & Progress Engine
Milestones and issues maintain a **bidirectional relationship** orchestrated by `along milestone sync` and `along issue update`:
- **Bidirectional Linkage**:
  - Issues declare their assigned milestone via frontmatter `milestone: <slug>`.
  - Milestones declare their target issues via frontmatter `target_issues: [<type>--<slug>, ...]`.
- **Dynamic Discovery**:
  Running `along milestone sync [<slug>]` scans all issues across `.along/ISSUES/` and `.along/ISSUES/done/`. Any issue declaring `milestone: <slug>` is dynamically aggregated into `target_issues` (sorted alphabetically by canonical key).
- **Progress Calculation**:
  Progress percentage is automatically computed based on terminal issue states:
  $$\text{progress\_pct} = \operatorname{round}\left(\frac{\text{done\_count}}{\text{total\_target\_issues}} \times 100\right)$$
  Where `done_count` includes all issues in `.along/ISSUES/done/` or having a terminal status (`done`, `superseded`, `cancelled`, `duplicate`). If `total_target_issues` is 0, `progress_pct` evaluates to 100 if the milestone is already completed, else 0.
- **Automated Status State Machine**:
  - `total > 0` and `done_count == total`: Milestone status transitions to `completed`.
  - `total > 0` and (`in_progress_count > 0` or `done_count > 0`) with `done_count < total`: Milestone status transitions to `in-progress`.
  - `total > 0` and `done_count == 0` and `in_progress_count == 0`: Milestone status transitions to `open`.
- **Fuzzy Milestone Resolution**:
  Commands accepting milestone identifiers (`along milestone show`, `along issue update --milestone`) support 3 levels of query matching:
  1. *Exact Match*: Exact slug or filename stem (e.g. `v4.0.0-runtime-gates-and-worktree-isolation`).
  2. *Version Prefix Match*: Version query with or without leading `v` (e.g. `4.0`, `v4.0`, `4.0.0` resolve to `v4.0.0-runtime-gates-and-worktree-isolation`).
  3. *Substring Match*: Unambiguous substring in slug or title (e.g. `runtime-gates`).

---

### 4. Work Sessions (`.along/SESSIONS/<YYYY>/<YYYY-MM-DD>--<slug>.md`)
Chronological work journal written by `along wrap` (and `along issue done`, `along scratch purge`, `along session gc`) before the session blackboard is deleted. A log does not repeat git or the plan: it keeps the front matter, the summary, the decisions, and the blackboard record (step table, research, execution trace, notes, reviews). The paths attributed to the issue are kept as the `files:` front matter, which `along session close`, `along start` and `along doctor` read to find uncommitted work of wrapped issues (logs written before v4.6.0 carry an `### Attributed Files` table instead, still read).

#### Schema:
```yaml
---
protocol: along
date: 2026-09-01
slug: skills-architecture-overhaul
agent: antigravity
branch: main
commit: a1b2c3d
summary: Complete overhaul of docs/ Knowledge Base and full 18-skill reference.
milestone: v2.2.0-along
issues_advanced: []
issues_completed:
  - docs--comprehensive-knowledge-base-and-skills-architecture
decisions: []
files:
  - docs/topic--skills-reference.md
  - skills/along-wrap/SKILL.md
---
```

---

### 5. Project History Chronicle (`.along/HISTORY.md`)
Single-line append-only chronological log, one line per slug, written by `along wrap` (and `along history append` / `along session create`, which go through the same writer). It is the one-line record of a completion; the issue body stays in `ISSUES/done/` and the details in the session log:
```markdown
# History

2026-09-01 - skills-architecture-overhaul - antigravity - Rebuild Knowledge Base and 18-skill reference - [Session Log](./SESSIONS/2026/2026-09-01--skills-architecture-overhaul.md)
```

---

### 6. Knowledge Base (`docs/topic--*.md`, `docs/INDEX.md`)
Curated, cross-linked LLM-Wiki articles maintaining domain architecture, API contracts, dependencies, and developer guides.

`.along/VISION.md` and `.along/GLOSSARY.md` complete the context: the repository root gets them on `along init`; a nested context (subproject) creates them on first use.

---

### 7. Cross-Runtime Session Entities (`.along/.session/<slug>/`)
Ephemeral coordination bus enabling disparate vendor runtimes (Claude Code, OpenAI Codex, OpenCode, Antigravity) to execute multi-step workflows without shared memory:

#### 1. Run Records (`.along/.session/<slug>/runs/<run-id>.json`)
Tracks individual agent runtime executions within an issue session:
```json
{
  "run_id": "run-20261023T014500Z-abcd",
  "role": "implementer",
  "runtime": "claude-code",
  "model": "claude-3-7-sonnet",
  "step": 1,
  "start": "2026-10-23T01:45:00Z",
  "end": "2026-10-23T01:48:30Z",
  "exit_code": 0,
  "outcome": "done",
  "changed_files": ["scripts/alongkit/handoff.py"],
  "usage": { "input_tokens": 12000, "output_tokens": 1500 },
  "handoff_note": "handoff.md"
}
```
- **Outcomes**: `done`, `fail`, `needs-input`, `timeout`, `in-progress`.
- **Usage**: Serves as single source of truth for operator cards and observability.
- **Identifiers**: `run_id`, question ids and the slug are single path components (`[A-Za-z0-9][A-Za-z0-9._-]*`, no `..`); anything else is rejected.

#### 2. Machine-Readable Review Verdicts (`reviews/step-N.md`)
Enforces automated gate evaluation via YAML front-matter without brittle prose parsing:
```yaml
---
verdict: fail
defects:
  - severity: blocking
    description: "Missing collision prevention check when acquiring live claim"
    file: "scripts/alongkit/handoff.py"
    line: 215
---

# Step 1 Code Review
Detailed reviewer critique and evaluation against acceptance criteria.
```
- **Severities**: `blocking` (must fix, fails verdict), `important` (should fix, fails verdict), `nit` (informational, passes verdict).
- **Invariance**: Verdict MUST be `fail` when blocking or important defects are present.
- **Fail closed**: the orchestrator passes a step only on a valid `verdict: pass`. A missing review, a missing `verdict`, or a verdict that breaks the invariance (`fail` with only nits, `pass` with a blocking defect) fails the step with a blocking defect, as does an implementer run with outcome `fail` (no review runs).

#### 3. Questions Entity (`.along/.session/<slug>/questions/<id>.md`)
Asynchronous operator clarification mechanism replacing interactive stdin bridges:
```yaml
---
id: q-1
status: answered
question: "Which database backend should be selected for session caching?"
options:
  - "In-memory dict"
  - "SQLite blackboard"
recommended: "In-memory dict"
answer: "In-memory dict"
answered_by: "operator"
created_at: "2026-10-23T01:40:00Z"
answered_at: "2026-10-23T01:42:00Z"
---

Additional context regarding throughput requirements.
```
- When an agent requires human decision, it writes a question, exits with outcome `needs-input`, and awaits operator resolution.

#### 4. Claim Management (`state.json` `claimed_by`)
Prevents concurrency collisions across autonomous runner daemons:
```json
{
  "claimed_by": {
    "run_id": "run-20261023T014500Z-abcd",
    "runtime": "antigravity",
    "claimed_at": "2026-10-23T01:45:00Z",
    "expires_at": "2026-10-23T02:15:00Z"
  }
}
```
- Active claims block secondary runs on the same issue.
- Expired claims (`now >= expires_at`) can be taken over automatically.
- Acquire and release run under `claim.lock` in the session directory (created exclusively; a lock older than 30 s is treated as stale), so two runners never both take the same claim.
- The orchestrator renews its claim before every runner invocation (TTL = run timeout + 300 s), stops with `blocked` when another run holds it, and releases only its own claim.
- `along orchestrate --dry-run` previews phases, runtimes and brief sizes without claiming or changing the blackboard.

#### 5. Handoff Notes & Brief Engine (`handoff.md` & `along brief`)
- **Handoff Note** (`handoff.md`): Compact note (under 25 lines) written at run completion detailing what was done, what remains, and traps.
- **Brief Engine** (`along brief <slug> --role <role>`): Compiles deterministic, compact, size-bounded prompt payload containing issue goal, `REQ-N`, criteria, step plan, constraints, open defects, answered questions, handoff note, git diff stat, and review policies.

---

## 3. Graph Invariance & Canonical Slug Linking

To prevent link breakage and dependency graph drift, Along enforces **Canonical Slug Invariance**:

1. **Canonical Key References**:
   - Entities reference other entities strictly by their canonical key (`<type>--<slug>` or `<slug>`), **NEVER** by filesystem paths (`.along/ISSUES/open/...`).
   - *Example*: `blocked_by: [feat--db-schema]` remains 100% valid when the target file moves from `.along/ISSUES/feat--db-schema.md` to `.along/ISSUES/done/feat--db-schema.md`.
2. **Unidirectional Graph Storage**:
   - In YAML front-matter, relationships are stored unidirectionally (`blocked_by: []`, `related: []`, `parent: <slug>`).
   - Reciprocal relationships (`blocks`, `children`) and full DAG topologies are computed dynamically by graph parsers and the Along dashboard engine, eliminating LLM synchronization drift.
   - Exception for submodule portability (ADR-2026-11-10--children-allowed-for-cross-context-links-only): an umbrella issue in a superproject may declare `children: [<path>:<child-key>]` when the child subproject forbids upward `parent:` links. A link is stored in exactly one direction, never both. Unqualified `children` entries or dual-direction declarations trigger validation warnings.
3. **Cross-Context Resolution**:
   - Reference fields (`parent`, `blocked_by`, `related`, `superseded_by`, `duplicate_of`, `children`) resolve along the chain of enclosing `.along/` contexts up to the outermost one below home, crossing nested `.git` / submodule boundaries (`repo.context_chain`, `entities.ancestor_contexts`); each context is searched in `ISSUES/` and `ISSUES/done/`. A child issue in a submodule can therefore name the workspace umbrella above it.
   - A `parent` equal to the issue's own key (a child sharing the umbrella's key) resolves only in enclosing contexts; otherwise it is the error `invalid self-parent reference`.
   - The qualifier `root:<key>` (e.g. `parent: root:feat--identity-platform`) resolves only in the outermost context. In standalone checkouts without enclosing contexts, `root:<key>` emits a non-blocking warning rather than a dangling error.
   - `along issue sync` prints `<key>: parent <parent> (found in <ctx>)` for each cross-context parent; commit-time snapshot checks add the working-tree keys of contexts above the git top; the dashboard graph shows an external parent as a node with status `external`.

---

## 4. Automated Intent Recognition Heuristics

To ensure zero administrative overhead for developers, Along host agents automatically infer project tracking actions from natural language prompts:

| Natural User Prompt / Trigger | Inferred Entity | Automatic Background Agent Action |
| :--- | :--- | :--- |
| *"Build feature X"*, *"Add endpoint Y"* | **`feat ISSUE`** | Auto-creates `.along/ISSUES/feat--<slug>.md` with `status: in-progress`. Updates `ISSUES.md`. |
| *"Fix bug X"*, *"Fix crash on Y"* | **`bug ISSUE`** | Auto-creates `.along/ISSUES/bug--<slug>.md` with `priority: high`. |
| *"Refactor module X"*, *"Clean up Y"* | **`debt ISSUE`** | Auto-creates `.along/ISSUES/debt--<slug>.md`. |
| *"Update documentation for X"* | **`docs ISSUE`** | Auto-creates `.along/ISSUES/docs--<slug>.md`. |
| *"Rate limit hit"*, *"Blocked on API key"* | **`risk`-tagged ISSUE** | Auto-creates `.along/ISSUES/debt--<slug>.md` tagged `risk` with a `## Mitigation` section; the blocked issue gets `status: blocked` and `blocked_by: [debt--<slug>]`. |
| *"Benchmark X vs Y"*, *"Test if Z works"* | **`spike ISSUE`** | Auto-creates `.along/ISSUES/spike--<slug>.md` (`along issue create spike <slug>`); records the `## Outcome` and the resulting ADR before it is wrapped. |
| *"Target for next sprint"*, *"Release v2.0"* | **`MILESTONE`** | Auto-creates `.along/MILESTONES/<slug>.md`; binds target issues. |
| *"I'm done for today"*, *"Wrap up"* | **`SESSION & WRAP`** | Executes `/along-wrap`: verifies tests, records session log, moves completed issues to `done/`, updates `HISTORY.md`. |

---

## Document: docs/topic--license.md (License)

# License

Along is distributed under the terms of the MIT License.

- Source file: [LICENSE](https://github.com/actdim/along/blob/main/LICENSE)

```text
MIT License

Copyright (c) 2026 actdim

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```

---

## Document: docs/topic--llm-wiki-architecture.md (Topic-Based Knowledge Base Architecture & Paradigm)

# Topic-Based Knowledge Base Architecture & Paradigm

Along implements a **Deterministic Topic-Based Knowledge Architecture**, combining industrial technical communication standards (**IBM DITA**, **Canonical Diataxis**), classical Information Retrieval (**TF-IDF**), and repository-native AI navigation into a single, unified source of truth for software engineering teams.

---

## 1. Why Topic-Based Architecture? (Industrial Reality vs Naive LLM-Wiki)

While Andrej Karpathy popularized the concept of an "LLM-Wiki" for digesting unstructured personal media (papers, podcasts, raw personal notes), directly transplanting that model into software engineering creates severe operational failure modes:

### The Three Failure Modes of Naive LLM-Wiki in Codebases
1. **Stochastic Git Jitter & Broken Code Review**:
   - If documentation is treated as a secondary byproduct periodically recompiled by an LLM, every sync floods Git history with non-deterministic phrasing rewrites and synthetic churn.
   - Pull requests become unreviewable, Git diffs are polluted with noise, and hallucinations silently overwrite verified technical contracts.
2. **The Split-Brain Trap (Two Conflicting Sources of Truth)**:
   - If developers write unstructured "raw notes" while a machine compiles a "secondary wiki", the team maintains two competing realities.
   - If a developer updates a raw note, the wiki is immediately stale. If an agent or engineer updates the wiki, the raw note is stale or direct edits are wiped out on the next rebuild.
3. **Chronic Merge Conflict Hell**:
   - Unstructured or monolithic documentation files guarantee Git merge collisions whenever multiple developers or parallel agents work on different features concurrently.

### The Dual Problem: Prompt Stuffing vs Opaque Vector DBs
AI coding agents face two equally flawed extremes:
- **Context Bloat & Prompt Saturation (Prompt Stuffing)**: Loading multi-kilobyte documentation into agent prompts consumes 10,000 to 30,000+ tokens per interaction, exhausting the context window and degrading model reasoning.
- **Opaque & Fragile External Vector DBs**: Vector databases slice code across arbitrary token boundaries, blur exact symbols into fuzzy semantic vectors, fail during branch switching, and introduce complex native C++ dependencies.

For an exhaustive architectural comparison against vector DBs, passive conversational scrapers (jevmem, Laya), and prompt stuffing, see [System Comparisons & Alternative Memory Architectures](./topic--system-comparisons.md).

### The Solution: Deterministic Topic-Based Architecture
Along synthesizes 25 years of industrial technical writing and 50 years of information retrieval into a production-grade system:
- **Modular Topic Files (`docs/topic--*.md`)**: Single, human-readable source of truth in Git, organized by domain.
- **Zero-Manual-Merge Indexing (`docs/INDEX.md`)**: Catalog and navigation compiled 100% deterministically by lightweight Python scripts without LLM hallucinations.
- **In-Memory Lexical Retrieval (`along-kb-search`)**: Pure standard-library TF-IDF engine returning the single best-matching paragraph (<= 150 words) with its section heading and exact line range, instead of whole files.

---

## 2. Topic-Based Architecture & Data Flow

```mermaid
flowchart TD
    subgraph RawSources["In-Place Sources Layer"]
        RAW["Raw Notes, External Specs, Code Files (wiki/, kb/, scripts/)"]
    end

    subgraph Compiler["Along Native Compiler (along-kb-sync)"]
        INGEST["In-Place Ingestion & Provenance Hasher"]
        LINTER["Link Linting & Graph Validation"]
        INDEXER["INDEX.md Catalog Compiler"]
        LLMS_COMPILER["Deterministic llms.txt & llms-full.txt Generator"]
    end

    subgraph ActiveWiki["Active Curated Knowledge Base (docs/)"]
        TOPICS["docs/topic--*.md (Structured YAML Front-matter & Provenance)"]
        CATALOG["docs/INDEX.md (Dynamic Topic Catalog & Graph)"]
    end

    subgraph Exports["Deterministic LLM Context Exports"]
        LLMS["llms.txt (.well-known/ or root)"]
        LLMS_FULL["llms-full.txt (.well-known/ or root)"]
    end

    subgraph Retrieval["Agent Fast Retrieval (along-kb-search)"]
        SEARCH["Multi-Tier Weighted Search Engine"]
        SNIPPET["Best Paragraph Snippet (<= 150 Words + Line Range)"]
        AGENT["Host AI Agent (Antigravity / Claude / Codex)"]
    end

    RAW --> INGEST
    INGEST --> TOPICS
    TOPICS --> LINTER
    LINTER --> CATALOG
    CATALOG --> LLMS_COMPILER
    TOPICS --> LLMS_COMPILER
    LLMS_COMPILER --> LLMS
    LLMS_COMPILER --> LLMS_FULL
    CATALOG --> SEARCH
    TOPICS --> SEARCH
    SEARCH --> SNIPPET
    SNIPPET --> AGENT
```

---

## 3. Fast Retrieval Mechanics & 50-Year IR Foundations (TF-IDF & Karen Sparck Jones)

Instead of deploying opaque, heavy vector databases or dumping whole articles into prompts, Along grounds its retrieval engine in 50 years of classical Computer Science and Information Retrieval (IR):

### The Classical Lineage of Lexical Retrieval
- **Hans Peter Luhn (IBM, 1957)**: Introduced Term Frequency (TF), measuring the prominence of terms within a passage.
- **Karen Sparck Jones (1972)**: Established Inverse Document Frequency (IDF) in her foundational paper, proving that rare terms across a corpus carry exponentially higher discriminative value.
- **Gerard Salton (Cornell, 1975)**: Unified these concepts into the classic TF-IDF vector space model, powering Lucene, Elasticsearch, and global enterprise search.

### Why Classical TF-IDF Outperforms Vector Databases in Codebases
1. **Exact Code Symbol Precision**:
   - Vector embeddings project distinct identifiers (`user_id`, `user_uuid`, `get_user_account`) into nearby fuzzy clusters, causing ambiguity during code refactoring.
   - TF-IDF enforces exact token and quoted phrase matching, ensuring agents locate the precise function, flag, or configuration key without semantic drift.
2. **Zero Native Dependencies, No Index to Rebuild**:
   - Pure Python standard library implementation: no embeddings, no database, no native builds (no `onnxruntime` or `hnswlib` compilation failures on developer machines).
   - The corpus is read from the working tree on every call, so a branch switch never leaves a stale index behind.
3. **Bounded Snippets**:
   - Search returns one paragraph per hit (<= 150 words) with its section heading and an exact file path and line range (`docs/topic--cli-reference.md#L589-L605`), feeding the [Progressive Disclosure Ladder](#5-progressive-disclosure-ladder).

### Corpus & Query Semantics
- **Corpus**: `docs/` topics, `.along/PROTOCOL.md`, and living memory (issues, ADRs, milestones, sessions); `--category` narrows it. Archived entities (done issues, session logs, superseded ADRs) are excluded unless `-a` / `--archive` is passed. Results default to the top 8 (`--limit`).
- **Tokens**: lowercase word tokens (`[\w\-]+`), so hyphenated and underscored identifiers such as `kb-sync` or slugs stay one token and match only as a whole (or by prefix with `--prefix`).
- **Stemming**: `light_stem` strips English suffixes (`-s`, `-es`, `-ies`, `-ing`, `-ed`). Non-English text is matched by exact tokens only.
- **AND by default**: every query term and quoted phrase must match somewhere in the entry. `--any` switches to OR; `--prefix` lets terms match token prefixes.
- **Quoted phrases**: `"bounded context budget"` must appear as an exact adjacent sequence.
- **Literal mode** (`--literal`): a raw substring match with its own fixed scoring (see below).

### IDF Formula
`compute_idf` counts document frequency over title, slug, tags and body (stems are counted too) and applies smoothed IDF:

```text
IDF(term) = ln((N + 1) / (df + 1)) + 1
```

A term found in 1-2 topics out of hundreds scores several times higher than a term found everywhere. That is why one-topic-per-file matters (see [Authoring Topics for Retrieval](#4-authoring-topics-for-retrieval)).

### Ranking Weights
`search_knowledge_base` adds up the following per entry. Each term scores at most one tier per field (exact > stem > prefix).

| Match Scope | Exact | Stem | Prefix (`--prefix`) | Rationale |
| :--- | :--- | :--- | :--- | :--- |
| **Title** | **+15 x IDF** | +7.5 x IDF | +6 x IDF | Direct match on the article subject. |
| **Slug** | **+12 x IDF** | +6 x IDF | +5 x IDF | Stable architectural identifier. |
| **Tags** | **+10 x IDF** | - | - | Curated keywords; whole-tag exact match only. |
| **Body** | **min(TF x IDF, 25)** | stems add to TF | prefix TF if no exact hit | Frequency is capped so long articles cannot drown short precise ones. |
| **Quoted Phrase** | +30 title / +20 slug / min(15 x count, 30) body | - | - | Exact adjacent sequence. |

| Entry Adjustment | Weight | Rationale |
| :--- | :--- | :--- |
| **Curated docs boost** | **+20** | `docs/topic--*.md` and `.along/PROTOCOL.md` outrank issues and sessions that merely mention the same words. |
| **Active status** | +2 | Open, in-progress, active or accepted entities. |
| **Archived** | -10 | Only when archived entities are included. |

**Literal mode** scores differently: base 100, +50 slug substring, +30 title substring, min(10 x count, 30) body, +20 curated docs, -10 archived.

### Snippet Extraction
`extract_passage_location_and_snippet` splits the matched file into blocks. A block is a paragraph separated by blank lines or headings. Front-matter is skipped and a fenced code block stays whole. Each block is scored (+15 per phrase, +6 per exact term, +3 per stem match); the best block is returned with:
- its enclosing heading (`section`),
- its 1-indexed line range (`file#Lstart-Lend`),
- its text, flattened and capped at **150 words**.

### Measured Performance
`scripts/bench_kb_search.py` measures both the real repository and a synthetic 1,000-entity fixture. Sample run on this repository (Windows, Python 3.12, 2026-11-13):

| Corpus | Load | Query p50 | Query p95 | Snippet vs matched documents |
| :--- | :--- | :--- | :--- | :--- |
| This repository (837 entities, ~0.8M tokens) | ~0.8 s | ~245 ms | ~290 ms | 95-98% fewer tokens |
| Synthetic fixture (1,000 entities) | - | ~158 ms | ~168 ms | ~85% fewer tokens |

- The ADR-2026-09-09 gate is **p95 < 250 ms on the 1,000-entity fixture**.
- Measured against the whole corpus rather than the matched documents, savings exceed 99%. `--stats` prints live corpus size, returned tokens and the savings percentage for any query.

---

## 4. Authoring Topics for Retrieval

Search quality is a property of how topics are written. Every authoring rule below produces a concrete ranking or snippet signal in `along-kb-search`:

| Structure Rule | Search Signal It Produces |
| :--- | :--- |
| **One topic per file (DITA)** | Clean document boundaries. A domain term appears in few files, so its IDF is high and it points at the right topic instead of being diluted across mixed articles. |
| **Specific `title`** | Strongest field: +15 x IDF per exact term. Name the subject in words people search for. |
| **Descriptive `slug`** | +12 x IDF, but only when the query contains the whole slug: hyphens do not split tokens, so `llm-wiki-architecture` is one token (`--prefix` also matches its beginning). Put every searchable word in the title too. |
| **`tags` in front-matter** | +10 x IDF for synonyms and concepts the body may not spell out. Tags match whole: prefer single-word tags (`search`, `idf`) over long multi-word ones. |
| **`##` headings + short paragraphs** | The snippet is one paragraph. Short, single-idea paragraphs under a clear heading return a complete answer with its section and line range. |
| **Exact identifiers in backticks** | Lexical exact match on `kb-sync`, `compute_idf`, flag names. Hyphenated and underscored names are single tokens, so a query for `search` does not hit `kb-search`; spell the plain words out in prose as well. The AST grounding gate also checks identifiers against the code. |
| **English prose** | `light_stem` normalizes plural and tense forms only for English text. |
| **Topic lives in `docs/`** | +20 curated boost over issues and sessions mentioning the same terms. |

### Author Checklist
1. One subject per `docs/topic--<slug>.md`; split when a file starts answering two unrelated questions.
2. Title and slug use the words a reader would type.
3. Add 5-12 single-word tags, including synonyms absent from the body.
4. Keep paragraphs short and self-contained under `##` / `###` headings. A paragraph should make sense when returned alone.
5. Write identifiers exactly as in code, in backticks.
6. Check with `along kb-search "<query>" --stats` that the topic ranks first for its own subject.

---

## 5. Progressive Disclosure Ladder

Humans and agents read the knowledge base the same way. They descend one step at a time and stop as soon as they have enough:

```text
INDEX.md  ->  front-matter  ->  search snippet   ->  surrounding lines  ->  full file
(catalog)     (what it is)      (<= 150 words)       (20-30 lines)          (last resort)
```

1. **`docs/INDEX.md`** (or the compact `along kb-search --toc` catalog): compiled list of topics with titles and tags.
2. **Front-matter**: title, type, tags, provenance sources and write policy tell what a topic covers and how far to trust it.
3. **Snippet**: `along kb-search` returns the best paragraph with `file#Lstart-Lend`.
4. **Surrounding lines**: read 20-30 lines around that range when the paragraph needs context.
5. **Full file**: only when the task really concerns the whole topic.

---

## 6. In-Place Source Grounding, Provenance & Drift Gate

Along enforces in-place provenance for all synthesized Knowledge Base articles:

1. **In-Place Source Preservation**:
   - Raw sources, specifications, and reference notes remain in their original project locations (e.g. `wiki/`, `kb/`, `scripts/`). Files are NEVER moved into a hidden `.archive/` directory.
   - Every compiled article in `docs/topic--*.md` explicitly tracks its originating source files via the `sources: [{path, hash}]` YAML front-matter list.
2. **SHA-256 Drift Detection**:
   - The compiler computes normalized SHA-256 hashes of tracked sources during sync.
   - Running `python scripts/along_kb_sync.py --check` detects if underlying code or raw specifications have evolved, emitting `[DRIFT]` warnings that alert agents to review and reconcile documentation.
3. **Intent Gate for Content Reduction (`--prune-intent`)**:
   - To guard against accidental LLM deletions, `along-kb-sync` calculates net line-count reductions against Git `HEAD`.
   - In monorepos and nested subprojects, path queries use `HEAD:./<rel_path>` to ensure Git resolves paths relative to the subproject working directory rather than the repository root.
   - If an article shrinks by >25% in lines (and at least 10 lines), compilation halts with exit code 2 unless `--prune-intent [REASON]` is explicitly supplied.

---

## 7. Deterministic LLM Context Compilation: llms.txt & llms-full.txt

To provide external LLMs and IDE assistants with immediate context, `along-kb-sync` deterministically manages both index and full-context exports:

1. **Path Resolution & `.well-known/` Support**:
   - Resolves target files using `alongkit.repo.resolve_llm_targets(...)`.
   - Follows web standard precedence:
     - If `.well-known/llms.txt` exists, updates in `.well-known/`.
     - If root `llms.txt` exists, updates in root.
     - If both exist, synchronizes both to prevent drift.
     - If neither exists, creates in `.well-known/` if that directory exists, else defaults to repository root.
2. **Smart Non-Destructive `llms.txt`**:
   - Updates the `## Documentation Links` section to match active `docs/topic--*.md` articles.
   - Non-destructively preserves user-defined custom sections, descriptions, and external HTTP(S) references.
   - On initial creation, extracts project title and introductory summary from `README.md` (identifying the first H1 header and extracting the first valid blockquote or prose paragraph while ignoring GitHub alert callouts like `> [!NOTE]`, badges, and raw HTML).
3. **Pure Script Deterministic `llms-full.txt` Compilation**:
   - Zero LLM generation: compiled 100% deterministically by script.
   - Assembles `README.md`, `AGENTS.md`, and all `docs/topic--*.md` articles in sorted order.
   - Strips YAML front-matter and structures documents with clean Markdown section headers.
4. **Cascading Subproject Synchronization**:
   - Automatically walks downward to discover all subproject Along contexts and synchronizes their local `llms.txt` and `llms-full.txt` files whenever nested documentation exists.

---

## 8. Documentation Blast Radius & Code-Graph-to-Wiki Synchronization

In the LLM-Wiki paradigm, documentation is a living asset that evolves alongside code. Along enforces a **Deterministic 2-Phase Blast Radius Gate**:

```mermaid
flowchart LR
    DIFF["Code Modifications (git diff)"] --> CRG["along graph-impact (code-review-graph AST)"]
    CRG --> IMPACT["Impacted Symbols & Downstream Callers"]
    IMPACT --> SEARCH["along-kb-search (Topic Query)"]
    SEARCH --> TOPICS["Targeted docs/topic--*.md Files"]
    TOPICS --> EDIT["Factual Article Updates"]
    EDIT --> KBSYNC["along-kb-sync --strict (Integrity Gate)"]
    KBSYNC --> INDEX["docs/INDEX.md & Verified Links"]
```

1. **AST Blast Radius Discovery**: During task review, agents invoke `along graph-impact` (powered directly by `code-review-graph` CLI) to trace caller hierarchies, caller depth, and affected execution flows.
2. **Topic Mapping**: Agents query `along-kb-search` with the modified symbol names to pinpoint the exact `docs/topic--*.md` files documenting those interfaces.
3. **Factual Updating**: Agents update the affected topic articles with concrete code facts (zero placeholders).
4. **Compilation & Link Gate**: Running `python scripts/along_kb_sync.py --strict` validates relative links across the repository and recompiles `docs/INDEX.md`.

---

## 9. Deterministic Topic Dictionary, Auto-Crosslinking & AST Symbol Grounding

To guarantee factual precision and cross-reference coherence without human micro-management, Along equips `along-kb-sync` with three deterministic compiler mechanisms:

### Deterministic Topic Dictionary & Auto-Crosslinking
- **TopicDictionary Indexing**: The compiler automatically extracts title, slug, and tag permutations across all `docs/topic--*.md` files. Entries are sorted longest-first to prioritize specific domain aliases (e.g. `LLM-Wiki Architecture` before `Architecture`).
- **Bounded Cross-Link Replacement**:
  - `scan_crosslinks()` and `apply_crosslinks()` audit prose for unlinked concept opportunities.
  - Skips Markdown headings (`#`, `##`), fenced code blocks (` ``` `), inline code spans (`` `...` ``), and existing relative/absolute links.
  - Enforces the **First Occurrence Per Section Rule**: only the first unlinked mention within any H2 section (`## `) is converted to a link (`[Term](./topic--slug.md)`).
  - Self-linking to the current article is strictly excluded.
  - Idempotent: re-running `--crosslink-apply` yields zero modifications.
- **CLI Options**:
  - `along kb-sync --crosslink-check`: Audits documentation for unlinked topic opportunities without modifying files.
  - `along kb-sync --crosslink-apply`: Applies deterministic cross-links in-place.

### AST Code Symbol Grounding Gate
- **AST Symbol Extraction**: Parses Python source files across `scripts/`, `dashboard/`, `tests/`, and `.along/scripts/` using Python's native `ast` module. Discovers classes, functions, async functions, methods, and uppercase module-level constants.
- **Ghost Symbol Detection (`--check-symbols`)**:
  - Inspects backticked spans (`` `symbol` ``) across all `docs/topic--*.md` articles.
  - Identifies identifier signatures (snake_case, PascalCase, UPPER_SNAKE, dotted member accesses) and checks them against the AST symbol inventory.
  - Flags ungrounded "ghost symbols" (non-existent classes, phantom functions, obsolete identifiers) that hallucinate codebase capabilities.
  - Builtin filter whitelists Python keywords, standard library modules/attributes (`sys.path`, `os.remove`), Win32 platform APIs, Dynstruct framework symbols, and code intelligence tools.
  - Exits with non-zero status in strict mode (`--check-symbols --strict`) when ghost symbols exist.

### Structured Section Taxonomy Contracts
- **Standard Article Schemas**: Core documentation types must satisfy required section structures defined in `SECTION_CONTRACTS`:
  - `architecture`: System Topology & Overview, Core Components & Engine Implementation, Data Flow & Execution Workflow, Invariants & Failure Modes.
  - `domain-model`: Entity Taxonomy & Ecosystem, Front-matter Schemas & Metadata, Graph Invariance & Relationships.
  - `setup-workflow`: Prerequisites & Installation, Runner Commands & Lifecycle Scripts, Quality Gates & Verification.
- **Fuzzy Heading & Non-Empty Body Verification**:
  - Matches headings with flexible regex pattern sets (supporting numbered variants such as `## 1. System Topology & Architecture`).
  - Requires each mandatory section to contain substantive documentation lines (preventing empty header stubs).
- **Enforcement**:
  - Automatically audited and logged as `[WARN]` during sync.
  - Strictly enforced via `along kb-sync --strict-sections`, exiting with code 1 on violations.

### Topic Types Taxonomy & Write Policy Protection

Along adopts the industrial **Diataxis technical writing framework** (standardized across Python, Django, and Canonical) paired with **IBM DITA** information typing. This establishes a strict classification to distinguish machine-critical interface contracts from human-centric conceptual models:

| Topic Type | Classification | Validation & Grounding | Write Policy | Typical Scope |
| :--- | :--- | :--- | :--- | :--- |
| **`reference`** | Technical Contract | AST code symbols enforced (`--check-symbols`) | `agent` (default) | CLI commands, APIs, configuration schemas |
| **`architecture`** | System Architecture | Section contracts + AST symbol grounding | `agent` (default) | Topology, core components, invariants |
| **`domain-model`** | Domain Model | Section contracts + AST symbol grounding | `agent` (default) | Entity taxonomies, DAG relationships |
| **`setup-workflow`** | Setup & Workflow | Section contracts + AST symbol grounding | `agent` (default) | Installation, lifecycle scripts, gates |
| **`explanation`** | Concept & Rationale | Exempt from AST symbol grounding | `manual` (optional) | Architectural rationale, market fit, comparisons |
| **`comparison`** | Comparative Analysis | Exempt from AST symbol grounding | `manual` (optional) | Alternative architectures, trade-off matrices |
| **`guide`** | How-To Guide | AST symbol grounding if code references exist | `agent` (default) | Step-by-step procedures, runbooks |
| **`topic`** | General Article | Standard fallback | `agent` (default) | Unclassified domain topics |

#### Write Policy & Manual Lock Gate (`[gate: doc-manual-lock]`)
- **`write_policy: agent`** (default): Living documentation maintained automatically. Agents update these files during code modifications (Doc Blast Radius).
- **`write_policy: manual`** (or `locked: true`): Curated, human-governed content (such as product pitches, executive comparisons, or business rationale).
  - Excluded from automated blast-radius candidate documentation (`along graph-impact`).
  - Exempt from auto-crosslinking mutation during `along kb-sync --crosslink-apply`.
  - Mechanically locked by runtime gate `[gate: doc-manual-lock]`: automated agent file edits are rejected unless an explicit documentation task (`docs--<slug>`) is active.

---

## 10. References & Useful Links

- **DITA (Darwin Information Typing Architecture)**: OASIS standard for modular, topic-based technical authoring developed by IBM (2001).
- **Diataxis Framework (Daniele Procida)**: Architecture for technical documentation used by Python, Django, and Canonical (Tutorials, How-To Guides, Reference, Explanation).
- **Karen Sparck Jones (1972)**: "A Statistical Interpretation of Term Specificity and Its Application in Retrieval", Journal of Documentation.
- **Andrej Karpathy's LLM-Wiki Note**: Conceptual observation of LLM navigation over interlinked Markdown files.
- **`scripts/bench_kb_search.py`**: Reproducible latency and token-savings benchmark for `along-kb-search`.
- **[System Architecture & Flow](./topic--architecture.md)**: System topology, multi-branch concurrency, and multi-agent state machine.
- **[System Comparisons & Alternative Memory Architectures](./topic--system-comparisons.md)**: Comparative analysis against jevmem, Laya, vector databases, and prompt stuffing.
- **[Domain Model & Entity Ecosystem](./topic--domain-model.md)**: Taxonomy of issues, milestones, ADRs, and living memory.
- **[Skills & Slash Commands Reference](./topic--skills-reference.md)**: Technical breakdown of all 18 automation skills.
- **[Setup & Developer Workflow](./topic--setup-and-workflow.md)**: Installation, runner hooks, and day-in-the-life development flow.

---

## Document: docs/topic--migrations.md (Protocol & Repository Migrations Guide)

# Protocol & Repository Migrations Guide

This guide documents the versioned migration pipeline for the `ALONG-PROTOCOL` (`.along/`).

---

## 1. Overview & Execution Engine

The migration engine (`scripts/migrate_protocol.py`) inspects the target repository's
current structure and executes sequential migration steps to bring it up to the latest
standard. It is invoked by `/along-init` and `/along-update`, and by hand:

```bash
python scripts/migrate_protocol.py <target_root> --dry-run   # print the plan, write nothing
python scripts/migrate_protocol.py <target_root> --apply     # perform it
python scripts/migrate_protocol.py <target_root> --apply --force   # ignore the recorded state
```

Installing does not migrate. `install.ps1` / `install.sh` print how to run the engine and
do nothing to the repository unless given `-Migrate` / `--migrate`.

```mermaid
flowchart TD
    A["Legacy Repo (v1.0)"] -->|Step 1: Tasks to Issues| B["v1.1.0 (ISSUES structure)"]
    B -->|Step 2: Scaffolding KB & Graph| C["v1.3.0 (Knowledge Base & Graph)"]
    C -->|Step 3: Entity Ecosystem| D["v1.5.0 (Milestones, Done Issues, Sessions)"]
    D -->|Step 4: Along Directory| E["v2.0.0 (Along Ecosystem & protocol: along)"]
    E -->|Step 7: LLM-Wiki & docs/| F["v2.1.0 (docs/ KB, In-Place Provenance, Domain-First Skills)"]
    F -->|Step 10: Version SSOT Cleanup| G["v3.0.0 (Version SSOT & KB Schema Decoupling)"]
```

---

## 2. What the Engine Is Allowed To Do

The engine used to move legacy content by deleting whatever occupied the destination
(`os.remove(dst)` followed by `shutil.move`). A repository holding both a legacy
`.agents/` and an already-started `.along/` - a partial migration, or two branches
migrating separately - therefore lost the newer `DECISIONS.md` and `HISTORY.md`, which
are append-only by protocol and so irrecoverable. Four rules now hold, each with a
behavioral test in `tests/test_migration.py`:

1. **A destination file is never deleted.** What happens on a collision depends on the
   file class, and every outcome keeps both bodies:

   | Destination | Policy | Result |
   | :--- | :--- | :--- |
   | `DECISIONS.md`, `HISTORY.md` | Union merge | Entries the legacy copy has and the destination lacks are appended, deduplicated. This is what `.gitattributes` already does across branches (`merge=union`). |
   | `ISSUES.md`, `INDEX.md`, `DASHBOARD.md`, `dashboard.html` | Keep destination | Derived projections carry nothing their sources do not. The legacy copy is dropped; recompile with `/along-issue-sync` or `/along-kb-sync`. |
   | Entity files, anything else | Keep destination | The legacy copy is preserved as `<name>.legacy.md` beside it and reported as a resolved collision. |

2. **Dry run is the default for anything but a human at a terminal.** A caller that is
   not attached to a TTY gets the plan and a notice; mutation requires `--apply`. The two
   ways this engine used to run - from the installer and from the test suite - were both
   invocations nobody had asked for.
3. **A backup precedes the first change.** `.along/` and `.agents/` are copied to
   `.along/.migration-backup/<timestamp>/` before anything is modified, and the path is
   printed. The backup directory ignores itself via its own `.gitignore`, so it never
   reaches history and never edits the user's. Machine-local state (`diagnostics/`,
   `.session/`, `artifacts/`, `worktrees/`) is not copied, and only the newest 5 snapshots
   are kept (`migration.BACKUP_SKIP`, `migration.BACKUP_KEEP`). Rule-pack backups
   (`along rules restore`, `rules attach` on conflict) land in the same self-ignoring directory.
4. **Undecodable files are skipped and reported.** Markdown was read with
   `errors="ignore"` and written back, which deleted every byte that was not valid UTF-8.
   Reads are strict; a file that fails to decode is listed in the report and left alone.

`.along/.protocol-version` records the version the repository was last migrated to, so a
second run reports `already at v<version>; nothing to do` instead of re-executing eight
steps whose idempotency held only by accident. `--force` overrides it.

Every operation is recorded, so both modes end with the same report: the operations
grouped by kind, the collisions and how each was resolved, the skipped files, and the
backup path. All of it is implemented once, in `scripts/alongkit/migration.py`; a test
fails if the engine calls `shutil.move`, `os.remove` or their neighbours directly.

---

## 3. Version Migration Steps

### `v1.0.0` -> `v1.1.0`: Tasks to Issues
- Renames `TASKS.md` -> `ISSUES.md` and `TASKS/` -> `ISSUES/`.
- Enforces kebab-case `<type>--<slug>.md` naming for all issue files.

### `v1.1.0` -> `v1.3.0`: Knowledge Base & Code Graph
- Scaffolds initial Knowledge Base (`INDEX.md`, `topic--architecture.md`, `topic--domain-model.md`, `topic--setup-and-workflow.md`).
- Creates `.code-review-graph-ignore` with standard excludes (`node_modules/`, `dist/`, `build/`, `SESSIONS/`).

### `v1.3.0` -> `v1.5.0`: Entity Ecosystem & Retro-Synthesis
- Scaffolds `.along/MILESTONES/`, `.along/ISSUES/done/` and `.along/SESSIONS/<YYYY>/` (risk, spike and checklist folders are no longer created; see Step 16).
- Retroactively synthesizes completed milestones from Git history and session logs.
- Sanitizes non-ASCII typography (replacing em-dashes with standard ASCII hyphens).

### `v1.5.0` -> `v2.0.0`: Along Rebranding & Isolated `.along/`
- Migrates `.agents/` to `.along/` and updates `protocol: along` YAML front-matter across all entities.
- Validates entity relationships (`blocked_by`, `related`, `parent`) and verifies zero DAG cycles.

### `v2.0.0` -> `v2.1.0`: LLM-Wiki Architecture & Singular Domain-First Skills
- Migrates active Knowledge Base articles from `.along/KB/` to top-level `docs/`.
- Preserves raw, unmanaged source notes in-place with SHA-256 provenance tracking.
- Standardizes all 3-part skills to Singular Domain-First format (`along-<entity>-<action>`).
- Enforces mandatory `along-kb-search` agent querying rule to minimize token usage.

### `v2.2.27` -> `v3.0.0`: Version SSOT Cleanup & KB Schema Decoupling (Step 10)
- Strips legacy hardcoded `protocol_version` declarations from `docs/*.md` (`topic--*.md` and `INDEX.md`) front-matter while preserving mandatory `protocol: along` marker.
- Strips ` [vX.Y.Z]` title suffixes from local `skills/*/SKILL.md` manifests.
- Decouples documentation sync from version bump churn, preventing spurious diffs and hash invalidation across releases.

### `v4.4.3` -> `v4.4.4`: One VISION per Context (Step 13)
- A folder's own root `VISION.md` is reconciled into `.along/VISION.md` and deleted (copy kept in `.along/.migration-backup/<timestamp>/root/`):
  - `.along/VISION.md` missing or an empty skeleton (only headings, italic lines, comments) -> content moved;
  - same content -> root copy removed;
  - both with content -> root content appended inside `<!-- along:imported-vision needs-restructure ... -->` ... `<!-- /along:imported-vision -->`, which the agent decomposes (scope / non-goals / roadmap stay; architecture -> `docs/topic--architecture.md`; backlog -> issues and milestones) and `along doctor` reports until it is gone.
- Links to the root file are repointed: from `README.md` and `docs/` to `docs/INDEX.md` (stable entry point), from `.along/` files to `.along/VISION.md`. Relative links inside the moved text are rebased.
- Root notes (`ROADMAP.md`, `ARCHITECTURE.md`, `SPEC.md`, `TODO.md`, `DESIGN.md`) are listed as agent actions, never moved.
- Runs as a standalone pass on a repository already at the current version, so a root `VISION.md` added later is still healed without re-running the version chain.
- `VISION.md` files in subfolders are never touched: they belong to their subproject.

### `v4.4.5`: Per-Machine Diagnostics Leave the Index (Step 14)
- Files under any `.along/diagnostics/` (hook audit, activity traces, heartbeat, a leftover `circuit_breaker.json` from before the breaker was removed) that were committed before the directory ignored itself are removed from the git index with `git rm --cached`; the files stay on disk and the removal is staged for the next commit.
- Runs on every migration, including an up-to-date repository; a second run finds nothing, outside git it does nothing, `--dry-run` only lists the paths.
- From then on the `untracked_exports` gate rejects staging them again, and `along doctor` reports any that remain.

### `v4.5.1`: Retired Gate Artifacts (Step 15)
- The circuit breaker and the tool-nature classifier were removed in `debt--gate-simplification`; nothing reads what they left. `.along/diagnostics/circuit_breaker.json`, `.along/diagnostics/syntax_churn.json` and `.along/tool_rules.yaml` are deleted after a backup to `.along/.migration-backup/`.
- A top-level `tools:` section in `.along/rules/gates.yaml` is ignored by the gate loader. Since the file is repository-owned, the step only reports it (`[WARN]`, recorded as `review`); remove it by hand.
- The live activity traces (`.along/diagnostics/activity_trace.json`, `.along/diagnostics/activity/`) stay.
- Runs on every migration, including an up-to-date repository (as a heal pass); a second run finds nothing, `--dry-run` only lists the paths.

### `v4.5.1`: Entity Model Slimming (Step 16)
- The separate risk, spike and checklist entities were removed in `debt--entity-model-slimming`; `step_slim_entity_model` converts what `.along/RISKS/`, `.along/SPIKES/` and `.along/CHECKLISTS/` still hold:
  - a risk becomes a `debt--<slug>` issue tagged `risk` (severity -> priority, mitigation -> `## Mitigation`); a resolved or mitigated risk is closed as `done` in `ISSUES/done/`;
  - a spike becomes a `spike--<slug>` issue (hypothesis and outcome -> sections, `resulting_adr` -> `related`); a concluded spike is closed as `done`;
  - front-matter references are rewritten (`risk--x` or a bare risk slug -> `debt--x`);
  - the scaffolded `pre-commit.md` and `stage-completion.md` are discarded after a backup (the completion checklist lives in `AGENTS.md` / `.along/PROTOCOL.md` and is printed by `along wrap`); any other checklist moves to `docs/topic--<slug>.md`.
- The emptied folders are removed. A collision is kept and reported, every removal is backed up to `.along/.migration-backup/`.
- Runs on every migration, including an up-to-date repository (as a heal pass), so `along update` applies it; a second run finds nothing, `--dry-run` only lists the operations.

---

## Document: docs/topic--multi-runtime-orchestration.md (Multi-Runtime Orchestration, Named Profiles & OpenObserve Observability)

# Multi-Runtime Orchestration, Named Profiles & OpenObserve Observability

## 1. Overview and Problem Statement

Engineering tasks vary widely in complexity. A single-file bugfix or typo correction does not warrant multi-agent decomposition, while complex refactorings benefit from specialized models (such as an advanced model for architecture and planning, a cost-efficient or local code model for step implementation, and an independent model for code review).

To prevent operational overhead and excessive token consumption, Along separates task execution into configurable **Orchestration Profiles**. These profiles govern which agent runtime harnesses (Claude Code, OpenAI Codex, OpenCode, Google Antigravity) execute each phase, while streaming real-time OpenTelemetry (OTel) traces to an analytical backend such as **OpenObserve**.

---

## 2. Core Components & Engine Implementation

Along provides a decoupled engine architecture for multi-runtime task execution:

### 2.1 Orchestration Modes

Along supports three distinct operational modes:

1. **`direct` (Single-Agent Fast-Path)**:
   - A single agent runtime handles the entire task in one continuous session.
   - Skips dedicated Scout and Reviewer subagent phases.
   - Ideal for S-size tasks (1-2 files), documentation updates, and straightforward fixes.

2. **`team-native` (In-Harness Sequential Roles)**:
   - Execution is divided into deterministic roles (`scout`, `architect`, `implementer`, `reviewer`).
   - All roles run within a single provider harness (for example, native Antigravity subagents or Claude Code `Task` tools, falling back to a single-agent Ralph loop when subagents are unavailable).
   - Suitable for M-size tasks requiring structured planning and review without cross-runtime switching.

3. **`cross-runtime` (Heterogeneous Multi-CLI Orchestration)**:
   - Supervised by `CrossRuntimeOrchestrator`.
   - Each role is dispatched to a dedicated CLI process and model configuration (for example, Claude Code for planning, OpenCode for coding, Codex or Antigravity for review).
   - Artifacts and state are synchronized via the repository session blackboard (`.along/.session/<slug>/`).
   - Designed for L/XL tasks and specialized enterprise or air-gapped environments.

### 2.2 Named Profiles Configuration & Schema

Profiles are defined as declarative YAML documents stored in `.along/orchestration/<name>.yaml`. Shorthand configs can also reside directly in `along.yaml` or `.along/config.yaml`.

```yaml
name: "cross-tiered"
description: "Tiered multi-agent execution with Claude planner and OpenCode worker"
mode: "cross-runtime" # direct | team-native | cross-runtime
workspace: "inherit"  # inherit | worktree
timeout: 1800         # global timeout in seconds

roles:
  scout:
    runtime: "claude-code"
    model: "claude-3-7-sonnet"
    timeout: 600
    args: ["--permission-mode", "headless"]
    env:
      ANTHROPIC_API_KEY: "${ANTHROPIC_API_KEY}"

  architect:
    runtime: "claude-code"
    model: "claude-3-7-sonnet"
    timeout: 900

  implementer:
    runtime: "opencode"
    model: "qwen2.5-coder:32b"
    timeout: 1800
    args: ["--variant", "code"]
    env:
      OPENAI_BASE_URL: "http://localhost:11434/v1"
      OPENAI_API_KEY: "ollama"

  reviewer:
    runtime: "codex"
    model: "o3-mini"
    timeout: 600
```

For a simple single-agent profile (`.along/orchestration/direct.yaml`):

```yaml
name: "direct"
description: "Default single-agent fast path"
mode: "direct"
workspace: "inherit"
runner:
  runtime: "claude-code"
  model: "claude-3-7-sonnet"
  timeout: 1200
```

---

## 3. Data Flow & Execution Workflows

### 3.1 Parameter Resolution Cascade

Orchestration parameters resolve in strict order of precedence:

1. **CLI Overrides (Highest Precedence)**:
   Flags passed directly to `along orchestrate <slug>`:
   ```bash
   along orchestrate <slug> --profile cross-tiered --model "claude-3-7-sonnet" --timeout 2400
   ```
2. **Issue Front-Matter**:
   Specified in `.along/ISSUES/<slug>.md`:
   ```yaml
   ---
   slug: core-compiler-refactor
   orchestration: cross-tiered
   ---
   ```
3. **Repository Profiles Directory**:
   Matching `.along/orchestration/<name>.yaml` file.
4. **Repository Default Configuration**:
   Default profile specified in `along.yaml` or `.along/config.yaml`:
   ```yaml
   orchestration: "direct"
   ```
5. **Built-in Fallback (Lowest Precedence)**:
   In-memory `direct` mode using the currently active agent runtime.

### 3.2 Phased Execution Lifecycle

The execution lifecycle coordinates across isolated subprocesses:

1. **Phase 1: Scout (Research)**: Generates `research.md` containing symbols, dependencies, and blast radius.
2. **Phase 2: Architect (Living Plan)**: Creates `plan.md` with numbered steps (`Step 1`, `Step 2`). Requires human or automated plan approval before mutating code.
3. **Phase 3 & 4: Step Implementation & Review Loop**:
   - `Implementer` executes Step N, updates code, and records touched files.
   - `Reviewer` audits git diff, executes automated tests, and issues a verdict (`PASS` / `FAIL`).
   - On `PASS`, advances to Step N+1. On `FAIL`, increments retry counter and feeds defects back into the prompt.
4. **Phase 5: Wrap & Closeout**: Reconciles history, synchronizes knowledge base projections, and creates release commit.

---

## 4. Invariants, Security Boundaries & Failure Modes

1. **Fail-Open Telemetry Invariant**:
   Network failures, timeouts, or unreachable OpenObserve instances MUST NOT halt or crash orchestrator execution. Failed span batches are safely appended to local disk WAL files (`.along/.session/<slug>/telemetry/spool.wal`).
2. **Single-Run Concurrency Claim**:
   Only one supervisor run may hold an active lock on an issue at any given time. Process claims are recorded in `state.json` with bounded TTL margins (`CLAIM_TTL_MARGIN_SECONDS = 300`).
3. **Plan Approval Guard**:
   Source code mutation is strictly locked until a living plan is verified and approved (`[gate: require-plan-approval]`).
4. **Workspace Isolation**:
   When configured with `workspace: worktree`, work is executed in an isolated git worktree branch linked with directory junctions for `node_modules` and `.venv`, protecting the parent working tree.


---

## 5. OpenObserve Telemetry Integration

During orchestration, `CrossRuntimeOrchestrator` instruments every execution phase with standard OpenTelemetry traces sent over OTLP/HTTP to OpenObserve.

### 5.1 Telemetry Configuration

Telemetry settings can be set in `along.yaml`, `.along/config.yaml`, or via standard OpenTelemetry environment variables:

```yaml
telemetry:
  endpoint: "http://localhost:5080/api/default/v1/traces"
  headers:
    Authorization: "Basic YWRtaW5AZXhhbXBsZS5jb206UGFzc3dvcmQxMjM="
  service_name: "actdim-along"
  timeout: 3.0
```

Environment variables supported:
- `OTEL_EXPORTER_OTLP_ENDPOINT`: Full traces endpoint URL (e.g. `http://localhost:5080/api/default/v1/traces`).
- `OTEL_EXPORTER_OTLP_HEADERS`: Comma-separated or key-value headers (e.g. `Authorization=Basic YWRtaW46cGFzc3dvcmQ=`).
- `OTEL_SERVICE_NAME`: Logical service identifier (defaults to `actdim-along`).

### 5.2 Span Hierarchy and Semantic Conventions

Every orchestration run generates a structured trace hierarchy:

- **Root Span**: `along.orchestrator.run`
  - Attributes:
    - `along.issue.slug`: Target issue slug.
    - `along.orchestration.profile`: Profile name (e.g. `cross-tiered`).
    - `along.orchestration.mode`: Execution mode (`direct`, `team-native`, `cross-runtime`).
    - `along.run.id`: Unique orchestrator execution identifier.
    - `along.workspace.mode`: `inherit` or `worktree`.

- **Phase Spans (Child Spans)**:
  - `phase.scout`: Execution of the research/scout role.
  - `phase.architect`: Generation and validation of `plan.md`.
  - `phase.step.<N>`: Implementation of step N by the designated worker.
    - Attributes: `runner.runtime`, `runner.model`, `step.number`, `process.exit_code`.
  - `phase.reviewer.<N>`: Audit of step N against reviewer rubrics.
    - Attributes: `reviewer.verdict` (`PASS` | `FAIL`), `reviewer.retries`.

### 5.3 Fail-Open Disk Spooling

Telemetry is strictly non-blocking and fail-open:
- If the OpenObserve server is offline, returns an HTTP error, or times out, spans are spooled to local disk in `.along/.session/<slug>/telemetry/spool.wal`.
- Telemetry network failures never cause orchestrator execution or test suites to fail.

---

## 6. Strategic Positioning: Quality Governance vs Process Multiplexers

When evaluating AI multi-agent orchestration for production engineering, it is crucial to distinguish between two fundamentally different layers of the software stack: **Infrastructure Process Multiplexers** and **Engineering Governance Protocols**.

### 6.1 The Limits of Pure Process Multiplexing (T3 Code, Herdr, BB IDE)

Recent desktop applications such as T3 Code, Herdr, and BB IDE function primarily as **Host Runtime Multiplexers and Terminal Switchboards**:
- **What they solve:** They manage OS-level processes, PTY sessions, WebSockets, desktop tabs, and git worktree directories, allowing a developer to run multiple terminal CLI sessions (Claude Code, Codex, Cursor) side-by-side.
- **Where they stop:** To a process multiplexer, the AI coding agent is an uninspected black box. The runner captures `stdout`, detects whether the process is idle or busy, and waits for exit code 0. It has no understanding of repository architectural invariants, test regressions, negative constraints, or whether the agent fabricated its verification claims.
- **The failure mode in real projects:** Running 5 uncoordinated agents in separate terminal windows without an engineering protocol rapidly produces merge conflicts, architectural drift, instruction decay, and unverified commits.

### 6.2 The Along Protocol Advantage: Deterministic Engineering Control

Along operates at the **Repository, Protocol, and Living Memory Layer**:
- **Living State Machine:** Tasks progress through deterministic, auditable roles: Supervisor -> Scout (read-only research) -> Architect (living plan) -> Implementer (step execution) -> Reviewer (rubric verification) -> Reassess (retry control) -> Wrap.
- **Quality Gates:** Code edits unlock only after explicit plan approval (`[gate: require-plan-approval]`); commits are strictly bound to issue slugs (`[gate: commit-issue-binding]`); and sessions cannot close without passing tests (`[gate: test_before_stop]`).
- **Unified Observability via OpenObserve:** Rather than parsing raw terminal streams, Along streams structured OpenTelemetry and OpenInference traces directly into OpenObserve, exposing exact step durations, token costs, runner exit codes, and failure events across all heterogeneous CLIs.
- **Git-Committed Memory:** State is not trapped in ephemeral application databases or local caches. Architectural decisions (ADRs), issue history, session logs, and living plans are committed directly to Git, surviving machine migrations and team handoffs.

### 6.3 Layered Symbiosis

Along does not compete with process multiplexers; it complements them:

```text
+-------------------------------------------------------------+
| User Interface & Terminal Layer (T3 Code, Herdr, Ghostty)   |
| (Manages PTYs, windows, notifications, remote access)       |
+-------------------------------------------------------------+
                              |
                              v
+-------------------------------------------------------------+
| Along Engineering Protocol Layer (along-team, alongkit)     |
| (Living Plan, Quality Gates, ADRs, Blast Radius, Blackboard)|
+-------------------------------------------------------------+
                              |
                              v
+-------------------------------------------------------------+
| Heterogeneous Agent Runtimes (Claude, Codex, OpenCode, AGY) |
| (Code generation, reasoning, tool execution)                |
+-------------------------------------------------------------+
                              |
                              v
+-------------------------------------------------------------+
| Observability Layer (OpenObserve / OTLP)                    |
| (Real-time traces, span metrics, error events, audit logs)  |
+-------------------------------------------------------------+
```

An agent running inside Herdr, T3 Code, or a cloud VPS runner that adopts the Along protocol transforms from an unconstrained terminal process into a disciplined senior engineer that plans before modifying code, verifies every step against automated rubrics, and emits transparent telemetry.

### 6.4 Comparative Evaluation Matrix

| Capability / Invariant | Host Process Multiplexers (T3 Code, Herdr, BB IDE) | ActDim Along Protocol |
| :--- | :--- | :--- |
| **Primary Scope** | OS-level PTY/terminal multiplexing, process supervisor, and desktop GUI | Repository-level engineering protocol, living memory, and quality gates |
| **Verification & Review** | None (relies on model self-reporting and exit code 0) | Independent Reviewer role with deterministic pass/fail rubrics and retry limits |
| **Living Plan & Approval** | None (unstructured conversational chat) | Formal `plan.md` state machine with mandatory human/supervisor approval gate |
| **Observability Standard** | Ephemeral terminal logs and UI websocket events | Standard OpenTelemetry (OTel) traces streamed to OpenObserve |
| **Project Memory Persistence** | Local SQLite, app-specific thread caches, or lost on exit | Versioned repository artifacts (`.along/ISSUES/`, `DECISIONS/`, `HISTORY.md`) |
| **Multi-Model Heterogeneity** | Can launch multiple CLI tools concurrently | Can orchestrate specific roles across different CLIs with shared blackboard |
| **CI/CD & Headless Portability**| Requires desktop GUI or running Node/Electron daemon | Zero daemon requirement; runs in pure CLI, CI/CD, or containers |

---

## Document: docs/topic--parallel-sessions.md (Parallel Sessions & Closeout Guide)

# Parallel Sessions & Closeout Guide

How several agent sessions work on several issues in one working tree, and how the user closes
the finished ones in one step: "close all sessions". Working on one isolated issue at a time is
never required. The record kept for each issue is described in
[Session Lifecycle](./topic--session-lifecycle.md); commands are in the
[CLI Reference](./topic--cli-reference.md).

## 1. Working in parallel

- Each agent session binds itself to its issue with `along start <slug>`; parallel sessions keep
  their own bindings (`along session bindings`).
- Sessions may touch the same files. Avoiding that is the user's concern; Along records who
  touched what.
- Every edit made with the agent's file tools is attributed to the issue the session is bound to:
  one record in that issue's event ledger (`.along/.session/<slug>/events.jsonl`) with the path,
  its kind (`source`, `docs`, `state`) and the session. Test runs (`along test`, the wrap and commit
  test gates) are recorded with their result.
- A session that is not bound to an issue attributes nothing: its edits show up as unattributed
  changes.
- Changes made by shell commands (`sed`, code generators, `git mv`) are not seen by the hooks and
  are unattributed too. Make edits with the file tools, or commit such changes yourself.

## 2. Is it finished?

```bash
along session list
along session list --json
```

For every issue in progress, every bound issue and every blackboard it shows:

| Field | Meaning |
| --- | --- |
| sessions | bound sessions and the time of their last recorded event |
| files | attributed files: exclusive, or shared with which other issues; how many are still uncommitted |
| tests | the last test run and its result, compared with the last edit |
| criteria | acceptance criteria ticked / total (`## Acceptance Criteria` of the issue) |
| plan | whether the approved plan was recorded |
| verdict | `ready`, or `blocked` with the reasons |

An issue is `blocked` when its plan was never recorded, no test ran after its last edit, the last
run failed, criteria are unticked, its blackboard or issue is missing, or its ledger could not be
written. For the repository it lists unattributed changes, staged files, a merge or rebase in
progress and conflict markers.

Uncommitted files left behind by issues that were previously wrapped are grouped separately by their
done issue key (with commit and closeout commands suggested in `along session list` and `along doctor`),
rather than being mixed into generic unattributed changes.

`along session list` cannot know whether a parallel agent is still typing: the last-event time of
each session is shown, and the user decides.

## 3. Closing out

1. Show the user `along session list` (or `along session close --ready --dry-run`, which prints
   the commit plan and writes nothing).
2. After the user's explicit yes, record the approval in the session that will close out (a fresh
   session works too):

   ```bash
   along plan approve --closeout --ready
   ```

   or name the issues: `along plan approve --closeout alpha beta`.
3. Close out:

   ```bash
   along session close --ready --push
   ```

What `along session close` does:

1. Refuses during a merge, rebase, cherry-pick or revert, with conflicts, with files already
   staged, or without the approval for every issue it would close.
2. Plans the commits from the attribution, before anything changes.
3. Runs the test suite once. If it fails, nothing is wrapped or committed.
4. Wraps each issue: the blackboard goes into the session log (its attributed files into the
   `files:` front matter), the
   issue moves to `done/`, `HISTORY.md` gets a line.
5. Commits by attribution, each commit through `along commit` with its gates:
   - files attributed to one issue: one commit for that issue, with its issue file and session log;
   - files attributed to several closed issues: one combined commit with all their refs;
   - projections (`ISSUES.md`, `HISTORY.md`, KB indexes and what the wraps' KB sync rewrote): last.
6. With `--push`, pushes once at the end.

The test gate of each commit reuses the closeout's green run: the wraps change only Along state
and documentation. A source change made while the closeout runs makes the commits run the tests
again.

Never committed: unattributed changes, and files that are also attributed to an issue that is not
being closed now (held back until that issue closes). Issues that are not ready are listed with
their blockers and left untouched.

Done issues with uncommitted attributed files: `along session close <done-slug>` can also be invoked
directly for an issue that was already wrapped. It reconstructs the attributed file list from the
issue's session log (the `files:` front matter, or the `### Attributed Files` table of a log
written before that list existed) and commits those files cleanly without re-wrapping.

## 4. When something fails

- The run is saved in `.along/.session/.closeout.json`. Fix the cause and run
  `along session close` again: wrapped issues are not wrapped twice, finished commits are skipped.
- A closed issue that needs more work: `along issue reopen <slug>`, then `along start <slug>`.
- `along doctor` reports stale bindings, issues in progress that no session is bound to, and
  orphan blackboards.

## 5. Limits

- Attribution lives on the machine where the work was done (blackboard ledger) and, after the
  wrap, in the committed session log. A closeout on another machine sees only what was archived.
- The closeout approval lapses after 72 hours, like a session binding.

---

## Document: docs/topic--requirement-format.md (Controlled Natural Language (STE-Inspired) Requirement Format)

# Controlled Natural Language (STE-Inspired) Requirement Format

A pragmatic guide to writing unambiguous, testable specifications for human and agent workflows in Along repositories.

---

## 1. Background & Purpose

In multi-agent and cross-runtime workflows, requirements written by an architect model (such as a high-reasoning model) are handed off to cheaper implementer models and verified by automated reviewers.

When requirements contain vague wording, polite conditionals, or multiple actions per bullet, implementer models guess implementation details. This introduces defects and leads to repeated review rejection loops.

Along adopts principles inspired by Simplified Technical English (ASD-STE100) and Controlled Natural Language (CNL) as a **writing convention and handoff contract**, not as a brittle runtime gate.

---

## 2. The REQ-N Specification Pattern

Every requirement in an issue or implementation plan MUST follow the standardized atomic pattern:

```text
[Subject] + MUST | MUST NOT + [one verifiable action] + [object] + [condition]
```

### Core Rules

1. **One Observable Action**: Each requirement specifies exactly one verifiable, testable action. If an action has multiple parts, split it into separate requirements (`REQ-1`, `REQ-2`).
2. **Strict Imperative Keywords**: Use standard RFC 2119 imperatives: `MUST` for mandatory actions and `MUST NOT` for strict prohibitions.
3. **Explicit Condition**: State the triggering condition, input state, or boundary clearly (e.g., `when X occurs`, `if Y is omitted`, `under condition Z`).
4. **Verifiable Outcome**: State outcomes that can be confirmed through unit tests, exit codes, file states, or schema validators.

---

## 3. Banned Vague Terms

To prevent ambiguity, requirements MUST NOT include subjective qualifiers or open-ended phrasing.

| Banned Term | Why It Is Prohibited | Verifiable Alternative |
| :--- | :--- | :--- |
| `should`, `could`, `might` | Creates ambiguous obligation; implementer models may skip it. | Use `MUST` or `MUST NOT`. |
| `preferably` | Makes compliance optional without clear fallback rules. | State the exact required behavior or explicit fallback. |
| `appropriate`, `suitable` | Subjective judgment that automated tests cannot evaluate. | Specify exact status codes, types, or schemas. |
| `various`, `several` | Indeterminate quantity; impossible to know when scope is complete. | Enumerate items or state an explicit count/range. |
| `as needed`, `if possible` | Leaves scope decisions to the implementer model. | Define the exact condition when the action occurs. |
| `etc.`, `and so on` | Open-ended placeholder concealing unspecified requirements. | Explicitly list all required elements. |
| `fast`, `performant` | Unbounded performance claim without a metric. | Specify latency thresholds (e.g., `< 50ms at p99`). |

---

## 4. Good and Bad Specification Examples

### Example 1: Input Validation

- **Bad**:
  > `The system should preferably validate user registration input appropriately.`
  - *Flaws*: Uses `should`, `preferably`, and `appropriately`. Does not define which inputs, what validation rules apply, or what happens when validation fails.
- **Good**:
  > `The registration endpoint MUST return HTTP 400 with error code INVALID_EMAIL when the email address does not contain an @ character.`
  - *Why it works*: Explicit subject (`The registration endpoint`), keyword (`MUST`), single action (`return HTTP 400`), object (`error code INVALID_EMAIL`), and measurable condition (`when email lacks @`).

### Example 2: Caching Behavior

- **Bad**:
  > `Implement various caching mechanisms as needed for fast dashboard loading.`
  - *Flaws*: Uses `various`, `as needed`, and `fast`. Implementer must guess which cache backend, TTL, and cache key strategy to use.
- **Good**:
  > `The dashboard service MUST cache user project summaries in Redis for 300 seconds when the tenant has read-only access.`
  - *Why it works*: Identifies exact data (`user project summaries`), backend (`Redis`), duration (`300 seconds`), and trigger condition (`read-only access`).

### Example 3: CLI Error Handling

- **Bad**:
  > `The CLI could show helpful error messages etc. when things fail.`
  - *Flaws*: Uses `could`, `helpful`, `etc.`, and vague `when things fail`.
- **Good**:
  > `The CLI runner MUST write the subprocess exit code and stderr to standard error when a child process exits with non-zero code.`
  - *Why it works*: Names the exact output streams (`standard error`), content (`exit code and stderr`), and precise failure trigger (`child process non-zero exit`).

---

## 5. Convention vs Runtime Gate

Along purposefully treats STE-CNL as a **writing convention**, not as a runtime gate:

1. **No Brittle Linters**: Passive-voice detectors and regex word counters suffer from high false-positive rates on natural prose. Along does not block commits or builds on natural prose variations.
2. **Verbatim Handoff**: In cross-runtime handoffs (`feat--cross-runtime-handoff-entities`), tools like `along brief` forward the `## Requirements` section verbatim from architect to implementer and reviewer.
3. **Review Evaluation**: The reviewer role audits whether the diff satisfies `REQ-N` using test assertions and explicit rubric checks rather than checking grammar ASTs.

---

## Document: docs/topic--runtime-hooks-and-gates.md (Runtime Lifecycle Hooks & Mechanical Gates)

# Runtime Lifecycle Hooks & Mechanical Gates

## 1. System Topology & Overview

Passive prose instructions in `AGENTS.md` and `skills/*/SKILL.md` decay as agent conversation transcripts expand. When context windows fill, probabilistic LLMs cut corners, emit forbidden non-ASCII typography (em-dashes, curly quotes, guillemets), write heredocs over shell tools, or attempt to terminate turns prematurely without executing tests.

The Along Runtime Hook and Gate System establishes deterministic, programmatic interception at the agent harness boundary. Rather than relying on fragile in-process monkey-patching or invasive Git-level hooks (`.git/hooks/*`), Along hooks directly into host agent runtime lifecycle events (`PreToolUse`, `PostToolUse`, `Stop`) supported natively by Google Antigravity, Claude Code, and OpenAI Codex.

```text
+-------------------------------------------------------------------------+
|                         Agent Runtime Harness                           |
|       Google Antigravity (.agents/hooks.json)                           |
|       Claude Code (.claude/settings.json)                               |
|       OpenAI Codex (.codex/hooks.json)                                  |
+-------------------------------------------------------------------------+
                                   |
                         stdin (JSON / protojson)
                                   v
+-------------------------------------------------------------------------+
|                  Universal Dispatcher: scripts/along_hook.py            |
|                  --runtime <name> --event <event_type>                  |
+-------------------------------------------------------------------------+
                                   |
                                   v
+-------------------------------------------------------------------------+
|                       alongkit.hooks Pipeline                           |
|                                                                         |
|  1. Configuration & Governance (alongkit.hooks.config):                 |
|     - Modes: enforce vs shadow                                          |
|     - Audit Log: .along/diagnostics/hooks_audit.jsonl                   |
|                                                                         |
|  2. Stateless Content & Command Gates (alongkit.hooks.gates):           |
|     - TypographyGate: blocks non-ASCII typography (table in typography) |
|     - ProjectionProtectionGate: blocks manual edits to ISSUES.md/INDEX  |
|     - CliSafetyGate: warns on heredocs, inline writers, global installs |
|                                                                         |
|  3. Runtime Adapters (alongkit.hooks.adapters):                         |
|     - AntigravityAdapter: JSON { decision: "deny" | "allow" }          |
|     - ClaudeCodeAdapter: exit code 0 (allow) / 2 (deny + stderr)        |
|     - CodexAdapter: exit code 0 (allow) / 2 (deny + stderr)             |
+-------------------------------------------------------------------------+
```

---

## 2. Core Components & Engine Implementation

### 2.1 Canonical Event Models (`alongkit.hooks.models`)
- `HookEventType`: Enumerates `PreToolUse`, `PostToolUse`, `PreInvocation`, `PostInvocation`, `Stop`, and `UserPromptSubmit`.
- `HookEvent`: Carries normalized event data (`tool_name`, `tool_args`, `workspace_root`, `conversation_id`, `step_idx`).
- `GateDecision`: Categorizes decisions into `allow`, `deny`, `ask`, and `force_ask`.
- `GateResult`: Carries the final decision, remediation message, gate identifier, and optional argument overwrites.

### 2.2 Gate Implementations (`alongkit.hooks.gates`)
1. **`TypographyGate`** (`typography`):
   - Runs at commit only (`enforcement: [git, ci]`: pre-commit, CI and `along lint`); there is no runtime hook on file writes.
   - Uses `alongkit.typography.findings()` to scan text payloads.
   - Forbids em-dashes (U+2014), en-dashes (U+2013), math minus (U+2212), curly quotes (U+201C, U+201D), guillemets (U+00AB, U+00BB), ellipsis glyphs (U+2026), and non-breaking spaces (U+00A0, U+202F, U+200B).
   - Exempts localized resource directories (`locales/`, `i18n/`, `translations/`).
   - Returns exact 1-based line numbers and character descriptions in remediation messages.
2. **`ProjectionProtectionGate`**:
   - Intercepts file mutation tools.
   - Prevents direct manual writes to compiled projection views (`.along/ISSUES.md`, `docs/INDEX.md`).
   - Instructs agents to mutate atomic files (`.along/ISSUES/<type>--<slug>.md`) and run compiler sync commands.
3. **`CliSafetyGate`**:
   - Intercepts command execution tools (`run_command`, `execute_command`, `bash`).
   - Scans command strings for heredocs (`<<EOF`), inline Python file writers (`python -c "open('...', 'w')"`) and unauthorized global package managers (`npm install -g`). It is a warning in every profile (`cli_safety`); `git reset --hard` and `git clean -f` belong to `destructive_command` (see 2.11).
   - The echo/printf file-writer rule (`alongkit.hooks.shellwrite`) is quote-aware: it flags only `echo` / `printf` / `Write-Output ... > file`, `>> file`, `1> file`, `&> file` and `echo ... | tee file`. `2>/dev/null`, `>/dev/null`, `2>&1`, `&>/dev/null`, `>&2`, other pipes and a `>` inside quotes pass.
4. **`DocRoutingComplianceGate`** (`doc_routing_compliance`):
   - Intercepts file mutation tools (`write_to_file`, `replace_file_content`, etc.).
   - Enforces the Along Documentation Routing Tree: `README.md` must remain a high-level overview.
   - Forbids deep code fences (>50 lines) and oversized coding convention or technical reference sections (>50 lines) directly in `README.md`.
   - Forbids `AGENTS.md` from referencing `README.md` as the conventions source of truth instead of `docs/topic--<slug>.md` or `docs/INDEX.md`.
   - Enforced across runtime hooks, git `pre-commit`, `--ci`, `along kb sync`, and `along doctor`.

### 2.3 Declarative Extension & Traceability Matrix
Beyond hardcoded Python gates, Along provides an extensible, declarative YAML gate catalogue (`default_gates.yaml` and `.along/rules/gates.yaml`) enforcing 33 canonical gates, 11 of them git/CI-only commit-time checks (typography, anti-stub, AI co-author trailers, code fences, links, entry point, filenames, exports, issue lifecycle, session records, secrets; run on demand by `along lint`). Runtime gates include `require_plan_approval` (file-tool target path before the write, `git status` at turn end), `destructive_command`, `worktree_env_readiness` and `workspace_containment`, which keeps file, search and shell-cwd paths inside the workspace; see [Declarative Gates](./topic--declarative-gates-and-traceability.md). The catalogue is verified bi-directionally against prose badges (`[gate: <id>]`) via `along hook verify`.
For full specification and architecture, see [Declarative Gate Engine & Traceability Matrix](./topic--declarative-gates-and-traceability.md).


### 2.4 Runtime Adapters (`alongkit.hooks.adapters`)
- **`AntigravityAdapter`**: Translates Google Antigravity JSON payloads (`toolCall.name`, `toolCall.args`) to `HookEvent`, returning JSON stdout with `allow`/`deny` decisions.
- **`ClaudeCodeAdapter`**: Translates Anthropic Claude Code payloads to `HookEvent`, mapping `Write` to `write_to_file`, `Edit`/`MultiEdit`/`NotebookEdit` to `replace_file_content`, `Bash`/`PowerShell` to `run_command`, and `Read`/`Grep`/`Glob` to the read tools; `session_id` becomes the event's session id. Responses: exit 0 for allow; exit 2 with the remediation on `stderr` for a denial; exit 0 with `hookSpecificOutput.permissionDecision: "ask"` for an ASK (the user decides); on `Stop` with `stop_hook_active: true` a denial is reported once as a `systemMessage` instead of forcing another continuation.
- **Claude Code hook schema**: `along hook install --runtime claude [--global]` writes the nested schema Claude Code reads, `{"matcher": ..., "hooks": [{"type": "command", "command": ..., "timeout": 30}]}`, for `PreToolUse` (`Write|Edit|MultiEdit|NotebookEdit|Bash|PowerShell|Read|Grep|Glob`), `PostToolUse` (edits and `ExitPlanMode`), `Stop` and `UserPromptSubmit` (no matcher; records the time of the user's last message, see 2.8). Legacy flat `{matcher, command}` entries, which Claude Code ignores, are migrated in place; foreign hooks are kept.
- **`CodexAdapter`**: Translates OpenAI Codex CLI and headless harness JSON payloads to HookEvent, mapping write_file/create_file to write_to_file, edit_file/patch to replace_file_content, and shell/bash/exec to run_command. Formats exit code 0 for allow, and exit code 2 with the remediation message written to stderr for gate denials.
- **`GenericCliAdapter`**: Translates generic CLI tool invocations, terminal proxy wrappers, Cursor (`.cursor/hooks.json`), and OpenCode to `HookEvent`. Normalizes arguments across tool types, supports plain command strings as fallback `run_command`, and formats exit code 0 for allow or exit code 2 with stderr remediation message for gate denials.

### 2.5 Execution Pipeline & Dispatcher (`alongkit.hooks.engine` & `scripts/along_hook.py`)
- `HookEngine`: Evaluates incoming events sequentially against all registered gates (both built-in and declarative).
- `along_hook.py`: Universal CLI driver handling process I/O, error recovery, adapter dispatch, and `verify` audit.
- **Activation** (`alongkit.hookpreflight`, stdlib only, before the dependency bootstrap): the gates apply only inside an Along context. A context is an Along installation (`repo.is_installed`): a `.along/` holding Along state (`repo.STATE_ENTRIES`: `ISSUES`, `HISTORY.md`, `DECISIONS`, `.protocol-version`, ...; an empty `.along/` or one with only what Along writes on its own - `diagnostics/`, `scripts/`, `artifacts/`, `.session/`, `.migration-backup/` - is not), a legacy `.agents/` with Along entities, or a declared root. A bare `AGENTS.md` does not activate anything: it is a tool-agnostic convention and, in a subfolder, a folder guide. Outside a context the hook allows and exits without loading dependencies; `Read`/`Grep`/`Glob` inside the root and outside `docs/` and the state directory are answered the same way. Progress notes of the bootstrap are suppressed in hooks, since hook stderr lands in every tool result.
- **Declared roots** (`repo.declared_root`): a directory whose Along state lives elsewhere, for example a nested personal repository, declares it with `<!-- along-root: .local -->` in its `AGENTS.md`, or without touching shared files in `~/.along/config.json`:

  ```json
  { "context_roots": [ { "workspace": "D:/work/product/src", "root": ".local" } ] }
  ```

  State then resolves to `<root>/.along/` (`repo.state_dir`), while gates keep evaluating paths against the declaring directory; paths inside the state directory are matched as `.along/...`.
- Subcommand `along hook install`: Scaffolds runtime hook configurations (`.agents/hooks.json` for Antigravity, `.claude/settings.json` for Claude Code, `.codex/hooks.json` for OpenAI Codex, `plugins/along-gates.js` for OpenCode, `.cursor/hooks.json` for Cursor). Accepts `--runtime {antigravity,claude,codex,cursor,opencode,all}`. Also turns off AI commit attribution where the runtime documents a key for it (see 2.7).
- Subcommand `along run <cmd...>` (and `along_hook.py run <cmd...>`): Command proxy wrapper evaluating `run_command` through `HookEngine` prior to execution. Provides mechanical gate enforcement in environments without native PreToolUse lifecycle hooks (CI and external terminals).
- Subcommand `along hook verify`: Audits bi-directional traceability between prose badges and YAML gates.

### 2.6 End-of-Turn Result Check (`alongkit.hooks.turnstate`)
Gates do not predict harm from command text: whether a shell command writes is not decidable before it runs (`debt--gate-simplification`). `require_plan_approval` (catalogue `event: [PreToolUse, Stop]`) judges facts instead:
- **Before a file-writing tool** (`PreToolUse`): the target path. It holds a write to a repository file that is not a planning or session artifact while no plan is approved. Shell commands are never checked before they run. Compiled projections (such as `.along/ISSUES.md`, `.along/DECISIONS.md`, `docs/INDEX.md`, or package-level indexes like `packages/<pkg>/docs/INDEX.md` carrying `protocol: along` and `type: index`) are not plan-governed (`closeout.is_compiled_projection`).
- **Baseline** (`UserPromptSubmit`): `turnstate.snapshot` records `git status --porcelain -uall` plus content hashes of the dirty files as `turn_baseline` in the session activity trace.
- **At turn end** (`Stop`): `turnstate.changed_since` compares the working tree with the baseline. Paths the turn changed outside Along state (`.along/**`, except `.along/scripts/**`), compiled projections, and planning artifacts, with no approved plan, hold the turn once: `PLAN_REQUIRED [gate: require-plan-approval]: this turn changed <files> ... Ask the user: approve (...) or revert (...)`. The Stop check filters mutations by session-attributed writes (`turn_writes` from file tools or pending shell diff snapshots), ensuring changes from external tools or concurrent sessions are not falsely attributed to the active turn. Files already dirty before the turn and unchanged are not attributed to it.
- **One continuation**: Claude Code's `stop_hook_active` keeps the hold to a single continuation. Antigravity still gets ASK for file-tool holds.
- **Commits** (`along commit`, `git commit`) are not held by this gate.
- **Process hangs** are handled by runner timeouts; there is no circuit breaker and Stop gates do not wait on one.

### 2.7 Commit Attribution Policy (`alongkit.attribution`)
Agent runtimes append `Co-Authored-By:` trailers naming themselves (for example `Claude ... <noreply@anthropic.com>`). GitHub resolves the trailer email to an account and lists the vendor as a repository contributor; undoing it later needs a history rewrite and a force-push. The `commit_no_ai_coauthor` gate (`enforcement: [git, ci]`) and the attribution settings keep the trailers out in three layers:

| Layer | Where | What it does |
| :--- | :--- | :--- |
| Runtime config | `along hook install --runtime claude` | Sets `attribution.commit = ""` and legacy `includeCoAuthoredBy = false` in `settings.json`; other keys are kept. |
| Runtime config | `along hook install --runtime cursor --global` | Sets `attribution.attributeCommitsToAgent = false` in `~/.cursor/cli-config.json`. |
| Reconcile | `along hook attribution [--runtime claude\|cursor\|all]`, `install.ps1` / `install.sh`, every `/along-update` run | `reconcile_attribution` writes only the attribution keys above, only for runtime homes that already exist, even when the install is up to date. `--no-hooks` skips it in `/along-update`. |
| Gate | `commit_no_ai_coauthor` (`predicates.check_ai_coauthor`) | Rejects a commit whose message carries an AI co-author trailer, at commit time (commit-msg hook, CI, `along lint`). Human co-authors pass. |
| Commit engine | `/along-commit` | Strips AI co-author trailers from the message before committing. |

Codex and Antigravity document no attribution key; for them the gate and `/along-commit` are the only layers. Opt out per repository with `.along/config.json`:

```json
{ "commits": { "allow_ai_coauthor": true } }
```

### 2.8 Agent-Session Binding & Plan Approval (`alongkit.session`)
Several agent sessions may work in one repository at once, so gates never read a repository-wide "active issue". Each session is bound to one issue:

- **Binding**: `along start <slug>` writes `.along/.session/bindings/<runtime>--<session_id>.json` (`slug`, `context`, `plan_approved`, `approved_slug`). The session id comes from the hook payload (`session_id`, antigravity conversation id) and, for CLI calls, from `CLAUDE_CODE_SESSION_ID`, `ANTIGRAVITY_CONVERSATION_ID`, `CODEX_SESSION_ID` or `ALONG_SESSION_ID` (+ `ALONG_SESSION_RUNTIME`). Bindings live in the outermost `.along/` of the workspace (up to the git top, never `~/.along`); `context` names the `.along/` the issue belongs to, so a session bound to a subproject issue is visible at the root.
- **Resolution** (`session.resolve_active_session`): `ALONG_ISSUE_SLUG` (runner) > own binding > the single in-progress blackboard not bound to another session > none. Several unbound candidates are `ambiguous`: gates refuse and point at `along start <slug>`. A single candidate names the issue, but its blackboard's `plan_approved` counts only for the session bound to it (or a runner's `ALONG_ISSUE_SLUG`): an unbound session with a known id never inherits the approval of a blackboard whose session ended. Runtimes that pass no session id keep it.
- **Plan approval**: `along start` binds with `phase: planning`, `plan_approved: false`. Approval is recorded per session when the user accepts a plan in Claude Code (`PostToolUse` on `ExitPlanMode`; the plan text from `tool_input.plan` is written into the blackboard `plan.md`, or kept as `pending_plan` in the binding until the first `along start`), or by `along plan approve [<slug>] [--plan-file <path>]` after the user's explicit yes, which is refused while `plan.md` is still the scaffold (`session.is_scaffold_plan`); an approval given before `along start` carries over to the first bound slug, and an `ExitPlanMode` approval carries over to a newly started slug until the user's next message (the plan is recorded under the new slug). `along start --approved` is for scripted runs.
- **Issue plans approved ahead** ([feat--pre-approved-plans], ADR-2026-10-23--issue-plans-approved-ahead): an issue's plan is `.along/ISSUES/<key>/plan.md` (`session.plan_path`; a plan written into an issue's blackboard `plan.md` is moved there on first use). Every CLI or `ExitPlanMode` approval of a slug with a ticket also sets the ticket's `plan_status: approved` (`session.approve_issue_plan`) and appends `{slug, event: approve, at, via, session}` to `.along/.session/plan-approvals.jsonl`; `along plan rework` appends `event: rework`. `along plan approve <slug>` before `along start` does only that (no blackboard). `along start` binds approved when `session.issue_plan_state` is `ready` (status `approved` and the log's last event for the slug an approval). The plan gate denies file-tool writes to the log (`APPROVAL_RECORD_PATTERNS`) and file-tool edits of a ticket that add `plan_status: approved` (`_sets_plan_approved`), and at Stop reports tickets the turn changed that say `approved` with no logged approval (`_unlogged_plan_approvals`).
- **User reply check** (`session.record_user_prompt`, `session.check_cli_approval`): the Claude Code `UserPromptSubmit` hook records the time of the user's last message in `.along/.session/prompts/<key>.json` (it does not bind the session). CLI approvals (`along plan approve`, `along start --approved`, `along scratch approve|phase --approve|update --approve`) are refused when the plan file changed after that message ("plan changed after the user's last message; show it and wait for a reply"); with no recorded message they pass as `approved_via: cli-unverified`. Bindings record `approved_via` (`exit-plan-mode` | `cli` | `cli-unverified`), `approved_at` and `plan_sha256`. The denial hint reads: "Call EnterPlanMode, write the plan, then ExitPlanMode. If plan mode is unavailable, show the plan in chat and wait for the user's reply; run 'along plan approve' only after that reply."
- **What the plan gate holds** (see 2.6): file-tool writes to repository files before approval, and at turn end the files the turn changed according to `git status`. Shell commands are never classified before they run. File-tool writes to `.along/ISSUES|SESSIONS|.session|diagnostics` (spike issues included), compiled projections (`closeout.is_compiled_projection`), and planning artifacts (`implementation_plan.md`, `walkthrough.md`, `living_plan.md`) pass, and the end-of-turn check ignores Along state under `.along/` (except `.along/scripts/`), so an issue can be written and started before a plan exists.
- **Unbound sessions**: `require_plan_approval` and `test_before_stop` hold only sessions bound to an issue (`along start`, or `ALONG_ISSUE_SLUG` from a runner). A repository that wants unbound sessions held too sets `enforce_unbound: true` for those gates in `.along/rules/gates.yaml` (this repository does). `require_active_issue` is unaffected: source edits still need an in-progress issue.
- **Completion tokens**: `along wrap` purges the blackboard and every binding of the wrapped slug. The wrapping session, if its plan for that slug was approved, keeps a token in its binding (`completed: [{slug, approved_at, wrapped_at}]`; `slug` and approval cleared). The token is ignored after 72 h (by `wrapped_at`), survives `along start <other>`, and leaves with the binding (`along session gc`). `along scratch purge` leaves no token. Tokens and closeout approvals serve `along session close` and the `wrapped_work_uncommitted` warning; commits are not held by `require_plan_approval`.
- **Shell parsing** (`alongkit.hooks.shellparse`): only `split_segments()` and `words()` remain, used to find the explicit forms of `destructive_command` (2.11) and entity deletions (`entity_deletion_protection`). Command substitutions become the placeholder word `SUBST`. There is no read-only or verification classification, so tests and builds run in every phase without a special case.
- **Session root**: the hook evaluates against the session's project, not the agent's current shell cwd (which follows `cd`). With Claude Code, `CLAUDE_PROJECT_DIR` anchors the root whenever the cwd lies inside it (`repo.find_session_root`), so session bindings and containment survive a `cd` into a nested `.along/` context.
- **Entity reference integrity**: the Stop predicate runs only after an entity file changed and blocks only problems absent at `HEAD` (`gitgates.baseline_entity_problems` validates a `git archive` snapshot of every `.along/` entity dir); problems already committed are left to `along doctor --entities`. Schema findings on archived issues (`.along/ISSUES/done/`: enums, dates, slug, dangling milestone) are warnings marked `(archived issue)`, so an older archive never fails `along update` or `issue sync`; dangling issue references stay errors there too. `along doctor --fix` is not read-only for the plan gate. References resolve upward (enclosing contexts up to the outermost one below home, crossing nested git / submodule boundaries; the snapshot check adds the working-tree keys of contexts above the git top, `gitgates.outer_context_keys`) and downward (nested subproject contexts, `entities.descendant_entity_keys`) and sideways (sibling contexts of the same git repository, `entities.sibling_entity_keys`).
- **Repository-level `.along/.session/state.json`** is read only for runtimes that pass no session id; `purge` removes it when it points at the purged slug.
- **Housekeeping**: `along plan status`, `along session bindings`, `along session gc [--dry-run]` (bindings older than 72 h or without a blackboard; unbound blackboards of closed issues are archived into the session log and removed, those of missing issues only reported). `along scratch purge` / `along wrap` remove the slug's bindings (`along wrap` keeps the wrapping session's completion token).
- **Activity trace** (`test_before_stop`): per session in `.along/diagnostics/activity/<key>.json`; edits under `.along/` are not source edits, and documentation edits (Markdown anywhere, anything under a `docs/`) count only when the gate sets `count_docs: true` (this repository does, since its suite tests Markdown). Under `count_docs: true`, doc-only edits can be satisfied by a scoped run of Markdown-facing tests (`along test --doc` or `python .along/scripts/test.py --doc`, running declared `doc_tests: [...]` from `.along/rules/gates.yaml`) rather than the full suite. Built-in test-inert paths (`.vscode/**`, `.idea/**`, `*.code-workspace`, `.editorconfig`, `.claude/**`, `.codex/**`, `.cursor/**`) and patterns declared under `ignore_paths` in `.along/rules/gates.yaml` update neither edit timestamp and never arm `test_before_stop`. On turn completion rejection, the Stop gate message lists up to 5 modified source files. The activity trace tracks `last_doc_test_time` separately from `last_test_time`. Only what the gates let through is recorded: an edit on `PostToolUse` (the tool succeeded), a test run on `PreToolUse` after every gate allowed it, so changes made outside the session or writes a gate rejected never count. Full test runs reset `edited_files`. Where `.along/scripts/test.py` exists only `along test` / that script count as a test run; raw runners are named in the Stop message. The same trace holds `turn_baseline` (2.6).
- **Execution trace** (`session.trace_event`): the bound issue's `.along/.session/<slug>/execution_trace.md` records, in direct and role-based mode, every repository edit (`PostToolUse`, except `.along/.session/**` and diagnostics; repeated edits of a path collapse to `(xN)`), enforced gate denials (`engine.py` -> `predicates.record_gate_denial`), plan recorded / approved, phase, step and retry changes (`session.update_state`), and test runs with their result from `along test` and the wrap / commit test gate (`gates.run_repository_tests`). Raw runners are not traced (no Bash `PostToolUse`). Unbound sessions write nothing; the trace keeps the newest 400 entries. See [Session Lifecycle](./topic--session-lifecycle.md).
- **Session event ledger** (ADR-2026-10-05--session-event-ledger-feeds-telemetry): the same capture points append one versioned record `{schema, ts, session, slug, kind, path, path_kind, ok}` (`kind`: edit, test, plan, approve, deny, resolve, ack; `path_kind`: source, docs, state; `path` relative to the workspace root; gate-denial records add `id`, `gate`, `tool`, `target`, `reason`, `procedural`, `via`, `note`) to `.along/.session/<slug>/events.jsonl` (`session.record_event`, append only, at most 2000 events per issue, oldest edits dropped first). It is the source of truth for attribution and closeout readiness (`alongkit.closeout`); the session log keeps the attributed paths as the front-matter list `files:` (older logs carry a `### Attributed Files` table, still read). A failed append is reported on stderr and counted in `.along/diagnostics/ledger_errors.json`, which blocks that issue's closeout. With a runner Tracer, the PostToolUse span event carries the same record (`along.session.key`, `along.event.*`, `along.issue.slug`; fail-open).
- **Gate denials** (`unresolved_gate_denial`, [feat--anti-silent-fallback-gate]): an enforced denial of a bound session's tool call (PreToolUse; Stop denials hold the turn by themselves) is a `deny` ledger event with a short id, recorded once per gate and target while open (`predicates.record_gate_denial`); the session's activity trace keeps `open_denials` with a digest of the raw target. Stop denials (such as `require-plan-approval` at `Stop`) are also recorded in the session activity trace with deterministic IDs (`predicates.stop_denials`) and can be listed or acknowledged via `along gates ack <id>` even after session unbinding or wrap. It is settled by an allowed retry on the same target (`resolve`, via retry: a write once it succeeded on PostToolUse, any other tool on Pre- or PostToolUse), by a later `approve` event when the catalogue marks the gate `denial: procedural` (`require_plan_approval`, `require_active_issue`), or disclosed by `along gates ack` (`ack`, counted once the user replied after it, as for bypasses). The Stop gate holds a turn with open denials raised since the user's last message (strict/standard block, light warn); `session.denial_blockers` adds the closeout reasons that `along session status/close`, `along wrap` and `along issue done` (delivered statuses) refuse on, passable only with `--force-reason` under the bypass rules. Unsettled denials are listed in the session log under "Disclosed Gate Denials".
- **Test reuse & baseline** (`alongkit.testruns`): every test run is recorded with the tree hash of the working tree (`git write-tree` through a throwaway index; `.along/` except `.along/scripts/`, KB projections, `__pycache__`, and test-inert paths left out) in `.along/diagnostics/test_runs.json`. The Stop gate (`test_before_stop`) as well as `along wrap`, `along commit` and `along bump` reuse the last run on the same tree when it was green (`testruns.green_run_for(repo_root, tree_hash)`), allowing clean or reverted trees to pass immediately without re-running tests. Failing test runs output a `[Baseline]` diagnostic indicating whether the suite already failed at `HEAD` (pre-existing defect: report to user and file an issue, do not fix under the active task, bypass with agreement) or passed at `HEAD` (regressions introduced by the working-tree changes). `along bump` records a green run for the post-bump tree so `along wrap` can reuse it. `along test` always runs.
- **Diagnostics** (`hooks_audit.jsonl`, activity traces, `hook_heartbeat.json`) are machine-local: `.along/diagnostics/` carries its own `*` `.gitignore`. They go to the resolved state directory (`repo.diagnostics_dir`); without one they go to `~/.along/diagnostics/workspaces/<path>/`. The hooks never create a `.along/` of their own.

### 2.9 along-team Step Discipline & Wrap Record
- `along scratch init` creates a `role-based` blackboard (`--mode direct` opts out); `along start` creates a `direct` one. `[gate: team-step-active]` denies source edits in a role-based session while no step is `in-progress`; `[gate: team-reviews-before-stop]` blocks the turn end while a `passed` step lacks `reviews/step-N.md`.
- `along scratch purge` and `along wrap` refuse while role-based steps are open or reviews are missing; `--force --reason` / `--force-reason` records why in `execution_trace.md`. `along scratch fallback <slug> --reason` switches to single-agent execution with the reason in the trace.
- `along wrap` requires `--decisions ADR-...` or `--no-decisions`, writes (or extends) today's session log with `issues_completed: [<type>--<slug>]`, the decisions answer, the attributed paths as `files:` and the blackboard record (step table, research, trace, notes, reviews; the plan is not copied: an issue's plan stays committed in `.along/ISSUES/<key>/plan.md`, moved to `done/` with the ticket, and the record names it), and purges the blackboard only after its transaction committed. It refuses a blackboard whose `plan.md` is the scaffold unless `--force-reason`.
- One archive path (`lifecycle.write_session_record`, `lifecycle.archive_and_purge`) serves `along wrap`, `along scratch purge`, `along issue done` and `along session gc`: no blackboard is deleted without its record; scaffold placeholders are not rendered; a forced purge's reason goes into the record; a second record on the same day is appended as `## Blackboard Record (<n>, <ts>)`.
- `wrap_before_stop` (Stop): every issue closed as `done` today (local date) must be in `issues_completed` of a session log of today. `along doctor` warns about orphan blackboards (no binding, issue closed or missing), stale bindings and issues in progress with no session bound.
- `session_record_append_only` (git, ci; `gitgates.check_session_records`, also run by `along commit`): a change never removes or rewrites lines inside a `## Blackboard Record` section of a committed session log; the Summary stays editable.

### 2.10 Stop Gates, Subproject Boundary & Gate Tiers
- **`projection_sync_before_stop`** (`predicates.check_projection_sync_before_stop`): compares content (the compiled board vs `ISSUES.md`, not mtimes) in every context and rewrites a stale board itself, reporting `Auto-synced stale projection(s): ...` on stderr. It never blocks.
- **`wrapped_work_uncommitted`** (Stop): lists in full only the current session's issues (its completion tokens, its bound slug, issues whose ledger names this session); other sessions' issues collapse to "N other session issue(s) have uncommitted attributed files ('along session list')". Without a session id everything is listed.
- **`subproject_boundary`** (`predicates.check_subproject_boundary`): decided from the target file path and the session binding, never the shell cwd. A session bound to a subproject issue may write root `.along/` entities only on that issue's parent chain (`_bound_subproject_owns_root_entity`, `_parent_chain_slugs`); an umbrella issue covers its children at any depth (`ISSUES/` and `done/`).
- **Gate tiers** (`hooks.config.GATE_TIERS`): `invariant` gates (`workspace_containment`, `no_tracked_secrets`, `projection_protection`, `rule_pack_protection`, `entity_deletion_protection`) always enforce, cannot be shadowed or disabled by repository config and have no bypass. `advisory` gates (`wrapped_work_uncommitted`, `projection_sync_before_stop`) always run in shadow. All other gates are `process` gates that follow the configured mode.
- **Bypass accountability** (`alongkit.bypass`): `along commit -n --reason`, `along wrap -n --reason` (or `--force-reason`), `along wrap --force-reason` (when a check is actually forced), `along bump -n --reason`, `along scratch fallback --reason` and `along scratch purge --force --reason` need a non-empty reason. Where user messages are recorded (Claude Code `UserPromptSubmit`), the gate must have failed in this session and the user must have replied after the failure; otherwise the bypass is allowed and marked `unverified`. Every bypass goes to the session trace and to `.along/diagnostics/hooks_audit.jsonl` (`decision: bypass`); a commit also carries an `Along-Bypass: <gate>; <verified|unverified>; <reason>` trailer.
- **Audit record**: each `hooks_audit.jsonl` entry ends with `target`, the command or file path the gate judged (redacted with the telemetry Redactor, cut to 200 chars). A shadow-mode record carries `decision: "warn"`, not the raw `deny`, so an advisory gate such as `wrapped_work_uncommitted` no longer shows up as denials.
- **Gate stats** (`alongkit.gatestats`): `along gates stats [--since YYYY-MM-DD]` prints per-gate blocked / warned / bypassed counts from `hooks_audit.jsonl`, plus "Repeated blocks": identical (gate, target) blocks >= 3 in one conversation, a loop indicator (entries without `target` fall back to the reason). `along doctor` warns about gates set to shadow by config and about the most-bypassed gates (a gate bypassed about as often as it blocks is wrong or too strict).

### 2.11 Destructive Command Gate (`alongkit.hooks.deletion`)
`destructive_command` (`predicates.check_destructive_command`, `PreToolUse` on shell tools) looks only at explicit forms, segment by segment:
- Recursive deletes: `rm -r` / `-rf` / `--recursive`, `Remove-Item -Recurse` (`ri`, PowerShell `rm` / `rd` / `del` with `-Recurse`), `del /s`, `erase /s`, `rd /s`, `rmdir /s`.
- History rewrites: `git clean -f`, `git reset --hard`, `git push --force` (`-f`, `--force-with-lease`).

When it holds:
- A delete target is empty, holds an unexpandable variable or a command substitution, is outside the repository (children of the system temp directory excepted), is or contains the repository root, or holds uncommitted work (`git status --porcelain` non-empty under it). Ignored files such as `node_modules` do not count; a non-existent path passes.
- `git reset --hard` when tracked files are modified; `git clean -f` when its dry run (`git clean -n`) would remove something; `git push --force` always.

The message reads `DESTRUCTIVE [gate: destructive-command]: '<segment>': <why>. Fix: <fix>.` Decision: ASK in interactive sessions, DENY in autonomous ones (`ALONG_AUTONOMOUS=1` or Claude Code `bypassPermissions`). Everything else passes; scripts and other tools are out of reach by design (the container covers them, see `debt--gate-simplification`).

---

## 3. Data Flow & Execution Workflow

When an agent emits a tool call, the execution loop flows through the hook harness:

```text
[Agent Emits Tool Call]
          |
          v
[Runtime Harness: PreToolUse]
          |
          +--> Invokes: python ../scripts/along_hook.py --runtime antigravity --event PreToolUse
                     |
                     v (JSON payload over stdin)
          [Adapter parses HookEvent]
                     |
                     v
          [HookEngine evaluates Gates]
                     |
         +-----------+-----------+
         |                       |
     (Violation)              (Clean)
         |                       |
   [Mode == enforce?]            v
      /         \         [GateResult: ALLOW]
    YES          NO (shadow)     |
     |            |              v
     v            +--------> [Audit Log Appended]
 [GateResult: DENY]              |
     |                           v
     +---------------------> [Adapter formats JSON stdout]
                                 |
                                 v
                     [Runtime Harness receives output]
                                 |
                     +-----------+-----------+
                     |                       |
                (ALLOW: runs tool)      (DENY: blocks tool & reports reason to model)
```

---

## 4. Invariants & Failure Modes

1. **No Git Hooks by Default Invariant** (supersedes "Zero Git Hooks", see ADR `opt-in-git-hooks-supersede-zero-git-hooks`):
   - Nothing Along installs by default (`along-init`, `along update`, `install.*`) writes `.git/hooks/*`. Standard Git commands stay untouched until the user opts in.
   - Opt-in: `along hooks install --git` writes `pre-commit` and `commit-msg` shims that run `along gates check --hook <name>`. A foreign hook already in place is moved to `<hook>.pre-along` and run first; with `core.hooksPath` (husky, lefthook) nothing is written and the command to add to the manager is printed. `--uninstall` removes the shims and restores the previous hooks. The checks are read-only.
   - Merge drivers (`along git setup`) are per-clone `.git/config` entries, not hooks. See ADR `projection-merge-driver-defers-recompile`.
   - Runtime gates (`PreToolUse`, `Stop`) remain the primary layer, but they exist only where the host runtime loads Along's hooks. The portable baseline is the CI job `along gates check --ci`, plus the opt-in git hooks. Each gate declares its layers in `enforcement: [runtime, git, ci]`; `along hook verify` prints the matrix.
2. **Deterministic Rejection over Silent Overwrites**:
   - In `enforce` mode, gate violations result in an immediate `deny` decision with actionable remediation text. Silent auto-replacement is avoided so LLMs receive explicit negative feedback and learn rule adherence.
3. **Dual-Mode Governance (Shadow vs Enforce)**:
   - Configurable per-gate in `.along/config.json` or via `ALONG_HOOK_MODE`.
   - In `shadow` mode, violations emit a stderr warning and append a structured event (`decision: "warn"`) to `.along/diagnostics/hooks_audit.jsonl` without halting tool execution.
4. **Hermetic Test Guarantees**:
   - All hook engine unit tests target temporary directories (`tempfile.mkdtemp()`).
   - The test suite strictly asserts that `.along/diagnostics/` is never written into the repository root during automated testing.
5. **Fail-Open & Crash Resilience Invariant**:
   - Runtime lifecycle hooks must never cause agent paralysis (tool interception deadlock) due to missing scripts, unhandled exceptions, or non-Along workspaces.
   - Hook commands use direct, robust script paths rather than fragile shell inline scripts (`python -c`).
   - If `along_hook.py` encounters any unexpected internal error or runs in a workspace without Along protocol files, it catches the exception and exits `0` (`ALLOW`), ensuring tools are never blocked by infrastructure faults.
   - A missing `ruamel.yaml` with no usable `uv` is such a fault: `along_hook.py` calls `bootstrap.ensure_deps(missing_exit_code=0)`, because Claude Code reads exit code `2` as "block the tool".
   - When the interpreter lacks the dependencies, `bootstrap.ensure_deps()` re-executes into a cached runtime environment (`~/.along/venv`, override with `ALONG_VENV`). It is built once with `uv`, stamped with the dependency specs in `.along-deps`, and rebuilt when those specs change. `uv run --with` is only the fallback when the build fails, so a hook does not re-resolve dependencies on every tool use.
   - The re-exec marker (`ALONGKIT_BOOTSTRAPPED`) guards one re-exec only: `ensure_deps()` clears it once the dependencies import, so an engine started from a bootstrapped process (an installer running `install_manifest.py` under a bare interpreter) still bootstraps itself instead of exiting `2`.
   - `~/.along/venv` carries the runtime dependencies only. The repository's own test hook (`.along/scripts/test.py`) first calls `bootstrap.ensure_project_env()`, which re-executes through `uv run --project <repo>` so the suite gets the `dev` group (the dashboard stack); without `uv`, tests that need that stack are skipped with a reason.
   - On Windows, global hook commands use forward slashes only (`python C:/Users/<user>/.along/bin/along_hook.py ...`). Claude Code runs hooks through Git Bash, which strips backslashes; Python then cannot open the script and exits `2`, blocking every tool. Re-running `along update --global` rewrites old entries in place.
6. **Global Hook Centralization & Recursive Monorepo Purge**:
   - Since Along v3.9.2, runtime hooks are installed globally in user home configurations (`~/.gemini/config/hooks.json`, `~/.claude/settings.json`, `~/.codex/hooks.json`).
   - Consumer repositories and all nested subprojects are recursively purged of legacy local hooks during `along update`.
   - Out-of-band execution via `along update` in an external OS terminal serves as the canonical disaster recovery path if runtime hooks are ever damaged.

## 4a. Protocol Rule Enforcement Audit

Every rule of the managed `AGENTS.md` block, classified: **a** enforced by a gate or test, **b** mechanically checkable but not yet enforced, **c** judgment-only. Layers come from the catalogue `enforcement` field (`along hook verify` prints the full matrix). Class-a rules are one line in `AGENTS.md` with a gate tag; the gate's error message carries the detail. Commit-time checks (typography, anti-stub, AI co-author, code fences, links, entry point, filenames, secrets) carry no tag: `AGENTS.md` lists them on one line as checked by `along lint` (pre-commit and CI), not while you work.

Since `debt--agents-md-core-slimming` the managed block is a core of at most 6 KB: where state lives, issue anchoring, every gate tag with one line, and class-c rules as one-liners. The full wording of every rule below, plus situational procedure (completion checklist, documentation routing tree, concurrency and merge, parallel closeout, along-team routing, tool-use rules), lives in Along Protocol Reference (`.along/PROTOCOL.md`). Its source is `skills/along-init/protocol-reference.md`; `along init` / `along update` render it into each FULL root's `.along/`. `tests/test_scaffold_profiles.py` checks that no gate tag leaves the core and no named rule leaves the reference.

| Rule | Class | Enforced by | Layer |
| :--- | :--- | :--- | :--- |
| Nearest context boundary, precedence, session-start reading | c | - | - |
| Subproject localization (edits under a subproject `.along/` need its issue or a root umbrella with `parent:` children) | a | `subproject_boundary` | runtime |
| Subproject boundary: only a nested `.git` or a user-run `along init` (never a manifest folder) | a | `subproject_boundary` ignores bare manifests; `along update` creates no context; `along doctor` lists unmarked nested installs | runtime |
| Zero-manual-merge of projections | a | `projection_protection`, merge drivers (`along git setup`) | runtime, git, ci |
| Append-only `HISTORY.md` merge | a | `along git setup` writes `merge=union` | git |
| Untracked exports | a | `untracked_exports` | git, ci |
| Context isolation | c | - | - |
| No code without issue | a | `require_active_issue` | runtime |
| Commit binding | a | `commit_issue_binding` | runtime, git, ci |
| No AI co-authors | a | `commit_no_ai_coauthor` | git, ci |
| Canonical keys, reference by key (front-matter reference fields) | a | `entity_reference_integrity` (a path or unknown key is dangling) | runtime, git, ci |
| Never delete a referenced entity; rename / supersede | a | `entity_reference_integrity`, `along issue rename` / `supersede` | runtime, git, ci |
| ADRs never edited, only superseded | c | - | - |
| Issue lifecycle (`done/` placement) | a | `issue_lifecycle` | git, ci |
| Session log Blackboard Record is append-only | a | `session_record_append_only` (also `along commit`) | git, ci |
| Auto-entity creation | c | - | - |
| Stable entry point | a | `stable_entry_point` (also `along kb-sync --check`) | git, ci |
| Portable links | a | `portable_links` (also `along kb-sync --check`) | git, ci |
| Fact grounding, doc blast radius, routing tree | c | - | - |
| Fast retrieval (`along kb-search` recommended) | c | - | - |
| Manual document lock | a | `doc_manual_lock` | runtime, git, ci |
| Managed rule packs (`.along/rules/**/*.md`) not edited by agents | a | `rule_pack_protection` (runtime: file tools only; shell edits are caught at commit, where git / ci check that the body matches the managed header hash) | runtime, git, ci |
| Lifecycle hooks first, token hygiene, post-change review | c | - | - |
| Checklist: tests (edits under `.along/scripts/` count as source edits) | a | `test_before_stop` | runtime |
| Checklist: session log | a | `wrap_before_stop` | runtime |
| Checklist: denied tool calls redone or disclosed, never dropped silently | a | `unresolved_gate_denial` (closeout, `along wrap`, `along issue done` refuse unsettled denials) | runtime |
| Checklist: uncommitted wrapped work | a | `wrapped_work_uncommitted` | runtime |
| Checklist: projections | a | `projection_sync_before_stop`, projection freshness in `along gates check` | runtime, git, ci |
| Checklist: file integrity, review, reconciliation, HISTORY, compaction | c | - | - |
| Environment isolation (no global installs) | a | `cli_safety` (warning) | runtime |
| Workspace containment | a | `workspace_containment` | runtime |
| Explicit recursive deletes and history rewrites (`rm -rf`, `git reset --hard`, `git clean -f`, `git push --force`) on unrecoverable targets | a | `destructive_command` (ASK interactive, DENY autonomous) | runtime |
| Anti-deletion, anchored edits | c | - | - |
| No stubs or skeletons | a | `anti_stub_injection`, `along lint` | git, ci |
| Clean ASCII (incl. BOM) | a | `typography`, `along sanitize`, `along lint` | git, ci |
| Code fence languages | a | `code_fence_language` | git, ci |
| File content via tools only | a | `cli_safety` (warning) | runtime |
| CLI black-box invariance | c | - (Treat Along CLI as strict opaque black box; no engine source inspection in consumer repos) | - |
| Verify written files | c | - | - |
| Hermetic tests | a | `tests/test_zz_hermetic_suite.py` (this repo) | ci |
| Plan approval before repository changes (file-tool target path; files changed by the turn at Stop) | a | `require_plan_approval` | runtime |
| Complexity escalation to `along-team` | c | - | - |
| along-team step loop and reviews | a | `team_step_active`, `team_reviews_before_stop`, `along scratch purge` / `along wrap` refusal | runtime |
| Bounded subagent step prompt footprint | a | `bounded_prompt_gate` (`[gate: bounded-prompt-gate]`, hard limit 32 KB, soft warning 16 KB, attention leak detection) | runtime |
| ADR question at wrap | a | `along wrap --decisions / --no-decisions` (required) | runtime |
| Windows-safe filenames | a | `windows_safe_filenames` | git, ci |
| `ISSUES.md` compact | a | `along context-budget --check`, `tests/test_context_budget.py` | ci |
| No secrets in tracked files | a | `no_tracked_secrets` | git, ci |

## 5. Runtime Capability Matrix

Gates are mechanical only where the runtime loads Along's `PreToolUse`/`Stop` hooks. Everywhere else the protocol in `AGENTS.md` is advisory: the agent must self-apply every gate-tagged rule and route tests, commits, entity changes, and wrap through the `along` CLI. `along doctor` prints the level for the runtime it runs in (`alongkit.runtime`).

| Runtime | Along skills | Along runtime hooks | Enforcement |
| :--- | :--- | :--- | :--- |
| Claude Code | auto (`~/.claude/skills`) | yes (`~/.claude/settings.json`, nested schema) | mechanical once `along hook install` ran; `along doctor` also checks the schema and the last hook heartbeat |
| Google Antigravity | auto (`~/.gemini`) | yes (`~/.gemini/config/hooks.json`) | mechanical once installed |
| OpenAI Codex | auto (`~/.codex`) | yes (`~/.codex/hooks.json`) | mechanical once installed |
| Claude Cowork | not loaded (Cowork reads plugins from the claude.ai account, not `~/.claude`) | no (Cowork ignores `settings.json`; plugin hooks are tracked in `feat--cowork-plugin-skill-packaging`) | advisory |
| OpenCode | commands (`~/.config/opencode/commands`) | yes (`plugins/along-gates.js`) | mechanical once `along hook install --runtime opencode` ran |
| Cursor, plain shell, human | rules only | no | advisory |

Advisory runtimes are still covered at commit time by the portable layer: `along hooks install --git` (opt-in, local) and the CI job `along gates check --ci` enforce the gates whose catalogue entry lists `git` / `ci` (typography, conflict markers, anti-stub on added lines, issue binding, AI co-author trailers, projection freshness, rule pack integrity), regardless of which agent or human made the commit.

Runtime detection (`entities.detect_agent`) honours `--agent` and `ALONG_AGENT` first; Claude Cowork is recognised by `ALONG_RUNTIME=cowork`, or by `CLAUDE_CODE_HOST_HTTP_PROXY_PORT` together with a `/sessions/` home (markers observed 2026-09-27, heuristic).

### Working from Claude Cowork

Cowork runs the agent in a cloud container plus a Linux VM on the user's machine, with connected folders mounted under `$HOME/mnt/<folder>`:

1. Connect the repository folder in the Claude desktop app.
2. Grant delete permission for the folder before any git write. Without it the mount allows create and rename but not unlink, so `git status`, `git add`, and `git commit` leave a stale `.git/index.lock` and `along wrap` cannot move an issue into `done/`. `along doctor` warns when the lock exists.
3. Run the CLI with a supported interpreter, for example `uv run --python 3.12 --with ruamel.yaml python scripts/along_exec.py <command>` (Python 3.10 is supported from v4.3.0; see `bug--py310-fstring-syntax-error`).
4. Do not run `along worktree` from the VM: the repository is on the host filesystem (`core.symlinks=false`), so worktree metadata would record VM paths. `along doctor` warns on a cross-OS mount.
5. Pass `--agent cowork` only when detection reports `unknown`.

---

## 6. Gate Strictness Profiles per Model Tier

Complex procedural ceremonies and rigid review checklists impose significant token overhead. To accommodate varying model capabilities, Along decouples the immutable **state layer** from the **control layer** via named Gate Strictness Profiles.

### 6.1 Named Profiles

| Profile | Target Tier | Behavior |
| :--- | :--- | :--- |
| `strict` | Standard & Junior models | Full procedural ceremony, mandatory plan approval for all mutations, low complexity escalation thresholds, full 9-step completion checklist. |
| `standard` | Default baseline | Preserves default Along behavior: all 33 catalogue gates at their default severity, role-based escalation for multi-file/cross-system tasks. |
| `light` | Frontier / Strong models | Streamlines procedural ceremony: warns rather than blocks on procedural gates (`require_plan_approval`, `code_fence_language`, `team_step_active`), compacts the Stage Completion Checklist to 5 core invariants, and allows direct execution with user alignment. |

Profile-specific prose is declared in the protocol sources, not patched in by code: a line `<!-- profile: light -->` (or `<!-- profile: !light -->`, or a comma list) opens a section that only the named profiles keep (or that every other profile keeps), and `<!-- /profile -->` closes it. `alongkit.scaffold.render_profile_sections` resolves the sections and strips the markers for both the `AGENTS.md` core and `.along/PROTOCOL.md`. `along init` and `along update` both render for the resolved active profile.

### 6.2 State-Layer Invariance

Regardless of active profile (`strict`, `standard`, or `light`), immutable state integrity gates and safety invariants ALWAYS evaluate to `block`:
- **State-Layer Gates**: `require_active_issue`, `projection_protection`, `test_before_stop`.
- **Invariant Safety Gates**: `workspace_containment`, `no_tracked_secrets`, `rule_pack_protection`, `entity_deletion_protection`.

### 6.3 Resolution Hierarchy

Active profile resolves through the following precedence order:
1. **Session Binding**: `along start <slug> --profile <p>` or `.along/.session/<slug>/state.json`.
2. **Environment Variable**: `ALONG_PROFILE=<p>`.
3. **Repository Configuration**: `.along/config.json` or `.along/config.yaml` (`{"profile": "<p>"}`).
4. **Default Baseline**: `standard`.

### 6.4 Inspection & Visibility

- `along doctor`: Reports active profile, resolution source, strictness counts, and the complete gate strictness matrix.
- `along hook verify`: Shows active profile in the traceability report header and annotates each gate with its active strictness mode (`[BLOCK]`, `[WARN]`, `[OFF]`).
- `along init --profile <p>`: Scaffolds `AGENTS.md` with rules tailored to the selected profile.

---

## Document: docs/topic--session-lifecycle.md (Session & Blackboard Lifecycle Guide)

# Session & Blackboard Lifecycle Guide

How the working record of an issue is kept from `along start` to the committed session log, and
which commands and gates keep it from being lost. Command details are in the
[CLI Reference](./topic--cli-reference.md); the gates are in
[Runtime Hooks & Gates](./topic--runtime-hooks-and-gates.md).

## 1. The blackboard

Each issue in progress has a blackboard in `.along/.session/<slug>/` (not tracked by git):

| File | Content | Written by |
| --- | --- | --- |
| `state.json` | phase, approval, execution mode, steps, retries | `along start`, `along scratch`, approval |
| `plan.md` | the approved plan, with `## Revision N` sections | `ExitPlanMode`, `along plan approve --plan-file`, the agent |
| `research.md` | findings (role-based work) | the agent |
| `execution_trace.md` | edits, test runs and results, gate denials, approvals, phase and step changes | hooks and Along commands |
| `events.jsonl` | the event ledger: one record per edit, test run, plan, approval and gate denial (with its resolve / ack), used for attribution and closeout | hooks and Along commands |
| `reviews/step-N.md` | step verdicts (role-based work) | the agent |

`along start` creates a `direct` blackboard, `along scratch init` a `role-based` one (held to the
along-team step loop). Both are recorded the same way; `direct` only means "no step loop".

## 2. Recording the plan

The plan the user approved is part of the record:

- **Claude Code**: accepting a plan with `ExitPlanMode` stores its text in `plan.md` of the bound
  issue. A plan accepted before `along start` waits in the session binding and goes to the first
  issue started; an accepted plan also carries to a newly started slug until the user's next
  message (the plan is recorded under the new slug).
- **Elsewhere**: after the user's explicit yes, write the plan to a file and run
  `along plan approve <slug> --plan-file <path>`, or write it into `plan.md` yourself and run
  `along plan approve <slug>`.
- Approval is refused while `plan.md` is still the scaffold `along start` created.
- Where user messages are recorded (Claude Code `UserPromptSubmit` hook, in
  `.along/.session/prompts/<key>.json`), a CLI approval is refused when the plan file changed
  after the user's last message: show the plan and wait for a reply. With no recorded message
  it passes as `approved_via: cli-unverified`. The binding records `approved_via`
  (`exit-plan-mode`, `cli`, `cli-unverified`), `approved_at` and `plan_sha256`.
- A revised plan is appended as the next `## Revision N`; earlier revisions stay.

```bash
along start token-refresh
along plan approve token-refresh --plan-file plan.md
```

## 3. The execution trace

The trace of the issue the session is bound to is written automatically:

- every repository edit made with the agent's file tools (repeated edits of one file collapse to
  `(xN)`); the blackboard and diagnostics themselves are left out;
- `along test` runs and the test gates of `along wrap` / `along commit`, with pass or FAIL;
- gate denials (gate id and the first line of the reason);
- plan recorded and approved; phase, step-status and retry changes.

Raw test runners (`pytest`, `npm test` called directly) are not traced; use `along test`. A
session that is not bound to an issue writes no trace. The newest 400 entries are kept.

## 4. Closing an issue

Every way a blackboard leaves the repository writes it into the issue's session log
`.along/SESSIONS/<YYYY>/<date>--<slug>.md` first, as a `## Blackboard Record` section:

| Command | Session log | Blackboard |
| --- | --- | --- |
| `along wrap <slug> --no-decisions -m "..."` | record, `issues_completed`, decisions | purged after the wrap committed |
| `along issue done <slug>` | record (if any), `issues_completed` for `done` | purged after the move committed |
| `along scratch purge <slug> [--force --reason "..."]` | record, with the reason when forced | purged after the log is written |
| `along session gc` | record, for unbound blackboards whose issue is closed | purged after the log is written |

- `along wrap` refuses a blackboard whose plan was never recorded, unless
  `--force-reason "..."` says why; the reason is kept in the trace and the session log.
- `along wrap` runs every check before its first write, so a failed wrap leaves the tree unchanged:
  - Role-based steps (no open steps or missing reviews);
  - Approved living plan recorded (not a scaffold);
  - Issue and plan checklists: verifies that all `- [ ]` checklist items in the issue's `## Acceptance Criteria` and in the living plan `plan.md` are completed (`- [x]`); open checklist items abort wrap unless `--force-reason` is passed;
  - Pre-flight automated tests (or green test run reuse);
  - Zero-byte audit across the working tree;
  - Entity reference integrity (`--force-reason` passes the check).
  KB sync runs after the transaction commits and only warns when it fails.
- The log keeps its front matter, `## Summary`, `## Decisions` and the `## Blackboard Record`
  (step table, `### Research` if edited, `### Execution Trace`, `### Notes`, reviews, structured
  working context). The approved plan is not copied into the log (git and the plan gate hold it),
  and template placeholders (empty research headings, the generic step list) are not written.
- Attributed paths go to the front-matter list `files:` (merged on a same-day second record), not
  to a table. `along session close`, `along start`, `along doctor` and the stop gate read `files:`,
  and still read the legacy `### Attributed Files` table of older logs.
- Purge operations refuse across all commands (`along wrap`, `along scratch purge`, `along issue done`,
  `along session close`) if an unknown non-scaffold file is present in the blackboard.
- A second record of the same issue on the same day is appended as
  `## Blackboard Record (<n>, <timestamp>)`.

## 5. Checks that keep the record

- **wrap-before-stop** (end of turn): every issue closed as `done` today must be listed in
  `issues_completed` of a session log of today. Fix a gap with `along wrap <slug> --no-decisions`,
  which also works for an issue already in `done/`.
- **session-record-append-only** (`along commit`, `along gates check`, CI): a change may not
  remove or rewrite lines inside a `## Blackboard Record` of a committed session log. The Summary
  and Decisions sections stay editable.
- **`along doctor`**: warns about orphan blackboards (no session bound, issue closed or missing)
  and suggests `along session gc` or `along scratch purge <slug>`. `along session gc` archives into
  the session log and removes unbound blackboards whose issue is already closed (blackboards of
  missing issues are only reported); `along scratch purge <slug>` archives and removes one. Run
  `along doctor issues` to audit scaffold stubs.

## 6. Committing wrapped work

- **Atomic wrap auto-commit**: By default, `along wrap` automatically creates an atomic Git commit linked to the wrapped issue slug (`<type>: <summary> (refs #<slug>)`), bundling all attributed files, the moved issue file in `done/`, today's session log, and recompiled projections. Engine-written files carry no edit events, so two rules cover them. The managed `.along/PROTOCOL.md` counts as a projection. A changed `AGENTS.md` (root or nested) is included when its only difference from `HEAD` lies inside the managed `ALONG-PROTOCOL` / `ALONG-RULES` blocks; a hand edit outside them leaves it to attribution. `along session close` applies the same rules.
- **Opting out with `--no-commit`**: When `--no-commit` is passed, `along wrap` leaves changes uncommitted. The wrap purge removes the session's binding but preserves a completion token, so a subsequent manual `along commit -i <slug> --paths ...` passes the plan gate without a new approval and consumes the token.
- **Parallel closeout**: Several issues finished in parallel are closed in one step with `along session close`; the log of each one then also lists its attributed files in `files:`. See [Parallel Sessions](./topic--parallel-sessions.md).

---

## Document: docs/topic--setup-and-workflow.md (Setup & Developer Workflow)

# Setup & Developer Workflow

Complete guide for installing Along, configuring repository lifecycle runners, and executing day-to-day development workflows across host AI agent runtimes.

---

## 1. Installation & Multi-Platform Setup

Along installs globally and configures provider-agnostic agent discoverability across Claude Code, OpenAI Codex, OpenCode, and Google Antigravity.

### One-Liner Installation (Recommended)

Install Along across all supported agent runtimes without cloning the repository manually:

**Windows (PowerShell)**:
```powershell
powershell -NoProfile -ExecutionPolicy Bypass -Command "irm https://raw.githubusercontent.com/actdim/along/main/install.ps1 | iex"
```

**Linux / macOS (Bash)**:
```bash
curl -fsSL https://raw.githubusercontent.com/actdim/along/main/install.sh | bash
```

The one-liner detects standalone/remote execution, bootstraps the repository into `~/.cache/actdim-along/repo` (using shallow `git clone` or downloading the GitHub archive if `git` is absent), and executes the installer with manifest tracking.

### Manual / Local Checkout Installation

When working from a local clone of the repository:

**Windows**:
```powershell
# Install for all supported agent runtimes (Claude, Codex, Antigravity, OpenCode)
powershell -NoProfile -ExecutionPolicy Bypass -File install.ps1 -Target all

# Or run the batch installer, which forwards its arguments to install.ps1
install.bat -Target all
```

**Linux / macOS**:
```bash
# Make installer executable and run
chmod +x install.sh
./install.sh --target=all
```

### Supported Installation Targets
- `-Target all`: Deploys skills to `~/.claude/skills/`, `~/.codex/skills/`, `~/.gemini/config/skills/`, and `~/.config/opencode/commands/`.
- `-Target claude`: Deploys only to Claude Code.
- `-Target codex`: Deploys only to OpenAI Codex.
- `-Target antigravity`: Deploys only to Google Antigravity.
- `-Target opencode`: Deploys only to OpenCode.

### What an Install Writes

| Artifact | Destination | Notes |
| :--- | :--- | :--- |
| Skill folders (`skills/along-*`) | `<provider home>/skills/` | Copied, or linked with `-Symlink` / `--symlink`. |
| Language & platform rule packs (`rules/`) | `<provider home>/rules/` | Copied over the destination, never replacing the directory. |
| Engines and `alongkit/` | `~/.along/bin/` | The shared package travels with the engines. |
| OpenCode commands | `~/.config/opencode/commands/along-*.md` | Generated from the same `SKILL.md` bodies. |
| Default configuration | `~/.along/config.json` | Seeded only when absent; yours afterwards. |
| Install manifest | `~/.along/install-manifest.json` | Version, target homes, and every file the install wrote. |

Both installers write exactly the same artifact set; `tests/test_installers.py` runs each
one against a throwaway checkout and compares the result to the single layout description
in `alongkit.install.planned_files`.

Every root is overridable, which is how the tests run a real installer without touching
your own home: `--along-home=DIR --claude-home=DIR --codex-home=DIR --opencode-home=DIR
--antigravity-home=DIR --cursor-home=DIR` (`-AlongHome DIR`, `-ClaudeHome DIR`, ... in PowerShell).

The install also turns off AI commit attribution (`Co-Authored-By:` trailers) in Claude Code
`settings.json` and, when a Cursor home exists, in Cursor `cli-config.json`.
`/along-update` repeats this on every run, including when the install is already up to date;
`python ~/.along/bin/along_hook.py attribution` does it on demand. See
[Runtime Hooks & Gates](./topic--runtime-hooks-and-gates.md).

### Removing an Install

```bash
./install.sh --uninstall
powershell -NoProfile -ExecutionPolicy Bypass -File install.ps1 -Uninstall
```

The uninstall removes exactly the files listed in `~/.along/install-manifest.json` and
nothing else: rules you wrote yourself, `~/.along/config.json`, and any provider
configuration stay. The same manifest is what lets a re-install remove a file Along used
to ship without deleting the directory that holds it. See
[ADR-2026-09-01--installers-never-delete-what-they-did-not-write](./decisions/ADR-2026-09-01--installers-never-delete-what-they-did-not-write.md).

### Code Intelligence & MCP Decoupling

Code intelligence capabilities (`code-review-graph`) run on-demand directly via command-line execution (`along graph-impact`, `along graph-arch`, `along graph-sync`, `along graph-check`), eliminating background daemon requirements, JSON-RPC stdio pipe stalls, and IDE security approval dialogs.

Historically, `code-review-graph` was registered as an MCP server. This registration is decoupled and deprecated. To remove legacy `code-review-graph` entries from existing provider configuration files (`~/.claude.json`, `~/.codex/config.toml`, `opencode.json`, `mcp_config.json`), run:
```bash
python scripts/configure_mcp.py --clean
```
If legacy configuration entries are present, they are inert and can be cleaned without impacting CLI code-intelligence workflows.

### Windows Git Concurrency & Index Handling

When running rapid AI coding agents (such as Google Antigravity, Claude Code, or Codex) on Windows, tools generate multiple file modifications in quick succession (< 500ms).

#### The Problem on Windows NTFS
By default, Git commands attempt to replace `.git/index` by writing to `.git/index.lock` and atomically replacing `.git/index` via Windows `ReplaceFileW`. If another process (such as Windows Defender, Search Indexer, or an IDE file watcher) has `.git/index` open for reading, NTFS sharing constraints cause `ReplaceFileW` to fail or get interrupted, leaving `.git/index` truncated to 0 bytes:
```text
fatal: .git/index: index file smaller than expected
```

#### Safe Mitigations
1. **Exclude `.git` from Antivirus and Search Indexing**:
   Add the repository root or `.git` directory to Windows Defender and Windows Search exclusion lists. Background file scanners are the primary source of file locking collisions during Git atomic replacements on NTFS.

2. **Self-Healing Index Recovery**:
   If `.git/index` becomes corrupted or truncated to 0 bytes due to an external lock collision, Along automatically executes index self-healing via `git read-tree HEAD` or `git reset` to restore the index without data loss.

3. **Avoid Disabling Stat-Cache Flags**:
   Do not set `GIT_OPTIONAL_LOCKS=0` or `diff.autoRefreshIndex false`. While intended to prevent lock contention during read operations, these flags disable Git stat-cache refresh on Windows, causing clean files to be falsely reported as modified (`" M"`) whenever file timestamps change.

#### Line Ending Normalization & `.gitattributes`
To eliminate conversion warnings and CRLF/LF diff noise on Windows:
1. **Repository-Managed Line Endings**:
   `.gitattributes` defines exact line endings per file class: `eol=lf` for Markdown, Python, JSON, YAML, Shell, and text files; `eol=crlf` strictly for `.ps1` and `.bat`.
2. **Recommended Git Configuration**:
   Set `git config core.autocrlf false` in the repository so Git relies strictly on `.gitattributes` rather than performing unprompted system-wide CRLF conversions.
3. **Working Tree Normalization**:
   If cloning onto a Windows environment with pre-existing CRLF drift, renormalize via:
   ```bash
   git add --renormalize .
   ```

---

## 2. Python Runtime & Dependencies

The engines behind the skills need one third-party package, `ruamel.yaml`, to read and
write entity front-matter. Everything else is standard library.

```bash
# Recommended: install the toolchain with uv (creates an isolated environment)
uv tool install actdim-along

# Working inside this repository: initialize local .venv and install alongkit in editable mode
along dev-env

# Working inside this repository: uv resolves the environment from pyproject.toml
uv run python .along/scripts/test.py -q

# Running tests with pattern filter or pytest-style node selectors:
python .along/scripts/test.py -k <pattern>
python .along/scripts/test.py tests/test_x.py::TestClass::test_method

# Running tests directly via pytest:
uv run pytest -q tests/test_x.py

# No uv, no install: add the dependency to the active interpreter
python -m pip install "ruamel.yaml>=0.18"
```

An engine invoked directly as `python scripts/along_exec.py ...` or
`python ~/.along/bin/along_exec.py ...` checks for the dependency itself: if it is missing
and `uv` is on `PATH`, the engine re-executes once under `uv run` and continues. If `uv` is
absent it exits with code 2 and the two commands above, rather than a traceback.

Why a dependency at all: front-matter is YAML because tools that are not Along read it, and
a hand-rolled parser silently dropped block sequences and emitted blocks that no strict YAML
reader accepts. See [ADR-2026-09-01--frontmatter-on-ruamel-yaml](./decisions/ADR-2026-09-01--frontmatter-on-ruamel-yaml.md).

The dashboard (`/along-dash`) additionally needs FastAPI, Uvicorn, Pydantic, and Rich,
declared as the `dash` extra and resolved automatically by `uv run scripts/along_dash.py`.

---
## 3. Bootstrapping a New or Existing Repository

To initialize Along in any repository:
```bash
# Inside the repository root, run:
along init
```
*(Or invoke `/along-init` directly inside your AI agent prompt: the skill runs `along init` and then does the judgment steps.)*

### What `along init` Configures:
1. `AGENTS.md`: Generates the root protocol context with the managed `ALONG-PROTOCOL v4.9.0` block (a short REF block in a nested folder of the same git repository; a hand-written file keeps its text under `## Project specifics`). The block is a small core (state locations, issue anchoring, gates) rendered for the active gate strictness profile.
   - `.along/PROTOCOL.md`: the managed on-demand protocol reference (completion checklist, documentation routing tree, merge rules, along-team routing, full rule wording) the core points to; refreshed on every `along init` / `along update`, written only at a FULL root.
2. `CLAUDE.md`: Scaffolds the standard `@AGENTS.md` import line.
3. `.gitattributes`: Configures `merge=union` for `.along/HISTORY.md` and `.along/DECISIONS.md` to prevent merge collisions across branches.
4. `.along/`: Creates the persistent repository memory skeleton (`ISSUES/`, `DECISIONS/`, `MILESTONES/`, `SESSIONS/`, `docs/`; `GLOSSARY.md` and the `VISION.md` skeleton at the repository root - a nested context under a FULL ancestor creates them on first use).
5. `VISION.md`: A root `VISION.md` is moved into `.along/VISION.md` (or merged under a `needs-restructure` marker the agent resolves); there is never a second copy.
6. Pipeline: rule packs, git merge drivers, runtime hooks, migration.

The agent then works through the report's `AGENT ACTIONS` (imported VISION section, root notes such as `ROADMAP.md`, `## Project specifics`) and, on a re-run, asks the `RE-RUN QUESTIONS`. See [Along CLI Command Reference](./topic--cli-reference.md).

---

## 4. Repository Lifecycle Runners (`.along/scripts/`)

Along establishes a unified interface for project lifecycle operations via `.along/scripts/`. This allows AI agents to build, test, run, and bump versions across any technology stack without requiring custom prompt tuning.

```mermaid
flowchart LR
    AGENT["AI Agent Command (/along-test)"] --> ROUTER["along_exec.py Router"]
    ROUTER --> CHECK{"Custom .along/scripts/ hook exists?"}
    CHECK -->|Yes| CUSTOM[".along/scripts/test.py (Hook)"]
    CHECK -->|No| DETECT["Auto-Detect Stack (npm, cargo, dotnet, pytest)"]
    DETECT --> RUNNER["Execute with Quiet Flags (-q, -v q)"]
    CUSTOM --> RUNNER
```

### Standard Lifecycle Commands:

| Command | Canonical Script | Fallback Stack Auto-Detection | Purpose |
| :--- | :--- | :--- | :--- |
| `/along-build` | `.along/scripts/build.py` | `npm run build` \| `cargo build` \| `dotnet build` \| `python -m build` | Compiles source artifacts. |
| `/along-test` | `.along/scripts/test.py` | `pytest -q` \| `npm test` \| `cargo test -q` \| `dotnet test -v q` | Executes unit tests with quiet flags. |
| `/along-dev` | `.along/scripts/dev.py` | `npm run dev` \| `cargo run` \| `dotnet run` \| `python main.py` | Starts local development server. |
| `/along-version-bump` | `.along/scripts/bump_version.py` | Node `package.json` \| Python `pyproject.toml` \| Rust `Cargo.toml` \| .NET `*.csproj` | Bumps version and orchestrates release. |
| `/along-dep-scan` | `.along/scripts/dep_scan.py` | Node `package.json` \| Python `pyproject.toml` \| Rust `Cargo.toml` \| .NET `*.csproj` \| Go `go.mod` | Discovers dependencies and AI instruction rules. |

### Polyglot Hook Selection & Security

Lifecycle hooks are not limited to Python. Along detects the file extension and selects the appropriate interpreter:

| Extension | Runtime / Interpreter | Invocation Pattern |
| :--- | :--- | :--- |
| `.py` | Current Python runtime | `[sys.executable, script_path, *args]` |
| `.sh` | Bash shell | `[bash, script_path, *args]` |
| `.ps1` | PowerShell Core / Desktop | `[pwsh, -NoProfile, -File, script_path, *args]` |
| `.bat`, `.cmd` | Windows Command Processor | `[cmd.exe, /c, script_path, *args]` |
| (binary) | Direct executable | `[script_path, *args]` |

Every invocation enforces `shell=False` and passes command arguments as pre-split lists (`argv`). This guarantees that argument spaces, quotes, and shell metacharacters arrive in the child process without shell injection vulnerabilities.

### Zero-Config Auto-Synthesis & Status Tags

When an AI agent runs `/along-test` or `/along-build` in a repository that lacks `.along/scripts/`:
1. Along scans repository manifests to identify the active ecosystem (Node.js, Rust, .NET, Python, Go).
2. If recognized, Along synthesizes a verified hook file (e.g. `.along/scripts/test.py`) with quiet flags (`-q`, `-v q`) and writes a `# Status: verified` header tag. Node gets `npm test` only when `package.json` has a `test` script, and no `--silent` (the test gate counts executed tests from the runner summary).
3. If the ecosystem cannot be inferred, Along generates a safe template marked `# Status: unconfigured`, prompting the developer or agent to customize the command.

### Test Policy (`verify`)

The wrap / commit / bump test gate follows the effective `verify` policy resolved for the active context and issue:

```json
{
  "verify": {
    "tests": "required",
    "scopes": {
      "api": ["src/api/**", "tests/api/**"],
      "web": ["src/web/**", "tests/web/**"]
    }
  }
}
```

#### Policy Levels & Precedence

1. **Repository Level** (`.along/config.json`):
   - `tests: "required"` (default): automated tests must run and exit code 0.
   - `tests: "none"`: requires `reason` and `tracked_by` pointing to an existing issue. Declared `checks` (`build`, `lint`, `typecheck`) run instead.
   - `scopes`: mapping of scope names to path globs for targeted test runs.
2. **Issue Level** (YAML frontmatter in `.along/ISSUES/<type>--<slug>.md`):
   - `verify: {tests: required | affected | scoped | none, scope: "<name>", reason: "...", tracked_by: "...", checks: []}`
   - `affected`: runs tests targeting attributed files. Falls back to `full` if no attributed files exist.
   - `scoped`: runs tests for the named scope declared in repository `verify.scopes`.
   - `none`: requires `reason` and `tracked_by` (except spikes, which are exempt from `tracked_by`).
   - Every mode other than `required` requires `reason`.
3. **Plan Approval Snapshot**:
   - The issue-level verify policy takes effect **only** when snapshotted during `along plan approve`.
   - Manual edits to the issue frontmatter after plan approval trigger a drift warning; the gate uses the approved snapshot until the plan is re-approved.
   - Effective precedence: approved issue plan snapshot > repository config > default (`required`).

#### Runner Contract & Scoping

The test runner passes execution context to `.along/scripts/test.py` via environment variables:
- `ALONG_TEST_MODE`: `full | affected | scoped`
- `ALONG_TEST_SCOPE`: scope name from `verify.scopes`
- `ALONG_ATTRIBUTED_FILES`: path to file listing repo-relative paths of modified files

#### Target-Repository Guidance

- **Choosing Mode**: Use `required` for broad changes; use `scoped` for isolated modular components declared in `verify.scopes`; use `affected` for targeted incremental updates; use `none` on spikes or early prototypes tracked by debt issues.
- **Scoped `test.py`**: In `.along/scripts/test.py`, inspect `os.environ.get("ALONG_TEST_MODE")` and dispatch to targeted runners or test file paths.
- **AGENTS.md Project Specifics**: Document available test scopes and runner commands in the project specifics section of `AGENTS.md`.

- `along commit` skips the test gate when the change touches only `*.md`, `docs/**`, `.along/**` (not `.along/scripts/`), `llms*.txt` or a version-only `package.json` change.
- `along status`, `along doctor` and dashboard metrics (`verify_policy`) show the effective policy line, e.g. `tests: scoped (api) - <reason> (issue feat--slug)`.

### Typography: checking and repairing

`along sanitize` (or `python scripts/sanitize_typography.py`) reports banned characters
by file and line. It **checks by default and writes nothing**; repairing is an explicit act.

| Invocation | Effect |
| :--- | :--- |
| `along sanitize` | Report findings, exit 1. Nothing is written. |
| `along sanitize --dry-run` | Report findings, exit 0. Nothing is written. |
| `along sanitize --write` | Apply the ASCII replacements. |
| `along sanitize --json` | The same report as JSON on stdout, for tooling and CI. |
| `along sanitize --include-data` | Also scan `.json`, `.yaml`, `.yml`, `.toml`. |
| `along sanitize --exclude '<glob>'` | Skip matching paths; `.alongsanitizeignore` in the repository root does the same, one glob per line. |

Scope is `.md`, `.py`, `.sh`, `.ps1`, `.bat`; hidden directories such as `.along/` are
included; localized resource directories (`locales/`, `i18n/`, `translations/`, ...) are
never scanned. A file that is not valid UTF-8 is skipped and reported, and existing line
endings are preserved, so a CRLF `.ps1` stays CRLF. See
[ADR-2026-09-01--typography-rule-scope](./decisions/ADR-2026-09-01--typography-rule-scope.md).

### Repository Diagnostics, Health & Token Budgets

Along provides terminal utilities for inspecting repository state, verifying protocol adherence, and guarding context budgets:

- **`along status`**: Quick terminal overview of repository health, active issues, and recent sessions.
- **`along doctor [--entities] [--issues] [--docs]`**: Comprehensive repository health check validating directory structure, `.gitattributes`, ADR headers, entity DAG dependencies (`--entities`), issue template placeholders and incomplete criteria (`--issues`), and abandoned documentation stubs (`--docs`).
- **`along budget [--check]`**: Audits context footprint across root protocol files (`AGENTS.md`, `CLAUDE.md`, `.along/ISSUES.md`, `.along/CONSTRAINTS.md`) against strict limits (7 KB for `AGENTS.md`, measured without its "Project specifics" section; that section has a 4 KB soft limit that only warns), exiting with code 1 on budget breach. Limits are overridable in the `budget` block of `.along/config.json`.

For full command syntax, flags, exit codes, and subcommands, see the [Along CLI Command Reference](./topic--cli-reference.md).

### Releasing: gates first, then a transaction

`/along-version-bump [patch|minor|major|<version>]` runs in a fixed order, and the order is
the point: the tests, the typography check, and the Markdown link check all run **before the
first byte is written**, on every invocation. A bump without `--commit` is verified exactly
as strictly as one with it.

| Step | What it writes |
| :--- | :--- |
| 1. Gates | Nothing. Tests, typography check, `along_kb_sync.py --check --strict`. |
| 2. Version | `.along/scripts/bump_version.py` if present, else the detected manifest (`package.json`, `pyproject.toml`, `Cargo.toml`, `VERSION`, or the Along protocol files). |
| 3. Milestone | Front-matter of the milestone in `.along/MILESTONES/` whose `slug` names the version: `status: completed`, `progress_pct: 100`. The body is never touched. |
| 4. CHANGELOG | A `## v<version>` section listing commit subjects since the previous tag. |
| 5. Commit and tag (`-c`) | Stages only the paths steps 2 to 4 wrote, commits `release: v<version>`, creates the annotated tag `v<version>`. `-p` pushes both. |

Steps 2 to 4 are transactional. A failure in any of them, or in staging, restores every file
byte for byte and prints what it put back; the transaction closes once the commit exists,
because past that point a rollback would discard committed work. `--fix-typography` opts
into repairing the findings from step 1 and is itself covered by the rollback. `-n` /
`--no-verify --reason "..."` is the one documented way past the gates; it is a recorded bypass.

A release writes nothing outside the repository. Installing skills for your providers is
`/along-update` or `install.ps1` / `install.sh`, run deliberately.

### Monorepo Workspaces vs Git Submodules in Releases

When managing multi-component projects, the release pipeline behaves fundamentally differently depending on whether components are organized as Monorepo Workspaces or Git Submodules:

#### Monorepo Workspaces (`packages/*`)
In monorepos sharing a single `.git` repository (such as pnpm or npm workspaces):
- `along bump` automatically detects all workspace manifests (e.g. root `package.json` and nested `packages/*/package.json`).
- Version updates, changelog generation, git commit (`release: vX.Y.Z`), annotated git tag, and remote push happen in a single atomic transaction.
- There are no detached commit pointers or distributed push failure risks.

#### Git Submodules (`.gitmodules`)
Git submodules are independent remote repositories. Git fundamentally forbids committing files belonging to a nested `.git` from the parent repository; the parent repository only records a 40-character commit hash pointer.

Because of this distributed architecture:
- **Default root `along bump` does NOT cascade into submodules**: Running `along bump` in the root repository bumps only the root repository. It will not blindly create commits or push tags to foreign submodule remotes.
- **Two-phase release sequence**: If code changed both in a submodule and in the root application:
  1. **Phase 1 (Submodule)**: Finalize the submodule task (`along wrap`) and release the submodule (`along bump patch -cp` inside the submodule). Push the submodule commit and tag to its remote.
  2. **Phase 2 (Root)**: Stage the updated submodule commit SHA in the root repository (`along commit "chore: update submodule pointer"`), then release the root (`along bump patch -cp`).

### Cascading Releases Across Git Submodules (.along/scripts/bump_version.py)

If a project requires Unified / Lockstep Versioning (where changing the root version must automatically cascade the exact same version string, commit, tag, and push across all Git submodules), this behavior must be explicitly implemented via the project hook `.along/scripts/bump_version.py`.

Standard `along bump` delegates to `.along/scripts/bump_version.py` whenever this file exists. The custom hook orchestrates the distributed release:

```python
#!/usr/bin/env python3
"""Custom project version bumper with cascading submodule release."""
import subprocess
import sys
import os

def run(cmd, cwd=None):
    res = subprocess.run(cmd, cwd=cwd, check=True)
    return res.returncode

def main():
    bump_arg = sys.argv[1] if len(sys.argv) > 1 else "patch"
    repo_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))

    # 1. Target submodules requiring lockstep release
    submodules = ["packages/ui-core", "packages/common-api"]

    # 2. Step through each submodule: run tests, bump version, commit, and push
    for sub in submodules:
        sub_dir = os.path.join(repo_root, sub)
        print(f"-> Cascading release to submodule: {sub}")
        # Run submodule along bump with commit and push (-cp)
        # Submodules MUST push immediately so their commit SHA exists on the remote
        run(["along", "bump", bump_arg, "-cp"], cwd=sub_dir)

    # 3. In root repository: stage updated submodule pointers
    run(["git", "add", *submodules], cwd=repo_root)

    # 4. Return new version to Along release engine
    print("4.5.0")
    return 0

if __name__ == "__main__":
    sys.exit(main())
```

> [!WARNING]
> Distributed submodule releases are not atomic across Git remotes. If a network error or test failure occurs midway through a cascading push, already-pushed submodule tags cannot be automatically rolled back without administrative force-pushes. For tightly coupled components released on the same cadence, a Monorepo Workspace is strongly recommended over Git Submodules.

### Continuous Integration

`.github/workflows/tests.yml` runs on every push to `main` and every pull request:

| Job | What it checks |
| :--- | :--- |
| `python` | Syntax gate (`compileall`) and `python .along/scripts/test.py -q` on Python 3.10, 3.11, 3.12, 3.13 x `ubuntu-latest`, `windows-latest`. |
| `gates` | Typography gate (`sanitize_typography.py --check`, blocking) and the Markdown link report (`along_kb_sync.py --check --strict`, report-only until the links into `node_modules` in `docs/topic--dependencies.md` are fixed). |
| `dashboard-ui` | `pnpm install --frozen-lockfile` and `typecheck` for `packages/dashboard-ui`. |

A green `Tests` run on the release commit is the precondition for `/along-version-bump`: the
local gates see only one interpreter and one operating system.

---

## 5. Day-in-the-Life Developer & Agent Workflow

The standard developer workflow in an Along-enabled repository flows through 6 phases:

```mermaid
sequenceDiagram
    autonumber
    actor Dev as Developer
    participant Agent as AI Agent (Antigravity / Claude)
    participant Protocol as .along/ ISSUES & Memory
    participant Runners as Lifecycle Runners (test / build)
    participant Wrap as along-wrap & along-commit

    Dev->>Agent: "Add rate limiting middleware to auth routes"
    Note over Agent: Phase 1: Intent Heuristics & Issue Anchoring
    Agent->>Protocol: Auto-create .along/ISSUES/feat--rate-limiting-middleware.md
    
    Note over Agent: Phase 2: Autonomous Multi-Agent Execution (/along-team)
    Agent->>Agent: Scout researches auth routes -> Architect creates Living Plan
    loop Step Loop (1..N)
        Agent->>Agent: Implementer applies code edits
        Agent->>Runners: Reviewer runs /along-test & checks AST blast radius
    end

    Note over Dev,Agent: Phase 3: Validation & Committing
    Dev->>Agent: "Commit and wrap up"
    Agent->>Wrap: /along-commit (ASCII validation + Conventional Commit)
    Agent->>Wrap: /along-wrap (Test gate, move issue to done/, update SESSIONS/ and HISTORY.md)
    Agent-->>Dev: Final concise summary
```

### Step 1: Morning Sync & Task Triage
- Launch `/along-dash` to inspect sprint KPIs, active blockers (issues tagged `risk`), and the entity DAG.
- Review active issues in `.along/ISSUES.md` or inspect milestone progress via `along milestone list` and `along milestone show <slug>`.

### Step 2: Task Claiming & Atomic Session Start
- Issue a natural language prompt to the agent (e.g. *"Fix Windows path escaping in CLI"*) or invoke `along start <slug> [--worktree]`.
- The agent infers the issue type (`bug`), creates `.along/ISSUES/bug--windows-path-escaping.md`, and runs `along start <slug> [--worktree]`.
- **Atomic Initialization**:
  - Sets issue `status: in-progress` and updates `updated: YYYY-MM-DD`.
  - Recompiles the active board projection (`.along/ISSUES.md`).
  - Initializes session blackboard in `.along/.session/<slug>/` (`state.json` and `plan.md`).
  - Marks the plan as approved (`phase: execution`, `plan_approved: true`) and binds the active issue.
  - If `--worktree` is specified, provisions an isolated Git worktree at `.along/worktrees/<slug>` with linked dependencies.
- **Mid-Flight Metadata Adjustments**:
  Use `along issue update <slug> [--milestone <m>] [--priority <p>] [--tags <t>]` to adjust issue metadata without manually editing YAML frontmatter.

### Step 3: Execution via `/along-team`
- For S-size tasks (1-2 files): The agent fast-paths edits directly and runs tests.
- For M/L/XL-size tasks: The agent activates the multi-agent sequential state machine, creating a dynamic Living Plan and verifying each step with an independent Reviewer subagent.

### Git Worktree Workspace Isolation (`along worktree`)
For complex or autonomous tasks requiring complete isolation from uncommitted developer work:
- Run with `--worktree` flag (e.g. `/along-team <slug> --worktree` or `along worktree create <slug>`).
- **Environment Readiness Contract** [gate: worktree-env-readiness]:
  - Package dependencies (`node_modules`, `.venv`) are linked via NTFS directory junctions on Windows (`mklink /J`) or symlinks on POSIX (`os.symlink`) without duplicating storage.
  - Untracked configuration files (`.env`, `.env.local`) are copied to the worktree.
  - Ephemeral session blackboards (`.along/.session/<slug>/`) are shared in real time and preserved before teardown.
- **Fail-Fast Policy**: If worktree isolation is requested but environment readiness cannot be satisfied, execution halts immediately in Phase 0.
- **CLI Commands**:
  - `along worktree create <slug> [--branch <name>]`: Provisions `.along/worktrees/<slug>` and links dependencies.
  - `along worktree remove <slug> [--force]`: Safely unlinks junctions (`os.rmdir`) and prunes worktree with Windows lock retry backoff.
  - `along worktree merge <slug> [--squash]`: Merges worktree branch into current working branch.
  - `along worktree status [--json]`: Lists active worktrees and environment readiness states.
  - `along worktree gc`: Prunes orphaned worktrees and purges deferred trash directories.

For complete options, flags, and teardown mechanics, see [Along CLI Command Reference: along worktree](./topic--cli-reference.md#along-worktree).

### Step 4: Verification & AST Blast Radius Gate
- Run `/along-test` to ensure zero regressions.
- Execute `/along-graph-check` to trace caller contracts and map affected symbols to `docs/topic--*.md` Knowledge Base articles.

### Step 5: Clean Conventional Commit
- Execute `/along-commit -i <slug> -m "<summary>"`.
- Verifies clean ASCII typography (no em-dashes, no curly quotes) and binds the commit to the active issue.
- The typography gate **reports and aborts**; it does not rewrite the working tree. Findings
  are printed with file and line. Add `--fix-typography` to apply the replacements in the
  same run, or clean them by hand.
- A file that is not valid UTF-8 is skipped and named, never decoded lossily and rewritten.
  See [ADR-2026-09-01--typography-rule-scope](./decisions/ADR-2026-09-01--typography-rule-scope.md).

### Step 6: Session Wrap-Up
- Invoke `/along-wrap` to execute the mandatory completion checklist:
  1. Automated test suite check.
  2. Documentation blast radius sync (`/along-kb-sync`).
  3. Move issue to `.along/ISSUES/done/`.
  4. Reconcile `ISSUES.md` projection.
  5. Record work session log in `.along/SESSIONS/<YYYY>/`.
  6. Append history line to `.along/HISTORY.md`.
  7. Purge ephemeral blackboard `.along/.session/<slug>/`.

---

## 6. Writing Tests: the Hermetic Rule

Agents write most of the tests in this repository, so the rule that keeps the suite
trustworthy is stated here as well as in the protocol (a one-liner in the `AGENTS.md` core, the full rule
in Along Protocol Reference (`.along/PROTOCOL.md`)).

**A test must never point an engine at the repository that contains it.** The engines
write: `migrate_protocol.py` normalizes front-matter, sanitizes typography, and rewrites
Markdown links across the whole tree; `along_update.py` regenerates the managed protocol
block; `along_exec.py` creates and moves entities. Three tests used to pass `REPO_ROOT`
straight into those engines, and one of them rewrote a newly created issue file mid-session,
turning `protocol_version: "2.2.8"` into `protocol_version: 2.2.8`. A suite in that state
cannot act as a gate, because "the suite is green" and "the tree is clean" are no longer
simultaneously achievable, and CI cannot tell a real change from test noise.

### How to write one

```python
import hermetic          # tests/hermetic.py

def test_engine_does_the_thing(self):
    with hermetic.repo_fixture(prefix="along-mything-") as fixture:
        res = proc.run_capture([sys.executable, engine_script, fixture])
        self.assertEqual(res.returncode, 0, res.stderr)
```

`hermetic.repo_fixture()` builds a throwaway repository that looks like a current Along
project (`AGENTS.md` with the managed block, `.along/` with one valid entity, an ADR, the
board, and a small `docs/` Knowledge Base) and removes it afterwards. It is deliberately
not a git repository, so nothing a test runs can reach a real index or history. For an
engine that resolves its target from the working directory, such as `along_exec.py`, pass
the fixture as `cwd` instead of as an argument.

Reading live repository content is still allowed and several guards depend on it: the ADR
format guard in `tests/test_kb_search.py`, the entity-status guard in
`tests/test_issue_lifecycle.py`, and the typography and link gates. Those tests open files
read-only and never invoke an engine that writes.

### What enforces it

`tests/test_zz_hermetic_suite.py` runs last (alphabetically, under `unittest discover`) and
holds two gates:

| Gate | What it does |
| :--- | :--- |
| `test_01_working_tree_is_unchanged_by_the_suite` | Snapshots `git status --porcelain -u` at import time and again after the suite, failing on any path that appeared, vanished, or changed status. |
| `test_02_no_test_targets_the_repository_root` | Parses every `tests/*.py` and fails on a command-shaped list literal built with `REPO_ROOT` as an argument, so a regression is caught when it is written rather than when it happens to do damage. |

Run the suite with `python .along/scripts/test.py` (it resolves `ruamel.yaml` through `uv`
when the interpreter lacks it), `uv run python .along/scripts/test.py`, or `npm run test:quiet`
(`-q` / `--quiet` switches to dot output). This runner is the only supported entry point for
this repository: `tests/__init__.py` refuses raw `python -m unittest` and `pytest`, because the
suite needs `ALONG_TEST_RUNNER`, the pre-flight syntax gate, and the resolved dependencies.
The generic test-runner patterns in the `require-plan-approval` gate allowlist (`pytest`,
`python -m unittest`, `npm test`, ...) stay, because they describe consumer repositories, not
this one.

---

## Document: docs/topic--skills-reference.md (Skills & Slash Commands Technical Reference)

# Skills & Slash Commands Technical Reference

Along provides an integrated suite of **21 singular automation skills** operating across Claude Code, OpenAI Codex, OpenCode, and Google Antigravity.

Each skill is built on a domain-first naming pattern (`along-<entity>-<action>`), guarantees clean ASCII output, operates on strongly typed repository entities, and can be invoked either explicitly via slash commands/CLI or automatically via semantic intent recognition.

---

## Skills Ecosystem & Workflow Phases

```mermaid
flowchart TD
    subgraph Phase1["1. Bootstrap & Protocol"]
        INIT["along-init"]
        UPDATE["along-update"]
        BUMP["along-version-bump"]
    end

    subgraph Phase2["2. Planning & Multi-Agent"]
        TEAM["along-team"]
        ISSUE_SYNC["along-issue-sync"]
        DEC_SYNC["along-decision-sync"]
    end

    subgraph Phase3["3. Lifecycle Runners"]
        BUILD["along-build"]
        TEST["along-test"]
        DEV["along-dev"]
    end

    subgraph Phase4["4. Quality & Code Graph"]
        COMMIT["along-commit"]
        GRAPH["along-graph-check"]
        GRAPH_SYNC["along-graph-sync"]
        GRAPH_IMPACT["along-graph-impact"]
        GRAPH_ARCH["along-graph-arch"]
        DEP["along-dep-scan"]
    end

    subgraph Phase5["5. LLM-Wiki Intelligence"]
        KB_SYNC["along-kb-sync"]
        KB_SEARCH["along-kb-search"]
    end

    subgraph Phase6["6. Analytics & Wrap"]
        DASH["along-dash"]
        HIST_SYNC["along-history-sync"]
        FEEDBACK["along-feedback"]
        WRAP["along-wrap"]
    end

    INIT --> TEAM
    TEAM --> BUILD & TEST & DEV
    TEST --> GRAPH & COMMIT
    COMMIT --> KB_SYNC & KB_SEARCH
    KB_SYNC --> DASH & WRAP
```

---

## 1. Bootstrap & Repository Protocol Management

### `along-init`
- **What it is**: The foundation bootstrapping engine for Along in any repository. Scaffolds or refreshes root `AGENTS.md` (carrying the managed protocol block), `CLAUDE.md`, `.gitattributes` (with `merge=union`), and the `.along/` directory skeleton (`ISSUES/`, `DECISIONS.md`, `MILESTONES/`, `SESSIONS/`, `docs/`; `GLOSSARY.md` and the `VISION.md` skeleton only where the context is not nested under a FULL ancestor).
- **Architectural Rationale**:
  - *Idempotent Managed Block*: Never overwrites custom human developer instructions in `AGENTS.md`; only refreshes the block between `<!-- BEGIN ALONG-PROTOCOL ... -->` and `<!-- END ALONG-PROTOCOL -->`.
  - *Core + On-Demand Reference*: the block is a small always-loaded core; situational procedure lives in the managed `.along/PROTOCOL.md` (rendered from `skills/along-init/protocol-reference.md` at FULL roots, refreshed only while it carries the managed marker), pulled via `/along-kb-search`. Both are rendered for the active gate strictness profile.
  - *Non-Destructive Initialization*: Creates directories and template files only if missing, preserving existing project history.
  - *Deterministic Engine, Judgment by the Agent*: `along init` performs every mechanical step (FULL/REF protocol block bounded by the git working tree, hand-written `AGENTS.md` adoption under `## Project specifics`, root `VISION.md` moved into `.along/VISION.md`, rule packs, merge drivers, hooks, migration). The agent then decomposes an imported VISION section, routes root notes (`ROADMAP.md`, `ARCHITECTURE.md`, ...) and runs the re-run dialog.
- **Invocation Triggers**:
  - *Explicit*: `/along-init`, `install.ps1`, `install.sh`.
  - *Semantic / Automatic*: Triggered when an agent detects an uninitialized repository, missing `AGENTS.md`, or a user prompt like *"Set up Along in this repo"*, *"Initialize agent instructions"*.
- **Entities Operated On**: `AGENTS.md`, `CLAUDE.md`, `.gitattributes`, `.along/ISSUES/`, `.along/DECISIONS.md`, `docs/`.
- **Ecosystem Chaining**: Followed immediately by `/along-kb-sync` (to ingest `README.md`) and `/along-dep-scan`.

---

### `along-update`
- **What it is**: Automated protocol, skill, and runtime hook synchronizer. Checks and pulls latest Along skills, migrations, and protocol definitions across user home directories (`~/.claude`, `~/.codex`, `~/.gemini`) and local repositories, and automatically reconciles runtime lifecycle hooks across supported agent environments.
- **Architectural Rationale**:
  - Eliminates skill drift across multiple developer machines while isolating updates to the target repository by default (global machine skills update requires an explicit `--global` flag).
  - Automatically executes retroactive migration scripts (`scripts/migrate_protocol.py`) to upgrade legacy front-matter schemas and directory layouts without data loss.
  - Automatically scaffolds and updates runtime lifecycle hooks (`.agents/hooks.json`, `.claude/settings.json`, `.codex/hooks.json`), guaranteeing that mechanical quality gates and typography invariants are enforced across all active agent tools without manual setup.
- **Invocation Triggers**:
  - *Explicit*: `/along-update`, `along update` (fallback: `python ~/.along/bin/along_exec.py update`).
  - *Semantic / Automatic*: Triggered on protocol version mismatch, outdated skills warnings, or prompts like *"Upgrade Along protocol"*, *"Update agents"*.
- **Entities Operated On**: Global skill folders (`~/.gemini/config/skills/along-*`), target repository `AGENTS.md`, `scripts/`, and runtime hook configurations (`.claude/`, `.codex/`, `.agents/`).
- **Ecosystem Chaining**: Runs `migrate_protocol.py`, reconciles runtime hooks, and triggers `/along-kb-sync --strict` to validate repository link integrity after updates.

---

### `along-version-bump`
- **What it is**: Universal multi-stack semantic version bumper and release orchestrator. Updates project versions across Node (`package.json`), Python (`pyproject.toml`), Rust (`Cargo.toml`), .NET (`*.csproj`), or Along protocol files.
- **Architectural Rationale**:
  - *Stack-Agnostic Hook Architecture*: Executes repository-specific hooks in `.along/scripts/bump_version.py` with automatic fallback to stack auto-detection.
  - *Pre-Release Quality Gate & CI Precondition*: Looks up the CI status of the commit being released via `gh run list --commit <sha>` before mutating when workflows and `gh` exist (bypassed with `--skip-ci --reason "..."`). Runs the test suite, the typography check, and the Markdown link check BEFORE the first byte is written, on every invocation rather than only when `--commit` is passed. The typography step aborts on a finding rather than rewriting the tree; `--fix-typography` opts into the repair.
  - *Transactional Release*: Every mutation is recorded by `alongkit.transaction.FileTransaction`. A failure anywhere up to the git commit restores each file byte for byte and reports what it put back, so an aborted release leaves no half-released tree. The transaction closes once the commit exists.
  - *No Global Side Effects*: A version bump never reinstalls the machine's agent configuration. Installing globally is `/along-update` or the installer.
- **Invocation Triggers**:
  - *Explicit*: `/along-version-bump [patch|minor|major|<version>] [-c|--commit] [-p|--push] [--fix-typography] [-n|--no-verify] [--skip-ci] [--carry-over <milestone>]`, `along bump` (fallback: `python ~/.along/bin/along_exec.py bump`).
  - *Semantic / Automatic*: Triggered when preparing a release, completing a milestone sprint, or prompted with *"Release version 2.3.0"*, *"Bump patch version"*.
- **Entities Operated On**: `package.json`, `pyproject.toml`, `Cargo.toml`, `*.csproj`, `VERSION`, `AGENTS.md`, `CHANGELOG.md`, the milestone in `.along/MILESTONES/` whose front-matter `slug` names the released version.
- **Ecosystem Chaining**: Chains with `/along-test` for pre-release validation, `/along-kb-sync --check --strict` for the link gate, and creates the release commit plus the annotated `v<version>` tag itself.

---

## 2. Orchestration, Planning & Multi-Agent Teams

### `along-team`
- **What it is**: Sequential multi-agent development engine and living plan orchestrator. Replaces chaotic chat rooms with a deterministic state machine: `Supervisor -> Scout (Research) -> Architect (Living Plan) -> Step Loop [Implementer -> Reviewer/Tester -> Reassess] -> Wrap`.
- **Architectural Rationale**:
  - *Context Pruning Gatekeeping*: The Supervisor strips raw tool outputs from the Scout, injecting only distilled facts into the Implementer to prevent prompt saturation.
  - *Dual-Track UI & Memory Projections*: Projects the Living Plan and Walkthrough into native IDE visual design cards (`implementation_plan.md` with interactive "Proceed" feedback, and `walkthrough.md`) when running under Google Antigravity, while persisting portable Markdown on disk (`.along/.session/<slug>/`) across all CLI runtimes (Claude Code, OpenAI Codex, OpenCode).
  - *Loop Disambiguation (Fix Loop vs Re-plan Loop)*: Distinguishes local micro-iterations (`[Fix Loop]`: worker resolves test/lint errors within immediate diff, max 2 retries) from structural architectural revisions (`[Re-plan Loop]`: Architect increments living plan to `Revision N+1` on blockers or assumption changes).
  - *Engineering Provenance Compilation*: Captures the full trajectory (initial plan baseline, execution trace of fix and re-plan loops, and final gate verification manifest) and compiles it into the permanent session log in `.along/SESSIONS/`.
  - *Independent Gatekeeper Review*: Reviewer evaluates code in an isolated subagent context (or single-agent fallback) against the conditional 7-point verification rubric (file integrity, automated tests, diff scope, requirement traceability, AST blast radius, documentation parity, clean ASCII).
  - *Adaptive Complexity Routing*: Fast-paths S-size tasks (1-2 files) without subagents; uses full state machine only for M/L/XL tasks.
- **Invocation Triggers**:
  - *Explicit*: `/along-team <slug>`, `/goal <task>`.
  - *Semantic / Automatic*: Triggered automatically for multi-file feature requests, complex refactorings, or prompts like *"Implement this feature with the agent team"*.
- **Entities Operated On**: `.along/ISSUES/<type>--<slug>.md`, `.along/.session/<slug>/` (ephemeral blackboard: `living_plan.md`, `execution_trace.md`, `blackboard.md`), `docs/`.
- **Ecosystem Chaining**: Uses `along-build`, `along-test`, `along-graph-check` during step loops, and finishes via `along-wrap`.

---

### `along-issue-sync`
- **What it is**: Idempotent synchronization engine that reconciles atomic issue files (`.along/ISSUES/*.md`, `.along/ISSUES/done/*.md`) into the compact active issue board projection (`.along/ISSUES.md`).
- **Architectural Rationale**:
  - *Zero-Manual-Merge Principle*: Because `ISSUES.md` is a compiled projection, git merge conflicts are resolved automatically by running `along-issue-sync` rather than manually resolving diffs.
- **Invocation Triggers**:
  - *Explicit*: `/along-issue-sync`, `along issue sync` (fallback: `python ~/.along/bin/along_exec.py issue sync`).
  - *Semantic / Automatic*: Triggered during `/along-wrap`, when an issue changes status, or during post-git-merge reconciliation.
- **Entities Operated On**: `.along/ISSUES/*.md`, `.along/ISSUES/done/*.md`, `.along/ISSUES.md`.
- **Ecosystem Chaining**: Feeds data into `along-dash` and `along-wrap`.

---

### `along-decision-sync`
- **What it is**: Architectural Decision Record (ADR) recorder. Appends structured architectural decisions with decentralized slug headers (`## ADR-YYYY-MM-DD--<slug>`) into `.along/DECISIONS.md`.
- **Architectural Rationale**:
  - *Decentralized Slug Headers*: Prevents merge collisions across concurrent branches compared to sequential integer numbering (`#012`).
  - *Append-Only Invariance*: Old decisions are never deleted or rewritten; when superseded, they are marked `superseded by ADR-YYYY-MM-DD--<slug>`.
- **Invocation Triggers**:
  - *Explicit*: `/along-decision-sync`, `along decision create` (fallback: `python ~/.along/bin/along_exec.py decision create`).
  - *Semantic / Automatic*: Triggered whenever a non-trivial architectural choice, library selection, or database schema design is confirmed during a session or spike.
- **Entities Operated On**: `.along/DECISIONS.md`.
- **Ecosystem Chaining**: Governs Reviewer checks in `along-team` and informs documentation updates in `along-kb-sync`.

---

## 3. Development & Lifecycle Execution Runners

### `along-build`
- **What it is**: Universal build runner. Executes repository build lifecycle via `.along/scripts/build.py` (or `.sh`, `.ps1`, `.bat`) with fallback to auto-detected package runners (`npm run build`, `cargo build`, `dotnet build`, `python -m build`). Custom project hooks in `.along/scripts/` take absolute precedence.
- **Architectural Rationale**:
  - *Non-Destructive Standardized Interface*: AI agents execute a single unified command (`along-build`) across any programming language or technology stack without needing custom per-repo prompt tuning.
- **Invocation Triggers**:
  - *Explicit*: `/along-build`, `along build` (fallback: `python ~/.along/bin/along_exec.py build`).
  - *Semantic / Automatic*: Triggered after code edits, before pre-commit checks, or when the user prompts *"Build the project"*.
- **Entities Operated On**: `.along/scripts/build.py` (and `.sh`, `.ps1`, `.bat`), build output targets (`dist/`, `build/`, `bin/`).
- **Ecosystem Chaining**: Prerequisite for `along-test` and `along-dash` UI builds.

---

### `along-test`
- **What it is**: Universal automated test runner with quiet flags (`pytest -q`, `npm test`, `cargo test -q`, `dotnet test -v q`). Executes `.along/scripts/test.py` (or `.sh`, `.ps1`, `.bat`) with custom hooks taking absolute precedence over auto-detection.
- **Architectural Rationale**:
  - *Token Hygiene via Quiet Flags*: Suppresses massive verbose test logs in agent prompts, emitting clean summary counts (pass/fail) to conserve context budget.
- **Invocation Triggers**:
  - *Explicit*: `/along-test`, `along test` (fallback: `python ~/.along/bin/along_exec.py test`).
  - *Semantic / Automatic*: Triggered during every Reviewer step in `along-team`, before pre-commit in `along-commit`, and during `/along-wrap`.
- **Entities Operated On**: `.along/scripts/test.py` (and `.sh`, `.ps1`, `.bat`), test suites (`tests/`, `src/**/*.test.ts`).
- **Ecosystem Chaining**: Core quality gate for `along-team`, `along-commit`, and `along-version-bump`.

---

### `along-dev`
- **What it is**: Development server runner. Launches local dev servers or debug runners via `.along/scripts/dev.py` (or `.sh`, `.ps1`, `.bat`) or auto-detected runners (`npm run dev`, `cargo run`, `dotnet run`, `python main.py`).
- **Architectural Rationale**:
  - Provides a single standardized hook (`.along/scripts/dev.py`) for background daemon execution.
- **Invocation Triggers**:
  - *Explicit*: `/along-dev`, `along dev` (fallback: `python ~/.along/bin/along_exec.py dev`).
  - *Semantic / Automatic*: Triggered when the user requests *"Start local dev server"*, *"Run application locally"*.
- **Entities Operated On**: `.along/scripts/dev.py` (and `.sh`, `.ps1`, `.bat`).
- **Ecosystem Chaining**: Pairs with `along-dash` for local interactive debugging.

---

## 4. Quality Gates, Code Graph & Commit Integrity

### `along-commit`
- **What it is**: Smart, ASCII-clean Conventional Committer. Validates typography, binds commit messages to active `.along/` issues, and creates clean Git commits.
- **Architectural Rationale**:
  - *Typography & Non-ASCII Gate*: Scans repository text to block forbidden typographic characters (em-dash, smart curly quotes, non-breaking spaces, byte order marks) that corrupt Windows shell execution or AST parsers. It reports findings by file and line and aborts; it does not rewrite the tree unless `--fix-typography` is passed, and it never rewrites a file that is not valid UTF-8. See [ADR-2026-09-01--typography-rule-scope](./decisions/ADR-2026-09-01--typography-rule-scope.md).
  - *Issue Traceability*: Enforces issue slug references (`(refs #<slug>)` or `[<slug>]`) for 100% auditability.
- **Invocation Triggers**:
  - *Explicit*: `/along-commit -i <slug> -m "<message>" [--fix-typography]`, `along commit` (fallback: `python ~/.along/bin/along_exec.py commit`).
  - *Semantic / Automatic*: Triggered when completing a task or when prompted with *"Commit changes"*.
- **Entities Operated On**: Git staging index, `.along/ISSUES/`, active commit logs.
- **Ecosystem Chaining**: Precedes `/along-wrap`.

---

### `along-graph-check`
- **What it is**: AST call graph and code intelligence preflight engine. Performs health check, binary validation, and `.code-review-graph-ignore` audit for the `code-review-graph` AST engine.
- **Architectural Rationale**:
  - *Deterministic Blast Radius*: Prevents silent regression bugs by identifying all dependent callers across the codebase before code is merged.
  - *Graph-Ignore Filtering*: Enforces `.code-review-graph-ignore` to exclude `node_modules` and vendor directories, preventing graph database ballooning.
- **Invocation Triggers**:
  - *Explicit*: `/along-graph-check`, `along graph-check` (fallback: `python ~/.along/bin/along_exec.py graph-check`).
  - *Semantic / Automatic*: Triggered during Phase 4 (Reviewer) in `along-team` and before session wrap-up for non-trivial refactorings.
- **Entities Operated On**: `.code-review-graph-ignore`, AST symbol database.
- **Ecosystem Chaining**: Maps identified AST symbols directly into `along-kb-search` for Knowledge Base synchronization.

---

### `along-graph-sync`
- **What it is**: Code intelligence AST graph build and incremental synchronization engine. Connects to `code-review-graph` to index repository symbols, functions, classes, and call hierarchies.
- **Architectural Rationale**:
  - *Incremental Synchronization*: Updates only modified files by default, keeping the AST database current without long rebuild delays.
  - *Self-Healing Exclusions*: Automatically creates or verifies `.code-review-graph-ignore` with standard exclusions to prevent parser bloat from `node_modules` and build directories.
- **Invocation Triggers**:
  - *Explicit*: `/along-graph-sync`, `along graph-sync` (or `along graph-build`), `along graph-sync --full`.
  - *Semantic / Automatic*: Invoked during `along-init` (initial index), `along-update` (symbol refresh), and before blast-radius review in `along-wrap`.
- **Entities Operated On**: `.code-review-graph-ignore`, AST graph database.
- **Ecosystem Chaining**: Feeds the AST call graph used by `along-graph-impact` during `along-wrap` and `along-team`.

---

### `along-graph-impact`
- **What it is**: Semantic blast radius and affected execution flow analyzer. Queries the `code-review-graph` AST database to evaluate the downstream impact of planned or executed modifications.
- **Architectural Rationale**:
  - *Comprehensive Downstream Tracing*: Traces direct callers, callees, and impacted execution paths, eliminating blind spots when refactoring shared functions.
  - *Candidate Test Selection*: Pinpoints covering automated test files to guide targeted pre-commit verification.
  - *Documentation Mapping*: Directly maps affected symbols to Knowledge Base articles in `docs/topic--*.md`.
  - *Resilient Degradation*: Automatically degrades to static search if `code-review-graph` or `uvx` is offline, ensuring review gates are never skipped.
- **Invocation Triggers**:
  - *Explicit*: `/along-graph-impact <symbol|file>`, `along graph-impact <symbol|file>`, `along graph impact <symbol|file>`.
  - *Semantic / Automatic*: Invoked during `along-team` Phase 2 (Architect) and Phase 4 (Reviewer), and during `along-wrap` before session finalization.
- **Entities Operated On**: AST symbol graph, source files, `tests/`, `docs/topic--*.md`.
- **Ecosystem Chaining**: Uses the AST database built by `along-graph-sync` and provides input to `along-test` and `along-wrap`.

---

### `along-graph-arch`
- **What it is**: High-level architectural overview, modular community structure, and coupling hotspot analyzer using `code-review-graph`.
- **Architectural Rationale**:
  - *Community Boundary Analysis*: Groups codebase symbols into cohesive functional communities and evaluates cross-boundary dependency coupling.
  - *Hub Hotspot Detection*: Identifies high fan-in / high fan-out symbols carrying high architectural and refactoring risk.
  - *Bottleneck Bridge Identification*: Detects critical bridge nodes sitting on shortest execution paths across subsystems.
- **Invocation Triggers**:
  - *Explicit*: `/along-graph-arch`, `along graph-arch`, `along graph arch`.
  - *Semantic / Automatic*: Triggered before large refactorings or during architectural review gates in `along-team`.
- **Entities Operated On**: AST graph database, package structure, cross-community dependency graph.
- **Ecosystem Chaining**: Informs architectural decision-making in `.along/DECISIONS/` and `along-decision-sync`.

---

### `along-dep-scan`
- **What it is**: Hierarchical multi-project and submodule dependency scanner. Scans package manifests (`package.json`, `pyproject.toml`, `Cargo.toml`, `*.csproj`), custom hooks (`.along/scripts/dep_scan.py`), submodules, and symlinks for declared AI instructions and vendor rules.
- **Architectural Rationale**:
  - Extracts subproject constraints, custom ecosystem hooks, and vendor AI rules into `docs/topic--dependencies.md`, giving agents unified visibility into third-party constraints without manual file hunting.
- **Invocation Triggers**:
  - *Explicit*: `/along-dep-scan`, `along dep-scan` (fallback: `python ~/.along/bin/along_exec.py dep-scan`).
  - *Semantic / Automatic*: Triggered during `/along-init`, after dependency updates, or when adding a new Git submodule.
- **Entities Operated On**: `package.json`, `pyproject.toml`, `Cargo.toml`, `*.csproj`, `.along/scripts/dep_scan.py`, `docs/topic--dependencies.md`.
- **Ecosystem Chaining**: Feeds architectural constraints into `docs/topic--dependencies.md` and `along-kb-sync`.

---

## 5. Knowledge Base & LLM-Wiki Intelligence

### `along-kb-sync`
- **What it is**: Idempotent LLM-Wiki compiler, inbound link rewriter, and link integrity gate for `docs/`.
- **Architectural Rationale**:
  - *LLM-Wiki Paradigm*: Implements Andrej Karpathy's LLM-Wiki architecture in Python with a single runtime dependency (`ruamel.yaml`, for front-matter), resolved automatically by `uv`.
  - *Inbound Link Rewriter*: Recursively scans Markdown files and safely rewrites legacy internal paths (`.along/KB/...`, `.agents/KB/...`) to standard relative `docs/` paths only when target exists on disk, skipping code fences and unrelated numbered docs unless opted in.
  - *Link Integrity Gate*: In `--strict` mode, validates that every relative Markdown link physically resolves to an existing file on disk.
  - *In-Place Source Provenance & Drift Gate*: Reconciles raw notes, code, and specs in-place with `sources: [{path, hash}]` front-matter tracking, detecting drift via SHA-256 and guarding accidental reductions via the `--prune-intent` gate.
  - *Deterministic LLM Context Exports*: Non-destructively reconciles `llms.txt` and compiles `llms-full.txt` across `.well-known/` and context root locations for whole-project and subproject contexts.
- **Invocation Triggers**:
  - *Explicit*: `/along-kb-sync [--strict] [--prune-intent [REASON]] [--dry-run] [--migrate-numbered]`, `along kb-sync` (fallback: `python ~/.along/bin/along_exec.py kb-sync`).
  - *Semantic / Automatic*: Triggered during `/along-wrap`, after modifying documentation in `docs/`, or during protocol migration.
- **Entities Operated On**: `docs/*.md`, `docs/INDEX.md`, `llms.txt`, `llms-full.txt`, `.well-known/`, all repository Markdown files.
- **Ecosystem Chaining**: Compiles the Knowledge Base queried by `along-kb-search` and visualized by `along-dash`.

---

### `along-kb-search`
- **What it is**: Ultra-fast, token-efficient multi-scope search engine across Knowledge Base (`docs/`) and living project memory (`ISSUES/` including spikes, `DECISIONS.md`, `MILESTONES/`, `SESSIONS/`). Categories: `all`, `kb`, `issue`, `decision`, `milestone`, `session`.
- **Architectural Rationale**:
  - *Targeted Snippet Window Extraction*: Instead of reading whole multi-kilobyte documents into prompt context, retrieves concise word-boundary aligned snippet windows (typically under 150 tokens), verifiable via `--stats`.
  - *Multi-Tier Relevance Scoring & IDF Weighting*: Ranks results using word-boundary token matching, lightweight stemming, smoothed inverse document frequency (IDF), and exact phrase matching with AND semantics by default (`--any` for OR).
  - *Recommended, Not Enforced*: Agents SHOULD query `along kb-search` before grepping or reading whole files under `docs/` and `.along/` to save tokens. No gate blocks `grep_search` / `find_by_name` there (the former `fast_retrieval` gate was removed in `debt--gate-simplification`).
- **Invocation Triggers**:
  - *Explicit*: `/along-kb-search "<query>" [--category <cat>] [--any] [--prefix] [--stats]`, `along kb-search` (fallback: `python ~/.along/bin/along_exec.py kb-search`).
  - *Semantic / Automatic*: Recommended first step for agents when researching domain architecture, investigating existing decisions, or mapping blast radius.
- **Entities Operated On**: `docs/`, `.along/ISSUES/`, `.along/DECISIONS.md`, `.along/MILESTONES/`, `.along/SESSIONS/`.
- **Ecosystem Chaining**: Used by Scout and Supervisor in `along-team` during Phase 1 (Research).

---

## 6. Visual Analytics, History & Diagnostics

### `along-dash`
- **What it is**: Multi-mode executive dashboard and interactive Cytoscape DAG visualizer. Serves a FastAPI REST API and Server-Sent Events (SSE) stream with a modern reactive UI.
- **Architectural Rationale**:
  - *Autonomous Multi-Mode Architecture*: Runs in 3 decoupled modes via `scripts/along_dash.py`: CLI Mode, Interactive Web Mode (`http://127.0.0.1:8765`), and Static HTML Export (`--export`, untracked).
  - *Zero Setup Overhead*: Uses PEP 723 inline script metadata (`# /// script ...`) for instant zero-config execution.
- **Invocation Triggers**:
  - *Explicit*: `/along-dash [-w|--web] [-c|--cli] [-e|--export]`, `along dash` (fallback: `python ~/.along/bin/along_exec.py dash`).
  - *Semantic / Automatic*: Triggered when the user asks for a project status overview, dependency visualization, or sprint progress report.
- **Entities Operated On**: `.along/`, `docs/`.
- **Ecosystem Chaining**: Visualizes the entire entity DAG created by `along-team`, `along-issue-sync`, and `along-kb-sync`.

---

### `along-history-sync`
- **What it is**: Git history reconstruction engine. Reconciles `.along/` entities, closed issues, milestones, and session journals from historical Git commits, tags, and pull requests.
- **Architectural Rationale**:
  - Enables legacy repositories adopting Along to immediately gain full project memory and completed issue archives without manual retrospective data entry.
- **Invocation Triggers**:
  - *Explicit*: `/along-history-sync`, `along history-sync` (fallback: `python ~/.along/bin/along_exec.py history-sync`).
  - *Semantic / Automatic*: Triggered during initial onboarding on existing git repositories or after major branch rebases.
- **Entities Operated On**: Git commit log, `.along/ISSUES/done/`, `.along/SESSIONS/`, `.along/HISTORY.md`.
- **Ecosystem Chaining**: Reconstructs historical data visualized in `along-dash`.

---

### `along-feedback`
- **What it is**: Self-diagnostics, incident reporting, and maintainer feedback subsystem. Collects sanitized diagnostic logs, redacts PII and credentials, and dispatches feedback via GitHub Pull Request, Telegram, Webhook, or File export.
- **Architectural Rationale**:
  - *Zero-Leak Redaction*: Automatic regex-based redaction of user home paths, tokens, and credentials guarantees that sensitive data is never transmitted.
  - *Pluggable Transports*: Supports GitHub Pull Request creation (with automatic fork and browser web fallback), offline file export, direct Telegram bot notifications, or custom webhook endpoints.
  - *Explicit User Consent*: GitHub Pull Request creation requires explicit confirmation (`--yes`) before any network dispatch or browser interaction.
- **Invocation Triggers**:
  - *Explicit*: `/along-feedback`, `along feedback` (fallback: `python ~/.along/bin/along_exec.py feedback`), `along feedback send --channel github --title "<title>" --body-file <path> --yes`.
  - *Semantic / Automatic*: Triggered when an Along internal script encounters unhandled exceptions or when prompted with *"Report bug in Along"* or *"Create feedback for Along"*.
- **Entities Operated On**: `~/.along/diagnostics/incidents/`, `~/.along/diagnostics/REPORT.md`, `.along/inbox/`.
- **Ecosystem Chaining**: Provides operational telemetry, user feedback loops, and continuous improvement for the Along protocol.

---

### `along-wrap`
- **What it is**: Unified session and stage wrap-up orchestrator. Executes the mandatory completion checklist: runs tests, checks documentation blast radius, moves finished issues to `done/`, reconciles `ISSUES.md`, appends to `HISTORY.md`, compiles engineering provenance, and purges session blackboards.
- **Architectural Rationale**:
  - *Consolidated Lifecycle & Engineering Provenance*: Eliminates fragmentation between session wrap-up and stage wrap-up, providing a single deterministic checklist. For multi-step tasks or `along-team` runs, writes the blackboard into the session log as a `## Blackboard Record` (step table, research, execution trace, notes, reviews); attributed paths go to the `files:` front matter and the approved plan is not copied.
  - *Automated Garbage Collection*: Completely cleans up ephemeral blackboard directories (`.along/.session/<slug>/`), ensuring zero leftover state files.
- **Invocation Triggers**:
  - *Explicit*: `/along-wrap`, `along wrap` (fallback: `python ~/.along/bin/along_exec.py wrap`).
  - *Semantic / Automatic*: Triggered whenever a developer says *"I'm done for today"*, *"Wrap up session"*, or upon completing all steps in an issue.
- **Entities Operated On**: `.along/ISSUES/`, `.along/ISSUES/done/`, `.along/ISSUES.md`, `.along/SESSIONS/`, `.along/HISTORY.md`, `.along/.session/`.
- **Ecosystem Chaining**: Finalizes work executed by `along-team` and triggers `along-kb-sync` and `along-issue-sync`.

---

## Document: docs/topic--system-comparisons.md (System Comparisons & Alternative Architectural Paradigms)

# System Comparisons & Alternative Architectural Paradigms

## 1. Ecosystem Overview & Tool Comparison Matrix

AI engineering workflows employ a diverse range of tools to manage agent context, prompt specifications, and task progression. These approaches range from lightweight specification templates and terminal task trackers to editor-specific rules and comprehensive multi-agent context protocols:

- **GitHub spec-kit**: Specification-driven prompt scaffolding and structured specification templates for generating features.
- **Task Master / issue tracking CLIs**: Command-line issue and backlog tracking designed for agents or terminal users.
- **Beads / Kiro specs**: Task DAG dependency tracking (Beads) and modular constraint specifications (Kiro).
- **Native static instructions (`CLAUDE.md` / `AGENTS.md`)**: Baseline static markdown conventions loaded by agent harnesses at session start (e.g. Claude Code reading `CLAUDE.md`, Codex and Antigravity reading `AGENTS.md`).
- **Cursor rules (`.cursorrules` / `.cursor/rules/`)**: Editor-scoped prompt instructions and file-glob-matched rules for Cursor IDE.
- **ActDim Along**: Provider-agnostic context protocol embedding dual-tier memory (evergreen wiki + living governance), mechanical lifecycle gates, and zero-vector snippet retrieval across multiple agent platforms.

The following table evaluates these tools and paradigms objectively, detailing their primary scope, enforcement models, concurrency mechanisms, and core engineering trade-offs.

### Comparative Feature & Trade-Off Matrix

| Tool / Paradigm | Primary Scope | Enforcement Mechanism | Concurrency Model | Key Strengths | Engineering Trade-offs |
| :--- | :--- | :--- | :--- | :--- | :--- |
| **GitHub spec-kit** | Specification authoring and prompt expansion for spec-first feature design | Advisory prompt guidance via Markdown specification templates | Relies on standard Git PR workflows and manual merge resolution | Clear requirement definition upfront; human-readable templates; straightforward integration into GitHub-centric workflows | Prompt-based only without active lifecycle interception (`PreToolUse`, `Stop`); lacks transactional task DAG or live session state tracking; no automated cross-session snippet retrieval |
| **Task Master / issue tracking CLIs** | Terminal-based task and issue tracking for agent workflows | CLI command invocations; status progression (`open` -> `in-progress` -> `done`) | Centralized local database or flat file tracking | Structured command-line issue management; lightweight task metadata; easy to script in CI or shell workflows | Task management only without architectural wiki (`docs/`), ADR governance, or AST symbol validation; lacks agent lifecycle hook interception and multi-provider context protocol management |
| **Beads / Kiro specs** | Task DAG dependency tracking (Beads) and structured constraint specifications (Kiro) | CLI or file status tracking; DAG edge resolution; advisory prompt injection | Local file or database storage; file-level versioning | Explicit task dependency graphs; structured blocker tracking; programmatic task progression | Task graph management only without architectural LLM-Wiki (`docs/`), ADR governance, or code AST validation; lacks agent lifecycle hook interception and multi-provider context protocol management |
| **Native static instructions (`CLAUDE.md` / `AGENTS.md`)** | Baseline agent instructions, repository conventions, and command definitions | Advisory system prompt injection by agent harnesses at startup | Single static file tracked in Git | Zero runtime dependencies; native static loading by major agent harnesses (Claude Code via `CLAUDE.md`, Codex and Antigravity via `AGENTS.md`); simple to author and maintain | Subject to soft prompt decay and context displacement as conversation length grows; static files cannot dynamically track task progression, session state, or multi-agent worktrees; risks token bloat when instructions or project guidelines grow large |
| **Cursor rules (`.cursorrules` / `.cursor/rules/`)** | Editor-scoped guidelines and pattern-matched rules for Cursor IDE | Advisory context injection scoped to file globs within the editor | File-level versioning in repository | Tailored developer experience within Cursor; glob pattern scoping to target specific file types or subdirectories; low barrier to entry | Tied to a specific editor environment; advisory prompt augmentation without tool-level mechanical execution interception or git-level enforcement; lacks persistent session provenance, ADR compilation, or provider-agnostic CLI tooling |
| **ActDim Along** | Provider-agnostic agent-context protocol, dual-tier memory (evergreen wiki + living governance), mechanical gates, and execution skills | Multi-layer enforcement: mechanical tool-level interception (`PreToolUse`, `Stop`) where hooks are supported, backed by opt-in git hooks and CI quality gates | Git worktree workspace isolation, atomic issue files, and Git union merge drivers (`merge=union`) for append-only logs | Provider-agnostic across Claude Code, Antigravity, Codex, OpenCode; mechanical quality gates; dual-tier memory with bounded snippet search (<= 150 words) avoiding full-file ingestion; full engineering provenance in session logs | Higher initial conceptual complexity and larger repository footprint than single static instruction files; requires Python 3.10+ and standard toolchain for CLI engines; runtime tool interception requires agent environments that expose lifecycle hooks (advisory elsewhere) |

---

## 2. Paradigm 1: Continuous Conversational Chat Scraping & Neural System-1 Controllers

### Core Mechanism of the Alternative
Interception hooks (such as `Stop` hooks) spy on raw turn-by-turn chat transcripts between the developer and the AI assistant. An external cloud classification API (e.g. TypeSafe Jev) or a local BERT-sized neural model (e.g. Laya) evaluates each turn with probabilistic classifiers (nouls) to guess whether a sentence represents an architectural decision, constraint, or bug. Saved lines are appended to a flat markdown file (e.g. `JEVMEM.md`).

More recent academic proposals extend this by arguing for a dual-process cognitive architecture (System-1 vs. System-2): a lightweight non-autoregressive neural model acts as a "System-1" controller that manages multi-relational memory graphs, decides edge insertion, allocates retrieval budgets, and determines adaptive stopping criteria, while leaving only final answer synthesis to the heavy "System-2" LLM. Such systems report impressive numbers on conversational benchmarks (e.g. LoCoMo).

### What Along Adopted / Evaluated
- **Secret Scrubbing in Diagnostic Logs**: The practice of aggressively redacting sensitive credential shapes (API keys, tokens, connection passwords) before any diagnostic logs or audit trails are written to disk. Along adopted this pattern by connecting its `alongkit.telemetry.redactor` engine to lifecycle hook audit records.
- **The Principle of Separating Reflexive Control from Deliberative Reasoning**: Offloading high-frequency checks and filtering away from expensive autoregressive LLM token generation. Along applies this principle rigorously, but through deterministic mechanical software gates rather than probabilistic neural models.

### What Along Critically Rejected and Why
1. **Conversational Eavesdropping (High False-Positive Noise)**:
   - In real-world software engineering, developers frequently discuss throwaway debug workarounds, speculative ideas, and rejected prototypes. Treating raw chat text as long-term memory inevitably pollutes context with noise and half-truths.
2. **Monolithic Flat Files (`JEVMEM.md`) and Mutable Dynamic Graphs**:
   - Storing all memories in a single flat file or maintaining an evolving, consolidated graph database creates chronic Git merge conflicts in team workflows and multi-agent branches.
3. **Heavy Runtimes and Cloud Vendor Lock-in**:
   - Forcing a hard dependency on a closed SaaS classification API, or requiring local deployment of heavy 421M parameter PyTorch models, introduces massive environment fragility, GPU/CUDA overhead, and high token costs.
4. **The "Neural System-1" Latency and Drift Trap**:
   - Academic architectures report ~0.93 seconds per query as "fast" compared to pure autoregressive LLM memory agents (which take 2-30 seconds). Raw latency is not the deciding factor: a cold `along kb-search` call is of the same order (corpus load plus a ~0.25 s in-memory query, see `scripts/bench_kb_search.py`). The difference is that every ranking step is deterministic and inspectable, with no model inference or GPU in the loop. Neural probabilistic memory consolidation, by contrast, causes memory drift, where critical constraints can be silently de-prioritized by neural link weights.
5. **The Chatbot Benchmark Fallacy (LoCoMo vs. Software Engineering)**:
   - Success on conversational QA benchmarks (such as LoCoMo) measures trivia recall across long character chats ("when did character X buy item Y?"). It completely fails to reflect the core constraints of software engineering: Git multi-branch concurrency, AST symbol call graphs, compilation invariants, and mechanical gate enforcement.

### The Along Engineering Advantage: Conscious Project Governance & Mechanical System-1
Along replaces passive chat scraping and neural controllers with **intentional state capture and mechanical deterministic control**:
- Tasks are tracked in machine-parseable DAG files (`.along/ISSUES/<type>--<slug>.md`).
- Architectural choices are deliberately recorded as modular ADRs (`.along/DECISIONS/ADR-*.md`).
- Verified technical facts live in the LLM-Wiki (`docs/topic--*.md`).
- **Mechanical System-1**: High-frequency reflexive decisions (link integrity, clean typography, test execution, compilation, AST boundary checks) are executed by deterministic mechanical gates (`along_hook.py`) and zero-vector lexical search (`along-kb-search`), reserving the LLM strictly as System-2 for deep architectural reasoning and code generation.
- Context remains 100% signal, zero noise, with full rationale and trade-offs preserved.

---

## 3. Paradigm 2: External Vector Databases & Opaque RAG

### Core Mechanism of the Alternative
Repository documentation and code are processed through blind token chunkers (e.g. 512 tokens with 50-token overlap), passed through embedding models, and stored in vector databases (Chroma, Pinecone, Weaviate, FAISS). Agents query these indexes via cosine similarity.

### What Along Adopted / Evaluated
- **The LLM-Wiki Idea, Made Deterministic**: Along adopted the core idea of Andrej Karpathy's LLM-Wiki, an interconnected, human-readable repository wiki (`docs/`) that AI agents navigate. It implements it as authored, topic-based documentation (IBM DITA, Diataxis) with deterministic `llms.txt` and `llms-full.txt` catalogs, not as an LLM-recompiled secondary wiki. See [Topic-Based Knowledge Base Architecture & Paradigm](./topic--llm-wiki-architecture.md) for why the naive LLM-Wiki model was rejected.

### What Along Critically Rejected and Why
1. **Destruction of Syntax and AST Boundaries**:
   - Arbitrary token chunking slices functions in half, severs method signatures from docstrings, and breaks YAML front-matter headers, causing models to hallucinate corrupt API interfaces.
2. **Opaque and Non-Versioned State**:
   - Vector databases cannot be inspected in a Git diff, cannot be reviewed in Pull Requests, and drift out of sync when developers switch Git branches.
3. **Heavy Native C++ / Rust Dependencies**:
   - Vector libraries require compilation of native binary extensions (`hnswlib`, `onnxruntime`, C++ build tools), causing constant installation failures on developer machines (especially Windows).

### The Along Engineering Advantage: Zero-Vector In-Repo Intelligence
Along implemented **Zero-Vector Retrieval** (`along-kb-search`):
- Operates on pure standard library Python with smoothed TF-IDF scoring and word-boundary token matching.
- Delivers bounded snippets (< 150 tokens) directly to agent prompts.
- Reduces exploration context consumption by extracting bounded snippets (< 150 tokens) rather than loading complete documents, with zero vector DBs, zero cloud dependencies, and zero background daemon processes (benchmarked via [scripts/bench_kb_search.py](../scripts/bench_kb_search.py)).
- Maintains in-place SHA-256 provenance hashes (`sources: [{path, hash}]`) in markdown headers to detect source drift.

---

## 4. Paradigm 3: Editor-Locked Runtime Interceptors

### Core Mechanism of the Alternative
Standalone extension scripts or proxy daemons (e.g. Harmonist-style) that intercept tool calls specifically within a single IDE or editor (such as Cursor).

### What Along Adopted / Evaluated
- **Mechanical Runtime Interception**: The insight that passive prose instructions in markdown files inevitably suffer from "soft prompt decay" as context expands. Deterministic programmatic gates must intercept agent tool execution at the harness boundary.

### What Along Critically Rejected and Why
1. **Single-Editor Confinement**:
   - Building tooling tied to a single IDE isolates team members who use different tools.
2. **Probabilistic Guardrail Checks**:
   - Running tool arguments through an LLM during `PreToolUse` introduces 300 ms to 4,000 ms of latency per step, risks network failure, and produces probabilistic false blocks on valid refactors.

### The Along Engineering Advantage: Universal Multi-Runtime Dispatcher
Along engineered an open, provider-agnostic lifecycle engine:
- A universal CLI dispatcher (`along_hook.py`) with native adapters for Google Antigravity, Claude Code, OpenAI Codex, and OpenCode (`GenericCliAdapter`).
- Deterministic mechanical gates (`TypographyGate`, `ProjectionProtectionGate`, `CliSafetyGate`, `CircuitBreaker`).
- A declarative YAML gate engine (`default_gates.yaml`) backed by machine-checked bi-directional traceability (`along hook verify`).

---

## 5. Paradigm 4: External Agentic Telemetry & Logging Servers

### Core Mechanism of the Alternative
Sending agent execution logs, prompt histories, and tool invocation traces to closed, proprietary cloud monitoring services (e.g. Atlas-style external loggers).

### What Along Adopted / Evaluated
- **Structured Agent Execution Observability**: The necessity of capturing rich diagnostic traces, execution latencies, token consumption, and failure loops for post-run analysis.

### What Along Critically Rejected and Why
- Sending internal proprietary source code, shell execution commands, and tool payloads to closed cloud logging servers poses severe intellectual property and security risks.

### The Along Engineering Advantage: Standardized Local Agent Run Protocol (ARP/AEP)
Along established an open, in-repo observability standard:
- Built strictly on OpenTelemetry and OpenInference standards (`scripts/alongkit/telemetry/`).
- Local Write-Ahead Log (WAL) spooling (`spool.py`) with offline buffering in `.along/telemetry/`.
- Automatic PII and credential scrubbing (`redactor.py`) ensuring no API keys or secrets leak into traces.
- Optional asynchronous offloading to any standard OTLP-compatible backend.

---

## 6. Paradigm 5: External Graph Orchestration Frameworks

### Core Mechanism of the Alternative
Using external DAG workflow engines or heavy graph coordination libraries (e.g. Knot-style frameworks) to manage agent task states.

### What Along Critically Rejected and Why
- External workflow engines impose proprietary serialization formats, database requirements, and execution runtimes that live outside Git version control.

### The Along Engineering Advantage: Git-Native Decentralized Entities
Along anchors all coordination directly in the repository filesystem:
- Tasks are plain markdown files with YAML front-matter (`.along/ISSUES/`) linked via explicit keys (`blocked_by: [type--slug]`).
- Decisions are modular date-slug ADRs (`.along/DECISIONS/ADR-YYYY-MM-DD--<slug>.md`).
- Multi-branch concurrency is guaranteed by Git union merge drivers (`merge=union`) on append-only files and atomic single-file mutations.
- Multi-agent coordination uses an ephemeral session blackboard (`.along/.session/<slug>/`) and Git worktree isolation (`along worktree`).

---

## 7. Paradigm 6: TypeScript / Bun Heavy Runtimes for Protocol Tooling

### Core Mechanism of the Alternative
Implementing repository automation, hooks, and CLI tools in TypeScript powered by modern JavaScript runtimes like Bun (e.g. Oh-My-OpenAgent-style).

### What Along Evaluated and Rejected
- While TypeScript provides excellent typing, requiring developers to install Node.js, Bun, or NPM in non-JavaScript repositories (Python, .NET, Go, Rust, C++) introduces immediate environment friction.
- Furthermore, runtime execution of alternative engines on Windows environments frequently presents stability and subprocess piping challenges.

### The Along Engineering Advantage: Zero-Install Hermetic Python
Along standardizes on Python with automated PEP 723 dependency delivery:
- Standard library core with `alongkit`.
- Dependency bootstrapping via `uv` runs in milliseconds in isolated cache directories without system-wide package installations.
- Universal polyglot lifecycle hooks (`.along/scripts/` in Python, PowerShell, Bash, or Batch).

---

## 8. Paradigm 7: Conversational History Accumulation vs. Explicit Execution State (Skill State Pattern)

### Core Mechanism of the Alternative: Three Execution Models Contrasted
Modern agent runtimes and research architectures operate across three fundamentally distinct execution architectures:

1. **Append-Only Conversational History (ReAct, LangGraph with Transcripts, MemGPT)**:
   - Every intermediate reasoning step, action payload, and raw environment observation is continuously appended to an ever-growing prompt transcript.
   - Over extended task horizons (T > 50-200 turns), this causes quadratic token consumption \(O(T^2)\), prompt bloating, severe context pollution, and catastrophic attention drag.

2. **Pure Ephemeral State Transition (Skill State Pattern)**:
   - Replaces conversational transcripts with an explicit, mutable execution state \(\Sigma_t\).
   - At each turn, the model receives only the immutable procedural specification \(P\), the current structured state \(\Sigma_t\), and the latest distilled observation \(O_t\).
   - Intermediate reasoning (Chain-of-Thought) and historical observations are discarded immediately after producing a validated state patch \(\Delta \Sigma_t\), achieving a bounded \(O(1)\) prompt footprint and linear \(O(T)\) cumulative token complexity.

3. **Along's Dual-Tier State & Provenance Architecture**:
   - Reconciles the execution efficiency of ephemeral clean-turn worker loops with the engineering necessity of persistent historical auditability.
   - Operational Tier isolates subagent step loops with bounded state snapshots and distilled observations, while Provenance Tier anchors immutable plans, ADRs, and session records into Git version control.

### What Along Adopted / Evaluated
- **Bounded Prompt Footprints & Linear Token Scaling**: Discarding runaway conversational histories in subagent worker loops allows prompt token costs to scale linearly \(O(T)\) rather than quadratically \(O(T^2)\). Along bounds context consumption while executing autonomous multi-turn tasks.
- **Observation Distillation**: Background telemetry, system chatter, and verbose passing test outputs cause severe attention drag. Along integrates observation distillation into CLI runners (`along test`, `along build`, `alongkit.proc.run_capture`) to filter noisy subprocess telemetry and return bounded, high-signal results.
- **Ephemeral Reasoning Discard in Worker Retry Loops**: In `along-team`, worker retries in `[Fix Loop]` discard intermediate failed conversational reasoning traces to prevent error inertia and hallucinated repetitive failures, while delivering the reviewer's exact failure diagnostics (assertion, error trace, and diff) to the subsequent attempt.
- **Deterministic Runtime Merge Operator with Null-Deletion Semantics**: In `alongkit.session` (`along scratch update`), Along adopts structured state merging where key deletion is expressed via `null` values, and schema validation runs deterministically in the Python runtime.

### What Along Critically Rejected and Why
1. **The "Sufficient Statistic" Trap / Lost History**:
   - Discarding all prior reasoning and historical observations assumes that every piece of information relevant to future actions can be recognized and projected into a structured JSON state immediately upon receipt.
   - In complex software engineering (compilation bugs, race conditions, edge-case debugging), an agent often notices an obscure detail whose critical relevance only becomes apparent 10 steps later. If intermediate reasoning and logs are completely wiped out, the agent is blinded and cannot trace the root cause.
2. **State Corruption on Pure LLM Generation**:
   - Offloading critical state tracking purely to LLM generation without runtime validation is error-prone, as models can accidentally omit or overwrite keys when producing state patches. Along pairs structured state schemas with deterministic Python runtime validation.
3. **Destruction of Engineering Provenance**:
   - Erasing Chain-of-Thought reasoning traces eliminates the audit trail. In Along, engineering provenance (`ADR-2026-09-06--engineering-provenance`) requires that the baseline plan, execution loop trace, and gate verification manifest survive into permanent repository memory (`.along/SESSIONS/`) for code reviews and post-mortems.
4. **Single-Agent Simplification vs. Multi-Agent Concurrency**:
   - A single mutable JSON state dictionary does not scale to multi-agent collaboration with parallel branches and worktrees without distributed concurrency control. Along anchors concurrency in Git worktrees and atomic issue files rather than a single in-memory state lock.

### The Along Engineering Advantage: Dual-Tier State & Provenance Architecture
Along reconciles the tension between token efficiency and historical traceability through a two-tier architecture:
- **Operational Tier (Clean-Turn Ephemeral Execution)**: Subagents and worker loops operate with distilled observations and bounded state snapshots (`.along/.session/<slug>/state.json`), achieving flat token footprints and zero-step error recovery.
- **Provenance Tier (Git-Grounded Repository Memory)**: High-level architectural decisions are committed to modular ADRs (`.along/DECISIONS/`), task requirements are tracked in DAG issues (`.along/ISSUES/`), and execution traces are compiled asynchronously into session records (`.along/SESSIONS/`).

---

## 9. Master Architectural Advantage Matrix

| Core Architectural Metric | Alternative Paradigms (Scrapers, Vector DBs, Cloud Memories) | ActDim Along Engineering Model |
| :--- | :--- | :--- |
| **System Scope** | Point solutions (isolated chat scrapers or vector wrappers). | Unified Context & Governance OS (Wiki + Issues + ADRs + Gates + Worktrees). |
| **Memory Signal Quality** | Low. Conversational noise, temporary hacks, speculative chat. | High. Vetted architectural ADRs, active DAG issues, and curated Wiki topics. |
| **Retrieval Footprint** | Heavy. External vector DBs, dense embeddings, cloud RPCs. | Zero-Vector. Pure Python TF-IDF snippet retrieval (bounded <= 150 words, benchmarked in scripts/bench_kb_search.py). |
| **Runtime Dependencies** | PyTorch, CUDA, Docker, C++ extensions, or proprietary SaaS. | Standard Python standard library + uv. Zero external services. |
| **Lifecycle Guardrails** | Soft prompts or slow probabilistic neural scoring (300ms - 4s). | Deterministic mechanical gates with minimal process overhead. |
| **Git Concurrency** | High conflict risk on shared flat files (`JEVMEM.md`). | Minimizes merge conflicts via modular date-slug files and union merges. |
| **Offline Independence** | Requires network connection to cloud APIs or heavy local GPU. | 100% offline-first, hermetic, and provider-agnostic. |
| **AST Symbol Verification** | None. Blind token chunking breaks code symbol boundaries. | AST-grounded via code-review-graph integration and link integrity gates. |
| **Cognitive Control (System-1 / System-2)** | Neural System-1 (probabilistic encoder / cloud API, ~1s latency, graph weight drift). | Mechanical System-1 (deterministic gates, AST graph, local lexical TF-IDF) + System-2 LLM. |
| **Execution History & Memory Model** | Append-only chat bloat \(O(T^2)\) (ReAct) or blind state wiping (ephemeral state wiping without provenance). | Dual-Tier: Clean-Turn Worker Loops + Ephemeral Blackboard + Git Provenance. |

---

## 10. Related Architectural Specifications

- [LLM-Wiki Knowledge Base Architecture & Paradigm](./topic--llm-wiki-architecture.md): Mechanics of Along's token-efficient knowledge base.
- [Runtime Lifecycle Hooks & Mechanical Gates](./topic--runtime-hooks-and-gates.md): Deterministic runtime interception vs. probabilistic rules.
- [Agent Run Protocol (ARP/AEP) & OpenTelemetry Engine](./topic--agent-run-protocol.md): Local observability and sensitive data redaction.
- [System Architecture & Flow](./topic--architecture.md): Topological overview of provider flow and context boundaries.

---

## Document: docs/topic--troubleshooting.md (Troubleshooting & Developer Diagnostics Guide)

# Troubleshooting & Developer Diagnostics Guide

Practical guide for diagnosing issues, discovering internal APIs, and understanding runtime isolation in Along repositories.

---

## 1. Internal Packaging Architecture

Along is architected as a lightweight, provider-agnostic protocol and agent toolkit. To avoid system pollution and package collisions, Along intentionally isolates its internal engines:

- **Internal Engine Package (`alongkit`)**: The core logic resides in `scripts/alongkit/`. It is **not** installed globally into the host operating system Python or user site-packages.
- **Script Wrappers & Entry Points (`scripts/`)**: User-facing and agent-facing commands (such as `scripts/along_commit.py`, `scripts/along_kb_sync.py`, and `scripts/along_exec.py`) reside in `scripts/`. They dynamically bootstrap access to `alongkit` via `scripts/alongkit/bootstrap.py` or the command router.
- **PEP 723 Inline Dependency Isolation**: Individual scripts declare their external dependencies inline using PEP 723 metadata blocks:
  ```python
  # /// script
  # requires-python = ">=3.10"
  # dependencies = [
  #     "ruamel.yaml>=0.18.0",
  # ]
  # ///
  ```
- **Hermetic `uv` Runner**: Along invokes scripts and test runners through `uv` (or `.along/scripts/test.py`), automatically resolving inline dependencies into isolated ephemeral environments without requiring global `pip install` modifications.

---

## 2. The Anti-Pattern: Ad-Hoc Shell Code Probing

When encountering a test regression or exploring internal functions, agents sometimes attempt exploratory one-liners in the shell:

```bash
# ANTI-PATTERN: DO NOT USE
python -c "import alongkit; print(dir(alongkit))"
python -c "from alongkit import rules; print(rules.__file__)"
```

### Why Exploratory `python -c` Fails

1. **Uninstalled Modules**: Because `alongkit` is not installed globally, standard Python invocations outside the project runner fail with `ModuleNotFoundError: No module named 'alongkit'`.
2. **Missing Inline Dependencies**: Standalone Python invocations bypass the PEP 723 / `uv` dependency wrapper, causing `ImportError` on third-party libraries (e.g. `ruamel.yaml`).
3. **Misleading Error Cascades**: The resulting error traces reflect the un-isolated execution environment rather than any actual codebase bug. This frequently misleads agents into attempting unnecessary package installations or corrupting local configurations.
4. **Violation of CLI Safety**: Running inline code via shell strings triggers Along's `cli_safety` warning: code belongs in files rather than inline strings.

### CLI Black-Box Invariance

Agents must treat the Along CLI and development tools as strict opaque black-box executables:
- **No Engine Code Probing in Consumer Repositories**: Reading Along engine source code (`.along/bin/*.py`, `~/.along/bin/`, `alongkit/**`, `along_*.py`) to inspect internals, arguments, or private data structures is strictly forbidden unless actively working on the Along repository itself.
- **Contract-Based Discovery**: Always use `along <command> --help` or official documentation in `docs/`.
- **Immediate Error Reporting**: If an Along command returns an error or fails validation, report the exact CLI error output to the user immediately. Do not attempt to reverse-engineer or debug the Along engine internals.

---

## 3. Recommended Workflows for API Discovery

Instead of ad-hoc shell probing, developers and agents should use the following structured workflows:

### A. Static File Inspection

Examine source files directly using agent file tools or standard text search:
- **Inspect Definitions**: Use `view_file` to read classes, function signatures, docstrings, and type hints directly in `scripts/alongkit/`.
- **Search Symbol References**: Use `grep_search` or `find_by_name` across `scripts/alongkit/` and `scripts/` to see how functions are called across the codebase.

### B. AST & Blast Radius Analysis

Use Along's built-in graph intelligence commands to inspect callers, callees, and dependencies:
```bash
# Determine callers, flows, and impact for a symbol or file
along graph-impact <symbol-or-file>

# Inspect architectural coupling hotspots and bridges
along graph-arch

# Update or synchronize code-review-graph AST database
along graph-sync
```

### C. Official CLI Subcommands & Help

Inspect supported commands, options, and arguments using the built-in router:
```bash
# Global router overview
along --help

# Subcommand-specific help
along issue --help
along session --help
along scratch --help
along worktree --help
```

### D. Dedicated Hermetic Unit Tests

To verify behavior, test assumptions, or reproduce an issue, write a test in `tests/` using the hermetic test fixture:
```python
from tests import hermetic
import unittest

class TestFeature(unittest.TestCase):
    def test_behavior(self):
        with hermetic.repo_fixture() as repo:
            # Test behavior against a clean, throwaway fixture
            pass
```

Run the tests through the canonical test runner:
```bash
python .along/scripts/test.py tests.test_my_feature
```

---

## 4. Diagnostics & Health Verification

Along provides dedicated diagnostic commands to inspect repository health and isolate failures:

- **`along doctor`**: Validates repository structure, `.gitattributes`, ADR headers, and entity DAG consistency. Run `along doctor --entities` to check entity relationships.
- **`along feedback`**: Inspects self-diagnostics, captures incident logs, and provides feedback channels.
- **`along gates stats`**: Reviews gate execution counts and recorded bypass reasons, and lists "Repeated blocks" (the same gate holding the same target >= 3 times in one conversation, a loop).
- **`along lint`**: Runs the commit-time checks (typography, anti-stub, code fences, links, filenames, secrets) on demand.

### Gate Messages

- **`PLAN_REQUIRED [gate: require-plan-approval]: this turn changed <files> ...`** at the end of a turn: the turn changed repository files (by a file tool or a shell command) while the bound issue has no approved plan. Fix: ask the user, then either approve the plan (`EnterPlanMode` / `ExitPlanMode`, or `along plan approve --plan-file <path>` after the user's yes) or revert the listed files (`git checkout -- <files>`, delete new files). Files that were already dirty before the turn and unchanged are not listed.
  - **Compiled projections (`INDEX.md`, `ISSUES.md`, `DECISIONS.md`)**: Projections generated by `along kb-sync` or wrap pipelines at any workspace depth (including package-level index files such as `packages/<pkg>/docs/INDEX.md` carrying `protocol: along` and `type: index`) are compiled views and exempt from plan approval (`closeout.is_compiled_projection`). If a custom index file triggers `PLAN_REQUIRED`, ensure it carries standard front-matter metadata identifying it as a projection.
  - **Concurrent or external writes**: The Stop check isolates session-attributed writes (`turn_writes` from file tools or pending shell diff snapshots), preventing background processes or parallel sessions from causing false positives in the active turn.
  - **Acknowledging Stop denials**: Stop-time denials generate deterministic IDs (`d-stop-require-plan-approval-...`) recorded in the session activity trace. They can be inspected via `along gates denials` and acknowledged via `along gates ack <id> --note "..."` even after the issue session unbinds or wraps.
- **`DESTRUCTIVE [gate: destructive-command]: ...`** asks before a recursive delete, `git clean -f`, `git reset --hard` or `git push --force` (denied in autonomous sessions): the target is empty, unexpandable, outside the repository, the repository itself, or holds uncommitted work. Fix: follow the `Fix:` in the message - commit or stash the work first, or name a committed or ignored path inside the repository, or let the user run the command.

---

## 5. Related Topics

- [Setup & Developer Workflow](./topic--setup-and-workflow.md) - Installation and runner configuration
- [Along CLI Command Reference](./topic--cli-reference.md) - Complete CLI command reference
- [Runtime Lifecycle Hooks & Mechanical Gates](./topic--runtime-hooks-and-gates.md) - Gate enforcement and safety rules
