Audit and fill data gaps: lore detail view vs glab

## Background
For lore to be the definitive read path, its single-entity detail view must return everything glab returns PLUS lore-exclusive enrichments.

## Current Issue Detail Output (lore -J issues N)
Fields returned: assignees, author_username, closing_merge_requests, created_at, description, discussions, due_date, id, iid, labels, milestone, project_path, state, status_color, status_icon_name, status_name, status_synced_at, title, updated_at, web_url

## Gap Analysis (Verified 2026-02-12)

### Raw Payload Audit
Issue raw_payloads store exactly 15 fields: assignees, author, closed_at, created_at, description, due_date, id, iid, labels, milestone, project_id, state, title, updated_at, web_url.

Fields NOT in raw payloads (require ingestion pipeline update to capture from GitLab API):
- closed_by, confidential, upvotes, downvotes, weight, issue_type, time_stats, health_status, references

### Phase 1 — Computed fields (NO schema change, NO ingestion change)
These can be derived from existing data:
1. `references_full`: format!("{path_with_namespace}#{iid}") — project_path already in show.rs:IssueDetail
2. `user_notes_count`: SELECT COUNT(*) FROM notes n JOIN discussions d ON n.discussion_id = d.id WHERE d.noteable_type = 'Issue' AND d.noteable_id = ? AND n.is_system = 0
3. `merge_requests_count`: COUNT from closing_merge_requests vec already loaded in show.rs (just .len())

### Phase 2 — Extract from existing raw payloads (schema change, NO ingestion change)
`closed_at` IS in raw_payloads for closed issues. Can be backfilled:
1. Add `closed_at TEXT` column to issues table (migration 023)
2. Backfill: UPDATE issues SET closed_at = json_extract((SELECT payload FROM raw_payloads WHERE id = issues.raw_payload_id), '$.closed_at') WHERE state = 'closed'
3. Capture during ingestion going forward

### Phase 3 — Requires ingestion pipeline update (schema change + API capture)
These fields are in the GitLab Issues API response but NOT captured by lore's ingestion:
1. `closed_by` (object with username) — add closed_by_username TEXT to issues
2. `confidential` (boolean) — add confidential INTEGER DEFAULT 0 to issues
3. Both require updating src/ingestion/ to extract these fields during sync

### Phase 4 — Same audit for MR detail view
MR detail (src/cli/commands/show.rs MrDetail struct lines 14-33) already includes: closed_at, merged_at, draft, source/target branch, reviewers. Missing: approvers_count, pipeline_status.

## Implementation: show.rs Modifications

### IssueDetail struct (src/cli/commands/show.rs:69-91)
Add fields:
```rust
pub references_full: String,        // Phase 1: computed
pub user_notes_count: i64,          // Phase 1: computed
pub merge_requests_count: usize,    // Phase 1: computed (closing_merge_requests.len())
pub closed_at: Option<String>,      // Phase 2: from DB after migration
pub confidential: bool,             // Phase 3: from DB after ingestion update
```

### SQL for computed fields
```sql
-- user_notes_count
SELECT COUNT(*) FROM notes n
JOIN discussions d ON n.discussion_id = d.id
WHERE d.noteable_type = 'Issue' AND d.noteable_id = ?1 AND n.is_system = 0

-- references_full (in Rust)
format!("{}#{}", project_path, iid)

-- merge_requests_count (in Rust)
closing_merge_requests.len()
```

## Migration 023 (after bd-2l3s takes 022)
```sql
-- migrations/023_issue_detail_fields.sql
ALTER TABLE issues ADD COLUMN closed_at TEXT;
ALTER TABLE issues ADD COLUMN confidential INTEGER NOT NULL DEFAULT 0;

-- Backfill closed_at from raw_payloads
UPDATE issues SET closed_at = (
    SELECT json_extract(rp.payload, '$.closed_at')
    FROM raw_payloads rp
    WHERE rp.id = issues.raw_payload_id
) WHERE state = 'closed' AND raw_payload_id IS NOT NULL;

INSERT INTO schema_version (version, applied_at, description)
VALUES (23, strftime('%s', 'now') * 1000, 'Issue detail fields: closed_at, confidential');
```

NOTE: raw_payload_id column on issues — verify this exists. If issues don't have a direct FK to raw_payloads, the backfill SQL needs adjustment (may need to join through another path).

## TDD Loop
RED: Tests in src/cli/commands/show.rs:
- test_show_issue_has_references_full: insert issue with known project_path, assert JSON output contains "project/path#123"
- test_show_issue_has_notes_count: insert issue + 3 user notes + 1 system note, assert user_notes_count = 3
- test_show_issue_closed_has_closed_at: insert closed issue with closed_at in raw_payload, run migration, verify closed_at appears

GREEN: Add computed fields to IssueDetail, add migration 023 for closed_at + confidential columns

VERIFY:
```bash
cargo test show:: && cargo clippy --all-targets -- -D warnings
cargo run --release -- -J issues 3864 | jq '{references_full, user_notes_count, merge_requests_count}'
```

## Acceptance Criteria
- [ ] lore -J issues N includes references_full (string, e.g., "vs/typescript-code#3864")
- [ ] lore -J issues N includes user_notes_count (integer, excludes system notes)
- [ ] lore -J issues N includes merge_requests_count (integer)
- [ ] lore -J issues N includes closed_at (ISO string for closed issues, null for open)
- [ ] lore -J issues N includes confidential (boolean, after Phase 3)
- [ ] --fields minimal preset updated to include references_full
- [ ] Migration 023 adds closed_at and confidential columns to issues table
- [ ] Backfill SQL populates closed_at from existing raw_payloads
- [ ] cargo test passes with new show:: tests

## Edge Cases
- Issue with zero notes: user_notes_count = 0 (not null)
- Issue with no closing MRs: merge_requests_count = 0
- Open issue: closed_at = null (serialized as JSON null, not omitted)
- confidential before Phase 3: default false (safe default)
- MR detail: different computed fields (approvers_count, pipeline_status if available)
- Raw payload missing for very old issues (raw_payload_id = NULL): closed_at stays NULL
- raw_payload_id column: verify it exists on the issues table before writing backfill SQL

## Files to Modify
- src/cli/commands/show.rs (IssueDetail struct + query logic)
- src/core/db.rs (migration 023: wire into MIGRATIONS array)
- NEW: migrations/023_issue_detail_fields.sql
- src/ingestion/ (Phase 3: capture closed_by, confidential during sync — specify exact file after reviewing ingestion pipeline)

Data gaps filled: references_full, user_notes_count, merge_requests_count, closed_at, confidential via migration 023


[CP1] gi list issues command

List issues from the database.

## Module
src/cli/commands/list.rs

## Clap Definition
List {
    #[arg(value_parser = ["issues", "mrs"])]
    entity: String,

    #[arg(long, default_value = "20")]
    limit: usize,

    #[arg(long)]
    project: Option<String>,

    #[arg(long, value_parser = ["opened", "closed", "all"])]
    state: Option<String>,
}

## Output Format
Issues (showing 20 of 3,801)

  #1234  Authentication redesign                       opened   @johndoe   3 days ago
  #1233  Fix memory leak in cache                      closed   @janedoe   5 days ago
  #1232  Add dark mode support                         opened   @bobsmith  1 week ago
  ...

## Implementation
- Query issues table with filters
- Join with projects table for display
- Format updated_at as relative time ("3 days ago")
- Truncate title if too long

Files: src/cli/commands/list.rs
Done when: List displays issues with proper filtering and formatting


OBSERV: Add log file diagnostics to lore doctor

## Background
lore doctor is the diagnostic entry point. Adding log file info lets users verify logging is working and check disk usage. The existing DoctorChecks struct (src/cli/commands/doctor.rs:43-51) has checks for config, database, gitlab, projects, ollama.

## Approach
Add a new LoggingCheck struct and field to DoctorChecks:

```rust
#[derive(Debug, Serialize)]
pub struct LoggingCheck {
    pub result: CheckResult,
    pub log_dir: String,
    pub file_count: usize,
    pub total_bytes: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub oldest_file: Option<String>,
}
```

Add to DoctorChecks (src/cli/commands/doctor.rs:43-51):
```rust
pub logging: LoggingCheck,
```

Implement check_logging() function:
```rust
fn check_logging() -> LoggingCheck {
    let log_dir = get_log_dir(None); // TODO: accept config override
    let mut file_count = 0;
    let mut total_bytes = 0u64;
    let mut oldest: Option<String> = None;

    if let Ok(entries) = std::fs::read_dir(&log_dir) {
        for entry in entries.flatten() {
            let name = entry.file_name().to_string_lossy().to_string();
            if name.starts_with("lore.") && name.ends_with(".log") {
                file_count += 1;
                if let Ok(meta) = entry.metadata() {
                    total_bytes += meta.len();
                }
                if oldest.as_ref().map_or(true, |o| name < *o) {
                    oldest = Some(name);
                }
            }
        }
    }

    LoggingCheck {
        result: CheckResult { status: CheckStatus::Ok, message: None },
        log_dir: log_dir.display().to_string(),
        file_count,
        total_bytes,
        oldest_file: oldest,
    }
}
```

Call from run_doctor() (src/cli/commands/doctor.rs:91-126) and add to DoctorChecks construction.

For interactive output in print_doctor_results(), add a section:
```
Logging
  Log directory: ~/.local/share/lore/logs/
  Log files: 7 (2.3 MB)
  Oldest: lore.2026-01-28.log
```

## Acceptance Criteria
- [ ] lore doctor shows log directory path, file count, total size
- [ ] lore --robot doctor JSON includes logging field with log_dir, file_count, total_bytes, oldest_file
- [ ] When no log files exist: file_count=0, total_bytes=0, oldest_file=null
- [ ] cargo clippy --all-targets -- -D warnings passes

## Files
- src/cli/commands/doctor.rs (add LoggingCheck struct, check_logging fn, wire into DoctorChecks)

## TDD Loop
RED: test_check_logging_with_files, test_check_logging_empty_dir
GREEN: Implement LoggingCheck struct and check_logging function
VERIFY: cargo test && cargo clippy --all-targets -- -D warnings

## Edge Cases
- Log directory doesn't exist yet (first run before any sync): report file_count=0, status Ok
- Permission errors on read_dir: report status Warning with message

Added LoggingCheck to DoctorChecks with log_dir, file_count, total_bytes; shows in both interactive and robot output


[CP1] Database migration 002_issues.sql

## Background

The 002_issues.sql migration creates tables for issues, labels, issue_labels, discussions, and notes. This is the data foundation for Checkpoint 1, enabling issue ingestion with cursor-based sync, label tracking, and discussion storage.

## Approach

Create `migrations/002_issues.sql` with complete SQL statements.

### Full Migration SQL

```sql
-- Migration 002: Issue Ingestion Tables
-- Applies on top of 001_initial.sql

-- Issues table
CREATE TABLE issues (
    id INTEGER PRIMARY KEY,
    gitlab_id INTEGER UNIQUE NOT NULL,
    project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
    iid INTEGER NOT NULL,
    title TEXT,
    description TEXT,
    state TEXT NOT NULL CHECK (state IN ('opened', 'closed')),
    author_username TEXT,
    created_at INTEGER NOT NULL,           -- ms epoch UTC
    updated_at INTEGER NOT NULL,           -- ms epoch UTC
    last_seen_at INTEGER NOT NULL,         -- updated on every upsert
    discussions_synced_for_updated_at INTEGER, -- watermark for dependent sync
    web_url TEXT,
    raw_payload_id INTEGER REFERENCES raw_payloads(id)
);

CREATE INDEX idx_issues_project_updated ON issues(project_id, updated_at);
CREATE INDEX idx_issues_author ON issues(author_username);
CREATE UNIQUE INDEX uq_issues_project_iid ON issues(project_id, iid);

-- Labels table (name-only for CP1)
CREATE TABLE labels (
    id INTEGER PRIMARY KEY,
    gitlab_id INTEGER,                      -- optional, for future Labels API
    project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
    name TEXT NOT NULL,
    color TEXT,
    description TEXT
);

CREATE UNIQUE INDEX uq_labels_project_name ON labels(project_id, name);
CREATE INDEX idx_labels_name ON labels(name);

-- Issue-label junction (DELETE before INSERT for stale removal)
CREATE TABLE issue_labels (
    issue_id INTEGER NOT NULL REFERENCES issues(id) ON DELETE CASCADE,
    label_id INTEGER NOT NULL REFERENCES labels(id) ON DELETE CASCADE,
    PRIMARY KEY(issue_id, label_id)
);

CREATE INDEX idx_issue_labels_label ON issue_labels(label_id);

-- Discussion threads for issues (MR discussions added in CP2)
CREATE TABLE discussions (
    id INTEGER PRIMARY KEY,
    gitlab_discussion_id TEXT NOT NULL,     -- GitLab string ID (e.g., "6a9c1750b37d...")
    project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
    issue_id INTEGER REFERENCES issues(id) ON DELETE CASCADE,
    merge_request_id INTEGER,               -- FK added in CP2 via ALTER TABLE
    noteable_type TEXT NOT NULL CHECK (noteable_type IN ('Issue', 'MergeRequest')),
    individual_note INTEGER NOT NULL DEFAULT 0,  -- 0=threaded, 1=standalone
    first_note_at INTEGER,                  -- min(note.created_at) for ordering
    last_note_at INTEGER,                   -- max(note.created_at) for "recently active"
    last_seen_at INTEGER NOT NULL,          -- updated on every upsert
    resolvable INTEGER NOT NULL DEFAULT 0,  -- MR discussions can be resolved
    resolved INTEGER NOT NULL DEFAULT 0,
    CHECK (
        (noteable_type = 'Issue' AND issue_id IS NOT NULL AND merge_request_id IS NULL) OR
        (noteable_type = 'MergeRequest' AND merge_request_id IS NOT NULL AND issue_id IS NULL)
    )
);

CREATE UNIQUE INDEX uq_discussions_project_discussion_id ON discussions(project_id, gitlab_discussion_id);
CREATE INDEX idx_discussions_issue ON discussions(issue_id);
CREATE INDEX idx_discussions_mr ON discussions(merge_request_id);
CREATE INDEX idx_discussions_last_note ON discussions(last_note_at);

-- Notes belong to discussions
CREATE TABLE notes (
    id INTEGER PRIMARY KEY,
    gitlab_id INTEGER UNIQUE NOT NULL,
    discussion_id INTEGER NOT NULL REFERENCES discussions(id) ON DELETE CASCADE,
    project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
    note_type TEXT,                         -- 'DiscussionNote' | 'DiffNote' | null
    is_system INTEGER NOT NULL DEFAULT 0,   -- 1 for system-generated notes
    author_username TEXT,
    body TEXT,
    created_at INTEGER NOT NULL,            -- ms epoch
    updated_at INTEGER NOT NULL,            -- ms epoch
    last_seen_at INTEGER NOT NULL,          -- updated on every upsert
    position INTEGER,                       -- 0-indexed array order from API
    resolvable INTEGER NOT NULL DEFAULT 0,
    resolved INTEGER NOT NULL DEFAULT 0,
    resolved_by TEXT,
    resolved_at INTEGER,
    -- DiffNote position metadata (populated for MR DiffNotes in CP2)
    position_old_path TEXT,
    position_new_path TEXT,
    position_old_line INTEGER,
    position_new_line INTEGER,
    raw_payload_id INTEGER REFERENCES raw_payloads(id)
);

CREATE INDEX idx_notes_discussion ON notes(discussion_id);
CREATE INDEX idx_notes_author ON notes(author_username);
CREATE INDEX idx_notes_system ON notes(is_system);

-- Update schema version
INSERT INTO schema_version (version, applied_at, description)
VALUES (2, strftime('%s', 'now') * 1000, 'Issue ingestion tables');
```

## Acceptance Criteria

- [ ] Migration file exists at `migrations/002_issues.sql`
- [ ] All tables created: issues, labels, issue_labels, discussions, notes
- [ ] All indexes created as specified
- [ ] CHECK constraints on state and noteable_type work correctly
- [ ] CASCADE deletes work (project deletion cascades)
- [ ] Migration applies cleanly on fresh DB after 001_initial.sql
- [ ] schema_version updated to 2 after migration
- [ ] `gi doctor` shows schema_version = 2

## Files

- migrations/002_issues.sql (create)

## TDD Loop

RED:
```rust
// tests/migration_tests.rs
#[test] fn migration_002_creates_issues_table()
#[test] fn migration_002_creates_labels_table()
#[test] fn migration_002_creates_discussions_table()
#[test] fn migration_002_creates_notes_table()
#[test] fn migration_002_enforces_state_check()
#[test] fn migration_002_enforces_noteable_type_check()
#[test] fn migration_002_cascades_on_project_delete()
```

GREEN: Create migration file with all SQL

VERIFY:
```bash
# Apply migration to test DB
sqlite3 :memory: < migrations/001_initial.sql
sqlite3 :memory: < migrations/002_issues.sql

# Verify schema_version
sqlite3 test.db "SELECT version FROM schema_version ORDER BY version DESC LIMIT 1"
# Expected: 2

cargo test migration_002
```

## Edge Cases

- Applying twice - should fail on UNIQUE constraint (idempotency via version check)
- Missing 001 - foreign key to projects fails
- Long label names - TEXT handles any length
- NULL description - allowed by schema
- Empty discussions_synced_for_updated_at - NULL means never synced

Created 002_issues.sql with issues/labels/issue_labels/discussions/notes tables, 8 passing tests verify schema, constraints, and cascades


Implement Doctor + Stats screens

## Background
Doctor shows environment health checks (config, auth, DB, Ollama). Stats shows database statistics (entity counts, index sizes, FTS coverage). Both are informational screens using ftui JsonView or simple table layouts.

## Approach
State:
- DoctorState: checks (Vec<HealthCheck>), overall_status (Healthy|Warning|Error)
- StatsState: entity_stats (EntityStats), index_stats (IndexStats), fts_stats (FtsStats)

Action:
- run_doctor(config, conn) -> Vec<HealthCheck>: reuses existing lore doctor logic
- fetch_stats(conn) -> StatsData: reuses existing lore stats logic

View:
- Doctor: vertical list of health checks with pass/fail/warn indicators
- Stats: table of entity counts, index sizes, FTS document count, embedding coverage

## Acceptance Criteria
- [ ] Doctor shows config, auth, DB, and Ollama health status
- [ ] Stats shows entity counts matching lore --robot stats output
- [ ] Both screens accessible via navigation (gd for Doctor)
- [ ] Health check results color-coded: green pass, yellow warn, red fail

## Files
- CREATE: crates/lore-tui/src/state/doctor.rs
- CREATE: crates/lore-tui/src/state/stats.rs
- CREATE: crates/lore-tui/src/view/doctor.rs
- CREATE: crates/lore-tui/src/view/stats.rs
- MODIFY: crates/lore-tui/src/action.rs (add run_doctor, fetch_stats)

## TDD Anchor
RED: Write test_fetch_stats_counts that creates DB with known data, asserts fetch_stats returns correct counts.
GREEN: Implement fetch_stats with COUNT queries.
VERIFY: cargo test --manifest-path crates/lore-tui/Cargo.toml test_fetch_stats

## Edge Cases
- Ollama not running: Doctor shows warning, not error (optional dependency)
- Very large databases: stats queries should be fast (use shadow tables for FTS count)

## Dependency Context
Uses existing doctor and stats logic from lore CLI commands.
Uses DbManager from "Implement DbManager" task.


Migration 021: Add status columns to issues table

## Background
GitLab issues have work item status (To do, In progress, Done, Won't do, Duplicate) only available via GraphQL. We need 5 nullable columns on the issues table to store this data after enrichment. The status_synced_at column tracks when enrichment last wrote/cleared each row (ms epoch UTC).

## Approach
Create a new SQL migration file and register it in the MIGRATIONS array. SQLite ALTER TABLE ADD COLUMN is non-destructive — existing rows get NULL defaults. Add a compound index for --status filter performance.

## Files
- migrations/021_work_item_status.sql (NEW)
- src/core/db.rs (add entry to MIGRATIONS array)

## Implementation

migrations/021_work_item_status.sql:
  ALTER TABLE issues ADD COLUMN status_name TEXT;
  ALTER TABLE issues ADD COLUMN status_category TEXT;
  ALTER TABLE issues ADD COLUMN status_color TEXT;
  ALTER TABLE issues ADD COLUMN status_icon_name TEXT;
  ALTER TABLE issues ADD COLUMN status_synced_at INTEGER;
  CREATE INDEX IF NOT EXISTS idx_issues_project_status_name ON issues(project_id, status_name);

In src/core/db.rs, add as last entry in MIGRATIONS array:
  ("021", include_str!("../../migrations/021_work_item_status.sql")),
LATEST_SCHEMA_VERSION is computed as MIGRATIONS.len() as i32 — auto-becomes 21.

## Acceptance Criteria
- [ ] Migration file exists at migrations/021_work_item_status.sql
- [ ] MIGRATIONS array has 21 entries ending with ("021", ...)
- [ ] In-memory DB: PRAGMA table_info(issues) includes all 5 new columns
- [ ] In-memory DB: PRAGMA index_list(issues) includes idx_issues_project_status_name
- [ ] Existing rows have NULL for all 5 new columns
- [ ] cargo check --all-targets passes

## TDD Loop
RED: test_migration_021_adds_columns, test_migration_021_adds_index
  Pattern: create_connection(Path::new(":memory:")) + run_migrations(&conn), then PRAGMA queries
GREEN: Create SQL file + register in MIGRATIONS
VERIFY: cargo test test_migration_021

## Edge Cases
- Migration has 5 columns (including status_synced_at INTEGER), not 4
- Test project insert uses gitlab_project_id, path_with_namespace, web_url (no name/last_seen_at)

Implemented by agent swarm — all quality gates pass (595 tests, 0 failures)


Implement DbManager (read pool + dedicated writer)

## Background
The TUI needs concurrent database access: multiple read queries can run in parallel (e.g., loading dashboard stats while prefetching issue list), but writes must be serialized. The DbManager provides a read pool (3 connections, round-robin) plus a dedicated writer connection, accessed via closures.

The database uses WAL mode with 5000ms busy_timeout (already configured in lore's create_connection). WAL allows concurrent readers + single writer. The TUI is self-contained — it does NOT detect or react to external CLI sync operations. If someone runs lore sync externally while the TUI is open, WAL prevents conflicts and the TUI's natural re-query on navigation handles stale data implicitly.

## Approach
Create `crates/lore-tui/src/db.rs`:

```rust
pub struct DbManager {
    readers: Vec<Connection>,  // 3 connections, WAL mode
    writer: Connection,         // dedicated writer
    next_reader: AtomicUsize,   // round-robin index
}
```

- `DbManager::open(path: &Path) -> Result<Self>` — opens 4 connections (3 read + 1 write), all with WAL + busy_timeout via lore::core::db::create_connection
- `with_reader<F, T>(&self, f: F) -> Result<T> where F: FnOnce(&Connection) -> Result<T>` — closure-based read access, round-robin selection
- `with_writer<F, T>(&self, f: F) -> Result<T> where F: FnOnce(&Connection) -> Result<T>` — closure-based write access (serialized)
- Reader connections set `PRAGMA query_only = ON` as a safety guard
- All connections reuse lore's `create_connection()` which sets WAL + busy_timeout + foreign_keys

The DbManager is created once at app startup and shared (via Arc) across all screen states and action tasks.

## Acceptance Criteria
- [ ] DbManager opens 3 reader + 1 writer connection
- [ ] Readers use round-robin selection via AtomicUsize
- [ ] Reader connections have query_only = ON
- [ ] Writer connection allows INSERT/UPDATE/DELETE
- [ ] with_reader and with_writer use closure-based access (no connection leaking)
- [ ] All connections use WAL mode and 5000ms busy_timeout
- [ ] DbManager is Send + Sync (can be shared via Arc across async tasks)
- [ ] Unit test: concurrent reads don't block each other
- [ ] Unit test: write through reader connection fails (query_only guard)

## Files
- CREATE: crates/lore-tui/src/db.rs
- MODIFY: crates/lore-tui/src/lib.rs (add pub mod db)

## TDD Anchor
RED: Write `test_reader_is_query_only` that opens a DbManager on an in-memory DB, attempts an INSERT via with_reader, and asserts it fails.
GREEN: Implement DbManager with query_only pragma on readers.
VERIFY: cargo test -p lore-tui db -- --nocapture

Additional tests:
- test_writer_allows_mutations
- test_round_robin_rotates_readers
- test_dbmanager_is_send_sync (compile-time assert)
- test_concurrent_reads (spawn threads, all complete without blocking)

## Edge Cases
- Database file doesn't exist — create_connection handles this (creates new DB)
- Database locked by external process — busy_timeout handles retry
- Connection pool exhaustion — not possible with closure-based access (connection is borrowed, not taken)
- AtomicUsize overflow — wraps around, which is fine for round-robin (modulo 3)

## Dependency Context
Depends on bd-3ddw (scaffold) for the crate to exist. Uses lore::core::db::create_connection for connection setup. All screen action modules depend on DbManager for data access.

Implemented DbManager: 3 reader pool (query_only, round-robin) + 1 writer, Mutex-wrapped for Send+Sync. 7 tests passing, clippy clean.


Implement MR List (state + action + view)

## Background
The MR List mirrors the Issue List pattern with MR-specific columns (target branch, source branch, draft status, reviewer). Same keyset pagination, snapshot fence, and filter bar DSL.

## Approach
State (state/mr_list.rs):
- MrListState: same structure as IssueListState but with MrFilter and MrListRow, plus snapshot_upper_updated_at, filter_hash, peek_visible, peek_content
- MrFilter: state, author, reviewer, target_branch, source_branch, label, draft (bool), free_text, project_id
- MrListRow: project_path, iid, title, state, author, reviewer, target_branch, labels, updated_at, draft
- MrCursor: updated_at, iid for keyset pagination
- handle_key(): j/k scroll, J/K page, Enter select, / focus filter, Tab sort, g+g top, G bottom, r refresh, Space toggle Quick Peek

**Snapshot fence:** Same pattern as Issue List — store snapshot_upper_updated_at on first load and refresh, filter subsequent pages. Explicit refresh (r) resets.

**filter_hash:** Same pattern as Issue List — filter change resets cursor to page 1.

**Quick Peek (Space key):**
- Space toggles right-side preview pane (40% width) showing selected MR detail
- Preview loads asynchronously via TaskSupervisor
- j/k updates preview for newly selected row
- Narrow terminals (<100 cols): peek replaces list

Action (action.rs):
- fetch_mrs(conn, filter, cursor, page_size, clock, snapshot_fence) -> Result<MrListPage, LoreError>: keyset query against merge_requests table. Uses idx_mrs_list_default index.
- fetch_mr_peek(conn, entity_key) -> Result<MrDetail, LoreError>: loads MR detail for Quick Peek preview

View (view/mr_list.rs):
- render_mr_list(frame, state, area, theme): FilterBar + EntityTable with MR columns
- When peek_visible: split area horizontally — list (60%) | peek preview (40%)
- Columns: IID, Title (flex), State, Author, Target, Labels, Updated, Draft indicator
- Draft MRs shown with muted style and [WIP] tag

## Acceptance Criteria
- [ ] Keyset pagination works for MR list (same pattern as issues)
- [ ] Browse snapshot fence prevents rows shifting during concurrent sync
- [ ] Explicit refresh (r) resets snapshot fence
- [ ] filter_hash resets cursor on filter change
- [ ] MR-specific filter fields: draft, reviewer, target_branch, source_branch
- [ ] Draft MRs visually distinguished with [WIP] indicator
- [ ] State filter supports: opened, merged, closed, locked, all
- [ ] Columns: IID, Title, State, Author, Target Branch, Labels, Updated
- [ ] Enter navigates to MrDetail, Esc returns with state preserved
- [ ] Space toggles Quick Peek right-side preview pane
- [ ] Quick Peek loads MR detail asynchronously
- [ ] j/k in peek mode updates preview for newly selected row
- [ ] Narrow terminal (<100 cols): peek replaces list

## Files
- MODIFY: crates/lore-tui/src/state/mr_list.rs (expand from stub)
- MODIFY: crates/lore-tui/src/action.rs (add fetch_mrs, fetch_mr_peek)
- CREATE: crates/lore-tui/src/view/mr_list.rs

## TDD Anchor
RED: Write test_fetch_mrs_draft_filter in action.rs that inserts 5 MRs (3 draft, 2 not), calls fetch_mrs with draft=true filter, asserts 3 results.
GREEN: Implement fetch_mrs with draft filter.
VERIFY: cargo test --manifest-path crates/lore-tui/Cargo.toml test_fetch_mrs

Additional tests:
- test_mr_snapshot_fence: verify fence excludes newer rows
- test_mr_filter_hash_reset: verify filter change resets cursor

## Edge Cases
- MR state "locked" is rare but must be handled in filter and display
- Very long branch names: truncate with ellipsis
- MRs with no reviewer: show "-" in reviewer column
- Quick Peek on empty list: no-op
- Rapid j/k with peek open: debounce peek loads

## Dependency Context
Uses EntityTable and FilterBar from "Implement entity table + filter bar widgets" (bd-18qs).
Uses same keyset pagination pattern from "Implement Issue List" (bd-3ei1).
Uses MrListState from "Implement AppState composition" (bd-1v9m).
Uses TaskSupervisor for load management from "Implement TaskSupervisor" (bd-3le2).
Requires idx_mrs_list_default index from "Add required TUI indexes" (bd-3pm2).


Per-note search: search individual comments at note granularity

## Background
Most knowledge in a GitLab project is buried in discussion threads. Current lore search operates at document level (one doc per issue/MR/discussion). An agent searching for "we decided to use Redis" only finds the parent issue, not the specific comment where that decision was stated.

## Current State (Verified 2026-02-12)
- documents table (migration 007): source_type, source_id, project_id, author_username, label_names, content_text, content_hash, etc. NO source_note_id column.
- source_type values: 'issue', 'merge_request', 'discussion' — discussion docs concatenate all notes into one text blob
- notes table: 282K rows with individual note body, author, timestamps, is_system flag
- discussions table: links notes to their parent entity (noteable_type, noteable_id)
- FTS5 index (documents_fts): operates on coarse document-level text
- Document generation: src/documents/extractor.rs extracts issue/MR/discussion documents
- Document regeneration: src/documents/regenerator.rs handles dirty document refresh
- PRD exists: docs/prd-per-note-search.md with 5 feedback iterations

## Approach

### Schema (Migration 022)
This bead owns migration 022. bd-2g50 (data gaps) ships after this and uses migration 023.

```sql
-- migrations/022_note_documents.sql
ALTER TABLE documents ADD COLUMN source_note_id INTEGER REFERENCES notes(id);
CREATE INDEX idx_documents_source_note ON documents(source_note_id) WHERE source_note_id IS NOT NULL;
```
- source_note_id = NULL for existing entity-level documents (backwards compatible)
- source_note_id = notes.id for new note-level documents

Wire into src/core/db.rs MIGRATIONS array as entry ("022", include_str!("../../migrations/022_note_documents.sql")). LATEST_SCHEMA_VERSION auto-updates since it's `MIGRATIONS.len() as i32`.

### Document Generation (src/documents/extractor.rs)
Add a new extraction function alongside existing `extract_issue_document()` (line 85), `extract_mr_document()` (line 186), `extract_discussion_document()` (line 302):

```rust
pub fn extract_note_documents(
    conn: &Connection,
    project_id: i64,
) -> Result<Vec<DocumentData>> {
    // SELECT n.id, n.body, n.author_username, n.created_at, n.updated_at,
    //        d.noteable_type, d.noteable_id
    // FROM notes n
    // JOIN discussions d ON n.discussion_id = d.id
    // WHERE n.is_system = 0
    //   AND LENGTH(n.body) >= 50
    //   AND d.project_id = ?1
    //   AND n.id NOT IN (SELECT source_note_id FROM documents WHERE source_note_id IS NOT NULL)

    // For each qualifying note:
    // - source_type = 'note'
    // - source_id = note.id (the note's local DB id)
    // - source_note_id = note.id
    // - title = format!("Re: {}", parent_entity_title)
    // - author_username = note.author_username
    // - content_text = note.body
    // - content_hash = sha256(note.body) for deduplication
}
```

Minimum note length (50 chars) filters out "+1", "LGTM", emoji-only notes. is_system=0 filters automated state change notes.

NOTE: The documents table CHECK constraint for source_type needs updating — currently enforces `CHECK (source_type IN ('issue','merge_request','discussion'))`. Migration 022 must also:
```sql
-- Drop and recreate the CHECK constraint is not supported in SQLite ALTER TABLE.
-- Instead, the check is only on INSERT, so we need to handle this:
-- Option A: Don't add 'note' to CHECK — just insert with source_type='note' and let
--           SQLite ignore the CHECK on ALTER (it won't — CHECK is enforced).
-- Option B: Use source_type='discussion' for note docs (semantically wrong).
-- Option C: Recreate the table (heavy migration).
-- RECOMMENDED: Use a new migration that drops the CHECK constraint entirely.
--   SQLite doesn't support ALTER TABLE ... DROP CONSTRAINT, so:
--   CREATE TABLE documents_new (... without CHECK ...);
--   INSERT INTO documents_new SELECT * FROM documents;
--   DROP TABLE documents;
--   ALTER TABLE documents_new RENAME TO documents;
--   Recreate indexes and triggers.
-- This is the only correct approach. The CHECK constraint is in migration 007.
```

### Search Integration
Add --granularity flag to search command:

```rust
// In SearchCliFilters or SearchFilters (src/search/filters.rs:15)
pub granularity: Option<Granularity>,  // note | entity (default)

// In FTS query construction (src/search/fts.rs)
// When granularity = note:
//   AND d.source_note_id IS NOT NULL
// When granularity = entity (or default):
//   AND d.source_note_id IS NULL (existing behavior)
```

### Robot Mode Output (note granularity)
```json
{
  "source_type": "note",
  "title": "Re: Switch Health Card",
  "parent_type": "issue",
  "parent_iid": 3864,
  "parent_title": "Switch Health Card (Throw Times)",
  "note_author": "teernisse",
  "note_created_at": "2026-02-01T...",
  "discussion_id": "abc123",
  "snippet": "...decided to use once-per-day ingestion from BNSF...",
  "score": 0.87
}
```

Join path for note metadata:
```sql
SELECT d.source_note_id, n.author_username, n.created_at,
       disc.gitlab_discussion_id,
       CASE disc.noteable_type
         WHEN 'Issue' THEN 'issue'
         WHEN 'MergeRequest' THEN 'merge_request'
       END as parent_type,
       disc.noteable_id
FROM documents d
JOIN notes n ON d.source_note_id = n.id
JOIN discussions disc ON n.discussion_id = disc.id
WHERE d.source_note_id IS NOT NULL AND d.id IN (...)
```

## TDD Loop
RED: Tests in src/documents/extractor.rs (or new test file):
- test_note_document_generation: insert issue + discussion + 3 notes (one 10 chars, one 60 chars, one 200 chars), run extract_note_documents, assert 2 note-level documents created (>= 50 chars only)
- test_note_document_skips_system_notes: insert system note (is_system=1) with 100-char body, assert no document generated
- test_note_document_content_hash_dedup: insert note, generate doc, re-run, assert no duplicate created
- test_note_document_parent_title: assert generated doc title starts with "Re: "

Tests in src/cli/commands/search.rs:
- test_search_granularity_note_filter: with note docs in DB, --granularity note returns only note results
- test_search_granularity_entity_default: default behavior unchanged, does NOT return note docs

GREEN: Add migration, update extractor, add --granularity flag to search

VERIFY:
```bash
cargo test note_document && cargo test search_granularity
cargo clippy --all-targets -- -D warnings
cargo run --release -- -J search 'ingestion' --granularity note | jq '.data.results[0].parent_iid'
```

## Acceptance Criteria
- [ ] Migration 022 adds source_note_id to documents table (nullable, indexed, FK to notes)
- [ ] Migration 022 handles the source_type CHECK constraint (allows 'note' as valid value)
- [ ] extract_note_documents creates note-level docs for notes >= 50 chars, non-system
- [ ] Content hash deduplication prevents duplicate note documents
- [ ] lore search --granularity note returns note-level results with parent context
- [ ] lore search (no flag) returns entity-level results only (backwards compatible)
- [ ] Robot mode includes parent_type, parent_iid, parent_title, note_author, note_created_at
- [ ] Performance: note-level FTS search across expanded index completes in <200ms
- [ ] Embedding pipeline handles note-level documents (embed individually, same as entity docs)
- [ ] lore stats shows note document count separately from entity document count

## Edge Cases
- Note with only markdown formatting (no text after stripping): skip (LENGTH(body) >= 50 handles most)
- Note body is a quote of another note (duplicated text): deduplicate via content_hash
- Very long note (>32KB): apply same truncation as entity documents (src/documents/truncation.rs)
- Discussion with 100+ notes: each becomes its own document (correct behavior)
- Deleted notes (if tracked): should not generate documents
- Notes on confidential issues: inherit visibility (future concern, not blocking)
- source_type CHECK constraint: migration MUST handle this — SQLite enforces CHECK on INSERT, so inserting source_type='note' will fail without updating the constraint

## Files to Modify
- NEW: migrations/022_note_documents.sql (schema change + CHECK constraint update)
- src/core/db.rs (wire migration 022 into MIGRATIONS array)
- src/documents/extractor.rs (add extract_note_documents function)
- src/documents/mod.rs (export new function)
- src/search/fts.rs (add granularity filter to FTS queries)
- src/search/filters.rs (add granularity to SearchFilters at line 15)
- src/cli/commands/search.rs (--granularity flag, note metadata in SearchResultDisplay)
- src/cli/commands/stats.rs (show note document count)

Replaced by granular beads broken out from docs/prd-per-note-search.md


WHO: Mode resolution, path helpers, run_who entry point

## Background

Core scaffolding that all 5 query modes depend on. Defines the mode discrimination logic, path normalization, path-to-SQL translation (with project-scoped DB probes), time resolution, and the run_who() entry point that dispatches to query functions.

## Approach

### WhoMode enum
```rust
enum WhoMode<'a> {
    Expert { path: String },       // owns String (normalization produces new strings)
    Workload { username: &'a str },  // borrows from args
    Reviews { username: &'a str },
    Active,
    Overlap { path: String },
}
```

### resolve_mode() discrimination rules:
1. --path flag always wins -> Expert
2. --active -> Active
3. --overlap -> Overlap
4. positional target with --reviews -> Reviews
5. positional target containing '/' -> Expert (username never contains /)
6. positional target without '/' -> Workload (strip @ prefix)
7. No args -> error with usage examples

### normalize_repo_path(): strips ./, leading /, collapses //, converts \ to / (Windows paste, only when no / present), trims whitespace

### PathQuery + build_path_query(conn, path, project_id):
- Struct: `{ value: String, is_prefix: bool }`
- Trailing / forces directory prefix
- Root path (no /) without trailing / -> exact match (handles Makefile, LICENSE via --path)
- Last segment contains . -> heuristic: file (exact)
- **Two-way DB probe** (project-scoped): when heuristics are ambiguous, probe DB:
  - Probe 1: exact path exists? `SELECT 1 FROM notes WHERE note_type='DiffNote' AND is_system=0 AND position_new_path = ?1 AND (?2 IS NULL OR project_id = ?2) LIMIT 1`
  - Probe 2 (only if exact miss, not forced-dir): prefix exists?
  - Decision: forced_dir -> prefix; exact_exists -> exact; prefix_exists -> prefix; else heuristic
- **CRITICAL**: escape_like() is ONLY called for prefix (LIKE) matches. For exact matches (=), use raw path — LIKE metacharacters (_, %) are not special in = comparisons.

### Result types: WhoRun, WhoResolvedInput (since_mode tri-state: "default"/"explicit"/"none"), WhoResult enum, all 5 mode-specific result structs (see plan Step 2 "Result Types")

### run_who() entry: resolve project -> resolve mode -> resolve since -> dispatch to query_* -> return WhoRun

### since_mode semantics:
- Expert/Reviews/Active/Overlap: default window applies if --since absent -> "default"
- Workload: no default window; --since absent -> "none"
- Any mode with explicit --since -> "explicit"

## Files

- `src/cli/commands/who.rs` — all code in this file

## TDD Loop

RED:
```
test_is_file_path_discrimination — resolve_mode for paths/usernames/@/--reviews/--path
test_build_path_query — directory/file/root/dotted/underscore/dotless
test_build_path_query_exact_does_not_escape — _ in exact path stays raw
test_path_flag_dotless_root_file_is_exact — Makefile/Dockerfile via --path
test_build_path_query_dotless_subdir_file_uses_db_probe — src/Dockerfile with/without DB data
test_build_path_query_probe_is_project_scoped — data in proj 1, query proj 2
test_escape_like — normal/underscore/percent/backslash
test_normalize_repo_path — ./ / \\ // whitespace identity
test_lookup_project_path — basic round-trip
```

GREEN: Implement all functions. Query functions can be stubs (todo!()) for now.
VERIFY: `cargo test -- who`

## Acceptance Criteria

- [ ] resolve_mode correctly discriminates all 7 cases (see tests)
- [ ] build_path_query returns exact for files, prefix for dirs
- [ ] build_path_query DB probe is project-scoped (cross-project isolation)
- [ ] escape_like escapes %, _, \ correctly
- [ ] normalize_repo_path handles ./, /, \\, //, whitespace
- [ ] WhoResolvedInput.since_mode is "none" for Workload without --since

## Edge Cases

- Dotless files in subdirectories (src/Dockerfile, infra/Makefile) — DB probe catches these, heuristic alone would misclassify as directory
- Windows path paste (src\foo\bar.rs) — convert \ to / only when no / present
- LIKE metacharacters in filenames (README_with_underscore.md) — must NOT be escaped for exact match
- Root files without / (README.md, LICENSE, Makefile) — must use --path flag, positional would treat as username

Implemented by agent team: migration 017, CLI skeleton, all 5 query modes, human+robot output, 20 tests. All quality gates pass.


Implement Clock trait (SystemClock + FakeClock)

## Background
All relative-time rendering (e.g., "3h ago" labels) must use an injected Clock, not wall-clock time. This ensures deterministic snapshot tests and consistent timestamps within a single frame. FakeClock lets tests control time precisely.

## Approach
Create crates/lore-tui/src/clock.rs with:
- Clock trait: fn now(&self) -> chrono::DateTime<chrono::Utc>
- SystemClock: impl Clock using chrono::Utc::now()
- FakeClock: wraps Arc<Mutex<DateTime<Utc>>>, impl Clock returning the frozen value. Methods: new(fixed_time), advance(duration), set(time)
- Both cloneable (SystemClock is Copy, FakeClock shares Arc)

## Acceptance Criteria
- [ ] Clock trait with now() method
- [ ] SystemClock returns real wall-clock time
- [ ] FakeClock returns frozen time, advance() moves it forward
- [ ] FakeClock is Clone (shared Arc)
- [ ] Tests pass: frozen clock returns same time on repeated calls
- [ ] Tests pass: advance() moves time forward by exact duration

## Files
- CREATE: crates/lore-tui/src/clock.rs

## TDD Anchor
RED: Write test_fake_clock_frozen that creates FakeClock at a fixed time, calls now() twice, asserts both return the same value.
GREEN: Implement FakeClock with Arc<Mutex<DateTime>>.
VERIFY: cargo test --manifest-path crates/lore-tui/Cargo.toml test_fake_clock

## Edge Cases
- FakeClock must be Send+Sync for use across Cmd::task threads
- advance() must handle chrono overflow gracefully (use checked_add)

Clock trait + SystemClock + FakeClock with 7 tests: frozen time, advance, set, clone-shares-state, Send+Sync, trait object. Clippy clean.


[CP1] Unit tests for transformers

Comprehensive unit tests for issue and discussion transformers.

## Issue Transformer Tests (tests/issue_transformer_tests.rs)

- transforms_gitlab_issue_to_normalized_schema
- extracts_labels_from_issue_payload
- handles_missing_optional_fields_gracefully
- converts_iso_timestamps_to_ms_epoch
- sets_last_seen_at_to_current_time

## Discussion Transformer Tests (tests/discussion_transformer_tests.rs)

- transforms_discussion_payload_to_normalized_schema
- extracts_notes_array_from_discussion
- sets_individual_note_flag_correctly
- flags_system_notes_with_is_system_true
- preserves_note_order_via_position_field
- computes_first_note_at_and_last_note_at_correctly
- computes_resolvable_and_resolved_status

## Test Setup
- Load from test fixtures
- Use serde_json for deserialization
- Compare against expected NormalizedX structs

Files: tests/issue_transformer_tests.rs, tests/discussion_transformer_tests.rs
Done when: All transformer unit tests pass


Epic: Gate A - Lexical MVP

## Background
Gate A delivers the lexical search MVP — the foundation that works without sqlite-vec or Ollama. It introduces the document layer (documents, document_labels, document_paths), FTS5 indexing, search filters, and the search + stats + generate-docs CLI commands. Gate A is independently shippable — users get working search with FTS5 only.

## Gate A Deliverables
1. Document generation from issues/MRs/discussions with FTS5 indexing
2. Lexical search + filters + snippets + lore stats

## Bead Dependencies (execution order)
1. **bd-3lc** — Rename GiError to LoreError (no deps, enables all subsequent work)
2. **bd-hrs** — Migration 007 (blocked by bd-3lc)
3. **bd-221** — Migration 008 FTS5 (blocked by bd-hrs)
4. **bd-36p** — Document types + extractor module (blocked by bd-3lc)
5. **bd-18t** — Truncation logic (blocked by bd-36p)
6. **bd-247** — Issue extraction (blocked by bd-36p, bd-hrs)
7. **bd-1yz** — MR extraction (blocked by bd-36p, bd-hrs)
8. **bd-2fp** — Discussion extraction (blocked by bd-36p, bd-hrs, bd-18t)
9. **bd-1u1** — Document regenerator (blocked by bd-36p, bd-38q, bd-hrs)
10. **bd-1k1** — FTS5 search (blocked by bd-221)
11. **bd-3q2** — Search filters (blocked by bd-36p)
12. **bd-3lu** — Search CLI (blocked by bd-1k1, bd-3q2, bd-36p)
13. **bd-3qs** — Generate-docs CLI (blocked by bd-1u1, bd-3lu)
14. **bd-pr1** — Stats CLI (blocked by bd-hrs)
15. **bd-2dk** — Project resolution (blocked by bd-3lc)

## Acceptance Criteria
- [ ] `lore search "query"` returns FTS5 results with snippets
- [ ] `lore search --type issue --label bug "query"` filters correctly
- [ ] `lore generate-docs` creates documents from all entities
- [ ] `lore generate-docs --full` regenerates everything
- [ ] `lore stats` shows document/FTS/queue counts
- [ ] `lore stats --check` verifies FTS consistency
- [ ] No sqlite-vec dependency in Gate A

All Gate A sub-beads complete. Lexical MVP delivered: document extraction (issue/MR/discussion), FTS5 indexing, search with filters/snippets/RRF, generate-docs CLI, stats CLI with integrity check/repair.


Implement trace query: file -> MR -> issue -> discussion chain

## Background

The trace query builds a chain from file path -> MRs -> issues -> discussions, combining data from mr_file_changes (Gate 4), entity_references (Gate 2), and the existing discussions/notes tables. This is the backend for the trace CLI command.

**Spec reference:** `docs/phase-b-temporal-intelligence.md` Section 5.4 (Query Flow Tier 1).

## Codebase Context

- entity_references table (migration 011): source_entity_type, source_entity_id, target_entity_type, target_entity_id, reference_type, source_method
- mr_file_changes table (migration 016, bd-1oo): merge_request_id, project_id, old_path, new_path, change_type
- discussions table: issue_id, merge_request_id
- notes table: discussion_id, author_username, body, created_at, is_system, position_new_path (for DiffNotes)
- merge_requests table: iid, title, state, author_username, web_url, merged_at, updated_at
- issues table: iid, title, state, web_url
- resolve_rename_chain() from bd-1yx (src/core/file_history.rs) provides multi-path matching
- reference_type values: 'closes', 'mentioned', 'related'

## Approach

Create `src/core/trace.rs`:

```rust
use rusqlite::Connection;
use crate::core::file_history::resolve_rename_chain;
use crate::core::error::Result;

#[derive(Debug, Clone, Serialize)]
pub struct TraceChain {
    pub merge_request: TraceMr,
    pub issues: Vec<TraceIssue>,
    pub discussions: Vec<TraceDiscussion>,
}

#[derive(Debug, Clone, Serialize)]
pub struct TraceMr {
    pub iid: i64,
    pub title: String,
    pub state: String,
    pub author_username: String,
    pub web_url: Option<String>,
    pub merged_at: Option<i64>,
    pub merge_commit_sha: Option<String>,
    pub file_change_type: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct TraceIssue {
    pub iid: i64,
    pub title: String,
    pub state: String,
    pub web_url: Option<String>,
    pub reference_type: String,   // "closes", "mentioned", "related"
}

#[derive(Debug, Clone, Serialize)]
pub struct TraceDiscussion {
    pub author_username: String,
    pub body_snippet: String,     // truncated to 500 chars
    pub created_at: i64,
    pub is_diff_note: bool,       // true if position_new_path matched
}

#[derive(Debug, Clone, Serialize)]
pub struct TraceResult {
    pub path: String,
    pub resolved_paths: Vec<String>,
    pub chains: Vec<TraceChain>,
}

pub fn run_trace(
    conn: &Connection,
    project_id: i64,
    path: &str,
    follow_renames: bool,
    include_discussions: bool,
    limit: usize,
) -> Result<TraceResult> {
    // 1. Resolve rename chain (unless !follow_renames)
    let paths = if follow_renames {
        resolve_rename_chain(conn, project_id, path, 10)?
    } else {
        vec![path.to_string()]
    };

    // 2. Find MRs via mr_file_changes for all resolved paths
    //    Dynamic IN-clause for path set
    // 3. For each MR, find linked issues via entity_references
    // 4. If include_discussions, fetch DiffNote discussions on traced file
    // 5. Order chains by COALESCE(merged_at, updated_at) DESC, apply limit
}
```

### SQL for step 2 (find MRs):

Build dynamic IN-clause placeholders for the resolved path set:
```sql
SELECT DISTINCT mr.id, mr.iid, mr.title, mr.state, mr.author_username,
       mr.web_url, mr.merged_at, mr.updated_at, mr.merge_commit_sha,
       mfc.change_type
FROM mr_file_changes mfc
JOIN merge_requests mr ON mr.id = mfc.merge_request_id
WHERE mfc.project_id = ?1
  AND (mfc.new_path IN (...placeholders...) OR mfc.old_path IN (...placeholders...))
ORDER BY COALESCE(mr.merged_at, mr.updated_at) DESC
LIMIT ?N
```

### SQL for step 3 (linked issues):
```sql
SELECT i.iid, i.title, i.state, i.web_url, er.reference_type
FROM entity_references er
JOIN issues i ON i.id = er.target_entity_id
WHERE er.source_entity_type = 'merge_request'
  AND er.source_entity_id = ?1
  AND er.target_entity_type = 'issue'
```

### SQL for step 4 (DiffNote discussions):
```sql
SELECT n.author_username, n.body, n.created_at, n.position_new_path
FROM notes n
JOIN discussions d ON d.id = n.discussion_id
WHERE d.merge_request_id = ?1
  AND n.position_new_path IN (...placeholders...)
  AND n.is_system = 0
ORDER BY n.created_at ASC
```

Register in `src/core/mod.rs`: `pub mod trace;`

## Acceptance Criteria

- [ ] run_trace() returns chains ordered by COALESCE(merged_at, updated_at) DESC
- [ ] Rename-aware: uses all paths from resolve_rename_chain
- [ ] Issues linked via entity_references (closes, mentioned, related)
- [ ] DiffNote discussions correctly filtered to traced file paths via position_new_path
- [ ] Discussion body_snippet truncated to 500 chars
- [ ] Empty result (file not in any MR) returns TraceResult with empty chains
- [ ] Limit applies to number of chains (MRs), not total discussions
- [ ] Module registered in src/core/mod.rs as `pub mod trace;`
- [ ] `cargo check --all-targets` passes
- [ ] `cargo clippy --all-targets -- -D warnings` passes

## Files

- `src/core/trace.rs` (NEW)
- `src/core/mod.rs` (add `pub mod trace;`)

## TDD Loop

RED:
- `test_trace_empty_file` — unknown file returns empty chains
- `test_trace_finds_mr` — file in mr_file_changes returns chain with correct MR
- `test_trace_follows_renames` — renamed file finds historical MRs
- `test_trace_links_issues` — MR with entity_references shows linked issues
- `test_trace_limits_chains` — limit=1 returns at most 1 chain
- `test_trace_no_follow_renames` — follow_renames=false only matches literal path

Tests need in-memory DB with migrations applied through 016 + test fixtures for mr_file_changes, entity_references, discussions, notes.

GREEN: Implement SQL queries and chain assembly.

VERIFY: `cargo test --lib -- trace`

## Edge Cases

- MR with no linked issues: chain has empty issues vec
- Same issue linked from multiple MRs: appears in each chain independently
- DiffNote on old_path (before rename): captured via resolved path set
- include_discussions=false: skip DiffNote query for performance
- Null merged_at: falls back to updated_at for ordering
- Dynamic IN-clause: use rusqlite::params_from_iter for parameterized queries


[CP1] Issue ingestion module

Fetch and store issues with cursor-based incremental sync.

Implement ingestIssues(options) → { fetched, upserted, labelsCreated }

Logic:
1. Get current cursor from sync_cursors
2. Paginate through issues updated after cursor
3. Apply local filtering for tuple cursor semantics
4. For each issue:
   - Store raw payload (compressed)
   - Upsert issue record
   - Extract and upsert labels
   - Link issue to labels via junction
5. Update cursor after each page commit

Files: src/ingestion/issues.ts
Tests: tests/integration/issue-ingestion.test.ts
Done when: Issues, labels, issue_labels populated correctly with resumable cursor


Implement snapshot test infrastructure + terminal compat matrix

## Background
Snapshot tests ensure deterministic rendering using FakeClock and ftui's test backend. They capture rendered TUI output as styled text and compare against golden files, catching visual regressions without a real terminal. The terminal compatibility matrix is a separate documentation artifact, not an automated test.

## Approach

### Snapshot Infrastructure

**Test Backend**: Use `ftui_harness::TestBackend` (or equivalent from ftui-harness crate) which captures rendered output as a Buffer without needing a real terminal. If ftui-harness is not available, create a minimal TestBackend that implements ftui's backend trait and stores cells in a `Vec<Vec<Cell>>`.

**Deterministic Rendering**:
- Inject FakeClock (from bd-2lg6) to freeze all relative time computations ("2 hours ago" always renders the same)
- Fix terminal size to 120x40 for all snapshot tests
- Use synthetic DB fixture with known data (same fixture pattern as parity tests)

**Snapshot Capture Flow**:
```rust
fn capture_snapshot(app: &LoreApp, size: (u16, u16)) -> String {
    let backend = TestBackend::new(size.0, size.1);
    // Render app.view() to backend
    // Convert buffer cells to plain text with ANSI annotations
    // Return as String
}
```

**Golden File Management**:
- Golden files stored in `crates/lore-tui/tests/snapshots/` as `.snap` files
- Naming: `{test_name}.snap` (e.g., `dashboard_default.snap`)
- Update mode: set env var `UPDATE_SNAPSHOTS=1` to overwrite golden files instead of comparing
- Use `insta` crate (or manual file comparison) for snapshot assertion

**Fixture Data** (synthetic, deterministic):
- 50 issues (mix of opened/closed/locked states, various labels)
- 25 MRs (mix of opened/merged/closed/draft)
- 100 discussions with notes
- Known timestamps relative to FakeClock's frozen time

### Snapshot Tests

Each test:
1. Creates in-memory DB with fixture data
2. Creates LoreApp with FakeClock frozen at 2026-01-15T12:00:00Z
3. Sets initial screen state
4. Renders via TestBackend at 120x40
5. Compares output against golden file

Tests to implement:
- `test_dashboard_snapshot`: Dashboard screen with fixture counts and recent activity
- `test_issue_list_snapshot`: Issue list with default sort, showing state badges and relative times
- `test_issue_detail_snapshot`: Single issue detail with description and discussion thread
- `test_mr_list_snapshot`: MR list showing draft indicators and review status
- `test_search_results_snapshot`: Search results with highlighted matches
- `test_empty_state_snapshot`: Dashboard with empty DB (zero issues/MRs)

### Terminal Compatibility Matrix (Documentation)

This is a manual verification checklist, NOT an automated test. Document results in `crates/lore-tui/TERMINAL_COMPAT.md`:

| Feature | iTerm2 | tmux | Alacritty | kitty |
|---------|--------|------|-----------|-------|
| True color (RGB) | | | | |
| Unicode width (CJK) | | | | |
| Box-drawing chars | | | | |
| Bold/italic/underline | | | | |
| Mouse events | | | | |
| Resize handling | | | | |
| Alt screen | | | | |

Fill in during manual QA, not during automated test implementation.

## Acceptance Criteria
- [ ] At least 6 snapshot tests pass with golden files committed to repo
- [ ] All snapshots use FakeClock frozen at 2026-01-15T12:00:00Z
- [ ] All snapshots render at fixed 120x40 terminal size
- [ ] Dashboard snapshot matches golden file (deterministic)
- [ ] Issue list snapshot matches golden file (deterministic)
- [ ] Empty state snapshot matches golden file
- [ ] UPDATE_SNAPSHOTS=1 env var overwrites golden files for updates
- [ ] Golden files are plain text (diffable in version control)
- [ ] TERMINAL_COMPAT.md template created (to be filled during manual QA)

## Files
- CREATE: crates/lore-tui/tests/snapshot_tests.rs
- CREATE: crates/lore-tui/tests/snapshots/ (directory for golden files)
- CREATE: crates/lore-tui/tests/snapshots/dashboard_default.snap
- CREATE: crates/lore-tui/tests/snapshots/issue_list_default.snap
- CREATE: crates/lore-tui/tests/snapshots/issue_detail.snap
- CREATE: crates/lore-tui/tests/snapshots/mr_list_default.snap
- CREATE: crates/lore-tui/tests/snapshots/search_results.snap
- CREATE: crates/lore-tui/tests/snapshots/empty_state.snap
- CREATE: crates/lore-tui/TERMINAL_COMPAT.md (template)

## TDD Anchor
RED: Write `test_dashboard_snapshot` that creates LoreApp with FakeClock and fixture DB, renders Dashboard at 120x40, asserts output matches `snapshots/dashboard_default.snap`. Fails because golden file does not exist yet.
GREEN: Render the Dashboard, run with UPDATE_SNAPSHOTS=1 to generate golden file, then run normally to verify match.
VERIFY: cargo test --manifest-path crates/lore-tui/Cargo.toml snapshot

## Edge Cases
- Golden file encoding: always UTF-8, normalize line endings to LF
- FakeClock must be injected into all components that compute relative time (e.g., "2 hours ago")
- Snapshot diffs on CI: print a clear diff showing expected vs actual when mismatch occurs
- Fixture data must NOT include non-deterministic values (random IDs, current timestamps)
- If ftui-harness API changes, TestBackend shim may need updating

## Dependency Context
- Uses FakeClock from bd-2lg6 (Implement Clock trait)
- Uses all screen views from Phase 2 (Dashboard, Issue List, MR List, Detail views)
- Uses TestBackend from ftui-harness crate (or custom implementation)
- Depends on bd-3h00 (session persistence) per phase ordering — screens must be complete before snapshotting
- Downstream: bd-nu0d (fuzz tests) and bd-3fjk (race tests) depend on this infrastructure


OBSERV Epic: Phase 2 - Spans + Correlation IDs

Add tracing spans to all sync stages and generate UUID-based run_id for correlation. Every log line within a sync run includes run_id in JSON span context. Nested spans produce correct parent-child chains.

Depends on: Phase 1 (subscriber must support span recording)
Unblocks: Phase 3 (metrics), Phase 5 (rate limit logging)

Files: src/cli/commands/sync.rs, src/cli/commands/ingest.rs, src/ingestion/orchestrator.rs, src/documents/regenerator.rs, src/embedding/pipeline.rs, src/main.rs

Acceptance criteria (PRD Section 6.2):
- Every log line includes run_id in JSON span context
- Nested spans produce chain: fetch_pages includes parent ingest_issues span
- run_id is 8-char hex (truncated UUIDv4)
- Spans visible in -vv stderr output

Phase 2 complete: run_id correlation IDs generated at sync/ingest entry, root spans with .instrument() for async, #[instrument] on 5 key pipeline functions


Write integration tests

## Background
Integration tests verify that modules work together with a real SQLite database. They test FTS search (stemming, empty results), embedding storage (sqlite-vec ops), hybrid search (combined retrieval), and sync orchestration (full pipeline). Each test creates a fresh in-memory DB with migrations applied.

## Approach
Create integration test files in `tests/`:

**1. tests/fts_search.rs:**
- Create DB, apply migrations 001-008
- Insert test documents via SQL
- Verify FTS5 triggers fired (documents_fts has matching count)
- Search with various queries: stemming, prefix, empty, special chars
- Verify result ranking (BM25 ordering)
- Verify snippet generation

**2. tests/embedding.rs:**
- Create DB, apply migrations 001-009 (requires sqlite-vec)
- Insert test documents + embeddings with known vectors
- Verify KNN search returns nearest neighbors
- Verify chunk deduplication
- Verify orphan cleanup trigger (delete document -> embeddings gone)

**3. tests/hybrid_search.rs:**
- Create DB, apply all migrations
- Insert documents + embeddings
- Test all three modes: lexical, semantic, hybrid
- Verify RRF ranking produces expected order
- Test graceful degradation (no embeddings -> FTS fallback)
- Test adaptive recall with filters

**4. tests/sync.rs:**
- Test sync orchestration with mock/stub GitLab responses
- Verify pipeline stages execute in order
- Verify lock acquisition/release
- Verify --no-embed and --no-docs flags

**Test fixtures:**
- Deterministic embedding vectors (no Ollama required): e.g., [1.0, 0.0, 0.0, ...] for doc1, [0.0, 1.0, 0.0, ...] for doc2
- Known documents with predictable search results
- Fixed timestamps for reproducibility

## Acceptance Criteria
- [ ] FTS search tests pass (stemming, prefix, empty, special chars)
- [ ] Embedding tests pass (KNN, dedup, orphan cleanup)
- [ ] Hybrid search tests pass (all 3 modes, graceful degradation)
- [ ] Sync tests pass (pipeline orchestration)
- [ ] All tests use in-memory DB (no file I/O)
- [ ] No external dependencies (no Ollama, no GitLab) — use fixtures/stubs
- [ ] `cargo test --test fts_search --test embedding --test hybrid_search --test sync` passes

## Files
- `tests/fts_search.rs` — new file
- `tests/embedding.rs` — new file
- `tests/hybrid_search.rs` — new file
- `tests/sync.rs` — new file
- `tests/fixtures/` — optional: test helper functions (shared DB setup)

## TDD Loop
These ARE integration tests — they verify the combined behavior of multiple beads.
VERIFY: `cargo test --test fts_search && cargo test --test embedding && cargo test --test hybrid_search && cargo test --test sync`

## Edge Cases
- sqlite-vec not available: embedding tests should skip gracefully (or require feature flag)
- In-memory DB with WAL mode: may behave differently than file DB — test both if critical
- Concurrent test execution: each test creates its own DB (no shared state)

Integration tests: 10 FTS search tests (stemming, empty, special chars, ordering, triggers, null title), 5 embedding tests (KNN, limit, dedup, orphan trigger, empty DB), 6 hybrid search tests (lexical mode, FTS-only, graceful degradation, RRF ranking, filters, mode variants). 310 total tests pass.


OBSERV Epic: Phase 1 - Verbosity Flags + Structured File Logging

Foundation layer for observability. Add -v/-vv/-vvv CLI flags, dual-layer tracing subscriber (stderr + file), daily log rotation via tracing-appender, log retention cleanup, --log-format json flag, and LoggingConfig.

Depends on: nothing (first phase)
Unblocks: Phase 2, and transitively all other phases

Files: Cargo.toml, src/cli/mod.rs, src/main.rs, src/core/config.rs, src/core/paths.rs, src/cli/commands/doctor.rs

Acceptance criteria (PRD Section 6.1):
- JSON log files written to ~/.local/share/lore/logs/ with zero config
- -v/-vv/-vvv control stderr verbosity per table in PRD 4.3
- RUST_LOG overrides -v for both layers
- --log-format json emits JSON on stderr
- Daily rotation, retention cleanup on startup
- --quiet suppresses stderr, does NOT affect file layer
- lore doctor reports log directory info

Phase 1 complete: dual-layer subscriber, -v/--verbose flags, --log-format json, LoggingConfig, get_log_dir(), log retention, doctor diagnostics


Epic: TUI Phase 5.6 — CLI/TUI Parity Pack

## Background
Phase 5.6 ensures the TUI displays the same data as the CLI robot mode, preventing drift between interfaces. Tests compare TUI query results against CLI --robot output for counts, list data, detail data, and search results.

## Acceptance Criteria
- [ ] Dashboard counts match lore --robot count output
- [ ] Issue/MR list data matches lore --robot issues/mrs output
- [ ] Issue/MR detail data matches lore --robot issues/mrs <iid> output
- [ ] Search results identity (same IDs, same order) matches lore --robot search output
- [ ] Terminal safety sanitization applied consistently in TUI and CLI


Implement entity cache + render cache

## Background
Entity cache provides near-instant detail view reopens during Enter/Esc drill workflows by caching IssueDetail/MrDetail payloads. Render cache prevents per-frame recomputation of expensive render artifacts (markdown to styled text, discussion tree shaping). Both use bounded LRU eviction with selective invalidation.

## Approach

### Entity Cache (entity_cache.rs)

```rust
use std::collections::HashMap;

pub struct EntityCache<V> {
    entries: HashMap<EntityKey, (V, u64)>,  // value + last-access tick
    capacity: usize,
    tick: u64,
}

impl<V> EntityCache<V> {
    pub fn new(capacity: usize) -> Self;
    pub fn get(&mut self, key: &EntityKey) -> Option<&V>;  // updates tick
    pub fn put(&mut self, key: EntityKey, value: V);       // evicts oldest if at capacity
    pub fn invalidate(&mut self, keys: &[EntityKey]);      // selective by key set
}
```

- `EntityKey` is `(EntityType, i64)` from core types (bd-c9gk) — e.g., `(EntityType::Issue, 42)`
- Default capacity: 64 entries (sufficient for typical drill-in/out workflows)
- LRU eviction: on `put()` when at capacity, find entry with lowest tick and remove it
- `get()` bumps the access tick to keep recently-accessed entries alive
- `invalidate()` takes a slice of changed keys (from sync results) and removes only those entries — NOT a blanket clear

### Render Cache (render_cache.rs)

```rust
pub struct RenderCacheKey {
    content_hash: u64,      // FxHash of source content
    terminal_width: u16,    // width affects line wrapping
}

pub struct RenderCache<V> {
    entries: HashMap<RenderCacheKey, V>,
    capacity: usize,
}

impl<V> RenderCache<V> {
    pub fn new(capacity: usize) -> Self;
    pub fn get(&self, key: &RenderCacheKey) -> Option<&V>;
    pub fn put(&mut self, key: RenderCacheKey, value: V);
    pub fn invalidate_width(&mut self, keep_width: u16);  // remove entries NOT matching this width
    pub fn invalidate_all(&mut self);                      // theme change = full clear
}
```

- Default capacity: 256 entries
- Used for: markdown->styled text, discussion tree layout, issue body rendering
- `content_hash` uses `std::hash::Hasher` with FxHash (or std DefaultHasher) on source text
- `invalidate_width(keep_width)`: on terminal resize, remove entries cached at old width
- `invalidate_all()`: on theme change, clear everything (colors changed)
- Both caches are NOT thread-safe (single-threaded TUI event loop). No Arc/Mutex needed.

### Integration Point
Both caches live as fields on the main LoreApp struct. Cache miss falls through to normal DB query transparently — the action functions check cache first, query DB on miss, populate cache on return.

## Acceptance Criteria
- [ ] EntityCache::get returns Some for recently put items
- [ ] EntityCache::put evicts the least-recently-accessed entry when at capacity
- [ ] EntityCache::invalidate removes only the specified keys, leaves others intact
- [ ] EntityCache capacity defaults to 64
- [ ] RenderCache::get returns Some for matching (hash, width) pair
- [ ] RenderCache::invalidate_width removes entries with non-matching width
- [ ] RenderCache::invalidate_all clears everything
- [ ] RenderCache capacity defaults to 256
- [ ] Both caches are Send (no Rc, no raw pointers) but NOT required to be Sync
- [ ] No unsafe code

## Files
- CREATE: crates/lore-tui/src/entity_cache.rs
- CREATE: crates/lore-tui/src/render_cache.rs
- MODIFY: crates/lore-tui/src/lib.rs (add `pub mod entity_cache; pub mod render_cache;`)

## TDD Anchor
RED: Write `test_entity_cache_lru_eviction` that creates EntityCache with capacity 3, puts 4 items, asserts first item (lowest tick) is evicted and the other 3 remain.
GREEN: Implement LRU eviction using tick-based tracking.
VERIFY: cargo test --manifest-path crates/lore-tui/Cargo.toml entity_cache

Additional tests:
- test_entity_cache_get_bumps_tick (accessed item survives eviction over older untouched items)
- test_entity_cache_invalidate_selective (removes only specified keys)
- test_entity_cache_invalidate_nonexistent_key (no panic)
- test_render_cache_width_invalidation (entries at old width removed, current width kept)
- test_render_cache_invalidate_all (empty after call)
- test_render_cache_capacity_eviction

## Edge Cases
- Invalidating an EntityKey not in the cache is a no-op (no panic)
- Zero-capacity cache: all gets return None, all puts are no-ops (degenerate but safe)
- RenderCacheKey equality: two different strings can have the same hash (collision) — accept this; worst case is a wrong cached render that gets corrected on next invalidation
- Entity cache should NOT be prewarmed synchronously during sync — sync results just invalidate stale entries, and the next view() call repopulates on demand

## Dependency Context
Depends on bd-c9gk (core types) for EntityKey type definition.
Both caches are integrated into LoreApp (bd-6pmy) as struct fields.
Action functions (from Phase 2/3 screen beads) check cache before querying DB.


[CP1] Epic: Issue Ingestion

Ingest all issues, labels, and issue discussions from configured GitLab repositories with resumable cursor-based incremental sync. This establishes the core data ingestion pattern reused for MRs in CP2.

## Success Criteria
- gi ingest --type=issues fetches all issues (count matches GitLab UI)
- Labels extracted from issue payloads (name-only)
- Label linkage reflects current GitLab state (removed labels unlinked on re-sync)
- Issue discussions fetched per-issue (dependent sync)
- Cursor-based sync is resumable (re-running fetches 0 new items)
- Discussion sync skips unchanged issues (per-issue watermark)
- Sync tracking records all runs
- Single-flight lock prevents concurrent runs

## Internal Gates
- Gate A: Issues only (cursor + upsert + raw payloads + list/count/show)
- Gate B: Labels correct (stale-link removal verified)
- Gate C: Dependent discussion sync (watermark prevents redundant refetch)
- Gate D: Resumability proof (kill mid-run, rerun; bounded redo)

Reference: docs/prd/checkpoint-1.md


WHO: CLI skeleton — WhoArgs, Commands::Who, dispatch arm

## Background

Wire up the CLI plumbing so `lore who --help` works and dispatch reaches the who module. This is pure boilerplate — no query logic yet.

## Approach

### 1. src/cli/mod.rs — WhoArgs struct (after TimelineArgs, ~line 195)

```rust
#[derive(Parser)]
#[command(after_help = "\x1b[1mExamples:\x1b[0m
  lore who src/features/auth/           # Who knows about this area?
  lore who @asmith                      # What is asmith working on?
  lore who @asmith --reviews            # What review patterns does asmith have?
  lore who --active                     # What discussions need attention?
  lore who --overlap src/features/auth/ # Who else is touching these files?
  lore who --path README.md             # Expert lookup for a root file")]
pub struct WhoArgs {
    /// Username or file path (path if contains /)
    pub target: Option<String>,

    /// Force expert mode for a file/directory path (handles root files like README.md, Makefile)
    #[arg(long, help_heading = "Mode", conflicts_with_all = ["active", "overlap", "reviews"])]
    pub path: Option<String>,

    /// Show active unresolved discussions
    #[arg(long, help_heading = "Mode", conflicts_with_all = ["target", "overlap", "reviews", "path"])]
    pub active: bool,

    /// Find users with MRs/notes touching this file path
    #[arg(long, help_heading = "Mode", conflicts_with_all = ["target", "active", "reviews", "path"])]
    pub overlap: Option<String>,

    /// Show review pattern analysis (requires username target)
    #[arg(long, help_heading = "Mode", requires = "target", conflicts_with_all = ["active", "overlap", "path"])]
    pub reviews: bool,

    /// Time window (7d, 2w, 6m, YYYY-MM-DD). Default varies by mode.
    #[arg(long, help_heading = "Filters")]
    pub since: Option<String>,

    /// Scope to a project (supports fuzzy matching)
    #[arg(short = 'p', long, help_heading = "Filters")]
    pub project: Option<String>,

    /// Maximum results per section (1..=500)
    #[arg(short = 'n', long = "limit", default_value = "20",
          value_parser = clap::value_parser!(u16).range(1..=500),
          help_heading = "Output")]
    pub limit: u16,
}
```

### 2. Commands enum — add Who(WhoArgs) after Timeline, before hidden List

### 3. src/cli/commands/mod.rs — add `pub mod who;` and re-exports:
```rust
pub use who::{run_who, print_who_human, print_who_json, WhoRun};
```

### 4. src/main.rs — dispatch arm + handler:
```rust
Some(Commands::Who(args)) => handle_who(cli.config.as_deref(), args, robot_mode),
```

### 5. src/cli/commands/who.rs — stub file with signatures that compile

## Files

- `src/cli/mod.rs` — WhoArgs struct + Commands::Who variant
- `src/cli/commands/mod.rs` — pub mod who + re-exports
- `src/main.rs` — dispatch arm + handle_who function + imports
- `src/cli/commands/who.rs` — CREATE stub file

## TDD Loop

RED: `cargo check --all-targets` fails (missing who module)
GREEN: Create stub who.rs with empty/todo!() implementations, wire up all 4 files
VERIFY: `cargo check --all-targets && cargo run -- who --help`

## Acceptance Criteria

- [ ] `cargo check --all-targets` passes
- [ ] `lore who --help` displays all flags with correct grouping (Mode, Filters, Output)
- [ ] `lore who --active --overlap foo` rejected by clap (conflicts_with)
- [ ] `lore who --reviews` rejected by clap (requires target)
- [ ] WhoArgs is pub and importable from lore::cli

## Edge Cases

- conflicts_with_all on --path must NOT include "target" (--path is used alongside positional target in some cases... actually no, --path replaces target — check the plan: it conflicts with active/overlap/reviews but NOT target. Wait, looking at the plan: --path does NOT conflict with target. But if both target and --path are provided, --path takes priority in resolve_mode. The clap struct allows both.)


Dynamic shell completions for file paths (lore complete-path)

## Background

Tab-completion for lore commands currently only covers static subcommand/flag names via clap_complete v4 (src/main.rs handle_completions(), line ~1667). Users frequently type file paths (for who --path, file-history) and entity IIDs (for issues, mrs, show) manually. Dynamic completions would allow tab-completing these from the local SQLite database.

**Pattern:** kubectl, gh, docker all use hidden subcommands for dynamic completions. clap_complete v4 has a custom completer API that can shell out to these hidden subcommands.

## Codebase Context

- **Static completions**: Commands::Completions variant in src/cli/mod.rs, handled by handle_completions() in src/main.rs (line ~1667) using clap_complete::generate()
- **clap_complete v4**: Already in Cargo.toml. Supports custom completer API for dynamic values.
- **Commands taking IIDs**: IssuesArgs (iid: Option<i64>), MrsArgs (iid: Option<i64>), Drift (for: EntityRef), Show (hidden, takes entity ref)
- **path_resolver**: src/core/path_resolver.rs (245 lines). build_path_query() (lines 71-187) and suffix_probe() (lines 192-240) resolve partial paths against mr_file_changes. SuffixResult::Ambiguous(Vec<String>) returns multiple matches — perfect for completions.
- **who --path**: WhoArgs has `path: Option<String>` field, already uses path_resolver
- **DB access**: create_connection() from src/core/db.rs, config loading from src/core/config.rs
- **Performance**: Must complete in <100ms. SQLite queries against indexed columns are sub-ms.

## Approach

### 1. Hidden Subcommands (src/cli/mod.rs)

Add hidden subcommands that query the DB and print completion candidates:

```rust
/// Hidden: emit file path completions for shell integration
#[command(name = "complete-path", hide = true)]
CompletePath {
    /// Partial path prefix to complete
    prefix: String,
    /// Project scope
    #[arg(short = 'p', long)]
    project: Option<String>,
},

/// Hidden: emit issue IID completions
#[command(name = "complete-issue", hide = true)]
CompleteIssue {
    /// Partial IID prefix
    prefix: String,
    #[arg(short = 'p', long)]
    project: Option<String>,
},

/// Hidden: emit MR IID completions
#[command(name = "complete-mr", hide = true)]
CompleteMr {
    /// Partial IID prefix
    prefix: String,
    #[arg(short = 'p', long)]
    project: Option<String>,
},
```

### 2. Completion Handlers (src/cli/commands/completions.rs NEW)

```rust
pub fn complete_path(conn: &Connection, prefix: &str, project_id: Option<i64>) -> Result<Vec<String>> {
    // Use suffix_probe() from path_resolver if prefix looks like a suffix (no leading /)
    // Otherwise: SELECT DISTINCT new_path FROM mr_file_changes WHERE new_path LIKE ?||'%' LIMIT 50
    // Also check old_path for rename awareness
}

pub fn complete_issue(conn: &Connection, prefix: &str, project_id: Option<i64>) -> Result<Vec<String>> {
    // SELECT iid, title FROM issues WHERE CAST(iid AS TEXT) LIKE ?||'%' ORDER BY updated_at DESC LIMIT 30
    // Output: "123\tFix login bug" (tab-separated for shell description)
}

pub fn complete_mr(conn: &Connection, prefix: &str, project_id: Option<i64>) -> Result<Vec<String>> {
    // SELECT iid, title FROM merge_requests WHERE CAST(iid AS TEXT) LIKE ?||'%' ORDER BY updated_at DESC LIMIT 30
    // Output: "456\tAdd OAuth support"
}
```

### 3. Wire in main.rs

Add match arms for CompletePath, CompleteIssue, CompleteMr. Each:
1. Opens DB connection (read-only)
2. Resolves project if -p given
3. Calls completion handler
4. Prints one candidate per line to stdout
5. Exits 0

### 4. Shell Integration

Update handle_completions() to generate shell scripts that call the hidden subcommands. For fish:
```fish
complete -c lore -n '__fish_seen_subcommand_from issues' -a '(lore complete-issue "")'
complete -c lore -n '__fish_seen_subcommand_from who' -l path -a '(lore complete-path (commandline -ct))'
```

Similar for bash (using `_lore_complete()` function) and zsh.

## Acceptance Criteria

- [ ] `lore complete-path "src/co"` prints matching file paths from mr_file_changes
- [ ] `lore complete-issue "12"` prints matching issue IIDs with titles
- [ ] `lore complete-mr "45"` prints matching MR IIDs with titles
- [ ] All three hidden subcommands respect -p for project scoping
- [ ] All three complete in <100ms (SQLite indexed queries)
- [ ] Empty prefix returns recent/popular results (not all rows)
- [ ] Hidden subcommands don't appear in --help or completions themselves
- [ ] Shell completion scripts (fish, bash, zsh) call hidden subcommands for dynamic values
- [ ] Static completions (subcommands, flags) still work as before
- [ ] No DB connection attempted if DB doesn't exist (graceful degradation — return no completions)
- [ ] `cargo check --all-targets` passes
- [ ] `cargo clippy --all-targets -- -D warnings` passes
- [ ] `cargo fmt --check` passes

## Files

- MODIFY: src/cli/mod.rs (add CompletePath, CompleteIssue, CompleteMr hidden variants)
- CREATE: src/cli/commands/completions.rs (complete_path, complete_issue, complete_mr handlers)
- MODIFY: src/cli/commands/mod.rs (add pub mod completions)
- MODIFY: src/main.rs (match arms for hidden subcommands + update handle_completions shell scripts)

## TDD Anchor

RED:
- test_complete_path_suffix_match (in-memory DB with mr_file_changes rows, verify suffix matching returns correct paths)
- test_complete_issue_prefix (in-memory DB with issues, verify IID prefix filtering)
- test_complete_mr_prefix (same for MRs)
- test_complete_empty_prefix_returns_recent (verify limited results ordered by updated_at DESC)

GREEN: Implement completion handlers with SQL queries.

VERIFY: cargo test --lib -- completions && cargo check --all-targets

## Edge Cases

- DB doesn't exist yet (first run before sync): return empty completions, exit 0 (not error)
- mr_file_changes empty (sync hasn't run with --fetch-mr-diffs): complete-path returns nothing, no error
- Very long prefix with no matches: empty output, exit 0
- Special characters in paths (spaces, brackets): shell quoting handled by completion framework
- Project ambiguous with -p: exit 18, same as other commands (resolve_project pattern)
- IID prefix "0": return nothing (no issues/MRs have iid=0)

## Dependency Context

- **path_resolver** (src/core/path_resolver.rs): provides suffix_probe() which returns SuffixResult::Exact/Ambiguous/NotFound — reuse for complete-path instead of raw SQL when prefix looks like a suffix
- **mr_file_changes** (migration 016): provides new_path/old_path columns for file path completions
- **clap_complete v4** (Cargo.toml): provides generate() for static completions and custom completer API for dynamic shell integration


OBSERV: Replace subscriber init with dual-layer setup

## Background
This is the core infrastructure bead for Phase 1. It replaces the single-layer subscriber (src/main.rs:44-58) with a dual-layer registry that separates stderr and file concerns. The file layer provides always-on post-mortem data; the stderr layer respects -v flags.

## Approach
Replace src/main.rs lines 44-58 with a function (e.g., init_tracing()) that:

1. Build stderr filter from -v count (or RUST_LOG override):
```rust
fn build_stderr_filter(verbose: u8, quiet: bool) -> EnvFilter {
    if let Ok(rust_log) = std::env::var("RUST_LOG") {
        return EnvFilter::new(rust_log);
    }
    if quiet {
        return EnvFilter::new("lore=warn,error");
    }
    match verbose {
        0 => EnvFilter::new("lore=info,warn"),
        1 => EnvFilter::new("lore=debug,warn"),
        2 => EnvFilter::new("lore=debug,info"),
        _ => EnvFilter::new("trace,debug"),
    }
}
```

2. Build file filter (always lore=debug,warn unless RUST_LOG set):
```rust
fn build_file_filter() -> EnvFilter {
    if let Ok(rust_log) = std::env::var("RUST_LOG") {
        return EnvFilter::new(rust_log);
    }
    EnvFilter::new("lore=debug,warn")
}
```

3. Assemble the registry:
```rust
let stderr_layer = fmt::layer()
    .with_target(false)
    .with_writer(SuspendingWriter);
// Conditionally add .json() based on log_format

let file_appender = tracing_appender::rolling::daily(log_dir, "lore");
let (non_blocking, _guard) = tracing_appender::non_blocking(file_appender);
let file_layer = fmt::layer()
    .json()
    .with_writer(non_blocking);

tracing_subscriber::registry()
    .with(stderr_layer.with_filter(build_stderr_filter(cli.verbose, cli.quiet)))
    .with(file_layer.with_filter(build_file_filter()))
    .init();
```

CRITICAL: The non_blocking _guard must be held for the program's lifetime. Store it in main() scope, NOT in the init function. If the guard drops, the file writer thread stops and buffered logs are lost.

CRITICAL: Per-layer filtering requires each .with_filter() to produce a Filtered<L, F, S> type. The two layers will have different concrete types (one with json, one without). This is fine -- the registry accepts heterogeneous layers via .with().

When --log-format json: wrap stderr_layer with .json() too. This requires conditional construction. Two approaches:
  A) Use Box<dyn Layer<S>> for dynamic dispatch (simpler, tiny perf hit)
  B) Use an enum wrapper (zero cost but more code)
Recommend approach A for simplicity. The overhead is one vtable indirection per log event, dwarfed by I/O.

When file_logging is false (LoggingConfig.file_logging == false): skip adding the file layer entirely.

## Acceptance Criteria
- [ ] lore sync writes JSON log lines to ~/.local/share/lore/logs/lore.YYYY-MM-DD.log
- [ ] lore -v sync shows DEBUG lore::* on stderr, deps at WARN
- [ ] lore -vv sync shows DEBUG lore::* + INFO deps on stderr
- [ ] lore -vvv sync shows TRACE everything on stderr
- [ ] RUST_LOG=lore::gitlab=trace overrides -v for both layers
- [ ] lore --log-format json sync emits JSON on stderr
- [ ] -q + -v: -q wins (stderr at WARN+)
- [ ] -q does NOT affect file layer (still DEBUG+)
- [ ] File layer does NOT use SuspendingWriter
- [ ] Non-blocking guard kept alive for program duration
- [ ] Existing behavior unchanged when no new flags passed
- [ ] cargo clippy --all-targets -- -D warnings passes

## Files
- src/main.rs (replace lines 44-58, add init_tracing function or inline)

## TDD Loop
RED:
  - test_verbosity_filter_construction: assert filter directives for verbose=0,1,2,3
  - test_rust_log_overrides_verbose: set env, assert TRACE not DEBUG
  - test_quiet_overrides_verbose: -q + -v => WARN+
  - test_json_log_output_format: capture file output, parse as JSON
  - test_suspending_writer_dual_layer: no garbled stderr with progress bars
GREEN: Implement build_stderr_filter, build_file_filter, assemble registry
VERIFY: cargo test && cargo clippy --all-targets -- -D warnings

## Edge Cases
- _guard lifetime: if guard is dropped early, buffered log lines are lost. MUST hold in main() scope.
- Type erasure: stderr layer with/without .json() produces different types. Use Box<dyn Layer<_>> or separate init paths.
- Empty RUST_LOG string: env::var returns Ok(""), which EnvFilter::new("") defaults to TRACE. May want to check is_empty().
- File I/O error on log dir: tracing-appender handles this gracefully (no panic), but logs will be silently lost. The doctor command (bd-2i10) can diagnose this.

Replaced single-layer subscriber with dual-layer setup: stderr (human/json, -v controlled) + file (always-on JSON, daily rotation via tracing-appender)


Robot sync envelope: status enrichment metadata

## Background
Agents need machine-readable status enrichment metadata in the robot sync output to detect issues like unsupported GraphQL, partial errors, or enrichment failures. Without this, enrichment problems are invisible to automation.

## Approach
Wire IngestProjectResult status fields into the per-project robot sync JSON. Add aggregate error count to top-level summary.

## Files
- Wherever robot sync output JSON is constructed (likely src/cli/commands/ingest.rs or the sync output serialization path — search for IngestProjectResult -> JSON conversion)

## Implementation

Per-project status_enrichment object in robot sync JSON:
{
  "mode": "fetched" | "unsupported" | "skipped",
  "reason": null | "graphql_endpoint_missing" | "auth_forbidden",
  "seen": N,
  "enriched": N,
  "cleared": N,
  "without_widget": N,
  "partial_errors": N,
  "first_partial_error": null | "message",
  "error": null | "message"
}

Source fields from IngestProjectResult:
  mode <- status_enrichment_mode
  reason <- status_unsupported_reason
  seen <- statuses_seen
  enriched <- statuses_enriched
  cleared <- statuses_cleared
  without_widget <- statuses_without_widget
  partial_errors <- partial_error_count
  first_partial_error <- first_partial_error
  error <- status_enrichment_error

Top-level sync summary: add status_enrichment_errors: N (count of projects where error is Some)

Field semantics:
  mode "fetched": enrichment ran (even if 0 statuses or error occurred)
  mode "unsupported": 404/403 from GraphQL
  mode "skipped": config toggle off
  seen > 0 + enriched == 0: project has issues but none with status
  partial_errors > 0: some pages returned incomplete data

## Acceptance Criteria
- [ ] Robot sync JSON includes per-project status_enrichment object
- [ ] All 9 fields present with correct types
- [ ] mode reflects actual enrichment outcome (fetched/unsupported/skipped)
- [ ] Top-level status_enrichment_errors count present
- [ ] Test: full robot sync output validates structure

## TDD Loop
RED: test_robot_sync_includes_status_enrichment
GREEN: Wire fields into JSON serialization
VERIFY: cargo test robot_sync

## Edge Cases
- Find the exact location where IngestProjectResult is serialized to JSON — may be in a Serialize impl or manual json! macro
- All numeric fields default to 0, all Option fields default to null in JSON
- mode is always present (never null)


Implement lore embed CLI command

## Background
The embed CLI command is the user-facing wrapper for the embedding pipeline. It runs Ollama health checks, selects documents to embed (pending or failed), shows progress, and reports results. This is the standalone command for building embeddings outside of the sync orchestrator.

## Approach
Create `src/cli/commands/embed.rs` per PRD Section 4.4.

**IMPORTANT: The embed command is async.** The underlying `embed_documents()` function is `async fn` (uses `FuturesUnordered` for concurrent HTTP to Ollama). The CLI runner must use tokio runtime.

**Core function (async):**
```rust
pub async fn run_embed(
    config: &Config,
    retry_failed: bool,
) -> Result<EmbedResult>
```

**Pipeline:**
1. Create OllamaClient from config.embedding (base_url, model, timeout_secs)
2. Run `client.health_check().await` — fail early with clear error if Ollama unavailable or model missing
3. Determine selection: `EmbedSelection::RetryFailed` if --retry-failed, else `EmbedSelection::Pending`
4. Call `embed_documents(conn, &client, selection, concurrency, progress_callback).await`
   - `concurrency` param controls max in-flight HTTP requests to Ollama
   - `progress_callback` drives indicatif progress bar
5. Show progress bar (indicatif) during embedding
6. Return EmbedResult with counts

**CLI args:**
```rust
#[derive(Args)]
pub struct EmbedArgs {
    #[arg(long)]
    retry_failed: bool,
}
```

**Output:**
- Human: "Embedded 42 documents (15 chunks), 2 errors, 5 skipped (unchanged)"
- JSON: `{"ok": true, "data": {"embedded": 42, "chunks": 15, "errors": 2, "skipped": 5}}`

**Tokio integration note:**
The embed command runs async code. Either:
- Use `#[tokio::main]` on main and propagate async through CLI dispatch
- Or use `tokio::runtime::Runtime::new()` in the embed command handler

## Acceptance Criteria
- [ ] Command is async (embed_documents is async, health_check is async)
- [ ] OllamaClient created from config.embedding settings
- [ ] Health check runs first — clear error if Ollama down (exit code 14)
- [ ] Clear error if model not found: "Pull the model: ollama pull nomic-embed-text" (exit code 15)
- [ ] Embeds pending documents (no existing embeddings or stale content_hash)
- [ ] --retry-failed re-attempts documents with last_error
- [ ] Progress bar shows during embedding (indicatif)
- [ ] embed_documents called with concurrency parameter
- [ ] embed_documents called with progress_callback for progress bar
- [ ] Human + JSON output
- [ ] `cargo build` succeeds

## Files
- `src/cli/commands/embed.rs` — new file
- `src/cli/commands/mod.rs` — add `pub mod embed;`
- `src/cli/mod.rs` — add EmbedArgs, wire up embed subcommand
- `src/main.rs` — add embed command handler (async dispatch)

## TDD Loop
RED: Integration test needing Ollama
GREEN: Implement run_embed (async)
VERIFY: `cargo build && cargo test embed`

## Edge Cases
- No documents in DB: "No documents to embed" (not error)
- All documents already embedded and unchanged: "0 documents to embed (all up to date)"
- Ollama goes down mid-embedding: pipeline records errors for remaining docs, returns partial result
- --retry-failed with no failed docs: "No failed documents to retry"

Embed CLI command fully wired: EmbedArgs, Commands::Embed variant, handle_embed handler, clean build, all tests pass


Epic: TUI Phase 1 — Foundation

## Background
Phase 1 builds the foundational infrastructure that all screens depend on: the full LoreApp Model implementation with key dispatch, navigation stack, task supervisor for async work management, theme configuration, common widgets, and the state/action architecture. Phase 1 deliverables are the skeleton that Phase 2 screens plug into.

## Acceptance Criteria
- [ ] LoreApp update() dispatches all Msg variants through 5-stage key pipeline
- [ ] NavigationStack supports push/pop/forward/jump with state preservation
- [ ] TaskSupervisor manages background tasks with dedup, cancellation, and generation IDs
- [ ] Theme renders correctly with adaptive light/dark colors
- [ ] Status bar, breadcrumb, loading, error toast, and help overlay widgets render
- [ ] CommandRegistry is the single source of truth for keybindings/help/palette
- [ ] AppState composition with per-screen states and LoadState map

## Scope
Blocked by Phase 0 (Toolchain Gate). Blocks Phase 2 (Core Screens).

All 7 acceptance criteria met: 5-stage key pipeline, NavigationStack, TaskSupervisor, Theme, common widgets, CommandRegistry, AppState composition. 177 tests pass. Unblocks Phase 2.


[CP1] gi ingest --type=issues command

CLI command to orchestrate issue ingestion.

## Module
src/cli/commands/ingest.rs

## Clap Definition
#[derive(Subcommand)]
pub enum Commands {
    Ingest {
        #[arg(long, value_parser = ["issues", "merge_requests"])]
        r#type: String,

        #[arg(long)]
        project: Option<String>,

        #[arg(long)]
        force: bool,
    },
}

## Implementation
1. Acquire app lock with heartbeat (respect --force for stale lock)
2. Create sync_run record (status='running')
3. For each configured project (or filtered --project):
   - Call orchestrator to ingest issues and discussions
   - Show progress (spinner or progress bar)
4. Update sync_run (status='succeeded', metrics_json with counts)
5. Release lock

## Output Format
Ingesting issues...

  group/project-one: 1,234 issues fetched, 45 new labels

Fetching discussions (312 issues with updates)...

  group/project-one: 312 issues → 1,234 discussions, 5,678 notes

Total: 1,234 issues, 1,234 discussions, 5,678 notes (excluding 1,234 system notes)
Skipped discussion sync for 922 unchanged issues.

## Error Handling
- Lock acquisition failure: exit with DatabaseLockError message
- Network errors: show GitLabNetworkError, exit non-zero
- Rate limiting: respect backoff, show progress

Files: src/cli/commands/ingest.rs, src/cli/commands/mod.rs
Tests: tests/integration/sync_runs_tests.rs
Done when: Full issue + discussion ingestion works end-to-end


[CP1] Epic: Issue Ingestion

Ingest all issues, labels, and issue discussions from configured GitLab repositories with resumable cursor-based incremental sync. This checkpoint establishes the core data ingestion pattern that will be reused for MRs in Checkpoint 2.

## Success Criteria
- gi ingest --type=issues fetches all issues (count matches GitLab UI)
- Labels extracted from issue payloads (name-only)
- Label linkage reflects current GitLab state (removed labels unlinked on re-sync)
- Issue discussions fetched per-issue (dependent sync)
- Cursor-based sync is resumable (re-running fetches 0 new items)
- Discussion sync skips unchanged issues (per-issue watermark)
- Sync tracking records all runs (sync_runs table)
- Single-flight lock prevents concurrent runs

## Internal Gates
- **Gate A**: Issues only - cursor + upsert + raw payloads + list/count/show working
- **Gate B**: Labels correct - stale-link removal verified; label count matches GitLab
- **Gate C**: Dependent discussion sync - watermark prevents redundant refetch; concurrency bounded
- **Gate D**: Resumability proof - kill mid-run, rerun; bounded redo and no redundant discussion refetch

## Reference
docs/prd/checkpoint-1.md

CP1 Issue Ingestion complete: all sub-tasks done, 71 tests pass, CLI commands working