Implement Trace screen (file -> MR -> issue chain drill-down)

## Background
The Trace screen answers "Why was this code introduced?" by building file -> MR -> issue -> discussion chains. It wraps run_trace() from src/core/trace.rs (added in v0.8.1) in an interactive TUI view where users can drill down into any linked entity. The CLI prints flat output; the TUI makes the chain navigable.

The core query accepts a file path (with optional :line suffix), resolves renames via BFS, finds MRs that touched the file, links issues via entity_references, and extracts DiffNote discussions. Each result is a TraceChain: MR metadata + linked issues + relevant discussions.

## Data Shapes (from src/core/trace.rs)

```rust
pub struct TraceResult {
    pub path: String,
    pub resolved_paths: Vec<String>,      // rename chain via BFS
    pub renames_followed: bool,
    pub trace_chains: Vec<TraceChain>,
    pub total_chains: usize,
}

pub struct TraceChain {
    pub mr_iid: i64,
    pub mr_title: String,
    pub mr_state: String,                 // merged/opened/closed
    pub mr_author: String,
    pub change_type: String,              // added/modified/deleted/renamed
    pub merged_at_iso: Option<String>,
    pub updated_at_iso: String,
    pub web_url: Option<String>,
    pub issues: Vec<TraceIssue>,          // linked via entity_references
    pub discussions: Vec<TraceDiscussion>, // DiffNote threads on this file
}

pub struct TraceIssue {
    pub iid: i64, pub title: String, pub state: String,
    pub reference_type: String, pub web_url: Option<String>,
}

pub struct TraceDiscussion {
    pub discussion_id: String, pub mr_iid: i64,
    pub author_username: String, pub body: String,
    pub path: String, pub created_at_iso: String,
}
```

run_trace() signature (src/core/trace.rs):
```rust
pub fn run_trace(
    conn: &Connection,
    project_id: Option<i64>,
    path: &str,
    follow_renames: bool,
    include_discussions: bool,
    limit: usize,
) -> Result<TraceResult>
```

parse_trace_path() (src/cli/commands/trace.rs, made pub by bd-1f5b):
```rust
pub fn parse_trace_path(input: &str) -> (String, Option<u32>)
```

## Approach

**Screen enum** (message.rs):
Add Screen::Trace variant (no parameters — path is entered on-screen). Label: "Trace". Breadcrumb: "Trace".

**Path autocomplete**: Query DISTINCT new_path from mr_file_changes (scoped to project_id if set) for fuzzy matching as user types. Cache results on first focus. SQL:
```sql
SELECT DISTINCT new_path FROM mr_file_changes
WHERE project_id = ?1 ORDER BY new_path
```
Store as Vec<String> in TraceState. Filter client-side with case-insensitive substring match.

**State** (state/trace.rs):
```rust
#[derive(Debug, Default)]
pub struct TraceState {
    pub path_input: String,
    pub path_focused: bool,
    pub line_filter: Option<u32>,        // from :line suffix
    pub result: Option<TraceResult>,
    pub selected_chain_index: usize,
    pub expanded_chains: HashSet<usize>,  // multiple can be expanded
    pub follow_renames: bool,            // default true
    pub include_discussions: bool,        // default true
    pub scroll_offset: u16,
    pub known_paths: Vec<String>,        // autocomplete cache
    pub autocomplete_matches: Vec<String>, // filtered suggestions
    pub autocomplete_index: usize,
}
```

**Action** (action.rs):
- fetch_trace(conn, project_id, path, follow_renames, include_discussions, limit) -> Result<TraceResult, LoreError>: calls run_trace() directly from src/core/trace.rs
- fetch_known_paths(conn, project_id) -> Result<Vec<String>, LoreError>: queries mr_file_changes for autocomplete

**View** (view/trace.rs):
- Top: path input with autocomplete dropdown + toggle indicators [renames: on] [discussions: on]
- If renames followed: rename chain breadcrumb (old_path -> ... -> new_path) in dimmed text
- Main area: scrollable list of TraceChain entries:
  - Collapsed: MR state icon + !iid + title + author + change_type + date (single line)
  - Expanded: indented sections for linked issues and discussion snippets
    - Issues: state icon + #iid + title + reference_type
    - Discussions: @author + date + body preview (first 2 lines, truncated at 120 chars)
- Keyboard:
  - j/k: scroll chains
  - Enter: toggle expand/collapse on selected chain
  - Enter on highlighted issue: navigate to IssueDetail(EntityKey)
  - Enter on highlighted MR line: navigate to MrDetail(EntityKey)
  - /: focus path input
  - Tab: cycle autocomplete suggestions when path focused
  - r: toggle follow_renames (re-fetches)
  - d: toggle include_discussions (re-fetches)
  - q: back

**Contextual entry points** (wired from other screens):
- MR Detail: when cursor is on a file path in the file changes list, t opens Trace pre-filled with that path
- Issue Detail: if discussion references a file path, t opens Trace for that path
- Requires MrDetailState and IssueDetailState to expose selected_file_path() -> Option<String>

## Acceptance Criteria
- [ ] Screen::Trace added to message.rs Screen enum with label "Trace" and breadcrumb
- [ ] TraceState struct with all fields, Default impl
- [ ] Path input with autocomplete dropdown from mr_file_changes (fuzzy substring match)
- [ ] :line suffix parsing via parse_trace_path (line_filter stored but used for future highlighting)
- [ ] Rename chain displayed as breadcrumb when renames_followed is true
- [ ] TraceChain list with expand/collapse — multiple chains expandable simultaneously
- [ ] MR state icons: merged (purple), opened (green), closed (red) — matching CLI theme
- [ ] Enter on issue row navigates to IssueDetail(EntityKey::issue(project_id, iid))
- [ ] Enter on MR header navigates to MrDetail(EntityKey::mr(project_id, iid))
- [ ] r toggles follow_renames, d toggles include_discussions — both trigger re-fetch
- [ ] Empty state: "No trace chains found" with hint "Run 'lore sync' to fetch MR file changes"
- [ ] Contextual navigation: t on file path in MR Detail opens Trace pre-filled
- [ ] Registered in command palette (label "Trace file", keywords ["trace", "provenance", "why"])
- [ ] AppState.has_text_focus() updated to include trace.path_focused
- [ ] AppState.blur_text_focus() updated to include trace.path_focused = false

## Files
- MODIFY: crates/lore-tui/src/message.rs (add Screen::Trace variant + label + is_detail_or_entity)
- CREATE: crates/lore-tui/src/state/trace.rs (TraceState struct + Default)
- MODIFY: crates/lore-tui/src/state/mod.rs (pub mod trace, pub use TraceState, add to AppState, update has_text_focus/blur_text_focus)
- MODIFY: crates/lore-tui/src/action.rs (add fetch_trace, fetch_known_paths)
- CREATE: crates/lore-tui/src/view/trace.rs (render_trace fn)
- MODIFY: crates/lore-tui/src/view/mod.rs (add Screen::Trace dispatch arm in render_screen)
- MODIFY: crates/lore-tui/src/view/mr_detail.rs (add t keybinding for contextual trace — deferred if mr_detail not yet implemented)

## TDD Anchor
RED: Write test_fetch_trace_returns_chain in action tests. Setup: in-memory DB, insert project, MR, mr_file_changes row (new_path="src/main.rs"), entity_reference linking MR to issue. Call fetch_trace(conn, Some(project_id), "src/main.rs", true, true, 50). Assert: result.trace_chains.len() == 1, result.trace_chains[0].issues.len() == 1.
GREEN: Implement fetch_trace calling run_trace from src/core/trace.rs.
VERIFY: cargo test -p lore-tui trace -- --nocapture

Additional tests:
- test_trace_empty_result: path "nonexistent.rs" returns total_chains=0
- test_trace_rename_chain: insert rename chain A->B->C, query A, assert resolved_paths contains all 3
- test_trace_discussion_toggle: include_discussions=false returns empty discussions vec per chain
- test_parse_trace_path_with_line: "src/main.rs:42" -> ("src/main.rs", Some(42))
- test_parse_trace_path_no_line: "src/main.rs" -> ("src/main.rs", None)
- test_autocomplete_filters_paths: known_paths=["src/a.rs","src/b.rs","lib/c.rs"], input="src/" -> matches=["src/a.rs","src/b.rs"]

## Edge Cases
- File path not in any MR: empty state with sync hint
- Very long rename chains (>5 paths): show first 2 + "... N more" + last path
- Hundreds of trace chains: limit default 50, show "showing 50 of N" footer
- Path with Windows drive letter (C:/foo.rs): parse_trace_path handles this correctly
- Autocomplete with thousands of paths: substring filter is O(n) but fast enough for <100k paths
- Project scope: if global_scope.project_id is set, pass it to run_trace and autocomplete query
- Contextual entry from MR Detail: if MR Detail screen not yet implemented, defer the t keybinding to a follow-up

## Dependency Context
- bd-1f5b (blocks): Makes parse_trace_path() pub in src/cli/commands/trace.rs. Without this, TUI must reimplement the parser.
- src/core/trace.rs: run_trace() is already pub — no changes needed. TUI calls it directly.
- src/core/file_history.rs: resolve_rename_chain() used transitively by run_trace — TUI does not call it directly.
- Navigation: uses NavigationStack.push(Screen::IssueDetail(key)) and Screen::MrDetail(key) from crates/lore-tui/src/navigation.rs.
- AppState composition: TraceState added as field in AppState struct (state/mod.rs line ~154-174). has_text_focus and blur_text_focus at lines 194-207 must include trace.path_focused.
- Contextual entry: requires MrDetailState to expose the currently selected file path. If MR Detail is not yet built, the contextual keybinding is deferred.

Trace screen complete: view/trace.rs + wiring. 586 TUI tests pass.


Add half-life fields and config validation to ScoringConfig

## Background
The flat-weight ScoringConfig (config.rs:155-167) has only 3 fields: author_weight (25), reviewer_weight (10), note_bonus (1). Time-decay scoring needs half-life parameters, a reviewer split (participated vs assigned-only), closed MR discount, substantive-note threshold, and bot filtering.

## Approach
Extend the existing ScoringConfig struct at config.rs:155. Add new fields with #[serde(default)] and camelCase rename to match existing convention (authorWeight, reviewerWeight, noteBonus). Extend the Default impl at config.rs:169 with new defaults. Extend validate_scoring() at config.rs:274-291 (currently validates 3 weights >= 0).

### New fields to add:
```rust
#[serde(rename = "reviewerAssignmentWeight")]
pub reviewer_assignment_weight: i64,     // default: 3
#[serde(rename = "authorHalfLifeDays")]
pub author_half_life_days: u32,          // default: 180
#[serde(rename = "reviewerHalfLifeDays")]
pub reviewer_half_life_days: u32,        // default: 90
#[serde(rename = "reviewerAssignmentHalfLifeDays")]
pub reviewer_assignment_half_life_days: u32, // default: 45
#[serde(rename = "noteHalfLifeDays")]
pub note_half_life_days: u32,            // default: 45
#[serde(rename = "closedMrMultiplier")]
pub closed_mr_multiplier: f64,           // default: 0.5
#[serde(rename = "reviewerMinNoteChars")]
pub reviewer_min_note_chars: u32,        // default: 20
#[serde(rename = "excludedUsernames")]
pub excluded_usernames: Vec<String>,     // default: vec![]
```

### Validation additions to validate_scoring() (config.rs:274):
- All *_half_life_days must be > 0 AND <= 3650
- All *_weight / *_bonus must be >= 0
- reviewer_assignment_weight must be >= 0
- closed_mr_multiplier must be finite (not NaN/Inf) AND in (0.0, 1.0]
- reviewer_min_note_chars must be >= 0 AND <= 4096
- excluded_usernames entries must be non-empty strings
- Return LoreError::ConfigInvalid with clear message on failure

## TDD Loop

### RED (write first):
```rust
#[test]
fn test_config_validation_rejects_zero_half_life() {
    let mut cfg = ScoringConfig::default();
    assert!(validate_scoring(&cfg).is_ok());
    cfg.author_half_life_days = 0;
    assert!(validate_scoring(&cfg).is_err());
    cfg.author_half_life_days = 180;
    cfg.reviewer_half_life_days = 0;
    assert!(validate_scoring(&cfg).is_err());
    cfg.reviewer_half_life_days = 90;
    cfg.closed_mr_multiplier = 0.0;
    assert!(validate_scoring(&cfg).is_err());
    cfg.closed_mr_multiplier = 1.5;
    assert!(validate_scoring(&cfg).is_err());
    cfg.closed_mr_multiplier = 1.0;
    assert!(validate_scoring(&cfg).is_ok());
}

#[test]
fn test_config_validation_rejects_absurd_half_life() {
    let mut cfg = ScoringConfig::default();
    cfg.author_half_life_days = 5000; // > 3650 cap
    assert!(validate_scoring(&cfg).is_err());
    cfg.author_half_life_days = 3650; // boundary: valid
    assert!(validate_scoring(&cfg).is_ok());
    cfg.reviewer_min_note_chars = 5000; // > 4096 cap
    assert!(validate_scoring(&cfg).is_err());
    cfg.reviewer_min_note_chars = 4096; // boundary: valid
    assert!(validate_scoring(&cfg).is_ok());
}

#[test]
fn test_config_validation_rejects_nan_multiplier() {
    let mut cfg = ScoringConfig::default();
    cfg.closed_mr_multiplier = f64::NAN;
    assert!(validate_scoring(&cfg).is_err());
    cfg.closed_mr_multiplier = f64::INFINITY;
    assert!(validate_scoring(&cfg).is_err());
    cfg.closed_mr_multiplier = f64::NEG_INFINITY;
    assert!(validate_scoring(&cfg).is_err());
}
```

### GREEN: Add fields to struct + Default impl + validation rules.
### VERIFY: cargo test -p lore -- test_config_validation

## Acceptance Criteria
- [ ] test_config_validation_rejects_zero_half_life passes
- [ ] test_config_validation_rejects_absurd_half_life passes
- [ ] test_config_validation_rejects_nan_multiplier passes
- [ ] ScoringConfig::default() returns correct values for all 11 fields
- [ ] cargo check --all-targets passes
- [ ] Existing config deserialization works (#[serde(default)] fills new fields)
- [ ] validate_scoring() is pub(crate) or accessible from config.rs test module

## Files
- MODIFY: src/core/config.rs (struct at line 155, Default impl at line 169, validate_scoring at line 274)

## Edge Cases
- f64 comparison: use .is_finite() for NaN/Inf check, > 0.0 and <= 1.0 for range
- Vec<String> default: use Vec::new()
- Upper bounds prevent silent misconfig (5000-day half-life effectively disables decay)

Completed: added 8 new fields to ScoringConfig, extended Default impl, and added validation for half-life bounds, closed_mr_multiplier, reviewer_min_note_chars, and excluded_usernames. All 19 config tests pass.


Ship timeline CLI with human and robot renderers

## Problem
The timeline pipeline (5-stage SEED->HYDRATE->EXPAND->COLLECT->RENDER) is implemented but not wired to the CLI. This is one of lore's most unique features — chronological narrative reconstruction from resource events, cross-references, and notes — and it is invisible to users and agents.

## Current State
- Types defined: src/core/timeline.rs (TimelineEvent, TimelineSeed, etc.)
- Seed stage: src/core/timeline_seed.rs (FTS search -> seed entities)
- Expand stage: src/core/timeline_expand.rs (cross-reference expansion)
- Collect stage: src/core/timeline_collect.rs (event gathering from resource events + notes)
- CLI command structure: src/cli/commands/timeline.rs (exists but incomplete)
- Remaining beads: bd-1nf (CLI wiring), bd-2f2 (human renderer), bd-dty (robot renderer)

## Acceptance Criteria
1. lore timeline 'authentication refactor' works end-to-end:
   - Searches for matching entities (SEED)
   - Fetches raw data (HYDRATE)
   - Expands via cross-references (EXPAND with --depth flag, default 1)
   - Collects events chronologically (COLLECT)
   - Renders human-readable narrative (RENDER)
2. Human renderer output:
   - Chronological event stream with timestamps
   - Color-coded by event type (state change, label change, note, reference)
   - Actor names with role context
   - Grouped by day/week for readability
   - Evidence snippets from notes (first 200 chars)
3. Robot renderer output (--robot / -J):
   - JSON array of events with: timestamp, event_type, actor, entity_ref, body/snippet, metadata
   - Seed entities listed separately (what matched the query)
   - Expansion depth metadata (how far from seed)
   - Total event count and time range
4. CLI flags:
   - --project (scope to project)
   - --since (time range)
   - --depth N (expansion depth, default 1, max 3)
   - --expand-mentions (follow mention references, not just closes/related)
   - -n LIMIT (max events)
5. Performance: timeline for a single issue with 50 events renders in <200ms

## Relationship to Existing Beads
This supersedes/unifies: bd-1nf (CLI wiring), bd-2f2 (human renderer), bd-dty (robot renderer). Those can be closed when this ships.

## Files to Modify
- src/cli/commands/timeline.rs (CLI wiring, flag parsing, output dispatch)
- src/core/timeline.rs (may need RENDER stage types)
- New: src/cli/render/timeline_human.rs or inline in timeline.rs
- New: src/cli/render/timeline_robot.rs or inline in timeline.rs

Already implemented: run_timeline(), print_timeline(), print_timeline_json_with_meta(), handle_timeline() all exist and are fully wired. Code audit 2026-02-12.


Implement Sync screen (running + summary modes + progress coalescer)

## Background
The Sync screen provides real-time progress visualization during data synchronization. The TUI drives sync directly via lore library calls (not subprocess) — this gives direct access to progress callbacks, proper error propagation, and cooperative cancellation via CancelToken. The TUI is the primary human interface; the CLI serves robots/scripts.

After sync completes, the screen transitions to a summary view showing exact changed entity counts. A progress coalescer prevents render thrashing by batching rapid progress updates.

Design principle: the TUI is self-contained. It does NOT detect or react to external CLI sync operations. If someone runs lore sync externally, the TUI's natural re-query on navigation handles stale data implicitly.

## Approach
Create state, action, and view modules for the Sync screen:

**State** (crates/lore-tui/src/screen/sync/state.rs):
- SyncScreenMode enum: FullScreen, Inline (for use from Bootstrap screen)
- SyncState enum: Idle, Running(SyncProgress), Complete(SyncSummary), Error(String)
- SyncProgress: per-lane progress (issues, MRs, discussions, notes, events, statuses) with counts and ETA
- SyncSummary: changed entity counts (new, updated, deleted per type), duration, errors
- ProgressCoalescer: buffers progress updates, emits at most every 100ms to prevent render thrash

**sync_delta_ledger** (crates/lore-tui/src/screen/sync/delta_ledger.rs):
- SyncDeltaLedger: in-memory per-run record of changed entity IDs
- Fields: new_issue_iids (Vec<i64>), updated_issue_iids (Vec<i64>), new_mr_iids (Vec<i64>), updated_mr_iids (Vec<i64>)
- record_change(entity_type, iid, change_kind) — called by sync progress callback
- summary() -> SyncSummary — produces the final counts for the summary view
- Purpose: after sync completes, the dashboard and list screens can use the ledger to highlight "new since last sync" items

**Action** (crates/lore-tui/src/screen/sync/action.rs):
- start_sync(db: &DbManager, config: &Config, cancel: CancelToken) -> Cmd<Msg>
- Calls lore library ingestion functions directly: ingest_issues, ingest_mrs, ingest_discussions, etc.
- Progress callback sends Msg::SyncProgress(lane, count, total) via channel
- On completion sends Msg::SyncComplete(SyncSummary)
- On cancel sends Msg::SyncCancelled(partial_summary)

**Per-project fault isolation:** If sync for one project fails, continue syncing other projects. Collect per-project errors and display in summary view. Don't abort entire sync on single project failure.

**View** (crates/lore-tui/src/screen/sync/view.rs):
- Running view: per-lane progress bars with counts/totals, overall ETA, cancel hint (Esc)
- Stream stats footer: show items/sec throughput for active lanes
- Summary view: table of entity types with new/updated/deleted columns, total duration, per-project error list
- Error view: error message with retry option
- Inline mode: compact single-line progress for embedding in Bootstrap screen

The Sync screen uses TaskSupervisor for the background sync task with cooperative cancellation.

## Acceptance Criteria
- [ ] Sync screen launches sync via lore library calls (NOT subprocess)
- [ ] Per-lane progress bars update in real-time during sync
- [ ] ProgressCoalescer batches updates to at most 10/second (100ms floor)
- [ ] Esc cancels sync cooperatively via CancelToken, shows partial summary
- [ ] Sync completion transitions to summary view with accurate change counts
- [ ] Summary view shows new/updated/deleted counts per entity type
- [ ] Error during sync shows error message with retry option
- [ ] Sync task registered with TaskSupervisor (dedup by TaskKey::Sync)
- [ ] Per-project fault isolation: single project failure doesn't abort entire sync
- [ ] SyncDeltaLedger records changed entity IDs for post-sync highlighting
- [ ] Stream stats footer shows items/sec throughput
- [ ] ScreenMode::Inline renders compact single-line progress for Bootstrap embedding
- [ ] Unit tests for ProgressCoalescer batching behavior
- [ ] Unit tests for SyncDeltaLedger record/summary
- [ ] Integration test: mock sync with FakeClock verifies progress -> summary transition

## Files
- CREATE: crates/lore-tui/src/screen/sync/state.rs
- CREATE: crates/lore-tui/src/screen/sync/action.rs
- CREATE: crates/lore-tui/src/screen/sync/view.rs
- CREATE: crates/lore-tui/src/screen/sync/delta_ledger.rs
- CREATE: crates/lore-tui/src/screen/sync/mod.rs
- MODIFY: crates/lore-tui/src/screen/mod.rs (add pub mod sync)

## TDD Anchor
RED: Write test_progress_coalescer_batches_rapid_updates that sends 50 progress updates in 10ms and asserts coalescer emits at most 1.
GREEN: Implement ProgressCoalescer with configurable floor interval.
VERIFY: cargo test -p lore-tui sync -- --nocapture

Additional tests:
- test_sync_cancel_produces_partial_summary
- test_sync_complete_produces_full_summary
- test_sync_error_shows_retry
- test_sync_dedup_prevents_double_launch
- test_delta_ledger_records_changes: record 5 new issues and 3 updated MRs, assert summary counts
- test_per_project_fault_isolation: simulate one project failure, verify others complete

## Edge Cases
- Sync cancelled immediately after start — partial summary with zero counts is valid
- Network timeout during sync — error state with last-known progress preserved
- Very large sync (100k+ entities) — progress coalescer prevents render thrash
- Sync started while another sync TaskKey::Sync exists — TaskSupervisor dedup rejects it
- Inline mode from Bootstrap: compact rendering, no full progress bars

## Dependency Context
Uses TaskSupervisor from bd-3le2 for dedup and cancellation. Uses DbManager from bd-2kop for database access. Uses lore library ingestion module directly for sync operations. Used by Bootstrap screen (bd-3ty8) in inline mode.

Completed in previous session: Sync screen view + all 9 message handlers wired.


Add work item status via GraphQL enrichment

## Summary

GitLab 18.2+ has native work item status (To do, In progress, Done, Won't do, Duplicate) available ONLY via GraphQL, not REST. This enriches synced issues with status information by making supplementary GraphQL calls after REST ingestion.

**Plan document:** plans/work-item-status-graphql.md

## Critical Findings (from API research)

- **EE-only (Premium/Ultimate)** — Free tier won't have the widget at all
- **GraphQL auth differs from REST** — must use `Authorization: Bearer <token>`, NOT `PRIVATE-TOKEN`
- **Must use `workItems` resolver, NOT `project.issues`** — legacy issues path doesn't expose status widgets
- **5 categories:** TRIAGE, TO_DO, IN_PROGRESS, DONE, CANCELED (not 3 as originally assumed)
- **Max 100 items per GraphQL page** (standard GitLab limit)
- **Custom statuses possible on 18.5+** — can't assume only system-defined statuses

## Migration

Uses migration **021** (001-020 already exist on disk).
Adds `status_name TEXT` and `status_category TEXT` to `issues` table (both nullable).

## Files

- src/gitlab/graphql.rs (NEW — minimal GraphQL client + status fetcher)
- src/gitlab/mod.rs (add pub mod graphql)
- src/gitlab/types.rs (WorkItemStatus, WorkItemStatusCategory enum)
- src/core/db.rs (migration 021 in MIGRATIONS array)
- src/core/config.rs (fetch_work_item_status toggle in SyncConfig)
- src/ingestion/orchestrator.rs (enrichment step after issue sync)
- src/cli/commands/show.rs (display status)
- src/cli/commands/list.rs (status in list output + --status filter)

## Acceptance Criteria

- [ ] GraphQL client POSTs queries with Bearer auth and handles errors
- [ ] Status fetched via workItems resolver with pagination
- [ ] Migration 021 adds status_name and status_category to issues
- [ ] lore show issue displays status (when available)
- [ ] lore --robot show issue includes status in JSON
- [ ] lore list issues --status filter works
- [ ] Graceful degradation: Free tier, old GitLab, disabled GraphQL all handled
- [ ] Config toggle: fetch_work_item_status (default true)
- [ ] cargo check + clippy + tests pass

Already implemented: GraphQL status enrichment shipped in v0.8.x — migration 021, graphql.rs, --status filter, --no-status flag all complete


Implement user flow integration tests (9 PRD flows)

## Background

The PRD Section 6 defines 9 end-to-end user flows that exercise cross-screen navigation, state preservation, and data flow. The existing vertical slice test (bd-1mju) covers one flow (Dashboard -> Issue List -> Issue Detail -> Sync). These integration tests cover the remaining 8 flows plus re-test the vertical slice from a user-journey perspective. Each test simulates a realistic keystroke sequence using FrankenTUI's test harness and verifies that the correct screens are reached with the correct data visible.

## Approach

Create a test module `tests/tui_user_flows.rs` with 9 test functions, each simulating a keystroke sequence against a FrankenTUI `TestHarness` with a pre-populated test database. Tests use `FakeClock` for deterministic timestamps.

**Test database fixture**: A shared setup function creates an in-memory SQLite DB with ~20 issues, ~10 MRs, ~30 discussions, a few experts, and timeline events. This fixture is reused across all flow tests.

**Flow tests**:

1. **`test_flow_find_expert`** — Dashboard -> `w` -> type "src/auth/" -> verify Expert mode results appear -> `↓` select first person -> `Enter` -> verify navigation to Issue List filtered by that person
2. **`test_flow_timeline_query`** — Dashboard -> `t` -> type "auth timeout" -> `Enter` -> verify Timeline shows seed events -> `Enter` on first event -> verify entity detail opens -> `Esc` -> back on Timeline
3. **`test_flow_quick_search`** — Any screen -> `/` -> type query -> verify results appear -> `Tab` (switch mode) -> verify mode label changes -> `Enter` -> verify entity detail opens
4. **`test_flow_sync_and_browse`** — Dashboard -> `s` -> `Enter` (start sync) -> wait for completion -> verify Summary shows deltas -> `i` -> verify Issue List filtered to new items
5. **`test_flow_review_workload`** — Dashboard -> `w` -> `Tab` (Workload mode) -> type "@bjones" -> verify workload sections appear (assigned, authored, reviewing)
6. **`test_flow_command_palette`** — Any screen -> `Ctrl+P` -> type "mrs draft" -> verify fuzzy match -> `Enter` -> verify MR List opened with draft filter
7. **`test_flow_morning_triage`** — Dashboard -> `i` -> verify Issue List (opened, sorted by updated) -> `Enter` on first -> verify Issue Detail -> `Esc` -> verify cursor preserved on same row -> `j` -> verify cursor moved
8. **`test_flow_direct_screen_jumps`** — Issue Detail -> `gt` -> verify Timeline -> `gw` -> verify Who -> `gi` -> verify Issue List -> `H` -> verify Dashboard (clean reset)
9. **`test_flow_risk_sweep`** — Dashboard -> scroll to Insights -> `Enter` on first insight -> verify pre-filtered Issue List

Each test follows the pattern:
```rust
#[test]
fn test_flow_X() {
    let (harness, app) = setup_test_harness_with_fixture();
    // Send keystrokes
    harness.send_key(Key::Char('w'));
    // Assert screen state
    assert_eq!(app.current_screen(), Screen::Who);
    // Assert visible content
    let frame = harness.render();
    assert!(frame.contains("Expert"));
}
```

## Acceptance Criteria
- [ ] All 9 flow tests exist and compile
- [ ] Each test uses the shared DB fixture (no per-test DB setup)
- [ ] Each test verifies screen transitions via `current_screen()` assertions
- [ ] Each test verifies at least one content assertion (rendered text contains expected data)
- [ ] test_flow_morning_triage verifies cursor preservation after Enter/Esc round-trip
- [ ] test_flow_direct_screen_jumps verifies the g-prefix navigation chain
- [ ] test_flow_sync_and_browse verifies delta-filtered navigation after sync
- [ ] All tests use FakeClock for deterministic timestamps
- [ ] Tests complete in <5 seconds each (no real I/O)

## Files
- CREATE: crates/lore-tui/tests/tui_user_flows.rs
- MODIFY: (none — this is a new test file only)

## TDD Anchor
RED: Write `test_flow_morning_triage` first — it exercises the most common daily workflow (Dashboard -> Issue List -> Issue Detail -> back with cursor preservation). Start with just the Dashboard -> Issue List transition.
GREEN: Requires all Phase 2 core screens to be working; the test itself is the GREEN verification.
VERIFY: cargo test -p lore-tui test_flow_morning_triage

Additional tests: All 9 flows listed above.

## Edge Cases
- Flow tests must handle async data loading — use harness.tick() or harness.wait_for_idle() to let async tasks complete before asserting
- g-prefix timeout (500ms) — tests must send the second key within the timeout; use harness clock control
- Sync flow test needs a mock sync that completes quickly — use a pre-populated SyncDeltaLedger rather than running actual sync

## Dependency Context
- Depends on bd-1mju (vertical slice integration test) which establishes the test harness patterns and fixture setup.
- Depends on bd-2nfs (snapshot test infrastructure) which provides the FakeClock and TestHarness setup.
- Depends on all Phase 2 core screen beads (bd-35g5 Dashboard, bd-3ei1 Issue List, bd-8ab7 Issue Detail, bd-2kr0 MR List, bd-3t1b MR Detail) being implemented.
- Depends on Phase 3 power feature beads (bd-1zow Search, bd-29qw Timeline, bd-u7se Who, bd-wzqi Command Palette) being implemented.
- Depends on bd-2x2h (Sync screen) for the sync+browse flow test.


Fetch MR diffs API and populate mr_file_changes

## Background

This bead fetches MR diff metadata from the GitLab API and populates the mr_file_changes table created by migration 016. It extracts only file-level metadata (paths, change type) and discards actual diff content.

**Spec reference:** `docs/phase-b-temporal-intelligence.md` Section 4.3 (Ingestion).

## Codebase Context

- pending_dependent_fetches already has `job_type='mr_diffs'` in CHECK constraint (migration 011)
- dependent_queue.rs has: enqueue_job(), claim_jobs(), complete_job(), fail_job() with exponential backoff
- Orchestrator pattern: enqueue after entity ingestion, drain after primary ingestion completes
- GitLab client uses fetch_all_pages() for pagination
- Existing drain patterns in orchestrator.rs: drain_resource_events() and drain_mr_closes_issues() — follow same pattern
- config.sync.fetch_mr_file_changes flag guards enqueue (see bd-jec)
- mr_file_changes table created by migration 016 (bd-1oo) — NOT 015 (015 is commit SHAs)
- merge_commit_sha and squash_commit_sha already captured during MR ingestion (src/ingestion/merge_requests.rs lines 184, 205-206, 230-231) — no work needed for those fields

## Approach

### 1. API Client — add to `src/gitlab/client.rs`:

```rust
pub async fn fetch_mr_diffs(
    &self,
    project_id: i64,
    mr_iid: i64,
) -> Result<Vec<GitLabMrDiff>> {
    let path = format\!("/projects/{project_id}/merge_requests/{mr_iid}/diffs");
    self.fetch_all_pages(&path, &[("per_page", "100")]).await
        .or_else(|e| coalesce_not_found(e, Vec::new()))
}
```

### 2. Types — add to `src/gitlab/types.rs`:

```rust
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct GitLabMrDiff {
    pub old_path: String,
    pub new_path: String,
    pub new_file: bool,
    pub renamed_file: bool,
    pub deleted_file: bool,
    // Ignore: diff, a_mode, b_mode, generated_file (not stored)
}
```

Add `GitLabMrDiff` to `src/gitlab/mod.rs` re-exports.

### 3. Change Type Derivation (in new file):

```rust
fn derive_change_type(diff: &GitLabMrDiff) -> &'static str {
    if diff.new_file { "added" }
    else if diff.renamed_file { "renamed" }
    else if diff.deleted_file { "deleted" }
    else { "modified" }
}
```

### 4. DB Storage — new `src/ingestion/mr_diffs.rs`:

```rust
pub fn upsert_mr_file_changes(
    conn: &Connection,
    mr_local_id: i64,
    project_id: i64,
    diffs: &[GitLabMrDiff],
) -> Result<usize> {
    // DELETE FROM mr_file_changes WHERE merge_request_id = ?
    // INSERT each diff row with derived change_type
    // DELETE+INSERT is simpler than UPSERT for array replacement
}
```

Add `pub mod mr_diffs;` to `src/ingestion/mod.rs`.

### 5. Queue Integration — in orchestrator.rs:

```rust
// After MR upsert, if config.sync.fetch_mr_file_changes:
enqueue_job(conn, project_id, "merge_request", mr_iid, mr_local_id, "mr_diffs")?;
```

Add `drain_mr_diffs()` following the drain_mr_closes_issues() pattern. Call it after drain_mr_closes_issues() in the sync pipeline.

## Acceptance Criteria

- [ ] `fetch_mr_diffs()` calls GET /projects/:id/merge_requests/:iid/diffs with pagination
- [ ] GitLabMrDiff type added to src/gitlab/types.rs and re-exported from src/gitlab/mod.rs
- [ ] Change type derived: new_file->added, renamed_file->renamed, deleted_file->deleted, else->modified
- [ ] mr_file_changes rows have correct old_path, new_path, change_type
- [ ] Old rows deleted before insert (clean replacement per MR)
- [ ] Jobs only enqueued when config.sync.fetch_mr_file_changes is true
- [ ] 404/403 API errors handled gracefully (empty result, not failure)
- [ ] drain_mr_diffs() added to orchestrator.rs sync pipeline
- [ ] `pub mod mr_diffs;` added to src/ingestion/mod.rs
- [ ] `cargo check --all-targets` passes
- [ ] `cargo clippy --all-targets -- -D warnings` passes

## Files

- `src/gitlab/client.rs` (add fetch_mr_diffs method)
- `src/gitlab/types.rs` (add GitLabMrDiff struct)
- `src/gitlab/mod.rs` (re-export GitLabMrDiff)
- `src/ingestion/mr_diffs.rs` (NEW — upsert_mr_file_changes + derive_change_type)
- `src/ingestion/mod.rs` (add pub mod mr_diffs)
- `src/ingestion/orchestrator.rs` (enqueue mr_diffs jobs + drain_mr_diffs)

## TDD Loop

RED:
- `test_derive_change_type_added` - new_file=true -> "added"
- `test_derive_change_type_renamed` - renamed_file=true -> "renamed"
- `test_derive_change_type_deleted` - deleted_file=true -> "deleted"
- `test_derive_change_type_modified` - all false -> "modified"
- `test_upsert_replaces_existing` - second upsert replaces first

GREEN: Implement API client, type derivation, DB ops, orchestrator wiring.

VERIFY: `cargo test --lib -- mr_diffs`

## Edge Cases

- MR with 500+ files: paginate properly via fetch_all_pages
- Binary files: handled as modified (renamed_file/new_file/deleted_file all false)
- File renamed AND modified: renamed_file=true takes precedence
- Draft MRs: still fetch diffs
- Deleted MR: 404 -> empty vec via coalesce_not_found()
- merge_commit_sha/squash_commit_sha: already handled in merge_requests.rs ingestion — NOT part of this bead

Implemented: GitLabMrDiff type, fetch_mr_diffs client method, upsert_mr_file_changes in new mr_diffs.rs module, enqueue_mr_diffs_jobs + drain_mr_diffs in orchestrator, migration 020 for diffs_synced_for_updated_at watermark, progress events, autocorrect registry. All 390 tests pass, clippy clean.


[CP1] Issue transformer with label extraction

Transform GitLab issue payloads to normalized database schema.

Functions to implement:
- transformIssue(gitlabIssue, localProjectId) → NormalizedIssue
- extractLabels(gitlabIssue, localProjectId) → Label[]

Transformation rules:
- Convert ISO timestamps to ms epoch using isoToMs()
- Set last_seen_at to nowMs()
- Handle labels vs labels_details (prefer details when available)
- Handle missing optional fields gracefully

Files: src/gitlab/transformers/issue.ts
Tests: tests/unit/issue-transformer.test.ts
Done when: Unit tests pass for payload transformation and label extraction


[CP1] Cargo.toml updates - async-stream and futures

## Background

The GitLab client pagination methods require async streaming capabilities. The `async-stream` crate provides the `stream!` macro for creating async iterators, and `futures` provides `StreamExt` for consuming them with `.next()` and other combinators.

## Approach

Add these dependencies to Cargo.toml:

```toml
[dependencies]
async-stream = "0.3"
futures = { version = "0.3", default-features = false, features = ["alloc"] }
```

Use minimal features on `futures` to avoid pulling unnecessary code.

## Acceptance Criteria

- [ ] `async-stream = "0.3"` is in Cargo.toml [dependencies]
- [ ] `futures` with `alloc` feature is in Cargo.toml [dependencies]
- [ ] `cargo check` succeeds after adding dependencies

## Files

- Cargo.toml (edit)

## TDD Loop

RED: Not applicable (dependency addition)
GREEN: Add lines to Cargo.toml
VERIFY: `cargo check`

## Edge Cases

- If `futures` is already present, merge features rather than duplicate
- Use exact version pins for reproducibility

Added async-stream 0.3 and futures 0.3 (alloc feature) to Cargo.toml, cargo check passes


Add timestamp-aware test helpers

## Background
Existing test helpers (who.rs:2469-2598) use now_ms() for all timestamps. Time-decay tests need precise timestamp control to verify decay math, state-aware timestamps, and as-of filtering.

## Approach
Add three new helpers in the test module (who.rs after insert_file_change at line 2598), patterned after existing helpers:

### insert_mr_at() — variant of insert_mr (who.rs:2469-2493):
```rust
#[allow(clippy::too_many_arguments)]
fn insert_mr_at(
    conn: &Connection,
    id: i64,
    project_id: i64,
    iid: i64,
    author: &str,
    state: &str,
    updated_at_ms: i64,
    merged_at_ms: Option<i64>,
    closed_at_ms: Option<i64>,
) {
    conn.execute(
        "INSERT INTO merge_requests (id, gitlab_id, project_id, iid, title, author_username, state, last_seen_at, updated_at, merged_at, closed_at)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
        rusqlite::params![id, id * 10, project_id, iid, format!("MR {iid}"), author, state, now_ms(), updated_at_ms, merged_at_ms, closed_at_ms],
    ).unwrap();
}
```

### insert_diffnote_at() — variant of insert_diffnote (who.rs:2541-2580):
```rust
#[allow(clippy::too_many_arguments)]
fn insert_diffnote_at(
    conn: &Connection,
    id: i64,
    discussion_id: i64,
    project_id: i64,
    author: &str,
    new_path: &str,
    old_path: Option<&str>,
    body: &str,
    created_at_ms: i64,
) {
    conn.execute(
        "INSERT INTO notes (id, gitlab_id, project_id, discussion_id, author_username, note_type, is_system, position_new_path, position_old_path, body, created_at, updated_at)
         VALUES (?1, ?2, ?3, ?4, ?5, 'DiffNote', 0, ?6, ?7, ?8, ?9, ?9)",
        rusqlite::params![id, id * 10, project_id, discussion_id, author, new_path, old_path, body, created_at_ms],
    ).unwrap();
}
```

### insert_file_change_with_old_path() — variant of insert_file_change (who.rs:2585-2598):
```rust
fn insert_file_change_with_old_path(
    conn: &Connection,
    mr_id: i64,
    project_id: i64,
    new_path: &str,
    old_path: Option<&str>,
    change_type: &str,
) {
    conn.execute(
        "INSERT INTO mr_file_changes (merge_request_id, project_id, new_path, old_path, change_type)
         VALUES (?1, ?2, ?3, ?4, ?5)",
        rusqlite::params![mr_id, project_id, new_path, old_path, change_type],
    ).unwrap();
}
```

Note: mr_file_changes already has an old_path column (from migration 016). The existing insert_file_change helper simply omits it (defaults to NULL).

## Acceptance Criteria
- [ ] insert_mr_at compiles and inserts with explicit updated_at, merged_at, closed_at
- [ ] insert_diffnote_at compiles and inserts with explicit old_path and created_at
- [ ] insert_file_change_with_old_path compiles and inserts with explicit old_path
- [ ] Existing helpers (insert_mr, insert_diffnote, insert_file_change) unchanged
- [ ] cargo check --all-targets passes
- [ ] All three helpers are used by downstream beads (bd-13q8, bd-1h3f)

## Files
- MODIFY: src/cli/commands/who.rs (test module, after insert_file_change at line ~2598)

## TDD Loop
N/A — these are test utilities. Verified indirectly by tests in bd-13q8 and bd-1h3f.
VERIFY: cargo check --all-targets (compiles cleanly)

## Edge Cases
- merged_at_ms/closed_at_ms as Option<i64> — NULL when not applicable
- old_path as Option<&str> — NULL when no rename occurred
- created_at_ms used for both created_at and updated_at on notes (matching existing insert_diffnote pattern)
- #[allow(clippy::too_many_arguments)] needed on helpers with 8+ params (project uses pedantic clippy)

Dependencies:
  -> bd-2w1p (blocks) - Add half-life fields and config validation to ScoringConfig

Implemented by time-decay swarm: 3 agents, 12 tasks, 621 tests passing, all quality gates green


Epic: Gate 1 - Resource Events Ingestion

## Background
Gate 1 transforms gitlore from a snapshot engine into a temporal data store by ingesting structured event data from GitLab Resource Events APIs (state, label, milestone changes). This is the foundation — Gates 2-5 all depend on the event tables and dependent fetch queue that Gate 1 establishes.

Currently, when an issue is closed or a label changes, gitlore overwrites the current state. The transition is lost. Gate 1 captures these transitions as discrete events with timestamps, actors, and provenance, enabling temporal queries like "when did this issue become critical?" and "who closed this MR?"

## Architecture
- **Three new tables:** resource_state_events, resource_label_events, resource_milestone_events (migration 011, already shipped as bd-hu3)
- **Generic dependent fetch queue:** pending_dependent_fetches table replaces per-type queue tables. Supports job_types: resource_events, mr_closes_issues, mr_diffs. Used by Gates 1, 2, and 4.
- **Opt-in via config:** sync.fetchResourceEvents (default true). --no-events CLI flag to skip.
- **Incremental:** Only changed entities enqueued. --full re-enqueues all.
- **Crash recovery:** locked_at column with 5-minute stale lock reclaim.

## Children (Execution Order)
1. **bd-hu3** [CLOSED] — Migration 011: event tables + entity_references + dependent fetch queue
2. **bd-2e8** [CLOSED] — fetchResourceEvents config flag
3. **bd-2fm** [CLOSED] — GitLab Resource Event serde types
4. **bd-sqw** [CLOSED] — Resource Events API endpoints in GitLab client
5. **bd-1uc** [CLOSED] — DB upsert functions for resource events
6. **bd-tir** [CLOSED] — Generic dependent fetch queue (enqueue + drain)
7. **bd-1ep** [CLOSED] — Wire resource event fetching into sync pipeline
8. **bd-3sh** [CLOSED] — lore count events command
9. **bd-1m8** [CLOSED] — lore stats --check for event integrity + queue health

## Gate Completion Criteria
- [ ] All 9 children closed
- [ ] `lore sync` fetches resource events for changed entities
- [ ] `lore sync --no-events` skips event fetching
- [ ] Event fetch failures queued for retry with exponential backoff
- [ ] Stale locks auto-reclaimed on next sync run
- [ ] `lore count events` shows counts by type (state/label/milestone)
- [ ] `lore stats --check` validates referential integrity + queue health
- [ ] Robot mode JSON for all new commands
- [ ] Integration test: full sync cycle with events enabled

## Dependencies
- None (Gate 1 is the foundation)
- Downstream: Gate 2 (bd-1se) depends on event tables and dependent fetch queue

Already implemented: migration 011 exists, events_db.rs has upsert functions, client.rs has fetch_*_state_events, orchestrator.rs has drain_resource_events. Full Gate 1 functionality is live.


[CP1] GitLab client pagination methods

Add async stream methods for paginated GitLab API calls.

## Methods to Add to GitLabClient

### paginate_issues(gitlab_project_id, updated_after, cursor_rewind_seconds) -> Stream<GitLabIssue>
- Use async_stream::try_stream! macro
- Query params: scope=all, state=all, order_by=updated_at, sort=asc, per_page=100
- If updated_after provided, apply cursor_rewind_seconds (subtract from timestamp)
- Clamp to 0 to avoid underflow: (ts - rewind_ms).max(0)
- Follow x-next-page header until empty/absent
- Fall back to empty-page detection if headers missing

### paginate_issue_discussions(gitlab_project_id, issue_iid) -> Stream<GitLabDiscussion>
- Paginate through discussions for single issue
- per_page=100
- Follow x-next-page header

### request_with_headers<T>(path, params) -> Result<(T, HeaderMap)>
- Acquire rate limiter
- Make request with PRIVATE-TOKEN header
- Return both deserialized data and response headers

## Dependencies
- async-stream = "0.3" (for try_stream! macro)
- futures = "0.3" (for Stream trait and StreamExt)

Files: src/gitlab/client.rs
Tests: tests/pagination_tests.rs
Done when: Pagination handles multiple pages and respects cursors, tests pass


[CP1] Discussion ingestion module

Fetch and store discussions/notes for each issue.

Implement ingestIssueDiscussions(options) → { discussionsFetched, discussionsUpserted, notesUpserted, systemNotesCount }

Logic:
1. Paginate through all discussions for given issue
2. For each discussion:
   - Store raw payload (compressed)
   - Upsert discussion record with correct issue FK
   - Transform and upsert all notes
   - Store raw payload per note
   - Track system notes count

Files: src/ingestion/discussions.ts
Tests: tests/integration/issue-discussion-ingestion.test.ts
Done when: Discussions and notes populated with correct FKs and is_system flags


Epic: CP2 Gate B - Labels + Assignees + Reviewers

## Background
Gate B validates junction tables for labels, assignees, and reviewers. Ensures relationships are tracked correctly and stale links are removed on resync. This is critical for filtering (`--reviewer=alice`) and display.

## Acceptance Criteria (Pass/Fail)
- [ ] `mr_labels` table has rows for MRs with labels
- [ ] Label count per MR matches GitLab UI (spot check 3 MRs)
- [ ] `mr_assignees` table has rows for MRs with assignees
- [ ] Assignee usernames match GitLab UI (spot check 3 MRs)
- [ ] `mr_reviewers` table has rows for MRs with reviewers
- [ ] Reviewer usernames match GitLab UI (spot check 3 MRs)
- [ ] Remove label in GitLab -> resync -> link removed from mr_labels
- [ ] Add reviewer in GitLab -> resync -> link added to mr_reviewers
- [ ] `gi list mrs --label=bugfix` filters correctly
- [ ] `gi list mrs --reviewer=alice` filters correctly

## Validation Script
```bash
#!/bin/bash
set -e

DB_PATH="${XDG_DATA_HOME:-$HOME/.local/share}/gitlab-inbox/db.sqlite3"

echo "=== Gate B: Labels + Assignees + Reviewers ==="

# 1. Check label linkage exists
echo "Step 1: Check label linkage..."
LABEL_LINKS=$(sqlite3 "$DB_PATH" "SELECT COUNT(*) FROM mr_labels;")
echo "  Total label links: $LABEL_LINKS"

# 2. Show sample label linkage
echo "Step 2: Sample label linkage..."
sqlite3 "$DB_PATH" "
  SELECT m.iid, GROUP_CONCAT(l.name, ', ') as labels
  FROM merge_requests m
  JOIN mr_labels ml ON ml.merge_request_id = m.id
  JOIN labels l ON l.id = ml.label_id
  GROUP BY m.id
  LIMIT 5;
"

# 3. Check assignee linkage
echo "Step 3: Check assignee linkage..."
ASSIGNEE_LINKS=$(sqlite3 "$DB_PATH" "SELECT COUNT(*) FROM mr_assignees;")
echo "  Total assignee links: $ASSIGNEE_LINKS"

# 4. Show sample assignee linkage
echo "Step 4: Sample assignee linkage..."
sqlite3 "$DB_PATH" "
  SELECT m.iid, GROUP_CONCAT(a.username, ', ') as assignees
  FROM merge_requests m
  JOIN mr_assignees a ON a.merge_request_id = m.id
  GROUP BY m.id
  LIMIT 5;
"

# 5. Check reviewer linkage
echo "Step 5: Check reviewer linkage..."
REVIEWER_LINKS=$(sqlite3 "$DB_PATH" "SELECT COUNT(*) FROM mr_reviewers;")
echo "  Total reviewer links: $REVIEWER_LINKS"

# 6. Show sample reviewer linkage
echo "Step 6: Sample reviewer linkage..."
sqlite3 "$DB_PATH" "
  SELECT m.iid, GROUP_CONCAT(r.username, ', ') as reviewers
  FROM merge_requests m
  JOIN mr_reviewers r ON r.merge_request_id = m.id
  GROUP BY m.id
  LIMIT 5;
"

# 7. Test filter commands
echo "Step 7: Test filter commands..."
# Get a label that exists
LABEL=$(sqlite3 "$DB_PATH" "SELECT name FROM labels LIMIT 1;")
if [ -n "$LABEL" ]; then
  echo "  Testing --label=$LABEL"
  gi list mrs --label="$LABEL" --limit=3
fi

# Get a reviewer that exists
REVIEWER=$(sqlite3 "$DB_PATH" "SELECT username FROM mr_reviewers LIMIT 1;")
if [ -n "$REVIEWER" ]; then
  echo "  Testing --reviewer=$REVIEWER"
  gi list mrs --reviewer="$REVIEWER" --limit=3
fi

echo ""
echo "=== Gate B: PASSED ==="
```

## Stale Link Removal Test (Manual)
```bash
# 1. Pick an MR with labels in GitLab UI
MR_IID=123

# 2. Note current label count
sqlite3 "$DB_PATH" "
  SELECT COUNT(*) FROM mr_labels ml
  JOIN merge_requests m ON m.id = ml.merge_request_id
  WHERE m.iid = $MR_IID;
"
# Example: 3 labels

# 3. Remove a label in GitLab UI (manually)

# 4. Resync
gi ingest --type=merge_requests

# 5. Verify label removed
sqlite3 "$DB_PATH" "
  SELECT COUNT(*) FROM mr_labels ml
  JOIN merge_requests m ON m.id = ml.merge_request_id
  WHERE m.iid = $MR_IID;
"
# Should be: 2 labels (one less)
```

## Test Commands (Quick Verification)
```bash
# Check counts:
sqlite3 ~/.local/share/gitlab-inbox/db.sqlite3 "
  SELECT
    (SELECT COUNT(*) FROM mr_labels) as label_links,
    (SELECT COUNT(*) FROM mr_assignees) as assignee_links,
    (SELECT COUNT(*) FROM mr_reviewers) as reviewer_links;
"

# Test filtering:
gi list mrs --label=enhancement --limit=5
gi list mrs --reviewer=alice --limit=5
gi list mrs --assignee=bob --limit=5
```

## Dependencies
This gate requires:
- bd-ser (MR ingestion with label/assignee/reviewer linking via clear-and-relink pattern)
- Gate A must pass first

## Edge Cases
- MRs with no labels/assignees/reviewers: junction tables should have no rows for that MR
- Labels shared across issues and MRs: labels table is shared, only junction differs
- Usernames are case-sensitive: `Alice` != `alice`


[CP1] Test fixtures for mocked GitLab responses

Create mock response files for integration tests.

Fixtures to create:
- gitlab-issue.json (single issue with labels)
- gitlab-issues-page.json (paginated list)
- gitlab-discussion.json (single discussion with notes)
- gitlab-discussions-page.json (paginated list)

Include edge cases:
- Issue with labels_details
- Issue with no labels
- Discussion with individual_note=true
- System notes with system=true

Files: tests/fixtures/mock-responses/gitlab-issue*.json, gitlab-discussion*.json
Done when: MSW handlers can use fixtures for deterministic tests


[CP0] Project scaffold

## Background

This is the foundational scaffold for the GitLab Inbox CLI tool. Every subsequent bead depends on having the correct project structure, TypeScript configuration, and tooling in place. The configuration choices here (ESM modules, strict TypeScript, Vitest for testing) set constraints for all future code.

## Approach

Create a Node.js 20+ ESM project with TypeScript strict mode. Use flat ESLint config (v9+) with TypeScript plugin. Configure Vitest with coverage. Create the directory structure matching the PRD exactly.

**package.json essentials:**
- `"type": "module"` for ESM
- `"bin": { "gi": "./dist/cli/index.js" }` for CLI entry point
- Runtime deps: better-sqlite3, sqlite-vec, commander, zod, pino, pino-pretty, ora, chalk, cli-table3, inquirer
- Dev deps: typescript, @types/better-sqlite3, @types/node, vitest, msw, eslint, @typescript-eslint/*

**tsconfig.json:**
- `target: ES2022`, `module: Node16`, `moduleResolution: Node16`
- `strict: true`, `noImplicitAny: true`, `strictNullChecks: true`
- `outDir: ./dist`, `rootDir: ./src`

**vitest.config.ts:**
- Exclude `tests/live/**` unless `GITLAB_LIVE_TESTS=1`
- Coverage with v8 provider

## Acceptance Criteria

- [ ] `npm install` completes without errors
- [ ] `npm run build` compiles TypeScript to dist/
- [ ] `npm run test` runs vitest (0 tests is fine at this stage)
- [ ] `npm run lint` runs ESLint with no config errors
- [ ] All directories exist: src/cli/commands/, src/core/, src/gitlab/, src/types/, tests/unit/, tests/integration/, tests/live/, tests/fixtures/mock-responses/, migrations/

## Files

CREATE:
- package.json
- tsconfig.json
- vitest.config.ts
- eslint.config.js
- .gitignore
- src/cli/index.ts (empty placeholder with shebang)
- src/cli/commands/.gitkeep
- src/core/.gitkeep
- src/gitlab/.gitkeep
- src/types/index.ts (empty)
- tests/unit/.gitkeep
- tests/integration/.gitkeep
- tests/live/.gitkeep
- tests/fixtures/mock-responses/.gitkeep
- migrations/.gitkeep

## TDD Loop

N/A - scaffold only. Verify with:

```bash
npm install
npm run build
npm run lint
npm run test
```

## Edge Cases

- Node.js version < 20 will fail on ESM features - add `engines` field
- better-sqlite3 requires native compilation - may need python/build-essential
- sqlite-vec installation can fail on some platforms - document fallback


OBSERV: Implement log retention cleanup at startup

## Background
Log files accumulate at ~1-10 MB/day. Without cleanup, they grow unbounded. Retention runs BEFORE subscriber init so deleted file handles aren't held open by the appender.

## Approach
Add a cleanup function, called from main.rs before the subscriber is initialized (before current line 44):

```rust
/// Delete log files older than retention_days.
/// Matches files named lore.YYYY-MM-DD.log in the log directory.
pub fn cleanup_old_logs(log_dir: &Path, retention_days: u32) -> std::io::Result<usize> {
    if retention_days == 0 {
        return Ok(0); // 0 means file logging disabled, don't delete
    }
    let cutoff = SystemTime::now() - Duration::from_secs(u64::from(retention_days) * 86400);
    let mut deleted = 0;

    for entry in std::fs::read_dir(log_dir)? {
        let entry = entry?;
        let name = entry.file_name();
        let name_str = name.to_string_lossy();

        // Only match lore.YYYY-MM-DD.log pattern
        if !name_str.starts_with("lore.") || !name_str.ends_with(".log") {
            continue;
        }

        if let Ok(metadata) = entry.metadata() {
            if let Ok(modified) = metadata.modified() {
                if modified < cutoff {
                    std::fs::remove_file(entry.path())?;
                    deleted += 1;
                }
            }
        }
    }
    Ok(deleted)
}
```

Place this function in src/core/paths.rs (next to get_log_dir) or a new src/core/log_retention.rs. Prefer paths.rs since it's small and related.

Call from main.rs:
```rust
let log_dir = get_log_dir(config.logging.log_dir.as_deref());
let _ = cleanup_old_logs(&log_dir, config.logging.retention_days);
// THEN init subscriber
```

Note: Config must be loaded before cleanup runs. Current main.rs parses Cli at line 60, but config loading happens inside command handlers. This means we need to either:
  A) Load config early in main() before subscriber init (preferred)
  B) Defer cleanup to after config load

Since the subscriber must also know log_dir, approach A is natural: load config -> cleanup -> init subscriber -> dispatch command.

## Acceptance Criteria
- [ ] Files matching lore.*.log older than retention_days are deleted
- [ ] Files matching lore.*.log within retention_days are preserved
- [ ] Non-matching files (e.g., other.txt) are never deleted
- [ ] retention_days=0 skips cleanup entirely (no files deleted)
- [ ] Errors on individual files don't prevent cleanup of remaining files
- [ ] cargo clippy --all-targets -- -D warnings passes

## Files
- src/core/paths.rs (add cleanup_old_logs function)
- src/main.rs (call cleanup before subscriber init)

## TDD Loop
RED:
  - test_log_retention_cleanup: create tempdir with lore.2026-01-01.log through lore.2026-02-04.log, run with retention_days=7, assert old deleted, recent preserved
  - test_log_retention_ignores_non_log_files: create other.txt alongside old log files, assert other.txt untouched
  - test_log_retention_zero_days: retention_days=0, assert nothing deleted
GREEN: Implement cleanup_old_logs
VERIFY: cargo test && cargo clippy --all-targets -- -D warnings

## Edge Cases
- SystemTime::now() precision varies by OS; use file modified time, not name parsing (simpler and more reliable)
- read_dir on non-existent directory: get_log_dir creates it first, so this shouldn't happen. But handle gracefully.
- Permissions error on individual file: log a warning, continue with remaining files (don't propagate)
- Race condition: another process creates a file during cleanup. Not a concern -- we only delete old files.

Implemented cleanup_old_logs() with date-pattern matching and retention_days config, runs at startup before subscriber init


Implement timeline seed phase: FTS5 keyword search to entity IDs

## Background

The seed phase is steps 1-2 of the timeline pipeline (spec Section 3.2): SEED + HYDRATE. It converts a keyword query into entity IDs via FTS5 search and collects evidence note candidates.

**Spec reference:** `docs/phase-b-temporal-intelligence.md` Section 3.2 steps 1-2.

## Codebase Context

- FTS5 index exists: documents_fts table (migration 008)
- documents table: id, source_type ('issue'|'merge_request'|'discussion'), source_id, project_id, created_at, content
- discussions table: id, issue_id, merge_request_id
- notes table: discussion_id, author_username, body, created_at, is_system, id (note_id)
- Safe FTS query builder: src/search/fts.rs has to_fts_query(raw, FtsQueryMode::Safe) for sanitizing user input
- projects table: path_with_namespace
- issues/merge_requests: iid, project_id

## Approach

Create `src/core/timeline_seed.rs`:

```rust
use crate::core::timeline::{EntityRef, TimelineEvent, TimelineEventType};
use rusqlite::Connection;

pub struct SeedResult {
    pub seed_entities: Vec<EntityRef>,
    pub evidence_notes: Vec<TimelineEvent>,  // NoteEvidence events
}

pub fn seed_timeline(
    conn: &Connection,
    query: &str,
    project_id: Option<i64>,
    since_ms: Option<i64>,
    max_seeds: usize,           // default 50
) -> Result<SeedResult> { ... }
```

### SQL for SEED + HYDRATE (entity discovery):
```sql
SELECT DISTINCT d.source_type, d.source_id, d.project_id,
       CASE d.source_type
         WHEN 'issue' THEN (SELECT iid FROM issues WHERE id = d.source_id)
         WHEN 'merge_request' THEN (SELECT iid FROM merge_requests WHERE id = d.source_id)
         WHEN 'discussion' THEN NULL  -- discussions map to parent entity below
       END AS iid,
       CASE d.source_type
         WHEN 'issue' THEN (SELECT p.path_with_namespace FROM projects p JOIN issues i ON i.project_id = p.id WHERE i.id = d.source_id)
         WHEN 'merge_request' THEN (SELECT p.path_with_namespace FROM projects p JOIN merge_requests m ON m.project_id = p.id WHERE m.id = d.source_id)
         WHEN 'discussion' THEN NULL
       END AS project_path
FROM documents_fts fts
JOIN documents d ON d.id = fts.rowid
WHERE documents_fts MATCH ?1
  AND (?2 IS NULL OR d.project_id = ?2)
ORDER BY rank
LIMIT ?3
```

For 'discussion' source_type: resolve to parent entity via discussions.issue_id or discussions.merge_request_id.

### SQL for evidence notes (top 10 FTS5-matched notes):
```sql
SELECT n.id as note_id, n.body, n.created_at, n.author_username,
       disc.id as discussion_id,
       CASE WHEN disc.issue_id IS NOT NULL THEN 'issue' ELSE 'merge_request' END as parent_type,
       COALESCE(disc.issue_id, disc.merge_request_id) AS parent_entity_id
FROM documents_fts fts
JOIN documents d ON d.id = fts.rowid
JOIN discussions disc ON disc.id = d.source_id AND d.source_type = 'discussion'
JOIN notes n ON n.discussion_id = disc.id AND n.is_system = 0
WHERE documents_fts MATCH ?1
ORDER BY rank
LIMIT 10
```

Evidence notes become TimelineEvent with:
- event_type: NoteEvidence { note_id, snippet (first 200 chars), discussion_id }
- Use to_fts_query(query, FtsQueryMode::Safe) to sanitize user input before MATCH

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

## Acceptance Criteria

- [ ] seed_timeline() returns entities from FTS5 search
- [ ] Entities deduplicated (same entity from multiple docs appears once)
- [ ] Discussion documents resolved to parent entity (issue or MR)
- [ ] Evidence notes capped at 10
- [ ] Evidence note snippets truncated to 200 chars (safe UTF-8 boundary)
- [ ] Uses to_fts_query(query, FtsQueryMode::Safe) for input sanitization
- [ ] --since filter works
- [ ] -p filter works
- [ ] Empty result for zero-match queries (not error)
- [ ] Module registered in src/core/mod.rs
- [ ] `cargo check --all-targets` passes
- [ ] `cargo clippy --all-targets -- -D warnings` passes

## Files

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

## TDD Loop

RED:
- `test_seed_deduplicates_entities`
- `test_seed_resolves_discussion_to_parent`
- `test_seed_empty_query_returns_empty`
- `test_seed_evidence_capped_at_10`
- `test_seed_evidence_snippet_truncated`
- `test_seed_respects_since_filter`

Tests need in-memory DB with migrations 001-014 + documents/FTS test data.

GREEN: Implement FTS5 queries and deduplication.

VERIFY: `cargo test --lib -- timeline_seed`

## Edge Cases

- FTS5 MATCH invalid syntax: to_fts_query(query, FtsQueryMode::Safe) sanitizes
- Discussion orphans: LEFT JOIN handles deleted notes
- UTF-8 truncation: use char_indices() to find safe 200-char boundary
- Discussion source resolving to both issue_id and merge_request_id: prefer issue_id (shouldn't happen but be defensive)

Completed: Created src/core/timeline_seed.rs with seed_timeline() function. FTS5 search to entity IDs with discussion-to-parent resolution, entity deduplication, evidence note extraction (capped, snippet-truncated). 12 tests pass. All quality gates pass.


Implement Ollama API client

## Background
The Ollama API client provides the HTTP interface to the local Ollama embedding server. It handles health checks (is Ollama running? does the model exist?), batch embedding requests (up to 32 texts per call), and error translation to LoreError variants. This is the lowest-level embedding component — the pipeline (bd-am7) builds on top of it.

## Approach
Create \`src/embedding/ollama.rs\` per PRD Section 4.2. **Uses async reqwest (not blocking).**

```rust
use reqwest::Client;  // NOTE: async Client, not reqwest::blocking
use serde::{Deserialize, Serialize};
use crate::core::error::{LoreError, Result};

pub struct OllamaConfig {
    pub base_url: String,      // default \"http://localhost:11434\"
    pub model: String,         // default \"nomic-embed-text\"
    pub timeout_secs: u64,     // default 60
}

impl Default for OllamaConfig { /* PRD defaults */ }

pub struct OllamaClient {
    client: Client,      // async reqwest::Client
    config: OllamaConfig,
}

#[derive(Serialize)]
struct EmbedRequest { model: String, input: Vec<String> }

#[derive(Deserialize)]
struct EmbedResponse { model: String, embeddings: Vec<Vec<f32>> }

#[derive(Deserialize)]
struct TagsResponse { models: Vec<ModelInfo> }

#[derive(Deserialize)]
struct ModelInfo { name: String }

impl OllamaClient {
    pub fn new(config: OllamaConfig) -> Self;

    /// Async health check: GET /api/tags
    /// Model matched via starts_with (\"nomic-embed-text\" matches \"nomic-embed-text:latest\")
    pub async fn health_check(&self) -> Result<()>;

    /// Async batch embedding: POST /api/embed
    /// Input: Vec<String> of texts, Response: Vec<Vec<f32>> of 768-dim embeddings
    pub async fn embed_batch(&self, texts: Vec<String>) -> Result<Vec<Vec<f32>>>;
}

/// Quick health check without full client (async).
pub async fn check_ollama_health(base_url: &str) -> bool;
```

**Error mapping (per PRD):**
- Connection refused/timeout -> LoreError::OllamaUnavailable { base_url, source: Some(e) }
- Model not in /api/tags -> LoreError::OllamaModelNotFound { model }
- Non-200 from /api/embed -> LoreError::EmbeddingFailed { document_id: 0, reason: format!(\"HTTP {}: {}\", status, body) }

**Key PRD detail:** Model matching uses \`starts_with\` (not exact match) so \"nomic-embed-text\" matches \"nomic-embed-text:latest\".

## Acceptance Criteria
- [ ] Uses async reqwest::Client (not blocking)
- [ ] health_check() is async, detects server availability and model presence
- [ ] Model matched via starts_with (handles \":latest\" suffix)
- [ ] embed_batch() is async, sends POST /api/embed
- [ ] Batch size up to 32 texts
- [ ] Returns Vec<Vec<f32>> with 768 dimensions each
- [ ] OllamaUnavailable error includes base_url and source error
- [ ] OllamaModelNotFound error includes model name
- [ ] Non-200 response mapped to EmbeddingFailed with status + body
- [ ] Timeout: 60 seconds default (configurable via OllamaConfig)
- [ ] \`cargo build\` succeeds

## Files
- \`src/embedding/ollama.rs\` — new file
- \`src/embedding/mod.rs\` — add \`pub mod ollama;\` and re-exports

## TDD Loop
RED: Tests (unit tests with mock, integration needs Ollama):
- \`test_config_defaults\` — verify default base_url, model, timeout
- \`test_health_check_model_starts_with\` — \"nomic-embed-text\" matches \"nomic-embed-text:latest\"
- \`test_embed_batch_parse\` — mock response parsed correctly
- \`test_connection_error_maps_to_ollama_unavailable\`
GREEN: Implement OllamaClient
VERIFY: \`cargo test ollama\`

## Edge Cases
- Ollama returns model name with version tag (\"nomic-embed-text:latest\"): starts_with handles this
- Empty texts array: send empty batch, Ollama returns empty embeddings
- Ollama returns wrong number of embeddings (2 texts, 1 embedding): caller (pipeline) validates
- Non-JSON response: reqwest deserialization error -> wrap appropriately

Completed: OllamaClient with async health_check (starts_with model matching), embed_batch, error mapping to LoreError variants, check_ollama_health helper, 4 tests pass


Fetch and store GitLab linked issues (Related to)

## Background

GitLab's "Linked items" provides bidirectional issue linking distinct from "closes" and "mentioned" references. This data is only available via the issue links API (GET /projects/:id/issues/:iid/links). The goal is to fetch these links during sync and store them as entity_references so they appear in `lore show issue` and are queryable.

**Why:** Currently `lore show issue` displays closing MRs (via `get_closing_mrs()` in show.rs:~line 1544) but has NO related issues section. This bead adds that capability.

## Codebase Context

- **entity_references table** (migration 011): reference_type CHECK: 'closes' | 'mentioned' | 'related'; source_method CHECK: 'api' | 'note_parse' | 'description_parse'
- **pending_dependent_fetches** (migration 011): job_type CHECK: 'resource_events' | 'mr_closes_issues' | 'mr_diffs'. No later migrations modified this table.
- **CRITICAL:** Adding 'issue_links' to job_type CHECK requires recreating pending_dependent_fetches table (SQLite can't ALTER CHECK constraints). Migration **027** must copy data, drop, recreate with expanded CHECK, and reinsert.
- **Orchestrator** (src/ingestion/orchestrator.rs, 1745 lines): Three drain functions exist — drain_resource_events() (line 932), drain_mr_closes_issues() (line 1254), drain_mr_diffs() (line 1514). Follow the same claim/complete/fail pattern from dependent_queue.rs.
- **dependent_queue.rs**: enqueue_job(), claim_jobs(), complete_job(), fail_job() with exponential backoff
- **show.rs** (1544 lines): Has get_closing_mrs() for closing MR display. NO related_issues section exists yet.
- **GitLab API**: GET /projects/:id/issues/:iid/links returns link_type: "relates_to", "blocks", "is_blocked_by"
- **Migration count**: 26 migrations exist (001-026). Next migration = **027**.

## Approach

### Phase 1: API Client (src/gitlab/client.rs)
```rust
pub async fn fetch_issue_links(
    &self,
    project_id: i64,
    issue_iid: i64,
) -> Result<Vec<GitLabIssueLink>> {
    // GET /projects/:id/issues/:iid/links
    // Use fetch_all_pages() + coalesce_not_found()
}
```

### Phase 2: Types (src/gitlab/types.rs)
```rust
#[derive(Debug, Deserialize)]
pub struct GitLabIssueLink {
    pub id: i64,
    pub iid: i64,
    pub title: String,
    pub state: String,
    pub web_url: String,
    pub link_type: String,      // "relates_to", "blocks", "is_blocked_by"
    pub link_created_at: Option<String>,
}
```

### Phase 3: Migration 027 (migrations/027_issue_links_job_type.sql)
Recreate pending_dependent_fetches with expanded CHECK:
```sql
CREATE TABLE pending_dependent_fetches_new (
    id INTEGER PRIMARY KEY,
    project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
    entity_type TEXT NOT NULL CHECK (entity_type IN ('issue', 'merge_request')),
    entity_iid INTEGER NOT NULL,
    entity_local_id INTEGER NOT NULL,
    job_type TEXT NOT NULL CHECK (job_type IN (
        'resource_events', 'mr_closes_issues', 'mr_diffs', 'issue_links'
    )),
    payload_json TEXT,
    enqueued_at INTEGER NOT NULL,
    attempts INTEGER NOT NULL DEFAULT 0,
    last_error TEXT,
    next_retry_at INTEGER,
    locked_at INTEGER,
    UNIQUE(project_id, entity_type, entity_iid, job_type)
);
INSERT INTO pending_dependent_fetches_new SELECT * FROM pending_dependent_fetches;
DROP TABLE pending_dependent_fetches;
ALTER TABLE pending_dependent_fetches_new RENAME TO pending_dependent_fetches;
-- Recreate indexes from migration 011 (idx_pdf_job_type, idx_pdf_next_retry)
```

Register in MIGRATIONS array in src/core/db.rs (entry 27).

### Phase 4: Ingestion (src/ingestion/issue_links.rs NEW)
```rust
pub async fn fetch_and_store_issue_links(
    conn: &Connection,
    client: &GitLabClient,
    project_id: i64,
    issue_local_id: i64,
    issue_iid: i64,
) -> Result<usize> {
    // 1. Fetch links from API
    // 2. Resolve target issue to local DB id (SELECT id FROM issues WHERE project_id=? AND iid=?)
    // 3. Insert into entity_references: reference_type='related', source_method='api'
    // 4. Create bidirectional refs: A->B and B->A
    // 5. Skip self-links
    // 6. Cross-project: store with target_entity_id=NULL (unresolved)
}
```

### Phase 5: Queue Integration (src/ingestion/orchestrator.rs)
- Enqueue 'issue_links' job after issue ingestion (near the existing resource_events enqueue)
- Add drain_issue_links() following drain_mr_closes_issues() pattern (lines 1254-1512)
- Config gate: add `sync.fetchIssueLinks` (default true) to config, like existing `sync.fetchResourceEvents`

### Phase 6: Display (src/cli/commands/show.rs)
In `lore show issue 123`, add "Related Issues" section after closing MRs.
Pattern: query entity_references WHERE source_entity_type='issue' AND source_entity_id=<local_id> AND reference_type='related'.

## Acceptance Criteria

- [ ] API client fetches issue links with pagination (fetch_all_pages + coalesce_not_found)
- [ ] Stored as entity_reference: reference_type='related', source_method='api'
- [ ] Bidirectional: A links B creates both A->B and B->A references
- [ ] link_type captured (relates_to, blocks, is_blocked_by) — stored as 'related' for now
- [ ] Cross-project links stored as unresolved (target_entity_id NULL)
- [ ] Self-links skipped
- [ ] Migration **027** recreates pending_dependent_fetches with 'issue_links' in CHECK
- [ ] Migration registered in MIGRATIONS array in src/core/db.rs
- [ ] `lore show issue 123` shows related issues section
- [ ] `lore --robot show issue 123` includes related_issues in JSON
- [ ] Config gate: sync.fetchIssueLinks (default true, camelCase serde rename)
- [ ] `cargo check --all-targets` passes
- [ ] `cargo clippy --all-targets -- -D warnings` passes
- [ ] `cargo fmt --check` passes

## Files

- MODIFY: src/gitlab/client.rs (add fetch_issue_links)
- MODIFY: src/gitlab/types.rs (add GitLabIssueLink)
- CREATE: src/ingestion/issue_links.rs
- MODIFY: src/ingestion/mod.rs (add pub mod issue_links)
- MODIFY: src/ingestion/orchestrator.rs (enqueue + drain_issue_links)
- CREATE: migrations/027_issue_links_job_type.sql
- MODIFY: src/core/db.rs (add migration 027 to MIGRATIONS array)
- MODIFY: src/core/config.rs (add sync.fetchIssueLinks)
- MODIFY: src/cli/commands/show.rs (display related issues)

## TDD Anchor

RED:
- test_issue_link_deserialization (types.rs: deserialize GitLabIssueLink from JSON)
- test_store_issue_links_creates_bidirectional_references (in-memory DB, insert 2 issues, store link, verify 2 rows in entity_references)
- test_self_link_skipped (same issue_iid both sides, verify 0 rows)
- test_cross_project_link_unresolved (target not in DB, verify target_entity_id IS NULL)

GREEN: Implement API client, ingestion, migration, display.

VERIFY: cargo test --lib -- issue_links

## Edge Cases

- Cross-project links: target not in local DB -> unresolved reference (target_entity_id NULL)
- Self-links: skip entirely
- UNIQUE constraint on entity_references prevents duplicate refs on re-sync
- "blocks"/"is_blocked_by" semantics not modeled in entity_references yet — store as 'related'
- Table recreation migration: safe because pending_dependent_fetches is transient queue data that gets re-enqueued on next sync
- Recreated table must restore indexes: idx_pdf_job_type, idx_pdf_next_retry (check migration 011 for exact definitions)

## Dependency Context

- **entity_references** (migration 011): provides the target table. reference_type='related' already in CHECK.
- **dependent_queue.rs**: provides enqueue_job/claim_jobs/complete_job/fail_job lifecycle used by drain_issue_links()
- **orchestrator drain pattern**: drain_mr_closes_issues() (line 1254) is the closest template — fetch API data, insert entity_references, complete job


OBSERV: Implement MetricsLayer custom tracing subscriber layer

## Background
MetricsLayer is a custom tracing subscriber layer that records span timing and structured fields, then materializes them into Vec<StageTiming>. This avoids threading a mutable collector through every function signature -- spans are the single source of truth.

## Approach
Add to src/core/metrics.rs (same file as StageTiming):

```rust
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::Instant;
use tracing::span::{Attributes, Id, Record};
use tracing::Subscriber;
use tracing_subscriber::layer::{Context, Layer};
use tracing_subscriber::registry::LookupSpan;

#[derive(Debug)]
struct SpanData {
    name: String,
    parent_id: Option<Id>,
    start: Instant,
    fields: HashMap<String, serde_json::Value>,
}

#[derive(Debug, Clone)]
pub struct MetricsLayer {
    spans: Arc<Mutex<HashMap<u64, SpanData>>>,
    completed: Arc<Mutex<Vec<(u64, StageTiming)>>>,
}

impl MetricsLayer {
    pub fn new() -> Self {
        Self {
            spans: Arc::new(Mutex::new(HashMap::new())),
            completed: Arc::new(Mutex::new(Vec::new())),
        }
    }

    /// Extract timing tree for a completed run.
    /// Call this after the root span closes.
    pub fn extract_timings(&self) -> Vec<StageTiming> {
        let completed = self.completed.lock().unwrap();
        // Build tree: find root entries (no parent), attach children
        // ... tree construction logic
    }
}

impl<S> Layer<S> for MetricsLayer
where
    S: Subscriber + for<'a> LookupSpan<'a>,
{
    fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, ctx: Context<'_, S>) {
        let parent_id = ctx.span(id).and_then(|s| s.parent().map(|p| p.id()));
        let mut fields = HashMap::new();
        // Visit attrs to capture initial field values
        let mut visitor = FieldVisitor(&mut fields);
        attrs.record(&mut visitor);

        self.spans.lock().unwrap().insert(id.into_u64(), SpanData {
            name: attrs.metadata().name().to_string(),
            parent_id,
            start: Instant::now(),
            fields,
        });
    }

    fn on_record(&self, id: &Id, values: &Record<'_>, _ctx: Context<'_, S>) {
        // Capture recorded fields (items_processed, items_skipped, errors)
        if let Some(data) = self.spans.lock().unwrap().get_mut(&id.into_u64()) {
            let mut visitor = FieldVisitor(&mut data.fields);
            values.record(&mut visitor);
        }
    }

    fn on_close(&self, id: Id, _ctx: Context<'_, S>) {
        if let Some(data) = self.spans.lock().unwrap().remove(&id.into_u64()) {
            let elapsed = data.start.elapsed();
            let timing = StageTiming {
                name: data.name,
                project: data.fields.get("project").and_then(|v| v.as_str()).map(String::from),
                elapsed_ms: elapsed.as_millis() as u64,
                items_processed: data.fields.get("items_processed").and_then(|v| v.as_u64()).unwrap_or(0) as usize,
                items_skipped: data.fields.get("items_skipped").and_then(|v| v.as_u64()).unwrap_or(0) as usize,
                errors: data.fields.get("errors").and_then(|v| v.as_u64()).unwrap_or(0) as usize,
                sub_stages: vec![], // Will be populated during extract_timings tree construction
            };
            self.completed.lock().unwrap().push((id.into_u64(), timing));
        }
    }
}
```

Need a FieldVisitor struct implementing tracing::field::Visit to capture field values.

Register in subscriber stack (src/main.rs), alongside stderr and file layers:
```rust
let metrics_layer = MetricsLayer::new();
let metrics_handle = metrics_layer.clone(); // Clone Arc for later extraction

registry()
    .with(stderr_layer.with_filter(stderr_filter))
    .with(file_layer.with_filter(file_filter))
    .with(metrics_layer) // No filter -- captures all spans
    .init();
```

Pass metrics_handle to command handlers so they can call extract_timings() after the pipeline completes.

## Acceptance Criteria
- [ ] MetricsLayer captures span enter/close timing
- [ ] on_record captures items_processed, items_skipped, errors fields
- [ ] extract_timings() returns correctly nested Vec<StageTiming> tree
- [ ] Parallel spans (multiple projects) both appear as sub_stages of parent
- [ ] Thread-safe: Arc<Mutex<>> allows concurrent span operations
- [ ] cargo clippy --all-targets -- -D warnings passes

## Files
- src/core/metrics.rs (add MetricsLayer, FieldVisitor, tree construction)
- src/main.rs (register MetricsLayer in subscriber stack)

## TDD Loop
RED:
  - test_metrics_layer_single_span: enter/exit one span, extract, assert one StageTiming
  - test_metrics_layer_nested_spans: parent + child, assert child in parent.sub_stages
  - test_metrics_layer_parallel_spans: two sibling spans, assert both in parent.sub_stages
  - test_metrics_layer_field_recording: record items_processed=42, assert captured
GREEN: Implement MetricsLayer with on_new_span, on_record, on_close, extract_timings
VERIFY: cargo test && cargo clippy --all-targets -- -D warnings

## Edge Cases
- Span ID reuse: tracing may reuse span IDs after close. Using remove on close prevents stale data.
- Lock contention: Mutex per operation. For high-span-count scenarios, consider parking_lot::Mutex. But lore's span count is low (<100 per run), so std::sync::Mutex is fine.
- extract_timings tree construction: iterate completed Vec, build parent->children map, then recursively construct StageTiming tree. Root entries have parent_id matching the root span or None.
- MetricsLayer has no filter: it sees ALL spans. To avoid noise from dependency spans, check if span name starts with known stage names, or rely on the "stage" field being present.

Implemented MetricsLayer custom tracing subscriber layer with span timing capture, rate-limit/retry event detection, tree extraction, and 12 unit tests


Implement MR transformer

## Background
Transforms GitLab MR API responses into normalized schema for database storage. Handles deprecated field fallbacks and extracts metadata (labels, assignees, reviewers).

## Approach
Create new transformer module following existing issue transformer pattern:
- `NormalizedMergeRequest` - Database-ready struct
- `MergeRequestWithMetadata` - MR + extracted labels/assignees/reviewers
- `transform_merge_request()` - Main transformation function
- `extract_labels()` - Label extraction helper

## Files
- `src/gitlab/transformers/merge_request.rs` - New transformer module
- `src/gitlab/transformers/mod.rs` - Export new module
- `tests/mr_transformer_tests.rs` - Unit tests

## Acceptance Criteria
- [ ] `NormalizedMergeRequest` struct exists with all DB columns
- [ ] `MergeRequestWithMetadata` contains MR + label_names + assignee_usernames + reviewer_usernames
- [ ] `transform_merge_request()` returns `Result<MergeRequestWithMetadata, String>`
- [ ] `draft` computed as `gitlab_mr.draft || gitlab_mr.work_in_progress`
- [ ] `detailed_merge_status` prefers `detailed_merge_status` over `merge_status_legacy`
- [ ] `merge_user_username` prefers `merge_user` over `merged_by`
- [ ] `head_sha` extracted from `sha` field
- [ ] `references_short` and `references_full` extracted from `references` Option
- [ ] Timestamps parsed with `iso_to_ms()`, errors returned (not zeroed)
- [ ] `last_seen_at` set to `now_ms()`
- [ ] `cargo test mr_transformer` passes

## TDD Loop
RED: `cargo test mr_transformer` -> module not found
GREEN: Add transformer with all fields
VERIFY: `cargo test mr_transformer`

## Struct Definitions
```rust
#[derive(Debug, Clone)]
pub struct NormalizedMergeRequest {
    pub gitlab_id: i64,
    pub project_id: i64,
    pub iid: i64,
    pub title: String,
    pub description: Option<String>,
    pub state: String,
    pub draft: bool,
    pub author_username: String,
    pub source_branch: String,
    pub target_branch: String,
    pub head_sha: Option<String>,
    pub references_short: Option<String>,
    pub references_full: Option<String>,
    pub detailed_merge_status: Option<String>,
    pub merge_user_username: Option<String>,
    pub created_at: i64,
    pub updated_at: i64,
    pub merged_at: Option<i64>,
    pub closed_at: Option<i64>,
    pub last_seen_at: i64,
    pub web_url: String,
}

#[derive(Debug, Clone)]
pub struct MergeRequestWithMetadata {
    pub merge_request: NormalizedMergeRequest,
    pub label_names: Vec<String>,
    pub assignee_usernames: Vec<String>,
    pub reviewer_usernames: Vec<String>,
}
```

## Function Signature
```rust
pub fn transform_merge_request(
    gitlab_mr: &GitLabMergeRequest,
    local_project_id: i64,
) -> Result<MergeRequestWithMetadata, String>
```

## Key Logic
```rust
// Draft: prefer draft, fallback to work_in_progress
let is_draft = gitlab_mr.draft || gitlab_mr.work_in_progress;

// Merge status: prefer detailed_merge_status
let detailed_merge_status = gitlab_mr.detailed_merge_status
    .clone()
    .or_else(|| gitlab_mr.merge_status_legacy.clone());

// Merge user: prefer merge_user
let merge_user_username = gitlab_mr.merge_user
    .as_ref()
    .map(|u| u.username.clone())
    .or_else(|| gitlab_mr.merged_by.as_ref().map(|u| u.username.clone()));

// References extraction
let (references_short, references_full) = gitlab_mr.references
    .as_ref()
    .map(|r| (Some(r.short.clone()), Some(r.full.clone())))
    .unwrap_or((None, None));

// Head SHA
let head_sha = gitlab_mr.sha.clone();
```

## Edge Cases
- Invalid timestamps should return `Err`, not zero values
- Empty labels/assignees/reviewers should return empty Vecs, not None
- `state` must pass through as-is (including "locked")


WHO: Migration 017 — composite indexes for query paths

## Background

With 280K notes, the path/timestamp queries for lore who will degrade without composite indexes. Existing indexes cover note_type and position_new_path separately (migration 006) but not as composites aligned to the who query patterns. This is a non-breaking, additive-only migration.

## Approach

Add as entry 17 (index 16) in the MIGRATIONS array in src/core/db.rs. LATEST_SCHEMA_VERSION auto-updates via MIGRATIONS.len() as i32.

### Exact SQL for the migration entry:

```sql
-- Migration 017: Composite indexes for who query paths

-- Expert/Overlap: DiffNote path prefix + timestamp filter.
-- Leading with position_new_path (not note_type) because the partial index
-- predicate already handles the constant filter.
CREATE INDEX IF NOT EXISTS idx_notes_diffnote_path_created
    ON notes(position_new_path, created_at, project_id)
    WHERE note_type = 'DiffNote' AND is_system = 0;

-- Active/Workload: discussion participation lookups.
CREATE INDEX IF NOT EXISTS idx_notes_discussion_author
    ON notes(discussion_id, author_username)
    WHERE is_system = 0;

-- Active (project-scoped): unresolved discussions by recency.
CREATE INDEX IF NOT EXISTS idx_discussions_unresolved_recent
    ON discussions(project_id, last_note_at)
    WHERE resolvable = 1 AND resolved = 0;

-- Active (global): unresolved discussions by recency (no project scope).
-- Without this, (project_id, last_note_at) can't satisfy ORDER BY last_note_at DESC
-- efficiently when project_id is unconstrained.
CREATE INDEX IF NOT EXISTS idx_discussions_unresolved_recent_global
    ON discussions(last_note_at)
    WHERE resolvable = 1 AND resolved = 0;

-- Workload: issue assignees by username.
CREATE INDEX IF NOT EXISTS idx_issue_assignees_username
    ON issue_assignees(username, issue_id);
```

### Not added (already adequate):
- merge_requests(author_username) — idx_mrs_author (migration 006)
- mr_reviewers(username) — idx_mr_reviewers_username (migration 006)
- notes(discussion_id) — idx_notes_discussion (migration 002)

## Files

- `src/core/db.rs` — append to MIGRATIONS array as entry index 16

## TDD Loop

RED: `cargo test -- test_migration` (existing migration tests should still pass)
GREEN: Add the migration SQL string to the array
VERIFY: `cargo test && cargo check --all-targets`

## Acceptance Criteria

- [ ] MIGRATIONS array has 17 entries (index 0-16)
- [ ] LATEST_SCHEMA_VERSION is 17
- [ ] cargo test passes (in-memory DB runs all migrations including 017)
- [ ] No existing index names conflict

## Edge Cases

- The SQL uses CREATE INDEX IF NOT EXISTS — safe for idempotent reruns
- Partial indexes (WHERE clause) keep index size small: ~33K of 280K notes for DiffNote index

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


Implement Dashboard state + action + view

## Background
The Dashboard is the home screen — first thing users see. It shows entity counts, per-project sync status, recent activity, and a last-sync summary. Data comes from aggregation queries against the local SQLite database.

## Approach
State (state/dashboard.rs):
- DashboardState: counts (EntityCounts), projects (Vec<ProjectSyncInfo>), recent (Vec<RecentActivityItem>), last_sync (LastSyncInfo)
- EntityCounts: issues_open, issues_total, mrs_open, mrs_total, discussions, notes_total, notes_system_pct, documents, embeddings
- ProjectSyncInfo: path (String), minutes_since_sync (u64)
- RecentActivityItem: entity_type, iid, title, state, minutes_ago
- update(data: DashboardData) method

Action (action.rs):
- fetch_dashboard(conn: &Connection, clock: &dyn Clock) -> Result<DashboardData, LoreError>: runs aggregation queries for counts, recent activity, project sync status. Uses clock.now() for relative time calculations.

View (view/dashboard.rs):
- render_dashboard(frame, state: &DashboardState, area: Rect, theme: &Theme): responsive layout with breakpoints
  - Wide (>=120 cols): 3-column: [Stats | Projects | Recent]
  - Medium (80-119): 2-column: [Stats+Projects | Recent]
  - Narrow (<80): single column stacked
- render_stat_panel(): entity counts with colored numbers
- render_project_list(): project names with sync staleness indicators
- render_recent_activity(): scrollable list of recent changes
- render_sync_summary(): last sync stats (if available)

## Acceptance Criteria
- [ ] DashboardState stores counts, projects, recent activity, last sync info
- [ ] fetch_dashboard returns correct counts from DB
- [ ] Dashboard renders with responsive breakpoints (3/2/1 column layouts)
- [ ] Entity counts show open/total for issues and MRs
- [ ] Project list shows sync staleness with color coding (green <1h, yellow <6h, red >6h)
- [ ] Recent activity list is scrollable with j/k
- [ ] Relative timestamps use injected Clock (not wall-clock)

## Files
- MODIFY: crates/lore-tui/src/state/dashboard.rs (expand from stub)
- MODIFY: crates/lore-tui/src/action.rs (add fetch_dashboard)
- CREATE: crates/lore-tui/src/view/dashboard.rs

## TDD Anchor
RED: Write test_fetch_dashboard_counts in action.rs that creates in-memory DB with 5 issues (3 open, 2 closed), calls fetch_dashboard, asserts issues_open=3, issues_total=5.
GREEN: Implement fetch_dashboard with COUNT queries.
VERIFY: cargo test --manifest-path crates/lore-tui/Cargo.toml test_fetch_dashboard

## Edge Cases
- Empty database (first launch before sync): all counts should be 0, no crash
- Very long project paths: truncate to fit column width
- notes_system_pct: compute as (system_notes * 100 / total_notes), handle division by zero
- Clock injection ensures snapshot tests are deterministic (no "3 minutes ago" changing between runs)

## Dependency Context
Uses AppState, DashboardState, LoadState from "Implement AppState composition" task.
Uses DbManager from "Implement DbManager" task.
Uses Clock from "Implement Clock trait" task.
Uses theme from "Implement theme configuration" task.
Uses render_screen routing from "Implement common widgets" task.


Create golden query test suite

## Background
Golden query tests verify end-to-end search quality with known-good expected results. They use a seeded SQLite DB with deterministic fixture data and fixed embedding vectors (no Ollama dependency). Each test query must return at least one expected URL in the top 10 results. These tests catch search regressions (ranking changes, filter bugs, missing results).

## Approach
Create test infrastructure:

**1. tests/fixtures/golden_queries.json:**
```json
[
  {
    "query": "authentication login",
    "mode": "lexical",
    "filters": {},
    "expected_urls": ["https://gitlab.example.com/group/project/-/issues/234"],
    "min_results": 1,
    "max_rank": 10
  },
  {
    "query": "jwt token refresh",
    "mode": "hybrid",
    "filters": {"type": "merge_request"},
    "expected_urls": ["https://gitlab.example.com/group/project/-/merge_requests/456"],
    "min_results": 1,
    "max_rank": 10
  }
]
```

**2. Test harness (tests/golden_query_tests.rs):**
- Load golden_queries.json
- Create in-memory DB, apply all migrations
- Seed with deterministic fixture documents (issues, MRs, discussions)
- For hybrid/semantic queries: seed with fixed embedding vectors (768-dim, manually constructed for known similarity)
- For each query: run search, verify expected URL in top N results

**Fixture data design:**
- 10-20 documents covering different source types
- Known content that matches expected queries
- Fixed embeddings: construct vectors where similar documents have small cosine distance
- No randomness — fully deterministic

## Acceptance Criteria
- [ ] Golden queries file exists with at least 5 test queries
- [ ] Test harness loads queries and validates each
- [ ] All golden queries pass: expected URL in top 10
- [ ] No external dependencies (no Ollama, no GitLab)
- [ ] Deterministic fixture data (fixed embeddings, fixed content)
- [ ] `cargo test --test golden_query_tests` passes in CI

## Files
- `tests/fixtures/golden_queries.json` — new file
- `tests/golden_query_tests.rs` — new file (or tests/golden_queries.rs)

## TDD Loop
RED: Create golden_queries.json with expected results, harness fails (no fixture data)
GREEN: Seed fixture data that satisfies expected results
VERIFY: `cargo test --test golden_query_tests`

## Edge Cases
- Query matches multiple expected URLs: all must be present
- Lexical queries: FTS ranking determines position, not vector
- Hybrid queries: RRF combines both signals — fixed vectors must be designed to produce expected ranking
- Empty result for a golden query: test failure with clear message showing actual results

Golden query test suite: 7 golden queries in fixture, 8 seeded documents, 2 test functions (all_pass + fixture_valid), deterministic in-memory DB, no external deps. 312 total tests pass.


[CP1] Discussion and note transformers

Transform GitLab discussion/note payloads to normalized database schema.

Functions to implement:
- transformDiscussion(gitlabDiscussion, localProjectId, localIssueId) → NormalizedDiscussion
- transformNotes(gitlabDiscussion, localProjectId) → NormalizedNote[]

Transformation rules:
- Compute first_note_at/last_note_at from notes array
- Compute resolvable/resolved status from notes
- Set is_system from note.system
- Preserve note order via position (array index)
- Convert ISO timestamps to ms epoch

Files: src/gitlab/transformers/discussion.ts
Tests: tests/unit/discussion-transformer.test.ts
Done when: Unit tests pass for discussion/note transformation with system note flagging


Final validation and test coverage

## Background
Final validation gate ensuring all CP2 features work correctly. Verifies tests, lint, and manual smoke tests pass.

## Approach
Run comprehensive validation:
1. Automated tests (unit + integration)
2. Clippy and formatting
3. Critical test case verification
4. Gate A/B/C/D/E checklist
5. Manual smoke tests

## Files
None - validation only

## Acceptance Criteria
- [ ] `cargo test` passes (all tests green)
- [ ] `cargo test --release` passes
- [ ] `cargo clippy -- -D warnings` passes (zero warnings)
- [ ] `cargo fmt --check` passes
- [ ] Critical tests pass (see list below)
- [ ] Gate A/B/C/D/E verification complete
- [ ] Manual smoke tests pass

## Validation Commands
```bash
# 1. Build and test
cargo build --release
cargo test --release

# 2. Lint
cargo clippy -- -D warnings
cargo fmt --check

# 3. Run specific critical tests
cargo test does_not_advance_discussion_watermark_on_partial_failure
cargo test prefers_detailed_merge_status_when_both_fields_present
cargo test prefers_merge_user_when_both_fields_present
cargo test prefers_draft_when_both_draft_and_work_in_progress_present
cargo test atomic_note_replacement_preserves_data_on_parse_failure
cargo test full_sync_resets_discussion_watermarks
```

## Critical Test Cases
| Test | What It Verifies |
|------|------------------|
| `does_not_advance_discussion_watermark_on_partial_failure` | Pagination failure doesn't lose data |
| `prefers_detailed_merge_status_when_both_fields_present` | Non-deprecated field wins |
| `prefers_merge_user_when_both_fields_present` | Non-deprecated field wins |
| `prefers_draft_when_both_draft_and_work_in_progress_present` | OR semantics for draft |
| `atomic_note_replacement_preserves_data_on_parse_failure` | Parse before delete |
| `full_sync_resets_discussion_watermarks` | --full truly refreshes |

## Gate Checklist

### Gate A: MRs Only
- [ ] `gi ingest --type=merge_requests` fetches all MRs
- [ ] MR state supports: opened, merged, closed, locked
- [ ] draft field captured with work_in_progress fallback
- [ ] detailed_merge_status used with merge_status fallback
- [ ] head_sha and references captured
- [ ] Cursor-based sync is resumable

### Gate B: Labels + Assignees + Reviewers
- [ ] Labels linked via mr_labels junction
- [ ] Stale labels removed on resync
- [ ] Assignees linked via mr_assignees
- [ ] Reviewers linked via mr_reviewers

### Gate C: Dependent Discussion Sync
- [ ] Discussions fetched for MRs with updated_at advancement
- [ ] DiffNote position metadata captured
- [ ] DiffNote SHA triplet captured
- [ ] Upsert + sweep pattern for notes
- [ ] Watermark NOT advanced on partial failure
- [ ] Unchanged MRs skip discussion refetch

### Gate D: Resumability Proof
- [ ] Kill mid-run, rerun -> bounded redo
- [ ] `--full` resets cursor AND discussion watermarks
- [ ] Single-flight lock prevents concurrent runs

### Gate E: CLI Complete
- [ ] `gi list mrs` with all filters including --draft/--no-draft
- [ ] `gi show mr <iid>` with discussions and DiffNote context
- [ ] `gi count mrs` with state breakdown
- [ ] `gi sync-status` shows MR cursors

## Manual Smoke Tests
| Command | Expected |
|---------|----------|
| `gi ingest --type=merge_requests` | Completes, shows counts |
| `gi list mrs --limit=10` | Shows 10 MRs with correct columns |
| `gi list mrs --state=merged` | Only merged MRs |
| `gi list mrs --draft` | Only draft MRs with [DRAFT] prefix |
| `gi show mr <iid>` | Full detail with discussions |
| `gi count mrs` | Count with state breakdown |
| Re-run ingest | "0 new MRs", skipped discussion count |
| `gi ingest --type=merge_requests --full` | Full resync |

## Data Integrity Checks
```sql
-- MR count matches GitLab
SELECT COUNT(*) FROM merge_requests;

-- Every MR has raw payload
SELECT COUNT(*) FROM merge_requests WHERE raw_payload_id IS NULL;
-- Should be 0

-- Labels linked correctly
SELECT m.iid, COUNT(ml.label_id)
FROM merge_requests m
LEFT JOIN mr_labels ml ON ml.merge_request_id = m.id
GROUP BY m.id;

-- DiffNotes have position metadata
SELECT COUNT(*) FROM notes WHERE position_new_path IS NOT NULL;
```