docs: update TUI PRD, time-decay scoring, and plan-to-beads plans

TUI PRD v2 (frankentui): Rounds 10-11 feedback refining the hybrid
Ratatui terminal UI approach — component architecture, keybinding
model, and incremental search integration.

Time-decay expert scoring: Round 6 feedback on the weighted scoring
model for the `who` command's expert mode, covering decay curves,
activity normalization, and bot filtering thresholds.

Plan-to-beads v2: Draft specification for the next iteration of the
plan-to-beads skill that converts markdown plans into dependency-
aware beads with full agent-executable context.
This commit is contained in:
teernisse
2026-02-11 16:00:34 -05:00
parent 125938fba6
commit ffd074499a
6 changed files with 1132 additions and 131 deletions

View File

@@ -0,0 +1,250 @@
# plan-to-beads v2 — Draft for Review
This is a draft of the improved skill. Review before applying to `~/.claude/skills/plan-to-beads/SKILL.md`.
---
```markdown
---
name: plan-to-beads
description: Transforms markdown implementation plans into granular, agent-ready beads with dependency graphs. Each bead is fully self-contained — an agent can execute it with zero external context. Triggers on "break down this plan", "create beads from", "convert to beads", "make issues from plan".
argument-hint: "[path/to/plan.md]"
---
# Plan to Beads Conversion
## The Prime Directive
**Every bead must be executable by an agent that has ONLY the bead description.** No plan document. No Slack context. No "see the PRD." The bead IS the spec. If an agent can't start coding within 60 seconds of reading the bead, it's not ready.
## Workflow
```
┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐
│ 1. PARSE │──▶│ 2. MINE │──▶│ 3. BUILD │──▶│ 4. LINK │──▶│ 5. AUDIT │
│ Structure│ │ Context │ │ Beads │ │ Deps │ │ Quality │
└──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘
```
### 1. Parse Structure
Read the plan document. Identify:
- **Epics**: Major sections / phases / milestones
- **Tasks**: Implementable units with clear outcomes (1-4 hour scope)
- **Subtasks**: Granular steps within tasks
### 2. Mine Context
This is the critical step. For EACH identified task, extract everything an implementing agent will need.
#### From the plan document:
| Extract | Where to look | Example |
|---------|--------------|---------|
| **Rationale** | Intro paragraphs, "why" sections | "We need this because the current approach causes N+1 queries" |
| **Approach details** | Implementation notes, code snippets, architecture decisions | "Use a 5-stage pipeline: SEED → HYDRATE → ..." |
| **Test requirements** | TDD sections, acceptance criteria, "verify by" notes | "Test that empty input returns empty vec" |
| **Edge cases & risks** | Warnings, gotchas, "watch out for" notes | "Multi-byte UTF-8 chars can cause panics at byte boundaries" |
| **Data shapes** | Type definitions, struct descriptions, API contracts | "TimelineEvent { kind: EventKind, timestamp: DateTime, ... }" |
| **File paths** | Explicit mentions or inferable from module structure | "src/core/timeline_seed.rs" |
| **Dependencies on other tasks** | "requires X", "after Y is done", "uses Z from step N" | "Consumes the TimelineEvent struct from the types task" |
| **Verification commands** | Test commands, CLI invocations, expected outputs | "cargo test timeline_seed -- --nocapture" |
#### From the codebase:
Search the codebase to supplement what the plan says:
- Find existing files mentioned or implied by the plan
- Discover patterns the task should follow (e.g., how existing similar modules are structured)
- Check test files for naming conventions and test infrastructure in use
- Confirm exact file paths rather than guessing
Use codebase search tools (WarpGrep, Explore agent, or targeted Grep/Glob) appropriate to the scope of what you need to find.
### 3. Build Beads
Use `br` exclusively.
| Type | Priority | Command |
|------|----------|---------|
| Epic | 1 | `br create "Epic: [Title]" -p 1` |
| Task | 2-3 | `br create "[Verb] [Object]" -p 2` |
| Subtask | 3-4 | `br q "[Verb] [Object]"` |
**Granularity target**: Each bead completable in 1-4 hours by one agent.
#### Description Templates
Use the **full template** for all task-level beads. Use the **light template** only for trivially small tasks (config change, single-line fix, add a re-export).
##### Full Template (default)
```
## Background
[WHY this exists. What problem it solves. How it fits into the larger system.
Include enough context that an agent unfamiliar with the project understands
the purpose. Reference architectural patterns in use.]
## Approach
[HOW to implement. Be specific:
- Data structures / types to create or use (include field names and types)
- Algorithms or patterns to follow
- Code snippets from the plan if available
- Which existing code to reference for patterns (exact file paths)]
## Acceptance Criteria
### Specified (from plan — implement as-is)
- [ ] <criteria explicitly stated in the plan>
- [ ] <criteria explicitly stated in the plan>
### Proposed (inferred — confirm with user before implementing) [?]
- [ ] [?] <criteria the agent inferred but the plan didn't specify>
- [ ] [?] <criteria the agent inferred but the plan didn't specify>
**ASSUMPTION RULE**: If proposed criteria exceed ~30% of total, STOP.
The bead needs human input before it's ready for implementation. Flag it
in the audit output and ask the user to refine the ACs.
## Files
[Exact paths to create or modify. Confirmed by searching the codebase.]
- CREATE: src/foo/bar.rs
- MODIFY: src/foo/mod.rs (add pub mod bar)
- MODIFY: tests/foo_tests.rs (add test module)
## TDD Anchor
[The first test to write. This grounds the agent's work.]
RED: Write `test_<name>` in `<test_file>` that asserts <specific behavior>.
GREEN: Implement the minimal code to make it pass.
VERIFY: <project's test command> <pattern>
[If the plan specifies additional tests, list them all:]
- test_empty_input_returns_empty_vec
- test_single_issue_produces_one_event
- test_handles_missing_fields_gracefully
## Edge Cases
[Gotchas, risks, things that aren't obvious. Pulled from the plan's warnings,
known issues, or your analysis of the approach.]
- <edge case 1>
- <edge case 2>
## Dependency Context
[For each dependency, explain WHAT it provides that this bead consumes.
Not just "depends on bd-xyz" but "uses the `TimelineEvent` struct and
`SeedConfig` type defined in bd-xyz".]
```
##### Light Template (trivially small tasks only)
Use this ONLY when the task is a one-liner or pure mechanical change (add a re-export, flip a config flag, rename a constant). If there's any ambiguity about approach, use the full template.
```
## What
[One sentence: what to do and where.]
## Acceptance Criteria
- [ ] <single binary criterion>
## Files
- MODIFY: <exact path>
```
### 4. Link Dependencies
```bash
br dep add [blocker-id] [blocked-id]
```
Dependency patterns:
- Types/structs → code that uses them
- Infrastructure (DB, config) → features that need them
- Core logic → extensions/enhancements
- Tests may depend on test helpers
**Critical**: When linking deps, update the "Dependency Context" section in the blocked bead to describe exactly what it receives from the blocker.
### 5. Audit Quality
Before reporting, review EVERY bead against this checklist:
| Check | Pass criteria |
|-------|--------------|
| **Self-contained?** | Agent can start coding in 60 seconds with ONLY this description |
| **TDD anchor?** | First test to write is named and described |
| **Binary criteria?** | Every acceptance criterion is pass/fail, not subjective |
| **Exact paths?** | File paths verified against codebase, not guessed |
| **Edge cases?** | At least 1 non-obvious gotcha identified |
| **Dep context?** | Each dependency explains WHAT it provides, not just its ID |
| **Approach specifics?** | Types, field names, patterns — not "implement the thing" |
| **Assumption budget?** | Proposed [?] criteria are <30% of total ACs |
If a bead fails any check, fix it before moving on. If the assumption budget is exceeded, flag the bead for human review rather than inventing more ACs.
## Assumption & AC Guidance
Agents filling in beads will inevitably encounter gaps in the plan. The rules:
1. **Never silently fill gaps.** If the plan doesn't specify a behavior, don't assume one and bury it in the ACs. Mark it `[?]` so the implementing agent knows to ask.
2. **Specify provenance on every AC.** Specified = from the plan. Proposed = your inference. The implementing agent treats these differently:
- **Specified**: implement without question
- **Proposed [?]**: pause and confirm with the user before implementing
3. **The 30% rule.** If more than ~30% of ACs on a bead are proposed/inferred, the plan was too vague for this task. Don't create the bead as-is. Instead:
- Create it with status noting "needs AC refinement"
- List the open questions explicitly
- Flag it in the output report under "Beads Needing Human Input"
4. **Prefer smaller scope over more assumptions.** If you're unsure whether a task should handle edge case X, make the bead's scope explicitly exclude it and note it as a potential follow-up. A bead that does less but does it right beats one that guesses wrong.
5. **Implementing agents: honor the markers.** When you encounter `[?]` on an AC, you MUST ask the user before implementing that behavior. Do not silently resolve it in either direction.
## Output Format
After completion, report:
```
## Beads Created: N total (X epics, Y tasks, Z subtasks)
### Quality Audit
- Beads scoring 4+: N/N (target: 100%)
- [list any beads that needed extra attention and why]
### Beads Needing Human Input
[List any beads where proposed ACs exceeded 30%, or where significant
ambiguity in the plan made self-contained descriptions impossible.
Include the specific open questions for each.]
### Critical Path
[blocker] → [blocked] → [blocked]
### Ready to Start
- bd-xxx: [Title] — [one-line summary of what agent will do]
- bd-yyy: [Title] — [one-line summary of what agent will do]
### Dependency Graph
[Brief visualization or description of the dep structure]
```
## Risk Tiers
| Operation | Tier | Behavior |
|-----------|------|----------|
| `br create` | SAFE | Auto-proceed |
| `br dep add` | SAFE | Auto-proceed |
| `br update --description` | CAUTION | Verify content |
| Bulk creation (>20 beads) | CAUTION | Confirm count first |
## Anti-Patterns
| Anti-Pattern | Why it's bad | Fix |
|-------------|-------------|-----|
| "Implement the pipeline stage" | Agent doesn't know WHAT to implement | Name the types, the function signatures, the test |
| "See plan for details" | Plan isn't available to the agent | Copy the relevant details INTO the bead |
| "Files: probably src/foo/" | Agent wastes time finding the right file | Search the codebase, confirm exact paths |
| "Should work correctly" | Not binary, not testable | "test_x passes" or "output matches Y" |
| No TDD anchor | Agent doesn't know where to start | Always specify the first test to write |
| "Depends on bd-xyz" (without context) | Agent doesn't know what bd-xyz provides | "Uses FooStruct and bar() function from bd-xyz" |
| Single-line description | Score 1 bead, agent is stuck | Use the full template, every section |
| Silently invented ACs | User surprised by implementation choices | Mark inferred ACs with [?], honor the 30% rule |
```

View File

@@ -0,0 +1,134 @@
I avoided everything already listed in your `Rejected Ideas` section and focused on net-new upgrades.
1. Centralize MR temporal semantics in one `mr_activity` CTE (architecture + correctness)
Why this improves the plan: right now the state-aware timestamp logic is repeated across multiple signal branches, while `closed_mr_multiplier` is applied later in Rust by string state checks. That split is brittle. A single `mr_activity` CTE removes drift risk, simplifies query maintenance, and avoids per-row state-string handling in Rust.
```diff
diff --git a/plan.md b/plan.md
@@ SQL Restructure
+mr_activity AS (
+ SELECT
+ m.id AS mr_id,
+ m.project_id,
+ m.author_username,
+ m.state,
+ CASE
+ WHEN m.state = 'merged' THEN COALESCE(m.merged_at, m.created_at)
+ WHEN m.state = 'closed' THEN COALESCE(m.closed_at, m.created_at)
+ ELSE COALESCE(m.updated_at, m.created_at)
+ END AS activity_ts,
+ CASE
+ WHEN m.state = 'closed' THEN ?5
+ ELSE 1.0
+ END AS state_mult
+ FROM merge_requests m
+ WHERE m.state IN ('opened','merged','closed')
+),
@@
-... {state_aware_ts} AS seen_at, m.state AS mr_state
+... a.activity_ts AS seen_at, a.state_mult
@@
-SELECT username, signal, mr_id, qty, ts, mr_state FROM aggregated
+SELECT username, signal, mr_id, qty, ts, state_mult FROM aggregated
```
2. Parameterize `reviewer_min_note_chars` and tighten config validation (robustness)
Why this improves the plan: inlining `reviewer_min_note_chars` into SQL text creates statement-cache churn and avoidable SQL-text variability. Also, current validation misses finite-range guards (`NaN`, absurd half-lives). Parameterization + stronger validation reduces weird failure modes.
```diff
diff --git a/plan.md b/plan.md
@@ 1. ScoringConfig (config.rs)
- reviewer_min_note_chars must be >= 0
+ reviewer_min_note_chars must be <= 4096
+ all half-life values must be <= 3650 (10 years safety cap)
+ closed_mr_multiplier must be finite and in (0.0, 1.0]
@@ SQL Restructure
-AND LENGTH(TRIM(COALESCE(n_body.body, ''))) >= {reviewer_min_note_chars}
+AND LENGTH(TRIM(COALESCE(n_body.body, ''))) >= ?6
```
3. Add path canonicalization before probes/scoring (correctness + UX)
Why this improves the plan: rename-awareness helps only after path resolution succeeds. Inputs like `./src//foo.rs` or inconsistent trailing slashes can still miss. Canonicalizing query paths up front reduces false negatives and ambiguous suffix behavior.
```diff
diff --git a/plan.md b/plan.md
@@ 3a. Path Resolution Probes (who.rs)
+Add `normalize_query_path()` before `build_path_query()`:
+- strip leading `./`
+- collapse repeated `/`
+- trim whitespace
+- preserve trailing `/` only for explicit prefix intent
+Expose both `path_input_original` and `path_input_normalized` in `resolved_input`.
@@ New Tests
+test_path_normalization_handles_dot_and_double_slash
+test_path_normalization_preserves_explicit_prefix_semantics
```
4. Add epsilon-based tie buckets for stable ranking (determinism)
Why this improves the plan: even with deterministic summation order, tiny `powf` platform differences can reorder near-equal scores. Tie bucketing keeps ordering stable and user-meaningful.
```diff
diff --git a/plan.md b/plan.md
@@ 4. Rust-Side Aggregation (who.rs)
-Sort on raw `f64` score — `(raw_score DESC, last_seen DESC, username ASC)`.
+Sort using a tie bucket:
+`score_bucket = (raw_score / 1e-9).floor() as i64`
+Order by `(score_bucket DESC, raw_score DESC, last_seen DESC, username ASC)`.
+This preserves precision while preventing meaningless micro-delta reorderings.
@@ New Tests
+test_near_equal_scores_use_stable_tie_bucket_order
```
5. Add `--diagnose-score` aggregated diagnostics (operability)
Why this improves the plan: `--explain-score` tells “why this user scored”, but not “why this query behaved oddly” (path ambiguity, dedup collapse, old_path contribution share, filtered bots, window exclusions). Lightweight aggregate diagnostics are high-value without per-MR drill-down complexity.
```diff
diff --git a/plan.md b/plan.md
@@ CLI changes (who.rs)
+Add `--diagnose-score` flag (compatible with `--explain-score`, incompatible with `--detail`).
+When enabled, include:
+- matched_notes_raw_count
+- matched_notes_dedup_count
+- matched_file_changes_raw_count
+- matched_file_changes_dedup_count
+- rows_excluded_by_window_upper_bound
+- users_filtered_by_excluded_usernames
+- query_elapsed_ms
@@ Robot output
+`diagnostics` object emitted only when `--diagnose-score` is set.
```
6. Add probe-optimized indexes for path resolution (performance)
Why this improves the plan: current proposed indexes are optimized for scoring joins, but `build_path_query()` and `suffix_probe()` run existence/path-only probes where `author_username` is not constrained. Dedicated probe indexes will materially reduce latency for path lookup modes.
```diff
diff --git a/plan.md b/plan.md
@@ 6. Index Migration (db.rs)
+-- Fast exact/prefix/suffix path probes on notes (no author predicate)
+CREATE INDEX IF NOT EXISTS idx_notes_new_path_project_created
+ ON notes(position_new_path, project_id, created_at)
+ WHERE note_type = 'DiffNote' AND is_system = 0 AND position_new_path IS NOT NULL;
+
+CREATE INDEX IF NOT EXISTS idx_notes_old_path_project_created
+ ON notes(position_old_path, project_id, created_at)
+ WHERE note_type = 'DiffNote' AND is_system = 0 AND position_old_path IS NOT NULL;
```
7. Add multi-path expert scoring (`--path` repeatable) with dedup across paths (feature + utility)
Why this improves the plan: current model is single-path centric. Real ownership questions are usually subsystem-level. Repeatable paths/prefixes let users ask “who knows auth stack?” in one call. Dedup by `(username, signal, mr_id)` avoids double-counting same MR touching multiple requested paths.
```diff
diff --git a/plan.md b/plan.md
@@ CLI/feature scope
+Add repeatable `--path` in expert mode:
+`lore who --expert --path src/auth/ --path src/session/`
+Optional `--path-file <file>` for large path sets (one per line).
@@ SQL Restructure
+Add `requested_paths` CTE and match each source against that set.
+Ensure dedup key includes `(username, signal, mr_id)` so one MR contributes once per signal even if multiple paths match.
@@ New Tests
+test_multi_path_query_unions_results_without_double_counting
+test_multi_path_with_overlap_prefixes_is_idempotent
```
These 7 revisions keep your current model direction intact, but reduce correctness drift risk, harden edge handling, improve query observability, and make the feature materially more useful for real ownership workflows.

View File

@@ -2,12 +2,12 @@
plan: true
title: ""
status: iterating
iteration: 5
iteration: 6
target_iterations: 8
beads_revision: 1
related_plans: []
created: 2026-02-08
updated: 2026-02-09
updated: 2026-02-12
---
# Time-Decay Expert Scoring Model
@@ -70,7 +70,8 @@ Author/reviewer signals are deduplicated per MR (one signal per distinct MR). No
1. **`src/core/config.rs`** — Add half-life fields + assigned-only reviewer config to `ScoringConfig`; add config validation
2. **`src/cli/commands/who.rs`** — Core changes:
- Add `half_life_decay()` pure function
- Restructure `query_expert()`: SQL returns hybrid-aggregated signal rows with timestamps (MR-level for author/reviewer, note-count-per-MR for notes), Rust applies decay + `log2(1+count)` + final ranking
- Add `normalize_query_path()` for input canonicalization before path resolution
- Restructure `query_expert()`: SQL returns hybrid-aggregated signal rows with timestamps and state multiplier (MR-level for author/reviewer, note-count-per-MR for notes), Rust applies decay + `log2(1+count)` + final ranking
- Match both `new_path` and `old_path` in all signal queries (rename awareness)
- Extend rename awareness to `build_path_query()` probes and `suffix_probe()` (not just scoring)
- Split reviewer signal into participated vs assigned-only
@@ -106,10 +107,10 @@ pub struct ScoringConfig {
```
**Config validation**: Add a `validate_scoring()` call in `Config::load_from_path()` after deserialization:
- All `*_half_life_days` must be > 0 (prevents division by zero in decay function)
- All `*_half_life_days` must be > 0 and <= 3650 (prevents division by zero in decay function; rejects absurd 10+ year half-lives that would effectively disable decay)
- All `*_weight` / `*_bonus` must be >= 0 (negative weights produce nonsensical scores)
- `closed_mr_multiplier` must be in `(0.0, 1.0]` (0 would discard closed MRs entirely; >1 would over-weight them)
- `reviewer_min_note_chars` must be >= 0 (0 disables the filter; typical useful values: 10-50)
- `closed_mr_multiplier` must be finite (not NaN/Inf) and in `(0.0, 1.0]` (0 would discard closed MRs entirely; >1 would over-weight them; NaN/Inf would propagate through all scores)
- `reviewer_min_note_chars` must be >= 0 and <= 4096 (0 disables the filter; 4096 is a sane upper bound — no real review comment needs to be longer to qualify; typical useful values: 10-50)
- `excluded_usernames` entries must be non-empty strings (no blank entries)
- Return `LoreError::ConfigInvalid` with a clear message on failure
@@ -126,9 +127,9 @@ fn half_life_decay(elapsed_ms: i64, half_life_days: u32) -> f64 {
### 3. SQL Restructure (who.rs)
The SQL uses **CTE-based dual-path matching** and **hybrid aggregation**. Rather than repeating `OR old_path` in every signal subquery, two foundational CTEs (`matched_notes`, `matched_file_changes`) centralize path matching. A third CTE (`reviewer_participation`) precomputes which reviewers actually left DiffNotes, avoiding correlated `EXISTS`/`NOT EXISTS` subqueries.
The SQL uses **CTE-based dual-path matching**, a **centralized `mr_activity` CTE**, and **hybrid aggregation**. Rather than repeating `OR old_path` in every signal subquery, two foundational CTEs (`matched_notes`, `matched_file_changes`) centralize path matching. A `mr_activity` CTE centralizes the state-aware timestamp and state multiplier in one place, eliminating repetition of the CASE expression across signals 3, 4a, 4b. A fourth CTE (`reviewer_participation`) precomputes which reviewers actually left DiffNotes, avoiding correlated `EXISTS`/`NOT EXISTS` subqueries.
MR-level signals return one row per (username, signal, mr_id) with a timestamp; note signals return one row per (username, mr_id) with `note_count` and `max_ts`. This keeps row counts bounded (dozens to low hundreds per path) while giving Rust the data it needs for decay and `log2(1+count)`.
MR-level signals return one row per (username, signal, mr_id) with a timestamp and state multiplier; note signals return one row per (username, mr_id) with `note_count` and `max_ts`. This keeps row counts bounded (dozens to low hundreds per path) while giving Rust the data it needs for decay and `log2(1+count)`.
```sql
WITH matched_notes_raw AS (
@@ -177,6 +178,24 @@ matched_file_changes AS (
SELECT DISTINCT merge_request_id, project_id
FROM matched_file_changes_raw
),
mr_activity AS (
-- Centralized state-aware timestamps and state multiplier.
-- Defined once, referenced by all file-change-based signals (3, 4a, 4b).
-- Scoped to MRs matched by file changes to avoid materializing the full MR table.
SELECT DISTINCT
m.id AS mr_id,
m.author_username,
m.state,
CASE
WHEN m.state = 'merged' THEN COALESCE(m.merged_at, m.created_at)
WHEN m.state = 'closed' THEN COALESCE(m.closed_at, m.created_at)
ELSE COALESCE(m.updated_at, m.created_at)
END AS activity_ts,
CASE WHEN m.state = 'closed' THEN ?5 ELSE 1.0 END AS state_mult
FROM merge_requests m
JOIN matched_file_changes mfc ON mfc.merge_request_id = m.id
WHERE m.state IN ('opened','merged','closed')
),
reviewer_participation AS (
-- Precompute which (mr_id, username) pairs have substantive DiffNote participation.
-- Materialized once, then joined against mr_reviewers to classify.
@@ -185,17 +204,20 @@ reviewer_participation AS (
-- reviewer from 3-point to 10-point weight, defeating the purpose of the split.
-- Note: mn.id refers back to notes.id, so we join notes to access the body column
-- (not carried in matched_notes to avoid bloating that CTE with body text).
-- ?6 is the configured reviewer_min_note_chars value (default 20).
SELECT DISTINCT d.merge_request_id AS mr_id, mn.author_username AS username
FROM matched_notes mn
JOIN discussions d ON mn.discussion_id = d.id
JOIN notes n_body ON mn.id = n_body.id
WHERE d.merge_request_id IS NOT NULL
AND LENGTH(TRIM(COALESCE(n_body.body, ''))) >= {reviewer_min_note_chars}
AND LENGTH(TRIM(COALESCE(n_body.body, ''))) >= ?6
),
raw AS (
-- Signal 1: DiffNote reviewer (individual notes for note_cnt)
-- Computes state_mult inline (not via mr_activity) because this joins through discussions, not file changes.
SELECT mn.author_username AS username, 'diffnote_reviewer' AS signal,
m.id AS mr_id, mn.id AS note_id, mn.created_at AS seen_at, m.state AS mr_state
m.id AS mr_id, mn.id AS note_id, mn.created_at AS seen_at,
CASE WHEN m.state = 'closed' THEN ?5 ELSE 1.0 END AS state_mult
FROM matched_notes mn
JOIN discussions d ON mn.discussion_id = d.id
JOIN merge_requests m ON d.merge_request_id = m.id
@@ -205,8 +227,10 @@ raw AS (
UNION ALL
-- Signal 2: DiffNote MR author
-- Computes state_mult inline (same reason as signal 1).
SELECT m.author_username AS username, 'diffnote_author' AS signal,
m.id AS mr_id, NULL AS note_id, MAX(mn.created_at) AS seen_at, m.state AS mr_state
m.id AS mr_id, NULL AS note_id, MAX(mn.created_at) AS seen_at,
CASE WHEN m.state = 'closed' THEN ?5 ELSE 1.0 END AS state_mult
FROM merge_requests m
JOIN discussions d ON d.merge_request_id = m.id
JOIN matched_notes mn ON mn.discussion_id = d.id
@@ -216,65 +240,59 @@ raw AS (
UNION ALL
-- Signal 3: MR author via file changes (state-aware timestamp)
SELECT m.author_username AS username, 'file_author' AS signal,
m.id AS mr_id, NULL AS note_id,
{state_aware_ts} AS seen_at, m.state AS mr_state
FROM matched_file_changes mfc
JOIN merge_requests m ON mfc.merge_request_id = m.id
WHERE m.author_username IS NOT NULL
AND m.state IN ('opened','merged','closed')
AND {state_aware_ts} >= ?2
AND {state_aware_ts} < ?4
-- Signal 3: MR author via file changes (uses mr_activity CTE for timestamp + state_mult)
SELECT a.author_username AS username, 'file_author' AS signal,
a.mr_id, NULL AS note_id,
a.activity_ts AS seen_at, a.state_mult
FROM mr_activity a
WHERE a.author_username IS NOT NULL
AND a.activity_ts >= ?2
AND a.activity_ts < ?4
UNION ALL
-- Signal 4a: Reviewer participated (in mr_reviewers AND left DiffNotes on path)
SELECT r.username AS username, 'file_reviewer_participated' AS signal,
m.id AS mr_id, NULL AS note_id,
{state_aware_ts} AS seen_at, m.state AS mr_state
FROM matched_file_changes mfc
JOIN merge_requests m ON mfc.merge_request_id = m.id
JOIN mr_reviewers r ON r.merge_request_id = m.id
JOIN reviewer_participation rp ON rp.mr_id = m.id AND rp.username = r.username
a.mr_id, NULL AS note_id,
a.activity_ts AS seen_at, a.state_mult
FROM mr_activity a
JOIN mr_reviewers r ON r.merge_request_id = a.mr_id
JOIN reviewer_participation rp ON rp.mr_id = a.mr_id AND rp.username = r.username
WHERE r.username IS NOT NULL
AND (m.author_username IS NULL OR r.username != m.author_username)
AND m.state IN ('opened','merged','closed')
AND {state_aware_ts} >= ?2
AND {state_aware_ts} < ?4
AND (a.author_username IS NULL OR r.username != a.author_username)
AND a.activity_ts >= ?2
AND a.activity_ts < ?4
UNION ALL
-- Signal 4b: Reviewer assigned-only (in mr_reviewers, NO DiffNotes on path)
SELECT r.username AS username, 'file_reviewer_assigned' AS signal,
m.id AS mr_id, NULL AS note_id,
{state_aware_ts} AS seen_at, m.state AS mr_state
FROM matched_file_changes mfc
JOIN merge_requests m ON mfc.merge_request_id = m.id
JOIN mr_reviewers r ON r.merge_request_id = m.id
LEFT JOIN reviewer_participation rp ON rp.mr_id = m.id AND rp.username = r.username
a.mr_id, NULL AS note_id,
a.activity_ts AS seen_at, a.state_mult
FROM mr_activity a
JOIN mr_reviewers r ON r.merge_request_id = a.mr_id
LEFT JOIN reviewer_participation rp ON rp.mr_id = a.mr_id AND rp.username = r.username
WHERE rp.username IS NULL -- NOT in participation set
AND r.username IS NOT NULL
AND (m.author_username IS NULL OR r.username != m.author_username)
AND m.state IN ('opened','merged','closed')
AND {state_aware_ts} >= ?2
AND {state_aware_ts} < ?4
AND (a.author_username IS NULL OR r.username != a.author_username)
AND a.activity_ts >= ?2
AND a.activity_ts < ?4
),
aggregated AS (
-- MR-level signals: 1 row per (username, signal_class, mr_id) with MAX(ts)
SELECT username, signal, mr_id, 1 AS qty, MAX(seen_at) AS ts, mr_state
SELECT username, signal, mr_id, 1 AS qty, MAX(seen_at) AS ts, MAX(state_mult) AS state_mult
FROM raw WHERE signal != 'diffnote_reviewer'
GROUP BY username, signal, mr_id
UNION ALL
-- Note signals: 1 row per (username, mr_id) with note_count and max_ts
SELECT username, 'note_group' AS signal, mr_id, COUNT(*) AS qty, MAX(seen_at) AS ts, mr_state
SELECT username, 'note_group' AS signal, mr_id, COUNT(*) AS qty, MAX(seen_at) AS ts, MAX(state_mult) AS state_mult
FROM raw WHERE signal = 'diffnote_reviewer' AND note_id IS NOT NULL
GROUP BY username, mr_id
)
SELECT username, signal, mr_id, qty, ts, mr_state FROM aggregated WHERE username IS NOT NULL
SELECT username, signal, mr_id, qty, ts, state_mult FROM aggregated WHERE username IS NOT NULL
```
Where `{state_aware_ts}` is the state-aware timestamp expression (defined in the next section), `{path_op}` is either `= ?1` or `LIKE ?1 ESCAPE '\\'` depending on the path query type, `?4` is the `as_of_ms` exclusive upper bound (defaults to `now_ms` when `--as-of` is not specified), and `{reviewer_min_note_chars}` is the configured `reviewer_min_note_chars` value (default 20, inlined as a literal in the SQL string). The `>= ?2 AND < ?4` pattern (half-open interval) ensures that when `--as-of` is set to a past date, events at or after that date are excluded — without this, "future" events would leak in with full weight, breaking reproducibility. The exclusive upper bound avoids edge-case ambiguity when events have timestamps exactly equal to the as-of value.
Where `{path_op}` is either `= ?1` or `LIKE ?1 ESCAPE '\\'` depending on the path query type, `?2` is `since_ms`, `?3` is the optional project_id, `?4` is the `as_of_ms` exclusive upper bound (defaults to `now_ms` when `--as-of` is not specified), `?5` is the `closed_mr_multiplier` (default 0.5, bound as a parameter), and `?6` is the configured `reviewer_min_note_chars` value (default 20, bound as a parameter). The `>= ?2 AND < ?4` pattern (half-open interval) ensures that when `--as-of` is set to a past date, events at or after that date are excluded — without this, "future" events would leak in with full weight, breaking reproducibility. The exclusive upper bound avoids edge-case ambiguity when events have timestamps exactly equal to the as-of value.
**Rationale for CTE-based dual-path matching**: The previous approach (repeating `OR old_path` in every signal subquery) duplicated the path matching logic 5 times. Factoring it into foundational CTEs (`matched_notes_raw``matched_notes`, `matched_file_changes_raw``matched_file_changes`) means path matching is defined once, each index branch is explicit, and adding future path resolution logic (e.g., alias chains) only requires changes in one place. The UNION ALL + dedup pattern ensures SQLite uses the optimal index for each path column independently.
@@ -308,7 +326,21 @@ Both columns already exist in the schema (`notes.position_old_path` from migrati
- **Signal 4a** (`file_reviewer_participated`): User is in `mr_reviewers` AND appears in the `reviewer_participation` CTE (left DiffNotes on the path for that MR). Gets `reviewer_weight` (10) and `reviewer_half_life_days` (90).
- **Signal 4b** (`file_reviewer_assigned`): User is in `mr_reviewers` but NOT in the `reviewer_participation` CTE. Gets `reviewer_assignment_weight` (3) and `reviewer_assignment_half_life_days` (45).
### 3a. Path Resolution Probes (who.rs)
**Rationale for `mr_activity` CTE**: The previous approach repeated the state-aware CASE expression and `m.state` column in signals 3, 4a, and 4b, with the `closed_mr_multiplier` applied later in Rust by string-matching on `mr_state`. This split was brittle — the CASE expression could drift between signal branches, and per-row state-string handling in Rust was unnecessary indirection. The `mr_activity` CTE defines the timestamp and multiplier once, scoped to matched MRs only (via JOIN with `matched_file_changes`) to avoid materializing the full MR table. Signals 3, 4a, 4b now reference `a.activity_ts` and `a.state_mult` directly. Signals 1 and 2 (DiffNote-based) still compute `state_mult` inline because they join through `discussions`, not `matched_file_changes`, and adding them to `mr_activity` would require a second join path that doesn't simplify anything.
**Rationale for parameterized `reviewer_min_note_chars` and `closed_mr_multiplier`**: Previous iterations inlined `reviewer_min_note_chars` as a literal in the SQL string and kept `closed_mr_multiplier` in Rust only. Binding both as SQL parameters (`?5` for `closed_mr_multiplier`, `?6` for `reviewer_min_note_chars`) eliminates statement-cache churn (the SQL text is identical regardless of config values), avoids SQL-text variability that complicates EXPLAIN QUERY PLAN analysis, and centralizes the multiplier application in SQL for file-change signals. The DiffNote signals (1, 2) still compute `state_mult` inline because they don't go through `mr_activity`.
### 3a. Path Canonicalization and Resolution Probes (who.rs)
**Path canonicalization**: Before any path resolution or scoring, normalize the user's input path via `normalize_query_path()`:
- Strip leading `./` (e.g., `./src/foo.rs``src/foo.rs`)
- Collapse repeated `/` (e.g., `src//foo.rs``src/foo.rs`)
- Trim leading/trailing whitespace
- Preserve trailing `/` only when present — it signals explicit prefix intent
This is applied once at the top of `run_who()` before `build_path_query()`. The robot JSON `resolved_input` includes both `path_input_original` (raw user input) and `path_input_normalized` (after canonicalization) for debugging transparency. The normalization is purely syntactic — no filesystem lookups, no canonicalization against the database.
**Path resolution probes**: Rename awareness must extend beyond scoring queries to the path resolution layer. Currently `build_path_query()` (line 457) and `suffix_probe()` (line 584) only check `position_new_path` and `new_path`. If a user queries an old path name, these probes return "not found" and the scoring query never runs.
Rename awareness must extend beyond scoring queries to the path resolution layer. Currently `build_path_query()` (line 457) and `suffix_probe()` (line 584) only check `position_new_path` and `new_path`. If a user queries an old path name, these probes return "not found" and the scoring query never runs.
@@ -337,39 +369,29 @@ WHERE old_path IS NOT NULL
This ensures that querying by an old filename (e.g., `login.rs` after it was renamed to `auth.rs`) still resolves to a usable path for scoring. The UNION deduplicates so the same path appearing in both old and new columns doesn't cause false ambiguity.
**State-aware timestamps for file-change signals (signals 3, 4a, 4b)**: Replace `m.updated_at` with a state-aware expression:
```sql
CASE
WHEN m.state = 'merged' THEN COALESCE(m.merged_at, m.created_at)
WHEN m.state = 'closed' THEN COALESCE(m.closed_at, m.created_at)
ELSE COALESCE(m.updated_at, m.created_at) -- opened / other
END AS activity_ts
```
**State-aware timestamps for file-change signals (signals 3, 4a, 4b)**: Centralized in the `mr_activity` CTE (see section 3). The CASE expression uses `merged_at` for merged MRs, `closed_at` for closed MRs, and `updated_at` for open MRs, with `created_at` as fallback when the preferred timestamp is NULL.
**Rationale**: `updated_at` is noisy for merged MRs — it changes on label edits, title changes, rebases, and metadata touches, creating false recency. `merged_at` is the best indicator of when code expertise was formed (the moment the code entered the branch). But for **open MRs**, `updated_at` is actually the right signal because it reflects ongoing active work. `closed_at` anchors closed-without-merge MRs to their closure time (these represent review effort even if the code was abandoned). Each state gets the timestamp that best represents when expertise was last exercised.
### 4. Rust-Side Aggregation (who.rs)
For each username, accumulate into a struct with:
- **Author MRs**: `HashMap<i64, (i64, String)>` (mr_id -> (max timestamp, mr_state)) from `diffnote_author` + `file_author` signals
- **Reviewer Participated MRs**: `HashMap<i64, (i64, String)>` from `diffnote_reviewer` + `file_reviewer_participated` signals
- **Reviewer Assigned-Only MRs**: `HashMap<i64, (i64, String)>` from `file_reviewer_assigned` signals (excluding any MR already in participated set)
- **Notes per MR**: `HashMap<i64, (u32, i64, String)>` (mr_id -> (count, max_ts, mr_state)) from `note_group` rows in the aggregated query (already grouped per user+MR with note_count in `qty`). Used for `log2(1 + count)` diminishing returns.
- **Author MRs**: `HashMap<i64, (i64, f64)>` (mr_id -> (max timestamp, state_mult)) from `diffnote_author` + `file_author` signals
- **Reviewer Participated MRs**: `HashMap<i64, (i64, f64)>` from `diffnote_reviewer` + `file_reviewer_participated` signals
- **Reviewer Assigned-Only MRs**: `HashMap<i64, (i64, f64)>` from `file_reviewer_assigned` signals (excluding any MR already in participated set)
- **Notes per MR**: `HashMap<i64, (u32, i64, f64)>` (mr_id -> (count, max_ts, state_mult)) from `note_group` rows in the aggregated query (already grouped per user+MR with note_count in `qty`). Used for `log2(1 + count)` diminishing returns.
- **Last seen**: max of all timestamps
- **Components** (when `--explain-score`): Track per-component f64 subtotals for `author`, `reviewer_participated`, `reviewer_assigned`, `notes`
The `mr_state` field from each SQL row is stored alongside the timestamp so the Rust-side can apply `closed_mr_multiplier` when `mr_state == "closed"`.
The `state_mult` field from each SQL row (already computed in SQL as 1.0 for merged/open or `closed_mr_multiplier` for closed) is stored alongside the timestamp — no string-matching on MR state needed in Rust.
Compute score as `f64` with **deterministic contribution ordering**: within each signal type, sort contributions by `(mr_id ASC)` before summing. This eliminates platform-dependent HashMap iteration order as a source of f64 rounding variance near ties, ensuring CI reproducibility without the complexity of compensated summation (Neumaier/Kahan). Each MR-level contribution is multiplied by `closed_mr_multiplier` (default 0.5) when the MR's state is `"closed"`:
Compute score as `f64` with **deterministic contribution ordering**: within each signal type, sort contributions by `(mr_id ASC)` before summing. This eliminates platform-dependent HashMap iteration order as a source of f64 rounding variance near ties, ensuring CI reproducibility without the complexity of compensated summation (Neumaier/Kahan). Each MR-level contribution is multiplied by its `state_mult` (already computed in SQL):
```
state_mult(mr) = if mr.state == "closed" { closed_mr_multiplier } else { 1.0 }
raw_score =
sum(author_weight * state_mult(mr) * decay(now - ts, author_hl) for (mr, ts) in author_mrs)
+ sum(reviewer_weight * state_mult(mr) * decay(now - ts, reviewer_hl) for (mr, ts) in reviewer_participated)
+ sum(reviewer_assignment_weight * state_mult(mr) * decay(now - ts, reviewer_assignment_hl) for (mr, ts) in reviewer_assigned)
+ sum(note_bonus * state_mult(mr) * log2(1 + count) * decay(now - ts, note_hl) for (mr, count, ts) in notes_per_mr)
sum(author_weight * state_mult * decay(now - ts, author_hl) for (mr, ts, state_mult) in author_mrs)
+ sum(reviewer_weight * state_mult * decay(now - ts, reviewer_hl) for (mr, ts, state_mult) in reviewer_participated)
+ sum(reviewer_assignment_weight * state_mult * decay(now - ts, reviewer_assignment_hl) for (mr, ts, state_mult) in reviewer_assigned)
+ sum(note_bonus * state_mult * log2(1 + count) * decay(now - ts, note_hl) for (mr, count, ts, state_mult) in notes_per_mr)
```
**Why include closed MRs?** A closed-without-merge MR still represents review effort and code familiarity — the reviewer read the diff, left comments, and engaged with the code even though it was ultimately abandoned. Excluding closed MRs entirely (the previous plan's approach) discarded this signal. The `closed_mr_multiplier` (default 0.5) halves the contribution, reflecting that the code never landed but the reviewer's cognitive engagement was real. This also eliminates the dead-code inconsistency where the state-aware CASE expression handled `closed` but the WHERE clause excluded it.
@@ -458,9 +480,16 @@ CREATE INDEX IF NOT EXISTS idx_mfc_new_path_project_mr
CREATE INDEX IF NOT EXISTS idx_notes_diffnote_discussion_author
ON notes(discussion_id, author_username, created_at)
WHERE note_type = 'DiffNote' AND is_system = 0;
-- Support path resolution probes on old_path (build_path_query() and suffix_probe())
-- The existing idx_notes_diffnote_path_created covers new_path probes, but old_path probes
-- need their own index since probes don't constrain author_username.
CREATE INDEX IF NOT EXISTS idx_notes_old_path_project_created
ON notes(position_old_path, project_id, created_at)
WHERE note_type = 'DiffNote' AND is_system = 0 AND position_old_path IS NOT NULL;
```
**Rationale**: The existing indexes cover `position_new_path` and `new_path` but not their `old_path` counterparts. Without these, the `OR old_path` clauses would force table scans on renamed files. The `reviewer_participation` CTE joins `matched_notes` -> `discussions` -> `merge_requests`, so an index on `(discussion_id, author_username)` speeds up the CTE materialization.
**Rationale**: The existing indexes cover `position_new_path` and `new_path` but not their `old_path` counterparts. Without these, the `OR old_path` clauses would force table scans on renamed files. The `reviewer_participation` CTE joins `matched_notes` -> `discussions` -> `merge_requests`, so an index on `(discussion_id, author_username)` speeds up the CTE materialization. The `idx_notes_old_path_project_created` index supports path resolution probes (`build_path_query()` and `suffix_probe()`) which run existence/path-only checks without constraining `author_username` — the scoring-oriented `idx_notes_old_path_author` has `author_username` as the second column, which is suboptimal for these probes.
**Schema note**: The `notes` table uses `discussion_id` as its FK to `discussions`, which in turn has `merge_request_id`. There is no `noteable_id` column on `notes`. The previous plan revision incorrectly referenced `noteable_id` — this is corrected.
@@ -526,6 +555,14 @@ Add timestamp-aware variants:
**`test_null_timestamp_fallback_to_created_at`**: Insert a merged MR with `merged_at = NULL` (edge case: old data before the column was populated). The state-aware timestamp should fall back to `created_at`. Verify the score reflects `created_at`, not 0 or a panic.
**`test_path_normalization_handles_dot_and_double_slash`**: Call `normalize_query_path("./src//foo.rs")` — should return `"src/foo.rs"`. Call `normalize_query_path(" src/bar.rs ")` — should return `"src/bar.rs"`. Call `normalize_query_path("src/foo.rs")` — should return unchanged (already normalized). Call `normalize_query_path("")` — should return `""` (empty input passes through).
**`test_path_normalization_preserves_prefix_semantics`**: Call `normalize_query_path("./src/dir/")` — should return `"src/dir/"` (trailing slash preserved for prefix intent). Call `normalize_query_path("src/dir")` — should return `"src/dir"` (no trailing slash = file, not prefix).
**`test_config_validation_rejects_absurd_half_life`**: `ScoringConfig` with `author_half_life_days = 5000` (>3650 cap) should return `ConfigInvalid` error. Similarly, `reviewer_min_note_chars = 5000` (>4096 cap) should fail.
**`test_config_validation_rejects_nan_multiplier`**: `ScoringConfig` with `closed_mr_multiplier = f64::NAN` should return `ConfigInvalid` error. Same for `f64::INFINITY`.
#### Invariant tests (regression safety for ranking systems)
**`test_score_monotonicity_by_age`**: For any single signal type, an older timestamp must never produce a higher score than a newer timestamp with the same weight and half-life. Generate N random (age, half_life) pairs and assert `decay(older) <= decay(newer)` for all.
@@ -554,6 +591,8 @@ The `test_expert_scoring_weights_are_configurable` test needs `..Default::defaul
- Confirm that `matched_notes_raw` branch 1 uses the existing new_path index and branch 2 uses `idx_notes_old_path_author` (not a full table scan on either branch)
- Confirm that `matched_file_changes_raw` branch 1 uses `idx_mfc_new_path_project_mr` and branch 2 uses `idx_mfc_old_path_project_mr`
- Confirm that `reviewer_participation` CTE uses `idx_notes_diffnote_discussion_author`
- Confirm that `mr_activity` CTE joins `merge_requests` via primary key from `matched_file_changes`
- Confirm that path resolution probes (old_path leg) use `idx_notes_old_path_project_created`
- Document the observed plan in a comment near the SQL for future regression reference
7. Performance baseline (manual, not CI-gated):
- Run `time cargo run --release -- who --path <exact-path>` on the real database for exact, prefix, and suffix modes
@@ -571,6 +610,7 @@ The `test_expert_scoring_weights_are_configurable` test needs `..Default::defaul
- Spot-check that reviewers who only left "LGTM"-style notes are classified as assigned-only (not participated)
- Verify closed MRs contribute at ~50% of equivalent merged MR scores via `--explain-score`
- If the project has known bot accounts (e.g., renovate-bot), add them to `excluded_usernames` config and verify they no longer appear in results. Run again with `--include-bots` to confirm they reappear.
- Test path normalization: `who --path ./src//foo.rs` and `who --path src/foo.rs` should produce identical results
## Accepted from External Review
@@ -614,6 +654,14 @@ Ideas incorporated from ChatGPT review (feedback-1 through feedback-4) that genu
- **Performance baseline SLOs**: Added manual performance baseline step to verification — record timings for exact/prefix/suffix modes and flag >2x regressions. Kept lightweight (no CI gating, no synthetic benchmarks) to match the project's current maturity.
- **New tests**: `test_as_of_exclusive_upper_bound`, `test_excluded_usernames_filters_bots`, `test_include_bots_flag_disables_filtering`, `test_deterministic_accumulation_order` — cover the newly-accepted features.
**From feedback-6 (ChatGPT review):**
- **Centralized `mr_activity` CTE**: The state-aware timestamp CASE expression and `closed_mr_multiplier` were repeated across signals 3, 4a, 4b with the multiplier applied later in Rust via string-matching on `mr_state`. This was brittle — the CASE could drift between branches and the Rust-side string matching was unnecessary indirection. A single `mr_activity` CTE defines both `activity_ts` and `state_mult` once, scoped to matched MRs only (via JOIN with `matched_file_changes`). Signals 1 and 2 still compute `state_mult` inline because they join through `discussions`, not `matched_file_changes`.
- **Parameterized `reviewer_min_note_chars` and `closed_mr_multiplier`**: Previously `reviewer_min_note_chars` was inlined as a literal in the SQL string and `closed_mr_multiplier` was applied only in Rust. Binding both as SQL parameters (`?5` for `closed_mr_multiplier`, `?6` for `reviewer_min_note_chars`) eliminates statement-cache churn, ensures identical SQL text regardless of config values, and simplifies EXPLAIN QUERY PLAN analysis.
- **Tightened config validation**: Added upper bounds — `*_half_life_days <= 3650` (10-year safety cap), `reviewer_min_note_chars <= 4096`, and `closed_mr_multiplier` must be finite (not NaN/Inf). These prevent absurd configurations from silently producing nonsensical results.
- **Path canonicalization via `normalize_query_path()`**: Inputs like `./src//foo.rs` or whitespace-padded paths could fail path resolution even when the file exists in the database. A simple syntactic normalization (strip `./`, collapse `//`, trim whitespace, preserve trailing `/`) runs before `build_path_query()` to reduce false negatives. No filesystem or database lookups — purely string manipulation.
- **Probe-optimized `idx_notes_old_path_project_created` index**: The scoring-oriented `idx_notes_old_path_author` index has `author_username` as its second column, which is suboptimal for path resolution probes that don't constrain author. A dedicated probe index on `(position_old_path, project_id, created_at)` ensures `build_path_query()` and `suffix_probe()` old_path lookups are efficient.
- **New tests**: `test_path_normalization_handles_dot_and_double_slash`, `test_path_normalization_preserves_prefix_semantics`, `test_config_validation_rejects_absurd_half_life`, `test_config_validation_rejects_nan_multiplier` — cover the path canonicalization and tightened validation logic.
## Rejected Ideas (with rationale)
These suggestions were considered during review but explicitly excluded from this iteration:
@@ -635,3 +683,6 @@ These suggestions were considered during review but explicitly excluded from thi
- **Full evidence drill-down in `--explain-score`** (feedback-5 #8): Proposes `--explain-score=summary|full` with per-MR evidence rows. Already rejected in feedback-2 #7. Component totals are sufficient for v1 debugging — they answer "which signal type drives this user's score." Per-MR drill-down requires additional SQL queries and significant output format complexity. Deferred unless component breakdowns prove insufficient.
- **Neumaier compensated summation** (feedback-5 #7 partial): Accepted the sorting aspect for deterministic ordering, but rejected Neumaier/Kahan compensated summation. At the scale of dozens to low hundreds of contributions per user, the rounding error from naive f64 summation is on the order of 1e-14 — several orders of magnitude below any meaningful score difference. Compensated summation adds code complexity and a maintenance burden for no practical benefit at this scale.
- **Automated CI benchmark gate** (feedback-5 #10 partial): Accepted manual performance baselines, but rejected automated CI regression gating with synthetic fixtures (100k/1M/5M notes). Building and maintaining benchmark infrastructure is a significant investment that's premature for a CLI tool with ~3 users. Manual timing checks during development are sufficient until performance becomes a real concern.
- **Epsilon-based tie buckets for ranking** (feedback-6 #4) — rejected because the plan already has deterministic contribution ordering by `mr_id` within each signal type, which eliminates HashMap-iteration nondeterminism. Platform-dependent `powf` differences at the scale of dozens to hundreds of contributions per user are sub-epsilon (order of 1e-15). If two users genuinely score within 1e-9 of each other, the existing tiebreak by `(last_seen DESC, username ASC)` is already meaningful and deterministic. Adding a bucketing layer introduces a magic epsilon constant and floor operation for a problem that doesn't manifest in practice.
- **`--diagnose-score` aggregated diagnostics flag** (feedback-6 #5) — rejected because this is diagnostic/debugging tooling that adds a new flag, new output format, and new counting logic (matched_notes_raw_count, dedup_count, window exclusions, etc.) across the SQL pipeline. The existing `--explain-score` component breakdown + manual EXPLAIN QUERY PLAN verification already covers the debugging need. The additional SQL instrumentation required (counting rows at each CTE stage) would complicate the query for a feature with unclear demand. A v2 addition if operational debugging becomes a recurring need.
- **Multi-path expert scoring (`--path` repeatable)** (feedback-6 #7) — rejected because this is a feature expansion, not a plan improvement for the time-decay model. Multi-path requires a `requested_paths` CTE, modified dedup logic keyed on `(username, signal, mr_id)` across paths, CLI parsing changes for repeatable `--path` and `--path-file`, and new test cases for overlap/prefix/dedup semantics. This is a separate bead/feature that should be designed independently — it's orthogonal to time-decay scoring and can be added later without requiring any changes to the decay model.

View File

@@ -0,0 +1,214 @@
I found 9 high-impact revisions that materially improve correctness, robustness, and usability without reintroducing anything in `## Rejected Recommendations`.
### 1. Prevent stale async overwrites on **all** screens (not just search)
Right now, only `SearchExecuted` is generation-guarded. `IssueListLoaded`, `MrListLoaded`, `IssueDetailLoaded`, etc. can still race and overwrite newer state after rapid navigation/filtering. This is the biggest correctness risk in the current design.
```diff
diff --git a/PRD.md b/PRD.md
@@ message.rs
- IssueListLoaded(Vec<IssueRow>),
+ IssueListLoaded { generation: u64, rows: Vec<IssueRow> },
@@
- MrListLoaded(Vec<MrRow>),
+ MrListLoaded { generation: u64, rows: Vec<MrRow> },
@@
- IssueDetailLoaded { key: EntityKey, detail: IssueDetail },
- MrDetailLoaded { key: EntityKey, detail: MrDetail },
+ IssueDetailLoaded { generation: u64, key: EntityKey, detail: IssueDetail },
+ MrDetailLoaded { generation: u64, key: EntityKey, detail: MrDetail },
@@ update()
- Msg::IssueListLoaded(result) => {
+ Msg::IssueListLoaded { generation, rows } => {
+ if !self.task_supervisor.is_current(&TaskKey::LoadScreen(Screen::IssueList), generation) {
+ return Cmd::none();
+ }
self.state.set_loading(false);
- self.state.issue_list.set_result(result);
+ self.state.issue_list.set_result(rows);
Cmd::none()
}
```
### 2. Make cancellation safe with task-owned SQLite interrupt handles
The plan mentions `sqlite3_interrupt()` but uses pooled shared reader connections. Interrupting a shared connection can cancel unrelated work. Use per-task reader leases and store `InterruptHandle` in `TaskHandle`.
```diff
diff --git a/PRD.md b/PRD.md
@@ DbManager
- readers: Vec<Mutex<Connection>>,
+ readers: Vec<Mutex<Connection>>,
+ // task-scoped interrupt handles prevent cross-task cancellation bleed
+ // each dispatched query receives an owned ReaderLease
+pub struct ReaderLease {
+ conn: Connection,
+ interrupt: rusqlite::InterruptHandle,
+}
+
+impl DbManager {
+ pub fn lease_reader(&self) -> Result<ReaderLease, LoreError> { ... }
+}
@@ TaskHandle
pub struct TaskHandle {
pub key: TaskKey,
pub generation: u64,
pub cancel: Arc<CancelToken>,
+ pub interrupt: Option<rusqlite::InterruptHandle>,
}
@@ cancellation
-Query interruption: ... fires sqlite3_interrupt() on the connection.
+Query interruption: cancel triggers the task's owned InterruptHandle only.
+No shared-connection interrupt is permitted.
```
### 3. Harden keyset pagination for multi-project and sort changes
`updated_at + iid` cursor is not enough when rows share timestamps across projects or sort mode changes. This can duplicate/skip rows.
```diff
diff --git a/PRD.md b/PRD.md
@@ issue_list.rs
-pub struct IssueCursor {
- pub updated_at: i64,
- pub iid: i64,
-}
+pub struct IssueCursor {
+ pub sort_field: SortField,
+ pub sort_order: SortOrder,
+ pub updated_at: Option<i64>,
+ pub created_at: Option<i64>,
+ pub iid: i64,
+ pub project_id: i64, // deterministic tie-breaker
+ pub filter_hash: u64, // invalidates stale cursors on filter mutation
+}
@@ pagination section
-Windowed keyset pagination ...
+Windowed keyset pagination uses deterministic tuple ordering:
+`ORDER BY <primary_sort>, project_id, iid`.
+Cursor is rejected if `filter_hash` or sort tuple mismatches current query.
```
### 4. Replace ad-hoc filter parsing with a small typed DSL
Current `split_whitespace()` parser is brittle and silently lossy. Add quoted values, negation, and strict parse errors.
```diff
diff --git a/PRD.md b/PRD.md
@@ filter_bar.rs
- fn parse_tokens(&mut self) {
- let text = self.input.value().to_string();
- self.tokens = text.split_whitespace().map(|chunk| { ... }).collect();
- }
+ fn parse_tokens(&mut self) {
+ // grammar (v1):
+ // term := [ "-" ] (field ":" value | quoted_text | bare_text)
+ // value := quoted | unquoted
+ // examples:
+ // state:opened label:"P1 blocker" -author:bot since:14d
+ self.tokens = filter_dsl::parse(self.input.value())?;
+ }
@@ section 8 / keybindings-help
+Filter parser surfaces actionable inline diagnostics with cursor position,
+and never silently drops unknown fields.
```
### 5. Add render caches for markdown/tree shaping
Markdown and tree shaping are currently recomputed on every frame in several snippets. Cache render artifacts by `(entity, width, theme, content_hash)` to protect frame time.
```diff
diff --git a/PRD.md b/PRD.md
@@ module structure
+ render_cache.rs # Width/theme/content-hash keyed cache for markdown + tree layouts
@@ Assumptions / Performance
+Detail and search preview rendering uses memoized render artifacts.
+Cache invalidation triggers: content hash change, terminal width change, theme change.
```
### 6. Use one-shot timers for debounce/prefix timeout
`Every` is periodic; it wakes repeatedly and can produce edge-case repeated firings. One-shot subscriptions are cleaner and cheaper.
```diff
diff --git a/PRD.md b/PRD.md
@@ subscriptions()
- if self.state.search.debounce_pending() {
- subs.push(Box::new(
- Every::with_id(3, Duration::from_millis(200), move || {
- Msg::SearchDebounceFired { generation }
- })
- ));
- }
+ if self.state.search.debounce_pending() {
+ subs.push(Box::new(
+ After::with_id(3, Duration::from_millis(200), move || {
+ Msg::SearchDebounceFired { generation }
+ })
+ ));
+ }
@@ InputMode GoPrefix timeout
-The tick subscription compares clock instant...
+GoPrefix timeout is a one-shot `After(500ms)` tied to prefix generation.
```
### 7. New feature: list “Quick Peek” panel (`Space`) for triage speed
This adds immediate value without v2-level scope. Users can inspect selected issue/MR metadata/snippet without entering detail and coming back.
```diff
diff --git a/PRD.md b/PRD.md
@@ 5.2 Issue List
-Interaction: Enter detail
+Interaction: Enter detail, Space quick-peek (toggle right preview pane)
@@ 5.4 MR List
+Quick Peek mode mirrors Issue List: metadata + first discussion snippet + cross-refs.
@@ 8.2 List Screens
| `Enter` | Open selected item |
+| `Space` | Toggle Quick Peek panel for selected row |
```
### 8. Upgrade compatibility handshake from integer to machine-readable contract
Single integer compat is too coarse for real drift detection. Keep it simple but structured.
```diff
diff --git a/PRD.md b/PRD.md
@@ Nightly Rust Strategy / Compatibility contract
- 1. Binary compat version (`lore-tui --compat-version`) — integer check ...
+ 1. Binary compat contract (`lore-tui --compat-json`) — JSON:
+ `{ "protocol": 1, "compat_version": 2, "min_schema": 14, "max_schema": 16, "build": "..." }`
+ `lore` validates protocol + compat + schema range before spawn.
@@ CLI integration
-fn validate_tui_compat(...) { ... --compat-version ... }
+fn validate_tui_compat(...) { ... --compat-json ... }
```
### 9. Fix sync stream bug and formalize progress coalescing
The current snippet calls `try_send` for progress twice in one callback path and depth math is wrong. Also progress spam should be coalesced by lane.
```diff
diff --git a/PRD.md b/PRD.md
@@ start_sync_task()
- let current_depth = 2048 - tx.try_send(Msg::SyncProgress(event.clone()))
- .err().map_or(0, |_| 1);
- max_queue_depth = max_queue_depth.max(current_depth);
- if tx.try_send(Msg::SyncProgress(event.clone())).is_err() {
+ // coalesce by lane key at <=30Hz; one send attempt per flush
+ coalescer.update(event.clone());
+ if let Some(batch) = coalescer.flush_ready() {
+ if tx.try_send(Msg::SyncProgressBatch(batch)).is_err() {
dropped_count += 1;
let _ = tx.try_send(Msg::SyncBackpressureDrop);
+ } else {
+ max_queue_depth = max_queue_depth.max(observed_queue_depth());
+ }
}
```
---
If you want, I can produce a single consolidated patch-style rewrite of Sections `4.x`, `5.2/5.4`, `8.2`, `9.3`, and `10.x` so you can drop it directly into iteration 10.

View File

@@ -0,0 +1,177 @@
I reviewed the full PRD and avoided everything listed under `## Rejected Recommendations`.
These are the highest-impact revisions Id make.
1. Stable list pagination via snapshot fences
Why this improves the plan: your keyset cursor is deterministic for sort/filter, but still vulnerable to duplicates/skips if sync writes land between page fetches. Add a per-browse snapshot fence so one browse session sees a stable dataset.
Tradeoff: newest rows are hidden until refresh, which is correct for deterministic triage.
```diff
diff --git a/docs/plans/gitlore-tui-prd-v2.md b/docs/plans/gitlore-tui-prd-v2.md
@@ 5.2 Issue List
- **Pagination:** Windowed keyset pagination with explicit cursor state.
+ **Pagination:** Windowed keyset pagination with explicit cursor state.
+ **Snapshot fence:** On list entry, capture `snapshot_upper_updated_at` (ms) and pin all
+ list-page queries to `updated_at <= snapshot_upper_updated_at`. This guarantees no duplicate
+ or skipped rows during scrolling even if sync writes occur concurrently.
+ A "new data available" badge appears when a newer sync completes; `r` refreshes the fence.
@@ 5.4 MR List
- **Pagination:** Same windowed keyset pagination strategy as Issue List.
+ **Pagination:** Same strategy plus snapshot fence (`updated_at <= snapshot_upper_updated_at`)
+ for deterministic cross-page traversal under concurrent sync writes.
@@ 4.7 Navigation Stack Implementation
+ Browsing sessions carry a per-screen `BrowseSnapshot` token to preserve stable ordering
+ until explicit refresh or screen re-entry.
```
2. Query budgets and soft deadlines
Why this improves the plan: currently “slow query” is handled mostly by cancellation and stale-drop. Add explicit latency budgets so UI responsiveness stays predictable under worst-case filters.
Tradeoff: sometimes user gets partial/truncated results first, followed by full results on retry/refine.
```diff
diff --git a/docs/plans/gitlore-tui-prd-v2.md b/docs/plans/gitlore-tui-prd-v2.md
@@ 4.5 Async Action System
+ #### 4.5.2 Query Budgets and Soft Deadlines
+ Each query type gets a budget:
+ - list window fetch: 120ms target, 250ms hard deadline
+ - detail phase-1 metadata: 75ms target, 150ms hard deadline
+ - search lexical/hybrid: 250ms hard deadline
+ On hard deadline breach, return `QueryDegraded { truncated: true }` and show inline badge:
+ "results truncated; refine filter or press r to retry full".
+ Implementation uses SQLite progress handler + per-task interrupt deadline.
@@ 9.3 Phase 0 — Toolchain Gate
+ 26. Query deadline behavior validated: hard deadline cancels query and renders degraded badge
+ without blocking input loop.
```
3. Targeted cache invalidation and prewarm after sync
Why this improves the plan: `invalidate_all()` after sync throws away hot detail cache and hurts the exact post-sync workflow you optimized for. Invalidate only changed keys and prewarm likely-next entities.
Tradeoff: slightly more bookkeeping in sync result handling.
```diff
diff --git a/docs/plans/gitlore-tui-prd-v2.md b/docs/plans/gitlore-tui-prd-v2.md
@@ 4.1 Module Structure
- entity_cache.rs # Bounded LRU cache ... Invalidated on sync completion.
+ entity_cache.rs # Bounded LRU cache with selective invalidation by changed EntityKey
+ # and optional post-sync prewarm of top changed entities.
@@ 4.4 App — Implementing the Model Trait (Msg::SyncCompleted)
- // Invalidate entity cache — synced data may have changed.
- self.entity_cache.invalidate_all();
+ // Selective invalidation: evict only changed entities from sync delta.
+ self.entity_cache.invalidate_keys(&result.changed_entity_keys);
+ // Prewarm top N changed/new entities for immediate post-sync triage.
+ self.enqueue_cache_prewarm(&result.changed_entity_keys);
```
4. Exact “what changed” navigation without new DB tables
Why this improves the plan: your summary currently uses timestamp filter; this can include unrelated updates and miss edge cases. Keep an in-memory delta ledger per sync run and navigate by exact IDs.
Tradeoff: small memory overhead per run; no schema migration required.
```diff
diff --git a/docs/plans/gitlore-tui-prd-v2.md b/docs/plans/gitlore-tui-prd-v2.md
@@ 5.9 Sync (Summary mode)
-- `i` navigates to Issue List pre-filtered to "since last sync" (using `sync_status.last_completed_at` timestamp comparison)
-- `m` navigates to MR List pre-filtered to "since last sync" (using `sync_status.last_completed_at` timestamp comparison)
+- `i` navigates to Issue List filtered by exact issue IDs changed in this sync run
+- `m` navigates to MR List filtered by exact MR IDs changed in this sync run
+ (fallback to timestamp filter only if run delta not available)
@@ 10.1 New Files
+crates/lore-tui/src/sync_delta_ledger.rs # In-memory per-run exact changed/new IDs (issues/MRs/discussions)
```
5. Adaptive render governor (runtime performance safety)
Why this improves the plan: capability detection is static; you also need dynamic adaptation when frame time/backpressure worsens (SSH, tmux nesting, huge logs).
Tradeoff: visual richness may step down automatically under load.
```diff
diff --git a/docs/plans/gitlore-tui-prd-v2.md b/docs/plans/gitlore-tui-prd-v2.md
@@ 3.4.1 Capability-Adaptive Rendering
+#### 3.4.2 Adaptive Render Governor
+Runtime monitors frame time and stream pressure:
+- if frame p95 > 40ms or sync drops spike, switch to lighter profile:
+ plain markdown, reduced tree guides, slower spinner tick, less frequent repaint.
+- when stable for N seconds, restore previous profile.
+CLI override:
+`lore tui --render-profile=auto|quality|balanced|speed`
@@ 9.3 Phase 0 — Toolchain Gate
+27. Frame-time governor validated: under induced load, UI remains responsive and input latency
+stays within p95 < 75ms while auto-downgrading render profile.
```
6. First-run/data-not-ready screen (not an init wizard)
Why this improves the plan: empty DB or missing indexes will otherwise feel broken. A dedicated read-only readiness screen improves first impression and self-recovery.
Tradeoff: one extra lightweight screen/state.
```diff
diff --git a/docs/plans/gitlore-tui-prd-v2.md b/docs/plans/gitlore-tui-prd-v2.md
@@ 4.3 Core Types (Screen enum)
Sync,
Stats,
Doctor,
+ Bootstrap,
@@ 5.11 Doctor / Stats (Info Screens)
+### 5.12 Bootstrap (Data Readiness)
+Shown when no synced projects/documents are present or required indexes are missing.
+Displays concise readiness checks and exact CLI commands to recover:
+`lore sync`, `lore migrate`, `lore --robot doctor`.
+Read-only; no auto-execution.
```
7. Global project scope pinning across screens
Why this improves the plan: users repeatedly apply the same project filter across dashboard/list/search/timeline/who. Add a global scope pin to reduce repetitive filtering and speed triage.
Tradeoff: must show clear “scope active” indicator to avoid confusion.
```diff
diff --git a/docs/plans/gitlore-tui-prd-v2.md b/docs/plans/gitlore-tui-prd-v2.md
@@ 4.1 Module Structure
+ scope.rs # Global project scope context (all-projects or pinned project set)
@@ 8.1 Global (Available Everywhere)
+| `P` | Open project scope picker / toggle global scope pin |
@@ 4.10 State Module — Complete
+pub global_scope: ScopeContext, // Applies to dashboard/list/search/timeline/who queries
@@ 10.11 Action Module — Query Bridge
- pub fn fetch_issues(conn: &Connection, filter: &IssueFilter) -> Result<Vec<IssueListRow>, LoreError>
+ pub fn fetch_issues(conn: &Connection, scope: &ScopeContext, filter: &IssueFilter) -> Result<Vec<IssueListRow>, LoreError>
```
8. Concurrency correctness tests for pagination and cancellation races
Why this improves the plan: current reliability tests are good, but missing a direct test for duplicate/skip behavior under concurrent sync writes while paginating.
Tradeoff: additional integration test complexity.
```diff
diff --git a/docs/plans/gitlore-tui-prd-v2.md b/docs/plans/gitlore-tui-prd-v2.md
@@ 9.2 Phases (Phase 5.5 — Reliability Test Pack)
+ Concurrent pagination/write race tests :p55j, after p55h, 1d
+ Query deadline cancellation race tests :p55k, after p55j, 0.5d
@@ 9.3 Phase 0 — Toolchain Gate
+28. Concurrent pagination/write test proves no duplicates/skips within a pinned browse snapshot.
+29. Cancellation race test proves no cross-task interrupt bleed and no stuck loading state.
```
9. URL opening policy v2: allowlisted GitLab entity paths
Why this improves the plan: host validation is necessary but not always sufficient. Restrict default browser opens to known GitLab entity paths and require confirmation for unusual paths on same host.
Tradeoff: occasional extra prompt for uncommon but valid URLs.
```diff
diff --git a/docs/plans/gitlore-tui-prd-v2.md b/docs/plans/gitlore-tui-prd-v2.md
@@ 3.1 Risk Matrix
-| Malicious URL in entity data opened in browser | Medium | Low | URL host validated against configured GitLab instance before `open`/`xdg-open` |
+| Malicious URL in entity data opened in browser | Medium | Low | Validate scheme+host+port and path pattern allowlist (`/-/issues/`, `/-/merge_requests/`, project issue/MR routes). Unknown same-host paths require explicit confirm modal. |
@@ 10.4.1 Terminal Safety — Untrusted Text Sanitization
- pub fn is_safe_url(url: &str, allowed_origins: &[AllowedOrigin]) -> bool
+ pub fn classify_safe_url(url: &str, policy: &UrlPolicy) -> UrlSafety
+ // UrlSafety::{AllowedEntityPath, AllowedButUnrecognizedPath, Blocked}
```
These 9 changes are additive, avoid previously rejected ideas, and materially improve determinism, responsiveness, post-sync usefulness, and safety without forcing a big architecture reset.

View File

@@ -2,12 +2,12 @@
plan: true
title: "Gitlore TUI PRD v2 - FrankenTUI"
status: iterating
iteration: 9
iteration: 11
target_iterations: 10
beads_revision: 0
related_plans: []
created: 2026-02-11
updated: 2026-02-11
updated: 2026-02-12
---
# Gitlore TUI — Product Requirements Document
@@ -135,7 +135,7 @@ We are making a deliberate bet that FrankenTUI's technical superiority justifies
| Runtime panic leaves user blocked | High | Medium | Panic hook captures crash context (last 2000 events ring buffer + screen/nav/task/build/db snapshot), restores terminal, offers fallback CLI command. Retention: latest 20 crash files, oldest auto-pruned. |
| Hard-to-reproduce input race bugs | Medium | Medium | Crash context ring buffer includes last 2000 normalized events + current screen + in-flight task keys/generations + build version + DB fingerprint for post-mortem replay |
| Interrupted sync loses partial progress | Medium | Medium | Per-project fault isolation; failed lanes marked degraded while others continue. Resumable checkpoints planned for post-v1 (requires `sync_checkpoints` table). |
| Malicious URL in entity data opened in browser | Medium | Low | URL host validated against configured GitLab instance before `open`/`xdg-open` |
| Malicious URL in entity data opened in browser | Medium | Low | Validate scheme+host+port AND path pattern allowlist (`/-/issues/`, `/-/merge_requests/`, project issue/MR routes) before `open`/`xdg-open`. Unknown same-host paths require explicit confirm modal. |
| Terminal escape/control-sequence injection via issue/note text | High | Medium | Strip ANSI/OSC/control chars + C1 controls (U+0080..U+009F) + bidi overrides + directional marks (LRM/RLM/ALM) via `sanitize_for_terminal()` before render; origin-normalized URL validation before open; disable raw HTML in markdown rendering |
### 3.2 Nightly Rust Strategy
@@ -288,7 +288,9 @@ crates/lore-tui/src/
safety.rs # sanitize_for_terminal(), safe_url_policy()
redact.rs # redact_sensitive(): strip tokens, Authorization headers, and credential patterns from logs and crash reports before persisting to disk
session.rs # Versioned session state persistence + corruption quarantine
entity_cache.rs # Bounded LRU cache for detail payloads (IssueDetail, MrDetail). Keyed by EntityKey. Invalidated on sync completion. Enables near-instant reopen during Enter/Esc drill-in/out workflows without re-querying.
scope.rs # Global project scope context: all-projects or pinned project set. Applied to dashboard/list/search/timeline/who queries. Persisted in session state.
entity_cache.rs # Bounded LRU cache for detail payloads (IssueDetail, MrDetail). Keyed by EntityKey. Selective invalidation by changed EntityKey set on sync completion (not blanket invalidate_all). Optional post-sync prewarm of top changed entities for immediate triage. Enables near-instant reopen during Enter/Esc drill-in/out workflows without re-querying.
render_cache.rs # Width/theme/content-hash keyed cache for expensive render artifacts (markdown → styled text, discussion tree shaping). Invalidation triggers: content hash change, terminal width change, theme change. Prevents per-frame recomputation of markdown parsing and tree layout.
crash_context.rs # Ring buffer of last 2000 normalized events + current screen/task snapshot for crash diagnostics. Captured by panic hook for post-mortem debugging.
```
@@ -359,20 +361,24 @@ pub enum Msg {
CommandPaletteSelect(usize),
// Issue list
IssueListLoaded(Vec<IssueRow>),
/// Generation-guarded: stale results from superseded filter/nav are dropped.
IssueListLoaded { generation: u64, rows: Vec<IssueRow> },
IssueListFilterChanged(IssueFilter),
IssueListSortChanged(SortField, SortOrder),
IssueSelected(EntityKey),
// MR list
MrListLoaded(Vec<MrRow>),
/// Generation-guarded: stale results from superseded filter/nav are dropped.
MrListLoaded { generation: u64, rows: Vec<MrRow> },
MrListFilterChanged(MrFilter),
MrSelected(EntityKey),
// Detail views
IssueDetailLoaded { key: EntityKey, detail: IssueDetail },
MrDetailLoaded { key: EntityKey, detail: MrDetail },
DiscussionsLoaded(Vec<Discussion>),
/// Generation-guarded: prevents stale detail overwrites after rapid navigation.
IssueDetailLoaded { generation: u64, key: EntityKey, detail: IssueDetail },
/// Generation-guarded: prevents stale detail overwrites after rapid navigation.
MrDetailLoaded { generation: u64, key: EntityKey, detail: MrDetail },
DiscussionsLoaded { generation: u64, discussions: Vec<Discussion> },
// Search
SearchQueryChanged(String),
@@ -395,6 +401,9 @@ pub enum Msg {
// Sync
SyncStarted,
SyncProgress(ProgressEvent),
/// Coalesced batch of progress events (one per lane key).
/// Reduces render pressure by batching at <=30Hz per lane.
SyncProgressBatch(Vec<ProgressEvent>),
SyncLogLine(String),
SyncBackpressureDrop,
SyncCompleted(SyncResult),
@@ -454,6 +463,7 @@ pub enum Screen {
Sync,
Stats,
Doctor,
Bootstrap,
}
/// Composite key for entity identity across multi-project datasets.
@@ -553,7 +563,7 @@ impl Default for InputMode {
// crates/lore-tui/src/app.rs
use ftui_runtime::program::{Model, Cmd, TaskSpec};
use ftui_runtime::subscription::{Subscription, Every};
use ftui_runtime::subscription::{Subscription, Every, After};
use ftui_core::event::{Event, KeyEvent, KeyCode, KeyEventKind, Modifiers};
use ftui_render::frame::Frame;
use rusqlite::Connection;
@@ -626,6 +636,20 @@ pub struct DbManager {
next_reader: AtomicUsize,
}
/// A task-scoped reader lease that owns an interrupt handle for safe cancellation.
/// Unlike interrupting a shared pooled connection (which can cancel unrelated work),
/// each dispatched query receives its own ReaderLease. The InterruptHandle stored in
/// TaskHandle targets only this lease's connection, preventing cross-task cancellation bleed.
pub struct ReaderLease<'a> {
conn: std::sync::MutexGuard<'a, Connection>,
/// Owned interrupt handle — safe to fire without affecting other tasks.
pub interrupt: rusqlite::InterruptHandle,
}
impl<'a> ReaderLease<'a> {
pub fn conn(&self) -> &Connection { &self.conn }
}
impl DbManager {
pub fn new(db_path: &Path, reader_count: usize) -> Result<Self, LoreError> {
let mut readers = Vec::with_capacity(reader_count);
@@ -663,6 +687,19 @@ impl DbManager {
.map_err(|e| LoreError::Internal(format!("writer lock poisoned: {e}")))?;
f(&conn)
}
/// Lease a reader connection with a task-owned interrupt handle.
/// The returned `ReaderLease` holds the mutex guard and provides
/// an `InterruptHandle` that can be stored in `TaskHandle` for
/// safe per-task cancellation. This prevents cross-task interrupt bleed
/// that would occur with shared-connection `sqlite3_interrupt()`.
pub fn lease_reader(&self) -> Result<ReaderLease<'_>, LoreError> {
let idx = self.next_reader.fetch_add(1, Ordering::Relaxed) % self.readers.len();
let conn = self.readers[idx].lock()
.map_err(|e| LoreError::Internal(format!("reader lock poisoned: {e}")))?;
let interrupt = conn.get_interrupt_handle();
Ok(ReaderLease { conn, interrupt })
}
}
impl LoreApp {
@@ -786,9 +823,11 @@ impl LoreApp {
}),
Screen::IssueList => {
let filter = self.state.issue_list.current_filter();
let handle = self.task_supervisor.submit(TaskKey::LoadScreen(Screen::IssueList));
let generation = handle.generation;
Cmd::task(move || {
match db.with_reader(|conn| crate::tui::action::fetch_issues(conn, &filter)) {
Ok(result) => Msg::IssueListLoaded(result),
Ok(rows) => Msg::IssueListLoaded { generation, rows },
Err(e) => Msg::Error(AppError::Internal(e.to_string())),
}
})
@@ -797,21 +836,26 @@ impl LoreApp {
// Check entity cache first — enables near-instant reopen
// during Enter/Esc drill-in/out workflows.
if let Some(cached) = self.entity_cache.get_issue(key) {
return Cmd::msg(Msg::IssueDetailLoaded { key: key.clone(), detail: cached.clone() });
let handle = self.task_supervisor.submit(TaskKey::LoadScreen(Screen::IssueDetail(key.clone())));
return Cmd::msg(Msg::IssueDetailLoaded { generation: handle.generation, key: key.clone(), detail: cached.clone() });
}
let handle = self.task_supervisor.submit(TaskKey::LoadScreen(Screen::IssueDetail(key.clone())));
let generation = handle.generation;
let key = key.clone();
Cmd::task(move || {
match db.with_reader(|conn| crate::tui::action::fetch_issue_detail(conn, &key)) {
Ok(detail) => Msg::IssueDetailLoaded { key, detail },
Ok(detail) => Msg::IssueDetailLoaded { generation, key, detail },
Err(e) => Msg::Error(AppError::Internal(e.to_string())),
}
})
}
Screen::MrList => {
let filter = self.state.mr_list.current_filter();
let handle = self.task_supervisor.submit(TaskKey::LoadScreen(Screen::MrList));
let generation = handle.generation;
Cmd::task(move || {
match db.with_reader(|conn| crate::tui::action::fetch_mrs(conn, &filter)) {
Ok(result) => Msg::MrListLoaded(result),
Ok(rows) => Msg::MrListLoaded { generation, rows },
Err(e) => Msg::Error(AppError::Internal(e.to_string())),
}
})
@@ -819,12 +863,15 @@ impl LoreApp {
Screen::MrDetail(key) => {
// Check entity cache first
if let Some(cached) = self.entity_cache.get_mr(key) {
return Cmd::msg(Msg::MrDetailLoaded { key: key.clone(), detail: cached.clone() });
let handle = self.task_supervisor.submit(TaskKey::LoadScreen(Screen::MrDetail(key.clone())));
return Cmd::msg(Msg::MrDetailLoaded { generation: handle.generation, key: key.clone(), detail: cached.clone() });
}
let handle = self.task_supervisor.submit(TaskKey::LoadScreen(Screen::MrDetail(key.clone())));
let generation = handle.generation;
let key = key.clone();
Cmd::task(move || {
match db.with_reader(|conn| crate::tui::action::fetch_mr_detail(conn, &key)) {
Ok(detail) => Msg::MrDetailLoaded { key, detail },
Ok(detail) => Msg::MrDetailLoaded { generation, key, detail },
Err(e) => Msg::Error(AppError::Internal(e.to_string())),
}
})
@@ -895,9 +942,11 @@ impl LoreApp {
Screen::IssueList => {
let filter = self.state.issue_list.current_filter();
let db = Arc::clone(&self.db);
let handle = self.task_supervisor.submit(TaskKey::FilterRequery(Screen::IssueList));
let generation = handle.generation;
Cmd::task(move || {
match db.with_reader(|conn| crate::tui::action::fetch_issues(conn, &filter)) {
Ok(result) => Msg::IssueListLoaded(result),
Ok(rows) => Msg::IssueListLoaded { generation, rows },
Err(e) => Msg::Error(AppError::Internal(e.to_string())),
}
})
@@ -905,9 +954,11 @@ impl LoreApp {
Screen::MrList => {
let filter = self.state.mr_list.current_filter();
let db = Arc::clone(&self.db);
let handle = self.task_supervisor.submit(TaskKey::FilterRequery(Screen::MrList));
let generation = handle.generation;
Cmd::task(move || {
match db.with_reader(|conn| crate::tui::action::fetch_mrs(conn, &filter)) {
Ok(result) => Msg::MrListLoaded(result),
Ok(rows) => Msg::MrListLoaded { generation, rows },
Err(e) => Msg::Error(AppError::Internal(e.to_string())),
}
})
@@ -961,15 +1012,18 @@ impl LoreApp {
if cancel_token.load(std::sync::atomic::Ordering::Relaxed) {
return; // Early exit — orchestrator handles partial state
}
// Track queue depth for stream stats
let current_depth = 2048 - tx.try_send(Msg::SyncProgress(event.clone()))
.err().map_or(0, |_| 1);
max_queue_depth = max_queue_depth.max(current_depth);
if tx.try_send(Msg::SyncProgress(event.clone())).is_err() {
// Channel full — drop this progress update rather than
// blocking the sync thread. Track for stats.
dropped_count += 1;
let _ = tx.try_send(Msg::SyncBackpressureDrop);
// Coalesce progress events by lane key at <=30Hz to reduce
// render pressure. Each lane (project x resource_type) keeps
// only its latest progress snapshot. The coalescer flushes
// a batch when 33ms have elapsed since last flush.
coalescer.update(event.clone());
if let Some(batch) = coalescer.flush_ready() {
if tx.try_send(Msg::SyncProgressBatch(batch)).is_err() {
// Channel full — drop this batch rather than
// blocking the sync thread. Track for stats.
dropped_count += 1;
let _ = tx.try_send(Msg::SyncBackpressureDrop);
}
}
let _ = tx.try_send(Msg::SyncLogLine(format!("{event:?}")));
},
@@ -1143,23 +1197,35 @@ impl Model for LoreApp {
self.state.dashboard.update(data);
Cmd::none()
}
Msg::IssueListLoaded(result) => {
Msg::IssueListLoaded { generation, rows } => {
if !self.task_supervisor.is_current(&TaskKey::LoadScreen(Screen::IssueList), generation) {
return Cmd::none(); // Stale — superseded by newer nav/filter
}
self.state.set_loading(false);
self.state.issue_list.set_result(result);
self.state.issue_list.set_result(rows);
Cmd::none()
}
Msg::IssueDetailLoaded { key, detail } => {
Msg::IssueDetailLoaded { generation, key, detail } => {
if !self.task_supervisor.is_current(&TaskKey::LoadScreen(Screen::IssueDetail(key.clone())), generation) {
return Cmd::none(); // Stale — user navigated away
}
self.state.set_loading(false);
self.entity_cache.put_issue(key, detail.clone());
self.state.issue_detail.set(detail);
Cmd::none()
}
Msg::MrListLoaded(result) => {
Msg::MrListLoaded { generation, rows } => {
if !self.task_supervisor.is_current(&TaskKey::LoadScreen(Screen::MrList), generation) {
return Cmd::none(); // Stale — superseded by newer nav/filter
}
self.state.set_loading(false);
self.state.mr_list.set_result(result);
self.state.mr_list.set_result(rows);
Cmd::none()
}
Msg::MrDetailLoaded { key, detail } => {
Msg::MrDetailLoaded { generation, key, detail } => {
if !self.task_supervisor.is_current(&TaskKey::LoadScreen(Screen::MrDetail(key.clone())), generation) {
return Cmd::none(); // Stale — user navigated away
}
self.state.set_loading(false);
self.entity_cache.put_mr(key, detail.clone());
self.state.mr_detail.set(detail);
@@ -1219,6 +1285,12 @@ impl Model for LoreApp {
self.state.sync.update_progress(event);
Cmd::none()
}
Msg::SyncProgressBatch(events) => {
for event in events {
self.state.sync.update_progress(event);
}
Cmd::none()
}
Msg::SyncLogLine(line) => {
self.state.sync.push_log(line);
Cmd::none()
@@ -1234,10 +1306,15 @@ impl Model for LoreApp {
Cmd::none()
}
Msg::SyncCompleted(result) => {
self.state.sync.complete(result);
// Invalidate entity cache — synced data may have changed.
self.entity_cache.invalidate_all();
Cmd::none()
self.state.sync.complete(&result);
// Selective invalidation: evict only changed entities from sync delta.
self.entity_cache.invalidate_keys(&result.changed_entity_keys);
// Prewarm top N changed/new entities for immediate post-sync triage.
// This is lazy — enqueues Cmd::task fetches, doesn't block the event loop.
let prewarm_cmds = self.enqueue_cache_prewarm(&result.changed_entity_keys);
// Notify list screens that new data is available (snapshot fence refresh badge).
self.state.notify_data_changed();
prewarm_cmds
}
Msg::SyncFailed(err) => {
self.state.sync.fail(err);
@@ -1416,21 +1493,23 @@ impl Model for LoreApp {
));
}
// Go-prefix timeout enforcement: tick even when nothing is loading.
// Without this, GoPrefix mode can get "stuck" when idle (no other
// events to drive the Tick that checks the 500ms timeout).
// Go-prefix timeout: one-shot After(500ms) tied to the prefix start.
// Uses After (one-shot) instead of Every (periodic) — the prefix
// either completes with a valid key or times out exactly once.
if matches!(self.input_mode, InputMode::GoPrefix { .. }) {
subs.push(Box::new(
Every::with_id(2, Duration::from_millis(50), || Msg::Tick)
After::with_id(2, Duration::from_millis(500), || Msg::Tick)
));
}
// Search debounce timer: fires SearchDebounceFired after 200ms.
// Search debounce timer: one-shot fires SearchDebounceFired after 200ms.
// Only active when a debounce is pending (armed by keystroke).
// Uses After (one-shot) instead of Every (periodic) to avoid repeated
// firings from a periodic timer — one debounce = one fire.
if self.state.search.debounce_pending() {
let generation = self.state.search.debounce_generation();
subs.push(Box::new(
Every::with_id(3, Duration::from_millis(200), move || {
After::with_id(3, Duration::from_millis(200), move || {
Msg::SearchDebounceFired { generation }
})
));
@@ -1485,7 +1564,7 @@ pub fn with_read_snapshot<T>(
}
```
**Query interruption:** Long-running queries register interrupt checks tied to `CancelToken` to avoid >1s uninterruptible stalls during rapid navigation/filtering. When the user navigates away from a detail screen before queries complete, the cancel token fires `sqlite3_interrupt()` on the connection.
**Query interruption:** Long-running queries use task-owned `ReaderLease` interrupt handles (from `DbManager::lease_reader()`) to avoid >1s uninterruptible stalls during rapid navigation/filtering. When the user navigates away from a detail screen before queries complete, the `TaskHandle`'s owned `InterruptHandle` fires `sqlite3_interrupt()` on that specific leased connection — never on a shared pool connection. This prevents cross-task cancellation bleed where interrupting one query accidentally cancels an unrelated query on the same pooled connection.
#### 4.5.1 Task Supervisor (Dedup + Cancellation + Priority)
@@ -1549,6 +1628,10 @@ pub struct TaskHandle {
pub key: TaskKey,
pub generation: u64,
pub cancel: Arc<CancelToken>,
/// Per-task SQLite interrupt handle. When set, cancellation fires
/// this handle instead of interrupting shared pool connections.
/// Prevents cross-task cancellation bleed.
pub interrupt: Option<rusqlite::InterruptHandle>,
}
/// The TaskSupervisor manages active tasks, deduplicates by key, and tracks
@@ -1756,6 +1839,11 @@ pub struct NavigationStack {
/// This mirrors vim's jump list behavior.
jump_list: Vec<Screen>,
jump_index: usize,
/// Browse snapshot token: each list/search screen carries a per-screen
/// `BrowseSnapshot` that preserves stable ordering until explicit refresh
/// or screen re-entry. This works with the snapshot fence to ensure
/// deterministic pagination during concurrent sync writes.
browse_snapshots: HashMap<ScreenKind, BrowseSnapshot>,
}
impl NavigationStack {
@@ -1979,9 +2067,21 @@ Insights are computed from local data during dashboard load. Each insight row is
**Data source:** `lore issues` query against SQLite
**Columns:** Configurable — iid, title, state, author, labels, milestone, updated_at
**Sorting:** Click column header or Tab to cycle (iid, updated, created)
**Filtering:** Interactive filter bar with field:value syntax
**Filtering:** Interactive filter bar with typed DSL parser. Grammar (v1):
- `term := [ "-" ] (field ":" value | quoted_text | bare_text)`
- `value := quoted | unquoted`
- Examples: `state:opened label:"P1 blocker" -author:bot since:14d`
- Negation prefix (`-`) excludes matches for that term
- Quoted values allow spaces in filter values
- Parser surfaces inline diagnostics with cursor position for parse errors — never silently drops unknown fields
**Pagination:** Windowed keyset pagination with explicit cursor state. The list state maintains `window` (current visible rows), `next_cursor` / `prev_cursor` (keyset boundary values for forward/back navigation), `prefetching` flag (background fetch of next window in progress), and a fixed `window_size` (default 200 rows). First paint uses current window only; no full-result materialization. Virtual scrolling within the window for smooth UX. When the user scrolls past ~80% of the window, the next window is prefetched in the background.
**Snapshot fence:** On list entry, capture `snapshot_upper_updated_at` (current max `updated_at` in the result set) and pin all list-page queries to `updated_at <= snapshot_upper_updated_at`. This guarantees no duplicate or skipped rows during scrolling even if sync writes occur concurrently. A "new data available" badge appears when a newer sync completes; `r` refreshes the fence and re-queries from the top.
**Quick Peek (`Space`):** Toggle a right-side preview pane showing the selected item's metadata, first discussion snippet, and cross-references without entering the full detail view. This enables rapid triage scanning — the user can evaluate issues at a glance without the Enter/Esc cycle. The peek pane uses the same progressive hydration as detail views (metadata first, discussions lazy). The pane width adapts to terminal breakpoints (hidden at Xs/Sm, 40% width at Md+).
**Cursor determinism:** Keyset pagination uses deterministic tuple ordering: `ORDER BY <primary_sort>, project_id, iid`. The cursor struct includes the current `sort_field`, `sort_order`, `project_id` (tie-breaker for multi-project datasets where rows share timestamps), and a `filter_hash: u64` (hash of the active filter state). On cursor resume, the cursor is rejected if `filter_hash` or sort tuple mismatches the current query — this prevents stale cursors from producing duplicate/skipped rows after the user changes sort mode or filters mid-browse.
### 5.3 Issue Detail
```
@@ -2052,7 +2152,9 @@ Identical structure to Issue List with MR-specific columns:
| Author | MR author |
| Updated | Relative time |
**Pagination:** Same windowed keyset pagination strategy as Issue List (window=200, background prefetch).
**Pagination:** Same windowed keyset pagination strategy as Issue List (window=200, background prefetch, deterministic cursor with `project_id` tie-breaker and `filter_hash` invalidation). Same snapshot fence (`updated_at <= snapshot_upper_updated_at`) for deterministic cross-page traversal under concurrent sync writes.
**Quick Peek (`Space`):** Same as Issue List — toggle right preview pane showing MR metadata, first discussion snippet, and cross-references for rapid triage without entering detail view.
**Additional filters:** `--draft`, `--no-draft`, `--target-branch`, `--source-branch`, `--reviewer`
@@ -2294,8 +2396,8 @@ The Sync screen has two modes: **running** (progress + log) and **summary** (pos
**Summary mode:**
- Shows delta counts (new, updated) for each entity type
- `i` navigates to Issue List pre-filtered to "since last sync" (using `sync_status.last_completed_at` timestamp comparison)
- `m` navigates to MR List pre-filtered to "since last sync" (using `sync_status.last_completed_at` timestamp comparison)
- `i` navigates to Issue List filtered by exact issue IDs changed in this sync run (from in-memory `SyncDeltaLedger`). Falls back to timestamp filter via `sync_status.last_completed_at` only if run delta is not available (e.g., after app restart).
- `m` navigates to MR List filtered by exact MR IDs changed in this sync run (from in-memory `SyncDeltaLedger`). Falls back to timestamp filter only if run delta is not available.
- `r` restarts sync
### 5.10 Command Palette (Overlay)
@@ -2349,6 +2451,21 @@ The Sync screen has two modes: **running** (progress + log) and **summary** (pos
- Does NOT auto-execute commands — the user always runs them manually for safety
- Scrollable with j/k, Esc to go back
### 5.12 Bootstrap (Data Readiness)
Shown automatically when the TUI detects no synced projects/documents or required indexes are missing. This is a read-only screen — it never auto-executes commands.
Displays concise readiness checks with pass/fail indicators:
- Synced projects present?
- Issues/MRs populated?
- FTS index built?
- Embedding index built? (optional — warns but doesn't block)
- Required migration version met?
For each failing check, shows the exact CLI command to recover (e.g., `lore sync`, `lore migrate`, `lore --robot doctor`). The user exits the TUI and runs the commands manually.
This prevents the "blank screen" first-run experience where a user launches `lore tui` before syncing data and sees an empty dashboard with no indication of what to do next.
---
## 6. User Flows
@@ -2483,8 +2600,8 @@ graph TD
style F fill:#51cf66,stroke:#333,color:#fff
```
**Keystrokes:** `i``j/k` to scan → `Enter` to peek`Esc` to return → continue scanning
**State preservation:** After pressing Esc from Issue Detail, the cursor returns to exactly the same row in the list. Filter state and scroll offset are preserved. This tight Enter/Esc loop is the most common daily workflow.
**Keystrokes:** `i``j/k` to scan → `Space` to Quick Peek (or `Enter` for full detail)`Esc` to return → continue scanning
**State preservation:** After pressing Esc from Issue Detail, the cursor returns to exactly the same row in the list. Filter state and scroll offset are preserved. This tight Enter/Esc loop is the most common daily workflow. Quick Peek (`Space`) makes triage even faster — preview metadata and first discussion snippet without leaving the list.
### 6.8 Flow: "Jump between screens without returning to Dashboard"
@@ -2591,6 +2708,7 @@ graph TD
| `Ctrl+O` | Jump backward in jump list (entity hops) |
| `Alt+o` | Jump forward in jump list (entity hops) |
| `Ctrl+R` | Reset session state for current screen (clear filters, scroll to top) |
| `P` | Open project scope picker / toggle global scope pin. When a scope is pinned, all list/search/timeline/who queries are filtered to that project set. A visible `[scope: project/path]` indicator appears in the status bar. |
| `Ctrl+C` | Quit (force) |
### 8.2 List Screens (Issues, MRs, Search Results)
@@ -2600,6 +2718,7 @@ graph TD
| `j` / `↓` | Move selection down |
| `k` / `↑` | Move selection up |
| `Enter` | Open selected item |
| `Space` | Toggle Quick Peek panel for selected row |
| `G` | Jump to bottom |
| `g` `g` | Jump to top |
| `Tab` / `f` | Focus filter bar |
@@ -2614,7 +2733,7 @@ graph TD
3. Global shortcuts — `q`, `H`, `?`, `o`, `Ctrl+C`, `Ctrl+P`, `Esc`, `g` prefix
4. Screen-local shortcuts — per-screen key handlers (the table above)
**Go-prefix timeout:** 500ms from first `g` press, enforced by `InputMode::GoPrefix { started_at }` state checked on each tick via `clock.now_instant()`. If no valid continuation key arrives within 500ms, the prefix cancels and a brief "g--" flash clears from the status bar. The tick subscription compares the injected Clock's current instant against `started_at` — no separate timer task needed. Using `InputMode` instead of ad-hoc boolean flags makes the state machine explicit and deterministic. Feedback is immediate — the status bar shows "g--" within the same frame as the keypress.
**Go-prefix timeout:** 500ms from first `g` press, enforced by a one-shot `After(500ms)` subscription tied to the prefix generation. If no valid continuation key arrives within 500ms, the timer fires a single `Msg::Tick` which checks `InputMode::GoPrefix { started_at }` via `clock.now_instant()` and cancels the prefix. A brief "g--" flash clears from the status bar. Using `After` (one-shot) instead of `Every` (periodic) avoids unnecessary repeated ticks. Using `InputMode` instead of ad-hoc boolean flags makes the state machine explicit and deterministic. Feedback is immediate — the status bar shows "g--" within the same frame as the keypress.
**Terminal keybinding safety notes:**
- `Ctrl+I` is NOT used — it is indistinguishable from `Tab` in most terminals (both send `\x09`). Jump-forward uses `Alt+o` instead.
@@ -2783,6 +2902,8 @@ gantt
Event fuzz tests (key/resize/paste, deterministic seed replay):p55g, after p55e, 1d
Deterministic clock/render tests:p55i, after p55g, 0.5d
30-minute soak test (no panic/leak):p55h, after p55i, 1d
Concurrent pagination/write race tests :p55j, after p55h, 1d
Query cancellation race tests :p55k, after p55j, 0.5d
section Phase 5.6 — CLI/TUI Parity Pack
Dashboard count parity tests :p56a, after p55h, 0.5d
@@ -2802,7 +2923,7 @@ Ensures the TUI displays the same data as the CLI robot mode, preventing drift b
**Success criterion:** Parity suite passes on CI fixtures (S and M tiers). Parity is asserted by field-level comparison, not string formatting comparison — the TUI and CLI may format differently but must present the same underlying data.
**Total estimated scope:** ~47 implementation days across 9 phases (increased from ~43 to account for Phase 2.5 vertical slice gate, entity cache, crash context ring buffer, timer-based debounce, and expanded success criteria 24-25).
**Total estimated scope:** ~51 implementation days across 9 phases (increased from ~49 to account for snapshot fences, sync delta ledger, bootstrap screen, global scope pinning, concurrent pagination/write race tests, and cancellation race tests).
### 9.3 Phase 0 — Toolchain Gate
@@ -2848,6 +2969,8 @@ This is a hard gate. If Phase 0 fails, we evaluate alternatives before proceedin
23. Single-instance lock enforced: second TUI launch attempt yields clear error message and non-zero exit.
24. Sync stream stats are emitted and rendered; terminal events (completed/failed/cancelled) delivery is 100% under induced backpressure.
25. Entity cache provides near-instant reopen for Issue/MR detail views during Enter/Esc drill-in/out workflows; cache invalidated on sync completion.
26. Concurrent pagination/write race test proves no duplicate or skipped rows within a pinned browse snapshot fence under concurrent sync writes.
27. Cancellation race test proves no cross-task interrupt bleed and no stuck loading state after rapid cancel-then-resubmit sequences.
**Performance SLO rationale:** Interactive TUI responsiveness requires sub-100ms for list operations and sub-250ms for search. Tiered fixtures catch scaling regressions at different data magnitudes — a query that's fast at 10k rows may degrade at 100k without proper indexing or pagination. Memory ceilings prevent unbounded growth from large in-memory result sets. These targets are validated with synthetic SQLite fixtures during Phase 0 and enforced as CI benchmark gates thereafter. Required indexes are documented and migration-backed before TUI GA.
@@ -2912,7 +3035,12 @@ crates/lore-tui/src/theme.rs # ftui Theme config
crates/lore-tui/src/action.rs # Query bridge functions (uses lore core)
crates/lore-tui/src/db_manager.rs # DbManager: closure-based read pool (with_reader) + dedicated writer (with_writer). Prevents lock-poison panics and accidental long-held guards.
crates/lore-tui/src/task_supervisor.rs # TaskSupervisor: unified submit() → TaskHandle API with dedup, cancellation, generation IDs, and priority lanes
crates/lore-tui/src/entity_cache.rs # Bounded LRU cache for IssueDetail/MrDetail payloads. Keyed by EntityKey. Invalidated on sync completion. Enables near-instant reopen during Enter/Esc drill-in/out workflows.
crates/lore-tui/src/entity_cache.rs # Bounded LRU cache for IssueDetail/MrDetail payloads. Keyed by EntityKey. Selective invalidation by changed EntityKey set (not blanket invalidate_all). Optional post-sync prewarm of top changed entities. Enables near-instant reopen during Enter/Esc drill-in/out workflows.
crates/lore-tui/src/render_cache.rs # Width/theme/content-hash keyed cache for expensive render artifacts (markdown → styled text, discussion tree shaping). Prevents per-frame recomputation.
crates/lore-tui/src/filter_dsl.rs # Typed filter bar DSL parser: quoted values, negation prefix, field:value syntax, inline diagnostics with cursor position. Replaces brittle split_whitespace() parsing.
crates/lore-tui/src/progress_coalescer.rs # Per-lane progress event coalescer. Batches progress updates at <=30Hz per lane key (project x resource_type) to reduce render pressure during sync.
crates/lore-tui/src/sync_delta_ledger.rs # In-memory per-run exact changed/new entity IDs (issues, MRs, discussions). Populated from SyncCompleted result. Used by Sync Summary mode for exact "what changed" navigation without new DB tables. Cleared on next sync run start.
crates/lore-tui/src/scope.rs # Global project scope context (AllProjects or pinned project set). Flows through all query bridge functions. Persisted in session state. `P` keybinding opens scope picker overlay.
crates/lore-tui/src/crash_context.rs # Ring buffer of last 2000 normalized events + current screen/task/build snapshot. Captured by panic hook for post-mortem crash diagnostics with retention policy (latest 20 files).
crates/lore-tui/src/safety.rs # sanitize_for_terminal(), safe_url_policy()
crates/lore-tui/src/redact.rs # redact_sensitive(): strip tokens, Authorization headers, and credential patterns from logs and crash reports before persisting
@@ -3389,25 +3517,56 @@ pub fn sanitize_for_terminal(input: &str) -> String {
output
}
/// Validate a URL against the configured GitLab origin(s) before opening.
/// Enforces scheme + normalized host + port match to prevent deceptive variants
/// (e.g., IDN homograph attacks, unexpected port redirects).
pub fn is_safe_url(url: &str, allowed_origins: &[AllowedOrigin]) -> bool {
let Ok(parsed) = url::Url::parse(url) else { return false };
/// Classify a URL's safety level against the configured GitLab origin(s) and
/// known entity path patterns before opening in browser.
/// Returns tri-state: AllowedEntityPath (open immediately), AllowedButUnrecognizedPath
/// (prompt user to confirm), or Blocked (refuse to open).
pub fn classify_safe_url(url: &str, policy: &UrlPolicy) -> UrlSafety {
let Ok(parsed) = url::Url::parse(url) else { return UrlSafety::Blocked };
// Only allow HTTPS
if parsed.scheme() != "https" { return false; }
if parsed.scheme() != "https" { return UrlSafety::Blocked; }
// Normalize host (lowercase, IDNA-compatible) and match scheme+host+port
let Some(host) = parsed.host_str() else { return false; };
let Some(host) = parsed.host_str() else { return UrlSafety::Blocked; };
let host_lower = host.to_ascii_lowercase();
let port = parsed.port_or_known_default();
allowed_origins.iter().any(|origin| {
let origin_match = policy.allowed_origins.iter().any(|origin| {
origin.scheme == "https"
&& origin.host == host_lower
&& origin.port == port
})
});
if !origin_match {
return UrlSafety::Blocked;
}
// Check path against known GitLab entity patterns
let path = parsed.path();
if policy.entity_path_patterns.iter().any(|pat| pat.matches(path)) {
UrlSafety::AllowedEntityPath
} else {
UrlSafety::AllowedButUnrecognizedPath
}
}
/// Tri-state URL safety classification.
#[derive(Debug, Clone, PartialEq)]
pub enum UrlSafety {
/// Known GitLab entity path — open immediately without prompt.
AllowedEntityPath,
/// Same host but unrecognized path — show confirmation modal before opening.
AllowedButUnrecognizedPath,
/// Different host, wrong scheme, or parse failure — refuse to open.
Blocked,
}
/// URL validation policy: allowed origins + known GitLab entity path patterns.
pub struct UrlPolicy {
pub allowed_origins: Vec<AllowedOrigin>,
/// Path patterns for known GitLab entity routes (e.g., `/-/issues/`, `/-/merge_requests/`).
pub entity_path_patterns: Vec<PathPattern>,
}
/// Typed origin for URL validation (scheme + normalized host + port).
@@ -4285,6 +4444,7 @@ pub struct AppState {
pub command_palette: CommandPaletteState,
// Cross-cutting state
pub global_scope: ScopeContext, // Applies to dashboard/list/search/timeline/who queries. Default: AllProjects.
pub load_state: ScreenLoadStateMap,
pub error_toast: Option<String>,
pub show_help: bool,
@@ -5445,15 +5605,20 @@ pub fn fetch_dashboard(conn: &Connection) -> Result<DashboardData, LoreError> {
}
/// Fetch issues, converting TUI IssueFilter → CLI ListFilters.
/// The `scope` parameter applies global project pinning — when a scope is active,
/// it overrides any per-filter project selection, ensuring cross-screen consistency.
pub fn fetch_issues(
conn: &Connection,
scope: &ScopeContext,
filter: &IssueFilter,
) -> Result<Vec<IssueListRow>, LoreError> {
// Convert TUI filter to CLI filter format.
// The CLI already has query_issues() — we just need to bridge the types.
// Global scope overrides per-filter project when active.
let effective_project = scope.effective_project(filter.project.as_deref());
let cli_filter = ListFilters {
limit: filter.limit,
project: filter.project.as_deref(),
project: effective_project.as_deref(),
state: filter.state.as_deref(),
author: filter.author.as_deref(),
assignee: filter.assignee.as_deref(),
@@ -7806,3 +7971,13 @@ Recommendations from external review (feedback-8, ChatGPT) that were evaluated a
Recommendations from external review (feedback-9, ChatGPT) that were evaluated and declined:
- **Search Facets panel (entity type counts, top labels/projects/authors with one-key apply)** — rejected as feature scope expansion for v1. The concept (three-pane layout with facet counts and quick-apply shortcuts like `1/2/3` for type facets, `l` for label cycling) is compelling and would make search more actionable for triage workflows. However, it requires: new aggregate queries for facet counting that must perform well across all three data tiers, a third layout pane that breaks the current two-pane split design, new keybinding slots (`1/2/3/l`) that could conflict with future list navigation, and per-query facet recalculation that adds latency. The existing search with explicit field-based filters is sufficient for v1. Facets are a strong v2 candidate — once search has production mileage and users report wanting faster triage filtering, the aggregate query patterns and UI layout can be designed with real usage data.
Recommendations from external review (feedback-10, ChatGPT) that were evaluated and declined:
- **Structured compat handshake (`--compat-json` replacing `--compat-version` integer)** — rejected because the current two-step contract (integer compat version + separate schema version check) is intentionally minimal and robust. Adding JSON parsing (`{ "protocol": 1, "compat_version": 2, "min_schema": 14, "max_schema": 16, "build": "..." }`) to a preflight binary validation introduces a new failure mode (malformed JSON, missing fields, version parsing) for zero user-visible benefit. The integer check detects "too old to work" — the only case that matters before spawning the TUI. Schema range is already validated separately via `--check-schema`. Combining both into a single JSON response couples concerns that are better kept independent (binary compat vs schema compat). The current approach is more resilient: if `--compat-version` is missing (old binary), we warn and proceed; JSON parsing failure would be a hard error. KISS principle applies.
Recommendations from external review (feedback-11, ChatGPT) that were evaluated and declined:
- **Query budgets and soft deadlines (120ms/250ms hard deadlines with `QueryDegraded` truncation)** — rejected as over-engineering for a local SQLite tool. The proposal adds per-query-type latency budgets (list: 250ms, detail: 150ms, search: 250ms hard deadline) with SQLite progress handler interrupts and inline "results truncated" badges. This papers over slow queries with UX complexity rather than fixing the root cause. If a list query exceeds 250ms on a local SQLite database, the correct fix is adding an index or optimizing the query plan — not truncating results and showing a retry badge. The existing cancellation + stale-drop system already handles the interactive case (user navigates away before query completes). SQLite progress handlers are also tricky to implement correctly — they fire on every VM instruction, adding overhead to all queries, and the cancellation semantics interact poorly with SQLite's transaction semantics. The complexity-to-benefit ratio is wrong for a single-user local tool. If specific queries are slow, we fix them at the query/index level (Section 9.3.1 already documents required covering indexes).
- **Adaptive render governor (runtime frame-time monitoring with automatic profile downgrading)** — rejected for the same reason as feedback-3's SLO telemetry and runtime monitoring proposals. The proposal adds a frame-time p95 sliding window, stream pressure detection, automatic profile switching (quality/balanced/speed), hysteresis for recovery, and a `--render-profile` CLI flag. This is appropriate for a multi-user rendering engine or game, not a single-user TUI. The capability detection in Section 3.4.1 already handles the static case (detect terminal capabilities, choose appropriate rendering). If the TUI is slow in tmux or over SSH, the user can pass `--ascii` or reduce their terminal size. Adding a runtime monitoring system with automatic visual degradation introduces a state machine, requires frame-time measurement infrastructure, needs hysteresis tuning to avoid flapping, and must be tested across all the profiles it can switch between. This is significant complexity for an edge case that affects one user once and is solved by a flag. The `--render-profile` flag itself is a reasonable addition as a static override — but the dynamic adaptation runtime is rejected.