OBSERV Epic: Phase 2 - Spans + Correlation IDs

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

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

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

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

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


Write integration tests

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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


Epic: TUI Phase 5.6 — CLI/TUI Parity Pack

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

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


Implement entity cache + render cache

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

## Approach

### Entity Cache (entity_cache.rs)

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

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

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

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

### Render Cache (render_cache.rs)

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

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

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

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

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

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

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

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

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

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

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


[CP1] Epic: Issue Ingestion

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

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

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

Reference: docs/prd/checkpoint-1.md


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

## Background

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

## Approach

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

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

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

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

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

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

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

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

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

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

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

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

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

## Files

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

## TDD Loop

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

## Acceptance Criteria

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

## Edge Cases

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

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


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

## Background

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

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

## Codebase Context

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

## Approach

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

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

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

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

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

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

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

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

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

### 3. Wire in main.rs

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

### 4. Shell Integration

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

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

## Acceptance Criteria

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

## Files

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

## TDD Anchor

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

GREEN: Implement completion handlers with SQL queries.

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

## Edge Cases

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

## Dependency Context

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


OBSERV: Replace subscriber init with dual-layer setup

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


Robot sync envelope: status enrichment metadata

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

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

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

## Implementation

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

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

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

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

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

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

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

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


Implement lore embed CLI command

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

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

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

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

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

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

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

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

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

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

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

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

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


Epic: TUI Phase 1 — Foundation

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

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

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


[CP1] gi ingest --type=issues command

CLI command to orchestrate issue ingestion.

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

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

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

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

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

## Output Format
Ingesting issues...

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

Fetching discussions (312 issues with updates)...

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

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

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

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


[CP1] Epic: Issue Ingestion

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

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

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

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

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


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)

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


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.


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


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