Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

chore: clean up repo root and move install scripts to scripts/install/

Tanner Kocherc265e7c27188
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
deleted file mode 100644
index 8692eb9d..00000000
--- a/.claude-plugin/marketplace.json
+++ /dev/null
@@ -1,13 +0,0 @@
-{
- "name": "ix-memory",
- "owner": {
- "name": "ix-infrastructure"
- },
- "plugins": [
- {
- "name": "ix-memory",
- "source": "./ix-plugin",
- "description": "Keeps the Ix graph current as Claude edits files, and front-runs Grep/Glob with graph-aware ix searches for token-efficient codebase understanding."
- }
- ]
-}
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 0a9b5a1b..a490fd32 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -168,10 +168,10 @@ jobs:
### Quick install (no repo needed)
```bash
# macOS / Linux
- curl -fsSL https://raw.githubusercontent.com/${{ github.repository }}/main/install.sh | bash
+ curl -fsSL https://raw.githubusercontent.com/${{ github.repository }}/main/scripts/install/install.sh | bash
# Windows (PowerShell)
- irm https://raw.githubusercontent.com/${{ github.repository }}/main/install.ps1 | iex
+ irm https://raw.githubusercontent.com/${{ github.repository }}/main/scripts/install/install.ps1 | iex
# Homebrew
brew tap ${{ github.repository_owner }}/ix https://github.com/${{ github.repository }}
diff --git a/.gitignore b/.gitignore
index 6f71b798..40463502 100644
--- a/.gitignore
+++ b/.gitignore
@@ -5,6 +5,7 @@ target/
*.jar
.DS_Store
.worktrees/
+node_modules/
ix-cli/node_modules/*
core-ingestion/node_modules/*
core-ingestion/dist/
diff --git a/AGENTS.md b/AGENTS.md
deleted file mode 100644
index 1fe58ccd..00000000
--- a/AGENTS.md
+++ /dev/null
@@ -1,245 +0,0 @@
-# Ix CLI — Agent Usage Guide
-
-This file tells automated agents (Codex, Claude, etc.) how to use the `ix` CLI effectively.
-
-## Interface
-
-Use the `ix` CLI exclusively. All commands support `--format json` for machine-readable output.
-
-## JSON Mode
-
-Always use `--format json` when chaining commands or parsing results programmatically.
-
-JSON output is strict — no text preamble or postamble. The output is a single JSON object.
-
-### Standard JSON fields
-
-| Field | Description |
-|-------|-------------|
-| `resolvedTarget` | The entity that was resolved (`{id, kind, name}`) |
-| `resolutionMode` | How the entity was resolved: `exact`, `preferred-kind`, `ambiguous`, `heuristic` |
-| `resultSource` | Where results came from: `graph`, `text`, `graph+text`, `heuristic` |
-| `results` | Array of result entities |
-| `summary` | Counts and aggregates |
-| `diagnostics` | Array of `{code, message}` explaining empty or weak results |
-| `warning` | Human-readable warning string |
-
-### Diagnostic codes
-
-| Code | Meaning |
-|------|---------|
-| `no_edges` | Entity resolved but no graph edges of the requested type exist |
-| `unresolved_call_target` | A callee/caller could not be resolved to a named entity |
-| `dangling_reference_filtered` | Some results had unresolvable IDs |
-| `ambiguous_resolution` | Multiple entities matched; specify `--kind` or use entity ID |
-| `text_fallback_used` | Graph had no results; text search was used instead |
-| `parser_gap_suspected` | Results suggest the parser did not fully index this area |
-| `unfiltered_search` | No `--kind` filter used; results may be broad |
-
-## Result entities
-
-Each result entity in `results` includes:
-
-- `name` — human-readable name (present when `resolved: true`)
-- `kind` — entity kind (function, method, class, etc.)
-- `id` — resolvable entity ID (present when `resolved: true`)
-- `resolved` — boolean indicating whether this entity can be followed up
-- `path` — source file path (when available)
-- `suggestedCommand` — a follow-up `ix` command to get more details
-- `rawId` — raw graph ID (only present when `resolved: false`)
-
-**Rule:** Only use `id` fields from entities where `resolved: true`. Do not attempt `ix entity <rawId>` on unresolved references.
-
-## Command routing
-
-### Recommended loop
-
-1. `ix briefing --format json` — resume session context
-2. `ix overview <target> --format json` — understand a component
-3. `ix impact <target> --format json` — check blast radius
-4. `ix rank / ix inventory` — find hotspots or list entities
-5. `ix plan next <id> --with-workflow` — get next task
-6. `ix tasks --status pending` — see all pending tasks across plans
-
-### Start here — high-level workflow commands
-
-These are the preferred entry points. Use them first; drop to low-level commands only when you need fine-grained control.
-
-```
-ix impact <target> --format json # Blast radius / dependency consequences
-ix rank --by <metric> --kind <kind> --top N --format json # Hotspot discovery
-ix overview <target> --format json # One-shot structural summary of a component
-ix inventory --kind <kind> --format json # Scoped entity listing
-ix goal create <statement> --format json # Create a project goal
-ix plan create <title> --goal <id> --format json # Create a plan
-ix plan next <plan-id> --format json # Next actionable task
-ix decide <title> --rationale <text> --affects <entities> --format json # Record linked decision
-ix briefing --format json # Session-scoped resume summary
-ix bug create "title" --affects Entity # Track a bug
-ix bugs --format json # List bugs
-ix bug show <id> --format json # Bug details
-```
-
-**When to use which:**
-- "What breaks if I change X?" → `ix impact X`
-- "What are the most important classes?" → `ix rank --by dependents --kind class --top 10`
-- "Tell me about UserService" → `ix overview UserService`
-- "List all functions in auth.py" → `ix inventory --kind function --path auth.py`
-- "List all classes" → `ix inventory --kind class`
-- "What are the most critical methods?" → `ix rank --by callers --kind method --top 10`
-- "What changed between rev 5 and 10?" → `ix diff 5 10 --summary`
-- "Show me all changes" → `ix diff 5 10 --full --format json`
-- "Are there architectural problems?" → `ix smells --format json`
-- "Which subsystems are unhealthy?" → `ix subsystems --format json`
-
-### Low-level structural primitives
-
-Useful for debugging, fine-grained inspection, or when high-level commands don't cover your case.
-
-#### Finding code
-```
-# Always use --kind with search to get bounded results
-ix search <term> --kind <kind> --format json --limit 10
-ix text <term> --format json --language python
-ix locate <symbol> --format json
-ix read <file:lines>
-```
-
-#### Understanding entities
-```
-ix explain <symbol> --format json
-ix entity <id> --format json
-```
-
-#### Navigating relationships
-```
-ix callers <symbol> --format json
-ix callees <symbol> --format json
-ix contains <symbol> --format json
-ix imports <symbol> --format json
-ix imported-by <symbol> --format json
-ix depends <symbol> --format json
-```
-
-### Architecture analysis
-```
-ix smells --format json # Detect orphan files, god modules, weak components
-ix smells --list --format json # List previously stored smell claims
-ix smells --god-module-chunks 15 --god-module-fan 10 # Custom thresholds
-ix subsystems --format json # Score subsystems by health (0–1)
-ix subsystems --list --format json # List stored scores
-ix subsystems --level 2 --format json # Filter to subsystem level
-```
-
-**When to use which:**
-- "Are there any architectural problems?" → `ix smells`
-- "Which subsystems are unhealthy?" → `ix subsystems --format json`
-- "Show me god modules" → `ix smells --format json | jq '.candidates[] | select(.smell == "has_smell.god_module")'`
-
-### Updating the graph
-```
-ix map --format json
-ix ingest --github owner/repo --format json --limit 50
-ix ingest --github owner/repo --since 2026-01-01 --format json
-```
-
-### History and decisions
-```
-ix decisions --format json
-ix history <id> --format json
-ix diff <from> <to> --summary --format json # Fast revision summary
-ix diff <from> <to> --format json # Full diff (default limit 100)
-ix diff <from> <to> --full --format json # All changes, no limit
-```
-
-### Planning & decisions (Pro)
-```
-# Goals
-ix goal create "GitHub ingestion pipeline" --format json
-ix goal show <id-or-name> --format json
-ix goal list --status active --format json
-ix goals --format json # shorthand list
-
-# Plans
-ix plan create "GitHub Ingestion" --goal <goal-id> --responds-to <bugId> --format json
-ix plan status <plan-id> --format json # task list + critical path + open bug count
-ix plan next <plan-id> --with-workflow --format json # next actionable task + workflow
-ix plan next <plan-id> --run-workflow --stage discover --format json # execute one stage
-ix plans --format json # shorthand list
-
-# Tasks
-ix plan task "API fetch layer" --plan <plan-id> --depends-on <task-id> --format json
-ix plan task "title" --plan <id> --workflow-staged '{"discover":["ix overview X"],"implement":["ix map"],"validate":["ix smells"]}' --format json
-ix plan task "title" --plan <id> --resolves <bugId> --format json
-ix tasks --format json # list all tasks across plans
-ix tasks --status pending --plan <plan-id> --format json
-ix task show <task-id> --with-workflow --format json
-ix task update <task-id> --status done --format json
-ix task update <task-id> --run-workflow implement --format json # run a workflow stage
-
-# Decisions
-ix decide "Use client-side patch" --rationale "..." --affects IngestionService --format json
-ix decide "Use JWT" --rationale "..." --responds-to <bugId> --format json
-
-# Bugs
-ix bug create "title" --severity high --affects Entity --format json
-ix bug update <id> --status resolved --format json
-ix bug show <id> --format json
-ix bugs --status open --format json
-
-# Misc
-ix patches --limit 20 --format json # recent graph patches
-ix truth add "Support 100k file repos"
-ix truth list --format json
-```
-
-### Workflows (Pro)
-Staged command sequences attached to tasks, plans, or decisions. Stages: `discover → implement → validate`. All commands must start with `ix ` — no arbitrary shell.
-```
-ix workflow attach task <id> --file workflow.json # attach from JSON file
-ix workflow show task <id> --format json # view attached workflow
-ix workflow validate task <id> --format json # check structure
-ix workflow run task <id> --stage implement --format json # execute one stage
-```
-
-**Workflow JSON format:**
-```json
-{
- "discover": ["ix overview AuthService", "ix impact AuthService"],
- "implement": ["ix map"],
- "validate": ["ix smells --format json"]
-}
-```
-
-**When to use which:**
-- "What work is planned?" → `ix plans --format json` then `ix plan status <id>`
-- "What should I do next?" → `ix plan next <id> --with-workflow`
-- "Execute the next task's discovery phase" → `ix plan next <id> --run-workflow --stage discover`
-- "Mark a task done" → `ix task update <id> --status done`
-- "Link a decision to a bug" → `ix decide "title" --rationale "..." --responds-to <bugId>`
-
-## Semantic boundaries
-
-- **decision** — a choice between alternatives, with rationale. Use `ix decide`.
-- **bug** — something broken, missing, or incorrect. Use `ix bug create`.
-- **task/plan** — intended work and sequencing. Use `ix plan` / `ix plan task`.
-
-## Chaining pattern
-
-1. Start broad: `ix overview MyClass --format json` or `ix impact MyClass --format json`
-2. If you need more detail, drill in: `ix explain MyClass --format json` or `ix entity <id> --format json`
-3. Navigate edges: `ix callers MyClass --format json`
-
-## Handling unresolved references
-
-When a result has `resolved: false`:
-- Do NOT follow the `rawId` with `ix entity`
-- Instead, use `ix text "<name>"` or `ix read <file>` to locate it
-- Check `suggestedCommand` if present
-
-## Handling empty results
-
-Check `diagnostics` in the JSON response:
-- `no_edges` — entity exists but has no edges of this type. Try `ix text` instead.
-- `text_fallback_used` — graph traversal was empty; text matches shown instead.
-- `ambiguous_resolution` — re-run with `--kind <kind>` to disambiguate.
diff --git a/docs/plans/2026-03-02-ix-memory-design.md b/docs/plans/2026-03-02-ix-memory-design.md
deleted file mode 100644
index 7fb9c40b..00000000
--- a/docs/plans/2026-03-02-ix-memory-design.md
+++ /dev/null
@@ -1,787 +0,0 @@
-# Ix Memory Layer — Architecture & Design
-
-## 0. Context and Goals
-
-We are building an **epistemic operating system for LLMs** — a persistent knowledge system where **patch events** (graph mutations) are the source of truth. The system stores a hierarchy of modules, files, and symbols connected by imports, calls, ownership, and dependency relationships, all with time and provenance.
-
-### Core Principles
-
-- **Patch/Event Log = Source of Truth.** Normal databases store whether something exists. Ours stores patches that state who added something, why, what it replaced, and when it happened.
-- **The human prompt defines an initial intent hypothesis, and truth emerges as the event log accumulates verified observations aligned with that intent.**
-- **Every fact has time (Temporal Truth).** We don't just say if X is true — we say when it was true, when it became true, when it stopped being true.
-- **Provenance-first.** Every fact carries full provenance: who asserted it, from what source, using what extractor, when.
-- **Computed confidence.** Confidence scores are derived from provenance signals, never manually assigned.
-- **Conflict detection.** When two patches disagree, the system surfaces the contradiction — it doesn't silently pick a winner.
-
-### What We're Building (Scope)
-
-| Component | Description |
-|---|---|
-| **Memory Layer** | The core engine: context assembly, ingestion, confidence scoring, conflict detection, versioning. Scala service with HTTP API. |
-| **CLI** | Command-line interface for humans. Thin client calling the Memory Layer API. |
-| **MCP Server** | Model Context Protocol server for LLM tool use (Claude Desktop, Cursor, etc.). Thin client calling the Memory Layer API. |
-| **SDK** | TypeScript + Python client libraries for developers. Includes prompt builder and BYOK LLM caller. |
-
-### What We're NOT Building (Out of Scope)
-
-- Custom database (no Rust GraphDB / RocksDB work). Using existing ArangoDB.
-- Our own API key / authentication system (for now).
-- LLM hosting — developers bring their own keys (BYOK).
-
----
-
-## 1. System Overview
-
-### 1.1 Full Architecture
-
-```
-╔═══════════════════════════════════════════════════════════════════════╗
-║ DEVELOPER'S WORLD ║
-║ ║
-║ Developer's App ║
-║ ├── Uses Ix SDK (@ix/client or ix-python) ║
-║ ├── Provides their own LLM API key (Claude, OpenAI, etc.) ║
-║ ├── ix.getContext(query) → structured claims (no LLM call) ║
-║ └── ix.query(query) → LLM answer with provenance (uses their key) ║
-║ ║
-╚═══════════════════╤═══════════════════════════════════════════════════╝
- │
- THREE ENTRY POINTS INTO Ix:
- ┌───────────────┼───────────────────────┐
- │ │ │
- ▼ ▼ ▼
-┌────────┐ ┌───────────┐ ┌──────────────────┐
-│ CLI │ │ MCP Server│ │ HTTP API (SDK) │
-│(term) │ │ (stdio) │ │ (REST) │
-│ │ │ │ │ │
-│ix query│ │ Claude │ │POST /v1/context │
-│ix ingest │ Desktop │ │POST /v1/ingest │
-│ix diff │ │ Cursor │ │POST /v1/diff │
-│ix hist │ │ │ │GET /v1/entity/:id│
-└───┬────┘ └─────┬─────┘ └────────┬─────────┘
- │ │ │
- └──────────────┼───────────────────┘
- │
- All three call the same thing:
- │
- ▼
-┌──────────────────────────────────────────────────────┐
-│ MEMORY LAYER (Scala) │
-│ Port 8090 │
-│ │
-│ ┌─────────────────────────────────────────────────┐ │
-│ │ Service Layer │ │
-│ │ ├── ContextService (query pipeline) │ │
-│ │ ├── IngestionService (parse + commit) │ │
-│ │ ├── VersionService (diff, history, staleness) │ │
-│ │ └── ConflictService (detect + resolve) │ │
-│ └──────────────────────┬──────────────────────────┘ │
-│ │ │
-│ ┌──────────────────────▼──────────────────────────┐ │
-│ │ Graph Access Layer │ │
-│ │ (GraphWriteApi + GraphQueryApi traits) │ │
-│ └──────────────────────┬──────────────────────────┘ │
-└─────────────────────────┼────────────────────────────┘
- │
- ▼
- ┌──────────────┐
- │ ArangoDB │
- │ (8529) │
- └──────────────┘
-```
-
-### 1.2 Where the LLM API Key Lives
-
-The LLM API key is **BYOK (Bring Your Own Key)**. It never touches the Ix server.
-
-```
-Developer's Machine / App Ix Infrastructure
-═══════════════════════════ ═══════════════════
-
- LLM API Key lives HERE ──┐
- │ ┌── Ix Memory Layer
- Ix SDK ───────────────────┤ │ (NO LLM key)
- │ │ │ │
- ├─ getContext() ────────│── HTTP ──│───→ │── queries DB
- │ (no key needed) │ │ │
- ├─ query() ─────────────┤ │ │
- │ │ │ │ │
- │ ├─ getContext()──────│── HTTP ──│───→ │── queries DB
- │ │ │ │ │
- │ └─ call LLM ────────│── HTTPS──│───→ Claude/OpenAI
- │ (key used HERE, │ │ (LLM provider)
- │ never sent to Ix) │ │
- │ │ │
- └─ ingest() ────────────│── HTTP ──│───→ │── writes DB
-```
-
-### 1.3 Two Integration Patterns
-
-| Interface | Who controls the prompt | Truth enforced? | Use case |
-|---|---|---|---|
-| **MCP server** | The LLM (Claude Desktop, Cursor) | No — LLM can skip tool calls | Adding memory to existing tools |
-| **SDK (BYOK)** | Ix SDK (developer's app) | Yes — SDK injects context before every LLM call | Developers building apps with enforced memory |
-
----
-
-## 2. Patch / Event Log Model
-
-The event log is the source of truth. Every mutation is a patch with full provenance.
-
-### 2.1 GraphPatch (the atomic unit of truth)
-
-```
-{
- patch_id: "uuid-v7", // Unique, idempotency key
- tenant: "tenant_abc", // Isolation
- actor: "ci/tree-sitter", // WHO created this patch
- timestamp: "2026-03-02T...", // WHEN
- source: {
- uri: "billing.py", // FROM WHAT
- hash: "a1b2c3", // Content hash at time of observation
- extractor: "tree-sitter-python/1.0", // HOW it was extracted
- source_type: "code" // code|config|doc|inferred|human
- },
- base_rev: 42, // Optional: optimistic concurrency
- ops: [ // WHAT changed
- UpsertNode(id, kind, attrs),
- UpsertEdge(src, dst, predicate, attrs),
- DeleteNode(id),
- DeleteEdge(id),
- SetAttr(owner_id, key, value),
- DelAttr(owner_id, key),
- AssertClaim(entity_id, statement),
- RetractClaim(claim_id, reason)
- ],
- replaces: ["patch_id_old"], // What prior patches this supersedes
- intent: "Re-parsed billing.py after commit abc123" // WHY
-}
-```
-
-### 2.2 Traditional DB vs Ix Event Log
-
-```
-Traditional DB: Ix Event Log:
-═══════════════ ════════════
-
-retry_count = 3 Patch #1 (rev 1, 2026-01-15, actor: ci/parser)
- "retry_count = 3 observed in billing.py:45"
-(that's it. source: billing.py, hash: a1b2c3
- who set it? when?
- what was it before? Patch #2 (rev 7, 2026-02-01, actor: ci/parser)
- why? unknown.) "retry_count = 5 observed in README.md:22"
- source: README.md, hash: d4e5f6
-
- Patch #3 (rev 12, 2026-02-20, actor: human/riley)
- "retry_count = 3 confirmed by developer"
- source: manual assertion
-```
-
-The graph state at any revision is deterministically derivable from replaying the patch log up to that point.
-
----
-
-## 3. Data Model (Schema)
-
-### 3.1 Node Types (Kinds)
-
-**Structural Nodes** (from code/AST parsing):
-
-| Kind | Attributes |
-|---|---|
-| Module | name, path, language |
-| File | path, language, hash, size |
-| Class | name, file_path, line_start, line_end |
-| Function | name, signature, file_path, line_start, line_end |
-| Variable | name, type, scope |
-| Config | path, format |
-| ConfigEntry | key, value, type |
-| Service | name, port, protocol |
-| Endpoint | method, path, handler |
-
-**Knowledge Nodes** (from docs, comments, LLM extraction):
-
-| Kind | Attributes |
-|---|---|
-| Claim | statement, status (ACTIVE / STALE / RETRACTED) |
-| Decision | title, rationale, alternatives_considered |
-| ConflictSet | reason, status (OPEN / RESOLVED / DISMISSED), candidates[] |
-
-### 3.2 Common Node Fields
-
-Every node has:
-
-```
-{
- id: "uuid-v7",
- kind: "Function",
- tenant: "tenant_abc",
- attrs: { ... }, // Kind-specific attributes
- provenance: {
- source_uri: "billing.py",
- source_hash: "a1b2c3",
- extractor: "tree-sitter-python/1.0",
- source_type: "code",
- observed_at: "2026-03-01T10:00:00Z"
- },
- created_rev: 42, // MVCC: when created
- deleted_rev: null, // MVCC: when deleted (tombstone)
- created_at: "2026-03-01T...",
- updated_at: "2026-03-01T..."
-}
-```
-
-### 3.3 Edge Types (Predicates)
-
-**Structural Edges** (deterministic, from AST/parsing):
-
-| Predicate | From → To | Meaning |
-|---|---|---|
-| DEFINES | Module → Class/Function | "module defines function" |
-| CONTAINS | File → Class/Function | "file contains class" |
-| CALLS | Function → Function | "fn A calls fn B" |
-| IMPORTS | File → Module/File | "file imports module" |
-| DEPENDS_ON | Service → Service | "svc A depends on svc B" |
-| CONFIGURES | ConfigEntry → Service/Fn | "config entry configures svc" |
-| EXPOSES | Service → Endpoint | "service exposes endpoint" |
-| INHERITS | Class → Class | "class A extends class B" |
-| IMPLEMENTS | Class → Interface | "class implements interface" |
-
-**Knowledge Edges** (from LLM or human input):
-
-| Predicate | From → To | Meaning |
-|---|---|---|
-| HAS_CLAIM | Entity → Claim | "entity has this claim" |
-| SUPPORTS | Claim → Claim | "claim A supports claim B" |
-| CONTRADICTS | Claim → Claim | "claim A contradicts claim B" |
-| DECIDED_BY | Entity → Decision | "design decided by decision" |
-| MENTIONED_IN | Entity → File/Doc | "entity mentioned in doc" |
-| CHANGED_WITH | Entity → Entity | "these changed together" |
-| SAME_AS | Entity → Entity | "identity resolution" |
-| IN_CONFLICT | Claim → ConflictSet | "claim is part of conflict" |
-
-### 3.4 Common Edge Fields
-
-```
-{
- id: "uuid or derived from (src, dst, predicate)",
- src: "node_id",
- dst: "node_id",
- predicate: "CALLS",
- tenant: "tenant_abc",
- attrs: { weight?, metadata? },
- provenance: { ... }, // Same structure as node provenance
- created_rev: 42,
- deleted_rev: null
-}
-```
-
-### 3.5 MVCC Visibility Rule
-
-An entity is **visible at revision R** iff:
-
-```
-created_rev <= R AND (deleted_rev IS NULL OR R < deleted_rev)
-```
-
----
-
-## 4. Confidence Scoring Engine
-
-Confidence is **computed from provenance signals**, never manually assigned.
-
-### 4.1 Formula
-
-```
-confidence(claim) = clamp(0, 1,
- base_authority(source_type)
- × verification_multiplier(claim)
- × recency_multiplier(claim, latest_rev)
- × corroboration_multiplier(claim)
- × conflict_penalty(claim)
-)
-```
-
-### 4.2 Signal Definitions
-
-**Base Authority** (from source type — deterministic):
-
-| Source Type | Base Score | Why |
-|---|---|---|
-| Passing test | 0.95 | Verified by execution |
-| Code (AST-parsed) | 0.90 | The code IS the behavior |
-| Config file | 0.85 | Explicitly set values |
-| Schema/types | 0.85 | Compiler-enforced contracts |
-| Official spec/doc | 0.75 | Human-written, intended truth |
-| Commit message | 0.60 | Human intent, sometimes vague |
-| PR/issue comment | 0.50 | Discussion, not assertion |
-| LLM-inferred | 0.40 | Model guessed, not stated |
-| Chat/Slack | 0.35 | Informal, often stale |
-
-**Verification Multiplier:**
-
-| Verification State | Multiplier |
-|---|---|
-| Test passes that cover this | x 1.1 |
-| Human explicitly confirmed | x 1.1 |
-| Observed in running system | x 1.05 |
-| No verification | x 1.0 |
-| Test FAILS that covers this | x 0.3 |
-| Human explicitly denied | x 0.1 |
-
-**Recency Multiplier:**
-
-| Age (revisions since observed) | Multiplier |
-|---|---|
-| 0-5 revisions ago | x 1.0 |
-| 6-20 revisions ago | x 0.95 |
-| 21-50 revisions ago | x 0.85 |
-| 51-200 revisions ago | x 0.70 |
-| 200+ revisions ago | x 0.50 |
-
-Exception: if the source file hasn't changed since the observation, recency stays at x 1.0.
-
-**Corroboration Multiplier:**
-
-| Independent sources agreeing | Multiplier |
-|---|---|
-| 1 source (uncorroborated) | x 1.0 |
-| 2 sources agree | x 1.1 |
-| 3+ sources agree | x 1.15 |
-
-**Conflict Penalty:**
-
-| Conflict state | Multiplier |
-|---|---|
-| No conflicts | x 1.0 |
-| Conflict exists, this claim has higher authority | x 0.85 |
-| Conflict exists, this claim has lower authority | x 0.5 |
-| Conflict resolved AGAINST this claim | x 0.1 |
-| Conflict resolved FOR this claim | x 1.1 |
-
-### 4.3 Explainability
-
-Every confidence score includes a full breakdown:
-
-```json
-{
- "score": 0.925,
- "breakdown": {
- "base_authority": { "value": 0.90, "reason": "code, AST-parsed" },
- "verification": { "value": 1.1, "reason": "covered by passing test" },
- "recency": { "value": 1.0, "reason": "source unchanged since observation" },
- "corroboration": { "value": 1.1, "reason": "2 independent sources agree" },
- "conflict_penalty": { "value": 0.85, "reason": "conflict with README (lower authority)" }
- }
-}
-```
-
----
-
-## 5. Context Assembly Pipeline
-
-How the Memory Layer turns a question into structured context.
-
-### 5.1 Pipeline Steps
-
-```
-Input: "How does billing retry?"
-
-Step 1: Entity Extraction
- ├── Keyword: split + normalize → ["billing", "retry"]
- ├── Synonym expansion: "retry" → ["retry", "retries", "retry_handler"]
- └── Output: search terms
-
-Step 2: Graph Seed Lookup
- ├── Fulltext search on node names + attrs
- ├── Kind index scan for matching kinds
- └── Output: seed node IDs
-
-Step 3: Graph Expansion (1-2 hops)
- ├── Adjacency scan from seed nodes
- ├── Follow: DEFINES, CALLS, IMPORTS, CONFIGURES, HAS_CLAIM
- └── Output: subgraph (nodes + edges)
-
-Step 4: Claim Collection
- ├── Gather all Claims attached to subgraph nodes
- └── Output: claim list with provenance
-
-Step 5: Confidence Scoring
- ├── For each claim: compute confidence from provenance
- ├── Check source staleness, corroboration, conflicts
- └── Output: scored claims with breakdown
-
-Step 6: Conflict Detection
- ├── Find claim pairs that contradict
- └── Output: conflicts list
-
-Step 7: Ranking + Assembly
- ├── Sort claims by confidence descending
- ├── Group by entity for structure
- └── Output: StructuredContext
-```
-
-### 5.2 StructuredContext (output format)
-
-```json
-{
- "claims": [
- {
- "statement": "The billing service retries 3 times",
- "confidence": { "score": 0.925, "breakdown": { ... } },
- "provenance": {
- "source_uri": "billing.py:45",
- "source_type": "code",
- "extractor": "tree-sitter-python",
- "observed_rev": 43
- },
- "entity_id": "uuid-of-retry-handler"
- }
- ],
- "conflicts": [
- {
- "id": "conflict-uuid",
- "claim_a": { "statement": "retries 3 times", "confidence": 0.925 },
- "claim_b": { "statement": "retries 5 times", "confidence": 0.263 },
- "reason": "contradictory values for retry count",
- "recommendation": "trust code (0.925) over README (0.263)"
- }
- ],
- "graph": {
- "nodes": [ ... ],
- "edges": [ ... ]
- },
- "metadata": {
- "query": "How does billing retry?",
- "seed_entities": ["billing_service", "retry_handler"],
- "hops_expanded": 2,
- "as_of_rev": 48
- }
-}
-```
-
----
-
-## 6. Ingestion Pipeline
-
-### 6.1 Parser Routing
-
-| Source | Parser | LLM Needed? |
-|---|---|---|
-| Code files (.py, .ts, .scala) | AST (tree-sitter) | No |
-| Config files (.yaml, .json, .toml) | Schema parser | No |
-| Git history | Git log/diff parser | No |
-| Markdown/docs | Section parser + optional LLM | Maybe |
-| Unstructured text | LLM extraction | Yes (developer's key) |
-
-### 6.2 Ingestion Flow
-
-```
-Source file arrives (via CLI, SDK, or MCP)
- │
- ▼
- File discovery (walk directory, filter by language)
- │
- ▼
- Route to parser by file type
- ├── .py → tree-sitter-python (AST, deterministic, free)
- ├── .yaml → YAML schema parser (deterministic, free)
- ├── .md → Markdown section parser (deterministic)
- │ + optional LLM extraction (uses developer's key)
- └── .git → Git log parser (deterministic)
- │
- ▼
- Extract entities + relationships
- ├── Nodes: File, Module, Class, Function, Variable, Config...
- └── Edges: DEFINES, CALLS, IMPORTS, CONFIGURES...
- │
- ▼
- Build GraphPatch
- ├── Assign patch_id (uuid-v7)
- ├── Attach provenance (source_uri, hash, extractor, source_type)
- ├── Set actor (e.g., "ci/tree-sitter-python")
- └── List ops (UpsertNode, UpsertEdge, etc.)
- │
- ▼
- Validate patch
- ├── Schema valid?
- ├── Referential integrity?
- └── Invariant violations?
- │
- ▼
- Commit to DB
- ├── Apply ops atomically
- ├── Increment revision
- ├── Store idempotency key (patch_id → rev)
- └── Return { new_rev, status }
-```
-
----
-
-## 7. CLI
-
-```
-ix — the Ix Memory CLI
-
-COMMANDS:
-
- ix ingest <path> [--language <lang>] [--recursive] [--watch]
- Ingest source files into the graph.
-
- ix query <question> [--as-of-rev <rev>] [--format json|text]
- Query the graph. Returns structured context with claims,
- confidence, and conflicts.
-
- ix diff <revA> <revB> [--entity <id>] [--scope <kind>]
- Show what changed between two revisions.
-
- ix history <entity_id>
- Show the full revision history of an entity.
-
- ix conflicts [--status open|resolved|all]
- List active conflicts (contradictory claims).
-
- ix resolve <conflict_id> --winner <claim_id>
- Resolve a conflict by choosing the correct claim.
-
- ix entity <id> [--as-of-rev <rev>]
- Inspect a single entity: attrs, claims, edges, provenance.
-
- ix provenance <entity_id>
- Trace the full provenance chain.
-
- ix status
- Show graph stats: node/edge counts, latest rev, open conflicts.
-
-IMPLEMENTATION:
- - Scala, using decline for command parsing
- - Thin client: every command calls the Memory Layer HTTP API
- - Formats output for terminal (tables, colors, tree views)
- - Config: ~/.ix/config.yaml (endpoint, tenant, LLM key)
-```
-
----
-
-## 8. MCP Server
-
-```
-Transport: stdio (for Claude Desktop, Cursor, etc.)
-
-Tools:
-
- ix_query
- Input: { question: string, as_of_rev?: number }
- Output: { claims: Claim[], conflicts: Conflict[], graph: SubGraph }
-
- ix_ingest
- Input: { path: string, language?: string }
- Output: { patches_applied: number, new_rev: number }
-
- ix_entity
- Input: { id: string, as_of_rev?: number }
- Output: { node: Node, claims: Claim[], edges: Edge[], history: PatchRef[] }
-
- ix_diff
- Input: { rev_a: number, rev_b: number, scope?: string }
- Output: { added: Entity[], removed: Entity[], changed: Entity[] }
-
- ix_conflicts
- Input: { status?: "open" | "resolved" | "all" }
- Output: { conflicts: ConflictSet[] }
-
- ix_resolve_conflict
- Input: { conflict_id: string, winner_claim_id: string }
- Output: { resolved: boolean, new_rev: number }
-
- ix_expand
- Input: { entity_id: string, direction: "out"|"in"|"both",
- predicates?: string[], hops?: number }
- Output: { nodes: Node[], edges: Edge[] }
-
-IMPLEMENTATION:
- - Scala, MCP stdio protocol
- - Calls same Memory Layer HTTP API as CLI
- - Tool descriptions optimized for LLM comprehension
-```
-
----
-
-## 9. SDK (TypeScript + Python)
-
-### 9.1 TypeScript (@ix/client)
-
-```typescript
-import { IxClient } from '@ix/client';
-
-const ix = new IxClient({
- endpoint: 'http://localhost:8090',
- llmProvider: 'anthropic',
- llmApiKey: process.env.ANTHROPIC_KEY,
-});
-
-// Ingest code into the graph
-await ix.ingest('./src', { language: 'python', recursive: true });
-
-// Get raw structured context (no LLM call)
-const ctx = await ix.getContext('How does billing retry?');
-// ctx.claims, ctx.conflicts, ctx.graph
-
-// Full query with LLM (uses developer's key client-side)
-const answer = await ix.query('How does billing retry?');
-// answer.response, answer.sources, answer.confidence
-
-// Time travel
-const old = await ix.getContext('...', { asOfRev: 10 });
-
-// Diff
-const changes = await ix.diff(10, 43);
-
-// Inspect entity
-const entity = await ix.entity('uuid-of-retry-handler');
-```
-
-### 9.2 SDK Architecture
-
-```
-┌────────────────────────────────────────┐
-│ SDK │
-│ ├── HttpClient (calls Ix Memory API) │
-│ ├── PromptBuilder (turns Structured │
-│ │ Context into LLM system prompt) │
-│ ├── LlmCaller (calls Claude/OpenAI │
-│ │ using DEVELOPER'S key) │
-│ └── ResponseParser (extracts sources, │
-│ confidence from LLM response) │
-└────────────────────────────────────────┘
-
-The LLM API key lives ONLY in the SDK (client-side).
-The Ix server never sees it.
-```
-
----
-
-## 10. Repo Structure
-
-```
-IX-Memory-Repo/
-├── docs/
-│ └── plans/
-│ └── 2026-03-02-ix-memory-design.md
-│
-├── memory-layer/ (Scala, sbt)
-│ ├── build.sbt
-│ ├── src/main/scala/ix/memory/
-│ │ ├── Main.scala
-│ │ ├── api/
-│ │ │ └── Routes.scala
-│ │ ├── context/
-│ │ │ ├── ContextService.scala
-│ │ │ ├── EntityExtractor.scala
-│ │ │ ├── GraphSeeder.scala
-│ │ │ ├── GraphExpander.scala
-│ │ │ ├── ClaimCollector.scala
-│ │ │ ├── ConfidenceScorer.scala
-│ │ │ ├── ConflictDetector.scala
-│ │ │ └── ContextRanker.scala
-│ │ ├── ingestion/
-│ │ │ ├── IngestionService.scala
-│ │ │ ├── ParserRouter.scala
-│ │ │ ├── parsers/
-│ │ │ │ ├── TreeSitterParser.scala
-│ │ │ │ ├── SchemaParser.scala
-│ │ │ │ ├── MarkdownParser.scala
-│ │ │ │ └── GitParser.scala
-│ │ │ ├── GraphPatchBuilder.scala
-│ │ │ └── PatchValidator.scala
-│ │ ├── version/
-│ │ │ ├── VersionService.scala
-│ │ │ ├── DiffEngine.scala
-│ │ │ └── StalenessDetector.scala
-│ │ ├── conflict/
-│ │ │ ├── ConflictService.scala
-│ │ │ └── ConflictResolver.scala
-│ │ ├── model/
-│ │ │ ├── GraphPatch.scala
-│ │ │ ├── Node.scala
-│ │ │ ├── Edge.scala
-│ │ │ ├── Claim.scala
-│ │ │ ├── ConflictSet.scala
-│ │ │ ├── Provenance.scala
-│ │ │ ├── StructuredContext.scala
-│ │ │ └── ConfidenceBreakdown.scala
-│ │ └── db/
-│ │ ├── ArangoClient.scala
-│ │ ├── GraphWriteApi.scala
-│ │ └── GraphQueryApi.scala
-│ └── src/test/scala/ix/memory/
-│
-├── cli/ (Scala, shared sbt build)
-│ └── src/main/scala/ix/cli/
-│ ├── Main.scala
-│ ├── Commands.scala
-│ └── Formatter.scala
-│
-├── mcp-server/ (Scala, shared sbt build)
-│ └── src/main/scala/ix/mcp/
-│ ├── Main.scala
-│ ├── ToolRegistry.scala
-│ └── ToolHandlers.scala
-│
-├── sdk/
-│ ├── typescript/ (npm: @ix/client)
-│ │ ├── package.json
-│ │ ├── src/
-│ │ │ ├── client.ts
-│ │ │ ├── prompt-builder.ts
-│ │ │ ├── llm-caller.ts
-│ │ │ └── types.ts
-│ │ └── test/
-│ └── python/ (pip: ix-python)
-│ ├── pyproject.toml
-│ ├── ix/
-│ │ ├── client.py
-│ │ ├── prompt_builder.py
-│ │ ├── llm_caller.py
-│ │ └── types.py
-│ └── tests/
-│
-├── docker-compose.yml (ArangoDB + memory-layer)
-└── .gitignore
-```
-
----
-
-## 11. Build Phases
-
-### Phase 1: Memory Layer Core (the engine)
-
-- Data model (GraphPatch, Node, Edge, Claim, Provenance)
-- ArangoDB integration (reuse/adapt from SD_Query_Engine)
-- Ingestion pipeline: tree-sitter Python parser → GraphPatch → DB
-- Context pipeline: entity extraction → seed → expand → claims → rank
-- Confidence scoring engine (the computed formula)
-- Conflict detection
-- HTTP API: /v1/context, /v1/ingest, /v1/entity, /v1/diff
-- **Deliverable:** working Memory Layer with HTTP API
-
-### Phase 2: CLI + MCP Server (thin clients, can be parallel)
-
-- CLI: all commands calling Memory Layer HTTP API
-- MCP Server: all tools calling Memory Layer HTTP API
-- **Deliverable:** ix CLI + MCP server for Claude Desktop
-
-### Phase 3: SDK + More Parsers
-
-- TypeScript SDK with prompt builder + BYOK LLM caller
-- Python SDK
-- Additional parsers: TypeScript, config files, markdown, git
-- **Deliverable:** npm/pip packages developers can install
-
-### Phase 4: Advanced Intelligence
-
-- Corroboration counting across sources
-- Verification from test results (CI integration)
-- Staleness detection (source file changed since observation)
-- Working set continuity (session-scoped activation)
-- Intent-aware retrieval
-- **Deliverable:** the full "epistemic operating system"
diff --git a/docs/plans/2026-03-02-phase1-implementation-plan.md b/docs/plans/2026-03-02-phase1-implementation-plan.md
deleted file mode 100644
index a51463e9..00000000
--- a/docs/plans/2026-03-02-phase1-implementation-plan.md
+++ /dev/null
@@ -1,1608 +0,0 @@
-# Phase 1: Memory Layer Core — Implementation Plan
-
-> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
-
-**Goal:** Build the Memory Layer core engine — a Scala HTTP service that ingests source code into a temporal property graph, queries it for structured claims with computed confidence and conflict detection, and serves results via REST API.
-
-**Architecture:** Single Scala sbt project (multi-module: memory-layer, cli, mcp-server). Phase 1 focuses on memory-layer only. The service exposes HTTP endpoints backed by ArangoDB. Ingestion uses tree-sitter for Python AST parsing. The context pipeline extracts entities from queries, seeds the graph, expands neighborhoods, collects claims, scores confidence, detects conflicts, and returns StructuredContext.
-
-**Tech Stack:**
-- Scala 2.13, Cats Effect 3.5.4, http4s 0.23.x, Circe 0.14.x
-- ArangoDB Java Driver 7.12.0
-- java-tree-sitter 1.12.0 (ch.usi.si.seart) for Python AST parsing
-- ScalaTest 3.2.x for testing
-- Docker for ArangoDB
-
-**Reference:** Design doc at `docs/plans/2026-03-02-ix-memory-design.md`
-
----
-
-## Task 1: Project Scaffold
-
-**Files:**
-- Create: `build.sbt`
-- Create: `project/build.properties`
-- Create: `project/plugins.sbt`
-- Create: `.gitignore`
-- Create: `docker-compose.yml`
-- Create: `memory-layer/src/main/resources/logback.xml`
-
-**Step 1: Create build.sbt with multi-module layout**
-
-```scala
-ThisBuild / scalaVersion := "2.13.16"
-ThisBuild / organization := "ix"
-ThisBuild / version := "0.1.0-SNAPSHOT"
-
-val CatsEffectVersion = "3.5.4"
-val Http4sVersion = "0.23.30"
-val CirceVersion = "0.14.10"
-val ArangoVersion = "7.12.0"
-val TreeSitterVersion = "1.12.0"
-val LogbackVersion = "1.5.6"
-val Log4CatsVersion = "2.7.0"
-val ScalaTestVersion = "3.2.18"
-val CatsEffectTestVersion = "1.5.0"
-
-lazy val commonDeps = Seq(
- "org.typelevel" %% "cats-effect" % CatsEffectVersion,
- "io.circe" %% "circe-core" % CirceVersion,
- "io.circe" %% "circe-generic" % CirceVersion,
- "io.circe" %% "circe-parser" % CirceVersion,
- "org.typelevel" %% "log4cats-slf4j" % Log4CatsVersion,
- "ch.qos.logback" % "logback-classic" % LogbackVersion,
- "org.scalatest" %% "scalatest" % ScalaTestVersion % Test,
- "org.typelevel" %% "cats-effect-testing-scalatest" % CatsEffectTestVersion % Test
-)
-
-lazy val `memory-layer` = (project in file("memory-layer"))
- .settings(
- name := "ix-memory-layer",
- libraryDependencies ++= commonDeps ++ Seq(
- "org.http4s" %% "http4s-ember-server" % Http4sVersion,
- "org.http4s" %% "http4s-dsl" % Http4sVersion,
- "org.http4s" %% "http4s-circe" % Http4sVersion,
- "com.arangodb" % "arangodb-java-driver" % ArangoVersion,
- "ch.usi.si.seart" % "java-tree-sitter" % TreeSitterVersion
- ),
- assembly / mainClass := Some("ix.memory.Main"),
- assembly / assemblyJarName := "ix-memory-layer.jar",
- assembly / assemblyMergeStrategy := {
- case PathList("META-INF", _*) => MergeStrategy.discard
- case _ => MergeStrategy.first
- }
- )
-
-lazy val root = (project in file("."))
- .aggregate(`memory-layer`)
- .settings(name := "ix-memory")
-```
-
-**Step 2: Create project/build.properties**
-
-```
-sbt.version=1.10.7
-```
-
-**Step 3: Create project/plugins.sbt**
-
-```scala
-addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "2.3.0")
-```
-
-**Step 4: Create .gitignore**
-
-```
-target/
-.bsp/
-.idea/
-*.class
-*.jar
-.DS_Store
-```
-
-**Step 5: Create docker-compose.yml**
-
-```yaml
-version: "3.8"
-services:
- arangodb:
- image: arangodb:3.12
- ports:
- - "8529:8529"
- environment:
- ARANGO_ROOT_PASSWORD: ""
- ARANGO_NO_AUTH: "1"
- volumes:
- - arango-data:/var/lib/arangodb3
-volumes:
- arango-data:
-```
-
-**Step 6: Create memory-layer/src/main/resources/logback.xml**
-
-```xml
-<configuration>
- <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
- <encoder>
- <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
- </encoder>
- </appender>
- <root level="INFO">
- <appender-ref ref="STDOUT" />
- </root>
-</configuration>
-```
-
-**Step 7: Verify build compiles**
-
-Run: `cd /Users/rileythompson/startprojes/startup/IX-Memory-Repo && sbt compile`
-Expected: BUILD SUCCESS (no source files yet, just verifying deps resolve)
-
-**Step 8: Start ArangoDB**
-
-Run: `cd /Users/rileythompson/startprojes/startup/IX-Memory-Repo && docker compose up -d`
-Expected: ArangoDB running on port 8529
-
-**Step 9: Commit**
-
-```bash
-git add build.sbt project/ .gitignore docker-compose.yml memory-layer/
-git commit -m "feat: scaffold project with sbt multi-module build and docker-compose"
-```
-
----
-
-## Task 2: Core Data Model
-
-**Files:**
-- Create: `memory-layer/src/main/scala/ix/memory/model/Identifiers.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/model/Provenance.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/model/Node.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/model/Edge.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/model/Claim.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/model/GraphPatch.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/model/ConflictSet.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/model/ConfidenceBreakdown.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/model/StructuredContext.scala`
-- Test: `memory-layer/src/test/scala/ix/memory/model/ModelSpec.scala`
-
-**Step 1: Write the failing test for model serialization**
-
-```scala
-// memory-layer/src/test/scala/ix/memory/model/ModelSpec.scala
-package ix.memory.model
-
-import org.scalatest.flatspec.AnyFlatSpec
-import org.scalatest.matchers.should.Matchers
-import io.circe.syntax._
-import io.circe.parser._
-import java.time.Instant
-import java.util.UUID
-
-class ModelSpec extends AnyFlatSpec with Matchers {
-
- "Provenance" should "round-trip through JSON" in {
- val p = Provenance(
- sourceUri = "billing.py",
- sourceHash = Some("a1b2c3"),
- extractor = "tree-sitter-python/1.0",
- sourceType = SourceType.Code,
- observedAt = Instant.parse("2026-03-01T10:00:00Z")
- )
- val json = p.asJson
- val decoded = json.as[Provenance]
- decoded shouldBe Right(p)
- }
-
- "GraphPatch" should "serialize with all ops" in {
- val patch = GraphPatch(
- patchId = PatchId(UUID.randomUUID()),
- tenant = TenantId("test"),
- actor = "ci/tree-sitter",
- timestamp = Instant.now(),
- source = PatchSource(
- uri = "billing.py",
- hash = Some("a1b2c3"),
- extractor = "tree-sitter-python/1.0",
- sourceType = SourceType.Code
- ),
- baseRev = None,
- ops = Vector(
- PatchOp.UpsertNode(
- NodeId(UUID.randomUUID()),
- NodeKind.Function,
- Map("name" -> "retry_handler".asJson, "line_start" -> 45.asJson)
- )
- ),
- replaces = Vector.empty,
- intent = Some("Parsed billing.py")
- )
- val json = patch.asJson
- json.hcursor.get[String]("patch_id").isRight shouldBe true
- json.hcursor.get[String]("actor") shouldBe Right("ci/tree-sitter")
- }
-
- "SourceType" should "encode and decode correctly" in {
- SourceType.Code.asJson.noSpaces shouldBe "\"code\""
- parse("\"config\"").flatMap(_.as[SourceType]) shouldBe Right(SourceType.Config)
- }
-
- "NodeKind" should "encode and decode correctly" in {
- NodeKind.Function.asJson.noSpaces shouldBe "\"function\""
- NodeKind.Module.asJson.noSpaces shouldBe "\"module\""
- }
-
- "ConfidenceBreakdown" should "compute score from factors" in {
- val breakdown = ConfidenceBreakdown(
- baseAuthority = Factor(0.90, "code, AST-parsed"),
- verification = Factor(1.1, "covered by passing test"),
- recency = Factor(1.0, "source unchanged"),
- corroboration = Factor(1.1, "2 independent sources agree"),
- conflictPenalty = Factor(0.85, "conflict with lower-authority source")
- )
- // 0.90 * 1.1 * 1.0 * 1.1 * 0.85 = 0.92565
- breakdown.score shouldBe 0.926 +- 0.001
- }
-}
-```
-
-**Step 2: Run test to verify it fails**
-
-Run: `cd /Users/rileythompson/startprojes/startup/IX-Memory-Repo && sbt "memory-layer/testOnly ix.memory.model.ModelSpec"`
-Expected: FAIL — classes don't exist yet
-
-**Step 3: Implement Identifiers.scala**
-
-```scala
-// memory-layer/src/main/scala/ix/memory/model/Identifiers.scala
-package ix.memory.model
-
-import java.util.UUID
-import io.circe.{Encoder, Decoder}
-
-case class TenantId(value: String) extends AnyVal
-object TenantId {
- implicit val encoder: Encoder[TenantId] = Encoder.encodeString.contramap(_.value)
- implicit val decoder: Decoder[TenantId] = Decoder.decodeString.map(TenantId(_))
-}
-
-case class NodeId(value: UUID) extends AnyVal
-object NodeId {
- def random: NodeId = NodeId(UUID.randomUUID())
- implicit val encoder: Encoder[NodeId] = Encoder.encodeUUID.contramap(_.value)
- implicit val decoder: Decoder[NodeId] = Decoder.decodeUUID.map(NodeId(_))
-}
-
-case class EdgeId(value: UUID) extends AnyVal
-object EdgeId {
- def random: EdgeId = EdgeId(UUID.randomUUID())
- def derived(src: NodeId, dst: NodeId, predicate: String): EdgeId = {
- val name = s"${src.value}:${dst.value}:$predicate"
- EdgeId(UUID.nameUUIDFromBytes(name.getBytes("UTF-8")))
- }
- implicit val encoder: Encoder[EdgeId] = Encoder.encodeUUID.contramap(_.value)
- implicit val decoder: Decoder[EdgeId] = Decoder.decodeUUID.map(EdgeId(_))
-}
-
-case class PatchId(value: UUID) extends AnyVal
-object PatchId {
- def random: PatchId = PatchId(UUID.randomUUID())
- implicit val encoder: Encoder[PatchId] = Encoder.encodeUUID.contramap(_.value)
- implicit val decoder: Decoder[PatchId] = Decoder.decodeUUID.map(PatchId(_))
-}
-
-case class ClaimId(value: UUID) extends AnyVal
-object ClaimId {
- def random: ClaimId = ClaimId(UUID.randomUUID())
- implicit val encoder: Encoder[ClaimId] = Encoder.encodeUUID.contramap(_.value)
- implicit val decoder: Decoder[ClaimId] = Decoder.decodeUUID.map(ClaimId(_))
-}
-
-case class ConflictId(value: UUID) extends AnyVal
-object ConflictId {
- def random: ConflictId = ConflictId(UUID.randomUUID())
- implicit val encoder: Encoder[ConflictId] = Encoder.encodeUUID.contramap(_.value)
- implicit val decoder: Decoder[ConflictId] = Decoder.decodeUUID.map(ConflictId(_))
-}
-
-// Monotonic revision counter per tenant
-case class Rev(value: Long) extends AnyVal
-object Rev {
- implicit val encoder: Encoder[Rev] = Encoder.encodeLong.contramap(_.value)
- implicit val decoder: Decoder[Rev] = Decoder.decodeLong.map(Rev(_))
-}
-```
-
-**Step 4: Implement Provenance.scala**
-
-```scala
-// memory-layer/src/main/scala/ix/memory/model/Provenance.scala
-package ix.memory.model
-
-import java.time.Instant
-import io.circe.{Encoder, Decoder}
-import io.circe.generic.semiauto._
-
-sealed trait SourceType
-object SourceType {
- case object Code extends SourceType
- case object Config extends SourceType
- case object Doc extends SourceType
- case object Test extends SourceType
- case object Schema extends SourceType
- case object Commit extends SourceType
- case object Comment extends SourceType
- case object Inferred extends SourceType
- case object Human extends SourceType
-
- implicit val encoder: Encoder[SourceType] = Encoder.encodeString.contramap {
- case Code => "code"
- case Config => "config"
- case Doc => "doc"
- case Test => "test"
- case Schema => "schema"
- case Commit => "commit"
- case Comment => "comment"
- case Inferred => "inferred"
- case Human => "human"
- }
-
- implicit val decoder: Decoder[SourceType] = Decoder.decodeString.emap {
- case "code" => Right(Code)
- case "config" => Right(Config)
- case "doc" => Right(Doc)
- case "test" => Right(Test)
- case "schema" => Right(Schema)
- case "commit" => Right(Commit)
- case "comment" => Right(Comment)
- case "inferred" => Right(Inferred)
- case "human" => Right(Human)
- case other => Left(s"Unknown source type: $other")
- }
-
- def baseAuthority(st: SourceType): Double = st match {
- case Test => 0.95
- case Code => 0.90
- case Config => 0.85
- case Schema => 0.85
- case Doc => 0.75
- case Commit => 0.60
- case Comment => 0.50
- case Inferred => 0.40
- case Human => 0.80
- }
-}
-
-case class Provenance(
- sourceUri: String,
- sourceHash: Option[String],
- extractor: String,
- sourceType: SourceType,
- observedAt: Instant
-)
-object Provenance {
- implicit val encoder: Encoder[Provenance] = deriveEncoder
- implicit val decoder: Decoder[Provenance] = deriveDecoder
-}
-```
-
-**Step 5: Implement remaining model files**
-
-Implement `Node.scala`, `Edge.scala`, `Claim.scala`, `GraphPatch.scala`, `ConflictSet.scala`, `ConfidenceBreakdown.scala`, `StructuredContext.scala` following the design doc schema. Each file follows the same pattern: case class + Circe encoder/decoder.
-
-Key types:
-
-```scala
-// Node.scala
-sealed trait NodeKind
-object NodeKind {
- case object Module extends NodeKind
- case object File extends NodeKind
- case object Class extends NodeKind
- case object Function extends NodeKind
- case object Variable extends NodeKind
- case object Config extends NodeKind
- case object ConfigEntry extends NodeKind
- case object Service extends NodeKind
- case object Endpoint extends NodeKind
- // encoder/decoder mapping to lowercase strings
-}
-
-case class GraphNode(
- id: NodeId,
- kind: NodeKind,
- tenant: TenantId,
- attrs: io.circe.Json,
- provenance: Provenance,
- createdRev: Rev,
- deletedRev: Option[Rev],
- createdAt: Instant,
- updatedAt: Instant
-)
-
-// Edge.scala
-case class EdgePredicate(value: String) extends AnyVal
-
-case class GraphEdge(
- id: EdgeId,
- src: NodeId,
- dst: NodeId,
- predicate: EdgePredicate,
- tenant: TenantId,
- attrs: io.circe.Json,
- provenance: Provenance,
- createdRev: Rev,
- deletedRev: Option[Rev]
-)
-
-// Claim.scala
-sealed trait ClaimStatus
-object ClaimStatus {
- case object Active extends ClaimStatus
- case object Stale extends ClaimStatus
- case object Retracted extends ClaimStatus
-}
-
-case class Claim(
- id: ClaimId,
- entityId: NodeId,
- statement: String,
- status: ClaimStatus,
- provenance: Provenance,
- createdRev: Rev,
- deletedRev: Option[Rev]
-)
-
-// GraphPatch.scala — PatchOp and GraphPatch
-sealed trait PatchOp
-object PatchOp {
- case class UpsertNode(id: NodeId, kind: NodeKind, attrs: Map[String, io.circe.Json]) extends PatchOp
- case class UpsertEdge(src: NodeId, dst: NodeId, predicate: String, attrs: Map[String, io.circe.Json]) extends PatchOp
- case class DeleteNode(id: NodeId) extends PatchOp
- case class DeleteEdge(id: EdgeId) extends PatchOp
- case class AssertClaim(entityId: NodeId, statement: String) extends PatchOp
- case class RetractClaim(claimId: ClaimId, reason: String) extends PatchOp
-}
-
-case class PatchSource(
- uri: String,
- hash: Option[String],
- extractor: String,
- sourceType: SourceType
-)
-
-case class GraphPatch(
- patchId: PatchId,
- tenant: TenantId,
- actor: String,
- timestamp: Instant,
- source: PatchSource,
- baseRev: Option[Rev],
- ops: Vector[PatchOp],
- replaces: Vector[PatchId],
- intent: Option[String]
-)
-
-// ConflictSet.scala
-sealed trait ConflictStatus
-object ConflictStatus {
- case object Open extends ConflictStatus
- case object Resolved extends ConflictStatus
- case object Dismissed extends ConflictStatus
-}
-
-case class ConflictSet(
- id: ConflictId,
- reason: String,
- status: ConflictStatus,
- candidateClaims: Vector[ClaimId],
- winnerClaimId: Option[ClaimId],
- createdRev: Rev
-)
-
-// ConfidenceBreakdown.scala
-case class Factor(value: Double, reason: String)
-
-case class ConfidenceBreakdown(
- baseAuthority: Factor,
- verification: Factor,
- recency: Factor,
- corroboration: Factor,
- conflictPenalty: Factor
-) {
- def score: Double = {
- val raw = baseAuthority.value *
- verification.value *
- recency.value *
- corroboration.value *
- conflictPenalty.value
- math.max(0.0, math.min(1.0, raw))
- }
-}
-
-// StructuredContext.scala
-case class ScoredClaim(
- claim: Claim,
- confidence: ConfidenceBreakdown
-)
-
-case class ConflictReport(
- id: ConflictId,
- claimA: ScoredClaim,
- claimB: ScoredClaim,
- reason: String,
- recommendation: String
-)
-
-case class StructuredContext(
- claims: Vector[ScoredClaim],
- conflicts: Vector[ConflictReport],
- nodes: Vector[GraphNode],
- edges: Vector[GraphEdge],
- metadata: ContextMetadata
-)
-
-case class ContextMetadata(
- query: String,
- seedEntities: Vector[String],
- hopsExpanded: Int,
- asOfRev: Rev
-)
-```
-
-**Step 6: Run tests to verify they pass**
-
-Run: `cd /Users/rileythompson/startprojes/startup/IX-Memory-Repo && sbt "memory-layer/testOnly ix.memory.model.ModelSpec"`
-Expected: PASS — all model serialization tests green
-
-**Step 7: Commit**
-
-```bash
-git add memory-layer/src/
-git commit -m "feat: add core data model — GraphPatch, Node, Edge, Claim, Provenance, Confidence"
-```
-
----
-
-## Task 3: ArangoDB Client + Schema
-
-**Files:**
-- Create: `memory-layer/src/main/scala/ix/memory/db/ArangoClient.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/db/ArangoSchema.scala`
-- Test: `memory-layer/src/test/scala/ix/memory/db/ArangoClientSpec.scala`
-
-**Prereq:** ArangoDB running via docker-compose (Task 1, Step 8)
-
-**Step 1: Write the failing integration test**
-
-```scala
-// memory-layer/src/test/scala/ix/memory/db/ArangoClientSpec.scala
-package ix.memory.db
-
-import cats.effect.IO
-import cats.effect.testing.scalatest.AsyncIOSpec
-import org.scalatest.flatspec.AsyncFlatSpec
-import org.scalatest.matchers.should.Matchers
-import io.circe.Json
-
-class ArangoClientSpec extends AsyncFlatSpec with AsyncIOSpec with Matchers {
-
- // Requires ArangoDB running on localhost:8529
- val clientResource = ArangoClient.resource(
- host = "localhost", port = 8529,
- database = "ix_memory_test", user = "root", password = ""
- )
-
- "ArangoClient" should "connect and ensure schema" in {
- clientResource.use { client =>
- client.ensureSchema().map(_ => succeed)
- }
- }
-
- it should "execute a simple query" in {
- clientResource.use { client =>
- for {
- _ <- client.ensureSchema()
- results <- client.query("RETURN 1", Map.empty)
- } yield results.size shouldBe 1
- }
- }
-
- it should "insert and retrieve a document" in {
- clientResource.use { client =>
- for {
- _ <- client.ensureSchema()
- _ <- client.execute(
- "INSERT { _key: @key, name: @name } INTO nodes",
- Map("key" -> "test1", "name" -> "testNode")
- )
- result <- client.queryOne(
- "FOR n IN nodes FILTER n._key == @key RETURN n",
- Map("key" -> "test1")
- )
- } yield {
- result shouldBe defined
- result.get.hcursor.get[String]("name") shouldBe Right("testNode")
- }
- }
- }
-}
-```
-
-**Step 2: Run test to verify it fails**
-
-Run: `sbt "memory-layer/testOnly ix.memory.db.ArangoClientSpec"`
-Expected: FAIL — ArangoClient doesn't exist
-
-**Step 3: Implement ArangoClient.scala**
-
-Adapt from SD_Query_Engine's `ArangoClient.scala`. Key changes:
-- Use `ix_memory` database name by default
-- Resource-based lifecycle with Cats Effect
-- `query`, `queryOne`, `execute` methods wrapping ArangoDB Java driver
-- `ensureSchema()` delegates to `ArangoSchema`
-
-```scala
-// memory-layer/src/main/scala/ix/memory/db/ArangoClient.scala
-package ix.memory.db
-
-import cats.effect.{IO, Resource}
-import com.arangodb.{ArangoDB, ArangoDatabase}
-import com.arangodb.entity.CollectionType
-import com.arangodb.model.CollectionCreateOptions
-import io.circe.{Json, parser => circeParser}
-import scala.jdk.CollectionConverters._
-
-class ArangoClient private (db: ArangoDatabase) {
-
- def query(aql: String, bindVars: Map[String, AnyRef]): IO[List[Json]] = IO.blocking {
- val cursor = db.query(aql, classOf[String], bindVars.asJava)
- cursor.asListRemaining().asScala.toList.flatMap(s =>
- circeParser.parse(s).toOption
- )
- }
-
- def queryOne(aql: String, bindVars: Map[String, AnyRef]): IO[Option[Json]] =
- query(aql, bindVars).map(_.headOption)
-
- def execute(aql: String, bindVars: Map[String, AnyRef]): IO[Unit] = IO.blocking {
- db.query(aql, classOf[Void], bindVars.asJava)
- ()
- }
-
- def ensureSchema(): IO[Unit] = ArangoSchema.ensure(this, db)
-}
-
-object ArangoClient {
- def resource(
- host: String, port: Int,
- database: String, user: String, password: String
- ): Resource[IO, ArangoClient] = {
- Resource.make(IO.blocking {
- val arango = new ArangoDB.Builder()
- .host(host, port)
- .user(user)
- .password(password)
- .build()
- // Ensure database exists
- if (!arango.getDatabases.contains(database)) {
- arango.createDatabase(database)
- }
- val db = arango.db(database)
- (arango, new ArangoClient(db))
- })(pair => IO.blocking(pair._1.shutdown())).map(_._2)
- }
-}
-```
-
-**Step 4: Implement ArangoSchema.scala**
-
-```scala
-// memory-layer/src/main/scala/ix/memory/db/ArangoSchema.scala
-package ix.memory.db
-
-import cats.effect.IO
-import com.arangodb.ArangoDatabase
-import com.arangodb.entity.CollectionType
-import com.arangodb.model.{CollectionCreateOptions, HashIndexOptions, TtlIndexOptions}
-import scala.jdk.CollectionConverters._
-
-object ArangoSchema {
- def ensure(client: ArangoClient, db: ArangoDatabase): IO[Unit] = IO.blocking {
- // Vertex collections
- ensureCollection(db, "nodes")
- ensureCollection(db, "claims")
- ensureCollection(db, "conflict_sets")
- ensureCollection(db, "patches") // The event log
- ensureCollection(db, "revisions") // Per-tenant revision counter
- ensureCollection(db, "idempotency_keys")
-
- // Edge collection
- ensureCollection(db, "edges", edge = true)
-
- // Indexes
- val nodes = db.collection("nodes")
- nodes.ensureHashIndex(List("tenant", "kind").asJava, new HashIndexOptions())
- nodes.ensureHashIndex(List("tenant", "attrs.name").asJava,
- new HashIndexOptions().sparse(true))
-
- val edges = db.collection("edges")
- edges.ensureHashIndex(List("tenant", "src").asJava, new HashIndexOptions())
- edges.ensureHashIndex(List("tenant", "dst").asJava, new HashIndexOptions())
- edges.ensureHashIndex(List("tenant", "predicate").asJava, new HashIndexOptions())
-
- val claims = db.collection("claims")
- claims.ensureHashIndex(List("tenant", "entity_id").asJava, new HashIndexOptions())
- claims.ensureHashIndex(List("tenant", "status").asJava, new HashIndexOptions())
-
- val patches = db.collection("patches")
- patches.ensureHashIndex(List("tenant", "patch_id").asJava,
- new HashIndexOptions().unique(true))
-
- val idem = db.collection("idempotency_keys")
- idem.ensureHashIndex(List("key").asJava, new HashIndexOptions().unique(true))
- idem.ensureTtlIndex(List("created_at").asJava, new TtlIndexOptions().expireAfter(86400))
- }
-
- private def ensureCollection(db: ArangoDatabase, name: String, edge: Boolean = false): Unit = {
- if (!db.collection(name).exists()) {
- val opts = new CollectionCreateOptions()
- if (edge) opts.`type`(CollectionType.EDGES)
- db.createCollection(name, opts)
- }
- }
-}
-```
-
-**Step 5: Run tests to verify they pass**
-
-Run: `sbt "memory-layer/testOnly ix.memory.db.ArangoClientSpec"`
-Expected: PASS (requires ArangoDB running)
-
-**Step 6: Commit**
-
-```bash
-git add memory-layer/src/
-git commit -m "feat: add ArangoDB client with schema initialization"
-```
-
----
-
-## Task 4: Graph Write API — Patch Commit
-
-**Files:**
-- Create: `memory-layer/src/main/scala/ix/memory/db/GraphWriteApi.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/db/ArangoGraphWriteApi.scala`
-- Test: `memory-layer/src/test/scala/ix/memory/db/GraphWriteApiSpec.scala`
-
-**Step 1: Write the failing test**
-
-```scala
-package ix.memory.db
-
-class GraphWriteApiSpec extends AsyncFlatSpec with AsyncIOSpec with Matchers {
-
- "GraphWriteApi" should "commit a patch and increment revision" in {
- clientResource.use { client =>
- val api = ArangoGraphWriteApi(client)
- val patch = GraphPatch(
- patchId = PatchId.random,
- tenant = TenantId("test"),
- actor = "test",
- timestamp = Instant.now(),
- source = PatchSource("test.py", None, "test", SourceType.Code),
- baseRev = None,
- ops = Vector(PatchOp.UpsertNode(NodeId.random, NodeKind.Function,
- Map("name" -> "foo".asJson))),
- replaces = Vector.empty,
- intent = Some("test")
- )
- for {
- _ <- client.ensureSchema()
- result <- api.commitPatch(patch)
- } yield {
- result.newRev.value should be > 0L
- result.status shouldBe CommitStatus.Ok
- }
- }
- }
-
- it should "be idempotent on duplicate patch_id" in {
- clientResource.use { client =>
- val api = ArangoGraphWriteApi(client)
- val patchId = PatchId.random
- val patch = // ... same patch with same patchId
- for {
- _ <- client.ensureSchema()
- r1 <- api.commitPatch(patch)
- r2 <- api.commitPatch(patch)
- } yield {
- r1.status shouldBe CommitStatus.Ok
- r2.status shouldBe CommitStatus.Idempotent
- r1.newRev shouldBe r2.newRev
- }
- }
- }
-}
-```
-
-**Step 2: Run test, verify fails**
-
-**Step 3: Implement GraphWriteApi trait + ArangoGraphWriteApi**
-
-The `commitPatch` method:
-1. Check idempotency (patch_id already applied → return stored rev)
-2. Load latest_rev for tenant
-3. If base_rev provided and != latest_rev → return CONFLICT
-4. new_rev = latest_rev + 1
-5. For each op in patch: execute the corresponding AQL
-6. Store patch in `patches` collection
-7. Store idempotency key
-8. Update tenant revision
-9. Return CommitResult(new_rev, status)
-
-```scala
-trait GraphWriteApi {
- def commitPatch(patch: GraphPatch): IO[CommitResult]
-}
-
-case class CommitResult(newRev: Rev, status: CommitStatus)
-
-sealed trait CommitStatus
-object CommitStatus {
- case object Ok extends CommitStatus
- case object Idempotent extends CommitStatus
- case object BaseRevMismatch extends CommitStatus
- case object Error extends CommitStatus
-}
-```
-
-**Step 4: Run tests, verify pass**
-
-**Step 5: Commit**
-
-```bash
-git commit -m "feat: add GraphWriteApi with patch commit, MVCC, and idempotency"
-```
-
----
-
-## Task 5: Graph Query API
-
-**Files:**
-- Create: `memory-layer/src/main/scala/ix/memory/db/GraphQueryApi.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/db/ArangoGraphQueryApi.scala`
-- Test: `memory-layer/src/test/scala/ix/memory/db/GraphQueryApiSpec.scala`
-
-**Step 1: Write the failing test**
-
-Test should:
-- Commit a patch with 2 nodes and 1 edge
-- Query getNode by id → returns the node with correct attrs
-- Query expand from node → returns connected nodes + edges
-- Query with asOfRev → returns only entities visible at that revision
-- Query findNodesByKind → returns nodes of a given kind
-- Fulltext search by node name → returns matching nodes
-
-**Step 2: Implement GraphQueryApi trait**
-
-```scala
-trait GraphQueryApi {
- def getNode(tenant: TenantId, id: NodeId, asOfRev: Option[Rev] = None): IO[Option[GraphNode]]
- def findNodesByKind(tenant: TenantId, kind: NodeKind, limit: Int = 100): IO[Vector[GraphNode]]
- def searchNodes(tenant: TenantId, text: String, limit: Int = 20): IO[Vector[GraphNode]]
- def expand(tenant: TenantId, nodeId: NodeId, direction: Direction,
- predicates: Option[Set[String]] = None, hops: Int = 1,
- asOfRev: Option[Rev] = None): IO[ExpandResult]
- def getClaims(tenant: TenantId, entityId: NodeId): IO[Vector[Claim]]
- def getLatestRev(tenant: TenantId): IO[Rev]
-}
-
-sealed trait Direction
-object Direction {
- case object Out extends Direction
- case object In extends Direction
- case object Both extends Direction
-}
-
-case class ExpandResult(nodes: Vector[GraphNode], edges: Vector[GraphEdge])
-```
-
-**Step 3: Implement ArangoGraphQueryApi** with AQL queries:
-- `getNode`: `FOR n IN nodes FILTER n._key == @id AND n.tenant == @tenant AND n.created_rev <= @rev AND (n.deleted_rev == null OR @rev < n.deleted_rev) RETURN n`
-- `expand`: adjacency query using edges collection, filtering by direction and predicate
-- `searchNodes`: `FOR n IN nodes FILTER n.tenant == @tenant AND CONTAINS(LOWER(n.attrs.name), LOWER(@text)) RETURN n`
-
-**Step 4: Run tests, verify pass**
-
-**Step 5: Commit**
-
-```bash
-git commit -m "feat: add GraphQueryApi with getNode, expand, search, and MVCC visibility"
-```
-
----
-
-## Task 6: Ingestion — Tree-Sitter Python Parser
-
-**Files:**
-- Create: `memory-layer/src/main/scala/ix/memory/ingestion/IngestionService.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/ingestion/ParserRouter.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/ingestion/parsers/TreeSitterPythonParser.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/ingestion/GraphPatchBuilder.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/ingestion/PatchValidator.scala`
-- Test: `memory-layer/src/test/scala/ix/memory/ingestion/TreeSitterPythonParserSpec.scala`
-- Test fixture: `memory-layer/src/test/resources/fixtures/billing_service.py`
-
-**Step 1: Create test fixture**
-
-```python
-# memory-layer/src/test/resources/fixtures/billing_service.py
-import http_client
-from config import RETRY_COUNT
-
-class BillingService:
- def __init__(self, gateway):
- self.gateway = gateway
-
- def process_payment(self, amount, currency):
- result = self.gateway.charge(amount, currency)
- if not result.success:
- self.retry_handler(amount, currency)
- return result
-
- def retry_handler(self, amount, currency, max_retries=3):
- for attempt in range(max_retries):
- result = self.gateway.charge(amount, currency)
- if result.success:
- return result
- raise PaymentError("Max retries exceeded")
-
-def standalone_function():
- return BillingService(None)
-```
-
-**Step 2: Write the failing test**
-
-```scala
-class TreeSitterPythonParserSpec extends AnyFlatSpec with Matchers {
-
- val parser = new TreeSitterPythonParser()
-
- "TreeSitterPythonParser" should "extract functions from Python source" in {
- val source = scala.io.Source.fromResource("fixtures/billing_service.py").mkString
- val result = parser.parse("billing_service.py", source)
-
- val nodeNames = result.nodes.flatMap(_.attrs.hcursor.get[String]("name").toOption)
- nodeNames should contain("BillingService")
- nodeNames should contain("process_payment")
- nodeNames should contain("retry_handler")
- nodeNames should contain("standalone_function")
- }
-
- it should "extract import relationships" in {
- val source = scala.io.Source.fromResource("fixtures/billing_service.py").mkString
- val result = parser.parse("billing_service.py", source)
-
- val importEdges = result.edges.filter(_.predicate == "IMPORTS")
- importEdges.size should be >= 2
- }
-
- it should "extract class-to-method DEFINES edges" in {
- val source = scala.io.Source.fromResource("fixtures/billing_service.py").mkString
- val result = parser.parse("billing_service.py", source)
-
- val definesEdges = result.edges.filter(_.predicate == "DEFINES")
- definesEdges.size should be >= 3 // BillingService defines __init__, process_payment, retry_handler
- }
-
- it should "extract function call relationships" in {
- val source = scala.io.Source.fromResource("fixtures/billing_service.py").mkString
- val result = parser.parse("billing_service.py", source)
-
- val callEdges = result.edges.filter(_.predicate == "CALLS")
- callEdges.size should be >= 1 // process_payment calls retry_handler
- }
-}
-```
-
-**Step 3: Implement TreeSitterPythonParser**
-
-Uses `ch.usi.si.seart:java-tree-sitter`:
-- Parse source with `Language.PYTHON`
-- Query for `function_definition`, `class_definition`, `import_statement`, `import_from_statement`, `call`
-- Build intermediate `ParseResult(nodes, edges)` with extracted entities
-
-```scala
-case class ParsedEntity(
- name: String,
- kind: NodeKind,
- attrs: Map[String, Json],
- lineStart: Int,
- lineEnd: Int
-)
-
-case class ParsedRelationship(
- srcName: String,
- dstName: String,
- predicate: String
-)
-
-case class ParseResult(
- entities: Vector[ParsedEntity],
- relationships: Vector[ParsedRelationship]
-)
-```
-
-Tree-sitter queries:
-- Functions: `(function_definition name: (identifier) @name)`
-- Classes: `(class_definition name: (identifier) @name)`
-- Imports: `[(import_statement) @imp (import_from_statement) @imp]`
-- Calls: `(call function: (identifier) @fn)`
-
-**Step 4: Implement GraphPatchBuilder**
-
-Takes `ParseResult` + file metadata → produces `GraphPatch` with proper provenance:
-- Each ParsedEntity → `PatchOp.UpsertNode`
-- Each ParsedRelationship → `PatchOp.UpsertEdge`
-- Deterministic NodeId from `(tenant, file_path, entity_name)` using UUID.nameUUIDFromBytes
-- Provenance set from file path, content hash, extractor name
-
-**Step 5: Implement ParserRouter**
-
-Routes by file extension:
-- `.py` → `TreeSitterPythonParser`
-- Others → error (future parsers)
-
-**Step 6: Implement IngestionService**
-
-Orchestrates: discover files → parse → build patches → validate → commit
-
-```scala
-class IngestionService(parserRouter: ParserRouter, writeApi: GraphWriteApi) {
- def ingestPath(tenant: TenantId, path: Path, language: Option[String],
- recursive: Boolean): IO[IngestionResult]
- def ingestFile(tenant: TenantId, filePath: Path): IO[CommitResult]
-}
-
-case class IngestionResult(
- filesProcessed: Int,
- patchesApplied: Int,
- entitiesCreated: Int,
- latestRev: Rev
-)
-```
-
-**Step 7: Run tests, verify pass**
-
-**Step 8: Commit**
-
-```bash
-git commit -m "feat: add ingestion pipeline with tree-sitter Python parser"
-```
-
----
-
-## Task 7: Context Service — Query Pipeline
-
-**Files:**
-- Create: `memory-layer/src/main/scala/ix/memory/context/ContextService.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/context/EntityExtractor.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/context/GraphSeeder.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/context/GraphExpander.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/context/ClaimCollector.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/context/ContextRanker.scala`
-- Test: `memory-layer/src/test/scala/ix/memory/context/ContextServiceSpec.scala`
-
-**Step 1: Write the failing integration test**
-
-Test should:
-1. Ingest the billing_service.py fixture
-2. Call `contextService.query("How does billing retry?")`
-3. Verify the returned StructuredContext contains:
- - Nodes related to billing/retry
- - Claims (if any were asserted during ingestion)
- - Proper metadata (query, seed entities, revision)
-
-**Step 2: Implement EntityExtractor**
-
-Simple keyword extraction: split query into words, normalize, filter stopwords.
-
-```scala
-object EntityExtractor {
- private val stopwords = Set("how", "does", "the", "is", "a", "an", "what", "when", "where", "why", "do", "it")
-
- def extract(query: String): Vector[String] = {
- query.toLowerCase
- .split("[\\s,;.!?]+")
- .map(_.trim)
- .filter(w => w.nonEmpty && !stopwords.contains(w))
- .toVector
- .distinct
- }
-}
-```
-
-**Step 3: Implement GraphSeeder**
-
-Takes keywords → searches graph for matching nodes → returns seed IDs.
-
-```scala
-class GraphSeeder(queryApi: GraphQueryApi) {
- def seed(tenant: TenantId, terms: Vector[String],
- asOfRev: Option[Rev]): IO[Vector[GraphNode]] =
- terms.traverse(term => queryApi.searchNodes(tenant, term)).map(_.flatten.distinct)
-}
-```
-
-**Step 4: Implement GraphExpander**
-
-Takes seed nodes → expands 1-2 hops → returns subgraph.
-
-```scala
-class GraphExpander(queryApi: GraphQueryApi) {
- def expand(tenant: TenantId, seeds: Vector[NodeId], hops: Int,
- predicates: Option[Set[String]],
- asOfRev: Option[Rev]): IO[ExpandResult]
-}
-```
-
-**Step 5: Implement ClaimCollector**
-
-Gathers all claims attached to nodes in the expanded subgraph.
-
-```scala
-class ClaimCollector(queryApi: GraphQueryApi) {
- def collect(tenant: TenantId, nodeIds: Vector[NodeId]): IO[Vector[Claim]]
-}
-```
-
-**Step 6: Implement ContextRanker**
-
-Sorts claims by confidence descending, groups by entity.
-
-**Step 7: Implement ContextService**
-
-Orchestrates the full pipeline: extract → seed → expand → collect claims → score → detect conflicts → rank → assemble StructuredContext.
-
-```scala
-class ContextService(
- queryApi: GraphQueryApi,
- seeder: GraphSeeder,
- expander: GraphExpander,
- claimCollector: ClaimCollector,
- confidenceScorer: ConfidenceScorer,
- conflictDetector: ConflictDetector,
- ranker: ContextRanker
-) {
- def query(tenant: TenantId, question: String,
- asOfRev: Option[Rev] = None): IO[StructuredContext]
-}
-```
-
-**Step 8: Run tests, verify pass**
-
-**Step 9: Commit**
-
-```bash
-git commit -m "feat: add context service with entity extraction, seeding, expansion, and ranking"
-```
-
----
-
-## Task 8: Confidence Scorer
-
-**Files:**
-- Create: `memory-layer/src/main/scala/ix/memory/context/ConfidenceScorer.scala`
-- Test: `memory-layer/src/test/scala/ix/memory/context/ConfidenceScorerSpec.scala`
-
-**Step 1: Write the failing test**
-
-```scala
-class ConfidenceScorerSpec extends AnyFlatSpec with Matchers {
-
- val scorer = new ConfidenceScorer()
-
- "ConfidenceScorer" should "score code-sourced claims higher than doc-sourced" in {
- val codeClaim = makeClaim(SourceType.Code)
- val docClaim = makeClaim(SourceType.Doc)
-
- val codeScore = scorer.score(codeClaim, context)
- val docScore = scorer.score(docClaim, context)
-
- codeScore.score should be > docScore.score
- }
-
- it should "penalize claims with conflicts" in {
- val claim = makeClaim(SourceType.Code)
- val noConflict = scorer.score(claim, contextWithoutConflict)
- val withConflict = scorer.score(claim, contextWithConflict)
-
- noConflict.score should be > withConflict.score
- }
-
- it should "boost claims with corroboration" in {
- val claim = makeClaim(SourceType.Code)
- val single = scorer.score(claim, contextWith1Source)
- val corroborated = scorer.score(claim, contextWith3Sources)
-
- corroborated.score should be > single.score
- }
-
- it should "provide explainable breakdown" in {
- val claim = makeClaim(SourceType.Code)
- val result = scorer.score(claim, context)
-
- result.baseAuthority.reason should include("code")
- result.score should be > 0.0
- result.score should be <= 1.0
- }
-}
-```
-
-**Step 2: Implement ConfidenceScorer**
-
-Implements the formula from the design doc:
-- `baseAuthority` from `SourceType.baseAuthority(claim.provenance.sourceType)`
-- `verification` from test coverage data (default 1.0 for Phase 1)
-- `recency` from revision distance + source staleness check
-- `corroboration` from count of agreeing sources
-- `conflictPenalty` from conflict presence and relative authority
-
-```scala
-class ConfidenceScorer {
- def score(claim: Claim, ctx: ScoringContext): ConfidenceBreakdown = {
- val base = Factor(
- SourceType.baseAuthority(claim.provenance.sourceType),
- s"${claim.provenance.sourceType}, ${claim.provenance.extractor}"
- )
- val verif = Factor(1.0, "no verification data available")
- val recency = computeRecency(claim, ctx.latestRev, ctx.sourceChanged)
- val corr = computeCorroboration(claim, ctx.corroboratingCount)
- val conflict = computeConflictPenalty(claim, ctx.conflictState)
- ConfidenceBreakdown(base, verif, recency, corr, conflict)
- }
-}
-
-case class ScoringContext(
- latestRev: Rev,
- sourceChanged: Boolean, // Has the source file changed since observation?
- corroboratingCount: Int, // How many independent sources agree?
- conflictState: ConflictState
-)
-
-sealed trait ConflictState
-object ConflictState {
- case object None extends ConflictState
- case object ExistsHigherAuthority extends ConflictState
- case object ExistsLowerAuthority extends ConflictState
- case object ResolvedFor extends ConflictState
- case object ResolvedAgainst extends ConflictState
-}
-```
-
-**Step 3: Run tests, verify pass**
-
-**Step 4: Commit**
-
-```bash
-git commit -m "feat: add confidence scorer with explainable breakdowns"
-```
-
----
-
-## Task 9: Conflict Detector
-
-**Files:**
-- Create: `memory-layer/src/main/scala/ix/memory/conflict/ConflictDetector.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/conflict/ConflictService.scala`
-- Test: `memory-layer/src/test/scala/ix/memory/conflict/ConflictDetectorSpec.scala`
-
-**Step 1: Write the failing test**
-
-Test should:
-- Given two claims on the same entity with contradictory statements
-- ConflictDetector identifies them as conflicting
-- Creates a ConflictSet with both candidates
-- Generates a recommendation based on authority ranking
-
-**Step 2: Implement ConflictDetector**
-
-Phase 1 conflict detection: simple heuristic — two claims on the same entity with different values for the same attribute or contradictory statements.
-
-```scala
-class ConflictDetector {
- def detect(claims: Vector[ScoredClaim]): Vector[ConflictReport] = {
- // Group claims by entity_id
- // Within each group, find pairs where statements are contradictory
- // For now: same entity, different statement, both ACTIVE
- // Generate ConflictReport with recommendation based on confidence
- }
-}
-```
-
-**Step 3: Implement ConflictService**
-
-Wraps ConflictDetector + persistence of ConflictSets to DB + resolution API.
-
-```scala
-class ConflictService(queryApi: GraphQueryApi, writeApi: GraphWriteApi) {
- def detectAndStore(tenant: TenantId, claims: Vector[ScoredClaim]): IO[Vector[ConflictReport]]
- def listConflicts(tenant: TenantId, status: Option[ConflictStatus]): IO[Vector[ConflictSet]]
- def resolve(tenant: TenantId, conflictId: ConflictId, winnerClaimId: ClaimId): IO[Rev]
-}
-```
-
-**Step 4: Run tests, verify pass**
-
-**Step 5: Commit**
-
-```bash
-git commit -m "feat: add conflict detection and resolution service"
-```
-
----
-
-## Task 10: HTTP API Routes
-
-**Files:**
-- Create: `memory-layer/src/main/scala/ix/memory/api/Routes.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/api/ContextRoutes.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/api/IngestionRoutes.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/api/EntityRoutes.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/api/DiffRoutes.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/api/ConflictRoutes.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/api/ErrorHandler.scala`
-- Test: `memory-layer/src/test/scala/ix/memory/api/RoutesSpec.scala`
-
-**Step 1: Write the failing test**
-
-Test with http4s test client:
-
-```scala
-class RoutesSpec extends AsyncFlatSpec with AsyncIOSpec with Matchers {
-
- "POST /v1/context" should "return structured context" in {
- // Build the full app in-memory
- // POST /v1/context with { "query": "billing retry", "tenant": "test" }
- // Expect 200 with StructuredContext JSON
- }
-
- "POST /v1/ingest" should "accept a file path and return ingestion result" in {
- // POST /v1/ingest with { "path": "/tmp/test.py", "tenant": "test" }
- // Expect 200 with { patches_applied, new_rev, entities_created }
- }
-
- "GET /v1/entity/:id" should "return entity with claims and edges" in {
- // After ingesting, GET a known entity
- // Expect 200 with node, claims, edges, provenance
- }
-
- "GET /v1/health" should "return ok" in {
- // GET /v1/health
- // Expect 200 with { "status": "ok" }
- }
-}
-```
-
-**Step 2: Implement routes**
-
-Endpoints:
-
-| Method | Path | Handler | Description |
-|--------|------|---------|-------------|
-| GET | /v1/health | HealthRoute | Health check |
-| POST | /v1/context | ContextRoutes | Query graph for structured context |
-| POST | /v1/ingest | IngestionRoutes | Ingest source files |
-| GET | /v1/entity/:id | EntityRoutes | Get entity with claims + edges |
-| POST | /v1/diff | DiffRoutes | Diff between revisions |
-| GET | /v1/conflicts | ConflictRoutes | List conflicts |
-| POST | /v1/conflicts/:id/resolve | ConflictRoutes | Resolve a conflict |
-| POST | /v1/provenance/:id | EntityRoutes | Trace provenance chain |
-
-Request/response models:
-
-```scala
-// POST /v1/context
-case class ContextRequest(query: String, tenant: String, asOfRev: Option[Long])
-// Response: StructuredContext
-
-// POST /v1/ingest
-case class IngestRequest(path: String, tenant: String, language: Option[String], recursive: Option[Boolean])
-case class IngestResponse(filesProcessed: Int, patchesApplied: Int, entitiesCreated: Int, latestRev: Long)
-
-// POST /v1/conflicts/:id/resolve
-case class ResolveRequest(winnerClaimId: String)
-```
-
-**Step 3: Implement ErrorHandler**
-
-Map domain errors to HTTP status codes (same pattern as SD_Query_Engine).
-
-**Step 4: Run tests, verify pass**
-
-**Step 5: Commit**
-
-```bash
-git commit -m "feat: add HTTP API routes for context, ingestion, entity, diff, and conflicts"
-```
-
----
-
-## Task 11: Main Server Wiring
-
-**Files:**
-- Create: `memory-layer/src/main/scala/ix/memory/Main.scala`
-- Test: Manual smoke test
-
-**Step 1: Implement Main.scala**
-
-Wire everything together using Cats Effect Resource composition:
-
-```scala
-package ix.memory
-
-import cats.effect.{IO, IOApp, Resource}
-import org.http4s.ember.server.EmberServerBuilder
-import org.http4s.server.Router
-import com.comcast.ip4s._
-
-object Main extends IOApp.Simple {
- override def run: IO[Unit] = {
- val serverResource = for {
- // 1. ArangoDB client
- arangoClient <- ArangoClient.resource(
- host = sys.env.getOrElse("ARANGO_HOST", "localhost"),
- port = sys.env.getOrElse("ARANGO_PORT", "8529").toInt,
- database = sys.env.getOrElse("ARANGO_DATABASE", "ix_memory"),
- user = sys.env.getOrElse("ARANGO_USER", "root"),
- password = sys.env.getOrElse("ARANGO_PASSWORD", "")
- )
- _ <- Resource.eval(arangoClient.ensureSchema())
-
- // 2. Core APIs
- writeApi = ArangoGraphWriteApi(arangoClient)
- queryApi = ArangoGraphQueryApi(arangoClient)
-
- // 3. Services
- parserRouter = ParserRouter()
- ingestionService = IngestionService(parserRouter, writeApi)
- seeder = GraphSeeder(queryApi)
- expander = GraphExpander(queryApi)
- claimCollector = ClaimCollector(queryApi)
- confidenceScorer = ConfidenceScorer()
- conflictDetector = ConflictDetector()
- ranker = ContextRanker()
- contextService = ContextService(queryApi, seeder, expander,
- claimCollector, confidenceScorer,
- conflictDetector, ranker)
- conflictService = ConflictService(queryApi, writeApi)
-
- // 4. HTTP routes
- routes = Routes.all(contextService, ingestionService,
- queryApi, conflictService)
-
- // 5. Server
- server <- EmberServerBuilder
- .default[IO]
- .withHost(host"0.0.0.0")
- .withPort(
- Port.fromInt(sys.env.getOrElse("PORT", "8090").toInt)
- .getOrElse(port"8090"))
- .withHttpApp(Router("/" -> routes).orNotFound)
- .build
- } yield server
-
- serverResource.use { server =>
- IO.println(s"Ix Memory Layer running at ${server.address}") *> IO.never
- }
- }
-}
-```
-
-**Step 2: Smoke test**
-
-Run: `sbt "memory-layer/run"`
-Expected: Server starts on port 8090
-
-Test endpoints:
-```bash
-curl http://localhost:8090/v1/health
-# {"status":"ok"}
-
-curl -X POST http://localhost:8090/v1/ingest \
- -H "Content-Type: application/json" \
- -d '{"path":"/tmp/test.py","tenant":"test"}'
-
-curl -X POST http://localhost:8090/v1/context \
- -H "Content-Type: application/json" \
- -d '{"query":"billing retry","tenant":"test"}'
-```
-
-**Step 3: Commit**
-
-```bash
-git commit -m "feat: add Main server wiring — Memory Layer fully operational"
-```
-
----
-
-## Task 12: End-to-End Integration Test
-
-**Files:**
-- Create: `memory-layer/src/test/scala/ix/memory/EndToEndSpec.scala`
-- Create: `memory-layer/src/test/resources/fixtures/sample_project/billing_service.py`
-- Create: `memory-layer/src/test/resources/fixtures/sample_project/config.yaml`
-
-**Step 1: Write the full end-to-end test**
-
-```scala
-class EndToEndSpec extends AsyncFlatSpec with AsyncIOSpec with Matchers {
-
- "Ix Memory Layer" should "ingest Python code and answer queries with provenance" in {
- // 1. Start ArangoDB client + all services
- // 2. Ingest sample_project/billing_service.py
- // 3. Query "How does billing retry?"
- // 4. Verify:
- // - StructuredContext contains nodes for BillingService, retry_handler
- // - Claims are present with provenance pointing to billing_service.py
- // - Confidence scores are computed with explainable breakdowns
- // - Metadata shows correct seed entities and revision
- }
-
- it should "detect conflicts between contradictory sources" in {
- // 1. Ingest billing_service.py (says retry 3 times in code)
- // 2. Manually commit a patch asserting "retries 5 times" from README
- // 3. Query about retries
- // 4. Verify conflict is detected and reported
- // 5. Verify code-sourced claim has higher confidence
- }
-
- it should "support time-travel queries" in {
- // 1. Ingest file at rev N
- // 2. Modify and re-ingest at rev N+1
- // 3. Query asOfRev=N → old state
- // 4. Query asOfRev=N+1 → new state
- }
-
- it should "be idempotent on re-ingestion" in {
- // 1. Ingest billing_service.py → rev R1
- // 2. Ingest same file again (no changes) → rev R1 (idempotent)
- // 3. Node count should not increase
- }
-}
-```
-
-**Step 2: Run tests, verify pass**
-
-Run: `sbt "memory-layer/testOnly ix.memory.EndToEndSpec"`
-Expected: All integration tests pass
-
-**Step 3: Commit**
-
-```bash
-git commit -m "feat: add end-to-end integration tests for full ingestion-to-query pipeline"
-```
-
----
-
-## Summary
-
-| Task | Component | Depends On |
-|------|-----------|------------|
-| 1 | Project scaffold | — |
-| 2 | Core data model | 1 |
-| 3 | ArangoDB client + schema | 1 |
-| 4 | Graph write API (patch commit) | 2, 3 |
-| 5 | Graph query API | 2, 3 |
-| 6 | Ingestion (tree-sitter Python) | 2, 4 |
-| 7 | Context service (query pipeline) | 5, 8, 9 |
-| 8 | Confidence scorer | 2 |
-| 9 | Conflict detector | 2 |
-| 10 | HTTP API routes | 6, 7 |
-| 11 | Main server wiring | 10 |
-| 12 | End-to-end integration test | 11 |
-
-**Critical path:** 1 → 2 → 3 → 4 → 5 → 7 → 10 → 11 → 12
-**Parallel tracks:** Tasks 8 and 9 can be built in parallel with Tasks 4-5. Task 6 can be built in parallel with Task 5.
diff --git a/docs/plans/2026-03-03-ix-implementation-plan.md b/docs/plans/2026-03-03-ix-implementation-plan.md
deleted file mode 100644
index 34f164d2..00000000
--- a/docs/plans/2026-03-03-ix-implementation-plan.md
+++ /dev/null
@@ -1,1612 +0,0 @@
-# Ix Memory Layer Redesign — Implementation Plan
-
-> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
-
-**Goal:** Adapt the existing Scala Memory Layer (remove tenant, add Intent/Decision nodes, fix UpsertNode versioning, add parser-generated claims, update pipeline to 8 steps) and build a new TypeScript CLI + MCP server.
-
-**Architecture:** Phase 1 modifies existing Scala codebase (48 files). Phase 2 creates new TypeScript package. Both talk to ArangoDB via Docker. Design spec: `docs/plans/2026-03-03-ix-redesign.md`.
-
-**Tech Stack:**
-- **Phase 1:** Scala 2.13, Cats Effect 3, http4s 0.23, Circe 0.14, ArangoDB 7.12
-- **Phase 2:** TypeScript, commander.js, @modelcontextprotocol/sdk, node-fetch
-
----
-
-## Phase 1: Adapt Memory Layer (Scala)
-
-### Task 1: Remove TenantId from Model Classes
-
-**Files:**
-- Modify: `memory-layer/src/main/scala/ix/memory/model/Identifiers.scala`
-- Modify: `memory-layer/src/main/scala/ix/memory/model/Node.scala`
-- Modify: `memory-layer/src/main/scala/ix/memory/model/Edge.scala`
-- Modify: `memory-layer/src/main/scala/ix/memory/model/GraphPatch.scala`
-- Test: `memory-layer/src/test/scala/ix/memory/ModelSpec.scala`
-
-**Step 1: Write the failing test**
-
-In `ModelSpec.scala`, add a test that creates a `GraphNode` without tenant:
-
-```scala
-"GraphNode" should "not require TenantId" in {
- val node = GraphNode(
- id = NodeId(UUID.randomUUID()),
- kind = NodeKind.Function,
- attrs = Json.obj("name" -> "retry".asJson),
- provenance = testProvenance,
- createdRev = Rev(1L),
- deletedRev = None,
- createdAt = Instant.now(),
- updatedAt = Instant.now()
- )
- node.kind shouldBe NodeKind.Function
-}
-```
-
-**Step 2: Run test to verify it fails**
-
-Run: `cd memory-layer && sbt "testOnly ix.memory.ModelSpec"`
-Expected: FAIL — `GraphNode` still requires `tenant` parameter
-
-**Step 3: Remove TenantId from models**
-
-In `Identifiers.scala` — delete lines 7-11 (the full `TenantId` case class, object, encoder, decoder). Keep all other identifiers.
-
-In `Node.scala` — remove `tenant: TenantId` from `GraphNode` case class (line 52). Update encoder/decoder.
-
-In `Edge.scala` — remove `tenant: TenantId` from `GraphEdge` case class (line 17). Update encoder/decoder.
-
-In `GraphPatch.scala` — remove `tenant: TenantId` from `GraphPatch` case class (line 76). Remove comment on line 137 about tenant. Update encoder/decoder.
-
-**Step 4: Fix all compilation errors**
-
-Every file that imports or references `TenantId` will fail to compile. Fix each one by removing the `tenant` parameter. This touches ~25 files. For each file:
-- Remove `import ix.memory.model.TenantId` (or from wildcard import)
-- Remove `tenant` parameters from method signatures
-- Remove `tenant` from AQL query bind variables
-- Remove `"tenant" ->` from JSON objects being sent to ArangoDB
-
-Key files to update:
-- `db/GraphQueryApi.scala` — remove tenant from all 7 method signatures
-- `db/ArangoGraphQueryApi.scala` — remove tenant from all methods + AQL queries
-- `db/ArangoGraphWriteApi.scala` — remove tenant from commit path
-- `context/ContextService.scala` — remove tenant from `query()`
-- `context/GraphSeeder.scala` — remove tenant from `seed()`
-- `context/GraphExpander.scala` — remove tenant from `expand()`
-- `context/ClaimCollector.scala` — remove tenant from `collect()`
-- `conflict/ConflictService.scala` — remove tenant from all 4 methods
-- `ingestion/IngestionService.scala` — remove tenant from `ingestFile()` and `ingestPath()`
-- `ingestion/GraphPatchBuilder.scala` — remove tenant from `build()`, update deterministic ID: change `s"${tenant.value}:$filePath:$name"` to `s"$filePath:$name"`
-- `api/ContextRoutes.scala` — remove tenant from request parsing
-- `api/IngestionRoutes.scala` — remove tenant from request parsing
-- `api/EntityRoutes.scala` — remove tenant from query params
-- `api/DiffRoutes.scala` — remove tenant from request parsing
-- `api/ConflictRoutes.scala` — remove tenant from query params
-
-**Step 5: Run all tests to verify compilation**
-
-Run: `cd memory-layer && sbt compile`
-Expected: PASS (compiles with no tenant references)
-
-**Step 6: Update all existing tests**
-
-Update every test file to remove `TenantId` usage:
-- `ModelSpec.scala` — remove TenantId from test data
-- `GraphWriteApiSpec.scala` — remove tenant from test patches
-- `GraphQueryApiSpec.scala` — remove tenant from queries
-- `ContextServiceSpec.scala` — remove tenant from test calls
-- `EndToEndSpec.scala` — remove tenant from all 4 tests
-- `RoutesSpec.scala` — remove tenant from request bodies/query params
-- `ConflictDetectorSpec.scala` — remove tenant references
-- `ConfidenceScorerSpec.scala` — remove tenant references
-
-**Step 7: Run all tests**
-
-Run: `cd memory-layer && sbt test`
-Expected: All tests PASS (some may fail due to ArangoDB schema needing updates — that's Task 3)
-
-**Step 8: Commit**
-
-```bash
-git add memory-layer/src/
-git commit -m "feat: remove TenantId from all models and APIs (single-codebase system)"
-```
-
----
-
-### Task 2: Add Intent, Decision Node Kinds and FULFILLS Edge
-
-**Files:**
-- Modify: `memory-layer/src/main/scala/ix/memory/model/Node.scala`
-- Modify: `memory-layer/src/main/scala/ix/memory/model/StructuredContext.scala`
-- Test: `memory-layer/src/test/scala/ix/memory/ModelSpec.scala`
-
-**Step 1: Write the failing test**
-
-```scala
-"NodeKind" should "include Intent and Decision" in {
- NodeKind.fromString("Intent") shouldBe Some(NodeKind.Intent)
- NodeKind.fromString("Decision") shouldBe Some(NodeKind.Decision)
- NodeKind.Intent.baseAuthority shouldBe 0.85
- NodeKind.Decision.baseAuthority shouldBe 0.85
-}
-```
-
-**Step 2: Run test to verify it fails**
-
-Run: `cd memory-layer && sbt "testOnly ix.memory.ModelSpec"`
-Expected: FAIL — NodeKind.Intent does not exist
-
-**Step 3: Add Intent and Decision to NodeKind**
-
-In `Node.scala`, add to the `NodeKind` sealed trait:
-
-```scala
-case object Intent extends NodeKind
-case object Decision extends NodeKind
-```
-
-Update `baseAuthority()` method to include:
-```scala
-case Intent => 0.85
-case Decision => 0.85
-```
-
-Update `fromString()` and the Circe encoder/decoder to handle `"Intent"` and `"Decision"`.
-
-**Step 4: Update StructuredContext**
-
-In `StructuredContext.scala`, add:
-
-```scala
-final case class DecisionReport(
- title: String,
- rationale: String,
- entityId: Option[NodeId],
- intentId: Option[NodeId],
- rev: Rev
-)
-
-final case class IntentReport(
- id: NodeId,
- statement: String,
- status: String,
- confidence: Double,
- parentIntent: Option[String]
-)
-```
-
-Update `StructuredContext` to include:
-```scala
-final case class StructuredContext(
- claims: Vector[ScoredClaim],
- conflicts: Vector[ConflictReport],
- decisions: Vector[DecisionReport],
- intents: Vector[IntentReport],
- nodes: Vector[GraphNode],
- edges: Vector[GraphEdge],
- metadata: ContextMetadata
-)
-```
-
-Add `depth: Option[String]` to `ContextMetadata`.
-
-Add Circe encoders/decoders for new types.
-
-**Step 5: Run tests**
-
-Run: `cd memory-layer && sbt "testOnly ix.memory.ModelSpec"`
-Expected: PASS
-
-**Step 6: Commit**
-
-```bash
-git add memory-layer/src/main/scala/ix/memory/model/
-git commit -m "feat: add Intent, Decision node kinds and update StructuredContext"
-```
-
----
-
-### Task 3: Update ArangoDB Schema (Remove Tenant Indexes)
-
-**Files:**
-- Modify: `memory-layer/src/main/scala/ix/memory/db/ArangoSchema.scala`
-- Test: `memory-layer/src/test/scala/ix/memory/ArangoClientSpec.scala`
-
-**Step 1: Write the failing test**
-
-```scala
-"ensureSchema" should "create schema without tenant indexes" in {
- clientResource.use { client =>
- for {
- _ <- client.ensureSchema()
- // Verify nodes collection exists
- result <- client.query("RETURN LENGTH(nodes)", Map.empty)
- } yield {
- result should not be empty
- }
- }
-}
-```
-
-**Step 2: Run test to verify current state**
-
-Run: `cd memory-layer && sbt "testOnly ix.memory.ArangoClientSpec"`
-
-**Step 3: Update ArangoSchema**
-
-In `ArangoSchema.scala`, update `ensure()` method:
-- Remove all `"tenant"` fields from index definitions
-- Change index on nodes from `["tenant", "kind"]` to `["kind"]`
-- Change index on nodes from `["tenant", "name"]` to `["name"]` (fulltext)
-- Change index on edges from `["tenant", "src"]` to `["src"]`
-- Change index on edges from `["tenant", "dst"]` to `["dst"]`
-- Change index on claims from `["tenant", "entity_id"]` to `["entity_id"]`
-- Change index on claims from `["tenant", "status"]` to `["status"]`
-- Change index on patches from `["tenant", "patch_id"]` to `["patch_id"]`
-- Change revisions key from tenant-based to a single `"current"` key
-- Add index on claims for `["statement"]` (fulltext, for claim-based search)
-- Add index on patches for `["source_uri", "extractor"]` (for replaces discovery)
-
-**Step 4: Run test**
-
-Run: `cd memory-layer && sbt "testOnly ix.memory.ArangoClientSpec"`
-Expected: PASS
-
-**Step 5: Commit**
-
-```bash
-git add memory-layer/src/main/scala/ix/memory/db/ArangoSchema.scala
-git commit -m "feat: update ArangoDB schema — remove tenant indexes, add claim/patch indexes"
-```
-
----
-
-### Task 4: Fix UpsertNode Versioning (Tombstone + New Row)
-
-**Files:**
-- Modify: `memory-layer/src/main/scala/ix/memory/db/ArangoGraphWriteApi.scala`
-- Test: `memory-layer/src/test/scala/ix/memory/GraphWriteApiSpec.scala`
-
-**Step 1: Write the failing test**
-
-```scala
-"UpsertNode" should "version node when attrs change (tombstone old, create new)" in {
- clientResource.use { client =>
- val writeApi = new ArangoGraphWriteApi(client)
- val queryApi = new ArangoGraphQueryApi(client)
- val nodeId = NodeId(UUID.randomUUID())
-
- val patch1 = makePatch(ops = Vector(
- PatchOp.UpsertNode(nodeId, NodeKind.Function, "retry", Map("max_retries" -> Json.fromInt(3)))
- ))
- val patch2 = makePatch(baseRev = Rev(1L), ops = Vector(
- PatchOp.UpsertNode(nodeId, NodeKind.Function, "retry", Map("max_retries" -> Json.fromInt(5)))
- ))
-
- for {
- _ <- client.ensureSchema()
- commit1 <- writeApi.commitPatch(patch1)
- commit2 <- writeApi.commitPatch(patch2)
- // Query at rev 1 should see max_retries=3
- nodeAtRev1 <- queryApi.getNode(nodeId, asOfRev = Some(commit1.newRev))
- // Query at rev 2 should see max_retries=5
- nodeAtRev2 <- queryApi.getNode(nodeId, asOfRev = Some(commit2.newRev))
- } yield {
- nodeAtRev1 shouldBe defined
- nodeAtRev1.get.attrs.hcursor.get[Int]("max_retries").toOption shouldBe Some(3)
-
- nodeAtRev2 shouldBe defined
- nodeAtRev2.get.attrs.hcursor.get[Int]("max_retries").toOption shouldBe Some(5)
- }
- }
-}
-```
-
-**Step 2: Run test to verify it fails**
-
-Run: `cd memory-layer && sbt "testOnly ix.memory.GraphWriteApiSpec"`
-Expected: FAIL — nodeAtRev1 returns max_retries=5 (current behavior overwrites attrs)
-
-**Step 3: Update ArangoGraphWriteApi UpsertNode handler**
-
-In `ArangoGraphWriteApi.scala`, modify the `executeOp` case for `UpsertNode` (currently ~lines 100-140):
-
-```scala
-case PatchOp.UpsertNode(id, kind, name, attrs) =>
- val logicalId = id.value.toString
- // Check if node exists at current state
- val checkAql = """
- FOR n IN nodes
- FILTER n._key LIKE CONCAT(@logicalId, "%")
- AND n.deleted_rev == null
- RETURN n
- """
- for {
- existing <- client.queryOne(checkAql, Map("logicalId" -> logicalId), txId)
- _ <- existing match {
- case Some(existingJson) =>
- // Node exists — check if attrs changed
- val existingAttrs = existingJson.hcursor.get[Json]("attrs").getOrElse(Json.Null)
- val newAttrsJson = attrsToJson(attrs)
- if (existingAttrs == newAttrsJson) {
- // Same attrs — idempotent no-op
- IO.unit
- } else {
- // Different attrs — tombstone old row + create new row
- val existingKey = existingJson.hcursor.get[String]("_key").getOrElse(logicalId)
- val tombstoneAql = """
- UPDATE { _key: @key } WITH { deleted_rev: @rev } IN nodes
- OPTIONS { waitForSync: true }
- """
- val newKey = s"${logicalId}_${newRev.value}"
- val insertAql = """
- INSERT {
- _key: @key, logical_id: @logicalId, kind: @kind, name: @name,
- attrs: @attrs, provenance: @prov,
- created_rev: @rev, deleted_rev: null,
- created_at: @now, updated_at: @now
- } INTO nodes OPTIONS { waitForSync: true }
- """
- for {
- _ <- client.execute(tombstoneAql, Map("key" -> existingKey, "rev" -> newRev.value), txId)
- _ <- client.execute(insertAql, Map(
- "key" -> newKey, "logicalId" -> logicalId,
- "kind" -> kind.toString, "name" -> name,
- "attrs" -> newAttrsJson, "prov" -> provenanceJson,
- "rev" -> newRev.value, "now" -> Instant.now().toString
- ), txId)
- } yield ()
- }
-
- case None =>
- // New node — create first row
- val newKey = s"${logicalId}_${newRev.value}"
- val insertAql = """
- INSERT {
- _key: @key, logical_id: @logicalId, kind: @kind, name: @name,
- attrs: @attrs, provenance: @prov,
- created_rev: @rev, deleted_rev: null,
- created_at: @now, updated_at: @now
- } INTO nodes OPTIONS { waitForSync: true }
- """
- client.execute(insertAql, Map(
- "key" -> newKey, "logicalId" -> logicalId,
- "kind" -> kind.toString, "name" -> name,
- "attrs" -> attrsToJson(attrs), "prov" -> provenanceJson,
- "rev" -> newRev.value, "now" -> Instant.now().toString
- ), txId)
- }
- } yield ()
-```
-
-**Step 4: Update ArangoGraphQueryApi to use logical_id**
-
-In `ArangoGraphQueryApi.scala`, update `getNode()` to filter by `logical_id` and MVCC:
-
-```scala
-def getNode(id: NodeId, asOfRev: Option[Rev] = None): IO[Option[GraphNode]] = {
- val rev = asOfRev.getOrElse(/* latest */)
- val aql = """
- FOR n IN nodes
- FILTER n.logical_id == @id
- AND n.created_rev <= @rev
- AND (n.deleted_rev == null OR @rev < n.deleted_rev)
- RETURN n
- """
- client.queryOne(aql, Map("id" -> id.value.toString, "rev" -> rev.value))
- .map(_.flatMap(parseNode))
-}
-```
-
-Update all other query methods similarly — use `logical_id` instead of `_key` for node lookups.
-
-**Step 5: Run test**
-
-Run: `cd memory-layer && sbt "testOnly ix.memory.GraphWriteApiSpec"`
-Expected: PASS — time-travel returns correct attrs at each revision
-
-**Step 6: Commit**
-
-```bash
-git add memory-layer/src/main/scala/ix/memory/db/
-git commit -m "feat: UpsertNode versioning — tombstone old row, create new row for attr changes"
-```
-
----
-
-### Task 5: Add Parser-Generated Claims to Ingestion
-
-**Files:**
-- Modify: `memory-layer/src/main/scala/ix/memory/ingestion/GraphPatchBuilder.scala`
-- Modify: `memory-layer/src/main/scala/ix/memory/ingestion/ParseResult.scala`
-- Test: `memory-layer/src/test/scala/ix/memory/ingestion/TreeSitterPythonParserSpec.scala`
-
-**Step 1: Write the failing test**
-
-```scala
-"GraphPatchBuilder" should "generate claims from parsed entities" in {
- val parseResult = ParseResult(
- entities = Vector(
- ParsedEntity("BillingService", NodeKind.Class, Map.empty, Some(3), Some(10)),
- ParsedEntity("retry_payment", NodeKind.Function,
- Map("signature" -> "retry_payment(self, amount, max_retries=3)"),
- Some(4), Some(9))
- ),
- relationships = Vector(
- ParsedRelationship("BillingService", "retry_payment", "DEFINES")
- )
- )
-
- val builder = new GraphPatchBuilder("billing_service.py", "abc123")
- val patch = builder.build(parseResult)
-
- val assertOps = patch.ops.collect { case a: PatchOp.AssertClaim => a }
- assertOps should not be empty
- assertOps.exists(_.statement == "defines_method:retry_payment") shouldBe true
-}
-```
-
-**Step 2: Run test to verify it fails**
-
-Run: `cd memory-layer && sbt "testOnly *TreeSitterPythonParserSpec"`
-Expected: FAIL — no AssertClaim ops generated
-
-**Step 3: Update GraphPatchBuilder to generate claims**
-
-In `GraphPatchBuilder.scala`, add claim generation after node/edge ops:
-
-```scala
-// After building UpsertNode and UpsertEdge ops, add claims:
-val claimOps: Vector[PatchOp] = relationships.flatMap { rel =>
- val srcId = nodeIdFor(rel.srcName)
- Vector(
- PatchOp.AssertClaim(srcId, s"${rel.predicate.toLowerCase}:${rel.dstName}",
- Json.fromString(rel.dstName), None)
- )
-} ++ entities.flatMap { entity =>
- val entityId = nodeIdFor(entity.name)
- // Generate claims from attrs (e.g., signature → parameter defaults)
- entity.attrs.flatMap { case (key, value) =>
- Vector(PatchOp.AssertClaim(entityId, s"$key", Json.fromString(value), None))
- }.toVector
-}
-
-// Combine: nodes + edges + claims
-val allOps = nodeOps ++ edgeOps ++ claimOps
-```
-
-**Step 4: Run test**
-
-Run: `cd memory-layer && sbt "testOnly *TreeSitterPythonParserSpec"`
-Expected: PASS
-
-**Step 5: Commit**
-
-```bash
-git add memory-layer/src/main/scala/ix/memory/ingestion/
-git commit -m "feat: parsers now generate claims alongside nodes and edges"
-```
-
----
-
-### Task 6: Add Replaces Discovery Mechanism
-
-**Files:**
-- Modify: `memory-layer/src/main/scala/ix/memory/db/GraphQueryApi.scala`
-- Modify: `memory-layer/src/main/scala/ix/memory/db/ArangoGraphQueryApi.scala`
-- Modify: `memory-layer/src/main/scala/ix/memory/ingestion/IngestionService.scala`
-- Test: `memory-layer/src/test/scala/ix/memory/EndToEndSpec.scala`
-
-**Step 1: Write the failing test**
-
-```scala
-"IngestionService" should "set replaces when re-ingesting a changed file" in {
- clientResource.use { client =>
- val writeApi = new ArangoGraphWriteApi(client)
- val queryApi = new ArangoGraphQueryApi(client)
- val parserRouter = new ParserRouter()
- val ingestion = new IngestionService(parserRouter, writeApi, queryApi)
-
- for {
- _ <- client.ensureSchema()
- commit1 <- ingestion.ingestFile(fixtureFilePath)
- // Modify file content hash simulation — re-ingest
- commit2 <- ingestion.ingestFile(fixtureFilePath)
- // Get patches for the file
- patches <- queryApi.getPatchesBySource("billing_service.py", "tree-sitter-python")
- } yield {
- patches.size should be >= 1
- // Second ingestion should either be idempotent (same hash) or have replaces set
- }
- }
-}
-```
-
-**Step 2: Run test to verify it fails**
-
-Run: `cd memory-layer && sbt "testOnly ix.memory.EndToEndSpec"`
-Expected: FAIL — `getPatchesBySource` method doesn't exist, `IngestionService` doesn't accept `queryApi`
-
-**Step 3: Add getPatchesBySource to GraphQueryApi**
-
-In `GraphQueryApi.scala` trait, add:
-```scala
-def getPatchesBySource(sourceUri: String, extractor: String): IO[Vector[Json]]
-```
-
-In `ArangoGraphQueryApi.scala`, implement:
-```scala
-def getPatchesBySource(sourceUri: String, extractor: String): IO[Vector[Json]] = {
- val aql = """
- FOR p IN patches
- FILTER p.source.uri == @uri AND p.source.extractor == @extractor
- SORT p.base_rev DESC
- RETURN p
- """
- client.query(aql, Map("uri" -> sourceUri, "extractor" -> extractor))
-}
-```
-
-**Step 4: Update IngestionService to use replaces**
-
-In `IngestionService.scala`, update constructor to accept `queryApi: GraphQueryApi`. In `ingestFile()`:
-
-```scala
-def ingestFile(filePath: Path): IO[CommitResult] = {
- for {
- content <- IO(java.nio.file.Files.readString(filePath))
- hash = MessageDigest.getInstance("SHA-256")
- .digest(content.getBytes).map("%02x".format(_)).mkString
- parser <- IO.fromOption(parserRouter.parserFor(filePath))(
- new UnsupportedOperationException(s"No parser for $filePath"))
- result <- parser.parse(filePath, content)
- // Check for existing patch from same source+extractor
- existing <- queryApi.getPatchesBySource(filePath.toString, parser.name)
- prevPatch = existing.headOption
- prevHash = prevPatch.flatMap(_.hcursor.downField("source").get[String]("hash").toOption)
- _ <- if (prevHash.contains(hash)) IO.raiseError(new RuntimeException("Idempotent — no changes"))
- else IO.unit
- prevPatchId = prevPatch.flatMap(_.hcursor.get[String]("patch_id").toOption).map(UUID.fromString).map(PatchId(_))
- replaces = prevPatchId.toVector
- builder = new GraphPatchBuilder(filePath.toString, hash)
- patch = builder.build(result).copy(replaces = replaces)
- validated <- IO.fromEither(PatchValidator.validate(patch).leftMap(e => new IllegalArgumentException(e)))
- commit <- writeApi.commitPatch(validated)
- } yield commit
-}
-```
-
-**Step 5: Update Main.scala to pass queryApi to IngestionService**
-
-```scala
-ingestionService = new IngestionService(parserRouter, writeApi, queryApi)
-```
-
-**Step 6: Run test**
-
-Run: `cd memory-layer && sbt "testOnly ix.memory.EndToEndSpec"`
-Expected: PASS
-
-**Step 7: Commit**
-
-```bash
-git add memory-layer/src/
-git commit -m "feat: add replaces discovery — re-ingestion links to previous patch by source+extractor"
-```
-
----
-
-### Task 7: Update Confidence Scorer (6 Factors, Wall-Clock Recency)
-
-**Files:**
-- Modify: `memory-layer/src/main/scala/ix/memory/model/ConfidenceBreakdown.scala`
-- Modify: `memory-layer/src/main/scala/ix/memory/context/ConfidenceScorer.scala`
-- Test: `memory-layer/src/test/scala/ix/memory/ConfidenceScorerSpec.scala`
-
-**Step 1: Write the failing test**
-
-```scala
-"ConfidenceScorerImpl" should "include intent alignment factor in score" in {
- val scorer = new ConfidenceScorerImpl()
- val claim = testClaim(sourceType = SourceType.Code)
- val ctx = ScoringContext(
- latestRev = Rev(10L),
- sourceChanged = false,
- corroboratingCount = 1,
- conflictState = ConflictState.NoConflict,
- intentAlignment = IntentAlignment.DirectlyLinked,
- observedAt = Instant.now()
- )
- val breakdown = scorer.score(claim, ctx)
- breakdown.intentAlignment.value shouldBe 1.1
- breakdown.score should be > 0.0
-}
-```
-
-**Step 2: Run test to verify it fails**
-
-Run: `cd memory-layer && sbt "testOnly ix.memory.ConfidenceScorerSpec"`
-Expected: FAIL — `intentAlignment` field doesn't exist, `IntentAlignment` enum doesn't exist
-
-**Step 3: Update ConfidenceBreakdown**
-
-Add `intentAlignment: Factor` field to `ConfidenceBreakdown`. Update the `score` method to multiply by it.
-
-**Step 4: Add IntentAlignment enum to ScoringContext**
-
-```scala
-sealed trait IntentAlignment
-object IntentAlignment {
- case object DirectlyLinked extends IntentAlignment // × 1.1
- case object WithinTwoHops extends IntentAlignment // × 1.05
- case object NoConnection extends IntentAlignment // × 1.0
- case object ContradictsIntent extends IntentAlignment // × 0.85
-}
-```
-
-Add `intentAlignment: IntentAlignment` and `observedAt: Instant` to `ScoringContext`.
-
-**Step 5: Update ConfidenceScorerImpl**
-
-Change `computeRecency` to use wall-clock time:
-
-```scala
-private def computeRecency(ctx: ScoringContext): Factor = {
- if (!ctx.sourceChanged) return Factor(1.0, "Source unchanged since observation")
- val age = java.time.Duration.between(ctx.observedAt, Instant.now())
- val days = age.toDays
- val (value, reason) = days match {
- case d if d < 1 => (1.0, "< 1 day ago")
- case d if d <= 7 => (0.95, "1-7 days ago")
- case d if d <= 28 => (0.85, "1-4 weeks ago")
- case d if d <= 180 => (0.70, "1-6 months ago")
- case _ => (0.50, "6+ months ago")
- }
- Factor(value, reason)
-}
-```
-
-Add `computeIntentAlignment`:
-
-```scala
-private def computeIntentAlignment(ctx: ScoringContext): Factor = {
- ctx.intentAlignment match {
- case IntentAlignment.DirectlyLinked => Factor(1.1, "Directly linked to active intent")
- case IntentAlignment.WithinTwoHops => Factor(1.05, "Connected to intent within 2 hops")
- case IntentAlignment.NoConnection => Factor(1.0, "No connection to intent")
- case IntentAlignment.ContradictsIntent => Factor(0.85, "Contradicts active intent")
- }
-}
-```
-
-**Step 6: Run test**
-
-Run: `cd memory-layer && sbt "testOnly ix.memory.ConfidenceScorerSpec"`
-Expected: PASS
-
-**Step 7: Commit**
-
-```bash
-git add memory-layer/src/
-git commit -m "feat: confidence scoring — 6 factors, wall-clock recency, intent alignment"
-```
-
----
-
-### Task 8: Update Conflict Detector (Multi-Pass)
-
-**Files:**
-- Modify: `memory-layer/src/main/scala/ix/memory/context/ConflictDetector.scala`
-- Test: `memory-layer/src/test/scala/ix/memory/ConflictDetectorSpec.scala`
-
-**Step 1: Write the failing test**
-
-```scala
-"ConflictDetectorImpl" should "detect keyword-overlap conflicts (pass 2)" in {
- val detector = new ConflictDetectorImpl()
- val claims = Vector(
- testScoredClaim("max_retries", Json.fromInt(3), 0.90),
- testScoredClaim("does not retry", Json.fromBoolean(true), 0.64)
- )
- val conflicts = detector.detect(claims)
- // "max_retries" and "does not retry" both contain "retr" → potential conflict
- conflicts should not be empty
-}
-```
-
-**Step 2: Run test to verify it fails**
-
-Run: `cd memory-layer && sbt "testOnly ix.memory.ConflictDetectorSpec"`
-Expected: FAIL — current detector only matches exact field names
-
-**Step 3: Implement multi-pass conflict detection**
-
-```scala
-class ConflictDetectorImpl extends ConflictDetector {
- def detect(claims: Vector[ScoredClaim]): Vector[ConflictReport] = {
- val byEntity = claims.groupBy(_.claim.entityId)
- byEntity.values.flatMap { entityClaims =>
- val activeClaims = entityClaims.filter(_.claim.status == ClaimStatus.Active)
- if (activeClaims.size < 2) Vector.empty
- else {
- val pairs = activeClaims.combinations(2).toVector
- pairs.flatMap { case Vector(a, b) =>
- // Pass 1: exact field match, different value
- if (a.claim.statement == b.claim.statement && a.claim.value != b.claim.value) {
- Some(makeConflict(a, b, "Same field, different values"))
- }
- // Pass 2: keyword overlap
- else if (keywordsOverlap(a.claim.statement, b.claim.statement)) {
- Some(makeConflict(a, b, "Contradictory statements (keyword overlap)"))
- }
- else None
- }
- }
- }.toVector
- }
-
- private def keywordsOverlap(a: String, b: String): Boolean = {
- val wordsA = tokenize(a)
- val wordsB = tokenize(b)
- // Check for shared stems (3+ chars) that could indicate contradiction
- val stemsA = wordsA.map(_.take(4).toLowerCase).toSet
- val stemsB = wordsB.map(_.take(4).toLowerCase).toSet
- (stemsA intersect stemsB).nonEmpty
- }
-
- private def tokenize(s: String): Vector[String] =
- s.split("[^a-zA-Z0-9]+").filter(_.length >= 3).toVector
-}
-```
-
-**Step 4: Run test**
-
-Run: `cd memory-layer && sbt "testOnly ix.memory.ConflictDetectorSpec"`
-Expected: PASS
-
-**Step 5: Commit**
-
-```bash
-git add memory-layer/src/
-git commit -m "feat: multi-pass conflict detection — exact match + keyword overlap"
-```
-
----
-
-### Task 9: Update Context Pipeline (8 Steps, Relevance, Edge Priority)
-
-**Files:**
-- Modify: `memory-layer/src/main/scala/ix/memory/context/ContextService.scala`
-- Modify: `memory-layer/src/main/scala/ix/memory/context/GraphExpander.scala`
-- Modify: `memory-layer/src/main/scala/ix/memory/context/ContextRanker.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/context/RelevanceScorer.scala`
-- Test: `memory-layer/src/test/scala/ix/memory/ContextServiceSpec.scala`
-
-**Step 1: Write the failing test**
-
-```scala
-"ContextService" should "return relevance-scored claims in StructuredContext" in {
- // Setup: create nodes, claims, query
- // Verify: claims have relevance scores, sorted by relevance × confidence
- result.claims.head.relevance should be > 0.0
- result.metadata.depth shouldBe Some("standard")
-}
-```
-
-**Step 2: Run test to verify it fails**
-
-Run: `cd memory-layer && sbt "testOnly ix.memory.ContextServiceSpec"`
-Expected: FAIL — `relevance` field doesn't exist on ScoredClaim
-
-**Step 3: Create RelevanceScorer**
-
-```scala
-package ix.memory.context
-
-import ix.memory.model._
-
-object RelevanceScorer {
- def score(
- claims: Vector[ScoredClaim],
- seedNodeIds: Set[NodeId],
- expandedEdges: Vector[GraphEdge]
- ): Vector[ScoredClaim] = {
- // Build hop-distance map
- val oneHopIds = expandedEdges
- .flatMap(e => Vector(e.src, e.dst))
- .toSet -- seedNodeIds
-
- claims.map { sc =>
- val relevance = if (seedNodeIds.contains(sc.claim.entityId)) 1.0
- else if (oneHopIds.contains(sc.claim.entityId)) 0.7
- else 0.4
- sc.copy(relevance = relevance, finalScore = relevance * sc.confidence.score)
- }
- }
-}
-```
-
-Add `relevance: Double = 1.0` and `finalScore: Double = 0.0` to `ScoredClaim`.
-
-**Step 4: Update GraphExpander with edge priority**
-
-Add priority filtering to the expand method — skip low-priority edges (MENTIONED_IN, CHANGED_WITH, SAME_AS) at hop 2+.
-
-**Step 5: Update ContextService to use 8-step pipeline**
-
-```scala
-def query(question: String, asOfRev: Option[Rev] = None, depth: Option[String] = None): IO[StructuredContext] = {
- for {
- terms <- IO(EntityExtractor.extract(question)) // Step 1
- seeds <- seeder.seed(terms, asOfRev) // Step 2
- expanded <- expander.expand(seeds.map(_.id), asOfRev) // Step 3 (with priority)
- allNodeIds = (seeds.map(_.id) ++ expanded.nodes.map(_.id)).toSet
- claims <- collector.collect(allNodeIds) // Step 4
- scored <- scoreAll(claims, asOfRev) // Step 5
- conflicts = detector.detect(scored) // Step 6
- relevant = RelevanceScorer.score(scored, seeds.map(_.id).toSet, expanded.edges) // Step 7
- ranked = relevant.sortBy(-_.finalScore) // Step 8
- // Collect decisions and intents from expanded nodes
- decisions = expanded.nodes.filter(_.kind == NodeKind.Decision).map(toDecisionReport)
- intents = expanded.nodes.filter(_.kind == NodeKind.Intent).map(toIntentReport)
- metadata = ContextMetadata(question, seeds.map(_.id.value.toString),
- hopsExpanded = 1, asOfRev = asOfRev.getOrElse(Rev(0L)),
- depth = depth)
- } yield StructuredContext(ranked, conflicts, decisions, intents,
- expanded.nodes, expanded.edges, metadata)
-}
-```
-
-**Step 6: Run tests**
-
-Run: `cd memory-layer && sbt "testOnly ix.memory.ContextServiceSpec"`
-Expected: PASS
-
-**Step 7: Commit**
-
-```bash
-git add memory-layer/src/
-git commit -m "feat: 8-step context pipeline — relevance scoring, edge priority, intent/decision collection"
-```
-
----
-
-### Task 10: Add New API Endpoints
-
-**Files:**
-- Create: `memory-layer/src/main/scala/ix/memory/api/DecideRoutes.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/api/SearchRoutes.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/api/TruthRoutes.scala`
-- Create: `memory-layer/src/main/scala/ix/memory/api/PatchRoutes.scala`
-- Modify: `memory-layer/src/main/scala/ix/memory/api/Routes.scala`
-- Modify: `memory-layer/src/main/scala/ix/memory/Main.scala`
-- Test: `memory-layer/src/test/scala/ix/memory/RoutesSpec.scala`
-
-**Step 1: Write the failing tests**
-
-```scala
-"POST /v1/decide" should "create a decision node" in {
- val body = json"""{"title": "Use exponential backoff", "rationale": "Better for transient failures"}"""
- val req = Request[IO](Method.POST, uri"/v1/decide").withEntity(body)
- routes.run(req).flatMap { resp =>
- resp.status shouldBe Status.Ok
- resp.as[Json].map { body =>
- body.hcursor.get[String]("status").toOption shouldBe Some("Ok")
- }
- }
-}
-
-"POST /v1/search" should "find nodes by term" in {
- val body = json"""{"term": "billing"}"""
- val req = Request[IO](Method.POST, uri"/v1/search").withEntity(body)
- routes.run(req).flatMap { resp =>
- resp.status shouldBe Status.Ok
- }
-}
-
-"GET /v1/truth" should "return intent hierarchy" in {
- val req = Request[IO](Method.GET, uri"/v1/truth")
- routes.run(req).flatMap { resp =>
- resp.status shouldBe Status.Ok
- }
-}
-
-"GET /v1/patches" should "list recent patches" in {
- val req = Request[IO](Method.GET, uri"/v1/patches")
- routes.run(req).flatMap { resp =>
- resp.status shouldBe Status.Ok
- }
-}
-```
-
-**Step 2: Run tests to verify they fail**
-
-Run: `cd memory-layer && sbt "testOnly ix.memory.RoutesSpec"`
-Expected: FAIL — routes don't exist
-
-**Step 3: Implement route classes**
-
-Create each route file following the pattern from existing routes (ContextRoutes, EntityRoutes). Each is a thin HTTP handler that calls the appropriate service.
-
-`DecideRoutes.scala` — POST /v1/decide → creates Decision node via GraphWriteApi
-`SearchRoutes.scala` — POST /v1/search → calls queryApi.searchNodes
-`TruthRoutes.scala` — GET /v1/truth, POST /v1/truth → manage Intent nodes
-`PatchRoutes.scala` — GET /v1/patches, GET /v1/patches/:id → query patches collection
-
-**Step 4: Wire into Routes.scala**
-
-```scala
-val decideRoutes = new DecideRoutes(writeApi).routes
-val searchRoutes = new SearchRoutes(queryApi).routes
-val truthRoutes = new TruthRoutes(writeApi, queryApi).routes
-val patchRoutes = new PatchRoutes(queryApi).routes
-
-health <+> contextRoutes <+> ingestionRoutes <+> entityRoutes <+>
- diffRoutes <+> conflictRoutes <+> decideRoutes <+> searchRoutes <+>
- truthRoutes <+> patchRoutes
-```
-
-Update `Main.scala` to pass the new dependencies.
-
-**Step 5: Run tests**
-
-Run: `cd memory-layer && sbt "testOnly ix.memory.RoutesSpec"`
-Expected: PASS
-
-**Step 6: Commit**
-
-```bash
-git add memory-layer/src/
-git commit -m "feat: add /v1/decide, /v1/search, /v1/truth, /v1/patches endpoints"
-```
-
----
-
-### Task 11: Update All Existing Tests for No-Tenant + New Schema
-
-**Files:**
-- Modify: all test files in `memory-layer/src/test/scala/ix/memory/`
-
-**Step 1: Run full test suite**
-
-Run: `cd memory-layer && sbt test`
-Note all failures.
-
-**Step 2: Fix each test file**
-
-Remove TenantId from test data, update assertions for new StructuredContext fields, ensure ArangoDB schema initialization works with new indexes.
-
-**Step 3: Run full test suite again**
-
-Run: `cd memory-layer && sbt test`
-Expected: ALL PASS
-
-**Step 4: Commit**
-
-```bash
-git add memory-layer/src/test/
-git commit -m "test: update all tests for no-tenant, versioned upserts, and new pipeline"
-```
-
----
-
-## Phase 2: TypeScript CLI + MCP Server
-
-### Task 12: Initialize TypeScript Project
-
-**Files:**
-- Create: `ix-cli/package.json`
-- Create: `ix-cli/tsconfig.json`
-- Create: `ix-cli/src/index.ts`
-
-**Step 1: Create project structure**
-
-```bash
-mkdir -p ix-cli/src/{cli,mcp/{tools,resources},client}
-mkdir -p ix-cli/test
-cd ix-cli
-```
-
-**Step 2: Initialize package.json**
-
-```json
-{
- "name": "@ix/cli",
- "version": "0.1.0",
- "description": "Ix Memory — Persistent Memory for LLM Systems",
- "main": "dist/index.js",
- "bin": {
- "ix": "dist/cli/main.js"
- },
- "scripts": {
- "build": "tsc",
- "test": "vitest",
- "dev": "tsx src/cli/main.ts"
- },
- "dependencies": {
- "commander": "^12.0.0",
- "@modelcontextprotocol/sdk": "^1.0.0",
- "node-fetch": "^3.3.0",
- "chalk": "^5.3.0",
- "yaml": "^2.4.0"
- },
- "devDependencies": {
- "typescript": "^5.4.0",
- "vitest": "^1.6.0",
- "tsx": "^4.7.0",
- "@types/node": "^20.0.0"
- }
-}
-```
-
-**Step 3: Create tsconfig.json**
-
-```json
-{
- "compilerOptions": {
- "target": "ES2022",
- "module": "Node16",
- "moduleResolution": "Node16",
- "outDir": "dist",
- "rootDir": "src",
- "strict": true,
- "esModuleInterop": true,
- "declaration": true
- },
- "include": ["src"]
-}
-```
-
-**Step 4: Install dependencies**
-
-Run: `cd ix-cli && npm install`
-
-**Step 5: Verify build**
-
-Run: `cd ix-cli && npm run build`
-Expected: Compiles with no errors
-
-**Step 6: Commit**
-
-```bash
-git add ix-cli/
-git commit -m "feat: initialize ix-cli TypeScript project with dependencies"
-```
-
----
-
-### Task 13: Build HTTP Client for Memory Layer API
-
-**Files:**
-- Create: `ix-cli/src/client/api.ts`
-- Create: `ix-cli/src/client/types.ts`
-- Test: `ix-cli/test/client.test.ts`
-
-**Step 1: Create types.ts**
-
-Define TypeScript interfaces matching the Scala API responses:
-
-```typescript
-export interface CommitResult {
- newRev: number;
- status: "Ok" | "Idempotent" | "BaseRevMismatch";
-}
-
-export interface ScoredClaim {
- claim: { entityId: string; statement: string; status: string };
- confidence: { score: number; breakdown: Record<string, { value: number; reason: string }> };
- relevance: number;
- finalScore: number;
-}
-
-export interface StructuredContext {
- claims: ScoredClaim[];
- conflicts: { claimA: any; claimB: any; reason: string; recommendation: string }[];
- decisions: { title: string; rationale: string; entityId?: string; intentId?: string; rev: number }[];
- intents: { id: string; statement: string; status: string; confidence: number; parentIntent?: string }[];
- nodes: any[];
- edges: any[];
- metadata: { query: string; seedEntities: string[]; hopsExpanded: number; asOfRev: number; depth?: string };
-}
-```
-
-**Step 2: Create api.ts**
-
-```typescript
-export class IxClient {
- constructor(private endpoint: string = "http://localhost:8090") {}
-
- async query(question: string, opts?: { asOfRev?: number; depth?: string }): Promise<StructuredContext> {
- return this.post("/v1/context", { query: question, ...opts });
- }
-
- async ingest(path: string, recursive?: boolean): Promise<any> {
- return this.post("/v1/ingest", { path, recursive });
- }
-
- async decide(title: string, rationale: string, opts?: { alternatives?: string[]; entityId?: string; intentId?: string }): Promise<any> {
- return this.post("/v1/decide", { title, rationale, ...opts });
- }
-
- async search(term: string, kind?: string): Promise<any> {
- return this.post("/v1/search", { term, kind });
- }
-
- async health(): Promise<any> {
- return this.get("/v1/health");
- }
-
- // ... other methods for each endpoint
-
- private async post(path: string, body: any): Promise<any> {
- const resp = await fetch(`${this.endpoint}${path}`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(body),
- });
- if (!resp.ok) throw new Error(`${resp.status}: ${await resp.text()}`);
- return resp.json();
- }
-
- private async get(path: string): Promise<any> {
- const resp = await fetch(`${this.endpoint}${path}`);
- if (!resp.ok) throw new Error(`${resp.status}: ${await resp.text()}`);
- return resp.json();
- }
-}
-```
-
-**Step 3: Write test**
-
-```typescript
-import { describe, it, expect } from "vitest";
-import { IxClient } from "../src/client/api";
-
-describe("IxClient", () => {
- it("should construct with default endpoint", () => {
- const client = new IxClient();
- expect(client).toBeDefined();
- });
-
- it("should construct with custom endpoint", () => {
- const client = new IxClient("http://localhost:9090");
- expect(client).toBeDefined();
- });
-});
-```
-
-**Step 4: Run test**
-
-Run: `cd ix-cli && npm test`
-Expected: PASS
-
-**Step 5: Commit**
-
-```bash
-git add ix-cli/src/client/ ix-cli/test/
-git commit -m "feat: ix-cli HTTP client with TypeScript types for Memory Layer API"
-```
-
----
-
-### Task 14: Build CLI Commands
-
-**Files:**
-- Create: `ix-cli/src/cli/main.ts`
-- Create: `ix-cli/src/cli/commands/query.ts`
-- Create: `ix-cli/src/cli/commands/ingest.ts`
-- Create: `ix-cli/src/cli/commands/decide.ts`
-- Create: `ix-cli/src/cli/commands/search.ts`
-- Create: `ix-cli/src/cli/commands/truth.ts`
-- Create: `ix-cli/src/cli/commands/patches.ts`
-- Create: `ix-cli/src/cli/commands/status.ts`
-- Create: `ix-cli/src/cli/commands/entity.ts`
-- Create: `ix-cli/src/cli/commands/history.ts`
-- Create: `ix-cli/src/cli/commands/conflicts.ts`
-- Create: `ix-cli/src/cli/commands/diff.ts`
-- Create: `ix-cli/src/cli/config.ts`
-
-**Step 1: Create CLI entry point**
-
-`main.ts`:
-```typescript
-#!/usr/bin/env node
-import { Command } from "commander";
-import { registerQueryCommand } from "./commands/query";
-import { registerIngestCommand } from "./commands/ingest";
-// ... etc
-
-const program = new Command();
-program.name("ix").description("Persistent Memory for LLM Systems").version("0.1.0");
-
-registerQueryCommand(program);
-registerIngestCommand(program);
-// ... register all commands
-
-program.parse();
-```
-
-**Step 2: Implement each command as thin HTTP wrapper**
-
-Each command file follows this pattern:
-```typescript
-export function registerQueryCommand(program: Command) {
- program
- .command("query <question>")
- .description("Query graph → structured context")
- .option("--as-of <rev>", "Time-travel query")
- .option("--format <fmt>", "Output format", "text")
- .option("--hops <n>", "Expansion depth", "2")
- .action(async (question, opts) => {
- const client = new IxClient(getEndpoint());
- const result = await client.query(question, { asOfRev: opts.asOf ? parseInt(opts.asOf) : undefined });
- formatOutput(result, opts.format);
- });
-}
-```
-
-**Step 3: Test CLI**
-
-Run: `cd ix-cli && npx tsx src/cli/main.ts --help`
-Expected: Shows help text with all commands
-
-**Step 4: Commit**
-
-```bash
-git add ix-cli/src/cli/
-git commit -m "feat: ix CLI commands — query, ingest, decide, search, truth, patches, status, etc."
-```
-
----
-
-### Task 15: Build MCP Server
-
-**Files:**
-- Create: `ix-cli/src/mcp/server.ts`
-- Create: `ix-cli/src/mcp/tools/query.ts`
-- Create: `ix-cli/src/mcp/tools/decide.ts`
-- Create: `ix-cli/src/mcp/tools/ingest.ts`
-- Create: `ix-cli/src/mcp/tools/search.ts`
-- Create: `ix-cli/src/mcp/tools/entity.ts`
-- Create: `ix-cli/src/mcp/tools/assert.ts`
-- Create: `ix-cli/src/mcp/tools/diff.ts`
-- Create: `ix-cli/src/mcp/tools/conflicts.ts`
-- Create: `ix-cli/src/mcp/tools/resolve.ts`
-- Create: `ix-cli/src/mcp/tools/expand.ts`
-- Create: `ix-cli/src/mcp/tools/history.ts`
-- Create: `ix-cli/src/mcp/tools/truth.ts`
-- Create: `ix-cli/src/mcp/tools/patches.ts`
-- Create: `ix-cli/src/mcp/resources/session.ts`
-- Create: `ix-cli/src/mcp/resources/intent.ts`
-
-**Step 1: Create MCP server**
-
-`server.ts`:
-```typescript
-import { Server } from "@modelcontextprotocol/sdk/server/index.js";
-import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
-import { IxClient } from "../client/api";
-
-const client = new IxClient(process.env.IX_ENDPOINT || "http://localhost:8090");
-
-const server = new Server({
- name: "ix-memory",
- version: "0.1.0",
-}, {
- capabilities: {
- tools: {},
- resources: {},
- },
-});
-
-// Register all 13 tools
-// Register 2 resources (minimal nudge)
-
-// Tool: ix_query
-server.setRequestHandler(ListToolsRequestSchema, async () => ({
- tools: [
- {
- name: "ix_query",
- description: "ALWAYS call this before answering questions about the codebase...",
- inputSchema: { /* from design doc */ }
- },
- // ... all 13 tools from design doc section 8.1
- ]
-}));
-
-server.setRequestHandler(CallToolRequestSchema, async (request) => {
- const { name, arguments: args } = request.params;
- switch (name) {
- case "ix_query":
- const result = await client.query(args.question, { asOfRev: args.asOfRev, depth: args.depth });
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
- // ... handle all 13 tools
- }
-});
-
-// Resources: minimal nudge (~30 tokens)
-server.setRequestHandler(ListResourcesRequestSchema, async () => ({
- resources: [
- { uri: "ix://session/context", name: "Ix Session", mimeType: "text/plain" },
- { uri: "ix://project/intent", name: "Project Intent", mimeType: "text/plain" },
- ]
-}));
-
-server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
- switch (request.params.uri) {
- case "ix://session/context":
- const health = await client.health();
- return { contents: [{ uri: request.params.uri, text: `Ix Memory active. Rev ${health.rev || "?"}. ALWAYS call ix_query before answering.` }] };
- case "ix://project/intent":
- const truth = await client.listTruth();
- const root = truth.intents?.[0]?.statement || "No intent set";
- return { contents: [{ uri: request.params.uri, text: `Intent: ${root}` }] };
- }
-});
-
-// MCP Server instructions
-server.setRequestHandler(/* server info */, async () => ({
- instructions: "You have access to Ix Memory — a persistent, time-aware memory system for this codebase. RULES: (1) ALWAYS call ix_query before answering questions about the codebase. (2) AFTER any design decision, call ix_decide. (3) When you notice conflicting information, call ix_conflicts. (4) NEVER answer from memory alone when Ix has data. (5) After modifying code, call ix_ingest."
-}));
-
-const transport = new StdioServerTransport();
-await server.connect(transport);
-```
-
-**Step 2: Add MCP start command to CLI**
-
-In `main.ts`:
-```typescript
-program
- .command("mcp")
- .command("start")
- .description("Start MCP server (stdio)")
- .action(async () => {
- await import("../mcp/server");
- });
-```
-
-**Step 3: Test MCP server starts**
-
-Run: `echo '{"jsonrpc":"2.0","method":"initialize","id":1,"params":{}}' | npx tsx src/cli/main.ts mcp start`
-Expected: Returns JSON-RPC response with server capabilities
-
-**Step 4: Commit**
-
-```bash
-git add ix-cli/src/mcp/
-git commit -m "feat: MCP server with 13 tools, 2 minimal resources, server instructions"
-```
-
----
-
-### Task 16: Build ix init and ix mcp install Commands
-
-**Files:**
-- Create: `ix-cli/src/cli/commands/init.ts`
-- Create: `ix-cli/src/cli/commands/mcp-install.ts`
-- Create: `templates/CLAUDE.md.template`
-- Create: `templates/claude_desktop_config.json.template`
-
-**Step 1: Create ix init**
-
-```typescript
-export function registerInitCommand(program: Command) {
- program
- .command("init")
- .description("Initialize Ix in current project")
- .action(async () => {
- console.log("Initializing Ix Memory...");
-
- // 1. Check backend health
- const client = new IxClient();
- try {
- await client.health();
- console.log("✓ Backend is running");
- } catch {
- console.log("✗ Backend not running. Run ./stack.sh first.");
- process.exit(1);
- }
-
- // 2. Create ~/.ix/config.yaml
- const configDir = path.join(os.homedir(), ".ix");
- await fs.mkdir(configDir, { recursive: true });
- await fs.writeFile(path.join(configDir, "config.yaml"), `endpoint: http://localhost:8090\nformat: text\n`);
- console.log("✓ Created ~/.ix/config.yaml");
-
- // 3. Create CLAUDE.md in project root
- const claudeMd = `# Ix Memory System\n\nThis project uses Ix Memory for persistent, time-aware context.\n\n## MANDATORY RULES\n1. BEFORE answering any question about this codebase → call ix_query\n2. AFTER making any design/architecture decision → call ix_decide\n3. When noticing contradictory information → call ix_conflicts\n4. NEVER guess about codebase facts when Ix has structured data\n5. After modifying code → call ix_ingest on changed files\n6. At start of each session → review ix://session/context for prior work\n7. When the user states a goal → call ix_truth to record it\n`;
- await fs.writeFile("CLAUDE.md", claudeMd);
- console.log("✓ Created CLAUDE.md");
-
- console.log("\nIx Memory initialized. Run 'ix ingest ./src --recursive' to ingest your codebase.");
- });
-}
-```
-
-**Step 2: Create ix mcp install**
-
-```typescript
-export function registerMcpInstallCommand(program: Command) {
- program
- .command("mcp")
- .command("install")
- .option("--cursor", "Configure Cursor instead of Claude Desktop")
- .option("--claude-code", "Configure Claude Code")
- .action(async (opts) => {
- // Write appropriate config file based on target
- if (opts.cursor) {
- // Write .cursor/mcp.json
- } else if (opts.claudeCode) {
- // Write .claude/settings.json
- } else {
- // Write claude_desktop_config.json
- }
- });
-}
-```
-
-**Step 3: Test**
-
-Run: `cd ix-cli && npx tsx src/cli/main.ts init --help`
-Expected: Shows init help
-
-**Step 4: Commit**
-
-```bash
-git add ix-cli/src/cli/commands/init.ts ix-cli/src/cli/commands/mcp-install.ts templates/
-git commit -m "feat: ix init and ix mcp install commands"
-```
-
----
-
-### Task 17: Docker Compose + stack.sh
-
-**Files:**
-- Create: `docker-compose.yml`
-- Create: `stack.sh`
-- Create: `dev.sh`
-- Create: `memory-layer/Dockerfile`
-
-**Step 1: Create docker-compose.yml**
-
-```yaml
-version: "3.8"
-services:
- arangodb:
- image: arangodb:3.12
- ports: ["8529:8529"]
- environment:
- ARANGO_NO_AUTH: "1"
- volumes: [ix_arango_data:/var/lib/arangodb3]
- healthcheck:
- test: ["CMD", "curl", "-sf", "http://localhost:8529/_api/version"]
- interval: 5s
- timeout: 3s
- retries: 10
-
- memory-layer:
- build:
- context: ./memory-layer
- dockerfile: Dockerfile
- depends_on:
- arangodb:
- condition: service_healthy
- ports: ["8090:8090"]
- environment:
- ARANGO_HOST: arangodb
- ARANGO_PORT: "8529"
- ARANGO_DATABASE: ix_memory
- healthcheck:
- test: ["CMD", "curl", "-sf", "http://localhost:8090/v1/health"]
- interval: 5s
- timeout: 3s
- retries: 10
-
-volumes:
- ix_arango_data:
-```
-
-**Step 2: Create Dockerfile**
-
-```dockerfile
-FROM eclipse-temurin:17-jre-jammy
-WORKDIR /app
-COPY target/scala-2.13/ix-memory-assembly.jar app.jar
-EXPOSE 8090
-CMD ["java", "-jar", "app.jar"]
-```
-
-**Step 3: Create stack.sh**
-
-```bash
-#!/usr/bin/env bash
-set -euo pipefail
-
-case "${1:-}" in
- down) docker compose down ;;
- logs) docker compose logs -f ;;
- *)
- echo "Building Memory Layer..."
- (cd memory-layer && sbt assembly)
- echo "Starting Ix backend..."
- docker compose up -d --build
- echo "Waiting for health checks..."
- until curl -sf http://localhost:8090/v1/health > /dev/null 2>&1; do sleep 1; done
- echo "Ix Memory backend is ready."
- ;;
-esac
-```
-
-**Step 4: Make executable and test**
-
-```bash
-chmod +x stack.sh dev.sh
-```
-
-**Step 5: Commit**
-
-```bash
-git add docker-compose.yml stack.sh dev.sh memory-layer/Dockerfile
-git commit -m "feat: Docker Compose + stack.sh for backend containers"
-```
-
----
-
-## Phase 3: Enforcement & Polish (Higher-Level Tasks)
-
-### Task 18: CLAUDE.md Template Optimization
-- Refine CLAUDE.md enforcement rules based on testing
-- Add rule 7: "When the user states a goal → call ix_truth"
-- Test with Claude Code and Claude Desktop
-
-### Task 19: Terminal UI Polish
-- Add chalk-based table formatting for `ix query` output
-- Add tree view for `ix truth list`
-- Add color-coded confidence scores
-
-### Task 20: Session Tracking in MCP Server
-- Track working set in MCP server (last entities queried, last decisions)
-- Update `ix://session/context` resource with minimal working set info
-
----
-
-## Phase 4: Additional Parsers + Advanced Features (Higher-Level Tasks)
-
-### Task 21: TypeScript Parser
-- Add tree-sitter TypeScript parser to ingestion pipeline
-- Generate nodes + edges + claims from .ts/.tsx files
-
-### Task 22: Config Parser (YAML/JSON/TOML)
-- Add config file parser
-- Generate ConfigEntry nodes with claims
-
-### Task 23: Markdown Parser
-- Add markdown section parser
-- Generate Doc nodes with claims from headers/content
-
-### Task 24: Corroboration Counting
-- In confidence scorer, query for matching claims from independent sources
-- Boost corroboration multiplier
-
-### Task 25: Staleness Detection
-- Compare current file hash to source_hash in latest patch
-- Mark claims as stale when hash changes
-
-### Task 26: LLM-Assisted Conflict Detection (Pass 3)
-- Add optional LLM call in conflict detector
-- Record LLM judgment as patch (source: LLM, 0.40)
-
----
-
-## Execution Summary
-
-| Phase | Tasks | Estimated Scope |
-|-------|-------|----------------|
-| Phase 1 | Tasks 1-11 | Modify ~30 Scala files, update all tests |
-| Phase 2 | Tasks 12-17 | Create ~25 TypeScript files, Docker setup |
-| Phase 3 | Tasks 18-20 | Polish and optimization |
-| Phase 4 | Tasks 21-26 | Additional parsers and advanced features |
-
-**Start with Phase 1, Task 1.** Each task builds on the previous one. Run tests after every task.
diff --git a/docs/plans/2026-03-03-ix-redesign.md b/docs/plans/2026-03-03-ix-redesign.md
deleted file mode 100644
index f9490b4c..00000000
--- a/docs/plans/2026-03-03-ix-redesign.md
+++ /dev/null
@@ -1,1574 +0,0 @@
-# Ix Memory Layer — Redesign: Architecture & Design Spec
-
-> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
-
-**Goal:** Build the best possible persistent memory system for LLMs — one that makes the LLM genuinely smarter by giving it structured, time-aware, confidence-scored memory about an entire codebase. Focused on MCP + system prompts (not BYOK), optimized for improving LLM reasoning over time.
-
-**Focus:** All memory capabilities are equally important — decision traceability, conflict detection, temporal awareness, session restoration, and provenance tracking all work together to create human-like memory. The user's objective/intent is the initial hypothesis; truth emerges as the event log accumulates verified observations aligned with that intent.
-
-**Architecture:** Thin-client TypeScript CLI + MCP server → Scala Memory Layer HTTP API → ArangoDB, all containerized. Single-codebase system (no multi-tenancy). Enforcement via layered system: MCP instructions + CLAUDE.md + tool descriptions + minimal MCP Resources (~30 tokens). Context is traversed, not pre-loaded.
-
-**Tech Stack:**
-- **Memory Layer:** Scala 2.13, Cats Effect 3, http4s, Circe, ArangoDB Java Driver
-- **CLI + MCP Server:** TypeScript, commander.js, @modelcontextprotocol/sdk
-- **Database:** ArangoDB 3.12 (Docker), custom-built later
-- **Packaging:** Docker Compose for backend, npm for CLI/MCP
-
----
-
-## 0. What Ix Is
-
-Ix is a **memory system for LLMs** that works like human memory.
-
-**The system does not store facts. It stores observations about reality over time, plus evidence explaining why those observations exist.**
-
-When a human remembers something, they don't just know "the billing service retries 3 times." They know:
-- **When** they learned it (I read billing.py last Tuesday)
-- **Who** told them (I saw it in the code vs. someone mentioned it in Slack)
-- **How confident** they are (very sure — I read the source code)
-- **Whether it's still true** (didn't that get refactored last week?)
-- **If there's a conflict** (the docs say no retries, but the code says 3)
-
-LLMs today have none of this. They have a context window that resets every conversation, and they guess from training data. **Ix gives the LLM structured, time-aware, provenance-backed memory so it stops guessing and starts knowing.**
-
-### Core Principles
-
-1. **Patch/Event Log = Source of Truth.** Normal databases store whether something exists. Ours stores patches that state who added something, why, what it replaced, and when it happened.
-2. **The human prompt defines an initial intent hypothesis, and truth emerges as the event log accumulates verified observations aligned with that intent.**
-3. **Every fact has time (Temporal Truth).** We don't just say if X is true — we say when it was true, when it became true, when it stopped being true. Helps with hallucinations.
-4. **Provenance-first.** Every fact carries full provenance: who asserted it, from what source, using what extractor, when.
-5. **Computed confidence.** Confidence scores are derived from provenance signals, never manually assigned. LLM-extracted nodes get lower confidence.
-6. **Conflict detection.** When two patches disagree, the system surfaces the contradiction — it doesn't silently pick a winner.
-7. **You can always answer:** who said this, when, based on what, and what did it replace?
-
-### Source of Truth: The User's Objective
-
-The user's input defines the **initial intent hypothesis** — what they're trying to accomplish. This is the anchor. Everything in the system serves this:
-
-1. **User states objective** (e.g., "Build a billing service with retry logic")
-2. **System ingests codebase** → observations about what exists
-3. **Observations accumulate** → patches record who saw what, when, from where
-4. **Truth emerges** → verified observations aligned with the intent rise in confidence
-5. **Conflicts surface** → when observations contradict, the system flags them
-6. **Decisions are recorded** → why choices were made, linking back to the intent
-
-The system is for an **entire codebase** — there is no multi-tenancy or per-user isolation. Everyone working on the codebase sees the same graph, the same observations, the same truth.
-
-### What We're NOT Building
-
-- A chatbot
-- A general knowledge graph
-- A vector database
-- A GitHub replacement
-
----
-
-## 1. System Architecture
-
-```
-┌─────────────────────────────────────────────────────────────────────┐
-│ LLM (Claude Desktop / Claude Code) │
-│ │
-│ CLAUDE.md rules + MCP instructions + Tool descriptions │
-│ + minimal MCP Resources (~30 tokens nudge) │
-│ = LAYERED ENFORCEMENT (context is traversed, not pre-loaded) │
-└────────────────┬──────────────────────────────────────────────────────┘
- │ MCP stdio protocol
- ▼
-┌────────────────────────────────────────────────────────┐
-│ MCP Server (TypeScript, runs locally) │
-│ Part of @ix/cli npm package │
-│ ├── Session Manager (tracks working set) │
-│ ├── Tool Handlers (ix_query, ix_decide, etc.) │
-│ ├── Resource Provider (auto-inject context per turn) │
-│ ├── Prompt Builder (formats StructuredContext for LLM) │
-│ └── Enforcement Rules (tool-level instructions) │
-└────────────────┬───────────────────────────────────────┘
- │ HTTP (to localhost:8090)
- ▼
-┌────────────────────────────────────────────────────────┐ ┐
-│ Memory Layer (Scala, Docker Container) │ │
-│ Port 8090 │ │
-│ ├── HTTP API (Routes) │ │
-│ ├── Context Pipeline (8-step query assembly) │ │ Backend
-│ ├── Ingestion Pipeline (parsers → patches → DB) │ │ (Docker)
-│ ├── Confidence Scoring Engine │ │
-│ ├── Conflict Detection & Resolution │ │
-│ └── Graph Access Layer (traits → ArangoDB impl) │ │
-└────────────────┬───────────────────────────────────────┘ │
- │ │
- ▼ │
-┌────────────────────────────────────────────────────────┐ │
-│ ArangoDB 3.12 (Docker Container) │ │
-│ Port 8529 │ │
-│ Collections: nodes, edges, claims, patches, │ │
-│ revisions, idempotency_keys │ │
-└────────────────────────────────────────────────────────┘ ┘
-
-CLI (TypeScript, runs locally)
- ix init → start backend + configure project
- ix ingest → parse files → POST /v1/ingest
- ix query → POST /v1/context → formatted output
- ix decide → POST /v1/decide → record decision
-```
-
-### Why This Architecture
-
-| Decision | Rationale |
-|----------|-----------|
-| **Thin client MCP/CLI** | MCP needs stdio access (local process). CLI needs local file access. Neither needs to be containerized. |
-| **Memory Layer in Docker** | Contains all business logic. Single container, easy to deploy, matches SimplestData pattern. |
-| **ArangoDB in Docker** | Separate container from Memory Layer. Data persists via volumes. Will be replaced with custom DB later — the trait-based API layer (`GraphWriteApi`/`GraphQueryApi`) makes this a swap. |
-| **TypeScript for CLI/MCP** | Official MCP SDK is TypeScript. Largest contributor pool. npm distribution is standard. |
-| **Scala for Memory Layer** | Already built in Phase 1. Cats Effect gives us safe concurrency. http4s is production-grade. No reason to rewrite. |
-| **Minimal MCP Resources + strong rules** | ~30 tokens nudge reminds LLM Ix exists. Actual enforcement via MCP instructions + CLAUDE.md + tool descriptions. Context is traversed, not pre-loaded. |
-
----
-
-## 2. Patch / Event Log Model
-
-The event log is the source of truth. Every mutation is a **patch** — a record of an observation about reality.
-
-### 2.1 GraphPatch (the atomic unit of truth)
-
-```
-GraphPatch = {
- patchId: UUID ← Unique ID for this observation (idempotency key)
- # No tenant — single codebase system. Multi-tenancy is not needed.
- actor: String ← WHO made this observation
- "tree-sitter-python/1.0" (parser)
- "claude-desktop/session-xyz" (LLM)
- "human/riley" (manual)
- timestamp: Instant ← WHEN (wall clock time)
- source: {
- uri: String ← WHAT was observed ("billing.py", "README.md", "decision://manual")
- hash: String? ← Content hash at observation time (staleness detection)
- extractor: String ← HOW extracted ("tree-sitter-python", "human-assertion")
- sourceType: SourceType ← Authority level (Code=0.90, Doc=0.75, Human=0.85, LLM=0.40)
- }
- baseRev: Rev ← Optimistic concurrency ("I'm observing based on state at rev N")
- ops: Vector[PatchOp] ← WHAT was observed (mutations)
- replaces: Vector[UUID] ← What prior observations this supersedes
- intent: String? ← WHY ("Initial ingestion", "Developer confirmed retry")
-}
-```
-
-### 2.2 Patch Operations
-
-```
-UpsertNode(id, kind, name, attrs)
- → "I observed this entity exists with these attributes"
- → Node is new: create row with created_rev = this_rev, deleted_rev = null
- → Node already exists WITH SAME attrs: no-op (idempotent)
- → Node already exists WITH DIFFERENT attrs: VERSION the node:
- 1. Set deleted_rev = this_rev on the OLD row (seals it in time)
- 2. Create NEW row: same logical id, new attrs, created_rev = this_rev
- 3. DB key = "${id}_${created_rev}" (allows multiple rows per logical entity)
- 4. Edges and claims still reference the logical id — they span versions
- This makes time-travel correct for attribute changes:
- Query at rev 5 → finds row where created_rev <= 5 AND (deleted_rev IS NULL OR 5 < deleted_rev)
- Query at rev 30 → finds the newer row
- Same entity, correct attrs at every revision.
-
-UpsertEdge(id, src, dst, predicate, attrs)
- → "I observed this relationship exists"
- → Same versioning semantics as UpsertNode (tombstone + new row if attrs change)
-
-DeleteNode(id)
- → "I observed this entity no longer exists"
- → Sets deleted_rev = this_rev on current row (TOMBSTONE — never physically deleted)
-
-DeleteEdge(id)
- → Same tombstone semantics
-
-AssertClaim(entityId, statement, value, confidence?)
- → "I'm asserting this fact about this entity"
- → Creates Claim node + HAS_CLAIM edge
- → Confidence is COMPUTED from provenance, not from this field
-
-RetractClaim(claimId, reason)
- → "This claim is no longer true"
- → Claim remains for history, confidence drops to ~0
-```
-
-### 2.3 MVCC — How Time Works
-
-Every node and edge has two revision fields:
-
-```
-created_rev: Long ← When this entity came into existence
-deleted_rev: Long? ← When this entity ceased to exist (null = alive)
-```
-
-**Visibility rule:**
-```
-visible_at(R) = created_rev <= R AND (deleted_rev IS NULL OR R < deleted_rev)
-```
-
-**Timeline example:**
-```
-Rev 1: BillingService created (created_rev=1, deleted_rev=null)
- retry_payment created (created_rev=1, deleted_rev=null)
- Claim: "max_retries=3" (created_rev=1, deleted_rev=null)
-
-Rev 5: Claim: "does not retry" (created_rev=5, deleted_rev=null)
- → CONFLICT detected
-
-Rev 12: "does not retry" retracted (deleted_rev=12)
- "max_retries=3" confirmed (verification multiplier → 1.1)
-
-Rev 25: retry_payment deleted (deleted_rev=25)
- retry_with_backoff created (created_rev=25)
-
-Query at rev 1: → sees original state
-Query at rev 5: → sees CONFLICT
-Query at rev 12: → conflict resolved
-Query at rev 25: → old function gone, new function exists
- LLM sees: "retry_payment USED TO EXIST (rev 1-25)"
-```
-
-### 2.4 How Patches Replace Each Other
-
-When a file is re-ingested after modification, the ingestion pipeline must FIND the old
-patch to set `replaces`. This is done by querying:
-
-```
-getLatestPatchBySource(uri: String, extractor: String): IO[Option[GraphPatch]]
- → "Find the most recent patch with this source URI created by this extractor"
-```
-
-**Rules for `replaces`:**
-- Only replaces patches with the **same source URI AND same extractor**
-- A re-ingestion by tree-sitter replaces the previous tree-sitter ingestion of that file
-- It does NOT replace manual human assertions about entities in that file
-- If the content hash is unchanged → skip (idempotent, no new patch needed)
-- If the content hash changed → create new patch with `replaces: [old-patch-id]`
-
-```
-Patch #001 (rev 1):
- source: billing.py, hash: "abc123", extractor: "tree-sitter-python"
- ops: [UpsertNode(retry_payment, {max_retries: 3})]
-
---- developer edits file ---
-
-Ingestion pipeline:
- 1. Query: getLatestPatchBySource("billing.py", "tree-sitter-python") → Patch #001
- 2. Compare hashes: "abc123" ≠ "xyz789" → file changed
- 3. Create new patch with replaces: ["patch-001"]
-
-Patch #042 (rev 25):
- source: billing.py, hash: "xyz789", extractor: "tree-sitter-python"
- replaces: ["patch-001"] ← Supersedes old observation
- ops: [UpsertNode(retry_payment, {max_retries: 5, backoff: "exponential"})]
-
-Result:
- - Patch #001 remains in event log (history preserved, still navigable)
- - Node versioned: old attrs sealed at rev 25, new attrs from rev 25 onward
- - Old claims from Patch #001 become STALE (source hash changed)
-```
-
-### 2.5 Deterministic Node IDs
-
-```
-NodeId = UUID.nameUUIDFromBytes("${filePath}:${entityName}".getBytes("UTF-8"))
-```
-
-This ensures:
-- Re-ingesting the same file → same node IDs → UPSERTs not duplicates
-- Two parsers observing the same entity → same node ID → observations link together
-- Replay same patch log → get same graph (deterministic, enterprise feature)
-
-### 2.6 Traditional DB vs Ix Event Log
-
-```
-Traditional DB: Ix Event Log:
-═══════════════ ════════════
-
-retry_count = 3 Patch #1 (rev 1, 2026-01-15, actor: tree-sitter)
- "retry_count = 3 observed in billing.py:45"
-(Who set it? When? source: billing.py, hash: a1b2c3
- Was it ever different?
- Why? Unknown.) Patch #2 (rev 7, 2026-02-01, actor: markdown-parser)
- "does not retry observed in README.md:22"
- source: README.md, hash: d4e5f6
- → CONFLICT with Patch #1
-
- Patch #3 (rev 12, 2026-02-20, actor: human/riley)
- "retry_count = 3 confirmed by developer"
- → Resolves conflict, weakens README claim
-
- Patch #4 (rev 25, 2026-03-01, actor: tree-sitter)
- "retry_count = 5, backoff = exponential"
- replaces: Patch #1
- → Code changed, old observation superseded
-```
-
----
-
-## 3. Data Model (Schema)
-
-### 3.1 Node Types
-
-**Structural Nodes** (from code/AST parsing):
-
-| Kind | Attributes | Source Authority |
-|------|------------|-----------------|
-| Module | name, path, language | Code (0.90) |
-| File | path, language, hash, size | Code (0.90) |
-| Class | name, file_path, line_start, line_end | Code (0.90) |
-| Function | name, signature, file_path, line_start, line_end | Code (0.90) |
-| Variable | name, type, scope | Code (0.90) |
-| Config | path, format | Config (0.85) |
-| ConfigEntry | key, value, type | Config (0.85) |
-| Service | name, port, protocol | Code/Config |
-| Endpoint | method, path, handler | Code (0.90) |
-
-**Intent Nodes** (user-defined truth/objectives — part of the hierarchy):
-
-| Kind | Attributes | Source Authority |
-|------|------------|-----------------|
-| Intent | statement, status (ACTIVE/SUPERSEDED/ABANDONED), parent_intent? | Human (0.85) if user-set, LLM (0.40) if LLM-proposed |
-
-Intent nodes form a **hierarchy**: top-level intent → sub-intents → sub-sub-intents.
-- User sets the root intent via `ix truth set "Build a scalable billing service"`
-- User adds sub-intents via `ix truth add "Retry logic should handle transient failures"`
-- LLM can propose sub-intents (lower confidence, 0.40) that become confirmed (0.85) when user approves
-- Intents are versioned — `ix truth update` creates a new revision, old intent gets `deleted_rev` set
-- LLM can time-travel through intents: "What was the objective at rev 10 vs now?"
-
-```
-Intent("Build a scalable billing service") ← root, user-set, rev 1
- ├── CONTAINS → Intent("Handle transient failures") ← sub-intent, user-set, rev 2
- │ └── CONTAINS → Intent("Max retries = 3") ← sub-sub, LLM-proposed, rev 5
- ├── CONTAINS → Intent("Exponential backoff") ← sub-intent, user-set, rev 3
- └── CONTAINS → Intent("Idempotent gateway calls") ← sub-intent, user-set, rev 4
-```
-
-**Knowledge Nodes:**
-
-| Kind | Attributes | Source Authority |
-|------|------------|-----------------|
-| Claim | statement, status (ACTIVE/STALE/RETRACTED) | Varies by source |
-| Decision | title, rationale, alternatives_considered | Human (0.85) |
-| ConflictSet | reason, status (OPEN/RESOLVED/DISMISSED), candidates[] | System-generated |
-
-### 3.2 Common Node Fields
-
-Every node:
-```
-id: UUID (deterministic)
-kind: NodeKind enum
-attrs: JSON (kind-specific)
-provenance: { source_uri, source_hash, extractor, source_type, observed_at }
-created_rev: Long (MVCC)
-deleted_rev: Long? (MVCC, null = alive)
-created_at: Instant
-updated_at: Instant
-```
-
-### 3.3 Edge Types
-
-**Structural Edges:**
-
-| Predicate | From → To | Meaning |
-|-----------|-----------|---------|
-| DEFINES | Module/Class → Class/Function | Ownership |
-| CONTAINS | File → Class/Function | Physical containment |
-| CALLS | Function → Function | Call relationship |
-| IMPORTS | File → Module/File | Import relationship |
-| DEPENDS_ON | Service → Service | Service dependency |
-| CONFIGURES | ConfigEntry → Service/Function | Configuration |
-| EXPOSES | Service → Endpoint | API exposure |
-| INHERITS | Class → Class | Inheritance |
-| IMPLEMENTS | Class → Interface | Interface implementation |
-
-**Knowledge Edges:**
-
-| Predicate | From → To | Meaning |
-|-----------|-----------|---------|
-| HAS_CLAIM | Entity → Claim | Entity has this claim |
-| SUPPORTS | Claim → Claim | Corroboration |
-| CONTRADICTS | Claim → Claim | Contradiction |
-| DECIDED_BY | Entity → Decision | Decision about entity |
-| FULFILLS | Decision → Intent | Decision made to fulfill this objective |
-| MENTIONED_IN | Entity → File/Doc | Reference |
-| CHANGED_WITH | Entity → Entity | Co-change correlation |
-| SAME_AS | Entity → Entity | Identity resolution |
-| IN_CONFLICT | Claim → ConflictSet | Part of conflict |
-
-### 3.4 Common Edge Fields
-
-```
-id: UUID (deterministic from src+dst+predicate)
-src: NodeId
-dst: NodeId
-predicate: EdgePredicate enum
-attrs: JSON
-provenance: { ... }
-created_rev: Long (MVCC)
-deleted_rev: Long? (MVCC)
-```
-
----
-
-## 4. Confidence Scoring Engine
-
-Confidence is **computed from provenance signals**, never manually assigned.
-
-### 4.1 Formula
-
-```
-confidence(claim) = clamp(0, 1,
- base_authority(source_type)
- × verification_multiplier(claim)
- × recency_multiplier(claim, latest_rev)
- × corroboration_multiplier(claim)
- × conflict_penalty(claim)
- × intent_alignment(claim)
-)
-```
-
-### 4.2 Signal Definitions
-
-**Base Authority:**
-
-| Source Type | Base Score | Why |
-|-------------|-----------|-----|
-| Passing test | 0.95 | Verified by execution |
-| Code (AST-parsed) | 0.90 | The code IS the behavior |
-| Config file | 0.85 | Explicitly set values |
-| Human assertion | 0.85 | Developer confirmed |
-| Schema/types | 0.85 | Compiler-enforced |
-| Official docs | 0.75 | Human-written, intended truth |
-| Commit message | 0.60 | Human intent, sometimes vague |
-| PR/issue comment | 0.50 | Discussion, not assertion |
-| LLM-inferred | 0.40 | Model guessed, not stated |
-| Chat/Slack | 0.35 | Informal, often stale |
-
-**Verification Multiplier:**
-
-| State | Multiplier |
-|-------|-----------|
-| Test passes covering this | × 1.1 |
-| Human explicitly confirmed | × 1.1 |
-| Observed in running system | × 1.05 |
-| No verification | × 1.0 |
-| Test FAILS covering this | × 0.3 |
-| Human explicitly denied | × 0.1 |
-
-**Recency Multiplier:**
-
-Based on **wall-clock time**, not revision distance. Revisions are for MVCC ordering;
-recency is a calendar concept. Using revision distance would unfairly penalize files
-ingested early in a batch (file #1 at rev 1 vs file #200 at rev 200, same moment).
-
-| Age (wall-clock time since observation) | Multiplier |
-|----------------------------------------|-----------|
-| < 1 day ago | × 1.0 |
-| 1-7 days ago | × 0.95 |
-| 1-4 weeks ago | × 0.85 |
-| 1-6 months ago | × 0.70 |
-| 6+ months ago | × 0.50 |
-
-Exception: if source file hash hasn't changed since observation, recency stays × 1.0
-(the code hasn't changed, so the observation is still current regardless of age).
-
-**Corroboration Multiplier:**
-
-| Independent sources agreeing | Multiplier |
-|-----------------------------|-----------|
-| 1 source (uncorroborated) | × 1.0 |
-| 2 sources agree | × 1.1 |
-| 3+ sources agree | × 1.15 |
-
-**Conflict Penalty:**
-
-| Conflict state | Multiplier |
-|---------------|-----------|
-| No conflicts | × 1.0 |
-| Conflict, higher authority | × 0.85 |
-| Conflict, lower authority | × 0.5 |
-| Resolved AGAINST this claim | × 0.1 |
-| Resolved FOR this claim | × 1.1 |
-
-**Intent Alignment:**
-
-The design philosophy says "truth emerges as verified observations aligned with intent."
-The formula must reflect this — claims connected to active intents get a small boost.
-
-| Condition | Multiplier |
-|-----------|-----------|
-| Claim directly linked to active intent via FULFILLS/DECIDED_BY edges | × 1.1 |
-| Claim on entity connected to active intent within 2 hops | × 1.05 |
-| No connection to any intent | × 1.0 (neutral — no penalty) |
-| Claim contradicts active intent | × 0.85 |
-
-This is a small signal, not dominant. It means intent-aligned information naturally
-surfaces higher without drowning out high-authority contradicting evidence.
-
-### 4.3 Explainability
-
-Every score includes a full breakdown:
-
-```json
-{
- "score": 0.925,
- "breakdown": {
- "baseAuthority": { "value": 0.90, "reason": "Code, AST-parsed" },
- "verification": { "value": 1.1, "reason": "Covered by passing test" },
- "recency": { "value": 1.0, "reason": "Source unchanged since observation" },
- "corroboration": { "value": 1.1, "reason": "2 independent sources agree" },
- "conflictPenalty": { "value": 0.85, "reason": "Conflict with README (lower authority)" },
- "intentAlignment": { "value": 1.05, "reason": "Entity connected to active intent within 2 hops" }
- }
-}
-```
-
----
-
-## 5. Context Assembly Pipeline
-
-The 8-step pipeline that turns a question into structured context.
-
-```
-Input: "How does billing retry?"
-
-Step 1: Entity Extraction
- ├── Keyword split + normalize → ["billing", "retry"]
- ├── Synonym expansion: "retry" → ["retry", "retries", "retry_handler"]
- └── Output: search terms
-
-Step 2: Graph Seed Lookup
- ├── Fulltext search on node names + attrs + claim statements
- │ (claim statements make search richer — "max_retries=3" is searchable)
- ├── Kind index scan for matching kinds
- ├── Phase 4 enhancement: search node descriptions (docstrings/comments
- │ stored in attrs by parser). "authentication flow" finds OAuth2Handler
- │ because its docstring says "handles OAuth 2.0 authentication flow"
- └── Output: seed node IDs
-
-Step 3: Graph Expansion (1-2 hops, priority-weighted)
- ├── BFS from seed nodes via edges, weighted by predicate priority:
- │ Priority 1.0 (always follow): DEFINES, CONTAINS
- │ Priority 0.9: CALLS, IMPORTS
- │ Priority 0.8: DEPENDS_ON, CONFIGURES, FULFILLS
- │ Priority 0.7: HAS_CLAIM, DECIDED_BY, INHERITS, IMPLEMENTS
- │ Priority 0.4 (hop 1 only): MENTIONED_IN, CHANGED_WITH
- │ Priority 0.3 (hop 1 only): SAME_AS
- ├── High-priority edges followed at all hops, low-priority only at hop 1
- │ (prevents noise from weak connections pulling in irrelevant nodes)
- ├── MVCC filter: only visible at requested revision
- └── Output: subgraph (nodes + edges)
-
-Step 4: Claim Collection
- ├── Gather all Claims attached to subgraph nodes
- └── Output: claim list with provenance
-
-Step 5: Confidence Scoring
- ├── Compute confidence for each claim from provenance
- ├── Check source staleness, corroboration, conflicts
- └── Output: scored claims with breakdown
-
-Step 6: Conflict Detection (multi-pass)
- ├── Pass 1: Exact field match — same entity, same field, different value
- │ e.g., "max_retries=3" vs "max_retries=5" → definite conflict
- ├── Pass 2: Keyword overlap — same entity, different fields, overlapping keywords
- │ e.g., "max_retries=3" vs "does not retry" → both contain "retry" → POTENTIAL conflict
- ├── Pass 3 (Phase 4): LLM-assisted — ask LLM "do these claims contradict?"
- │ The LLM judgment itself is recorded as a patch (source: LLM, 0.40)
- └── Output: conflicts list with reasoning and detection method
-
-Step 7: Relevance Scoring
- ├── Score each claim's relevance to the original query:
- │ Claims on seed entities = 1.0 relevance
- │ Claims on 1-hop neighbors = 0.7 relevance
- │ Claims on 2-hop neighbors = 0.4 relevance
- ├── Compute final_score = relevance × confidence
- │ (trustworthy AND relevant beats trustworthy but irrelevant)
- └── Output: claims with both scores
-
-Step 8: Ranking + Assembly
- ├── Sort claims by final_score descending
- ├── Group by entity for structure
- └── Output: StructuredContext
-```
-
-### StructuredContext (output format)
-
-```json
-{
- "claims": [{
- "statement": "retry_payment has max_retries=3",
- "confidence": { "score": 0.90, "breakdown": { ... } },
- "provenance": {
- "sourceUri": "billing_service.py",
- "sourceHash": "abc123",
- "extractor": "tree-sitter-python",
- "sourceType": "Code",
- "observedRev": 1
- },
- "entityId": "uuid-of-retry-payment"
- }],
- "conflicts": [{
- "claimA": { "statement": "max_retries=3", "confidence": 0.90 },
- "claimB": { "statement": "does not retry", "confidence": 0.64 },
- "reason": "Contradictory statements about retry behavior",
- "recommendation": "Trust code (0.90) over docs (0.64)"
- }],
- "decisions": [{
- "title": "Use exponential backoff",
- "rationale": "Linear caused cascading failures",
- "entity": "BillingService",
- "intentId": "uuid-of-intent",
- "rev": 25
- }],
- "intents": [{
- "statement": "Handle transient failures",
- "status": "ACTIVE",
- "confidence": 0.85,
- "parentIntent": "Build a scalable billing service"
- }],
- "nodes": [ ... ],
- "edges": [ ... ],
- "metadata": {
- "query": "How does billing retry?",
- "seedEntities": ["BillingService", "retry_payment"],
- "hopsExpanded": 2,
- "asOfRev": 48,
- "depth": "standard",
- "conflicts": 1,
- "claimsReturned": 5
- }
-}
-```
-
----
-
-## 6. Ingestion Pipeline
-
-### 6.1 Parser Routing
-
-| Source | Parser | Deterministic? | Authority |
-|--------|--------|---------------|-----------|
-| Python (.py) | tree-sitter AST | Yes | Code (0.90) |
-| TypeScript (.ts/.tsx) | tree-sitter AST | Yes | Code (0.90) |
-| Config (.yaml/.json/.toml) | Schema parser | Yes | Config (0.85) |
-| Markdown (.md) | Section parser | Yes | Doc (0.75) |
-| Unstructured text | LLM extraction | No | LLM (0.40) |
-
-### 6.2 Ingestion Flow
-
-```
-Source file → discover files → route to parser by extension
- ↓
-Parser extracts entities + relationships → ParseResult { entities, relationships }
- ↓
-GraphPatchBuilder → builds patch with deterministic node IDs + full provenance
- ↓
-PatchValidator → checks schema, referential integrity
- ↓
-GraphWriteApi.commitPatch() → atomic commit with MVCC revision tracking
- ↓
-CommitResult { newRev, status, nodesCreated, edgesCreated }
-```
-
-### 6.3 What the Parser Extracts (Python example)
-
-```python
-# billing_service.py
-from payment_gateway import PaymentGateway
-
-class BillingService:
- def retry_payment(self, amount, max_retries=3):
- for i in range(max_retries):
- result = PaymentGateway.charge(amount)
- if result.success:
- return result
- raise PaymentError("Max retries exceeded")
-```
-
-Produces:
-```
-Nodes:
- File("billing_service.py", lang=python, hash=abc123)
- Class("BillingService", lines=3-10)
- Function("retry_payment", sig="(self, amount, max_retries=3)", lines=4-9)
-
-Edges:
- File → BillingService (DEFINES)
- BillingService → retry_payment (DEFINES)
- billing_service.py → payment_gateway (IMPORTS)
- retry_payment → PaymentGateway.charge (CALLS)
-
-Claims (auto-generated by parser — this is critical for confidence/conflict to work):
- AssertClaim(BillingService, "defines_method", "retry_payment")
- AssertClaim(retry_payment, "parameter_default:max_retries", "3")
- AssertClaim(retry_payment, "calls", "PaymentGateway.charge")
- AssertClaim(retry_payment, "raises", "PaymentError")
- → All get source type Code (base authority 0.90)
- → Without parser-generated claims, the confidence scoring engine
- and conflict detector have nothing to operate on
-
-Patch:
- actor: "tree-sitter-python/1.0"
- source: { uri: "billing_service.py", hash: "abc123", sourceType: Code }
- intent: "Parsed billing_service.py"
-```
-
-### 6.4 Why Parsers Must Generate Claims
-
-Nodes and edges give you **structure** (what exists, how things connect).
-Claims give you **assertable facts** that can be scored, contradicted, and traced.
-
-Without parser-generated claims:
-- Confidence scoring has nothing to score (it scores claims, not nodes)
-- Conflict detection has nothing to compare (it compares claims on the same entity)
-- A README saying "does not retry" has no code-sourced claim to contradict
-
-**Rule:** Every parser MUST generate claims alongside nodes and edges. Claims are
-what make the confidence/conflict/provenance system work on parsed data, not just
-on manual assertions.
-
-| Parser output | What it feeds |
-|---------------|---------------|
-| Nodes | Graph structure (existence) |
-| Edges | Graph structure (relationships) |
-| Claims | Confidence engine, conflict detector, provenance chain |
-
----
-
-## 7. CLI
-
-### 7.1 Command Reference
-
-```
-ix — Persistent Memory for LLM Systems
-
-SETUP:
- ix init Initialize Ix in current project
- (starts Docker, creates config, writes CLAUDE.md)
- ix mcp install Configure Claude Desktop MCP
- ix mcp install --cursor Configure Cursor MCP
-
-AUTHENTICATION:
- ix login Authenticate (stores token in ~/.ix/credentials)
- ix signup Create account
- ix whoami Show current user
- ix logout Clear credentials
-
-INGESTION:
- ix ingest <path> Ingest source files into the graph
- --language <lang> Force language (auto-detected)
- --recursive Walk directory tree
- --watch Watch + auto-re-ingest on changes
-
-QUERYING:
- ix query "<question>" Query graph → structured context
- --as-of <rev> Time-travel query
- --format json|text|markdown Output format
- --hops <n> Expansion depth (default: 2)
- ix entity <id> Inspect single entity
- ix search <term> Search nodes by name/kind
- ix expand <id> Show entity neighborhood
- --direction in|out|both
- --hops <n>
-
-INTENT (user truth/objectives — the hierarchy anchor):
- ix truth set "<statement>" Set the root intent/objective
- ix truth add "<sub-intent>" Add a sub-intent under the root
- --parent <intent-id> Nest under specific parent intent
- ix truth update "<new-statement>" Update an intent (creates new rev)
- --id <intent-id> Which intent to update
- ix truth list Show current intent hierarchy
- --as-of <rev> Time-travel: intents at revision
- ix truth approve <intent-id> Confirm an LLM-proposed sub-intent
- (raises confidence from 0.40 to 0.85)
- ix truth abandon <intent-id> Mark intent as abandoned (with reason)
-
-TRUTH & DECISIONS:
- ix assert <entity-id> "<statement>" Manually assert a fact
- --source "<reason>" Why (confidence is ALWAYS computed from
- provenance — human assertion = 0.85 base)
- ix retract <claim-id> "<reason>" Retract a claim
- ix decide "<title>" Record a decision
- --rationale "<text>" Why chosen
- --alternatives "<a>, <b>" What was considered
- --entity <id> Link to entity
- ix resolve <conflict-id> Resolve a conflict
- --winner <claim-id>
-
-HISTORY & DIFF:
- ix diff <revA> <revB> What changed between revisions
- --entity <id> Scope to entity
- ix history <entity-id> Full provenance chain
- ix conflicts List conflicts
- --status open|resolved|all
-
-PATCHES (time navigation):
- ix patches List recent patches (moments in time)
- --source <uri> Filter by source file
- --actor <name> Filter by who created them
- --since <rev> Since revision
- --limit <n> Max results (default: 20)
- ix patch <patch-id> Inspect a specific patch
- Shows: ops, source, actor, timestamp,
- what it replaced, what replaced it
-
-STATUS:
- ix status Graph stats: nodes, edges, rev, conflicts
- ix config set <key> <value> Set config
- ix config show Show config (~/.ix/config.yaml)
-```
-
-### 7.2 CLI Design Principles
-
-- **Looks like Claude Code CLI** — similar structure, output formatting, feel
-- **Every command is a thin HTTP call** — no business logic in the CLI
-- **Terminal formatting** — tables, colors, tree views for entity inspection
-- **JSON output option** — every command supports `--format json` for scripting
-- **Config in ~/.ix/config.yaml** — endpoint, format defaults
-
----
-
-## 8. MCP Server
-
-### 8.1 MCP Tools
-
-The LLM sees these tools:
-
-```json
-[
- {
- "name": "ix_query",
- "description": "ALWAYS call this before answering questions about the codebase. Returns structured context with confidence-scored claims, conflicts, and provenance. Your training data may be stale — this tool has current observations backed by evidence. Start with 'summary' depth and drill down with ix_expand/ix_entity if needed.",
- "inputSchema": {
- "type": "object",
- "properties": {
- "question": { "type": "string", "description": "The question to answer" },
- "asOfRev": { "type": "number", "description": "Optional: query at specific revision for time-travel" },
- "depth": { "type": "string", "enum": ["summary", "standard", "full"], "description": "Response detail level. summary (~200 tokens): top 5 claims + conflict/decision counts. standard (~500-1000 tokens, default): claims + conflicts + decisions + seed nodes. full (~2000+ tokens): everything including all nodes, edges, full provenance breakdowns. Start with summary or standard, drill down with ix_expand/ix_entity." }
- },
- "required": ["question"]
- }
- },
- {
- "name": "ix_decide",
- "description": "Call this AFTER making any design or architecture decision. Records the decision with rationale so future sessions can trace why things were built this way. Creates a Decision node linked to the relevant entity (DECIDED_BY edge) and intent (FULFILLS edge).",
- "inputSchema": {
- "type": "object",
- "properties": {
- "title": { "type": "string", "description": "Brief title of the decision" },
- "rationale": { "type": "string", "description": "Why this was chosen" },
- "alternatives": { "type": "array", "items": { "type": "string" }, "description": "What other options were considered" },
- "entityId": { "type": "string", "description": "Optional: entity this decision relates to (creates DECIDED_BY edge)" },
- "intentId": { "type": "string", "description": "Optional: intent this decision fulfills (creates FULFILLS edge). Enables tracing: Intent → FULFILLS → Decision → DECIDED_BY → Entity" }
- },
- "required": ["title", "rationale"]
- }
- },
- {
- "name": "ix_ingest",
- "description": "Call this after modifying code files. Re-ingests the file to update the memory graph with current state.",
- "inputSchema": {
- "type": "object",
- "properties": {
- "path": { "type": "string", "description": "File or directory path to ingest" },
- "recursive": { "type": "boolean", "description": "Walk directory tree" }
- },
- "required": ["path"]
- }
- },
- {
- "name": "ix_entity",
- "description": "Inspect a specific entity: its attributes, claims, edges, and provenance chain.",
- "inputSchema": {
- "type": "object",
- "properties": {
- "id": { "type": "string", "description": "Entity UUID" },
- "asOfRev": { "type": "number", "description": "Optional: inspect at specific revision" }
- },
- "required": ["id"]
- }
- },
- {
- "name": "ix_search",
- "description": "Search for entities by name or kind. Use when you need to find specific nodes in the graph.",
- "inputSchema": {
- "type": "object",
- "properties": {
- "term": { "type": "string", "description": "Search term (name, keyword)" },
- "kind": { "type": "string", "description": "Optional: filter by node kind (Class, Function, etc.)" }
- },
- "required": ["term"]
- }
- },
- {
- "name": "ix_assert",
- "description": "Manually assert a fact about an entity. Use when you have information not captured by automatic parsing.",
- "inputSchema": {
- "type": "object",
- "properties": {
- "entityId": { "type": "string", "description": "Entity to assert about" },
- "statement": { "type": "string", "description": "The fact being asserted" },
- "source": { "type": "string", "description": "Why you're asserting this" }
- },
- "required": ["entityId", "statement"]
- }
- },
- {
- "name": "ix_diff",
- "description": "Show what changed between two revisions. Use for 'what changed since last session?' queries.",
- "inputSchema": {
- "type": "object",
- "properties": {
- "revA": { "type": "number", "description": "Start revision" },
- "revB": { "type": "number", "description": "End revision (default: latest)" },
- "entityId": { "type": "string", "description": "Optional: scope to entity" }
- },
- "required": ["revA"]
- }
- },
- {
- "name": "ix_conflicts",
- "description": "Check for contradictory claims. Call when you notice conflicting information or want to verify consistency.",
- "inputSchema": {
- "type": "object",
- "properties": {
- "status": { "type": "string", "enum": ["open", "resolved", "all"], "description": "Filter by status" }
- }
- }
- },
- {
- "name": "ix_resolve",
- "description": "Resolve a conflict by choosing the correct claim. Use after investigating contradictory information.",
- "inputSchema": {
- "type": "object",
- "properties": {
- "conflictId": { "type": "string", "description": "Conflict to resolve" },
- "winnerClaimId": { "type": "string", "description": "The claim that is correct" }
- },
- "required": ["conflictId", "winnerClaimId"]
- }
- },
- {
- "name": "ix_expand",
- "description": "Explore the neighborhood of an entity — what it connects to via edges.",
- "inputSchema": {
- "type": "object",
- "properties": {
- "entityId": { "type": "string", "description": "Entity to expand from" },
- "direction": { "type": "string", "enum": ["in", "out", "both"], "description": "Edge direction" },
- "hops": { "type": "number", "description": "Number of hops (default: 1)" }
- },
- "required": ["entityId"]
- }
- },
- {
- "name": "ix_history",
- "description": "Trace the full provenance chain of an entity — every patch that touched it, when, by whom, and why.",
- "inputSchema": {
- "type": "object",
- "properties": {
- "entityId": { "type": "string", "description": "Entity to trace" }
- },
- "required": ["entityId"]
- }
- },
- {
- "name": "ix_truth",
- "description": "View or manage the project's intent hierarchy (user-defined objectives). Call this to understand WHAT the project is trying to accomplish. When the user states a new goal or sub-goal, call this to record it. When you want to propose a sub-intent based on your analysis, call this with proposed=true.",
- "inputSchema": {
- "type": "object",
- "properties": {
- "action": { "type": "string", "enum": ["list", "set", "add", "update", "approve", "abandon"], "description": "What to do" },
- "statement": { "type": "string", "description": "The intent statement (for set/add/update)" },
- "intentId": { "type": "string", "description": "Target intent ID (for update/approve/abandon)" },
- "parentId": { "type": "string", "description": "Parent intent ID (for add, to create sub-intent)" },
- "proposed": { "type": "boolean", "description": "True if this is an LLM-proposed sub-intent (lower confidence until user approves)" }
- },
- "required": ["action"]
- }
- },
- {
- "name": "ix_patches",
- "description": "Search and inspect patches — moments in time. Each patch records what was observed, by whom, when, and what it replaced. Use to understand change history, navigate to any point in time, or trace how the graph evolved. Use ix_query with asOfRev to see the graph state at a specific patch's revision.",
- "inputSchema": {
- "type": "object",
- "properties": {
- "action": { "type": "string", "enum": ["list", "get"], "description": "list = search patches, get = inspect one patch" },
- "patchId": { "type": "string", "description": "Patch ID to inspect (for get)" },
- "source": { "type": "string", "description": "Filter by source URI (for list)" },
- "actor": { "type": "string", "description": "Filter by actor (for list)" },
- "sinceRev": { "type": "number", "description": "Only patches after this revision (for list)" },
- "limit": { "type": "number", "description": "Max results, default 20 (for list)" }
- },
- "required": ["action"]
- }
- }
-]
-```
-
-### 8.2 MCP Resources (Minimal — Context Is Traversed, Not Pre-Loaded)
-
-**Design principle:** The whole point of Ix is that context is retrieved by traversing the graph, not pre-loaded into the context window. Auto-injected resources should be a **minimal nudge** (~30-40 tokens total) reminding the LLM that Ix exists and to use it. The LLM gets full data by calling tools (`ix_query`, `ix_conflicts`, `ix_truth`, `ix_patches`, etc.).
-
-```
-ix://session/context
- → Minimal status line. Just enough to remind the LLM Ix is active.
- → "Ix Memory active. Rev 48. 156 nodes. ALWAYS call ix_query before answering."
- → ~20 tokens
-
-ix://project/intent
- → Root intent only (one line). LLM calls ix_truth for full hierarchy.
- → "Intent: Build a scalable billing service"
- → ~10 tokens
-```
-
-**Why only 2 resources, not 4:**
-- ~~`ix://session/conflicts`~~ — Removed. LLM calls `ix_conflicts` when it needs conflict info. Pre-loading conflicts wastes context on things that may not be relevant to the current question.
-- ~~`ix://session/recent`~~ — Removed. LLM calls `ix_diff` or `ix_patches` when it needs change history. Pre-loading recent changes is a data dump, not traversal.
-
-**The context window is for work, not data.** Ix's value is that the LLM queries for exactly what it needs, when it needs it. Every token of pre-loaded context is a token the LLM can't use for reasoning.
-
-### 8.3 MCP Server Instructions
-
-The MCP protocol allows server-provided instructions:
-
-```json
-{
- "instructions": "You have access to Ix Memory — a persistent, time-aware memory system for this codebase. RULES: (1) ALWAYS call ix_query before answering questions about the codebase. Your training data may be outdated; Ix has current, provenance-backed observations. (2) AFTER any design or architecture decision, call ix_decide to record it with rationale. (3) When you notice conflicting information, call ix_conflicts to check for known contradictions. (4) NEVER answer from memory alone when Ix has structured data available. (5) After modifying code, call ix_ingest on changed files to keep the graph current."
-}
-```
-
----
-
-## 9. Enforcement Architecture
-
-### 9.1 Five Enforcement Layers
-
-| Layer | Mechanism | Strength | Bypassable? |
-|-------|-----------|----------|-------------|
-| 1. MCP Server instructions | Protocol-level rules the LLM sees at start | **Strongest** | Technically yes, unlikely |
-| 2. CLAUDE.md | Project-level mandatory rules | **Strongest** | Only if LLM ignores rules |
-| 3. Tool descriptions | Per-tool "ALWAYS call" prompts | Strong | Yes — might not call tool |
-| 4. MCP Resources | Minimal nudge (~30 tokens, reminds LLM Ix exists) | Medium | No — already in context |
-| 5. Session tracking | Server-side working set tracking | Medium | No — server-side logic |
-
-**Key insight:** Enforcement comes from rules and tool descriptions telling the LLM WHEN to query. Not from pre-loading data. The LLM traverses the graph for context — that's the whole point of Ix.
-
-### 9.2 Configuration Files
-
-**claude_desktop_config.json** (for Claude Desktop):
-```json
-{
- "mcpServers": {
- "ix-memory": {
- "command": "ix",
- "args": ["mcp", "start"],
- "env": {
- "IX_ENDPOINT": "http://localhost:8090",
- "IX_PROJECT": "my-project"
- }
- }
- }
-}
-```
-
-**CLAUDE.md** (for Claude Code, auto-generated by `ix init`):
-```markdown
-# Ix Memory System
-
-This project uses Ix Memory for persistent, time-aware context.
-
-## MANDATORY RULES
-1. BEFORE answering any question about this codebase → call ix_query
-2. AFTER making any design/architecture decision → call ix_decide
-3. When noticing contradictory information → call ix_conflicts
-4. NEVER guess about codebase facts when Ix has structured data
-5. After modifying code → call ix_ingest on changed files
-6. At start of each session → review ix://session/context for prior work
-```
-
-### 9.3 How Enforcement Works in Practice
-
-```
-Turn 1: User asks "How does billing retry?"
-
- 1. MCP Resource ix://session/context auto-injects (~20 tokens):
- "Ix Memory active. Rev 48. 156 nodes. ALWAYS call ix_query before answering."
-
- 2. CLAUDE.md says: "BEFORE answering → call ix_query"
-
- 3. Tool ix_query description says: "ALWAYS call this first"
-
- 4. LLM calls ix_query("How does billing retry?")
- → Traverses graph → Gets StructuredContext with claims, confidence, provenance
-
- 5. LLM responds WITH provenance:
- "Based on billing_service.py (confidence 0.90, rev 1):
- retry_payment uses max_retries=3..."
-
-Turn 2: User asks "Should we use circuit breaker instead?"
-
- 1. MCP Resource still just the nudge:
- "Ix Memory active. Rev 48. 156 nodes. ALWAYS call ix_query before answering."
-
- 2. LLM calls ix_query("circuit breaker vs exponential backoff")
- → Traverses graph for relevant context
-
- 3. LLM discusses options, then decides:
- "I recommend keeping exponential backoff over circuit breaker."
-
- 4. CLAUDE.md says: "AFTER design decision → call ix_decide"
-
- 5. LLM calls ix_decide({
- title: "Keep exponential backoff over circuit breaker",
- rationale: "Circuit breaker adds complexity, exponential backoff
- already handles transient failures well",
- alternatives: ["circuit breaker", "linear backoff", "no retry"]
- })
-
- 6. Decision recorded in graph as a patch with full provenance.
-```
-
----
-
-## 10. Packaging & Distribution
-
-### 10.1 Repository Structure
-
-```
-IX-Memory-Repo/
-├── stack.sh # Start/stop backend containers
-├── dev.sh # Local dev mode
-├── docker-compose.yml # Backend: ArangoDB + Memory Layer
-│
-├── memory-layer/ # Scala — core engine (Docker)
-│ ├── build.sbt
-│ ├── Dockerfile
-│ ├── dist/ # Pre-built ix-memory.jar
-│ └── src/main/scala/ix/memory/
-│ ├── Main.scala
-│ ├── api/ # HTTP routes
-│ ├── context/ # Query pipeline
-│ ├── ingestion/ # Parsers
-│ ├── model/ # Data types
-│ ├── db/ # ArangoDB
-│ └── conflict/ # Conflict service
-│
-├── ix-cli/ # TypeScript — CLI + MCP (npm)
-│ ├── package.json # @ix/cli
-│ ├── tsconfig.json
-│ ├── src/
-│ │ ├── cli/ # Commands (commander.js)
-│ │ ├── mcp/ # MCP server
-│ │ │ ├── server.ts # stdio handler
-│ │ │ ├── tools/ # Tool definitions
-│ │ │ ├── resources/ # Resource providers
-│ │ │ └── session.ts # Session state
-│ │ └── client/ # HTTP client
-│ └── test/
-│
-├── templates/ # Config templates for ix init
-│ ├── CLAUDE.md.template
-│ └── claude_desktop_config.json.template
-│
-└── docs/plans/ # Design documents
-```
-
-### 10.2 Docker Architecture
-
-```yaml
-# docker-compose.yml
-services:
- arangodb:
- image: arangodb:3.12
- ports: ["8529:8529"]
- volumes: [ix_arango_data:/var/lib/arangodb3]
- healthcheck: curl -sf http://localhost:8529/_api/version
-
- memory-layer:
- image: ix/memory-layer:local
- depends_on: { arangodb: { condition: service_healthy } }
- ports: ["8090:8090"]
- environment:
- ARANGO_HOST: arangodb
- ARANGO_PORT: "8529"
- ARANGO_DATABASE: ix_memory
- healthcheck: curl -sf http://localhost:8090/v1/health
-```
-
-### 10.3 First-Run Experience
-
-```bash
-# Install CLI
-npm install -g @ix/cli
-
-# Initialize in project
-cd ~/my-project
-ix init
-# → Starts Docker containers
-# → Creates ~/.ix/config.yaml
-# → Creates ./CLAUDE.md
-# → Optionally configures Claude Desktop
-# → Optionally ingests project
-
-# Use
-ix ingest ./src --recursive
-ix query "How does billing retry?"
-ix status
-```
-
-### 10.4 stack.sh
-
-Single script to manage backend:
-```bash
-./stack.sh # Build + start (ArangoDB + Memory Layer)
-./stack.sh down # Stop everything
-./stack.sh logs # View logs
-```
-
----
-
-## 11. User Guide: Starting the Stack
-
-> Lives at: `docs/guides/user-guide.md` (full version) + summarized in `README.md`
-
-### 11.1 Prerequisites
-
-```
-- Docker Desktop (or Docker Engine + Docker Compose)
-- Node.js 18+ (for the CLI)
-- npm (comes with Node.js)
-```
-
-### 11.2 Quick Start
-
-```bash
-# 1. Clone the repo
-git clone https://github.com/ix-infrastructure/IX-Memory-Repo.git
-cd IX-Memory-Repo
-
-# 2. Start the backend (ArangoDB + Memory Layer)
-./stack.sh
-
-# What this does:
-# ┌──────────────────────────────────────────────────────────┐
-# │ stack.sh │
-# │ 1. Checks Docker is installed and running │
-# │ 2. Builds Memory Layer JAR (if not pre-built) │
-# │ 3. Builds Docker image: ix/memory-layer:local │
-# │ 4. Runs: docker compose up -d │
-# │ ├── arangodb:3.12 → port 8529 (graph database) │
-# │ └── memory-layer → port 8090 (API server) │
-# │ 5. Waits for health check to pass │
-# │ 6. Prints: "Ix Memory backend is ready" │
-# └──────────────────────────────────────────────────────────┘
-
-# 3. Install the CLI
-npm install -g @ix/cli
-
-# 4. Initialize Ix in your project
-cd ~/your-project
-ix init
-
-# What this does:
-# ┌──────────────────────────────────────────────────────────┐
-# │ ix init │
-# │ 1. Verifies backend is running (http://localhost:8090) │
-# │ 2. Creates ~/.ix/config.yaml (endpoint, defaults) │
-# │ 3. Creates ./CLAUDE.md (enforcement rules for LLM) │
-# │ 4. Asks: "Configure Claude Desktop?" → updates config │
-# │ 5. Asks: "Ingest this project?" → parses codebase │
-# └──────────────────────────────────────────────────────────┘
-
-# 5. Ingest your codebase
-ix ingest ./src --recursive
-
-# 6. Query
-ix query "How does billing handle retries?"
-
-# 7. Check status
-ix status
-```
-
-### 11.3 Managing the Stack
-
-```bash
-./stack.sh # Start backend (build if needed)
-./stack.sh down # Stop all containers
-./stack.sh logs # Tail container logs
-
-# Check container health
-docker compose ps
-
-# Reset database (delete all data)
-docker compose down -v # -v removes volumes
-./stack.sh # Fresh start
-```
-
-### 11.4 Development Mode
-
-For working on the Memory Layer itself (no Docker for the Scala service):
-
-```bash
-./dev.sh # Starts ArangoDB in Docker, runs Memory Layer via sbt
-./dev.sh stop # Stops ArangoDB container
-```
-
----
-
-## 12. LLM Integration Guide: Connecting Ix to Your LLM
-
-> Lives at: `docs/guides/llm-integration.md` (full version) + summarized in `README.md`
-
-### 12.1 Overview
-
-Ix integrates with LLMs through two mechanisms:
-1. **MCP Server** — provides tools and auto-injected context to the LLM
-2. **System prompts** (CLAUDE.md) — rules that tell the LLM to use Ix
-
-```
-Your LLM (Claude Desktop, Claude Code, Cursor)
- │
- ├── Reads CLAUDE.md → learns the rules ("always call ix_query first")
- ├── Connects to MCP Server → gets tools (ix_query, ix_decide, etc.)
- └── Receives MCP Resources → auto-injected context every turn
-```
-
-### 12.2 Claude Desktop Integration
-
-**Step 1:** Run `ix mcp install` (or do it manually):
-
-```json
-// ~/Library/Application Support/Claude/claude_desktop_config.json (macOS)
-// %APPDATA%/Claude/claude_desktop_config.json (Windows)
-{
- "mcpServers": {
- "ix-memory": {
- "command": "ix",
- "args": ["mcp", "start"],
- "env": {
- "IX_ENDPOINT": "http://localhost:8090",
- "IX_PROJECT": "my-project"
- }
- }
- }
-}
-```
-
-**Step 2:** Restart Claude Desktop. You should see "ix-memory" in the MCP tools list.
-
-**Step 3:** Open a conversation. The LLM now has access to:
-
-| What | How | Enforcement |
-|------|-----|-------------|
-| **13 tools** (ix_query, ix_decide, ix_ingest, ix_patches, etc.) | LLM calls them like functions | Tool descriptions say WHEN to call |
-| **2 resources** (session status + root intent, ~30 tokens) | Minimal nudge every turn | Passive — reminds LLM to use Ix |
-| **Server instructions** | Sent via MCP protocol | Rules the LLM sees at start |
-
-### 12.3 Claude Code Integration
-
-**Step 1:** Add CLAUDE.md to your project root (auto-generated by `ix init`):
-
-```markdown
-# Ix Memory System
-
-This project uses Ix Memory for persistent, time-aware context.
-
-## MANDATORY RULES
-1. BEFORE answering any question about this codebase → call ix_query
-2. AFTER making any design/architecture decision → call ix_decide
-3. When noticing contradictory information → call ix_conflicts
-4. NEVER guess about codebase facts when Ix has structured data
-5. After modifying code → call ix_ingest on changed files
-6. At start of each session → review ix://session/context for prior work
-7. When the user states a goal → call ix_truth to record it
-```
-
-**Step 2:** Add MCP server to Claude Code settings (`.claude/settings.json` or via `ix mcp install --claude-code`):
-
-```json
-{
- "mcpServers": {
- "ix-memory": {
- "command": "ix",
- "args": ["mcp", "start"],
- "env": {
- "IX_ENDPOINT": "http://localhost:8090"
- }
- }
- }
-}
-```
-
-**Step 3:** Start Claude Code in your project directory. Both CLAUDE.md rules and MCP tools are active.
-
-### 12.4 Cursor Integration
-
-```bash
-ix mcp install --cursor
-```
-
-This writes to `.cursor/mcp.json`:
-
-```json
-{
- "mcpServers": {
- "ix-memory": {
- "command": "ix",
- "args": ["mcp", "start"],
- "env": {
- "IX_ENDPOINT": "http://localhost:8090"
- }
- }
- }
-}
-```
-
-### 12.5 How Enforcement Works (What the LLM Sees)
-
-On every conversation turn, the LLM receives:
-
-**1. Auto-injected resources (minimal nudge, ~30 tokens — NOT a data dump):**
-
-```
-[ix://session/context]
-Ix Memory active. Rev 48. 156 nodes. ALWAYS call ix_query before answering.
-
-[ix://project/intent]
-Intent: Build a scalable billing service
-```
-
-Context is traversed, not pre-loaded. The LLM calls tools to get the data it needs.
-
-**2. Available tools with enforcement descriptions (13 tools):**
-
-```
-ix_query: "ALWAYS call this before answering questions about the codebase..."
-ix_decide: "Call this AFTER making any design or architecture decision..."
-ix_ingest: "Call this after modifying code files..."
-ix_truth: "View or manage the project's intent hierarchy..."
-ix_patches: "Search and inspect patches — moments in time..."
-ix_conflicts: "Check for contradictory claims..."
-```
-
-**3. CLAUDE.md rules (Claude Code only):**
-
-```
-MANDATORY: BEFORE answering → call ix_query
-MANDATORY: AFTER decisions → call ix_decide
-```
-
-### 12.6 Verification: Is It Working?
-
-After setup, test the integration:
-
-```bash
-# 1. Make sure backend is running
-ix status
-# Should show: "Connected to http://localhost:8090, rev: N, X nodes, Y edges"
-
-# 2. In your LLM, ask a question about your codebase
-# "How does billing handle retries?"
-
-# 3. The LLM should:
-# a. Call ix_query (you'll see the tool call in the UI)
-# b. Respond with provenance: "Based on billing_service.py (confidence 0.90)..."
-# c. Mention conflicts if any exist
-
-# 4. Check what the LLM recorded
-ix history <entity-id>
-# Should show patches from both ingestion AND LLM decisions
-```
-
-### 12.7 Troubleshooting
-
-| Problem | Solution |
-|---------|----------|
-| LLM doesn't call ix_query | Check CLAUDE.md exists in project root. Check MCP server is listed in config. |
-| "Connection refused" | Run `./stack.sh` to start backend. Check `ix status`. |
-| MCP tools not showing | Restart Claude Desktop/Cursor after config change. |
-| Stale data | Run `ix ingest ./src --recursive` to refresh. |
-| LLM ignores memory | Strengthen CLAUDE.md rules. Check MCP server instructions field. |
-
----
-
-## 13. Documentation Structure
-
-```
-IX-Memory-Repo/
-├── README.md # Quick-start summary with links
-│ ├── What is Ix? (2 sentences)
-│ ├── Quick Start (5 commands)
-│ ├── Link → docs/guides/user-guide.md
-│ └── Link → docs/guides/llm-integration.md
-│
-├── docs/
-│ ├── guides/
-│ │ ├── user-guide.md # Full: stack.sh, CLI, commands
-│ │ └── llm-integration.md # Full: MCP, CLAUDE.md, enforcement
-│ └── plans/
-│ ├── 2026-03-03-ix-redesign.md # This design document
-│ └── (implementation plan)
-```
-
----
-
-## 14. Build Phases (Redesign)
-
-### Phase 1: Adapt Memory Layer (Scala) — EXISTING, needs updates
-
-The existing Phase 1 code is mostly reusable. Updates needed:
-- **Remove TenantId** from all models, APIs, and DB queries (single-codebase system)
-- Add Decision node type + DECIDED_BY edge to model
-- Add `/v1/decide` endpoint
-- Add `/v1/search` endpoint
-- Update StructuredContext to include decisions
-- Update deterministic ID generation to remove tenant prefix
-- Ensure all existing E2E tests still pass (updated for no-tenant)
-
-### Phase 2: CLI + MCP Server (TypeScript) — NEW
-
-Build the TypeScript package:
-- CLI commands (commander.js, all calling Memory Layer HTTP API)
-- MCP server (stdio, @modelcontextprotocol/sdk)
-- MCP Resources (session context, conflicts, recent changes)
-- Session manager (track working set)
-- `ix init` command (Docker setup, config generation, CLAUDE.md)
-- `ix mcp install` command (configure Claude Desktop/Cursor)
-
-### Phase 3: Enforcement & Polish
-
-- CLAUDE.md template with optimal enforcement rules
-- Tool descriptions optimized for maximum LLM compliance
-- MCP server instructions field
-- Session restoration across conversations
-- Terminal UI polish (tables, colors, tree views)
-
-### Phase 4: Additional Parsers + Advanced Features
-
-- TypeScript parser (tree-sitter)
-- Config parser (YAML/JSON/TOML)
-- Markdown parser
-- Corroboration counting across sources
-- Staleness detection (source hash changed)
-- Working set continuity
-- Metrics: comparing old system vs new (accuracy measurement)
-
----
-
-## 15. Key Design Decisions (Rationale)
-
-| Decision | Chosen | Alternatives Considered | Why |
-|----------|--------|------------------------|-----|
-| MCP enforcement model | MCP-Heavy (Resources + instructions + tool descriptions) | Stateless proxy, Dual-layer | Maximum enforcement. Resources = passive injection = closest to 100% |
-| CLI/MCP language | TypeScript | Rust, Go, Kotlin, Scala | Official MCP SDK is TypeScript. Largest contributor pool. npm distribution standard. |
-| Memory Layer language | Scala (keep existing) | Rewrite in Rust/Go | Already built, 48 files, full test suite. Cats Effect is production-grade. No reason to rewrite. |
-| Backend packaging | Docker Compose | Kubernetes, bare metal | Matches SimplestData. Simple for dev/demo. K8s later for prod. |
-| CLI/MCP packaging | npm (local install) | Docker, Homebrew | MCP needs stdio (local). CLI needs file access (local). npm is standard. |
-| No multi-tenancy | Single codebase system | Per-org/per-user isolation | System serves one codebase. Everyone sees same graph. Simpler model, no TenantId on every entity. |
-| DB | ArangoDB now, custom later | Neo4j, SurrealDB, Memgraph | Already integrated. Trait-based API allows swap. Custom DB is long-term goal. |
-| Node IDs | Deterministic (UUID.nameUUIDFromBytes) | Random UUID, sequential | Enables idempotent re-ingestion. Same file → same nodes. Deterministic graph from same patch log. |
-| Confidence | Computed from provenance, never manual | Manual scores, fixed weights | Eliminates subjectivity. Explainable breakdowns. Changes automatically as evidence accumulates. |
-| Conflicts | Surfaced to user, not auto-resolved | Auto-pick winner, ignore | "Conflict is a feature, not a bug." Human judgment for resolution. Transparency. |
diff --git a/docs/plans/2026-03-07-symbol-extraction-design.md b/docs/plans/2026-03-07-symbol-extraction-design.md
deleted file mode 100644
index b9ab0f93..00000000
--- a/docs/plans/2026-03-07-symbol-extraction-design.md
+++ /dev/null
@@ -1,206 +0,0 @@
-# Symbol-Level Extraction Design
-
-**Date:** 2026-03-07
-**Goal:** Evolve Ix from file/blob-centric retrieval toward symbol-centric scene-graph retrieval while preserving the current parser architecture.
-
-**Approach:** Enhance existing regex parsers + query/search layer. No tree-sitter. No parser rewrites.
-
----
-
-## 1. New NodeKinds
-
-Add 4 cases to `sealed trait NodeKind` in `Node.scala`:
-
-- **Object** — Scala objects (companion objects, singletons)
-- **Trait** — Scala traits
-- **Interface** — TypeScript interfaces
-- **Method** — Class/object/trait methods (vs top-level `Function`)
-
-### Mapping Rules
-
-| Language | Construct | NodeKind |
-|----------|-----------|----------|
-| Scala | `trait Foo` | Trait |
-| Scala | `object Foo` | Object |
-| Scala | `class Foo` / `case class Foo` | Class |
-| Scala | `def bar` inside container | Method |
-| Scala | `def bar` top-level | Function |
-| TypeScript | `interface Foo` | Interface |
-| TypeScript | `class Foo` | Class |
-| TypeScript | method inside class | Method |
-| TypeScript | top-level function/arrow | Function |
-
----
-
-## 2. Parser Enhancements
-
-### ScalaParser
-
-- Use `Trait` kind for trait matches (was `Class`)
-- Use `Object` kind for object matches (was `Class`)
-- Use `Method` for def inside a container, `Function` for top-level def
-- Add `signature` attr — capture the def line up to `=` or `{`
-- Add `visibility` attr — detect `private`/`protected` prefixes
-- Verify trait->method and object->method emit CONTAINS edges
-- Keep existing DEFINES, IMPORTS edges
-
-### TypeScriptParser
-
-- Use `Interface` for interface matches (was `Class`)
-- Use `Method` for methods inside classes (was `Function`)
-- Add CONTAINS edges — file->class, class->method (currently only DEFINES)
-- Add `signature` attr — capture matched line
-- Add `visibility` attr — detect public/private/protected
-- Keep existing DEFINES, IMPORTS, CALLS edges
-- Keep file-level content on File node
-
-### Symbol Attributes
-
-| Attribute | Source | Required |
-|-----------|--------|----------|
-| name | Already emitted | Yes |
-| language | Already emitted | Yes |
-| lineStart | Already emitted | Yes |
-| lineEnd | Already emitted | Yes |
-| signature | First line of match, trimmed | Optional |
-| visibility | Regex prefix check | Optional |
-| summary | Already emitted for some | Keep if exists |
-
----
-
-## 3. Query Ranking — Symbol Preference
-
-### RelevanceScorer Changes
-
-Add a `kindBoost` factor to the existing relevance formula:
-
-```
-relevance = min(1.0, hopRelevance * exactBoost * pathBoost * kindBoost)
-```
-
-| NodeKind | Boost | Rationale |
-|----------|-------|-----------|
-| Method, Function | 1.3x | Most useful for "what does X do" queries |
-| Class, Trait, Object, Interface | 1.3x | Symbol-level structural answers |
-| Module | 1.2x | Useful but less specific |
-| File | 0.6x | Content blob — deprioritize when symbols exist |
-| Config, ConfigEntry | 1.0x | Neutral |
-| Doc | 1.0x | Neutral |
-| Intent, Decision, Service, Endpoint, Variable | 1.0x | Neutral |
-
-### Implementation
-
-Pass `Map[NodeId, NodeKind]` from already-fetched nodes in `ContextService` into `RelevanceScorer.scoreWithTerms()`. No extra DB queries needed.
-
----
-
-## 4. Search Improvements
-
-### Sort symbols first
-
-Add ordering to the search AQL — symbol NodeKinds sort above file/config/doc nodes:
-
-```aql
-SORT n.kind IN ["function","method","class","trait","object","interface"] ? 0 : 1,
- n.name ASC
-```
-
-### Add attribute search
-
-Search node attrs (especially signature) in addition to name/provenance/claims:
-
-```aql
-LET attr_matches = (
- FOR n IN nodes
- FILTER n.deleted_rev == null
- AND CONTAINS(LOWER(TO_STRING(n.attrs)), LOWER(@text))
- RETURN DISTINCT n.logical_id
-)
-```
-
-No fulltext index needed at current scale.
-
----
-
-## 5. Preserved Behavior
-
-The following must not regress:
-
-- File-level content on TypeScript and Scala file nodes
-- compactClaims token efficiency
-- Config/Markdown/Python parsing (untouched)
-- Decisions and intents (ix_decide, ix_truth, neutral kindBoost)
-- Global diff without entityId
-- Cross-file import edge resolution
-- Existing DEFINES, CONTAINS, IMPORTS, CALLS edges
-
----
-
-## 6. Files Modified
-
-| File | Change |
-|------|--------|
-| `Node.scala` | Add Object, Trait, Interface, Method to NodeKind |
-| `ScalaParser.scala` | Use correct kinds, add signature/visibility attrs |
-| `TypeScriptParser.scala` | Use Interface/Method, add CONTAINS edges, add attrs |
-| `RelevanceScorer.scala` | Add kindBoost factor |
-| `ContextService.scala` | Pass node-kind map to scorer |
-| `ArangoGraphQueryApi.scala` | Add attr search + sort to search query |
-
----
-
-## 7. Not In Scope
-
-- Tree-sitter integration
-- New MCP tools or routes
-- Schema migrations or new ArangoDB collections
-- Fulltext indexing
-- Type resolution or inheritance graphs
-- Parser rewrites
-- Languages beyond TypeScript and Scala
-
----
-
-## 8. Expected Outcome
-
-A query like "what parses claims?" returns:
-
-```
-parseClaim
- kind: Method
- file: ArangoGraphQueryApi.scala
- line: 48-96
- signature: def parseClaim(doc: VPackSlice): Claim
- summary: deserializes Arango JSON into Claim model
-```
-
-Instead of a file content blob.
-
----
-
-## 9. Validation Checklist
-
-### TypeScript
-- [ ] `.ts` file still has file-level content
-- [ ] Symbol nodes emitted (Class, Interface, Function, Method)
-- [ ] CONTAINS edges (file->class, class->method)
-- [ ] IMPORTS edges preserved
-- [ ] CALLS edges preserved
-
-### Scala
-- [ ] `.scala` file produces symbol nodes (Trait, Object, Class, Method, Function)
-- [ ] CONTAINS edges (class->method, trait->method, object->method)
-- [ ] IMPORTS edges preserved
-- [ ] DEFINES edges preserved
-- [ ] signature and visibility attrs present
-
-### Query
-- [ ] "what parses claims" returns symbol-level result, not file blob
-- [ ] compact query remains small (8 claims, 8 nodes, 10 edges)
-- [ ] File content still accessible in full/standard depth
-
-### Search
-- [ ] `ix_search("parseClaim")` finds the symbol
-- [ ] `ix_search("ContextService")` finds the symbol
-- [ ] `ix_search("GraphPatchBuilder")` finds the symbol
-- [ ] Symbol nodes sort above file nodes in results
diff --git a/docs/plans/2026-03-07-symbol-extraction-plan.md b/docs/plans/2026-03-07-symbol-extraction-plan.md
deleted file mode 100644
index 4da9ebda..00000000
--- a/docs/plans/2026-03-07-symbol-extraction-plan.md
+++ /dev/null
@@ -1,1208 +0,0 @@
-# Symbol-Level Extraction Implementation Plan
-
-> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
-
-**Goal:** Evolve Ix from file-blob retrieval to symbol-centric scene-graph retrieval by adding 4 NodeKinds, enhancing parsers, boosting symbol relevance in queries, and improving search.
-
-**Architecture:** Additive changes to 6 existing files. No new routes, tools, collections, or schema migrations. Parsers emit richer NodeKinds and CONTAINS edges. RelevanceScorer applies a kindBoost to prefer symbols over file blobs. Search AQL sorts symbols first and searches attrs.
-
-**Tech Stack:** Scala 2.13, Cats Effect 3, ArangoDB AQL, ScalaTest (AnyFlatSpec + Matchers)
-
----
-
-### Task 1: Add NodeKind variants (Object, Trait, Interface, Method)
-
-**Files:**
-- Modify: `memory-layer/src/main/scala/ix/memory/model/Node.scala:8-56`
-- Modify: `memory-layer/src/test/scala/ix/memory/model/ModelSpec.scala:70-89`
-
-**Step 1: Write the failing test**
-
-Add the 4 new variants to the existing `ModelSpec` NodeKind round-trip test.
-
-In `memory-layer/src/test/scala/ix/memory/model/ModelSpec.scala`, replace the `variants` list in the `"NodeKind" should "encode and decode all variants correctly"` test (lines 71-83) with:
-
-```scala
- "NodeKind" should "encode and decode all variants correctly" in {
- val variants: List[NodeKind] = List(
- NodeKind.Module,
- NodeKind.File,
- NodeKind.Class,
- NodeKind.Function,
- NodeKind.Variable,
- NodeKind.Config,
- NodeKind.ConfigEntry,
- NodeKind.Service,
- NodeKind.Endpoint,
- NodeKind.Intent,
- NodeKind.Decision,
- NodeKind.Doc,
- NodeKind.Object,
- NodeKind.Trait,
- NodeKind.Interface,
- NodeKind.Method
- )
-
- variants.foreach { nk =>
- val json = nk.asJson
- json.isString shouldBe true
- decode[NodeKind](json.noSpaces) shouldBe Right(nk)
- }
- }
-```
-
-**Step 2: Run test to verify it fails**
-
-Run: `cd memory-layer && sbt "testOnly ix.memory.model.ModelSpec"`
-Expected: Compilation failure — `Object`, `Trait`, `Interface`, `Method` not found in `NodeKind`
-
-**Step 3: Write minimal implementation**
-
-In `memory-layer/src/main/scala/ix/memory/model/Node.scala`, add 4 case objects and update `nameMap` + `encoder`:
-
-```scala
-sealed trait NodeKind
-object NodeKind {
- case object Module extends NodeKind
- case object File extends NodeKind
- case object Class extends NodeKind
- case object Function extends NodeKind
- case object Variable extends NodeKind
- case object Config extends NodeKind
- case object ConfigEntry extends NodeKind
- case object Service extends NodeKind
- case object Endpoint extends NodeKind
- case object Intent extends NodeKind
- case object Decision extends NodeKind
- case object Doc extends NodeKind
- case object Object extends NodeKind
- case object Trait extends NodeKind
- case object Interface extends NodeKind
- case object Method extends NodeKind
-
- private val nameMap: Map[String, NodeKind] = Map(
- "module" -> Module,
- "file" -> File,
- "class" -> Class,
- "function" -> Function,
- "variable" -> Variable,
- "config" -> Config,
- "config_entry" -> ConfigEntry,
- "service" -> Service,
- "endpoint" -> Endpoint,
- "intent" -> Intent,
- "decision" -> Decision,
- "doc" -> Doc,
- "object" -> Object,
- "trait" -> Trait,
- "interface" -> Interface,
- "method" -> Method
- )
-
- implicit val encoder: Encoder[NodeKind] = Encoder[String].contramap {
- case Module => "module"
- case File => "file"
- case Class => "class"
- case Function => "function"
- case Variable => "variable"
- case Config => "config"
- case ConfigEntry => "config_entry"
- case Service => "service"
- case Endpoint => "endpoint"
- case Intent => "intent"
- case Decision => "decision"
- case Doc => "doc"
- case Object => "object"
- case Trait => "trait"
- case Interface => "interface"
- case Method => "method"
- }
-
- implicit val decoder: Decoder[NodeKind] = Decoder[String].emap { s =>
- nameMap.get(s).toRight(s"Unknown NodeKind: $s")
- }
-}
-```
-
-**Step 4: Run test to verify it passes**
-
-Run: `cd memory-layer && sbt "testOnly ix.memory.model.ModelSpec"`
-Expected: All tests PASS
-
-**Step 5: Commit**
-
-```bash
-git add memory-layer/src/main/scala/ix/memory/model/Node.scala memory-layer/src/test/scala/ix/memory/model/ModelSpec.scala
-git commit -m "feat: add Object, Trait, Interface, Method NodeKinds"
-```
-
----
-
-### Task 2: Enhance ScalaParser — use correct NodeKinds, add signature/visibility
-
-**Files:**
-- Modify: `memory-layer/src/main/scala/ix/memory/ingestion/parsers/ScalaParser.scala:1-220`
-- Modify: `memory-layer/src/test/scala/ix/memory/ingestion/parsers/ScalaParserSpec.scala:1-129`
-
-**Step 1: Write the failing tests**
-
-Replace `ScalaParserSpec.scala` entirely. Key changes: expect `NodeKind.Trait` instead of `NodeKind.Class` for traits, `NodeKind.Object` for objects, `NodeKind.Method` for contained defs, `NodeKind.Function` for top-level defs. Add tests for `signature` and `visibility` attrs, and CONTAINS edges.
-
-```scala
-package ix.memory.ingestion.parsers
-
-import org.scalatest.flatspec.AnyFlatSpec
-import org.scalatest.matchers.should.Matchers
-import ix.memory.model.NodeKind
-import io.circe.Json
-
-class ScalaParserSpec extends AnyFlatSpec with Matchers {
- val parser = new ScalaParser
-
- val sampleCode: String =
- """package ix.memory.context
- |
- |import cats.effect.IO
- |import ix.memory.model.{Claim, GraphNode}
- |
- |trait ConfidenceScorer {
- | def score(claim: Claim, ctx: ScoringContext): ScoredClaim
- |}
- |
- |class ConfidenceScorerImpl extends ConfidenceScorer {
- | override def score(claim: Claim, ctx: ScoringContext): ScoredClaim = {
- | val base = computeBase(claim)
- | ScoredClaim(claim, base)
- | }
- |
- | private def computeBase(claim: Claim): Double = {
- | claim.provenance.sourceType match {
- | case SourceType.Code => 0.9
- | case _ => 0.5
- | }
- | }
- |}
- |
- |object ConfidenceScorerImpl {
- | def apply(): ConfidenceScorerImpl = new ConfidenceScorerImpl
- |}
- |""".stripMargin
-
- "ScalaParser" should "create a File entity" in {
- val result = parser.parse("ConfidenceScorer.scala", sampleCode)
- val file = result.entities.find(_.kind == NodeKind.File)
- file shouldBe defined
- file.get.name shouldBe "ConfidenceScorer.scala"
- file.get.attrs.get("language") shouldBe Some(Json.fromString("scala"))
- }
-
- it should "extract trait definitions with Trait kind" in {
- val result = parser.parse("ConfidenceScorer.scala", sampleCode)
- val traits = result.entities.filter(_.kind == NodeKind.Trait)
- traits.map(_.name) should contain("ConfidenceScorer")
- }
-
- it should "extract class definitions with Class kind" in {
- val result = parser.parse("ConfidenceScorer.scala", sampleCode)
- val classes = result.entities.filter(_.kind == NodeKind.Class)
- classes.map(_.name) should contain("ConfidenceScorerImpl")
- }
-
- it should "extract object definitions with Object kind" in {
- val result = parser.parse("ConfidenceScorer.scala", sampleCode)
- val objects = result.entities.filter(_.kind == NodeKind.Object)
- objects.map(_.name) should contain("ConfidenceScorerImpl")
- }
-
- it should "extract contained defs as Method kind" in {
- val result = parser.parse("ConfidenceScorer.scala", sampleCode)
- val methods = result.entities.filter(_.kind == NodeKind.Method)
- methods.map(_.name) should contain allOf ("score", "computeBase", "apply")
- }
-
- it should "extract top-level defs as Function kind" in {
- val code =
- """def topLevel(x: Int): Int = x + 1
- |
- |class Foo {
- | def bar(): Unit = ()
- |}
- |""".stripMargin
- val result = parser.parse("TopLevel.scala", code)
- val functions = result.entities.filter(_.kind == NodeKind.Function)
- functions.map(_.name) should contain("topLevel")
- val methods = result.entities.filter(_.kind == NodeKind.Method)
- methods.map(_.name) should contain("bar")
- }
-
- it should "extract import statements" in {
- val result = parser.parse("ConfidenceScorer.scala", sampleCode)
- val imports = result.entities.filter(_.kind == NodeKind.Module)
- imports.map(_.name) should contain allOf ("cats.effect.IO", "ix.memory.model")
- }
-
- it should "create DEFINES relationships from file to types" in {
- val result = parser.parse("ConfidenceScorer.scala", sampleCode)
- val defines = result.relationships.filter(_.predicate == "DEFINES")
- defines.map(r => (r.srcName, r.dstName)) should contain allOf (
- ("ConfidenceScorer.scala", "ConfidenceScorer"),
- ("ConfidenceScorer.scala", "ConfidenceScorerImpl")
- )
- }
-
- it should "create CONTAINS relationships from types to methods" in {
- val result = parser.parse("ConfidenceScorer.scala", sampleCode)
- val contains = result.relationships.filter(_.predicate == "CONTAINS")
- contains.map(r => (r.srcName, r.dstName)) should contain allOf (
- ("ConfidenceScorerImpl", "score"),
- ("ConfidenceScorerImpl", "computeBase")
- )
- }
-
- it should "create IMPORTS relationships" in {
- val result = parser.parse("ConfidenceScorer.scala", sampleCode)
- val imports = result.relationships.filter(_.predicate == "IMPORTS")
- imports should not be empty
- }
-
- it should "store method signature attr" in {
- val result = parser.parse("ConfidenceScorer.scala", sampleCode)
- val method = result.entities.find(_.name == "computeBase").get
- val sig = method.attrs.get("signature").flatMap(_.asString)
- sig shouldBe defined
- sig.get should include("computeBase")
- }
-
- it should "store visibility attr for private defs" in {
- val result = parser.parse("ConfidenceScorer.scala", sampleCode)
- val method = result.entities.find(_.name == "computeBase").get
- val vis = method.attrs.get("visibility").flatMap(_.asString)
- vis shouldBe Some("private")
- }
-
- it should "default visibility to public" in {
- val result = parser.parse("ConfidenceScorer.scala", sampleCode)
- // "score" has override but no private/protected
- val method = result.entities.find(e => e.name == "score" && e.kind == NodeKind.Method)
- method shouldBe defined
- val vis = method.get.attrs.get("visibility").flatMap(_.asString)
- vis shouldBe Some("public")
- }
-
- it should "not store raw file content" in {
- val result = parser.parse("ConfidenceScorer.scala", sampleCode)
- val file = result.entities.find(_.kind == NodeKind.File).get
- file.attrs.get("content") shouldBe None
- }
-
- it should "handle case classes" in {
- val code = """case class Foo(bar: String, baz: Int)""".stripMargin
- val result = parser.parse("Foo.scala", code)
- val classes = result.entities.filter(_.kind == NodeKind.Class)
- classes.map(_.name) should contain("Foo")
- // case classes still keep scala_kind attr
- val foo = classes.find(_.name == "Foo").get
- foo.attrs.get("scala_kind") shouldBe Some(Json.fromString("case_class"))
- }
-
- it should "preserve scala_kind attr on traits" in {
- val result = parser.parse("ConfidenceScorer.scala", sampleCode)
- val tr = result.entities.find(_.name == "ConfidenceScorer").get
- tr.attrs.get("scala_kind") shouldBe Some(Json.fromString("trait"))
- }
-
- it should "preserve scala_kind attr on objects" in {
- val result = parser.parse("ConfidenceScorer.scala", sampleCode)
- val obj = result.entities.find(e => e.name == "ConfidenceScorerImpl" && e.kind == NodeKind.Object).get
- obj.attrs.get("scala_kind") shouldBe Some(Json.fromString("object"))
- }
-}
-```
-
-**Step 2: Run tests to verify they fail**
-
-Run: `cd memory-layer && sbt "testOnly ix.memory.ingestion.parsers.ScalaParserSpec"`
-Expected: FAIL — traits still emit `NodeKind.Class`, methods still emit `NodeKind.Function`, no CONTAINS edges, no signature/visibility attrs
-
-**Step 3: Write minimal implementation**
-
-Replace `ScalaParser.scala` with the enhanced version. Key changes:
-- Trait → `NodeKind.Trait`
-- Object → `NodeKind.Object`
-- Class/CaseClass → `NodeKind.Class` (unchanged)
-- Def inside container → `NodeKind.Method` + CONTAINS edge
-- Def top-level → `NodeKind.Function` + DEFINES edge
-- Add `signature` attr (trimmed first line up to `=` or `{`)
-- Add `visibility` attr (`private`/`protected`/`public`)
-
-```scala
-package ix.memory.ingestion.parsers
-
-import ix.memory.ingestion.{Parser, ParseResult, ParsedEntity, ParsedRelationship}
-import ix.memory.model.NodeKind
-import io.circe.Json
-
-import scala.util.matching.Regex
-
-class ScalaParser extends Parser {
-
- private val TraitPattern: Regex = """^\s*(?:sealed\s+|abstract\s+|private\s+|protected\s+)*trait\s+(\w+)""".r
- private val ClassPattern: Regex = """^\s*(?:sealed\s+|abstract\s+|private\s+|protected\s+)*class\s+(\w+)""".r
- private val CaseClassPattern: Regex = """^\s*(?:sealed\s+|abstract\s+|private\s+|protected\s+)*case\s+class\s+(\w+)""".r
- private val ObjectPattern: Regex = """^\s*(?:sealed\s+|abstract\s+|private\s+|protected\s+)*(?:case\s+)?object\s+(\w+)""".r
- private val DefPattern: Regex = """^\s*(?:override\s+)?(?:private(?:\[\w+\])?\s+|protected(?:\[\w+\])?\s+)?(?:final\s+)?def\s+(\w+)""".r
- private val ImportPattern: Regex = """^\s*import\s+(.+)$""".r
-
- private val VisibilityPattern: Regex = """(?:override\s+)?(?:(private|protected)(?:\[\w+\])?\s+)""".r
-
- def parse(fileName: String, source: String): ParseResult = {
- val lines = source.split("\n", -1)
-
- val fileEntity = ParsedEntity(
- name = fileName,
- kind = NodeKind.File,
- attrs = Map("language" -> Json.fromString("scala")),
- lineStart = 1,
- lineEnd = lines.length
- )
-
- var entities = Vector(fileEntity)
- var relationships = Vector.empty[ParsedRelationship]
-
- var typeRanges = Vector.empty[(String, Int, Int)]
-
- for ((line, idx) <- lines.zipWithIndex) {
- val lineNum = idx + 1
- val trimmed = line.trim
-
- if (trimmed.startsWith("//") || trimmed.startsWith("*") || trimmed.startsWith("/*")) {
- // no-op
- } else {
-
- val handledAsType = CaseClassPattern.findFirstMatchIn(line) match {
- case Some(m) =>
- val name = m.group(1)
- val endLine = findBraceBlockEnd(lines, idx).getOrElse(lineNum)
- entities = entities :+ ParsedEntity(
- name = name,
- kind = NodeKind.Class,
- attrs = Map("scala_kind" -> Json.fromString("case_class"), "language" -> Json.fromString("scala")),
- lineStart = lineNum,
- lineEnd = endLine
- )
- relationships = relationships :+ ParsedRelationship(fileName, name, "DEFINES")
- typeRanges = typeRanges :+ (name, lineNum, endLine)
- true
-
- case None =>
- TraitPattern.findFirstMatchIn(line) match {
- case Some(m) =>
- val name = m.group(1)
- val endLine = findBraceBlockEnd(lines, idx).getOrElse(lineNum)
- entities = entities :+ ParsedEntity(
- name = name,
- kind = NodeKind.Trait,
- attrs = Map("scala_kind" -> Json.fromString("trait"), "language" -> Json.fromString("scala")),
- lineStart = lineNum,
- lineEnd = endLine
- )
- relationships = relationships :+ ParsedRelationship(fileName, name, "DEFINES")
- typeRanges = typeRanges :+ (name, lineNum, endLine)
- true
-
- case None =>
- ObjectPattern.findFirstMatchIn(line) match {
- case Some(m) =>
- val name = m.group(1)
- val endLine = findBraceBlockEnd(lines, idx).getOrElse(lineNum)
- entities = entities :+ ParsedEntity(
- name = name,
- kind = NodeKind.Object,
- attrs = Map("scala_kind" -> Json.fromString("object"), "language" -> Json.fromString("scala")),
- lineStart = lineNum,
- lineEnd = endLine
- )
- relationships = relationships :+ ParsedRelationship(fileName, name, "DEFINES")
- typeRanges = typeRanges :+ (name, lineNum, endLine)
- true
-
- case None =>
- ClassPattern.findFirstMatchIn(line) match {
- case Some(m) =>
- val name = m.group(1)
- val endLine = findBraceBlockEnd(lines, idx).getOrElse(lineNum)
- entities = entities :+ ParsedEntity(
- name = name,
- kind = NodeKind.Class,
- attrs = Map("scala_kind" -> Json.fromString("class"), "language" -> Json.fromString("scala")),
- lineStart = lineNum,
- lineEnd = endLine
- )
- relationships = relationships :+ ParsedRelationship(fileName, name, "DEFINES")
- typeRanges = typeRanges :+ (name, lineNum, endLine)
- true
- case None => false
- }
- }
- }
- }
-
- if (!handledAsType) {
- DefPattern.findFirstMatchIn(line).foreach { m =>
- val funcName = m.group(1)
- val endLine = findBraceBlockEnd(lines, idx).getOrElse(lineNum)
-
- val signature = extractSignature(trimmed)
- val visibility = extractVisibility(trimmed)
-
- val enclosing = typeRanges.find { case (_, start, end) =>
- lineNum > start && lineNum <= end
- }
-
- val (kind, rel) = enclosing match {
- case Some((typeName, _, _)) =>
- (NodeKind.Method, ParsedRelationship(typeName, funcName, "CONTAINS"))
- case None =>
- (NodeKind.Function, ParsedRelationship(fileName, funcName, "DEFINES"))
- }
-
- entities = entities :+ ParsedEntity(
- name = funcName,
- kind = kind,
- attrs = Map(
- "language" -> Json.fromString("scala"),
- "summary" -> Json.fromString(signature),
- "signature" -> Json.fromString(signature),
- "visibility" -> Json.fromString(visibility)
- ),
- lineStart = lineNum,
- lineEnd = endLine
- )
-
- relationships = relationships :+ rel
- }
- }
-
- ImportPattern.findFirstMatchIn(line).foreach { m =>
- val importPath = m.group(1).trim
- val moduleName = if (importPath.contains("{")) {
- importPath.substring(0, importPath.indexOf('{')).stripSuffix(".").trim
- } else {
- importPath
- }
-
- if (!entities.exists(e => e.name == moduleName && e.kind == NodeKind.Module)) {
- entities = entities :+ ParsedEntity(
- name = moduleName,
- kind = NodeKind.Module,
- attrs = Map.empty,
- lineStart = lineNum,
- lineEnd = lineNum
- )
- }
- relationships = relationships :+ ParsedRelationship(fileName, moduleName, "IMPORTS")
- }
-
- }
- }
-
- ParseResult(entities, relationships)
- }
-
- private def extractSignature(trimmedLine: String): String = {
- val sig = trimmedLine
- .replaceAll("""\s*\{.*""", "")
- .replaceAll("""\s*=\s*\{.*""", "")
- .replaceAll("""\s*=\s*$""", "")
- .take(120)
- sig
- }
-
- private def extractVisibility(trimmedLine: String): String = {
- val cleaned = trimmedLine.replaceFirst("^override\\s+", "")
- if (cleaned.startsWith("private")) "private"
- else if (cleaned.startsWith("protected")) "protected"
- else "public"
- }
-
- private def findBraceBlockEnd(lines: Array[String], startIdx: Int): Option[Int] = {
- var braceCount = 0
- var foundOpen = false
- var i = startIdx
-
- while (i < lines.length) {
- val line = lines(i)
- for (ch <- line) {
- ch match {
- case '{' =>
- braceCount += 1
- foundOpen = true
- case '}' =>
- braceCount -= 1
- if (foundOpen && braceCount == 0) {
- return Some(i + 1)
- }
- case _ =>
- }
- }
- i += 1
- }
-
- if (foundOpen) Some(lines.length) else None
- }
-}
-```
-
-**Step 4: Run tests to verify they pass**
-
-Run: `cd memory-layer && sbt "testOnly ix.memory.ingestion.parsers.ScalaParserSpec"`
-Expected: All tests PASS
-
-**Step 5: Commit**
-
-```bash
-git add memory-layer/src/main/scala/ix/memory/ingestion/parsers/ScalaParser.scala memory-layer/src/test/scala/ix/memory/ingestion/parsers/ScalaParserSpec.scala
-git commit -m "feat: ScalaParser emits Trait/Object/Method kinds, signature, visibility, CONTAINS edges"
-```
-
----
-
-### Task 3: Enhance TypeScriptParser — use Interface/Method kinds, add CONTAINS edges, attrs
-
-**Files:**
-- Modify: `memory-layer/src/main/scala/ix/memory/ingestion/parsers/TypeScriptParser.scala:1-329`
-- Modify: `memory-layer/src/test/scala/ix/memory/ingestion/parsers/TypeScriptParserSpec.scala:1-229`
-
-**Step 1: Write the failing tests**
-
-Add/update tests in `TypeScriptParserSpec.scala`. Key new assertions:
-- Interfaces use `NodeKind.Interface` (not `NodeKind.Class`)
-- Class methods use `NodeKind.Method` (not `NodeKind.Function`)
-- CONTAINS edges from file→class and class→method exist
-- Methods have `signature` and `visibility` attrs
-
-Add these test cases to the existing spec (append before the closing `}`):
-
-```scala
- it should "use Interface kind for interfaces" in {
- val source = """
- |export interface UserProps {
- | name: string;
- | age: number;
- |}
- """.stripMargin
- val result = parser.parse("types.ts", source)
- val iface = result.entities.find(e => e.name == "UserProps")
- iface shouldBe defined
- iface.get.kind shouldBe NodeKind.Interface
- }
-
- it should "use Method kind for class methods" in {
- val source = """
- |class Api {
- | async fetch(url: string) {
- | return this.http.get(url);
- | }
- |
- | private parse(data: string) {
- | return data.split(',');
- | }
- |}
- """.stripMargin
- val result = parser.parse("api.ts", source)
- val methods = result.entities.filter(_.kind == NodeKind.Method)
- methods.map(_.name) should contain allOf ("fetch", "parse")
- }
-
- it should "emit CONTAINS edges from file to class" in {
- val source = """
- |export class UserService {
- | getUser(id: string): User {
- | return this.db.find(id);
- | }
- |}
- """.stripMargin
- val result = parser.parse("service.ts", source)
- result.relationships.exists(r =>
- r.srcName == "service.ts" && r.dstName == "UserService" && r.predicate == "CONTAINS"
- ) shouldBe true
- }
-
- it should "emit CONTAINS edges from class to method" in {
- val source = """
- |class Api {
- | fetch(url: string) {
- | return url;
- | }
- |}
- """.stripMargin
- val result = parser.parse("api.ts", source)
- result.relationships.exists(r =>
- r.srcName == "Api" && r.dstName == "fetch" && r.predicate == "CONTAINS"
- ) shouldBe true
- }
-
- it should "store visibility attr on methods" in {
- val source = """
- |class Api {
- | private parse(data: string) {
- | return data;
- | }
- | public fetch(url: string) {
- | return url;
- | }
- |}
- """.stripMargin
- val result = parser.parse("api.ts", source)
- val parse = result.entities.find(_.name == "parse").get
- parse.attrs.get("visibility").flatMap(_.asString) shouldBe Some("private")
- val fetch = result.entities.find(_.name == "fetch").get
- fetch.attrs.get("visibility").flatMap(_.asString) shouldBe Some("public")
- }
-
- it should "store signature attr on methods" in {
- val source = """
- |class Api {
- | async fetch(url: string): Promise<Response> {
- | return url;
- | }
- |}
- """.stripMargin
- val result = parser.parse("api.ts", source)
- val fetch = result.entities.find(_.name == "fetch").get
- fetch.attrs.get("signature").flatMap(_.asString) shouldBe defined
- fetch.attrs("signature").asString.get should include("fetch")
- }
-```
-
-Also update the existing interface test (lines 134-146) to expect `NodeKind.Interface`:
-
-```scala
- it should "extract interface definitions with Interface kind" in {
- val source = """
- |export interface UserProps {
- | name: string;
- | age: number;
- |}
- """.stripMargin
- val result = parser.parse("types.ts", source)
- val iface = result.entities.find(e => e.name == "UserProps")
- iface shouldBe defined
- iface.get.kind shouldBe NodeKind.Interface
- iface.get.attrs.get("ts_kind").map(_.noSpaces) shouldBe Some("\"interface\"")
- }
-```
-
-And update the method detection test (lines 169-184) to expect `Method` kind:
-
-```scala
- it should "detect methods inside classes" in {
- val source = """
- |class Api {
- | async fetch(url: string) {
- | return this.http.get(url);
- | }
- |
- | private parse(data: string) {
- | return data.split(',');
- | }
- |}
- """.stripMargin
- val result = parser.parse("api.ts", source)
- result.entities.exists(e => e.name == "fetch" && e.kind == NodeKind.Method) shouldBe true
- result.entities.exists(e => e.name == "parse" && e.kind == NodeKind.Method) shouldBe true
- result.relationships.exists(r => r.srcName == "Api" && r.dstName == "fetch" && r.predicate == "CONTAINS") shouldBe true
- result.relationships.exists(r => r.srcName == "Api" && r.dstName == "parse" && r.predicate == "CONTAINS") shouldBe true
- }
-```
-
-Update the "store method/function signature" test (lines 62-69) — methods are now `NodeKind.Method`, top-level functions stay `NodeKind.Function`:
-
-```scala
- it should "store method/function signature as summary attr" in {
- val result = parser.parse("api.ts", sampleCode)
- val funcs = result.entities.filter(e => e.kind == NodeKind.Function || e.kind == NodeKind.Method)
- funcs should not be empty
- funcs.foreach { f =>
- f.attrs.get("summary") shouldBe defined
- f.attrs("summary").asString.get should not be empty
- }
- }
-```
-
-Update fixture-based "extract methods" test to check for `Method` kind:
-
-```scala
- it should "extract methods from classes" in {
- val result = parser.parse("api.ts", sampleCode)
- val methods = result.entities.filter(_.kind == NodeKind.Method)
- val names = methods.map(_.name)
- names should contain("getUser")
- names should contain("updateUser")
- names should contain("parseResponse")
- }
-```
-
-**Step 2: Run tests to verify they fail**
-
-Run: `cd memory-layer && sbt "testOnly ix.memory.ingestion.parsers.TypeScriptParserSpec"`
-Expected: FAIL — interfaces still Class, methods still Function, no CONTAINS edges
-
-**Step 3: Write minimal implementation**
-
-Modify `TypeScriptParser.scala` with these changes:
-
-1. **Interface**: Change `NodeKind.Class` → `NodeKind.Interface` at line 158
-2. **Class methods in `extractMethods`**: Change `NodeKind.Function` → `NodeKind.Method` at line 243, change `"DEFINES"` → `"CONTAINS"` at line 250
-3. **File→Class CONTAINS**: Add `ParsedRelationship(fileName, className, "CONTAINS")` after the DEFINES edge at line 60
-4. **Visibility attr on methods**: Extract from method line
-5. **Signature attr on methods**: Already stored as `summary`, add as `signature` too
-6. **Duplicate guard for interfaces**: Change `e.kind == NodeKind.Class` → `e.kind == NodeKind.Interface` in the guard at line 154
-
-The key code changes in `extractMethods`:
-
-```scala
- private def extractMethods(
- lines: Array[String],
- classStartIdx: Int,
- classEndLine: Int,
- className: String
- ): (Vector[ParsedEntity], Vector[ParsedRelationship]) = {
- var entities = Vector.empty[ParsedEntity]
- var relationships = Vector.empty[ParsedRelationship]
-
- var i = classStartIdx + 1
- while (i < lines.length && (i + 1) <= classEndLine) {
- val line = lines(i)
- val lineNum = i + 1
-
- if (!line.trim.startsWith("//") && !line.trim.startsWith("*")) {
- MethodPattern.findFirstMatchIn(line).foreach { m =>
- val methodName = m.group(1)
- if (!TypeScriptKeywords.contains(methodName)) {
- val methodEnd = findBraceBlockEnd(lines, i)
- val summary = line.trim.take(120)
- val visibility = extractVisibility(line.trim)
- entities = entities :+ ParsedEntity(
- name = methodName,
- kind = NodeKind.Method,
- attrs = Map(
- "language" -> Json.fromString("typescript"),
- "summary" -> Json.fromString(summary),
- "signature" -> Json.fromString(summary),
- "visibility" -> Json.fromString(visibility)
- ),
- lineStart = lineNum,
- lineEnd = methodEnd
- )
- relationships = relationships :+ ParsedRelationship(className, methodName, "CONTAINS")
-
- val calls = extractCalls(lines, i, methodEnd, methodName)
- relationships = relationships ++ calls
- }
- }
- }
- i += 1
- }
-
- (entities, relationships)
- }
-
- private def extractVisibility(trimmedLine: String): String = {
- if (trimmedLine.startsWith("private ") || trimmedLine.startsWith("private\t")) "private"
- else if (trimmedLine.startsWith("protected ") || trimmedLine.startsWith("protected\t")) "protected"
- else "public"
- }
-```
-
-For the class entity — add CONTAINS after DEFINES:
-
-```scala
- ClassPattern.findFirstMatchIn(line).foreach { m =>
- val className = m.group(1)
- val classEnd = findBraceBlockEnd(lines, idx)
- entities = entities :+ ParsedEntity(
- name = className,
- kind = NodeKind.Class,
- attrs = Map("language" -> Json.fromString("typescript")),
- lineStart = lineNum,
- lineEnd = classEnd
- )
- relationships = relationships :+ ParsedRelationship(fileName, className, "DEFINES")
- relationships = relationships :+ ParsedRelationship(fileName, className, "CONTAINS")
- classRanges = classRanges :+ (className, lineNum, classEnd)
-
- val methods = extractMethods(lines, idx, classEnd, className)
- entities = entities ++ methods._1
- relationships = relationships ++ methods._2
- }
-```
-
-For interfaces — change kind:
-
-```scala
- InterfacePattern.findFirstMatchIn(line).foreach { m =>
- val ifaceName = m.group(1)
- if (!entities.exists(e => e.name == ifaceName && e.kind == NodeKind.Interface)) {
- val ifaceEnd = findBraceBlockEnd(lines, idx)
- entities = entities :+ ParsedEntity(
- name = ifaceName,
- kind = NodeKind.Interface,
- attrs = Map(
- "language" -> Json.fromString("typescript"),
- "ts_kind" -> Json.fromString("interface")
- ),
- lineStart = lineNum,
- lineEnd = ifaceEnd
- )
- relationships = relationships :+ ParsedRelationship(fileName, ifaceName, "DEFINES")
- }
- }
-```
-
-Also add `signature` attr to top-level functions (alongside existing `summary`):
-
-```scala
- FuncPattern.findFirstMatchIn(line).foreach { m =>
- val funcName = m.group(1)
- val funcEnd = findBraceBlockEnd(lines, idx)
- val summary = line.trim.take(120)
- entities = entities :+ ParsedEntity(
- name = funcName,
- kind = NodeKind.Function,
- attrs = Map(
- "language" -> Json.fromString("typescript"),
- "summary" -> Json.fromString(summary),
- "signature" -> Json.fromString(summary),
- "visibility" -> Json.fromString("public")
- ),
- lineStart = lineNum,
- lineEnd = funcEnd
- )
- // ... rest unchanged
-```
-
-Same for arrow functions / const functions.
-
-**Step 4: Run tests to verify they pass**
-
-Run: `cd memory-layer && sbt "testOnly ix.memory.ingestion.parsers.TypeScriptParserSpec"`
-Expected: All tests PASS
-
-**Step 5: Run all tests to check for regressions**
-
-Run: `cd memory-layer && sbt test`
-Expected: All tests PASS. Check especially that RoutesSpec, EndToEndSpec, and other integration tests still pass.
-
-**Step 6: Commit**
-
-```bash
-git add memory-layer/src/main/scala/ix/memory/ingestion/parsers/TypeScriptParser.scala memory-layer/src/test/scala/ix/memory/ingestion/parsers/TypeScriptParserSpec.scala
-git commit -m "feat: TypeScriptParser emits Interface/Method kinds, CONTAINS edges, signature/visibility"
-```
-
----
-
-### Task 4: Add kindBoost to RelevanceScorer
-
-**Files:**
-- Modify: `memory-layer/src/main/scala/ix/memory/context/RelevanceScorer.scala:1-40`
-- Modify: `memory-layer/src/test/scala/ix/memory/context/RelevanceScorerSpec.scala:1-80`
-
-**Step 1: Write the failing tests**
-
-Add tests to `RelevanceScorerSpec.scala`. The scorer needs a `nodeKindMap` parameter. Add these test cases:
-
-```scala
- it should "boost symbol node claims with kindBoost 1.3x" in {
- val seedId = NodeId(UUID.randomUUID())
- val kindMap = Map(seedId -> NodeKind.Function)
- val claims = Vector(makeClaim(seedId))
- val result = RelevanceScorer.scoreWithTerms(claims, Set(seedId), Vector.empty, Vector.empty, kindMap)
- // hopRelevance=1.0 * kindBoost=1.3 → clamped to 1.0
- result.head.relevance shouldBe 1.0
- }
-
- it should "penalize File node claims with kindBoost 0.6x" in {
- val seedId = NodeId(UUID.randomUUID())
- val kindMap = Map(seedId -> NodeKind.File)
- val claims = Vector(makeClaim(seedId))
- val result = RelevanceScorer.scoreWithTerms(claims, Set(seedId), Vector.empty, Vector.empty, kindMap)
- // hopRelevance=1.0 * kindBoost=0.6 = 0.6
- result.head.relevance shouldBe 0.6
- result.head.finalScore shouldBe (0.6 * defaultBreakdown.score +- 0.001)
- }
-
- it should "rank Method claims above File claims for same seed" in {
- val methodId = NodeId(UUID.randomUUID())
- val fileId = NodeId(UUID.randomUUID())
- val kindMap = Map(methodId -> NodeKind.Method, fileId -> NodeKind.File)
- val claims = Vector(makeClaim(fileId), makeClaim(methodId))
- val result = RelevanceScorer.scoreWithTerms(
- claims, Set(methodId, fileId), Vector.empty, Vector.empty, kindMap
- ).sortBy(-_.finalScore)
- result.head.claim.entityId shouldBe methodId
- }
-
- it should "apply neutral 1.0x kindBoost for Config nodes" in {
- val seedId = NodeId(UUID.randomUUID())
- val kindMap = Map(seedId -> NodeKind.Config)
- val claims = Vector(makeClaim(seedId))
- val result = RelevanceScorer.scoreWithTerms(claims, Set(seedId), Vector.empty, Vector.empty, kindMap)
- result.head.relevance shouldBe 1.0
- }
-
- it should "use default kindBoost 1.0 when nodeKindMap is empty" in {
- val seedId = NodeId(UUID.randomUUID())
- val claims = Vector(makeClaim(seedId))
- val result = RelevanceScorer.scoreWithTerms(claims, Set(seedId), Vector.empty, Vector.empty, Map.empty)
- result.head.relevance shouldBe 1.0
- }
-```
-
-**Step 2: Run tests to verify they fail**
-
-Run: `cd memory-layer && sbt "testOnly ix.memory.context.RelevanceScorerSpec"`
-Expected: Compilation failure — `scoreWithTerms` doesn't accept `nodeKindMap` parameter
-
-**Step 3: Write minimal implementation**
-
-Replace `RelevanceScorer.scala`:
-
-```scala
-package ix.memory.context
-
-import ix.memory.model._
-
-object RelevanceScorer {
- def score(
- claims: Vector[ScoredClaim],
- seedNodeIds: Set[NodeId],
- expandedEdges: Vector[GraphEdge]
- ): Vector[ScoredClaim] =
- scoreWithTerms(claims, seedNodeIds, expandedEdges, Vector.empty, Map.empty)
-
- def scoreWithTerms(
- claims: Vector[ScoredClaim],
- seedNodeIds: Set[NodeId],
- expandedEdges: Vector[GraphEdge],
- queryTerms: Vector[String],
- nodeKindMap: Map[NodeId, NodeKind] = Map.empty
- ): Vector[ScoredClaim] = {
- val oneHopIds = expandedEdges
- .flatMap(e => Vector(e.src, e.dst))
- .toSet -- seedNodeIds
- val termsLower = queryTerms.map(_.toLowerCase)
-
- claims.map { sc =>
- val hopRelevance =
- if (seedNodeIds.contains(sc.claim.entityId)) 1.0
- else if (oneHopIds.contains(sc.claim.entityId)) 0.7
- else 0.4
-
- val fieldLower = sc.claim.statement.toLowerCase
- val exactBoost = if (termsLower.exists(t => fieldLower.contains(t))) 1.2 else 1.0
-
- val pathLower = sc.claim.provenance.sourceUri.toLowerCase
- val pathBoost = if (termsLower.exists(t => pathLower.contains(t))) 1.1 else 1.0
-
- val kindBoost = nodeKindMap.get(sc.claim.entityId) match {
- case Some(NodeKind.Method) | Some(NodeKind.Function) => 1.3
- case Some(NodeKind.Class) | Some(NodeKind.Trait)
- | Some(NodeKind.Object) | Some(NodeKind.Interface) => 1.3
- case Some(NodeKind.Module) => 1.2
- case Some(NodeKind.File) => 0.6
- case _ => 1.0
- }
-
- val relevance = math.min(1.0, hopRelevance * exactBoost * pathBoost * kindBoost)
- sc.copy(relevance = relevance, finalScore = relevance * sc.confidence.score)
- }
- }
-}
-```
-
-**Step 4: Run tests to verify they pass**
-
-Run: `cd memory-layer && sbt "testOnly ix.memory.context.RelevanceScorerSpec"`
-Expected: All tests PASS
-
-**Step 5: Commit**
-
-```bash
-git add memory-layer/src/main/scala/ix/memory/context/RelevanceScorer.scala memory-layer/src/test/scala/ix/memory/context/RelevanceScorerSpec.scala
-git commit -m "feat: add kindBoost to RelevanceScorer — 1.3x symbols, 0.6x files"
-```
-
----
-
-### Task 5: Wire kindBoost into ContextService
-
-**Files:**
-- Modify: `memory-layer/src/main/scala/ix/memory/context/ContextService.scala:70`
-
-**Step 1: Build the nodeKindMap and pass it to RelevanceScorer**
-
-This is a one-line change. In `ContextService.scala`, at line 70, the current call is:
-
-```scala
- relevant = RelevanceScorer.scoreWithTerms(scored, seeds.map(_.id).toSet, expanded.edges, terms)
-```
-
-Change to:
-
-```scala
- nodeKindMap = allNodesAll.map(n => n.id -> n.kind).toMap
- relevant = RelevanceScorer.scoreWithTerms(scored, seeds.map(_.id).toSet, expanded.edges, terms, nodeKindMap)
-```
-
-But wait — `allNodesAll` is defined later (line 93). We need `nodeKindMap` from the combined seeds + expanded nodes. Move the node assembly up or compute the map inline. The simplest approach: compute it inline from `seeds` and `expanded.nodes`:
-
-```scala
- nodeKindMap: Map[NodeId, NodeKind] = (seeds ++ expanded.nodes).map(n => n.id -> n.kind).toMap
- relevant = RelevanceScorer.scoreWithTerms(scored, seeds.map(_.id).toSet, expanded.edges, terms, nodeKindMap)
-```
-
-**Step 2: Run all tests**
-
-Run: `cd memory-layer && sbt test`
-Expected: All tests PASS (ContextServiceSpec may test query flow — verify it still passes)
-
-**Step 3: Commit**
-
-```bash
-git add memory-layer/src/main/scala/ix/memory/context/ContextService.scala
-git commit -m "feat: wire nodeKindMap into RelevanceScorer for symbol preference"
-```
-
----
-
-### Task 6: Improve search — sort symbols first, add attr search
-
-**Files:**
-- Modify: `memory-layer/src/main/scala/ix/memory/db/ArangoGraphQueryApi.scala:48-96`
-
-**Step 1: Update the searchNodes AQL query**
-
-Replace the `searchNodes` method body (lines 48-96) with an enhanced version that:
-- Adds `attr_matches` subquery searching `TO_STRING(n.attrs)`
-- Sorts results: symbol kinds first (function, method, class, trait, object, interface), then others
-- Sorts by name within each group
-
-```scala
- override def searchNodes(text: String, limit: Int = 20): IO[Vector[GraphNode]] =
- client.query(
- """LET name_matches = (
- | FOR n IN nodes
- | FILTER CONTAINS(LOWER(n.name), LOWER(@text))
- | AND n.deleted_rev == null
- | RETURN DISTINCT n.logical_id
- |)
- |
- |LET provenance_matches = (
- | FOR n IN nodes
- | FILTER CONTAINS(LOWER(n.provenance.source_uri), LOWER(@text))
- | AND n.deleted_rev == null
- | RETURN DISTINCT n.logical_id
- |)
- |
- |LET claim_matches = (
- | FOR c IN claims
- | FILTER c.deleted_rev == null
- | AND (
- | CONTAINS(LOWER(c.field), LOWER(@text))
- | OR CONTAINS(LOWER(TO_STRING(c.value)), LOWER(@text))
- | )
- | RETURN DISTINCT c.entity_id
- |)
- |
- |LET decision_matches = (
- | FOR n IN nodes
- | FILTER n.kind == "decision"
- | AND n.deleted_rev == null
- | AND (
- | CONTAINS(LOWER(TO_STRING(n.attrs.title)), LOWER(@text))
- | OR CONTAINS(LOWER(TO_STRING(n.attrs.rationale)), LOWER(@text))
- | )
- | RETURN DISTINCT n.logical_id
- |)
- |
- |LET attr_matches = (
- | FOR n IN nodes
- | FILTER n.deleted_rev == null
- | AND CONTAINS(LOWER(TO_STRING(n.attrs)), LOWER(@text))
- | RETURN DISTINCT n.logical_id
- |)
- |
- |LET all_ids = UNION_DISTINCT(name_matches, provenance_matches, claim_matches, decision_matches, attr_matches)
- |
- |FOR id IN all_ids
- | FOR n IN nodes
- | FILTER n.logical_id == id AND n.deleted_rev == null
- | LET symbol_priority = n.kind IN ["function", "method", "class", "trait", "object", "interface"] ? 0 : 1
- | SORT symbol_priority ASC, n.name ASC
- | LIMIT @limit
- | RETURN n""".stripMargin,
- Map(
- "text" -> text.asInstanceOf[AnyRef],
- "limit" -> Int.box(limit).asInstanceOf[AnyRef]
- )
- ).map(_.flatMap(parseNode).toVector)
-```
-
-**Step 2: Run all tests**
-
-Run: `cd memory-layer && sbt test`
-Expected: All tests PASS. The search tests in RoutesSpec/EndToEndSpec should not be affected by the added subquery and sort.
-
-**Step 3: Commit**
-
-```bash
-git add memory-layer/src/main/scala/ix/memory/db/ArangoGraphQueryApi.scala
-git commit -m "feat: search sorts symbols first, adds attr search for signatures"
-```
-
----
-
-### Task 7: Run full test suite and verify no regressions
-
-**Step 1: Run all tests**
-
-Run: `cd memory-layer && sbt test`
-Expected: All tests PASS
-
-**Step 2: Verify compilation**
-
-Run: `cd memory-layer && sbt compile`
-Expected: No warnings about exhaustive match (the new NodeKind cases must be handled in the encoder pattern match)
-
-**Step 3: If any test failures, fix them**
-
-Common issues to watch for:
-- `ModelSpec` — the NodeKind list must include all 16 variants
-- `TypeScriptParserSpec` — existing tests that check `NodeKind.Class` for interfaces or `NodeKind.Function` for methods must be updated
-- `ContextServiceSpec` — if it constructs `RelevanceScorer.scoreWithTerms` calls directly, the new `nodeKindMap` parameter has a default value so it shouldn't break
-- `RoutesSpec` / `EndToEndSpec` — integration tests that assert on node kinds in API responses may need updating
-
-**Step 4: Commit any fixes**
-
-```bash
-git add -A
-git commit -m "fix: update tests for new NodeKind variants"
-```
-
----
-
-## Dependency Graph
-
-```
-Task 1 (NodeKinds)
- ├── Task 2 (ScalaParser) ──────┐
- ├── Task 3 (TypeScriptParser) ─┼── Task 4 (RelevanceScorer) ── Task 5 (ContextService) ── Task 7 (Full test)
- └── Task 6 (Search) ──────────┘
-```
-
-Tasks 2, 3, and 6 can run in parallel after Task 1.
-Task 4 can run after Task 1 (doesn't depend on parser changes).
-Task 5 depends on Task 4.
-Task 7 runs last.
diff --git a/docs/plans/2026-03-08-github-ingestion-design.md b/docs/plans/2026-03-08-github-ingestion-design.md
deleted file mode 100644
index ee141c68..00000000
--- a/docs/plans/2026-03-08-github-ingestion-design.md
+++ /dev/null
@@ -1,77 +0,0 @@
-# GitHub Ingestion Design
-
-## Goal
-
-Ingest GitHub issues, PRs, and commits into the Ix knowledge graph via `ix ingest --github owner/repo`, driven entirely from the CLI with one small backend addition (a direct patch submission endpoint).
-
-## Architecture
-
-The CLI fetches data from GitHub's REST API, transforms it into GraphPatch operations, and submits them to a new `POST /v1/patch` endpoint. The backend commits patches using existing infrastructure — no GitHub awareness needed.
-
-Auth resolves in order: `gh auth token` → `GITHUB_TOKEN` env → `--token <pat>`.
-
-## Command Surface
-
-```
-ix ingest --github owner/repo [--token <pat>] [--since <date>] [--limit <n>] [--format json]
-```
-
-- `--since` defaults to 30 days ago
-- `--limit` caps items per category (default 50 issues, 50 PRs, 100 commits)
-- `--format json` returns structured IngestResult
-
-## Entity Mapping
-
-| GitHub Concept | NodeKind | SourceType | URI Pattern |
-|---|---|---|---|
-| Issue | `intent` | `Comment` | `github://owner/repo/issues/123` |
-| Issue comment | `doc` | `Comment` | `github://owner/repo/issues/123/comments/456` |
-| Pull Request | `decision` | `Comment` | `github://owner/repo/pull/45` |
-| PR review comment | `doc` | `Comment` | `github://owner/repo/pull/45/comments/789` |
-| Commit | `doc` | `Commit` | `github://owner/repo/commit/abc123` |
-
-## Edge Mapping
-
-| Relationship | Edge Predicate |
-|---|---|
-| Issue → mentioned file | REFERENCES |
-| PR → changed file | REFERENCES |
-| PR → linked issue | REFERENCES |
-| Commit → changed file | REFERENCES |
-| Issue ← comment | CONTAINS |
-| PR ← review comment | CONTAINS |
-
-## Node Attrs
-
-Issues: `{ number, url, author, labels, state, created_at, title }`
-PRs: `{ number, url, author, state, merged, base_branch, head_branch, created_at, title, changed_files_count }`
-Commits: `{ sha, url, author, message, created_at, changed_files_count }`
-Comments: `{ url, author, created_at, body (truncated to 2000 chars) }`
-
-## Identity
-
-Deterministic node IDs from URI string (same scheme as file-based ingestion). Re-ingesting the same repo is idempotent.
-
-## Backend Addition
-
-One small Scala change: add `POST /v1/patch` endpoint that accepts a GraphPatch JSON body and calls `writeApi.commitPatch()`. The infrastructure already exists — DecideRoutes and TruthRoutes use the same pattern internally.
-
-Corresponding `IxClient.commitPatch()` method in the CLI client.
-
-## File References
-
-PR changed files and commit changed files are matched against already-ingested file nodes by path suffix. Issue/PR body text is scanned for file path patterns to create REFERENCES edges.
-
-## Bounds
-
-- `--limit` per category (default 50/50/100)
-- `--since` date filter (default 30 days)
-- Comment body truncated to 2000 chars
-- Pagination handled automatically up to limit
-
-## Not Included
-
-- Webhooks / real-time sync
-- GitHub Actions / workflows
-- Discussions, releases, tags
-- Full diff content (just changed file list)
diff --git a/docs/plans/2026-03-08-github-ingestion-plan.md b/docs/plans/2026-03-08-github-ingestion-plan.md
deleted file mode 100644
index 86c136ee..00000000
--- a/docs/plans/2026-03-08-github-ingestion-plan.md
+++ /dev/null
@@ -1,1019 +0,0 @@
-# GitHub Ingestion Implementation Plan
-
-> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
-
-**Goal:** Ingest GitHub issues, PRs, and commits into the Ix knowledge graph via `ix ingest --github owner/repo`.
-
-**Architecture:** The CLI fetches data from GitHub's REST API, builds GraphPatch operations (UpsertNode, UpsertEdge, AssertClaim), and submits them to a new `POST /v1/patch` backend endpoint. The backend commits patches using existing infrastructure. Auth resolves via `gh auth token` → `GITHUB_TOKEN` env → `--token` flag.
-
-**Tech Stack:** TypeScript CLI (commander, node fetch), Scala backend (http4s, circe), GitHub REST API
-
----
-
-### Task 1: Add `POST /v1/patch` Backend Endpoint
-
-**Files:**
-- Create: `memory-layer/src/main/scala/ix/memory/api/PatchCommitRoutes.scala`
-- Modify: `memory-layer/src/main/scala/ix/memory/api/Routes.scala:28-50`
-
-**Step 1: Write the PatchCommitRoutes class**
-
-Create `memory-layer/src/main/scala/ix/memory/api/PatchCommitRoutes.scala`:
-
-```scala
-package ix.memory.api
-
-import cats.effect.IO
-import io.circe.syntax._
-import io.circe.Json
-import org.http4s.HttpRoutes
-import org.http4s.circe.CirceEntityCodec._
-import org.http4s.dsl.io._
-
-import ix.memory.db.GraphWriteApi
-import ix.memory.model.GraphPatch
-
-class PatchCommitRoutes(writeApi: GraphWriteApi) {
-
- val routes: HttpRoutes[IO] = HttpRoutes.of[IO] {
- case req @ POST -> Root / "v1" / "patch" =>
- (for {
- patch <- req.as[GraphPatch]
- result <- writeApi.commitPatch(patch)
- resp <- Ok(Json.obj(
- "status" -> result.status.toString.asJson,
- "rev" -> result.newRev.value.asJson
- ))
- } yield resp).handleErrorWith(ErrorHandler.handle(_))
- }
-}
-```
-
-**Step 2: Wire into Routes.scala**
-
-In `memory-layer/src/main/scala/ix/memory/api/Routes.scala`, add after line 42 (`val statsRoutes`):
-
-```scala
-val patchCommitRoutes = new PatchCommitRoutes(writeApi).routes
-```
-
-And add `<+> patchCommitRoutes` to the route chain on line 45.
-
-**Step 3: Build backend**
-
-Run: `cd memory-layer && sbt compile`
-Expected: Compiles successfully
-
-**Step 4: Commit**
-
-```bash
-git add memory-layer/src/main/scala/ix/memory/api/PatchCommitRoutes.scala \
- memory-layer/src/main/scala/ix/memory/api/Routes.scala
-git commit -m "feat: add POST /v1/patch endpoint for direct patch submission"
-```
-
----
-
-### Task 2: Add `commitPatch` to CLI Client
-
-**Files:**
-- Modify: `ix-cli/src/client/api.ts:1-173`
-- Modify: `ix-cli/src/client/types.ts:1-153`
-
-**Step 1: Add PatchOp and GraphPatch types to types.ts**
-
-Add at the end of `ix-cli/src/client/types.ts`:
-
-```typescript
-export interface PatchSource {
- uri: string;
- sourceHash?: string;
- extractor: string;
- sourceType: string; // "code" | "config" | "doc" | "commit" | "comment" | "human"
-}
-
-export interface PatchOp {
- type: string;
- [key: string]: unknown;
-}
-
-export interface GraphPatchPayload {
- patchId: string;
- actor: string;
- timestamp: string;
- source: PatchSource;
- baseRev: number;
- ops: PatchOp[];
- replaces: string[];
- intent?: string;
-}
-
-export interface PatchCommitResult {
- status: string;
- rev: number;
-}
-```
-
-**Step 2: Add commitPatch method to IxClient**
-
-Add to `ix-cli/src/client/api.ts` after the `provenance` method (around line 142):
-
-```typescript
-async commitPatch(patch: GraphPatchPayload): Promise<PatchCommitResult> {
- return this.post("/v1/patch", patch);
-}
-```
-
-Add `GraphPatchPayload, PatchCommitResult` to the imports from `./types.js` at line 1.
-
-**Step 3: Build CLI**
-
-Run: `cd ix-cli && npm run build`
-Expected: Compiles successfully
-
-**Step 4: Commit**
-
-```bash
-git add ix-cli/src/client/api.ts ix-cli/src/client/types.ts
-git commit -m "feat: add commitPatch client method and GraphPatch types"
-```
-
----
-
-### Task 3: Add GitHub Auth Helper
-
-**Files:**
-- Create: `ix-cli/src/cli/github/auth.ts`
-- Test: `ix-cli/src/cli/__tests__/github-auth.test.ts`
-
-**Step 1: Write the failing test**
-
-Create `ix-cli/src/cli/__tests__/github-auth.test.ts`:
-
-```typescript
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-
-// We'll test the resolution logic without actually calling gh
-describe("GitHub auth resolution", () => {
- const originalEnv = process.env;
-
- beforeEach(() => {
- process.env = { ...originalEnv };
- });
-
- afterEach(() => {
- process.env = originalEnv;
- });
-
- it("uses --token flag when provided", async () => {
- const { resolveGitHubToken } = await import("../github/auth.js");
- const token = await resolveGitHubToken("my-pat-token");
- expect(token).toBe("my-pat-token");
- });
-
- it("uses GITHUB_TOKEN env when no --token", async () => {
- process.env.GITHUB_TOKEN = "env-token-123";
- const { resolveGitHubToken } = await import("../github/auth.js");
- const token = await resolveGitHubToken(undefined);
- expect(token).toBe("env-token-123");
- });
-});
-```
-
-**Step 2: Run test to verify it fails**
-
-Run: `npx vitest run src/cli/__tests__/github-auth.test.ts`
-Expected: FAIL with "Cannot find module"
-
-**Step 3: Write minimal implementation**
-
-Create `ix-cli/src/cli/github/auth.ts`:
-
-```typescript
-import { execFile } from "node:child_process";
-import { promisify } from "node:util";
-
-const execFileAsync = promisify(execFile);
-
-/**
- * Resolve a GitHub token using this priority:
- * 1. Explicit --token flag
- * 2. GITHUB_TOKEN environment variable
- * 3. `gh auth token` CLI command
- */
-export async function resolveGitHubToken(explicitToken?: string): Promise<string> {
- if (explicitToken) return explicitToken;
-
- if (process.env.GITHUB_TOKEN) return process.env.GITHUB_TOKEN;
-
- try {
- const { stdout } = await execFileAsync("gh", ["auth", "token"]);
- const token = stdout.trim();
- if (token) return token;
- } catch {
- // gh not installed or not authenticated
- }
-
- throw new Error(
- "GitHub authentication required. Provide one of:\n" +
- " --token <pat> Personal access token\n" +
- " GITHUB_TOKEN=<pat> Environment variable\n" +
- " gh auth login GitHub CLI authentication"
- );
-}
-```
-
-**Step 4: Run test to verify it passes**
-
-Run: `npx vitest run src/cli/__tests__/github-auth.test.ts`
-Expected: PASS
-
-**Step 5: Commit**
-
-```bash
-git add ix-cli/src/cli/github/auth.ts ix-cli/src/cli/__tests__/github-auth.test.ts
-git commit -m "feat: add GitHub auth resolution (token flag → env → gh CLI)"
-```
-
----
-
-### Task 4: Add GitHub API Fetcher
-
-**Files:**
-- Create: `ix-cli/src/cli/github/fetch.ts`
-- Test: `ix-cli/src/cli/__tests__/github-fetch.test.ts`
-
-**Step 1: Write the failing test**
-
-Create `ix-cli/src/cli/__tests__/github-fetch.test.ts`:
-
-```typescript
-import { describe, it, expect } from "vitest";
-
-describe("parseGitHubRepo", () => {
- it("parses owner/repo format", async () => {
- const { parseGitHubRepo } = await import("../github/fetch.js");
- expect(parseGitHubRepo("ix-infrastructure/IX-Memory")).toEqual({
- owner: "ix-infrastructure",
- repo: "IX-Memory",
- });
- });
-
- it("throws on invalid format", async () => {
- const { parseGitHubRepo } = await import("../github/fetch.js");
- expect(() => parseGitHubRepo("invalid")).toThrow();
- });
-});
-```
-
-**Step 2: Run test to verify it fails**
-
-Run: `npx vitest run src/cli/__tests__/github-fetch.test.ts`
-Expected: FAIL
-
-**Step 3: Write implementation**
-
-Create `ix-cli/src/cli/github/fetch.ts`:
-
-```typescript
-export interface GitHubRepo {
- owner: string;
- repo: string;
-}
-
-export function parseGitHubRepo(input: string): GitHubRepo {
- const parts = input.split("/");
- if (parts.length !== 2 || !parts[0] || !parts[1]) {
- throw new Error(`Invalid repo format: "${input}". Expected "owner/repo".`);
- }
- return { owner: parts[0], repo: parts[1] };
-}
-
-export interface GitHubIssue {
- number: number;
- title: string;
- body: string | null;
- state: string;
- user: { login: string } | null;
- labels: { name: string }[];
- created_at: string;
- updated_at: string;
- html_url: string;
- comments: number;
-}
-
-export interface GitHubPR {
- number: number;
- title: string;
- body: string | null;
- state: string;
- merged_at: string | null;
- user: { login: string } | null;
- base: { ref: string };
- head: { ref: string };
- created_at: string;
- updated_at: string;
- html_url: string;
- changed_files?: number;
-}
-
-export interface GitHubCommit {
- sha: string;
- commit: { message: string; author: { name: string; date: string } | null };
- html_url: string;
- files?: { filename: string; status: string }[];
-}
-
-export interface GitHubComment {
- id: number;
- body: string;
- user: { login: string } | null;
- created_at: string;
- html_url: string;
-}
-
-export interface GitHubFetchResult {
- issues: GitHubIssue[];
- issueComments: Map<number, GitHubComment[]>;
- pullRequests: GitHubPR[];
- prComments: Map<number, GitHubComment[]>;
- commits: GitHubCommit[];
-}
-
-async function ghFetch<T>(url: string, token: string): Promise<T> {
- const resp = await fetch(url, {
- headers: {
- Authorization: `Bearer ${token}`,
- Accept: "application/vnd.github+json",
- "X-GitHub-Api-Version": "2022-11-28",
- },
- });
- if (!resp.ok) {
- const text = await resp.text();
- throw new Error(`GitHub API ${resp.status}: ${text}`);
- }
- return resp.json() as Promise<T>;
-}
-
-export async function fetchGitHubData(
- repo: GitHubRepo,
- token: string,
- opts: { since?: string; limit?: number }
-): Promise<GitHubFetchResult> {
- const { owner, repo: repoName } = repo;
- const base = `https://api.github.com/repos/${owner}/${repoName}`;
- const limit = opts.limit ?? 50;
- const sinceParam = opts.since ? `&since=${opts.since}` : "";
-
- // Fetch issues (excludes PRs with is:issue filter via state param)
- const issues = await ghFetch<GitHubIssue[]>(
- `${base}/issues?state=all&per_page=${limit}&sort=updated&direction=desc${sinceParam}`,
- token
- );
- // GitHub /issues includes PRs — filter them out
- const realIssues = issues.filter((i: any) => !i.pull_request);
-
- // Fetch PRs
- const pullRequests = await ghFetch<GitHubPR[]>(
- `${base}/pulls?state=all&per_page=${limit}&sort=updated&direction=desc`,
- token
- );
-
- // Fetch commits
- const commitLimit = Math.min(limit * 2, 100);
- const commits = await ghFetch<GitHubCommit[]>(
- `${base}/commits?per_page=${commitLimit}${sinceParam}`,
- token
- );
-
- // Fetch comments for top issues (max 10 to avoid rate limits)
- const issueComments = new Map<number, GitHubComment[]>();
- for (const issue of realIssues.slice(0, 10)) {
- if (issue.comments > 0) {
- try {
- const comments = await ghFetch<GitHubComment[]>(
- `${base}/issues/${issue.number}/comments?per_page=10`,
- token
- );
- issueComments.set(issue.number, comments);
- } catch { /* skip on error */ }
- }
- }
-
- // Fetch review comments for top PRs (max 10)
- const prComments = new Map<number, GitHubComment[]>();
- for (const pr of pullRequests.slice(0, 10)) {
- try {
- const comments = await ghFetch<GitHubComment[]>(
- `${base}/pulls/${pr.number}/comments?per_page=10`,
- token
- );
- if (comments.length > 0) {
- prComments.set(pr.number, comments);
- }
- } catch { /* skip on error */ }
- }
-
- return { issues: realIssues, issueComments, pullRequests, prComments, commits };
-}
-```
-
-**Step 4: Run test to verify it passes**
-
-Run: `npx vitest run src/cli/__tests__/github-fetch.test.ts`
-Expected: PASS
-
-**Step 5: Commit**
-
-```bash
-git add ix-cli/src/cli/github/fetch.ts ix-cli/src/cli/__tests__/github-fetch.test.ts
-git commit -m "feat: add GitHub API fetcher for issues, PRs, commits"
-```
-
----
-
-### Task 5: Add GitHub-to-GraphPatch Transformer
-
-**Files:**
-- Create: `ix-cli/src/cli/github/transform.ts`
-- Test: `ix-cli/src/cli/__tests__/github-transform.test.ts`
-
-**Step 1: Write the failing test**
-
-Create `ix-cli/src/cli/__tests__/github-transform.test.ts`:
-
-```typescript
-import { describe, it, expect } from "vitest";
-
-describe("GitHub transform", () => {
- it("creates deterministic node IDs from URIs", async () => {
- const { deterministicId } = await import("../github/transform.js");
- const id1 = deterministicId("github://owner/repo/issues/1");
- const id2 = deterministicId("github://owner/repo/issues/1");
- const id3 = deterministicId("github://owner/repo/issues/2");
- expect(id1).toBe(id2); // same input = same ID
- expect(id1).not.toBe(id3); // different input = different ID
- // Should be valid UUID format
- expect(id1).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/);
- });
-
- it("transforms an issue into UpsertNode ops", async () => {
- const { transformIssue } = await import("../github/transform.js");
- const ops = transformIssue(
- { owner: "acme", repo: "app" },
- {
- number: 42,
- title: "Fix login bug",
- body: "Login fails on mobile",
- state: "open",
- user: { login: "alice" },
- labels: [{ name: "bug" }],
- created_at: "2026-01-01T00:00:00Z",
- updated_at: "2026-01-02T00:00:00Z",
- html_url: "https://github.com/acme/app/issues/42",
- comments: 0,
- }
- );
- expect(ops.length).toBeGreaterThanOrEqual(1);
- const upsert = ops.find((op: any) => op.type === "UpsertNode");
- expect(upsert).toBeDefined();
- expect(upsert!.kind).toBe("intent");
- expect(upsert!.name).toBe("Fix login bug");
- });
-
- it("transforms a PR into UpsertNode ops with decision kind", async () => {
- const { transformPR } = await import("../github/transform.js");
- const ops = transformPR(
- { owner: "acme", repo: "app" },
- {
- number: 10,
- title: "Add auth flow",
- body: "Implements OAuth",
- state: "closed",
- merged_at: "2026-01-05T00:00:00Z",
- user: { login: "bob" },
- base: { ref: "main" },
- head: { ref: "feature/auth" },
- created_at: "2026-01-03T00:00:00Z",
- updated_at: "2026-01-05T00:00:00Z",
- html_url: "https://github.com/acme/app/pull/10",
- changed_files: 5,
- }
- );
- const upsert = ops.find((op: any) => op.type === "UpsertNode");
- expect(upsert).toBeDefined();
- expect(upsert!.kind).toBe("decision");
- expect(upsert!.name).toBe("Add auth flow");
- });
-
- it("transforms a commit into UpsertNode ops with doc kind", async () => {
- const { transformCommit } = await import("../github/transform.js");
- const ops = transformCommit(
- { owner: "acme", repo: "app" },
- {
- sha: "abc123def456",
- commit: { message: "fix: resolve null pointer", author: { name: "carol", date: "2026-01-04T00:00:00Z" } },
- html_url: "https://github.com/acme/app/commit/abc123def456",
- files: [{ filename: "src/auth.ts", status: "modified" }],
- }
- );
- const upsert = ops.find((op: any) => op.type === "UpsertNode");
- expect(upsert).toBeDefined();
- expect(upsert!.kind).toBe("doc");
- expect(upsert!.name).toContain("fix: resolve null pointer");
- });
-});
-```
-
-**Step 2: Run test to verify it fails**
-
-Run: `npx vitest run src/cli/__tests__/github-transform.test.ts`
-Expected: FAIL
-
-**Step 3: Write implementation**
-
-Create `ix-cli/src/cli/github/transform.ts`:
-
-```typescript
-import { createHash } from "node:crypto";
-import type { PatchOp } from "../../client/types.js";
-import type { GitHubRepo, GitHubIssue, GitHubPR, GitHubCommit, GitHubComment } from "./fetch.js";
-
-/** Generate a deterministic UUID v5-like ID from a string. */
-export function deterministicId(input: string): string {
- const hash = createHash("sha256").update(input).digest("hex");
- // Format as UUID: 8-4-4-4-12
- return [
- hash.slice(0, 8),
- hash.slice(8, 12),
- hash.slice(12, 16),
- hash.slice(16, 20),
- hash.slice(20, 32),
- ].join("-");
-}
-
-function truncate(s: string | null | undefined, max: number): string {
- if (!s) return "";
- return s.length > max ? s.slice(0, max) + "..." : s;
-}
-
-export function transformIssue(repo: GitHubRepo, issue: GitHubIssue): PatchOp[] {
- const uri = `github://${repo.owner}/${repo.repo}/issues/${issue.number}`;
- const nodeId = deterministicId(uri);
- const ops: PatchOp[] = [
- {
- type: "UpsertNode",
- id: nodeId,
- kind: "intent",
- name: issue.title,
- attrs: {
- number: issue.number,
- url: issue.html_url,
- author: issue.user?.login ?? "unknown",
- labels: issue.labels.map(l => l.name),
- state: issue.state,
- created_at: issue.created_at,
- body: truncate(issue.body, 2000),
- source_uri: uri,
- },
- },
- ];
- return ops;
-}
-
-export function transformIssueComment(
- repo: GitHubRepo,
- issueNumber: number,
- comment: GitHubComment
-): PatchOp[] {
- const parentUri = `github://${repo.owner}/${repo.repo}/issues/${issueNumber}`;
- const commentUri = `${parentUri}/comments/${comment.id}`;
- const parentId = deterministicId(parentUri);
- const commentId = deterministicId(commentUri);
- const edgeId = deterministicId(`${parentUri}:CONTAINS:${commentUri}`);
-
- return [
- {
- type: "UpsertNode",
- id: commentId,
- kind: "doc",
- name: `Issue #${issueNumber} comment by ${comment.user?.login ?? "unknown"}`,
- attrs: {
- url: comment.html_url,
- author: comment.user?.login ?? "unknown",
- created_at: comment.created_at,
- body: truncate(comment.body, 2000),
- source_uri: commentUri,
- },
- },
- {
- type: "UpsertEdge",
- id: edgeId,
- src: parentId,
- dst: commentId,
- predicate: "CONTAINS",
- attrs: {},
- },
- ];
-}
-
-export function transformPR(repo: GitHubRepo, pr: GitHubPR): PatchOp[] {
- const uri = `github://${repo.owner}/${repo.repo}/pull/${pr.number}`;
- const nodeId = deterministicId(uri);
- const ops: PatchOp[] = [
- {
- type: "UpsertNode",
- id: nodeId,
- kind: "decision",
- name: pr.title,
- attrs: {
- number: pr.number,
- url: pr.html_url,
- author: pr.user?.login ?? "unknown",
- state: pr.state,
- merged: !!pr.merged_at,
- base_branch: pr.base.ref,
- head_branch: pr.head.ref,
- created_at: pr.created_at,
- changed_files_count: pr.changed_files,
- body: truncate(pr.body, 2000),
- rationale: truncate(pr.body, 500),
- source_uri: uri,
- },
- },
- ];
- return ops;
-}
-
-export function transformPRComment(
- repo: GitHubRepo,
- prNumber: number,
- comment: GitHubComment
-): PatchOp[] {
- const parentUri = `github://${repo.owner}/${repo.repo}/pull/${prNumber}`;
- const commentUri = `${parentUri}/comments/${comment.id}`;
- const parentId = deterministicId(parentUri);
- const commentId = deterministicId(commentUri);
- const edgeId = deterministicId(`${parentUri}:CONTAINS:${commentUri}`);
-
- return [
- {
- type: "UpsertNode",
- id: commentId,
- kind: "doc",
- name: `PR #${prNumber} review by ${comment.user?.login ?? "unknown"}`,
- attrs: {
- url: comment.html_url,
- author: comment.user?.login ?? "unknown",
- created_at: comment.created_at,
- body: truncate(comment.body, 2000),
- source_uri: commentUri,
- },
- },
- {
- type: "UpsertEdge",
- id: edgeId,
- src: parentId,
- dst: commentId,
- predicate: "CONTAINS",
- attrs: {},
- },
- ];
-}
-
-export function transformCommit(repo: GitHubRepo, commit: GitHubCommit): PatchOp[] {
- const uri = `github://${repo.owner}/${repo.repo}/commit/${commit.sha}`;
- const nodeId = deterministicId(uri);
- const message = commit.commit.message.split("\n")[0]; // first line only for name
-
- const ops: PatchOp[] = [
- {
- type: "UpsertNode",
- id: nodeId,
- kind: "doc",
- name: message,
- attrs: {
- sha: commit.sha,
- url: commit.html_url,
- author: commit.commit.author?.name ?? "unknown",
- created_at: commit.commit.author?.date,
- message: truncate(commit.commit.message, 2000),
- changed_files: commit.files?.map(f => f.filename) ?? [],
- source_uri: uri,
- },
- },
- ];
-
- // Add REFERENCES edges to changed files
- if (commit.files) {
- for (const file of commit.files) {
- const fileNodeId = deterministicId(`${repo.owner}/${repo.repo}::${file.filename}`);
- const edgeId = deterministicId(`${uri}:REFERENCES:${file.filename}`);
- ops.push({
- type: "UpsertEdge",
- id: edgeId,
- src: nodeId,
- dst: fileNodeId,
- predicate: "REFERENCES",
- attrs: { change_type: file.status },
- });
- }
- }
-
- return ops;
-}
-```
-
-**Step 4: Run test to verify it passes**
-
-Run: `npx vitest run src/cli/__tests__/github-transform.test.ts`
-Expected: PASS
-
-**Step 5: Commit**
-
-```bash
-git add ix-cli/src/cli/github/transform.ts ix-cli/src/cli/__tests__/github-transform.test.ts
-git commit -m "feat: add GitHub-to-GraphPatch transformer (issues→intent, PRs→decision, commits→doc)"
-```
-
----
-
-### Task 6: Add `--github` Flag to Ingest Command
-
-**Files:**
-- Modify: `ix-cli/src/cli/commands/ingest.ts:1-65`
-
-**Step 1: Add the --github flag and wire everything together**
-
-Replace the entire contents of `ix-cli/src/cli/commands/ingest.ts`:
-
-```typescript
-import * as nodePath from "node:path";
-import type { Command } from "commander";
-import chalk from "chalk";
-import { IxClient } from "../../client/api.js";
-import type { GraphPatchPayload } from "../../client/types.js";
-import { getEndpoint, resolveWorkspaceRoot } from "../config.js";
-import { resolveGitHubToken } from "../github/auth.js";
-import { parseGitHubRepo, fetchGitHubData } from "../github/fetch.js";
-import {
- deterministicId,
- transformIssue,
- transformIssueComment,
- transformPR,
- transformPRComment,
- transformCommit,
-} from "../github/transform.js";
-
-export function registerIngestCommand(program: Command): void {
- program
- .command("ingest [path]")
- .description("Ingest source files or GitHub data into the knowledge graph")
- .option("--recursive", "Recursively ingest directory")
- .option("--github <owner/repo>", "Ingest issues, PRs, and commits from a GitHub repository")
- .option("--token <pat>", "GitHub personal access token")
- .option("--since <date>", "Only fetch items updated after this date (ISO 8601)")
- .option("--limit <n>", "Max items per category (default 50)", "50")
- .option("--format <fmt>", "Output format (text|json)", "text")
- .option("--root <dir>", "Workspace root directory")
- .addHelpText("after", "\nExamples:\n ix ingest ./src --recursive\n ix ingest --github owner/repo\n ix ingest --github owner/repo --since 2026-01-01 --limit 20 --format json\n ix ingest --github owner/repo --token ghp_xxxx")
- .action(async (path: string | undefined, opts: {
- recursive?: boolean; github?: string; token?: string;
- since?: string; limit: string; format: string; root?: string
- }) => {
- if (opts.github) {
- await ingestGitHub(opts);
- } else if (path) {
- await ingestFiles(path, opts);
- } else {
- console.error("Error: provide a <path> or use --github <owner/repo>");
- process.exit(1);
- }
- });
-}
-
-async function ingestFiles(
- path: string,
- opts: { recursive?: boolean; format: string; root?: string }
-): Promise<void> {
- const resolvedPath = nodePath.isAbsolute(path)
- ? path
- : nodePath.resolve(resolveWorkspaceRoot(opts.root), path);
- const client = new IxClient(getEndpoint());
- const start = performance.now();
-
- const spinner = ["\u28CB", "\u28D9", "\u28F9", "\u28F8", "\u28FC", "\u28F4", "\u28E6", "\u28E7", "\u28C7", "\u28CF"];
- let spinIdx = 0;
- const interval = opts.format === "text" ? setInterval(() => {
- const elapsed = ((performance.now() - start) / 1000).toFixed(0);
- process.stderr.write(`\r${spinner[spinIdx++ % spinner.length]} Ingesting... ${elapsed}s`);
- }, 200) : null;
-
- try {
- const result = await client.ingest(resolvedPath, opts.recursive);
- if (interval) {
- clearInterval(interval);
- process.stderr.write("\r" + " ".repeat(40) + "\r");
- }
- const elapsed = ((performance.now() - start) / 1000).toFixed(2);
-
- if (opts.format === "json") {
- console.log(JSON.stringify({ ...result, elapsedSeconds: parseFloat(elapsed) }, null, 2));
- } else {
- console.log(chalk.bold("\nIngest summary"));
- console.log(` processed: ${result.patchesApplied} files (${elapsed}s)`);
- console.log(` discovered: ${result.filesProcessed} files`);
- if (result.skipReasons) {
- const sr = result.skipReasons;
- if (sr.unchanged > 0) console.log(` ${chalk.dim("skipped unchanged:")} ${sr.unchanged}`);
- if (sr.emptyFile > 0) console.log(` ${chalk.dim("skipped empty:")} ${sr.emptyFile}`);
- if (sr.parseError > 0) console.log(` ${chalk.red("parse errors:")} ${sr.parseError}`);
- if (sr.tooLarge > 0) console.log(` ${chalk.dim("skipped too large:")} ${sr.tooLarge}`);
- } else if (result.filesSkipped) {
- console.log(` ${chalk.dim("skipped:")} ${result.filesSkipped} unchanged files`);
- }
- console.log(` rev: ${result.latestRev}`);
-
- if (result.patchesApplied === 0 && result.filesProcessed === 0) {
- console.log(chalk.yellow("\n Warning: No files ingested. The path may be outside the project root,"));
- console.log(chalk.yellow(" contain no supported file types, or not exist."));
- } else if (result.patchesApplied === 0 && result.filesProcessed > 0) {
- console.log(chalk.dim("\n All files unchanged since last ingest."));
- }
- console.log();
- }
- } finally {
- if (interval) clearInterval(interval);
- }
-}
-
-async function ingestGitHub(opts: {
- github?: string; token?: string; since?: string;
- limit: string; format: string
-}): Promise<void> {
- const repo = parseGitHubRepo(opts.github!);
- const token = await resolveGitHubToken(opts.token);
- const client = new IxClient(getEndpoint());
- const limit = parseInt(opts.limit, 10);
- const start = performance.now();
-
- // Default --since to 30 days ago
- const since = opts.since ?? new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10);
-
- if (opts.format !== "json") {
- process.stderr.write(`Fetching from ${repo.owner}/${repo.repo} (since ${since})...\n`);
- }
-
- const data = await fetchGitHubData(repo, token, { since, limit });
-
- // Build all patch ops
- const allOps: any[] = [];
-
- for (const issue of data.issues) {
- allOps.push(...transformIssue(repo, issue));
- }
- for (const [issueNum, comments] of data.issueComments) {
- for (const comment of comments) {
- allOps.push(...transformIssueComment(repo, issueNum, comment));
- }
- }
- for (const pr of data.pullRequests) {
- allOps.push(...transformPR(repo, pr));
- }
- for (const [prNum, comments] of data.prComments) {
- for (const comment of comments) {
- allOps.push(...transformPRComment(repo, prNum, comment));
- }
- }
- for (const commit of data.commits) {
- allOps.push(...transformCommit(repo, commit));
- }
-
- // Submit as a single patch
- const patch: GraphPatchPayload = {
- patchId: deterministicId(`github://${repo.owner}/${repo.repo}:${since}:${Date.now()}`),
- actor: "ix/github-ingest",
- timestamp: new Date().toISOString(),
- source: {
- uri: `github://${repo.owner}/${repo.repo}`,
- extractor: "github-ingest/1.0",
- sourceType: "comment",
- },
- baseRev: 0,
- ops: allOps,
- replaces: [],
- intent: `GitHub ingestion: ${repo.owner}/${repo.repo}`,
- };
-
- const result = await client.commitPatch(patch);
- const elapsed = ((performance.now() - start) / 1000).toFixed(2);
-
- if (opts.format === "json") {
- console.log(JSON.stringify({
- source: `${repo.owner}/${repo.repo}`,
- issues: data.issues.length,
- pullRequests: data.pullRequests.length,
- commits: data.commits.length,
- issueComments: [...data.issueComments.values()].reduce((s, c) => s + c.length, 0),
- prComments: [...data.prComments.values()].reduce((s, c) => s + c.length, 0),
- totalOps: allOps.length,
- rev: result.rev,
- status: result.status,
- elapsedSeconds: parseFloat(elapsed),
- }, null, 2));
- } else {
- console.log(chalk.bold("\nGitHub ingest summary"));
- console.log(` repo: ${repo.owner}/${repo.repo}`);
- console.log(` issues: ${data.issues.length}`);
- console.log(` pull requests: ${data.pullRequests.length}`);
- console.log(` commits: ${data.commits.length}`);
- const issueCommentCount = [...data.issueComments.values()].reduce((s, c) => s + c.length, 0);
- const prCommentCount = [...data.prComments.values()].reduce((s, c) => s + c.length, 0);
- if (issueCommentCount > 0) console.log(` issue comments: ${issueCommentCount}`);
- if (prCommentCount > 0) console.log(` PR comments: ${prCommentCount}`);
- console.log(` total ops: ${allOps.length}`);
- console.log(` rev: ${result.rev}`);
- console.log(` elapsed: ${elapsed}s`);
- console.log();
- }
-}
-```
-
-**Step 2: Build**
-
-Run: `cd ix-cli && npm run build`
-Expected: Compiles successfully
-
-**Step 3: Commit**
-
-```bash
-git add ix-cli/src/cli/commands/ingest.ts
-git commit -m "feat: add --github flag to ix ingest for GitHub repo ingestion"
-```
-
----
-
-### Task 7: Run Full Test Suite and Fix
-
-**Step 1: Run all tests**
-
-Run: `npx vitest run`
-Expected: All tests pass
-
-**Step 2: If any test fails, fix it**
-
-The ingest command changed from `ingest <path>` to `ingest [path]` (optional). Check if any existing tests reference the old signature.
-
-**Step 3: Commit fixes if needed**
-
-```bash
-git add -A
-git commit -m "fix: update tests for optional ingest path"
-```
-
----
-
-### Task 8: Update Docs
-
-**Files:**
-- Modify: `CLAUDE.md`
-- Modify: `AGENTS.md`
-- Modify: `README.md`
-
-**Step 1: Add GitHub ingestion to CLAUDE.md routing table**
-
-In the `### Ingestion & Health` section, add:
-
-```
-| Ingest GitHub data | `ix ingest` | `ix ingest --github owner/repo --limit 50` |
-```
-
-**Step 2: Add to AGENTS.md**
-
-In the command routing section, add under "### Ingesting data":
-
-```
-ix ingest --github owner/repo --format json --limit 50
-ix ingest --github owner/repo --since 2026-01-01 --format json
-```
-
-**Step 3: Add to README.md core commands**
-
-Add a row for `ix ingest --github` in the commands table.
-
-**Step 4: Commit**
-
-```bash
-git add CLAUDE.md AGENTS.md README.md
-git commit -m "docs: add GitHub ingestion to CLI routing guides"
-```
-
----
-
-### Task 9: Push
-
-**Step 1: Push all commits**
-
-```bash
-git push origin feature/ix-redesign
-```
diff --git a/docs/plans/2026-03-08-plan-graph-decision-linking-design.md b/docs/plans/2026-03-08-plan-graph-decision-linking-design.md
deleted file mode 100644
index 9d475ea6..00000000
--- a/docs/plans/2026-03-08-plan-graph-decision-linking-design.md
+++ /dev/null
@@ -1,115 +0,0 @@
-# Plan Graph + Decision Linking Design
-
-**Goal:** Transform Ix from low-level graph primitives into a planning and reasoning layer for LLM agents.
-
-**Scope:** MCP removal, CLI output fix, decision linking, plan graph, doc updates. Verification layer deferred to part 2.
-
----
-
-## 1. MCP Removal
-
-Delete `ix-cli/src/mcp/` entirely:
-- `server.ts`, `session.ts`, tests
-- Remove `mcp-start` and `mcp-install` commands from `main.ts`
-- Remove `@modelcontextprotocol/sdk` from `package.json`
-- Remove MCP references from README, CLAUDE.md, AGENTS.md
-
-After this, `ix CLI --format json` is the only agent interface.
-
-## 2. CLI Output Fix
-
-Create a `stderr()` utility wrapping `console.error()`. All human-readable status messages (`printResolved()`, disambiguation warnings, progress indicators) go through `stderr()`. stdout is reserved exclusively for the command's primary output.
-
-- `--format json` produces clean, pipeable JSON on stdout
-- `--format text` (default) keeps human-readable output on stdout
-- Diagnostic/status messages always go to stderr regardless of format
-
-## 3. Decision Linking
-
-### New flags on `ix decide`
-
-- `--affects <entity1,entity2,...>` — resolves each entity, creates `DECISION_AFFECTS` edges
-- `--supersedes <decision-id>` — creates `DECISION_SUPERSEDES` edge from new to old
-- `--parent <decision-id>` — creates `DECISION_CHILD` edge from parent to new
-
-### New edge predicates
-
-- `DECISION_AFFECTS` — Decision → Entity
-- `DECISION_SUPERSEDES` — Decision → Decision
-- `DECISION_CHILD` — Decision → Decision
-
-### Implementation
-
-Client-side via GraphPatch. CLI resolves entity names, builds patch ops (UpsertNode for decision + UpsertEdge for each link), submits to `POST /v1/patch`. Same pattern as GitHub ingestion.
-
-### Surfacing
-
-`ix overview <entity>` gains a `decisions` field by expanding incoming `DECISION_AFFECTS` edges.
-
-## 4. Plan Graph
-
-### Node kinds
-
-- **Goal** — reuse existing `Intent` node kind. `ix goal create` = alias for `ix truth add`.
-- **Plan** — new `NodeKind.Plan`
-- **Task** — new `NodeKind.Task`
-
-### Edge predicates
-
-- `GOAL_HAS_PLAN` — Intent → Plan
-- `PLAN_HAS_TASK` — Plan → Task
-- `DEPENDS_ON` — Task → Task
-- `TASK_AFFECTS` — Task → any entity
-
-### Task statuses
-
-Stored as a claim attribute on the Task node: `pending`, `in_progress`, `blocked`, `done`, `abandoned`.
-
-### CLI commands
-
-| Command | Purpose |
-|---------|---------|
-| `ix goal create <statement>` | Alias for `ix truth add` |
-| `ix goal list` | Alias for `ix truth list` |
-| `ix plan create <title> --goal <goal-id>` | Create Plan node + GOAL_HAS_PLAN edge |
-| `ix plan task <title> --plan <plan-id> [--depends-on <id>] [--affects <entity>]` | Create Task + edges |
-| `ix plan status <plan-id>` | Tasks with statuses, critical path, next actionable |
-| `ix plan next <plan-id>` | Highest-priority unblocked task |
-| `ix task update <task-id> --status <status>` | Update task status |
-
-### Plan status algorithm
-
-1. Expand `PLAN_HAS_TASK` to get all tasks
-2. For each task, expand outgoing `DEPENDS_ON` to find blockers
-3. Critical path = tasks with most downstream `DEPENDS_ON` chains
-4. Next actionable = not-done task with all dependencies satisfied, first by creation order
-
-### Surfacing
-
-`ix overview <entity>` gains a `tasks` field by expanding incoming `TASK_AFFECTS` edges.
-
-## 5. Doc Updates
-
-Preferred agent routing:
-
-| Goal | Command |
-|------|---------|
-| Understand an entity | `ix overview` |
-| Blast radius | `ix impact` |
-| Find hotspots | `ix rank` |
-| List entities | `ix inventory` |
-| Plan work | `ix plan create` / `ix plan next` |
-| Track decisions | `ix decide --affects` |
-| Resume work | `ix plan next` |
-
-Low-level commands (`callers`, `callees`, `contains`, `imports`, `depends`) described as structural primitives.
-
-Remove all MCP references from docs.
-
-## 6. Deferred (Part 2)
-
-Verification layer: `ix task verify <task>` — check if affected entities changed since task creation. Requires tracking revision at task creation time.
-
-## Implementation approach
-
-All new features are client-side via GraphPatch submissions. No new backend routes needed beyond the existing `POST /v1/patch`. Deterministic IDs via SHA-256 (same pattern as GitHub ingestion).
diff --git a/docs/plans/2026-03-08-plan-graph-decision-linking-plan.md b/docs/plans/2026-03-08-plan-graph-decision-linking-plan.md
deleted file mode 100644
index 470e6445..00000000
--- a/docs/plans/2026-03-08-plan-graph-decision-linking-plan.md
+++ /dev/null
@@ -1,1248 +0,0 @@
-# Plan Graph + Decision Linking Implementation Plan
-
-> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
-
-**Goal:** Transform Ix from low-level graph primitives into a planning and reasoning layer — add plan graph, decision linking, remove MCP, fix CLI output.
-
-**Architecture:** All new features are client-side via GraphPatch submissions to `POST /v1/patch`. Two new NodeKinds (Plan, Task) added to the backend. CLI output split: stderr for human diagnostics, stdout for primary output. MCP deleted entirely.
-
-**Tech Stack:** TypeScript (CLI), Scala (backend NodeKind only), Commander, vitest
-
----
-
-### Task 1: Remove MCP completely
-
-**Files:**
-- Delete: `ix-cli/src/mcp/server.ts`
-- Delete: `ix-cli/src/mcp/session.ts`
-- Delete: `ix-cli/src/mcp/__tests__/server.test.ts`
-- Delete: `ix-cli/src/mcp/__tests__/session.test.ts`
-- Delete: `ix-cli/src/cli/commands/mcp-install.ts`
-- Modify: `ix-cli/src/cli/main.ts`
-- Modify: `ix-cli/package.json`
-
-**Step 1: Delete MCP files**
-
-```bash
-rm -rf ix-cli/src/mcp/
-rm ix-cli/src/cli/commands/mcp-install.ts
-```
-
-**Step 2: Remove MCP from main.ts**
-
-In `ix-cli/src/cli/main.ts`:
-- Remove the import: `import { registerMcpInstallCommand } from "./commands/mcp-install.js";`
-- Remove the registration: `registerMcpInstallCommand(program);`
-- Remove the inline `mcp-start` command block (lines 67-72):
-```typescript
-// DELETE THIS ENTIRE BLOCK:
-program
- .command("mcp-start")
- .description("Start the MCP server (stdio transport)")
- .action(async () => {
- await import("../mcp/server.js");
- });
-```
-
-**Step 3: Remove MCP SDK from package.json**
-
-In `ix-cli/package.json`, remove from dependencies:
-```json
-"@modelcontextprotocol/sdk": "^1.0.0",
-```
-
-**Step 4: Remove MCP references from init.ts CLAUDE.md template**
-
-In `ix-cli/src/cli/commands/init.ts`, update the `IX_CLAUDE_MD_BLOCK` template:
-- Line 20: change `Use the \`ix\` CLI exclusively. Do NOT use MCP tools — the CLI is the canonical agent interface.` to `Use the \`ix\` CLI exclusively. All commands support \`--format json\`.`
-- Line 66: remove `- MCP tools — deprecated, use CLI instead`
-
-**Step 5: Verify build and tests**
-
-```bash
-cd ix-cli && npm run build && npm test
-```
-
-Expected: Build succeeds, all existing tests pass (MCP tests are deleted so they won't run).
-
-**Step 6: Commit**
-
-```bash
-git add -A
-git commit -m "feat: remove MCP completely — CLI is the only agent interface"
-```
-
----
-
-### Task 2: CLI output fix — stderr for diagnostics
-
-**Files:**
-- Create: `ix-cli/src/cli/stderr.ts`
-- Modify: `ix-cli/src/cli/resolve.ts`
-
-**Step 1: Create stderr utility**
-
-Create `ix-cli/src/cli/stderr.ts`:
-
-```typescript
-import chalk from "chalk";
-
-/** Write a diagnostic/status message to stderr (never pollutes stdout/JSON). */
-export function stderr(message: string): void {
- process.stderr.write(message + "\n");
-}
-
-/** Write a styled diagnostic to stderr. */
-export function stderrDim(message: string): void {
- process.stderr.write(chalk.dim(message) + "\n");
-}
-```
-
-**Step 2: Update resolve.ts to use stderr**
-
-In `ix-cli/src/cli/resolve.ts`:
-
-Replace all `console.log` calls with `stderr` imports:
-
-```typescript
-import { stderr } from "./stderr.js";
-```
-
-Change line 27:
-```typescript
-// OLD: console.log(`No entity found matching "${symbol}".`);
-stderr(`No entity found matching "${symbol}".`);
-```
-
-Change line 60:
-```typescript
-// OLD: console.log(`Multiple matches for "${symbol}":`);
-stderr(`Multiple matches for "${symbol}":`);
-```
-
-Change line 69:
-```typescript
-// OLD: console.log(` ${chalk.cyan(...)}`);
-stderr(` ${chalk.cyan((node.kind ?? "").padEnd(10))} ${chalk.dim(shortId)} ${name}`);
-```
-
-Change line 71:
-```typescript
-// OLD: console.log(chalk.dim(`\nUse --kind <kind> to disambiguate.`));
-stderr(chalk.dim(`\nUse --kind <kind> to disambiguate.`));
-```
-
-Change line 84 (`printResolved`):
-```typescript
-// OLD: console.log(`${chalk.dim("Resolved:")} ...`);
-stderr(`${chalk.dim("Resolved:")} ${chalk.cyan(target.kind)} ${chalk.dim(shortId)} ${chalk.bold(target.name)}${modeStr}\n`);
-```
-
-**Step 3: Verify build and tests**
-
-```bash
-cd ix-cli && npm run build && npm test
-```
-
-**Step 4: Commit**
-
-```bash
-git add ix-cli/src/cli/stderr.ts ix-cli/src/cli/resolve.ts
-git commit -m "feat: route diagnostic output to stderr — stdout reserved for data"
-```
-
----
-
-### Task 3: Add Plan and Task node kinds to backend
-
-**Files:**
-- Modify: `memory-layer/src/main/scala/ix/memory/model/Node.scala`
-
-**Step 1: Add Plan and Task to NodeKind**
-
-In `memory-layer/src/main/scala/ix/memory/model/Node.scala`:
-
-Add after `case object Method extends NodeKind` (line 25):
-```scala
- case object Plan extends NodeKind
- case object Task extends NodeKind
-```
-
-Add to `nameMap` after `"method" -> Method`:
-```scala
- "plan" -> Plan,
- "task" -> Task
-```
-
-Add to `encoder` after `case Method => "method"`:
-```scala
- case Plan => "plan"
- case Task => "task"
-```
-
-**Step 2: Verify backend compiles**
-
-```bash
-cd memory-layer && sbt compile
-```
-
-Expected: Compiles cleanly. The exhaustive match in the encoder will require all cases.
-
-**Step 3: Commit**
-
-```bash
-git add memory-layer/src/main/scala/ix/memory/model/Node.scala
-git commit -m "feat: add Plan and Task node kinds to backend"
-```
-
----
-
-### Task 4: Decision linking — extend ix decide
-
-**Files:**
-- Modify: `ix-cli/src/cli/commands/decide.ts`
-- Test: `ix-cli/src/cli/__tests__/decide-linking.test.ts`
-
-**Step 1: Write the failing test**
-
-Create `ix-cli/src/cli/__tests__/decide-linking.test.ts`:
-
-```typescript
-import { describe, it, expect } from "vitest";
-import { buildDecisionPatch } from "../commands/decide.js";
-
-describe("buildDecisionPatch", () => {
- it("creates a patch with DECISION_AFFECTS edges", () => {
- const patch = buildDecisionPatch(
- "Use client-side patch",
- "Avoid server coupling",
- {
- affects: [
- { id: "entity-1", kind: "class", name: "IngestionService" },
- { id: "entity-2", kind: "class", name: "IxClient" },
- ],
- }
- );
- expect(patch.ops.length).toBe(3); // 1 UpsertNode + 2 UpsertEdge
- expect(patch.ops[0].type).toBe("UpsertNode");
- expect(patch.ops[0].kind).toBe("decision");
- expect(patch.ops[1].type).toBe("UpsertEdge");
- expect(patch.ops[1].predicate).toBe("DECISION_AFFECTS");
- expect(patch.ops[2].predicate).toBe("DECISION_AFFECTS");
- });
-
- it("creates DECISION_SUPERSEDES edge when supersedes is provided", () => {
- const patch = buildDecisionPatch("New approach", "Better", {
- supersedes: "old-decision-id",
- });
- expect(patch.ops.length).toBe(2); // 1 UpsertNode + 1 UpsertEdge
- expect(patch.ops[1].predicate).toBe("DECISION_SUPERSEDES");
- expect(patch.ops[1].src).toBe(patch.ops[0].id); // new decision → old
- expect(patch.ops[1].dst).toBe("old-decision-id");
- });
-
- it("creates DECISION_CHILD edge when parent is provided", () => {
- const patch = buildDecisionPatch("Sub-decision", "Detail", {
- parent: "parent-decision-id",
- });
- expect(patch.ops.length).toBe(2);
- expect(patch.ops[1].predicate).toBe("DECISION_CHILD");
- expect(patch.ops[1].src).toBe("parent-decision-id"); // parent → child
- expect(patch.ops[1].dst).toBe(patch.ops[0].id);
- });
-});
-```
-
-**Step 2: Run test to verify it fails**
-
-```bash
-cd ix-cli && npx vitest run src/cli/__tests__/decide-linking.test.ts
-```
-
-Expected: FAIL — `buildDecisionPatch` is not exported.
-
-**Step 3: Implement buildDecisionPatch and update decide command**
-
-Rewrite `ix-cli/src/cli/commands/decide.ts`:
-
-```typescript
-import type { Command } from "commander";
-import { IxClient } from "../../client/api.js";
-import { getEndpoint } from "../config.js";
-import { resolveEntity } from "../resolve.js";
-import { deterministicId } from "../github/transform.js";
-import type { GraphPatchPayload, PatchOp } from "../../client/types.js";
-
-interface DecisionLinkOpts {
- affects?: { id: string; kind: string; name: string }[];
- supersedes?: string;
- parent?: string;
-}
-
-export function buildDecisionPatch(
- title: string,
- rationale: string,
- linkOpts: DecisionLinkOpts = {}
-): GraphPatchPayload {
- const now = new Date().toISOString();
- const decisionId = deterministicId(`decision:${title}:${now}`);
- const ops: PatchOp[] = [];
-
- // 1. UpsertNode for the decision
- ops.push({
- type: "UpsertNode",
- id: decisionId,
- kind: "decision",
- name: title,
- attrs: { rationale, created_at: now },
- });
-
- // 2. DECISION_AFFECTS edges
- if (linkOpts.affects) {
- for (const entity of linkOpts.affects) {
- ops.push({
- type: "UpsertEdge",
- id: deterministicId(`${decisionId}:DECISION_AFFECTS:${entity.id}`),
- src: decisionId,
- dst: entity.id,
- predicate: "DECISION_AFFECTS",
- attrs: {},
- });
- }
- }
-
- // 3. DECISION_SUPERSEDES edge
- if (linkOpts.supersedes) {
- ops.push({
- type: "UpsertEdge",
- id: deterministicId(`${decisionId}:DECISION_SUPERSEDES:${linkOpts.supersedes}`),
- src: decisionId,
- dst: linkOpts.supersedes,
- predicate: "DECISION_SUPERSEDES",
- attrs: {},
- });
- }
-
- // 4. DECISION_CHILD edge (parent → child)
- if (linkOpts.parent) {
- ops.push({
- type: "UpsertEdge",
- id: deterministicId(`${linkOpts.parent}:DECISION_CHILD:${decisionId}`),
- src: linkOpts.parent,
- dst: decisionId,
- predicate: "DECISION_CHILD",
- attrs: {},
- });
- }
-
- return {
- patchId: decisionId,
- actor: "ix-cli",
- timestamp: now,
- source: {
- uri: `ix://decision/${encodeURIComponent(title)}`,
- extractor: "ix-cli:decide",
- sourceType: "Decision",
- },
- baseRev: 0,
- ops,
- replaces: [],
- };
-}
-
-export function registerDecideCommand(program: Command): void {
- program
- .command("decide <title>")
- .description("Record a design decision")
- .requiredOption("--rationale <text>", "Rationale for the decision")
- .option("--intent-id <id>", "Link to an intent")
- .option("--affects <entities>", "Comma-separated entity names to link (creates DECISION_AFFECTS edges)")
- .option("--supersedes <id>", "Decision ID this supersedes")
- .option("--parent <id>", "Parent decision ID")
- .option("--format <fmt>", "Output format (text|json)", "text")
- .action(
- async (
- title: string,
- opts: {
- rationale: string;
- intentId?: string;
- affects?: string;
- supersedes?: string;
- parent?: string;
- format: string;
- }
- ) => {
- const client = new IxClient(getEndpoint());
- const hasLinks = opts.affects || opts.supersedes || opts.parent;
-
- if (hasLinks) {
- // Use GraphPatch path for linked decisions
- let resolvedAffects: { id: string; kind: string; name: string }[] | undefined;
-
- if (opts.affects) {
- const names = opts.affects.split(",").map((s) => s.trim());
- resolvedAffects = [];
- for (const name of names) {
- const resolved = await resolveEntity(client, name, [
- "class", "module", "file", "function", "method", "trait", "object", "interface",
- ]);
- if (resolved) {
- resolvedAffects.push({ id: resolved.id, kind: resolved.kind, name: resolved.name });
- }
- }
- }
-
- const patch = buildDecisionPatch(title, opts.rationale, {
- affects: resolvedAffects,
- supersedes: opts.supersedes,
- parent: opts.parent,
- });
-
- if (opts.intentId) {
- patch.intent = opts.intentId;
- }
-
- const result = await client.commitPatch(patch);
- if (opts.format === "json") {
- console.log(JSON.stringify({ ...result, decisionId: patch.ops[0].id }, null, 2));
- } else {
- console.log(`Decision recorded: ${patch.ops[0].id} (rev ${result.rev})`);
- if (resolvedAffects?.length) {
- console.log(` Linked to: ${resolvedAffects.map((e) => e.name).join(", ")}`);
- }
- }
- } else {
- // Use the original backend endpoint for simple decisions
- const result = await client.decide(title, opts.rationale, { intentId: opts.intentId });
- if (opts.format === "json") {
- console.log(JSON.stringify(result, null, 2));
- } else {
- console.log(`Decision recorded: ${result.nodeId} (rev ${result.rev})`);
- }
- }
- }
- );
-}
-```
-
-**Step 4: Run tests**
-
-```bash
-cd ix-cli && npx vitest run src/cli/__tests__/decide-linking.test.ts
-```
-
-Expected: PASS (3 tests)
-
-**Step 5: Verify full build and all tests**
-
-```bash
-cd ix-cli && npm run build && npm test
-```
-
-**Step 6: Commit**
-
-```bash
-git add ix-cli/src/cli/commands/decide.ts ix-cli/src/cli/__tests__/decide-linking.test.ts
-git commit -m "feat: add decision linking — --affects, --supersedes, --parent flags"
-```
-
----
-
-### Task 5: Surface decisions in ix overview
-
-**Files:**
-- Modify: `ix-cli/src/cli/commands/overview.ts`
-
-**Step 1: Add decisions field to OverviewResult interface**
-
-In `ix-cli/src/cli/commands/overview.ts`, add to `OverviewResult` interface (after `signature: string | null;`):
-
-```typescript
- decisions: { id: string; title: string; rationale?: string }[];
-```
-
-**Step 2: Fetch DECISION_AFFECTS edges in overviewContainer**
-
-In the `overviewContainer` function, add to the `Promise.all` array (after the inboundResult fetch):
-
-```typescript
- client.expand(target.id, { direction: "in", predicates: ["DECISION_AFFECTS"] }),
-```
-
-Destructure the result:
-```typescript
- const [details, membersResult, importsResult, inboundResult, decisionsResult] = await Promise.all([...]);
-```
-
-Map the decisions:
-```typescript
- const decisions = decisionsResult.nodes.map((n: any) => ({
- id: n.id,
- title: n.name || n.attrs?.name || "(unnamed)",
- rationale: n.attrs?.rationale ?? undefined,
- }));
-```
-
-Add to the result object:
-```typescript
- decisions,
-```
-
-Add to text output (after the key members section):
-```typescript
- if (decisions.length > 0) {
- console.log(`\nDecisions:`);
- for (const d of decisions) {
- console.log(` ${chalk.yellow(d.title)}`);
- }
- }
-```
-
-**Step 3: Do the same for overviewCallable**
-
-Add `DECISION_AFFECTS` expand to the callable path's `Promise.all`, map the results, add to output.
-
-**Step 4: Verify build and tests**
-
-```bash
-cd ix-cli && npm run build && npm test
-```
-
-**Step 5: Commit**
-
-```bash
-git add ix-cli/src/cli/commands/overview.ts
-git commit -m "feat: surface linked decisions in ix overview output"
-```
-
----
-
-### Task 6: Plan graph — goal aliases
-
-**Files:**
-- Create: `ix-cli/src/cli/commands/goal.ts`
-- Modify: `ix-cli/src/cli/main.ts`
-
-**Step 1: Create goal command (aliases for truth)**
-
-Create `ix-cli/src/cli/commands/goal.ts`:
-
-```typescript
-import type { Command } from "commander";
-import { IxClient } from "../../client/api.js";
-import { getEndpoint } from "../config.js";
-import { formatIntents } from "../format.js";
-
-export function registerGoalCommand(program: Command): void {
- const goal = program
- .command("goal")
- .description("Manage project goals (aliases for ix truth)");
-
- goal
- .command("create <statement>")
- .description("Create a new goal")
- .option("--parent <id>", "Parent goal ID")
- .option("--format <fmt>", "Output format (text|json)", "text")
- .action(async (statement: string, opts: { parent?: string; format: string }) => {
- const client = new IxClient(getEndpoint());
- const result = await client.createTruth(statement, opts.parent);
- if (opts.format === "json") {
- console.log(JSON.stringify(result, null, 2));
- } else {
- console.log(`Goal created: ${result.nodeId} (rev ${result.rev})`);
- }
- });
-
- goal
- .command("list")
- .description("List all goals")
- .option("--format <fmt>", "Output format (text|json)", "text")
- .action(async (opts: { format: string }) => {
- const client = new IxClient(getEndpoint());
- const intents = await client.listTruth();
- formatIntents(intents, opts.format);
- });
-}
-```
-
-**Step 2: Register in main.ts**
-
-Add import:
-```typescript
-import { registerGoalCommand } from "./commands/goal.js";
-```
-
-Add registration:
-```typescript
-registerGoalCommand(program);
-```
-
-**Step 3: Verify build**
-
-```bash
-cd ix-cli && npm run build
-```
-
-**Step 4: Commit**
-
-```bash
-git add ix-cli/src/cli/commands/goal.ts ix-cli/src/cli/main.ts
-git commit -m "feat: add ix goal create/list — aliases for ix truth"
-```
-
----
-
-### Task 7: Plan graph — plan create command
-
-**Files:**
-- Create: `ix-cli/src/cli/commands/plan.ts`
-- Create: `ix-cli/src/cli/__tests__/plan-patch.test.ts`
-- Modify: `ix-cli/src/cli/main.ts`
-
-**Step 1: Write the failing test**
-
-Create `ix-cli/src/cli/__tests__/plan-patch.test.ts`:
-
-```typescript
-import { describe, it, expect } from "vitest";
-import { buildPlanPatch, buildTaskPatch, buildTaskUpdatePatch } from "../commands/plan.js";
-
-describe("buildPlanPatch", () => {
- it("creates a Plan node and GOAL_HAS_PLAN edge", () => {
- const patch = buildPlanPatch("GitHub Ingestion", "goal-id-123");
- expect(patch.ops.length).toBe(2);
- expect(patch.ops[0].type).toBe("UpsertNode");
- expect(patch.ops[0].kind).toBe("plan");
- expect(patch.ops[0].name).toBe("GitHub Ingestion");
- expect(patch.ops[1].type).toBe("UpsertEdge");
- expect(patch.ops[1].predicate).toBe("GOAL_HAS_PLAN");
- expect(patch.ops[1].src).toBe("goal-id-123");
- expect(patch.ops[1].dst).toBe(patch.ops[0].id);
- });
-});
-
-describe("buildTaskPatch", () => {
- it("creates a Task node and PLAN_HAS_TASK edge", () => {
- const patch = buildTaskPatch("Fetch GitHub API", { planId: "plan-123" });
- expect(patch.ops[0].type).toBe("UpsertNode");
- expect(patch.ops[0].kind).toBe("task");
- expect(patch.ops[0].attrs.status).toBe("pending");
- expect(patch.ops[1].predicate).toBe("PLAN_HAS_TASK");
- });
-
- it("adds DEPENDS_ON edge when dependsOn is provided", () => {
- const patch = buildTaskPatch("Transform layer", {
- planId: "plan-123",
- dependsOn: "task-abc",
- });
- expect(patch.ops.length).toBe(3); // node + PLAN_HAS_TASK + DEPENDS_ON
- expect(patch.ops[2].predicate).toBe("DEPENDS_ON");
- expect(patch.ops[2].src).toBe(patch.ops[0].id); // this task depends on...
- expect(patch.ops[2].dst).toBe("task-abc");
- });
-
- it("adds TASK_AFFECTS edges when affects is provided", () => {
- const patch = buildTaskPatch("Wire up service", {
- planId: "plan-123",
- affects: [
- { id: "entity-1", kind: "class", name: "IngestionService" },
- ],
- });
- expect(patch.ops.length).toBe(3); // node + PLAN_HAS_TASK + TASK_AFFECTS
- expect(patch.ops[2].predicate).toBe("TASK_AFFECTS");
- });
-});
-
-describe("buildTaskUpdatePatch", () => {
- it("creates an AssertClaim for status change", () => {
- const patch = buildTaskUpdatePatch("task-id-123", "done");
- expect(patch.ops.length).toBe(1);
- expect(patch.ops[0].type).toBe("AssertClaim");
- expect(patch.ops[0].field).toBe("status");
- expect(patch.ops[0].value).toBe("done");
- });
-});
-```
-
-**Step 2: Run test to verify it fails**
-
-```bash
-cd ix-cli && npx vitest run src/cli/__tests__/plan-patch.test.ts
-```
-
-Expected: FAIL — module not found.
-
-**Step 3: Implement plan.ts**
-
-Create `ix-cli/src/cli/commands/plan.ts`:
-
-```typescript
-import type { Command } from "commander";
-import { IxClient } from "../../client/api.js";
-import { getEndpoint } from "../config.js";
-import { resolveEntity } from "../resolve.js";
-import { deterministicId } from "../github/transform.js";
-import type { GraphPatchPayload, PatchOp } from "../../client/types.js";
-
-// ── Patch builders (exported for testing) ────────────────────────────────
-
-export function buildPlanPatch(title: string, goalId: string): GraphPatchPayload {
- const now = new Date().toISOString();
- const planId = deterministicId(`plan:${title}:${now}`);
- const ops: PatchOp[] = [
- {
- type: "UpsertNode",
- id: planId,
- kind: "plan",
- name: title,
- attrs: { created_at: now },
- },
- {
- type: "UpsertEdge",
- id: deterministicId(`${goalId}:GOAL_HAS_PLAN:${planId}`),
- src: goalId,
- dst: planId,
- predicate: "GOAL_HAS_PLAN",
- attrs: {},
- },
- ];
-
- return {
- patchId: planId,
- actor: "ix-cli",
- timestamp: now,
- source: {
- uri: `ix://plan/${encodeURIComponent(title)}`,
- extractor: "ix-cli:plan",
- sourceType: "Plan",
- },
- baseRev: 0,
- ops,
- replaces: [],
- };
-}
-
-interface TaskOpts {
- planId: string;
- dependsOn?: string;
- affects?: { id: string; kind: string; name: string }[];
-}
-
-export function buildTaskPatch(title: string, opts: TaskOpts): GraphPatchPayload {
- const now = new Date().toISOString();
- const taskId = deterministicId(`task:${title}:${now}`);
- const ops: PatchOp[] = [
- {
- type: "UpsertNode",
- id: taskId,
- kind: "task",
- name: title,
- attrs: { status: "pending", created_at: now },
- },
- {
- type: "UpsertEdge",
- id: deterministicId(`${opts.planId}:PLAN_HAS_TASK:${taskId}`),
- src: opts.planId,
- dst: taskId,
- predicate: "PLAN_HAS_TASK",
- attrs: {},
- },
- ];
-
- if (opts.dependsOn) {
- ops.push({
- type: "UpsertEdge",
- id: deterministicId(`${taskId}:DEPENDS_ON:${opts.dependsOn}`),
- src: taskId,
- dst: opts.dependsOn,
- predicate: "DEPENDS_ON",
- attrs: {},
- });
- }
-
- if (opts.affects) {
- for (const entity of opts.affects) {
- ops.push({
- type: "UpsertEdge",
- id: deterministicId(`${taskId}:TASK_AFFECTS:${entity.id}`),
- src: taskId,
- dst: entity.id,
- predicate: "TASK_AFFECTS",
- attrs: {},
- });
- }
- }
-
- return {
- patchId: taskId,
- actor: "ix-cli",
- timestamp: now,
- source: {
- uri: `ix://task/${encodeURIComponent(title)}`,
- extractor: "ix-cli:plan",
- sourceType: "Task",
- },
- baseRev: 0,
- ops,
- replaces: [],
- };
-}
-
-export function buildTaskUpdatePatch(taskId: string, status: string): GraphPatchPayload {
- const now = new Date().toISOString();
- return {
- patchId: deterministicId(`task-update:${taskId}:${status}:${now}`),
- actor: "ix-cli",
- timestamp: now,
- source: {
- uri: `ix://task-update/${taskId}`,
- extractor: "ix-cli:task",
- sourceType: "Task",
- },
- baseRev: 0,
- ops: [
- {
- type: "AssertClaim",
- entityId: taskId,
- field: "status",
- value: status,
- confidence: 1.0,
- },
- ],
- replaces: [],
- };
-}
-
-// ── CLI command registration ─────────────────────────────────────────────
-
-export function registerPlanCommand(program: Command): void {
- const plan = program
- .command("plan")
- .description("Manage plans and tasks");
-
- plan
- .command("create <title>")
- .description("Create a new plan linked to a goal")
- .requiredOption("--goal <id>", "Goal (intent) ID to link this plan to")
- .option("--format <fmt>", "Output format (text|json)", "text")
- .action(async (title: string, opts: { goal: string; format: string }) => {
- const client = new IxClient(getEndpoint());
- const patch = buildPlanPatch(title, opts.goal);
- const result = await client.commitPatch(patch);
- const planId = patch.ops[0].id;
- if (opts.format === "json") {
- console.log(JSON.stringify({ ...result, planId }, null, 2));
- } else {
- console.log(`Plan created: ${planId} (rev ${result.rev})`);
- }
- });
-
- plan
- .command("task <title>")
- .description("Add a task to a plan")
- .requiredOption("--plan <id>", "Plan ID to add this task to")
- .option("--depends-on <id>", "Task ID this depends on")
- .option("--affects <entities>", "Comma-separated entity names this task affects")
- .option("--format <fmt>", "Output format (text|json)", "text")
- .action(
- async (
- title: string,
- opts: {
- plan: string;
- dependsOn?: string;
- affects?: string;
- format: string;
- }
- ) => {
- const client = new IxClient(getEndpoint());
- let resolvedAffects: { id: string; kind: string; name: string }[] | undefined;
-
- if (opts.affects) {
- const names = opts.affects.split(",").map((s) => s.trim());
- resolvedAffects = [];
- for (const name of names) {
- const resolved = await resolveEntity(client, name, [
- "class", "module", "file", "function", "method", "trait", "object", "interface",
- ]);
- if (resolved) {
- resolvedAffects.push({ id: resolved.id, kind: resolved.kind, name: resolved.name });
- }
- }
- }
-
- const patch = buildTaskPatch(title, {
- planId: opts.plan,
- dependsOn: opts.dependsOn,
- affects: resolvedAffects,
- });
- const result = await client.commitPatch(patch);
- const taskId = patch.ops[0].id;
- if (opts.format === "json") {
- console.log(JSON.stringify({ ...result, taskId }, null, 2));
- } else {
- console.log(`Task created: ${taskId} (rev ${result.rev})`);
- }
- }
- );
-
- plan
- .command("status <planId>")
- .description("Show plan status — tasks, critical path, next actionable")
- .option("--format <fmt>", "Output format (text|json)", "text")
- .action(async (planId: string, opts: { format: string }) => {
- const client = new IxClient(getEndpoint());
-
- // 1. Get all tasks in this plan
- const tasksResult = await client.expand(planId, {
- direction: "out",
- predicates: ["PLAN_HAS_TASK"],
- });
- const tasks = tasksResult.nodes;
-
- // 2. For each task, get status claim and dependencies
- const taskDetails = await Promise.all(
- tasks.map(async (t: any) => {
- const [entityResult, depsResult] = await Promise.all([
- client.entity(t.id),
- client.expand(t.id, { direction: "out", predicates: ["DEPENDS_ON"] }),
- ]);
- const claims = (entityResult.claims ?? []) as any[];
- const statusClaim = claims.find((c: any) => c.field === "status" || c.statement?.includes("status"));
- const status = t.attrs?.status ?? statusClaim?.value ?? "pending";
- const deps = depsResult.nodes.map((d: any) => d.id);
- return {
- id: t.id,
- title: t.name || t.attrs?.name || "(unnamed)",
- status: String(status),
- dependsOn: deps,
- };
- })
- );
-
- // 3. Find next actionable: not done, all deps satisfied
- const doneIds = new Set(
- taskDetails.filter((t) => t.status === "done").map((t) => t.id)
- );
- const actionable = taskDetails.filter(
- (t) => t.status !== "done" && t.status !== "abandoned" && t.dependsOn.every((d) => doneIds.has(d))
- );
- const nextActionable = actionable.length > 0 ? actionable[0].title : null;
-
- // 4. Critical path: tasks with most downstream dependents
- const dependentCount = new Map<string, number>();
- for (const t of taskDetails) {
- for (const dep of t.dependsOn) {
- dependentCount.set(dep, (dependentCount.get(dep) || 0) + 1);
- }
- }
- const criticalPath = taskDetails
- .filter((t) => (dependentCount.get(t.id) || 0) > 0)
- .sort((a, b) => (dependentCount.get(b.id) || 0) - (dependentCount.get(a.id) || 0))
- .map((t) => t.title);
-
- if (opts.format === "json") {
- console.log(
- JSON.stringify(
- {
- planId,
- tasks: taskDetails.map((t) => ({ title: t.title, status: t.status, id: t.id })),
- criticalPath,
- nextActionable,
- summary: {
- total: taskDetails.length,
- done: taskDetails.filter((t) => t.status === "done").length,
- pending: taskDetails.filter((t) => t.status === "pending").length,
- inProgress: taskDetails.filter((t) => t.status === "in_progress").length,
- blocked: taskDetails.filter((t) => t.status === "blocked").length,
- },
- },
- null,
- 2
- )
- );
- } else {
- console.log(`Plan: ${planId}\n`);
- for (const t of taskDetails) {
- const icon = t.status === "done" ? "✓" : t.status === "in_progress" ? "▶" : t.status === "blocked" ? "✗" : "○";
- console.log(` ${icon} [${t.status.padEnd(11)}] ${t.title}`);
- }
- if (nextActionable) {
- console.log(`\nNext: ${nextActionable}`);
- }
- }
- });
-
- plan
- .command("next <planId>")
- .description("Show the next actionable task in a plan")
- .option("--format <fmt>", "Output format (text|json)", "text")
- .action(async (planId: string, opts: { format: string }) => {
- const client = new IxClient(getEndpoint());
-
- const tasksResult = await client.expand(planId, {
- direction: "out",
- predicates: ["PLAN_HAS_TASK"],
- });
- const tasks = tasksResult.nodes;
-
- const taskDetails = await Promise.all(
- tasks.map(async (t: any) => {
- const depsResult = await client.expand(t.id, {
- direction: "out",
- predicates: ["DEPENDS_ON"],
- });
- const status = t.attrs?.status ?? "pending";
- return {
- id: t.id,
- title: t.name || t.attrs?.name || "(unnamed)",
- status: String(status),
- dependsOn: depsResult.nodes.map((d: any) => d.id),
- };
- })
- );
-
- const doneIds = new Set(
- taskDetails.filter((t) => t.status === "done").map((t) => t.id)
- );
- const actionable = taskDetails.filter(
- (t) => t.status !== "done" && t.status !== "abandoned" && t.dependsOn.every((d) => doneIds.has(d))
- );
-
- if (actionable.length === 0) {
- if (opts.format === "json") {
- console.log(JSON.stringify({ task: null, reason: "no actionable tasks" }, null, 2));
- } else {
- console.log("No actionable tasks remaining.");
- }
- return;
- }
-
- const next = actionable[0];
- if (opts.format === "json") {
- console.log(
- JSON.stringify(
- { task: next.title, taskId: next.id, reason: "all dependencies satisfied" },
- null,
- 2
- )
- );
- } else {
- console.log(`Next: ${next.title}`);
- console.log(` ID: ${next.id}`);
- console.log(` Reason: all dependencies satisfied`);
- }
- });
-}
-
-// ── Task update command (top-level) ──────────────────────────────────────
-
-export function registerTaskCommand(program: Command): void {
- const task = program
- .command("task")
- .description("Manage tasks");
-
- task
- .command("update <taskId>")
- .description("Update task status")
- .requiredOption("--status <status>", "New status: pending, in_progress, blocked, done, abandoned")
- .option("--format <fmt>", "Output format (text|json)", "text")
- .action(async (taskId: string, opts: { status: string; format: string }) => {
- const validStatuses = ["pending", "in_progress", "blocked", "done", "abandoned"];
- if (!validStatuses.includes(opts.status)) {
- console.error(`Invalid status: ${opts.status}. Valid: ${validStatuses.join(", ")}`);
- process.exit(1);
- }
-
- const client = new IxClient(getEndpoint());
- const patch = buildTaskUpdatePatch(taskId, opts.status);
- const result = await client.commitPatch(patch);
- if (opts.format === "json") {
- console.log(JSON.stringify({ ...result, taskId, status: opts.status }, null, 2));
- } else {
- console.log(`Task ${taskId} → ${opts.status} (rev ${result.rev})`);
- }
- });
-}
-```
-
-**Step 4: Register in main.ts**
-
-Add imports:
-```typescript
-import { registerPlanCommand, registerTaskCommand } from "./commands/plan.js";
-```
-
-Add registrations:
-```typescript
-registerPlanCommand(program);
-registerTaskCommand(program);
-```
-
-**Step 5: Run tests**
-
-```bash
-cd ix-cli && npx vitest run src/cli/__tests__/plan-patch.test.ts
-```
-
-Expected: PASS (4 tests)
-
-**Step 6: Verify full build and all tests**
-
-```bash
-cd ix-cli && npm run build && npm test
-```
-
-**Step 7: Commit**
-
-```bash
-git add ix-cli/src/cli/commands/plan.ts ix-cli/src/cli/commands/goal.ts ix-cli/src/cli/__tests__/plan-patch.test.ts ix-cli/src/cli/main.ts
-git commit -m "feat: add plan graph — ix goal, ix plan, ix task commands"
-```
-
----
-
-### Task 8: Surface tasks in ix overview
-
-**Files:**
-- Modify: `ix-cli/src/cli/commands/overview.ts`
-
-**Step 1: Add tasks field to OverviewResult**
-
-Add to `OverviewResult` interface (after `decisions`):
-```typescript
- tasks: { id: string; title: string; status: string }[];
-```
-
-**Step 2: Fetch TASK_AFFECTS edges in both container and callable paths**
-
-Add to both `Promise.all` arrays:
-```typescript
- client.expand(target.id, { direction: "in", predicates: ["TASK_AFFECTS"] }),
-```
-
-Map the results:
-```typescript
- const tasks = tasksResult.nodes.map((n: any) => ({
- id: n.id,
- title: n.name || n.attrs?.name || "(unnamed)",
- status: n.attrs?.status ?? "pending",
- }));
-```
-
-Add to text output:
-```typescript
- if (tasks.length > 0) {
- console.log(`\nTasks:`);
- for (const t of tasks) {
- const icon = t.status === "done" ? "✓" : "○";
- console.log(` ${icon} [${t.status}] ${t.title}`);
- }
- }
-```
-
-**Step 3: Verify build and tests**
-
-```bash
-cd ix-cli && npm run build && npm test
-```
-
-**Step 4: Commit**
-
-```bash
-git add ix-cli/src/cli/commands/overview.ts
-git commit -m "feat: surface linked tasks in ix overview output"
-```
-
----
-
-### Task 9: Update documentation
-
-**Files:**
-- Modify: `AGENTS.md`
-- Modify: `CLAUDE.md`
-- Modify: `README.md`
-- Modify: `ix-cli/src/cli/commands/init.ts` (CLAUDE.md template)
-
-**Step 1: Update AGENTS.md**
-
-Remove all MCP references. Add plan/decision commands to routing:
-
-Add to the "Start here" section:
-```
-ix goal create <statement> --format json # Create a project goal
-ix plan create <title> --goal <id> --format json # Create a plan
-ix plan next <plan-id> --format json # Next actionable task
-ix decide <title> --rationale <text> --affects <entities> --format json # Record linked decision
-```
-
-Add a new "Planning & Decisions" section:
-```
-### Planning & decisions
-ix goal create "GitHub ingestion pipeline" --format json
-ix plan create "GitHub Ingestion" --goal <goal-id> --format json
-ix plan task "API fetch layer" --plan <plan-id> --depends-on <task-id> --format json
-ix plan status <plan-id> --format json
-ix plan next <plan-id> --format json
-ix task update <task-id> --status done --format json
-ix decide "Use client-side patch" --rationale "..." --affects IngestionService --format json
-```
-
-Remove MCP references from all sections.
-
-**Step 2: Update CLAUDE.md**
-
-Add to the "High-Level Workflow Commands" table:
-```
-| Plan work | `ix plan` | `ix plan next <plan-id> --format json` |
-| Track decisions | `ix decide` | `ix decide "Use X" --rationale "..." --affects Entity` |
-| Create goals | `ix goal` | `ix goal create "Support GitHub" --format json` |
-```
-
-Remove all MCP references. Remove the "Do NOT Use" line about MCP tools.
-
-**Step 3: Update README.md**
-
-Add Plan & Task commands to the CLI Commands section:
-
-```markdown
-### Planning & Tasks
-
-| Command | Usage | Description |
-|---------|-------|-------------|
-| `ix goal create` | `ix goal create <statement>` | Create a project goal |
-| `ix goal list` | `ix goal list` | List all goals |
-| `ix plan create` | `ix plan create <title> --goal <id>` | Create a plan linked to a goal |
-| `ix plan task` | `ix plan task <title> --plan <id>` | Add a task to a plan |
-| `ix plan status` | `ix plan status <plan-id>` | Show plan progress and next task |
-| `ix plan next` | `ix plan next <plan-id>` | Get the next actionable task |
-| `ix task update` | `ix task update <id> --status done` | Update task status |
-```
-
-Remove all MCP sections from README.
-
-**Step 4: Update init.ts CLAUDE.md template**
-
-Update the `IX_CLAUDE_MD_BLOCK` in `init.ts` to include the plan/decision commands and remove MCP references. Match the updated CLAUDE.md content.
-
-**Step 5: Verify build**
-
-```bash
-cd ix-cli && npm run build && npm test
-```
-
-**Step 6: Commit**
-
-```bash
-git add AGENTS.md CLAUDE.md README.md ix-cli/src/cli/commands/init.ts
-git commit -m "docs: update all docs for plan graph, decision linking, remove MCP"
-```
-
----
-
-Plan complete and saved to `docs/plans/2026-03-08-plan-graph-decision-linking-plan.md`. Two execution options:
-
-**1. Subagent-Driven (this session)** — I dispatch fresh subagent per task, review between tasks, fast iteration
-
-**2. Parallel Session (separate)** — Open new session with executing-plans, batch execution with checkpoints
-
-Which approach?
\ No newline at end of file
diff --git a/docs/plans/2026-03-08-stabilize-optimize-design.md b/docs/plans/2026-03-08-stabilize-optimize-design.md
deleted file mode 100644
index 90b7b9c1..00000000
--- a/docs/plans/2026-03-08-stabilize-optimize-design.md
+++ /dev/null
@@ -1,38 +0,0 @@
-# Stabilize and Optimize Existing Ix Workflows — Design
-
-**Goal:** Fix broken high-level commands, make JSON mode fully strict, improve defaults for agent safety.
-
-**Scope:** Backend list endpoint, rank/inventory fixes, JSON audit, safer search defaults, doc updates. Diff optimization and callers fallback changes deferred — both already work.
-
----
-
-## 1. Fix rank and inventory
-
-**Root cause:** Both commands use `client.search("", { kind })` which matches everything in ArangoDB (CONTAINS with empty string returns true for all values). The backend already has `findNodesByKind()` but no REST route exposes it.
-
-**Backend change:** Add `POST /v1/list` route exposing `findNodesByKind()`. Request: `{ kind: string, limit?: number }`. Response: array of GraphNode. ~30 lines of Scala.
-
-**CLI client:** Add `IxClient.listByKind(kind, opts?)` method calling `POST /v1/list`.
-
-**inventory.ts:** Replace `client.search("")` with `client.listByKind()`. Add client-side path filtering on provenance source_uri.
-
-**rank.ts:** Same replacement. Ranking logic stays the same.
-
-## 2. Strict JSON cleanup
-
-**Already done:** `resolve.ts` routes all diagnostics to stderr (previous patch Task 2).
-
-**Remaining:** Audit all command files for unguarded `console.log` calls that leak to stdout in JSON mode. Fix any found to use `stderr()` or format guards. Remove stray `console.log("CLI depth:")` in api.ts.
-
-## 3. Safer search defaults
-
-Lower default search limit from 20 to 10. Add `unfiltered_search` diagnostic when no `--kind` filter used.
-
-## 4. Doc updates
-
-Update AGENTS.md, CLAUDE.md to reflect working rank/inventory, emphasize `--kind` on search, keep high-level commands as preferred entry points.
-
-## Deferred
-
-- Diff server-side summary optimization — current client-side summary works
-- Callers fallback tightening — already bounded (10 matches max)
diff --git a/docs/plans/2026-03-08-stabilize-optimize-plan.md b/docs/plans/2026-03-08-stabilize-optimize-plan.md
deleted file mode 100644
index e65b7b81..00000000
--- a/docs/plans/2026-03-08-stabilize-optimize-plan.md
+++ /dev/null
@@ -1,329 +0,0 @@
-# Stabilize and Optimize Existing Ix Workflows — Implementation Plan
-
-> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
-
-**Goal:** Fix broken rank/inventory commands, make JSON mode fully strict, improve search defaults for agent safety.
-
-**Architecture:** Add a `POST /v1/list` backend route exposing the existing `findNodesByKind()` method. Add `listByKind()` to the CLI client. Rewire rank and inventory to use it. Audit and fix JSON stdout leaks. Tighten search defaults.
-
-**Tech Stack:** Scala (backend route), TypeScript (CLI), vitest
-
----
-
-### Task 1: Add POST /v1/list backend route
-
-**Files:**
-- Create: `memory-layer/src/main/scala/ix/memory/api/ListRoutes.scala`
-- Modify: `memory-layer/src/main/scala/ix/memory/api/Routes.scala`
-
-**Step 1: Create ListRoutes.scala**
-
-Create `memory-layer/src/main/scala/ix/memory/api/ListRoutes.scala`:
-
-```scala
-package ix.memory.api
-
-import cats.effect.IO
-import io.circe.Decoder
-import io.circe.generic.semiauto.deriveDecoder
-import io.circe.syntax._
-import org.http4s.HttpRoutes
-import org.http4s.circe.CirceEntityCodec._
-import org.http4s.dsl.io._
-
-import ix.memory.db.GraphQueryApi
-import ix.memory.model._
-
-case class ListRequest(
- kind: String,
- limit: Option[Int] = None
-)
-
-object ListRequest {
- implicit val decoder: Decoder[ListRequest] = deriveDecoder[ListRequest]
-}
-
-class ListRoutes(queryApi: GraphQueryApi) {
-
- val routes: HttpRoutes[IO] = HttpRoutes.of[IO] {
- case req @ POST -> Root / "v1" / "list" =>
- (for {
- body <- req.as[ListRequest]
- kind <- IO.fromEither(
- NodeKind.decoder.decodeJson(io.circe.Json.fromString(body.kind))
- .left.map(e => new IllegalArgumentException(s"Unknown kind: ${body.kind}"))
- )
- nodes <- queryApi.findNodesByKind(kind, body.limit.getOrElse(200))
- resp <- Ok(nodes.asJson)
- } yield resp).handleErrorWith(ErrorHandler.handle(_))
- }
-}
-```
-
-**Step 2: Wire into Routes.scala**
-
-In `memory-layer/src/main/scala/ix/memory/api/Routes.scala`:
-
-Add after `val patchCommitRoutes` (line 45):
-```scala
- val listRoutes = new ListRoutes(queryApi).routes
-```
-
-Add `listRoutes` to the combinator chain on lines 47-50:
-```scala
- health <+> contextRoutes <+> ingestionRoutes <+> entityRoutes <+>
- diffRoutes <+> conflictRoutes <+> decideRoutes <+> searchRoutes <+>
- truthRoutes <+> patchRoutes <+> decisionListRoutes <+> expandRoutes <+>
- statsRoutes <+> patchCommitRoutes <+> listRoutes
-```
-
-**Step 3: Verify backend compiles**
-
-```bash
-cd memory-layer && sbt compile
-```
-
-**Step 4: Commit**
-
-```bash
-git add memory-layer/src/main/scala/ix/memory/api/ListRoutes.scala memory-layer/src/main/scala/ix/memory/api/Routes.scala
-git commit -m "feat: add POST /v1/list endpoint — list entities by kind"
-```
-
----
-
-### Task 2: Add listByKind to CLI client
-
-**Files:**
-- Modify: `ix-cli/src/client/api.ts`
-
-**Step 1: Add listByKind method**
-
-In `ix-cli/src/client/api.ts`, add after the `search` method (after line 56):
-
-```typescript
- async listByKind(
- kind: string,
- opts?: { limit?: number }
- ): Promise<GraphNode[]> {
- return this.post("/v1/list", {
- kind,
- limit: opts?.limit,
- });
- }
-```
-
-**Step 2: Remove stray console.log**
-
-In `ix-cli/src/client/api.ts` line 19, remove:
-```typescript
- console.log("CLI depth:", opts?.depth);
-```
-
-**Step 3: Verify build**
-
-```bash
-cd ix-cli && npm run build && npm test
-```
-
-**Step 4: Commit**
-
-```bash
-git add ix-cli/src/client/api.ts
-git commit -m "feat: add listByKind client method, remove stray console.log"
-```
-
----
-
-### Task 3: Fix inventory to use listByKind
-
-**Files:**
-- Modify: `ix-cli/src/cli/commands/inventory.ts`
-
-**Step 1: Replace search("") with listByKind**
-
-In `ix-cli/src/cli/commands/inventory.ts`, replace lines 27-30:
-
-```typescript
- // OLD:
- let nodes = await client.search("", {
- limit,
- kind: opts.kind,
- });
-```
-
-With:
-
-```typescript
- let nodes = await client.listByKind(opts.kind, { limit });
-```
-
-No other changes needed — the rest of the command (path filtering, JSON output, text output) stays the same.
-
-**Step 2: Verify build**
-
-```bash
-cd ix-cli && npm run build && npm test
-```
-
-**Step 3: Commit**
-
-```bash
-git add ix-cli/src/cli/commands/inventory.ts
-git commit -m "fix: inventory uses listByKind instead of empty-string search"
-```
-
----
-
-### Task 4: Fix rank to use listByKind
-
-**Files:**
-- Modify: `ix-cli/src/cli/commands/rank.ts`
-
-**Step 1: Replace search("") with listByKind**
-
-In `ix-cli/src/cli/commands/rank.ts`, replace line 58:
-
-```typescript
- // OLD:
- const allNodes = await client.search("", { limit: 200, kind: opts.kind });
-```
-
-With:
-
-```typescript
- const allNodes = await client.listByKind(opts.kind, { limit: 200 });
-```
-
-No other changes needed.
-
-**Step 2: Verify build**
-
-```bash
-cd ix-cli && npm run build && npm test
-```
-
-**Step 3: Commit**
-
-```bash
-git add ix-cli/src/cli/commands/rank.ts
-git commit -m "fix: rank uses listByKind instead of empty-string search"
-```
-
----
-
-### Task 5: Tighten search defaults
-
-**Files:**
-- Modify: `ix-cli/src/cli/commands/search.ts`
-
-**Step 1: Lower default limit and add unfiltered warning**
-
-In `ix-cli/src/cli/commands/search.ts`:
-
-Change line 10 default limit from "20" to "10":
-```typescript
- .option("--limit <n>", "Max results", "10")
-```
-
-After the `formatNodes(nodes, opts.format)` call (line 26), add a diagnostic when format is JSON and no kind filter:
-
-Replace lines 20-27 with:
-
-```typescript
- const client = new IxClient(getEndpoint());
- const limit = parseInt(opts.limit, 10);
- const nodes = await client.search(term, {
- limit,
- kind: opts.kind,
- language: opts.language,
- asOfRev: opts.asOf ? parseInt(opts.asOf, 10) : undefined,
- });
-
- if (opts.format === "json") {
- const diagnostics: { code: string; message: string }[] = [];
- if (!opts.kind) {
- diagnostics.push({
- code: "unfiltered_search",
- message: "Results may be broad. Use --kind to filter.",
- });
- }
- console.log(JSON.stringify({
- results: nodes.map((n) => ({
- id: n.id,
- name: n.name || (n.attrs as any)?.name || "(unnamed)",
- kind: n.kind,
- path: n.provenance?.sourceUri ?? undefined,
- })),
- summary: { count: nodes.length },
- diagnostics,
- }, null, 2));
- } else {
- formatNodes(nodes, opts.format);
- }
-```
-
-Add the import for formatNodes stays as-is.
-
-**Step 2: Verify build and tests**
-
-```bash
-cd ix-cli && npm run build && npm test
-```
-
-**Step 3: Commit**
-
-```bash
-git add ix-cli/src/cli/commands/search.ts
-git commit -m "feat: tighten search defaults — lower limit, add unfiltered_search diagnostic"
-```
-
----
-
-### Task 6: Update documentation
-
-**Files:**
-- Modify: `AGENTS.md`
-- Modify: `CLAUDE.md`
-- Modify: `README.md`
-
-**Step 1: Update AGENTS.md**
-
-In the "Start here — high-level workflow commands" section, ensure rank and inventory are listed with notes that they now work properly.
-
-Add to the "When to use which" section:
-```
-- "List all classes" → `ix inventory --kind class`
-- "What are the most critical methods?" → `ix rank --by callers --kind method --top 10`
-```
-
-In the low-level primitives section, add a note to search:
-```
-# Always use --kind with search to get bounded results
-ix search <term> --kind <kind> --format json --limit 10
-```
-
-**Step 2: Update CLAUDE.md**
-
-In the "Best Practices" section, add:
-```
-- Always use `--kind` with `ix search` to get bounded results
-- Use `ix inventory` instead of `ix search ""` for listing entities by kind
-```
-
-**Step 3: Update README.md**
-
-Ensure the Core Usage section mentions `--kind` with search examples.
-
-**Step 4: Verify build**
-
-```bash
-cd ix-cli && npm run build && npm test
-```
-
-**Step 5: Commit**
-
-```bash
-git add AGENTS.md CLAUDE.md README.md
-git commit -m "docs: update docs for stabilization — rank/inventory working, search best practices"
-```
diff --git a/docs/plans/2026-03-08-stabilize-phase2-design.md b/docs/plans/2026-03-08-stabilize-phase2-design.md
deleted file mode 100644
index 1e8b8a6a..00000000
--- a/docs/plans/2026-03-08-stabilize-phase2-design.md
+++ /dev/null
@@ -1,52 +0,0 @@
-# Stabilize and Optimize Phase 2 — Design
-
-**Goal:** Complete the remaining stabilization work: optimize diff, bound fallback output, fix remaining JSON leaks.
-
-**Scope:** Backend diff summary + limit, CLI diff flags, callers/locate fallback capping, JSON audit fixes. Entity --summary deferred — YAGNI.
-
----
-
-## 1. Diff Optimization
-
-**Problem:** `--summary` is purely client-side. Backend always returns full `DiffResponse` with complete `GraphNode` objects at both revisions. Broad diffs produce MB-scale payloads.
-
-**Backend change:** Add `summary: Option[Boolean]` and `limit: Option[Int]` to `DiffRequest`.
-
-When `summary = true`, run a lightweight AQL counting query that groups changes by type (`added`/`modified`/`removed`) without hydrating full nodes. Return counts only.
-
-When `limit` is set (default 100), return at most N `DiffEntry` records plus `truncated: true` and `totalChanges: Int` metadata.
-
-**Summary AQL:** Single query that collects logical IDs changed between revisions, determines change type via subqueries, then aggregates counts by type — no full node hydration.
-
-**CLI changes:**
-- Pass `summary` and `limit` to client
-- Default broad diff: limit 100 changes, include truncation metadata
-- `--full` flag overrides limit (sets to max)
-- `--limit <n>` for explicit control
-- `--summary` triggers backend summary mode
-
-## 2. Bound Fallback Behavior
-
-**Problem:** callers text fallback has `--max-count 10` per file in ripgrep but JSON mode doesn't cap total results across files.
-
-**Fix:** Hard-cap fallback results to 10 total in all modes. Add `candidatesFound` vs `candidatesReturned` to summary so agents know there were more.
-
-**Commands affected:**
-- `callers.ts` — cap ripgrep results to 10, restructure fallback output
-- `locate.ts` — cap ripgrep matches to 10 before merging with graph results
-
-**Not affected:** callees, depends, imports, imported-by, contains — all graph-only, no fallback.
-
-## 3. JSON Audit Fixes
-
-**Remaining leaks (minor):**
-- `callers.ts` line 67 — warning `console.log` not format-guarded → use `stderr()` + guard
-- `query.ts` — deprecation warning prints to stdout unconditionally → move to `stderr()`
-- `read.ts` — `console.error()` → `stderr()` for consistency
-- `text.ts` — `console.error()` → `stderr()` for consistency
-
-**Not changed:** `init.ts` — interactive setup command, not used in JSON pipelines.
-
-## Deferred
-
-- Entity `--summary` flag — YAGNI, entity is intentionally detailed as a low-level primitive
diff --git a/docs/plans/2026-03-08-stabilize-phase2-plan.md b/docs/plans/2026-03-08-stabilize-phase2-plan.md
deleted file mode 100644
index 8abf4256..00000000
--- a/docs/plans/2026-03-08-stabilize-phase2-plan.md
+++ /dev/null
@@ -1,629 +0,0 @@
-# Stabilize Phase 2 — Implementation Plan
-
-> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
-
-**Goal:** Optimize diff with server-side summary + bounded defaults, cap fallback output, fix remaining JSON stdout leaks.
-
-**Architecture:** Add `getDiffSummary()` to backend trait + ArangoDB implementation. Extend `DiffRequest` with `summary` and `limit` fields. Cap callers/locate text fallback to 10 results. Fix 4 CLI files with stdout leaks.
-
-**Tech Stack:** Scala (backend), TypeScript (CLI), vitest
-
----
-
-### Task 1: Add getDiffSummary to backend
-
-**Files:**
-- Modify: `memory-layer/src/main/scala/ix/memory/db/GraphQueryApi.scala`
-- Modify: `memory-layer/src/main/scala/ix/memory/db/ArangoGraphQueryApi.scala`
-
-**Step 1: Add trait method**
-
-In `memory-layer/src/main/scala/ix/memory/db/GraphQueryApi.scala`, add after `getChangedEntities` (line 21):
-
-```scala
- def getDiffSummary(fromRev: Rev, toRev: Rev): IO[Map[String, Int]]
-```
-
-**Step 2: Implement in ArangoGraphQueryApi**
-
-In `memory-layer/src/main/scala/ix/memory/db/ArangoGraphQueryApi.scala`, add after the `getChangedEntities` method (after line 306):
-
-```scala
- override def getDiffSummary(fromRev: Rev, toRev: Rev): IO[Map[String, Int]] = {
- val aql = """
- FOR n IN nodes
- FILTER n.created_rev > @fromRev AND n.created_rev <= @toRev
- COLLECT logicalId = n.logical_id
- LET atFrom = FIRST(
- FOR x IN nodes
- FILTER x.logical_id == logicalId
- AND x.created_rev <= @fromRev
- AND (x.deleted_rev == null OR @fromRev < x.deleted_rev)
- RETURN x
- )
- LET atTo = FIRST(
- FOR x IN nodes
- FILTER x.logical_id == logicalId
- AND x.created_rev <= @toRev
- AND (x.deleted_rev == null OR @toRev < x.deleted_rev)
- RETURN x
- )
- LET changeType = (atFrom == null ? "added" : (atTo.deleted_rev != null ? "removed" : "modified"))
- COLLECT type = changeType WITH COUNT INTO cnt
- RETURN { type: type, cnt: cnt }
- """
- client.query(aql, Map(
- "fromRev" -> Long.box(fromRev.value).asInstanceOf[AnyRef],
- "toRev" -> Long.box(toRev.value).asInstanceOf[AnyRef]
- )).map { results =>
- results.flatMap { json =>
- for {
- t <- json.hcursor.downField("type").as[String].toOption
- c <- json.hcursor.downField("cnt").as[Int].toOption
- } yield t -> c
- }.toMap
- }
- }
-```
-
-**Step 3: Verify backend compiles**
-
-```bash
-cd memory-layer && sbt compile
-```
-
-**Step 4: Commit**
-
-```bash
-git add memory-layer/src/main/scala/ix/memory/db/GraphQueryApi.scala memory-layer/src/main/scala/ix/memory/db/ArangoGraphQueryApi.scala
-git commit -m "feat: add getDiffSummary — server-side diff counting without full hydration"
-```
-
----
-
-### Task 2: Extend DiffRoutes with summary and limit support
-
-**Files:**
-- Modify: `memory-layer/src/main/scala/ix/memory/api/DiffRoutes.scala`
-
-**Step 1: Add fields to DiffRequest**
-
-Replace the `DiffRequest` case class (line 15):
-
-```scala
-case class DiffRequest(
- fromRev: Long,
- toRev: Long,
- entityId: Option[String] = None,
- summary: Option[Boolean] = None,
- limit: Option[Int] = None
-)
-```
-
-**Step 2: Add DiffSummaryResponse**
-
-Add after `DiffResponse` (after line 38):
-
-```scala
-case class DiffSummaryResponse(
- fromRev: Long,
- toRev: Long,
- summary: Map[String, Int],
- total: Int
-)
-
-object DiffSummaryResponse {
- implicit val encoder: Encoder[DiffSummaryResponse] = deriveEncoder[DiffSummaryResponse]
-}
-```
-
-**Step 3: Add summary branch to route handler**
-
-Replace the route handler body (lines 44-76) with:
-
-```scala
- val routes: HttpRoutes[IO] = HttpRoutes.of[IO] {
- case req @ POST -> Root / "v1" / "diff" =>
- (for {
- body <- req.as[DiffRequest]
- _ <- IO.raiseWhen(body.fromRev >= body.toRev)(
- new IllegalArgumentException("fromRev must be less than toRev")
- )
- resp <- if (body.summary.getOrElse(false)) {
- // Server-side summary: counts only, no node hydration
- queryApi.getDiffSummary(Rev(body.fromRev), Rev(body.toRev)).flatMap { counts =>
- val total = counts.values.sum
- Ok(DiffSummaryResponse(body.fromRev, body.toRev, counts, total))
- }
- } else {
- val effectiveLimit = body.limit.getOrElse(100)
- body.entityId match {
- case Some(eidStr) =>
- for {
- eid <- IO.fromTry(scala.util.Try(UUID.fromString(eidStr))).map(NodeId(_))
- result <- diffEntity(eid, Rev(body.fromRev), Rev(body.toRev))
- } yield result.toVector
- case None =>
- queryApi.getChangedEntities(Rev(body.fromRev), Rev(body.toRev)).map { pairs =>
- pairs.map { case (atTo, atFromOpt) =>
- val changeType = if (atFromOpt.isEmpty) "added"
- else if (atTo.deletedRev.isDefined) "removed"
- else "modified"
- val summary = atFromOpt.map { atFrom =>
- diffAttrs(atFrom.attrs, atTo.attrs)
- }
- DiffEntry(
- entityId = atTo.id,
- changeType = changeType,
- atFromRev = atFromOpt,
- atToRev = Some(atTo),
- summary = summary.filter(_.nonEmpty)
- )
- }
- }
- }
- }.flatMap {
- case resp: IO[org.http4s.Response[IO]] @unchecked => resp
- case changes: Vector[DiffEntry] @unchecked =>
- val effectiveLimit = body.limit.getOrElse(100)
- val totalChanges = changes.size
- val truncated = totalChanges > effectiveLimit
- val limited = if (truncated) changes.take(effectiveLimit) else changes
- Ok(DiffResponse(body.fromRev, body.toRev, limited, truncated, totalChanges))
- }
- } yield resp).handleErrorWith(ErrorHandler.handle(_))
- }
-```
-
-Actually, let me simplify. The branching is cleaner as two separate paths:
-
-Replace the entire route handler (lines 42-77) with:
-
-```scala
- val routes: HttpRoutes[IO] = HttpRoutes.of[IO] {
- case req @ POST -> Root / "v1" / "diff" =>
- (for {
- body <- req.as[DiffRequest]
- _ <- IO.raiseWhen(body.fromRev >= body.toRev)(
- new IllegalArgumentException("fromRev must be less than toRev")
- )
- resp <- if (body.summary.getOrElse(false)) {
- // Summary mode: server-side counting, no node hydration
- for {
- counts <- queryApi.getDiffSummary(Rev(body.fromRev), Rev(body.toRev))
- r <- Ok(DiffSummaryResponse(body.fromRev, body.toRev, counts, counts.values.sum))
- } yield r
- } else {
- // Full diff mode with optional limit
- val effectiveLimit = body.limit.getOrElse(100)
- val changesIO = body.entityId match {
- case Some(eidStr) =>
- for {
- eid <- IO.fromTry(scala.util.Try(UUID.fromString(eidStr))).map(NodeId(_))
- result <- diffEntity(eid, Rev(body.fromRev), Rev(body.toRev))
- } yield result.toVector
- case None =>
- queryApi.getChangedEntities(Rev(body.fromRev), Rev(body.toRev)).map { pairs =>
- pairs.map { case (atTo, atFromOpt) =>
- val changeType = if (atFromOpt.isEmpty) "added"
- else if (atTo.deletedRev.isDefined) "removed"
- else "modified"
- val attrSummary = atFromOpt.map { atFrom =>
- diffAttrs(atFrom.attrs, atTo.attrs)
- }
- DiffEntry(
- entityId = atTo.id,
- changeType = changeType,
- atFromRev = atFromOpt,
- atToRev = Some(atTo),
- summary = attrSummary.filter(_.nonEmpty)
- )
- }
- }
- }
- for {
- allChanges <- changesIO
- totalCount = allChanges.size
- truncated = totalCount > effectiveLimit
- limited = if (truncated) allChanges.take(effectiveLimit) else allChanges
- r <- Ok(DiffResponse(body.fromRev, body.toRev, limited, truncated, totalCount))
- } yield r
- }
- } yield resp).handleErrorWith(ErrorHandler.handle(_))
- }
-```
-
-**Step 4: Update DiffResponse to include truncation metadata**
-
-Replace the `DiffResponse` case class (line 34):
-
-```scala
-case class DiffResponse(
- fromRev: Long,
- toRev: Long,
- changes: Vector[DiffEntry],
- truncated: Boolean,
- totalChanges: Int
-)
-```
-
-**Step 5: Verify backend compiles**
-
-```bash
-cd memory-layer && sbt compile
-```
-
-**Step 6: Commit**
-
-```bash
-git add memory-layer/src/main/scala/ix/memory/api/DiffRoutes.scala
-git commit -m "feat: diff supports server-side summary and limit with truncation metadata"
-```
-
----
-
-### Task 3: Update CLI diff client and command
-
-**Files:**
-- Modify: `ix-cli/src/client/api.ts`
-- Modify: `ix-cli/src/cli/commands/diff.ts`
-
-**Step 1: Update client diff method**
-
-In `ix-cli/src/client/api.ts`, replace the `diff` method (lines 139-145):
-
-```typescript
- async diff(
- fromRev: number,
- toRev: number,
- opts?: { entityId?: string; summary?: boolean; limit?: number }
- ): Promise<unknown> {
- return this.post("/v1/diff", {
- fromRev,
- toRev,
- entityId: opts?.entityId,
- summary: opts?.summary,
- limit: opts?.limit,
- });
- }
-```
-
-**Step 2: Rewrite diff command**
-
-Replace the entire contents of `ix-cli/src/cli/commands/diff.ts`:
-
-```typescript
-import type { Command } from "commander";
-import chalk from "chalk";
-import { IxClient } from "../../client/api.js";
-import { getEndpoint } from "../config.js";
-import { formatDiff } from "../format.js";
-
-export function registerDiffCommand(program: Command): void {
- program
- .command("diff <fromRev> <toRev>")
- .description("Show diff between two revisions")
- .option("--entity <id>", "Filter by entity ID")
- .option("--summary", "Show compact summary only (server-side, fast)")
- .option("--limit <n>", "Max changes to return (default 100)")
- .option("--full", "Return all changes (no limit)")
- .option("--format <fmt>", "Output format (text|json)", "text")
- .action(async (fromRev: string, toRev: string, opts: {
- entity?: string; summary?: boolean; limit?: string; full?: boolean; format: string;
- }) => {
- const client = new IxClient(getEndpoint());
- const from = parseInt(fromRev, 10);
- const to = parseInt(toRev, 10);
-
- if (opts.summary) {
- // Server-side summary — no full payload
- const result: any = await client.diff(from, to, { summary: true });
-
- if (opts.format === "json") {
- console.log(JSON.stringify(result, null, 2));
- } else {
- const s = result.summary || {};
- console.log(chalk.cyan.bold(`\nDiff: rev ${result.fromRev} → ${result.toRev}`));
- if (s.added) console.log(` ${chalk.green("Added:")} ${s.added}`);
- if (s.modified) console.log(` ${chalk.yellow("Modified:")} ${s.modified}`);
- if (s.removed) console.log(` ${chalk.red("Removed:")} ${s.removed}`);
- if (!s.added && !s.modified && !s.removed) console.log(chalk.dim(" No changes."));
- console.log(` ${chalk.dim("Total:")} ${result.total}`);
- console.log();
- }
- return;
- }
-
- // Full diff mode
- const limit = opts.full ? undefined : (opts.limit ? parseInt(opts.limit, 10) : undefined);
- const result: any = await client.diff(from, to, {
- entityId: opts.entity,
- limit,
- });
-
- if (opts.format === "json") {
- console.log(JSON.stringify(result, null, 2));
- } else {
- if (result.truncated) {
- console.log(chalk.yellow(`Showing ${result.changes.length} of ${result.totalChanges} changes. Use --full to see all.\n`));
- }
- formatDiff(result, "text");
- }
- });
-}
-```
-
-**Step 3: Verify build and tests**
-
-```bash
-cd ix-cli && npm run build && npm test
-```
-
-**Step 4: Commit**
-
-```bash
-git add ix-cli/src/client/api.ts ix-cli/src/cli/commands/diff.ts
-git commit -m "feat: CLI diff supports --summary (server-side), --limit, --full flags"
-```
-
----
-
-### Task 4: Cap callers text fallback to 10 results
-
-**Files:**
-- Modify: `ix-cli/src/cli/commands/callers.ts`
-
-**Step 1: Add stderr import and cap fallback results**
-
-Replace the entire text fallback block in `ix-cli/src/cli/commands/callers.ts` (lines 33-81):
-
-```typescript
- if (result.nodes.length === 0) {
- // Fallback to text search
- try {
- const root = resolveWorkspaceRoot();
- const { stdout } = await execFileAsync("rg", [
- "--json", "--max-count", "10", target.name, root,
- ], { maxBuffer: 5 * 1024 * 1024 });
-
- const allTextResults: any[] = [];
- for (const line of stdout.split("\n")) {
- if (!line.trim()) continue;
- try {
- const parsed = JSON.parse(line);
- if (parsed.type === "match") {
- const data = parsed.data;
- allTextResults.push({
- id: "",
- kind: "text-match",
- name: `${data.path?.text ?? ""}:${data.line_number ?? 0}`,
- resolved: false,
- path: data.path?.text ?? "",
- line: data.line_number ?? 0,
- attrs: { snippet: data.lines?.text?.trim() ?? "" },
- });
- }
- } catch { /* skip malformed lines */ }
- }
-
- const candidatesFound = allTextResults.length;
- const textResults = allTextResults.slice(0, 10);
-
- if (textResults.length > 0) {
- if (opts.format === "json") {
- console.log(JSON.stringify({
- results: textResults,
- resultSource: "text",
- resolvedTarget: target,
- summary: {
- candidatesFound,
- candidatesReturned: textResults.length,
- },
- diagnostics: [{
- code: "text_fallback_used",
- message: "No graph-backed callers found; showing bounded lexical candidates.",
- }],
- }, null, 2));
- } else {
- stderr(chalk.dim("No graph-backed callers found. Showing text-based candidate usages.\n"));
- for (const r of textResults) {
- const snippet = r.attrs?.snippet ?? "";
- console.log(` ${chalk.dim(r.name)} ${snippet}`);
- }
- if (candidatesFound > 10) {
- stderr(chalk.dim(`\n (${candidatesFound} total candidates; showing 10)`));
- }
- }
- return;
- }
- } catch { /* ripgrep not available or no matches */ }
-
- // Both graph and text empty
- formatEdgeResults([], "callers", target.name, opts.format, target, "graph");
- } else {
- formatEdgeResults(result.nodes.slice(0, limit), "callers", target.name, opts.format, target, "graph");
- }
-```
-
-**Step 2: Add stderr import**
-
-At the top of `ix-cli/src/cli/commands/callers.ts`, add to the imports (after line 8):
-
-```typescript
-import { stderr } from "../stderr.js";
-```
-
-**Step 3: Verify build and tests**
-
-```bash
-cd ix-cli && npm run build && npm test
-```
-
-**Step 4: Commit**
-
-```bash
-git add ix-cli/src/cli/commands/callers.ts
-git commit -m "fix: cap callers text fallback to 10 results, route warning to stderr"
-```
-
----
-
-### Task 5: Cap locate text results to 10
-
-**Files:**
-- Modify: `ix-cli/src/cli/commands/locate.ts`
-
-**Step 1: Cap ripgrep results before merging**
-
-In `ix-cli/src/cli/commands/locate.ts`, after the ripgrep parsing loop (after line 49, before the "Build results" comment), add:
-
-```typescript
- // Cap text hits to prevent oversized output
- textHits = textHits.slice(0, 10);
-```
-
-**Step 2: Verify build and tests**
-
-```bash
-cd ix-cli && npm run build && npm test
-```
-
-**Step 3: Commit**
-
-```bash
-git add ix-cli/src/cli/commands/locate.ts
-git commit -m "fix: cap locate text results to 10 to prevent oversized output"
-```
-
----
-
-### Task 6: Fix remaining JSON stdout leaks
-
-**Files:**
-- Modify: `ix-cli/src/cli/commands/query.ts`
-- Modify: `ix-cli/src/cli/commands/read.ts`
-- Modify: `ix-cli/src/cli/commands/text.ts`
-
-**Step 1: Fix query.ts — route deprecation to stderr**
-
-Replace all `console.log` calls in the deprecation block (lines 15-34) of `ix-cli/src/cli/commands/query.ts`:
-
-```typescript
-import { stderr } from "../stderr.js";
-```
-
-Add import at top. Then replace lines 15-34:
-
-```typescript
- stderr("\n\u26a0 ix query is DEPRECATED \u2014 broad NLP-style graph queries produce oversized, low-signal responses.");
- stderr(" Decompose your question into targeted commands instead:\n");
- stderr(" ix search <term> Find entities by name/kind");
- stderr(" ix explain <symbol> Structure, container, history, calls");
- stderr(" ix callers <symbol> What calls a function (cross-file)");
- stderr(" ix callees <symbol> What a function calls");
- stderr(" ix contains <symbol> Members of a class/module");
- stderr(" ix imports <symbol> What an entity imports");
- stderr(" ix imported-by <symbol> What imports an entity");
- stderr(" ix depends <symbol> Dependency impact analysis");
- stderr(" ix text <term> Fast lexical search (ripgrep)");
- stderr(" ix read <target> Read source code directly");
- stderr(" ix decisions List design decisions");
- stderr(" ix history <entityId> Provenance chain");
- stderr(" ix diff <from> <to> Changes between revisions\n");
- if (!opts.unsafe) {
- stderr("Pass --unsafe to run anyway (not recommended).\n");
- return;
- }
- stderr("Running with --unsafe...\n");
-```
-
-**Step 2: Fix read.ts — use stderr()**
-
-In `ix-cli/src/cli/commands/read.ts`, add import at top:
-
-```typescript
-import { stderr } from "../stderr.js";
-```
-
-Replace line 56:
-```typescript
- stderr(`Could not resolve symbol: ${target}`);
-```
-
-Replace line 73:
-```typescript
- stderr(`Source file not found: ${sourceUri ?? "(no provenance)"}`);
-```
-
-**Step 3: Fix text.ts — use stderr()**
-
-In `ix-cli/src/cli/commands/text.ts`, add import at top:
-
-```typescript
-import { stderr } from "../stderr.js";
-```
-
-Replace line 65:
-```typescript
- stderr("Error: ripgrep (rg) is not installed. Install it: https://github.com/BurntSushi/ripgrep#installation");
-```
-
-**Step 4: Verify build and tests**
-
-```bash
-cd ix-cli && npm run build && npm test
-```
-
-**Step 5: Commit**
-
-```bash
-git add ix-cli/src/cli/commands/query.ts ix-cli/src/cli/commands/read.ts ix-cli/src/cli/commands/text.ts
-git commit -m "fix: route all remaining stdout leaks to stderr — query, read, text commands"
-```
-
----
-
-### Task 7: Update documentation
-
-**Files:**
-- Modify: `AGENTS.md`
-- Modify: `CLAUDE.md`
-
-**Step 1: Update AGENTS.md**
-
-In the "Start here — high-level workflow commands" section, update the diff example:
-```
-ix diff <from> <to> --summary --format json # Fast revision summary
-```
-
-In the "When to use which" section, add:
-```
-- "What changed between rev 5 and 10?" → `ix diff 5 10 --summary`
-- "Show me all changes" → `ix diff 5 10 --full --format json`
-```
-
-In the diagnostic codes table, add:
-```
-| `truncated_diff` | Diff results were capped; use --full for all changes |
-```
-
-**Step 2: Update CLAUDE.md**
-
-In the Best Practices section, add:
-```
-- Use `ix diff --summary` for broad revision comparisons (server-side, fast)
-- Use `--full` only when you need every individual change
-```
-
-**Step 3: Verify build and tests**
-
-```bash
-cd ix-cli && npm run build && npm test
-```
-
-**Step 4: Commit**
-
-```bash
-git add AGENTS.md CLAUDE.md
-git commit -m "docs: update docs for phase 2 — diff optimization, fallback bounding, JSON cleanup"
-```
diff --git a/docs/plans/2026-03-10-query-usefulness-plan.md b/docs/plans/2026-03-10-query-usefulness-plan.md
deleted file mode 100644
index 9301c573..00000000
--- a/docs/plans/2026-03-10-query-usefulness-plan.md
+++ /dev/null
@@ -1,815 +0,0 @@
-# Query Usefulness: REFERENCES Wiring + Integration Tests
-
-> **For agentic workers:** REQUIRED: Use superpowers:subagent-driven-development (if subagents available) or superpowers:executing-plans to implement this plan. Steps use checkbox (`- [ ]`) syntax for tracking.
-
-**Goal:** Make parser-emitted REFERENCES edges actually power CLI dependency queries, so `ix depends NodeKind`, `ix callers registerExplainCommand`, and `ix overview` return materially useful results.
-
-**Architecture:** The backend already stores and queries REFERENCES edges correctly — the gap is purely in CLI command files that hardcode predicate arrays without `"REFERENCES"`. Fix is additive: add `"REFERENCES"` to predicate lists in 7 CLI command files, update the `DependencyNode` type in `depends.ts`, add `"referenced-by"` relationship in `locate.ts`, and add ArangoDB-dependent integration tests.
-
-**Tech Stack:** TypeScript (CLI commands, vitest), Scala (integration tests, scalatest + ArangoDB)
-
----
-
-## File Structure
-
-| File | Action | Responsibility |
-|---|---|---|
-| `ix-cli/src/cli/commands/depends.ts` | Modify | Add REFERENCES expand + `referenced_by` relation |
-| `ix-cli/src/cli/commands/callers.ts` | Modify | Add REFERENCES to expandByName predicates |
-| `ix-cli/src/cli/commands/overview.ts` | Modify | Add REFERENCES to inbound queries |
-| `ix-cli/src/cli/commands/impact.ts` | Modify | Add REFERENCES to dependents + member queries |
-| `ix-cli/src/cli/commands/rank.ts` | Modify | Add REFERENCES to `dependents` metric config |
-| `ix-cli/src/cli/commands/locate.ts` | Modify | Add REFERENCES expand + `referenced-by` relationship |
-| `memory-layer/src/test/resources/fixtures/command_registration.ts` | Create | TS fixture: main.ts-style imports with .js extensions |
-| `memory-layer/src/test/resources/fixtures/command_module.ts` | Create | TS fixture: explain.ts-style export |
-| `memory-layer/src/test/resources/fixtures/node_kind.scala` | Create | Scala fixture: sealed trait + companion with case objects |
-| `memory-layer/src/test/resources/fixtures/node_kind_user.scala` | Create | Scala fixture: class using NodeKind in signatures + bodies |
-| `memory-layer/src/test/scala/ix/memory/QueryUsefulnessSpec.scala` | Create | ArangoDB integration tests |
-
----
-
-### Task 1: Add REFERENCES to `depends.ts`
-
-**Files:**
-- Modify: `ix-cli/src/cli/commands/depends.ts:10-16,49-52,56,86-87`
-
-The `depends` command does two parallel expands (CALLS inbound, IMPORTS inbound). Add a third for REFERENCES inbound.
-
-- [ ] **Step 1: Update DependencyNode type**
-
-In `ix-cli/src/cli/commands/depends.ts`, update the `DependencyNode` interface (lines 15-16):
-
-```typescript
-// Before:
- relation: "called_by" | "imported_by";
- sourceEdge: "CALLS" | "IMPORTS";
-
-// After:
- relation: "called_by" | "imported_by" | "referenced_by";
- sourceEdge: "CALLS" | "IMPORTS" | "REFERENCES";
-```
-
-- [ ] **Step 2: Widen processNodes inline parameter types**
-
-The `processNodes` inner function (line 56) has inline type unions that must be widened to include the new values:
-
-```typescript
-// Before:
- const processNodes = async (nodes: any[], relation: "called_by" | "imported_by", sourceEdge: "CALLS" | "IMPORTS") => {
-
-// After:
- const processNodes = async (nodes: any[], relation: "called_by" | "imported_by" | "referenced_by", sourceEdge: "CALLS" | "IMPORTS" | "REFERENCES") => {
-```
-
-- [ ] **Step 3: Add REFERENCES expand call**
-
-In `buildDependencyTree` function (lines 49-52), add a third parallel expand:
-
-```typescript
-// Before:
- const [callResult, importResult] = await Promise.all([
- client.expand(nodeId, { direction: "in", predicates: ["CALLS"], hops: 1 }),
- client.expand(nodeId, { direction: "in", predicates: ["IMPORTS"], hops: 1 }),
- ]);
-
-// After:
- const [callResult, importResult, refResult] = await Promise.all([
- client.expand(nodeId, { direction: "in", predicates: ["CALLS"], hops: 1 }),
- client.expand(nodeId, { direction: "in", predicates: ["IMPORTS"], hops: 1 }),
- client.expand(nodeId, { direction: "in", predicates: ["REFERENCES"], hops: 1 }),
- ]);
-```
-
-- [ ] **Step 4: Process REFERENCES results**
-
-After line 87 (`await processNodes(importResult.nodes, "imported_by", "IMPORTS");`), add:
-
-```typescript
- await processNodes(refResult.nodes, "referenced_by", "REFERENCES");
-```
-
-- [ ] **Step 5: Verify CLI builds**
-
-Run: `cd ix-cli && npx tsc --noEmit`
-Expected: No errors
-
-- [ ] **Step 6: Commit**
-
-```bash
-git add ix-cli/src/cli/commands/depends.ts
-git commit -m "feat: add REFERENCES to depends command predicate list"
-```
-
----
-
-### Task 2: Add REFERENCES to `callers.ts`
-
-**Files:**
-- Modify: `ix-cli/src/cli/commands/callers.ts:30-33`
-
-The `callers` command uses `expandByName` with `["CALLS"]`. Add `"REFERENCES"` so that type/value references also show up as callers.
-
-- [ ] **Step 1: Update callers predicates**
-
-In `ix-cli/src/cli/commands/callers.ts` line 32, update:
-
-```typescript
-// Before:
- const result = await client.expandByName(target.name, {
- direction: "in",
- predicates: ["CALLS"],
- kinds: ["function", "method"],
- });
-
-// After:
- const result = await client.expandByName(target.name, {
- direction: "in",
- predicates: ["CALLS", "REFERENCES"],
- kinds: ["function", "method"],
- });
-```
-
-- [ ] **Step 2: Update diagnostic message**
-
-In line 79, update the text fallback diagnostic to mention REFERENCES:
-
-```typescript
-// Before:
- message: "No graph-backed CALLS edges found. If files were ingested before CALLS extraction was added, run: ix ingest --force --recursive .",
-
-// After:
- message: "No graph-backed CALLS/REFERENCES edges found. If files were ingested before extraction was added, run: ix ingest --force --recursive .",
-```
-
-Also update line 83:
-```typescript
-// Before:
- stderr(chalk.dim("No graph-backed CALLS edges found. Showing text-based candidate usages."));
-
-// After:
- stderr(chalk.dim("No graph-backed CALLS/REFERENCES edges found. Showing text-based candidate usages."));
-```
-
-- [ ] **Step 3: Verify CLI builds**
-
-Run: `cd ix-cli && npx tsc --noEmit`
-Expected: No errors
-
-- [ ] **Step 4: Commit**
-
-```bash
-git add ix-cli/src/cli/commands/callers.ts
-git commit -m "feat: add REFERENCES to callers command predicate list"
-```
-
----
-
-### Task 3: Add REFERENCES to `overview.ts`
-
-**Files:**
-- Modify: `ix-cli/src/cli/commands/overview.ts:88,135-137,228-229,262-263`
-
-The `overview` command has two paths: container (file/class/object) and callable (function/method). Both need REFERENCES.
-
-- [ ] **Step 1: Update container overview — inbound dependents**
-
-In `overviewContainer` (line 88), add REFERENCES to the inbound query:
-
-```typescript
-// Before:
- client.expand(target.id, { direction: "in", predicates: ["CALLS", "IMPORTS"] }),
-
-// After:
- client.expand(target.id, { direction: "in", predicates: ["CALLS", "IMPORTS", "REFERENCES"] }),
-```
-
-- [ ] **Step 2: Update container overview — member caller counts**
-
-In `overviewContainer` (lines 135-137), add REFERENCES to member caller count queries:
-
-```typescript
-// Before:
- const callersResult = await client.expand(m.id, {
- direction: "in",
- predicates: ["CALLS"],
- });
-
-// After:
- const callersResult = await client.expand(m.id, {
- direction: "in",
- predicates: ["CALLS", "REFERENCES"],
- });
-```
-
-- [ ] **Step 3: Update callable overview — callers and callees**
-
-In `overviewCallable` (lines 228-229), add REFERENCES:
-
-```typescript
-// Before:
- client.expand(target.id, { direction: "in", predicates: ["CALLS"] }),
- client.expand(target.id, { direction: "out", predicates: ["CALLS"] }),
-
-// After:
- client.expand(target.id, { direction: "in", predicates: ["CALLS", "REFERENCES"] }),
- client.expand(target.id, { direction: "out", predicates: ["CALLS", "REFERENCES"] }),
-```
-
-- [ ] **Step 4: Update callable overview — empty diagnostic**
-
-In `overviewCallable` (lines 262-263), update the diagnostic message:
-
-```typescript
-// Before:
- diagnostics.push("No CALLS edges found. If files were ingested before CALLS extraction, run: ix ingest --force --recursive .");
-
-// After:
- diagnostics.push("No CALLS/REFERENCES edges found. If files were ingested before extraction was added, run: ix ingest --force --recursive .");
-```
-
-- [ ] **Step 5: Verify CLI builds**
-
-Run: `cd ix-cli && npx tsc --noEmit`
-Expected: No errors
-
-- [ ] **Step 6: Commit**
-
-```bash
-git add ix-cli/src/cli/commands/overview.ts
-git commit -m "feat: add REFERENCES to overview command predicate lists"
-```
-
----
-
-### Task 4: Add REFERENCES to `impact.ts`
-
-**Files:**
-- Modify: `ix-cli/src/cli/commands/impact.ts:58,84-86,197-198`
-
-- [ ] **Step 1: Update container impact — direct dependents**
-
-In `containerImpact` (line 58), add REFERENCES:
-
-```typescript
-// Before:
- client.expand(target.id, { direction: "in", predicates: ["CALLS"] }),
-
-// After:
- client.expand(target.id, { direction: "in", predicates: ["CALLS", "REFERENCES"] }),
-```
-
-- [ ] **Step 2: Update container impact — member caller counts**
-
-In `containerImpact` (lines 84-86), add REFERENCES:
-
-```typescript
-// Before:
- const callersResult = await client.expand(member.id, {
- direction: "in",
- predicates: ["CALLS"],
- });
-
-// After:
- const callersResult = await client.expand(member.id, {
- direction: "in",
- predicates: ["CALLS", "REFERENCES"],
- });
-```
-
-- [ ] **Step 3: Update leaf impact — callers and callees**
-
-In `leafImpact` (lines 197-198), add REFERENCES:
-
-```typescript
-// Before:
- client.expand(target.id, { direction: "in", predicates: ["CALLS"] }),
- client.expand(target.id, { direction: "out", predicates: ["CALLS"] }),
-
-// After:
- client.expand(target.id, { direction: "in", predicates: ["CALLS", "REFERENCES"] }),
- client.expand(target.id, { direction: "out", predicates: ["CALLS", "REFERENCES"] }),
-```
-
-- [ ] **Step 4: Verify CLI builds**
-
-Run: `cd ix-cli && npx tsc --noEmit`
-Expected: No errors
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add ix-cli/src/cli/commands/impact.ts
-git commit -m "feat: add REFERENCES to impact command predicate lists"
-```
-
----
-
-### Task 5: Add REFERENCES to `rank.ts`
-
-**Files:**
-- Modify: `ix-cli/src/cli/commands/rank.ts:8-13`
-
-- [ ] **Step 1: Update METRIC_CONFIG**
-
-In `ix-cli/src/cli/commands/rank.ts` (lines 8-13), add REFERENCES to the `dependents` and `callers` metrics:
-
-```typescript
-// Before:
-const METRIC_CONFIG: Record<Metric, { direction: string; predicates: string[] }> = {
- dependents: { direction: "in", predicates: ["CALLS", "IMPORTS"] },
- callers: { direction: "in", predicates: ["CALLS"] },
- importers: { direction: "in", predicates: ["IMPORTS"] },
- members: { direction: "out", predicates: ["CONTAINS"] },
-};
-
-// After:
-const METRIC_CONFIG: Record<Metric, { direction: string; predicates: string[] }> = {
- dependents: { direction: "in", predicates: ["CALLS", "IMPORTS", "REFERENCES"] },
- callers: { direction: "in", predicates: ["CALLS", "REFERENCES"] },
- importers: { direction: "in", predicates: ["IMPORTS"] },
- members: { direction: "out", predicates: ["CONTAINS"] },
-};
-```
-
-- [ ] **Step 2: Verify CLI builds**
-
-Run: `cd ix-cli && npx tsc --noEmit`
-Expected: No errors
-
-- [ ] **Step 3: Commit**
-
-```bash
-git add ix-cli/src/cli/commands/rank.ts
-git commit -m "feat: add REFERENCES to rank command metric config"
-```
-
----
-
-### Task 6: Add REFERENCES to `locate.ts`
-
-**Files:**
-- Modify: `ix-cli/src/cli/commands/locate.ts:15-20,90-106,142-156`
-
-- [ ] **Step 1: Update RelatedItem type**
-
-In `ix-cli/src/cli/commands/locate.ts` (line 19), add `referenced-by`:
-
-```typescript
-// Before:
- relationship: "contains" | "contained-by" | "depends-on" | "imported-by" | "calls" | "called-by";
-
-// After:
- relationship: "contains" | "contained-by" | "depends-on" | "imported-by" | "calls" | "called-by" | "referenced-by";
-```
-
-- [ ] **Step 2: Add REFERENCES expand call**
-
-In the parallel expand block (lines 90-106), add a REFERENCES expand:
-
-```typescript
-// Before:
- const [
- details,
- containsResult,
- callersResult,
- calleesResult,
- importsResult,
- importedByResult,
- ] = await Promise.all([
- client.entity(target.id),
- isContainer
- ? client.expand(target.id, { direction: "out", predicates: ["CONTAINS"] })
- : client.expand(target.id, { direction: "in", predicates: ["CONTAINS"] }),
- client.expand(target.id, { direction: "in", predicates: ["CALLS"] }),
- client.expand(target.id, { direction: "out", predicates: ["CALLS"] }),
- client.expand(target.id, { direction: "out", predicates: ["IMPORTS"] }),
- client.expand(target.id, { direction: "in", predicates: ["IMPORTS"] }),
- ]);
-
-// After:
- const [
- details,
- containsResult,
- callersResult,
- calleesResult,
- importsResult,
- importedByResult,
- referencedByResult,
- ] = await Promise.all([
- client.entity(target.id),
- isContainer
- ? client.expand(target.id, { direction: "out", predicates: ["CONTAINS"] })
- : client.expand(target.id, { direction: "in", predicates: ["CONTAINS"] }),
- client.expand(target.id, { direction: "in", predicates: ["CALLS"] }),
- client.expand(target.id, { direction: "out", predicates: ["CALLS"] }),
- client.expand(target.id, { direction: "out", predicates: ["IMPORTS"] }),
- client.expand(target.id, { direction: "in", predicates: ["IMPORTS"] }),
- client.expand(target.id, { direction: "in", predicates: ["REFERENCES"] }),
- ]);
-```
-
-- [ ] **Step 3: Process REFERENCES results into relationships**
-
-After the `importedByResult` loop (after line 156), add:
-
-```typescript
- for (const n of referencedByResult.nodes) {
- relationships.push(nodeToRelated(n, "referenced-by"));
- }
-```
-
-- [ ] **Step 4: Verify CLI builds**
-
-Run: `cd ix-cli && npx tsc --noEmit`
-Expected: No errors
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add ix-cli/src/cli/commands/locate.ts
-git commit -m "feat: add REFERENCES to locate command"
-```
-
----
-
-### Task 7: Create test fixtures
-
-**Files:**
-- Create: `memory-layer/src/test/resources/fixtures/command_registration.ts`
-- Create: `memory-layer/src/test/resources/fixtures/command_module.ts`
-- Create: `memory-layer/src/test/resources/fixtures/node_kind.scala`
-- Create: `memory-layer/src/test/resources/fixtures/node_kind_user.scala`
-
-- [ ] **Step 1: Create TS command registration fixture**
-
-Create `memory-layer/src/test/resources/fixtures/command_registration.ts`:
-
-```typescript
-import { Command } from "commander";
-import { registerExplainCommand } from "./commands/command_module.js";
-
-const program = new Command();
-program.name("test-cli").version("0.1.0");
-
-registerExplainCommand(program);
-
-program.parse();
-```
-
-- [ ] **Step 2: Create TS command module fixture**
-
-Create `memory-layer/src/test/resources/fixtures/command_module.ts`:
-
-```typescript
-import type { Command } from "commander";
-
-export function registerExplainCommand(program: Command): void {
- program
- .command("explain <symbol>")
- .description("Explain an entity")
- .action(async (symbol: string) => {
- const result = await resolveEntity(symbol);
- console.log(result);
- });
-}
-
-async function resolveEntity(symbol: string): Promise<string> {
- return `Resolved: ${symbol}`;
-}
-```
-
-- [ ] **Step 3: Create Scala NodeKind fixture**
-
-Create `memory-layer/src/test/resources/fixtures/node_kind.scala`:
-
-```scala
-package ix.memory.model
-
-sealed trait NodeKind
-
-object NodeKind {
- case object File extends NodeKind
- case object Module extends NodeKind
- case object Class extends NodeKind
- case object Function extends NodeKind
- case object Method extends NodeKind
-}
-```
-
-- [ ] **Step 4: Create Scala NodeKind user fixture**
-
-Create `memory-layer/src/test/resources/fixtures/node_kind_user.scala`:
-
-```scala
-package ix.memory.ingestion
-
-class GraphPatchBuilder {
- def buildNode(kind: NodeKind, name: String): GraphNode = {
- val effectiveKind = NodeKind.File
- val result = createNode(name, effectiveKind)
- result
- }
-
- private def createNode(name: String, kind: NodeKind): GraphNode = {
- GraphNode(name, kind)
- }
-}
-```
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add memory-layer/src/test/resources/fixtures/command_registration.ts \
- memory-layer/src/test/resources/fixtures/command_module.ts \
- memory-layer/src/test/resources/fixtures/node_kind.scala \
- memory-layer/src/test/resources/fixtures/node_kind_user.scala
-git commit -m "test: add fixtures for query usefulness integration tests"
-```
-
----
-
-### Task 8: Create integration tests
-
-**Files:**
-- Create: `memory-layer/src/test/scala/ix/memory/QueryUsefulnessSpec.scala`
-
-These tests require a running ArangoDB instance. They follow the same pattern as `EndToEndSpec.scala`.
-
-- [ ] **Step 1: Write the integration test file**
-
-Create `memory-layer/src/test/scala/ix/memory/QueryUsefulnessSpec.scala`:
-
-```scala
-package ix.memory
-
-import java.nio.file.{Path, Paths}
-
-import cats.effect.IO
-import cats.effect.testing.scalatest.AsyncIOSpec
-import org.scalatest.flatspec.AsyncFlatSpec
-import org.scalatest.matchers.should.Matchers
-
-import ix.memory.db._
-import ix.memory.ingestion.{IngestionService, ParserRouter}
-import ix.memory.model._
-
-/**
- * Integration tests verifying that parser-emitted edges (especially REFERENCES)
- * are persisted and queryable via the expand API.
- *
- * Requires a running ArangoDB instance on localhost:8529.
- */
-class QueryUsefulnessSpec extends AsyncFlatSpec with AsyncIOSpec with Matchers with TestDbHelper {
-
- val clientResource = ArangoClient.resource(
- host = "localhost", port = 8529,
- database = "ix_memory_test", user = "root", password = ""
- )
-
- private def fixturePath(name: String): Path = {
- val url = getClass.getClassLoader.getResource(s"fixtures/$name")
- Paths.get(url.toURI)
- }
-
- // ── Scala REFERENCES: object references become query-useful ──
-
- "QueryUsefulness" should "persist REFERENCES edges from Scala parser and return them via expand" in {
- clientResource.use { client =>
- val writeApi = new ArangoGraphWriteApi(client)
- val queryApi = new ArangoGraphQueryApi(client)
- val router = new ParserRouter()
- val service = new IngestionService(router, writeApi, queryApi)
-
- for {
- _ <- cleanDatabase(client)
- // Ingest the NodeKind fixture (defines sealed trait + companion with case objects)
- _ <- service.ingestFile(fixturePath("node_kind.scala"))
- // Ingest the user fixture (uses NodeKind in signatures and bodies)
- _ <- service.ingestFile(fixturePath("node_kind_user.scala"))
-
- // Search for NodeKind entity
- nodeKindResults <- queryApi.searchNodes("NodeKind", limit = 10, nameOnly = true)
- nodeKindEntity = nodeKindResults.find(n => n.name == "NodeKind" && n.kind != NodeKind.Module)
-
- _ = nodeKindEntity shouldBe defined
-
- // Expand inbound REFERENCES edges to NodeKind
- refResult <- queryApi.expand(
- nodeKindEntity.get.id,
- Direction.In,
- predicates = Some(Set("REFERENCES")),
- hops = 1
- )
-
- // Should have at least one REFERENCES edge (from buildNode or createNode)
- _ = refResult.nodes should not be empty
- refNames = refResult.nodes.map(_.name)
- _ = refNames should contain atLeastOneOf ("buildNode", "createNode")
- } yield succeed
- }
- }
-
- it should "return REFERENCES edges alongside CALLS in combined dependency queries" in {
- clientResource.use { client =>
- val writeApi = new ArangoGraphWriteApi(client)
- val queryApi = new ArangoGraphQueryApi(client)
- val router = new ParserRouter()
- val service = new IngestionService(router, writeApi, queryApi)
-
- for {
- _ <- cleanDatabase(client)
- _ <- service.ingestFile(fixturePath("node_kind.scala"))
- _ <- service.ingestFile(fixturePath("node_kind_user.scala"))
-
- nodeKindResults <- queryApi.searchNodes("NodeKind", limit = 10, nameOnly = true)
- nodeKindEntity = nodeKindResults.find(n => n.name == "NodeKind" && n.kind != NodeKind.Module)
- _ = nodeKindEntity shouldBe defined
-
- // Combined query: CALLS + IMPORTS + REFERENCES (what `depends` now uses)
- combinedResult <- queryApi.expand(
- nodeKindEntity.get.id,
- Direction.In,
- predicates = Some(Set("CALLS", "IMPORTS", "REFERENCES")),
- hops = 1
- )
-
- // Should include REFERENCES-backed dependents
- _ = combinedResult.nodes should not be empty
- } yield succeed
- }
- }
-
- // ── Scala nested CONTAINS: object membership is queryable ──
-
- it should "persist nested CONTAINS edges for case objects inside companion" in {
- clientResource.use { client =>
- val writeApi = new ArangoGraphWriteApi(client)
- val queryApi = new ArangoGraphQueryApi(client)
- val router = new ParserRouter()
- val service = new IngestionService(router, writeApi, queryApi)
-
- for {
- _ <- cleanDatabase(client)
- _ <- service.ingestFile(fixturePath("node_kind.scala"))
-
- // Find the NodeKind object entity
- results <- queryApi.searchNodes("NodeKind", limit = 10, nameOnly = true)
- nodeKindObj = results.find(n => n.name == "NodeKind" && n.kind == NodeKind.Object)
- _ = nodeKindObj shouldBe defined
-
- // Expand CONTAINS — should show case object members
- containsResult <- queryApi.expand(
- nodeKindObj.get.id,
- Direction.Out,
- predicates = Some(Set("CONTAINS")),
- hops = 1
- )
-
- memberNames = containsResult.nodes.map(_.name)
- _ = memberNames should contain allOf ("File", "Module", "Class", "Function", "Method")
- } yield succeed
- }
- }
-
- // ── TypeScript: file-level CALLS correctness ──
-
- it should "not create false file-level CALLS for exported function definitions" in {
- clientResource.use { client =>
- val writeApi = new ArangoGraphWriteApi(client)
- val queryApi = new ArangoGraphQueryApi(client)
- val router = new ParserRouter()
- val service = new IngestionService(router, writeApi, queryApi)
-
- for {
- _ <- cleanDatabase(client)
- _ <- service.ingestFile(fixturePath("command_module.ts"))
-
- // Find the file entity
- fileResults <- queryApi.searchNodes("command_module.ts", limit = 5, nameOnly = true)
- fileEntity = fileResults.find(n => n.name == "command_module.ts" && n.kind == NodeKind.File)
- _ = fileEntity shouldBe defined
-
- // File-level CALLS should not include registerExplainCommand (it's a definition, not a call)
- callsResult <- queryApi.expand(
- fileEntity.get.id,
- Direction.Out,
- predicates = Some(Set("CALLS")),
- hops = 1
- )
-
- calleeNames = callsResult.nodes.map(_.name)
- _ = calleeNames should not contain ("registerExplainCommand")
- } yield succeed
- }
- }
-
- // ── TypeScript: cross-file caller attribution ──
-
- it should "create cross-file CALLS edges for imported function invocations" in {
- clientResource.use { client =>
- val writeApi = new ArangoGraphWriteApi(client)
- val queryApi = new ArangoGraphQueryApi(client)
- val router = new ParserRouter()
- val service = new IngestionService(router, writeApi, queryApi)
-
- for {
- _ <- cleanDatabase(client)
- // Ingest command_module first (defines registerExplainCommand)
- _ <- service.ingestFile(fixturePath("command_module.ts"))
- // Then command_registration (imports and calls registerExplainCommand)
- _ <- service.ingestFile(fixturePath("command_registration.ts"))
-
- // Find registerExplainCommand function entity
- funcResults <- queryApi.searchNodes("registerExplainCommand", limit = 10, nameOnly = true)
- funcEntity = funcResults.find(n => n.name == "registerExplainCommand" && n.kind == NodeKind.Function)
- _ = funcEntity shouldBe defined
-
- // Expand inbound CALLS — should include command_registration.ts (file-level call)
- callersResult <- queryApi.expand(
- funcEntity.get.id,
- Direction.In,
- predicates = Some(Set("CALLS")),
- hops = 1
- )
-
- callerNames = callersResult.nodes.map(_.name)
- // command_registration.ts should call registerExplainCommand at file level
- _ = callerNames should contain ("command_registration.ts")
- // command_module.ts should NOT be a caller (it defines it)
- _ = callerNames should not contain ("command_module.ts")
- } yield succeed
- }
- }
-}
-```
-
-- [ ] **Step 2: Verify the test compiles**
-
-The test uses:
-- `TestDbHelper` trait (at `memory-layer/src/test/scala/ix/memory/TestDbHelper.scala`) — provides `cleanDatabase(client: ArangoClient): IO[Unit]`
-- `Direction.In` / `Direction.Out` — from `ix.memory.db.Direction` (imported via `ix.memory.db._`)
-- `queryApi.expand(nodeId: NodeId, direction: Direction, predicates: Option[Set[String]], hops: Int)` — standard API
-
-Run: `sbt "Test / compile"`
-Expected: Compiles without errors
-
-- [ ] **Step 3: Run integration tests (requires ArangoDB)**
-
-Run: `sbt "testOnly *QueryUsefulnessSpec"`
-
-Expected: All 5 tests pass (if ArangoDB is running). If ArangoDB is not running, tests will fail with connection errors — this is expected for CI environments without ArangoDB.
-
-- [ ] **Step 4: Commit**
-
-```bash
-git add memory-layer/src/test/scala/ix/memory/QueryUsefulnessSpec.scala
-git commit -m "test: add integration tests for REFERENCES query usefulness"
-```
-
----
-
-### Task 9: Build CLI and verify
-
-- [ ] **Step 1: Build CLI**
-
-Run: `cd ix-cli && npx tsc --noEmit`
-Expected: No type errors
-
-- [ ] **Step 2: Run existing CLI tests**
-
-Run: `cd ix-cli && npx vitest run`
-Expected: All existing tests pass
-
-- [ ] **Step 3: Run parser unit tests**
-
-Run: `sbt "testOnly *TypeScriptParserSpec" "testOnly *ScalaParserSpec"`
-Expected: All 71 tests pass (unchanged from previous patch)
-
-- [ ] **Step 4: Final commit (if any adjustments needed)**
-
-```bash
-git add -A
-git commit -m "chore: final build verification"
-```
-
----
-
-## Verification (post-deploy)
-
-After deploying the backend and rebuilding the CLI, re-ingest and verify:
-
-```bash
-# Re-ingest
-ix ingest ix-cli/src/cli/ --recursive
-ix ingest memory-layer/src/main/scala/ix/memory/model/ --recursive
-
-# TS source-file queries
-ix depends explain.ts --format json # Should show dependents
-ix imported-by explain.ts --format json # Should show main.ts
-ix callers registerExplainCommand --format json # Should show main.ts caller
-
-# Scala object queries
-ix overview NodeKind --format json # Should show members + inbound dependents
-ix depends NodeKind --format json # Should show REFERENCES-backed deps
-ix callers NodeKind --format json # Should show functions referencing NodeKind
-```
diff --git a/docs/plans/2026-03-25-large-repo-ingest-perf.md b/docs/plans/2026-03-25-large-repo-ingest-perf.md
deleted file mode 100644
index ce589a67..00000000
--- a/docs/plans/2026-03-25-large-repo-ingest-perf.md
+++ /dev/null
@@ -1,288 +0,0 @@
-# Large Repo Ingest Performance
-
-Date: 2026-03-25
-Branch: `feature/claude-plugin`
-
----
-
-## Baseline
-
-Kubernetes repo (`files=16010`) before this work:
-
-| Phase | Time |
-|---|---|
-| `ix map` ingest | ~466s |
-| `ix map` map computation | ~53s |
-| **Total `ix map`** | **~519s** |
-
-Debug profile at baseline:
-```
-resolveEdgesMs=29581 buildPatchMs=10156 commitMs=386443 totalSaveMs=426834
-```
-
-The commit path dominated — 386s out of 427s total save time.
-
----
-
-## What We Did (already merged)
-
-### 1. Compound DB indexes (`memory-layer/src/main/scala/ix/memory/db/ArangoSchema.scala`)
-
-Added compound indexes on `nodes(logical_id, deleted_rev)` and `claims(entity_id, deleted_rev)`. Tombstone + retire AQL queries filter both fields; without this, Arango returned all historical node versions then post-filtered. Now it does direct point lookups.
-
-### 2. Upfront batch tombstone + retire (`memory-layer/src/main/scala/ix/memory/db/BulkWriteApi.scala`)
-
-In `commitBatchChunked`, when multiple DB chunks exist and `baseRev > 0`, now collects all entity IDs upfront and runs tombstone + retire **once in parallel** before any inserts (`skipTombstone = true` passed to each per-chunk call). Previously ran 320 AQL UPDATE passes for Kubernetes; now runs 2.
-
-Also parallelized tombstone + retire within `commitBatch` for the single-chunk case using `IO.both`.
-
-### 3. Generated file filtering (`ix-cli/src/cli/commands/ingest.ts`)
-
-Skip known generated files by filename before parsing: `*.pb.go`, `zz_generated*`, `*_deepcopy.go`, `*_mock.go`, `mock_*`, `*.pb.ts`, `*.pb.js`, `_pb.ts`, `_pb.js`. Applied in both `walkFiles` and `tryGitLsFiles`.
-
-### 4. Parallel HTTP save requests (`ix-cli/src/cli/commands/ingest.ts`)
-
-Replaced sequential `for` loop in `commitPreparedPatches` with a 4-worker pool (`COMMIT_CONCURRENCY = 4` at line ~416). Fixed progress bar to use `Math.max` so it doesn't jump backward when an out-of-order chunk completes.
-
----
-
-## Current State (2026-03-25, pre-session baseline)
-
-| Phase | Before | After | Delta |
-|---|---|---|---|
-| Ingest | ~466s | ~200s | **-57%** |
-| Map computation | ~53s | ~87s | +64% (regression) |
-| **Total `ix map`** | **~519s** | **~287s** | **-45%** |
-
-Graph after full Kubernetes ingest:
-```
-nodes: 312,140 (113k chunk, 76k module, 43k function, 42k method, 16k class, 15k file)
-edges: 840,843 (319k CALLS, 107k CONTAINS_CHUNK, 105k CONTAINS, 95k NEXT, 76k IMPORTS)
-```
-
----
-
-## Current State (2026-03-26, post-session)
-
-| Phase | Before | After | Delta |
-|---|---|---|---|
-| Ingest | ~200s | ~227s | +13% (conflict fix overhead) |
-| Map computation | ~87s | ~82s | -6% |
-| **Total `ix map`** | **~287s** | **~309s** | +8% |
-
-Ingest debug breakdown (15035 files, full fresh ingest):
-```
-resolveEdgesMs=26252 buildPatchMs=8731 commitMs=607952 totalSaveMs=188862
-```
-
-Ingest is currently slightly slower than the pre-session baseline. The chunk-skipping benefit (~30% fewer DB inserts) is real but offset by the COMMIT_CONCURRENCY revert to 4 (was already 4 at baseline, no gain there) and normal run variance. Ingest is clean — zero write-write conflict errors.
-
-Map regression (82s vs 53s pre-"What We Did") is **unresolved** — this is Task 3.
-
----
-
-## Targets
-
-| Phase | Current | Target |
-|---|---|---|
-| Ingest | ~227s | ~90s |
-| Map computation | ~82s | ~20s |
-| **Total** | **~309s** | **~110s** |
-
----
-
-## Task List
-
-Tasks are independent unless noted. Each is scoped to be completable by a single Claude instance with no context from the others.
-
----
-
-### Task 1 — Bump `COMMIT_CONCURRENCY` 4 → 6 ⚠️ BLOCKED
-
-**Priority:** High — blocked by write-write conflict bug (see Task 1b below).
-
-Bumping to 6 caused systemic write-write conflicts in ArangoDB. Root cause was identified and fixed (see Task 1b), but after that fix concurrency was left at 4. Re-attempting the bump to 6 should now be safe — the `updateRevision` conflict is eliminated, and `retryOnConflict` handles any residual tombstone conflicts.
-
-**Acceptance:** Run `IX_DEBUG=1 ix map <kubernetes-repo>` with no `[commit error]` lines and confirm `commitMs` drops vs the 607952ms baseline.
-
----
-
-### Task 1b — Fix `updateRevision` write-write conflict ✅ DONE
-
-**Root cause:** `updateRevision` used an AQL `UPSERT { _key: "current" }` on the `revisions` collection. Every HTTP commit request ends with this call. With multiple concurrent workers, all requests raced to update the same document → ArangoDB write-write conflict error 1200.
-
-**Fix (`memory-layer/src/main/scala/ix/memory/db/BulkWriteApi.scala`):**
-Replaced the AQL UPSERT with two Document API inserts via the existing `bulkInsert(..., overwriteMode="replace")`. The Document API replace is atomic at the document level — concurrent replaces on the same `_key` don't conflict; last writer wins (acceptable since all concurrent requests write the same rev value).
-
-Also added `retryOnConflict` in the client (`ix-cli/src/cli/commands/ingest.ts`) with 10ms base jitter backoff as a safety net for any residual tombstone-phase conflicts.
-
----
-
-### Task 2 — Skip chunk nodes/edges during map-triggered ingest ✅ DONE
-
-**Priority:** High — estimated ~30% fewer DB inserts.
-
-**Files:**
-- `ix-cli/src/cli/commands/ingest.ts` — add `skipChunks` flag, filter nodes/edges before patch submission
-- `ix-cli/src/client/api.ts` — pass flag through to request if needed
-- `ix-cli/src/client/types.ts` — add type if needed
-
-**Background:**
-Current insert volume per 200-file HTTP batch (estimated):
-- ~4,154 nodes, of which ~36% are `chunk` kind nodes
-- ~11,186 edges, of which ~24% are `CONTAINS_CHUNK` + `NEXT` edges
-
-Chunk nodes and their edges are LLM context artifacts (for `ix read`). The Louvain clustering in `MapService.computeAndPersistMap` runs on `IMPORTS` and `CALLS` edges between file nodes — it never touches chunks. Skipping them during `ix map` doesn't affect map quality.
-
-**What to do:**
-
-1. In `ingest.ts`, find where `PreparedPatch` objects are built (the `buildPatch` / `resolveEdges` path). Add a `mapMode: boolean` parameter that, when true, strips:
- - Any node with `kind === "chunk"`
- - Any edge with `kind === "CONTAINS_CHUNK"` or `kind === "NEXT"`
-
-2. The `ix map` code path in `ingest.ts` (around line ~544 and ~598, the `commitPreparedPatches` calls) should pass `mapMode: true`.
-
-3. The `ix ingest` code path (full ingest, used for `ix read`) must continue writing chunks — pass `mapMode: false` or omit the flag.
-
-4. Do not change the server side. The filtering should be purely client-side before the HTTP payload is built.
-
-**Acceptance:**
-- `IX_DEBUG=1 ix map <kubernetes-repo>` shows fewer nodes/edges inserted per batch (verify via backend `insertNodes`/`insertEdges` log lines)
-- `ix read <any-file>` after a full `ix ingest` still returns chunk content (chunks must still be written on full ingest)
-- No change to `ix map` output quality (regions/subsystems unchanged or better)
-
----
-
-### Task 3 — Profile and fix map computation regression (82s → target 20s)
-
-**Priority:** High — map computation is the bottleneck for incremental `ix map` runs. Every file save triggers a re-map; keeping this fast matters more than ingest speed.
-
-**Note on terminology:** `ix ingest` is deprecated. `ix map` is the primary command. It has two phases: ingest phase (parse + commit files) and map computation phase (Louvain clustering + persist). Task 3 is about the map computation phase only.
-
-**Files:**
-- `memory-layer/src/main/scala/ix/memory/map/MapService.scala` — primary target
-- `memory-layer/src/main/scala/ix/memory/map/MapGraphBuilder.scala` — if `build()` is the bottleneck
-
-**Current timing:** map computation = ~82s on Kubernetes (15035 files, 828 regions). Pre-regression baseline was ~53s. Target: ≤20s (30s acceptable).
-
-**Background:**
-`computeAndPersistMap` has four steps:
-1. `builder.build()` — loads file graph from DB (IMPORTS/CALLS edges between file nodes)
-2. `detectCrosscut(rawGraph)` — pure CPU
-3. `LouvainClustering.cluster(...)` — pure CPU, `maxLevels=3`
-4. `persistMap(fresh, cached)` — writes region nodes to DB, compares old vs new regions
-
-The regression likely lives in `builder.build()` (more nodes/edges to load since ingest changes) or `persistMap` (`sameRegions` comparison may be slow at 828 regions).
-
-**What to do:**
-
-1. Read `MapService.scala` first to find `computeAndPersistMap` and understand the current structure before adding instrumentation.
-
-2. Add coarse `System.currentTimeMillis()` timing around each of the four steps and log at INFO level:
- ```scala
- val t0 = System.currentTimeMillis()
- rawGraph <- builder.build()
- val t1 = System.currentTimeMillis()
- // ... etc
- logger.info(s"map build=${t1-t0}ms crosscut=${t2-t1}ms cluster=${t3-t2}ms persist=${t4-t3}ms")
- ```
-
-3. After adding instrumentation, rebuild and restart the backend:
- ```bash
- # from repo root (/home/ianhock/ix/IX-Memory)
- ./rebuild.sh
- ```
-
-4. Run to collect the timing breakdown:
- ```bash
- IX_DEBUG=1 ix map /home/ianhock/kubernetes 2>&1 | tee /tmp/ix-map-debug.log
- grep "map build=" /tmp/ix-map-debug.log
- ```
-
-5. Fix the dominant step:
- - If `builder.build()` is slow: check `MapGraphBuilder` — it queries all IMPORTS/CALLS edges between file nodes. Look for missing indexes or N+1 queries. Check `ArangoSchema.scala` for relevant indexes.
- - If `persistMap` is slow: check `sameRegions` — it sorts and compares full `Region` objects. At 828 regions this is O(n log n) with potentially high constant. Also check `submitMapPatch` / `loadOldRegionIds`.
- - If `LouvainClustering.cluster` is slow: the graph got larger. Check how many file nodes are passed to the clusterer vs pre-regression.
-
-**Acceptance:**
-- Map computation ≤ 30s on Kubernetes (20s target, 30s acceptable for this task)
-- Timing log line visible in backend output during `IX_DEBUG=1 ix map`
-- No regression in `ix map` output (828 regions expected, same or similar structure)
-- Rebuild via `./rebuild.sh` from repo root before testing
-
----
-
-### Task 4 — Vacuum old tombstoned node versions
-
-**Priority:** Medium — reduces DB size and disk I/O over time; not urgent for this sprint.
-
-**Files:**
-- `memory-layer/src/main/scala/ix/memory/db/ArangoClient.scala` — add vacuum method
-- `memory-layer/src/main/scala/ix/memory/api/` — add a `/vacuum` or `/admin/vacuum` HTTP endpoint
-- `ix-cli/src/client/api.ts` and `ix-cli/src/cli/commands/` — add `ix vacuum` CLI command
-
-**Background:**
-Every ingest revision leaves behind tombstoned docs in the `nodes` collection (`deleted_rev IS NOT NULL`). After N ingests of Kubernetes (312k live nodes), the collection has ~N × 312k docs. These bloat ArangoDB's working set, spill indexes to disk, and account for the 12.4GB disk write profile.
-
-**What to do:**
-
-1. In `ArangoClient.scala`, add a method:
- ```scala
- def vacuumTombstoned(keepRevisions: Int): IO[Long]
- ```
- That runs:
- ```aql
- FOR n IN nodes
- FILTER n.deleted_rev != null
- AND n.deleted_rev < @cutoffRev
- LIMIT 50000
- REMOVE n IN nodes
- RETURN 1
- ```
- Where `cutoffRev = latestRev - keepRevisions`. Use `LIMIT 50000` per pass and loop until 0 rows removed to avoid ArangoDB memory pressure on large deletes. Apply the same pattern to the `edges` and `claims` collections.
-
-2. Expose it via a backend endpoint (e.g. `POST /admin/vacuum?keepRevisions=5`).
-
-3. Add `ix vacuum [--keep-revisions N]` CLI command (default `--keep-revisions 5`).
-
-**Acceptance:**
-- After `ix vacuum` on Kubernetes graph, `nodes` collection count drops by at least 50% (or confirms there are minimal tombstoned docs if this is a fresh graph)
-- Subsequent `ix map` run shows reduced disk I/O in `IX_DEBUG=1` output
-- `ix vacuum` completes without OOM or ArangoDB timeout (batched deletes required)
-
----
-
-### Task 5 — Dynamic concurrency auto-tuning (stretch goal)
-
-**Priority:** Low — only needed if fixed concurrency of 6 still leaves headroom.
-
-**File:** `ix-cli/src/cli/commands/ingest.ts`
-
-**What to do:**
-Replace the fixed `COMMIT_CONCURRENCY` constant with a simple AIMD (additive increase / multiplicative decrease) controller:
-- Track rolling P90 latency of the last 10 batch commits
-- If P90 < 8s, increment concurrency (up to max 12)
-- If P90 > 15s or a batch times out, decrement concurrency (min 2)
-- Log current concurrency level in the `[ingest-save]` debug line
-
-**Acceptance:**
-- On Kubernetes, concurrency auto-settles to a stable value within the first 10 batches
-- Total ingest time is ≤ fixed-concurrency-6 time (must not be slower)
-- No batch timeout errors introduced
-
----
-
-## Profiling Instructions
-
-To collect the data needed for Task 3:
-
-```bash
-IX_DEBUG=1 ix map <kubernetes-repo-path> 2>&1 | tee /tmp/ix-map-debug.log
-```
-
-Look for:
-- Client: `[ingest-save]` lines — per-batch phase breakdown
-- Client: `[slow saving]` lines — which batch numbers are slow
-- Backend: `ix.bulk-write` log lines — `insertNodes`, `insertEdges`, `insertClaims`, `insertPatches` per-stage breakdown
-- Backend: `pre-tombstone` line — tombstone+retire time
-- Backend (after Task 3 instrumentation): `map build=Xms crosscut=Yms cluster=Zms persist=Wms`
diff --git a/docs/plans/2026-03-25-large-repo-map-followup.md b/docs/plans/2026-03-25-large-repo-map-followup.md
deleted file mode 100644
index dc293c87..00000000
--- a/docs/plans/2026-03-25-large-repo-map-followup.md
+++ /dev/null
@@ -1,154 +0,0 @@
-# Large Repo `ix map` Follow-up
-
-Date: 2026-03-25
-
-## Current user workflow
-
-Use `ix map` only.
-
-Do not assume `ix ingest` is part of the normal workflow anymore. Any large-repo performance work needs to be evaluated through `ix map`, since `ix map` triggers ingest first and that is what the user experiences.
-
-## Main problem
-
-Large repos improved for map computation, but ingest/save regressed badly.
-
-Observed user report for Kubernetes:
-
-- `ix map` total ingest time on current branch: about `466s`
-- `ix map` total map time on current branch: about `53s`
-- Earlier target / expected behavior from dev: ingest closer to `90s`
-- Previous map-only improvement target: Kubernetes map around `20s`
-
-Observed debug sample from user:
-
-- `files=16010`
-- `resolveEdgesMs=29581`
-- `buildPatchMs=10156`
-- `commitMs=386443`
-- `totalSaveMs=426834`
-
-Conclusion: the dominant regression is still in the save/commit path, not parse, resolve, or map clustering.
-
-## Confirmed issues
-
-### 1. Save path is the bottleneck on large repos
-
-Client debug logs showed repeated slow commit chunks during saving, for example:
-
-- `commit 3401-3600 ... (15s)`
-- `commit 5601-5800 ... (17s)`
-- `commit 7801-8000 ... (25s)`
-
-This points at backend bulk commit behavior, especially chunk sizing and/or Arango bulk insert characteristics on large batches.
-
-### 2. `ix map` output had duplicate top-level regions
-
-The map output showed repeated roots like:
-
-- `MODULE Edges`
-- `SUBSYSTEM Edges`
-- `SYSTEM Edges`
-
-and similarly for `Builder`.
-
-Cause found:
-
-- the same file set could survive across multiple hierarchy levels
-- those duplicate regions shared the same deterministic region ID
-- they were all rendered as roots/orphans
-
-Status:
-
-- fixed in code by collapsing duplicate hierarchy levels to the coarsest retained region
-- regression test added
-- verified on a fresh backend
-
-Remaining note:
-
-- `Edges` and `Builder` may still appear once each as top-level systems because they are still weakly connected / isolated in the graph
-- that is a separate modeling issue from the duplicate-root bug
-
-## Changes already made
-
-### Map hierarchy fix
-
-Updated:
-
-- `memory-layer/src/main/scala/ix/memory/map/MapService.scala`
-- `memory-layer/src/test/scala/ix/memory/map/MapServiceScopeSpec.scala`
-
-What changed:
-
-- collapse duplicate same-member-set regions across module/subsystem/system levels
-- keep only the coarsest retained region
-- preserve children pointing at that surviving region
-
-### Ingest/save tuning already tried
-
-Updated:
-
-- `ix-cli/src/cli/commands/ingest.ts`
-- `memory-layer/src/main/scala/ix/memory/db/BulkWriteApi.scala`
-
-What changed:
-
-- reduced client bulk HTTP batch size from `1000` files to `200`
-- reduced backend revision chunk size from `500` files to `100`
-- reduced backend payload cap from `16MB` to `4MB`
-- capped patch document insert batches instead of inserting arbitrarily large patch arrays
-
-## Measured result after tuning
-
-On a fresh isolated backend, full ingest of this repo improved from an earlier sample with:
-
-- `commitMs ~10899`
-
-to:
-
-- `commitMs 4021`
-- total ingest `5.48s` for `221` changed files
-
-This confirms the chunk-size rollback helped on the repo-sized benchmark.
-
-## What is still unresolved
-
-The large-repo `ix map` path for Kubernetes is still much too slow.
-
-Even after chunk-size reductions, the real user-facing test case remains:
-
-- `ix map <kubernetes repo>`
-
-and the unresolved part is:
-
-- save/commit time at large scale
-
-## What to collect next
-
-Since the user uses `ix map`, collect logs from `ix map`, not a standalone `ix ingest` run.
-
-Needed evidence next time:
-
-1. Client-side `ix map` debug output including:
- - slow saving lines
- - final `[ingest-save]` line
- - final `ingest Xms · map Yms`
-2. Backend `memory-layer` logs at the same time, especially `ix.bulk-write` timings
-3. Identify which backend stage dominates:
- - `insertNodes`
- - `insertEdges`
- - `insertClaims`
- - `insertPatches`
- - tombstoning / retiring old claims
- - revision update
-
-## Likely next investigation targets
-
-1. Arango bulk insert performance for edges and patches on very large repos
-2. Whether generated files (`zz_generated`, `.pb.go`, deepcopy/defaults, etc.) should be skipped or downgraded during `ix map`
-3. Whether `ix map` should use a cheaper ingest mode than full graph ingest for very large repos
-4. Whether chunk sizing should adapt dynamically based on actual commit latency rather than fixed file counts
-5. Whether large repo map should avoid persisting some low-value entities/claims during the map-triggered ingest path
-
-## Operational note
-
-If a fix appears to work in code but not in normal `ix map` output, confirm the running backend has actually been restarted. During this session, the old `8090` backend continued serving stale behavior until a fresh backend process was started separately.
diff --git a/docs/plans/ingestion-perf-fix.md b/docs/plans/ingestion-perf-fix.md
deleted file mode 100644
index 1d07a5ec..00000000
--- a/docs/plans/ingestion-perf-fix.md
+++ /dev/null
@@ -1,140 +0,0 @@
-# Ingestion Performance Fix
-
-## Context
-
-`core-ingestion/src/index.ts` on this branch added chunk extraction (`ParsedChunk`) which is
-great, but introduced 3 regressions vs the fast baseline. Fix all three.
-
-## Change Tracking
-
-This section is the handoff record for follow-up review and bug fixing.
-
-### Files changed
-
-- `core-ingestion/src/index.ts`
- Restored a module-level tree-sitter query cache, replaced `source.split('\n')`
- with a character-scan line counter, and moved per-definition chunk hash work
- into a post-match pass using a `pendingChunks` buffer. Also added one explicit
- `(s: string)` type annotation in existing import parsing code so the package
- still builds under the current TypeScript settings.
-- `docs/plans/ingestion-perf-fix.md`
- Added this change-tracking section and will keep verification notes here.
-
-### Verification notes
-
-- `core-ingestion`: `npm run build` passed on 2026-03-22
-- `ix map` cold-ingest check: not run; skipped because `ix reset --code -y`
- mutates indexed state and was not necessary to complete the code change
-
----
-
-## Fix 1 — Restore the per-process query cache (CRITICAL)
-
-**File:** `core-ingestion/src/index.ts`
-
-**Problem:** `parseFile()` currently calls `new Parser.Query(grammar, queries)` on every
-invocation. Compiling a tree-sitter query (S-expression → automata) is expensive. With
-100 TypeScript files, it compiles the same TS query 100 times.
-
-**Fix:** Add a module-level query cache (already existed in the baseline) and use it inside
-`parseFile()`.
-
-Add this block near the existing `_parser` singleton (around line 180):
-
-```typescript
-// Per-process cache for compiled tree-sitter queries, keyed by language.
-// Avoids recompiling the same query string for every file of the same language.
-const _queryCache = new Map<SupportedLanguages | 'tsx', { grammar: any; query: any }>();
-
-function getCachedQuery(language: SupportedLanguages | 'tsx', grammar: any, querySource: string): any {
- const cached = _queryCache.get(language);
- if (cached && cached.grammar === grammar) return cached.query;
- const query = new Parser.Query(grammar, querySource);
- _queryCache.set(language, { grammar, query });
- return query;
-}
-```
-
-Then inside `parseFile()`, replace:
-```typescript
-const query = new Parser.Query(grammar, queries);
-```
-with:
-```typescript
-const cacheKey = isTsx ? 'tsx' as const : language;
-const query = getCachedQuery(cacheKey, grammar, queries);
-```
-
----
-
-## Fix 2 — Replace `source.split('\n')` with a char scan
-
-**File:** `core-ingestion/src/index.ts`
-
-**Problem:** `const lines = source.split('\n')` allocates a full string array only used for
-`lines.length` and `lines.length` in the `file_body` fallback chunk. Wasteful on large files.
-
-**Fix:** Replace the split with a char scan for the line count, and keep a separate
-`sourceLineCount` variable. Use it wherever `lines.length` is currently referenced.
-
-Replace:
-```typescript
-const lines = source.split('\n');
-```
-with:
-```typescript
-let sourceLineCount = 1;
-for (let i = 0; i < source.length; i++) { if (source.charCodeAt(i) === 10) sourceLineCount++; }
-```
-
-Then replace every reference to `lines.length` with `sourceLineCount`.
-
----
-
-## Fix 3 — Move chunk SHA-256 hashing out of the hot definition loop
-
-**File:** `core-ingestion/src/index.ts`
-
-**Problem:** Inside the first-pass definition loop, every definition does:
-```typescript
-const chunkText = source.slice(startByte, endByte);
-const contentHash = crypto.createHash('sha256').update(chunkText).digest('hex').slice(0, 16);
-```
-This runs a full SHA-256 for every function/class/method at parse time. For a file with
-20 definitions that's 20 crypto operations, plus the `source.slice()` allocations.
-
-**Fix:** Keep the chunk data (startByte, endByte) in a temporary structure during the loop,
-then compute all content hashes in a single pass after the loop completes. This doesn't
-change output — just batches the hashing after the tree-sitter work is done so the two
-phases don't interleave.
-
-Concretely: collect `{ name, kind, lineStart, lineEnd, startByte, endByte, language, container }`
-into a `pendingChunks` array during the loop, then after the loop iterate `pendingChunks`
-to compute `contentHash` and push into `chunks[]`. The `file_body` fallback should also
-keep its hash computation (it's only one hash for the whole file when no chunks exist).
-
----
-
-## Do NOT change
-
-- The `ParsedChunk` interface and its fields — keep as-is.
-- The chunk ops in `patch-builder.ts` (`CONTAINS_CHUNK`, `DEFINES`, `NEXT` edges) — keep as-is.
-- The `buildPatchWithResolution` function — keep as-is.
-- `resolveEdges` in `index.ts` — keep as-is.
-- The `_parser` singleton — keep as-is.
-- All query string constants in `queries.ts` — keep as-is.
-
----
-
-## Verification
-
-After the changes, run:
-
-```bash
-cd core-ingestion && npm run build
-ix reset --code -y && IX_DEBUG=1 ix map
-```
-
-Expected: parse phase timing should drop from ~9s to ~2-3s for 200 files. The
-`Source hash lookup: 0 known hashes` line confirms a clean cold ingest.
-The map output should still show chunk-based regions (the visual output should be unchanged).
diff --git a/docs/plans/map-algorithm-overhaul.md b/docs/plans/map-algorithm-overhaul.md
deleted file mode 100644
index aa4cef10..00000000
--- a/docs/plans/map-algorithm-overhaul.md
+++ /dev/null
@@ -1,256 +0,0 @@
-# ix map Algorithm: Speed & Accuracy Overhaul
-
-**Plan ID:** `46ecf20c-8bb2-9e54-121b-f5388adc8156`
-**Goal ID:** `ec6a17f4-3d75-4a18-a614-c23e3fd709ae`
-
----
-
-## Overview
-
-`ix map` runs a multi-level Louvain community detection algorithm over a weighted file-coupling graph built from the knowledge graph. This document tracks planned improvements to make it both faster and more accurate.
-
-Pipeline stages:
-
-```
-ArangoDB → WeightedFileGraph → (crosscut penalty) → Louvain → Regions → Labels → Confidence → Persist
-```
-
----
-
-## Implementation Status
-
-Status: implemented in code.
-
-What shipped:
-
-- `MapGraphBuilder.fetchCouplingByUri` no longer builds a giant `MERGE` map. It now resolves edge endpoints with direct `nodes` lookups keyed by `logical_id` and aggregates with `COLLECT ... WITH COUNT`.
-- `MapGraphBuilder.liveFileCount` now uses `COLLECT WITH COUNT` instead of loading all file rows.
-- `MapGraphBuilder.computeGraph` now precomputes directory segments once, short-circuits same-directory path proximity to `1.0`, and caps synthetic structural edge growth with `MaxEdges`.
-- `WeightedFileGraph` now carries `predicatePairs`, which restores dominant signal computation downstream.
-- `LouvainClustering.cluster` now runs three deterministic seeds, applies adaptive resolution by repository size, stops on modularity-gain convergence instead of a fixed 30-pass cap, and uses in-place Fisher-Yates shuffle.
-- `MapService` now uses the tuned signal weights:
- - `CALLS = 1.0`
- - `IMPORTS = 0.5`
- - `EXTENDS/IMPLEMENTS = 1.2`
- - `PATH = 0.2`
-- The CLI text renderer now defaults to the hierarchy graph view, with the ranked list preserved behind `ix map --list`.
-- Cross-cut token detection was expanded with layer/framework tokens including `service`, `controller`, `repository`, `handler`, `middleware`, `model`, `entity`, `dto`, `interface`, `types`, and `errors`.
-- Confidence scoring now uses:
-
-```scala
-val brScore = tanh(boundaryRatio / 2.5)
-val cohScore = cohesion.min(1.0)
-val sizeBonus = tanh(size / 8.0)
-val crossPenalty = crosscutScore * 0.4
-```
-
-- Labeling now prefers filtered suffixes first, then discriminative directory scoring, then filename-token fallback. Weak suffix tokens like `api`, `service`, and `common` no longer win by default.
-- `dominant_signals` is now populated from real intra-region predicate counts instead of being emitted empty.
-
-Validation summary:
-
-- `sbt memoryLayer/compile` passed after the changes.
-- A fresh backend using the new build returned `empty_dominant_signals = 0`.
-- Sequential timing checks on this repo remained within the target range for a repo of this size, though end-to-end `ix map` time here is heavily influenced by ingest/persist overhead rather than the clustering math alone.
-
----
-
-## Current Known Issues
-
-### Speed
-
-| Location | Issue | Severity |
-|---|---|---|
-| `MapGraphBuilder.fetchCouplingByUri` | AQL `MERGE` over all live nodes to build `uri_map` — full collection scan on every call | High |
-| `MapGraphBuilder.fetchFiles` | Full table scan, no index on `kind` | Medium |
-| `MapGraphBuilder.currentInputRev` | Two separate full table scans (nodes + edges) | Medium |
-| `MapGraphBuilder.liveFileCount` | Calls `fetchFiles()` just to count — fetches all data unnecessarily | Low |
-| `MapGraphBuilder.computeGraph` (path-proximity pass) | O(n²) within each directory — 100-file directory = 4,950 pairs; `pathProximity` called per pair with string splits | High |
-| `MapGraphBuilder.pathProximity` | Splits path strings on every call, no precomputation | Medium |
-| `LouvainClustering.louvainPass` | `rng.shuffle(nodes)` on every pass — allocates new list up to 30× | Low |
-| `MapService.applyPenalty` | Copies full adjacency map — could be done in-place since graph is not reused | Low |
-| `MapService.loadCachedMap` → `liveFileCount` | Separate DB round trip just to populate `fileCount` | Low |
-
-### Accuracy
-
-| Location | Issue | Severity |
-|---|---|---|
-| `MapService.buildOneRegion` | `dominantSignals` always `[]` — per-predicate counts lost after graph construction | Medium |
-| Signal weights (α=1.0 β=0.7 γ=0.9 ε=0.3) | Arbitrary, not empirically validated | Medium |
-| `crosscutTokens` set | Missing common framework terms: "service", "controller", "repository", "handler", "middleware" | Medium |
-| `computeConfidence` weights (0.4/0.3/0.3) | Ad-hoc formula, not validated against real-world repo quality | Low |
-| `inferLabel` | Strategy 1 (longest common dir suffix) fires before the better strategy 2 (discriminative segment scoring) — can produce misleading labels for deeply nested monorepos | Medium |
-| Louvain resolution fixed at 1.0 | Higher resolution → smaller communities; lower → larger. Should adapt to repo size or be tunable | Medium |
-| Louvain seed fixed at 42 | Single deterministic run may hit local optima — multiple seeds with best-modularity selection improves stability | Low |
-| `minCommunitySize` hardcoded | 3 for 3-level repos, 2 otherwise — should scale with repo size | Low |
-
----
-
-## Tasks
-
-### Task 1 — Optimize AQL queries in MapGraphBuilder
-**ID:** `adb844f1-62a3-98f2-a27e-33cc50364ae0`
-
-The two costliest DB operations:
-
-**`fetchCouplingByUri` MERGE approach:**
-```aql
-LET uri_map = MERGE(
- FOR n IN nodes FILTER ... RETURN {[n.logical_id]: n.provenance.source_uri}
-)
-```
-`MERGE` over thousands of nodes is slow and memory-heavy. Replace with a direct join:
-```aql
-FOR e IN edges
- FILTER e.predicate IN @predicates AND e.deleted_rev == null
- LET sn = FIRST(FOR n IN nodes FILTER n.logical_id == e.src ... RETURN n.provenance.source_uri)
- LET dn = FIRST(FOR n IN nodes FILTER n.logical_id == e.dst ... RETURN n.provenance.source_uri)
- FILTER sn != null AND dn != null AND sn != dn
- COLLECT srcUri = sn, dstUri = dn, pred = e.predicate WITH COUNT INTO cnt
- RETURN {srcUri, dstUri, predicate: pred, count: cnt}
-```
-Or with `AQL FOR` subqueries if the ArangoDB index on `logical_id` is usable (it should be, as it's the document key).
-
-**`liveFileCount`:** Replace with a `COLLECT WITH COUNT` query instead of fetching all file data.
-
-**`currentInputRev`:** Benchmark whether combining into one AQL pass is faster.
-
----
-
-### Task 2 — Fix O(n²) path-proximity pass
-**ID:** `9544f83f-e0bb-8973-aa1c-a4d642a63ef0`
-
-**Problem:** The same-directory edge pass is:
-```scala
-for (i <- dirFiles.indices; j <- (i + 1) until dirFiles.size) {
- pathProximity(sv.path, dv.path) // splits strings every call
-}
-```
-For a directory with D files, this is O(D²) calls. Monorepos can have 50+ files in src/.
-
-**Fix:**
-1. Precompute `dirSegments: Map[NodeId, Array[String]]` for all files once.
-2. Replace `pathProximity(a, b)` with an index lookup using precomputed segments.
-3. For same-directory files the result is always `1.0 / (1.0 + 0)` = 1.0 — can hardcode for the same-dir case.
-4. Add an `adjMut.size > MaxEdges` safety cap to prevent quadratic blowup in dense directories.
-
----
-
-### Task 3 — Improve Louvain convergence and stability
-**ID:** `ca2b0225-c97d-77bf-021f-32b6e1b51884`
-
-**Multi-seed best-of selection:**
-```scala
-val runs = (1 to 3).map(seed => louvainPass(graph, resolution, new Random(seed)))
-val best = runs.maxBy(a => modularity(graph, a))
-```
-3 runs with different seeds, pick the one with highest modularity. Cost: 3× but more stable results.
-
-**Adaptive resolution:**
-- Small repos (< 50 files): resolution 1.2 (prefers smaller, tighter communities)
-- Medium repos (50–500 files): resolution 1.0 (default)
-- Large repos (> 500 files): resolution 0.8 (allows larger communities, avoids over-fragmentation)
-
-**Convergence check:** The 30-pass hard cap is arbitrary. Add a modularity delta check — stop when ΔQ < 1e-6 rather than forcing 30 passes.
-
-**`rng.shuffle` allocation:** Use Fisher-Yates in-place shuffle on an `Array[NodeId]` instead of `rng.shuffle(nodes)` which allocates a new `Vector` each pass.
-
----
-
-### Task 4 — Tune signal weights, crosscut detection, and confidence formula
-**ID:** `fc9c3ec1-5b6e-3889-8974-ecc9d6dc8995`
-
-**Signal weights — proposed tuned values:**
-
-| Signal | Current | Proposed | Rationale |
-|---|---|---|---|
-| α (CALLS) | 1.0 | 1.0 | Keep as anchor |
-| β (IMPORTS) | 0.7 | 0.5 | Imports are noisier than calls in TypeScript/Python; over-weighted |
-| γ (EXTENDS/IMPLEMENTS) | 0.9 | 1.2 | Type hierarchy is a very strong cohesion signal, especially in Scala/Java |
-| ε (path proximity) | 0.3 | 0.2 | Structural prior should be weak; files in same dir ≠ same subsystem |
-
-**Crosscut token expansion:**
-```scala
-CrosscutTokens = Set(
- // existing
- "util", "utils", "helper", "helpers", "common", "shared", "base",
- "logging", "log", "logger", "config", "conf", "constants", "constant",
- "extensions", "ext", "mixin", "mixins", "core", "framework",
- // add: framework layer names
- "service", "services", "controller", "controllers",
- "repository", "repositories", "repo", "handler", "handlers",
- "middleware", "interceptor", "filter", "filters",
- "model", "models", "entity", "entities", "dto", "dtos",
- "interface", "interfaces", "types", "errors", "exceptions"
-)
-```
-These are all cross-cutting by nature in layered architectures.
-
-**`computeConfidence` — boundary ratio saturation:**
-
-Current `brScore = tanh(br / 3.0)` saturates at br ≈ 9. Real repos often have br in 0.5–5 range, so the curve is well-placed. But the size bonus `tanh(size / 10)` gives half-credit to 7-file regions. Proposed:
-```scala
-val brScore = math.tanh(boundaryRatio / 2.5) // slightly tighter saturation
-val cohScore = cohesion.min(1.0)
-val sizeBonus = math.tanh(size / 8.0) // penalize tiny regions more
-val crossPenalty = crosscutScore * 0.4 // stronger crosscut penalty
-```
-
----
-
-### Task 5 — Restore dominant_signals and improve label inference
-**ID:** `8c897b67-c639-5705-c0d3-4278b4fa54f3`
-
-**Dominant signals:**
-The `dominantSignals` field was cleared in the bug-fix review because `signalCounts` was never populated. The right fix is to thread per-predicate counts through from `MapGraphBuilder` into `buildOneRegion`.
-
-Option A: Add `predicateCounts: Map[(NodeId,NodeId), Map[String,Int]]` to `WeightedFileGraph` (keeps graph builder responsible).
-
-Option B: In `buildOneRegion`, iterate the adjacency and compute a signal breakdown from the raw weights by inverting the weight formula (approximate).
-
-Option A is cleaner. Add to `WeightedFileGraph`:
-```scala
-final case class WeightedFileGraph(
- vertices: Vector[FileVertex],
- adjMatrix: Map[NodeId, Map[NodeId, Double]],
- degrees: Map[NodeId, Double],
- totalWeight: Double,
- predicatePairs: Map[(NodeId, NodeId), Map[String, Int]] // NEW
-)
-```
-
-**Label inference — fix strategy order:**
-
-Strategy 1 (longest common suffix) fires even when the common segment is a noise token like "api" or "db". Proposed:
-
-1. Try longest common suffix after filtering noise tokens (current).
-2. If result length < 3 chars, fall through to strategy 2.
-3. Strategy 2 (discriminative depth-weighted segments) should be weighted by _intra-cluster_ frequency vs. _corpus_ frequency — a segment appearing in 80% of this cluster but only 10% of all files is highly discriminative.
-4. Fallback: most frequent camelCase token from filenames.
-
----
-
-## Performance Benchmarks Needed
-
-Before tuning, establish baselines on this repo:
-
-```bash
-time ix map --format json > /dev/null # end-to-end
-time ix map --format json > /dev/null # second run (should hit cache)
-```
-
-Target metrics:
-- Cold map (no cache): < 5s for this repo (~150 files)
-- Cache hit: < 500ms
-- Large repo (2000+ files): < 30s cold, < 1s cached
-
----
-
-## Files Affected
-
-| File | Changes |
-|---|---|
-| `memory-layer/src/main/scala/ix/memory/map/MapGraphBuilder.scala` | Tasks 1, 2 |
-| `memory-layer/src/main/scala/ix/memory/map/LouvainClustering.scala` | Task 3 |
-| `memory-layer/src/main/scala/ix/memory/map/MapService.scala` | Task 4, 5 |
-| `memory-layer/src/main/scala/ix/memory/map/MapTypes.scala` | Task 5 (add `predicatePairs` to `WeightedFileGraph`) |
diff --git a/docs/plans/map-algorithm-review.md b/docs/plans/map-algorithm-review.md
deleted file mode 100644
index 748fe938..00000000
--- a/docs/plans/map-algorithm-review.md
+++ /dev/null
@@ -1,334 +0,0 @@
-# ix map Performance + Scalability Fix Plan
-
-**Files reviewed:** `MapGraphBuilder.scala`, `MapService.scala`, `LouvainClustering.scala`, `MapTypes.scala`
-**Date:** 2026-03-22
-
----
-
-## Change Tracking
-
-This section is the running handoff record for follow-up review and bug fixing.
-
-### Files changed
-
-- `memory-layer/src/main/scala/ix/memory/map/MapGraphBuilder.scala`
- Rewrote `fetchCouplingByUri()` to build a single `logical_id -> source_uri`
- lookup map inside AQL, pushed source-extension filtering into `fetchFiles()`,
- added directory-size guardrails for path-proximity edges, and changed
- `currentInputRev()` to use a dedicated `source-graph` revision with a scan
- fallback for older data.
-- `memory-layer/src/main/scala/ix/memory/map/MapService.scala`
- Replaced O(R²) parent wiring in `buildRegions()` with partition-based lookup,
- removed subset-scan recomputation from `rehydrateRelationships()`, trimmed
- `CrosscutTokens`, replaced the max-degree heuristic with a real percentile
- cutoff, and precomputed signal adjacency so dominant-signal scoring only
- touches region-local incident pairs.
-- `memory-layer/src/main/scala/ix/memory/map/LouvainClustering.scala`
- Added seed gating for small graphs and reused the community-weight map inside
- the hot Louvain loop instead of allocating it per node.
-- `memory-layer/src/main/scala/ix/memory/db/BulkWriteApi.scala`
- Updated revision writes so bulk ingestion advances both the global revision
- and the dedicated `source-graph` revision.
-- `memory-layer/src/main/scala/ix/memory/db/ArangoGraphWriteApi.scala`
- Added source-graph revision tracking for patch commits that touch map inputs,
- while leaving derived writes on the global revision only.
-- `docs/plans/map-algorithm-review.md`
- Revised the recommendations so they match the current codebase, added this
- tracking section, and recorded implementation and verification status.
-
-### Implementation notes
-
-- `currentInputRev()` needs a dedicated source-graph revision, not just the
- global revision, because non-map-input writes also advance the main revision
- counter.
-- `buildRegions()` can use partition assignments directly, but only after
- accounting for communities filtered out by `minCommunitySize`.
-- `CrosscutTokens` cleanup should be paired with a fix to the current
- pseudo-percentile degree threshold.
-
-### Verification notes
-
-- Build: `sbt memoryLayer/compile` passed on 2026-03-22
-- Runtime benchmark: not run
-- `ix map` end-to-end validation: not run in this pass
-
----
-
-## TL;DR
-
-Primary bottlenecks:
-
-1. O(E × N) database query in `fetchCouplingByUri()`
-2. Full graph scan per run in `currentInputRev()`
-3. O(R²) region construction in `buildRegions()`
-
-These issues cause `ix map` to degrade from near-linear toward quadratic behavior, leading to Docker crashes and unusable performance on large codebases.
-
-Fixing these should reduce runtime from minutes to seconds for 500-2,000 file repos.
-
----
-
-## Summary
-
-The algorithm is architecturally correct: multi-level Louvain plus weighted signals is the right direction.
-
-The problem is **scalability**, not correctness.
-
-**Severity legend:** Critical / High / Medium / Low
-
----
-
-# 1. Critical Bottlenecks
-
-## `fetchCouplingByUri()` - O(E × N) correlated subqueries
-
-Each edge performs two full scans over `nodes` to resolve `src` and `dst`. Without an index on `logical_id`, this is O(E × N) - for 5,000 edges and 50,000 nodes that's 250M comparisons per `ix map`.
-
-**Fix (preferred):** build the URI map once, then join:
-
-```aql
-LET uriMap = (
- FOR n IN nodes
- FILTER n.deleted_rev == null
- AND n.provenance.source_uri != null
- AND n.kind NOT IN @ignoredKinds
- RETURN { id: n.logical_id, uri: n.provenance.source_uri }
-)
-
-LET byId = ZIP(uriMap[*].id, uriMap[*].uri)
-
-FOR e IN edges
- FILTER e.predicate IN @predicates
- AND e.deleted_rev == null
- LET su = byId[e.src]
- LET du = byId[e.dst]
- FILTER su != null AND du != null AND su != du
- COLLECT srcUri = su, dstUri = du, pred = e.predicate WITH COUNT INTO cnt
- RETURN { srcUri, dstUri, predicate: pred, count: cnt }
-```
-
-**Alternative:** add a persistent index on `nodes.logical_id`. Cuts each subquery from O(N) to O(log N) without rewriting the query.
-
----
-
-## `currentInputRev()` - full graph scan per run
-
-Runs a MAX aggregation over all nodes and edges on every `ix map` call, even when the graph is unchanged and the cached map will be reused.
-
-**Fix:** maintain a dedicated source-graph revision entry updated only when source-graph inputs change. Do not reuse the global revision counter directly, because map persistence and other derived writes also advance it.
-
-One viable implementation is a separate revisions entry:
-
-```json
-{ "_key": "source-graph", "rev": 123 }
-```
-
-Then `currentInputRev()` becomes a single key lookup, with a fallback full scan only for older databases that do not yet have the dedicated metadata:
-
-```aql
-FOR doc IN revisions
- FILTER doc._key == "source-graph"
- LIMIT 1
- RETURN doc.rev
-```
-
-Result: O(1) instead of O(N + E).
-
----
-
-# 2. High Priority Fixes
-
-## `buildRegions()` - O(R²) parent-child wiring
-
-Currently calls `region.memberFiles.subsetOf(p.memberFiles)` for every `(region, parent)` pair. Replace with a direct lookup from the Louvain partition, but preserve correctness when some communities are filtered out by `minCommunitySize`:
-
-```scala
-val fileToParent: Map[NodeId, Int] = coarseLevel.assignment
-
-val parentOpt = memberFiles.headOption
- .flatMap(fileToParent.get)
- .flatMap(coarseRegionByCommunity.get)
-```
-
-Where `coarseRegionByCommunity` only contains retained coarse communities, and equal-set coarse regions should still be treated as "no parent" to match the current hierarchy behavior.
-
----
-
-## `rehydrateRelationships()` - remove recomputation
-
-`parentId` and `childRegionIds` are already persisted on region nodes. Do not rerun the subset scan on cache load. Wire children directly from the loaded data:
-
-```scala
-val childrenByParent = regions
- .flatMap(r => r.parentId.map(pid => pid -> r.id))
- .groupBy(_._1)
- .view
- .mapValues(_.map(_._2).toSet)
- .toMap
-```
-
----
-
-## `CrosscutTokens` - too many false positives
-
-Tokens like `"service"`, `"controller"`, `"repository"`, `"model"`, `"entity"`, `"dto"` are standard naming conventions, not cross-cutting concerns. Flagging them applies a penalty to the coupling signals that should cluster those files together.
-
-Also fix the degree-side heuristic: the current code uses `maxDeg * 0.9`, which is not actually "top 10% by degree". If percentile behavior matters, compute it from the observed degree distribution instead of scaling the maximum.
-
-Remove architectural terms. Keep only genuine horizontal concerns:
-
-```scala
-private val CrosscutTokens = Set(
- "util", "utils", "helper", "helpers", "common", "shared",
- "logging", "config", "constants", "base"
-)
-```
-
----
-
-# 3. Medium Fixes
-
-## `computeDominantSignals()` - O(total edges) per region
-
-Iterates all `graph.predicatePairs` for each region. Build a per-file signal index once before the region loop so each region only touches incident pairs for its own members.
-
-```scala
-Map[NodeId, Vector[(NodeId, Map[String, Int])]]
-```
-
----
-
-## Path proximity - O(N²) per directory
-
-Only run the path proximity pass for directories with between 2 and 50 files. Large flat directories (generated code, fixtures) add noise and inflate the graph without contributing architectural signal.
-
-Also push source-extension filtering into the `fetchFiles()` AQL so the JVM does not deserialize non-source file rows it will drop anyway.
-
----
-
-## Louvain optimizations
-
-**Seed gating** - skip the extra two seeds for small graphs:
-
-```scala
-val numSeeds = if (graph.vertices.size < 30) 1 else 3
-```
-
-**Avoid map allocation in hot loop** - allocate once and clear per node:
-
-```scala
-val wToComm = mutable.HashMap[Int, Double]()
-// inside the loop:
-wToComm.clear()
-```
-
----
-
-# 4. Graph Guardrails
-
-Hard limits to prevent runaway memory and time on large repos:
-
-**Node limits:**
-- V > 5,000: disable path proximity edges; cap soft edges per node at 5
-- V > 10,000: switch to coarse mode (directory-level clustering only)
-
-**Density limits:**
-- E / V > 50: prune lowest-weight edges before clustering
-
-**Edge budget by type:**
-- Structural edges (imports, calls): unlimited
-- Path similarity: max 3 per node
-
----
-
-# 5. Execution Plan
-
-## Phase 1 - Database
-
-- Fix `fetchCouplingByUri()` query
-- Replace `currentInputRev()` with dedicated source-graph revision metadata
-
-**Validate:** identical output, runtime measurably reduced.
-
-## Phase 2 - Region construction
-
-- Replace `buildRegions()` subset scan with direct lookup
-- Remove recomputation in `rehydrateRelationships()`
-- Precompute dominant-signal adjacency once per graph
-
-**Validate:** same region hierarchy, no missing parents.
-
-## Phase 3 - Graph density controls
-
-- Limit path proximity to small/medium directories
-- Push source-extension filtering into the DB query
-
-**Validate:** lower edge count on large flat trees with no missing file vertices.
-
-## Phase 4 - Louvain optimization
-
-- Seed gating by graph size
-- Reuse `wToComm` map across iterations
-
-**Validate:** clustering stable across runs, runtime improved.
-
-## Phase 5 - Cross-cut cleanup
-
-- Fix `CrosscutTokens`
-- Replace the pseudo-percentile threshold with a real percentile cutoff
-
-## Phase 6 - Scaling safeguards
-
-- Implement graph guardrails
-- Add coarse mode for V > 10,000
-
----
-
-# 6. Constraints
-
-- Output of `ix map` should remain materially consistent: same broad region membership and hierarchy unless a heuristic fix explicitly justifies a behavior change
-- Do not introduce new edge types
-- Do not alter signal weights without justification
-
----
-
-# 7. Anti-Patterns
-
-- O(N²) similarity computations across the whole repo
-- Full collection scans inside per-edge or per-node loops
-- Per-node or per-edge database queries
-- Rebuilding the full graph on every cache lookup
-- Dense adjacency matrices
-
----
-
-# 8. Success Criteria
-
-| Metric | Target |
-|---|---|
-| `fetchCouplingByUri` | < 100ms for 10k edges |
-| `currentInputRev` | < 5ms |
-| 500 files | < 5s end-to-end |
-| 2,000 files | < 10s end-to-end |
-
----
-
-# 9. Priority Order
-
-| Priority | Fix |
-|---|---|
-| 1 | `fetchCouplingByUri` query rewrite |
-| 2 | `currentInputRev` dedicated source-graph revision |
-| 3 | Path proximity directory-size guardrail |
-| 4 | `CrosscutTokens` cleanup + real percentile threshold |
-| 5 | `rehydrateRelationships` recompute removal |
-| 6 | `buildRegions` O(R²) replacement |
-| 7 | Louvain seed gating + map reuse |
-
----
-
-## Final Note
-
-Target complexity: **O(V + E)**.
-
-If performance degrades superlinearly, the graph is too dense or queries are unindexed. Diagnose with `IX_DEBUG=1 ix map` and inspect per-phase timing before adding more signal types or hierarchy levels.
diff --git a/docs/plans/subsystem-explain.md b/docs/plans/subsystem-explain.md
deleted file mode 100644
index a9077221..00000000
--- a/docs/plans/subsystem-explain.md
+++ /dev/null
@@ -1,514 +0,0 @@
-# `ix subsystems <target> --explain`
-
-**Date:** 2026-03-22
-
----
-
-## Overview
-
-`ix explain` produces a narrative breakdown of an individual symbol (function, class, file).
-`ix subsystems <target> --explain` does the same thing one level up — for an architectural
-region produced by `ix map`.
-
-The goal is to answer: *"What is this subsystem, what does it contain, how healthy is it, and
-why does it matter?"* — in plain English, with enough structural context that a developer new
-to the codebase can orient themselves immediately.
-
----
-
-## Reality Check
-
-The basic shape of this plan is correct, but the current codebase has two gaps the original
-draft did not account for:
-
-1. The existing scoped subsystem payload is sufficient for most of `--explain`, but it does
- **not** currently expose enough revision metadata to support a reliable
- `"health score may be stale"` note.
-2. Large-repo ingestion is currently fragile for architectural reasons that are adjacent to
- this feature work: the ingest path materializes too much in memory, queries too much state
- up front, and emits oversized patch payloads for non-code files.
-
-This document now covers both:
-- the concrete changes required for `ix subsystems <target> --explain`
-- the concrete changes required to stop ingestion from failing on large repositories
-
----
-
-## Change Tracking
-
-### Files changed
-
-- `docs/plans/subsystem-explain.md`
- Expanded the plan so it reflects the current subsystem APIs and the large-repo ingestion
- failure modes discovered during code review.
-
-### Verification notes
-
-- Doc-only update; no code or tests run in this pass.
-
----
-
-## CLI Interface
-
-```
-ix subsystems <target> --explain
-ix subsystems <target> --explain --format json
-ix subsystems <target> --explain --pick <n>
-```
-
-`--explain` is a new flag on the existing `subsystems` command, layered on top of the current
-target-scoping behaviour. It is mutually exclusive with `--list`.
-
-**Examples:**
-
-```
-ix subsystems api --explain
-ix subsystems "Ingestion Layer" --explain
-ix subsystems auth --explain --pick 2
-ix subsystems auth --explain --format json
-```
-
-`--pick` resolves ambiguous matches the same way it does today.
-
----
-
-## Data Sources
-
-Two existing server calls are combined — no new endpoints required.
-
-| Data | Source |
-|---|---|
-| Region label, level, parent, children, files, confidence, dominant signals, cross-cutting flag | `GET /v1/subsystems/map?target=…` → `ScopedSubsystemResult` |
-| Health score, chunk density, smell rate, smell files, total chunks | `GET /v1/subsystems` → `SubsystemScore[]`, filtered to the resolved region id |
-
-If the health score has not yet been computed for the region (e.g. `ix map` was run but
-`ix subsystems` has not been run since), the Health section is omitted and a note is printed:
-`Run 'ix subsystems' to compute health scores.`
-
-### Current Data Contract Gap
-
-The current score payload is enough to render Health, but not enough to prove staleness.
-
-Today:
-- `GET /v1/subsystems/map` returns scoped region structure without score metadata.
-- `GET /v1/subsystems` returns health scores without a `map_rev` or score revision field.
-
-That means this note from the original draft is **not implementable as written**:
-
-`Health score may be stale — run 'ix subsystems' to refresh.`
-
-To support that note cleanly, one of these must change:
-
-1. Add `map_rev` to each stored subsystem score result.
-2. Add score `created_rev` or score computation revision to the list response.
-3. Remove the stale-health note from v1 and only keep the `"Run 'ix subsystems' to compute health scores."` note when the score is missing.
-
-Recommended v1 choice:
-- Keep the feature server-light.
-- Do **not** add a stale-health note yet.
-- Only add it after score revision metadata is exposed.
-
----
-
-## Output Sections
-
-### Text Format
-
-```
-Explanation
- `Ingestion Layer` serves as a subsystem spanning 34 files. It groups components
- responsible for parsing source files and committing patches to the graph. It sits
- inside the Core System and is well-defined with import coupling as its primary
- structural signal.
-
-Context
- Level: subsystem (level 2)
- Parent: Core System (system)
- Files: 34
- Children: 4 modules
- Confidence: Well-defined (88%)
- Signals: import coupling · path proximity
-
-Composition
- ● MODULE File Parser Well-defined 91% 12 files
- ● MODULE Patch Builder Well-defined 84% 9 files
- ● MODULE Bulk Writer Moderate 66% 8 files
- ● MODULE Ingestion Loader Fuzzy 44% 5 files
- 3 well-defined · 1 moderate · 0 fuzzy · 0 cross-cutting
-
-Health
- Score: ████░ 0.74
- Chunk density: 5.1 chunks/file
- Smell rate: 6% (2 files flagged)
- Status: Good — rich structure, low smell coverage
-
-Why it matters
- Ingestion Layer is the primary entry path for all source data into the graph.
- Its high chunk density indicates thorough code coverage in the knowledge graph.
- 2 files have active smell claims — run `ix smells` to review.
- Run `ix impact "Ingestion Layer"` to see what depends on this subsystem.
-```
-
-### JSON Format
-
-`--format json` returns a single object:
-
-```json
-{
- "resolvedTarget": {
- "id": "uuid",
- "label": "Ingestion Layer",
- "level": 2,
- "label_kind": "subsystem"
- },
- "explanation": "...",
- "context": {
- "level": 2,
- "label_kind": "subsystem",
- "parent": { "id": "uuid", "label": "Core System", "label_kind": "system" },
- "file_count": 34,
- "child_count": 4,
- "confidence": 0.88,
- "dominant_signals": ["import coupling", "path proximity"],
- "is_cross_cutting": false
- },
- "composition": {
- "children": [
- { "label": "File Parser", "level": 1, "label_kind": "module", "file_count": 12, "confidence": 0.91, "is_cross_cutting": false }
- ],
- "summary": { "well_defined": 3, "moderate": 1, "fuzzy": 0, "cross_cutting": 0 }
- },
- "health": {
- "score": 0.74,
- "chunk_density": 5.1,
- "smell_rate": 0.06,
- "smell_files": 2,
- "total_chunks": 173,
- "status": "good"
- },
- "whyItMatters": "...",
- "notes": []
-}
-```
-
-`health` is `null` if no score has been computed yet.
-
----
-
-## Section Definitions
-
-### Explanation
-
-One to two sentence prose summary synthesised from the region label, level, parent name,
-dominant signals, file count, and cross-cutting flag. No LLM — constructed from templates,
-the same way `ix explain`'s `describeRoleLocal` and `synthesizeSystemRole` work.
-
-Template inputs:
-
-| Signal | Mapped meaning |
-|---|---|
-| `level === 3` | "system" — top-level architectural boundary |
-| `level === 2` | "subsystem" — a bounded functional area |
-| `level === 1` | "module" — a focused implementation cluster |
-| `is_cross_cutting` | adds "…and is cross-cutting — it spans multiple subsystems" |
-| `dominant_signals` | "Its primary structural signal is import coupling" |
-| `parent.label` | "It sits inside the `<parent>` system" |
-| `confidence ≥ 0.75` | "well-defined" |
-| `confidence ≥ 0.50` | "moderately defined" |
-| `confidence < 0.50` | "loosely defined" |
-
-### Context
-
-Tabular structural facts — mirrors the `ix explain` Context section:
-
-```
-Level: subsystem (level 2)
-Parent: Core System (system)
-Files: 34
-Children: 4 modules
-Confidence: Well-defined (88%)
-Signals: import coupling · path proximity
-```
-
-Omit `Children` line when there are none (leaf modules).
-Omit `Parent` line for top-level systems with no parent.
-
-### Composition
-
-Renders the immediate child regions as a mini tree, sorted by file count descending
-(same comparator as `renderScopedTreeNode`). Capped at 10 children; if more exist,
-append ` … N more. Use 'ix subsystems <target>' for the full tree.`
-
-Followed by the existing well-defined / moderate / fuzzy / cross-cutting tally from
-`ScopedSubsystemResult.summary`.
-
-Omit the entire section for leaf regions (no children).
-
-### Health
-
-Uses the `SubsystemScore` for the resolved region id.
-
-```
-Score: ████░ 0.74 (healthBar using 5-block scale, same as --list)
-Chunk density: 5.1 chunks/file
-Smell rate: 6% (2 files flagged)
-Status: <status phrase>
-```
-
-**Status phrases** (derived from score thresholds):
-
-| Score | Status phrase |
-|---|---|
-| ≥ 0.80 | `Healthy — rich structure, minimal technical debt` |
-| ≥ 0.65 | `Good — rich structure, low smell coverage` |
-| ≥ 0.45 | `Moderate — structure is present, smell coverage is elevated` |
-| < 0.45 | `Needs attention — sparse structure or significant smell coverage` |
-
-Chunk density context lines (appended to Status line as a note):
-
-| Density | Note |
-|---|---|
-| ≥ 5.0 | `High chunk density indicates thorough code coverage in the knowledge graph.` |
-| ≥ 2.0 | *(no note)* |
-| < 2.0 | `Low chunk density — run 'ix ingest' to improve coverage.` |
-
-### Why it matters
-
-Single prose paragraph synthesised from health, level, cross-cutting status, and parent
-context. Mirrors the structure of `ix explain`'s `renderWhyItMatters`.
-
-Decision tree:
-
-1. **Cross-cutting + fuzzy confidence** → architectural drift warning:
- `<label> spans multiple subsystems and has low clustering confidence, suggesting architectural drift. Consider decomposing or clarifying its boundaries.`
-
-2. **High health (≥ 0.80) + top-level (level 3)** → stable anchor:
- `<label> is a stable, well-defined system boundary. Changes within it are well-contained. Run 'ix impact "<label>"' to review cross-system dependencies.`
-
-3. **Low health (< 0.45) + smell files > 0** → needs attention:
- `<label> has <N> files with active smell claims and a health score of <score>. Prioritize refactoring here before expanding the subsystem. Run 'ix smells' to review.`
-
-4. **Normal** → role + callers suggestion:
- `<label> is a <status> <level label> <parent phrase>. Run 'ix impact "<label>"' to understand its downstream blast radius.`
-
-### Notes
-
-Mirrors `ix explain`'s Notes section. Sources:
-- Health score missing: `Run 'ix subsystems' to compute health scores for this region.`
-- Health score computed at a different revision than current graph:
- `Health score may be stale — run 'ix subsystems' to refresh.`
-
-Implementation note:
-- This second note requires new score revision metadata and should be treated as optional
- follow-up work, not part of the minimum implementation.
-
----
-
-## Ambiguity Handling
-
-Identical to the current `ix subsystems <target>` behaviour. If the target is ambiguous,
-the existing `renderSubsystemError` output is shown and `--explain` is ignored:
-
-```
-Ambiguous target "auth". Multiple architecture regions matched:
-
-1. Auth Middleware subsystem 12 files
-2. Auth Tests module 8 files
-
-Run:
- ix subsystems auth --pick <n> --explain
-```
-
----
-
-## Implementation Plan
-
-### Phase 1 — Client (subsystems.ts)
-
-1. Add `--explain` flag to the command definition.
-2. When `--explain` is set and a `ScopedSubsystemResult` is returned:
- a. Make a second call to `client.listSubsystems()` and find the matching `SubsystemScore`
- by `region_id`.
- b. Call a new `renderSubsystemExplanation(scoped, score | null)` function.
-3. `renderSubsystemExplanation` implements the five sections above using template functions
- (no new server endpoints, no LLM).
-4. If `--format json` is set, return a purpose-built explanation object instead of the current
- scoped map JSON.
-
-New functions (all in `subsystems.ts` or a new `explain/subsystem.ts`):
-
-| Function | Purpose |
-|---|---|
-| `synthesizeSubsystemExplanation(region, parent)` | Returns the explanation string |
-| `healthStatus(score)` | Returns the status phrase |
-| `renderSubsystemExplanation(scoped, score)` | Assembles all five sections |
-| `renderSubsystemExplanationJson(scoped, score)` | Returns the JSON object |
-
-Primary files to change:
-
-- `ix-cli/src/cli/commands/subsystems.ts`
- Add the new flag, target validation, second score lookup, text rendering, and JSON rendering.
-- `ix-cli/src/client/api.ts`
- Likely no required API changes for v1, but tighten typings for `listSubsystems()` and
- `getSubsystemMap()` if the implementation needs stricter data contracts.
-- `memory-layer/src/main/scala/ix/memory/api/SubsystemRoutes.scala`
- No new endpoint required for v1. Only change this file if revision metadata is added later.
-- `memory-layer/src/main/scala/ix/memory/api/MapEncoder.scala`
- No required change for v1 text mode. Only change this file if scoped JSON needs extra fields
- or if you choose to expose `map_rev`.
-- `memory-layer/src/main/scala/ix/memory/subsystem/SubsystemScoringService.scala`
- Only required if you want the stale-health note in v1 by exposing score revision metadata.
-
-### Phase 2 — Optional score metadata
-
-Only needed if stale-health notes are required:
-
-1. Extend stored score payloads to include `map_rev` or score creation revision.
-2. Extend `listScores()` so the CLI can compare the score revision to the current scoped region.
-3. Add the stale-health note only when the score metadata proves drift.
-
-Suggested file targets:
-
-- `memory-layer/src/main/scala/ix/memory/subsystem/SubsystemScoringService.scala`
-- `memory-layer/src/main/scala/ix/memory/api/SubsystemRoutes.scala`
-- `ix-cli/src/client/api.ts`
-- `ix-cli/src/cli/commands/subsystems.ts`
-
-### Phase 3 — Validation
-
-- Smoke test against two regions: one with a health score, one without.
-- Confirm `--format json` produces valid parseable output.
-- Confirm `--explain` + ambiguous target shows the error, not a stack trace.
-- Confirm `--explain` without a target produces the intended CLI error.
-- If stale-health metadata is implemented, verify both fresh and stale note paths.
-
----
-
-## Large-Repo Ingestion Failures
-
-This is separate from `subsystems --explain`, but it is the other major issue discovered while
-reviewing the current architecture and should be fixed in parallel.
-
-### Failure Mode 1 — all parse results are retained in memory before any write
-
-Current behavior:
-- `BulkIngestionService.ingestPath()` discovers all files.
-- Loads all existing hashes for all files.
-- Parses all files with `parTraverseN`.
-- Keeps every `Parsed(FileBatch)` in memory.
-- Only then starts chunked writes.
-
-That makes the current chunked commit logic too late to protect memory.
-
-Required change:
-- Convert ingestion into a bounded pipeline:
- 1. discover files
- 2. slice into file batches
- 3. load hashes for that slice
- 4. parse only that slice
- 5. commit only that slice
- 6. release memory before moving to the next slice
-
-Primary file:
-- `memory-layer/src/main/scala/ix/memory/ingestion/BulkIngestionService.scala`
-
-### Failure Mode 2 — source hash lookup is one giant query
-
-Current behavior:
-- `getSourceHashes(sourceUris)` is called with the full discovered file list.
-- The query scans `patches`, sorts by revision, and groups by URI in one shot.
-
-On large repos, the bind payload and query work both become too large.
-
-Required change:
-- Chunk source-hash lookups to the same batch size as ingestion.
-- Keep hash lookup local to each parse/commit slice.
-- If needed later, add an indexed materialized source-hash table rather than scanning `patches`.
-
-Primary files:
-- `memory-layer/src/main/scala/ix/memory/ingestion/BulkIngestionService.scala`
-- `memory-layer/src/main/scala/ix/memory/db/ArangoGraphQueryApi.scala`
-
-### Failure Mode 3 — discovery is broader than parser support
-
-Current behavior:
-- File discovery includes many docs, configs, scripts, build files, and other text-like files.
-- Parser routing only has dedicated parsers for Python, TypeScript, Scala, config, and Markdown.
-- Unsupported files fall back to generic text ingestion.
-
-That means large repos do not just ingest code; they also ingest a wide tail of raw text.
-
-Required change:
-- Narrow default discovery to parser-supported file types for normal ingestion.
-- Optionally add an explicit `--include-generic-text` or similar opt-in later.
-- At minimum, stop treating unsupported text as full-content graph facts by default.
-
-Primary files:
-- `memory-layer/src/main/scala/ix/memory/ingestion/FileDiscovery.scala`
-- `memory-layer/src/main/scala/ix/memory/ingestion/ParserRouter.scala`
-- `memory-layer/src/main/scala/ix/memory/api/IngestionRoutes.scala`
-- `ix-cli/src/client/api.ts`
-
-### Failure Mode 4 — generic text path stores full content and explodes patch size
-
-Current behavior:
-- Generic text fallback stores `"content"` in entity attrs.
-- `GraphPatchBuilder` converts attrs into claims.
-- Bulk ingestion persists node docs, claim docs, and the full patch document.
-
-This duplicates large text payloads across multiple persisted artifacts.
-
-Required change:
-- Remove full raw content from generic-text attrs by default.
-- Replace it with compact metadata only:
- - file name
- - line count
- - maybe a short preview
- - content fingerprint / source hash
-- Do not emit claims for raw file content.
-
-Primary files:
-- `memory-layer/src/main/scala/ix/memory/ingestion/BulkIngestionService.scala`
-- `memory-layer/src/main/scala/ix/memory/ingestion/IngestionService.scala`
-- `memory-layer/src/main/scala/ix/memory/ingestion/GraphPatchBuilder.scala`
-- `memory-layer/src/main/scala/ix/memory/ingestion/ParseResult.scala`
-
-### Failure Mode 5 — chunking is by file count, not payload size
-
-Current behavior:
-- Bulk writes use a fixed `chunkSize = 100`.
-- A 100-file batch can still serialize into an oversized bulk request.
-
-Required change:
-- Chunk by estimated payload size, not just file count.
-- Keep a file-count cap as a secondary guardrail.
-- Emit progress based on committed slices, not only discovered totals.
-
-Primary files:
-- `memory-layer/src/main/scala/ix/memory/ingestion/BulkIngestionService.scala`
-- `memory-layer/src/main/scala/ix/memory/db/BulkWriteApi.scala`
-- `memory-layer/src/main/scala/ix/memory/db/ArangoClient.scala`
-
-### Recommended ingestion order
-
-1. Refactor bulk ingestion into bounded discovery/hash/parse/commit slices.
-2. Chunk `getSourceHashes()` by slice.
-3. Remove raw-content attrs and claims from generic text ingestion.
-4. Narrow default discovery to parser-supported files.
-5. Add payload-size-aware commit chunking.
-
-This order addresses the actual failure mode first: unbounded memory retention.
-
----
-
-## Constraints
-
-- No new server endpoints.
-- No LLM calls — explanations are template-driven, same as `ix explain`.
-- `--explain` is ignored when `--list` is also passed (error message).
-- `--explain` without a `<target>` is an error: `--explain requires a target.`
-- Output is intentionally terse — one screen of text for the full explanation.
-- Do not claim stale health in the output unless the score payload actually exposes revision
- metadata that proves staleness.
-- Large-repo ingestion fixes should prefer bounded-memory behavior over preserving the current
- exact batching structure.
diff --git a/install.cmd b/install.cmd
deleted file mode 100644
index a6e8e466..00000000
--- a/install.cmd
+++ /dev/null
@@ -1,2 +0,0 @@
-@echo off
-powershell -NoProfile -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/ix-infrastructure/IX-Memory/main/install.ps1'))"
diff --git a/ix-cli/src/cli/commands/upgrade.ts b/ix-cli/src/cli/commands/upgrade.ts
index ead6cf63..cc492712 100644
--- a/ix-cli/src/cli/commands/upgrade.ts
+++ b/ix-cli/src/cli/commands/upgrade.ts
@@ -170,7 +170,7 @@ export function registerUpgradeCommand(program: Command): void {
console.error(`[error] Failed to download ${url}`);
console.error(" You can also upgrade manually:");
console.error(
- ` curl -fsSL https://raw.githubusercontent.com/${GITHUB_ORG}/${GITHUB_REPO}/main/install.sh | bash`
+ ` curl -fsSL https://raw.githubusercontent.com/${GITHUB_ORG}/${GITHUB_REPO}/main/scripts/install/install.sh | bash`
);
rmSync(tmpDirRaw, { recursive: true, force: true });
process.exit(1);
diff --git a/node_modules/.vite/vitest/results.json b/node_modules/.vite/vitest/results.json
deleted file mode 100644
index e075ed9c..00000000
--- a/node_modules/.vite/vitest/results.json
+++ /dev/null
@@ -1 +0,0 @@
-{"version":"1.6.1","results":[[":ix-cli/src/cli/__tests__/subsystem-explain.test.ts",{"duration":18,"failed":false}]]}
\ No newline at end of file
diff --git a/scripts/install-mcp.sh b/scripts/install-mcp.sh
deleted file mode 100755
index 4a6b335f..00000000
--- a/scripts/install-mcp.sh
+++ /dev/null
@@ -1,110 +0,0 @@
-#!/usr/bin/env bash
-set -euo pipefail
-
-# ─────────────────────────────────────────────────────────────────────────────
-# Ix — Install MCP Server
-#
-# Registers the IX MCP server with your IDE so the LLM gets access to
-# the 13 IX tools and 2 resources.
-#
-# Usage:
-# ./scripts/install-mcp.sh # Claude Code (default)
-# ./scripts/install-mcp.sh --claude-desktop # Claude Desktop
-# ./scripts/install-mcp.sh --cursor # Cursor
-# ./scripts/install-mcp.sh --claude-code ~/my-project # Claude Code in specific dir
-# ─────────────────────────────────────────────────────────────────────────────
-
-IX_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
-CLI_DIR="$IX_DIR/ix-cli"
-IX_CMD="npx --prefix $CLI_DIR tsx $CLI_DIR/src/cli/main.ts"
-
-# ── Parse arguments ──────────────────────────────────────────────────────────
-
-IDE="claude-code"
-PROJECT_DIR=""
-
-while [[ $# -gt 0 ]]; do
- case "$1" in
- --claude-desktop) IDE="claude-desktop"; shift ;;
- --cursor) IDE="cursor"; shift ;;
- --claude-code) IDE="claude-code"; shift ;;
- -h|--help)
- echo "Usage: ./scripts/install-mcp.sh [IDE] [PROJECT_DIR]"
- echo ""
- echo "IDE Options:"
- echo " --claude-code Install for Claude Code (default)"
- echo " --claude-desktop Install for Claude Desktop"
- echo " --cursor Install for Cursor"
- echo ""
- echo "Arguments:"
- echo " PROJECT_DIR Target project directory (default: current directory)"
- echo " Only relevant for --claude-code and --cursor"
- echo ""
- echo "What this does:"
- echo " Writes MCP server config so the IDE auto-launches the IX MCP server."
- echo " The LLM then gets access to 13 tools (ix_search, ix_decide, etc.)"
- echo " and 2 resources (ix://session/context, ix://project/intent)."
- echo ""
- echo "Config file locations:"
- echo " Claude Code: .claude/settings.json (in project dir)"
- echo " Claude Desktop: ~/Library/Application Support/Claude/claude_desktop_config.json"
- echo " Cursor: .cursor/mcp.json (in project dir)"
- exit 0
- ;;
- *)
- if [ -d "$1" ]; then
- PROJECT_DIR="$1"
- else
- echo "Unknown option or invalid directory: $1"
- exit 1
- fi
- shift
- ;;
- esac
-done
-
-# ── Preflight ────────────────────────────────────────────────────────────────
-
-if [ ! -d "$CLI_DIR/dist" ] || [ ! -d "$CLI_DIR/node_modules" ]; then
- echo "Error: CLI is not built. Run first:"
- echo " ./scripts/build-cli.sh"
- exit 1
-fi
-
-# ── Install ──────────────────────────────────────────────────────────────────
-
-if [ -n "$PROJECT_DIR" ]; then
- cd "$PROJECT_DIR"
-fi
-
-echo "Installing IX MCP server for: $IDE"
-echo ""
-
-case "$IDE" in
- claude-code)
- $IX_CMD mcp-install --claude-code
- echo ""
- echo "Config written to: $(pwd)/.claude/settings.json"
- echo "Restart Claude Code to activate."
- ;;
- claude-desktop)
- $IX_CMD mcp-install
- echo ""
- echo "Restart Claude Desktop to activate."
- ;;
- cursor)
- $IX_CMD mcp-install --cursor
- echo ""
- echo "Config written to: $(pwd)/.cursor/mcp.json"
- echo "Restart Cursor to activate."
- ;;
-esac
-
-echo ""
-echo "[ok] MCP server installed"
-echo ""
-echo "The LLM will now have access to:"
-echo " Tools: ix_search, ix_ingest, ix_decide, ix_entity, ix_expand,"
-echo " ix_expand, ix_history, ix_truth, ix_diff, ix_conflicts,"
-echo " ix_resolve, ix_assert, ix_patches"
-echo " Resources: ix://session/context, ix://project/intent"
diff --git a/scripts/install/install.cmd b/scripts/install/install.cmd
new file mode 100644
index 00000000..e7cbb15b
--- /dev/null
+++ b/scripts/install/install.cmd
@@ -0,0 +1,2 @@
+@echo off
+powershell -NoProfile -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://ix-infra.com/install.ps1'))"
diff --git a/install.ps1 b/scripts/install/install.ps1
similarity index 99%
rename from install.ps1
rename to scripts/install/install.ps1
index 1ad4cc94..f91ac78e 100644
--- a/install.ps1
+++ b/scripts/install/install.ps1
@@ -8,7 +8,7 @@
# 4. Claude Code hooks (if Claude Code is installed)
#
# Usage:
-# irm https://raw.githubusercontent.com/ix-infrastructure/Ix/main/install.ps1 | iex
+# irm https://ix-infra.com/install.ps1 | iex
#
# Options (env vars):
# $env:IX_VERSION = "0.2.0" Override version
diff --git a/install.sh b/scripts/install/install.sh
similarity index 98%
rename from install.sh
rename to scripts/install/install.sh
index 215fae60..3ebccd8c 100755
--- a/install.sh
+++ b/scripts/install/install.sh
@@ -8,7 +8,7 @@
# 4. Claude Code hooks (if Claude Code is installed)
#
# Usage:
-# curl -fsSL https://raw.githubusercontent.com/ix-infrastructure/Ix/main/install.sh | bash
+# curl -fsSL https://ix-infra.com/install.sh | sh
#
# Options (env vars):
# IX_VERSION=0.2.0 Override version (default: latest)
@@ -394,5 +394,5 @@ echo " cd ~/my-project && ix init"
echo " ix map ./src"
echo ""
echo " To uninstall:"
-echo " curl -fsSL ${GITHUB_RAW}/uninstall.sh | bash"
+echo " curl -fsSL https://ix-infra.com/uninstall.sh | sh"
echo ""
diff --git a/uninstall.ps1 b/scripts/install/uninstall.ps1
similarity index 97%
rename from uninstall.ps1
rename to scripts/install/uninstall.ps1
index 63c78b2d..c812bf2d 100644
--- a/uninstall.ps1
+++ b/scripts/install/uninstall.ps1
@@ -2,7 +2,7 @@
# Ix — Windows Uninstaller (PowerShell)
#
# Usage:
-# irm https://raw.githubusercontent.com/ix-infrastructure/Ix/main/uninstall.ps1 | iex
+# irm https://ix-infra.com/uninstall.ps1 | iex
# ─────────────────────────────────────────────────────────────────────────────
$ErrorActionPreference = "Stop"
diff --git a/uninstall.sh b/scripts/install/uninstall.sh
similarity index 98%
rename from uninstall.sh
rename to scripts/install/uninstall.sh
index 1923c99c..08ae462e 100755
--- a/uninstall.sh
+++ b/scripts/install/uninstall.sh
@@ -8,7 +8,7 @@
# 3. Backend Docker containers + volumes (optional)
#
# Usage:
-# curl -fsSL https://raw.githubusercontent.com/ix-infrastructure/Ix/main/uninstall.sh | bash
+# curl -fsSL https://ix-infra.com/uninstall.sh | sh
#
# Options (env vars):
# IX_KEEP_DATA=1 Keep ArangoDB data volume (default: remove everything)
diff --git a/templates/CLAUDE.md.template b/templates/CLAUDE.md.template
deleted file mode 100644
index f810284b..00000000
--- a/templates/CLAUDE.md.template
+++ /dev/null
@@ -1,35 +0,0 @@
-# Ix Memory System
-
-This project uses Ix Memory for persistent, time-aware context.
-
-## Project
-- Name: {{PROJECT_NAME}}
-
-## Interface
-Use the `ix` CLI exclusively. Do NOT use MCP tools — the CLI is the canonical agent interface.
-All commands support `--format json` for machine-readable output.
-
-## MANDATORY RULES
-1. BEFORE answering codebase questions → use targeted `ix` CLI commands (see routing below)
-2. AFTER making any design/architecture decision → run `ix decide`
-3. When noticing contradictory information → run `ix conflicts`
-4. NEVER guess about codebase facts when Ix has structured data
-5. After modifying code → run `ix ingest` on changed files
-6. When the user states a goal → run `ix truth add`
-
-## Ix CLI Command Routing
-- `ix search` — find entities by name/kind/language
-- `ix explain` — understand a symbol (structure, container, calls)
-- `ix read` — read source code by path or symbol
-- `ix entity` — full entity details by ID
-- `ix text` — fast lexical search (ripgrep)
-- `ix callers` / `ix callees` — call graph navigation
-- `ix contains` — members of a class/module
-- `ix imports` / `ix imported-by` — import graph
-- `ix depends` — dependency impact analysis
-- `ix decisions` — list past design decisions
-- `ix history` / `ix diff` — temporal queries
-
-## Do NOT Use
-- `ix query` — deprecated, oversized low-signal responses
-- MCP tools — deprecated, use CLI instead
diff --git a/templates/claude_desktop_config.json.template b/templates/claude_desktop_config.json.template
deleted file mode 100644
index eeeedc15..00000000
--- a/templates/claude_desktop_config.json.template
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "mcpServers": {
- "ix-memory": {
- "command": "ix",
- "args": ["mcp", "start"],
- "env": {
- "IX_ENDPOINT": "{{IX_ENDPOINT}}",
- "IX_PROJECT": "{{IX_PROJECT}}"
- }
- }
- }
-}