Compare commits
108 Commits
f267578aab
...
trace
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
171260a772 | ||
|
|
a1bca10408 | ||
|
|
491dc52864 | ||
|
|
b9063aa17a | ||
|
|
fc0d9cb1d3 | ||
|
|
c8b47bf8f8 | ||
|
|
a570327a6b | ||
|
|
eef73decb5 | ||
|
|
bb6660178c | ||
|
|
64e73b1cab | ||
|
|
361757568f | ||
|
|
8572f6cc04 | ||
|
|
d0744039ef | ||
|
|
4b372dfb38 | ||
|
|
af8fc4af76 | ||
|
|
96b288ccdd | ||
|
|
d710403567 | ||
|
|
ebf64816c9 | ||
|
|
450951dee1 | ||
|
|
81f049a7fa | ||
|
|
dd00a2b840 | ||
|
|
c6a5461d41 | ||
|
|
a7f86b26e4 | ||
|
|
5ee8b0841c | ||
|
|
7062a3f1fd | ||
|
|
159c490ad7 | ||
|
|
e0041ed4d9 | ||
|
|
a34751bd47 | ||
|
|
0aecbf33c0 | ||
|
|
c10471ddb9 | ||
|
|
cbce4c9f59 | ||
|
|
94435c37f0 | ||
|
|
59f65b127a | ||
|
|
f36e900570 | ||
|
|
e2efc61beb | ||
|
|
2da1a228b3 | ||
|
|
0e65202778 | ||
|
|
f439c42b3d | ||
|
|
4f3ec72923 | ||
|
|
e6771709f1 | ||
|
|
8c86b0dfd7 | ||
|
|
6e55b2470d | ||
|
|
b05922d60b | ||
|
|
11fe02fac9 | ||
|
|
48fbd4bfdb | ||
|
|
9786ef27f5 | ||
|
|
7e0e6a91f2 | ||
|
|
5c2df3df3b | ||
|
|
94c8613420 | ||
|
|
ad4dd6e855 | ||
|
|
83cd16c918 | ||
|
|
fda9cd8835 | ||
|
|
c8d609ab78 | ||
|
|
35c828ba73 | ||
|
|
ecbfef537a | ||
|
|
47eecce8e9 | ||
|
|
b29c382583 | ||
|
|
e26816333f | ||
|
|
f772de8aef | ||
|
|
dd4d867c6e | ||
|
|
ffd074499a | ||
|
|
125938fba6 | ||
|
|
cd25cf61ca | ||
|
|
d9c9f6e541 | ||
|
|
acc5e12e3d | ||
|
|
039ab1c2a3 | ||
|
|
d63d6f0b9c | ||
|
|
3a1307dcdc | ||
|
|
6ea3108a20 | ||
|
|
81647545e7 | ||
|
|
39a832688d | ||
|
|
06229ce98b | ||
|
|
8d18552298 | ||
|
|
f3788eb687 | ||
|
|
e9af529f6e | ||
|
|
70271c14d6 | ||
|
|
d9f99ef21d | ||
|
|
f5967a8e52 | ||
|
|
2c9de1a6c3 | ||
|
|
1161edb212 | ||
|
|
5ea976583e | ||
|
|
dcfd449b72 | ||
|
|
6b75697638 | ||
|
|
dc49f5209e | ||
|
|
7d40a81512 | ||
|
|
4185abe05d | ||
|
|
d54f669c5e | ||
|
|
45126f04a6 | ||
|
|
dfa44e5bcd | ||
|
|
53ef21d653 | ||
|
|
41504b4941 | ||
|
|
d36850f181 | ||
|
|
5ce18e0ebc | ||
|
|
b168a58134 | ||
|
|
b704e33188 | ||
|
|
6e82f723c3 | ||
|
|
940a96375a | ||
|
|
7dd86d5433 | ||
|
|
429c6f07d2 | ||
|
|
754efa4369 | ||
|
|
c54a969269 | ||
|
|
95b7183add | ||
|
|
435a208c93 | ||
|
|
cc11d3e5a0 | ||
|
|
5786d7f4b6 | ||
|
|
d3306114eb | ||
|
|
e6b880cbcb | ||
|
|
121a634653 |
232
.beads/.br_history/issues.20260212_161438.jsonl
Normal file
232
.beads/.br_history/issues.20260212_161438.jsonl
Normal file
File diff suppressed because one or more lines are too long
295
.beads/.br_history/issues.20260212_171003.jsonl
Normal file
295
.beads/.br_history/issues.20260212_171003.jsonl
Normal file
File diff suppressed because one or more lines are too long
304
.beads/.br_history/issues.20260212_171103.jsonl
Normal file
304
.beads/.br_history/issues.20260212_171103.jsonl
Normal file
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1 +1 @@
|
||||
bd-1q8z
|
||||
bd-1sc6
|
||||
|
||||
17
.claude/hooks/on-file-write.sh
Executable file
17
.claude/hooks/on-file-write.sh
Executable file
@@ -0,0 +1,17 @@
|
||||
#!/bin/bash
|
||||
# Ultimate Bug Scanner - Claude Code Hook
|
||||
# Runs on every file save for UBS-supported languages (JS/TS, Python, C/C++, Rust, Go, Java, Ruby)
|
||||
# Claude Code hooks receive context as JSON on stdin.
|
||||
|
||||
INPUT=$(cat)
|
||||
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
|
||||
CWD=$(echo "$INPUT" | jq -r '.cwd // empty')
|
||||
|
||||
if [[ "$FILE_PATH" =~ \.(js|jsx|ts|tsx|mjs|cjs|py|pyw|pyi|c|cc|cpp|cxx|h|hh|hpp|hxx|rs|go|java|rb)$ ]]; then
|
||||
echo "🔬 Running bug scanner..."
|
||||
if ! command -v ubs >/dev/null 2>&1; then
|
||||
echo "⚠️ 'ubs' not found in PATH; install it before using this hook." >&2
|
||||
exit 0
|
||||
fi
|
||||
ubs "$FILE_PATH" --ci 2>&1 | head -50
|
||||
fi
|
||||
99
.claude/plan.md
Normal file
99
.claude/plan.md
Normal file
@@ -0,0 +1,99 @@
|
||||
# Plan: Add Colors to Sync Command Output
|
||||
|
||||
## Current State
|
||||
|
||||
The sync output has three layers, each needing color treatment:
|
||||
|
||||
### Layer 1: Stage Lines (during sync)
|
||||
```
|
||||
✓ Issues 10 issues from 2 projects 4.2s
|
||||
✓ Status 3 statuses updated · 5 seen 4.2s
|
||||
vs/typescript-code 2 issues · 1 statuses updated
|
||||
✓ MRs 5 merge requests from 2 projects 12.3s
|
||||
vs/python-code 3 MRs · 10 discussions
|
||||
✓ Docs 1,200 documents generated 8.1s
|
||||
✓ Embed 3,400 chunks embedded 45.2s
|
||||
```
|
||||
|
||||
**What's uncolored:** icons, labels, numbers, elapsed times, sub-row project paths, failure counts in parentheses.
|
||||
|
||||
### Layer 2: Summary (after sync)
|
||||
```
|
||||
Synced 10 issues and 5 MRs in 42.3s
|
||||
120 discussions · 45 events · 12 diffs · 3 statuses updated
|
||||
1,200 docs regenerated · 3,400 embedded
|
||||
```
|
||||
|
||||
**What's already colored:** headline ("Synced" = green bold, "Sync completed with issues" = warning bold), issue/MR counts (bold), error line (red). Detail lines are all dim.
|
||||
|
||||
### Layer 3: Timing breakdown (`-t` flag)
|
||||
```
|
||||
── Timing ──────────────────────
|
||||
issues .............. 4.2s
|
||||
merge_requests ...... 12.3s
|
||||
```
|
||||
|
||||
**What's already colored:** dots (dim), time (bold), errors (red), rate limits (warning).
|
||||
|
||||
---
|
||||
|
||||
## Color Plan
|
||||
|
||||
Using only existing `Theme` methods — no new colors needed.
|
||||
|
||||
### Stage Lines (`format_stage_line` + callers in sync.rs)
|
||||
|
||||
| Element | Current | Proposed | Theme method |
|
||||
|---------|---------|----------|-------------|
|
||||
| Icon (✓/⚠) | plain | green for success, yellow for warning | `Theme::success()` / `Theme::warning()` |
|
||||
| Label ("Issues", "MRs", etc.) | plain | bold | `Theme::bold()` |
|
||||
| Numbers in summary text | plain | bold | `Theme::bold()` (just the count) |
|
||||
| Elapsed time | plain | muted gray | `Theme::timing()` |
|
||||
| Failure text in parens | plain | warning/error color | `Theme::warning()` |
|
||||
|
||||
### Sub-rows (project breakdown lines)
|
||||
|
||||
| Element | Current | Proposed |
|
||||
|---------|---------|----------|
|
||||
| Project path | dim | `Theme::muted()` (slightly brighter than dim) |
|
||||
| Counts (numbers only) | dim | `Theme::dim()` but numbers in normal weight |
|
||||
| Error/failure counts | dim | `Theme::warning()` |
|
||||
| Middle dots | dim | keep dim (they're separators, should recede) |
|
||||
|
||||
### Summary (`print_sync`)
|
||||
|
||||
| Element | Current | Proposed |
|
||||
|---------|---------|----------|
|
||||
| Issue/MR counts in headline | bold only | `Theme::info()` + bold (cyan numbers pop) |
|
||||
| Time in headline | plain | `Theme::timing()` |
|
||||
| Detail line numbers | all dim | numbers in `Theme::info()`, rest stays dim |
|
||||
| Doc line numbers | all dim | numbers in `Theme::info()`, rest stays dim |
|
||||
| "Already up to date" time | plain | `Theme::timing()` |
|
||||
|
||||
---
|
||||
|
||||
## Files to Change
|
||||
|
||||
1. **`src/cli/progress.rs`** — `format_stage_line()`: apply color to icon, bold to label, `Theme::timing()` to elapsed
|
||||
2. **`src/cli/commands/sync.rs`** —
|
||||
- Pass colored icons to `format_stage_line` / `emit_stage_line` / `emit_stage_block`
|
||||
- Color failure text in `append_failures()`
|
||||
- Color numbers and time in `print_sync()`
|
||||
- Color error/failure counts in sub-row functions (`issue_sub_rows`, `mr_sub_rows`, `status_sub_rows`)
|
||||
|
||||
## Approach
|
||||
|
||||
- `format_stage_line` already receives the icon string — color it before passing
|
||||
- Add a `color_icon` helper that applies success/warning color to the icon glyph
|
||||
- Bold the label in `format_stage_line`
|
||||
- Apply `Theme::timing()` to elapsed in `format_stage_line`
|
||||
- In `append_failures`, wrap failure text in `Theme::warning()`
|
||||
- In `print_sync`, wrap count numbers with `Theme::info().bold()`
|
||||
- In sub-row functions, apply `Theme::warning()` to error/failure parts only (keep rest dim)
|
||||
|
||||
## Non-goals
|
||||
|
||||
- No changes to robot mode (JSON output)
|
||||
- No changes to dry-run output (already reasonably colored)
|
||||
- No new Theme colors — use existing palette
|
||||
- No changes to timing breakdown (already colored)
|
||||
106
.claude/skills/release/SKILL.md
Normal file
106
.claude/skills/release/SKILL.md
Normal file
@@ -0,0 +1,106 @@
|
||||
---
|
||||
name: release
|
||||
description: Bump version, tag, and prepare for next development cycle
|
||||
version: 1.0.0
|
||||
author: Taylor Eernisse
|
||||
category: automation
|
||||
tags: ["release", "versioning", "semver", "git"]
|
||||
---
|
||||
# Release
|
||||
|
||||
Automate SemVer version bumps for the `lore` CLI.
|
||||
|
||||
## Invocation
|
||||
|
||||
```
|
||||
/release <type>
|
||||
```
|
||||
|
||||
Where `<type>` is one of:
|
||||
- **major** — breaking changes (0.5.0 -> 1.0.0)
|
||||
- **minor** — new features (0.5.0 -> 0.6.0)
|
||||
- **patch** / **hotfix** — bug fixes (0.5.0 -> 0.5.1)
|
||||
|
||||
If no type is provided, ask the user.
|
||||
|
||||
## Procedure
|
||||
|
||||
Follow these steps exactly. Do NOT skip any step.
|
||||
|
||||
### 1. Determine bump type
|
||||
|
||||
Parse the argument. Accept these aliases:
|
||||
- `major`, `breaking` -> MAJOR
|
||||
- `minor`, `feature`, `feat` -> MINOR
|
||||
- `patch`, `hotfix`, `fix` -> PATCH
|
||||
|
||||
If the argument doesn't match, ask the user to clarify.
|
||||
|
||||
### 2. Read current version
|
||||
|
||||
Read `Cargo.toml` and extract the `version = "X.Y.Z"` line. Parse into major, minor, patch integers.
|
||||
|
||||
### 3. Compute new version
|
||||
|
||||
- MAJOR: `(major+1).0.0`
|
||||
- MINOR: `major.(minor+1).0`
|
||||
- PATCH: `major.minor.(patch+1)`
|
||||
|
||||
### 4. Check preconditions
|
||||
|
||||
Run `git status` and `git log --oneline -5`. Show the user:
|
||||
- Current version: X.Y.Z
|
||||
- New version: A.B.C
|
||||
- Bump type: major/minor/patch
|
||||
- Working tree status (clean or dirty)
|
||||
- Last 5 commits (so they can confirm scope)
|
||||
|
||||
If the working tree is dirty, warn: "You have uncommitted changes. They will NOT be included in the release tag. Continue?"
|
||||
|
||||
Ask the user to confirm before proceeding.
|
||||
|
||||
### 5. Update Cargo.toml
|
||||
|
||||
Edit the `version = "..."` line in Cargo.toml to the new version.
|
||||
|
||||
### 6. Update Cargo.lock
|
||||
|
||||
Run `cargo check` to update Cargo.lock with the new version. This also verifies the project compiles.
|
||||
|
||||
### 7. Commit the version bump
|
||||
|
||||
```bash
|
||||
git add Cargo.toml Cargo.lock
|
||||
git commit -m "release: v{NEW_VERSION}"
|
||||
```
|
||||
|
||||
### 8. Tag the release
|
||||
|
||||
```bash
|
||||
git tag v{NEW_VERSION}
|
||||
```
|
||||
|
||||
### 9. Report
|
||||
|
||||
Print a summary:
|
||||
```
|
||||
Release v{NEW_VERSION} created.
|
||||
|
||||
Previous: v{OLD_VERSION}
|
||||
Bump: {type}
|
||||
Tag: v{NEW_VERSION}
|
||||
Commit: {short hash}
|
||||
|
||||
To push: git push && git push --tags
|
||||
```
|
||||
|
||||
Do NOT push automatically. The user decides when to push.
|
||||
|
||||
## Examples
|
||||
|
||||
```
|
||||
/release minor -> 0.5.0 -> 0.6.0
|
||||
/release hotfix -> 0.5.0 -> 0.5.1
|
||||
/release patch -> 0.5.0 -> 0.5.1
|
||||
/release major -> 0.5.0 -> 1.0.0
|
||||
```
|
||||
50
.cline/rules
Normal file
50
.cline/rules
Normal file
@@ -0,0 +1,50 @@
|
||||
|
||||
````markdown
|
||||
## UBS Quick Reference for AI Agents
|
||||
|
||||
UBS stands for "Ultimate Bug Scanner": **The AI Coding Agent's Secret Weapon: Flagging Likely Bugs for Fixing Early On**
|
||||
|
||||
**Install:** `curl -sSL https://raw.githubusercontent.com/Dicklesworthstone/ultimate_bug_scanner/master/install.sh | bash`
|
||||
|
||||
**Golden Rule:** `ubs <changed-files>` before every commit. Exit 0 = safe. Exit >0 = fix & re-run.
|
||||
|
||||
**Commands:**
|
||||
```bash
|
||||
ubs file.ts file2.py # Specific files (< 1s) — USE THIS
|
||||
ubs $(git diff --name-only --cached) # Staged files — before commit
|
||||
ubs --only=js,python src/ # Language filter (3-5x faster)
|
||||
ubs --ci --fail-on-warning . # CI mode — before PR
|
||||
ubs --help # Full command reference
|
||||
ubs sessions --entries 1 # Tail the latest install session log
|
||||
ubs . # Whole project (ignores things like .venv and node_modules automatically)
|
||||
```
|
||||
|
||||
**Output Format:**
|
||||
```
|
||||
⚠️ Category (N errors)
|
||||
file.ts:42:5 – Issue description
|
||||
💡 Suggested fix
|
||||
Exit code: 1
|
||||
```
|
||||
Parse: `file:line:col` → location | 💡 → how to fix | Exit 0/1 → pass/fail
|
||||
|
||||
**Fix Workflow:**
|
||||
1. Read finding → category + fix suggestion
|
||||
2. Navigate `file:line:col` → view context
|
||||
3. Verify real issue (not false positive)
|
||||
4. Fix root cause (not symptom)
|
||||
5. Re-run `ubs <file>` → exit 0
|
||||
6. Commit
|
||||
|
||||
**Speed Critical:** Scope to changed files. `ubs src/file.ts` (< 1s) vs `ubs .` (30s). Never full scan for small edits.
|
||||
|
||||
**Bug Severity:**
|
||||
- **Critical** (always fix): Null safety, XSS/injection, async/await, memory leaks
|
||||
- **Important** (production): Type narrowing, division-by-zero, resource leaks
|
||||
- **Contextual** (judgment): TODO/FIXME, console logs
|
||||
|
||||
**Anti-Patterns:**
|
||||
- ❌ Ignore findings → ✅ Investigate each
|
||||
- ❌ Full scan per edit → ✅ Scope to file
|
||||
- ❌ Fix symptom (`if (x) { x.y }`) → ✅ Root cause (`x?.y`)
|
||||
````
|
||||
50
.codex/rules/ubs.md
Normal file
50
.codex/rules/ubs.md
Normal file
@@ -0,0 +1,50 @@
|
||||
|
||||
````markdown
|
||||
## UBS Quick Reference for AI Agents
|
||||
|
||||
UBS stands for "Ultimate Bug Scanner": **The AI Coding Agent's Secret Weapon: Flagging Likely Bugs for Fixing Early On**
|
||||
|
||||
**Install:** `curl -sSL https://raw.githubusercontent.com/Dicklesworthstone/ultimate_bug_scanner/master/install.sh | bash`
|
||||
|
||||
**Golden Rule:** `ubs <changed-files>` before every commit. Exit 0 = safe. Exit >0 = fix & re-run.
|
||||
|
||||
**Commands:**
|
||||
```bash
|
||||
ubs file.ts file2.py # Specific files (< 1s) — USE THIS
|
||||
ubs $(git diff --name-only --cached) # Staged files — before commit
|
||||
ubs --only=js,python src/ # Language filter (3-5x faster)
|
||||
ubs --ci --fail-on-warning . # CI mode — before PR
|
||||
ubs --help # Full command reference
|
||||
ubs sessions --entries 1 # Tail the latest install session log
|
||||
ubs . # Whole project (ignores things like .venv and node_modules automatically)
|
||||
```
|
||||
|
||||
**Output Format:**
|
||||
```
|
||||
⚠️ Category (N errors)
|
||||
file.ts:42:5 – Issue description
|
||||
💡 Suggested fix
|
||||
Exit code: 1
|
||||
```
|
||||
Parse: `file:line:col` → location | 💡 → how to fix | Exit 0/1 → pass/fail
|
||||
|
||||
**Fix Workflow:**
|
||||
1. Read finding → category + fix suggestion
|
||||
2. Navigate `file:line:col` → view context
|
||||
3. Verify real issue (not false positive)
|
||||
4. Fix root cause (not symptom)
|
||||
5. Re-run `ubs <file>` → exit 0
|
||||
6. Commit
|
||||
|
||||
**Speed Critical:** Scope to changed files. `ubs src/file.ts` (< 1s) vs `ubs .` (30s). Never full scan for small edits.
|
||||
|
||||
**Bug Severity:**
|
||||
- **Critical** (always fix): Null safety, XSS/injection, async/await, memory leaks
|
||||
- **Important** (production): Type narrowing, division-by-zero, resource leaks
|
||||
- **Contextual** (judgment): TODO/FIXME, console logs
|
||||
|
||||
**Anti-Patterns:**
|
||||
- ❌ Ignore findings → ✅ Investigate each
|
||||
- ❌ Full scan per edit → ✅ Scope to file
|
||||
- ❌ Fix symptom (`if (x) { x.y }`) → ✅ Root cause (`x?.y`)
|
||||
````
|
||||
16
.continue/config.json
Normal file
16
.continue/config.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"customCommands": [
|
||||
{
|
||||
"name": "scan-bugs",
|
||||
"description": "Run Ultimate Bug Scanner on current project",
|
||||
"prompt": "Run 'ubs --fail-on-warning .' and fix any critical issues found before proceeding"
|
||||
}
|
||||
],
|
||||
"slashCommands": [
|
||||
{
|
||||
"name": "quality",
|
||||
"description": "Check code quality with UBS",
|
||||
"run": "ubs ."
|
||||
}
|
||||
]
|
||||
}
|
||||
50
.cursor/rules
Normal file
50
.cursor/rules
Normal file
@@ -0,0 +1,50 @@
|
||||
|
||||
````markdown
|
||||
## UBS Quick Reference for AI Agents
|
||||
|
||||
UBS stands for "Ultimate Bug Scanner": **The AI Coding Agent's Secret Weapon: Flagging Likely Bugs for Fixing Early On**
|
||||
|
||||
**Install:** `curl -sSL https://raw.githubusercontent.com/Dicklesworthstone/ultimate_bug_scanner/master/install.sh | bash`
|
||||
|
||||
**Golden Rule:** `ubs <changed-files>` before every commit. Exit 0 = safe. Exit >0 = fix & re-run.
|
||||
|
||||
**Commands:**
|
||||
```bash
|
||||
ubs file.ts file2.py # Specific files (< 1s) — USE THIS
|
||||
ubs $(git diff --name-only --cached) # Staged files — before commit
|
||||
ubs --only=js,python src/ # Language filter (3-5x faster)
|
||||
ubs --ci --fail-on-warning . # CI mode — before PR
|
||||
ubs --help # Full command reference
|
||||
ubs sessions --entries 1 # Tail the latest install session log
|
||||
ubs . # Whole project (ignores things like .venv and node_modules automatically)
|
||||
```
|
||||
|
||||
**Output Format:**
|
||||
```
|
||||
⚠️ Category (N errors)
|
||||
file.ts:42:5 – Issue description
|
||||
💡 Suggested fix
|
||||
Exit code: 1
|
||||
```
|
||||
Parse: `file:line:col` → location | 💡 → how to fix | Exit 0/1 → pass/fail
|
||||
|
||||
**Fix Workflow:**
|
||||
1. Read finding → category + fix suggestion
|
||||
2. Navigate `file:line:col` → view context
|
||||
3. Verify real issue (not false positive)
|
||||
4. Fix root cause (not symptom)
|
||||
5. Re-run `ubs <file>` → exit 0
|
||||
6. Commit
|
||||
|
||||
**Speed Critical:** Scope to changed files. `ubs src/file.ts` (< 1s) vs `ubs .` (30s). Never full scan for small edits.
|
||||
|
||||
**Bug Severity:**
|
||||
- **Critical** (always fix): Null safety, XSS/injection, async/await, memory leaks
|
||||
- **Important** (production): Type narrowing, division-by-zero, resource leaks
|
||||
- **Contextual** (judgment): TODO/FIXME, console logs
|
||||
|
||||
**Anti-Patterns:**
|
||||
- ❌ Ignore findings → ✅ Investigate each
|
||||
- ❌ Full scan per edit → ✅ Scope to file
|
||||
- ❌ Fix symptom (`if (x) { x.y }`) → ✅ Root cause (`x?.y`)
|
||||
````
|
||||
50
.gemini/rules
Normal file
50
.gemini/rules
Normal file
@@ -0,0 +1,50 @@
|
||||
|
||||
````markdown
|
||||
## UBS Quick Reference for AI Agents
|
||||
|
||||
UBS stands for "Ultimate Bug Scanner": **The AI Coding Agent's Secret Weapon: Flagging Likely Bugs for Fixing Early On**
|
||||
|
||||
**Install:** `curl -sSL https://raw.githubusercontent.com/Dicklesworthstone/ultimate_bug_scanner/master/install.sh | bash`
|
||||
|
||||
**Golden Rule:** `ubs <changed-files>` before every commit. Exit 0 = safe. Exit >0 = fix & re-run.
|
||||
|
||||
**Commands:**
|
||||
```bash
|
||||
ubs file.ts file2.py # Specific files (< 1s) — USE THIS
|
||||
ubs $(git diff --name-only --cached) # Staged files — before commit
|
||||
ubs --only=js,python src/ # Language filter (3-5x faster)
|
||||
ubs --ci --fail-on-warning . # CI mode — before PR
|
||||
ubs --help # Full command reference
|
||||
ubs sessions --entries 1 # Tail the latest install session log
|
||||
ubs . # Whole project (ignores things like .venv and node_modules automatically)
|
||||
```
|
||||
|
||||
**Output Format:**
|
||||
```
|
||||
⚠️ Category (N errors)
|
||||
file.ts:42:5 – Issue description
|
||||
💡 Suggested fix
|
||||
Exit code: 1
|
||||
```
|
||||
Parse: `file:line:col` → location | 💡 → how to fix | Exit 0/1 → pass/fail
|
||||
|
||||
**Fix Workflow:**
|
||||
1. Read finding → category + fix suggestion
|
||||
2. Navigate `file:line:col` → view context
|
||||
3. Verify real issue (not false positive)
|
||||
4. Fix root cause (not symptom)
|
||||
5. Re-run `ubs <file>` → exit 0
|
||||
6. Commit
|
||||
|
||||
**Speed Critical:** Scope to changed files. `ubs src/file.ts` (< 1s) vs `ubs .` (30s). Never full scan for small edits.
|
||||
|
||||
**Bug Severity:**
|
||||
- **Critical** (always fix): Null safety, XSS/injection, async/await, memory leaks
|
||||
- **Important** (production): Type narrowing, division-by-zero, resource leaks
|
||||
- **Contextual** (judgment): TODO/FIXME, console logs
|
||||
|
||||
**Anti-Patterns:**
|
||||
- ❌ Ignore findings → ✅ Investigate each
|
||||
- ❌ Full scan per edit → ✅ Scope to file
|
||||
- ❌ Fix symptom (`if (x) { x.y }`) → ✅ Root cause (`x?.y`)
|
||||
````
|
||||
21
.github/workflows/roam.yml
vendored
Normal file
21
.github/workflows/roam.yml
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
name: Roam Code Analysis
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main, master]
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
jobs:
|
||||
roam:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
- run: pip install roam-code
|
||||
- run: roam index
|
||||
- run: roam fitness
|
||||
- run: roam pr-risk --json
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -41,6 +41,9 @@ lore.config.json
|
||||
*.db-shm
|
||||
|
||||
|
||||
# Mock seed data
|
||||
tools/mock-seed/
|
||||
|
||||
# Added by cargo
|
||||
|
||||
/target
|
||||
|
||||
50
.opencode/rules
Normal file
50
.opencode/rules
Normal file
@@ -0,0 +1,50 @@
|
||||
|
||||
````markdown
|
||||
## UBS Quick Reference for AI Agents
|
||||
|
||||
UBS stands for "Ultimate Bug Scanner": **The AI Coding Agent's Secret Weapon: Flagging Likely Bugs for Fixing Early On**
|
||||
|
||||
**Install:** `curl -sSL https://raw.githubusercontent.com/Dicklesworthstone/ultimate_bug_scanner/master/install.sh | bash`
|
||||
|
||||
**Golden Rule:** `ubs <changed-files>` before every commit. Exit 0 = safe. Exit >0 = fix & re-run.
|
||||
|
||||
**Commands:**
|
||||
```bash
|
||||
ubs file.ts file2.py # Specific files (< 1s) — USE THIS
|
||||
ubs $(git diff --name-only --cached) # Staged files — before commit
|
||||
ubs --only=js,python src/ # Language filter (3-5x faster)
|
||||
ubs --ci --fail-on-warning . # CI mode — before PR
|
||||
ubs --help # Full command reference
|
||||
ubs sessions --entries 1 # Tail the latest install session log
|
||||
ubs . # Whole project (ignores things like .venv and node_modules automatically)
|
||||
```
|
||||
|
||||
**Output Format:**
|
||||
```
|
||||
⚠️ Category (N errors)
|
||||
file.ts:42:5 – Issue description
|
||||
💡 Suggested fix
|
||||
Exit code: 1
|
||||
```
|
||||
Parse: `file:line:col` → location | 💡 → how to fix | Exit 0/1 → pass/fail
|
||||
|
||||
**Fix Workflow:**
|
||||
1. Read finding → category + fix suggestion
|
||||
2. Navigate `file:line:col` → view context
|
||||
3. Verify real issue (not false positive)
|
||||
4. Fix root cause (not symptom)
|
||||
5. Re-run `ubs <file>` → exit 0
|
||||
6. Commit
|
||||
|
||||
**Speed Critical:** Scope to changed files. `ubs src/file.ts` (< 1s) vs `ubs .` (30s). Never full scan for small edits.
|
||||
|
||||
**Bug Severity:**
|
||||
- **Critical** (always fix): Null safety, XSS/injection, async/await, memory leaks
|
||||
- **Important** (production): Type narrowing, division-by-zero, resource leaks
|
||||
- **Contextual** (judgment): TODO/FIXME, console logs
|
||||
|
||||
**Anti-Patterns:**
|
||||
- ❌ Ignore findings → ✅ Investigate each
|
||||
- ❌ Full scan per edit → ✅ Scope to file
|
||||
- ❌ Fix symptom (`if (x) { x.y }`) → ✅ Root cause (`x?.y`)
|
||||
````
|
||||
11
.roam/fitness.yaml
Normal file
11
.roam/fitness.yaml
Normal file
@@ -0,0 +1,11 @@
|
||||
rules:
|
||||
- name: No circular imports in core
|
||||
type: dependency
|
||||
source: "src/**"
|
||||
forbidden_target: "tests/**"
|
||||
reason: "Production code should not import test modules"
|
||||
- name: Complexity threshold
|
||||
type: metric
|
||||
metric: cognitive_complexity
|
||||
threshold: 30
|
||||
reason: "Functions above 30 cognitive complexity need refactoring"
|
||||
120
AGENTS.md
120
AGENTS.md
@@ -14,6 +14,14 @@ If I tell you to do something, even if it goes against what follows below, YOU M
|
||||
|
||||
---
|
||||
|
||||
## Version Control: jj-First (CRITICAL)
|
||||
|
||||
**ALWAYS prefer jj (Jujutsu) over git for all VCS operations.** This is a colocated repo with both `.jj/` and `.git/`. When instructed to use git by anything — even later in this file — use the best jj replacement commands instead. Only fall back to raw `git` for things jj cannot do (hooks, LFS, submodules, `gh` CLI interop).
|
||||
|
||||
See `~/.claude/rules/jj-vcs/` for the full command reference, translation table, revsets, patterns, and recovery recipes.
|
||||
|
||||
---
|
||||
|
||||
## Irreversible Git & Filesystem Actions — DO NOT EVER BREAK GLASS
|
||||
|
||||
> **Note:** Treat destructive commands as break-glass. If there's any doubt, stop and ask.
|
||||
@@ -316,7 +324,7 @@ bv --robot-insights | jq '.Cycles' # Circular deps (must
|
||||
|
||||
```bash
|
||||
ubs file.rs file2.rs # Specific files (< 1s) — USE THIS
|
||||
ubs $(git diff --name-only --cached) # Staged files — before commit
|
||||
ubs $(jj diff --name-only) # Changed files — before commit
|
||||
ubs --only=rust,toml src/ # Language filter (3-5x faster)
|
||||
ubs --ci --fail-on-warning . # CI mode — before PR
|
||||
ubs . # Whole project (ignores target/, Cargo.lock)
|
||||
@@ -428,9 +436,9 @@ Returns structured results with file paths, line ranges, and extracted code snip
|
||||
|
||||
## Beads Workflow Integration
|
||||
|
||||
This project uses [beads_viewer](https://github.com/Dicklesworthstone/beads_viewer) for issue tracking. Issues are stored in `.beads/` and tracked in git.
|
||||
This project uses [beads_viewer](https://github.com/Dicklesworthstone/beads_viewer) for issue tracking. Issues are stored in `.beads/` and tracked in version control.
|
||||
|
||||
**Note:** `br` is non-invasive—it never executes git commands directly. You must run git commands manually after `br sync --flush-only`.
|
||||
**Note:** `br` is non-invasive—it never executes VCS commands directly. You must commit manually after `br sync --flush-only`.
|
||||
|
||||
### Essential Commands
|
||||
|
||||
@@ -446,7 +454,7 @@ br create --title="..." --type=task --priority=2
|
||||
br update <id> --status=in_progress
|
||||
br close <id> --reason="Completed"
|
||||
br close <id1> <id2> # Close multiple issues at once
|
||||
br sync --flush-only # Export to JSONL (then manually: git add .beads/ && git commit)
|
||||
br sync --flush-only # Export to JSONL (then: jj commit -m "Update beads")
|
||||
```
|
||||
|
||||
### Workflow Pattern
|
||||
@@ -466,15 +474,14 @@ br sync --flush-only # Export to JSONL (then manually: git add .beads/ && git c
|
||||
|
||||
### Session Protocol
|
||||
|
||||
**Before ending any session, run this checklist:**
|
||||
**Before ending any session, run this checklist (solo/lead only — workers skip VCS):**
|
||||
|
||||
```bash
|
||||
git status # Check what changed
|
||||
git add <files> # Stage code changes
|
||||
br sync --flush-only # Export beads to JSONL
|
||||
git add .beads/ # Stage beads changes
|
||||
git commit -m "..." # Commit code and beads
|
||||
git push # Push to remote
|
||||
jj status # Check what changed
|
||||
br sync --flush-only # Export beads to JSONL
|
||||
jj commit -m "..." # Commit code and beads (jj auto-tracks all changes)
|
||||
jj bookmark set <name> -r @- # Point bookmark at committed work
|
||||
jj git push -b <name> # Push to remote
|
||||
```
|
||||
|
||||
### Best Practices
|
||||
@@ -483,13 +490,15 @@ git push # Push to remote
|
||||
- Update status as you work (in_progress → closed)
|
||||
- Create new issues with `br create` when you discover tasks
|
||||
- Use descriptive titles and set appropriate priority/type
|
||||
- Always run `br sync --flush-only` then commit .beads/ before ending session
|
||||
- Always run `br sync --flush-only` then commit before ending session (jj auto-tracks .beads/)
|
||||
|
||||
<!-- end-bv-agent-instructions -->
|
||||
|
||||
## Landing the Plane (Session Completion)
|
||||
|
||||
**When ending a work session**, you MUST complete ALL steps below. Work is NOT complete until `git push` succeeds.
|
||||
**When ending a work session**, you MUST complete ALL steps below. Work is NOT complete until push succeeds.
|
||||
|
||||
**WHO RUNS THIS:** Solo agents run it themselves. In multi-agent sessions, ONLY the team lead runs this. Workers skip VCS entirely.
|
||||
|
||||
**MANDATORY WORKFLOW:**
|
||||
|
||||
@@ -498,19 +507,20 @@ git push # Push to remote
|
||||
3. **Update issue status** - Close finished work, update in-progress items
|
||||
4. **PUSH TO REMOTE** - This is MANDATORY:
|
||||
```bash
|
||||
git pull --rebase
|
||||
br sync --flush-only
|
||||
git add .beads/
|
||||
git commit -m "Update beads"
|
||||
git push
|
||||
git status # MUST show "up to date with origin"
|
||||
jj git fetch # Get latest remote state
|
||||
jj rebase -d trunk() # Rebase onto latest trunk if needed
|
||||
br sync --flush-only # Export beads to JSONL
|
||||
jj commit -m "Update beads" # Commit (jj auto-tracks .beads/ changes)
|
||||
jj bookmark set <name> -r @- # Point bookmark at committed work
|
||||
jj git push -b <name> # Push to remote
|
||||
jj log -r '<name>' # Verify bookmark position
|
||||
```
|
||||
5. **Clean up** - Clear stashes, prune remote branches
|
||||
5. **Clean up** - Abandon empty orphan changes if any (`jj abandon <rev>`)
|
||||
6. **Verify** - All changes committed AND pushed
|
||||
7. **Hand off** - Provide context for next session
|
||||
|
||||
**CRITICAL RULES:**
|
||||
- Work is NOT complete until `git push` succeeds
|
||||
- Work is NOT complete until `jj git push` succeeds
|
||||
- NEVER stop before pushing - that leaves work stranded locally
|
||||
- NEVER say "ready to push when you are" - YOU must push
|
||||
- If push fails, resolve and retry until it succeeds
|
||||
@@ -618,6 +628,9 @@ LORE_ROBOT=1 lore issues
|
||||
lore --robot issues -n 10
|
||||
lore --robot mrs -s opened
|
||||
|
||||
# Filter issues by work item status (case-insensitive)
|
||||
lore --robot issues --status "In progress"
|
||||
|
||||
# List with field selection (reduces token usage ~60%)
|
||||
lore --robot issues --fields minimal
|
||||
lore --robot mrs --fields iid,title,state,draft
|
||||
@@ -740,3 +753,68 @@ lore -J mrs --fields iid,title,state,draft,labels # Custom field list
|
||||
- Use `lore --robot health` as a fast pre-flight check before queries
|
||||
- Use `lore robot-docs` for response schema discovery
|
||||
- The `-p` flag supports fuzzy project matching (suffix and substring)
|
||||
|
||||
---
|
||||
|
||||
## Read/Write Split: lore vs glab
|
||||
|
||||
| Operation | Tool | Why |
|
||||
|-----------|------|-----|
|
||||
| List issues/MRs | lore | Richer: includes status, discussions, closing MRs |
|
||||
| View issue/MR detail | lore | Pre-joined discussions, work-item status |
|
||||
| Search across entities | lore | FTS5 + vector hybrid search |
|
||||
| Expert/workload analysis | lore | who command — no glab equivalent |
|
||||
| Timeline reconstruction | lore | Chronological narrative — no glab equivalent |
|
||||
| Create/update/close | glab | Write operations |
|
||||
| Approve/merge MR | glab | Write operations |
|
||||
| CI/CD pipelines | glab | Not in lore scope |
|
||||
|
||||
````markdown
|
||||
## UBS Quick Reference for AI Agents
|
||||
|
||||
UBS stands for "Ultimate Bug Scanner": **The AI Coding Agent's Secret Weapon: Flagging Likely Bugs for Fixing Early On**
|
||||
|
||||
**Install:** `curl -sSL https://raw.githubusercontent.com/Dicklesworthstone/ultimate_bug_scanner/master/install.sh | bash`
|
||||
|
||||
**Golden Rule:** `ubs <changed-files>` before every commit. Exit 0 = safe. Exit >0 = fix & re-run.
|
||||
|
||||
**Commands:**
|
||||
```bash
|
||||
ubs file.ts file2.py # Specific files (< 1s) — USE THIS
|
||||
ubs $(git diff --name-only --cached) # Staged files — before commit
|
||||
ubs --only=js,python src/ # Language filter (3-5x faster)
|
||||
ubs --ci --fail-on-warning . # CI mode — before PR
|
||||
ubs --help # Full command reference
|
||||
ubs sessions --entries 1 # Tail the latest install session log
|
||||
ubs . # Whole project (ignores things like .venv and node_modules automatically)
|
||||
```
|
||||
|
||||
**Output Format:**
|
||||
```
|
||||
⚠️ Category (N errors)
|
||||
file.ts:42:5 – Issue description
|
||||
💡 Suggested fix
|
||||
Exit code: 1
|
||||
```
|
||||
Parse: `file:line:col` → location | 💡 → how to fix | Exit 0/1 → pass/fail
|
||||
|
||||
**Fix Workflow:**
|
||||
1. Read finding → category + fix suggestion
|
||||
2. Navigate `file:line:col` → view context
|
||||
3. Verify real issue (not false positive)
|
||||
4. Fix root cause (not symptom)
|
||||
5. Re-run `ubs <file>` → exit 0
|
||||
6. Commit
|
||||
|
||||
**Speed Critical:** Scope to changed files. `ubs src/file.ts` (< 1s) vs `ubs .` (30s). Never full scan for small edits.
|
||||
|
||||
**Bug Severity:**
|
||||
- **Critical** (always fix): Null safety, XSS/injection, async/await, memory leaks
|
||||
- **Important** (production): Type narrowing, division-by-zero, resource leaks
|
||||
- **Contextual** (judgment): TODO/FIXME, console logs
|
||||
|
||||
**Anti-Patterns:**
|
||||
- ❌ Ignore findings → ✅ Investigate each
|
||||
- ❌ Full scan per edit → ✅ Scope to file
|
||||
- ❌ Fix symptom (`if (x) { x.y }`) → ✅ Root cause (`x?.y`)
|
||||
````
|
||||
|
||||
742
AGENTS.md.backup
Normal file
742
AGENTS.md.backup
Normal file
@@ -0,0 +1,742 @@
|
||||
# AGENTS.md
|
||||
|
||||
## RULE 0 - THE FUNDAMENTAL OVERRIDE PEROGATIVE
|
||||
|
||||
If I tell you to do something, even if it goes against what follows below, YOU MUST LISTEN TO ME. I AM IN CHARGE, NOT YOU.
|
||||
|
||||
---
|
||||
|
||||
## RULE NUMBER 1: NO FILE DELETION
|
||||
|
||||
**YOU ARE NEVER ALLOWED TO DELETE A FILE WITHOUT EXPRESS PERMISSION.** Even a new file that you yourself created, such as a test code file. You have a horrible track record of deleting critically important files or otherwise throwing away tons of expensive work. As a result, you have permanently lost any and all rights to determine that a file or folder should be deleted.
|
||||
|
||||
**YOU MUST ALWAYS ASK AND RECEIVE CLEAR, WRITTEN PERMISSION BEFORE EVER DELETING A FILE OR FOLDER OF ANY KIND.**
|
||||
|
||||
---
|
||||
|
||||
## Irreversible Git & Filesystem Actions — DO NOT EVER BREAK GLASS
|
||||
|
||||
> **Note:** Treat destructive commands as break-glass. If there's any doubt, stop and ask.
|
||||
|
||||
1. **Absolutely forbidden commands:** `git reset --hard`, `git clean -fd`, `rm -rf`, or any command that can delete or overwrite code/data must never be run unless the user explicitly provides the exact command and states, in the same message, that they understand and want the irreversible consequences.
|
||||
2. **No guessing:** If there is any uncertainty about what a command might delete or overwrite, stop immediately and ask the user for specific approval. "I think it's safe" is never acceptable.
|
||||
3. **Safer alternatives first:** When cleanup or rollbacks are needed, request permission to use non-destructive options (`git status`, `git diff`, `git stash`, copying to backups) before ever considering a destructive command.
|
||||
4. **Mandatory explicit plan:** Even after explicit user authorization, restate the command verbatim, list exactly what will be affected, and wait for a confirmation that your understanding is correct. Only then may you execute it—if anything remains ambiguous, refuse and escalate.
|
||||
5. **Document the confirmation:** When running any approved destructive command, record (in the session notes / final response) the exact user text that authorized it, the command actually run, and the execution time. If that record is absent, the operation did not happen.
|
||||
|
||||
---
|
||||
|
||||
## Toolchain: Rust & Cargo
|
||||
|
||||
We only use **Cargo** in this project, NEVER any other package manager.
|
||||
|
||||
- **Edition/toolchain:** Follow `rust-toolchain.toml` (if present). Do not assume stable vs nightly.
|
||||
- **Dependencies:** Explicit versions for stability; keep the set minimal.
|
||||
- **Configuration:** Cargo.toml only
|
||||
- **Unsafe code:** Forbidden (`#![forbid(unsafe_code)]`)
|
||||
|
||||
When writing Rust code, reference RUST_CLI_TOOLS_BEST_PRACTICES.md
|
||||
|
||||
### Release Profile
|
||||
|
||||
Use the release profile defined in `Cargo.toml`. If you need to change it, justify the
|
||||
performance/size tradeoff and how it impacts determinism and cancellation behavior.
|
||||
|
||||
---
|
||||
|
||||
## Code Editing Discipline
|
||||
|
||||
### No Script-Based Changes
|
||||
|
||||
**NEVER** run a script that processes/changes code files in this repo. Brittle regex-based transformations create far more problems than they solve.
|
||||
|
||||
- **Always make code changes manually**, even when there are many instances
|
||||
- For many simple changes: use parallel subagents
|
||||
- For subtle/complex changes: do them methodically yourself
|
||||
|
||||
### No File Proliferation
|
||||
|
||||
If you want to change something or add a feature, **revise existing code files in place**.
|
||||
|
||||
**NEVER** create variations like:
|
||||
- `mainV2.rs`
|
||||
- `main_improved.rs`
|
||||
- `main_enhanced.rs`
|
||||
|
||||
New files are reserved for **genuinely new functionality** that makes zero sense to include in any existing file. The bar for creating new files is **incredibly high**.
|
||||
|
||||
---
|
||||
|
||||
## Backwards Compatibility
|
||||
|
||||
We do not care about backwards compatibility—we're in early development with no users. We want to do things the **RIGHT** way with **NO TECH DEBT**.
|
||||
|
||||
- Never create "compatibility shims"
|
||||
- Never create wrapper functions for deprecated APIs
|
||||
- Just fix the code directly
|
||||
|
||||
---
|
||||
|
||||
## Compiler Checks (CRITICAL)
|
||||
|
||||
**After any substantive code changes, you MUST verify no errors were introduced:**
|
||||
|
||||
```bash
|
||||
# Check for compiler errors and warnings
|
||||
cargo check --all-targets
|
||||
|
||||
# Check for clippy lints (pedantic + nursery are enabled)
|
||||
cargo clippy --all-targets -- -D warnings
|
||||
|
||||
# Verify formatting
|
||||
cargo fmt --check
|
||||
```
|
||||
|
||||
If you see errors, **carefully understand and resolve each issue**. Read sufficient context to fix them the RIGHT way.
|
||||
|
||||
---
|
||||
|
||||
## Testing
|
||||
|
||||
### Unit & Property Tests
|
||||
|
||||
```bash
|
||||
# Run all tests
|
||||
cargo test
|
||||
|
||||
# Run with output
|
||||
cargo test -- --nocapture
|
||||
```
|
||||
|
||||
When adding or changing primitives, add tests that assert the core invariants:
|
||||
|
||||
- no task leaks
|
||||
- no obligation leaks
|
||||
- losers are drained after races
|
||||
- region close implies quiescence
|
||||
|
||||
Prefer deterministic lab-runtime tests for concurrency-sensitive behavior.
|
||||
|
||||
---
|
||||
|
||||
## MCP Agent Mail — Multi-Agent Coordination
|
||||
|
||||
A mail-like layer that lets coding agents coordinate asynchronously via MCP tools and resources. Provides identities, inbox/outbox, searchable threads, and advisory file reservations with human-auditable artifacts in Git.
|
||||
|
||||
### Why It's Useful
|
||||
|
||||
- **Prevents conflicts:** Explicit file reservations (leases) for files/globs
|
||||
- **Token-efficient:** Messages stored in per-project archive, not in context
|
||||
- **Quick reads:** `resource://inbox/...`, `resource://thread/...`
|
||||
|
||||
### Same Repository Workflow
|
||||
|
||||
1. **Register identity:**
|
||||
```
|
||||
ensure_project(project_key=<abs-path>)
|
||||
register_agent(project_key, program, model)
|
||||
```
|
||||
|
||||
2. **Reserve files before editing:**
|
||||
```
|
||||
file_reservation_paths(project_key, agent_name, ["src/**"], ttl_seconds=3600, exclusive=true)
|
||||
```
|
||||
|
||||
3. **Communicate with threads:**
|
||||
```
|
||||
send_message(..., thread_id="FEAT-123")
|
||||
fetch_inbox(project_key, agent_name)
|
||||
acknowledge_message(project_key, agent_name, message_id)
|
||||
```
|
||||
|
||||
4. **Quick reads:**
|
||||
```
|
||||
resource://inbox/{Agent}?project=<abs-path>&limit=20
|
||||
resource://thread/{id}?project=<abs-path>&include_bodies=true
|
||||
```
|
||||
|
||||
### Macros vs Granular Tools
|
||||
|
||||
- **Prefer macros for speed:** `macro_start_session`, `macro_prepare_thread`, `macro_file_reservation_cycle`, `macro_contact_handshake`
|
||||
- **Use granular tools for control:** `register_agent`, `file_reservation_paths`, `send_message`, `fetch_inbox`, `acknowledge_message`
|
||||
|
||||
### Common Pitfalls
|
||||
|
||||
- `"from_agent not registered"`: Always `register_agent` in the correct `project_key` first
|
||||
- `"FILE_RESERVATION_CONFLICT"`: Adjust patterns, wait for expiry, or use non-exclusive reservation
|
||||
- **Auth errors:** If JWT+JWKS enabled, include bearer token with matching `kid`
|
||||
|
||||
---
|
||||
|
||||
## Beads (br) — Dependency-Aware Issue Tracking
|
||||
|
||||
Beads provides a lightweight, dependency-aware issue database and CLI (`br` / beads_rust) for selecting "ready work," setting priorities, and tracking status. It complements MCP Agent Mail's messaging and file reservations.
|
||||
|
||||
**Note:** `br` is non-invasive—it never executes git commands directly. You must run git commands manually after `br sync --flush-only`.
|
||||
|
||||
### Conventions
|
||||
|
||||
- **Single source of truth:** Beads for task status/priority/dependencies; Agent Mail for conversation and audit
|
||||
- **Shared identifiers:** Use Beads issue ID (e.g., `br-123`) as Mail `thread_id` and prefix subjects with `[br-123]`
|
||||
- **Reservations:** When starting a task, call `file_reservation_paths()` with the issue ID in `reason`
|
||||
|
||||
### Typical Agent Flow
|
||||
|
||||
1. **Pick ready work (Beads):**
|
||||
```bash
|
||||
br ready --json # Choose highest priority, no blockers
|
||||
```
|
||||
|
||||
2. **Reserve edit surface (Mail):**
|
||||
```
|
||||
file_reservation_paths(project_key, agent_name, ["src/**"], ttl_seconds=3600, exclusive=true, reason="br-123")
|
||||
```
|
||||
|
||||
3. **Announce start (Mail):**
|
||||
```
|
||||
send_message(..., thread_id="br-123", subject="[br-123] Start: <title>", ack_required=true)
|
||||
```
|
||||
|
||||
4. **Work and update:** Reply in-thread with progress
|
||||
|
||||
5. **Complete and release:**
|
||||
```bash
|
||||
br close br-123 --reason "Completed"
|
||||
```
|
||||
```
|
||||
release_file_reservations(project_key, agent_name, paths=["src/**"])
|
||||
```
|
||||
Final Mail reply: `[br-123] Completed` with summary
|
||||
|
||||
### Mapping Cheat Sheet
|
||||
|
||||
| Concept | Value |
|
||||
|---------|-------|
|
||||
| Mail `thread_id` | `br-###` |
|
||||
| Mail subject | `[br-###] ...` |
|
||||
| File reservation `reason` | `br-###` |
|
||||
| Commit messages | Include `br-###` for traceability |
|
||||
|
||||
---
|
||||
|
||||
## bv — Graph-Aware Triage Engine
|
||||
|
||||
bv is a graph-aware triage engine for Beads projects (`.beads/beads.jsonl`). It computes PageRank, betweenness, critical path, cycles, HITS, eigenvector, and k-core metrics deterministically.
|
||||
|
||||
**Scope boundary:** bv handles *what to work on* (triage, priority, planning). For agent-to-agent coordination (messaging, work claiming, file reservations), use MCP Agent Mail.
|
||||
|
||||
**CRITICAL: Use ONLY `--robot-*` flags. Bare `bv` launches an interactive TUI that blocks your session.**
|
||||
|
||||
### The Workflow: Start With Triage
|
||||
|
||||
**`bv --robot-triage` is your single entry point.** It returns:
|
||||
- `quick_ref`: at-a-glance counts + top 3 picks
|
||||
- `recommendations`: ranked actionable items with scores, reasons, unblock info
|
||||
- `quick_wins`: low-effort high-impact items
|
||||
- `blockers_to_clear`: items that unblock the most downstream work
|
||||
- `project_health`: status/type/priority distributions, graph metrics
|
||||
- `commands`: copy-paste shell commands for next steps
|
||||
|
||||
```bash
|
||||
bv --robot-triage # THE MEGA-COMMAND: start here
|
||||
bv --robot-next # Minimal: just the single top pick + claim command
|
||||
```
|
||||
|
||||
### Command Reference
|
||||
|
||||
**Planning:**
|
||||
| Command | Returns |
|
||||
|---------|---------|
|
||||
| `--robot-plan` | Parallel execution tracks with `unblocks` lists |
|
||||
| `--robot-priority` | Priority misalignment detection with confidence |
|
||||
|
||||
**Graph Analysis:**
|
||||
| Command | Returns |
|
||||
|---------|---------|
|
||||
| `--robot-insights` | Full metrics: PageRank, betweenness, HITS, eigenvector, critical path, cycles, k-core, articulation points, slack |
|
||||
| `--robot-label-health` | Per-label health: `health_level`, `velocity_score`, `staleness`, `blocked_count` |
|
||||
| `--robot-label-flow` | Cross-label dependency: `flow_matrix`, `dependencies`, `bottleneck_labels` |
|
||||
| `--robot-label-attention [--attention-limit=N]` | Attention-ranked labels |
|
||||
|
||||
**History & Change Tracking:**
|
||||
| Command | Returns |
|
||||
|---------|---------|
|
||||
| `--robot-history` | Bead-to-commit correlations |
|
||||
| `--robot-diff --diff-since <ref>` | Changes since ref: new/closed/modified issues, cycles |
|
||||
|
||||
**Other:**
|
||||
| Command | Returns |
|
||||
|---------|---------|
|
||||
| `--robot-burndown <sprint>` | Sprint burndown, scope changes, at-risk items |
|
||||
| `--robot-forecast <id\|all>` | ETA predictions with dependency-aware scheduling |
|
||||
| `--robot-alerts` | Stale issues, blocking cascades, priority mismatches |
|
||||
| `--robot-suggest` | Hygiene: duplicates, missing deps, label suggestions |
|
||||
| `--robot-graph [--graph-format=json\|dot\|mermaid]` | Dependency graph export |
|
||||
| `--export-graph <file.html>` | Interactive HTML visualization |
|
||||
|
||||
### Scoping & Filtering
|
||||
|
||||
```bash
|
||||
bv --robot-plan --label backend # Scope to label's subgraph
|
||||
bv --robot-insights --as-of HEAD~30 # Historical point-in-time
|
||||
bv --recipe actionable --robot-plan # Pre-filter: ready to work
|
||||
bv --recipe high-impact --robot-triage # Pre-filter: top PageRank
|
||||
bv --robot-triage --robot-triage-by-track # Group by parallel work streams
|
||||
bv --robot-triage --robot-triage-by-label # Group by domain
|
||||
```
|
||||
|
||||
### Understanding Robot Output
|
||||
|
||||
**All robot JSON includes:**
|
||||
- `data_hash` — Fingerprint of source beads.jsonl
|
||||
- `status` — Per-metric state: `computed|approx|timeout|skipped` + elapsed ms
|
||||
- `as_of` / `as_of_commit` — Present when using `--as-of`
|
||||
|
||||
**Two-phase analysis:**
|
||||
- **Phase 1 (instant):** degree, topo sort, density
|
||||
- **Phase 2 (async, 500ms timeout):** PageRank, betweenness, HITS, eigenvector, cycles
|
||||
|
||||
### jq Quick Reference
|
||||
|
||||
```bash
|
||||
bv --robot-triage | jq '.quick_ref' # At-a-glance summary
|
||||
bv --robot-triage | jq '.recommendations[0]' # Top recommendation
|
||||
bv --robot-plan | jq '.plan.summary.highest_impact' # Best unblock target
|
||||
bv --robot-insights | jq '.status' # Check metric readiness
|
||||
bv --robot-insights | jq '.Cycles' # Circular deps (must fix!)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## UBS — Ultimate Bug Scanner
|
||||
|
||||
**Golden Rule:** `ubs <changed-files>` before every commit. Exit 0 = safe. Exit >0 = fix & re-run.
|
||||
|
||||
### Commands
|
||||
|
||||
```bash
|
||||
ubs file.rs file2.rs # Specific files (< 1s) — USE THIS
|
||||
ubs $(git diff --name-only --cached) # Staged files — before commit
|
||||
ubs --only=rust,toml src/ # Language filter (3-5x faster)
|
||||
ubs --ci --fail-on-warning . # CI mode — before PR
|
||||
ubs . # Whole project (ignores target/, Cargo.lock)
|
||||
```
|
||||
|
||||
### Output Format
|
||||
|
||||
```
|
||||
⚠️ Category (N errors)
|
||||
file.rs:42:5 – Issue description
|
||||
💡 Suggested fix
|
||||
Exit code: 1
|
||||
```
|
||||
|
||||
Parse: `file:line:col` → location | 💡 → how to fix | Exit 0/1 → pass/fail
|
||||
|
||||
### Fix Workflow
|
||||
|
||||
1. Read finding → category + fix suggestion
|
||||
2. Navigate `file:line:col` → view context
|
||||
3. Verify real issue (not false positive)
|
||||
4. Fix root cause (not symptom)
|
||||
5. Re-run `ubs <file>` → exit 0
|
||||
6. Commit
|
||||
|
||||
### Bug Severity
|
||||
|
||||
- **Critical (always fix):** Memory safety, use-after-free, data races, SQL injection
|
||||
- **Important (production):** Unwrap panics, resource leaks, overflow checks
|
||||
- **Contextual (judgment):** TODO/FIXME, println! debugging
|
||||
|
||||
---
|
||||
|
||||
## ast-grep vs ripgrep
|
||||
|
||||
**Use `ast-grep` when structure matters.** It parses code and matches AST nodes, ignoring comments/strings, and can **safely rewrite** code.
|
||||
|
||||
- Refactors/codemods: rename APIs, change import forms
|
||||
- Policy checks: enforce patterns across a repo
|
||||
- Editor/automation: LSP mode, `--json` output
|
||||
|
||||
**Use `ripgrep` when text is enough.** Fastest way to grep literals/regex.
|
||||
|
||||
- Recon: find strings, TODOs, log lines, config values
|
||||
- Pre-filter: narrow candidate files before ast-grep
|
||||
|
||||
### Rule of Thumb
|
||||
|
||||
- Need correctness or **applying changes** → `ast-grep`
|
||||
- Need raw speed or **hunting text** → `rg`
|
||||
- Often combine: `rg` to shortlist files, then `ast-grep` to match/modify
|
||||
|
||||
### Rust Examples
|
||||
|
||||
```bash
|
||||
# Find structured code (ignores comments)
|
||||
ast-grep run -l Rust -p 'fn $NAME($$$ARGS) -> $RET { $$$BODY }'
|
||||
|
||||
# Find all unwrap() calls
|
||||
ast-grep run -l Rust -p '$EXPR.unwrap()'
|
||||
|
||||
# Quick textual hunt
|
||||
rg -n 'println!' -t rust
|
||||
|
||||
# Combine speed + precision
|
||||
rg -l -t rust 'unwrap\(' | xargs ast-grep run -l Rust -p '$X.unwrap()' --json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Morph Warp Grep — AI-Powered Code Search
|
||||
|
||||
**Use `mcp__morph-mcp__warp_grep` for exploratory "how does X work?" questions.** An AI agent expands your query, greps the codebase, reads relevant files, and returns precise line ranges with full context.
|
||||
|
||||
**Use `ripgrep` for targeted searches.** When you know exactly what you're looking for.
|
||||
|
||||
**Use `ast-grep` for structural patterns.** When you need AST precision for matching/rewriting.
|
||||
|
||||
### When to Use What
|
||||
|
||||
| Scenario | Tool | Why |
|
||||
|----------|------|-----|
|
||||
| "How is pattern matching implemented?" | `warp_grep` | Exploratory; don't know where to start |
|
||||
| "Where is the quick reject filter?" | `warp_grep` | Need to understand architecture |
|
||||
| "Find all uses of `Regex::new`" | `ripgrep` | Targeted literal search |
|
||||
| "Find files with `println!`" | `ripgrep` | Simple pattern |
|
||||
| "Replace all `unwrap()` with `expect()`" | `ast-grep` | Structural refactor |
|
||||
|
||||
### warp_grep Usage
|
||||
|
||||
```
|
||||
mcp__morph-mcp__warp_grep(
|
||||
repoPath: "/path/to/dcg",
|
||||
query: "How does the safe pattern whitelist work?"
|
||||
)
|
||||
```
|
||||
|
||||
Returns structured results with file paths, line ranges, and extracted code snippets.
|
||||
|
||||
### Anti-Patterns
|
||||
|
||||
- **Don't** use `warp_grep` to find a specific function name → use `ripgrep`
|
||||
- **Don't** use `ripgrep` to understand "how does X work" → wastes time with manual reads
|
||||
- **Don't** use `ripgrep` for codemods → risks collateral edits
|
||||
|
||||
<!-- bv-agent-instructions-v1 -->
|
||||
|
||||
---
|
||||
|
||||
## Beads Workflow Integration
|
||||
|
||||
This project uses [beads_viewer](https://github.com/Dicklesworthstone/beads_viewer) for issue tracking. Issues are stored in `.beads/` and tracked in git.
|
||||
|
||||
**Note:** `br` is non-invasive—it never executes git commands directly. You must run git commands manually after `br sync --flush-only`.
|
||||
|
||||
### Essential Commands
|
||||
|
||||
```bash
|
||||
# View issues (launches TUI - avoid in automated sessions)
|
||||
bv
|
||||
|
||||
# CLI commands for agents (use these instead)
|
||||
br ready # Show issues ready to work (no blockers)
|
||||
br list --status=open # All open issues
|
||||
br show <id> # Full issue details with dependencies
|
||||
br create --title="..." --type=task --priority=2
|
||||
br update <id> --status=in_progress
|
||||
br close <id> --reason="Completed"
|
||||
br close <id1> <id2> # Close multiple issues at once
|
||||
br sync --flush-only # Export to JSONL (then manually: git add .beads/ && git commit)
|
||||
```
|
||||
|
||||
### Workflow Pattern
|
||||
|
||||
1. **Start**: Run `br ready` to find actionable work
|
||||
2. **Claim**: Use `br update <id> --status=in_progress`
|
||||
3. **Work**: Implement the task
|
||||
4. **Complete**: Use `br close <id>`
|
||||
5. **Sync**: Run `br sync --flush-only`, then `git add .beads/ && git commit -m "Update beads"`
|
||||
|
||||
### Key Concepts
|
||||
|
||||
- **Dependencies**: Issues can block other issues. `br ready` shows only unblocked work.
|
||||
- **Priority**: P0=critical, P1=high, P2=medium, P3=low, P4=backlog (use numbers, not words)
|
||||
- **Types**: task, bug, feature, epic, question, docs
|
||||
- **Blocking**: `br dep add <issue> <depends-on>` to add dependencies
|
||||
|
||||
### Session Protocol
|
||||
|
||||
**Before ending any session, run this checklist:**
|
||||
|
||||
```bash
|
||||
git status # Check what changed
|
||||
git add <files> # Stage code changes
|
||||
br sync --flush-only # Export beads to JSONL
|
||||
git add .beads/ # Stage beads changes
|
||||
git commit -m "..." # Commit code and beads
|
||||
git push # Push to remote
|
||||
```
|
||||
|
||||
### Best Practices
|
||||
|
||||
- Check `br ready` at session start to find available work
|
||||
- Update status as you work (in_progress → closed)
|
||||
- Create new issues with `br create` when you discover tasks
|
||||
- Use descriptive titles and set appropriate priority/type
|
||||
- Always run `br sync --flush-only` then commit .beads/ before ending session
|
||||
|
||||
<!-- end-bv-agent-instructions -->
|
||||
|
||||
## Landing the Plane (Session Completion)
|
||||
|
||||
**When ending a work session**, you MUST complete ALL steps below. Work is NOT complete until `git push` succeeds.
|
||||
|
||||
**MANDATORY WORKFLOW:**
|
||||
|
||||
1. **File issues for remaining work** - Create issues for anything that needs follow-up
|
||||
2. **Run quality gates** (if code changed) - Tests, linters, builds
|
||||
3. **Update issue status** - Close finished work, update in-progress items
|
||||
4. **PUSH TO REMOTE** - This is MANDATORY:
|
||||
```bash
|
||||
git pull --rebase
|
||||
br sync --flush-only
|
||||
git add .beads/
|
||||
git commit -m "Update beads"
|
||||
git push
|
||||
git status # MUST show "up to date with origin"
|
||||
```
|
||||
5. **Clean up** - Clear stashes, prune remote branches
|
||||
6. **Verify** - All changes committed AND pushed
|
||||
7. **Hand off** - Provide context for next session
|
||||
|
||||
**CRITICAL RULES:**
|
||||
- Work is NOT complete until `git push` succeeds
|
||||
- NEVER stop before pushing - that leaves work stranded locally
|
||||
- NEVER say "ready to push when you are" - YOU must push
|
||||
- If push fails, resolve and retry until it succeeds
|
||||
|
||||
---
|
||||
|
||||
## cass — Cross-Agent Session Search
|
||||
|
||||
`cass` indexes prior agent conversations (Claude Code, Codex, Cursor, Gemini, ChatGPT, etc.) so we can reuse solved problems.
|
||||
|
||||
**Rules:** Never run bare `cass` (TUI). Always use `--robot` or `--json`.
|
||||
|
||||
### Examples
|
||||
|
||||
```bash
|
||||
cass health
|
||||
cass search "async runtime" --robot --limit 5
|
||||
cass view /path/to/session.jsonl -n 42 --json
|
||||
cass expand /path/to/session.jsonl -n 42 -C 3 --json
|
||||
cass capabilities --json
|
||||
cass robot-docs guide
|
||||
```
|
||||
|
||||
### Tips
|
||||
|
||||
- Use `--fields minimal` for lean output
|
||||
- Filter by agent with `--agent`
|
||||
- Use `--days N` to limit to recent history
|
||||
|
||||
stdout is data-only, stderr is diagnostics; exit code 0 means success.
|
||||
|
||||
Treat cass as a way to avoid re-solving problems other agents already handled.
|
||||
|
||||
---
|
||||
|
||||
## Note for Codex/GPT-5.2
|
||||
|
||||
You constantly bother me and stop working with concerned questions that look similar to this:
|
||||
|
||||
```
|
||||
Unexpected changes (need guidance)
|
||||
|
||||
- Working tree still shows edits I did not make in Cargo.toml, Cargo.lock, src/runtime.rs, src/scope.rs. Please advise whether to keep/commit/revert these before any further work. I did not touch them.
|
||||
|
||||
Next steps (pick one)
|
||||
|
||||
1. Decide how to handle the unrelated modified files above so we can resume cleanly.
|
||||
```
|
||||
|
||||
NEVER EVER DO THAT AGAIN. The answer is literally ALWAYS the same: those are changes created by the potentially dozen of other agents working on the project at the same time. This is not only a common occurence, it happens multiple times PER MINUTE. The way to deal with it is simple: you NEVER, under ANY CIRCUMSTANCE, stash, revert, overwrite, or otherwise disturb in ANY way the work of other agents. Just treat those changes identically to changes that you yourself made. Just fool yourself into thinking YOU made the changes and simply don't recall it for some reason.
|
||||
|
||||
---
|
||||
|
||||
## Note on Built-in TODO Functionality
|
||||
|
||||
Also, if I ask you to explicitly use your built-in TODO functionality, don't complain about this and say you need to use beads. You can use built-in TODOs if I tell you specifically to do so. Always comply with such orders.
|
||||
|
||||
## TDD Requirements
|
||||
|
||||
Test-first development is mandatory:
|
||||
1. **RED** - Write failing test first
|
||||
2. **GREEN** - Minimal implementation to pass
|
||||
3. **REFACTOR** - Clean up while green
|
||||
|
||||
## Key Patterns
|
||||
|
||||
Find the simplest solution that meets all acceptance criteria.
|
||||
Use third party libraries whenever there's a well-maintained, active, and widely adopted solution (for example, date-fns for TS date math)
|
||||
Build extensible pieces of logic that can easily be integrated with other pieces.
|
||||
DRY principles should be loosely held.
|
||||
Architecture MUST be clear and well thought-out. Ask the user for clarification whenever ambiguity is discovered around architecture, or you think a better approach than planned exists.
|
||||
|
||||
---
|
||||
|
||||
## Third-Party Library Usage
|
||||
|
||||
If you aren't 100% sure how to use a third-party library, **SEARCH ONLINE** to find the latest documentation and mid-2025 best practices.
|
||||
|
||||
---
|
||||
|
||||
## Gitlore Robot Mode
|
||||
|
||||
The `lore` CLI has a robot mode optimized for AI agent consumption with compact JSON output, structured errors with machine-actionable recovery steps, meaningful exit codes, response timing metadata, field selection for token efficiency, and TTY auto-detection.
|
||||
|
||||
### Activation
|
||||
|
||||
```bash
|
||||
# Explicit flag
|
||||
lore --robot issues -n 10
|
||||
|
||||
# JSON shorthand (-J)
|
||||
lore -J issues -n 10
|
||||
|
||||
# Auto-detection (when stdout is not a TTY)
|
||||
lore issues | jq .
|
||||
|
||||
# Environment variable
|
||||
LORE_ROBOT=1 lore issues
|
||||
```
|
||||
|
||||
### Robot Mode Commands
|
||||
|
||||
```bash
|
||||
# List issues/MRs with JSON output
|
||||
lore --robot issues -n 10
|
||||
lore --robot mrs -s opened
|
||||
|
||||
# List with field selection (reduces token usage ~60%)
|
||||
lore --robot issues --fields minimal
|
||||
lore --robot mrs --fields iid,title,state,draft
|
||||
|
||||
# Show detailed entity info
|
||||
lore --robot issues 123
|
||||
lore --robot mrs 456 -p group/repo
|
||||
|
||||
# Count entities
|
||||
lore --robot count issues
|
||||
lore --robot count discussions --for mr
|
||||
|
||||
# Search indexed documents
|
||||
lore --robot search "authentication bug"
|
||||
|
||||
# Check sync status
|
||||
lore --robot status
|
||||
|
||||
# Run full sync pipeline
|
||||
lore --robot sync
|
||||
|
||||
# Run sync without resource events
|
||||
lore --robot sync --no-events
|
||||
|
||||
# Run ingestion only
|
||||
lore --robot ingest issues
|
||||
|
||||
# Check environment health
|
||||
lore --robot doctor
|
||||
|
||||
# Document and index statistics
|
||||
lore --robot stats
|
||||
|
||||
# Quick health pre-flight check (exit 0 = healthy, 19 = unhealthy)
|
||||
lore --robot health
|
||||
|
||||
# Generate searchable documents from ingested data
|
||||
lore --robot generate-docs
|
||||
|
||||
# Generate vector embeddings via Ollama
|
||||
lore --robot embed
|
||||
|
||||
# Agent self-discovery manifest (all commands, flags, exit codes, response schemas)
|
||||
lore robot-docs
|
||||
|
||||
# Version information
|
||||
lore --robot version
|
||||
```
|
||||
|
||||
### Response Format
|
||||
|
||||
All commands return compact JSON with a uniform envelope and timing metadata:
|
||||
|
||||
```json
|
||||
{"ok":true,"data":{...},"meta":{"elapsed_ms":42}}
|
||||
```
|
||||
|
||||
Errors return structured JSON to stderr with machine-actionable recovery steps:
|
||||
|
||||
```json
|
||||
{"error":{"code":"CONFIG_NOT_FOUND","message":"...","suggestion":"Run 'lore init'","actions":["lore init"]}}
|
||||
```
|
||||
|
||||
The `actions` array contains executable shell commands for automated recovery. It is omitted when empty.
|
||||
|
||||
### Field Selection
|
||||
|
||||
The `--fields` flag on `issues` and `mrs` list commands controls which fields appear in the JSON response:
|
||||
|
||||
```bash
|
||||
lore -J issues --fields minimal # Preset: iid, title, state, updated_at_iso
|
||||
lore -J mrs --fields iid,title,state,draft,labels # Custom field list
|
||||
```
|
||||
|
||||
### Exit Codes
|
||||
|
||||
| Code | Meaning |
|
||||
|------|---------|
|
||||
| 0 | Success |
|
||||
| 1 | Internal error / not implemented |
|
||||
| 2 | Usage error (invalid flags or arguments) |
|
||||
| 3 | Config invalid |
|
||||
| 4 | Token not set |
|
||||
| 5 | GitLab auth failed |
|
||||
| 6 | Resource not found |
|
||||
| 7 | Rate limited |
|
||||
| 8 | Network error |
|
||||
| 9 | Database locked |
|
||||
| 10 | Database error |
|
||||
| 11 | Migration failed |
|
||||
| 12 | I/O error |
|
||||
| 13 | Transform error |
|
||||
| 14 | Ollama unavailable |
|
||||
| 15 | Ollama model not found |
|
||||
| 16 | Embedding failed |
|
||||
| 17 | Not found (entity does not exist) |
|
||||
| 18 | Ambiguous match (use `-p` to specify project) |
|
||||
| 19 | Health check failed |
|
||||
| 20 | Config not found |
|
||||
|
||||
### Configuration Precedence
|
||||
|
||||
1. CLI flags (highest priority)
|
||||
2. Environment variables (`LORE_ROBOT`, `GITLAB_TOKEN`, `LORE_CONFIG_PATH`)
|
||||
3. Config file (`~/.config/lore/config.json`)
|
||||
4. Built-in defaults (lowest priority)
|
||||
|
||||
### Best Practices
|
||||
|
||||
- Use `lore --robot` or `lore -J` for all agent interactions
|
||||
- Check exit codes for error handling
|
||||
- Parse JSON errors from stderr; use `actions` array for automated recovery
|
||||
- Use `--fields minimal` to reduce token usage (~60% fewer tokens)
|
||||
- Use `-n` / `--limit` to control response size
|
||||
- Use `-q` / `--quiet` to suppress progress bars and non-essential output
|
||||
- Use `--color never` in non-TTY automation for ANSI-free output
|
||||
- Use `-v` / `-vv` / `-vvv` for increasing verbosity (debug/trace logging)
|
||||
- Use `--log-format json` for machine-readable log output to stderr
|
||||
- TTY detection handles piped commands automatically
|
||||
- Use `lore --robot health` as a fast pre-flight check before queries
|
||||
- Use `lore robot-docs` for response schema discovery
|
||||
- The `-p` flag supports fuzzy project matching (suffix and substring)
|
||||
174
Cargo.lock
generated
174
Cargo.lock
generated
@@ -169,6 +169,23 @@ version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
|
||||
|
||||
[[package]]
|
||||
name = "charmed-lipgloss"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "45e10db01f5eaea11d98ca5c5cffd8cc4add7ac56d0128d91ba1f2a3757b6c5a"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"colored",
|
||||
"crossterm",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror",
|
||||
"toml",
|
||||
"tracing",
|
||||
"unicode-width 0.1.14",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "chrono"
|
||||
version = "0.4.43"
|
||||
@@ -239,14 +256,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75"
|
||||
|
||||
[[package]]
|
||||
name = "comfy-table"
|
||||
version = "7.2.2"
|
||||
name = "colored"
|
||||
version = "2.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "958c5d6ecf1f214b4c2bbbbf6ab9523a864bd136dcf71a7e8904799acfe1ad47"
|
||||
checksum = "117725a109d387c937a1533ce01b450cbde6b88abceea8473c4d7a85853cda3c"
|
||||
dependencies = [
|
||||
"crossterm",
|
||||
"unicode-segmentation",
|
||||
"unicode-width",
|
||||
"lazy_static",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -258,10 +274,19 @@ dependencies = [
|
||||
"encode_unicode",
|
||||
"libc",
|
||||
"once_cell",
|
||||
"unicode-width",
|
||||
"unicode-width 0.2.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "convert_case"
|
||||
version = "0.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9"
|
||||
dependencies = [
|
||||
"unicode-segmentation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation"
|
||||
version = "0.9.4"
|
||||
@@ -319,9 +344,13 @@ checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"crossterm_winapi",
|
||||
"derive_more",
|
||||
"document-features",
|
||||
"mio",
|
||||
"parking_lot",
|
||||
"rustix",
|
||||
"signal-hook",
|
||||
"signal-hook-mio",
|
||||
"winapi",
|
||||
]
|
||||
|
||||
@@ -371,6 +400,28 @@ dependencies = [
|
||||
"powerfmt",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "derive_more"
|
||||
version = "2.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"
|
||||
dependencies = [
|
||||
"derive_more-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "derive_more-impl"
|
||||
version = "2.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"
|
||||
dependencies = [
|
||||
"convert_case",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"rustc_version",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dialoguer"
|
||||
version = "0.12.0"
|
||||
@@ -976,7 +1027,7 @@ checksum = "9375e112e4b463ec1b1c6c011953545c65a30164fbab5b581df32b3abf0dcb88"
|
||||
dependencies = [
|
||||
"console",
|
||||
"portable-atomic",
|
||||
"unicode-width",
|
||||
"unicode-width 0.2.2",
|
||||
"unit-prefix",
|
||||
"web-time",
|
||||
]
|
||||
@@ -1106,18 +1157,19 @@ checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
|
||||
|
||||
[[package]]
|
||||
name = "lore"
|
||||
version = "0.1.0"
|
||||
version = "0.8.3"
|
||||
dependencies = [
|
||||
"async-stream",
|
||||
"charmed-lipgloss",
|
||||
"chrono",
|
||||
"clap",
|
||||
"clap_complete",
|
||||
"comfy-table",
|
||||
"console",
|
||||
"dialoguer",
|
||||
"dirs",
|
||||
"flate2",
|
||||
"futures",
|
||||
"httpdate",
|
||||
"indicatif",
|
||||
"libc",
|
||||
"open",
|
||||
@@ -1180,6 +1232,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"log",
|
||||
"wasi",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
@@ -1573,6 +1626,15 @@ dependencies = [
|
||||
"sqlite-wasm-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc_version"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
|
||||
dependencies = [
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "1.1.3"
|
||||
@@ -1669,6 +1731,12 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "semver"
|
||||
version = "1.0.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.228"
|
||||
@@ -1712,6 +1780,15 @@ dependencies = [
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_spanned"
|
||||
version = "0.6.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_urlencoded"
|
||||
version = "0.7.1"
|
||||
@@ -1756,6 +1833,27 @@ version = "1.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
|
||||
|
||||
[[package]]
|
||||
name = "signal-hook"
|
||||
version = "0.3.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"signal-hook-registry",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "signal-hook-mio"
|
||||
version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"mio",
|
||||
"signal-hook",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "signal-hook-registry"
|
||||
version = "1.4.5"
|
||||
@@ -2027,6 +2125,47 @@ dependencies = [
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml"
|
||||
version = "0.8.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_spanned",
|
||||
"toml_datetime",
|
||||
"toml_edit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_datetime"
|
||||
version = "0.6.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_edit"
|
||||
version = "0.22.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"
|
||||
dependencies = [
|
||||
"indexmap",
|
||||
"serde",
|
||||
"serde_spanned",
|
||||
"toml_datetime",
|
||||
"toml_write",
|
||||
"winnow",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_write"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"
|
||||
|
||||
[[package]]
|
||||
name = "tower"
|
||||
version = "0.5.3"
|
||||
@@ -2182,6 +2321,12 @@ version = "1.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-width"
|
||||
version = "0.1.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-width"
|
||||
version = "0.2.2"
|
||||
@@ -2610,6 +2755,15 @@ version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
|
||||
|
||||
[[package]]
|
||||
name = "winnow"
|
||||
version = "0.7.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a5364e9d77fcdeeaa6062ced926ee3381faa2ee02d3eb83a5c27a8825540829"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wiremock"
|
||||
version = "0.6.5"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "lore"
|
||||
version = "0.1.0"
|
||||
version = "0.8.3"
|
||||
edition = "2024"
|
||||
description = "Gitlore - Local GitLab data management with semantic search"
|
||||
authors = ["Taylor Eernisse"]
|
||||
@@ -25,7 +25,7 @@ clap_complete = "4"
|
||||
dialoguer = "0.12"
|
||||
console = "0.16"
|
||||
indicatif = "0.18"
|
||||
comfy-table = "7"
|
||||
lipgloss = { package = "charmed-lipgloss", version = "0.1", default-features = false, features = ["native"] }
|
||||
open = "5"
|
||||
|
||||
# HTTP
|
||||
@@ -45,6 +45,7 @@ rand = "0.8"
|
||||
sha2 = "0.10"
|
||||
flate2 = "1"
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
httpdate = "1"
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
regex = "1"
|
||||
strsim = "0.11"
|
||||
|
||||
425
PROPOSED_CODE_FILE_REORGANIZATION_PLAN.md
Normal file
425
PROPOSED_CODE_FILE_REORGANIZATION_PLAN.md
Normal file
@@ -0,0 +1,425 @@
|
||||
# Proposed Code File Reorganization Plan
|
||||
|
||||
## Executive Summary
|
||||
|
||||
The codebase is 79 Rust source files / 46K lines across 7 top-level modules. Most modules (`gitlab/`, `embedding/`, `search/`, `documents/`, `ingestion/`) are well-organized. The pain points are:
|
||||
|
||||
1. **`core/` is a grab-bag** — 22 files mixing infrastructure, domain logic, DB operations, and an entire timeline pipeline
|
||||
2. **`main.rs` is 2713 lines** — ~30 handler functions that bridge CLI args to commands
|
||||
3. **`cli/mod.rs` is 949 lines** — every clap argument struct is packed into one file
|
||||
4. **Giant command files** — `who.rs` (6067 lines), `list.rs` (2931 lines) are unwieldy
|
||||
|
||||
This plan is organized into **three tiers** based on impact-to-risk ratio. Tier 1 changes are "no-brainers" — they reduce confusion with minimal import churn. Tier 2 changes are valuable but involve more cross-cutting import updates. Tier 3 changes are "maybe later" — they'd be nice but the juice might not be worth the squeeze right now.
|
||||
|
||||
---
|
||||
|
||||
## Current Structure (Annotated)
|
||||
|
||||
```
|
||||
src/
|
||||
├── main.rs (2713 lines) ← dispatch + ~30 handler functions + error helpers
|
||||
├── lib.rs (9 lines)
|
||||
├── cli/
|
||||
│ ├── mod.rs (949 lines) ← ALL clap arg structs crammed here
|
||||
│ ├── autocorrect.rs (945 lines)
|
||||
│ ├── progress.rs (92 lines)
|
||||
│ ├── robot.rs (111 lines)
|
||||
│ └── commands/
|
||||
│ ├── mod.rs (50 lines) — re-exports
|
||||
│ ├── auth_test.rs
|
||||
│ ├── count.rs (406 lines)
|
||||
│ ├── doctor.rs (576 lines)
|
||||
│ ├── drift.rs (642 lines)
|
||||
│ ├── embed.rs
|
||||
│ ├── generate_docs.rs (320 lines)
|
||||
│ ├── ingest.rs (1064 lines)
|
||||
│ ├── init.rs (174 lines)
|
||||
│ ├── list.rs (2931 lines) ← handles issues, MRs, AND notes listing
|
||||
│ ├── search.rs (418 lines)
|
||||
│ ├── show.rs (1377 lines)
|
||||
│ ├── stats.rs (505 lines)
|
||||
│ ├── sync_status.rs (454 lines)
|
||||
│ ├── sync.rs (576 lines)
|
||||
│ ├── timeline.rs (488 lines)
|
||||
│ └── who.rs (6067 lines) ← 5 sub-modes: expert, workload, active, overlap, reviews
|
||||
├── core/
|
||||
│ ├── mod.rs (25 lines)
|
||||
│ ├── backoff.rs ← retry logic (used by ingestion)
|
||||
│ ├── config.rs (789 lines) ← configuration types
|
||||
│ ├── db.rs (970 lines) ← connection + 22 migrations
|
||||
│ ├── dependent_queue.rs (330 lines) ← job queue (used by ingestion orchestrator)
|
||||
│ ├── error.rs (295 lines) ← error enum + exit codes
|
||||
│ ├── events_db.rs (199 lines) ← resource event upserts (used by ingestion)
|
||||
│ ├── lock.rs (228 lines) ← filesystem sync lock
|
||||
│ ├── logging.rs (179 lines) ← tracing filter builders
|
||||
│ ├── metrics.rs (566 lines) ← tracing-based stage timing
|
||||
│ ├── note_parser.rs (563 lines) ← cross-ref extraction from note bodies
|
||||
│ ├── paths.rs ← config/db/log file path resolution
|
||||
│ ├── payloads.rs (204 lines) ← raw JSON payload storage
|
||||
│ ├── project.rs (274 lines) ← fuzzy project resolution from DB
|
||||
│ ├── references.rs (551 lines) ← entity cross-reference extraction
|
||||
│ ├── shutdown.rs ← graceful shutdown via tokio signal
|
||||
│ ├── sync_run.rs (218 lines) ← sync run recording to DB
|
||||
│ ├── time.rs ← time conversion utilities
|
||||
│ ├── timeline.rs (284 lines) ← timeline types + EntityRef
|
||||
│ ├── timeline_collect.rs (695 lines) ← Stage 4: collect events from DB
|
||||
│ ├── timeline_expand.rs (557 lines) ← Stage 3: expand via cross-refs
|
||||
│ └── timeline_seed.rs (552 lines) ← Stage 1: FTS search seeding
|
||||
├── documents/ ← well-organized, 3 focused files
|
||||
├── embedding/ ← well-organized, 6 focused files
|
||||
├── gitlab/ ← well-organized, with transformers/ subdir
|
||||
├── ingestion/ ← well-organized, 8 focused files
|
||||
└── search/ ← well-organized, 5 focused files
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Tier 1: No-Brainers (Do First)
|
||||
|
||||
### 1.1 Extract `timeline/` from `core/`
|
||||
|
||||
**What:** Move the 4 timeline files into their own top-level module `src/timeline/`.
|
||||
|
||||
**Current location:**
|
||||
- `core/timeline.rs` (284 lines) — types: `EntityRef`, `ExpandedEntityRef`, `TimelineEvent`, `TimelineEventType`, etc.
|
||||
- `core/timeline_seed.rs` (552 lines) — Stage 1: FTS-based seeding
|
||||
- `core/timeline_expand.rs` (557 lines) — Stage 3: cross-reference expansion
|
||||
- `core/timeline_collect.rs` (695 lines) — Stage 4: event collection from DB
|
||||
|
||||
**New structure:**
|
||||
```
|
||||
src/timeline/
|
||||
├── mod.rs ← types (from timeline.rs) + re-exports
|
||||
├── seed.rs ← from timeline_seed.rs
|
||||
├── expand.rs ← from timeline_expand.rs
|
||||
└── collect.rs ← from timeline_collect.rs
|
||||
```
|
||||
|
||||
**Rationale:** These 4 files form a cohesive 5-stage pipeline (SEED→HYDRATE→EXPAND→COLLECT→RENDER). They have nothing to do with "core" infrastructure like `db.rs`, `config.rs`, or `error.rs`. They only import from `core::error`, `core::time`, and `search::fts` — all of which remain accessible via `crate::core::*` and `crate::search::*` after the move.
|
||||
|
||||
**Import changes needed:**
|
||||
- `cli/commands/timeline.rs`: `use crate::core::timeline::*` → `use crate::timeline::*`, same for `timeline_seed`, `timeline_expand`, `timeline_collect`
|
||||
- `core/mod.rs`: remove the 4 `pub mod timeline*` lines
|
||||
- `lib.rs`: add `pub mod timeline;`
|
||||
|
||||
**Risk: LOW** — Only 1 consumer (`cli/commands/timeline.rs`) + internal cross-references between the 4 files.
|
||||
|
||||
---
|
||||
|
||||
### 1.2 Extract `xref/` (cross-reference extraction) from `core/`
|
||||
|
||||
**What:** Move `note_parser.rs` and `references.rs` into `src/xref/`.
|
||||
|
||||
**Current location:**
|
||||
- `core/note_parser.rs` (563 lines) — parses note bodies for "mentioned in group/repo#123" patterns, persists to `note_cross_references` table
|
||||
- `core/references.rs` (551 lines) — extracts entity references from state events and closing MRs, writes to `entity_references` table
|
||||
|
||||
**New structure:**
|
||||
```
|
||||
src/xref/
|
||||
├── mod.rs ← re-exports
|
||||
├── note_parser.rs ← from core/note_parser.rs
|
||||
└── references.rs ← from core/references.rs
|
||||
```
|
||||
|
||||
**Rationale:** These files implement a specific domain concept — extracting and persisting cross-references between issues and MRs. They are not "core infrastructure." They're consumed by `ingestion/orchestrator.rs` for the cross-reference extraction phase, and the data they produce is consumed by the timeline pipeline. Putting them in their own module makes the data flow clearer: `ingestion → xref → timeline`.
|
||||
|
||||
**Import changes needed:**
|
||||
- `ingestion/orchestrator.rs`: `use crate::core::references::*` → `use crate::xref::references::*`
|
||||
- `ingestion/orchestrator.rs`: `use crate::core::note_parser::*` (if used directly — needs verification) → `use crate::xref::*`
|
||||
- `core/mod.rs`: remove `pub mod note_parser; pub mod references;`
|
||||
- `lib.rs`: add `pub mod xref;`
|
||||
- Internal: the files use `super::error::Result` and `super::time::now_ms` which become `crate::core::error::Result` and `crate::core::time::now_ms`
|
||||
|
||||
**Risk: LOW** — 2-3 consumers at most. The files already use `super::` internally which just needs updating to `crate::core::`.
|
||||
|
||||
---
|
||||
|
||||
## Tier 2: Good Improvements (Do After Tier 1)
|
||||
|
||||
### 2.1 Group ingestion-adjacent DB operations
|
||||
|
||||
**What:** Move `events_db.rs`, `dependent_queue.rs`, `payloads.rs`, and `sync_run.rs` from `core/` into `ingestion/` since they exclusively serve the ingestion pipeline.
|
||||
|
||||
**Current consumers:**
|
||||
- `events_db.rs` → only used by `cli/commands/count.rs` (for event counts)
|
||||
- `dependent_queue.rs` → only used by `ingestion/orchestrator.rs` and `main.rs` (to release locked jobs)
|
||||
- `payloads.rs` → only used by `ingestion/discussions.rs`, `ingestion/issues.rs`, `ingestion/merge_requests.rs`, `ingestion/mr_discussions.rs`
|
||||
- `sync_run.rs` → only used by `cli/commands/sync.rs` and `cli/commands/sync_status.rs`
|
||||
|
||||
**New structure:**
|
||||
```
|
||||
src/ingestion/
|
||||
├── (existing files...)
|
||||
├── events_db.rs ← from core/events_db.rs
|
||||
├── dependent_queue.rs ← from core/dependent_queue.rs
|
||||
├── payloads.rs ← from core/payloads.rs
|
||||
└── sync_run.rs ← from core/sync_run.rs
|
||||
```
|
||||
|
||||
**Rationale:** All 4 files exist to support the ingestion pipeline:
|
||||
- `events_db.rs` upserts resource state/label/milestone events fetched during ingestion
|
||||
- `dependent_queue.rs` manages the job queue that drives incremental discussion fetching
|
||||
- `payloads.rs` stores the raw JSON payloads fetched from GitLab
|
||||
- `sync_run.rs` records when syncs start/finish and their metrics
|
||||
|
||||
When you're looking for "how does ingestion work?", you'd naturally look in `ingestion/`. Having these scattered in `core/` requires knowing the hidden dependency.
|
||||
|
||||
**Import changes needed:**
|
||||
- `events_db.rs`: 1 consumer in `cli/commands/count.rs` changes from `crate::core::events_db` → `crate::ingestion::events_db`
|
||||
- `dependent_queue.rs`: 2 consumers — `ingestion/orchestrator.rs` (becomes `super::dependent_queue`) and `main.rs`
|
||||
- `payloads.rs`: 4 consumers in `ingestion/*.rs` (become `super::payloads`)
|
||||
- `sync_run.rs`: 2 consumers in `cli/commands/sync.rs` and `sync_status.rs`
|
||||
- Internal references change from `super::error` / `super::time` to `crate::core::error` / `crate::core::time`
|
||||
|
||||
**Risk: MEDIUM** — More import changes, but all straightforward. The internal `super::` references need the most attention.
|
||||
|
||||
**Alternatively:** If moving feels like too much churn, a lighter option is to create `core/ingestion_db.rs` that re-exports from these 4 files, making the grouping visible without moving files. But I think the move is cleaner.
|
||||
|
||||
---
|
||||
|
||||
### 2.2 Split `cli/mod.rs` — move arg structs to their command files
|
||||
|
||||
**What:** Move each `*Args` struct from `cli/mod.rs` into the corresponding `cli/commands/*.rs` file. Keep `Cli` struct, `Commands` enum, and `detect_robot_mode_from_env()` in `cli/mod.rs`.
|
||||
|
||||
**Currently `cli/mod.rs` (949 lines) contains:**
|
||||
- `Cli` struct (81 lines) — the root clap parser
|
||||
- `Commands` enum (193 lines) — all subcommand variants
|
||||
- `IssuesArgs` (86 lines) → move to `commands/list.rs` or stay near issues handling
|
||||
- `MrsArgs` (93 lines) → move to `commands/list.rs` or stay near MRs handling
|
||||
- `NotesArgs` (99 lines) → move to `commands/list.rs`
|
||||
- `IngestArgs` (33 lines) → move to `commands/ingest.rs`
|
||||
- `StatsArgs` (19 lines) → move to `commands/stats.rs`
|
||||
- `SearchArgs` (58 lines) → move to `commands/search.rs`
|
||||
- `GenerateDocsArgs` (9 lines) → move to `commands/generate_docs.rs`
|
||||
- `SyncArgs` (39 lines) → move to `commands/sync.rs`
|
||||
- `EmbedArgs` (15 lines) → move to `commands/embed.rs`
|
||||
- `TimelineArgs` (53 lines) → move to `commands/timeline.rs`
|
||||
- `WhoArgs` (76 lines) → move to `commands/who.rs`
|
||||
- `CountArgs` (9 lines) → move to `commands/count.rs`
|
||||
|
||||
**After refactoring, `cli/mod.rs` shrinks to ~300 lines** (just `Cli` + `Commands` + the inlined variants like `Init`, `Drift`, `Backup`, `Reset`).
|
||||
|
||||
**Rationale:** When adding a new flag to the `who` command, you currently have to edit `cli/mod.rs` (the args struct), `cli/commands/who.rs` (the implementation), and `main.rs` (the dispatch). If the args struct lives in `commands/who.rs`, you only need two files. This is the standard pattern in mature clap-based Rust CLIs.
|
||||
|
||||
**Import changes needed:**
|
||||
- `main.rs` currently does `use lore::cli::{..., WhoArgs, ...}` — these would become `use lore::cli::commands::{..., WhoArgs, ...}` or the `commands/mod.rs` re-exports them
|
||||
- Each `commands/*.rs` gets its own `#[derive(Parser)]` struct
|
||||
- `Commands` enum in `cli/mod.rs` keeps using the types but imports from `commands::*`
|
||||
|
||||
**Risk: MEDIUM** — Lots of `use` path changes in `main.rs`, but purely mechanical. No logic changes.
|
||||
|
||||
---
|
||||
|
||||
## Tier 3: Consider Later
|
||||
|
||||
### 3.1 Split `main.rs` (2713 lines)
|
||||
|
||||
**The problem:** `main.rs` contains `main()`, ~30 `handle_*` functions, error handling, clap error formatting, fuzzy command matching, and the `robot-docs` JSON manifest (a 400+ line inline JSON literal).
|
||||
|
||||
**Possible approach:**
|
||||
- Extract `handle_*` functions into `cli/dispatch.rs` (the routing layer)
|
||||
- Extract error handling into `cli/errors.rs`
|
||||
- Extract `handle_robot_docs` + the JSON manifest into `cli/robot_docs.rs`
|
||||
- Keep `main()` in `main.rs` at ~150 lines (just the tracing setup + dispatch call)
|
||||
|
||||
**Why Tier 3:** This is the messiest split. The handler functions depend on the `cli::commands::*` functions AND the `cli::robot::*` helpers AND direct `std::process::exit` calls. Making this work cleanly requires careful thought about the error boundary between `main.rs` (binary) and `lib.rs` (library).
|
||||
|
||||
**Risk: HIGH** — Every handler function touches `robot_mode`, constructs its own timer, opens the DB, and manages error display. The boilerplate is high but consistent, so splitting would just move it around without reducing complexity.
|
||||
|
||||
---
|
||||
|
||||
### 3.2 Split `cli/commands/who.rs` (6067 lines)
|
||||
|
||||
**The problem:** This file implements 5 distinct modes (expert, workload, active, overlap, reviews), each with its own query, scoring model, and output formatting. It also includes the time-decay scoring model (~500 lines) and per-MR detail breakdown logic.
|
||||
|
||||
**Possible split:**
|
||||
```
|
||||
src/cli/commands/who/
|
||||
├── mod.rs ← WhoRun dispatcher, shared types
|
||||
├── expert.rs ← expert mode (path-based file expertise lookup)
|
||||
├── workload.rs ← workload mode (user's assigned issues/MRs)
|
||||
├── active.rs ← active discussions mode
|
||||
├── overlap.rs ← file overlap between users
|
||||
├── reviews.rs ← review pattern analysis
|
||||
└── scoring.rs ← time-decay expert scoring model
|
||||
```
|
||||
|
||||
**Why Tier 3:** The 5 modes share many helper functions, database connection patterns, and output formatting logic. Splitting would require carefully identifying the shared helpers and deciding where they live. The file is big but internally consistent — the modes use a shared dispatcher pattern and common types.
|
||||
|
||||
---
|
||||
|
||||
### 3.3 Split `cli/commands/list.rs` (2931 lines)
|
||||
|
||||
**The problem:** This file handles issue listing, MR listing, AND note listing — three related but distinct operations with separate query builders, output formatters, and test suites.
|
||||
|
||||
**Possible split:**
|
||||
```
|
||||
src/cli/commands/
|
||||
├── list_issues.rs ← issue listing + query builder
|
||||
├── list_mrs.rs ← MR listing + query builder
|
||||
├── list_notes.rs ← note listing + query builder
|
||||
└── list.rs ← shared types (ListFilters, etc.) + re-exports
|
||||
```
|
||||
|
||||
**Why Tier 3:** Same issue as `who.rs` — the three listing modes share query building patterns, field selection logic, and sorting code. Splitting requires identifying and extracting the shared pieces first.
|
||||
|
||||
---
|
||||
|
||||
## Files NOT Recommended to Move
|
||||
|
||||
These files belong exactly where they are:
|
||||
|
||||
| File | Why it belongs in `core/` |
|
||||
|------|--------------------------|
|
||||
| `config.rs` | Config types used by nearly everything |
|
||||
| `db.rs` | Database connection + migrations — foundational |
|
||||
| `error.rs` | Error types used by every module |
|
||||
| `paths.rs` | File path resolution — infrastructure |
|
||||
| `logging.rs` | Tracing setup — infrastructure |
|
||||
| `lock.rs` | Filesystem sync lock — infrastructure |
|
||||
| `shutdown.rs` | Graceful shutdown signal — infrastructure |
|
||||
| `backoff.rs` | Retry math — infrastructure |
|
||||
| `time.rs` | Time conversion — used everywhere |
|
||||
| `metrics.rs` | Tracing metrics layer — infrastructure |
|
||||
| `project.rs` | Fuzzy project resolution — used by 8+ consumers across modules |
|
||||
|
||||
These files are legitimate "core infrastructure" used across multiple modules. Moving them would create import churn with no clarity gain.
|
||||
|
||||
---
|
||||
|
||||
## Files NOT Recommended to Split/Merge
|
||||
|
||||
| File | Why leave it alone |
|
||||
|------|-------------------|
|
||||
| `documents/extractor.rs` (2341 lines) | One cohesive extractor per entity type — the size comes from per-type formatting logic, not mixed concerns |
|
||||
| `ingestion/orchestrator.rs` (1703 lines) | Single orchestration flow — splitting would scatter the pipeline |
|
||||
| `gitlab/graphql.rs` (1293 lines) | GraphQL client with adaptive paging — cohesive |
|
||||
| `gitlab/client.rs` (851 lines) | REST client with all endpoints — cohesive |
|
||||
| `cli/autocorrect.rs` (945 lines) | Correction registry + fuzzy matching — splitting gains nothing |
|
||||
|
||||
---
|
||||
|
||||
## Proposed Final Structure (Tiers 1+2)
|
||||
|
||||
```
|
||||
src/
|
||||
├── main.rs (2713 lines — unchanged for now)
|
||||
├── lib.rs (adds: pub mod timeline; pub mod xref;)
|
||||
├── cli/
|
||||
│ ├── mod.rs (~300 lines — Cli + Commands only, args moved out)
|
||||
│ ├── autocorrect.rs (unchanged)
|
||||
│ ├── progress.rs (unchanged)
|
||||
│ ├── robot.rs (unchanged)
|
||||
│ └── commands/
|
||||
│ ├── mod.rs (re-exports + WhoArgs, IssuesArgs, etc.)
|
||||
│ ├── (all existing files — unchanged but with args structs moved in)
|
||||
│ └── ...
|
||||
├── core/ (slimmed: 14 files → infrastructure only)
|
||||
│ ├── mod.rs
|
||||
│ ├── backoff.rs
|
||||
│ ├── config.rs
|
||||
│ ├── db.rs
|
||||
│ ├── error.rs
|
||||
│ ├── lock.rs
|
||||
│ ├── logging.rs
|
||||
│ ├── metrics.rs
|
||||
│ ├── paths.rs
|
||||
│ ├── project.rs
|
||||
│ ├── shutdown.rs
|
||||
│ └── time.rs
|
||||
├── timeline/ (NEW — extracted from core/)
|
||||
│ ├── mod.rs (types from core/timeline.rs)
|
||||
│ ├── seed.rs (from core/timeline_seed.rs)
|
||||
│ ├── expand.rs (from core/timeline_expand.rs)
|
||||
│ └── collect.rs (from core/timeline_collect.rs)
|
||||
├── xref/ (NEW — extracted from core/)
|
||||
│ ├── mod.rs
|
||||
│ ├── note_parser.rs (from core/note_parser.rs)
|
||||
│ └── references.rs (from core/references.rs)
|
||||
├── ingestion/ (gains 4 files from core/)
|
||||
│ ├── (existing files...)
|
||||
│ ├── events_db.rs (from core/events_db.rs)
|
||||
│ ├── dependent_queue.rs (from core/dependent_queue.rs)
|
||||
│ ├── payloads.rs (from core/payloads.rs)
|
||||
│ └── sync_run.rs (from core/sync_run.rs)
|
||||
├── documents/ (unchanged)
|
||||
├── embedding/ (unchanged)
|
||||
├── gitlab/ (unchanged)
|
||||
└── search/ (unchanged)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Import Change Tracking
|
||||
|
||||
### Tier 1.1: Timeline extraction
|
||||
|
||||
| Consumer file | Old import | New import |
|
||||
|---------------|-----------|------------|
|
||||
| `cli/commands/timeline.rs:10-15` | `crate::core::timeline::*` | `crate::timeline::*` |
|
||||
| `cli/commands/timeline.rs:13` | `crate::core::timeline_collect::collect_events` | `crate::timeline::collect_events` (or `crate::timeline::collect::collect_events`) |
|
||||
| `cli/commands/timeline.rs:14` | `crate::core::timeline_expand::expand_timeline` | `crate::timeline::expand_timeline` |
|
||||
| `cli/commands/timeline.rs:15` | `crate::core::timeline_seed::seed_timeline` | `crate::timeline::seed_timeline` |
|
||||
| `core/timeline_seed.rs:7-8` | `super::timeline::*` | `super::*` (or `crate::timeline::*` depending on structure) |
|
||||
| `core/timeline_expand.rs:6` | `super::timeline::*` | `super::*` |
|
||||
| `core/timeline_collect.rs:4` | `super::timeline::*` | `super::*` |
|
||||
| `core/timeline_seed.rs:8` | `crate::search::*` | `crate::search::*` (no change) |
|
||||
| `core/timeline_seed.rs:6-7` | `super::error::Result` | `crate::core::error::Result` |
|
||||
| `core/timeline_expand.rs:5` | `super::error::Result` | `crate::core::error::Result` |
|
||||
| `core/timeline_collect.rs:3` | `super::error::*` | `crate::core::error::*` |
|
||||
|
||||
### Tier 1.2: Cross-reference extraction
|
||||
|
||||
| Consumer file | Old import | New import |
|
||||
|---------------|-----------|------------|
|
||||
| `ingestion/orchestrator.rs:10-12` | `crate::core::references::*` | `crate::xref::references::*` |
|
||||
| `core/note_parser.rs:7-8` | `super::error::Result`, `super::time::now_ms` | `crate::core::error::Result`, `crate::core::time::now_ms` |
|
||||
| `core/references.rs:4-5` | `super::error::Result`, `super::time::now_ms` | `crate::core::error::Result`, `crate::core::time::now_ms` |
|
||||
|
||||
### Tier 2.1: Ingestion-adjacent DB ops
|
||||
|
||||
| Consumer file | Old import | New import |
|
||||
|---------------|-----------|------------|
|
||||
| `cli/commands/count.rs:9` | `crate::core::events_db::*` | `crate::ingestion::events_db::*` |
|
||||
| `ingestion/orchestrator.rs:6-8` | `crate::core::dependent_queue::*` | `super::dependent_queue::*` |
|
||||
| `main.rs:37` | `crate::core::dependent_queue::release_all_locked_jobs` | `crate::ingestion::dependent_queue::release_all_locked_jobs` |
|
||||
| `ingestion/discussions.rs:7` | `crate::core::payloads::*` | `super::payloads::*` |
|
||||
| `ingestion/issues.rs:9` | `crate::core::payloads::*` | `super::payloads::*` |
|
||||
| `ingestion/merge_requests.rs:8` | `crate::core::payloads::*` | `super::payloads::*` |
|
||||
| `ingestion/mr_discussions.rs:7` | `crate::core::payloads::*` | `super::payloads::*` |
|
||||
| `cli/commands/sync.rs` | (uses `crate::core::sync_run::*`) | `crate::ingestion::sync_run::*` |
|
||||
| `cli/commands/sync_status.rs` | (uses `crate::core::sync_run::*` or `crate::core::metrics::*`) | check and update |
|
||||
| Internal: `events_db.rs:4-5` | `super::error::*`, `super::time::*` | `crate::core::error::*`, `crate::core::time::*` |
|
||||
| Internal: `dependent_queue.rs:5-6` | `super::error::Result`, `super::time::now_ms` | `crate::core::error::Result`, `crate::core::time::now_ms` |
|
||||
| Internal: `payloads.rs:9-10` | `super::error::Result`, `super::time::now_ms` | `crate::core::error::Result`, `crate::core::time::now_ms` |
|
||||
| Internal: `sync_run.rs:2-4` | `super::error::*`, `super::metrics::*`, `super::time::*` | `crate::core::error::*`, `crate::core::metrics::*`, `crate::core::time::*` |
|
||||
|
||||
---
|
||||
|
||||
## Execution Order
|
||||
|
||||
1. **Tier 1.1** — Extract timeline → `src/timeline/` (LOW risk, 1 consumer)
|
||||
2. **Tier 1.2** — Extract xref → `src/xref/` (LOW risk, 1-2 consumers)
|
||||
3. **Cargo check + clippy + test** after each tier
|
||||
4. **Tier 2.1** — Move ingestion DB ops (MEDIUM risk, more consumers)
|
||||
5. **Cargo check + clippy + test**
|
||||
6. **Tier 2.2** — Split `cli/mod.rs` args (MEDIUM risk, mostly mechanical)
|
||||
7. **Cargo check + clippy + test + fmt**
|
||||
|
||||
Each tier should be its own commit for easy rollback.
|
||||
|
||||
---
|
||||
|
||||
## What This Achieves
|
||||
|
||||
**Before:** A developer looking at `core/` sees 22 files and has to mentally sort "infrastructure vs. domain logic vs. pipeline stage." The timeline pipeline is invisible unless you know to look in `core/`.
|
||||
|
||||
**After:**
|
||||
- `core/` has 12 files, all clearly infrastructure (db, config, error, paths, logging, lock, shutdown, backoff, time, metrics, project)
|
||||
- `timeline/` is a discoverable first-class module showing the 5-stage pipeline
|
||||
- `xref/` makes the cross-reference extraction domain visible
|
||||
- `ingestion/` contains everything related to data fetching: the orchestrator, entity ingestors, AND their supporting DB operations
|
||||
- `cli/mod.rs` is lean — just the top-level Cli struct and Commands enum
|
||||
|
||||
A new developer (or coding agent) can now answer "where is the timeline code?" → `src/timeline/`, "where is ingestion?" → `src/ingestion/`, "where is cross-reference extraction?" → `src/xref/`, without needing institutional knowledge.
|
||||
380
README.md
380
README.md
@@ -1,6 +1,6 @@
|
||||
# Gitlore
|
||||
|
||||
Local GitLab data management with semantic search and temporal intelligence. Syncs issues, MRs, discussions, and notes from GitLab to a local SQLite database for fast, offline-capable querying, filtering, hybrid search, and chronological event reconstruction.
|
||||
Local GitLab data management with semantic search, people intelligence, and temporal analysis. Syncs issues, MRs, discussions, notes, and work item statuses from GitLab to a local SQLite database for fast, offline-capable querying, filtering, hybrid search, chronological event reconstruction, and expert discovery.
|
||||
|
||||
## Features
|
||||
|
||||
@@ -8,16 +8,21 @@ Local GitLab data management with semantic search and temporal intelligence. Syn
|
||||
- **Incremental sync**: Cursor-based sync only fetches changes since last sync
|
||||
- **Full re-sync**: Reset cursors and fetch all data from scratch when needed
|
||||
- **Multi-project**: Track issues and MRs across multiple GitLab projects
|
||||
- **Rich filtering**: Filter by state, author, assignee, labels, milestone, due date, draft status, reviewer, branches
|
||||
- **Rich filtering**: Filter by state, author, assignee, labels, milestone, due date, draft status, reviewer, branches, work item status
|
||||
- **Hybrid search**: Combines FTS5 lexical search with Ollama-powered vector embeddings via Reciprocal Rank Fusion
|
||||
- **People intelligence**: Expert discovery, workload analysis, review patterns, active discussions, and code ownership overlap
|
||||
- **Timeline pipeline**: Reconstructs chronological event histories by combining search, graph traversal, and event aggregation across related entities
|
||||
- **Git history linking**: Tracks merge and squash commit SHAs to connect MRs with git history
|
||||
- **File change tracking**: Records which files each MR touches, enabling file-level history queries
|
||||
- **Raw payload storage**: Preserves original GitLab API responses for debugging
|
||||
- **Discussion threading**: Full support for issue and MR discussions including inline code review comments
|
||||
- **Cross-reference tracking**: Automatic extraction of "closes", "mentioned" relationships between MRs and issues
|
||||
- **Work item status enrichment**: Fetches issue statuses (e.g., "To do", "In progress", "Done") from GitLab's GraphQL API with adaptive page sizing, color-coded display, and case-insensitive filtering
|
||||
- **Resource event history**: Tracks state changes, label events, and milestone events for issues and MRs
|
||||
- **Robot mode**: Machine-readable JSON output with structured errors and meaningful exit codes
|
||||
- **Note querying**: Rich filtering over discussion notes by author, type, path, resolution status, time range, and body content
|
||||
- **Discussion drift detection**: Semantic analysis of how discussions diverge from original issue intent
|
||||
- **Robot mode**: Machine-readable JSON output with structured errors, meaningful exit codes, and actionable recovery steps
|
||||
- **Error tolerance**: Auto-corrects common CLI mistakes (case, typos, single-dash flags, value casing) with teaching feedback
|
||||
- **Observability**: Verbosity controls, JSON log format, structured metrics, and stage timing
|
||||
|
||||
## Installation
|
||||
@@ -60,6 +65,21 @@ lore mrs 456
|
||||
# Search across all indexed data
|
||||
lore search "authentication bug"
|
||||
|
||||
# Who knows about this code area?
|
||||
lore who src/features/auth/
|
||||
|
||||
# What is @asmith working on?
|
||||
lore who @asmith
|
||||
|
||||
# Timeline of events related to deployments
|
||||
lore timeline "deployment"
|
||||
|
||||
# Timeline for a specific issue
|
||||
lore timeline issue:42
|
||||
|
||||
# Query notes by author
|
||||
lore notes --author alice --since 7d
|
||||
|
||||
# Robot mode (machine-readable JSON)
|
||||
lore -J issues -n 5 | jq .
|
||||
```
|
||||
@@ -80,13 +100,15 @@ Configuration is stored in `~/.config/lore/config.json` (or `$XDG_CONFIG_HOME/lo
|
||||
{ "path": "group/project" },
|
||||
{ "path": "other-group/other-project" }
|
||||
],
|
||||
"defaultProject": "group/project",
|
||||
"sync": {
|
||||
"backfillDays": 14,
|
||||
"staleLockMinutes": 10,
|
||||
"heartbeatIntervalSeconds": 30,
|
||||
"cursorRewindSeconds": 2,
|
||||
"primaryConcurrency": 4,
|
||||
"dependentConcurrency": 2
|
||||
"dependentConcurrency": 2,
|
||||
"fetchWorkItemStatus": true
|
||||
},
|
||||
"storage": {
|
||||
"compressRawPayloads": true
|
||||
@@ -96,6 +118,15 @@ Configuration is stored in `~/.config/lore/config.json` (or `$XDG_CONFIG_HOME/lo
|
||||
"model": "nomic-embed-text",
|
||||
"baseUrl": "http://localhost:11434",
|
||||
"concurrency": 4
|
||||
},
|
||||
"scoring": {
|
||||
"authorWeight": 25,
|
||||
"reviewerWeight": 10,
|
||||
"noteBonus": 1,
|
||||
"authorHalfLifeDays": 180,
|
||||
"reviewerHalfLifeDays": 90,
|
||||
"noteHalfLifeDays": 45,
|
||||
"excludedUsernames": ["bot-user"]
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -107,12 +138,14 @@ Configuration is stored in `~/.config/lore/config.json` (or `$XDG_CONFIG_HOME/lo
|
||||
| `gitlab` | `baseUrl` | -- | GitLab instance URL (required) |
|
||||
| `gitlab` | `tokenEnvVar` | `GITLAB_TOKEN` | Environment variable containing API token |
|
||||
| `projects` | `path` | -- | Project path (e.g., `group/project`) |
|
||||
| *(top-level)* | `defaultProject` | none | Fallback project path used when `-p` is omitted. Must match a configured project path (exact or suffix). CLI `-p` always overrides. |
|
||||
| `sync` | `backfillDays` | `14` | Days to backfill on initial sync |
|
||||
| `sync` | `staleLockMinutes` | `10` | Minutes before sync lock considered stale |
|
||||
| `sync` | `heartbeatIntervalSeconds` | `30` | Frequency of lock heartbeat updates |
|
||||
| `sync` | `cursorRewindSeconds` | `2` | Seconds to rewind cursor for overlap safety |
|
||||
| `sync` | `primaryConcurrency` | `4` | Concurrent GitLab requests for primary resources |
|
||||
| `sync` | `dependentConcurrency` | `2` | Concurrent requests for dependent resources |
|
||||
| `sync` | `fetchWorkItemStatus` | `true` | Enrich issues with work item status via GraphQL (requires GitLab Premium/Ultimate) |
|
||||
| `storage` | `dbPath` | `~/.local/share/lore/lore.db` | Database file path |
|
||||
| `storage` | `backupDir` | `~/.local/share/lore/backups` | Backup directory |
|
||||
| `storage` | `compressRawPayloads` | `true` | Compress stored API responses with gzip |
|
||||
@@ -120,6 +153,15 @@ Configuration is stored in `~/.config/lore/config.json` (or `$XDG_CONFIG_HOME/lo
|
||||
| `embedding` | `model` | `nomic-embed-text` | Model name for embeddings |
|
||||
| `embedding` | `baseUrl` | `http://localhost:11434` | Ollama server URL |
|
||||
| `embedding` | `concurrency` | `4` | Concurrent embedding requests |
|
||||
| `scoring` | `authorWeight` | `25` | Points per MR where the user authored code touching the path |
|
||||
| `scoring` | `reviewerWeight` | `10` | Points per MR where the user reviewed code touching the path |
|
||||
| `scoring` | `noteBonus` | `1` | Bonus per inline review comment (DiffNote) |
|
||||
| `scoring` | `reviewerAssignmentWeight` | `3` | Points per MR where the user was assigned as reviewer |
|
||||
| `scoring` | `authorHalfLifeDays` | `180` | Half-life in days for author contribution decay |
|
||||
| `scoring` | `reviewerHalfLifeDays` | `90` | Half-life in days for reviewer contribution decay |
|
||||
| `scoring` | `noteHalfLifeDays` | `45` | Half-life in days for note/comment decay |
|
||||
| `scoring` | `closedMrMultiplier` | `0.5` | Score multiplier for closed (not merged) MRs |
|
||||
| `scoring` | `excludedUsernames` | `[]` | Usernames excluded from expert results (e.g., bots) |
|
||||
|
||||
### Config File Resolution
|
||||
|
||||
@@ -174,6 +216,8 @@ lore issues --since 1m # Updated in last month
|
||||
lore issues --since 2024-01-01 # Updated since date
|
||||
lore issues --due-before 2024-12-31 # Due before date
|
||||
lore issues --has-due # Only issues with due dates
|
||||
lore issues --status "In progress" # By work item status (case-insensitive)
|
||||
lore issues --status "To do" --status "In progress" # Multiple statuses (OR)
|
||||
lore issues -p group/repo # Filter by project
|
||||
lore issues --sort created --asc # Sort by created date, ascending
|
||||
lore issues -o # Open first result in browser
|
||||
@@ -183,13 +227,13 @@ lore -J issues --fields minimal # Compact: iid, title, state, updated_at_i
|
||||
lore -J issues --fields iid,title,labels,state # Custom fields
|
||||
```
|
||||
|
||||
When listing, output includes: IID, title, state, author, assignee, labels, and update time. In robot mode, the `--fields` flag controls which fields appear in the JSON response.
|
||||
When listing, output includes: IID, title, state, status (when any issue has one), assignee, labels, and update time. Status values display with their configured color. In robot mode, the `--fields` flag controls which fields appear in the JSON response.
|
||||
|
||||
When showing a single issue (e.g., `lore issues 123`), output includes: title, description, state, author, assignees, labels, milestone, due date, web URL, and threaded discussions.
|
||||
When showing a single issue (e.g., `lore issues 123`), output includes: title, description, state, work item status (with color and category), author, assignees, labels, milestone, due date, web URL, and threaded discussions.
|
||||
|
||||
#### Project Resolution
|
||||
|
||||
The `-p` / `--project` flag uses cascading match logic across all commands:
|
||||
When `-p` / `--project` is omitted, the `defaultProject` from config is used as a fallback. If neither is set, results span all configured projects. When a project is specified (via `-p` or config default), it uses cascading match logic across all commands:
|
||||
|
||||
1. **Exact match**: `group/project`
|
||||
2. **Case-insensitive**: `Group/Project`
|
||||
@@ -245,22 +289,226 @@ lore search "login flow" --mode semantic # Vector similarity only
|
||||
lore search "auth" --type issue # Filter by source type
|
||||
lore search "auth" --type mr # MR documents only
|
||||
lore search "auth" --type discussion # Discussion documents only
|
||||
lore search "auth" --type note # Individual notes only
|
||||
lore search "deploy" --author username # Filter by author
|
||||
lore search "deploy" -p group/repo # Filter by project
|
||||
lore search "deploy" --label backend # Filter by label (AND logic)
|
||||
lore search "deploy" --path src/ # Filter by file path (trailing / for prefix)
|
||||
lore search "deploy" --after 7d # Created after (7d, 2w, 1m, or YYYY-MM-DD)
|
||||
lore search "deploy" --updated-after 2w # Updated after
|
||||
lore search "deploy" --since 7d # Created since (7d, 2w, 1m, or YYYY-MM-DD)
|
||||
lore search "deploy" --updated-since 2w # Updated since
|
||||
lore search "deploy" -n 50 # Limit results (default 20, max 100)
|
||||
lore search "deploy" --explain # Show ranking explanation per result
|
||||
lore search "deploy" --fts-mode raw # Raw FTS5 query syntax (advanced)
|
||||
```
|
||||
|
||||
The `--fts-mode` flag defaults to `safe`, which sanitizes user input into valid FTS5 queries with automatic fallback. FTS5 boolean operators (`AND`, `OR`, `NOT`, `NEAR`) are passed through in safe mode, so queries like `"switch AND health"` work without switching to raw mode. Use `raw` for advanced FTS5 query syntax (phrase matching, column filters, prefix queries).
|
||||
|
||||
A progress spinner displays during search, showing the active mode (e.g., `Searching (hybrid)...`). In robot mode, spinners are suppressed for clean JSON output.
|
||||
|
||||
Requires `lore generate-docs` (or `lore sync`) to have been run at least once. Semantic and hybrid modes require `lore embed` (or `lore sync`) to have generated vector embeddings via Ollama.
|
||||
|
||||
### `lore who`
|
||||
|
||||
People intelligence: discover experts, analyze workloads, review patterns, active discussions, and code overlap.
|
||||
|
||||
#### Expert Mode
|
||||
|
||||
Find who has expertise in a code area based on authoring and reviewing history (DiffNote analysis). Scores use exponential half-life decay so recent contributions count more than older ones. Scoring weights and half-life periods are configurable via the `scoring` config section.
|
||||
|
||||
```bash
|
||||
lore who src/features/auth/ # Who knows about this directory?
|
||||
lore who src/features/auth/login.ts # Who knows about this file?
|
||||
lore who --path README.md # Root files need --path flag
|
||||
lore who --path Makefile # Dotless root files too
|
||||
lore who src/ --since 3m # Limit to recent 3 months
|
||||
lore who src/ -p group/repo # Scope to project
|
||||
lore who src/ --explain-score # Show per-component score breakdown
|
||||
lore who src/ --as-of 30d # Score as if "now" was 30 days ago
|
||||
lore who src/ --include-bots # Include bot users in results
|
||||
```
|
||||
|
||||
The target is auto-detected as a path when it contains `/`. For root files without `/` (e.g., `README.md`), use the `--path` flag. Default time window: 6 months.
|
||||
|
||||
#### Workload Mode
|
||||
|
||||
See what someone is currently working on.
|
||||
|
||||
```bash
|
||||
lore who @asmith # Full workload summary
|
||||
lore who @asmith -p group/repo # Scoped to one project
|
||||
```
|
||||
|
||||
Shows: assigned open issues, authored MRs, MRs under review, and unresolved discussions.
|
||||
|
||||
#### Reviews Mode
|
||||
|
||||
Analyze someone's code review patterns by area.
|
||||
|
||||
```bash
|
||||
lore who @asmith --reviews # Review activity breakdown
|
||||
lore who @asmith --reviews --since 3m # Recent review patterns
|
||||
```
|
||||
|
||||
Shows: total DiffNotes, categorized by code area with percentage breakdown.
|
||||
|
||||
#### Active Mode
|
||||
|
||||
Surface unresolved discussions needing attention.
|
||||
|
||||
```bash
|
||||
lore who --active # Unresolved discussions (last 7 days)
|
||||
lore who --active --since 30d # Wider time window
|
||||
lore who --active -p group/repo # Scoped to project
|
||||
```
|
||||
|
||||
Shows: discussion threads with participants and last activity timestamps.
|
||||
|
||||
#### Overlap Mode
|
||||
|
||||
Find who else is touching a file or directory.
|
||||
|
||||
```bash
|
||||
lore who --overlap src/features/auth/ # Who else works here?
|
||||
lore who --overlap src/lib.rs # Single file overlap
|
||||
```
|
||||
|
||||
Shows: users with touch counts (author vs. review), linked MR references. Default time window: 6 months.
|
||||
|
||||
#### Common Flags
|
||||
|
||||
| Flag | Description |
|
||||
|------|-------------|
|
||||
| `-p` / `--project` | Scope to a project (fuzzy match) |
|
||||
| `--since` | Time window (7d, 2w, 6m, YYYY-MM-DD). Default varies by mode. |
|
||||
| `-n` / `--limit` | Max results per section (1-500, default 20) |
|
||||
| `--all-history` | Remove the default time window, query all history |
|
||||
| `--detail` | Show per-MR detail breakdown (expert mode only) |
|
||||
| `--explain-score` | Show per-component score breakdown (expert mode only) |
|
||||
| `--as-of` | Score as if "now" is a past date (ISO 8601 or duration like 30d, expert mode only) |
|
||||
| `--include-bots` | Include bot users normally excluded via `scoring.excludedUsernames` |
|
||||
|
||||
### `lore timeline`
|
||||
|
||||
Reconstruct a chronological timeline of events matching a keyword query. The pipeline discovers related entities through cross-reference graph traversal and assembles a unified, time-ordered event stream.
|
||||
|
||||
```bash
|
||||
lore timeline "deployment" # Search-based seeding (hybrid search)
|
||||
lore timeline issue:42 # Direct entity seeding by issue IID
|
||||
lore timeline i:42 # Shorthand for issue:42
|
||||
lore timeline mr:99 # Direct entity seeding by MR IID
|
||||
lore timeline m:99 # Shorthand for mr:99
|
||||
lore timeline "auth" -p group/repo # Scoped to a project
|
||||
lore timeline "auth" --since 30d # Only recent events
|
||||
lore timeline "migration" --depth 2 # Deeper cross-reference expansion
|
||||
lore timeline "migration" --no-mentions # Skip 'mentioned' edges (reduces fan-out)
|
||||
lore timeline "deploy" -n 50 # Limit event count
|
||||
lore timeline "auth" --max-seeds 5 # Fewer seed entities
|
||||
```
|
||||
|
||||
The query can be either a search string (hybrid search finds matching entities) or an entity reference (`issue:N`, `i:N`, `mr:N`, `m:N`) which directly seeds the timeline from a specific entity and its cross-references.
|
||||
|
||||
#### Flags
|
||||
|
||||
| Flag | Default | Description |
|
||||
|------|---------|-------------|
|
||||
| `-p` / `--project` | all | Scope to a specific project (fuzzy match) |
|
||||
| `--since` | none | Only events after this date (7d, 2w, 6m, YYYY-MM-DD) |
|
||||
| `--depth` | `1` | Cross-reference expansion depth (0 = seeds only) |
|
||||
| `--no-mentions` | off | Skip "mentioned" edges during expansion (reduces fan-out) |
|
||||
| `-n` / `--limit` | `100` | Maximum events to display |
|
||||
| `--max-seeds` | `10` | Maximum seed entities from search |
|
||||
| `--max-entities` | `50` | Maximum entities discovered via cross-references |
|
||||
| `--max-evidence` | `10` | Maximum evidence notes included |
|
||||
| `--fields` | all | Select output fields (comma-separated, or 'minimal' preset) |
|
||||
|
||||
#### Pipeline Stages
|
||||
|
||||
Each stage displays a numbered progress spinner (e.g., `[1/3] Seeding timeline...`). In robot mode, spinners are suppressed for clean JSON output.
|
||||
|
||||
1. **SEED** -- Hybrid search (FTS5 lexical + Ollama vector similarity via Reciprocal Rank Fusion) identifies the most relevant issues and MRs. Falls back to lexical-only if Ollama is unavailable. Discussion notes matching the query are also discovered and attached to their parent entities.
|
||||
2. **HYDRATE** -- Evidence notes are extracted: the top search-matched discussion notes with 200-character snippets explaining *why* each entity was surfaced. Matched discussions are collected as full thread candidates.
|
||||
3. **EXPAND** -- Breadth-first traversal over the `entity_references` graph discovers related entities via "closes", "related", and "mentioned" references up to the configured depth. Use `--no-mentions` to exclude "mentioned" edges and reduce fan-out.
|
||||
4. **COLLECT** -- Events are gathered for all discovered entities. Event types include: creation, state changes, label adds/removes, milestone assignments, merge events, evidence notes, and full discussion threads. Events are sorted chronologically with stable tiebreaking.
|
||||
5. **RENDER** -- Events are formatted as human-readable text or structured JSON (robot mode).
|
||||
|
||||
#### Event Types
|
||||
|
||||
| Event | Description |
|
||||
|-------|-------------|
|
||||
| `Created` | Entity creation |
|
||||
| `StateChanged` | State transitions (opened, closed, reopened) |
|
||||
| `LabelAdded` | Label applied to entity |
|
||||
| `LabelRemoved` | Label removed from entity |
|
||||
| `MilestoneSet` | Milestone assigned |
|
||||
| `MilestoneRemoved` | Milestone removed |
|
||||
| `Merged` | MR merged (deduplicated against state events) |
|
||||
| `NoteEvidence` | Discussion note matched by search, with snippet |
|
||||
| `DiscussionThread` | Full discussion thread with all non-system notes |
|
||||
| `CrossReferenced` | Reference to another entity |
|
||||
|
||||
#### Unresolved References
|
||||
|
||||
When graph expansion encounters cross-project references to entities not yet synced locally, these are collected as unresolved references in the output. This enables discovery of external dependencies and can inform future sync targets.
|
||||
|
||||
### `lore notes`
|
||||
|
||||
Query individual notes from discussions with rich filtering options.
|
||||
|
||||
```bash
|
||||
lore notes # List 50 most recent notes
|
||||
lore notes --author alice --since 7d # Notes by alice in last 7 days
|
||||
lore notes --for-issue 42 -p group/repo # Notes on issue #42
|
||||
lore notes --for-mr 99 -p group/repo # Notes on MR !99
|
||||
lore notes --path src/ --resolution unresolved # Unresolved diff notes in src/
|
||||
lore notes --note-type DiffNote # Only inline code review comments
|
||||
lore notes --contains "TODO" # Substring search in note body
|
||||
lore notes --include-system # Include system-generated notes
|
||||
lore notes --since 2w --until 2024-12-31 # Time-bounded range
|
||||
lore notes --sort updated --asc # Sort by update time, ascending
|
||||
lore notes --format csv # CSV output
|
||||
lore notes --format jsonl # Line-delimited JSON
|
||||
lore notes -o # Open first result in browser
|
||||
|
||||
# Field selection (robot mode)
|
||||
lore -J notes --fields minimal # Compact: id, author_username, body, created_at_iso
|
||||
```
|
||||
|
||||
#### Filters
|
||||
|
||||
| Flag | Description |
|
||||
|------|-------------|
|
||||
| `-a` / `--author` | Filter by note author username |
|
||||
| `--note-type` | Filter by note type (DiffNote, DiscussionNote) |
|
||||
| `--contains` | Substring search in note body |
|
||||
| `--note-id` | Filter by internal note ID |
|
||||
| `--gitlab-note-id` | Filter by GitLab note ID |
|
||||
| `--discussion-id` | Filter by discussion ID |
|
||||
| `--include-system` | Include system notes (excluded by default) |
|
||||
| `--for-issue` | Notes on a specific issue IID (requires `-p`) |
|
||||
| `--for-mr` | Notes on a specific MR IID (requires `-p`) |
|
||||
| `-p` / `--project` | Scope to a project (fuzzy match) |
|
||||
| `--since` | Notes created since (7d, 2w, 1m, or YYYY-MM-DD) |
|
||||
| `--until` | Notes created until (YYYY-MM-DD, inclusive end-of-day) |
|
||||
| `--path` | Filter by file path (DiffNotes only; trailing `/` for prefix match) |
|
||||
| `--resolution` | Filter by resolution status (`any`, `unresolved`, `resolved`) |
|
||||
| `--sort` | Sort by `created` (default) or `updated` |
|
||||
| `--asc` | Sort ascending (default: descending) |
|
||||
| `--format` | Output format: `table` (default), `json`, `jsonl`, `csv` |
|
||||
| `-o` / `--open` | Open first result in browser |
|
||||
|
||||
### `lore drift`
|
||||
|
||||
Detect discussion divergence from the original intent of an issue by comparing the semantic similarity of discussion content against the issue description.
|
||||
|
||||
```bash
|
||||
lore drift issues 42 # Check divergence on issue #42
|
||||
lore drift issues 42 --threshold 0.6 # Higher threshold (stricter)
|
||||
lore drift issues 42 -p group/repo # Scope to project
|
||||
```
|
||||
|
||||
### `lore sync`
|
||||
|
||||
Run the full sync pipeline: ingest from GitLab, generate searchable documents, and compute embeddings.
|
||||
Run the full sync pipeline: ingest from GitLab (including work item status enrichment via GraphQL), generate searchable documents, and compute embeddings.
|
||||
|
||||
```bash
|
||||
lore sync # Full pipeline
|
||||
@@ -269,21 +517,24 @@ lore sync --force # Override stale lock
|
||||
lore sync --no-embed # Skip embedding step
|
||||
lore sync --no-docs # Skip document regeneration
|
||||
lore sync --no-events # Skip resource event fetching
|
||||
lore sync --no-file-changes # Skip MR file change fetching
|
||||
lore sync --dry-run # Preview what would be synced
|
||||
```
|
||||
|
||||
The sync command displays animated progress bars for each stage and outputs timing metrics on completion. In robot mode (`-J`), detailed stage timing is included in the JSON response.
|
||||
|
||||
### `lore ingest`
|
||||
|
||||
Sync data from GitLab to local database. Runs only the ingestion step (no doc generation or embeddings).
|
||||
Sync data from GitLab to local database. Runs only the ingestion step (no doc generation or embeddings). For issue ingestion, this includes a status enrichment phase that fetches work item statuses via the GitLab GraphQL API.
|
||||
|
||||
```bash
|
||||
lore ingest # Ingest everything (issues + MRs)
|
||||
lore ingest issues # Issues only
|
||||
lore ingest issues # Issues only (includes status enrichment)
|
||||
lore ingest mrs # MRs only
|
||||
lore ingest issues -p group/repo # Single project
|
||||
lore ingest --force # Override stale lock
|
||||
lore ingest --full # Full re-sync (reset cursors)
|
||||
lore ingest --dry-run # Preview what would change
|
||||
```
|
||||
|
||||
The `--full` flag resets sync cursors and discussion watermarks, then fetches all data from scratch. Useful when:
|
||||
@@ -291,6 +542,8 @@ The `--full` flag resets sync cursors and discussion watermarks, then fetches al
|
||||
- You want to ensure complete data after schema changes
|
||||
- Troubleshooting sync issues
|
||||
|
||||
Status enrichment uses adaptive page sizing (100 → 50 → 25 → 10) to handle GitLab GraphQL complexity limits. It gracefully handles instances without GraphQL support or Premium/Ultimate licensing. Disable via `sync.fetchWorkItemStatus: false` in config.
|
||||
|
||||
### `lore generate-docs`
|
||||
|
||||
Extract searchable documents from ingested issues, MRs, and discussions for the FTS5 index.
|
||||
@@ -307,6 +560,7 @@ Generate vector embeddings for documents via Ollama. Requires Ollama running wit
|
||||
|
||||
```bash
|
||||
lore embed # Embed new/changed documents
|
||||
lore embed --full # Re-embed all documents (clears existing)
|
||||
lore embed --retry-failed # Retry previously failed embeddings
|
||||
```
|
||||
|
||||
@@ -322,6 +576,9 @@ lore count discussions --for issue # Issue discussions only
|
||||
lore count discussions --for mr # MR discussions only
|
||||
lore count notes # Total notes (system vs user breakdown)
|
||||
lore count notes --for issue # Issue notes only
|
||||
lore count events # Total resource events
|
||||
lore count events --for issue # Issue events only
|
||||
lore count events --for mr # MR events only
|
||||
```
|
||||
|
||||
### `lore stats`
|
||||
@@ -332,6 +589,7 @@ Show document and index statistics, with optional integrity checks.
|
||||
lore stats # Document and index statistics
|
||||
lore stats --check # Run integrity checks
|
||||
lore stats --check --repair # Repair integrity issues
|
||||
lore stats --dry-run # Preview repairs without saving
|
||||
```
|
||||
|
||||
### `lore status`
|
||||
@@ -357,6 +615,17 @@ lore init --force # Overwrite existing config
|
||||
lore init --non-interactive # Fail if prompts needed
|
||||
```
|
||||
|
||||
When multiple projects are configured, `init` prompts whether to set a default project (used when `-p` is omitted). This can also be set via the `--default-project` flag.
|
||||
|
||||
In robot mode, `init` supports non-interactive setup via flags:
|
||||
|
||||
```bash
|
||||
lore -J init --gitlab-url https://gitlab.com \
|
||||
--token-env-var GITLAB_TOKEN \
|
||||
--projects "group/project,other/project" \
|
||||
--default-project group/project
|
||||
```
|
||||
|
||||
### `lore auth`
|
||||
|
||||
Verify GitLab authentication is working.
|
||||
@@ -392,7 +661,7 @@ lore migrate
|
||||
|
||||
### `lore health`
|
||||
|
||||
Quick pre-flight check for config, database, and schema version. Exits 0 if healthy, 1 if unhealthy.
|
||||
Quick pre-flight check for config, database, and schema version. Exits 0 if healthy, 19 if unhealthy.
|
||||
|
||||
```bash
|
||||
lore health
|
||||
@@ -407,6 +676,7 @@ Machine-readable command manifest for agent self-discovery. Returns a JSON schem
|
||||
```bash
|
||||
lore robot-docs # Pretty-printed JSON
|
||||
lore --robot robot-docs # Compact JSON for parsing
|
||||
lore robot-docs --brief # Omit response_schema (~60% smaller)
|
||||
```
|
||||
|
||||
### `lore version`
|
||||
@@ -458,7 +728,7 @@ The `actions` array contains executable shell commands an agent can run to recov
|
||||
|
||||
### Field Selection
|
||||
|
||||
The `--fields` flag on `issues` and `mrs` list commands controls which fields appear in the JSON response, reducing token usage for AI agent workflows:
|
||||
The `--fields` flag controls which fields appear in the JSON response, reducing token usage for AI agent workflows. Supported on `issues`, `mrs`, `notes`, `search`, `timeline`, and `who` list commands:
|
||||
|
||||
```bash
|
||||
# Minimal preset (~60% fewer tokens)
|
||||
@@ -471,10 +741,52 @@ lore -J issues --fields iid,title,state,labels,updated_at_iso
|
||||
# minimal: iid, title, state, updated_at_iso
|
||||
```
|
||||
|
||||
Valid fields for issues: `iid`, `title`, `state`, `author_username`, `labels`, `assignees`, `discussion_count`, `unresolved_count`, `created_at_iso`, `updated_at_iso`, `web_url`, `project_path`
|
||||
Valid fields for issues: `iid`, `title`, `state`, `author_username`, `labels`, `assignees`, `discussion_count`, `unresolved_count`, `created_at_iso`, `updated_at_iso`, `web_url`, `project_path`, `status_name`, `status_category`, `status_color`, `status_icon_name`, `status_synced_at_iso`
|
||||
|
||||
Valid fields for MRs: `iid`, `title`, `state`, `author_username`, `labels`, `draft`, `target_branch`, `source_branch`, `discussion_count`, `unresolved_count`, `created_at_iso`, `updated_at_iso`, `web_url`, `project_path`, `reviewers`
|
||||
|
||||
### Error Tolerance
|
||||
|
||||
The CLI auto-corrects common mistakes before parsing, emitting a teaching note to stderr. Corrections work in both human and robot modes:
|
||||
|
||||
| Correction | Example | Mode |
|
||||
|-----------|---------|------|
|
||||
| Single-dash long flag | `-robot` -> `--robot` | All |
|
||||
| Case normalization | `--Robot` -> `--robot` | All |
|
||||
| Flag prefix expansion | `--proj` -> `--project` (unambiguous only) | All |
|
||||
| Fuzzy flag match | `--projct` -> `--project` | All (threshold 0.9 in robot, 0.8 in human) |
|
||||
| Subcommand alias | `merge_requests` -> `mrs`, `robotdocs` -> `robot-docs` | All |
|
||||
| Value normalization | `--state Opened` -> `--state opened` | All |
|
||||
| Value fuzzy match | `--state opend` -> `--state opened` | All |
|
||||
| Subcommand prefix | `lore iss` -> `lore issues` (unambiguous only, via clap) | All |
|
||||
|
||||
In robot mode, corrections emit structured JSON to stderr:
|
||||
|
||||
```json
|
||||
{"warning":{"type":"ARG_CORRECTED","corrections":[...],"teaching":["Use double-dash for long flags: --robot (not -robot)"]}}
|
||||
```
|
||||
|
||||
When a command or flag is still unrecognized after corrections, the error response includes a fuzzy suggestion and, for enum-like flags, lists valid values:
|
||||
|
||||
```json
|
||||
{"error":{"code":"UNKNOWN_COMMAND","message":"...","suggestion":"Did you mean 'lore issues'? Example: lore --robot issues -n 10. Run 'lore robot-docs' for all commands"}}
|
||||
```
|
||||
|
||||
### Command Aliases
|
||||
|
||||
Commands accept aliases for common variations:
|
||||
|
||||
| Primary | Aliases |
|
||||
|---------|---------|
|
||||
| `issues` | `issue` |
|
||||
| `mrs` | `mr`, `merge-requests`, `merge-request` |
|
||||
| `notes` | `note` |
|
||||
| `search` | `find`, `query` |
|
||||
| `stats` | `stat` |
|
||||
| `status` | `st` |
|
||||
|
||||
Unambiguous prefixes also work via subcommand inference (e.g., `lore iss` -> `lore issues`, `lore time` -> `lore timeline`).
|
||||
|
||||
### Agent Self-Discovery
|
||||
|
||||
The `robot-docs` command provides a complete machine-readable manifest including response schemas for every command:
|
||||
@@ -562,7 +874,7 @@ Data is stored in SQLite with WAL mode and foreign keys enabled. Main tables:
|
||||
| Table | Purpose |
|
||||
|-------|---------|
|
||||
| `projects` | Tracked GitLab projects with metadata |
|
||||
| `issues` | Issue metadata (title, state, author, due date, milestone) |
|
||||
| `issues` | Issue metadata (title, state, author, due date, milestone, work item status) |
|
||||
| `merge_requests` | MR metadata (title, state, draft, branches, merge status, commit SHAs) |
|
||||
| `milestones` | Project milestones with state and due dates |
|
||||
| `labels` | Project labels with colors |
|
||||
@@ -591,42 +903,6 @@ Data is stored in SQLite with WAL mode and foreign keys enabled. Main tables:
|
||||
|
||||
The database is stored at `~/.local/share/lore/lore.db` by default (XDG compliant).
|
||||
|
||||
## Timeline Pipeline
|
||||
|
||||
The timeline pipeline reconstructs chronological event histories for GitLab entities by combining full-text search, cross-reference graph traversal, and resource event aggregation. Given a search query, it identifies relevant issues and MRs, discovers related entities through their reference graph, and assembles a unified, time-ordered event stream.
|
||||
|
||||
### Stages
|
||||
|
||||
The pipeline executes in five stages:
|
||||
|
||||
1. **SEED** -- Full-text search identifies the most relevant issues and MRs matching the query. Documents (issue bodies, MR descriptions, discussion notes) are ranked by BM25 relevance.
|
||||
|
||||
2. **HYDRATE** -- Evidence notes are extracted from the seed results: the top FTS-matched discussion notes with 200-character snippets that explain *why* each entity was surfaced.
|
||||
|
||||
3. **EXPAND** -- Breadth-first traversal over the `entity_references` graph discovers related entities. Starting from seed entities, the pipeline follows "closes", "related", and optionally "mentioned" references up to a configurable depth, tracking provenance (which entity referenced which, via what method).
|
||||
|
||||
4. **COLLECT** -- Events are gathered for all discovered entities (seeds + expanded). Event types include: creation, state changes, label adds/removes, milestone assignments, merge events, and evidence notes. Events are sorted chronologically with stable tiebreaking (timestamp, then entity ID, then event type).
|
||||
|
||||
5. **RENDER** -- Events are formatted for output as human-readable text or structured JSON.
|
||||
|
||||
### Event Types
|
||||
|
||||
| Event | Description |
|
||||
|-------|-------------|
|
||||
| `Created` | Entity creation |
|
||||
| `StateChanged` | State transitions (opened, closed, reopened) |
|
||||
| `LabelAdded` | Label applied to entity |
|
||||
| `LabelRemoved` | Label removed from entity |
|
||||
| `MilestoneSet` | Milestone assigned |
|
||||
| `MilestoneRemoved` | Milestone removed |
|
||||
| `Merged` | MR merged (deduplicated against state events) |
|
||||
| `NoteEvidence` | Discussion note matched by FTS, with snippet |
|
||||
| `CrossReferenced` | Reference to another entity |
|
||||
|
||||
### Unresolved References
|
||||
|
||||
When the graph expansion encounters cross-project references to entities not yet synced locally, these are collected as unresolved references in the pipeline output. This enables discovery of external dependencies and can inform future sync targets.
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
|
||||
245
docs/diagrams/01-human-flow-map.excalidraw
Normal file
245
docs/diagrams/01-human-flow-map.excalidraw
Normal file
@@ -0,0 +1,245 @@
|
||||
{
|
||||
"type": "excalidraw",
|
||||
"version": 2,
|
||||
"source": "https://excalidraw.com",
|
||||
"elements": [
|
||||
{ "type": "text", "id": "title", "x": 300, "y": 15, "text": "Human User Flow Map", "fontSize": 28 },
|
||||
{ "type": "text", "id": "subtitle", "x": 220, "y": 53, "text": "15 human workflows mapped to lore commands. Arrows show data dependency.", "fontSize": 14, "strokeColor": "#868e96" },
|
||||
|
||||
{ "type": "text", "id": "col-trigger", "x": 60, "y": 80, "text": "TRIGGER (Problem)", "fontSize": 16, "strokeColor": "#495057" },
|
||||
{ "type": "text", "id": "col-flow", "x": 400, "y": 80, "text": "COMMAND FLOW", "fontSize": 16, "strokeColor": "#495057" },
|
||||
{ "type": "text", "id": "col-gap", "x": 880, "y": 80, "text": "GAP", "fontSize": 16, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "rectangle", "id": "zone-daily", "x": 20, "y": 110, "width": 960, "height": 190,
|
||||
"backgroundColor": "#dbe4ff", "fillStyle": "solid", "roundness": { "type": 3 },
|
||||
"strokeColor": "#4a9eed", "strokeWidth": 1, "opacity": 20 },
|
||||
{ "type": "text", "id": "zone-daily-label", "x": 30, "y": 115, "text": "Daily Operations", "fontSize": 14, "strokeColor": "#1971c2" },
|
||||
|
||||
{ "type": "rectangle", "id": "h1-trigger", "x": 30, "y": 140, "width": 200, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#a5d8ff", "fillStyle": "solid",
|
||||
"label": { "text": "H1: Standup prep\n\"What moved overnight?\"", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h1-a1", "x": 230, "y": 165, "width": 50, "height": 0,
|
||||
"points": [[0,0],[50,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h1-cmd1", "x": 280, "y": 145, "width": 90, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "sync -q", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h1-a2", "x": 370, "y": 165, "width": 30, "height": 0,
|
||||
"points": [[0,0],[30,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h1-cmd2", "x": 400, "y": 145, "width": 140, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "issues --since 1d", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h1-a3", "x": 540, "y": 165, "width": 30, "height": 0,
|
||||
"points": [[0,0],[30,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h1-cmd3", "x": 570, "y": 145, "width": 130, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "mrs --since 1d", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h1-a4", "x": 700, "y": 165, "width": 30, "height": 0,
|
||||
"points": [[0,0],[30,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h1-cmd4", "x": 730, "y": 145, "width": 100, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "who @me", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h1-a5", "x": 830, "y": 165, "width": 40, "height": 0,
|
||||
"points": [[0,0],[40,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h1-gap", "x": 870, "y": 140, "width": 100, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffc9c9", "fillStyle": "solid", "strokeColor": "#ef4444",
|
||||
"label": { "text": "No @me\nNo feed", "fontSize": 14 } },
|
||||
|
||||
{ "type": "rectangle", "id": "h3-trigger", "x": 30, "y": 210, "width": 200, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#a5d8ff", "fillStyle": "solid",
|
||||
"label": { "text": "H3: Incident\n\"Deploy broke prod\"", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h3-a1", "x": 230, "y": 235, "width": 50, "height": 0,
|
||||
"points": [[0,0],[50,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h3-cmd1", "x": 280, "y": 215, "width": 130, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "timeline deploy", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h3-a2", "x": 410, "y": 235, "width": 30, "height": 0,
|
||||
"points": [[0,0],[30,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h3-cmd2", "x": 440, "y": 215, "width": 160, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "search deploy --mr", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h3-a3", "x": 600, "y": 235, "width": 30, "height": 0,
|
||||
"points": [[0,0],[30,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h3-cmd3", "x": 630, "y": 215, "width": 110, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "mrs <iid>", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h3-a4", "x": 740, "y": 235, "width": 30, "height": 0,
|
||||
"points": [[0,0],[30,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h3-cmd4", "x": 770, "y": 215, "width": 100, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "who --overlap", "fontSize": 14 } },
|
||||
|
||||
{ "type": "rectangle", "id": "zone-planning", "x": 20, "y": 310, "width": 960, "height": 190,
|
||||
"backgroundColor": "#d3f9d8", "fillStyle": "solid", "roundness": { "type": 3 },
|
||||
"strokeColor": "#22c55e", "strokeWidth": 1, "opacity": 20 },
|
||||
{ "type": "text", "id": "zone-planning-label", "x": 30, "y": 315, "text": "Planning & Assignment", "fontSize": 14, "strokeColor": "#15803d" },
|
||||
|
||||
{ "type": "rectangle", "id": "h2-trigger", "x": 30, "y": 340, "width": 200, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#a5d8ff", "fillStyle": "solid",
|
||||
"label": { "text": "H2: Sprint plan\n\"What's ready to pick?\"", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h2-a1", "x": 230, "y": 365, "width": 50, "height": 0,
|
||||
"points": [[0,0],[50,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h2-cmd1", "x": 280, "y": 345, "width": 170, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "issues -s opened -l ready", "fontSize": 13 } },
|
||||
{ "type": "arrow", "id": "h2-a2", "x": 450, "y": 365, "width": 30, "height": 0,
|
||||
"points": [[0,0],[30,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h2-cmd2", "x": 480, "y": 345, "width": 150, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "issues --has-due", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h2-a3", "x": 630, "y": 365, "width": 230, "height": 0,
|
||||
"points": [[0,0],[230,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h2-gap", "x": 860, "y": 340, "width": 110, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffc9c9", "fillStyle": "solid", "strokeColor": "#ef4444",
|
||||
"label": { "text": "No\n--no-assignee", "fontSize": 14 } },
|
||||
|
||||
{ "type": "rectangle", "id": "h8-trigger", "x": 30, "y": 410, "width": 200, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#a5d8ff", "fillStyle": "solid",
|
||||
"label": { "text": "H8: Assign work\n\"Who has bandwidth?\"", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h8-a1", "x": 230, "y": 435, "width": 50, "height": 0,
|
||||
"points": [[0,0],[50,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h8-cmd1", "x": 280, "y": 415, "width": 120, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffd8a8", "fillStyle": "solid",
|
||||
"label": { "text": "who @alice", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h8-a2", "x": 400, "y": 435, "width": 30, "height": 0,
|
||||
"points": [[0,0],[30,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h8-cmd2", "x": 430, "y": 415, "width": 110, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffd8a8", "fillStyle": "solid",
|
||||
"label": { "text": "who @bob", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h8-a3", "x": 540, "y": 435, "width": 30, "height": 0,
|
||||
"points": [[0,0],[30,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h8-cmd3", "x": 570, "y": 415, "width": 120, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffd8a8", "fillStyle": "solid",
|
||||
"label": { "text": "who @carol...", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h8-a4", "x": 690, "y": 435, "width": 170, "height": 0,
|
||||
"points": [[0,0],[170,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h8-gap", "x": 860, "y": 410, "width": 110, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffc9c9", "fillStyle": "solid", "strokeColor": "#ef4444",
|
||||
"label": { "text": "No team\nworkload view", "fontSize": 14 } },
|
||||
|
||||
{ "type": "rectangle", "id": "zone-investigation", "x": 20, "y": 510, "width": 960, "height": 260,
|
||||
"backgroundColor": "#fff3bf", "fillStyle": "solid", "roundness": { "type": 3 },
|
||||
"strokeColor": "#f59e0b", "strokeWidth": 1, "opacity": 20 },
|
||||
{ "type": "text", "id": "zone-invest-label", "x": 30, "y": 515, "text": "Investigation & Understanding", "fontSize": 14, "strokeColor": "#b45309" },
|
||||
|
||||
{ "type": "rectangle", "id": "h7-trigger", "x": 30, "y": 540, "width": 200, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#a5d8ff", "fillStyle": "solid",
|
||||
"label": { "text": "H7: Why this way?\n\"Understand a decision\"", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h7-a1", "x": 230, "y": 565, "width": 50, "height": 0,
|
||||
"points": [[0,0],[50,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h7-cmd1", "x": 280, "y": 545, "width": 160, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "search \"rationale\"", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h7-a2", "x": 440, "y": 565, "width": 30, "height": 0,
|
||||
"points": [[0,0],[30,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h7-cmd2", "x": 470, "y": 545, "width": 140, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "timeline --depth 2", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h7-a3", "x": 610, "y": 565, "width": 30, "height": 0,
|
||||
"points": [[0,0],[30,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h7-cmd3", "x": 640, "y": 545, "width": 100, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "issues 234", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h7-a4", "x": 740, "y": 565, "width": 120, "height": 0,
|
||||
"points": [[0,0],[120,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h7-gap", "x": 860, "y": 540, "width": 110, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffc9c9", "fillStyle": "solid", "strokeColor": "#ef4444",
|
||||
"label": { "text": "No per-note\nsearch", "fontSize": 14 } },
|
||||
|
||||
{ "type": "rectangle", "id": "h11-trigger", "x": 30, "y": 610, "width": 200, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#a5d8ff", "fillStyle": "solid",
|
||||
"label": { "text": "H11: Bug lifecycle\n\"Why does #321 reopen?\"", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h11-a1", "x": 230, "y": 635, "width": 50, "height": 0,
|
||||
"points": [[0,0],[50,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h11-cmd1", "x": 280, "y": 615, "width": 120, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "issues 321", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h11-a2", "x": 400, "y": 635, "width": 30, "height": 0,
|
||||
"points": [[0,0],[30,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h11-cmd2", "x": 430, "y": 615, "width": 130, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffd8a8", "fillStyle": "solid",
|
||||
"label": { "text": "timeline ???", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h11-a3", "x": 560, "y": 635, "width": 300, "height": 0,
|
||||
"points": [[0,0],[300,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h11-gap", "x": 860, "y": 610, "width": 110, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffc9c9", "fillStyle": "solid", "strokeColor": "#ef4444",
|
||||
"label": { "text": "No entity\ntimeline", "fontSize": 14 } },
|
||||
|
||||
{ "type": "rectangle", "id": "h14-trigger", "x": 30, "y": 680, "width": 200, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#a5d8ff", "fillStyle": "solid",
|
||||
"label": { "text": "H14: Prior art?\n\"Was this tried before?\"", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h14-a1", "x": 230, "y": 705, "width": 50, "height": 0,
|
||||
"points": [[0,0],[50,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h14-cmd1", "x": 280, "y": 685, "width": 170, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "search \"memory leak\"", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h14-a2", "x": 450, "y": 705, "width": 30, "height": 0,
|
||||
"points": [[0,0],[30,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h14-cmd2", "x": 480, "y": 685, "width": 120, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffd8a8", "fillStyle": "solid",
|
||||
"label": { "text": "mrs --closed?", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h14-a3", "x": 600, "y": 705, "width": 260, "height": 0,
|
||||
"points": [[0,0],[260,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h14-gap", "x": 860, "y": 680, "width": 110, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffc9c9", "fillStyle": "solid", "strokeColor": "#ef4444",
|
||||
"label": { "text": "No --state\non search", "fontSize": 14 } },
|
||||
|
||||
{ "type": "rectangle", "id": "zone-people", "x": 20, "y": 780, "width": 960, "height": 190,
|
||||
"backgroundColor": "#e5dbff", "fillStyle": "solid", "roundness": { "type": 3 },
|
||||
"strokeColor": "#8b5cf6", "strokeWidth": 1, "opacity": 20 },
|
||||
{ "type": "text", "id": "zone-people-label", "x": 30, "y": 785, "text": "People & Expertise", "fontSize": 14, "strokeColor": "#7048e8" },
|
||||
|
||||
{ "type": "rectangle", "id": "h4-trigger", "x": 30, "y": 810, "width": 200, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#a5d8ff", "fillStyle": "solid",
|
||||
"label": { "text": "H4: Review prep\n\"Context for MR !789\"", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h4-a1", "x": 230, "y": 835, "width": 50, "height": 0,
|
||||
"points": [[0,0],[50,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h4-cmd1", "x": 280, "y": 815, "width": 100, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "mrs 789", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h4-a2", "x": 380, "y": 835, "width": 30, "height": 0,
|
||||
"points": [[0,0],[30,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h4-cmd2", "x": 410, "y": 815, "width": 120, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "who src/auth/", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h4-a3", "x": 530, "y": 835, "width": 30, "height": 0,
|
||||
"points": [[0,0],[30,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h4-cmd3", "x": 560, "y": 815, "width": 130, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "search \"auth\"", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h4-a4", "x": 690, "y": 835, "width": 170, "height": 0,
|
||||
"points": [[0,0],[170,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h4-gap", "x": 860, "y": 810, "width": 110, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffc9c9", "fillStyle": "solid", "strokeColor": "#ef4444",
|
||||
"label": { "text": "No MR file\nlist output", "fontSize": 14 } },
|
||||
|
||||
{ "type": "rectangle", "id": "h6-trigger", "x": 30, "y": 880, "width": 200, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#a5d8ff", "fillStyle": "solid",
|
||||
"label": { "text": "H6: Find reviewer\n\"Who should review?\"", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h6-a1", "x": 230, "y": 905, "width": 50, "height": 0,
|
||||
"points": [[0,0],[50,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h6-cmd1", "x": 280, "y": 885, "width": 130, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffd8a8", "fillStyle": "solid",
|
||||
"label": { "text": "who src/auth/", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h6-a2", "x": 410, "y": 905, "width": 30, "height": 0,
|
||||
"points": [[0,0],[30,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h6-cmd2", "x": 440, "y": 885, "width": 140, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffd8a8", "fillStyle": "solid",
|
||||
"label": { "text": "who src/pay/", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h6-a3", "x": 580, "y": 905, "width": 30, "height": 0,
|
||||
"points": [[0,0],[30,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h6-cmd3", "x": 610, "y": 885, "width": 140, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffd8a8", "fillStyle": "solid",
|
||||
"label": { "text": "who @candidate", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "h6-a4", "x": 750, "y": 905, "width": 110, "height": 0,
|
||||
"points": [[0,0],[110,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "h6-gap", "x": 860, "y": 880, "width": 110, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffc9c9", "fillStyle": "solid", "strokeColor": "#ef4444",
|
||||
"label": { "text": "No multi-\npath query", "fontSize": 14 } },
|
||||
|
||||
{ "type": "text", "id": "callout-1", "x": 30, "y": 990, "text": "Pattern: Most human flows require 3-5 serial commands. Average gap rate: 73% of flows have at least one.", "fontSize": 14, "strokeColor": "#495057" },
|
||||
{ "type": "text", "id": "callout-2", "x": 30, "y": 1015, "text": "Top optimization: Composite commands (activity feed, team workload) would reduce multi-command flows by ~40%.", "fontSize": 14, "strokeColor": "#15803d" },
|
||||
{ "type": "text", "id": "callout-3", "x": 30, "y": 1040, "text": "Top missing data: MR file changes and entity references are stored but invisible to CLI users.", "fontSize": 14, "strokeColor": "#ef4444" }
|
||||
],
|
||||
"appState": { "viewBackgroundColor": "#ffffff", "gridSize": null },
|
||||
"files": {}
|
||||
}
|
||||
BIN
docs/diagrams/01-human-flow-map.png
Normal file
BIN
docs/diagrams/01-human-flow-map.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 274 KiB |
204
docs/diagrams/02-agent-flow-map.excalidraw
Normal file
204
docs/diagrams/02-agent-flow-map.excalidraw
Normal file
@@ -0,0 +1,204 @@
|
||||
{
|
||||
"type": "excalidraw",
|
||||
"version": 2,
|
||||
"source": "https://excalidraw.com",
|
||||
"elements": [
|
||||
{ "type": "text", "id": "title", "x": 320, "y": 15, "text": "AI Agent Flow Map", "fontSize": 28 },
|
||||
{ "type": "text", "id": "subtitle", "x": 180, "y": 53, "text": "15 agent automation workflows. Agents need structured JSON (-J), exit codes, and field selection.", "fontSize": 14, "strokeColor": "#868e96" },
|
||||
|
||||
{ "type": "text", "id": "col-trigger", "x": 60, "y": 80, "text": "TRIGGER (Agent Goal)", "fontSize": 16, "strokeColor": "#495057" },
|
||||
{ "type": "text", "id": "col-flow", "x": 400, "y": 80, "text": "COMMAND PIPELINE", "fontSize": 16, "strokeColor": "#495057" },
|
||||
{ "type": "text", "id": "col-gap", "x": 880, "y": 80, "text": "BLOCKED BY", "fontSize": 16, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "rectangle", "id": "zone-context", "x": 20, "y": 110, "width": 960, "height": 200,
|
||||
"backgroundColor": "#e5dbff", "fillStyle": "solid", "roundness": { "type": 3 },
|
||||
"strokeColor": "#8b5cf6", "strokeWidth": 1, "opacity": 20 },
|
||||
{ "type": "text", "id": "zone-context-label", "x": 30, "y": 115, "text": "Context Gathering (pre-action)", "fontSize": 14, "strokeColor": "#7048e8" },
|
||||
|
||||
{ "type": "rectangle", "id": "a1-trigger", "x": 30, "y": 140, "width": 200, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#d0bfff", "fillStyle": "solid",
|
||||
"label": { "text": "A1: Pre-edit context\nAbout to modify files", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "a1-a1", "x": 230, "y": 165, "width": 50, "height": 0,
|
||||
"points": [[0,0],[50,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "a1-cmd1", "x": 280, "y": 145, "width": 80, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "-J health", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "a1-a2", "x": 360, "y": 165, "width": 20, "height": 0,
|
||||
"points": [[0,0],[20,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "a1-cmd2", "x": 380, "y": 145, "width": 140, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "-J who src/auth/", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "a1-a3", "x": 520, "y": 165, "width": 20, "height": 0,
|
||||
"points": [[0,0],[20,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "a1-cmd3", "x": 540, "y": 145, "width": 170, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "-J search \"auth\" -n 10", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "a1-a4", "x": 710, "y": 165, "width": 20, "height": 0,
|
||||
"points": [[0,0],[20,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "a1-cmd4", "x": 730, "y": 145, "width": 130, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "-J who --overlap", "fontSize": 14 } },
|
||||
|
||||
{ "type": "rectangle", "id": "a6-trigger", "x": 30, "y": 210, "width": 200, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#d0bfff", "fillStyle": "solid",
|
||||
"label": { "text": "A6: Auto-assign reviewers\nBased on file expertise", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "a6-a1", "x": 230, "y": 235, "width": 50, "height": 0,
|
||||
"points": [[0,0],[50,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "a6-cmd1", "x": 280, "y": 215, "width": 100, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffd8a8", "fillStyle": "solid",
|
||||
"label": { "text": "-J mrs 456", "fontSize": 14 } },
|
||||
{ "type": "text", "id": "a6-block", "x": 390, "y": 218, "text": "file list not\nin response!", "fontSize": 12, "strokeColor": "#ef4444" },
|
||||
{ "type": "arrow", "id": "a6-a2", "x": 380, "y": 245, "width": 480, "height": -10,
|
||||
"points": [[0,0],[480,-10]], "endArrowhead": "arrow", "strokeColor": "#ef4444", "strokeStyle": "dashed" },
|
||||
{ "type": "rectangle", "id": "a6-gap", "x": 860, "y": 210, "width": 110, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffc9c9", "fillStyle": "solid", "strokeColor": "#ef4444",
|
||||
"label": { "text": "MR files\nnot exposed", "fontSize": 14 } },
|
||||
|
||||
{ "type": "rectangle", "id": "zone-report", "x": 20, "y": 320, "width": 960, "height": 200,
|
||||
"backgroundColor": "#d3f9d8", "fillStyle": "solid", "roundness": { "type": 3 },
|
||||
"strokeColor": "#22c55e", "strokeWidth": 1, "opacity": 20 },
|
||||
{ "type": "text", "id": "zone-report-label", "x": 30, "y": 325, "text": "Reporting & Synthesis", "fontSize": 14, "strokeColor": "#15803d" },
|
||||
|
||||
{ "type": "rectangle", "id": "a3-trigger", "x": 30, "y": 350, "width": 200, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#d0bfff", "fillStyle": "solid",
|
||||
"label": { "text": "A3: Sprint status report\n7 queries for 1 report", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "a3-a1", "x": 230, "y": 375, "width": 50, "height": 0,
|
||||
"points": [[0,0],[50,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "a3-cmd1", "x": 280, "y": 352, "width": 100, "height": 36,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "issues -s closed", "fontSize": 12 } },
|
||||
{ "type": "rectangle", "id": "a3-cmd2", "x": 390, "y": 352, "width": 100, "height": 36,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "issues --status", "fontSize": 12 } },
|
||||
{ "type": "rectangle", "id": "a3-cmd3", "x": 500, "y": 352, "width": 100, "height": 36,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "mrs -s merged", "fontSize": 12 } },
|
||||
{ "type": "rectangle", "id": "a3-cmd4", "x": 610, "y": 352, "width": 80, "height": 36,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "mrs -s open", "fontSize": 12 } },
|
||||
{ "type": "rectangle", "id": "a3-cmd5", "x": 700, "y": 352, "width": 80, "height": 36,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "count x2", "fontSize": 12 } },
|
||||
{ "type": "rectangle", "id": "a3-cmd6", "x": 790, "y": 352, "width": 60, "height": 36,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "who", "fontSize": 12 } },
|
||||
{ "type": "arrow", "id": "a3-agap", "x": 850, "y": 370, "width": 20, "height": 0,
|
||||
"points": [[0,0],[20,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "a3-gap", "x": 860, "y": 350, "width": 110, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffc9c9", "fillStyle": "solid", "strokeColor": "#ef4444",
|
||||
"label": { "text": "No summary\ncommand", "fontSize": 14 } },
|
||||
{ "type": "text", "id": "a3-note", "x": 280, "y": 395, "text": "7 sequential API calls for one report. A `lore summary` could reduce to 1.", "fontSize": 12, "strokeColor": "#868e96" },
|
||||
|
||||
{ "type": "rectangle", "id": "a7-trigger", "x": 30, "y": 430, "width": 200, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#d0bfff", "fillStyle": "solid",
|
||||
"label": { "text": "A7: Incident timeline\nPostmortem reconstruction", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "a7-a1", "x": 230, "y": 455, "width": 50, "height": 0,
|
||||
"points": [[0,0],[50,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "a7-cmd1", "x": 280, "y": 435, "width": 190, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "-J timeline --depth 2", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "a7-a2", "x": 470, "y": 455, "width": 20, "height": 0,
|
||||
"points": [[0,0],[20,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "a7-cmd2", "x": 490, "y": 435, "width": 170, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "-J search --since 3d", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "a7-a3", "x": 660, "y": 455, "width": 20, "height": 0,
|
||||
"points": [[0,0],[20,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "a7-cmd3", "x": 680, "y": 435, "width": 170, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "-J mrs -s merged", "fontSize": 14 } },
|
||||
|
||||
{ "type": "rectangle", "id": "zone-discover", "x": 20, "y": 530, "width": 960, "height": 200,
|
||||
"backgroundColor": "#fff3bf", "fillStyle": "solid", "roundness": { "type": 3 },
|
||||
"strokeColor": "#f59e0b", "strokeWidth": 1, "opacity": 20 },
|
||||
{ "type": "text", "id": "zone-discover-label", "x": 30, "y": 535, "text": "Discovery & Correlation", "fontSize": 14, "strokeColor": "#b45309" },
|
||||
|
||||
{ "type": "rectangle", "id": "a5-trigger", "x": 30, "y": 560, "width": 200, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#d0bfff", "fillStyle": "solid",
|
||||
"label": { "text": "A5: PR description\nFind related issues to link", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "a5-a1", "x": 230, "y": 585, "width": 50, "height": 0,
|
||||
"points": [[0,0],[50,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "a5-cmd1", "x": 280, "y": 565, "width": 170, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "-J search keywords", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "a5-a2", "x": 450, "y": 585, "width": 20, "height": 0,
|
||||
"points": [[0,0],[20,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "a5-cmd2", "x": 470, "y": 565, "width": 180, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "-J issues --fields iid,url", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "a5-a3", "x": 650, "y": 585, "width": 210, "height": 0,
|
||||
"points": [[0,0],[210,0]], "endArrowhead": "arrow", "strokeColor": "#ef4444", "strokeStyle": "dashed" },
|
||||
{ "type": "rectangle", "id": "a5-gap", "x": 860, "y": 560, "width": 110, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffc9c9", "fillStyle": "solid", "strokeColor": "#ef4444",
|
||||
"label": { "text": "No refs\nquery", "fontSize": 14 } },
|
||||
{ "type": "text", "id": "a5-note", "x": 280, "y": 612, "text": "Agent can't ask \"which issues does MR !456 close?\" -- entity_references data exists but isn't queryable.", "fontSize": 12, "strokeColor": "#868e96" },
|
||||
|
||||
{ "type": "rectangle", "id": "a11-trigger", "x": 30, "y": 640, "width": 200, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#d0bfff", "fillStyle": "solid",
|
||||
"label": { "text": "A11: Knowledge graph\nMap entity relationships", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "a11-a1", "x": 230, "y": 665, "width": 50, "height": 0,
|
||||
"points": [[0,0],[50,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "a11-cmd1", "x": 280, "y": 645, "width": 140, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "-J search -n 30", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "a11-a2", "x": 420, "y": 665, "width": 20, "height": 0,
|
||||
"points": [[0,0],[20,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "a11-cmd2", "x": 440, "y": 645, "width": 190, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "-J timeline --depth 2", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "a11-a3", "x": 630, "y": 665, "width": 230, "height": 0,
|
||||
"points": [[0,0],[230,0]], "endArrowhead": "arrow", "strokeColor": "#ef4444", "strokeStyle": "dashed" },
|
||||
{ "type": "rectangle", "id": "a11-gap", "x": 860, "y": 640, "width": 110, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffc9c9", "fillStyle": "solid", "strokeColor": "#ef4444",
|
||||
"label": { "text": "No refs\nquery", "fontSize": 14 } },
|
||||
|
||||
{ "type": "rectangle", "id": "zone-maint", "x": 20, "y": 740, "width": 960, "height": 140,
|
||||
"backgroundColor": "#dbe4ff", "fillStyle": "solid", "roundness": { "type": 3 },
|
||||
"strokeColor": "#4a9eed", "strokeWidth": 1, "opacity": 20 },
|
||||
{ "type": "text", "id": "zone-maint-label", "x": 30, "y": 745, "text": "Maintenance & Cleanup", "fontSize": 14, "strokeColor": "#1971c2" },
|
||||
|
||||
{ "type": "rectangle", "id": "a9-trigger", "x": 30, "y": 770, "width": 200, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#d0bfff", "fillStyle": "solid",
|
||||
"label": { "text": "A9: Stale issue cleanup\nWeekly backlog hygiene", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "a9-a1", "x": 230, "y": 795, "width": 50, "height": 0,
|
||||
"points": [[0,0],[50,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "a9-cmd1", "x": 280, "y": 775, "width": 200, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "-J issues --sort updated --asc", "fontSize": 12 } },
|
||||
{ "type": "arrow", "id": "a9-a2", "x": 480, "y": 795, "width": 20, "height": 0,
|
||||
"points": [[0,0],[20,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "a9-cmd2", "x": 500, "y": 775, "width": 120, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffd8a8", "fillStyle": "solid",
|
||||
"label": { "text": "filter client-side", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "a9-a3", "x": 620, "y": 795, "width": 240, "height": 0,
|
||||
"points": [[0,0],[240,0]], "endArrowhead": "arrow", "strokeColor": "#ef4444", "strokeStyle": "dashed" },
|
||||
{ "type": "rectangle", "id": "a9-gap", "x": 860, "y": 770, "width": 110, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffc9c9", "fillStyle": "solid", "strokeColor": "#ef4444",
|
||||
"label": { "text": "No --before\nNo offset", "fontSize": 14 } },
|
||||
|
||||
{ "type": "rectangle", "id": "a15-trigger", "x": 30, "y": 840, "width": 200, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#d0bfff", "fillStyle": "solid",
|
||||
"label": { "text": "A15: Conflict detect\n\"Safe to start work?\"", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "a15-a1", "x": 230, "y": 865, "width": 50, "height": 0,
|
||||
"points": [[0,0],[50,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "a15-cmd1", "x": 280, "y": 845, "width": 110, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "-J issues 123", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "a15-a2", "x": 390, "y": 865, "width": 20, "height": 0,
|
||||
"points": [[0,0],[20,0]], "endArrowhead": "arrow" },
|
||||
{ "type": "rectangle", "id": "a15-cmd2", "x": 410, "y": 845, "width": 130, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "-J who --overlap", "fontSize": 14 } },
|
||||
{ "type": "arrow", "id": "a15-a3", "x": 540, "y": 865, "width": 320, "height": 0,
|
||||
"points": [[0,0],[320,0]], "endArrowhead": "arrow", "strokeColor": "#ef4444", "strokeStyle": "dashed" },
|
||||
{ "type": "rectangle", "id": "a15-gap", "x": 860, "y": 840, "width": 110, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffc9c9", "fillStyle": "solid", "strokeColor": "#ef4444",
|
||||
"label": { "text": "No refs +\n--state", "fontSize": 14 } },
|
||||
|
||||
{ "type": "text", "id": "callout-1", "x": 30, "y": 910, "text": "Agent-specific pain: Agents always use -J and --fields minimal for token efficiency. Every extra query burns tokens.", "fontSize": 14, "strokeColor": "#495057" },
|
||||
{ "type": "text", "id": "callout-2", "x": 30, "y": 935, "text": "Biggest ROI: `lore refs` command would unblock A5, A11, A12, A15 instantly. Data already exists in entity_references table.", "fontSize": 14, "strokeColor": "#15803d" },
|
||||
{ "type": "text", "id": "callout-3", "x": 30, "y": 960, "text": "Token waste: Sprint report (A3) requires 7 calls. A composite `lore summary` could save ~85% of tokens.", "fontSize": 14, "strokeColor": "#ef4444" }
|
||||
],
|
||||
"appState": { "viewBackgroundColor": "#ffffff", "gridSize": null },
|
||||
"files": {}
|
||||
}
|
||||
BIN
docs/diagrams/02-agent-flow-map.png
Normal file
BIN
docs/diagrams/02-agent-flow-map.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 269 KiB |
203
docs/diagrams/03-command-coverage.excalidraw
Normal file
203
docs/diagrams/03-command-coverage.excalidraw
Normal file
@@ -0,0 +1,203 @@
|
||||
{
|
||||
"type": "excalidraw",
|
||||
"version": 2,
|
||||
"source": "https://excalidraw.com",
|
||||
"elements": [
|
||||
{ "type": "text", "id": "title", "x": 280, "y": 15, "text": "Command Coverage Heatmap", "fontSize": 28 },
|
||||
{ "type": "text", "id": "subtitle", "x": 220, "y": 53, "text": "Which commands serve which workflows? Darker = more essential to that flow.", "fontSize": 14, "strokeColor": "#868e96" },
|
||||
|
||||
{ "type": "text", "id": "col-issues", "x": 260, "y": 85, "text": "issues", "fontSize": 14, "strokeColor": "#1971c2" },
|
||||
{ "type": "text", "id": "col-mrs", "x": 330, "y": 85, "text": "mrs", "fontSize": 14, "strokeColor": "#1971c2" },
|
||||
{ "type": "text", "id": "col-search", "x": 390, "y": 85, "text": "search", "fontSize": 14, "strokeColor": "#1971c2" },
|
||||
{ "type": "text", "id": "col-who", "x": 465, "y": 85, "text": "who", "fontSize": 14, "strokeColor": "#1971c2" },
|
||||
{ "type": "text", "id": "col-timeline", "x": 520, "y": 85, "text": "timeline", "fontSize": 14, "strokeColor": "#1971c2" },
|
||||
{ "type": "text", "id": "col-sync", "x": 600, "y": 85, "text": "sync", "fontSize": 14, "strokeColor": "#1971c2" },
|
||||
{ "type": "text", "id": "col-count", "x": 660, "y": 85, "text": "count", "fontSize": 14, "strokeColor": "#1971c2" },
|
||||
{ "type": "text", "id": "col-status", "x": 720, "y": 85, "text": "status", "fontSize": 14, "strokeColor": "#1971c2" },
|
||||
{ "type": "text", "id": "col-missing", "x": 790, "y": 85, "text": "MISSING?", "fontSize": 14, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "text", "id": "grp-human", "x": 15, "y": 108, "text": "HUMAN FLOWS", "fontSize": 14, "strokeColor": "#15803d" },
|
||||
|
||||
{ "type": "text", "id": "h1-label", "x": 15, "y": 135, "text": "H1 Standup prep", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "h1-issues", "x": 255, "y": 130, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "h1-mrs", "x": 325, "y": 130, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "h1-who", "x": 460, "y": 130, "width": 50, "height": 28, "backgroundColor": "#b2f2bb", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "h1-sync", "x": 595, "y": 130, "width": 50, "height": 28, "backgroundColor": "#b2f2bb", "fillStyle": "solid" },
|
||||
{ "type": "text", "id": "h1-gap", "x": 780, "y": 135, "text": "activity feed", "fontSize": 12, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "text", "id": "h2-label", "x": 15, "y": 170, "text": "H2 Sprint planning", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "h2-issues", "x": 255, "y": 165, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "h2-count", "x": 655, "y": 165, "width": 50, "height": 28, "backgroundColor": "#b2f2bb", "fillStyle": "solid" },
|
||||
{ "type": "text", "id": "h2-gap", "x": 780, "y": 170, "text": "--no-assignee", "fontSize": 12, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "text", "id": "h3-label", "x": 15, "y": 205, "text": "H3 Incident response", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "h3-mrs", "x": 325, "y": 200, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "h3-search", "x": 390, "y": 200, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "h3-who", "x": 460, "y": 200, "width": 50, "height": 28, "backgroundColor": "#b2f2bb", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "h3-timeline", "x": 525, "y": 200, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "h3-sync", "x": 595, "y": 200, "width": 50, "height": 28, "backgroundColor": "#b2f2bb", "fillStyle": "solid" },
|
||||
|
||||
{ "type": "text", "id": "h4-label", "x": 15, "y": 240, "text": "H4 Code review prep", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "h4-mrs", "x": 325, "y": 235, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "h4-search", "x": 390, "y": 235, "width": 50, "height": 28, "backgroundColor": "#b2f2bb", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "h4-who", "x": 460, "y": 235, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "h4-timeline", "x": 525, "y": 235, "width": 50, "height": 28, "backgroundColor": "#b2f2bb", "fillStyle": "solid" },
|
||||
{ "type": "text", "id": "h4-gap", "x": 780, "y": 240, "text": "MR file list", "fontSize": 12, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "text", "id": "h5-label", "x": 15, "y": 275, "text": "H5 Onboarding", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "h5-issues", "x": 255, "y": 270, "width": 50, "height": 28, "backgroundColor": "#b2f2bb", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "h5-mrs", "x": 325, "y": 270, "width": 50, "height": 28, "backgroundColor": "#b2f2bb", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "h5-search", "x": 390, "y": 270, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "h5-who", "x": 460, "y": 270, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "h5-timeline", "x": 525, "y": 270, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
|
||||
{ "type": "text", "id": "h6-label", "x": 15, "y": 310, "text": "H6 Find reviewer", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "h6-who", "x": 460, "y": 305, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "text", "id": "h6-gap", "x": 780, "y": 310, "text": "multi-path who", "fontSize": 12, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "text", "id": "h7-label", "x": 15, "y": 345, "text": "H7 Why was this built?", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "h7-issues", "x": 255, "y": 340, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "h7-mrs", "x": 325, "y": 340, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "h7-search", "x": 390, "y": 340, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "h7-timeline", "x": 525, "y": 340, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "text", "id": "h7-gap", "x": 780, "y": 345, "text": "per-note search", "fontSize": 12, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "text", "id": "h8-label", "x": 15, "y": 380, "text": "H8 Team workload", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "h8-who", "x": 460, "y": 375, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "text", "id": "h8-gap", "x": 780, "y": 380, "text": "team view", "fontSize": 12, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "text", "id": "h9-label", "x": 15, "y": 415, "text": "H9 Release notes", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "h9-issues", "x": 255, "y": 410, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "h9-mrs", "x": 325, "y": 410, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "text", "id": "h9-gap", "x": 780, "y": 415, "text": "mrs --milestone", "fontSize": 12, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "text", "id": "h10-label", "x": 15, "y": 450, "text": "H10 Stale issues", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "h10-issues", "x": 255, "y": 445, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "text", "id": "h10-gap", "x": 780, "y": 450, "text": "--updated-before", "fontSize": 12, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "text", "id": "h11-label", "x": 15, "y": 485, "text": "H11 Bug lifecycle", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "h11-issues", "x": 255, "y": 480, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "h11-timeline", "x": 525, "y": 480, "width": 50, "height": 28, "backgroundColor": "#ffd8a8", "fillStyle": "solid" },
|
||||
{ "type": "text", "id": "h11-gap", "x": 780, "y": 485, "text": "entity timeline", "fontSize": 12, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "text", "id": "h12-label", "x": 15, "y": 520, "text": "H12 Who broke tests?", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "h12-search", "x": 390, "y": 515, "width": 50, "height": 28, "backgroundColor": "#b2f2bb", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "h12-who", "x": 460, "y": 515, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
|
||||
{ "type": "text", "id": "h13-label", "x": 15, "y": 555, "text": "H13 Feature tracking", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "h13-issues", "x": 255, "y": 550, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "h13-mrs", "x": 325, "y": 550, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "h13-timeline", "x": 525, "y": 550, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
|
||||
{ "type": "text", "id": "h14-label", "x": 15, "y": 590, "text": "H14 Prior art check", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "h14-search", "x": 390, "y": 585, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "h14-timeline", "x": 525, "y": 585, "width": 50, "height": 28, "backgroundColor": "#b2f2bb", "fillStyle": "solid" },
|
||||
{ "type": "text", "id": "h14-gap", "x": 780, "y": 590, "text": "--state on search", "fontSize": 12, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "text", "id": "h15-label", "x": 15, "y": 625, "text": "H15 My discussions", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "h15-who", "x": 460, "y": 620, "width": 50, "height": 28, "backgroundColor": "#ffd8a8", "fillStyle": "solid" },
|
||||
{ "type": "text", "id": "h15-gap", "x": 780, "y": 625, "text": "participant filter", "fontSize": 12, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "rectangle", "id": "divider", "x": 10, "y": 655, "width": 910, "height": 2, "backgroundColor": "#dee2e6", "fillStyle": "solid" },
|
||||
|
||||
{ "type": "text", "id": "grp-agent", "x": 15, "y": 668, "text": "AI AGENT FLOWS", "fontSize": 14, "strokeColor": "#7048e8" },
|
||||
|
||||
{ "type": "text", "id": "a1-label", "x": 15, "y": 695, "text": "A1 Pre-edit context", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "a1-mrs", "x": 325, "y": 690, "width": 50, "height": 28, "backgroundColor": "#b2f2bb", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "a1-search", "x": 390, "y": 690, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "a1-who", "x": 460, "y": 690, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
|
||||
{ "type": "text", "id": "a2-label", "x": 15, "y": 730, "text": "A2 Auto-triage", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "a2-issues", "x": 255, "y": 725, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "a2-search", "x": 390, "y": 725, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "a2-who", "x": 460, "y": 725, "width": 50, "height": 28, "backgroundColor": "#b2f2bb", "fillStyle": "solid" },
|
||||
{ "type": "text", "id": "a2-gap", "x": 780, "y": 730, "text": "detail --fields", "fontSize": 12, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "text", "id": "a3-label", "x": 15, "y": 765, "text": "A3 Sprint report", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "a3-issues", "x": 255, "y": 760, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "a3-mrs", "x": 325, "y": 760, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "a3-who", "x": 460, "y": 760, "width": 50, "height": 28, "backgroundColor": "#b2f2bb", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "a3-count", "x": 655, "y": 760, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "text", "id": "a3-gap", "x": 780, "y": 765, "text": "summary cmd", "fontSize": 12, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "text", "id": "a4-label", "x": 15, "y": 800, "text": "A4 Prior art", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "a4-search", "x": 390, "y": 795, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "a4-timeline", "x": 525, "y": 795, "width": 50, "height": 28, "backgroundColor": "#b2f2bb", "fillStyle": "solid" },
|
||||
{ "type": "text", "id": "a4-gap", "x": 780, "y": 800, "text": "per-note search", "fontSize": 12, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "text", "id": "a5-label", "x": 15, "y": 835, "text": "A5 PR description", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "a5-issues", "x": 255, "y": 830, "width": 50, "height": 28, "backgroundColor": "#b2f2bb", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "a5-search", "x": 390, "y": 830, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "text", "id": "a5-gap", "x": 780, "y": 835, "text": "entity refs query", "fontSize": 12, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "text", "id": "a6-label", "x": 15, "y": 870, "text": "A6 Reviewer assign", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "a6-mrs", "x": 325, "y": 865, "width": 50, "height": 28, "backgroundColor": "#ffd8a8", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "a6-who", "x": 460, "y": 865, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "text", "id": "a6-gap", "x": 780, "y": 870, "text": "MR file list", "fontSize": 12, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "text", "id": "a7-label", "x": 15, "y": 905, "text": "A7 Incident timeline", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "a7-mrs", "x": 325, "y": 900, "width": 50, "height": 28, "backgroundColor": "#b2f2bb", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "a7-search", "x": 390, "y": 900, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "a7-timeline", "x": 525, "y": 900, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
|
||||
{ "type": "text", "id": "a8-label", "x": 15, "y": 940, "text": "A8 Cross-project", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "a8-search", "x": 390, "y": 935, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "a8-timeline", "x": 525, "y": 935, "width": 50, "height": 28, "backgroundColor": "#b2f2bb", "fillStyle": "solid" },
|
||||
{ "type": "text", "id": "a8-gap", "x": 780, "y": 940, "text": "group by project", "fontSize": 12, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "text", "id": "a9-label", "x": 15, "y": 975, "text": "A9 Stale cleanup", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "a9-issues", "x": 255, "y": 970, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "a9-search", "x": 390, "y": 970, "width": 50, "height": 28, "backgroundColor": "#b2f2bb", "fillStyle": "solid" },
|
||||
{ "type": "text", "id": "a9-gap", "x": 780, "y": 975, "text": "--updated-before", "fontSize": 12, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "text", "id": "a10-label", "x": 15, "y": 1010, "text": "A10 Review context", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "a10-mrs", "x": 325, "y": 1005, "width": 50, "height": 28, "backgroundColor": "#ffd8a8", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "a10-who", "x": 460, "y": 1005, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "text", "id": "a10-gap", "x": 780, "y": 1010, "text": "MR file list", "fontSize": 12, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "text", "id": "a11-label", "x": 15, "y": 1045, "text": "A11 Knowledge graph", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "a11-search", "x": 390, "y": 1040, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "a11-timeline", "x": 525, "y": 1040, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "text", "id": "a11-gap", "x": 780, "y": 1045, "text": "entity refs query", "fontSize": 12, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "text", "id": "a12-label", "x": 15, "y": 1080, "text": "A12 Release check", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "a12-issues", "x": 255, "y": 1075, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "a12-mrs", "x": 325, "y": 1075, "width": 50, "height": 28, "backgroundColor": "#ffd8a8", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "a12-who", "x": 460, "y": 1075, "width": 50, "height": 28, "backgroundColor": "#b2f2bb", "fillStyle": "solid" },
|
||||
{ "type": "text", "id": "a12-gap", "x": 780, "y": 1080, "text": "mrs --milestone", "fontSize": 12, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "text", "id": "a13-label", "x": 15, "y": 1115, "text": "A13 What changed?", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "a13-issues", "x": 255, "y": 1110, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "a13-mrs", "x": 325, "y": 1110, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "text", "id": "a13-gap", "x": 780, "y": 1115, "text": "state-change filter", "fontSize": 12, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "text", "id": "a14-label", "x": 15, "y": 1150, "text": "A14 Meeting prep", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "a14-issues", "x": 255, "y": 1145, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "a14-mrs", "x": 325, "y": 1145, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "a14-who", "x": 460, "y": 1145, "width": 50, "height": 28, "backgroundColor": "#b2f2bb", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "a14-count", "x": 655, "y": 1145, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "text", "id": "a14-gap", "x": 780, "y": 1150, "text": "summary cmd", "fontSize": 12, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "text", "id": "a15-label", "x": 15, "y": 1185, "text": "A15 Conflict detect", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "a15-issues", "x": 255, "y": 1180, "width": 50, "height": 28, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "a15-mrs", "x": 325, "y": 1180, "width": 50, "height": 28, "backgroundColor": "#b2f2bb", "fillStyle": "solid" },
|
||||
{ "type": "rectangle", "id": "a15-who", "x": 460, "y": 1180, "width": 50, "height": 28, "backgroundColor": "#b2f2bb", "fillStyle": "solid" },
|
||||
{ "type": "text", "id": "a15-gap", "x": 780, "y": 1185, "text": "entity refs, --state", "fontSize": 12, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "text", "id": "legend-title", "x": 15, "y": 1230, "text": "Legend:", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "leg-essential", "x": 80, "y": 1228, "width": 20, "height": 20, "backgroundColor": "#22c55e", "fillStyle": "solid" },
|
||||
{ "type": "text", "id": "leg-essential-t", "x": 105, "y": 1230, "text": "Essential", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "leg-supporting", "x": 190, "y": 1228, "width": 20, "height": 20, "backgroundColor": "#b2f2bb", "fillStyle": "solid" },
|
||||
{ "type": "text", "id": "leg-supporting-t", "x": 215, "y": 1230, "text": "Supporting", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "leg-partial", "x": 310, "y": 1228, "width": 20, "height": 20, "backgroundColor": "#ffd8a8", "fillStyle": "solid" },
|
||||
{ "type": "text", "id": "leg-partial-t", "x": 335, "y": 1230, "text": "Partially blocked", "fontSize": 14 },
|
||||
{ "type": "text", "id": "leg-gap-t", "x": 470, "y": 1230, "text": "Red text = gap", "fontSize": 14, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "text", "id": "insight-1", "x": 15, "y": 1270, "text": "Key insight: `issues` and `search` are the workhorses (used in 20+ flows).", "fontSize": 14, "strokeColor": "#495057" },
|
||||
{ "type": "text", "id": "insight-2", "x": 15, "y": 1295, "text": "`who` is critical for people questions but siloed from file-change data.", "fontSize": 14, "strokeColor": "#495057" },
|
||||
{ "type": "text", "id": "insight-3", "x": 15, "y": 1320, "text": "`timeline` is powerful but keyword-only seeding limits entity-specific queries.", "fontSize": 14, "strokeColor": "#495057" },
|
||||
{ "type": "text", "id": "insight-4", "x": 15, "y": 1345, "text": "22/30 flows have at least one gap. Most gaps are filter additions, not new commands.", "fontSize": 14, "strokeColor": "#ef4444" }
|
||||
],
|
||||
"appState": { "viewBackgroundColor": "#ffffff", "gridSize": null },
|
||||
"files": {}
|
||||
}
|
||||
BIN
docs/diagrams/03-command-coverage.png
Normal file
BIN
docs/diagrams/03-command-coverage.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 217 KiB |
110
docs/diagrams/04-gap-priority-matrix.excalidraw
Normal file
110
docs/diagrams/04-gap-priority-matrix.excalidraw
Normal file
@@ -0,0 +1,110 @@
|
||||
{
|
||||
"type": "excalidraw",
|
||||
"version": 2,
|
||||
"source": "https://excalidraw.com",
|
||||
"elements": [
|
||||
{ "type": "text", "id": "title", "x": 300, "y": 20, "text": "Lore CLI Gap Priority Matrix", "fontSize": 28 },
|
||||
{ "type": "text", "id": "subtitle", "x": 310, "y": 58, "text": "20 identified gaps plotted by impact vs effort", "fontSize": 16, "strokeColor": "#868e96" },
|
||||
|
||||
{ "type": "rectangle", "id": "q1-zone", "x": 100, "y": 120, "width": 500, "height": 380,
|
||||
"backgroundColor": "#d3f9d8", "fillStyle": "solid", "roundness": { "type": 3 },
|
||||
"strokeColor": "#22c55e", "strokeWidth": 1, "opacity": 25 },
|
||||
{ "type": "text", "id": "q1-label", "x": 110, "y": 126, "text": "QUICK WINS", "fontSize": 18, "strokeColor": "#15803d" },
|
||||
|
||||
{ "type": "rectangle", "id": "q2-zone", "x": 620, "y": 120, "width": 500, "height": 380,
|
||||
"backgroundColor": "#fff3bf", "fillStyle": "solid", "roundness": { "type": 3 },
|
||||
"strokeColor": "#f59e0b", "strokeWidth": 1, "opacity": 25 },
|
||||
{ "type": "text", "id": "q2-label", "x": 630, "y": 126, "text": "STRATEGIC", "fontSize": 18, "strokeColor": "#b45309" },
|
||||
|
||||
{ "type": "rectangle", "id": "q3-zone", "x": 100, "y": 520, "width": 500, "height": 300,
|
||||
"backgroundColor": "#dbe4ff", "fillStyle": "solid", "roundness": { "type": 3 },
|
||||
"strokeColor": "#4a9eed", "strokeWidth": 1, "opacity": 25 },
|
||||
{ "type": "text", "id": "q3-label", "x": 110, "y": 526, "text": "FILL-IN", "fontSize": 18, "strokeColor": "#1971c2" },
|
||||
|
||||
{ "type": "rectangle", "id": "q4-zone", "x": 620, "y": 520, "width": 500, "height": 300,
|
||||
"backgroundColor": "#ffc9c9", "fillStyle": "solid", "roundness": { "type": 3 },
|
||||
"strokeColor": "#ef4444", "strokeWidth": 1, "opacity": 25 },
|
||||
{ "type": "text", "id": "q4-label", "x": 630, "y": 526, "text": "DEPRIORITIZE", "fontSize": 18, "strokeColor": "#c92a2a" },
|
||||
|
||||
{ "type": "text", "id": "y-axis-hi", "x": 30, "y": 130, "text": "HIGH\nIMPACT", "fontSize": 16, "strokeColor": "#495057", "textAlign": "center" },
|
||||
{ "type": "text", "id": "y-axis-lo", "x": 30, "y": 550, "text": "LOW\nIMPACT", "fontSize": 16, "strokeColor": "#495057", "textAlign": "center" },
|
||||
{ "type": "text", "id": "x-axis-lo", "x": 280, "y": 840, "text": "LOW EFFORT", "fontSize": 16, "strokeColor": "#495057" },
|
||||
{ "type": "text", "id": "x-axis-hi", "x": 800, "y": 840, "text": "HIGH EFFORT", "fontSize": 16, "strokeColor": "#495057" },
|
||||
|
||||
{ "type": "arrow", "id": "y-arrow", "x": 85, "y": 810, "width": 0, "height": -680,
|
||||
"points": [[0,0],[0,-680]], "endArrowhead": "arrow", "strokeColor": "#495057", "strokeWidth": 1 },
|
||||
{ "type": "arrow", "id": "x-arrow", "x": 85, "y": 810, "width": 1050, "height": 0,
|
||||
"points": [[0,0],[1050,0]], "endArrowhead": "arrow", "strokeColor": "#495057", "strokeWidth": 1 },
|
||||
|
||||
{ "type": "rectangle", "id": "g5", "x": 120, "y": 160, "width": 210, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "#5 @me alias", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "g8", "x": 120, "y": 225, "width": 210, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "#8 --state on search", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "g9", "x": 120, "y": 290, "width": 210, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "#9 mrs --milestone", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "g10", "x": 120, "y": 355, "width": 210, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "#10 --no-assignee", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "g11", "x": 350, "y": 160, "width": 230, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "#11 --updated-before", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "g14", "x": 350, "y": 225, "width": 230, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "#14 detail --fields", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "g18", "x": 350, "y": 290, "width": 230, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "#18 1y/12m duration", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "g20", "x": 350, "y": 355, "width": 230, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "#20 sort by due date", "fontSize": 16 } },
|
||||
|
||||
{ "type": "rectangle", "id": "g1", "x": 640, "y": 160, "width": 220, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffd8a8", "fillStyle": "solid",
|
||||
"label": { "text": "#1 MR file changes", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "g2", "x": 640, "y": 225, "width": 220, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffd8a8", "fillStyle": "solid",
|
||||
"label": { "text": "#2 entity refs query", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "g3", "x": 640, "y": 290, "width": 220, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffd8a8", "fillStyle": "solid",
|
||||
"label": { "text": "#3 per-note search", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "g4", "x": 880, "y": 160, "width": 220, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffd8a8", "fillStyle": "solid",
|
||||
"label": { "text": "#4 entity timeline", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "g6", "x": 880, "y": 225, "width": 220, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffd8a8", "fillStyle": "solid",
|
||||
"label": { "text": "#6 activity feed", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "g12", "x": 880, "y": 290, "width": 220, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffd8a8", "fillStyle": "solid",
|
||||
"label": { "text": "#12 team workload", "fontSize": 16 } },
|
||||
|
||||
{ "type": "rectangle", "id": "g13", "x": 120, "y": 570, "width": 210, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#a5d8ff", "fillStyle": "solid",
|
||||
"label": { "text": "#13 pagination/offset", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "g15", "x": 120, "y": 635, "width": 210, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#a5d8ff", "fillStyle": "solid",
|
||||
"label": { "text": "#15 group by project", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "g19", "x": 120, "y": 700, "width": 210, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#a5d8ff", "fillStyle": "solid",
|
||||
"label": { "text": "#19 participant filter", "fontSize": 16 } },
|
||||
|
||||
{ "type": "rectangle", "id": "g7", "x": 640, "y": 570, "width": 220, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffc9c9", "fillStyle": "solid",
|
||||
"label": { "text": "#7 multi-path who", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "g16", "x": 640, "y": 635, "width": 220, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffc9c9", "fillStyle": "solid",
|
||||
"label": { "text": "#16 trend metrics", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "g17", "x": 640, "y": 700, "width": 220, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffc9c9", "fillStyle": "solid",
|
||||
"label": { "text": "#17 --for-issue on mrs", "fontSize": 16 } },
|
||||
|
||||
{ "type": "text", "id": "q1-count", "x": 180, "y": 430, "text": "8 gaps - lowest hanging fruit", "fontSize": 14, "strokeColor": "#15803d" },
|
||||
{ "type": "text", "id": "q2-count", "x": 710, "y": 370, "text": "6 gaps - build deliberately", "fontSize": 14, "strokeColor": "#b45309" },
|
||||
{ "type": "text", "id": "q3-count", "x": 160, "y": 770, "text": "3 gaps - fill as needed", "fontSize": 14, "strokeColor": "#1971c2" },
|
||||
{ "type": "text", "id": "q4-count", "x": 680, "y": 770, "text": "3 gaps - defer or rethink", "fontSize": 14, "strokeColor": "#c92a2a" }
|
||||
],
|
||||
"appState": { "viewBackgroundColor": "#ffffff", "gridSize": null },
|
||||
"files": {}
|
||||
}
|
||||
BIN
docs/diagrams/04-gap-priority-matrix.png
Normal file
BIN
docs/diagrams/04-gap-priority-matrix.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 179 KiB |
184
docs/diagrams/05-data-flow-architecture.excalidraw
Normal file
184
docs/diagrams/05-data-flow-architecture.excalidraw
Normal file
@@ -0,0 +1,184 @@
|
||||
{
|
||||
"type": "excalidraw",
|
||||
"version": 2,
|
||||
"source": "https://excalidraw.com",
|
||||
"elements": [
|
||||
{ "type": "text", "id": "title", "x": 350, "y": 15, "text": "Lore Data Flow Architecture", "fontSize": 28 },
|
||||
{ "type": "text", "id": "subtitle", "x": 280, "y": 53, "text": "Green = queryable via CLI | Red = stored but hidden | Gray = internal", "fontSize": 14, "strokeColor": "#868e96" },
|
||||
|
||||
{ "type": "rectangle", "id": "zone-gitlab", "x": 30, "y": 90, "width": 200, "height": 300,
|
||||
"backgroundColor": "#e5dbff", "fillStyle": "solid", "roundness": { "type": 3 },
|
||||
"strokeColor": "#8b5cf6", "strokeWidth": 1, "opacity": 30 },
|
||||
{ "type": "text", "id": "zone-gitlab-label", "x": 55, "y": 96, "text": "GitLab APIs", "fontSize": 16, "strokeColor": "#7048e8" },
|
||||
|
||||
{ "type": "rectangle", "id": "rest-api", "x": 50, "y": 130, "width": 160, "height": 60,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#d0bfff", "fillStyle": "solid",
|
||||
"label": { "text": "REST API\n(paginated)", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "graphql-api", "x": 50, "y": 210, "width": 160, "height": 60,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#d0bfff", "fillStyle": "solid",
|
||||
"label": { "text": "GraphQL API\n(adaptive pages)", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "ollama-api", "x": 50, "y": 310, "width": 160, "height": 60,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#d0bfff", "fillStyle": "solid",
|
||||
"label": { "text": "Ollama\n(embeddings)", "fontSize": 16 } },
|
||||
|
||||
{ "type": "rectangle", "id": "zone-ingest", "x": 270, "y": 90, "width": 180, "height": 300,
|
||||
"backgroundColor": "#dbe4ff", "fillStyle": "solid", "roundness": { "type": 3 },
|
||||
"strokeColor": "#4a9eed", "strokeWidth": 1, "opacity": 30 },
|
||||
{ "type": "text", "id": "zone-ingest-label", "x": 300, "y": 96, "text": "Ingestion", "fontSize": 16, "strokeColor": "#1971c2" },
|
||||
|
||||
{ "type": "rectangle", "id": "ingest-issues", "x": 285, "y": 130, "width": 150, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#a5d8ff", "fillStyle": "solid",
|
||||
"label": { "text": "Issue Sync", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "ingest-mrs", "x": 285, "y": 195, "width": 150, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#a5d8ff", "fillStyle": "solid",
|
||||
"label": { "text": "MR Sync", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "ingest-disc", "x": 285, "y": 260, "width": 150, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#a5d8ff", "fillStyle": "solid",
|
||||
"label": { "text": "Discussion Sync", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "ingest-events", "x": 285, "y": 325, "width": 150, "height": 50,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#a5d8ff", "fillStyle": "solid",
|
||||
"label": { "text": "Event Sync", "fontSize": 16 } },
|
||||
|
||||
{ "type": "arrow", "id": "a-rest-issues", "x": 210, "y": 155, "width": 75, "height": 0,
|
||||
"points": [[0,0],[75,0]], "endArrowhead": "arrow", "strokeColor": "#495057" },
|
||||
{ "type": "arrow", "id": "a-rest-mrs", "x": 210, "y": 165, "width": 75, "height": 50,
|
||||
"points": [[0,0],[75,50]], "endArrowhead": "arrow", "strokeColor": "#495057" },
|
||||
{ "type": "arrow", "id": "a-graphql-issues", "x": 210, "y": 240, "width": 75, "height": -80,
|
||||
"points": [[0,0],[75,-80]], "endArrowhead": "arrow", "strokeColor": "#495057" },
|
||||
|
||||
{ "type": "rectangle", "id": "zone-sqlite", "x": 490, "y": 90, "width": 400, "height": 650,
|
||||
"backgroundColor": "#d3f9d8", "fillStyle": "solid", "roundness": { "type": 3 },
|
||||
"strokeColor": "#22c55e", "strokeWidth": 1, "opacity": 20 },
|
||||
{ "type": "text", "id": "zone-sqlite-label", "x": 570, "y": 96, "text": "SQLite (WAL mode)", "fontSize": 16, "strokeColor": "#15803d" },
|
||||
|
||||
{ "type": "text", "id": "grp-queryable", "x": 500, "y": 120, "text": "Queryable Tables", "fontSize": 14, "strokeColor": "#15803d" },
|
||||
|
||||
{ "type": "rectangle", "id": "t-projects", "x": 500, "y": 145, "width": 170, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "projects", "fontSize": 14 } },
|
||||
{ "type": "rectangle", "id": "t-issues", "x": 500, "y": 195, "width": 170, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "issues + assignees", "fontSize": 14 } },
|
||||
{ "type": "rectangle", "id": "t-mrs", "x": 500, "y": 245, "width": 170, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "merge_requests", "fontSize": 14 } },
|
||||
{ "type": "rectangle", "id": "t-discussions", "x": 500, "y": 295, "width": 170, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "discussions + notes", "fontSize": 14 } },
|
||||
{ "type": "rectangle", "id": "t-events", "x": 500, "y": 345, "width": 170, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "resource_*_events", "fontSize": 14 } },
|
||||
{ "type": "rectangle", "id": "t-docs", "x": 500, "y": 395, "width": 170, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "documents + FTS5", "fontSize": 14 } },
|
||||
{ "type": "rectangle", "id": "t-embed", "x": 500, "y": 445, "width": 170, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#b2f2bb", "fillStyle": "solid",
|
||||
"label": { "text": "embeddings (vec)", "fontSize": 14 } },
|
||||
|
||||
{ "type": "text", "id": "grp-hidden", "x": 700, "y": 120, "text": "Hidden Tables", "fontSize": 14, "strokeColor": "#c92a2a" },
|
||||
|
||||
{ "type": "rectangle", "id": "t-file-changes", "x": 695, "y": 145, "width": 180, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffc9c9", "fillStyle": "solid", "strokeColor": "#ef4444",
|
||||
"label": { "text": "mr_file_changes", "fontSize": 14 } },
|
||||
{ "type": "rectangle", "id": "t-entity-refs", "x": 695, "y": 195, "width": 180, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffc9c9", "fillStyle": "solid", "strokeColor": "#ef4444",
|
||||
"label": { "text": "entity_references", "fontSize": 14 } },
|
||||
{ "type": "rectangle", "id": "t-raw", "x": 695, "y": 245, "width": 180, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffc9c9", "fillStyle": "solid", "strokeColor": "#ef4444",
|
||||
"label": { "text": "raw_payloads", "fontSize": 14 } },
|
||||
|
||||
{ "type": "text", "id": "grp-internal", "x": 700, "y": 310, "text": "Internal Only", "fontSize": 14, "strokeColor": "#868e96" },
|
||||
|
||||
{ "type": "rectangle", "id": "t-sync", "x": 695, "y": 340, "width": 180, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#dee2e6", "fillStyle": "solid", "strokeColor": "#868e96",
|
||||
"label": { "text": "sync_runs + cursors", "fontSize": 14 } },
|
||||
{ "type": "rectangle", "id": "t-dirty", "x": 695, "y": 390, "width": 180, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#dee2e6", "fillStyle": "solid", "strokeColor": "#868e96",
|
||||
"label": { "text": "dirty_sources", "fontSize": 14 } },
|
||||
{ "type": "rectangle", "id": "t-locks", "x": 695, "y": 440, "width": 180, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#dee2e6", "fillStyle": "solid", "strokeColor": "#868e96",
|
||||
"label": { "text": "app_locks", "fontSize": 14 } },
|
||||
|
||||
{ "type": "arrow", "id": "a-ingest-tables", "x": 435, "y": 200, "width": 55, "height": 0,
|
||||
"points": [[0,0],[55,0]], "endArrowhead": "arrow", "strokeColor": "#495057" },
|
||||
|
||||
{ "type": "rectangle", "id": "zone-cli", "x": 930, "y": 90, "width": 250, "height": 650,
|
||||
"backgroundColor": "#fff3bf", "fillStyle": "solid", "roundness": { "type": 3 },
|
||||
"strokeColor": "#f59e0b", "strokeWidth": 1, "opacity": 25 },
|
||||
{ "type": "text", "id": "zone-cli-label", "x": 990, "y": 96, "text": "CLI Commands", "fontSize": 16, "strokeColor": "#b45309" },
|
||||
|
||||
{ "type": "rectangle", "id": "cmd-issues", "x": 950, "y": 130, "width": 210, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#fff3bf", "fillStyle": "solid",
|
||||
"label": { "text": "lore issues", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "cmd-mrs", "x": 950, "y": 185, "width": 210, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#fff3bf", "fillStyle": "solid",
|
||||
"label": { "text": "lore mrs", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "cmd-search", "x": 950, "y": 240, "width": 210, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#fff3bf", "fillStyle": "solid",
|
||||
"label": { "text": "lore search", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "cmd-who", "x": 950, "y": 295, "width": 210, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#fff3bf", "fillStyle": "solid",
|
||||
"label": { "text": "lore who", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "cmd-timeline", "x": 950, "y": 350, "width": 210, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#fff3bf", "fillStyle": "solid",
|
||||
"label": { "text": "lore timeline", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "cmd-count", "x": 950, "y": 405, "width": 210, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#fff3bf", "fillStyle": "solid",
|
||||
"label": { "text": "lore count", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "cmd-sync", "x": 950, "y": 460, "width": 210, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#fff3bf", "fillStyle": "solid",
|
||||
"label": { "text": "lore sync", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "cmd-status", "x": 950, "y": 515, "width": 210, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#fff3bf", "fillStyle": "solid",
|
||||
"label": { "text": "lore status", "fontSize": 16 } },
|
||||
|
||||
{ "type": "arrow", "id": "a-issues-cmd", "x": 670, "y": 215, "width": 270, "height": -65,
|
||||
"points": [[0,0],[270,-65]], "endArrowhead": "arrow", "strokeColor": "#22c55e", "strokeWidth": 2 },
|
||||
{ "type": "arrow", "id": "a-mrs-cmd", "x": 670, "y": 265, "width": 270, "height": -60,
|
||||
"points": [[0,0],[270,-60]], "endArrowhead": "arrow", "strokeColor": "#22c55e", "strokeWidth": 2 },
|
||||
{ "type": "arrow", "id": "a-docs-cmd", "x": 670, "y": 415, "width": 270, "height": -155,
|
||||
"points": [[0,0],[270,-155]], "endArrowhead": "arrow", "strokeColor": "#22c55e", "strokeWidth": 2 },
|
||||
{ "type": "arrow", "id": "a-embed-cmd", "x": 670, "y": 465, "width": 270, "height": -200,
|
||||
"points": [[0,0],[270,-200]], "endArrowhead": "arrow", "strokeColor": "#22c55e", "strokeWidth": 2 },
|
||||
{ "type": "arrow", "id": "a-events-cmd", "x": 670, "y": 365, "width": 270, "height": 5,
|
||||
"points": [[0,0],[270,5]], "endArrowhead": "arrow", "strokeColor": "#22c55e", "strokeWidth": 2 },
|
||||
|
||||
{ "type": "text", "id": "hidden-note-1", "x": 695, "y": 498, "text": "mr_file_changes: populated by\nMR sync but NOT queryable.\nBlocks H4, A6, A10 flows.", "fontSize": 14, "strokeColor": "#ef4444" },
|
||||
{ "type": "text", "id": "hidden-note-2", "x": 695, "y": 568, "text": "entity_references: used by\ntimeline internally but NOT\nqueryable. Blocks A5, A11.", "fontSize": 14, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "arrow", "id": "a-hidden-who", "x": 875, "y": 165, "width": 65, "height": 148,
|
||||
"points": [[0,0],[65,148]], "endArrowhead": "arrow", "strokeColor": "#ef4444", "strokeWidth": 2,
|
||||
"strokeStyle": "dashed" },
|
||||
{ "type": "text", "id": "hidden-who-label", "x": 880, "y": 240, "text": "who uses\nDiffNotes,\nnot file\nchanges", "fontSize": 12, "strokeColor": "#ef4444" },
|
||||
|
||||
{ "type": "arrow", "id": "a-hidden-timeline", "x": 875, "y": 215, "width": 65, "height": 155,
|
||||
"points": [[0,0],[65,155]], "endArrowhead": "arrow", "strokeColor": "#ef4444", "strokeWidth": 2,
|
||||
"strokeStyle": "dashed" },
|
||||
|
||||
{ "type": "rectangle", "id": "cmd-missing-refs", "x": 950, "y": 580, "width": 210, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffc9c9", "fillStyle": "solid", "strokeColor": "#ef4444", "strokeStyle": "dashed",
|
||||
"label": { "text": "lore refs (missing)", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "cmd-missing-files", "x": 950, "y": 635, "width": 210, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffc9c9", "fillStyle": "solid", "strokeColor": "#ef4444", "strokeStyle": "dashed",
|
||||
"label": { "text": "lore files (missing)", "fontSize": 16 } },
|
||||
{ "type": "rectangle", "id": "cmd-missing-activity", "x": 950, "y": 690, "width": 210, "height": 40,
|
||||
"roundness": { "type": 3 }, "backgroundColor": "#ffc9c9", "fillStyle": "solid", "strokeColor": "#ef4444", "strokeStyle": "dashed",
|
||||
"label": { "text": "lore activity (missing)", "fontSize": 16 } },
|
||||
|
||||
{ "type": "text", "id": "legend-title", "x": 30, "y": 430, "text": "Legend", "fontSize": 16 },
|
||||
{ "type": "rectangle", "id": "leg-green", "x": 30, "y": 460, "width": 20, "height": 20,
|
||||
"backgroundColor": "#b2f2bb", "fillStyle": "solid" },
|
||||
{ "type": "text", "id": "leg-green-t", "x": 60, "y": 462, "text": "Queryable via CLI", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "leg-red", "x": 30, "y": 490, "width": 20, "height": 20,
|
||||
"backgroundColor": "#ffc9c9", "fillStyle": "solid", "strokeColor": "#ef4444" },
|
||||
{ "type": "text", "id": "leg-red-t", "x": 60, "y": 492, "text": "Stored but hidden", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "leg-gray", "x": 30, "y": 520, "width": 20, "height": 20,
|
||||
"backgroundColor": "#dee2e6", "fillStyle": "solid", "strokeColor": "#868e96" },
|
||||
{ "type": "text", "id": "leg-gray-t", "x": 60, "y": 522, "text": "Internal bookkeeping", "fontSize": 14 },
|
||||
{ "type": "rectangle", "id": "leg-dashed", "x": 30, "y": 550, "width": 20, "height": 20,
|
||||
"backgroundColor": "#ffc9c9", "fillStyle": "solid", "strokeColor": "#ef4444", "strokeStyle": "dashed" },
|
||||
{ "type": "text", "id": "leg-dashed-t", "x": 60, "y": 552, "text": "Missing command", "fontSize": 14 }
|
||||
],
|
||||
"appState": { "viewBackgroundColor": "#ffffff", "gridSize": null },
|
||||
"files": {}
|
||||
}
|
||||
BIN
docs/diagrams/05-data-flow-architecture.png
Normal file
BIN
docs/diagrams/05-data-flow-architecture.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 238 KiB |
66
docs/ideas/README.md
Normal file
66
docs/ideas/README.md
Normal file
@@ -0,0 +1,66 @@
|
||||
# Gitlore Feature Ideas
|
||||
|
||||
Central registry of potential features. Each idea leverages data already ingested
|
||||
into the local SQLite database (issues, MRs, discussions, notes, resource events,
|
||||
entity references, embeddings, file changes).
|
||||
|
||||
## Priority Tiers
|
||||
|
||||
**Tier 1 — High confidence, low effort, immediate value:**
|
||||
|
||||
| # | Idea | File | Confidence |
|
||||
|---|------|------|------------|
|
||||
| 9 | Similar Issues Finder | [similar-issues.md](similar-issues.md) | 95% |
|
||||
| 17 | "What Changed?" Digest | [digest.md](digest.md) | 93% |
|
||||
| 5 | Who Knows About X? | [experts.md](experts.md) | 92% |
|
||||
| -- | Multi-Project Ergonomics | [project-ergonomics.md](project-ergonomics.md) | 90% |
|
||||
| 27 | Weekly Digest Generator | [weekly-digest.md](weekly-digest.md) | 90% |
|
||||
| 4 | Stale Discussion Finder | [stale-discussions.md](stale-discussions.md) | 90% |
|
||||
|
||||
**Tier 2 — Strong ideas, moderate effort:**
|
||||
|
||||
| # | Idea | File | Confidence |
|
||||
|---|------|------|------------|
|
||||
| 19 | MR-to-Issue Closure Gap | [closure-gaps.md](closure-gaps.md) | 88% |
|
||||
| 1 | Contributor Heatmap | [contributors.md](contributors.md) | 88% |
|
||||
| 21 | Knowledge Silo Detection | [silos.md](silos.md) | 87% |
|
||||
| 2 | Review Bottleneck Detector | [bottlenecks.md](bottlenecks.md) | 85% |
|
||||
| 14 | File Hotspot Report | [hotspots.md](hotspots.md) | 85% |
|
||||
| 26 | Unlinked MR Finder | [unlinked.md](unlinked.md) | 83% |
|
||||
| 6 | Decision Archaeology | [decisions.md](decisions.md) | 82% |
|
||||
| 18 | Label Hygiene Audit | [label-audit.md](label-audit.md) | 82% |
|
||||
|
||||
**Tier 3 — Promising, needs more design work:**
|
||||
|
||||
| # | Idea | File | Confidence |
|
||||
|---|------|------|------------|
|
||||
| 29 | Entity Relationship Explorer | [graph.md](graph.md) | 80% |
|
||||
| 12 | Milestone Risk Report | [milestone-risk.md](milestone-risk.md) | 78% |
|
||||
| 3 | Label Velocity | [label-flow.md](label-flow.md) | 78% |
|
||||
| 24 | Recurring Bug Patterns | [recurring-patterns.md](recurring-patterns.md) | 76% |
|
||||
| 7 | Cross-Project Impact Graph | [impact-graph.md](impact-graph.md) | 75% |
|
||||
| 16 | Idle Work Detector | [idle.md](idle.md) | 73% |
|
||||
| 8 | MR Churn Analysis | [churn.md](churn.md) | 72% |
|
||||
| 15 | Author Collaboration Network | [collaboration.md](collaboration.md) | 70% |
|
||||
| 28 | DiffNote Coverage Map | [review-coverage.md](review-coverage.md) | 75% |
|
||||
| 25 | MR Pipeline Efficiency | [mr-pipeline.md](mr-pipeline.md) | 78% |
|
||||
|
||||
## Rejected Ideas (with reasons)
|
||||
|
||||
| # | Idea | Reason |
|
||||
|---|------|--------|
|
||||
| 10 | Sprint Burndown from Labels | Too opinionated about label semantics |
|
||||
| 11 | Code Review Quality Score | Subjective "quality" scoring creates perverse incentives |
|
||||
| 13 | Discussion Sentiment Drift | Unreliable heuristic sentiment on technical text |
|
||||
| 20 | Response Time Leaderboard | Toxic "leaderboard" framing; metric folded into #2 |
|
||||
| 22 | Timeline Diff | Niche use case; timeline already interleaves events |
|
||||
| 23 | Discussion Thread Summarizer | Requires LLM inference; out of scope for local-first tool |
|
||||
| 30 | NL Query Interface | Over-engineered; existing filters cover this |
|
||||
|
||||
## How to use this list
|
||||
|
||||
1. Pick an idea from Tier 1 or Tier 2
|
||||
2. Read its detail file for implementation plan and SQL sketches
|
||||
3. Create a bead (`br create`) referencing the idea file
|
||||
4. Implement following TDD (test first, then minimal impl)
|
||||
5. Update the idea file with `status: implemented` when done
|
||||
555
docs/ideas/SYSTEM-PROPOSAL.md
Normal file
555
docs/ideas/SYSTEM-PROPOSAL.md
Normal file
@@ -0,0 +1,555 @@
|
||||
# Project Manager System — Design Proposal
|
||||
|
||||
## The Problem
|
||||
|
||||
We have a growing backlog of ideas and issues in markdown files. Agents can ship
|
||||
features in under an hour. The constraint isn't execution speed — it's knowing
|
||||
WHAT to execute NEXT, in what ORDER, and detecting when the plan needs to change.
|
||||
|
||||
We need a system that:
|
||||
1. Automatically scores and sequences work items
|
||||
2. Detects when scope changes during spec generation
|
||||
3. Tracks the full lifecycle: idea → spec → beads → shipped
|
||||
4. Re-triages instantly when the dependency graph changes
|
||||
5. Runs in seconds, not minutes
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ docs/ideas/*.md │
|
||||
│ docs/issues/*.md │
|
||||
│ (YAML frontmatter) │
|
||||
└──────────────────────────┬──────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ IDEA TRIAGE SKILL │
|
||||
│ │
|
||||
│ Phase 1: INGEST — parse all frontmatter │
|
||||
│ Phase 2: VALIDATE — check refs, detect staleness │
|
||||
│ Phase 3: EVALUATE — detect scope changes since last run │
|
||||
│ Phase 4: SCORE — compute priority with unlock graph │
|
||||
│ Phase 5: SEQUENCE — topological sort by dependency + score │
|
||||
│ Phase 6: RECOMMEND — top 3 + unlock advisories + warnings │
|
||||
└──────────────────────────┬──────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ HUMAN DECIDES │
|
||||
│ (picks from top 3, takes seconds) │
|
||||
└──────────────────────────┬──────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ SPEC GENERATION (Claude/GPT) │
|
||||
│ Takes the idea doc, generates detailed implementation spec │
|
||||
│ ALSO: re-evaluates frontmatter fields based on deeper │
|
||||
│ understanding. Updates effort, blocked-by, components. │
|
||||
│ This is the SCOPE CHANGE DETECTION point. │
|
||||
└──────────────────────────┬──────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ PLAN-TO-BEADS (existing skill) │
|
||||
│ Spec → granular beads with dependencies via br CLI │
|
||||
│ Links bead IDs back into the idea frontmatter │
|
||||
└──────────────────────────┬──────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ AGENT IMPLEMENTATION │
|
||||
│ Works beads via br/bv workflow │
|
||||
│ bv --robot-triage handles execution-phase prioritization │
|
||||
└──────────────────────────┬──────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ COMPLETION & RE-TRIAGE │
|
||||
│ Beads close → idea status updates to implemented │
|
||||
│ Skill re-runs → newly unblocked ideas surface │
|
||||
│ Loop back to top │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## The Two Systems and Their Boundary
|
||||
|
||||
| Concern | Ideas System (new) | Beads System (existing) |
|
||||
|---------|-------------------|------------------------|
|
||||
| Phase | Pre-commitment (what to build) | Execution (how to build) |
|
||||
| Data | docs/ideas/*.md, docs/issues/*.md | .beads/issues.jsonl |
|
||||
| Triage | Idea triage skill | bv --robot-triage |
|
||||
| Tracking | YAML frontmatter | JSONL records |
|
||||
| Granularity | Feature-level | Task-level |
|
||||
| Lifecycle | proposed → specced → promoted | open → in_progress → closed |
|
||||
|
||||
**The handoff point is promotion.** An idea becomes one or more beads. After that,
|
||||
the ideas system only tracks the idea's status (promoted/implemented). Beads owns
|
||||
execution.
|
||||
|
||||
An idea file is NEVER deleted. It's a permanent design record. Even after
|
||||
implementation, it documents WHY the feature was built and what tradeoffs were made.
|
||||
|
||||
---
|
||||
|
||||
## Data Model
|
||||
|
||||
### Frontmatter Schema
|
||||
|
||||
```yaml
|
||||
---
|
||||
# ── Identity ──
|
||||
id: idea-009 # stable unique identifier
|
||||
title: Similar Issues Finder
|
||||
type: idea # idea | issue
|
||||
status: proposed # see lifecycle below
|
||||
|
||||
# ── Timestamps ──
|
||||
created: 2026-02-09
|
||||
updated: 2026-02-09
|
||||
eval-hash: null # SHA of scoring fields at last triage run
|
||||
|
||||
# ── Scoring Inputs ──
|
||||
impact: high # high | medium | low
|
||||
effort: small # small | medium | large | xlarge
|
||||
severity: null # critical | high | medium | low (issues only)
|
||||
autonomy: full # full | needs-design | needs-human
|
||||
|
||||
# ── Dependency Graph ──
|
||||
blocked-by: [] # IDs of ideas/issues that must complete first
|
||||
unlocks: # IDs that become possible/better after this ships
|
||||
- idea-recurring-patterns
|
||||
requires: [] # external prerequisites (gate names)
|
||||
related: # soft links, not blocking
|
||||
- issue-001
|
||||
|
||||
# ── Implementation Context ──
|
||||
components: # source code paths this will touch
|
||||
- src/search/
|
||||
- src/embedding/
|
||||
command: lore similar # proposed CLI command (null for issues)
|
||||
has-spec: false # detailed spec has been generated
|
||||
spec-path: null # path to spec doc if it exists
|
||||
beads: [] # bead IDs after promotion
|
||||
|
||||
# ── Classification ──
|
||||
tags:
|
||||
- embeddings
|
||||
- search
|
||||
---
|
||||
```
|
||||
|
||||
### Status Lifecycle
|
||||
|
||||
```
|
||||
IDEA lifecycle:
|
||||
proposed ──→ accepted ──→ specced ──→ promoted ──→ implemented
|
||||
│ │
|
||||
└──→ rejected └──→ (scope changed, back to accepted)
|
||||
|
||||
ISSUE lifecycle:
|
||||
open ──→ accepted ──→ specced ──→ promoted ──→ resolved
|
||||
│
|
||||
└──→ wontfix
|
||||
```
|
||||
|
||||
Transitions:
|
||||
- `proposed → accepted`: Human confirms this is worth building
|
||||
- `accepted → specced`: Detailed implementation spec has been generated
|
||||
- `specced → promoted`: Beads created from the spec
|
||||
- `promoted → implemented`: All beads closed
|
||||
- Any → `rejected`/`wontfix`: Decided not to build (with reason in body)
|
||||
- `specced → accepted`: Scope changed during spec, needs re-evaluation
|
||||
|
||||
### Effort Calibration (Agent-Executed)
|
||||
|
||||
| Level | Wall Clock | Autonomy | Example |
|
||||
|-------|-----------|----------|---------|
|
||||
| small | ~30 min | Agent ships end-to-end | stale-discussions, closure-gaps |
|
||||
| medium | ~1 hour | Agent ships end-to-end | similar-issues, digest |
|
||||
| large | 1-2 hours | May need one design decision | recurring-patterns, experts |
|
||||
| xlarge | 2+ hours | Needs human architecture input | project groups |
|
||||
|
||||
### Gates Registry (docs/gates.yaml)
|
||||
|
||||
```yaml
|
||||
gates:
|
||||
gate-1:
|
||||
title: Resource Events Ingestion
|
||||
status: complete
|
||||
completed: 2025-12-15
|
||||
|
||||
gate-2:
|
||||
title: Cross-References & Entity Graph
|
||||
status: complete
|
||||
completed: 2026-01-10
|
||||
|
||||
gate-3:
|
||||
title: Timeline Pipeline
|
||||
status: complete
|
||||
completed: 2026-01-25
|
||||
|
||||
gate-4:
|
||||
title: MR File Changes Ingestion
|
||||
status: partial
|
||||
notes: Schema ready (migration 016), ingestion code exists but untested
|
||||
tracks: mr_file_changes table population
|
||||
|
||||
gate-5:
|
||||
title: Code Trace (file:line → commit → MR → issue)
|
||||
status: not-started
|
||||
blocked-by: gate-4
|
||||
notes: Requires git log parsing + commit SHA matching
|
||||
```
|
||||
|
||||
The skill reads this file to determine which `requires` entries are satisfied.
|
||||
|
||||
---
|
||||
|
||||
## Scoring Algorithm
|
||||
|
||||
### Priority Score
|
||||
|
||||
```
|
||||
For ideas:
|
||||
base = impact_weight # high=3, medium=2, low=1
|
||||
unlock = 1 + (0.5 × count_of_unlocks) # items this directly enables
|
||||
readiness = 0 if blocked, 1 if ready
|
||||
priority = base × unlock × readiness
|
||||
|
||||
For issues:
|
||||
base = severity_weight × 1.5 # critical=6, high=4.5, medium=3, low=1.5
|
||||
unlock = 1 + (0.5 × count_of_unlocks) # (bugs rarely unlock, but can)
|
||||
readiness = 0 if blocked, 1 if ready
|
||||
priority = base × unlock × readiness
|
||||
|
||||
Tiebreak (among equal priority):
|
||||
1. Prefer smaller effort (ships faster, starts next cycle sooner)
|
||||
2. Prefer autonomy:full over needs-design over needs-human
|
||||
3. Prefer older items (FIFO within same score)
|
||||
```
|
||||
|
||||
### Why This Works
|
||||
|
||||
- High-impact items that unlock other items float to the top
|
||||
- Blocked items score 0 regardless of impact (can't be worked)
|
||||
- Effort is a tiebreaker, not a primary factor (since execution is fast)
|
||||
- Issues with severity get a 1.5× multiplier (bugs degrade existing value)
|
||||
- Unlock multiplier captures the "do Gate 4 first" insight automatically
|
||||
|
||||
### Example Rankings
|
||||
|
||||
| Item | Impact | Unlocks | Readiness | Score |
|
||||
|------|--------|---------|-----------|-------|
|
||||
| project-ergonomics | high(3) | 10 | ready(1) | 3 × 6.0 = 18.0 |
|
||||
| gate-4-completion | med(2) | 5 | ready(1) | 2 × 3.5 = 7.0 |
|
||||
| similar-issues | high(3) | 1 | ready(1) | 3 × 1.5 = 4.5 |
|
||||
| stale-discussions | high(3) | 0 | ready(1) | 3 × 1.0 = 3.0 |
|
||||
| hotspots | high(3) | 1 | blocked(0) | 0.0 |
|
||||
|
||||
Project-ergonomics dominates because it unlocks 10 downstream items. This is the
|
||||
correct recommendation — it's the highest-leverage work even though "stale-discussions"
|
||||
is simpler.
|
||||
|
||||
---
|
||||
|
||||
## Scope Change Detection
|
||||
|
||||
This is the hardest problem. An idea's scope can change in three ways:
|
||||
|
||||
### 1. During Spec Generation (Primary Detection Point)
|
||||
|
||||
When Claude/GPT generates a detailed implementation spec from an idea doc, it
|
||||
understands the idea more deeply than the original sketch. The spec process should
|
||||
be instructed to:
|
||||
|
||||
- Re-evaluate effort (now that implementation is understood in detail)
|
||||
- Discover new dependencies (need to change schema first, need a new config option)
|
||||
- Identify component changes (touches more modules than originally thought)
|
||||
- Assess impact more accurately (this is actually higher/lower value than estimated)
|
||||
|
||||
**Mechanism:** The spec generation prompt includes an explicit "re-evaluate frontmatter"
|
||||
step. The spec output includes an updated frontmatter block. If scoring-relevant
|
||||
fields changed, the skill flags it:
|
||||
|
||||
```
|
||||
SCOPE CHANGE DETECTED:
|
||||
idea-009 (Similar Issues Finder)
|
||||
- effort: small → medium (needs embedding aggregation strategy)
|
||||
- blocked-by: [] → [gate-embeddings-populated]
|
||||
- components: +src/cli/commands/similar.rs (new file)
|
||||
Previous score: 4.5 → New score: 3.0
|
||||
Recommendation: Still top-3, but sequencing may change.
|
||||
```
|
||||
|
||||
### 2. During Implementation (Discovered Complexity)
|
||||
|
||||
An agent working on beads may discover the spec was wrong:
|
||||
- "This requires a database migration I didn't anticipate"
|
||||
- "This module doesn't expose the API I need"
|
||||
|
||||
**Mechanism:** When a bead is blocked or takes significantly longer than estimated,
|
||||
the agent should update the idea's frontmatter. The skill detects the change on
|
||||
next triage run via eval-hash comparison.
|
||||
|
||||
### 3. External Changes (Gate Completion, New Ideas)
|
||||
|
||||
When a gate completes or a new idea is added that changes the dependency graph:
|
||||
- Gate 4 completes → 5 ideas become unblocked
|
||||
- New idea added that's higher priority than current top-3
|
||||
- Two ideas discovered to be duplicates
|
||||
|
||||
**Mechanism:** The skill detects these automatically by re-computing the full graph
|
||||
on every run. The eval-hash tracks what the scoring fields looked like last time;
|
||||
if they haven't changed but the SCORE changed (because a dependency was resolved),
|
||||
the skill flags it as "newly unblocked."
|
||||
|
||||
### The eval-hash Field
|
||||
|
||||
```yaml
|
||||
eval-hash: "a1b2c3d4" # SHA-256 of: impact + effort + blocked-by + unlocks + requires
|
||||
```
|
||||
|
||||
Computed by hashing the concatenation of all scoring-relevant fields. When the skill
|
||||
runs, it compares:
|
||||
- If eval-hash matches AND score is same → no change, skip
|
||||
- If eval-hash matches BUT score changed → external change (dependency resolved)
|
||||
- If eval-hash differs → item was modified, re-evaluate
|
||||
|
||||
This avoids re-announcing unchanged items on every run.
|
||||
|
||||
---
|
||||
|
||||
## Skill Design
|
||||
|
||||
### Location
|
||||
|
||||
`.claude/skills/idea-triage/SKILL.md` (project-local)
|
||||
|
||||
### Trigger Phrases
|
||||
|
||||
- "triage ideas" / "what should I build next?"
|
||||
- "idea triage" / "prioritize ideas"
|
||||
- "what's the highest value work?"
|
||||
- `/idea-triage`
|
||||
|
||||
### Workflow Phases
|
||||
|
||||
**Phase 1: INGEST**
|
||||
- Glob docs/ideas/*.md and docs/issues/*.md
|
||||
- Parse YAML frontmatter from each file
|
||||
- Read docs/gates.yaml for capability status
|
||||
- Collect: id, title, type, status, impact, effort, severity, autonomy,
|
||||
blocked-by, unlocks, requires, has-spec, beads, eval-hash
|
||||
|
||||
**Phase 2: VALIDATE**
|
||||
- Required fields present (id, title, type, status, impact, effort)
|
||||
- All blocked-by IDs reference existing files
|
||||
- All unlocks IDs reference existing files
|
||||
- All requires entries exist in gates.yaml
|
||||
- No dependency cycles (blocked-by graph is a DAG)
|
||||
- Status transitions are valid (no "proposed" with beads linked)
|
||||
- Output: list of validation errors/warnings
|
||||
|
||||
**Phase 3: EVALUATE (Scope Change Detection)**
|
||||
- For each item, compute current eval-hash from scoring fields
|
||||
- Compare against stored eval-hash in frontmatter
|
||||
- If different: flag as SCOPE_CHANGED with field-level diff
|
||||
- If same but score changed (due to external dep resolution): flag as NEWLY_UNBLOCKED
|
||||
- If status is specced but has-spec is false: flag as INCONSISTENT
|
||||
|
||||
**Phase 4: SCORE**
|
||||
- Resolve requires against gates.yaml (is the gate complete?)
|
||||
- Resolve blocked-by against other items (is the blocker done?)
|
||||
- Compute readiness: 0 if any hard blocker is unresolved, 1 otherwise
|
||||
- Compute unlock count: count items whose blocked-by includes this ID
|
||||
- Apply scoring formula:
|
||||
- Ideas: impact_weight × (1 + 0.5 × unlock_count) × readiness
|
||||
- Issues: severity_weight × 1.5 × (1 + 0.5 × unlock_count) × readiness
|
||||
- Apply tiebreak: effort_weight, autonomy, created date
|
||||
|
||||
**Phase 5: SEQUENCE**
|
||||
- Separate into: actionable (score > 0) vs blocked (score = 0)
|
||||
- Among actionable: sort by score descending with tiebreak
|
||||
- Among blocked: sort by "what-if score" (score if blockers were resolved)
|
||||
- Compute unlock advisories: "completing X unblocks Y items worth Z total score"
|
||||
|
||||
**Phase 6: RECOMMEND**
|
||||
Output structured report:
|
||||
|
||||
```
|
||||
== IDEA TRIAGE ==
|
||||
Run: 2026-02-09T14:30:00Z
|
||||
Items: 22 (18 proposed, 2 accepted, 1 specced, 1 implemented)
|
||||
|
||||
RECOMMENDED SEQUENCE:
|
||||
1. [idea-project-ergonomics] Multi-Project Ergonomics
|
||||
impact:high effort:medium autonomy:full score:18.0
|
||||
WHY FIRST: Unlocks 10 downstream ideas. Highest leverage.
|
||||
COMPONENTS: src/core/config.rs, src/core/project.rs, src/cli/
|
||||
|
||||
2. [idea-009] Similar Issues Finder
|
||||
impact:high effort:small autonomy:full score:4.5
|
||||
WHY NEXT: Highest standalone impact. Ships in ~30 min.
|
||||
UNLOCKS: idea-recurring-patterns
|
||||
|
||||
3. [idea-004] Stale Discussion Finder
|
||||
impact:high effort:small autonomy:full score:3.0
|
||||
WHY NEXT: Quick win, no dependencies, immediate user value.
|
||||
|
||||
BLOCKED (would rank high if unblocked):
|
||||
idea-014 File Hotspots score-if-unblocked:4.5 BLOCKED BY: gate-4
|
||||
idea-021 Knowledge Silos score-if-unblocked:3.0 BLOCKED BY: gate-4
|
||||
UNLOCK ADVISORY: Completing gate-4 unblocks 5 items (combined: 15.0)
|
||||
|
||||
SCOPE CHANGES DETECTED:
|
||||
idea-009: effort changed small→medium (eval-hash mismatch)
|
||||
idea-017: now has spec (has-spec flipped to true)
|
||||
|
||||
NEWLY UNBLOCKED:
|
||||
(none this run)
|
||||
|
||||
WARNINGS:
|
||||
idea-016: status=proposed, unchanged for 30+ days
|
||||
idea-008: blocked-by references "idea-gate4" which doesn't exist (typo?)
|
||||
|
||||
HEALTH:
|
||||
Proposed: 18 | Accepted: 2 | Specced: 1 | Promoted: 0 | Implemented: 1
|
||||
Blocked: 6 | Actionable: 16
|
||||
Backlog runway at ~5/day: ~3 days
|
||||
```
|
||||
|
||||
### What the Skill Does NOT Do
|
||||
|
||||
- **Never modifies files.** Read-only triage. The agent or human updates frontmatter.
|
||||
Exception: the skill CAN update eval-hash after a triage run (opt-in).
|
||||
- **Never creates beads.** That's plan-to-beads skill territory.
|
||||
- **Never replaces bv.** Once work is in beads, bv --robot-triage handles execution
|
||||
prioritization. This skill owns pre-commitment only.
|
||||
- **Never generates specs.** That's a separate step with Claude/GPT.
|
||||
|
||||
---
|
||||
|
||||
## Integration Points
|
||||
|
||||
### With Spec Generation
|
||||
|
||||
The spec generation prompt (separate from this skill) should include:
|
||||
|
||||
```
|
||||
After generating the implementation spec, re-evaluate the idea's frontmatter:
|
||||
1. Is the effort estimate still accurate? (small/medium/large/xlarge)
|
||||
2. Did you discover new dependencies? (add to blocked-by)
|
||||
3. Are there components not listed? (add to components)
|
||||
4. Has the impact assessment changed?
|
||||
5. Can an agent ship this autonomously? (autonomy: full/needs-design/needs-human)
|
||||
|
||||
Output an UPDATED frontmatter block at the end of the spec.
|
||||
If any scoring field changed, explain what changed and why.
|
||||
```
|
||||
|
||||
### With plan-to-beads
|
||||
|
||||
When promoting an idea to beads:
|
||||
1. Run plan-to-beads on the spec
|
||||
2. Capture the created bead IDs
|
||||
3. Update the idea's frontmatter: status → promoted, beads → [bd-xxx, bd-yyy]
|
||||
4. Run br sync --flush-only && git add .beads/
|
||||
|
||||
### With bv --robot-triage
|
||||
|
||||
These systems don't talk to each other directly. The boundary is:
|
||||
- Idea triage skill → "build idea-009 next"
|
||||
- Human/agent generates spec → plan-to-beads → beads created
|
||||
- bv --robot-triage → "work on bd-xxx next"
|
||||
- Beads close → human/agent updates idea frontmatter → idea triage re-runs
|
||||
|
||||
### With New Item Ingestion
|
||||
|
||||
When someone adds a new file to docs/ideas/ or docs/issues/:
|
||||
- If it has valid frontmatter: picked up automatically on next triage run
|
||||
- If it has no/invalid frontmatter: flagged in WARNINGS section
|
||||
- Skill can suggest default frontmatter based on content analysis
|
||||
|
||||
---
|
||||
|
||||
## Failure Modes and Mitigations
|
||||
|
||||
### 1. Frontmatter Rot
|
||||
**Risk:** Fields don't get updated. Status says "proposed" but it's actually shipped.
|
||||
**Mitigation:** Cross-reference with beads. If an idea has beads and all beads are
|
||||
closed, flag that the idea should be "implemented" even if frontmatter says otherwise.
|
||||
The skill detects this inconsistency.
|
||||
|
||||
### 2. Score Gaming
|
||||
**Risk:** Someone inflates impact or unlocks count to make their idea rank higher.
|
||||
**Mitigation:** Unlocks are verified — the skill checks that the referenced items
|
||||
actually have this idea in their blocked-by. Impact is subjective but reviewed during
|
||||
spec generation (second opinion from a different model/session).
|
||||
|
||||
### 3. Stale Gates Registry
|
||||
**Risk:** gate-4 is actually complete but gates.yaml wasn't updated.
|
||||
**Mitigation:** Skill warns when a gate has been "partial" for a long time. Could
|
||||
also probe the codebase (check if mr_file_changes ingestion code exists and has tests).
|
||||
|
||||
### 4. Circular Dependencies
|
||||
**Risk:** A blocks B blocks A.
|
||||
**Mitigation:** Phase 2 validation explicitly checks for cycles in the blocked-by
|
||||
graph and reports them as errors.
|
||||
|
||||
### 5. Unlock Count Inflation
|
||||
**Risk:** An item claims to unlock 20 things, making it score astronomically.
|
||||
**Mitigation:** Unlock count is VERIFIED by checking reverse blocked-by references.
|
||||
If idea-X says it unlocks idea-Y, but idea-Y's blocked-by doesn't include idea-X,
|
||||
the claim is discounted. Both explicit unlocks and reverse blocked-by contribute to
|
||||
the count, but unverified claims are flagged.
|
||||
|
||||
### 6. Scope Creep During Spec
|
||||
**Risk:** Spec generation reveals the idea is actually 5× harder than estimated.
|
||||
The score drops, but the human has already mentally committed.
|
||||
**Mitigation:** The scope change detection makes this VISIBLE. The triage output
|
||||
explicitly shows "effort changed small→xlarge, score dropped from 4.5 to 0.75."
|
||||
Human can then decide: proceed anyway, or switch to a different top-3 pick.
|
||||
|
||||
### 7. Orphaned Ideas
|
||||
**Risk:** Ideas get promoted to beads, beads get implemented, but the idea file
|
||||
never gets updated. It sits in "promoted" forever.
|
||||
**Mitigation:** Skill checks: for each idea with status=promoted, look up the
|
||||
linked beads. If all beads are closed, flag: "idea-009 appears complete, update
|
||||
status to implemented."
|
||||
|
||||
---
|
||||
|
||||
## Implementation Plan
|
||||
|
||||
### Step 1: Create the Frontmatter Schema (this doc → applied to all files)
|
||||
- Define the exact YAML schema (above)
|
||||
- Create docs/gates.yaml
|
||||
- Apply frontmatter to all 22 existing files in docs/ideas/ and docs/issues/
|
||||
|
||||
### Step 2: Build the Skill
|
||||
- Create .claude/skills/idea-triage/SKILL.md
|
||||
- Implement all 6 phases in the skill prompt
|
||||
- The skill uses Glob, Read, and text processing — no external scripts needed
|
||||
(25 files is small enough for Claude to process directly)
|
||||
|
||||
### Step 3: Test the System
|
||||
- Run the skill against current files
|
||||
- Verify scoring matches manual expectations
|
||||
- Check that project-ergonomics ranks #1 (it should, due to unlock count)
|
||||
- Verify blocked items score 0
|
||||
- Check validation catches intentional errors
|
||||
|
||||
### Step 4: Run One Full Cycle
|
||||
- Pick the top recommendation
|
||||
- Generate a spec (separate session)
|
||||
- Verify scope change detection works (spec should update frontmatter)
|
||||
- Promote to beads via plan-to-beads
|
||||
- Implement
|
||||
- Verify completion detection works
|
||||
|
||||
### Step 5: Iterate
|
||||
- Run triage again after implementation
|
||||
- Verify newly unblocked items surface
|
||||
- Adjust scoring weights if rankings feel wrong
|
||||
- Add new ideas as they emerge
|
||||
88
docs/ideas/bottlenecks.md
Normal file
88
docs/ideas/bottlenecks.md
Normal file
@@ -0,0 +1,88 @@
|
||||
# Review Bottleneck Detector
|
||||
|
||||
- **Command:** `lore bottlenecks [--since <date>]`
|
||||
- **Confidence:** 85%
|
||||
- **Tier:** 2
|
||||
- **Status:** proposed
|
||||
- **Effort:** medium — join MRs with first review note, compute percentiles
|
||||
|
||||
## What
|
||||
|
||||
For MRs in a given time window, compute:
|
||||
1. **Time to first review** — created_at to first non-author DiffNote
|
||||
2. **Review cycles** — count of discussion resolution rounds
|
||||
3. **Time to merge** — created_at to merged_at
|
||||
|
||||
Flag MRs above P90 thresholds as bottlenecks.
|
||||
|
||||
## Why
|
||||
|
||||
Review bottlenecks are the #1 developer productivity killer. Making them visible
|
||||
and measurable is the first step to fixing them. This provides data for process
|
||||
retrospectives.
|
||||
|
||||
## Data Required
|
||||
|
||||
All exists today:
|
||||
- `merge_requests` (created_at, merged_at, author_username)
|
||||
- `notes` (note_type='DiffNote', author_username, created_at)
|
||||
- `discussions` (resolved, resolvable)
|
||||
|
||||
## Implementation Sketch
|
||||
|
||||
```sql
|
||||
-- Time to first review per MR
|
||||
SELECT
|
||||
mr.id,
|
||||
mr.iid,
|
||||
mr.title,
|
||||
mr.author_username,
|
||||
mr.created_at,
|
||||
mr.merged_at,
|
||||
p.path_with_namespace,
|
||||
MIN(n.created_at) as first_review_at,
|
||||
(MIN(n.created_at) - mr.created_at) / 3600000.0 as hours_to_first_review,
|
||||
(mr.merged_at - mr.created_at) / 3600000.0 as hours_to_merge
|
||||
FROM merge_requests mr
|
||||
JOIN projects p ON mr.project_id = p.id
|
||||
LEFT JOIN discussions d ON d.merge_request_id = mr.id
|
||||
LEFT JOIN notes n ON n.discussion_id = d.id
|
||||
AND n.note_type = 'DiffNote'
|
||||
AND n.is_system = 0
|
||||
AND n.author_username != mr.author_username
|
||||
WHERE mr.created_at >= ?1
|
||||
AND mr.state IN ('merged', 'opened')
|
||||
GROUP BY mr.id
|
||||
ORDER BY hours_to_first_review DESC NULLS FIRST;
|
||||
```
|
||||
|
||||
## Human Output
|
||||
|
||||
```
|
||||
Review Bottlenecks (last 30 days)
|
||||
|
||||
P50 time to first review: 4.2h
|
||||
P90 time to first review: 28.1h
|
||||
P50 time to merge: 2.1d
|
||||
P90 time to merge: 8.3d
|
||||
|
||||
Slowest to review:
|
||||
!234 Refactor auth 72h to first review (alice, still open)
|
||||
!228 Database migration 48h to first review (bob, merged in 5d)
|
||||
|
||||
Most review cycles:
|
||||
!234 Refactor auth 8 discussion threads, 4 resolved
|
||||
!225 API versioning 6 discussion threads, 6 resolved
|
||||
```
|
||||
|
||||
## Downsides
|
||||
|
||||
- Doesn't capture review done outside GitLab (Slack, in-person)
|
||||
- DiffNote timestamp != when reviewer started reading
|
||||
- Large MRs naturally take longer; no size normalization
|
||||
|
||||
## Extensions
|
||||
|
||||
- `lore bottlenecks --reviewer alice` — how fast does alice review?
|
||||
- Per-project comparison: which project has the fastest review cycle?
|
||||
- Trend line: is review speed improving or degrading over time?
|
||||
77
docs/ideas/churn.md
Normal file
77
docs/ideas/churn.md
Normal file
@@ -0,0 +1,77 @@
|
||||
# MR Churn Analysis
|
||||
|
||||
- **Command:** `lore churn [--since <date>]`
|
||||
- **Confidence:** 72%
|
||||
- **Tier:** 3
|
||||
- **Status:** proposed
|
||||
- **Effort:** medium — multi-table aggregation with composite scoring
|
||||
|
||||
## What
|
||||
|
||||
For merged MRs, compute a "contentiousness score" based on: number of review
|
||||
discussions, number of DiffNotes, resolution cycles, file count. Flag high-churn
|
||||
MRs as candidates for architectural review.
|
||||
|
||||
## Why
|
||||
|
||||
High-churn MRs often indicate architectural disagreements, unclear requirements,
|
||||
or code that's hard to review. Surfacing them post-merge enables retrospectives
|
||||
and identifies areas that need better design upfront.
|
||||
|
||||
## Data Required
|
||||
|
||||
All exists today:
|
||||
- `merge_requests` (state='merged')
|
||||
- `discussions` (merge_request_id, resolved, resolvable)
|
||||
- `notes` (note_type='DiffNote', discussion_id)
|
||||
- `mr_file_changes` (file count per MR)
|
||||
|
||||
## Implementation Sketch
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
mr.iid,
|
||||
mr.title,
|
||||
mr.author_username,
|
||||
p.path_with_namespace,
|
||||
COUNT(DISTINCT d.id) as discussion_count,
|
||||
COUNT(DISTINCT CASE WHEN n.note_type = 'DiffNote' THEN n.id END) as diffnote_count,
|
||||
COUNT(DISTINCT CASE WHEN d.resolvable = 1 AND d.resolved = 1 THEN d.id END) as resolved_threads,
|
||||
COUNT(DISTINCT mfc.id) as files_changed,
|
||||
-- Composite score: normalize each metric and weight
|
||||
(COUNT(DISTINCT d.id) * 2 + COUNT(DISTINCT n.id) + COUNT(DISTINCT mfc.id)) as churn_score
|
||||
FROM merge_requests mr
|
||||
JOIN projects p ON mr.project_id = p.id
|
||||
LEFT JOIN discussions d ON d.merge_request_id = mr.id AND d.noteable_type = 'MergeRequest'
|
||||
LEFT JOIN notes n ON n.discussion_id = d.id AND n.is_system = 0
|
||||
LEFT JOIN mr_file_changes mfc ON mfc.merge_request_id = mr.id
|
||||
WHERE mr.state = 'merged'
|
||||
AND mr.merged_at >= ?1
|
||||
GROUP BY mr.id
|
||||
ORDER BY churn_score DESC
|
||||
LIMIT ?2;
|
||||
```
|
||||
|
||||
## Human Output
|
||||
|
||||
```
|
||||
High-Churn MRs (last 90 days)
|
||||
|
||||
MR Discussions DiffNotes Files Score Title
|
||||
!234 12 28 8 60 Refactor auth middleware
|
||||
!225 8 19 5 39 API versioning v2
|
||||
!218 6 15 12 39 Database schema migration
|
||||
!210 5 8 3 21 Update logging framework
|
||||
```
|
||||
|
||||
## Downsides
|
||||
|
||||
- High discussion count could mean thorough review, not contention
|
||||
- Composite scoring weights are arbitrary; needs calibration per team
|
||||
- Large MRs naturally score higher regardless of contention
|
||||
|
||||
## Extensions
|
||||
|
||||
- Normalize by file count (discussions per file changed)
|
||||
- Compare against team averages (flag outliers, not absolute values)
|
||||
- `lore churn --author alice` — which of alice's MRs generate the most discussion?
|
||||
73
docs/ideas/closure-gaps.md
Normal file
73
docs/ideas/closure-gaps.md
Normal file
@@ -0,0 +1,73 @@
|
||||
# MR-to-Issue Closure Gap
|
||||
|
||||
- **Command:** `lore closure-gaps`
|
||||
- **Confidence:** 88%
|
||||
- **Tier:** 2
|
||||
- **Status:** proposed
|
||||
- **Effort:** low — single join query
|
||||
|
||||
## What
|
||||
|
||||
Find entity_references where reference_type='closes' AND the target issue is still
|
||||
open AND the source MR is merged. These represent broken auto-close links where a
|
||||
merge should have closed an issue but didn't.
|
||||
|
||||
## Why
|
||||
|
||||
Simple, definitive, actionable. If a merged MR says "closes #42" but #42 is still
|
||||
open, something is wrong. Either auto-close failed (wrong target branch), the
|
||||
reference was incorrect, or the issue needs manual attention.
|
||||
|
||||
## Data Required
|
||||
|
||||
All exists today:
|
||||
- `entity_references` (reference_type='closes')
|
||||
- `merge_requests` (state='merged')
|
||||
- `issues` (state='opened')
|
||||
|
||||
## Implementation Sketch
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
mr.iid as mr_iid,
|
||||
mr.title as mr_title,
|
||||
mr.merged_at,
|
||||
mr.target_branch,
|
||||
i.iid as issue_iid,
|
||||
i.title as issue_title,
|
||||
i.state as issue_state,
|
||||
p.path_with_namespace
|
||||
FROM entity_references er
|
||||
JOIN merge_requests mr ON er.source_entity_type = 'merge_request'
|
||||
AND er.source_entity_id = mr.id
|
||||
JOIN issues i ON er.target_entity_type = 'issue'
|
||||
AND er.target_entity_id = i.id
|
||||
JOIN projects p ON er.project_id = p.id
|
||||
WHERE er.reference_type = 'closes'
|
||||
AND mr.state = 'merged'
|
||||
AND i.state = 'opened';
|
||||
```
|
||||
|
||||
## Human Output
|
||||
|
||||
```
|
||||
Closure Gaps — merged MRs that didn't close their referenced issues
|
||||
|
||||
group/backend !234 merged 3d ago → #42 still OPEN
|
||||
"Refactor auth middleware" should have closed "Login timeout bug"
|
||||
Target branch: develop (default: main) — possible branch mismatch
|
||||
|
||||
group/frontend !45 merged 1w ago → #38 still OPEN
|
||||
"Update dashboard" should have closed "Dashboard layout broken"
|
||||
```
|
||||
|
||||
## Downsides
|
||||
|
||||
- Could be intentional (MR merged to wrong branch, issue tracked across branches)
|
||||
- Cross-project references may not be resolvable if target project not synced
|
||||
- GitLab auto-close only works when merging to default branch
|
||||
|
||||
## Extensions
|
||||
|
||||
- Flag likely cause: branch mismatch (target_branch != project.default_branch)
|
||||
- `lore closure-gaps --auto-close` — actually close the issues via API (dangerous, needs confirmation)
|
||||
101
docs/ideas/collaboration.md
Normal file
101
docs/ideas/collaboration.md
Normal file
@@ -0,0 +1,101 @@
|
||||
# Author Collaboration Network
|
||||
|
||||
- **Command:** `lore collaboration [--since <date>]`
|
||||
- **Confidence:** 70%
|
||||
- **Tier:** 3
|
||||
- **Status:** proposed
|
||||
- **Effort:** medium — self-join on notes, graph construction
|
||||
|
||||
## What
|
||||
|
||||
Build a weighted graph of author pairs: (author_A, author_B, weight) where weight =
|
||||
number of times A reviewed B's MR + B reviewed A's MR + they both commented on the
|
||||
same entity.
|
||||
|
||||
## Why
|
||||
|
||||
Reveals team structure empirically. Shows who collaborates across team boundaries
|
||||
and where knowledge transfer happens. Useful for re-orgs, onboarding planning,
|
||||
and identifying isolated team members.
|
||||
|
||||
## Data Required
|
||||
|
||||
All exists today:
|
||||
- `merge_requests` (author_username)
|
||||
- `notes` (author_username, note_type='DiffNote')
|
||||
- `discussions` (for co-participation)
|
||||
|
||||
## Implementation Sketch
|
||||
|
||||
```sql
|
||||
-- Review relationships: who reviews whose MRs
|
||||
SELECT
|
||||
mr.author_username as author,
|
||||
n.author_username as reviewer,
|
||||
COUNT(*) as review_count
|
||||
FROM merge_requests mr
|
||||
JOIN discussions d ON d.merge_request_id = mr.id
|
||||
JOIN notes n ON n.discussion_id = d.id
|
||||
WHERE n.note_type = 'DiffNote'
|
||||
AND n.is_system = 0
|
||||
AND n.author_username != mr.author_username
|
||||
AND mr.created_at >= ?1
|
||||
GROUP BY mr.author_username, n.author_username;
|
||||
|
||||
-- Co-participation: who comments on the same entities
|
||||
WITH entity_participants AS (
|
||||
SELECT
|
||||
COALESCE(d.issue_id, d.merge_request_id) as entity_id,
|
||||
d.noteable_type,
|
||||
n.author_username
|
||||
FROM discussions d
|
||||
JOIN notes n ON n.discussion_id = d.id
|
||||
WHERE n.is_system = 0
|
||||
AND n.created_at >= ?1
|
||||
)
|
||||
SELECT
|
||||
a.author_username as person_a,
|
||||
b.author_username as person_b,
|
||||
COUNT(DISTINCT a.entity_id) as shared_entities
|
||||
FROM entity_participants a
|
||||
JOIN entity_participants b
|
||||
ON a.entity_id = b.entity_id
|
||||
AND a.noteable_type = b.noteable_type
|
||||
AND a.author_username < b.author_username -- avoid duplicates
|
||||
GROUP BY a.author_username, b.author_username;
|
||||
```
|
||||
|
||||
## Output Formats
|
||||
|
||||
### JSON (for further analysis)
|
||||
```json
|
||||
{
|
||||
"nodes": ["alice", "bob", "charlie"],
|
||||
"edges": [
|
||||
{ "source": "alice", "target": "bob", "reviews": 15, "co_participated": 8 },
|
||||
{ "source": "bob", "target": "charlie", "reviews": 3, "co_participated": 12 }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Human
|
||||
```
|
||||
Collaboration Network (last 90 days)
|
||||
|
||||
alice <-> bob 15 reviews, 8 shared discussions [strong]
|
||||
bob <-> charlie 3 reviews, 12 shared discussions [moderate]
|
||||
alice <-> charlie 1 review, 2 shared discussions [weak]
|
||||
dave <-> (none) 0 reviews, 0 shared discussions [isolated]
|
||||
```
|
||||
|
||||
## Downsides
|
||||
|
||||
- Interpretation requires context; high collaboration might mean dependency
|
||||
- Doesn't capture collaboration outside GitLab
|
||||
- Self-join can be slow with many notes
|
||||
|
||||
## Extensions
|
||||
|
||||
- `lore collaboration --format dot` — GraphViz network diagram
|
||||
- `lore collaboration --isolated` — find team members with no collaboration edges
|
||||
- Team boundary detection via graph clustering algorithms
|
||||
86
docs/ideas/contributors.md
Normal file
86
docs/ideas/contributors.md
Normal file
@@ -0,0 +1,86 @@
|
||||
# Contributor Heatmap
|
||||
|
||||
- **Command:** `lore contributors [--since <date>]`
|
||||
- **Confidence:** 88%
|
||||
- **Tier:** 2
|
||||
- **Status:** proposed
|
||||
- **Effort:** medium — multiple aggregation queries
|
||||
|
||||
## What
|
||||
|
||||
Rank team members by activity across configurable time windows (7d, 30d, 90d). Shows
|
||||
issues authored, MRs authored, MRs merged, review comments made, discussions
|
||||
participated in.
|
||||
|
||||
## Why
|
||||
|
||||
Team leads constantly ask "who's been active?" or "who's contributing to reviews?"
|
||||
This answers it from local data without GitLab Premium analytics. Also useful for
|
||||
identifying team members who may be overloaded or disengaged.
|
||||
|
||||
## Data Required
|
||||
|
||||
All exists today:
|
||||
- `issues` (author_username, created_at)
|
||||
- `merge_requests` (author_username, created_at, merged_at)
|
||||
- `notes` (author_username, created_at, note_type, is_system)
|
||||
- `discussions` (for participation counting)
|
||||
|
||||
## Implementation Sketch
|
||||
|
||||
```sql
|
||||
-- Combined activity per author
|
||||
WITH activity AS (
|
||||
SELECT author_username, 'issue_authored' as activity_type, created_at
|
||||
FROM issues WHERE created_at >= ?1
|
||||
UNION ALL
|
||||
SELECT author_username, 'mr_authored', created_at
|
||||
FROM merge_requests WHERE created_at >= ?1
|
||||
UNION ALL
|
||||
SELECT author_username, 'mr_merged', merged_at
|
||||
FROM merge_requests WHERE merged_at >= ?1 AND state = 'merged'
|
||||
UNION ALL
|
||||
SELECT author_username, 'review_comment', created_at
|
||||
FROM notes WHERE created_at >= ?1 AND note_type = 'DiffNote' AND is_system = 0
|
||||
UNION ALL
|
||||
SELECT author_username, 'discussion_comment', created_at
|
||||
FROM notes WHERE created_at >= ?1 AND note_type != 'DiffNote' AND is_system = 0
|
||||
)
|
||||
SELECT
|
||||
author_username,
|
||||
COUNT(*) FILTER (WHERE activity_type = 'issue_authored') as issues,
|
||||
COUNT(*) FILTER (WHERE activity_type = 'mr_authored') as mrs_authored,
|
||||
COUNT(*) FILTER (WHERE activity_type = 'mr_merged') as mrs_merged,
|
||||
COUNT(*) FILTER (WHERE activity_type = 'review_comment') as reviews,
|
||||
COUNT(*) FILTER (WHERE activity_type = 'discussion_comment') as comments,
|
||||
COUNT(*) as total
|
||||
FROM activity
|
||||
GROUP BY author_username
|
||||
ORDER BY total DESC;
|
||||
```
|
||||
|
||||
Note: SQLite doesn't support FILTER — use SUM(CASE WHEN ... THEN 1 ELSE 0 END).
|
||||
|
||||
## Human Output
|
||||
|
||||
```
|
||||
Contributors (last 30 days)
|
||||
|
||||
Username Issues MRs Merged Reviews Comments Total
|
||||
alice 3 8 7 23 12 53
|
||||
bob 1 5 4 31 8 49
|
||||
charlie 5 3 2 4 15 29
|
||||
dave 0 1 0 2 3 6
|
||||
```
|
||||
|
||||
## Downsides
|
||||
|
||||
- Could be used for surveillance; frame as team health, not individual tracking
|
||||
- Activity volume != productivity (one thoughtful review > ten "LGTM"s)
|
||||
- Doesn't capture work done outside GitLab
|
||||
|
||||
## Extensions
|
||||
|
||||
- `lore contributors --project group/backend` — scoped to project
|
||||
- `lore contributors --type reviews` — focus on review activity only
|
||||
- Trend comparison: `--compare 30d,90d` shows velocity changes
|
||||
94
docs/ideas/decisions.md
Normal file
94
docs/ideas/decisions.md
Normal file
@@ -0,0 +1,94 @@
|
||||
# Decision Archaeology
|
||||
|
||||
- **Command:** `lore decisions <query>`
|
||||
- **Confidence:** 82%
|
||||
- **Tier:** 2
|
||||
- **Status:** proposed
|
||||
- **Effort:** medium — search pipeline + regex pattern matching on notes
|
||||
|
||||
## What
|
||||
|
||||
Search for discussion notes that contain decision-making language. Use the existing
|
||||
search pipeline but boost notes containing patterns like "decided", "agreed",
|
||||
"will go with", "tradeoff", "because we", "rationale", "the approach is", "we chose".
|
||||
Return the surrounding discussion context.
|
||||
|
||||
## Why
|
||||
|
||||
This is gitlore's unique value proposition — "why was this decision made?" is the
|
||||
question that no other tool answers well. Architecture Decision Records are rarely
|
||||
maintained; the real decisions live in discussion threads. This mines them.
|
||||
|
||||
## Data Required
|
||||
|
||||
All exists today:
|
||||
- `documents` + search pipeline (for finding relevant entities)
|
||||
- `notes` (body text for pattern matching)
|
||||
- `discussions` (for thread context)
|
||||
|
||||
## Implementation Sketch
|
||||
|
||||
```
|
||||
1. Run existing hybrid search to find entities matching the query topic
|
||||
2. For each result entity, query all discussion notes
|
||||
3. Score each note against decision-language patterns:
|
||||
- Strong signals (weight 3): "decided to", "agreed on", "the decision is",
|
||||
"we will go with", "approved approach"
|
||||
- Medium signals (weight 2): "tradeoff", "because", "rationale", "chosen",
|
||||
"opted for", "rejected", "alternative"
|
||||
- Weak signals (weight 1): "should we", "proposal", "option A", "option B",
|
||||
"pros and cons"
|
||||
4. Return notes scoring above threshold, with surrounding context (previous and
|
||||
next note in discussion thread)
|
||||
5. Sort by: search relevance * decision score
|
||||
```
|
||||
|
||||
### Decision Patterns (regex)
|
||||
|
||||
```rust
|
||||
const STRONG_PATTERNS: &[&str] = &[
|
||||
r"(?i)\b(decided|agreed|approved)\s+(to|on|that)\b",
|
||||
r"(?i)\bthe\s+(decision|approach|plan)\s+is\b",
|
||||
r"(?i)\bwe('ll| will| are going to)\s+(go with|use|implement)\b",
|
||||
r"(?i)\blet'?s\s+(go with|use|do)\b",
|
||||
];
|
||||
|
||||
const MEDIUM_PATTERNS: &[&str] = &[
|
||||
r"(?i)\b(tradeoff|trade-off|rationale|because we|opted for)\b",
|
||||
r"(?i)\b(rejected|ruled out|won't work|not viable)\b",
|
||||
r"(?i)\b(chosen|selected|picked)\b.{0,20}\b(over|instead of)\b",
|
||||
];
|
||||
```
|
||||
|
||||
## Human Output
|
||||
|
||||
```
|
||||
Decisions related to "authentication"
|
||||
|
||||
group/backend !234 — "Refactor auth middleware"
|
||||
Discussion #a1b2c3 (alice, 3w ago):
|
||||
"We decided to use JWT with short-lived tokens instead of session cookies.
|
||||
The tradeoff is more complexity in the refresh flow, but we get stateless
|
||||
auth which scales better."
|
||||
Decision confidence: HIGH (3 strong pattern matches)
|
||||
|
||||
group/backend #42 — "Auth architecture review"
|
||||
Discussion #d4e5f6 (bob, 2mo ago):
|
||||
"After discussing with the security team, we'll go with bcrypt for password
|
||||
hashing. Argon2 is theoretically better but bcrypt has wider library support."
|
||||
Decision confidence: HIGH (2 strong pattern matches)
|
||||
```
|
||||
|
||||
## Downsides
|
||||
|
||||
- Pattern matching is imperfect; may miss decisions phrased differently
|
||||
- May surface "discussion about deciding" rather than actual decisions
|
||||
- Non-English discussions won't match
|
||||
- Requires good search results as input (garbage in, garbage out)
|
||||
|
||||
## Extensions
|
||||
|
||||
- `lore decisions --recent` — decisions made in last 30 days
|
||||
- `lore decisions --author alice` — decisions made by specific person
|
||||
- Export as ADR (Architecture Decision Record) format
|
||||
- Combine with timeline for chronological decision history
|
||||
131
docs/ideas/digest.md
Normal file
131
docs/ideas/digest.md
Normal file
@@ -0,0 +1,131 @@
|
||||
# "What Changed?" Digest
|
||||
|
||||
- **Command:** `lore digest --since <date>`
|
||||
- **Confidence:** 93%
|
||||
- **Tier:** 1
|
||||
- **Status:** proposed
|
||||
- **Effort:** medium — multiple queries across event tables, formatting logic
|
||||
|
||||
## What
|
||||
|
||||
Generate a structured summary of all activity since a given date: issues
|
||||
opened/closed, MRs merged, labels changed, milestones updated, key discussions.
|
||||
Group by project and sort by significance (state changes > merges > label changes >
|
||||
new comments).
|
||||
|
||||
Default `--since` is 1 day (last 24 hours). Supports `7d`, `2w`, `YYYY-MM-DD`.
|
||||
|
||||
## Why
|
||||
|
||||
"What happened while I was on PTO?" is the most universal developer question. This
|
||||
is a killer feature that leverages ALL the event data gitlore has ingested. No other
|
||||
local tool provides this.
|
||||
|
||||
## Data Required
|
||||
|
||||
All exists today:
|
||||
- `resource_state_events` (opened/closed/merged/reopened)
|
||||
- `resource_label_events` (label add/remove)
|
||||
- `resource_milestone_events` (milestone add/remove)
|
||||
- `merge_requests` (merged_at for merge events)
|
||||
- `issues` (created_at for new issues)
|
||||
- `discussions` (last_note_at for active discussions)
|
||||
|
||||
## Implementation Sketch
|
||||
|
||||
```
|
||||
1. Parse --since into ms epoch timestamp
|
||||
2. Query each event table WHERE created_at >= since
|
||||
3. Query new issues WHERE created_at >= since
|
||||
4. Query merged MRs WHERE merged_at >= since
|
||||
5. Query active discussions WHERE last_note_at >= since
|
||||
6. Group all events by project
|
||||
7. Within each project, sort by: state changes first, then merges, then labels
|
||||
8. Format as human-readable sections or robot JSON
|
||||
```
|
||||
|
||||
### SQL Queries
|
||||
|
||||
```sql
|
||||
-- State changes in window
|
||||
SELECT rse.*, i.iid as issue_iid, mr.iid as mr_iid,
|
||||
COALESCE(i.title, mr.title) as title,
|
||||
p.path_with_namespace
|
||||
FROM resource_state_events rse
|
||||
LEFT JOIN issues i ON rse.issue_id = i.id
|
||||
LEFT JOIN merge_requests mr ON rse.merge_request_id = mr.id
|
||||
JOIN projects p ON rse.project_id = p.id
|
||||
WHERE rse.created_at >= ?1
|
||||
ORDER BY rse.created_at DESC;
|
||||
|
||||
-- Newly merged MRs
|
||||
SELECT mr.iid, mr.title, mr.author_username, mr.merged_at,
|
||||
p.path_with_namespace
|
||||
FROM merge_requests mr
|
||||
JOIN projects p ON mr.project_id = p.id
|
||||
WHERE mr.merged_at >= ?1
|
||||
ORDER BY mr.merged_at DESC;
|
||||
|
||||
-- New issues
|
||||
SELECT i.iid, i.title, i.author_username, i.created_at,
|
||||
p.path_with_namespace
|
||||
FROM issues i
|
||||
JOIN projects p ON i.project_id = p.id
|
||||
WHERE i.created_at >= ?1
|
||||
ORDER BY i.created_at DESC;
|
||||
```
|
||||
|
||||
## Human Output Format
|
||||
|
||||
```
|
||||
=== What Changed (last 7 days) ===
|
||||
|
||||
group/backend (12 events)
|
||||
Merged:
|
||||
!234 Refactor auth middleware (alice, 2d ago)
|
||||
!231 Fix connection pool leak (bob, 5d ago)
|
||||
Closed:
|
||||
#89 Login timeout on slow networks (closed by alice, 3d ago)
|
||||
Opened:
|
||||
#95 Rate limiting returns 500 (charlie, 1d ago)
|
||||
Labels:
|
||||
#90 +priority::high (dave, 4d ago)
|
||||
|
||||
group/frontend (3 events)
|
||||
Merged:
|
||||
!45 Update dashboard layout (eve, 6d ago)
|
||||
```
|
||||
|
||||
## Robot Mode Output
|
||||
|
||||
```json
|
||||
{
|
||||
"ok": true,
|
||||
"data": {
|
||||
"since": "2025-01-20T00:00:00Z",
|
||||
"projects": [
|
||||
{
|
||||
"path": "group/backend",
|
||||
"merged": [ { "iid": 234, "title": "...", "author": "alice" } ],
|
||||
"closed": [ { "iid": 89, "title": "...", "actor": "alice" } ],
|
||||
"opened": [ { "iid": 95, "title": "...", "author": "charlie" } ],
|
||||
"label_changes": [ { "iid": 90, "label": "priority::high", "action": "add" } ]
|
||||
}
|
||||
],
|
||||
"summary": { "total_events": 15, "projects_active": 2 }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Downsides
|
||||
|
||||
- Can be overwhelming for very active repos; needs `--limit` per category
|
||||
- Doesn't capture nuance (a 200-comment MR merge is more significant than a typo fix)
|
||||
- Only shows what gitlore has synced; stale data = stale digest
|
||||
|
||||
## Extensions
|
||||
|
||||
- `lore digest --author alice` — personal activity digest
|
||||
- `lore digest --project group/backend` — single project scope
|
||||
- `lore digest --format markdown` — paste-ready for Slack/email
|
||||
- Combine with weekly-digest for scheduled summaries
|
||||
120
docs/ideas/experts.md
Normal file
120
docs/ideas/experts.md
Normal file
@@ -0,0 +1,120 @@
|
||||
# Who Knows About X?
|
||||
|
||||
- **Command:** `lore experts <path-or-topic>`
|
||||
- **Confidence:** 92%
|
||||
- **Tier:** 1
|
||||
- **Status:** proposed
|
||||
- **Effort:** medium — two query paths (file-based, topic-based)
|
||||
|
||||
## What
|
||||
|
||||
Given a file path, find people who have authored MRs touching that file, left
|
||||
DiffNotes on that file, or discussed issues referencing that file. Given a topic
|
||||
string, use search to find relevant entities then extract the active participants.
|
||||
|
||||
## Why
|
||||
|
||||
"Who should I ask about the auth module?" is one of the most common questions in
|
||||
large teams. This answers it empirically from actual contribution and review data.
|
||||
No guessing, no out-of-date wiki pages.
|
||||
|
||||
## Data Required
|
||||
|
||||
All exists today:
|
||||
- `mr_file_changes` (new_path, merge_request_id) — who changed the file
|
||||
- `notes` (position_new_path, author_username) — who reviewed the file
|
||||
- `merge_requests` (author_username) — MR authorship
|
||||
- `documents` + search pipeline — for topic-based queries
|
||||
- `discussions` + `notes` — for participant extraction
|
||||
|
||||
## Implementation Sketch
|
||||
|
||||
### Path Mode: `lore experts src/auth/`
|
||||
|
||||
```
|
||||
1. Query mr_file_changes WHERE new_path LIKE 'src/auth/%'
|
||||
2. Join merge_requests to get author_username for each MR
|
||||
3. Query notes WHERE position_new_path LIKE 'src/auth/%'
|
||||
4. Collect all usernames with activity counts
|
||||
5. Rank by: MR authorship (weight 3) + DiffNote authorship (weight 2) + discussion participation (weight 1)
|
||||
6. Apply recency decay (recent activity weighted higher)
|
||||
```
|
||||
|
||||
### Topic Mode: `lore experts "authentication timeout"`
|
||||
|
||||
```
|
||||
1. Run existing hybrid search for the topic
|
||||
2. Collect top N document results
|
||||
3. For each document, extract author_username
|
||||
4. For each document's entity, query discussions and collect note authors
|
||||
5. Rank by frequency and recency
|
||||
```
|
||||
|
||||
### SQL (Path Mode)
|
||||
|
||||
```sql
|
||||
-- Authors who changed files matching pattern
|
||||
SELECT mr.author_username, COUNT(*) as changes, MAX(mr.merged_at) as last_active
|
||||
FROM mr_file_changes mfc
|
||||
JOIN merge_requests mr ON mfc.merge_request_id = mr.id
|
||||
WHERE mfc.new_path LIKE ?1
|
||||
AND mr.state = 'merged'
|
||||
GROUP BY mr.author_username
|
||||
ORDER BY changes DESC;
|
||||
|
||||
-- Reviewers who commented on files matching pattern
|
||||
SELECT n.author_username, COUNT(*) as reviews, MAX(n.created_at) as last_active
|
||||
FROM notes n
|
||||
WHERE n.position_new_path LIKE ?1
|
||||
AND n.note_type = 'DiffNote'
|
||||
AND n.is_system = 0
|
||||
GROUP BY n.author_username
|
||||
ORDER BY reviews DESC;
|
||||
```
|
||||
|
||||
## Human Output Format
|
||||
|
||||
```
|
||||
Experts for: src/auth/
|
||||
|
||||
alice 12 changes, 8 reviews (last active 3d ago) [top contributor]
|
||||
bob 3 changes, 15 reviews (last active 1d ago) [top reviewer]
|
||||
charlie 5 changes, 2 reviews (last active 2w ago)
|
||||
dave 1 change, 0 reviews (last active 3mo ago) [stale]
|
||||
```
|
||||
|
||||
## Robot Mode Output
|
||||
|
||||
```json
|
||||
{
|
||||
"ok": true,
|
||||
"data": {
|
||||
"query": "src/auth/",
|
||||
"query_type": "path",
|
||||
"experts": [
|
||||
{
|
||||
"username": "alice",
|
||||
"changes": 12,
|
||||
"reviews": 8,
|
||||
"discussions": 3,
|
||||
"score": 62,
|
||||
"last_active": "2025-01-25T10:00:00Z",
|
||||
"role": "top_contributor"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Downsides
|
||||
|
||||
- Historical data may be stale (people leave teams, change roles)
|
||||
- Path mode requires `mr_file_changes` to be populated (Gate 4 ingestion)
|
||||
- Topic mode quality depends on search quality
|
||||
- Doesn't account for org chart / actual ownership
|
||||
|
||||
## Extensions
|
||||
|
||||
- `lore experts --since 90d` — recency filter
|
||||
- `lore experts --min-activity 3` — noise filter
|
||||
- Combine with `lore silos` to highlight when an expert is the ONLY expert
|
||||
75
docs/ideas/graph.md
Normal file
75
docs/ideas/graph.md
Normal file
@@ -0,0 +1,75 @@
|
||||
# Entity Relationship Explorer
|
||||
|
||||
- **Command:** `lore graph <entity-type> <iid>`
|
||||
- **Confidence:** 80%
|
||||
- **Tier:** 3
|
||||
- **Status:** proposed
|
||||
- **Effort:** medium — BFS traversal (similar to timeline expand), output formatting
|
||||
|
||||
## What
|
||||
|
||||
Given an issue or MR, traverse `entity_references` and display all connected
|
||||
entities with relationship types and depths. Output as tree, JSON, or Mermaid diagram.
|
||||
|
||||
## Why
|
||||
|
||||
The entity_references graph is already built (Gate 2) but has no dedicated
|
||||
exploration command. Timeline shows events over time; this shows the relationship
|
||||
structure. "What's connected to this issue?" is a different question from "what
|
||||
happened to this issue?"
|
||||
|
||||
## Data Required
|
||||
|
||||
All exists today:
|
||||
- `entity_references` (source/target entity, reference_type)
|
||||
- `issues` / `merge_requests` (for entity context)
|
||||
- Timeline expand stage already implements BFS over this graph
|
||||
|
||||
## Implementation Sketch
|
||||
|
||||
```
|
||||
1. Resolve entity type + iid to local ID
|
||||
2. BFS over entity_references:
|
||||
- Follow source→target AND target→source (bidirectional)
|
||||
- Track depth (--depth flag, default 2)
|
||||
- Track reference_type for edge labels
|
||||
3. Hydrate each discovered entity with title, state, URL
|
||||
4. Format as tree / JSON / Mermaid
|
||||
```
|
||||
|
||||
## Human Output (Tree)
|
||||
|
||||
```
|
||||
#42 Login timeout bug (CLOSED)
|
||||
├── closes ── !234 Refactor auth middleware (MERGED)
|
||||
│ ├── mentioned ── #38 Connection timeout in auth flow (CLOSED)
|
||||
│ └── mentioned ── #51 Token refresh improvements (OPEN)
|
||||
├── related ── #45 Auth module documentation (OPEN)
|
||||
└── mentioned ── !228 Database migration (MERGED)
|
||||
└── closes ── #35 Schema version drift (CLOSED)
|
||||
```
|
||||
|
||||
## Mermaid Output
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
I42["#42 Login timeout"] -->|closes| MR234["!234 Refactor auth"]
|
||||
MR234 -->|mentioned| I38["#38 Connection timeout"]
|
||||
MR234 -->|mentioned| I51["#51 Token refresh"]
|
||||
I42 -->|related| I45["#45 Auth docs"]
|
||||
I42 -->|mentioned| MR228["!228 DB migration"]
|
||||
MR228 -->|closes| I35["#35 Schema drift"]
|
||||
```
|
||||
|
||||
## Downsides
|
||||
|
||||
- Overlaps somewhat with timeline (but different focus: structure vs chronology)
|
||||
- High fan-out for popular entities (need depth + limit controls)
|
||||
- Unresolved cross-project references appear as dead ends
|
||||
|
||||
## Extensions
|
||||
|
||||
- `lore graph --format dot` — GraphViz DOT output
|
||||
- `lore graph --format mermaid` — Mermaid diagram
|
||||
- `lore graph --include-discussions` — show discussion threads as nodes
|
||||
- Interactive HTML visualization (future web UI)
|
||||
70
docs/ideas/hotspots.md
Normal file
70
docs/ideas/hotspots.md
Normal file
@@ -0,0 +1,70 @@
|
||||
# File Hotspot Report
|
||||
|
||||
- **Command:** `lore hotspots [--since <date>]`
|
||||
- **Confidence:** 85%
|
||||
- **Tier:** 2
|
||||
- **Status:** proposed
|
||||
- **Effort:** low — single query on mr_file_changes (requires Gate 4 population)
|
||||
|
||||
## What
|
||||
|
||||
Rank files by frequency of appearance in merged MRs over a time window. Show
|
||||
change_type breakdown (modified vs added vs deleted). Optionally filter by project.
|
||||
|
||||
## Why
|
||||
|
||||
Hot files are where bugs live. This is a proven engineering metric (see "Your Code
|
||||
as a Crime Scene" by Adam Tornhill). High-churn files deserve extra test coverage,
|
||||
better documentation, and architectural review.
|
||||
|
||||
## Data Required
|
||||
|
||||
- `mr_file_changes` (new_path, change_type, merge_request_id) — needs Gate 4 population
|
||||
- `merge_requests` (merged_at, state='merged')
|
||||
|
||||
## Implementation Sketch
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
mfc.new_path,
|
||||
p.path_with_namespace,
|
||||
COUNT(*) as total_changes,
|
||||
SUM(CASE WHEN mfc.change_type = 'modified' THEN 1 ELSE 0 END) as modifications,
|
||||
SUM(CASE WHEN mfc.change_type = 'added' THEN 1 ELSE 0 END) as additions,
|
||||
SUM(CASE WHEN mfc.change_type = 'deleted' THEN 1 ELSE 0 END) as deletions,
|
||||
SUM(CASE WHEN mfc.change_type = 'renamed' THEN 1 ELSE 0 END) as renames,
|
||||
COUNT(DISTINCT mr.author_username) as unique_authors
|
||||
FROM mr_file_changes mfc
|
||||
JOIN merge_requests mr ON mfc.merge_request_id = mr.id
|
||||
JOIN projects p ON mfc.project_id = p.id
|
||||
WHERE mr.state = 'merged'
|
||||
AND mr.merged_at >= ?1
|
||||
GROUP BY mfc.new_path, p.path_with_namespace
|
||||
ORDER BY total_changes DESC
|
||||
LIMIT ?2;
|
||||
```
|
||||
|
||||
## Human Output
|
||||
|
||||
```
|
||||
File Hotspots (last 90 days, top 20)
|
||||
|
||||
File Changes Authors Type Breakdown
|
||||
src/auth/middleware.rs 18 4 14 mod, 3 add, 1 del
|
||||
src/api/routes.rs 15 3 12 mod, 2 add, 1 rename
|
||||
src/db/migrations.rs 12 2 8 mod, 4 add
|
||||
tests/integration/auth_test.rs 11 3 9 mod, 2 add
|
||||
```
|
||||
|
||||
## Downsides
|
||||
|
||||
- Requires `mr_file_changes` to be populated (Gate 4 ingestion)
|
||||
- Doesn't distinguish meaningful changes from trivial ones (formatting, imports)
|
||||
- Configuration files (CI, Cargo.toml) will rank high but aren't risky
|
||||
|
||||
## Extensions
|
||||
|
||||
- `lore hotspots --exclude "*.toml,*.yml"` — filter out config files
|
||||
- `lore hotspots --dir src/auth/` — scope to directory
|
||||
- Combine with `lore silos` for risk scoring: high churn + bus factor 1 = critical
|
||||
- Complexity trend: correlate with discussion count (churn + many discussions = problematic)
|
||||
69
docs/ideas/idle.md
Normal file
69
docs/ideas/idle.md
Normal file
@@ -0,0 +1,69 @@
|
||||
# Idle Work Detector
|
||||
|
||||
- **Command:** `lore idle [--days <N>] [--labels <pattern>]`
|
||||
- **Confidence:** 73%
|
||||
- **Tier:** 3
|
||||
- **Status:** proposed
|
||||
- **Effort:** medium — label event querying with configurable patterns
|
||||
|
||||
## What
|
||||
|
||||
Find entities that received an "in progress" or similar label but have had no
|
||||
discussion activity for N days. Cross-reference with assignee to show who might
|
||||
have forgotten about something.
|
||||
|
||||
## Why
|
||||
|
||||
Forgotten WIP is invisible waste. Developers start work, get pulled to something
|
||||
urgent, and the original task sits idle. This makes it visible before it becomes
|
||||
a problem.
|
||||
|
||||
## Data Required
|
||||
|
||||
All exists today:
|
||||
- `resource_label_events` (label_name, action='add', created_at)
|
||||
- `discussions` (last_note_at for entity activity)
|
||||
- `issues` / `merge_requests` (state, assignees)
|
||||
- `issue_assignees` / `mr_assignees`
|
||||
|
||||
## Implementation Sketch
|
||||
|
||||
```
|
||||
1. Query resource_label_events for labels matching "in progress" patterns
|
||||
Default patterns: "in-progress", "in_progress", "doing", "wip",
|
||||
"workflow::in-progress", "status::in-progress"
|
||||
Configurable via --labels flag
|
||||
2. For each entity with an "in progress" label still applied:
|
||||
a. Check if the label was subsequently removed (if so, skip)
|
||||
b. Get last_note_at from discussions for that entity
|
||||
c. Flag if last_note_at is older than threshold
|
||||
3. Join with assignees for attribution
|
||||
```
|
||||
|
||||
## Human Output
|
||||
|
||||
```
|
||||
Idle Work (labeled "in progress" but no activity for 14+ days)
|
||||
|
||||
group/backend
|
||||
#90 Rate limiting design assigned to: charlie idle 18 days
|
||||
Last activity: label +priority::high by dave
|
||||
#85 Cache invalidation fix assigned to: alice idle 21 days
|
||||
Last activity: discussion comment by bob
|
||||
|
||||
group/frontend
|
||||
!230 Dashboard redesign assigned to: eve idle 14 days
|
||||
Last activity: DiffNote by dave
|
||||
```
|
||||
|
||||
## Downsides
|
||||
|
||||
- Requires label naming conventions; no universal standard
|
||||
- Work may be happening outside GitLab (local branch, design doc)
|
||||
- "Idle" threshold is subjective; 14 days may be normal for large features
|
||||
|
||||
## Extensions
|
||||
|
||||
- `lore idle --assignee alice` — personal idle work check
|
||||
- `lore idle --notify` — generate message templates for nudging owners
|
||||
- Configurable label patterns in config.json for team-specific workflows
|
||||
92
docs/ideas/impact-graph.md
Normal file
92
docs/ideas/impact-graph.md
Normal file
@@ -0,0 +1,92 @@
|
||||
# Cross-Project Impact Graph
|
||||
|
||||
- **Command:** `lore impact-graph [--format json|dot|mermaid]`
|
||||
- **Confidence:** 75%
|
||||
- **Tier:** 3
|
||||
- **Status:** proposed
|
||||
- **Effort:** medium — aggregation over entity_references, graph output formatting
|
||||
|
||||
## What
|
||||
|
||||
Aggregate `entity_references` by project pair to produce a weighted adjacency matrix
|
||||
showing how projects reference each other. Output as JSON, DOT, or Mermaid for
|
||||
visualization.
|
||||
|
||||
## Why
|
||||
|
||||
Makes invisible architectural coupling visible. "Backend and frontend repos have
|
||||
47 cross-references this quarter" tells you about tight coupling that may need
|
||||
architectural attention.
|
||||
|
||||
## Data Required
|
||||
|
||||
All exists today:
|
||||
- `entity_references` (source/target entity IDs)
|
||||
- `issues` / `merge_requests` (project_id for source/target)
|
||||
- `projects` (path_with_namespace)
|
||||
|
||||
## Implementation Sketch
|
||||
|
||||
```sql
|
||||
-- Project-to-project reference counts
|
||||
WITH ref_projects AS (
|
||||
SELECT
|
||||
CASE er.source_entity_type
|
||||
WHEN 'issue' THEN i_src.project_id
|
||||
WHEN 'merge_request' THEN mr_src.project_id
|
||||
END as source_project_id,
|
||||
CASE er.target_entity_type
|
||||
WHEN 'issue' THEN i_tgt.project_id
|
||||
WHEN 'merge_request' THEN mr_tgt.project_id
|
||||
END as target_project_id,
|
||||
er.reference_type
|
||||
FROM entity_references er
|
||||
LEFT JOIN issues i_src ON er.source_entity_type = 'issue' AND er.source_entity_id = i_src.id
|
||||
LEFT JOIN merge_requests mr_src ON er.source_entity_type = 'merge_request' AND er.source_entity_id = mr_src.id
|
||||
LEFT JOIN issues i_tgt ON er.target_entity_type = 'issue' AND er.target_entity_id = i_tgt.id
|
||||
LEFT JOIN merge_requests mr_tgt ON er.target_entity_type = 'merge_request' AND er.target_entity_id = mr_tgt.id
|
||||
WHERE er.target_entity_id IS NOT NULL -- resolved references only
|
||||
)
|
||||
SELECT
|
||||
p_src.path_with_namespace as source_project,
|
||||
p_tgt.path_with_namespace as target_project,
|
||||
er.reference_type,
|
||||
COUNT(*) as weight
|
||||
FROM ref_projects rp
|
||||
JOIN projects p_src ON rp.source_project_id = p_src.id
|
||||
JOIN projects p_tgt ON rp.target_project_id = p_tgt.id
|
||||
WHERE rp.source_project_id != rp.target_project_id -- cross-project only
|
||||
GROUP BY p_src.path_with_namespace, p_tgt.path_with_namespace, er.reference_type
|
||||
ORDER BY weight DESC;
|
||||
```
|
||||
|
||||
## Output Formats
|
||||
|
||||
### Mermaid
|
||||
```mermaid
|
||||
graph LR
|
||||
Backend -->|closes 23| Frontend
|
||||
Backend -->|mentioned 47| Infrastructure
|
||||
Frontend -->|mentioned 12| Backend
|
||||
```
|
||||
|
||||
### DOT
|
||||
```dot
|
||||
digraph impact {
|
||||
"group/backend" -> "group/frontend" [label="closes: 23"];
|
||||
"group/backend" -> "group/infra" [label="mentioned: 47"];
|
||||
}
|
||||
```
|
||||
|
||||
## Downsides
|
||||
|
||||
- Requires multiple projects synced; limited value for single-project users
|
||||
- "Mentioned" references are noisy (high volume, low signal)
|
||||
- Doesn't capture coupling through shared libraries or APIs (code-level coupling)
|
||||
|
||||
## Extensions
|
||||
|
||||
- `lore impact-graph --since 90d` — time-scoped coupling analysis
|
||||
- `lore impact-graph --type closes` — only meaningful reference types
|
||||
- Include unresolved references to show dependencies on un-synced projects
|
||||
- Coupling trend: is cross-project coupling increasing over time?
|
||||
97
docs/ideas/label-audit.md
Normal file
97
docs/ideas/label-audit.md
Normal file
@@ -0,0 +1,97 @@
|
||||
# Label Hygiene Audit
|
||||
|
||||
- **Command:** `lore label-audit`
|
||||
- **Confidence:** 82%
|
||||
- **Tier:** 2
|
||||
- **Status:** proposed
|
||||
- **Effort:** low — straightforward aggregation queries
|
||||
|
||||
## What
|
||||
|
||||
Report on label health:
|
||||
- Labels used only once (may be typos or abandoned experiments)
|
||||
- Labels applied and removed within 1 hour (likely mistakes)
|
||||
- Labels with no active issues/MRs (orphaned)
|
||||
- Label name collisions across projects (same name, different meaning)
|
||||
- Labels never used at all (defined but not applied)
|
||||
|
||||
## Why
|
||||
|
||||
Label sprawl is real and makes filtering useless over time. Teams create labels
|
||||
ad-hoc and never clean them up. This simple audit surfaces maintenance tasks.
|
||||
|
||||
## Data Required
|
||||
|
||||
All exists today:
|
||||
- `labels` (name, project_id)
|
||||
- `issue_labels` / `mr_labels` (usage counts)
|
||||
- `resource_label_events` (add/remove pairs for mistake detection)
|
||||
- `issues` / `merge_requests` (state for "active" filtering)
|
||||
|
||||
## Implementation Sketch
|
||||
|
||||
```sql
|
||||
-- Labels used only once
|
||||
SELECT l.name, p.path_with_namespace, COUNT(*) as usage
|
||||
FROM labels l
|
||||
JOIN projects p ON l.project_id = p.id
|
||||
LEFT JOIN issue_labels il ON il.label_id = l.id
|
||||
LEFT JOIN mr_labels ml ON ml.label_id = l.id
|
||||
GROUP BY l.id
|
||||
HAVING COUNT(il.issue_id) + COUNT(ml.merge_request_id) = 1;
|
||||
|
||||
-- Flash labels (applied and removed within 1 hour)
|
||||
SELECT
|
||||
rle1.label_name,
|
||||
rle1.created_at as added_at,
|
||||
rle2.created_at as removed_at,
|
||||
(rle2.created_at - rle1.created_at) / 60000 as minutes_active
|
||||
FROM resource_label_events rle1
|
||||
JOIN resource_label_events rle2
|
||||
ON rle1.issue_id = rle2.issue_id
|
||||
AND rle1.label_name = rle2.label_name
|
||||
AND rle1.action = 'add'
|
||||
AND rle2.action = 'remove'
|
||||
AND rle2.created_at > rle1.created_at
|
||||
AND (rle2.created_at - rle1.created_at) < 3600000;
|
||||
|
||||
-- Unused labels (defined but never applied)
|
||||
SELECT l.name, p.path_with_namespace
|
||||
FROM labels l
|
||||
JOIN projects p ON l.project_id = p.id
|
||||
LEFT JOIN issue_labels il ON il.label_id = l.id
|
||||
LEFT JOIN mr_labels ml ON ml.label_id = l.id
|
||||
WHERE il.issue_id IS NULL AND ml.merge_request_id IS NULL;
|
||||
```
|
||||
|
||||
## Human Output
|
||||
|
||||
```
|
||||
Label Audit
|
||||
|
||||
Unused Labels (4):
|
||||
group/backend: deprecated-v1, needs-triage, wontfix-maybe
|
||||
group/frontend: old-design
|
||||
|
||||
Single-Use Labels (3):
|
||||
group/backend: perf-regression (1 issue)
|
||||
group/frontend: ux-debt (1 MR), mobile-only (1 issue)
|
||||
|
||||
Flash Labels (applied < 1hr, 2):
|
||||
group/backend #90: +priority::critical then -priority::critical (12 min)
|
||||
group/backend #85: +blocked then -blocked (5 min)
|
||||
|
||||
Cross-Project Collisions (1):
|
||||
"needs-review" used in group/backend (32 uses) AND group/frontend (8 uses)
|
||||
```
|
||||
|
||||
## Downsides
|
||||
|
||||
- Low glamour; this is janitorial work
|
||||
- Single-use labels may be legitimate (one-off categorization)
|
||||
- Cross-project collisions may be intentional (shared vocabulary)
|
||||
|
||||
## Extensions
|
||||
|
||||
- `lore label-audit --fix` — suggest deletions for unused labels
|
||||
- Trend: label count over time (is sprawl increasing?)
|
||||
74
docs/ideas/label-flow.md
Normal file
74
docs/ideas/label-flow.md
Normal file
@@ -0,0 +1,74 @@
|
||||
# Label Velocity
|
||||
|
||||
- **Command:** `lore label-flow <from-label> <to-label>`
|
||||
- **Confidence:** 78%
|
||||
- **Tier:** 3
|
||||
- **Status:** proposed
|
||||
- **Effort:** medium — self-join on resource_label_events, percentile computation
|
||||
|
||||
## What
|
||||
|
||||
For a given label pair (e.g., "needs-review" to "approved"), compute median and P90
|
||||
transition times using `resource_label_events`. Shows how fast work moves through
|
||||
your process labels.
|
||||
|
||||
Also supports: single label dwell time (how long does "in-progress" stay applied?).
|
||||
|
||||
## Why
|
||||
|
||||
Process bottlenecks become quantifiable. "Our code review takes a median of 3 days"
|
||||
is actionable data for retrospectives and process improvement.
|
||||
|
||||
## Data Required
|
||||
|
||||
All exists today:
|
||||
- `resource_label_events` (label_name, action, created_at, issue_id, merge_request_id)
|
||||
|
||||
## Implementation Sketch
|
||||
|
||||
```sql
|
||||
-- Label A → Label B transition time
|
||||
WITH add_a AS (
|
||||
SELECT issue_id, merge_request_id, MIN(created_at) as added_at
|
||||
FROM resource_label_events
|
||||
WHERE label_name = ?1 AND action = 'add'
|
||||
GROUP BY issue_id, merge_request_id
|
||||
),
|
||||
add_b AS (
|
||||
SELECT issue_id, merge_request_id, MIN(created_at) as added_at
|
||||
FROM resource_label_events
|
||||
WHERE label_name = ?2 AND action = 'add'
|
||||
GROUP BY issue_id, merge_request_id
|
||||
)
|
||||
SELECT
|
||||
(b.added_at - a.added_at) / 3600000.0 as hours_transition
|
||||
FROM add_a a
|
||||
JOIN add_b b ON a.issue_id = b.issue_id OR a.merge_request_id = b.merge_request_id
|
||||
WHERE b.added_at > a.added_at;
|
||||
```
|
||||
|
||||
Then compute percentiles in Rust (median, P75, P90).
|
||||
|
||||
## Human Output
|
||||
|
||||
```
|
||||
Label Flow: "needs-review" → "approved"
|
||||
|
||||
Transitions: 42 issues/MRs in last 90 days
|
||||
Median: 18.5 hours
|
||||
P75: 36.2 hours
|
||||
P90: 72.8 hours
|
||||
Slowest: !234 Refactor auth (168 hours)
|
||||
```
|
||||
|
||||
## Downsides
|
||||
|
||||
- Only works if teams use label-based workflows consistently
|
||||
- Labels may be applied out of order or skipped
|
||||
- Self-join performance could be slow with many events
|
||||
|
||||
## Extensions
|
||||
|
||||
- `lore label-flow --dwell "in-progress"` — how long does a label stay?
|
||||
- `lore label-flow --all` — auto-discover common transitions from event data
|
||||
- Visualization: label state machine with median transition times on edges
|
||||
81
docs/ideas/milestone-risk.md
Normal file
81
docs/ideas/milestone-risk.md
Normal file
@@ -0,0 +1,81 @@
|
||||
# Milestone Risk Report
|
||||
|
||||
- **Command:** `lore milestone-risk [title]`
|
||||
- **Confidence:** 78%
|
||||
- **Tier:** 3
|
||||
- **Status:** proposed
|
||||
- **Effort:** medium — milestone + issue aggregation with scope change detection
|
||||
|
||||
## What
|
||||
|
||||
For each active milestone (or a specific one): show total issues, % closed, issues
|
||||
added after milestone creation (scope creep), issues with no assignee, issues with
|
||||
overdue due_date. Flag milestones where completion rate is below expected trajectory.
|
||||
|
||||
## Why
|
||||
|
||||
Milestone health is usually assessed by gut feel. This provides objective signals
|
||||
from data already ingested. Project managers can spot risks early.
|
||||
|
||||
## Data Required
|
||||
|
||||
All exists today:
|
||||
- `milestones` (title, state, due_date)
|
||||
- `issues` (milestone_id, state, created_at, due_date, assignee)
|
||||
- `issue_assignees` (for unassigned detection)
|
||||
|
||||
## Implementation Sketch
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
m.title,
|
||||
m.state,
|
||||
m.due_date,
|
||||
COUNT(*) as total_issues,
|
||||
SUM(CASE WHEN i.state = 'closed' THEN 1 ELSE 0 END) as closed,
|
||||
SUM(CASE WHEN i.state = 'opened' THEN 1 ELSE 0 END) as open,
|
||||
SUM(CASE WHEN i.created_at > m.created_at THEN 1 ELSE 0 END) as scope_creep,
|
||||
SUM(CASE WHEN ia.username IS NULL AND i.state = 'opened' THEN 1 ELSE 0 END) as unassigned,
|
||||
SUM(CASE WHEN i.due_date < DATE('now') AND i.state = 'opened' THEN 1 ELSE 0 END) as overdue
|
||||
FROM milestones m
|
||||
JOIN issues i ON i.milestone_id = m.id
|
||||
LEFT JOIN issue_assignees ia ON ia.issue_id = i.id
|
||||
WHERE m.state = 'active'
|
||||
GROUP BY m.id;
|
||||
```
|
||||
|
||||
Note: `created_at` comparison for scope creep is approximate — GitLab doesn't
|
||||
expose when an issue was added to a milestone via its milestone_events.
|
||||
|
||||
Actually we DO have `resource_milestone_events` — use those for precise scope change
|
||||
detection.
|
||||
|
||||
## Human Output
|
||||
|
||||
```
|
||||
Milestone Risk Report
|
||||
|
||||
v2.0 (due Feb 15, 2025)
|
||||
Progress: 14/20 closed (70%)
|
||||
Scope: +3 issues added after milestone start
|
||||
Risks: 2 issues overdue, 1 issue unassigned
|
||||
Status: ON TRACK (70% complete, 60% time elapsed)
|
||||
|
||||
v2.1 (due Mar 30, 2025)
|
||||
Progress: 2/15 closed (13%)
|
||||
Scope: +8 issues added after milestone start
|
||||
Risks: 5 issues unassigned
|
||||
Status: AT RISK (13% complete, scope still growing)
|
||||
```
|
||||
|
||||
## Downsides
|
||||
|
||||
- Milestone semantics vary wildly between teams
|
||||
- "Scope creep" detection is noisy if teams batch-add issues to milestones
|
||||
- due_date comparison assumes consistent timezone handling
|
||||
|
||||
## Extensions
|
||||
|
||||
- `lore milestone-risk --history` — show scope changes over time
|
||||
- Velocity estimation: at current closure rate, will the milestone finish on time?
|
||||
- Combine with label-flow for "how fast are milestone issues moving through workflow"
|
||||
67
docs/ideas/mr-pipeline.md
Normal file
67
docs/ideas/mr-pipeline.md
Normal file
@@ -0,0 +1,67 @@
|
||||
# MR Pipeline Efficiency
|
||||
|
||||
- **Command:** `lore mr-pipeline [--since <date>]`
|
||||
- **Confidence:** 78%
|
||||
- **Tier:** 3
|
||||
- **Status:** proposed
|
||||
- **Effort:** medium — builds on bottleneck detector with more stages
|
||||
|
||||
## What
|
||||
|
||||
Track the full MR lifecycle: creation, first review, all reviews complete (threads
|
||||
resolved), approval, merge. Compute time spent in each stage across all MRs.
|
||||
Identify which stage is the bottleneck.
|
||||
|
||||
## Why
|
||||
|
||||
"Our merge process is slow" is vague. This breaks it into stages so teams can target
|
||||
the actual bottleneck. Maybe creation-to-review is fast but review-to-merge is slow
|
||||
(merge queue issues). Maybe first review is fast but resolution takes forever
|
||||
(contentious code).
|
||||
|
||||
## Data Required
|
||||
|
||||
All exists today:
|
||||
- `merge_requests` (created_at, merged_at)
|
||||
- `notes` (note_type='DiffNote', created_at, author_username)
|
||||
- `discussions` (resolved, resolvable, merge_request_id)
|
||||
- `resource_state_events` (state changes with timestamps)
|
||||
|
||||
## Implementation Sketch
|
||||
|
||||
For each merged MR, compute:
|
||||
1. **Created → First Review**: MIN(DiffNote.created_at) - mr.created_at
|
||||
2. **First Review → All Resolved**: MAX(discussion.resolved_at) - MIN(DiffNote.created_at)
|
||||
3. **All Resolved → Merged**: mr.merged_at - MAX(discussion.resolved_at)
|
||||
|
||||
Note: "resolved_at" isn't directly stored but can be approximated from the last
|
||||
note in resolved discussions, or from state events.
|
||||
|
||||
## Human Output
|
||||
|
||||
```
|
||||
MR Pipeline (last 30 days, 24 merged MRs)
|
||||
|
||||
Stage Median P75 P90
|
||||
Created → First Review 4.2h 12.1h 28.3h
|
||||
First Review → Resolved 8.1h 24.5h 72.0h <-- BOTTLENECK
|
||||
Resolved → Merged 0.5h 1.2h 3.1h
|
||||
|
||||
Total (Created → Merged) 18.4h 48.2h 96.1h
|
||||
|
||||
Biggest bottleneck: Review resolution (median 8.1h)
|
||||
Suggestion: Consider breaking large MRs into smaller reviewable chunks
|
||||
```
|
||||
|
||||
## Downsides
|
||||
|
||||
- "Resolved" timestamp approximation may be inaccurate
|
||||
- Pipeline assumes linear flow; real MRs have back-and-forth cycles
|
||||
- Draft MRs skew metrics (created early, reviewed late intentionally)
|
||||
|
||||
## Extensions
|
||||
|
||||
- `lore mr-pipeline --exclude-drafts` — cleaner metrics
|
||||
- Per-project comparison: which project has the fastest pipeline?
|
||||
- Trend line: weekly pipeline speed over time
|
||||
- Break down by MR size (files changed) to normalize
|
||||
265
docs/ideas/project-ergonomics.md
Normal file
265
docs/ideas/project-ergonomics.md
Normal file
@@ -0,0 +1,265 @@
|
||||
# Multi-Project Ergonomics
|
||||
|
||||
- **Confidence:** 90%
|
||||
- **Tier:** 1
|
||||
- **Status:** proposed
|
||||
- **Effort:** medium (multiple small improvements that compound)
|
||||
|
||||
## The Problem
|
||||
|
||||
Every command that touches project-scoped data requires `-p group/subgroup/project`
|
||||
to disambiguate. For users with 5+ projects synced, this is:
|
||||
|
||||
- Repetitive: typing `-p infra/platform/auth-service` on every query
|
||||
- Error-prone: mistyping long paths
|
||||
- Discoverable only by failure: you don't know you need `-p` until you hit an
|
||||
ambiguous error
|
||||
|
||||
The fuzzy matching in `resolve_project` is already good (suffix, substring,
|
||||
case-insensitive) but it only kicks in on the `-p` value itself. There's no way to
|
||||
set a default, group projects, or scope a whole session.
|
||||
|
||||
## Proposed Improvements
|
||||
|
||||
### 1. Project Aliases in Config
|
||||
|
||||
Let users define short aliases for long project paths.
|
||||
|
||||
```json
|
||||
{
|
||||
"projects": [
|
||||
{ "path": "infra/platform/auth-service", "alias": "auth" },
|
||||
{ "path": "infra/platform/billing-service", "alias": "billing" },
|
||||
{ "path": "frontend/customer-portal", "alias": "portal" },
|
||||
{ "path": "frontend/admin-dashboard", "alias": "admin" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Then: `lore issues -p auth` resolves via alias before falling through to fuzzy match.
|
||||
|
||||
**Implementation:** Add optional `alias` field to `ProjectConfig`. In
|
||||
`resolve_project`, check aliases before the existing exact/suffix/substring cascade.
|
||||
|
||||
```rust
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct ProjectConfig {
|
||||
pub path: String,
|
||||
#[serde(default)]
|
||||
pub alias: Option<String>,
|
||||
}
|
||||
```
|
||||
|
||||
Resolution order becomes:
|
||||
1. Exact alias match (new)
|
||||
2. Exact path match
|
||||
3. Case-insensitive path match
|
||||
4. Suffix match
|
||||
5. Substring match
|
||||
|
||||
### 2. Default Project (`LORE_PROJECT` env var)
|
||||
|
||||
Set a default project for your shell session so you don't need `-p` at all.
|
||||
|
||||
```bash
|
||||
export LORE_PROJECT=auth
|
||||
lore issues # scoped to auth-service
|
||||
lore mrs --state opened # scoped to auth-service
|
||||
lore search "timeout bug" # scoped to auth-service
|
||||
lore issues -p billing # explicit -p overrides the env var
|
||||
```
|
||||
|
||||
**Implementation:** In every command that accepts `-p`, fall back to
|
||||
`std::env::var("LORE_PROJECT")` when the flag is absent. The `-p` flag always wins.
|
||||
|
||||
Could also support a config-level default:
|
||||
|
||||
```json
|
||||
{
|
||||
"defaultProject": "auth"
|
||||
}
|
||||
```
|
||||
|
||||
Precedence: CLI flag > env var > config default > (no filter).
|
||||
|
||||
### 3. `lore use <project>` — Session Context Switcher
|
||||
|
||||
A command that sets `LORE_PROJECT` for the current shell by writing to a dotfile.
|
||||
|
||||
```bash
|
||||
lore use auth
|
||||
# writes ~/.local/state/lore/current-project containing "auth"
|
||||
|
||||
lore issues # reads current-project file, scopes to auth
|
||||
lore use --clear # removes the file, back to all-project mode
|
||||
lore use # shows current project context
|
||||
```
|
||||
|
||||
This is similar to `kubectl config use-context`, `nvm use`, or `tfenv use`.
|
||||
|
||||
**Implementation:** Write a one-line file at a known state path. Each command reads
|
||||
it as the lowest-priority default (below env var and CLI flag).
|
||||
|
||||
Precedence: CLI flag > env var > `lore use` state file > config default > (no filter).
|
||||
|
||||
### 4. `lore projects` — Project Listing and Discovery
|
||||
|
||||
A dedicated command to see what's synced, with aliases and activity stats.
|
||||
|
||||
```bash
|
||||
$ lore projects
|
||||
|
||||
Alias Path Issues MRs Last Sync
|
||||
auth infra/platform/auth-service 142 87 2h ago
|
||||
billing infra/platform/billing-service 56 34 2h ago
|
||||
portal frontend/customer-portal 203 112 2h ago
|
||||
admin frontend/admin-dashboard 28 15 3d ago
|
||||
- data/ml-pipeline 89 45 2h ago
|
||||
```
|
||||
|
||||
Robot mode returns the same as JSON with alias, path, counts, and last sync time.
|
||||
|
||||
**Implementation:** Query `projects` joined with `COUNT(issues)`, `COUNT(mrs)`,
|
||||
and `MAX(sync_runs.finished_at)`. Overlay aliases from config.
|
||||
|
||||
### 5. Project Groups in Config
|
||||
|
||||
Let users define named groups of projects for batch scoping.
|
||||
|
||||
```json
|
||||
{
|
||||
"projectGroups": {
|
||||
"backend": ["auth", "billing", "data/ml-pipeline"],
|
||||
"frontend": ["portal", "admin"],
|
||||
"all-infra": ["auth", "billing"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Then: `lore issues -p @backend` (or `--group backend`) queries across all projects
|
||||
in the group.
|
||||
|
||||
**Implementation:** When `-p` value starts with `@`, look up the group and resolve
|
||||
each member project. Pass as a `Vec<i64>` of project IDs to the query layer.
|
||||
|
||||
This is especially powerful for:
|
||||
- `lore search "auth bug" -p @backend` — search across related repos
|
||||
- `lore digest --since 7d -p @frontend` — team-scoped activity digest
|
||||
- `lore timeline "deployment" -p @all-infra` — cross-repo timeline
|
||||
|
||||
### 6. Git-Aware Project Detection
|
||||
|
||||
When running `lore` from inside a git repo that matches a synced project, auto-scope
|
||||
to that project without any flags.
|
||||
|
||||
```bash
|
||||
cd ~/code/auth-service
|
||||
lore issues # auto-detects this is infra/platform/auth-service
|
||||
```
|
||||
|
||||
**Implementation:** Read `.git/config` for the remote URL, extract the project path,
|
||||
check if it matches a synced project. Only activate when exactly one project matches.
|
||||
|
||||
Detection logic:
|
||||
```
|
||||
1. Check if cwd is inside a git repo (find .git)
|
||||
2. Parse git remote origin URL
|
||||
3. Extract path component (e.g., "infra/platform/auth-service.git" → "infra/platform/auth-service")
|
||||
4. Match against synced projects
|
||||
5. If exactly one match, use as implicit -p
|
||||
6. If ambiguous or no match, do nothing (fall through to normal behavior)
|
||||
```
|
||||
|
||||
Precedence: CLI flag > env var > `lore use` > config default > git detection > (no filter).
|
||||
|
||||
This is similar to how `gh` (GitHub CLI) auto-detects the repo you're in.
|
||||
|
||||
### 7. Prompt Integration / Shell Function
|
||||
|
||||
Provide a shell function that shows the current project context in the prompt.
|
||||
|
||||
```bash
|
||||
# In .bashrc / .zshrc
|
||||
eval "$(lore completions zsh)"
|
||||
PROMPT='$(lore-prompt)%~ %# '
|
||||
```
|
||||
|
||||
Output: `[lore:auth] ~/code/auth-service %`
|
||||
|
||||
Shows which project `lore` commands will scope to, using the same precedence chain.
|
||||
Helps users understand what context they're in before running a query.
|
||||
|
||||
### 8. Short Project References in Output
|
||||
|
||||
Once aliases exist, use them everywhere in output for brevity:
|
||||
|
||||
**Before:**
|
||||
```
|
||||
infra/platform/auth-service#42 Login timeout bug
|
||||
infra/platform/auth-service!234 Refactor auth middleware
|
||||
```
|
||||
|
||||
**After:**
|
||||
```
|
||||
auth#42 Login timeout bug
|
||||
auth!234 Refactor auth middleware
|
||||
```
|
||||
|
||||
With `--full-paths` flag to get the verbose form when needed.
|
||||
|
||||
## Combined UX Flow
|
||||
|
||||
With all improvements, a typical session looks like:
|
||||
|
||||
```bash
|
||||
# One-time config
|
||||
lore init # sets up aliases during interactive setup
|
||||
|
||||
# Daily use
|
||||
lore use auth # set context
|
||||
lore issues --state opened # no -p needed
|
||||
lore search "timeout" # scoped to auth
|
||||
lore timeline "login flow" # scoped to auth
|
||||
lore issues -p @backend # cross-repo query via group
|
||||
lore mrs -p billing # quick alias switch
|
||||
lore use --clear # back to global
|
||||
```
|
||||
|
||||
Or for the power user who never wants to type `lore use`:
|
||||
|
||||
```bash
|
||||
cd ~/code/auth-service
|
||||
lore issues # git-aware auto-detection
|
||||
```
|
||||
|
||||
Or for the scripter:
|
||||
|
||||
```bash
|
||||
LORE_PROJECT=auth lore --robot issues -n 50 # env var for automation
|
||||
```
|
||||
|
||||
## Priority Order
|
||||
|
||||
Implement in this order for maximum incremental value:
|
||||
|
||||
1. **Project aliases** — smallest change, biggest daily friction reduction
|
||||
2. **`LORE_PROJECT` env var** — trivial to implement, enables scripting
|
||||
3. **`lore projects` command** — discoverability, completes the alias story
|
||||
4. **`lore use` context** — nice-to-have for heavy users
|
||||
5. **Project groups** — high value for multi-repo teams
|
||||
6. **Git-aware detection** — polish, "it just works" feel
|
||||
7. **Short refs in output** — ties into timeline issue #001
|
||||
8. **Prompt integration** — extra polish
|
||||
|
||||
## Relationship to Issue #001
|
||||
|
||||
The timeline entity-ref ambiguity (issue #001) is solved naturally by items 7 and 8
|
||||
here. Once aliases exist, `format_entity_ref` can use the alias as the short project
|
||||
identifier in multi-project output:
|
||||
|
||||
```
|
||||
auth#42 instead of infra/platform/auth-service#42
|
||||
```
|
||||
|
||||
And in single-project timelines (detected via `lore use` or git-aware), the project
|
||||
prefix is omitted entirely — matching the current behavior but now intentionally.
|
||||
81
docs/ideas/recurring-patterns.md
Normal file
81
docs/ideas/recurring-patterns.md
Normal file
@@ -0,0 +1,81 @@
|
||||
# Recurring Bug Pattern Detector
|
||||
|
||||
- **Command:** `lore recurring-patterns [--min-cluster <N>]`
|
||||
- **Confidence:** 76%
|
||||
- **Tier:** 3
|
||||
- **Status:** proposed
|
||||
- **Effort:** high — vector clustering, threshold tuning
|
||||
|
||||
## What
|
||||
|
||||
Cluster closed issues by embedding similarity. Identify clusters of 3+ issues that
|
||||
are semantically similar — these represent recurring problems that need a systemic
|
||||
fix rather than one-off patches.
|
||||
|
||||
## Why
|
||||
|
||||
Finding the same bug filed 5 different ways is one of the most impactful things you
|
||||
can surface. This is a sophisticated use of the embedding pipeline that no competing
|
||||
tool offers. It turns "we keep having auth issues" from a gut feeling into data.
|
||||
|
||||
## Data Required
|
||||
|
||||
All exists today:
|
||||
- `documents` (source_type='issue', content_text)
|
||||
- `embeddings` (768-dim vectors)
|
||||
- `issues` (state='closed' for filtering)
|
||||
|
||||
## Implementation Sketch
|
||||
|
||||
```
|
||||
1. Collect all embeddings for closed issue documents
|
||||
2. For each issue, find K nearest neighbors (K=10)
|
||||
3. Build adjacency graph: edge exists if similarity > threshold (e.g., 0.80)
|
||||
4. Find connected components (simple DFS/BFS)
|
||||
5. Filter to components with >= min-cluster members (default 3)
|
||||
6. For each cluster:
|
||||
a. Extract common terms (TF-IDF or simple word frequency)
|
||||
b. Sort by recency (most recent issue first)
|
||||
c. Report cluster with: theme, member issues, time span
|
||||
```
|
||||
|
||||
### Similarity Threshold Tuning
|
||||
|
||||
This is the critical parameter. Too low = noise, too high = misses.
|
||||
- Start at 0.80 cosine similarity
|
||||
- Expose as `--threshold` flag for user tuning
|
||||
- Report cluster cohesion score for transparency
|
||||
|
||||
## Human Output
|
||||
|
||||
```
|
||||
Recurring Patterns (3+ similar closed issues)
|
||||
|
||||
Cluster 1: "Authentication timeout errors" (5 issues, spanning 6 months)
|
||||
#89 Login timeout on slow networks (closed 3d ago)
|
||||
#72 Auth flow hangs on cellular (closed 2mo ago)
|
||||
#58 Token refresh timeout (closed 3mo ago)
|
||||
#45 SSO login timeout for remote users (closed 5mo ago)
|
||||
#31 Connection timeout in auth middleware (closed 6mo ago)
|
||||
Avg similarity: 0.87 | Suggested: systemic fix for auth timeout handling
|
||||
|
||||
Cluster 2: "Cache invalidation issues" (3 issues, spanning 2 months)
|
||||
#85 Stale cache after deploy (closed 2w ago)
|
||||
#77 Cache headers not updated (closed 1mo ago)
|
||||
#69 Dashboard shows old data after settings change (closed 2mo ago)
|
||||
Avg similarity: 0.82 | Suggested: review cache invalidation strategy
|
||||
```
|
||||
|
||||
## Downsides
|
||||
|
||||
- Clustering quality depends on embedding quality and threshold tuning
|
||||
- May produce false clusters (issues that mention similar terms but are different problems)
|
||||
- Computationally expensive for large issue counts (N^2 comparisons)
|
||||
- Need to handle multi-chunk documents (aggregate embeddings)
|
||||
|
||||
## Extensions
|
||||
|
||||
- `lore recurring-patterns --open` — find clusters in open issues (duplicates to merge)
|
||||
- `lore recurring-patterns --cross-project` — patterns across repos
|
||||
- Trend detection: are cluster sizes growing? (escalating problem)
|
||||
- Export as report for engineering retrospectives
|
||||
78
docs/ideas/review-coverage.md
Normal file
78
docs/ideas/review-coverage.md
Normal file
@@ -0,0 +1,78 @@
|
||||
# DiffNote Coverage Map
|
||||
|
||||
- **Command:** `lore review-coverage <mr-iid>`
|
||||
- **Confidence:** 75%
|
||||
- **Tier:** 3
|
||||
- **Status:** proposed
|
||||
- **Effort:** medium — join DiffNote positions with mr_file_changes
|
||||
|
||||
## What
|
||||
|
||||
For a specific MR, show which files received review comments (DiffNotes) vs. which
|
||||
files were changed but received no review attention. Highlights blind spots in code
|
||||
review.
|
||||
|
||||
## Why
|
||||
|
||||
Large MRs often have files that get reviewed thoroughly and files that slip through
|
||||
with no comments. This makes the review coverage visible so teams can decide if
|
||||
un-reviewed files need a second look.
|
||||
|
||||
## Data Required
|
||||
|
||||
All exists today:
|
||||
- `mr_file_changes` (new_path per MR)
|
||||
- `notes` (position_new_path, note_type='DiffNote', discussion_id)
|
||||
- `discussions` (merge_request_id)
|
||||
|
||||
## Implementation Sketch
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
mfc.new_path,
|
||||
mfc.change_type,
|
||||
COUNT(DISTINCT n.id) as review_comments,
|
||||
COUNT(DISTINCT d.id) as review_threads,
|
||||
CASE WHEN COUNT(n.id) = 0 THEN 'NOT REVIEWED' ELSE 'REVIEWED' END as status
|
||||
FROM mr_file_changes mfc
|
||||
LEFT JOIN notes n ON n.position_new_path = mfc.new_path
|
||||
AND n.note_type = 'DiffNote'
|
||||
AND n.is_system = 0
|
||||
LEFT JOIN discussions d ON n.discussion_id = d.id
|
||||
AND d.merge_request_id = mfc.merge_request_id
|
||||
WHERE mfc.merge_request_id = ?1
|
||||
GROUP BY mfc.new_path
|
||||
ORDER BY review_comments DESC;
|
||||
```
|
||||
|
||||
## Human Output
|
||||
|
||||
```
|
||||
Review Coverage for !234 — Refactor auth middleware
|
||||
|
||||
REVIEWED (5 files, 23 comments)
|
||||
src/auth/middleware.rs 12 comments, 4 threads
|
||||
src/auth/jwt.rs 6 comments, 2 threads
|
||||
src/auth/session.rs 3 comments, 1 thread
|
||||
tests/auth/middleware_test.rs 1 comment, 1 thread
|
||||
src/auth/mod.rs 1 comment, 1 thread
|
||||
|
||||
NOT REVIEWED (3 files)
|
||||
src/auth/types.rs modified [no review comments]
|
||||
src/api/routes.rs modified [no review comments]
|
||||
Cargo.toml modified [no review comments]
|
||||
|
||||
Coverage: 5/8 files (62.5%)
|
||||
```
|
||||
|
||||
## Downsides
|
||||
|
||||
- Reviewers may have reviewed a file without leaving comments (approval by silence)
|
||||
- position_new_path matching may not cover all DiffNote position formats
|
||||
- Config files (Cargo.toml) not being reviewed is usually fine
|
||||
|
||||
## Extensions
|
||||
|
||||
- `lore review-coverage --all --since 30d` — aggregate coverage across all MRs
|
||||
- Per-reviewer breakdown: which reviewers cover which files?
|
||||
- Coverage heatmap: files that consistently escape review across multiple MRs
|
||||
90
docs/ideas/silos.md
Normal file
90
docs/ideas/silos.md
Normal file
@@ -0,0 +1,90 @@
|
||||
# Knowledge Silo Detection
|
||||
|
||||
- **Command:** `lore silos [--min-changes <N>]`
|
||||
- **Confidence:** 87%
|
||||
- **Tier:** 2
|
||||
- **Status:** proposed
|
||||
- **Effort:** medium — requires mr_file_changes population (Gate 4)
|
||||
|
||||
## What
|
||||
|
||||
For each file path (or directory), count unique MR authors. Flag paths where only
|
||||
1 person has ever authored changes (bus factor = 1). Aggregate by directory to show
|
||||
silo areas.
|
||||
|
||||
## Why
|
||||
|
||||
Bus factor analysis is critical for team resilience. If only one person has ever
|
||||
touched the auth module, that's a risk. This uses data already ingested to surface
|
||||
knowledge concentration that's otherwise invisible.
|
||||
|
||||
## Data Required
|
||||
|
||||
- `mr_file_changes` (new_path, merge_request_id) — needs Gate 4 ingestion
|
||||
- `merge_requests` (author_username, state='merged')
|
||||
- `projects` (path_with_namespace)
|
||||
|
||||
## Implementation Sketch
|
||||
|
||||
```sql
|
||||
-- Find directories with bus factor = 1
|
||||
WITH file_authors AS (
|
||||
SELECT
|
||||
mfc.new_path,
|
||||
mr.author_username,
|
||||
p.path_with_namespace,
|
||||
mfc.project_id
|
||||
FROM mr_file_changes mfc
|
||||
JOIN merge_requests mr ON mfc.merge_request_id = mr.id
|
||||
JOIN projects p ON mfc.project_id = p.id
|
||||
WHERE mr.state = 'merged'
|
||||
),
|
||||
directory_authors AS (
|
||||
SELECT
|
||||
project_id,
|
||||
path_with_namespace,
|
||||
-- Extract directory: everything before last '/'
|
||||
CASE
|
||||
WHEN INSTR(new_path, '/') > 0
|
||||
THEN SUBSTR(new_path, 1, LENGTH(new_path) - LENGTH(REPLACE(RTRIM(new_path, REPLACE(new_path, '/', '')), '', '')))
|
||||
ELSE '.'
|
||||
END as directory,
|
||||
COUNT(DISTINCT author_username) as unique_authors,
|
||||
COUNT(*) as total_changes,
|
||||
GROUP_CONCAT(DISTINCT author_username) as authors
|
||||
FROM file_authors
|
||||
GROUP BY project_id, directory
|
||||
)
|
||||
SELECT * FROM directory_authors
|
||||
WHERE unique_authors = 1
|
||||
AND total_changes >= ?1 -- min-changes threshold
|
||||
ORDER BY total_changes DESC;
|
||||
```
|
||||
|
||||
## Human Output
|
||||
|
||||
```
|
||||
Knowledge Silos (bus factor = 1, min 3 changes)
|
||||
|
||||
group/backend
|
||||
src/auth/ alice (8 changes) HIGH RISK
|
||||
src/billing/ bob (5 changes) HIGH RISK
|
||||
src/utils/cache/ charlie (3 changes) MODERATE RISK
|
||||
|
||||
group/frontend
|
||||
src/admin/ dave (12 changes) HIGH RISK
|
||||
```
|
||||
|
||||
## Downsides
|
||||
|
||||
- Historical authors may have left the team; needs recency weighting
|
||||
- Requires `mr_file_changes` to be populated (Gate 4)
|
||||
- Single-author directories may be intentional (ownership model)
|
||||
- Directory aggregation heuristic is imperfect for deep nesting
|
||||
|
||||
## Extensions
|
||||
|
||||
- `lore silos --since 180d` — only count recent activity
|
||||
- `lore silos --depth 2` — aggregate at directory depth N
|
||||
- Combine with `lore experts` to show both silos and experts in one view
|
||||
- Risk scoring: weight by directory size, change frequency, recency
|
||||
95
docs/ideas/similar-issues.md
Normal file
95
docs/ideas/similar-issues.md
Normal file
@@ -0,0 +1,95 @@
|
||||
# Similar Issues Finder
|
||||
|
||||
- **Command:** `lore similar <iid>`
|
||||
- **Confidence:** 95%
|
||||
- **Tier:** 1
|
||||
- **Status:** proposed
|
||||
- **Effort:** low — infrastructure exists, needs one new query path
|
||||
|
||||
## What
|
||||
|
||||
Given an issue IID, find the N most semantically similar issues using the existing
|
||||
vector embeddings. Show similarity score and overlapping keywords.
|
||||
|
||||
Can also work with MRs: `lore similar --mr <iid>`.
|
||||
|
||||
## Why
|
||||
|
||||
Duplicate detection is a constant problem on active projects. "Is this bug already
|
||||
filed?" becomes a one-liner. This is the most natural use of the embedding pipeline
|
||||
and the feature people expect when they hear "semantic search."
|
||||
|
||||
## Data Required
|
||||
|
||||
All exists today:
|
||||
- `documents` table (source_type, source_id, content_text)
|
||||
- `embeddings` virtual table (768-dim vectors via sqlite-vec)
|
||||
- `embedding_metadata` (document_hash for staleness check)
|
||||
|
||||
## Implementation Sketch
|
||||
|
||||
```
|
||||
1. Resolve IID → issue.id → document.id (via source_type='issue', source_id)
|
||||
2. Look up embedding vector(s) for that document
|
||||
3. Query sqlite-vec for K nearest neighbors (K = limit * 2 for headroom)
|
||||
4. Filter to source_type='issue' (or 'merge_request' if --include-mrs)
|
||||
5. Exclude self
|
||||
6. Rank by cosine similarity
|
||||
7. Return top N with: iid, title, project, similarity_score, url
|
||||
```
|
||||
|
||||
### SQL Core
|
||||
|
||||
```sql
|
||||
-- Get the embedding for target document (chunk 0 = representative)
|
||||
SELECT embedding FROM embeddings WHERE rowid = ?1 * 1000;
|
||||
|
||||
-- Find nearest neighbors
|
||||
SELECT
|
||||
rowid,
|
||||
distance
|
||||
FROM embeddings
|
||||
WHERE embedding MATCH ?1
|
||||
AND k = ?2
|
||||
ORDER BY distance;
|
||||
|
||||
-- Resolve back to entities
|
||||
SELECT d.source_type, d.source_id, d.title, d.url, i.iid, i.state
|
||||
FROM documents d
|
||||
JOIN issues i ON d.source_id = i.id AND d.source_type = 'issue'
|
||||
WHERE d.id = ?;
|
||||
```
|
||||
|
||||
## Robot Mode Output
|
||||
|
||||
```json
|
||||
{
|
||||
"ok": true,
|
||||
"data": {
|
||||
"query_issue": { "iid": 42, "title": "Login timeout on slow networks" },
|
||||
"similar": [
|
||||
{
|
||||
"iid": 38,
|
||||
"title": "Connection timeout in auth flow",
|
||||
"project": "group/backend",
|
||||
"similarity": 0.87,
|
||||
"state": "closed",
|
||||
"url": "https://gitlab.com/group/backend/-/issues/38"
|
||||
}
|
||||
]
|
||||
},
|
||||
"meta": { "elapsed_ms": 45, "candidates_scanned": 200 }
|
||||
}
|
||||
```
|
||||
|
||||
## Downsides
|
||||
|
||||
- Embedding quality depends on description quality; short issues may not match well
|
||||
- Multi-chunk documents need aggregation strategy (use chunk 0 or average?)
|
||||
- Requires embeddings to be generated first (`lore embed`)
|
||||
|
||||
## Extensions
|
||||
|
||||
- `lore similar --open-only` to filter to unresolved issues (duplicate triage)
|
||||
- `lore similar --text "free text query"` to find issues similar to arbitrary text
|
||||
- Batch mode: find all potential duplicate clusters across the entire database
|
||||
100
docs/ideas/stale-discussions.md
Normal file
100
docs/ideas/stale-discussions.md
Normal file
@@ -0,0 +1,100 @@
|
||||
# Stale Discussion Finder
|
||||
|
||||
- **Command:** `lore stale-discussions [--days <N>]`
|
||||
- **Confidence:** 90%
|
||||
- **Tier:** 1
|
||||
- **Status:** proposed
|
||||
- **Effort:** low — single query, minimal formatting
|
||||
|
||||
## What
|
||||
|
||||
List unresolved, resolvable discussions where `last_note_at` is older than a
|
||||
threshold (default 14 days), grouped by parent entity. Prioritize by discussion
|
||||
count per entity (more stale threads = more urgent).
|
||||
|
||||
## Why
|
||||
|
||||
Unresolved discussions are silent blockers. They prevent MR merges, stall
|
||||
decision-making, and represent forgotten conversations. This surfaces them so teams
|
||||
can take action: resolve, respond, or explicitly mark as won't-fix.
|
||||
|
||||
## Data Required
|
||||
|
||||
All exists today:
|
||||
- `discussions` (resolved, resolvable, last_note_at)
|
||||
- `issues` / `merge_requests` (for parent entity context)
|
||||
|
||||
## Implementation Sketch
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
d.id,
|
||||
d.noteable_type,
|
||||
CASE WHEN d.issue_id IS NOT NULL THEN i.iid ELSE mr.iid END as entity_iid,
|
||||
CASE WHEN d.issue_id IS NOT NULL THEN i.title ELSE mr.title END as entity_title,
|
||||
p.path_with_namespace,
|
||||
d.last_note_at,
|
||||
((?1 - d.last_note_at) / 86400000) as days_stale,
|
||||
COUNT(*) OVER (PARTITION BY COALESCE(d.issue_id, d.merge_request_id), d.noteable_type) as stale_count_for_entity
|
||||
FROM discussions d
|
||||
JOIN projects p ON d.project_id = p.id
|
||||
LEFT JOIN issues i ON d.issue_id = i.id
|
||||
LEFT JOIN merge_requests mr ON d.merge_request_id = mr.id
|
||||
WHERE d.resolved = 0
|
||||
AND d.resolvable = 1
|
||||
AND d.last_note_at < ?1
|
||||
ORDER BY days_stale DESC;
|
||||
```
|
||||
|
||||
## Human Output Format
|
||||
|
||||
```
|
||||
Stale Discussions (14+ days without activity)
|
||||
|
||||
group/backend !234 — Refactor auth middleware (3 stale threads)
|
||||
Discussion #a1b2c3 (28d stale) "Should we use JWT or session tokens?"
|
||||
Discussion #d4e5f6 (21d stale) "Error handling for expired tokens"
|
||||
Discussion #g7h8i9 (14d stale) "Performance implications of per-request validation"
|
||||
|
||||
group/backend #90 — Rate limiting design (1 stale thread)
|
||||
Discussion #j0k1l2 (18d stale) "Redis vs in-memory rate counter"
|
||||
```
|
||||
|
||||
## Robot Mode Output
|
||||
|
||||
```json
|
||||
{
|
||||
"ok": true,
|
||||
"data": {
|
||||
"threshold_days": 14,
|
||||
"total_stale": 4,
|
||||
"entities": [
|
||||
{
|
||||
"type": "merge_request",
|
||||
"iid": 234,
|
||||
"title": "Refactor auth middleware",
|
||||
"project": "group/backend",
|
||||
"stale_discussions": [
|
||||
{
|
||||
"discussion_id": "a1b2c3",
|
||||
"days_stale": 28,
|
||||
"first_note_preview": "Should we use JWT or session tokens?"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Downsides
|
||||
|
||||
- Some discussions are intentionally left open (design docs, long-running threads)
|
||||
- Could produce noise in repos with loose discussion hygiene
|
||||
- Doesn't distinguish "stale and blocking" from "stale and irrelevant"
|
||||
|
||||
## Extensions
|
||||
|
||||
- `lore stale-discussions --mr-only` — focus on MR review threads (most actionable)
|
||||
- `lore stale-discussions --author alice` — "threads I started that went quiet"
|
||||
- `lore stale-discussions --assignee bob` — "threads on my MRs that need attention"
|
||||
82
docs/ideas/unlinked.md
Normal file
82
docs/ideas/unlinked.md
Normal file
@@ -0,0 +1,82 @@
|
||||
# Unlinked MR Finder
|
||||
|
||||
- **Command:** `lore unlinked [--since <date>]`
|
||||
- **Confidence:** 83%
|
||||
- **Tier:** 2
|
||||
- **Status:** proposed
|
||||
- **Effort:** low — LEFT JOIN queries
|
||||
|
||||
## What
|
||||
|
||||
Two reports:
|
||||
1. Merged MRs with no entity_references at all (no "closes", no "mentioned",
|
||||
no "related") — orphan MRs with no issue traceability
|
||||
2. Closed issues with no MR reference — issues closed manually without code change
|
||||
|
||||
## Why
|
||||
|
||||
Process compliance metric. Unlinked MRs mean lost traceability — you can't trace
|
||||
a code change back to a requirement. Manually closed issues might mean work was done
|
||||
outside the tracked process, or issues were closed prematurely.
|
||||
|
||||
## Data Required
|
||||
|
||||
All exists today:
|
||||
- `merge_requests` (state, merged_at)
|
||||
- `issues` (state, closed/updated_at)
|
||||
- `entity_references` (for join/anti-join)
|
||||
|
||||
## Implementation Sketch
|
||||
|
||||
```sql
|
||||
-- Orphan merged MRs (no references at all)
|
||||
SELECT mr.iid, mr.title, mr.author_username, mr.merged_at,
|
||||
p.path_with_namespace
|
||||
FROM merge_requests mr
|
||||
JOIN projects p ON mr.project_id = p.id
|
||||
LEFT JOIN entity_references er
|
||||
ON er.source_entity_type = 'merge_request' AND er.source_entity_id = mr.id
|
||||
WHERE mr.state = 'merged'
|
||||
AND mr.merged_at >= ?1
|
||||
AND er.id IS NULL
|
||||
ORDER BY mr.merged_at DESC;
|
||||
|
||||
-- Closed issues with no MR reference
|
||||
SELECT i.iid, i.title, i.author_username, i.updated_at,
|
||||
p.path_with_namespace
|
||||
FROM issues i
|
||||
JOIN projects p ON i.project_id = p.id
|
||||
LEFT JOIN entity_references er
|
||||
ON er.target_entity_type = 'issue' AND er.target_entity_id = i.id
|
||||
AND er.source_entity_type = 'merge_request'
|
||||
WHERE i.state = 'closed'
|
||||
AND i.updated_at >= ?1
|
||||
AND er.id IS NULL
|
||||
ORDER BY i.updated_at DESC;
|
||||
```
|
||||
|
||||
## Human Output
|
||||
|
||||
```
|
||||
Unlinked MRs (merged with no issue reference, last 30 days)
|
||||
|
||||
!245 Fix typo in README (alice, merged 2d ago)
|
||||
!239 Update CI pipeline (bob, merged 1w ago)
|
||||
!236 Bump dependency versions (charlie, merged 2w ago)
|
||||
|
||||
Orphan Closed Issues (closed without any MR, last 30 days)
|
||||
|
||||
#92 Update documentation for v2 (closed by dave, 3d ago)
|
||||
#88 Investigate memory usage (closed by eve, 2w ago)
|
||||
```
|
||||
|
||||
## Downsides
|
||||
|
||||
- Some MRs legitimately don't reference issues (chores, CI fixes, dependency bumps)
|
||||
- Some issues are legitimately closed without code (questions, duplicates, won't-fix)
|
||||
- Noise level depends on team discipline
|
||||
|
||||
## Extensions
|
||||
|
||||
- `lore unlinked --ignore-labels "chore,ci"` — filter out expected orphans
|
||||
- Compliance score: % of MRs with issue links over time (trend metric)
|
||||
102
docs/ideas/weekly-digest.md
Normal file
102
docs/ideas/weekly-digest.md
Normal file
@@ -0,0 +1,102 @@
|
||||
# Weekly Digest Generator
|
||||
|
||||
- **Command:** `lore weekly [--since <date>]`
|
||||
- **Confidence:** 90%
|
||||
- **Tier:** 1
|
||||
- **Status:** proposed
|
||||
- **Effort:** medium — builds on digest infrastructure, adds markdown formatting
|
||||
|
||||
## What
|
||||
|
||||
Auto-generate a markdown document summarizing the week: MRs merged (grouped by
|
||||
project), issues closed, new issues opened, ongoing discussions, milestone progress.
|
||||
Formatted for pasting into Slack, email, or team standup notes.
|
||||
|
||||
Default window is 7 days. `--since` overrides.
|
||||
|
||||
## Why
|
||||
|
||||
Every team lead writes a weekly status update. This writes itself from the data.
|
||||
Leverages everything gitlore has ingested. Saves 30-60 minutes of manual summarization
|
||||
per week.
|
||||
|
||||
## Data Required
|
||||
|
||||
Same as digest (all exists today):
|
||||
- `resource_state_events`, `merge_requests`, `issues`, `discussions`
|
||||
- `milestones` for progress tracking
|
||||
|
||||
## Implementation Sketch
|
||||
|
||||
This is essentially `lore digest --since 7d --format markdown` with:
|
||||
1. Section headers for each category
|
||||
2. Milestone progress bars (X/Y issues closed)
|
||||
3. "Highlights" section with the most-discussed items
|
||||
4. "Risks" section with overdue issues and stale MRs
|
||||
|
||||
### Markdown Template
|
||||
|
||||
```markdown
|
||||
# Weekly Summary — Jan 20-27, 2025
|
||||
|
||||
## Highlights
|
||||
- **!234** Refactor auth middleware merged (12 discussions, 4 reviewers)
|
||||
- **#95** New critical bug: Rate limiting returns 500
|
||||
|
||||
## Merged (3)
|
||||
| MR | Title | Author | Reviewers |
|
||||
|----|-------|--------|-----------|
|
||||
| !234 | Refactor auth middleware | alice | bob, charlie |
|
||||
| !231 | Fix connection pool leak | bob | alice |
|
||||
| !45 | Update dashboard layout | eve | dave |
|
||||
|
||||
## Closed Issues (2)
|
||||
- **#89** Login timeout on slow networks (closed by alice)
|
||||
- **#87** Stale cache headers (closed by bob)
|
||||
|
||||
## New Issues (3)
|
||||
- **#95** Rate limiting returns 500 (priority::high, assigned to charlie)
|
||||
- **#94** Add rate limit documentation (priority::low)
|
||||
- **#93** Flaky test in CI pipeline (assigned to dave)
|
||||
|
||||
## Milestone Progress
|
||||
- **v2.0** — 14/20 issues closed (70%) — due Feb 15
|
||||
- **v1.9-hotfix** — 3/3 issues closed (100%) — COMPLETE
|
||||
|
||||
## Active Discussions
|
||||
- **#90** 8 new comments this week (needs-review)
|
||||
- **!230** 5 review threads unresolved
|
||||
```
|
||||
|
||||
## Robot Mode Output
|
||||
|
||||
```json
|
||||
{
|
||||
"ok": true,
|
||||
"data": {
|
||||
"period": { "from": "2025-01-20", "to": "2025-01-27" },
|
||||
"merged_count": 3,
|
||||
"closed_count": 2,
|
||||
"opened_count": 3,
|
||||
"highlights": [...],
|
||||
"merged": [...],
|
||||
"closed": [...],
|
||||
"opened": [...],
|
||||
"milestones": [...],
|
||||
"active_discussions": [...]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Downsides
|
||||
|
||||
- Formatting preferences vary by team; hard to please everyone
|
||||
- "Highlights" ranking is heuristic (discussion count as proxy for importance)
|
||||
- Doesn't capture work done outside GitLab
|
||||
|
||||
## Extensions
|
||||
|
||||
- `lore weekly --project group/backend` — single project scope
|
||||
- `lore weekly --author alice` — personal weekly summary
|
||||
- `lore weekly --output weekly.md` — write to file
|
||||
- Scheduled generation via cron + robot mode
|
||||
140
docs/issues/001-timeline-missing-project-in-entity-ref.md
Normal file
140
docs/issues/001-timeline-missing-project-in-entity-ref.md
Normal file
@@ -0,0 +1,140 @@
|
||||
# 001: Timeline human output omits project path from entity references
|
||||
|
||||
- **Severity:** medium
|
||||
- **Component:** `src/cli/commands/timeline.rs`
|
||||
- **Status:** open
|
||||
|
||||
## Problem
|
||||
|
||||
The `lore timeline` human-readable output renders entity references as bare `#42` or
|
||||
`!234` without the project path. When multiple projects are synced, this makes the
|
||||
output ambiguous — issue `#42` in `group/backend` and `#42` in `group/frontend` are
|
||||
indistinguishable.
|
||||
|
||||
### Affected code
|
||||
|
||||
`format_entity_ref` at `src/cli/commands/timeline.rs:201-207`:
|
||||
|
||||
```rust
|
||||
fn format_entity_ref(entity_type: &str, iid: i64) -> String {
|
||||
match entity_type {
|
||||
"issue" => format!("#{iid}"),
|
||||
"merge_request" => format!("!{iid}"),
|
||||
_ => format!("{entity_type}:{iid}"),
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This function is called in three places:
|
||||
|
||||
1. **Event lines** (`print_timeline_event`, line 130) — each event row shows `#42`
|
||||
with no project context
|
||||
2. **Footer seed list** (`print_timeline_footer`, line 161) — seed entities listed as
|
||||
`#42, !234` with no project disambiguation
|
||||
3. **Collect stage summaries** (`timeline_collect.rs:107`) — the `summary` field itself
|
||||
bakes in `"Issue #42 created: ..."` without project
|
||||
|
||||
### Current output (ambiguous)
|
||||
|
||||
```
|
||||
2025-01-20 CREATED #42 Issue #42 created: Login timeout bug @alice
|
||||
2025-01-21 LABEL+ #42 Label added: priority::high @dave
|
||||
2025-01-22 CREATED !234 MR !234 created: Refactor auth middleware @alice
|
||||
2025-01-25 MERGED !234 MR !234 merged @bob
|
||||
|
||||
Seed entities: #42, !234
|
||||
```
|
||||
|
||||
When multiple projects are synced, a reader cannot tell which project `#42` belongs to.
|
||||
|
||||
## Robot mode is partially affected
|
||||
|
||||
The robot JSON output (`EventJson`, line 387-416) DOES include a `project` field per
|
||||
event, so programmatic consumers can disambiguate. However, the `summary` string field
|
||||
still bakes in bare `#42` without project context, which is misleading if an agent uses
|
||||
the summary for display.
|
||||
|
||||
## Proposed fix
|
||||
|
||||
### 1. Add project to `format_entity_ref`
|
||||
|
||||
Pass `project_path` into `format_entity_ref` and use GitLab's full reference format:
|
||||
|
||||
```rust
|
||||
fn format_entity_ref(entity_type: &str, iid: i64, project_path: &str) -> String {
|
||||
match entity_type {
|
||||
"issue" => format!("{project_path}#{iid}"),
|
||||
"merge_request" => format!("{project_path}!{iid}"),
|
||||
_ => format!("{project_path}/{entity_type}:{iid}"),
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Smart elision for single-project timelines
|
||||
|
||||
When all events belong to the same project, the full path is visual noise. Detect
|
||||
this and fall back to bare `#42` / `!234`:
|
||||
|
||||
```rust
|
||||
fn should_show_project(events: &[TimelineEvent]) -> bool {
|
||||
let mut projects = events.iter().map(|e| &e.project_path).collect::<HashSet<_>>();
|
||||
projects.len() > 1
|
||||
}
|
||||
```
|
||||
|
||||
Then conditionally format:
|
||||
|
||||
```rust
|
||||
let entity_ref = if show_project {
|
||||
format_entity_ref(&event.entity_type, event.entity_iid, &event.project_path)
|
||||
} else {
|
||||
format_entity_ref_short(&event.entity_type, event.entity_iid)
|
||||
};
|
||||
```
|
||||
|
||||
### 3. Fix summary strings in collect stage
|
||||
|
||||
`timeline_collect.rs:107` bakes the summary as `"Issue #42 created: title"`. This
|
||||
should include the project when multi-project:
|
||||
|
||||
```rust
|
||||
let prefix = if multi_project {
|
||||
format!("{type_label} {project_path}#{iid}")
|
||||
} else {
|
||||
format!("{type_label} #{iid}")
|
||||
};
|
||||
summary = format!("{prefix} created: {title_str}");
|
||||
```
|
||||
|
||||
Same pattern for the merge summary at lines 317 and 347.
|
||||
|
||||
### 4. Update footer seed list
|
||||
|
||||
`print_timeline_footer` (line 155-164) should also use the project-aware format:
|
||||
|
||||
```rust
|
||||
result.seed_entities.iter()
|
||||
.map(|e| format_entity_ref(&e.entity_type, e.entity_iid, &e.project_path))
|
||||
```
|
||||
|
||||
## Expected output after fix
|
||||
|
||||
### Single project (no change)
|
||||
|
||||
```
|
||||
2025-01-20 CREATED #42 Issue #42 created: Login timeout bug @alice
|
||||
```
|
||||
|
||||
### Multi-project (project path added)
|
||||
|
||||
```
|
||||
2025-01-20 CREATED group/backend#42 Issue group/backend#42 created: Login timeout @alice
|
||||
2025-01-22 CREATED group/frontend#42 Issue group/frontend#42 created: Broken layout @eve
|
||||
```
|
||||
|
||||
## Impact
|
||||
|
||||
- Human output: ambiguous for multi-project users (the primary use case for gitlore)
|
||||
- Robot output: summary field misleading, but `project` field provides workaround
|
||||
- Timeline footer: seed entity list ambiguous
|
||||
- Collect-stage summaries: baked-in bare references propagate to both renderers
|
||||
179
docs/performance-audit-2026-02-12.md
Normal file
179
docs/performance-audit-2026-02-12.md
Normal file
@@ -0,0 +1,179 @@
|
||||
# Deep Performance Audit Report
|
||||
|
||||
**Date:** 2026-02-12
|
||||
**Branch:** `perf-audit` (e9bacc94)
|
||||
**Parent:** `039ab1c2` (master, v0.6.1)
|
||||
|
||||
---
|
||||
|
||||
## Methodology
|
||||
|
||||
1. **Baseline** — measured p50/p95 latency for all major commands with warm cache
|
||||
2. **Profile** — used macOS `sample` profiler and `EXPLAIN QUERY PLAN` to identify hotspots
|
||||
3. **Golden output** — captured exact numeric outputs before changes as equivalence oracle
|
||||
4. **One lever per change** — each optimization isolated and independently benchmarked
|
||||
5. **Revert threshold** — any optimization <1.1x speedup reverted per audit rules
|
||||
|
||||
---
|
||||
|
||||
## Baseline Measurements (warm cache, release build)
|
||||
|
||||
| Command | Latency | Notes |
|
||||
|---------|---------|-------|
|
||||
| `who --path src/core/db.rs` (expert) | 2200ms | **Hotspot** |
|
||||
| `who --active` | 83-93ms | Acceptable |
|
||||
| `who workload` | 22ms | Fast |
|
||||
| `stats` | 107-112ms | **Hotspot** |
|
||||
| `search "authentication"` | 1030ms | **Hotspot** (library-level) |
|
||||
| `list issues -n 50` | ~40ms | Fast |
|
||||
|
||||
---
|
||||
|
||||
## Optimization 1: INDEXED BY for DiffNote Queries
|
||||
|
||||
**Target:** `src/cli/commands/who.rs` — expert and reviews query paths
|
||||
|
||||
**Problem:** SQLite query planner chose `idx_notes_system` (38% selectivity, 106K rows) over `idx_notes_diffnote_path_created` (9.3% selectivity, 26K rows) for path-filtered DiffNote queries. The partial index `WHERE noteable_type = 'MergeRequest' AND type = 'DiffNote'` is far more selective but the planner's cost model didn't pick it.
|
||||
|
||||
**Change:** Added `INDEXED BY idx_notes_diffnote_path_created` to all 8 SQL queries across `query_expert`, `query_expert_details`, `query_reviews`, `build_path_query` (probes 1 & 2), and `suffix_probe`.
|
||||
|
||||
**Results:**
|
||||
|
||||
| Query | Before | After | Speedup |
|
||||
|-------|--------|-------|---------|
|
||||
| expert (specific path) | 2200ms | 56-58ms | **38x** |
|
||||
| expert (broad path) | 2200ms | 83ms | **26x** |
|
||||
| reviews | 1800ms | 24ms | **75x** |
|
||||
|
||||
**Isomorphism proof:** `INDEXED BY` only changes which index the planner uses, not the query semantics. Same rows matched, same ordering, same output. Verified by golden output comparison across 5+ runs.
|
||||
|
||||
---
|
||||
|
||||
## Optimization 2: Conditional Aggregates in Stats
|
||||
|
||||
**Target:** `src/cli/commands/stats.rs`
|
||||
|
||||
**Problem:** 12+ sequential `COUNT(*)` queries each requiring a full table scan of `documents` (61K rows). Each scan touched the same pages but couldn't share work.
|
||||
|
||||
**Changes:**
|
||||
- Documents: 5 sequential COUNTs -> 1 query with `SUM(CASE WHEN ... THEN 1 END)`
|
||||
- FTS count: `SELECT COUNT(*) FROM documents_fts` (virtual table, slow) -> `SELECT COUNT(*) FROM documents_fts_docsize` (shadow B-tree table, 19x faster)
|
||||
- Embeddings: 2 queries -> 1 with `COUNT(DISTINCT document_id), COUNT(*)`
|
||||
- Dirty sources: 2 queries -> 1 with conditional aggregates
|
||||
- Pending fetches: 2 queries -> 1 each (discussions, dependents)
|
||||
|
||||
**Results:**
|
||||
|
||||
| Metric | Before | After | Speedup |
|
||||
|--------|--------|-------|---------|
|
||||
| Warm median | 112ms | 66ms | **1.70x** |
|
||||
| Cold | 1220ms | ~700ms | ~1.7x |
|
||||
|
||||
**Golden output verified:**
|
||||
|
||||
```
|
||||
total:61652, issues:8241, mrs:10018, discussions:43393, truncated:63
|
||||
fts:61652, embedded:61652, chunks:88161
|
||||
```
|
||||
|
||||
All values match exactly across before/after runs.
|
||||
|
||||
**Isomorphism proof:** `SUM(CASE WHEN x THEN 1 END)` is algebraically identical to `COUNT(*) WHERE x`. The FTS5 shadow table `documents_fts_docsize` has exactly one row per FTS document by SQLite specification, so `COUNT(*)` on it equals the virtual table count.
|
||||
|
||||
---
|
||||
|
||||
## Investigation: Two-Phase FTS Search (REVERTED)
|
||||
|
||||
**Target:** `src/search/fts.rs`, `src/cli/commands/search.rs`
|
||||
|
||||
**Hypothesis:** FTS5 `snippet()` generation is expensive. Splitting search into Phase 1 (score-only MATCH+bm25) and Phase 2 (snippet for filtered results only) should reduce work.
|
||||
|
||||
**Implementation:** Created `fetch_fts_snippets()` that retrieves snippets only for post-filter document IDs via `json_each()` join.
|
||||
|
||||
**Results:**
|
||||
|
||||
| Metric | Before | After | Improvement |
|
||||
|--------|--------|-------|-------------|
|
||||
| search (limit 20) | 1030ms | 995ms | 3.5% |
|
||||
|
||||
**Decision:** Reverted. Per audit rules, <1.1x speedup does not justify added code complexity.
|
||||
|
||||
**Root cause:** The bottleneck is not snippet generation but `MATCH` + `bm25()` scoring itself. Profiling showed `strspn` (FTS5 tokenizer) and `memmove` as the top CPU consumers. The same query runs in 30ms on system sqlite3 but 1030ms in rusqlite's bundled SQLite — a ~125x gap despite both being SQLite 3.51.x compiled at -O3.
|
||||
|
||||
---
|
||||
|
||||
## Library-Level Finding: Bundled SQLite FTS5 Performance
|
||||
|
||||
**Observation:** FTS5 MATCH+bm25 queries are ~125x slower in rusqlite's bundled SQLite vs system sqlite3.
|
||||
|
||||
| Environment | Query Time | Notes |
|
||||
|-------------|-----------|-------|
|
||||
| System sqlite3 (macOS) | 30ms (with snippet), 8ms (without) | Same .db file |
|
||||
| rusqlite bundled | 1030ms | `features = ["bundled"]`, OPT_LEVEL=3 |
|
||||
|
||||
**Profiler data (macOS `sample`):**
|
||||
- Top hotspot: `strspn` in FTS5 tokenizer
|
||||
- Secondary: `memmove` in FTS5 internals
|
||||
- Scaling: ~5ms per result (limit 5 = 497ms, limit 20 = 995ms)
|
||||
|
||||
**Possible causes:**
|
||||
- Bundled SQLite compiled without platform-specific optimizations (SIMD, etc.)
|
||||
- Different memory allocator behavior
|
||||
- Missing compile-time tuning flags
|
||||
|
||||
**Recommendation for future:** Investigate switching from `features = ["bundled"]` to system SQLite linkage, or audit the bundled compile flags in the `libsqlite3-sys` build script.
|
||||
|
||||
---
|
||||
|
||||
## Exploration Agent Findings (Informational)
|
||||
|
||||
Four parallel exploration agents surveyed the entire codebase. Key findings beyond what was already addressed:
|
||||
|
||||
### Ingestion Pipeline
|
||||
- Serial DB writes in async context (acceptable — rusqlite is synchronous)
|
||||
- Label ingestion uses individual inserts (potential batch optimization, low priority)
|
||||
|
||||
### CLI / GitLab Client
|
||||
- GraphQL client recreated per call (`client.rs:98-100`) — caches connection pool, minor
|
||||
- Double JSON deserialization in GraphQL responses — medium priority
|
||||
- N+1 subqueries in `list` command (`list.rs:408-423`) — 4 correlated subqueries per row
|
||||
|
||||
### Search / Embedding
|
||||
- No N+1 patterns, no O(n^2) algorithms
|
||||
- Chunking is O(n) single-pass with proper UTF-8 safety
|
||||
- Ollama concurrency model is sound (parallel HTTP, serial DB writes)
|
||||
|
||||
### Database / Documents
|
||||
- O(n^2) prefix sum in `truncation.rs` — low traffic path
|
||||
- String allocation patterns in extractors — micro-optimization territory
|
||||
|
||||
---
|
||||
|
||||
## Opportunity Matrix
|
||||
|
||||
| Candidate | Impact | Confidence | Effort | Score | Status |
|
||||
|-----------|--------|------------|--------|-------|--------|
|
||||
| INDEXED BY for DiffNote | Very High | High | Low | **9.0** | Shipped |
|
||||
| Stats conditional aggregates | Medium | High | Low | **7.0** | Shipped |
|
||||
| Bundled SQLite FTS5 | Very High | Medium | High | 5.0 | Documented |
|
||||
| List N+1 subqueries | Medium | Medium | Medium | 4.0 | Backlog |
|
||||
| GraphQL double deser | Low | Medium | Low | 3.5 | Backlog |
|
||||
| Truncation O(n^2) | Low | High | Low | 3.0 | Backlog |
|
||||
|
||||
---
|
||||
|
||||
## Files Modified
|
||||
|
||||
| File | Change |
|
||||
|------|--------|
|
||||
| `src/cli/commands/who.rs` | INDEXED BY hints on 8 SQL queries |
|
||||
| `src/cli/commands/stats.rs` | Conditional aggregates, FTS5 shadow table, merged queries |
|
||||
|
||||
---
|
||||
|
||||
## Quality Gates
|
||||
|
||||
- All 603 tests pass
|
||||
- `cargo clippy --all-targets -- -D warnings` clean
|
||||
- `cargo fmt --check` clean
|
||||
- Golden output verified for both optimizations
|
||||
202
docs/plan-expose-discussion-ids.feedback-1.md
Normal file
202
docs/plan-expose-discussion-ids.feedback-1.md
Normal file
@@ -0,0 +1,202 @@
|
||||
No `## Rejected Recommendations` section appears in the plan you pasted, so the revisions below are all net-new.
|
||||
|
||||
1. **Add an explicit “Bridge Contract” and fix scope inconsistency**
|
||||
Analysis: The plan says “Three changes” but defines four. More importantly, identifier requirements are scattered. A single contract section prevents drift and makes every new read surface prove it can drive a write call.
|
||||
|
||||
```diff
|
||||
@@
|
||||
-**Scope**: Three changes, delivered in order:
|
||||
+**Scope**: Four workstreams, delivered in order:
|
||||
1. Add `gitlab_discussion_id` to notes output
|
||||
2. Add `gitlab_discussion_id` to show command discussion groups
|
||||
3. Add a standalone `discussions` list command
|
||||
4. Fix robot-docs to list actual field names instead of opaque type references
|
||||
+
|
||||
+## Bridge Contract (Cross-Cutting)
|
||||
+Every read payload that surfaces notes/discussions MUST include:
|
||||
+- `project_path`
|
||||
+- `noteable_type`
|
||||
+- `parent_iid`
|
||||
+- `gitlab_discussion_id`
|
||||
+- `gitlab_note_id` (when note-level data is returned)
|
||||
+This contract is required so agents can deterministically construct `glab api` write calls.
|
||||
```
|
||||
|
||||
2. **Normalize identifier naming now (break ambiguous names)**
|
||||
Analysis: Current `id`/`gitlab_id` naming is ambiguous in mixed payloads. Rename to explicit `note_id` and `gitlab_note_id` now (you explicitly don’t care about backward compatibility). This reduces automation mistakes.
|
||||
|
||||
```diff
|
||||
@@ 1b. Add field to `NoteListRow`
|
||||
-pub struct NoteListRow {
|
||||
- pub id: i64,
|
||||
- pub gitlab_id: i64,
|
||||
+pub struct NoteListRow {
|
||||
+ pub note_id: i64, // local DB id
|
||||
+ pub gitlab_note_id: i64, // GitLab note id
|
||||
@@
|
||||
@@ 1c. Add field to `NoteListRowJson`
|
||||
-pub struct NoteListRowJson {
|
||||
- pub id: i64,
|
||||
- pub gitlab_id: i64,
|
||||
+pub struct NoteListRowJson {
|
||||
+ pub note_id: i64,
|
||||
+ pub gitlab_note_id: i64,
|
||||
@@
|
||||
-#### 2f. Add `gitlab_note_id` to note detail structs in show
|
||||
-While we're here, add `gitlab_id` to `NoteDetail`, `MrNoteDetail`, and their JSON
|
||||
+#### 2f. Add `gitlab_note_id` to note detail structs in show
|
||||
+While we're here, add `gitlab_note_id` to `NoteDetail`, `MrNoteDetail`, and their JSON
|
||||
counterparts.
|
||||
```
|
||||
|
||||
3. **Stop positional column indexing for these changes**
|
||||
Analysis: In `list.rs`, row extraction is positional (`row.get(18)`, etc.). Adding fields is fragile and easy to break silently. Use named aliases and named lookup for robustness.
|
||||
|
||||
```diff
|
||||
@@ 1a/1b SQL + query_map
|
||||
- p.path_with_namespace AS project_path
|
||||
+ p.path_with_namespace AS project_path,
|
||||
+ d.gitlab_discussion_id AS gitlab_discussion_id
|
||||
@@
|
||||
- project_path: row.get(18)?,
|
||||
- gitlab_discussion_id: row.get(19)?,
|
||||
+ project_path: row.get("project_path")?,
|
||||
+ gitlab_discussion_id: row.get("gitlab_discussion_id")?,
|
||||
```
|
||||
|
||||
4. **Redesign `discussions` query to avoid correlated subquery fanout**
|
||||
Analysis: Proposed query uses many correlated subqueries per row. That’s acceptable for tiny MR-scoped sets, but degrades for project-wide scans. Use a base CTE + one rollup pass over notes.
|
||||
|
||||
```diff
|
||||
@@ 3c. SQL Query
|
||||
-SELECT
|
||||
- d.id,
|
||||
- ...
|
||||
- (SELECT COUNT(*) FROM notes n2 WHERE n2.discussion_id = d.id AND n2.is_system = 0) AS note_count,
|
||||
- (SELECT n3.author_username FROM notes n3 WHERE n3.discussion_id = d.id ORDER BY n3.position LIMIT 1) AS first_author,
|
||||
- ...
|
||||
-FROM discussions d
|
||||
+WITH base AS (
|
||||
+ SELECT d.id, d.gitlab_discussion_id, d.noteable_type, d.project_id, d.issue_id, d.merge_request_id,
|
||||
+ d.individual_note, d.first_note_at, d.last_note_at, d.resolvable, d.resolved
|
||||
+ FROM discussions d
|
||||
+ {where_sql}
|
||||
+),
|
||||
+note_rollup AS (
|
||||
+ SELECT n.discussion_id,
|
||||
+ COUNT(*) FILTER (WHERE n.is_system = 0) AS user_note_count,
|
||||
+ COUNT(*) AS total_note_count,
|
||||
+ MIN(CASE WHEN n.is_system = 0 THEN n.position END) AS first_user_pos
|
||||
+ FROM notes n
|
||||
+ JOIN base b ON b.id = n.discussion_id
|
||||
+ GROUP BY n.discussion_id
|
||||
+)
|
||||
+SELECT ...
|
||||
+FROM base b
|
||||
+LEFT JOIN note_rollup r ON r.discussion_id = b.id
|
||||
```
|
||||
|
||||
5. **Add explicit index work for new access patterns**
|
||||
Analysis: Existing indexes are good but not ideal for new list patterns (`project + last_note`, note position ordering inside discussion). Add migration entries to keep latency stable.
|
||||
|
||||
```diff
|
||||
@@ ## 3. Add Standalone `discussions` List Command
|
||||
+#### 3h. Add migration for discussion-list performance
|
||||
+**File**: `migrations/027_discussions_list_indexes.sql`
|
||||
+```sql
|
||||
+CREATE INDEX IF NOT EXISTS idx_discussions_project_last_note
|
||||
+ ON discussions(project_id, last_note_at DESC, id DESC);
|
||||
+CREATE INDEX IF NOT EXISTS idx_discussions_project_first_note
|
||||
+ ON discussions(project_id, first_note_at DESC, id DESC);
|
||||
+CREATE INDEX IF NOT EXISTS idx_notes_discussion_position
|
||||
+ ON notes(discussion_id, position);
|
||||
+```
|
||||
```
|
||||
|
||||
6. **Add keyset pagination (critical for agent workflows)**
|
||||
Analysis: `--limit` alone is not enough for automation over large datasets. Add cursor-based pagination with deterministic sort keys and `next_cursor` in JSON.
|
||||
|
||||
```diff
|
||||
@@ 3a. CLI Args
|
||||
+ /// Keyset cursor from previous response
|
||||
+ #[arg(long, help_heading = "Output")]
|
||||
+ pub cursor: Option<String>,
|
||||
@@
|
||||
@@ Response Schema
|
||||
- "total_count": 15,
|
||||
- "showing": 15
|
||||
+ "total_count": 15,
|
||||
+ "showing": 15,
|
||||
+ "next_cursor": "eyJsYXN0X25vdGVfYXQiOjE3MDAwMDAwMDAwMDAsImlkIjoxMjN9"
|
||||
@@
|
||||
@@ Validation Criteria
|
||||
+7. `lore -J discussions ... --cursor <token>` returns the next stable page without duplicates/skips
|
||||
```
|
||||
|
||||
7. **Fix semantic ambiguities in discussion summary fields**
|
||||
Analysis: `note_count` is ambiguous, and `first_author` can accidentally be a system note author. Make fields explicit and consistent with non-system default behavior.
|
||||
|
||||
```diff
|
||||
@@ Response Schema
|
||||
- "note_count": 3,
|
||||
- "first_author": "elovegrove",
|
||||
+ "user_note_count": 3,
|
||||
+ "total_note_count": 4,
|
||||
+ "first_user_author": "elovegrove",
|
||||
@@
|
||||
@@ 3d. Filters struct / path behavior
|
||||
-- `path` → `EXISTS (SELECT 1 FROM notes n WHERE n.discussion_id = d.id AND n.position_new_path LIKE ?)`
|
||||
+- `path` → match on BOTH `position_new_path` and `position_old_path` (exact/prefix)
|
||||
```
|
||||
|
||||
8. **Enrich show outputs with actionable thread metadata**
|
||||
Analysis: Adding only discussion id helps, but agents still need thread state and note ids to pick targets correctly. Add `resolvable`, `resolved`, `last_note_at_iso`, and `gitlab_note_id` in show discussion payloads.
|
||||
|
||||
```diff
|
||||
@@ 2a/2b show discussion structs
|
||||
pub struct DiscussionDetailJson {
|
||||
pub gitlab_discussion_id: String,
|
||||
+ pub resolvable: bool,
|
||||
+ pub resolved: bool,
|
||||
+ pub last_note_at_iso: String,
|
||||
pub notes: Vec<NoteDetailJson>,
|
||||
@@
|
||||
pub struct NoteDetailJson {
|
||||
+ pub gitlab_note_id: i64,
|
||||
pub author_username: String,
|
||||
```
|
||||
|
||||
9. **Harden robot-docs against schema drift with tests**
|
||||
Analysis: Static JSON in `main.rs` will drift again. Add a lightweight contract test that asserts docs include required fields for `notes`, `discussions`, and show payloads.
|
||||
|
||||
```diff
|
||||
@@ 4. Fix Robot-Docs Response Schemas
|
||||
+#### 4f. Add robot-docs contract tests
|
||||
+**File**: `src/main.rs` (or dedicated test module)
|
||||
+- Assert `robot-docs` contains `gitlab_discussion_id` and `gitlab_note_id` in:
|
||||
+ - `notes.response_schema`
|
||||
+ - `issues.response_schema.show`
|
||||
+ - `mrs.response_schema.show`
|
||||
+ - `discussions.response_schema`
|
||||
```
|
||||
|
||||
10. **Adjust delivery order to reduce rework and include missing CSV path**
|
||||
Analysis: In your sample `handle_discussions`, `csv` is declared in args but not handled. Also, robot-docs should land after all payload changes. Sequence should minimize churn.
|
||||
|
||||
```diff
|
||||
@@ Delivery Order
|
||||
-3. **Change 4** (robot-docs) — depends on 1 and 2 being done so schemas are accurate.
|
||||
-4. **Change 3** (discussions command) — largest change, depends on 1 for design consistency.
|
||||
+3. **Change 3** (discussions command + indexes + pagination) — largest change.
|
||||
+4. **Change 4** (robot-docs + contract tests) — last, after payloads are final.
|
||||
@@ 3e. Handler wiring
|
||||
- match format {
|
||||
+ match format {
|
||||
"json" => ...
|
||||
"jsonl" => ...
|
||||
+ "csv" => print_list_discussions_csv(&result),
|
||||
_ => ...
|
||||
}
|
||||
```
|
||||
|
||||
If you want, I can produce a single consolidated revised plan markdown with these edits applied so you can drop it in directly.
|
||||
162
docs/plan-expose-discussion-ids.feedback-2.md
Normal file
162
docs/plan-expose-discussion-ids.feedback-2.md
Normal file
@@ -0,0 +1,162 @@
|
||||
Best non-rejected upgrades I’d make to this plan are below. They focus on reducing schema drift, making robot output safer to consume, and improving performance behavior at scale.
|
||||
|
||||
1. Add a shared contract model and field constants first (before workstreams 1-4)
|
||||
Rationale: Right now each command has its own structs and ad-hoc mapping. That is exactly how drift happens. A single contract definition reused by `notes`, `show`, `discussions`, and robot-docs gives compile-time coupling between output payloads and docs. It also makes future fields cheaper and safer to add.
|
||||
|
||||
```diff
|
||||
@@ Scope: Four workstreams, delivered in order:
|
||||
-1. Add `gitlab_discussion_id` to notes output
|
||||
-2. Add `gitlab_discussion_id` to show command discussion groups
|
||||
-3. Add a standalone `discussions` list command
|
||||
-4. Fix robot-docs to list actual field names instead of opaque type references
|
||||
+0. Introduce shared Bridge Contract model/constants used by notes/show/discussions/robot-docs
|
||||
+1. Add `gitlab_discussion_id` to notes output
|
||||
+2. Add `gitlab_discussion_id` to show command discussion groups
|
||||
+3. Add a standalone `discussions` list command
|
||||
+4. Fix robot-docs to list actual field names instead of opaque type references
|
||||
|
||||
+## 0. Shared Contract Model (Cross-Cutting)
|
||||
+Define canonical required-field constants and shared mapping helpers, then consume them in:
|
||||
+- `src/cli/commands/list.rs`
|
||||
+- `src/cli/commands/show.rs`
|
||||
+- `src/cli/robot.rs`
|
||||
+- `src/main.rs` robot-docs builder
|
||||
+This removes duplicated field-name strings and prevents docs/output mismatch.
|
||||
```
|
||||
|
||||
2. Make bridge fields “non-droppable” in robot mode
|
||||
Rationale: The current plan adds fields, but `--fields` can still remove them. That breaks the core read/write bridge contract in exactly the workflows this change is trying to fix. In robot mode, contract fields should always be force-included.
|
||||
|
||||
```diff
|
||||
@@ ## Bridge Contract (Cross-Cutting)
|
||||
Every read payload that surfaces notes or discussions **MUST** include:
|
||||
- `project_path`
|
||||
- `noteable_type`
|
||||
- `parent_iid`
|
||||
- `gitlab_discussion_id`
|
||||
- `gitlab_note_id` (when note-level data is returned — i.e., in notes list and show detail)
|
||||
|
||||
+### Field Filtering Guardrail
|
||||
+In robot mode, `filter_fields` must force-include Bridge Contract fields even when users pass a narrower `--fields` list.
|
||||
+Human/table mode keeps existing behavior.
|
||||
```
|
||||
|
||||
3. Replace correlated subqueries in `discussions` rollup with a single-pass window/aggregate pattern
|
||||
Rationale: Your CTE is better than naive fanout, but it still uses multiple correlated sub-selects per discussion for first author/body/path. At 200K+ discussions this can regress badly depending on cache/index state. A window-ranked `notes` CTE with grouped aggregates is usually faster and more predictable in SQLite.
|
||||
|
||||
```diff
|
||||
@@ #### 3c. SQL Query
|
||||
-Core query uses a CTE + rollup to avoid correlated subquery fanout on larger result sets:
|
||||
+Core query uses a CTE + ranked-notes rollup (window function) to avoid per-row correlated subqueries:
|
||||
|
||||
-WITH filtered_discussions AS (...),
|
||||
-note_rollup AS (
|
||||
- SELECT
|
||||
- n.discussion_id,
|
||||
- SUM(...) AS note_count,
|
||||
- (SELECT ... LIMIT 1) AS first_author,
|
||||
- (SELECT ... LIMIT 1) AS first_note_body,
|
||||
- (SELECT ... LIMIT 1) AS position_new_path,
|
||||
- (SELECT ... LIMIT 1) AS position_new_line
|
||||
- FROM notes n
|
||||
- ...
|
||||
-)
|
||||
+WITH filtered_discussions AS (...),
|
||||
+ranked_notes AS (
|
||||
+ SELECT
|
||||
+ n.*,
|
||||
+ ROW_NUMBER() OVER (PARTITION BY n.discussion_id ORDER BY n.position, n.id) AS rn
|
||||
+ FROM notes n
|
||||
+ WHERE n.discussion_id IN (SELECT id FROM filtered_discussions)
|
||||
+),
|
||||
+note_rollup AS (
|
||||
+ SELECT
|
||||
+ discussion_id,
|
||||
+ SUM(CASE WHEN is_system = 0 THEN 1 ELSE 0 END) AS note_count,
|
||||
+ MAX(CASE WHEN rn = 1 AND is_system = 0 THEN author_username END) AS first_author,
|
||||
+ MAX(CASE WHEN rn = 1 AND is_system = 0 THEN body END) AS first_note_body,
|
||||
+ MAX(CASE WHEN position_new_path IS NOT NULL THEN position_new_path END) AS position_new_path,
|
||||
+ MAX(CASE WHEN position_new_line IS NOT NULL THEN position_new_line END) AS position_new_line
|
||||
+ FROM ranked_notes
|
||||
+ GROUP BY discussion_id
|
||||
+)
|
||||
```
|
||||
|
||||
4. Add direct GitLab ID filters for deterministic bridging
|
||||
Rationale: Bridge workflows often start from one known ID. You already have `gitlab_note_id` in notes filters, but discussion filtering still looks internal-ID-centric. Add explicit GitLab-ID filters so agents do not need extra translation calls.
|
||||
|
||||
```diff
|
||||
@@ #### 3a. CLI Args
|
||||
pub struct DiscussionsArgs {
|
||||
+ /// Filter by GitLab discussion ID
|
||||
+ #[arg(long, help_heading = "Filters")]
|
||||
+ pub gitlab_discussion_id: Option<String>,
|
||||
@@
|
||||
|
||||
@@ #### 3d. Filters struct
|
||||
pub struct DiscussionListFilters {
|
||||
+ pub gitlab_discussion_id: Option<String>,
|
||||
@@
|
||||
}
|
||||
```
|
||||
|
||||
```diff
|
||||
@@ ## 1. Add `gitlab_discussion_id` to Notes Output
|
||||
+#### 1g. Add `--gitlab-discussion-id` filter to notes
|
||||
+Allow filtering notes directly by GitLab thread ID (not only internal discussion ID).
|
||||
+This enables one-hop note retrieval from external references.
|
||||
```
|
||||
|
||||
5. Add optional note expansion to `discussions` for fewer round-trips
|
||||
Rationale: Today the agent flow is often `discussions -> show`. Optional embedded notes (`--include-notes N`) gives a fast path for “list unresolved threads with latest context” without forcing full show payloads.
|
||||
|
||||
```diff
|
||||
@@ ### Design
|
||||
lore -J discussions --for-mr 99 --resolution unresolved
|
||||
+lore -J discussions --for-mr 99 --resolution unresolved --include-notes 2
|
||||
|
||||
@@ #### 3a. CLI Args
|
||||
+ /// Include up to N latest notes per discussion (0 = none)
|
||||
+ #[arg(long, default_value = "0", help_heading = "Output")]
|
||||
+ pub include_notes: usize,
|
||||
```
|
||||
|
||||
6. Upgrade robot-docs from string blobs to structured schema + explicit contract block
|
||||
Rationale: `contains("gitlab_discussion_id")` tests on schema strings are brittle. A structured schema object gives machine-checked docs and reliable test assertions. Add a contract section for agent consumers.
|
||||
|
||||
```diff
|
||||
@@ ## 4. Fix Robot-Docs Response Schemas
|
||||
-#### 4a. Notes response_schema
|
||||
-Replace stringly-typed schema snippets...
|
||||
+#### 4a. Notes response_schema (structured)
|
||||
+Represent response fields as JSON objects (field -> type/nullable), not freeform strings.
|
||||
|
||||
+#### 4g. Add `bridge_contract` section in robot-docs
|
||||
+Publish canonical required fields per entity:
|
||||
+- notes
|
||||
+- discussions
|
||||
+- show.discussions
|
||||
+- show.notes
|
||||
```
|
||||
|
||||
7. Strengthen validation: add CLI-level contract tests and perf guardrails
|
||||
Rationale: Most current tests are unit-level struct/query checks. Add end-to-end JSON contract tests via command handlers, plus a benchmark-style regression test (ignored by default) so performance work stays intentional.
|
||||
|
||||
```diff
|
||||
@@ ## Validation Criteria
|
||||
8. Bridge Contract fields (...) are present in every applicable read payload
|
||||
+9. Contract fields remain present even with `--fields` in robot mode
|
||||
+10. `discussions` query meets performance guardrail on representative fixture (documented threshold)
|
||||
|
||||
@@ ### Tests
|
||||
+#### Test: robot-mode fields cannot drop bridge contract keys
|
||||
+Run notes/discussions JSON output through `filter_fields` path and assert required keys remain.
|
||||
+
|
||||
+#### Test: CLI contract integration
|
||||
+Invoke command handlers for `notes`, `discussions`, `mrs <iid>`, parse JSON, assert required keys and types.
|
||||
+
|
||||
+#### Test (ignored): large-fixture performance regression
|
||||
+Generate representative fixture and assert `query_discussions` stays under target elapsed time.
|
||||
```
|
||||
|
||||
If you want, I can now produce a full “v2 plan” document that applies these diffs end-to-end (including revised delivery order and complete updated sections).
|
||||
147
docs/plan-expose-discussion-ids.feedback-3.md
Normal file
147
docs/plan-expose-discussion-ids.feedback-3.md
Normal file
@@ -0,0 +1,147 @@
|
||||
1. **Make `gitlab_note_id` explicit in all note-level payloads without breaking existing consumers**
|
||||
Rationale: Your Bridge Contract already requires `gitlab_note_id`, but current plan keeps `gitlab_id` only in `notes` list while adding `gitlab_note_id` only in `show`. That forces agents to special-case commands. Add `gitlab_note_id` as an alias field everywhere note-level data appears, while keeping `gitlab_id` for compatibility.
|
||||
|
||||
```diff
|
||||
@@ Bridge Contract (Cross-Cutting)
|
||||
-Every read payload that surfaces notes or discussions MUST include:
|
||||
+Every read payload that surfaces notes or discussions MUST include:
|
||||
- project_path
|
||||
- noteable_type
|
||||
- parent_iid
|
||||
- gitlab_discussion_id
|
||||
- gitlab_note_id (when note-level data is returned — i.e., in notes list and show detail)
|
||||
+ - Back-compat rule: note payloads may continue exposing `gitlab_id`, but MUST also expose `gitlab_note_id` with the same value.
|
||||
|
||||
@@ 1. Add `gitlab_discussion_id` to Notes Output
|
||||
-#### 1c. Add field to `NoteListRowJson`
|
||||
+#### 1c. Add fields to `NoteListRowJson`
|
||||
+Add `gitlab_note_id` alias in addition to existing `gitlab_id` (no rename, no breakage).
|
||||
|
||||
@@ 1f. Update `--fields minimal` preset
|
||||
-"notes" => ["id", "author_username", "body", "created_at_iso", "gitlab_discussion_id"]
|
||||
+"notes" => ["id", "gitlab_note_id", "author_username", "body", "created_at_iso", "gitlab_discussion_id"]
|
||||
```
|
||||
|
||||
2. **Avoid duplicate flag semantics for discussion filtering**
|
||||
Rationale: `notes` already has `--discussion-id` and it already maps to `d.gitlab_discussion_id`. Adding a second independent flag/field (`--gitlab-discussion-id`) increases complexity and precedence bugs. Keep one backing filter field and make the new flag an alias.
|
||||
|
||||
```diff
|
||||
@@ 1g. Add `--gitlab-discussion-id` filter to notes
|
||||
-Allow filtering notes directly by GitLab discussion thread ID...
|
||||
+Normalize discussion ID flags:
|
||||
+- Keep one backing filter field (`discussion_id`)
|
||||
+- Support both `--discussion-id` (existing) and `--gitlab-discussion-id` (alias)
|
||||
+- If both are provided, clap should reject as duplicate/alias conflict
|
||||
```
|
||||
|
||||
3. **Add ambiguity guardrails for cross-project discussion IDs**
|
||||
Rationale: `gitlab_discussion_id` is unique per project, not globally. Filtering by discussion ID without project can return multiple rows across repos, which breaks deterministic write bridging. Fail fast with an `Ambiguous` error and actionable fix (`--project`).
|
||||
|
||||
```diff
|
||||
@@ Bridge Contract (Cross-Cutting)
|
||||
+### Ambiguity Guardrail
|
||||
+When filtering by `gitlab_discussion_id` without `--project`, if multiple projects match:
|
||||
+- return `Ambiguous` error
|
||||
+- include matching project paths in message
|
||||
+- suggest retry with `--project <path>`
|
||||
```
|
||||
|
||||
4. **Replace `--include-notes` N+1 retrieval with one batched top-N query**
|
||||
Rationale: The current plan’s per-discussion follow-up query scales poorly and creates latency spikes. Use a single window-function query over selected discussion IDs and group rows in Rust. This is both faster and more predictable.
|
||||
|
||||
```diff
|
||||
@@ 3c-ii. Note expansion query (--include-notes)
|
||||
-When `include_notes > 0`, after the main discussion query, run a follow-up query per discussion...
|
||||
+When `include_notes > 0`, run one batched query:
|
||||
+WITH ranked_notes AS (
|
||||
+ SELECT
|
||||
+ n.*,
|
||||
+ d.gitlab_discussion_id,
|
||||
+ ROW_NUMBER() OVER (
|
||||
+ PARTITION BY n.discussion_id
|
||||
+ ORDER BY n.created_at DESC, n.id DESC
|
||||
+ ) AS rn
|
||||
+ FROM notes n
|
||||
+ JOIN discussions d ON d.id = n.discussion_id
|
||||
+ WHERE n.discussion_id IN ( ...selected discussion ids... )
|
||||
+)
|
||||
+SELECT ... FROM ranked_notes WHERE rn <= ?
|
||||
+ORDER BY discussion_id, rn;
|
||||
+
|
||||
+Group by `discussion_id` in Rust and attach notes arrays without per-thread round-trips.
|
||||
```
|
||||
|
||||
5. **Add hard output guardrails and explicit truncation metadata**
|
||||
Rationale: `--limit` and `--include-notes` are unbounded today. For robot workflows this can accidentally generate huge payloads. Cap values and surface effective limits plus truncation state in `meta`.
|
||||
|
||||
```diff
|
||||
@@ 3a. CLI Args
|
||||
- pub limit: usize,
|
||||
+ pub limit: usize, // clamp to max (e.g., 500)
|
||||
|
||||
- pub include_notes: usize,
|
||||
+ pub include_notes: usize, // clamp to max (e.g., 20)
|
||||
|
||||
@@ Response Schema
|
||||
- "meta": { "elapsed_ms": 12 }
|
||||
+ "meta": {
|
||||
+ "elapsed_ms": 12,
|
||||
+ "effective_limit": 50,
|
||||
+ "effective_include_notes": 2,
|
||||
+ "has_more": true
|
||||
+ }
|
||||
```
|
||||
|
||||
6. **Strengthen deterministic ordering and null handling**
|
||||
Rationale: `first_note_at`, `last_note_at`, and note `position` can be null/incomplete during partial sync states. Add null-safe ordering to avoid unstable output and flaky automation.
|
||||
|
||||
```diff
|
||||
@@ 2c. Update queries to SELECT new fields
|
||||
-... ORDER BY first_note_at
|
||||
+... ORDER BY COALESCE(first_note_at, last_note_at, 0), id
|
||||
|
||||
@@ show note query
|
||||
-ORDER BY position
|
||||
+ORDER BY COALESCE(position, 9223372036854775807), created_at, id
|
||||
|
||||
@@ 3c. SQL Query
|
||||
-ORDER BY {sort_column} {order}
|
||||
+ORDER BY COALESCE({sort_column}, 0) {order}, fd.id {order}
|
||||
```
|
||||
|
||||
7. **Make write-bridging more useful with optional command hints**
|
||||
Rationale: Exposing IDs is necessary but not sufficient; agents still need to assemble endpoints repeatedly. Add optional `--with-write-hints` that injects compact endpoint templates (`reply`, `resolve`) derived from row context. This improves usability without bloating default output.
|
||||
|
||||
```diff
|
||||
@@ 3a. CLI Args
|
||||
+ /// Include machine-actionable glab write hints per row
|
||||
+ #[arg(long, help_heading = "Output")]
|
||||
+ pub with_write_hints: bool,
|
||||
|
||||
@@ Response Schema (notes/discussions/show)
|
||||
+ "write_hints?": {
|
||||
+ "reply_endpoint": "string",
|
||||
+ "resolve_endpoint?": "string"
|
||||
+ }
|
||||
```
|
||||
|
||||
8. **Upgrade robot-docs/contract validation from string-contains to parity checks**
|
||||
Rationale: `contains("gitlab_discussion_id")` catches very little and allows schema drift. Build field-set parity tests that compare actual serialized JSON keys to robot-docs declared fields for `notes`, `discussions`, and `show` discussion nodes.
|
||||
|
||||
```diff
|
||||
@@ 4f. Add robot-docs contract tests
|
||||
-assert!(notes_schema.contains("gitlab_discussion_id"));
|
||||
+let declared = parse_schema_field_list(notes_schema);
|
||||
+let sample = sample_notes_row_json_keys();
|
||||
+assert_required_subset(&declared, &["project_path","noteable_type","parent_iid","gitlab_discussion_id","gitlab_note_id"]);
|
||||
+assert_schema_matches_payload(&declared, &sample);
|
||||
|
||||
@@ 4g. Add CLI-level contract integration tests
|
||||
+Add parity tests for:
|
||||
+- notes list JSON
|
||||
+- discussions list JSON
|
||||
+- issues show discussions[*]
|
||||
+- mrs show discussions[*]
|
||||
```
|
||||
|
||||
If you want, I can produce a full revised v3 plan text with these edits merged end-to-end so it’s ready to execute directly.
|
||||
207
docs/plan-expose-discussion-ids.feedback-4.md
Normal file
207
docs/plan-expose-discussion-ids.feedback-4.md
Normal file
@@ -0,0 +1,207 @@
|
||||
Below are the highest-impact revisions I’d make to this plan. I excluded everything listed in your `## Rejected Recommendations` section.
|
||||
|
||||
**1. Fix a correctness bug in the ambiguity guardrail (must run before `LIMIT`)**
|
||||
|
||||
The current post-query ambiguity check can silently fail when `--limit` truncates results to one project even though multiple projects match the same `gitlab_discussion_id`. That creates non-deterministic write targeting risk.
|
||||
|
||||
```diff
|
||||
@@ ## Ambiguity Guardrail
|
||||
-**Implementation**: After the main query, if `gitlab_discussion_id` is set and no `--project`
|
||||
-was provided, check if the result set spans multiple `project_path` values.
|
||||
+**Implementation**: Run a preflight distinct-project check when `gitlab_discussion_id` is set
|
||||
+and `--project` was not provided, before the main list query applies `LIMIT`.
|
||||
+Use:
|
||||
+```sql
|
||||
+SELECT DISTINCT p.path_with_namespace
|
||||
+FROM discussions d
|
||||
+JOIN projects p ON p.id = d.project_id
|
||||
+WHERE d.gitlab_discussion_id = ?
|
||||
+LIMIT 3
|
||||
+```
|
||||
+If more than one project is found, return `LoreError::Ambiguous` (exit code 18) with project
|
||||
+paths and suggestion to retry with `--project <path>`.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**2. Add `gitlab_project_id` to the Bridge Contract**
|
||||
|
||||
`project_path` is human-friendly but mutable (renames/transfers). `gitlab_project_id` gives a stable write target and avoids path re-resolution failures.
|
||||
|
||||
```diff
|
||||
@@ ## Bridge Contract (Cross-Cutting)
|
||||
Every read payload that surfaces notes or discussions **MUST** include:
|
||||
- `project_path`
|
||||
+- `gitlab_project_id`
|
||||
- `noteable_type`
|
||||
- `parent_iid`
|
||||
- `gitlab_discussion_id`
|
||||
- `gitlab_note_id`
|
||||
@@
|
||||
const BRIDGE_FIELDS_NOTES: &[&str] = &[
|
||||
- "project_path", "noteable_type", "parent_iid",
|
||||
+ "project_path", "gitlab_project_id", "noteable_type", "parent_iid",
|
||||
"gitlab_discussion_id", "gitlab_note_id",
|
||||
];
|
||||
const BRIDGE_FIELDS_DISCUSSIONS: &[&str] = &[
|
||||
- "project_path", "noteable_type", "parent_iid",
|
||||
+ "project_path", "gitlab_project_id", "noteable_type", "parent_iid",
|
||||
"gitlab_discussion_id",
|
||||
];
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**3. Replace stringly-typed filter/sort fields with enums end-to-end**
|
||||
|
||||
Right now `sort`, `order`, `resolution`, `noteable_type` are mostly `String`. This is fragile and risks unsafe SQL interpolation drift over time. Typed enums make invalid states unrepresentable.
|
||||
|
||||
```diff
|
||||
@@ ## 3a. CLI Args
|
||||
- pub resolution: Option<String>,
|
||||
+ pub resolution: Option<ResolutionFilter>,
|
||||
@@
|
||||
- pub noteable_type: Option<String>,
|
||||
+ pub noteable_type: Option<NoteableTypeFilter>,
|
||||
@@
|
||||
- pub sort: String,
|
||||
+ pub sort: DiscussionSortField,
|
||||
@@
|
||||
- pub asc: bool,
|
||||
+ pub order: SortDirection,
|
||||
@@ ## 3d. Filters struct
|
||||
- pub resolution: Option<String>,
|
||||
- pub noteable_type: Option<String>,
|
||||
- pub sort: String,
|
||||
- pub order: String,
|
||||
+ pub resolution: Option<ResolutionFilter>,
|
||||
+ pub noteable_type: Option<NoteableTypeFilter>,
|
||||
+ pub sort: DiscussionSortField,
|
||||
+ pub order: SortDirection,
|
||||
@@
|
||||
+Map enum -> SQL fragment via `match` in query builder; never interpolate raw strings.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**4. Enforce snapshot consistency for multi-query commands**
|
||||
|
||||
`discussions` with `--include-notes` does multiple reads. Without a single read transaction, concurrent ingest can produce mismatched `total_count`, row set, and expanded notes.
|
||||
|
||||
```diff
|
||||
@@ ## 3c. SQL Query
|
||||
-pub fn query_discussions(...)
|
||||
+pub fn query_discussions(...)
|
||||
{
|
||||
+ // Run count query + page query + note expansion under one deferred read transaction
|
||||
+ // so output is a single consistent snapshot.
|
||||
+ let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Deferred)?;
|
||||
...
|
||||
+ tx.commit()?;
|
||||
}
|
||||
@@ ## 1. Add `gitlab_discussion_id` to Notes Output
|
||||
+Apply the same snapshot rule to `query_notes` when returning `total_count` + paged rows.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**5. Correct first-note rollup semantics (current CTE can return null/incorrect `first_author`)**
|
||||
|
||||
In the proposed SQL, `rn=1` is computed over all notes but then filtered with `is_system=0`, so threads with a leading system note may incorrectly lose `first_author`/snippet. Also path rollup uses non-deterministic `MAX(...)`.
|
||||
|
||||
```diff
|
||||
@@ ## 3c. SQL Query
|
||||
-ranked_notes AS (
|
||||
+ranked_notes AS (
|
||||
SELECT
|
||||
n.discussion_id,
|
||||
n.author_username,
|
||||
n.body,
|
||||
n.is_system,
|
||||
n.position_new_path,
|
||||
n.position_new_line,
|
||||
- ROW_NUMBER() OVER (
|
||||
- PARTITION BY n.discussion_id
|
||||
- ORDER BY n.position, n.id
|
||||
- ) AS rn
|
||||
+ ROW_NUMBER() OVER (
|
||||
+ PARTITION BY n.discussion_id
|
||||
+ ORDER BY CASE WHEN n.is_system = 0 THEN 0 ELSE 1 END, n.created_at, n.id
|
||||
+ ) AS rn_first_note,
|
||||
+ ROW_NUMBER() OVER (
|
||||
+ PARTITION BY n.discussion_id
|
||||
+ ORDER BY CASE WHEN n.position_new_path IS NULL THEN 1 ELSE 0 END, n.created_at, n.id
|
||||
+ ) AS rn_first_position
|
||||
@@
|
||||
- MAX(CASE WHEN rn = 1 AND is_system = 0 THEN author_username END) AS first_author,
|
||||
- MAX(CASE WHEN rn = 1 AND is_system = 0 THEN body END) AS first_note_body,
|
||||
- MAX(CASE WHEN position_new_path IS NOT NULL THEN position_new_path END) AS position_new_path,
|
||||
- MAX(CASE WHEN position_new_line IS NOT NULL THEN position_new_line END) AS position_new_line
|
||||
+ MAX(CASE WHEN rn_first_note = 1 AND is_system = 0 THEN author_username END) AS first_author,
|
||||
+ MAX(CASE WHEN rn_first_note = 1 AND is_system = 0 THEN body END) AS first_note_body,
|
||||
+ MAX(CASE WHEN rn_first_position = 1 THEN position_new_path END) AS position_new_path,
|
||||
+ MAX(CASE WHEN rn_first_position = 1 THEN position_new_line END) AS position_new_line
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**6. Add per-discussion truncation signals for `--include-notes`**
|
||||
|
||||
Top-level `has_more` is useful, but agents also need to know if an individual thread’s notes were truncated. Otherwise they can’t tell if a thread is complete.
|
||||
|
||||
```diff
|
||||
@@ ## Response Schema
|
||||
{
|
||||
"gitlab_discussion_id": "...",
|
||||
...
|
||||
- "notes": []
|
||||
+ "included_note_count": 0,
|
||||
+ "has_more_notes": false,
|
||||
+ "notes": []
|
||||
}
|
||||
@@ ## 3b. Domain Structs
|
||||
pub struct DiscussionListRowJson {
|
||||
@@
|
||||
+ pub included_note_count: usize,
|
||||
+ pub has_more_notes: bool,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub notes: Vec<NoteListRowJson>,
|
||||
}
|
||||
@@ ## 3c-ii. Note expansion query (--include-notes)
|
||||
-Group by `discussion_id` in Rust and attach notes arrays...
|
||||
+Group by `discussion_id` in Rust, attach notes arrays, and set:
|
||||
+`included_note_count = notes.len()`,
|
||||
+`has_more_notes = note_count > included_note_count`.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**7. Add explicit query-plan gate and targeted index workstream (measured, not speculative)**
|
||||
|
||||
This plan introduces heavy discussion-centric reads. You should bake in deterministic performance validation with `EXPLAIN QUERY PLAN` and only then add indexes if missing.
|
||||
|
||||
```diff
|
||||
@@ ## Scope: Four workstreams, delivered in order:
|
||||
-4. Fix robot-docs to list actual field names instead of opaque type references
|
||||
+4. Add query-plan validation + targeted index updates for new discussion queries
|
||||
+5. Fix robot-docs to list actual field names instead of opaque type references
|
||||
@@
|
||||
+## 4. Query-Plan Validation and Targeted Indexes
|
||||
+
|
||||
+Before and after implementing `query_discussions`, capture `EXPLAIN QUERY PLAN` for:
|
||||
+- `--for-mr <iid> --resolution unresolved`
|
||||
+- `--project <path> --since 7d --sort last_note`
|
||||
+- `--gitlab-discussion-id <id>`
|
||||
+
|
||||
+If plans show table scans on `notes`/`discussions`, add indexes in `MIGRATIONS` array:
|
||||
+- `discussions(project_id, gitlab_discussion_id)`
|
||||
+- `discussions(merge_request_id, last_note_at, id)`
|
||||
+- `notes(discussion_id, created_at DESC, id DESC)`
|
||||
+- `notes(discussion_id, position, id)`
|
||||
+
|
||||
+Tests: assert the new query paths return expected rows under indexed schema and no regressions.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
If you want, I can produce a single consolidated “iteration 4” version of the plan text with all seven revisions merged in place.
|
||||
160
docs/plan-expose-discussion-ids.feedback-4.md.bak
Normal file
160
docs/plan-expose-discussion-ids.feedback-4.md.bak
Normal file
@@ -0,0 +1,160 @@
|
||||
I reviewed the plan end-to-end and focused only on new improvements (none of the items in `## Rejected Recommendations` are re-proposed).
|
||||
|
||||
1. Add direct `--discussion-id` retrieval paths
|
||||
Rationale: This removes a full discovery hop for the exact workflow that failed (replying to a known thread). It also reduces ambiguity and query cost when an agent already has the thread ID.
|
||||
|
||||
```diff
|
||||
@@ Core Changes
|
||||
| 7 | Fix robot-docs to list actual field names | Docs | Small |
|
||||
+| 8 | Add direct `--discussion-id` filter to notes/discussions/show | Core | Small |
|
||||
|
||||
@@ Change 3: Add Standalone `discussions` List Command
|
||||
lore -J discussions --for-mr 99 --cursor <token> # keyset pagination
|
||||
+lore -J discussions --discussion-id 6a9c1750b37d... # direct lookup
|
||||
|
||||
@@ 3a. CLI Args
|
||||
+ #[arg(long, conflicts_with_all = ["for_issue", "for_mr"], help_heading = "Filters")]
|
||||
+ pub discussion_id: Option<String>,
|
||||
|
||||
@@ Change 1: Add `gitlab_discussion_id` to Notes Output
|
||||
+Add `--discussion-id <hex>` filter to `notes` for direct note retrieval within one thread.
|
||||
```
|
||||
|
||||
2. Add a shared filter compiler to eliminate count/query drift
|
||||
Rationale: The plan currently repeats filters across data query, `total_count`, and `incomplete_rows` count queries. That is a classic reliability bug source. A single compiled filter object makes count semantics provably consistent.
|
||||
|
||||
```diff
|
||||
@@ Count Semantics (Cross-Cutting Convention)
|
||||
+## Filter Compiler (NEW, Cross-Cutting Convention)
|
||||
+All list commands must build predicates via a shared `CompiledFilters` object that emits:
|
||||
+- SQL predicate fragment
|
||||
+- bind parameters
|
||||
+- canonical filter string (for cursor hash)
|
||||
+The same compiled object is reused by:
|
||||
+- page data query
|
||||
+- `total_count` query
|
||||
+- `incomplete_rows` query
|
||||
```
|
||||
|
||||
3. Harden keyset pagination semantics for `DESC`, limits, and client ergonomics
|
||||
Rationale: `(sort_value, id) > (?, ?)` is only correct for ascending order. Descending sort needs `<`. Also add explicit `has_more` so clients don’t infer from cursor nullability.
|
||||
|
||||
```diff
|
||||
@@ Keyset Pagination (Cross-Cutting, Change B)
|
||||
-```sql
|
||||
-WHERE (sort_value, id) > (?, ?)
|
||||
-```
|
||||
+Use comparator by order:
|
||||
+- ASC: `(sort_value, id) > (?, ?)`
|
||||
+- DESC: `(sort_value, id) < (?, ?)`
|
||||
|
||||
@@ 3a. CLI Args
|
||||
+ #[arg(short = 'n', long = "limit", default_value = "50", value_parser = clap::value_parser!(usize).range(1..=500), help_heading = "Output")]
|
||||
+ pub limit: usize,
|
||||
|
||||
@@ Response Schema
|
||||
- "next_cursor": "aW...xyz=="
|
||||
+ "next_cursor": "aW...xyz==",
|
||||
+ "has_more": true
|
||||
```
|
||||
|
||||
4. Add DB-level entity integrity invariants (not just response invariants)
|
||||
Rationale: Response-side filtering is good, but DB correctness should also be guarded. This prevents silent corruption and bad joins from ingestion or future migrations.
|
||||
|
||||
```diff
|
||||
@@ Contract Invariants (NEW)
|
||||
+### Entity Integrity Invariants (DB + Ingest)
|
||||
+1. `discussions` must belong to exactly one parent (`issue_id XOR merge_request_id`).
|
||||
+2. `discussions.noteable_type` must match the populated parent column.
|
||||
+3. Natural-key uniqueness is enforced where valid:
|
||||
+ - `(project_id, gitlab_discussion_id)` unique for discussions.
|
||||
+4. Ingestion must reject/quarantine rows violating invariants and report counts.
|
||||
|
||||
@@ Supporting Indexes (Cross-Cutting, Change D)
|
||||
+CREATE UNIQUE INDEX IF NOT EXISTS idx_discussions_project_gitlab_discussion_id
|
||||
+ ON discussions(project_id, gitlab_discussion_id);
|
||||
```
|
||||
|
||||
5. Switch bulk note loading to streaming grouping (avoid large intermediate vecs)
|
||||
Rationale: Current bulk strategy still materializes all notes before grouping. Streaming into the map cuts peak memory and improves large-MR stability.
|
||||
|
||||
```diff
|
||||
@@ Change 2e. Constructor — use bulk notes map
|
||||
-let all_note_rows: Vec<MrNoteDetail> = ... // From bulk query above
|
||||
-let notes_by_discussion: HashMap<i64, Vec<MrNoteDetail>> =
|
||||
- all_note_rows.into_iter().fold(HashMap::new(), |mut map, note| {
|
||||
- map.entry(note.discussion_id).or_insert_with(Vec::new).push(note);
|
||||
- map
|
||||
- });
|
||||
+let mut notes_by_discussion: HashMap<i64, Vec<MrNoteDetail>> = HashMap::new();
|
||||
+for row in bulk_note_stmt.query_map(params, map_note_row)? {
|
||||
+ let note = row?;
|
||||
+ notes_by_discussion.entry(note.discussion_id).or_default().push(note);
|
||||
+}
|
||||
```
|
||||
|
||||
6. Make freshness tri-state (`fresh|stale|unknown`) and fail closed on unknown with `--require-fresh`
|
||||
Rationale: `stale: bool` alone cannot represent “never synced / unknown project freshness.” For write safety, unknown freshness should be explicit and reject under freshness constraints.
|
||||
|
||||
```diff
|
||||
@@ Freshness Metadata & Staleness Guards
|
||||
pub struct ResponseMeta {
|
||||
pub elapsed_ms: i64,
|
||||
pub data_as_of_iso: String,
|
||||
pub sync_lag_seconds: i64,
|
||||
pub stale: bool,
|
||||
+ pub freshness_state: String, // "fresh" | "stale" | "unknown"
|
||||
+ #[serde(skip_serializing_if = "Option::is_none")]
|
||||
+ pub freshness_reason: Option<String>,
|
||||
pub incomplete_rows: i64,
|
||||
@@
|
||||
-if sync_lag_seconds > max_age_secs {
|
||||
+if freshness_state == "unknown" || sync_lag_seconds > max_age_secs {
|
||||
```
|
||||
|
||||
7. Tune indexes to match actual ORDER BY paths in window queries
|
||||
Rationale: `idx_notes_discussion_position` is likely insufficient for the two window orderings. A covering-style index aligned with partition/order keys reduces random table lookups.
|
||||
|
||||
```diff
|
||||
@@ Supporting Indexes (Cross-Cutting, Change D)
|
||||
--- Notes: window function ORDER BY (discussion_id, position) for ROW_NUMBER()
|
||||
-CREATE INDEX IF NOT EXISTS idx_notes_discussion_position
|
||||
- ON notes(discussion_id, position);
|
||||
+-- Notes: support dual ROW_NUMBER() orderings and reduce table lookups
|
||||
+CREATE INDEX IF NOT EXISTS idx_notes_discussion_window
|
||||
+ ON notes(discussion_id, is_system, position, created_at, gitlab_id);
|
||||
```
|
||||
|
||||
8. Add a phased rollout gate before strict exclusion becomes default
|
||||
Rationale: Enforcing `gitlab_* IS NOT NULL` immediately can hide data if existing rows are incomplete. A short observation gate prevents sudden regressions while preserving the end-state contract.
|
||||
|
||||
```diff
|
||||
@@ Delivery Order
|
||||
+Batch 0: Observability gate (NEW)
|
||||
+- Ship `incomplete_rows` and freshness meta first
|
||||
+- Measure incomplete rate across real datasets
|
||||
+- If incomplete ratio <= threshold, enable strict exclusion defaults
|
||||
+- If above threshold, block rollout and fix ingestion quality first
|
||||
+
|
||||
Change 1 (notes output) ──┐
|
||||
```
|
||||
|
||||
9. Add property-based invariants for pagination/count correctness
|
||||
Rationale: Your current tests are scenario-based and good, but randomized property tests are much better at catching edge-case cursor/count bugs.
|
||||
|
||||
```diff
|
||||
@@ Tests (Change 3 / Change B)
|
||||
+**Test 12**: Property-based pagination invariants (`proptest`)
|
||||
+```rust
|
||||
+#[test]
|
||||
+fn prop_discussion_cursor_no_overlap_no_gap_under_random_data() { /* ... */ }
|
||||
+```
|
||||
+
|
||||
+**Test 13**: Property-based count invariants
|
||||
+```rust
|
||||
+#[test]
|
||||
+fn prop_total_count_and_incomplete_rows_match_filter_partition() { /* ... */ }
|
||||
+```
|
||||
```
|
||||
|
||||
If you want, I can now produce a fully consolidated “Plan v4” that applies these diffs cleanly into your original document so it reads as a single coherent spec.
|
||||
158
docs/plan-expose-discussion-ids.feedback-5.md.bak
Normal file
158
docs/plan-expose-discussion-ids.feedback-5.md.bak
Normal file
@@ -0,0 +1,158 @@
|
||||
I reviewed the whole plan and only proposed changes that are not in your `## Rejected Recommendations`.
|
||||
|
||||
1. **Fix plan-internal inconsistencies first**
|
||||
Analysis: The plan currently has a few self-contradictions (`8` vs `9` cross-cutting improvements, `stale` still referenced after moving to tri-state freshness). Cleaning this prevents implementation drift and bad AC validation.
|
||||
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@
|
||||
-**Scope**: 8 core changes + 8 cross-cutting architectural improvements across 3 tiers:
|
||||
+**Scope**: 8 core changes + 9 cross-cutting architectural improvements across 3 tiers:
|
||||
@@ AC-7: Freshness Metadata Present & Staleness Guards Work
|
||||
-lore -J notes -n 1 | jq '.meta | {data_as_of_iso, sync_lag_seconds, stale}'
|
||||
-# All fields present, stale=false if recently synced
|
||||
+lore -J notes -n 1 | jq '.meta | {data_as_of_iso, sync_lag_seconds, freshness_state}'
|
||||
+# All fields present, freshness_state is one of fresh|stale|unknown
|
||||
@@ Change 6 Response Schema example
|
||||
- "stale": false,
|
||||
+ "freshness_state": "fresh",
|
||||
```
|
||||
|
||||
2. **Require snapshot-consistent list responses (page + counts)**
|
||||
Analysis: `total_count`, `incomplete_rows`, and page rows can drift if sync writes between queries. Enforcing a single read snapshot for all list commands makes pagination and counts deterministic.
|
||||
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@ Count Semantics (Cross-Cutting Convention)
|
||||
All list commands use consistent count fields:
|
||||
+All three queries (`page`, `total_count`, `incomplete_rows`) MUST execute inside one read transaction/snapshot.
|
||||
+This guarantees count/page consistency under concurrent sync writes.
|
||||
```
|
||||
|
||||
3. **Use RAII transactions instead of manual `BEGIN/COMMIT`**
|
||||
Analysis: Manual `execute_batch("BEGIN...")` is fragile on early returns. `rusqlite::Transaction` guarantees rollback on error and removes transaction-leak risk.
|
||||
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@ Change 2: Consistency guarantee
|
||||
-conn.execute_batch("BEGIN DEFERRED")?;
|
||||
-// ... discussion query ...
|
||||
-// ... bulk note query ...
|
||||
-conn.execute_batch("COMMIT")?;
|
||||
+let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Deferred)?;
|
||||
+// ... discussion query ...
|
||||
+// ... bulk note query ...
|
||||
+tx.commit()?;
|
||||
```
|
||||
|
||||
4. **Allow small focused new modules for query infrastructure**
|
||||
Analysis: Keeping everything in `list.rs`/`show.rs` will become a maintenance hotspot as filters/cursors/freshness expand. A small module split reduces coupling and regression risk.
|
||||
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@ Change 3: File Architecture
|
||||
-**No new files.** Follow existing patterns:
|
||||
+Allow focused infra modules for shared logic:
|
||||
+- `src/cli/query/filters.rs` (CompiledFilters + builders)
|
||||
+- `src/cli/query/cursor.rs` (encode/decode/validate v2 cursors)
|
||||
+- `src/cli/query/freshness.rs` (freshness computation + guards)
|
||||
+Command handlers remain in existing files.
|
||||
```
|
||||
|
||||
5. **Add ingest-time `discussion_rollups` to avoid repeated heavy window scans**
|
||||
Analysis: Window functions are good, but doing them on every read over large note volumes is still expensive. Precomputing rollups during ingest gives lower and more predictable p95 latency while keeping read paths simpler.
|
||||
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@ Architectural Improvements (Cross-Cutting)
|
||||
+| J | Ingest-time discussion rollups (`discussion_rollups`) | Performance | Medium |
|
||||
@@ Change 3 SQL strategy
|
||||
-Use `ROW_NUMBER()` window function instead of correlated subqueries...
|
||||
+Primary path: join precomputed `discussion_rollups` for `note_count`, `first_author`,
|
||||
+`first_note_body`, `position_new_path`, `position_new_line`.
|
||||
+Fallback path: window-function recompute if rollup row is missing (defensive correctness).
|
||||
```
|
||||
|
||||
6. **Add deterministic numeric project selector `--project-id`**
|
||||
Analysis: `-p group/repo` is human-friendly, but numeric project IDs are safer for robots and avoid fuzzy/project-path ambiguity. This reduces false ambiguity failures and lookup overhead.
|
||||
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@ DiscussionsArgs
|
||||
#[arg(short = 'p', long, help_heading = "Filters")]
|
||||
pub project: Option<String>,
|
||||
+ #[arg(long, conflicts_with = "project", help_heading = "Filters")]
|
||||
+ pub project_id: Option<i64>,
|
||||
@@ Ambiguity handling
|
||||
+If `--project-id` is provided, IID resolution is scoped directly to that project.
|
||||
+`--project-id` takes precedence over path-based project matching.
|
||||
```
|
||||
|
||||
7. **Make path filtering rename-aware (`old` + `new`)**
|
||||
Analysis: Current `--path` strategy only using `position_new_path` misses deleted/renamed-file discussions. Supporting side selection makes the feature materially more useful for review workflows.
|
||||
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@ DiscussionsArgs
|
||||
#[arg(long, help_heading = "Filters")]
|
||||
pub path: Option<String>,
|
||||
+ #[arg(long, value_parser = ["either", "new", "old"], default_value = "either", help_heading = "Filters")]
|
||||
+ pub path_side: String,
|
||||
@@ Change 3 filtering
|
||||
-Path filter matches `position_new_path`.
|
||||
+Path filter semantics:
|
||||
+- `either` (default): match `position_new_path` OR `position_old_path`
|
||||
+- `new`: match only `position_new_path`
|
||||
+- `old`: match only `position_old_path`
|
||||
```
|
||||
|
||||
8. **Add explicit freshness behavior for empty-result queries + bootstrap backfill**
|
||||
Analysis: Freshness based only on “participating rows” is undefined when results are empty. Define deterministic behavior and backfill `project_sync_state` on migration so `unknown` doesn’t spike unexpectedly after deploy.
|
||||
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@ Freshness state logic
|
||||
+Empty-result rules:
|
||||
+- If query is project-scoped (`-p` or `--project-id`), freshness is computed from that project even when no rows match.
|
||||
+- If query is unscoped and returns zero rows, freshness is computed from all tracked projects.
|
||||
@@ A1. Track per-project sync timestamp
|
||||
+Migration step: seed `project_sync_state` from latest known sync metadata where available
|
||||
+to avoid mass `unknown` freshness immediately after rollout.
|
||||
```
|
||||
|
||||
9. **Upgrade `--discussion-id` from filter-only to first-class thread retrieval**
|
||||
Analysis: Filtering list output by discussion ID still returns list-shaped data and partial note context. A direct thread retrieval mode is faster for agent workflows and avoids extra commands.
|
||||
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@ Core Changes
|
||||
-| 8 | Add direct `--discussion-id` filter to notes/discussions/show | Core | Small |
|
||||
+| 8 | Add direct `--discussion-id` filter + single-thread retrieval mode | Core | Medium |
|
||||
@@ Change 8
|
||||
+lore -J discussions --discussion-id <id> --full-thread
|
||||
+# Returns one discussion with full notes payload (same note schema as show command).
|
||||
```
|
||||
|
||||
10. **Replace ad-hoc AC performance timing with repeatable perf harness**
|
||||
Analysis: `time lore ...` is noisy and machine-dependent. A reproducible seeded benchmark test gives stable guardrails and catches regressions earlier.
|
||||
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@ AC-10: Performance Budget
|
||||
-time lore -J discussions --for-mr <iid> -n 100
|
||||
-# real 0m0.100s (p95 < 150ms)
|
||||
+cargo test --test perf_discussions -- --ignored --nocapture
|
||||
+# Uses seeded fixture DB and N repeated runs; asserts p95 < 150ms for target query shape.
|
||||
```
|
||||
|
||||
If you want, I can also produce a fully merged “iteration 5” rewritten plan document with these edits applied end-to-end so it’s directly executable by an implementation agent.
|
||||
143
docs/plan-expose-discussion-ids.feedback-6.md.bak
Normal file
143
docs/plan-expose-discussion-ids.feedback-6.md.bak
Normal file
@@ -0,0 +1,143 @@
|
||||
Strong plan overall. The biggest gaps I’d fix are around sync-health correctness, idempotency/integrity under repeated ingests, deleted-entity lifecycle, and reducing schema drift risk without heavy reflection machinery.
|
||||
|
||||
I avoided everything in your `## Rejected Recommendations` section.
|
||||
|
||||
**1. Add Sync Health Semantics (not just age)**
|
||||
Time freshness alone can mislead after partial/failed syncs. Agents need to know whether data is both recent and complete.
|
||||
|
||||
```diff
|
||||
@@ ## Freshness Metadata & Staleness Guards (Cross-Cutting, Change A/F/G)
|
||||
- pub freshness_state: String, // "fresh" | "stale" | "unknown"
|
||||
+ pub freshness_state: String, // "fresh" | "stale" | "unknown"
|
||||
+ pub sync_status: String, // "ok" | "partial" | "failed" | "never"
|
||||
+ pub last_successful_sync_run_id: Option<i64>,
|
||||
+ pub last_attempted_sync_run_id: Option<i64>,
|
||||
@@
|
||||
-#[arg(long, help_heading = "Freshness")]
|
||||
-pub require_fresh: Option<String>,
|
||||
+#[arg(long, help_heading = "Freshness")]
|
||||
+pub require_fresh: Option<String>,
|
||||
+#[arg(long, help_heading = "Freshness")]
|
||||
+pub require_sync_ok: bool,
|
||||
```
|
||||
|
||||
Rationale: this prevents false confidence when one project is fresh-by-time but latest sync actually failed or was partial.
|
||||
|
||||
---
|
||||
|
||||
**2. Add `--require-complete` Guard for Missing Required IDs**
|
||||
You already expose `meta.incomplete_rows`; add a hard gate for automation.
|
||||
|
||||
```diff
|
||||
@@ ## Count Semantics (Cross-Cutting Convention)
|
||||
`incomplete_rows` is computed via a dedicated COUNT query...
|
||||
+Add CLI guard:
|
||||
+`--require-complete` fails with exit code 19 when `meta.incomplete_rows > 0`.
|
||||
+Suggested action: `lore sync --full`.
|
||||
```
|
||||
|
||||
Rationale: agents can fail fast instead of silently acting on partial datasets.
|
||||
|
||||
---
|
||||
|
||||
**3. Strengthen Ingestion Idempotency + Referential Integrity for Notes**
|
||||
You added natural-key uniqueness for discussions; do the same for notes and enforce parent integrity at DB level.
|
||||
|
||||
```diff
|
||||
@@ ## Supporting Indexes (Cross-Cutting, Change D)
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_discussions_project_gitlab_discussion_id
|
||||
ON discussions(project_id, gitlab_discussion_id);
|
||||
+CREATE UNIQUE INDEX IF NOT EXISTS idx_notes_project_gitlab_id
|
||||
+ ON notes(project_id, gitlab_id);
|
||||
+
|
||||
+-- Referential integrity
|
||||
+-- notes.discussion_id REFERENCES discussions(id)
|
||||
+-- notes.project_id REFERENCES projects(id)
|
||||
```
|
||||
|
||||
Rationale: repeated syncs and retries won’t duplicate notes, and orphaned rows can’t accumulate.
|
||||
|
||||
---
|
||||
|
||||
**4. Add Deleted/Tombstoned Entity Lifecycle**
|
||||
Current plan excludes null IDs but doesn’t define behavior when GitLab entities are deleted after sync.
|
||||
|
||||
```diff
|
||||
@@ ## Contract Invariants (NEW)
|
||||
+### Deletion Lifecycle Invariant
|
||||
+1. Notes/discussions deleted upstream are tombstoned locally (`deleted_at`), not hard-deleted.
|
||||
+2. All list/show commands exclude tombstoned rows by default.
|
||||
+3. Optional flag `--include-deleted` exposes tombstoned rows for audit/debug.
|
||||
```
|
||||
|
||||
Rationale: preserves auditability, prevents ghost actions on deleted objects, and avoids destructive resync behavior.
|
||||
|
||||
---
|
||||
|
||||
**5. Expand Discussions Payload for Rename Accuracy + Better Triage**
|
||||
`--path-side old` is great, but output currently only returns `position_new_*`.
|
||||
|
||||
```diff
|
||||
@@ ## Change 3: Add Standalone `discussions` List Command
|
||||
pub position_new_path: Option<String>,
|
||||
pub position_new_line: Option<i64>,
|
||||
+ pub position_old_path: Option<String>,
|
||||
+ pub position_old_line: Option<i64>,
|
||||
+ pub last_author: Option<String>,
|
||||
+ pub participant_usernames: Vec<String>,
|
||||
```
|
||||
|
||||
Rationale: for renamed/deleted files, agents need old and new coordinates to act confidently; participants/last_author improve thread routing and prioritization.
|
||||
|
||||
---
|
||||
|
||||
**6. Add SQLite Busy Handling + Retry Policy**
|
||||
Read transactions + concurrent sync writes can still produce `SQLITE_BUSY` under load.
|
||||
|
||||
```diff
|
||||
@@ ## Count Semantics (Cross-Cutting Convention)
|
||||
**Snapshot consistency**: All three queries ... inside a single read transaction ...
|
||||
+**Busy handling**: set `PRAGMA busy_timeout` (e.g. 5000ms) and retry transient
|
||||
+`SQLITE_BUSY` errors up to 3 times with jittered backoff for read commands.
|
||||
```
|
||||
|
||||
Rationale: improves reliability in real multi-agent usage without changing semantics.
|
||||
|
||||
---
|
||||
|
||||
**7. Make Field Definitions Single-Source (Lightweight Drift Prevention)**
|
||||
You rejected full schema generation from code; a lower-cost middle ground is shared field manifests used by both docs and `--fields` validation.
|
||||
|
||||
```diff
|
||||
@@ ## Change 7: Fix Robot-Docs Response Schemas
|
||||
+#### 7h. Single-source field manifests (no reflection)
|
||||
+Define per-command field constants (e.g. `NOTES_FIELDS`, `DISCUSSIONS_FIELDS`)
|
||||
+used by:
|
||||
+1) `--fields` validation/filtering
|
||||
+2) `--fields minimal` expansion
|
||||
+3) `robot-docs` schema rendering
|
||||
```
|
||||
|
||||
Rationale: cuts drift risk materially while staying much simpler than reflection/snapshot infra.
|
||||
|
||||
---
|
||||
|
||||
**8. De-duplicate and Upgrade Test Strategy Around Concurrency**
|
||||
There are duplicated tests across Change 2 and Change 3; add explicit race tests where sync writes happen between list subqueries to prove tx consistency.
|
||||
|
||||
```diff
|
||||
@@ ## Tests
|
||||
-**Test 6**: `--project-id` scopes IID resolution directly
|
||||
-**Test 7**: `--path-side old` matches renamed file discussions
|
||||
-**Test 8**: `--path-side either` matches both old and new paths
|
||||
+Move shared discussion-filter tests to a single section under Change 3.
|
||||
+Add concurrency tests:
|
||||
+1) count/page/incomplete consistency under concurrent sync writes
|
||||
+2) show discussion+notes snapshot consistency under concurrent writes
|
||||
```
|
||||
|
||||
Rationale: less maintenance noise, better coverage of your highest-risk correctness path.
|
||||
|
||||
---
|
||||
|
||||
If you want, I can also produce a single consolidated patch block that rewrites your plan text end-to-end with these edits applied in-place.
|
||||
1907
docs/plan-expose-discussion-ids.md
Normal file
1907
docs/plan-expose-discussion-ids.md
Normal file
File diff suppressed because it is too large
Load Diff
169
docs/plan-surgical-sync.feedback-3.md
Normal file
169
docs/plan-surgical-sync.feedback-3.md
Normal file
@@ -0,0 +1,169 @@
|
||||
Below are the strongest **new** revisions I’d make (excluding everything in your rejected list), with rationale and plan-level diffs.
|
||||
|
||||
### 1. Add a durable run ledger (`sync_runs`) with phase state
|
||||
This makes surgical sync crash-resumable, auditable, and safer under Ctrl+C. Right now `run_id` is mostly ephemeral; persisting phase state removes ambiguity about what completed.
|
||||
|
||||
```diff
|
||||
@@ Design Constraints
|
||||
+9. **Durable run state**: Surgical sync MUST persist a `sync_runs` row keyed by `run_id`
|
||||
+ with phase transitions (`preflight`, `ingest`, `dependents`, `docs`, `embed`, `done`, `failed`).
|
||||
+ This is required for crash recovery, observability, and deterministic retries.
|
||||
|
||||
@@ Step 9: Create `run_sync_surgical`
|
||||
+Before Stage 0, insert `sync_runs(run_id, project_id, mode='surgical', requested_counts, started_at)`.
|
||||
+After each stage, update `sync_runs.phase`, counters, and `last_error` if present.
|
||||
+On success/failure, set terminal state (`done`/`failed`) and `finished_at`.
|
||||
```
|
||||
|
||||
### 2. Add `--preflight-only` (network validation without writes)
|
||||
`--dry-run` is intentionally zero-network, so it cannot validate IIDs. `--preflight-only` is high-value for agents: verifies existence/permissions quickly with no DB mutation.
|
||||
|
||||
```diff
|
||||
@@ CLI Interface
|
||||
lore sync --dry-run --issue 123 -p myproject
|
||||
+lore sync --preflight-only --issue 123 -p myproject
|
||||
|
||||
@@ Step 2: Add `--issue`, `--mr`, `-p` to `SyncArgs`
|
||||
+ /// Validate remote entities and auth without any DB writes
|
||||
+ #[arg(long, default_value_t = false)]
|
||||
+ pub preflight_only: bool,
|
||||
|
||||
@@ Step 10: Add branch in `run_sync`
|
||||
+if options.preflight_only && options.is_surgical() {
|
||||
+ return run_sync_surgical_preflight_only(config, &options, run_id, signal).await;
|
||||
+}
|
||||
```
|
||||
|
||||
### 3. Preflight should aggregate all missing/failed IIDs, not fail-fast
|
||||
Fail-fast causes repeated reruns. Aggregating errors gives one-shot correction and better robot automation.
|
||||
|
||||
```diff
|
||||
@@ Step 7: Create `src/ingestion/surgical.rs`
|
||||
-/// Returns the fetched payloads. If ANY fetch fails, the entire operation should abort.
|
||||
+/// Returns fetched payloads plus per-IID failures; caller aborts writes if failures exist.
|
||||
pub async fn preflight_fetch(...) -> Result<PreflightResult> {
|
||||
|
||||
@@
|
||||
#[derive(Debug, Default)]
|
||||
pub struct PreflightResult {
|
||||
pub issues: Vec<GitLabIssue>,
|
||||
pub merge_requests: Vec<GitLabMergeRequest>,
|
||||
+ pub failures: Vec<EntityFailure>, // stage="fetch"
|
||||
}
|
||||
|
||||
@@ Step 9: Create `run_sync_surgical`
|
||||
-let preflight = preflight_fetch(...).await?;
|
||||
+let preflight = preflight_fetch(...).await?;
|
||||
+if !preflight.failures.is_empty() {
|
||||
+ result.entity_failures = preflight.failures;
|
||||
+ return Err(LoreError::Other("Surgical preflight failed for one or more IIDs".into()).into());
|
||||
+}
|
||||
```
|
||||
|
||||
### 4. Stop filtering scoped queue drains with raw `json_extract` scans
|
||||
`json_extract(payload_json, '$.scope_run_id')` in hot drain queries will degrade as queue grows. Use indexed scope metadata.
|
||||
|
||||
```diff
|
||||
@@ Step 9b: Implement scoped drain helpers
|
||||
-// claim query adds:
|
||||
-// AND json_extract(payload_json, '$.scope_run_id') = ?
|
||||
+// Add migration:
|
||||
+// 1) Add `scope_run_id` generated/stored column derived from payload_json (or explicit column)
|
||||
+// 2) Create index on (project_id, job_type, scope_run_id, status, id)
|
||||
+// Scoped drains filter by indexed `scope_run_id`, not full-table JSON extraction.
|
||||
```
|
||||
|
||||
### 5. Replace `dirty_source_ids` collection-by-query with explicit run scoping
|
||||
Current approach can accidentally include prior dirty rows for same source and can duplicate work. Tag dirty rows with `origin_run_id` and consume by run.
|
||||
|
||||
```diff
|
||||
@@ Design Constraints
|
||||
-2. **Dirty queue scoping**: ... MUST call ... `run_generate_docs_for_dirty_ids`
|
||||
+2. **Dirty queue scoping**: Surgical sync MUST scope docs by `origin_run_id` on `dirty_sources`
|
||||
+ (or equivalent exact run marker) and MUST NOT drain unrelated dirty rows.
|
||||
|
||||
@@ Step 7: `SurgicalIngestResult`
|
||||
- pub dirty_source_ids: Vec<i64>,
|
||||
+ pub origin_run_id: String,
|
||||
|
||||
@@ Step 9a: Implement `run_generate_docs_for_dirty_ids`
|
||||
-pub fn run_generate_docs_for_dirty_ids(config: &Config, dirty_source_ids: &[i64]) -> Result<...>
|
||||
+pub fn run_generate_docs_for_run_id(config: &Config, run_id: &str) -> Result<...>
|
||||
```
|
||||
|
||||
### 6. Enforce transaction safety at the type boundary
|
||||
`unchecked_transaction()` + `&Connection` signatures is fragile. Accept `&Transaction` for ingest internals and use `TransactionBehavior::Immediate` for deterministic lock behavior.
|
||||
|
||||
```diff
|
||||
@@ Step 7: Create `src/ingestion/surgical.rs`
|
||||
-pub fn ingest_issue_by_iid_from_payload(conn: &Connection, ...)
|
||||
+pub fn ingest_issue_by_iid_from_payload(tx: &rusqlite::Transaction<'_>, ...)
|
||||
|
||||
-pub fn ingest_mr_by_iid_from_payload(conn: &Connection, ...)
|
||||
+pub fn ingest_mr_by_iid_from_payload(tx: &rusqlite::Transaction<'_>, ...)
|
||||
|
||||
-let tx = conn.unchecked_transaction()?;
|
||||
+let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
|
||||
```
|
||||
|
||||
### 7. Acquire sync lock only for mutation phases, not remote preflight
|
||||
This materially reduces lock contention and keeps normal sync throughput higher, while still guaranteeing mutation serialization.
|
||||
|
||||
```diff
|
||||
@@ Design Constraints
|
||||
+10. **Lock window minimization**: Preflight fetch runs without sync lock; lock is acquired immediately
|
||||
+ before first DB mutation and held through all mutation stages.
|
||||
|
||||
@@ Step 9: Create `run_sync_surgical`
|
||||
-// ── Acquire sync lock ──
|
||||
-...
|
||||
-// ── Stage 0: Preflight fetch ──
|
||||
+// ── Stage 0: Preflight fetch (no lock, no writes) ──
|
||||
...
|
||||
+// ── Acquire sync lock just before Stage 1 mutation ──
|
||||
```
|
||||
|
||||
### 8. Add explicit transient retry policy beyond 429
|
||||
Client already handles rate limits; surgical reliability improves a lot if 5xx/timeouts are retried with bounded backoff.
|
||||
|
||||
```diff
|
||||
@@ Design Constraints
|
||||
+11. **Transient retry policy**: Preflight and dependent remote fetches MUST retry boundedly on
|
||||
+ timeout/5xx with jittered backoff; permanent errors (404/401/403) fail immediately.
|
||||
|
||||
@@ Step 5: Add `get_issue_by_iid` / `get_mr_by_iid`
|
||||
+Document retry behavior for transient transport/server failures.
|
||||
```
|
||||
|
||||
### 9. Tighten automated tests around scoping invariants
|
||||
You already list manual checks; these should be enforced in unit/integration tests to prevent regressions.
|
||||
|
||||
```diff
|
||||
@@ Step 1: TDD — Write Failing Tests First
|
||||
+### 1d. New invariants tests
|
||||
+- `surgical_docs_scope_ignores_preexisting_dirty_rows`
|
||||
+- `scoped_queue_drain_ignores_orphaned_jobs`
|
||||
+- `preflight_aggregates_multiple_missing_iids`
|
||||
+- `preflight_only_performs_zero_writes`
|
||||
+- `dry_run_performs_zero_network_calls`
|
||||
+- `lock_window_does_not_block_during_preflight`
|
||||
|
||||
@@ Acceptance Criteria
|
||||
+32. Scoped queue/docs invariants are covered by automated tests (not manual-only verification).
|
||||
```
|
||||
|
||||
### 10. Make robot-mode surgical output first-class
|
||||
For agent workflows, include full stage telemetry and actionable recovery commands.
|
||||
|
||||
```diff
|
||||
@@ Step 15: Update `SyncResult` for robot mode structured output
|
||||
+ /// Per-stage elapsed ms for deterministic performance tracking
|
||||
+ pub stage_timings_ms: std::collections::BTreeMap<String, u64>,
|
||||
+ /// Suggested recovery commands (robot ergonomics)
|
||||
+ pub recovery_actions: Vec<String>,
|
||||
|
||||
@@ Step 14: Update `robot-docs` manifest
|
||||
+Document surgical-specific error codes and `actions` schema for automated recovery.
|
||||
```
|
||||
|
||||
If you want, I can now produce a fully rewritten **iteration 3** plan that merges these into your current structure end-to-end.
|
||||
212
docs/plan-surgical-sync.feedback-4.md
Normal file
212
docs/plan-surgical-sync.feedback-4.md
Normal file
@@ -0,0 +1,212 @@
|
||||
1. **Resolve the current contract contradictions (`preflight-only`, `dry-run`, `sync_runs`)**
|
||||
|
||||
Why this improves the plan:
|
||||
- Right now constraints conflict: “zero DB writes before commit” vs inserting `sync_runs` during preflight.
|
||||
- This ambiguity will cause implementation drift and flaky acceptance tests.
|
||||
- Splitting control-plane writes from content-plane writes keeps safety guarantees strict while preserving observability.
|
||||
|
||||
```diff
|
||||
@@ ## Design Constraints
|
||||
-6. **Preflight-then-commit**: All remote fetches happen BEFORE any DB writes. If any IID fetch fails (404, network error), the entire operation aborts with zero DB mutations.
|
||||
+6. **Preflight-then-commit (content-plane)**: All remote fetches happen BEFORE any writes to content tables (`issues`, `merge_requests`, `discussions`, `resource_events`, `documents`, `embeddings`).
|
||||
+7. **Control-plane exception**: `sync_runs` / `sync_run_entities` writes are allowed during preflight for observability and crash diagnostics.
|
||||
@@
|
||||
-11. **Preflight-only mode**: `--preflight-only` validates remote entity existence and permissions with zero DB writes.
|
||||
+11. **Preflight-only mode**: `--preflight-only` performs zero content writes; control-plane run-ledger writes are allowed.
|
||||
@@ ### For me to evaluate (functional):
|
||||
-24. **Preflight-only mode** ... no DB mutations beyond the sync_runs ledger entry
|
||||
+24. **Preflight-only mode** ... no content DB mutations; only run-ledger rows may be written
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
2. **Add stale-write protection to avoid TOCTOU regressions during unlocked preflight**
|
||||
|
||||
Why this improves the plan:
|
||||
- You intentionally preflight without lock; that’s good for throughput but introduces race risk.
|
||||
- Without a guard, a slower surgical run can overwrite newer data ingested by a concurrent normal sync.
|
||||
- This is a correctness bug under contention, not a nice-to-have.
|
||||
|
||||
```diff
|
||||
@@ ## Design Constraints
|
||||
+12. **Stale-write protection**: Surgical ingest MUST NOT overwrite fresher local rows. If local `updated_at` is newer than the preflight payload’s `updated_at`, skip that entity and record `skipped_stale`.
|
||||
@@ ## Step 7: Create `src/ingestion/surgical.rs`
|
||||
- let labels_created = process_single_issue(conn, config, project_id, issue)?;
|
||||
+ // Skip stale payloads to avoid TOCTOU overwrite after unlocked preflight.
|
||||
+ if is_local_newer_issue(conn, project_id, issue.iid, issue.updated_at)? {
|
||||
+ result.skipped_stale += 1;
|
||||
+ return Ok(result);
|
||||
+ }
|
||||
+ let labels_created = process_single_issue(conn, config, project_id, issue)?;
|
||||
@@
|
||||
+// same guard for MR path
|
||||
@@ ## Step 15: Update `SyncResult`
|
||||
+ /// Entities skipped because local row was newer than preflight payload
|
||||
+ pub skipped_stale: usize,
|
||||
@@ ### Edge cases to verify:
|
||||
+38. **TOCTOU safety**: if a normal sync updates entity after preflight but before ingest, surgical run skips stale payload (no overwrite)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
3. **Make dirty-source scoping exact (do not capture pre-existing rows for same entity)**
|
||||
|
||||
Why this improves the plan:
|
||||
- Current “query dirty rows by `source_id` after ingest” can accidentally include older dirty rows for the same entity.
|
||||
- That silently violates strict run scoping and can delete unrelated backlog rows.
|
||||
- You can fix this without adding `origin_run_id` to `dirty_sources` (which you already rejected).
|
||||
|
||||
```diff
|
||||
@@ ## Step 7: Create `src/ingestion/surgical.rs`
|
||||
- // Collect dirty_source rows for this entity
|
||||
- let mut stmt = conn.prepare(
|
||||
- "SELECT id FROM dirty_sources WHERE source_type = 'issue' AND source_id = ?1"
|
||||
- )?;
|
||||
+ // Capture only rows inserted by THIS call using high-water mark.
|
||||
+ let before_dirty_id: i64 = conn.query_row(
|
||||
+ "SELECT COALESCE(MAX(id), 0) FROM dirty_sources",
|
||||
+ [], |r| r.get(0),
|
||||
+ )?;
|
||||
+ // ... call process_single_issue ...
|
||||
+ let mut stmt = conn.prepare(
|
||||
+ "SELECT id FROM dirty_sources
|
||||
+ WHERE id > ?1 AND source_type = 'issue' AND source_id = ?2"
|
||||
+ )?;
|
||||
@@
|
||||
+ // same pattern for MR
|
||||
@@ ### 1d. Scoping invariant tests
|
||||
+#[test]
|
||||
+fn surgical_docs_scope_ignores_preexisting_dirty_rows_for_same_entity() {
|
||||
+ // pre-insert dirty row for iid=7, then surgical ingest iid=7
|
||||
+ // assert result.dirty_source_ids only contains newly inserted rows
|
||||
+}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
4. **Fix embed-stage leakage when `--no-docs` is used in surgical mode**
|
||||
|
||||
Why this improves the plan:
|
||||
- Current design can run global embed even when docs stage is skipped, which may embed unrelated backlog docs.
|
||||
- That breaks the surgical “scope only this run” promise.
|
||||
- This is both correctness and operator-trust critical.
|
||||
|
||||
```diff
|
||||
@@ ## Step 9: Create `run_sync_surgical`
|
||||
- if !options.no_embed {
|
||||
+ // Surgical embed only runs when surgical docs actually regenerated docs in this run.
|
||||
+ if !options.no_embed && !options.no_docs && result.documents_regenerated > 0 {
|
||||
@@ ## Step 4: Wire new fields in `handle_sync_cmd`
|
||||
+ if options.is_surgical() && options.no_docs && !options.no_embed {
|
||||
+ return Err(Box::new(LoreError::Other(
|
||||
+ "In surgical mode, --no-docs requires --no-embed (to preserve scoping guarantees)".to_string()
|
||||
+ )));
|
||||
+ }
|
||||
@@ ### For me to evaluate
|
||||
+39. **No embed leakage**: `sync --issue X --no-docs` never embeds unrelated unembedded docs
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
5. **Add queue-failure hygiene so scoped jobs do not leak forever**
|
||||
|
||||
Why this improves the plan:
|
||||
- Scoped drains prevent accidental processing, but failed runs can strand pending jobs permanently.
|
||||
- You need explicit terminalization (`aborted`) and optional replay mechanics.
|
||||
- Otherwise queue bloat and confusing diagnostics accumulate.
|
||||
|
||||
```diff
|
||||
@@ ## Step 8a: Add `sync_runs` table migration
|
||||
+ALTER TABLE dependent_queue ADD COLUMN aborted_reason TEXT;
|
||||
+-- status domain now includes: pending, claimed, done, failed, aborted
|
||||
@@ ## Step 9: run_sync_surgical failure paths
|
||||
+// On run failure/cancel:
|
||||
+conn.execute(
|
||||
+ "UPDATE dependent_queue
|
||||
+ SET status='aborted', aborted_reason=?1
|
||||
+ WHERE project_id=?2 AND scope_run_id=?3 AND status='pending'",
|
||||
+ rusqlite::params![failure_summary, project_id, run_id],
|
||||
+)?;
|
||||
@@ ## Acceptance Criteria
|
||||
+40. **No stranded scoped jobs**: failed surgical runs leave no `pending` rows for their `scope_run_id`
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
6. **Persist per-entity lifecycle (`sync_run_entities`) for real observability and deterministic retry**
|
||||
|
||||
Why this improves the plan:
|
||||
- `sync_runs` alone gives aggregate counters but not which IID failed at which stage.
|
||||
- Per-entity records make retries deterministic and robot output far more useful.
|
||||
- This is the missing piece for your stated “deterministic retry decisions.”
|
||||
|
||||
```diff
|
||||
@@ ## Step 8a: Add `sync_runs` table migration
|
||||
+CREATE TABLE IF NOT EXISTS sync_run_entities (
|
||||
+ id INTEGER PRIMARY KEY,
|
||||
+ run_id TEXT NOT NULL REFERENCES sync_runs(run_id),
|
||||
+ entity_type TEXT NOT NULL CHECK(entity_type IN ('issue','merge_request')),
|
||||
+ iid INTEGER NOT NULL,
|
||||
+ stage TEXT NOT NULL,
|
||||
+ status TEXT NOT NULL CHECK(status IN ('ok','failed','skipped_stale')),
|
||||
+ error_code TEXT,
|
||||
+ error_message TEXT,
|
||||
+ updated_at INTEGER NOT NULL
|
||||
+);
|
||||
+CREATE INDEX IF NOT EXISTS idx_sync_run_entities_run ON sync_run_entities(run_id, entity_type, iid);
|
||||
@@ ## Step 15: Update `SyncResult`
|
||||
+ pub failed_iids: Vec<(String, u64)>,
|
||||
+ pub skipped_stale_iids: Vec<(String, u64)>,
|
||||
@@ ## CLI Interface
|
||||
+lore --robot sync-runs --run-id <id>
|
||||
+lore --robot sync-runs --run-id <id> --retry-failed
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
7. **Use explicit error type for surgical preflight failures (not `LoreError::Other`)**
|
||||
|
||||
Why this improves the plan:
|
||||
- `Other(String)` loses machine semantics, weakens robot mode, and leads to bad exit-code behavior.
|
||||
- A typed error preserves structured failures and enables actionable recovery commands.
|
||||
|
||||
```diff
|
||||
@@ ## Step 9: run_sync_surgical
|
||||
- return Err(LoreError::Other(
|
||||
- format!("Surgical preflight failed for {} of {} IIDs: {}", ...)
|
||||
- ).into());
|
||||
+ return Err(LoreError::SurgicalPreflightFailed {
|
||||
+ run_id: run_id.to_string(),
|
||||
+ total: total_items,
|
||||
+ failures: preflight.failures.clone(),
|
||||
+ }.into());
|
||||
@@ ## Step 15: Update `SyncResult`
|
||||
+ /// Machine-actionable error summary for robot mode
|
||||
+ pub error_code: Option<String>,
|
||||
@@ ## Acceptance Criteria
|
||||
+41. **Typed failure**: preflight failures serialize structured errors (not generic `Other`) with machine-usable codes/actions
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
8. **Strengthen tests for rollback, contention, and stale-skip guarantees**
|
||||
|
||||
Why this improves the plan:
|
||||
- Current tests cover many happy-paths and scoping invariants, but key race/rollback behaviors are still under-tested.
|
||||
- These are exactly where regressions will appear first in production.
|
||||
|
||||
```diff
|
||||
@@ ## Step 1: TDD — Write Failing Tests First
|
||||
+### 1f. Transactional rollback + TOCTOU tests
|
||||
+1. `preflight_success_then_ingest_failure_rolls_back_all_content_writes`
|
||||
+2. `stale_payload_is_skipped_when_local_updated_at_is_newer`
|
||||
+3. `failed_run_aborts_pending_scoped_jobs`
|
||||
+4. `surgical_no_docs_requires_no_embed`
|
||||
@@ ### Automated scoping invariants
|
||||
-38. **Scoped queue/docs invariants are enforced by automated tests**
|
||||
+42. **Rollback and race invariants are enforced by automated tests** (no partial writes on ingest failure, no stale overwrite)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
These eight revisions keep your core approach intact, avoid your explicitly rejected ideas, and close the biggest correctness/operability gaps before implementation.
|
||||
130
docs/plan-surgical-sync.feedback-5.md
Normal file
130
docs/plan-surgical-sync.feedback-5.md
Normal file
@@ -0,0 +1,130 @@
|
||||
**Critical Gaps In Current Plan**
|
||||
1. `dirty_sources` scoping is based on `id`, but `dirty_sources` has no `id` column and uses `(source_type, source_id)` UPSERT semantics.
|
||||
2. Plan assumes a new `dependent_queue` with `status`, but current code uses `pending_dependent_fetches` (delete-on-complete), so queue-scoping design conflicts with existing invariants.
|
||||
3. Constraint 6 says all remote fetches happen before any content writes, but the proposed surgical flow fetches discussions/events/diffs after ingest writes.
|
||||
4. `sync_runs` is already an existing table and already used by `SyncRunRecorder`; the plan currently treats it like a new table.
|
||||
|
||||
**Best Revisions**
|
||||
|
||||
1. **Fix dirty-source scoping to match real schema (queued-at watermark, not `id` high-water).**
|
||||
Why this is better: This removes a correctness bug and makes same-entity re-ingest deterministic under UPSERT behavior.
|
||||
|
||||
```diff
|
||||
@@ Design Constraints
|
||||
-2. Dirty queue scoping: ... capture MAX(id) FROM dirty_sources ... run_generate_docs_for_dirty_ids ...
|
||||
+2. Dirty queue scoping: `dirty_sources` is keyed by `(source_type, source_id)` and updated via UPSERT.
|
||||
+ Surgical scoping MUST use:
|
||||
+ 1) a run-level `run_dirty_floor_ms` captured before surgical ingest, and
|
||||
+ 2) explicit touched source keys from ingest (`(source_type, source_id)`).
|
||||
+ Surgical docs MUST call a scoped API (e.g. `run_generate_docs_for_sources`) and MUST NOT drain global dirty queue.
|
||||
@@ Step 9a
|
||||
-pub fn run_generate_docs_for_dirty_ids(config: &Config, dirty_source_ids: &[i64]) -> Result<GenerateDocsResult>
|
||||
+pub fn run_generate_docs_for_sources(config: &Config, sources: &[(SourceType, i64)]) -> Result<GenerateDocsResult>
|
||||
```
|
||||
|
||||
2. **Bypass shared dependent queue in surgical mode; run dependents inline per target.**
|
||||
Why this is better: Avoids queue migration churn, avoids run-scope conflicts with existing unique constraints, and removes orphan-job hygiene complexity entirely.
|
||||
|
||||
```diff
|
||||
@@ Design Constraints
|
||||
-4. Dependent queue scoping: ... scope_run_id indexed column on dependent_queue ...
|
||||
+4. Surgical dependent execution: surgical mode MUST bypass `pending_dependent_fetches`.
|
||||
+ Dependents (resource_events, mr_closes_issues, mr_diffs) run inline for targeted entities only.
|
||||
+ Global queue remains for normal sync only.
|
||||
@@ Design Constraints
|
||||
-14. Queue failure hygiene: ... pending scoped jobs ... terminalized to aborted ...
|
||||
+14. Surgical failure hygiene: surgical mode MUST leave no queue artifacts because it does not enqueue dependent jobs.
|
||||
@@ Step 9b / 9c / Step 13
|
||||
-Implement scoped drain helpers and enqueue_job scope_run_id plumbing
|
||||
+Replace with direct per-entity helpers in ingestion layer:
|
||||
+ - sync_issue_resource_events_direct(...)
|
||||
+ - sync_mr_resource_events_direct(...)
|
||||
+ - sync_mr_closes_issues_direct(...)
|
||||
+ - sync_mr_diffs_direct(...)
|
||||
```
|
||||
|
||||
3. **Clarify atomicity contract to “primary-entity atomicity” (remove contradiction).**
|
||||
Why this is better: Keeps strong zero-write guarantees for missing IIDs while matching practical staged pipeline behavior.
|
||||
|
||||
```diff
|
||||
@@ Design Constraints
|
||||
-6. Preflight-then-commit (content-plane): All remote fetches happen BEFORE any writes to content tables ...
|
||||
+6. Primary-entity atomicity: all requested issue/MR payload fetches complete before first content write.
|
||||
+ If any primary IID fetch fails, primary ingest does zero content writes.
|
||||
+ Dependent stages (discussions/events/diffs/closes) are post-ingest and best-effort, with structured per-stage failure reporting.
|
||||
```
|
||||
|
||||
4. **Extend existing `sync_runs` schema instead of redefining it.**
|
||||
Why this is better: Preserves compatibility with current `SyncRunRecorder`, `sync_status`, and existing historical data.
|
||||
|
||||
```diff
|
||||
@@ Step 8a
|
||||
-Add `sync_runs` table migration (CREATE TABLE sync_runs ...)
|
||||
+Add migration 027 to extend existing `sync_runs` table:
|
||||
+ - ADD COLUMN mode TEXT NULL -- 'standard' | 'surgical'
|
||||
+ - ADD COLUMN phase TEXT NULL -- preflight|ingest|dependents|docs|embed|done|failed
|
||||
+ - ADD COLUMN surgical_summary_json TEXT NULL
|
||||
+Reuse `SyncRunRecorder` row lifecycle; do not introduce a parallel run-ledger model.
|
||||
```
|
||||
|
||||
5. **Strengthen TOCTOU stale protection for equal timestamps.**
|
||||
Why this is better: Prevents regressions when `updated_at` is equal but a fresher local fetch already happened.
|
||||
|
||||
```diff
|
||||
@@ Design Constraints
|
||||
-13. ... If local `updated_at` is newer than preflight payload `updated_at`, skip ...
|
||||
+13. ... Skip stale when:
|
||||
+ a) local.updated_at > payload.updated_at, OR
|
||||
+ b) local.updated_at == payload.updated_at AND local.last_seen_at > preflight_started_at_ms.
|
||||
+ This prevents equal-timestamp regressions under concurrent sync.
|
||||
@@ Step 1f tests
|
||||
+Add test: `equal_updated_at_but_newer_last_seen_is_skipped`.
|
||||
```
|
||||
|
||||
6. **Shrink lock window further: release `sync` lock before embed; use dedicated embed lock.**
|
||||
Why this is better: Prevents long embedding from blocking unrelated syncs and avoids concurrent embed writers.
|
||||
|
||||
```diff
|
||||
@@ Design Constraints
|
||||
-11. Lock ... held through all mutation stages.
|
||||
+11. Lock ... held through ingest/dependents/docs only.
|
||||
+ Release `AppLock("sync")` before embed.
|
||||
+ Embed stage uses `AppLock("embed")` for single-flight embedding writes.
|
||||
@@ Step 9
|
||||
-Embed runs inside the same sync lock window
|
||||
+Embed runs after sync lock release, under dedicated embed lock
|
||||
```
|
||||
|
||||
7. **Add the missing `sync-runs` robot read path (the plan references it but doesn’t define it).**
|
||||
Why this is better: Makes durable run-state actually useful for recovery automation and observability.
|
||||
|
||||
```diff
|
||||
@@ Step 14 (new)
|
||||
+## Step 14a: Add `sync-runs` read command
|
||||
+
|
||||
+CLI:
|
||||
+ lore --robot sync-runs --limit 20
|
||||
+ lore --robot sync-runs --run-id <id>
|
||||
+ lore --robot sync-runs --state failed
|
||||
+
|
||||
+Robot response fields:
|
||||
+ run_id, mode, phase, status, started_at, finished_at, counters, failures, suggested_retry_command
|
||||
```
|
||||
|
||||
8. **Add URL-native surgical targets (`--issue-url`, `--mr-url`) with project inference.**
|
||||
Why this is better: Much more agent-friendly and reduces project-resolution errors from copy/paste workflows.
|
||||
|
||||
```diff
|
||||
@@ CLI Interface
|
||||
lore sync --issue 123 --issue 456 -p myproject
|
||||
+lore sync --issue-url https://gitlab.example.com/group/proj/-/issues/123
|
||||
+lore sync --mr-url https://gitlab.example.com/group/proj/-/merge_requests/789
|
||||
@@ Step 2
|
||||
+Add repeatable flags:
|
||||
+ --issue-url <url>
|
||||
+ --mr-url <url>
|
||||
+Parse URL into (project_path, iid). If all targets are URL-derived and same project, `-p` is optional.
|
||||
+If mixed projects are provided in one command, reject with clear error.
|
||||
```
|
||||
|
||||
If you want, I can produce a single consolidated patched version of your plan (iteration 5 draft) with these revisions already merged.
|
||||
152
docs/plan-surgical-sync.feedback-6.md
Normal file
152
docs/plan-surgical-sync.feedback-6.md
Normal file
@@ -0,0 +1,152 @@
|
||||
Highest-impact revisions after reviewing your v5 plan:
|
||||
|
||||
1. **Fix a real scoping hole: embed can still process unrelated docs**
|
||||
Rationale: Current plan assumes scoped docs implies scoped embed, but that only holds while no other run creates unembedded docs. You explicitly release sync lock before embed, so another sync can enqueue/regenerate docs in between, and `run_embed` may embed unrelated backlog. This breaks surgical isolation and can hide backlog debt.
|
||||
```diff
|
||||
diff --git a/plan.md b/plan.md
|
||||
@@ Design Constraints
|
||||
-3. Embed scoping: Embedding runs only for documents regenerated by this surgical run. Because `run_embed` processes only unembedded docs, scoping is automatic IF docs are scoped correctly...
|
||||
+3. Embed scoping: Embedding MUST be explicitly scoped to documents regenerated by this surgical run.
|
||||
+ `run_generate_docs_for_sources` returns regenerated `document_ids`; surgical mode calls
|
||||
+ `run_embed_for_document_ids(document_ids)` and never global `run_embed`.
|
||||
+ This remains true even after lock release and under concurrent normal sync activity.
|
||||
@@ Step 9a: Implement `run_generate_docs_for_sources`
|
||||
-pub fn run_generate_docs_for_sources(...) -> Result<GenerateDocsResult> {
|
||||
+pub fn run_generate_docs_for_sources(...) -> Result<GenerateDocsResult> {
|
||||
+ // Return regenerated document IDs for scoped embedding.
|
||||
+ // GenerateDocsResult { regenerated, errored, regenerated_document_ids: Vec<i64> }
|
||||
@@ Step 9: Embed stage
|
||||
- match run_embed(config, false, false, None, signal).await {
|
||||
+ match run_embed_for_document_ids(config, &result.regenerated_document_ids, signal).await {
|
||||
```
|
||||
|
||||
2. **Make run-ledger lifecycle actually durable (and consistent with your own constraint 10)**
|
||||
Rationale: Plan text says “reuse `SyncRunRecorder`”, but Step 9 writes raw SQL directly. That creates lifecycle drift, missing heartbeats, and inconsistent failure handling as code evolves.
|
||||
```diff
|
||||
diff --git a/plan.md b/plan.md
|
||||
@@ Design Constraints
|
||||
-10. Durable run state: ... Reuses `SyncRunRecorder` row lifecycle ...
|
||||
+10. Durable run state: surgical sync MUST use `SyncRunRecorder` end-to-end (no ad-hoc SQL updates).
|
||||
+ Add recorder APIs for `set_mode`, `set_phase`, `set_counters`, `finish_succeeded`,
|
||||
+ `finish_failed`, `finish_cancelled`, and periodic `heartbeat`.
|
||||
@@ Step 9: Create `run_sync_surgical`
|
||||
- conn.execute("INSERT INTO sync_runs ...")
|
||||
- conn.execute("UPDATE sync_runs SET phase = ...")
|
||||
+ let mut recorder = SyncRunRecorder::start_surgical(...)?;
|
||||
+ recorder.set_phase("preflight")?;
|
||||
+ recorder.heartbeat_if_due()?;
|
||||
+ recorder.set_phase("ingest")?;
|
||||
+ ...
|
||||
+ recorder.finish_succeeded_with_warnings(...)?;
|
||||
```
|
||||
|
||||
3. **Add explicit `cancelled` terminal state**
|
||||
Rationale: Current early cancellation branches return `Ok(result)` without guaranteed run-row finalization. That leaves misleading `running` rows and weak crash diagnostics.
|
||||
```diff
|
||||
diff --git a/plan.md b/plan.md
|
||||
@@ Design Constraints
|
||||
+15. Cancellation semantics: If shutdown is observed after run start, phase is set to `cancelled`,
|
||||
+ status is `cancelled`, `finished_at` is written, and lock is released before return.
|
||||
@@ Step 8a migration
|
||||
+ALTER TABLE sync_runs ADD COLUMN warnings_count INTEGER NOT NULL DEFAULT 0;
|
||||
+ALTER TABLE sync_runs ADD COLUMN cancelled_at INTEGER;
|
||||
@@ Acceptance Criteria
|
||||
+47. Cancellation durability: Ctrl+C during surgical sync records `status='cancelled'`,
|
||||
+ `phase='cancelled'`, and `finished_at` in `sync_runs`.
|
||||
```
|
||||
|
||||
4. **Reduce lock contention further by separating dependent fetch and dependent write**
|
||||
Rationale: You currently hold lock through network-heavy dependent stages. That maximizes contention and increases lock timeout risk. Better: fetch dependents unlocked, write in short locked transactions with per-entity freshness guards.
|
||||
```diff
|
||||
diff --git a/plan.md b/plan.md
|
||||
@@ Design Constraints
|
||||
-11. Lock window minimization: ... held through ingest, dependents, and docs stages.
|
||||
+11. Lock window minimization: lock is held only for DB mutation windows.
|
||||
+ Dependents run in two phases:
|
||||
+ (a) fetch from GitLab without lock,
|
||||
+ (b) write results under lock in short transactions.
|
||||
+ Apply per-entity freshness checks before dependent writes.
|
||||
@@ Step 9: Dependent stages
|
||||
- // All dependents run INLINE per-entity ... while lock is held
|
||||
+ // Dependents fetch outside lock, then write under lock with CAS-style watermark guards.
|
||||
```
|
||||
|
||||
5. **Introduce stage timeout budgets to prevent hung surgical runs**
|
||||
Rationale: A single slow GitLab endpoint can stall the whole run and hold resources too long. Timeout budgets plus per-entity failure recording keep the run bounded and predictable.
|
||||
```diff
|
||||
diff --git a/plan.md b/plan.md
|
||||
@@ Design Constraints
|
||||
+16. Stage timeout budgets: each dependent fetch has a per-entity timeout and a global stage budget.
|
||||
+ Timed-out entities are recorded in `entity_failures` with code `TIMEOUT` and run continues best-effort.
|
||||
@@ Step 9 notes
|
||||
+ - Wrap dependent network calls with `tokio::time::timeout`.
|
||||
+ - Add config knobs:
|
||||
+ `sync.surgical_entity_timeout_seconds` (default 20),
|
||||
+ `sync.surgical_dependents_budget_seconds` (default 120).
|
||||
```
|
||||
|
||||
6. **Add payload integrity checks (project mismatch hard-fail)**
|
||||
Rationale: Surgical mode is precision tooling. If API/proxy misconfiguration returns payloads from wrong project, you should fail preflight loudly, not trust downstream assumptions.
|
||||
```diff
|
||||
diff --git a/plan.md b/plan.md
|
||||
@@ Step 7: preflight_fetch
|
||||
+ // Integrity check: payload.project_id must equal requested gitlab_project_id.
|
||||
+ // On mismatch, record EntityFailure { code: "PROJECT_MISMATCH", stage: "fetch" }.
|
||||
@@ Step 9d: error codes
|
||||
+PROJECT_MISMATCH -> usage/config data integrity failure (typed, machine-readable)
|
||||
@@ Acceptance Criteria
|
||||
+48. Project integrity: payloads with unexpected `project_id` are rejected in preflight
|
||||
+ and produce zero content writes.
|
||||
```
|
||||
|
||||
7. **Upgrade robot output from aggregate-only to per-entity lifecycle**
|
||||
Rationale: `entity_failures` alone is not enough for robust automation. Agents need a complete entity outcome map (fetched, ingested, stale-skipped, dependent failures) to retry deterministically.
|
||||
```diff
|
||||
diff --git a/plan.md b/plan.md
|
||||
@@ Step 15: Update `SyncResult`
|
||||
+pub struct EntityOutcome {
|
||||
+ pub entity_type: String,
|
||||
+ pub iid: u64,
|
||||
+ pub fetched: bool,
|
||||
+ pub ingested: bool,
|
||||
+ pub stale_skipped: bool,
|
||||
+ pub dependent_failures: Vec<EntityFailure>,
|
||||
+}
|
||||
@@
|
||||
+pub entity_outcomes: Vec<EntityOutcome>,
|
||||
+pub completion_status: String, // succeeded | succeeded_with_warnings | failed | cancelled
|
||||
@@ Robot mode
|
||||
- enables agents to detect partial failures via `entity_failures`
|
||||
+ enables deterministic, per-IID retry and richer UI messaging.
|
||||
```
|
||||
|
||||
8. **Index `sync_runs` for real observability at scale**
|
||||
Rationale: You’re adding mode/phase/counters and then querying recent surgical runs. Without indexes, this degrades as run history grows.
|
||||
```diff
|
||||
diff --git a/plan.md b/plan.md
|
||||
@@ Step 8a migration
|
||||
+CREATE INDEX IF NOT EXISTS idx_sync_runs_mode_started
|
||||
+ ON sync_runs(mode, started_at DESC);
|
||||
+CREATE INDEX IF NOT EXISTS idx_sync_runs_status_phase_started
|
||||
+ ON sync_runs(status, phase, started_at DESC);
|
||||
```
|
||||
|
||||
9. **Add tests specifically for the new failure-prone paths**
|
||||
Rationale: Current tests are strong on ingest and scoping, but still miss new high-risk runtime behavior (cancel state, timeout handling, scoped embed under concurrency).
|
||||
```diff
|
||||
diff --git a/plan.md b/plan.md
|
||||
@@ Step 1f tests
|
||||
+#[tokio::test]
|
||||
+async fn cancellation_marks_sync_run_cancelled() { ... }
|
||||
+
|
||||
+#[tokio::test]
|
||||
+async fn dependent_timeout_records_entity_failure_and_continues() { ... }
|
||||
+
|
||||
+#[tokio::test]
|
||||
+async fn scoped_embed_does_not_embed_unrelated_docs_created_after_docs_stage() { ... }
|
||||
@@ Acceptance Criteria
|
||||
+49. Scoped embed isolation under concurrency is verified by automated test.
|
||||
+50. Timeout path is verified (TIMEOUT code + continued processing).
|
||||
```
|
||||
|
||||
These revisions keep your core direction intact, avoid every rejected recommendation, and materially improve correctness under concurrency, operational observability, and agent automation quality.
|
||||
2240
docs/plan-surgical-sync.md
Normal file
2240
docs/plan-surgical-sync.md
Normal file
File diff suppressed because it is too large
Load Diff
131
docs/prd-per-note-search.feedback-6.md
Normal file
131
docs/prd-per-note-search.feedback-6.md
Normal file
@@ -0,0 +1,131 @@
|
||||
1. **Make immutable identity usable now (`--author-id`)**
|
||||
Why: The plan captures `author_id` but intentionally defers using it, so the core longitudinal-analysis problem is only half-fixed.
|
||||
|
||||
```diff
|
||||
@@ Phase 1: `lore notes` Command / Work Chunk 1A
|
||||
pub struct NoteListFilters<'a> {
|
||||
+ pub author_id: Option<i64>, // immutable identity filter
|
||||
@@
|
||||
- pub author: Option<&'a str>, // case-insensitive match via COLLATE NOCASE
|
||||
+ pub author: Option<&'a str>, // display-name filter
|
||||
+ // If both author and author_id are provided, apply both (AND) for precision.
|
||||
}
|
||||
@@
|
||||
Filter mappings:
|
||||
+ - `author_id`: `n.author_id = ?` (exact immutable identity)
|
||||
- `author`: strip `@` prefix, `n.author_username = ? COLLATE NOCASE`
|
||||
@@ Phase 1 / Work Chunk 1B (CLI)
|
||||
+ /// Filter by immutable author id
|
||||
+ #[arg(long = "author-id", help_heading = "Filters")]
|
||||
+ pub author_id: Option<i64>,
|
||||
@@ Phase 2 / Work Chunk 2F
|
||||
+ Add `--author-id` support to `lore search` filtering for note documents.
|
||||
@@ Phase 1 / Work Chunk 1E
|
||||
+ CREATE INDEX IF NOT EXISTS idx_notes_project_author_id_created
|
||||
+ ON notes(project_id, author_id, created_at DESC, id DESC)
|
||||
+ WHERE is_system = 0 AND author_id IS NOT NULL;
|
||||
```
|
||||
|
||||
2. **Fix document staleness on username changes**
|
||||
Why: Current plan says username changes are “not semantic,” but note documents include username in content/title, so docs go stale/inconsistent.
|
||||
|
||||
```diff
|
||||
@@ Work Chunk 0D: Immutable Author Identity Capture
|
||||
- Assert: changed_semantics = false (username change is not a semantic change for documents)
|
||||
+ Assert: changed_semantics = true (username affects note document content/title)
|
||||
@@ Work Chunk 0A: semantic-change detection
|
||||
- old_body != body || old_note_type != note_type || ...
|
||||
+ old_body != body || old_note_type != note_type || ...
|
||||
+ || old_author_username != author_username
|
||||
@@ Work Chunk 2C: Note Document Extractor header
|
||||
author: @{author}
|
||||
+ author_id: {author_id}
|
||||
```
|
||||
|
||||
3. **Replace `last_seen_at` sweep marker with monotonic `sync_run_id`**
|
||||
Why: Timestamp markers are vulnerable to clock skew and concurrent runs; run IDs are deterministic and safer.
|
||||
|
||||
```diff
|
||||
@@ Phase 0: Stable Note Identity
|
||||
+ ### Work Chunk 0E: Monotonic Run Marker
|
||||
+ Add `sync_runs` table and `notes.last_seen_run_id`.
|
||||
+ Ingest assigns one run_id per sync transaction.
|
||||
+ Upsert sets `last_seen_run_id = current_run_id`.
|
||||
+ Sweep condition becomes `last_seen_run_id < current_run_id` (when fetch_complete=true).
|
||||
@@ Work Chunk 0C
|
||||
- fetch_complete + last_seen_at-based sweep
|
||||
+ fetch_complete + run_id-based sweep
|
||||
```
|
||||
|
||||
4. **Materialize stale-note set once during sweep**
|
||||
Why: Current set-based SQL still re-runs the stale subquery 3 times; materializing once improves performance and guarantees identical deletion set.
|
||||
|
||||
```diff
|
||||
@@ Work Chunk 0B: Immediate Deletion Propagation
|
||||
- DELETE FROM documents ... IN (SELECT id FROM notes WHERE ...);
|
||||
- DELETE FROM dirty_sources ... IN (SELECT id FROM notes WHERE ...);
|
||||
- DELETE FROM notes WHERE ...;
|
||||
+ CREATE TEMP TABLE _stale_note_ids AS
|
||||
+ SELECT id, is_system FROM notes WHERE discussion_id = ? AND last_seen_run_id < ?;
|
||||
+ DELETE FROM documents
|
||||
+ WHERE source_type='note' AND source_id IN (SELECT id FROM _stale_note_ids WHERE is_system=0);
|
||||
+ DELETE FROM dirty_sources
|
||||
+ WHERE source_type='note' AND source_id IN (SELECT id FROM _stale_note_ids WHERE is_system=0);
|
||||
+ DELETE FROM notes WHERE id IN (SELECT id FROM _stale_note_ids);
|
||||
+ DROP TABLE _stale_note_ids;
|
||||
```
|
||||
|
||||
5. **Move historical note backfill out of migration into resumable runtime job**
|
||||
Why: Data-heavy migration can block startup and is harder to resume/recover on large DBs.
|
||||
|
||||
```diff
|
||||
@@ Work Chunk 2H
|
||||
- Backfill Existing Notes After Upgrade (Migration 024)
|
||||
+ Backfill Existing Notes After Upgrade (Resumable Runtime Backfill)
|
||||
@@
|
||||
- Files: `migrations/024_note_dirty_backfill.sql`, `src/core/db.rs`
|
||||
+ Files: `src/documents/backfill.rs`, `src/cli/commands/generate_docs.rs`
|
||||
@@
|
||||
- INSERT INTO dirty_sources ... SELECT ... FROM notes ...
|
||||
+ Introduce batched backfill API:
|
||||
+ `enqueue_missing_note_documents(batch_size: usize) -> BackfillProgress`
|
||||
+ invoked from `generate-docs`/`sync` until complete, resumable across runs.
|
||||
```
|
||||
|
||||
6. **Add streaming path for large `jsonl`/`csv` note exports**
|
||||
Why: Current `query_notes` materializes full result set in memory; streaming improves scalability and latency.
|
||||
|
||||
```diff
|
||||
@@ Work Chunk 1A
|
||||
+ Add `query_notes_stream(conn, filters, row_handler)` for forward-only row iteration.
|
||||
@@ Work Chunk 1C
|
||||
- print_list_notes_jsonl(&result)
|
||||
- print_list_notes_csv(&result)
|
||||
+ print_list_notes_jsonl_stream(config, filters)
|
||||
+ print_list_notes_csv_stream(config, filters)
|
||||
+ (table/json keep counted buffered path)
|
||||
```
|
||||
|
||||
7. **Add index for path-centric note queries**
|
||||
Why: `--path` + project/date queries are a stated hot path and not fully covered by current proposed indexes.
|
||||
|
||||
```diff
|
||||
@@ Work Chunk 1E: Composite Query Index
|
||||
+ CREATE INDEX IF NOT EXISTS idx_notes_project_path_created
|
||||
+ ON notes(project_id, position_new_path, created_at DESC, id DESC)
|
||||
+ WHERE is_system = 0 AND position_new_path IS NOT NULL;
|
||||
```
|
||||
|
||||
8. **Add property/invariant tests (not only examples)**
|
||||
Why: This feature touches ingestion identity, sweeping, deletion propagation, and document regeneration; randomized invariants will catch subtle regressions.
|
||||
|
||||
```diff
|
||||
@@ Verification Checklist
|
||||
+ Add property tests (proptest):
|
||||
+ - stable local IDs across randomized re-sync orderings
|
||||
+ - no orphan `documents(source_type='note')` after randomized deletions/sweeps
|
||||
+ - partial-fetch runs never reduce note count
|
||||
+ - repeated full rebuild converges (fixed-point idempotence)
|
||||
```
|
||||
|
||||
These revisions keep your existing direction, avoid all rejected items, and materially improve correctness, scale behavior, and long-term maintainability.
|
||||
2518
docs/prd-per-note-search.md
Normal file
2518
docs/prd-per-note-search.md
Normal file
File diff suppressed because it is too large
Load Diff
@@ -125,7 +125,7 @@ lore -J mrs --fields iid,title,state,draft,target_branch
|
||||
|
||||
### Available Fields
|
||||
|
||||
**Issues**: `iid`, `title`, `state`, `author_username`, `labels`, `assignees`, `discussion_count`, `unresolved_count`, `created_at_iso`, `updated_at_iso`, `web_url`, `project_path`
|
||||
**Issues**: `iid`, `title`, `state`, `author_username`, `labels`, `assignees`, `discussion_count`, `unresolved_count`, `created_at_iso`, `updated_at_iso`, `web_url`, `project_path`, `status_name`, `status_category`, `status_color`, `status_icon_name`, `status_synced_at_iso`
|
||||
|
||||
**MRs**: `iid`, `title`, `state`, `author_username`, `labels`, `draft`, `target_branch`, `source_branch`, `discussion_count`, `unresolved_count`, `created_at_iso`, `updated_at_iso`, `web_url`, `project_path`, `reviewers`
|
||||
|
||||
|
||||
541
docs/user-journeys.md
Normal file
541
docs/user-journeys.md
Normal file
@@ -0,0 +1,541 @@
|
||||
# Lore CLI User Journeys
|
||||
|
||||
## Purpose
|
||||
|
||||
Map realistic workflows for both human users and AI agents to identify gaps in the command surface and optimization opportunities. Each journey starts with a **problem** and traces the commands needed to reach a **resolution**.
|
||||
|
||||
---
|
||||
|
||||
## Part 1: Human User Flows
|
||||
|
||||
### H1. Morning Standup Prep
|
||||
|
||||
**Problem:** "What happened since yesterday? I need to know what moved before standup."
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore sync -q # Refresh data (quiet, no noise)
|
||||
lore issues -s opened --since 1d # Issues that changed overnight
|
||||
lore mrs -s opened --since 1d # MRs that moved
|
||||
lore who @me # My current workload snapshot
|
||||
```
|
||||
|
||||
**Gap identified:** No single "activity feed" command. User runs 3 queries to get what should be one view. No `--since 1d` shorthand for "since yesterday." No `@me` alias for the authenticated user.
|
||||
|
||||
---
|
||||
|
||||
### H2. Sprint Planning: What's Ready to Pick Up?
|
||||
|
||||
**Problem:** "We're planning the next sprint. What's open, unassigned, and actionable?"
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore issues -s opened -p myproject # All open issues
|
||||
lore issues -s opened -l "ready" # Issues labeled ready
|
||||
lore issues -s opened --has-due # Issues with deadlines approaching
|
||||
lore count issues -p myproject # How many total?
|
||||
```
|
||||
|
||||
**Gap identified:** No way to filter by "unassigned" issues (missing `--no-assignee` flag). No way to sort by due date. No way to see priority/weight. Can't combine filters like "opened AND no assignee AND has due date."
|
||||
|
||||
---
|
||||
|
||||
### H3. Investigating a Production Incident
|
||||
|
||||
**Problem:** "Deploy broke prod. I need the full timeline of what changed around the deploy."
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore sync -q # Get latest
|
||||
lore timeline "deploy" --since 7d # What happened around deploys
|
||||
lore search "deploy" --type mr # MRs mentioning deploy
|
||||
lore mrs 456 # Inspect the suspicious MR
|
||||
lore who --overlap src/deploy/ # Who else touches deploy code
|
||||
```
|
||||
|
||||
**Gap identified:** Timeline is keyword-based, not event-based. Can't filter by "MRs merged in the last 24 hours" directly. No way to see which MRs were merged between two dates (release diff). Would benefit from `lore mrs -s merged --since 1d`.
|
||||
|
||||
---
|
||||
|
||||
### H4. Preparing to Review Someone's MR
|
||||
|
||||
**Problem:** "I was assigned to review MR !789. I need context before diving in."
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore mrs 789 # Read the MR description + discussions
|
||||
lore mrs 789 -o # Open in browser for the actual diff
|
||||
lore who src/features/auth/ # Who are the experts in this area?
|
||||
lore search "auth refactor" --type issue # Related issues for background
|
||||
lore timeline "authentication" # History of auth changes
|
||||
```
|
||||
|
||||
**Gap identified:** No way to see the file list touched by an MR from the CLI (data is stored in `mr_file_changes` but not surfaced). No way to link an MR back to its closing issue(s) from the MR detail view. The cross-reference data exists in `entity_references` but isn't shown in `mrs <iid>` output.
|
||||
|
||||
---
|
||||
|
||||
### H5. Onboarding to an Unfamiliar Code Area
|
||||
|
||||
**Problem:** "I'm new to the team and need to understand how the billing module works."
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore search "billing" -n 20 # What exists about billing?
|
||||
lore who src/billing/ # Who knows billing best?
|
||||
lore timeline "billing" --depth 2 # History of billing changes
|
||||
lore mrs -s merged -l billing --since 6m # Recent merged billing work
|
||||
lore issues -s opened -l billing # Outstanding billing issues
|
||||
```
|
||||
|
||||
**Gap identified:** No way to get a "module overview" in one command. The search spans issues, MRs, and discussions but doesn't summarize by category. No way to see the most-discussed or most-referenced entities (high-signal items for understanding).
|
||||
|
||||
---
|
||||
|
||||
### H6. Finding the Right Reviewer for My PR
|
||||
|
||||
**Problem:** "I'm about to submit a PR touching auth and payments. Who should review?"
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore who src/features/auth/ # Auth experts
|
||||
lore who src/features/payments/ # Payment experts
|
||||
lore who @candidate1 # Check candidate1's workload
|
||||
lore who @candidate2 # Check candidate2's workload
|
||||
```
|
||||
|
||||
**Gap identified:** No way to query multiple paths at once (`lore who src/auth/ src/payments/`). No way to find the intersection of expertise. No workload-aware recommendation ("who knows this AND has bandwidth"). Four separate commands for what should be one decision.
|
||||
|
||||
---
|
||||
|
||||
### H7. Understanding Why a Feature Was Built This Way
|
||||
|
||||
**Problem:** "This code is weird. Why was it implemented like this? What was the original discussion?"
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore search "feature-name rationale" # Search for decision context
|
||||
lore timeline "feature-name" --depth 2 # Full history with cross-refs
|
||||
lore issues 234 # Read the original issue
|
||||
lore mrs 567 # Read the implementation MR
|
||||
```
|
||||
|
||||
**Gap identified:** No way to search within a specific issue's or MR's discussion notes. The search covers documents (titles + descriptions) but per-note search isn't available yet (PRD exists). No way to navigate "issue 234 was closed by MR 567" without manually knowing both IDs.
|
||||
|
||||
---
|
||||
|
||||
### H8. Checking Team Workload Before Assigning Work
|
||||
|
||||
**Problem:** "I need to assign this urgent bug. Who has the least on their plate?"
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore who @alice # Alice's workload
|
||||
lore who @bob # Bob's workload
|
||||
lore who @carol # Carol's workload
|
||||
lore who @dave # Dave's workload
|
||||
```
|
||||
|
||||
**Gap identified:** No team-level workload view. Must query each person individually. No way to list "all assignees and their open issue counts." No concept of a team roster. Would benefit from `lore who --team` or `lore workload`.
|
||||
|
||||
---
|
||||
|
||||
### H9. Preparing Release Notes
|
||||
|
||||
**Problem:** "We're cutting a release. I need to summarize what's in this version."
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore mrs -s merged --since 2w -p myproject # MRs merged since last release
|
||||
lore issues -s closed --since 2w -p myproject # Issues closed since last release
|
||||
lore mrs -s merged -l feature --since 2w # Feature MRs specifically
|
||||
lore mrs -s merged -l bugfix --since 2w # Bugfix MRs
|
||||
```
|
||||
|
||||
**Gap identified:** No way to filter by milestone (for version-based releases). Wait -- `issues` has `-m` for milestone but `mrs` does not. No changelog generation. No "what closed between tag A and tag B." No grouping by label for release note categories.
|
||||
|
||||
---
|
||||
|
||||
### H10. Finding and Closing Stale Issues
|
||||
|
||||
**Problem:** "Our backlog is bloated. Which issues haven't been touched in months?"
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore issues -s opened --sort updated --asc -n 50 # Oldest-updated first
|
||||
# Then manually inspect each one...
|
||||
lore issues 42 # Is this still relevant?
|
||||
```
|
||||
|
||||
**Gap identified:** No `--before` or `--updated-before` filter (only `--since` exists). Can sort ascending but can't filter "not updated in 90 days." No staleness indicator. No bulk operations concept.
|
||||
|
||||
---
|
||||
|
||||
### H11. Understanding a Bug's Full History
|
||||
|
||||
**Problem:** "Bug #321 keeps getting reopened. I need to understand its entire lifecycle."
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore issues 321 # Read the issue
|
||||
lore timeline "bug-keyword" -p myproject # Try to find timeline events
|
||||
# But timeline is keyword-based, not entity-based...
|
||||
```
|
||||
|
||||
**Gap identified:** No way to get a timeline for a specific entity by IID. `lore timeline` requires a keyword query, not an entity reference. Would benefit from `lore timeline --issue 321` or `lore timeline --mr 456` to get the event history of a specific entity directly.
|
||||
|
||||
---
|
||||
|
||||
### H12. Identifying Who to Ask About Failing Tests
|
||||
|
||||
**Problem:** "CI tests are failing in `src/lib/parser.rs`. Who last touched this?"
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore who src/lib/parser.rs # Expert lookup
|
||||
lore who --overlap src/lib/parser.rs # Who else has touched it
|
||||
lore search "parser" --type mr --since 2w # Recent MRs touching parser
|
||||
```
|
||||
|
||||
**Gap identified:** Expert mode uses DiffNote analysis (code review comments), not actual file change tracking. The `mr_file_changes` table has the real data but `who` doesn't use it for attribution. Could be much more accurate with file-change-based expertise.
|
||||
|
||||
---
|
||||
|
||||
### H13. Tracking a Feature Across Multiple MRs
|
||||
|
||||
**Problem:** "The 'dark mode' feature spans 5 MRs. I need to see them all together."
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore mrs -l dark-mode # MRs with the label
|
||||
lore issues -l dark-mode # Related issues
|
||||
lore timeline "dark mode" --depth 2 # Cross-referenced events
|
||||
```
|
||||
|
||||
**Gap identified:** Works reasonably well with labels as the grouping mechanism. But if the team didn't label consistently, there's no way to discover related MRs by content similarity. No "related items" view that combines issues + MRs + discussions for a topic.
|
||||
|
||||
---
|
||||
|
||||
### H14. Checking if a Similar Fix Was Already Attempted
|
||||
|
||||
**Problem:** "Before I implement this fix, was something similar tried before?"
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore search "memory leak connection pool" # Semantic search
|
||||
lore search "connection pool" --type mr -s all # Wait, no state filter on search
|
||||
lore mrs -s closed -l bugfix # Closed bugfix MRs (coarse)
|
||||
lore timeline "connection pool" # Historical context
|
||||
```
|
||||
|
||||
**Gap identified:** Search doesn't have a `--state` filter. Can't search only closed/merged items. The semantic search is powerful but can't be combined with entity state. Would benefit from `--state merged` on search to find past attempts.
|
||||
|
||||
---
|
||||
|
||||
### H15. Reviewing Discussions That Need My Attention
|
||||
|
||||
**Problem:** "Which discussion threads am I involved in that are still unresolved?"
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore who --active # All active unresolved discussions
|
||||
lore who --active --since 30d # Wider window
|
||||
# But can't filter to "discussions I'm in"...
|
||||
```
|
||||
|
||||
**Gap identified:** `--active` shows all unresolved discussions, not filtered by participant. No way to say "show me discussions where @me participated." No notification/mention tracking. No "my unresolved threads" view.
|
||||
|
||||
---
|
||||
|
||||
## Part 2: AI Agent Flows
|
||||
|
||||
### A1. Context Gathering Before Code Modification
|
||||
|
||||
**Problem:** Agent is about to modify `src/features/auth/session.rs` and needs full context.
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore -J health # Pre-flight check
|
||||
lore -J who src/features/auth/ # Who knows this area
|
||||
lore -J search "auth session" -n 10 # Related issues/MRs
|
||||
lore -J mrs -s merged --since 3m -l auth # Recent auth changes
|
||||
lore -J who --overlap src/features/auth/session.rs # Concurrent work risk
|
||||
```
|
||||
|
||||
**Gap identified:** No way to check "are there open MRs touching this file right now?" The overlap mode shows historical touches, not active branches. An agent needs to know about in-flight changes to avoid conflicts.
|
||||
|
||||
---
|
||||
|
||||
### A2. Auto-Triaging an Incoming Issue
|
||||
|
||||
**Problem:** Agent receives a new issue and needs to categorize it, find related work, and suggest assignees.
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore -J issues 999 # Read the new issue
|
||||
lore -J search "$(extract_keywords)" --explain # Find similar past issues
|
||||
lore -J who src/affected/path/ # Suggest experts as assignees
|
||||
lore -J issues -s opened -l same-label # Check for duplicates
|
||||
```
|
||||
|
||||
**Gap identified:** No way to get just the description text for programmatic keyword extraction. `issues <iid>` returns full detail including discussions. Agent must parse the full response to extract the description for a secondary search. Would benefit from `--fields description` on detail view. No duplicate detection built in.
|
||||
|
||||
---
|
||||
|
||||
### A3. Generating Sprint Status Report
|
||||
|
||||
**Problem:** Agent needs to produce a weekly status report for the team.
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore -J issues -s closed --since 1w --fields minimal # Completed work
|
||||
lore -J issues -s opened --status "In progress" # In-flight work
|
||||
lore -J mrs -s merged --since 1w --fields minimal # Merged PRs
|
||||
lore -J mrs -s opened -D --fields minimal # Open non-draft MRs
|
||||
lore -J count issues # Totals
|
||||
lore -J count mrs # MR totals
|
||||
lore -J who --active --since 1w # Discussions needing attention
|
||||
```
|
||||
|
||||
**Gap identified:** Seven separate queries for one report. No `lore summary` or `lore report` command. No way to get "issues transitioned from X to Y this week" (state change history exists in events but isn't queryable). No velocity metric (issues closed per week trend).
|
||||
|
||||
---
|
||||
|
||||
### A4. Finding Relevant Prior Art Before Implementing
|
||||
|
||||
**Problem:** Agent is implementing a caching layer and wants to find if similar patterns exist in the codebase's GitLab history.
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore -J search "caching" --mode hybrid -n 20 --explain
|
||||
lore -J search "cache invalidation" --mode hybrid -n 10
|
||||
lore -J search "redis" --mode lexical --type discussion # Exact term in discussions
|
||||
lore -J timeline "cache" --since 1y # Wait, max is 1y? Let's try 12m
|
||||
```
|
||||
|
||||
**Gap identified:** No way to search discussion notes individually (per-note search). Discussions are aggregated into documents, so individual note-level matches are lost. The `--explain` flag helps but doesn't show which specific note matched. No `--since 1y` or `--since 12m` duration format.
|
||||
|
||||
---
|
||||
|
||||
### A5. Building Context for PR Description
|
||||
|
||||
**Problem:** Agent wrote code and needs to generate a PR description that references relevant issues.
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore -J search "feature description keywords" --type issue
|
||||
lore -J issues -s opened -l feature-label --fields iid,title,web_url
|
||||
# Cross-reference: which issues does this MR close?
|
||||
# No command for this -- must manually scan search results
|
||||
```
|
||||
|
||||
**Gap identified:** No way to query the `entity_references` table directly. Agent can't ask "which issues reference MR !456" or "which issues contain 'closes #123' in their text." The data exists but isn't exposed as a query surface. Would benefit from `lore refs --mr 456` or `lore refs --issue 123`.
|
||||
|
||||
---
|
||||
|
||||
### A6. Identifying Affected Experts for Review Assignment
|
||||
|
||||
**Problem:** Agent needs to automatically assign reviewers based on the files changed in an MR.
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore -J mrs 456 # Get MR details
|
||||
# Parse file paths from response... but file changes aren't in the output
|
||||
lore -J who src/path/from/mr/ # Query each path
|
||||
lore -J who src/another/path/ # One at a time...
|
||||
lore -J who @candidate --fields minimal # Check workload
|
||||
```
|
||||
|
||||
**Gap identified:** MR detail view (`mrs <iid>`) doesn't include the file change list from `mr_file_changes`. Agent can't programmatically extract which files an MR touches. Must fall back to GitLab API or guess from description. The `who` command doesn't accept multiple paths. No "auto-reviewer" suggestion combining expertise + availability.
|
||||
|
||||
---
|
||||
|
||||
### A7. Incident Investigation and Timeline Reconstruction
|
||||
|
||||
**Problem:** Agent needs to reconstruct what happened during an outage for a postmortem.
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore -J timeline "outage" --since 3d --depth 2 --expand-mentions
|
||||
lore -J search "error 500" --since 3d
|
||||
lore -J mrs -s merged --since 3d -p production-service
|
||||
lore -J issues --status "In progress" -p production-service
|
||||
```
|
||||
|
||||
**Gap identified:** Timeline is keyword-seeded, which means if the outage wasn't described with that exact term, seeds may miss it. No way to seed a timeline from an entity ID (e.g., "start from issue #321 and expand outward"). No severity/priority filter. No way to correlate with merge times.
|
||||
|
||||
---
|
||||
|
||||
### A8. Cross-Project Impact Assessment
|
||||
|
||||
**Problem:** Agent needs to understand how a breaking API change in project A affects projects B and C.
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore -J search "api-endpoint-name" -p project-a
|
||||
lore -J search "api-endpoint-name" -p project-b
|
||||
lore -J search "api-endpoint-name" -p project-c
|
||||
# Or without project filter to search everywhere:
|
||||
lore -J search "api-endpoint-name" -n 50
|
||||
lore -J timeline "api-endpoint-name" --depth 2
|
||||
```
|
||||
|
||||
**Gap identified:** Cross-project references in entity_references are tracked but the timeline shows unresolved references for entities not synced locally. No way to see a cross-project dependency map. Search works across projects but doesn't group results by project.
|
||||
|
||||
---
|
||||
|
||||
### A9. Automated Stale Issue Recommendations
|
||||
|
||||
**Problem:** Agent runs weekly to identify issues that should be closed or re-prioritized.
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore -J issues -s opened --sort updated --asc -n 100 # Oldest first
|
||||
# For each issue, check:
|
||||
lore -J issues <iid> # Read details
|
||||
lore -J search "<issue title keywords>" # Any recent activity?
|
||||
```
|
||||
|
||||
**Gap identified:** No `--updated-before` filter, so agent must fetch all and filter client-side. No way to detect "issue has no assignee AND no activity in 90 days." The 100-issue limit means pagination is needed for large backlogs, but there's no cursor/offset pagination -- only `--limit`. Agent must do N+1 queries to inspect each candidate.
|
||||
|
||||
---
|
||||
|
||||
### A10. Code Review Preparation (File-Level Context)
|
||||
|
||||
**Problem:** Agent is reviewing MR !789 and needs to understand the history of each changed file.
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore -J mrs 789 # Get MR details
|
||||
# Can't get file list from output...
|
||||
# Fall back to search by MR title keywords
|
||||
lore -J search "feature-from-mr" --type mr
|
||||
lore -J who src/guessed/path/ # Expertise for each file
|
||||
lore -J who --overlap src/guessed/path/ # Concurrent changes
|
||||
```
|
||||
|
||||
**Gap identified:** Same as A6 -- `mr_file_changes` data isn't exposed. Agent is blind to the actual files in the MR unless it parses the description or uses the GitLab API directly. This is the single biggest gap for automated code review workflows.
|
||||
|
||||
---
|
||||
|
||||
### A11. Building a Knowledge Graph of Entity Relationships
|
||||
|
||||
**Problem:** Agent wants to map how issues, MRs, and discussions are connected for a feature.
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore -J search "feature-name" -n 30
|
||||
lore -J timeline "feature-name" --depth 2 --max-entities 100
|
||||
# Timeline shows expanded entities and cross-refs, but...
|
||||
# No way to query entity_references directly
|
||||
# No way to get "all entities that reference issue #123"
|
||||
```
|
||||
|
||||
**Gap identified:** The `entity_references` table (closes, related, mentioned) is used internally by timeline but isn't queryable as a standalone command. Agent can't ask "what closes issue #123?" or "what does MR !456 reference?" No graph export. Would enable powerful dependency mapping.
|
||||
|
||||
---
|
||||
|
||||
### A12. Release Readiness Assessment
|
||||
|
||||
**Problem:** Agent needs to verify all issues in milestone "v2.0" are closed and MRs are merged.
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore -J issues -m "v2.0" -s opened # Any open issues in milestone?
|
||||
lore -J issues -m "v2.0" -s closed # Closed issues
|
||||
# MRs don't have milestone filter...
|
||||
lore -J mrs -s opened -l "v2.0" # Try label as proxy
|
||||
lore -J who --active -p myproject # Unresolved discussions
|
||||
```
|
||||
|
||||
**Gap identified:** MRs don't have a `--milestone` filter (issues do). No way to check "all MRs linked to issues in milestone v2.0" -- would require joining `entity_references` with issue milestone. No release checklist concept. No way to verify "every issue in this milestone has a closing MR."
|
||||
|
||||
---
|
||||
|
||||
### A13. Answering "What Changed?" Between Two Points
|
||||
|
||||
**Problem:** Agent needs to diff project state between two dates for a stakeholder report.
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore -J issues -s closed --since 2w --fields minimal # Recently closed
|
||||
lore -J issues -s opened --since 2w --fields minimal # Recently opened
|
||||
lore -J mrs -s merged --since 2w --fields minimal # Recently merged
|
||||
# But no way to get "issues that CHANGED STATE" in a window
|
||||
# An issue opened 3 months ago but closed yesterday won't appear in --since 2w for issues -s opened
|
||||
```
|
||||
|
||||
**Gap identified:** `--since` filters by `updated_at`, not by "state changed at." An issue closed yesterday but created 6 months ago would appear in `issues -s closed --since 1d` (because updated_at changed), but the semantics are subtle. No explicit "state transitions in time window" query. The resource_state_events table has this data but it's not exposed as a filter.
|
||||
|
||||
---
|
||||
|
||||
### A14. Meeting Prep: Summarize Recent Activity for a Stakeholder
|
||||
|
||||
**Problem:** Agent needs to prepare a 2-minute summary for a project sponsor meeting.
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore -J count issues -p project # Current totals
|
||||
lore -J count mrs -p project # MR totals
|
||||
lore -J issues -s closed --since 1w -p project --fields minimal
|
||||
lore -J mrs -s merged --since 1w -p project --fields minimal
|
||||
lore -J issues -s opened --status "In progress" -p project
|
||||
lore -J who --active -p project --since 1w
|
||||
```
|
||||
|
||||
**Gap identified:** Six queries, same as A3. No summary/dashboard command. Agent must synthesize all responses. No trend data (is the open issue count growing or shrinking?). No "highlights" extraction.
|
||||
|
||||
---
|
||||
|
||||
### A15. Determining If Work Is Safe to Start (Conflict Detection)
|
||||
|
||||
**Problem:** Agent is about to start work on an issue and needs to check nobody else is already working on it.
|
||||
|
||||
**Flow:**
|
||||
```
|
||||
lore -J issues 123 # Read the issue
|
||||
# Check assignees from response
|
||||
lore -J mrs -s opened -A other-person # Are they working on related MRs?
|
||||
lore -J who --overlap src/target/path/ # Anyone actively touching these files?
|
||||
lore -J search "issue-123-keywords" --type mr -s opened # Wait, search has no --state
|
||||
```
|
||||
|
||||
**Gap identified:** No way to check "is there an open MR that closes issue #123?" -- the entity_references data exists but isn't queryable. Search doesn't support `--state` filter. No "conflict detection" or "in-flight work" check. Agent must do multiple queries and manually correlate.
|
||||
|
||||
---
|
||||
|
||||
## Part 3: Gap Summary
|
||||
|
||||
### Critical Gaps (high impact, blocks common workflows)
|
||||
|
||||
| # | Gap | Affected Flows | Suggested Command/Flag |
|
||||
|---|-----|----------------|----------------------|
|
||||
| 1 | **MR file changes not surfaced** | H4, A6, A10 | `lore mrs <iid> --files` or include in detail view |
|
||||
| 2 | **Entity references not queryable** | H7, A5, A11, A15 | `lore refs --issue 123` / `lore refs --mr 456` |
|
||||
| 3 | **Per-note search missing** | H7, A4 | `lore search --granularity note` (PRD exists) |
|
||||
| 4 | **No entity-based timeline** | H11, A7 | `lore timeline --issue 321` / `lore timeline --mr 456` |
|
||||
| 5 | **No @me / current-user alias** | H1, H15 | Resolve from auth token automatically |
|
||||
|
||||
### Important Gaps (significant friction, multiple workarounds needed)
|
||||
|
||||
| # | Gap | Affected Flows | Suggested Command/Flag |
|
||||
|---|-----|----------------|----------------------|
|
||||
| 6 | **No activity feed / summary** | H1, A3, A14 | `lore activity --since 1d` or `lore summary` |
|
||||
| 7 | **No multi-path who query** | H6, A6 | `lore who src/path1/ src/path2/` |
|
||||
| 8 | **No --state filter on search** | H14, A15 | `lore search --state merged` |
|
||||
| 9 | **MRs missing --milestone filter** | H9, A12 | `lore mrs -m "v2.0"` |
|
||||
| 10 | **No --no-assignee / --unassigned** | H2 | `lore issues --no-assignee` |
|
||||
| 11 | **No --updated-before filter** | H10, A9 | `lore issues --before 90d` or `--stale 90d` |
|
||||
| 12 | **No team workload view** | H8 | `lore who --team` or `lore workload` |
|
||||
|
||||
### Nice-to-Have Gaps (would improve agent efficiency)
|
||||
|
||||
| # | Gap | Affected Flows | Suggested Command/Flag |
|
||||
|---|-----|----------------|----------------------|
|
||||
| 13 | **No pagination/offset** | A9 | `--offset 100` for large result sets |
|
||||
| 14 | **No detail --fields on show** | A2 | `lore issues 999 --fields description` |
|
||||
| 15 | **No cross-project grouping** | A8 | `lore search --group-by project` |
|
||||
| 16 | **No trend/velocity metrics** | A3, A14 | `lore trends issues --period week` |
|
||||
| 17 | **No --for-issue on mrs** | A12, A15 | `lore mrs --closes 123` (query entity_refs) |
|
||||
| 18 | **1y/12m duration not supported** | A4 | Support `1y`, `12m`, `365d` in --since |
|
||||
| 19 | **No discussion participant filter** | H15 | `lore who --active --participant @me` |
|
||||
| 20 | **No sort by due date** | H2 | `lore issues --sort due` |
|
||||
@@ -1,434 +0,0 @@
|
||||
Below are the highest-leverage revisions I’d make to this plan. I’m focusing on correctness pitfalls, SQLite gotchas, query performance on 280K notes, and reducing “dynamic SQL + param juggling” complexity—without turning this into a new ingestion project.
|
||||
|
||||
Change 1 — Fix a hard SQLite bug in --active (GROUP_CONCAT DISTINCT + separator)
|
||||
Why
|
||||
|
||||
SQLite does not allow GROUP_CONCAT(DISTINCT x, sep). With DISTINCT, SQLite only permits a single argument (GROUP_CONCAT(DISTINCT x)). Your current query will error at runtime in many SQLite versions.
|
||||
|
||||
Revision
|
||||
|
||||
Use a subquery that selects distinct participants, then GROUP_CONCAT with your separator.
|
||||
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/Plan.md b/Plan.md
|
||||
@@ fn query_active(...)
|
||||
- (SELECT GROUP_CONCAT(DISTINCT n.author_username, X'1F')
|
||||
- FROM notes n
|
||||
- WHERE n.discussion_id = d.id
|
||||
- AND n.is_system = 0
|
||||
- AND n.author_username IS NOT NULL) AS participants
|
||||
+ (SELECT GROUP_CONCAT(username, X'1F') FROM (
|
||||
+ SELECT DISTINCT n.author_username AS username
|
||||
+ FROM notes n
|
||||
+ WHERE n.discussion_id = d.id
|
||||
+ AND n.is_system = 0
|
||||
+ AND n.author_username IS NOT NULL
|
||||
+ ORDER BY username
|
||||
+ )) AS participants
|
||||
|
||||
Change 2 — Replace “contains('.') => exact file match” with segment-aware path classification
|
||||
Why
|
||||
|
||||
path.contains('.') misclassifies directories like:
|
||||
|
||||
.github/workflows/
|
||||
|
||||
src/v1.2/auth/
|
||||
|
||||
It also fails the “root file” case (README.md) because your mode discriminator only treats paths as paths if they contain /.
|
||||
|
||||
Revision
|
||||
|
||||
Add explicit --path to force Expert mode (covers root files cleanly).
|
||||
|
||||
Classify file-vs-dir by checking last path segment for a dot, and whether the input ends with /.
|
||||
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/Plan.md b/Plan.md
|
||||
@@ pub struct WhoArgs {
|
||||
- /// Username or file path (path if contains /)
|
||||
- pub target: Option<String>,
|
||||
+ /// Username or file path shorthand (ambiguous for root files like README.md)
|
||||
+ pub target: Option<String>,
|
||||
+
|
||||
+ /// Force expert mode for a file/directory path (supports root files like README.md)
|
||||
+ #[arg(long, help_heading = "Mode", conflicts_with_all = ["active", "overlap", "reviews"])]
|
||||
+ pub path: Option<String>,
|
||||
@@ fn resolve_mode<'a>(args: &'a WhoArgs) -> Result<WhoMode<'a>> {
|
||||
- if let Some(target) = &args.target {
|
||||
+ if let Some(p) = &args.path {
|
||||
+ return Ok(WhoMode::Expert { path: p });
|
||||
+ }
|
||||
+ if let Some(target) = &args.target {
|
||||
let clean = target.strip_prefix('@').unwrap_or(target);
|
||||
if args.reviews {
|
||||
return Ok(WhoMode::Reviews { username: clean });
|
||||
}
|
||||
- // Disambiguation: if target contains '/', it's a file path.
|
||||
- // GitLab usernames never contain '/'.
|
||||
- if target.contains('/') {
|
||||
+ // Disambiguation:
|
||||
+ // - treat as path if it contains '/'
|
||||
+ // - otherwise treat as username (root files require --path)
|
||||
+ if target.contains('/') {
|
||||
return Ok(WhoMode::Expert { path: target });
|
||||
}
|
||||
return Ok(WhoMode::Workload { username: clean });
|
||||
}
|
||||
|
||||
|
||||
And update the path pattern logic used by Expert/Overlap:
|
||||
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/Plan.md b/Plan.md
|
||||
@@ fn query_expert(...)
|
||||
- // Normalize path for LIKE matching: add trailing % if no extension
|
||||
- let path_pattern = if path.contains('.') {
|
||||
- path.to_string() // Exact file match
|
||||
- } else {
|
||||
- let trimmed = path.trim_end_matches('/');
|
||||
- format!("{trimmed}/%")
|
||||
- };
|
||||
+ // Normalize:
|
||||
+ // - if ends_with('/') => directory prefix
|
||||
+ // - else if last segment contains '.' => file exact match
|
||||
+ // - else => directory prefix
|
||||
+ let trimmed = path.trim_end_matches('/');
|
||||
+ let last = trimmed.rsplit('/').next().unwrap_or(trimmed);
|
||||
+ let is_file = !path.ends_with('/') && last.contains('.');
|
||||
+ let path_pattern = if is_file { trimmed.to_string() } else { format!("{trimmed}/%") };
|
||||
|
||||
Change 3 — Stop building dynamic SQL strings for optional filters; always bind params
|
||||
Why
|
||||
|
||||
Right now you’re mixing:
|
||||
|
||||
dynamic project_clause string fragments
|
||||
|
||||
ad-hoc param vectors
|
||||
|
||||
placeholder renumbering by branch
|
||||
|
||||
That’s brittle and easy to regress (especially when you add more conditions later). SQLite/rusqlite can bind Option<T> to NULL, which enables a simple pattern:
|
||||
|
||||
sql
|
||||
Copy code
|
||||
AND (?3 IS NULL OR n.project_id = ?3)
|
||||
|
||||
Revision (representative; apply to all queries)
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/Plan.md b/Plan.md
|
||||
@@ fn query_expert(...)
|
||||
- let project_clause = if project_id.is_some() {
|
||||
- "AND n.project_id = ?3"
|
||||
- } else {
|
||||
- ""
|
||||
- };
|
||||
-
|
||||
- let sql = format!(
|
||||
+ let sql = format!(
|
||||
"SELECT username, role, activity_count, last_active_at FROM (
|
||||
@@
|
||||
FROM notes n
|
||||
WHERE n.position_new_path LIKE ?1
|
||||
AND n.is_system = 0
|
||||
AND n.author_username IS NOT NULL
|
||||
AND n.created_at >= ?2
|
||||
- {project_clause}
|
||||
+ AND (?3 IS NULL OR n.project_id = ?3)
|
||||
@@
|
||||
WHERE n.position_new_path LIKE ?1
|
||||
AND m.author_username IS NOT NULL
|
||||
AND m.updated_at >= ?2
|
||||
- {project_clause}
|
||||
+ AND (?3 IS NULL OR n.project_id = ?3)
|
||||
GROUP BY m.author_username
|
||||
- )"
|
||||
+ ) t"
|
||||
);
|
||||
-
|
||||
- let mut params: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();
|
||||
- params.push(Box::new(path_pattern.clone()));
|
||||
- params.push(Box::new(since_ms));
|
||||
- if let Some(pid) = project_id {
|
||||
- params.push(Box::new(pid));
|
||||
- }
|
||||
- let param_refs: Vec<&dyn rusqlite::ToSql> = params.iter().map(|p| p.as_ref()).collect();
|
||||
+ let param_refs = rusqlite::params![path_pattern, since_ms, project_id];
|
||||
|
||||
|
||||
Notes:
|
||||
|
||||
Adds required derived-table alias t (some SQLite configurations are stricter).
|
||||
|
||||
Eliminates the dynamic param vector and placeholder gymnastics.
|
||||
|
||||
Change 4 — Filter “path touch” queries to DiffNotes and escape LIKE properly
|
||||
Why
|
||||
|
||||
Only DiffNotes reliably have position_new_path; including other note types can skew counts and harm performance.
|
||||
|
||||
LIKE treats % and _ as wildcards—rare in file paths, but not impossible (generated files, templates). Escaping is a low-cost robustness win.
|
||||
|
||||
Revision
|
||||
|
||||
Add note_type='DiffNote' and LIKE ... ESCAPE '\' plus a tiny escape helper.
|
||||
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/Plan.md b/Plan.md
|
||||
@@ fn query_expert(...)
|
||||
- FROM notes n
|
||||
- WHERE n.position_new_path LIKE ?1
|
||||
+ FROM notes n
|
||||
+ WHERE n.note_type = 'DiffNote'
|
||||
+ AND n.position_new_path LIKE ?1 ESCAPE '\'
|
||||
AND n.is_system = 0
|
||||
@@
|
||||
diff --git a/Plan.md b/Plan.md
|
||||
@@ Helper Functions
|
||||
+fn escape_like(input: &str) -> String {
|
||||
+ input.replace('\\', "\\\\").replace('%', "\\%").replace('_', "\\_")
|
||||
+}
|
||||
|
||||
|
||||
And when building patterns:
|
||||
|
||||
diff
|
||||
Copy code
|
||||
- let path_pattern = if is_file { trimmed.to_string() } else { format!("{trimmed}/%") };
|
||||
+ let base = escape_like(trimmed);
|
||||
+ let path_pattern = if is_file { base } else { format!("{base}/%") };
|
||||
|
||||
|
||||
Apply the same changes to query_overlap and any other position_new_path LIKE ....
|
||||
|
||||
Change 5 — Use note timestamps for “touch since” semantics (Expert/Overlap author branch)
|
||||
Why
|
||||
|
||||
In Expert/Overlap “author” branches you filter by m.updated_at >= since. That answers “MR updated recently” rather than “MR touched at this path recently”, which can surface stale ownership.
|
||||
|
||||
Revision
|
||||
|
||||
Filter by the note creation time (and use it for “last touch” where relevant). You can still compute author activity, but anchor it to note activity.
|
||||
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/Plan.md b/Plan.md
|
||||
@@ fn query_overlap(...)
|
||||
- WHERE n.position_new_path LIKE ?1
|
||||
+ WHERE n.note_type = 'DiffNote'
|
||||
+ AND n.position_new_path LIKE ?1 ESCAPE '\'
|
||||
AND m.state IN ('opened', 'merged')
|
||||
AND m.author_username IS NOT NULL
|
||||
- AND m.updated_at >= ?2
|
||||
+ AND n.created_at >= ?2
|
||||
AND (?3 IS NULL OR m.project_id = ?3)
|
||||
|
||||
|
||||
Same idea in Expert mode’s “MR authors” branch.
|
||||
|
||||
Change 6 — Workload mode: apply --since consistently to unresolved discussions
|
||||
Why
|
||||
|
||||
Workload’s unresolved discussions ignore since_ms. That makes --since partially misleading and can dump very old threads.
|
||||
|
||||
Revision
|
||||
|
||||
Filter on d.last_note_at when since_ms is set.
|
||||
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/Plan.md b/Plan.md
|
||||
@@ fn query_workload(...)
|
||||
- let disc_sql = format!(
|
||||
+ let disc_since = if since_ms.is_some() {
|
||||
+ "AND d.last_note_at >= ?2"
|
||||
+ } else { "" };
|
||||
+ let disc_sql = format!(
|
||||
"SELECT d.noteable_type,
|
||||
@@
|
||||
WHERE d.resolvable = 1 AND d.resolved = 0
|
||||
AND EXISTS (
|
||||
@@
|
||||
)
|
||||
{disc_project_filter}
|
||||
+ {disc_since}
|
||||
ORDER BY d.last_note_at DESC
|
||||
LIMIT {limit}"
|
||||
);
|
||||
@@
|
||||
- // Rebuild params for discussion query (only username + optional project_id)
|
||||
- let mut disc_params: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();
|
||||
- disc_params.push(Box::new(username.to_string()));
|
||||
- if let Some(pid) = project_id {
|
||||
- disc_params.push(Box::new(pid));
|
||||
- }
|
||||
+ // Params: username, since_ms, project_id (NULLs ok)
|
||||
+ let disc_param_refs = rusqlite::params![username, since_ms, project_id];
|
||||
|
||||
|
||||
(If you adopt Change 3 fully, this becomes very clean.)
|
||||
|
||||
Change 7 — Make Overlap results represent “both roles” instead of collapsing to one
|
||||
Why
|
||||
|
||||
Collapsing to a single role loses valuable info (“they authored and reviewed”). Also your current “prefer author” rule is arbitrary for the “who else is touching this” question.
|
||||
|
||||
Revision
|
||||
|
||||
Track role counts separately and render as A, R, or A+R.
|
||||
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/Plan.md b/Plan.md
|
||||
@@ pub struct OverlapUser {
|
||||
pub username: String,
|
||||
- pub role: String,
|
||||
- pub touch_count: u32,
|
||||
+ pub author_touch_count: u32,
|
||||
+ pub review_touch_count: u32,
|
||||
+ pub touch_count: u32,
|
||||
pub last_touch_at: i64,
|
||||
pub mr_iids: Vec<i64>,
|
||||
}
|
||||
@@ fn query_overlap(...)
|
||||
- let entry = user_map.entry(username.clone()).or_insert_with(|| OverlapUser {
|
||||
+ let entry = user_map.entry(username.clone()).or_insert_with(|| OverlapUser {
|
||||
username: username.clone(),
|
||||
- role: role.clone(),
|
||||
+ author_touch_count: 0,
|
||||
+ review_touch_count: 0,
|
||||
touch_count: 0,
|
||||
last_touch_at: 0,
|
||||
mr_iids: Vec::new(),
|
||||
});
|
||||
entry.touch_count += count;
|
||||
+ if role == "author" { entry.author_touch_count += count; }
|
||||
+ if role == "reviewer" { entry.review_touch_count += count; }
|
||||
@@ human output
|
||||
- println!(
|
||||
- " {:<16} {:<8} {:>7} {:<12} {}",
|
||||
+ println!(
|
||||
+ " {:<16} {:<6} {:>7} {:<12} {}",
|
||||
...
|
||||
);
|
||||
@@
|
||||
- user.role,
|
||||
+ format_roles(user.author_touch_count, user.review_touch_count),
|
||||
|
||||
Change 8 — Add an “Index Audit + optional migration” step (big perf win, low blast radius)
|
||||
Why
|
||||
|
||||
With 280K notes, the path/timestamp queries will degrade quickly without indexes. This isn’t “scope creep”; it’s making the feature usable.
|
||||
|
||||
Revision (plan-level)
|
||||
|
||||
Add a non-breaking migration that only creates indexes if missing.
|
||||
|
||||
Optionally add a runtime check: if EXPLAIN QUERY PLAN indicates full table scan on notes, print a dim warning in human mode.
|
||||
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/Plan.md b/Plan.md
|
||||
@@ Implementation Order
|
||||
-| Step | What | Files |
|
||||
+| Step | What | Files |
|
||||
| 1 | CLI skeleton: `WhoArgs` + `Commands::Who` + dispatch + stub | `cli/mod.rs`, `commands/mod.rs`, `main.rs` |
|
||||
+| 1.5 | Index audit + add `CREATE INDEX IF NOT EXISTS` migration for who hot paths | `migrations/0xx_who_indexes.sql` |
|
||||
@@
|
||||
|
||||
|
||||
Suggested indexes (tune names to your conventions):
|
||||
|
||||
notes(note_type, position_new_path, created_at)
|
||||
|
||||
notes(discussion_id, is_system, author_username)
|
||||
|
||||
discussions(resolvable, resolved, last_note_at, project_id)
|
||||
|
||||
merge_requests(project_id, state, updated_at, author_username)
|
||||
|
||||
issue_assignees(username, issue_id)
|
||||
|
||||
Even if SQLite can’t perfectly index LIKE, these still help with join and timestamp filters.
|
||||
|
||||
Change 9 — Make robot JSON reproducible by echoing the effective query inputs
|
||||
Why
|
||||
|
||||
Agent workflows benefit from a stable “query record”: what mode ran, what path/user, resolved project, effective since, limit.
|
||||
|
||||
Revision
|
||||
|
||||
Include an input object in JSON output.
|
||||
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/Plan.md b/Plan.md
|
||||
@@ struct WhoJsonData {
|
||||
mode: String,
|
||||
+ input: serde_json::Value,
|
||||
#[serde(flatten)]
|
||||
result: serde_json::Value,
|
||||
}
|
||||
@@ pub fn print_who_json(...)
|
||||
- let output = WhoJsonEnvelope {
|
||||
+ let input = serde_json::json!({
|
||||
+ "project": /* resolved or raw args.project */,
|
||||
+ "since": /* resolved since ISO */,
|
||||
+ "limit": /* args.limit */,
|
||||
+ });
|
||||
+ let output = WhoJsonEnvelope {
|
||||
ok: true,
|
||||
data: WhoJsonData {
|
||||
mode: mode.to_string(),
|
||||
+ input,
|
||||
result: data,
|
||||
},
|
||||
meta: RobotMeta { elapsed_ms },
|
||||
};
|
||||
|
||||
Change 10 — Tighten clap constraints so invalid combinations never reach resolve_mode
|
||||
Why
|
||||
|
||||
Right now conflicts are enforced manually (or not at all). Clamp the invalid combos at the CLI layer:
|
||||
|
||||
--active should conflict with target, --overlap, --reviews, --path
|
||||
|
||||
--reviews should require a username (and should conflict with Expert path modes)
|
||||
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/Plan.md b/Plan.md
|
||||
@@ pub struct WhoArgs {
|
||||
- pub active: bool,
|
||||
+ #[arg(long, help_heading = "Mode", conflicts_with_all = ["target", "overlap", "reviews", "path"])]
|
||||
+ pub active: bool,
|
||||
@@
|
||||
- pub overlap: Option<String>,
|
||||
+ #[arg(long, help_heading = "Mode", conflicts_with_all = ["target", "active", "reviews", "path"])]
|
||||
+ pub overlap: Option<String>,
|
||||
@@
|
||||
- pub reviews: bool,
|
||||
+ #[arg(long, help_heading = "Mode", requires = "target", conflicts_with_all = ["active", "overlap", "path"])]
|
||||
+ pub reviews: bool,
|
||||
|
||||
Summary of what I’d definitely change
|
||||
|
||||
If you do nothing else, do these first:
|
||||
|
||||
Fix GROUP_CONCAT(DISTINCT ..., sep) in Active mode (runtime error).
|
||||
|
||||
Path classification: add --path, and stop using contains('.') globally.
|
||||
|
||||
Remove dynamic SQL + param vectors: always bind project_id as nullable and use (? IS NULL OR ...).
|
||||
|
||||
Filter to DiffNotes + LIKE escaping for correctness and fewer rows scanned.
|
||||
|
||||
Optional index migration: otherwise this will feel slow/non-deterministically slow depending on local DB state.
|
||||
|
||||
If you want, I can also provide a consolidated “v2 plan” as a single unified patch (one diff) rather than per-change snippets.
|
||||
@@ -1,303 +0,0 @@
|
||||
Below are the highest-leverage revisions I’d make to iteration 1 to tighten correctness, performance, and “agent usefulness” without blowing up scope. For each change: (1) rationale, (2) a focused unified diff against the plan you pasted.
|
||||
|
||||
Change 1 — Make robot “input echo” actually resolved (project_id, project_path, since_ms/iso, mode)
|
||||
Why
|
||||
|
||||
Your Design Principle #5 says the robot envelope should echo resolved inputs (“effective since, resolved project”), but the current input object echoes only raw CLI strings. Agents can’t reliably reproduce or compare runs (e.g., fuzzy project resolution may map differently over time).
|
||||
|
||||
This is also a reliability improvement: “what ran” should be computed once and propagated, not recomputed in output.
|
||||
|
||||
Plan diff
|
||||
diff
|
||||
Copy code
|
||||
--- a/who-command-design.md
|
||||
+++ b/who-command-design.md
|
||||
@@
|
||||
-5. **Robot-first reproducibility.** Robot JSON output includes an `input` object echoing the resolved query parameters (effective since, resolved project, limit) so agents can trace exactly what ran.
|
||||
+5. **Robot-first reproducibility.** Robot JSON output includes a `resolved_input` object (mode, since_ms + since_iso, resolved project_id + project_path, limit, db_path) so agents can trace exactly what ran.
|
||||
|
||||
@@
|
||||
-/// Main entry point. Resolves mode from args and dispatches.
|
||||
-pub fn run_who(config: &Config, args: &WhoArgs) -> Result<WhoResult> {
|
||||
+/// Main entry point. Resolves mode + resolved inputs once, then dispatches.
|
||||
+pub fn run_who(config: &Config, args: &WhoArgs) -> Result<WhoRun> {
|
||||
let db_path = get_db_path(config.storage.db_path.as_deref());
|
||||
let conn = create_connection(&db_path)?;
|
||||
|
||||
- let project_id = args
|
||||
+ let project_id = args
|
||||
.project
|
||||
.as_deref()
|
||||
.map(|p| resolve_project(&conn, p))
|
||||
.transpose()?;
|
||||
+ let project_path = project_id
|
||||
+ .map(|id| lookup_project_path(&conn, id))
|
||||
+ .transpose()?;
|
||||
|
||||
let mode = resolve_mode(args)?;
|
||||
|
||||
match mode {
|
||||
WhoMode::Expert { path } => {
|
||||
let since_ms = resolve_since(args.since.as_deref(), "6m")?;
|
||||
let result = query_expert(&conn, path, project_id, since_ms, args.limit)?;
|
||||
- Ok(WhoResult::Expert(result))
|
||||
+ Ok(WhoRun::new("expert", &db_path, project_id, project_path, since_ms, args.limit, WhoResult::Expert(result)))
|
||||
}
|
||||
@@
|
||||
}
|
||||
}
|
||||
+
|
||||
+/// Wrapper that carries resolved inputs for reproducible output.
|
||||
+pub struct WhoRun {
|
||||
+ pub mode: String,
|
||||
+ pub resolved_input: WhoResolvedInput,
|
||||
+ pub result: WhoResult,
|
||||
+}
|
||||
+
|
||||
+pub struct WhoResolvedInput {
|
||||
+ pub db_path: String,
|
||||
+ pub project_id: Option<i64>,
|
||||
+ pub project_path: Option<String>,
|
||||
+ pub since_ms: i64,
|
||||
+ pub since_iso: String,
|
||||
+ pub limit: usize,
|
||||
+}
|
||||
@@
|
||||
-pub fn print_who_json(result: &WhoResult, args: &WhoArgs, elapsed_ms: u64) {
|
||||
- let (mode, data) = match result {
|
||||
+pub fn print_who_json(run: &WhoRun, args: &WhoArgs, elapsed_ms: u64) {
|
||||
+ let (mode, data) = match &run.result {
|
||||
WhoResult::Expert(r) => ("expert", expert_to_json(r)),
|
||||
@@
|
||||
- let input = serde_json::json!({
|
||||
+ let input = serde_json::json!({
|
||||
"target": args.target,
|
||||
"path": args.path,
|
||||
"project": args.project,
|
||||
"since": args.since,
|
||||
"limit": args.limit,
|
||||
});
|
||||
+
|
||||
+ let resolved_input = serde_json::json!({
|
||||
+ "mode": run.mode,
|
||||
+ "db_path": run.resolved_input.db_path,
|
||||
+ "project_id": run.resolved_input.project_id,
|
||||
+ "project_path": run.resolved_input.project_path,
|
||||
+ "since_ms": run.resolved_input.since_ms,
|
||||
+ "since_iso": run.resolved_input.since_iso,
|
||||
+ "limit": run.resolved_input.limit,
|
||||
+ });
|
||||
@@
|
||||
- data: WhoJsonData {
|
||||
- mode: mode.to_string(),
|
||||
- input,
|
||||
- result: data,
|
||||
- },
|
||||
+ data: WhoJsonData { mode: mode.to_string(), input, resolved_input, result: data },
|
||||
meta: RobotMeta { elapsed_ms },
|
||||
};
|
||||
@@
|
||||
struct WhoJsonData {
|
||||
mode: String,
|
||||
input: serde_json::Value,
|
||||
+ resolved_input: serde_json::Value,
|
||||
#[serde(flatten)]
|
||||
result: serde_json::Value,
|
||||
}
|
||||
|
||||
Change 2 — Remove dynamic SQL format!(..LIMIT {limit}) and parameterize LIMIT everywhere
|
||||
Why
|
||||
|
||||
You explicitly prefer static SQL ((?N IS NULL OR ...)) to avoid subtle bugs; but Workload/Active use format! for LIMIT. Even though limit is typed, it’s an inconsistency that complicates statement caching and encourages future string assembly creep.
|
||||
|
||||
SQLite supports LIMIT ? with bound parameters; rusqlite can bind an i64.
|
||||
|
||||
Plan diff
|
||||
diff
|
||||
Copy code
|
||||
--- a/who-command-design.md
|
||||
+++ b/who-command-design.md
|
||||
@@
|
||||
- let issues_sql = format!(
|
||||
- "SELECT ...
|
||||
- ORDER BY i.updated_at DESC
|
||||
- LIMIT {limit}"
|
||||
- );
|
||||
- let mut stmt = conn.prepare(&issues_sql)?;
|
||||
+ let issues_sql =
|
||||
+ "SELECT ...
|
||||
+ ORDER BY i.updated_at DESC
|
||||
+ LIMIT ?4";
|
||||
+ let mut stmt = conn.prepare(issues_sql)?;
|
||||
let assigned_issues: Vec<WorkloadIssue> = stmt
|
||||
- .query_map(rusqlite::params![username, project_id, since_ms], |row| {
|
||||
+ .query_map(rusqlite::params![username, project_id, since_ms, limit as i64], |row| {
|
||||
@@
|
||||
- let authored_sql = format!(
|
||||
- "SELECT ...
|
||||
- ORDER BY m.updated_at DESC
|
||||
- LIMIT {limit}"
|
||||
- );
|
||||
- let mut stmt = conn.prepare(&authored_sql)?;
|
||||
+ let authored_sql =
|
||||
+ "SELECT ...
|
||||
+ ORDER BY m.updated_at DESC
|
||||
+ LIMIT ?4";
|
||||
+ let mut stmt = conn.prepare(authored_sql)?;
|
||||
@@
|
||||
- .query_map(rusqlite::params![username, project_id, since_ms], |row| {
|
||||
+ .query_map(rusqlite::params![username, project_id, since_ms, limit as i64], |row| {
|
||||
@@
|
||||
- let reviewing_sql = format!(
|
||||
- "SELECT ...
|
||||
- ORDER BY m.updated_at DESC
|
||||
- LIMIT {limit}"
|
||||
- );
|
||||
- let mut stmt = conn.prepare(&reviewing_sql)?;
|
||||
+ let reviewing_sql =
|
||||
+ "SELECT ...
|
||||
+ ORDER BY m.updated_at DESC
|
||||
+ LIMIT ?4";
|
||||
+ let mut stmt = conn.prepare(reviewing_sql)?;
|
||||
@@
|
||||
- .query_map(rusqlite::params![username, project_id, since_ms], |row| {
|
||||
+ .query_map(rusqlite::params![username, project_id, since_ms, limit as i64], |row| {
|
||||
@@
|
||||
- let disc_sql = format!(
|
||||
- "SELECT ...
|
||||
- ORDER BY d.last_note_at DESC
|
||||
- LIMIT {limit}"
|
||||
- );
|
||||
- let mut stmt = conn.prepare(&disc_sql)?;
|
||||
+ let disc_sql =
|
||||
+ "SELECT ...
|
||||
+ ORDER BY d.last_note_at DESC
|
||||
+ LIMIT ?4";
|
||||
+ let mut stmt = conn.prepare(disc_sql)?;
|
||||
@@
|
||||
- .query_map(rusqlite::params![username, project_id, since_ms], |row| {
|
||||
+ .query_map(rusqlite::params![username, project_id, since_ms, limit as i64], |row| {
|
||||
@@
|
||||
- let sql = format!(
|
||||
- "SELECT ...
|
||||
- ORDER BY d.last_note_at DESC
|
||||
- LIMIT {limit}"
|
||||
- );
|
||||
- let mut stmt = conn.prepare(&sql)?;
|
||||
+ let sql =
|
||||
+ "SELECT ...
|
||||
+ ORDER BY d.last_note_at DESC
|
||||
+ LIMIT ?3";
|
||||
+ let mut stmt = conn.prepare(sql)?;
|
||||
@@
|
||||
- .query_map(rusqlite::params![since_ms, project_id], |row| {
|
||||
+ .query_map(rusqlite::params![since_ms, project_id, limit as i64], |row| {
|
||||
|
||||
Change 3 — Fix path matching for dotless files (LICENSE/Makefile) via “exact OR prefix” (no new flags)
|
||||
Why
|
||||
|
||||
Your improved “dot only in last segment” heuristic still fails on dotless files (LICENSE, Makefile, Dockerfile) which are common, especially at repo root. Right now they’ll be treated as directories (LICENSE/%) and silently return nothing.
|
||||
|
||||
Best minimal UX: if user provides a path that’s ambiguous (no trailing slash), match either exact file OR directory prefix.
|
||||
|
||||
Plan diff
|
||||
diff
|
||||
Copy code
|
||||
--- a/who-command-design.md
|
||||
+++ b/who-command-design.md
|
||||
@@
|
||||
-/// Build a LIKE pattern from a user-supplied path, with proper LIKE escaping.
|
||||
-///
|
||||
-/// Rules:
|
||||
-/// - If the path ends with `/`, it's a directory prefix → `escaped_path%`
|
||||
-/// - If the last path segment contains `.`, it's a file → exact match
|
||||
-/// - Otherwise, it's a directory prefix → `escaped_path/%`
|
||||
+/// Build an exact + prefix match from a user-supplied path, with proper LIKE escaping.
|
||||
+///
|
||||
+/// Rules:
|
||||
+/// - If the path ends with `/`, treat as directory-only (prefix match)
|
||||
+/// - Otherwise, treat as ambiguous: exact match OR directory prefix
|
||||
+/// (fixes dotless files like LICENSE/Makefile without requiring new flags)
|
||||
@@
|
||||
-fn build_path_pattern(path: &str) -> String {
|
||||
+struct PathMatch {
|
||||
+ exact: String,
|
||||
+ prefix: String,
|
||||
+ dir_only: bool,
|
||||
+}
|
||||
+
|
||||
+fn build_path_match(path: &str) -> PathMatch {
|
||||
let trimmed = path.trim_end_matches('/');
|
||||
- let last_segment = trimmed.rsplit('/').next().unwrap_or(trimmed);
|
||||
- let is_file = !path.ends_with('/') && last_segment.contains('.');
|
||||
let escaped = escape_like(trimmed);
|
||||
-
|
||||
- if is_file {
|
||||
- escaped
|
||||
- } else {
|
||||
- format!("{escaped}/%")
|
||||
- }
|
||||
+ PathMatch {
|
||||
+ exact: escaped.clone(),
|
||||
+ prefix: format!("{escaped}/%"),
|
||||
+ dir_only: path.ends_with('/'),
|
||||
+ }
|
||||
}
|
||||
@@
|
||||
- let path_pattern = build_path_pattern(path);
|
||||
+ let pm = build_path_match(path);
|
||||
@@
|
||||
- AND n.position_new_path LIKE ?1 ESCAPE '\\'
|
||||
+ AND (
|
||||
+ (?4 = 1 AND n.position_new_path LIKE ?2 ESCAPE '\\')
|
||||
+ OR (?4 = 0 AND (n.position_new_path = ?1 OR n.position_new_path LIKE ?2 ESCAPE '\\'))
|
||||
+ )
|
||||
@@
|
||||
- let rows: Vec<(String, String, u32, i64)> = stmt
|
||||
- .query_map(rusqlite::params![path_pattern, since_ms, project_id], |row| {
|
||||
+ let rows: Vec<(String, String, u32, i64)> = stmt
|
||||
+ .query_map(rusqlite::params![pm.exact, pm.prefix, since_ms, i32::from(pm.dir_only), project_id], |row| {
|
||||
Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
|
||||
})?
|
||||
|
||||
|
||||
(Apply the same pattern to Overlap mode.)
|
||||
|
||||
Change 4 — Consistently exclude system notes in all DiffNote-based branches (Expert/Overlap author branches currently don’t)
|
||||
Why
|
||||
|
||||
You filter n.is_system = 0 for reviewer branches, but not in the author branches of Expert/Overlap. That can skew “author touch” via system-generated diff notes or bot activity.
|
||||
|
||||
Consistency here improves correctness and also enables more aggressive partial indexing.
|
||||
|
||||
Plan diff
|
||||
diff
|
||||
Copy code
|
||||
--- a/who-command-design.md
|
||||
+++ b/who-command-design.md
|
||||
@@
|
||||
- WHERE n.note_type = 'DiffNote'
|
||||
+ WHERE n.note_type = 'DiffNote'
|
||||
AND n.position_new_path LIKE ?1 ESCAPE '\\'
|
||||
+ AND n.is_system = 0
|
||||
AND m.author_username IS NOT NULL
|
||||
AND n.created_at >= ?2
|
||||
AND (?3 IS NULL OR m.project_id = ?3)
|
||||
@@
|
||||
- WHERE n.note_type = 'DiffNote'
|
||||
+ WHERE n.note_type = 'DiffNote'
|
||||
AND n.position_new_path LIKE ?1 ESCAPE '\\'
|
||||
+ AND n.is_system = 0
|
||||
AND m.state IN ('opened', 'merged')
|
||||
AND m.author_username IS NOT NULL
|
||||
AND n.created_at >= ?2
|
||||
AND (?3 IS NULL OR m.project_id = ?3)
|
||||
|
||||
Change 5 — Rework Migration 017 indexes to match real predicates + add one critical notes index for discussion participation
|
||||
Why
|
||||
|
||||
(a) idx_notes_diffnote_path_created currently leads with note_type even though it’s constant via partial index. You want the leading columns to match your most selective predicates: position_new_path prefix + created_at range, with optional project_id.
|
||||
|
||||
(b) Active + Workload discussion participation repeatedly hits notes by (discussion_id, author_username); you only guarantee notes(discussion_id) is indexed. Adding a narrow partial composite index pays off immediately for both “participants” and “EXISTS user participated” checks.
|
||||
|
||||
(c) The discussions index should focus on (project_id, last_note_at) with a partial predicate; resolvable/resolved a_
|
||||
@@ -1,471 +0,0 @@
|
||||
Below are the revisions I’d make to iteration 2 to improve correctness, determinism, query-plan quality, and multi-project usability without turning this into a bigger product.
|
||||
|
||||
I’m treating your plan as the “source of truth” and showing git-diff style patches against the plan text/code blocks you included.
|
||||
|
||||
Change 1 — Fix project scoping to hit the right index (DiffNote branches)
|
||||
Why
|
||||
|
||||
Your hot-path index is:
|
||||
|
||||
idx_notes_diffnote_path_created ON notes(position_new_path, created_at, project_id) WHERE note_type='DiffNote' AND is_system=0
|
||||
|
||||
But in Expert/Overlap you sometimes scope by m.project_id = ?3 (MR table), not n.project_id = ?3 (notes table). That weakens the optimizer’s ability to use the composite notes index (and can force broader joins before filtering).
|
||||
|
||||
Diff
|
||||
diff
|
||||
Copy code
|
||||
--- a/who-command-design.md
|
||||
+++ b/who-command-design.md
|
||||
@@ Query: Expert Mode @@
|
||||
- AND (?3 IS NULL OR m.project_id = ?3)
|
||||
+ -- IMPORTANT: scope on notes.project_id to maximize use of
|
||||
+ -- idx_notes_diffnote_path_created (notes is the selective table)
|
||||
+ AND (?3 IS NULL OR n.project_id = ?3)
|
||||
|
||||
@@ Query: Overlap Mode @@
|
||||
- AND (?3 IS NULL OR m.project_id = ?3)
|
||||
+ AND (?3 IS NULL OR n.project_id = ?3)
|
||||
|
||||
@@ Query: Overlap Mode (author branch) @@
|
||||
- AND (?3 IS NULL OR m.project_id = ?3)
|
||||
+ AND (?3 IS NULL OR n.project_id = ?3)
|
||||
|
||||
Change 2 — Introduce a “prefix vs exact” path query to avoid LIKE when you don’t need it
|
||||
Why
|
||||
|
||||
For exact file paths (e.g. src/auth/login.rs), you currently do:
|
||||
|
||||
position_new_path LIKE ?1 ESCAPE '\' where ?1 has no wildcard
|
||||
|
||||
That’s logically fine, but it’s a worse signal to the planner than = and can degrade performance depending on collation/case settings.
|
||||
|
||||
This doesn’t violate “static SQL” — you can pick between two static query strings.
|
||||
|
||||
Diff
|
||||
diff
|
||||
Copy code
|
||||
--- a/who-command-design.md
|
||||
+++ b/who-command-design.md
|
||||
@@ Helper: Path Pattern Construction @@
|
||||
-fn build_path_pattern(path: &str) -> String {
|
||||
+struct PathQuery {
|
||||
+ /// The parameter value to bind.
|
||||
+ value: String,
|
||||
+ /// If true: use LIKE value || '%'. If false: use '='.
|
||||
+ is_prefix: bool,
|
||||
+}
|
||||
+
|
||||
+fn build_path_query(path: &str) -> PathQuery {
|
||||
let trimmed = path.trim_end_matches('/');
|
||||
let last_segment = trimmed.rsplit('/').next().unwrap_or(trimmed);
|
||||
let is_file = !path.ends_with('/') && last_segment.contains('.');
|
||||
let escaped = escape_like(trimmed);
|
||||
|
||||
if is_file {
|
||||
- escaped
|
||||
+ PathQuery { value: escaped, is_prefix: false }
|
||||
} else {
|
||||
- format!("{escaped}/%")
|
||||
+ PathQuery { value: format!("{escaped}/%"), is_prefix: true }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
And then (example for DiffNote predicates):
|
||||
|
||||
diff
|
||||
Copy code
|
||||
@@ Query: Expert Mode @@
|
||||
- let path_pattern = build_path_pattern(path);
|
||||
+ let pq = build_path_query(path);
|
||||
|
||||
- let sql = " ... n.position_new_path LIKE ?1 ESCAPE '\\' ... ";
|
||||
+ let sql_prefix = " ... n.position_new_path LIKE ?1 ESCAPE '\\' ... ";
|
||||
+ let sql_exact = " ... n.position_new_path = ?1 ... ";
|
||||
|
||||
- let mut stmt = conn.prepare(sql)?;
|
||||
+ let mut stmt = if pq.is_prefix { conn.prepare_cached(sql_prefix)? }
|
||||
+ else { conn.prepare_cached(sql_exact)? };
|
||||
let rows = stmt.query_map(params![... pq.value ...], ...);
|
||||
|
||||
Change 3 — Push Expert aggregation into SQL (less Rust, fewer rows, SQL-level LIMIT)
|
||||
Why
|
||||
|
||||
Right now Expert does:
|
||||
|
||||
UNION ALL
|
||||
|
||||
return per-role rows
|
||||
|
||||
HashMap merge
|
||||
|
||||
score compute
|
||||
|
||||
sort/truncate
|
||||
|
||||
You can do all of that in SQL deterministically, then LIMIT ?N actually works.
|
||||
|
||||
Diff
|
||||
diff
|
||||
Copy code
|
||||
--- a/who-command-design.md
|
||||
+++ b/who-command-design.md
|
||||
@@ Query: Expert Mode @@
|
||||
- let sql = "SELECT username, role, activity_count, last_active_at FROM (
|
||||
- ...
|
||||
- )";
|
||||
+ let sql = "
|
||||
+ WITH activity AS (
|
||||
+ SELECT
|
||||
+ n.author_username AS username,
|
||||
+ 'reviewer' AS role,
|
||||
+ COUNT(*) AS cnt,
|
||||
+ MAX(n.created_at) AS last_active_at
|
||||
+ FROM notes n
|
||||
+ WHERE n.note_type = 'DiffNote'
|
||||
+ AND n.is_system = 0
|
||||
+ AND n.author_username IS NOT NULL
|
||||
+ AND n.created_at >= ?2
|
||||
+ AND (?3 IS NULL OR n.project_id = ?3)
|
||||
+ AND (
|
||||
+ (?4 = 1 AND n.position_new_path LIKE ?1 ESCAPE '\\') OR
|
||||
+ (?4 = 0 AND n.position_new_path = ?1)
|
||||
+ )
|
||||
+ GROUP BY n.author_username
|
||||
+
|
||||
+ UNION ALL
|
||||
+
|
||||
+ SELECT
|
||||
+ m.author_username AS username,
|
||||
+ 'author' AS role,
|
||||
+ COUNT(DISTINCT m.id) AS cnt,
|
||||
+ MAX(n.created_at) AS last_active_at
|
||||
+ FROM merge_requests m
|
||||
+ JOIN discussions d ON d.merge_request_id = m.id
|
||||
+ JOIN notes n ON n.discussion_id = d.id
|
||||
+ WHERE n.note_type = 'DiffNote'
|
||||
+ AND n.is_system = 0
|
||||
+ AND m.author_username IS NOT NULL
|
||||
+ AND n.created_at >= ?2
|
||||
+ AND (?3 IS NULL OR n.project_id = ?3)
|
||||
+ AND (
|
||||
+ (?4 = 1 AND n.position_new_path LIKE ?1 ESCAPE '\\') OR
|
||||
+ (?4 = 0 AND n.position_new_path = ?1)
|
||||
+ )
|
||||
+ GROUP BY m.author_username
|
||||
+ )
|
||||
+ SELECT
|
||||
+ username,
|
||||
+ SUM(CASE WHEN role='reviewer' THEN cnt ELSE 0 END) AS review_count,
|
||||
+ SUM(CASE WHEN role='author' THEN cnt ELSE 0 END) AS author_count,
|
||||
+ MAX(last_active_at) AS last_active_at,
|
||||
+ (SUM(CASE WHEN role='reviewer' THEN cnt ELSE 0 END) * 3.0) +
|
||||
+ (SUM(CASE WHEN role='author' THEN cnt ELSE 0 END) * 2.0) AS score
|
||||
+ FROM activity
|
||||
+ GROUP BY username
|
||||
+ ORDER BY score DESC, last_active_at DESC, username ASC
|
||||
+ LIMIT ?5
|
||||
+ ";
|
||||
|
||||
- // Aggregate by username: combine reviewer + author counts
|
||||
- let mut user_map: HashMap<...> = HashMap::new();
|
||||
- ...
|
||||
- experts.sort_by(...); experts.truncate(limit);
|
||||
+ // No Rust-side merge/sort needed; SQL already returns final rows.
|
||||
|
||||
Change 4 — Overlap output is ambiguous across projects: include stable MR refs (project_path!iid)
|
||||
Why
|
||||
|
||||
mr_iids: Vec<i64> is ambiguous in a multi-project DB. !123 only means something with a project.
|
||||
|
||||
Also: your MR IID dedup is currently Vec.contains() inside a loop (O(n²)). Use a HashSet.
|
||||
|
||||
Diff
|
||||
diff
|
||||
Copy code
|
||||
--- a/who-command-design.md
|
||||
+++ b/who-command-design.md
|
||||
@@ OverlapResult @@
|
||||
pub struct OverlapUser {
|
||||
pub username: String,
|
||||
@@
|
||||
- pub mr_iids: Vec<i64>,
|
||||
+ /// Stable MR references like "group/project!123"
|
||||
+ pub mr_refs: Vec<String>,
|
||||
}
|
||||
|
||||
@@ Query: Overlap Mode (SQL) @@
|
||||
- GROUP_CONCAT(DISTINCT m.iid) AS mr_iids
|
||||
+ GROUP_CONCAT(DISTINCT (p.path_with_namespace || '!' || m.iid)) AS mr_refs
|
||||
FROM notes n
|
||||
JOIN discussions d ON n.discussion_id = d.id
|
||||
JOIN merge_requests m ON d.merge_request_id = m.id
|
||||
+ JOIN projects p ON m.project_id = p.id
|
||||
@@
|
||||
- GROUP_CONCAT(DISTINCT m.iid) AS mr_iids
|
||||
+ GROUP_CONCAT(DISTINCT (p.path_with_namespace || '!' || m.iid)) AS mr_refs
|
||||
FROM merge_requests m
|
||||
JOIN discussions d ON d.merge_request_id = m.id
|
||||
JOIN notes n ON n.discussion_id = d.id
|
||||
+ JOIN projects p ON m.project_id = p.id
|
||||
|
||||
@@ Query: Overlap Mode (Rust merge) @@
|
||||
- let mr_iids: Vec<i64> = mr_iids_csv ...
|
||||
+ let mr_refs: Vec<String> = mr_refs_csv
|
||||
+ .as_deref()
|
||||
+ .map(|csv| csv.split(',').map(|s| s.trim().to_string()).collect())
|
||||
+ .unwrap_or_default();
|
||||
@@
|
||||
- // Merge MR IIDs, deduplicate
|
||||
- for iid in &mr_iids {
|
||||
- if !entry.mr_iids.contains(iid) {
|
||||
- entry.mr_iids.push(*iid);
|
||||
- }
|
||||
- }
|
||||
+ // Merge MR refs, deduplicate
|
||||
+ use std::collections::HashSet;
|
||||
+ let mut set: HashSet<String> = entry.mr_refs.drain(..).collect();
|
||||
+ for r in mr_refs { set.insert(r); }
|
||||
+ entry.mr_refs = set.into_iter().collect();
|
||||
|
||||
Change 5 — Active mode: avoid correlated subqueries by preselecting discussions, then aggregating notes once
|
||||
Why
|
||||
|
||||
Your Active query does two correlated subqueries per discussion row:
|
||||
|
||||
note_count
|
||||
|
||||
participants
|
||||
|
||||
With LIMIT 20 it’s not catastrophic, but it is still unnecessary work and creates “spiky” behavior if the planner chooses poorly.
|
||||
|
||||
Pattern to use:
|
||||
|
||||
CTE selects the limited set of discussions
|
||||
|
||||
Join notes once, aggregate with GROUP BY
|
||||
|
||||
Diff
|
||||
diff
|
||||
Copy code
|
||||
--- a/who-command-design.md
|
||||
+++ b/who-command-design.md
|
||||
@@ Query: Active Mode @@
|
||||
- let sql =
|
||||
- "SELECT
|
||||
- d.noteable_type,
|
||||
- ...
|
||||
- (SELECT COUNT(*) FROM notes n
|
||||
- WHERE n.discussion_id = d.id AND n.is_system = 0) AS note_count,
|
||||
- (SELECT GROUP_CONCAT(username, X'1F') FROM (
|
||||
- SELECT DISTINCT n.author_username AS username
|
||||
- FROM notes n
|
||||
- WHERE n.discussion_id = d.id
|
||||
- AND n.is_system = 0
|
||||
- AND n.author_username IS NOT NULL
|
||||
- ORDER BY username
|
||||
- )) AS participants
|
||||
- FROM discussions d
|
||||
- ...
|
||||
- LIMIT ?3";
|
||||
+ let sql = "
|
||||
+ WITH picked AS (
|
||||
+ SELECT d.id, d.noteable_type, d.issue_id, d.merge_request_id, d.project_id, d.last_note_at
|
||||
+ FROM discussions d
|
||||
+ WHERE d.resolvable = 1 AND d.resolved = 0
|
||||
+ AND d.last_note_at >= ?1
|
||||
+ AND (?2 IS NULL OR d.project_id = ?2)
|
||||
+ ORDER BY d.last_note_at DESC
|
||||
+ LIMIT ?3
|
||||
+ ),
|
||||
+ note_agg AS (
|
||||
+ SELECT
|
||||
+ n.discussion_id,
|
||||
+ COUNT(*) AS note_count,
|
||||
+ GROUP_CONCAT(n.author_username, X'1F') AS participants
|
||||
+ FROM (
|
||||
+ SELECT DISTINCT discussion_id, author_username
|
||||
+ FROM notes
|
||||
+ WHERE is_system = 0 AND author_username IS NOT NULL
|
||||
+ ) n
|
||||
+ JOIN picked p ON p.id = n.discussion_id
|
||||
+ GROUP BY n.discussion_id
|
||||
+ )
|
||||
+ SELECT
|
||||
+ p.noteable_type,
|
||||
+ COALESCE(i.iid, m.iid) AS entity_iid,
|
||||
+ COALESCE(i.title, m.title) AS entity_title,
|
||||
+ proj.path_with_namespace,
|
||||
+ p.last_note_at,
|
||||
+ COALESCE(na.note_count, 0) AS note_count,
|
||||
+ COALESCE(na.participants, '') AS participants
|
||||
+ FROM picked p
|
||||
+ JOIN projects proj ON p.project_id = proj.id
|
||||
+ LEFT JOIN issues i ON p.issue_id = i.id
|
||||
+ LEFT JOIN merge_requests m ON p.merge_request_id = m.id
|
||||
+ LEFT JOIN note_agg na ON na.discussion_id = p.id
|
||||
+ ORDER BY p.last_note_at DESC
|
||||
+ ";
|
||||
|
||||
Change 6 — Use prepare_cached() everywhere (cheap perf win, no scope creep)
|
||||
Why
|
||||
|
||||
You already worked hard to keep SQL static. Taking advantage of sqlite statement caching completes the loop.
|
||||
|
||||
Diff
|
||||
diff
|
||||
Copy code
|
||||
--- a/who-command-design.md
|
||||
+++ b/who-command-design.md
|
||||
@@ Query functions @@
|
||||
- let mut stmt = conn.prepare(sql)?;
|
||||
+ let mut stmt = conn.prepare_cached(sql)?;
|
||||
|
||||
|
||||
Apply in all query fns (query_workload, query_reviews, query_active, query_expert, query_overlap, lookup_project_path).
|
||||
|
||||
Change 7 — Human output: show project_path where ambiguity exists (Workload + Overlap)
|
||||
Why
|
||||
|
||||
When not project-scoped, #42 and !100 aren’t unique. You already have project paths in the query results — you’re just not printing them.
|
||||
|
||||
Diff
|
||||
diff
|
||||
Copy code
|
||||
--- a/who-command-design.md
|
||||
+++ b/who-command-design.md
|
||||
@@ print_workload_human @@
|
||||
- println!(
|
||||
- " {} {} {}",
|
||||
+ println!(
|
||||
+ " {} {} {} {}",
|
||||
style(format!("#{:<5}", item.iid)).cyan(),
|
||||
truncate_str(&item.title, 45),
|
||||
style(format_relative_time(item.updated_at)).dim(),
|
||||
+ style(&item.project_path).dim(),
|
||||
);
|
||||
|
||||
@@ print_workload_human (MRs) @@
|
||||
- println!(
|
||||
- " {} {}{} {}",
|
||||
+ println!(
|
||||
+ " {} {}{} {} {}",
|
||||
style(format!("!{:<5}", mr.iid)).cyan(),
|
||||
truncate_str(&mr.title, 40),
|
||||
style(draft).dim(),
|
||||
style(format_relative_time(mr.updated_at)).dim(),
|
||||
+ style(&mr.project_path).dim(),
|
||||
);
|
||||
|
||||
@@ print_overlap_human @@
|
||||
- let mr_str = user.mr_iids.iter().take(5).map(|iid| format!("!{iid}")).collect::<Vec<_>>().join(", ");
|
||||
+ let mr_str = user.mr_refs.iter().take(5).cloned().collect::<Vec<_>>().join(", ");
|
||||
|
||||
Change 8 — Robot JSON: add stable IDs + “defaulted” flags for reproducibility
|
||||
Why
|
||||
|
||||
You already added resolved_input — good. Two more reproducibility gaps remain:
|
||||
|
||||
Agents can’t reliably “open” an entity without IDs (discussion_id, mr_id, issue_id).
|
||||
|
||||
Agents can’t tell whether since was user-provided vs defaulted (important when replaying intent).
|
||||
|
||||
Diff
|
||||
diff
|
||||
Copy code
|
||||
--- a/who-command-design.md
|
||||
+++ b/who-command-design.md
|
||||
@@ WhoResolvedInput @@
|
||||
pub struct WhoResolvedInput {
|
||||
@@
|
||||
pub since_ms: Option<i64>,
|
||||
pub since_iso: Option<String>,
|
||||
+ pub since_was_default: bool,
|
||||
pub limit: usize,
|
||||
}
|
||||
|
||||
@@ run_who @@
|
||||
- let since_ms = resolve_since(args.since.as_deref(), "6m")?;
|
||||
+ let since_was_default = args.since.is_none();
|
||||
+ let since_ms = resolve_since(args.since.as_deref(), "6m")?;
|
||||
Ok(WhoRun {
|
||||
resolved_input: WhoResolvedInput {
|
||||
@@
|
||||
since_ms: Some(since_ms),
|
||||
since_iso: Some(ms_to_iso(since_ms)),
|
||||
+ since_was_default,
|
||||
limit: args.limit,
|
||||
},
|
||||
|
||||
@@ print_who_json resolved_input @@
|
||||
let resolved_input = serde_json::json!({
|
||||
@@
|
||||
"since_ms": run.resolved_input.since_ms,
|
||||
"since_iso": run.resolved_input.since_iso,
|
||||
+ "since_was_default": run.resolved_input.since_was_default,
|
||||
"limit": run.resolved_input.limit,
|
||||
});
|
||||
|
||||
|
||||
And for Active/Workload discussion items, add IDs in SQL and JSON:
|
||||
|
||||
diff
|
||||
Copy code
|
||||
@@ ActiveDiscussion @@
|
||||
pub struct ActiveDiscussion {
|
||||
+ pub discussion_id: i64,
|
||||
@@
|
||||
}
|
||||
|
||||
@@ query_active SELECT @@
|
||||
- SELECT
|
||||
- p.noteable_type,
|
||||
+ SELECT
|
||||
+ p.id AS discussion_id,
|
||||
+ p.noteable_type,
|
||||
|
||||
@@ active_to_json @@
|
||||
- "discussions": r.discussions.iter().map(|d| json!({
|
||||
+ "discussions": r.discussions.iter().map(|d| json!({
|
||||
+ "discussion_id": d.discussion_id,
|
||||
...
|
||||
}))
|
||||
|
||||
Change 9 — Make performance verification explicit: require EXPLAIN QUERY PLAN checks for each mode
|
||||
Why
|
||||
|
||||
You’re adding indexes specifically for these queries. The only way to ensure the planner is doing what you think is to lock in a short perf checklist (especially after schema drift or SQLite version differences).
|
||||
|
||||
Diff
|
||||
diff
|
||||
Copy code
|
||||
--- a/who-command-design.md
|
||||
+++ b/who-command-design.md
|
||||
@@ Verification @@
|
||||
# Manual verification against real data
|
||||
cargo run --release -- who src/features/global-search/
|
||||
@@
|
||||
cargo run --release -- who src/features/global-search/ -p typescript # project scoped
|
||||
+
|
||||
+# Perf verification (required before merge):
|
||||
+# Confirm idx_notes_diffnote_path_created is used for Expert/Overlap and
|
||||
+# idx_discussions_unresolved_recent is used for Active.
|
||||
+sqlite3 path/to/db.sqlite "
|
||||
+ EXPLAIN QUERY PLAN
|
||||
+ SELECT ... -- paste final Expert SQL with representative bindings
|
||||
+";
|
||||
|
||||
|
||||
(Keep it lightweight: one representative query per mode is enough.)
|
||||
|
||||
Net effect
|
||||
|
||||
Correctness: project scoping hits the notes index; IDs added for agent workflows.
|
||||
|
||||
Performance: fewer rows/materialization in Expert; statement caching everywhere; Active avoids correlated subqueries.
|
||||
|
||||
UX: human output no longer ambiguous across projects; Overlap MR references become actionable.
|
||||
|
||||
Reproducibility: agents can distinguish defaults vs explicit inputs; can dereference entities reliably.
|
||||
|
||||
If you want one “highest ROI” subset to implement first: Change 1 + Change 4 + Change 6 + Change 7. That’s where the real operational value lands.
|
||||
@@ -1,3 +0,0 @@
|
||||
ChatGPT said:
|
||||
Proposing code revisions for performance and determinism
|
||||
Answer now
|
||||
@@ -1,356 +0,0 @@
|
||||
Below are the highest-leverage revisions I’d make. They’re tightly scoped (no new tables/APIs), but fix a few real correctness issues and make the outputs more actionable.
|
||||
|
||||
1) Fix a correctness bug in PathQuery: don’t escape for =, and make --path Makefile actually work
|
||||
Why
|
||||
|
||||
Bug: build_path_query() currently runs escape_like() even when is_prefix = false (exact match). That will break exact matches for paths containing _, %, or \ because = does not treat those as metacharacters (so the escaped string won’t equal the stored path).
|
||||
|
||||
UX mismatch: The plan says --path handles dotless root files (Makefile/LICENSE), but the current logic still treats them as directory prefixes (Makefile/%) → zero results.
|
||||
|
||||
Change
|
||||
|
||||
Only escape for LIKE.
|
||||
|
||||
Treat root paths (no /) passed via --path as exact matches by default (unless they end with /).
|
||||
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/plan.md b/plan.md
|
||||
@@
|
||||
-/// Build a path query from a user-supplied path.
|
||||
-///
|
||||
-/// Rules:
|
||||
-/// - If the path ends with `/`, it's a directory prefix -> `escaped_path%` (LIKE)
|
||||
-/// - If the last path segment contains `.`, it's a file -> exact match (=)
|
||||
-/// - Otherwise, it's a directory prefix -> `escaped_path/%` (LIKE)
|
||||
+/// Build a path query from a user-supplied path.
|
||||
+///
|
||||
+/// Rules:
|
||||
+/// - If the path ends with `/`, it's a directory prefix -> `escaped_path/%` (LIKE)
|
||||
+/// - If the path is a root path (no `/`) and does NOT end with `/`, treat as exact (=)
|
||||
+/// (this makes `--path Makefile` and `--path LICENSE` work as intended)
|
||||
+/// - Else if the last path segment contains `.`, treat as exact (=)
|
||||
+/// - Otherwise, treat as directory prefix -> `escaped_path/%` (LIKE)
|
||||
@@
|
||||
-fn build_path_query(path: &str) -> PathQuery {
|
||||
+fn build_path_query(path: &str) -> PathQuery {
|
||||
let trimmed = path.trim_end_matches('/');
|
||||
let last_segment = trimmed.rsplit('/').next().unwrap_or(trimmed);
|
||||
- let is_file = !path.ends_with('/') && last_segment.contains('.');
|
||||
- let escaped = escape_like(trimmed);
|
||||
+ let is_root = !trimmed.contains('/');
|
||||
+ let is_file = !path.ends_with('/') && (is_root || last_segment.contains('.'));
|
||||
|
||||
if is_file {
|
||||
PathQuery {
|
||||
- value: escaped,
|
||||
+ // IMPORTANT: do NOT escape for exact match (=)
|
||||
+ value: trimmed.to_string(),
|
||||
is_prefix: false,
|
||||
}
|
||||
} else {
|
||||
+ let escaped = escape_like(trimmed);
|
||||
PathQuery {
|
||||
value: format!("{escaped}/%"),
|
||||
is_prefix: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@
|
||||
-/// **Known limitation:** Dotless root files (LICENSE, Makefile, Dockerfile)
|
||||
-/// without a trailing `/` will be treated as directory prefixes. Use `--path`
|
||||
-/// for these — the `--path` flag passes through to Expert mode directly,
|
||||
-/// and the `build_path_query` output for "LICENSE" is a prefix `LICENSE/%`
|
||||
-/// which will simply return zero results (a safe, obvious failure mode that the
|
||||
-/// help text addresses).
|
||||
+/// Note: Root file paths passed via `--path` (including dotless files like Makefile/LICENSE)
|
||||
+/// are treated as exact matches unless they end with `/`.
|
||||
|
||||
|
||||
Also update the --path help text to be explicit:
|
||||
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/plan.md b/plan.md
|
||||
@@
|
||||
- /// Force expert mode for a file/directory path (handles root files like
|
||||
- /// README.md, LICENSE, Makefile that lack a / and can't be auto-detected)
|
||||
+ /// Force expert mode for a file/directory path.
|
||||
+ /// Root files (README.md, LICENSE, Makefile) are treated as exact matches.
|
||||
+ /// Use a trailing `/` to force directory-prefix matching.
|
||||
|
||||
2) Fix Active mode: your note_count is currently counting participants, and the CTE scans too broadly
|
||||
Why
|
||||
|
||||
In note_agg, you do SELECT DISTINCT discussion_id, author_username and then COUNT(*) AS note_count. That’s participant count, not note count.
|
||||
|
||||
The current note_agg also builds the DISTINCT set from all notes then joins to picked. It’s avoidable work.
|
||||
|
||||
Change
|
||||
|
||||
Split into two aggregations scoped to picked:
|
||||
|
||||
note_counts: counts non-system notes per picked discussion.
|
||||
|
||||
participants: distinct usernames per picked discussion, then GROUP_CONCAT.
|
||||
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/plan.md b/plan.md
|
||||
@@
|
||||
- note_agg AS (
|
||||
- SELECT
|
||||
- n.discussion_id,
|
||||
- COUNT(*) AS note_count,
|
||||
- GROUP_CONCAT(n.author_username, X'1F') AS participants
|
||||
- FROM (
|
||||
- SELECT DISTINCT discussion_id, author_username
|
||||
- FROM notes
|
||||
- WHERE is_system = 0 AND author_username IS NOT NULL
|
||||
- ) n
|
||||
- JOIN picked p ON p.id = n.discussion_id
|
||||
- GROUP BY n.discussion_id
|
||||
- )
|
||||
+ note_counts AS (
|
||||
+ SELECT
|
||||
+ n.discussion_id,
|
||||
+ COUNT(*) AS note_count
|
||||
+ FROM notes n
|
||||
+ JOIN picked p ON p.id = n.discussion_id
|
||||
+ WHERE n.is_system = 0
|
||||
+ GROUP BY n.discussion_id
|
||||
+ ),
|
||||
+ participants AS (
|
||||
+ SELECT
|
||||
+ x.discussion_id,
|
||||
+ GROUP_CONCAT(x.author_username, X'1F') AS participants
|
||||
+ FROM (
|
||||
+ SELECT DISTINCT n.discussion_id, n.author_username
|
||||
+ FROM notes n
|
||||
+ JOIN picked p ON p.id = n.discussion_id
|
||||
+ WHERE n.is_system = 0 AND n.author_username IS NOT NULL
|
||||
+ ) x
|
||||
+ GROUP BY x.discussion_id
|
||||
+ )
|
||||
@@
|
||||
- LEFT JOIN note_agg na ON na.discussion_id = p.id
|
||||
+ LEFT JOIN note_counts nc ON nc.discussion_id = p.id
|
||||
+ LEFT JOIN participants pa ON pa.discussion_id = p.id
|
||||
@@
|
||||
- COALESCE(na.note_count, 0) AS note_count,
|
||||
- COALESCE(na.participants, '') AS participants
|
||||
+ COALESCE(nc.note_count, 0) AS note_count,
|
||||
+ COALESCE(pa.participants, '') AS participants
|
||||
|
||||
|
||||
Net effect: correctness fix + more predictable perf.
|
||||
|
||||
Add a test that would have failed before:
|
||||
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/plan.md b/plan.md
|
||||
@@
|
||||
#[test]
|
||||
fn test_active_query() {
|
||||
@@
|
||||
- insert_diffnote(&conn, 1, 1, 1, "reviewer_b", "src/foo.rs", "needs work");
|
||||
+ insert_diffnote(&conn, 1, 1, 1, "reviewer_b", "src/foo.rs", "needs work");
|
||||
+ insert_diffnote(&conn, 2, 1, 1, "reviewer_b", "src/foo.rs", "follow-up");
|
||||
@@
|
||||
- assert_eq!(result.discussions[0].participants, vec!["reviewer_b"]);
|
||||
+ assert_eq!(result.discussions[0].participants, vec!["reviewer_b"]);
|
||||
+ assert_eq!(result.discussions[0].note_count, 2);
|
||||
|
||||
3) Index fix: idx_discussions_unresolved_recent won’t help global --active ordering
|
||||
Why
|
||||
|
||||
Your index is (project_id, last_note_at) with WHERE resolvable=1 AND resolved=0.
|
||||
|
||||
When --active is not project-scoped (common default), SQLite can’t use (project_id, last_note_at) to satisfy ORDER BY last_note_at DESC efficiently because project_id isn’t constrained.
|
||||
|
||||
This can turn into a scan+sort over potentially large unresolved sets.
|
||||
|
||||
Change
|
||||
|
||||
Keep the project-scoped index, but add a global ordering index (partial, still small):
|
||||
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/plan.md b/plan.md
|
||||
@@
|
||||
CREATE INDEX IF NOT EXISTS idx_discussions_unresolved_recent
|
||||
ON discussions(project_id, last_note_at)
|
||||
WHERE resolvable = 1 AND resolved = 0;
|
||||
+
|
||||
+-- Active (global): unresolved discussions by recency (no project scope).
|
||||
+-- Supports ORDER BY last_note_at DESC LIMIT N when project_id is unconstrained.
|
||||
+CREATE INDEX IF NOT EXISTS idx_discussions_unresolved_recent_global
|
||||
+ ON discussions(last_note_at)
|
||||
+ WHERE resolvable = 1 AND resolved = 0;
|
||||
|
||||
4) Make Overlap “touches” coherent: count MRs for reviewers, not DiffNotes
|
||||
Why
|
||||
|
||||
Overlap’s question is “Who else has MRs touching my files?” but:
|
||||
|
||||
reviewer branch uses COUNT(*) (DiffNotes)
|
||||
|
||||
author branch uses COUNT(DISTINCT m.id) (MRs)
|
||||
|
||||
Those are different units; summing them into touch_count is misleading.
|
||||
|
||||
Change
|
||||
|
||||
Count distinct MRs on the reviewer branch too:
|
||||
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/plan.md b/plan.md
|
||||
@@
|
||||
- COUNT(*) AS touch_count,
|
||||
+ COUNT(DISTINCT m.id) AS touch_count,
|
||||
MAX(n.created_at) AS last_touch_at,
|
||||
GROUP_CONCAT(DISTINCT (p.path_with_namespace || '!' || m.iid)) AS mr_refs
|
||||
|
||||
|
||||
Also update human output labeling:
|
||||
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/plan.md b/plan.md
|
||||
@@
|
||||
- style("Touches").bold(),
|
||||
+ style("MRs").bold(),
|
||||
|
||||
|
||||
(You still preserve “strength” via mr_refs and last_touch_at.)
|
||||
|
||||
5) Make outputs more actionable: add a canonical ref field (group/project!iid, group/project#iid)
|
||||
Why
|
||||
|
||||
You already do this for Overlap (mr_refs). Doing the same for Workload and Active reduces friction for both humans and agents:
|
||||
|
||||
humans can copy/paste a single token
|
||||
|
||||
robots don’t need to stitch project_path + iid + prefix
|
||||
|
||||
Change (Workload structs + SQL)
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/plan.md b/plan.md
|
||||
@@
|
||||
pub struct WorkloadIssue {
|
||||
pub iid: i64,
|
||||
+ pub ref_: String,
|
||||
pub title: String,
|
||||
pub project_path: String,
|
||||
pub updated_at: i64,
|
||||
}
|
||||
@@
|
||||
pub struct WorkloadMr {
|
||||
pub iid: i64,
|
||||
+ pub ref_: String,
|
||||
pub title: String,
|
||||
pub draft: bool,
|
||||
pub project_path: String,
|
||||
@@
|
||||
- let issues_sql =
|
||||
- "SELECT i.iid, i.title, p.path_with_namespace, i.updated_at
|
||||
+ let issues_sql =
|
||||
+ "SELECT i.iid,
|
||||
+ (p.path_with_namespace || '#' || i.iid) AS ref,
|
||||
+ i.title, p.path_with_namespace, i.updated_at
|
||||
@@
|
||||
- iid: row.get(0)?,
|
||||
- title: row.get(1)?,
|
||||
- project_path: row.get(2)?,
|
||||
- updated_at: row.get(3)?,
|
||||
+ iid: row.get(0)?,
|
||||
+ ref_: row.get(1)?,
|
||||
+ title: row.get(2)?,
|
||||
+ project_path: row.get(3)?,
|
||||
+ updated_at: row.get(4)?,
|
||||
})
|
||||
@@
|
||||
- let authored_sql =
|
||||
- "SELECT m.iid, m.title, m.draft, p.path_with_namespace, m.updated_at
|
||||
+ let authored_sql =
|
||||
+ "SELECT m.iid,
|
||||
+ (p.path_with_namespace || '!' || m.iid) AS ref,
|
||||
+ m.title, m.draft, p.path_with_namespace, m.updated_at
|
||||
@@
|
||||
- iid: row.get(0)?,
|
||||
- title: row.get(1)?,
|
||||
- draft: row.get::<_, i32>(2)? != 0,
|
||||
- project_path: row.get(3)?,
|
||||
+ iid: row.get(0)?,
|
||||
+ ref_: row.get(1)?,
|
||||
+ title: row.get(2)?,
|
||||
+ draft: row.get::<_, i32>(3)? != 0,
|
||||
+ project_path: row.get(4)?,
|
||||
author_username: None,
|
||||
- updated_at: row.get(4)?,
|
||||
+ updated_at: row.get(5)?,
|
||||
})
|
||||
|
||||
|
||||
Then use ref_ in human output + robot JSON.
|
||||
|
||||
6) Reviews mode: tolerate leading whitespace before **prefix**
|
||||
Why
|
||||
|
||||
Many people write " **suggestion**: ...". Current LIKE '**%**%' misses that.
|
||||
|
||||
Change
|
||||
|
||||
Use ltrim(n.body) consistently:
|
||||
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/plan.md b/plan.md
|
||||
@@
|
||||
- AND n.body LIKE '**%**%'
|
||||
+ AND ltrim(n.body) LIKE '**%**%'
|
||||
@@
|
||||
- SUBSTR(n.body, 3, INSTR(SUBSTR(n.body, 3), '**') - 1) AS raw_prefix,
|
||||
+ SUBSTR(ltrim(n.body), 3, INSTR(SUBSTR(ltrim(n.body), 3), '**') - 1) AS raw_prefix,
|
||||
|
||||
7) Add two small tests that catch the above regressions
|
||||
Why
|
||||
|
||||
These are exactly the kind of issues that slip through without targeted tests.
|
||||
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/plan.md b/plan.md
|
||||
@@
|
||||
#[test]
|
||||
fn test_escape_like() {
|
||||
@@
|
||||
}
|
||||
+
|
||||
+ #[test]
|
||||
+ fn test_build_path_query_exact_does_not_escape() {
|
||||
+ // '_' must not be escaped for '='
|
||||
+ let pq = build_path_query("README_with_underscore.md");
|
||||
+ assert_eq!(pq.value, "README_with_underscore.md");
|
||||
+ assert!(!pq.is_prefix);
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn test_path_flag_dotless_root_file_is_exact() {
|
||||
+ let pq = build_path_query("Makefile");
|
||||
+ assert_eq!(pq.value, "Makefile");
|
||||
+ assert!(!pq.is_prefix);
|
||||
+ }
|
||||
|
||||
Summary of net effect
|
||||
|
||||
Correctness fixes: exact-path escaping bug; Active.note_count bug.
|
||||
|
||||
Perf fixes: global --active index; avoid broad note scans in Active.
|
||||
|
||||
Usefulness upgrades: coherent overlap “touch” metric; canonical refs everywhere; reviews prefix more robust.
|
||||
|
||||
If you want one extra “stretch” that still isn’t scope creep: add an unscoped warning line in human output when project_id == None (e.g., “Aggregated across projects; use -p to scope”) for Expert/Overlap/Active. That’s pure presentation, but prevents misinterpretation in multi-project DBs.
|
||||
@@ -1,471 +0,0 @@
|
||||
Proposed revisions (Iteration 6)
|
||||
|
||||
Below are the highest-leverage changes I’d make on top of your current Iteration 5 plan, with rationale and git-diff style edits to the plan text/snippets.
|
||||
|
||||
1) Fix a real edge case: dotless non-root files (src/Dockerfile, infra/Makefile, etc.)
|
||||
Why
|
||||
|
||||
Your current build_path_query() treats dotless last segments as directories (prefix match) unless the path is root. That misclassifies legitimate dotless files inside directories and silently produces path/% (zero hits or wrong hits).
|
||||
|
||||
Best minimal fix: keep your static SQL approach, but add a DB existence probe (static SQL) for path queries:
|
||||
|
||||
If user didn’t force directory (/), and exact path exists in DiffNotes, treat as exact =.
|
||||
|
||||
Otherwise use prefix LIKE 'dir/%'.
|
||||
|
||||
This avoids new CLI flags, avoids heuristics lists, and uses your existing partial index (idx_notes_diffnote_path_created) efficiently.
|
||||
|
||||
Diff
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/Plan.md b/Plan.md
|
||||
@@
|
||||
-struct PathQuery {
|
||||
+struct PathQuery {
|
||||
/// The parameter value to bind.
|
||||
value: String,
|
||||
/// If true: use `LIKE value ESCAPE '\'`. If false: use `= value`.
|
||||
is_prefix: bool,
|
||||
}
|
||||
|
||||
-/// Build a path query from a user-supplied path.
|
||||
+/// Build a path query from a user-supplied path, with a DB probe for dotless files.
|
||||
@@
|
||||
-fn build_path_query(path: &str) -> PathQuery {
|
||||
+fn build_path_query(conn: &Connection, path: &str) -> Result<PathQuery> {
|
||||
let trimmed = path.trim_end_matches('/');
|
||||
let last_segment = trimmed.rsplit('/').next().unwrap_or(trimmed);
|
||||
let is_root = !trimmed.contains('/');
|
||||
- let is_file = !path.ends_with('/') && (is_root || last_segment.contains('.'));
|
||||
+ let forced_dir = path.ends_with('/');
|
||||
+ let looks_like_file = !forced_dir && (is_root || last_segment.contains('.'));
|
||||
+
|
||||
+ // If it doesn't "look like a file" but the exact path exists in DiffNotes,
|
||||
+ // treat as exact (handles src/Dockerfile, infra/Makefile, etc.).
|
||||
+ let exact_exists = if !looks_like_file && !forced_dir {
|
||||
+ conn.query_row(
|
||||
+ "SELECT 1
|
||||
+ FROM notes
|
||||
+ WHERE note_type = 'DiffNote'
|
||||
+ AND is_system = 0
|
||||
+ AND position_new_path = ?1
|
||||
+ LIMIT 1",
|
||||
+ rusqlite::params![trimmed],
|
||||
+ |_| Ok(()),
|
||||
+ ).is_ok()
|
||||
+ } else {
|
||||
+ false
|
||||
+ };
|
||||
+
|
||||
+ let is_file = looks_like_file || exact_exists;
|
||||
|
||||
if is_file {
|
||||
PathQuery {
|
||||
value: trimmed.to_string(),
|
||||
is_prefix: false,
|
||||
}
|
||||
} else {
|
||||
let escaped = escape_like(trimmed);
|
||||
PathQuery {
|
||||
value: format!("{escaped}/%"),
|
||||
is_prefix: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Also update callers:
|
||||
|
||||
diff
|
||||
Copy code
|
||||
@@
|
||||
- let pq = build_path_query(path);
|
||||
+ let pq = build_path_query(conn, path)?;
|
||||
@@
|
||||
- let pq = build_path_query(path);
|
||||
+ let pq = build_path_query(conn, path)?;
|
||||
|
||||
|
||||
And tests:
|
||||
|
||||
diff
|
||||
Copy code
|
||||
@@
|
||||
- fn test_build_path_query() {
|
||||
+ fn test_build_path_query() {
|
||||
@@
|
||||
- // Dotless root file -> exact match (root path without '/')
|
||||
+ // Dotless root file -> exact match (root path without '/')
|
||||
let pq = build_path_query("Makefile");
|
||||
assert_eq!(pq.value, "Makefile");
|
||||
assert!(!pq.is_prefix);
|
||||
+
|
||||
+ // Dotless file in subdir should become exact if DB contains it (probe)
|
||||
+ // (set up: insert one DiffNote with position_new_path = "src/Dockerfile")
|
||||
|
||||
2) Make “reviewer” semantics correct: exclude MR authors commenting on their own diffs
|
||||
Why
|
||||
|
||||
Right now, Overlap (and Expert reviewer branch) will count MR authors as “reviewers” if they leave DiffNotes in their own MR (clarifications / replies), inflating A+R and contaminating “who reviewed here” signals.
|
||||
|
||||
You already enforce this in --reviews mode (m.author_username != ?1). Apply the same principle consistently:
|
||||
|
||||
Reviewer branch: only count notes where n.author_username != m.author_username (when both non-NULL).
|
||||
|
||||
Diff (Overlap reviewer branch)
|
||||
diff
|
||||
Copy code
|
||||
@@
|
||||
- WHERE n.note_type = 'DiffNote'
|
||||
+ WHERE n.note_type = 'DiffNote'
|
||||
AND n.position_new_path LIKE ?1 ESCAPE '\\'
|
||||
AND n.is_system = 0
|
||||
AND n.author_username IS NOT NULL
|
||||
+ AND (m.author_username IS NULL OR n.author_username != m.author_username)
|
||||
AND n.created_at >= ?2
|
||||
AND (?3 IS NULL OR n.project_id = ?3)
|
||||
|
||||
|
||||
Same change for sql_exact.
|
||||
|
||||
3) Expert mode scoring: align units + reduce single-MR “comment storms”
|
||||
Why
|
||||
|
||||
Expert currently mixes units:
|
||||
|
||||
reviewer side: DiffNote count
|
||||
|
||||
author side: distinct MR count
|
||||
|
||||
That makes score noisy and can crown “someone who wrote 30 comments on one MR” as top expert.
|
||||
|
||||
Fix: make both sides primarily MR-breadth:
|
||||
|
||||
reviewer: COUNT(DISTINCT m.id) as review_mr_count
|
||||
|
||||
author: COUNT(DISTINCT m.id) as author_mr_count
|
||||
Optionally keep review_note_count as a secondary intensity signal (but not the main driver).
|
||||
|
||||
Diff (types + SQL)
|
||||
diff
|
||||
Copy code
|
||||
@@
|
||||
pub struct Expert {
|
||||
pub username: String,
|
||||
- pub score: f64,
|
||||
- pub review_count: u32,
|
||||
- pub author_count: u32,
|
||||
+ pub score: i64,
|
||||
+ pub review_mr_count: u32,
|
||||
+ pub review_note_count: u32,
|
||||
+ pub author_mr_count: u32,
|
||||
pub last_active_ms: i64,
|
||||
}
|
||||
|
||||
|
||||
Reviewer branch now joins to MR so it can count distinct MRs and exclude self-comments:
|
||||
|
||||
diff
|
||||
Copy code
|
||||
@@
|
||||
- SELECT
|
||||
- n.author_username AS username,
|
||||
- 'reviewer' AS role,
|
||||
- COUNT(*) AS cnt,
|
||||
- MAX(n.created_at) AS last_active_at
|
||||
- FROM notes n
|
||||
+ SELECT
|
||||
+ n.author_username AS username,
|
||||
+ 'reviewer' AS role,
|
||||
+ COUNT(DISTINCT m.id) AS mr_cnt,
|
||||
+ COUNT(*) AS note_cnt,
|
||||
+ MAX(n.created_at) AS last_active_at
|
||||
+ FROM notes n
|
||||
+ JOIN discussions d ON n.discussion_id = d.id
|
||||
+ JOIN merge_requests m ON d.merge_request_id = m.id
|
||||
WHERE n.note_type = 'DiffNote'
|
||||
AND n.is_system = 0
|
||||
AND n.author_username IS NOT NULL
|
||||
+ AND (m.author_username IS NULL OR n.author_username != m.author_username)
|
||||
AND n.position_new_path LIKE ?1 ESCAPE '\\'
|
||||
AND n.created_at >= ?2
|
||||
AND (?3 IS NULL OR n.project_id = ?3)
|
||||
GROUP BY n.author_username
|
||||
|
||||
|
||||
Update author branch payload to match shape:
|
||||
|
||||
diff
|
||||
Copy code
|
||||
@@
|
||||
SELECT
|
||||
m.author_username AS username,
|
||||
'author' AS role,
|
||||
- COUNT(DISTINCT m.id) AS cnt,
|
||||
+ COUNT(DISTINCT m.id) AS mr_cnt,
|
||||
+ 0 AS note_cnt,
|
||||
MAX(n.created_at) AS last_active_at
|
||||
|
||||
|
||||
Aggregate:
|
||||
|
||||
diff
|
||||
Copy code
|
||||
@@
|
||||
SELECT
|
||||
username,
|
||||
- SUM(CASE WHEN role = 'reviewer' THEN cnt ELSE 0 END) AS review_count,
|
||||
- SUM(CASE WHEN role = 'author' THEN cnt ELSE 0 END) AS author_count,
|
||||
+ SUM(CASE WHEN role = 'reviewer' THEN mr_cnt ELSE 0 END) AS review_mr_count,
|
||||
+ SUM(CASE WHEN role = 'reviewer' THEN note_cnt ELSE 0 END) AS review_note_count,
|
||||
+ SUM(CASE WHEN role = 'author' THEN mr_cnt ELSE 0 END) AS author_mr_count,
|
||||
MAX(last_active_at) AS last_active_at,
|
||||
- (SUM(CASE WHEN role = 'reviewer' THEN cnt ELSE 0 END) * 3.0) +
|
||||
- (SUM(CASE WHEN role = 'author' THEN cnt ELSE 0 END) * 2.0) AS score
|
||||
+ (
|
||||
+ (SUM(CASE WHEN role = 'reviewer' THEN mr_cnt ELSE 0 END) * 20) +
|
||||
+ (SUM(CASE WHEN role = 'author' THEN mr_cnt ELSE 0 END) * 12) +
|
||||
+ (SUM(CASE WHEN role = 'reviewer' THEN note_cnt ELSE 0 END) * 1)
|
||||
+ ) AS score
|
||||
|
||||
|
||||
Human header:
|
||||
|
||||
diff
|
||||
Copy code
|
||||
@@
|
||||
- style("Reviews").bold(),
|
||||
- style("Authored").bold(),
|
||||
+ style("Reviewed(MRs)").bold(),
|
||||
+ style("Notes").bold(),
|
||||
+ style("Authored(MRs)").bold(),
|
||||
|
||||
4) Deterministic output: participants + MR refs + tie-breakers
|
||||
Why
|
||||
|
||||
You’ve correctly focused on reproducibility (resolved_input), but you still have nondeterministic lists:
|
||||
|
||||
participants: GROUP_CONCAT order is undefined → vector order changes run-to-run.
|
||||
|
||||
mr_refs: you dedup via HashSet then iterate → undefined order.
|
||||
|
||||
user sorting in overlap is missing stable tie-breakers.
|
||||
|
||||
This is a real “robot mode flake” source.
|
||||
|
||||
Diff (Active participants sort)
|
||||
diff
|
||||
Copy code
|
||||
@@
|
||||
- let participants: Vec<String> = participants_csv
|
||||
+ let mut participants: Vec<String> = participants_csv
|
||||
.as_deref()
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|csv| csv.split('\x1F').map(String::from).collect())
|
||||
.unwrap_or_default();
|
||||
+ participants.sort(); // stable, deterministic
|
||||
|
||||
Diff (Overlap MR refs sort + stable user sort)
|
||||
diff
|
||||
Copy code
|
||||
@@
|
||||
- users.sort_by(|a, b| b.touch_count.cmp(&a.touch_count));
|
||||
+ users.sort_by(|a, b| {
|
||||
+ b.touch_count.cmp(&a.touch_count)
|
||||
+ .then_with(|| b.last_touch_at.cmp(&a.last_touch_at))
|
||||
+ .then_with(|| a.username.cmp(&b.username))
|
||||
+ });
|
||||
@@
|
||||
- entry.mr_refs = set.into_iter().collect();
|
||||
+ let mut v: Vec<String> = set.into_iter().collect();
|
||||
+ v.sort();
|
||||
+ entry.mr_refs = v;
|
||||
|
||||
5) Make --limit actionable: surface truncation explicitly (human + robot)
|
||||
Why
|
||||
|
||||
Agents (and humans) need to know if results were cut off so they can rerun with a bigger -n.
|
||||
Right now there’s no signal.
|
||||
|
||||
Minimal pattern: query limit + 1, set truncated = true if you got > limit, then truncate.
|
||||
|
||||
Diff (result types)
|
||||
diff
|
||||
Copy code
|
||||
@@
|
||||
pub struct ExpertResult {
|
||||
pub path_query: String,
|
||||
pub experts: Vec<Expert>,
|
||||
+ pub truncated: bool,
|
||||
}
|
||||
@@
|
||||
pub struct ActiveResult {
|
||||
pub discussions: Vec<ActiveDiscussion>,
|
||||
pub total_unresolved: u32,
|
||||
+ pub truncated: bool,
|
||||
}
|
||||
@@
|
||||
pub struct OverlapResult {
|
||||
pub path_query: String,
|
||||
pub users: Vec<OverlapUser>,
|
||||
+ pub truncated: bool,
|
||||
}
|
||||
|
||||
Diff (query pattern example)
|
||||
diff
|
||||
Copy code
|
||||
@@
|
||||
- let limit_i64 = limit as i64;
|
||||
+ let limit_plus_one = (limit + 1) as i64;
|
||||
@@
|
||||
- LIMIT ?4
|
||||
+ LIMIT ?4
|
||||
@@
|
||||
- rusqlite::params![pq.value, since_ms, project_id, limit_i64],
|
||||
+ rusqlite::params![pq.value, since_ms, project_id, limit_plus_one],
|
||||
@@
|
||||
- Ok(ExpertResult {
|
||||
+ let truncated = experts.len() > limit;
|
||||
+ let experts = experts.into_iter().take(limit).collect();
|
||||
+ Ok(ExpertResult {
|
||||
path_query: path.to_string(),
|
||||
experts,
|
||||
+ truncated,
|
||||
})
|
||||
|
||||
|
||||
Human output hint:
|
||||
|
||||
diff
|
||||
Copy code
|
||||
@@
|
||||
if r.experts.is_empty() { ... }
|
||||
+ if r.truncated {
|
||||
+ println!(" {}", style("(showing first -n; rerun with a higher --limit)").dim());
|
||||
+ }
|
||||
|
||||
|
||||
Robot output field:
|
||||
|
||||
diff
|
||||
Copy code
|
||||
@@
|
||||
fn expert_to_json(r: &ExpertResult) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"path_query": r.path_query,
|
||||
+ "truncated": r.truncated,
|
||||
"experts": ...
|
||||
})
|
||||
}
|
||||
|
||||
6) Overlap merge hot loop: avoid repeated HashSet rebuild per row
|
||||
Why
|
||||
|
||||
This line is expensive in a UNION result with many rows:
|
||||
|
||||
rust
|
||||
Copy code
|
||||
let mut set: HashSet<String> = entry.mr_refs.drain(..).collect();
|
||||
|
||||
|
||||
It reallocates and rehashes every time.
|
||||
|
||||
Fix: store an accumulator with HashSet during merge, convert once at end.
|
||||
|
||||
Diff (internal accumulator)
|
||||
diff
|
||||
Copy code
|
||||
@@
|
||||
- let mut user_map: HashMap<String, OverlapUser> = HashMap::new();
|
||||
+ struct OverlapAcc {
|
||||
+ username: String,
|
||||
+ author_touch_count: u32,
|
||||
+ review_touch_count: u32,
|
||||
+ touch_count: u32,
|
||||
+ last_touch_at: i64,
|
||||
+ mr_refs: HashSet<String>,
|
||||
+ }
|
||||
+ let mut user_map: HashMap<String, OverlapAcc> = HashMap::new();
|
||||
@@
|
||||
- let entry = user_map.entry(username.clone()).or_insert_with(|| OverlapUser {
|
||||
+ let entry = user_map.entry(username.clone()).or_insert_with(|| OverlapAcc {
|
||||
username: username.clone(),
|
||||
author_touch_count: 0,
|
||||
review_touch_count: 0,
|
||||
touch_count: 0,
|
||||
last_touch_at: 0,
|
||||
- mr_refs: Vec::new(),
|
||||
+ mr_refs: HashSet::new(),
|
||||
});
|
||||
@@
|
||||
- let mut set: HashSet<String> = entry.mr_refs.drain(..).collect();
|
||||
- for r in mr_refs { set.insert(r); }
|
||||
- entry.mr_refs = set.into_iter().collect();
|
||||
+ for r in mr_refs { entry.mr_refs.insert(r); }
|
||||
@@
|
||||
- let mut users: Vec<OverlapUser> = user_map.into_values().collect();
|
||||
+ let mut users: Vec<OverlapUser> = user_map.into_values().map(|a| {
|
||||
+ let mut mr_refs: Vec<String> = a.mr_refs.into_iter().collect();
|
||||
+ mr_refs.sort();
|
||||
+ OverlapUser {
|
||||
+ username: a.username,
|
||||
+ author_touch_count: a.author_touch_count,
|
||||
+ review_touch_count: a.review_touch_count,
|
||||
+ touch_count: a.touch_count,
|
||||
+ last_touch_at: a.last_touch_at,
|
||||
+ mr_refs,
|
||||
+ }
|
||||
+ }).collect();
|
||||
|
||||
7) Tests to lock these behaviors
|
||||
Add tests (high value)
|
||||
|
||||
dotless subdir file uses DB probe → exact match
|
||||
|
||||
self-review exclusion prevents MR author showing up as reviewer
|
||||
|
||||
deterministic ordering for participants and mr_refs (sort)
|
||||
|
||||
Diff (test additions outline)
|
||||
diff
|
||||
Copy code
|
||||
@@
|
||||
#[test]
|
||||
+ fn test_build_path_query_dotless_subdir_file_uses_probe() {
|
||||
+ let conn = setup_test_db();
|
||||
+ insert_project(&conn, 1, "team/backend");
|
||||
+ insert_mr(&conn, 1, 1, 100, "author_a", "opened");
|
||||
+ insert_discussion(&conn, 1, 1, Some(1), None, true, false);
|
||||
+ insert_diffnote(&conn, 1, 1, 1, "reviewer_b", "src/Dockerfile", "note");
|
||||
+
|
||||
+ let pq = build_path_query(&conn, "src/Dockerfile").unwrap();
|
||||
+ assert_eq!(pq.value, "src/Dockerfile");
|
||||
+ assert!(!pq.is_prefix);
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn test_overlap_excludes_self_review_notes() {
|
||||
+ let conn = setup_test_db();
|
||||
+ insert_project(&conn, 1, "team/backend");
|
||||
+ insert_mr(&conn, 1, 1, 100, "author_a", "opened");
|
||||
+ insert_discussion(&conn, 1, 1, Some(1), None, true, false);
|
||||
+ // author_a comments on their own MR diff
|
||||
+ insert_diffnote(&conn, 1, 1, 1, "author_a", "src/auth/login.rs", "clarification");
|
||||
+
|
||||
+ let result = query_overlap(&conn, "src/auth/", None, 0, 20).unwrap();
|
||||
+ let u = result.users.iter().find(|u| u.username == "author_a");
|
||||
+ // should not be credited as reviewer touch
|
||||
+ assert!(u.map(|x| x.review_touch_count).unwrap_or(0) == 0);
|
||||
+ }
|
||||
|
||||
Net effect
|
||||
|
||||
Correctness: fixes dotless subdir files + self-review pollution.
|
||||
|
||||
Signal quality: Expert ranking becomes harder to game by comment volume.
|
||||
|
||||
Robot reproducibility: deterministic ordering + explicit truncation.
|
||||
|
||||
Performance: avoids rehash loops in overlap merges; path probe uses indexed equality.
|
||||
|
||||
If you want one “single best” change: #1 (DB probe exact-match) is the most likely to prevent confusing “why is this empty?” behavior without adding any user-facing complexity.
|
||||
@@ -1,353 +0,0 @@
|
||||
Below are the highest-leverage revisions I’d make to iteration 6 to improve correctness (multi-project edge cases), robot-mode reliability (bounded payloads + truncation), and signal quality—without changing the fundamental scope (still pure SQL over existing tables).
|
||||
|
||||
1) Make build_path_query project-aware and two-way probe (exact and prefix)
|
||||
Why
|
||||
|
||||
Your DB probe currently answers: “does this exact file exist anywhere in DiffNotes?” That can misclassify in a project-scoped run:
|
||||
|
||||
Path exists as a dotless file in Project A → probe returns true
|
||||
|
||||
User runs -p Project B where the path is a directory (or different shape) → you switch to exact, return empty, and miss valid prefix hits.
|
||||
|
||||
Also, you still have a minor heuristic fragility for dot directories when the user omits trailing / (e.g., .github/workflows): last segment has a dot → you treat as file unless forced dir.
|
||||
|
||||
Revision
|
||||
|
||||
Thread project_id into build_path_query(conn, path, project_id)
|
||||
|
||||
Probe exact first (scoped), then probe prefix (scoped)
|
||||
|
||||
Only fall back to heuristics if both probes fail
|
||||
|
||||
This keeps “static SQL, no dynamic assembly,” and costs at most 2 indexed existence queries per invocation.
|
||||
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/who-command-design.md b/who-command-design.md
|
||||
@@
|
||||
- fn build_path_query(conn: &Connection, path: &str) -> Result<PathQuery> {
|
||||
+ fn build_path_query(conn: &Connection, path: &str, project_id: Option<i64>) -> Result<PathQuery> {
|
||||
let trimmed = path.trim_end_matches('/');
|
||||
let last_segment = trimmed.rsplit('/').next().unwrap_or(trimmed);
|
||||
let is_root = !trimmed.contains('/');
|
||||
let forced_dir = path.ends_with('/');
|
||||
- let looks_like_file = !forced_dir && (is_root || last_segment.contains('.'));
|
||||
+ // Heuristic is now only a fallback; probes decide first.
|
||||
+ let looks_like_file = !forced_dir && (is_root || last_segment.contains('.'));
|
||||
|
||||
- let exact_exists = if !looks_like_file && !forced_dir {
|
||||
- conn.query_row(
|
||||
- "SELECT 1 FROM notes
|
||||
- WHERE note_type = 'DiffNote'
|
||||
- AND is_system = 0
|
||||
- AND position_new_path = ?1
|
||||
- LIMIT 1",
|
||||
- rusqlite::params![trimmed],
|
||||
- |_| Ok(()),
|
||||
- )
|
||||
- .is_ok()
|
||||
- } else {
|
||||
- false
|
||||
- };
|
||||
+ // Probe 1: exact file exists (scoped)
|
||||
+ let exact_exists = conn.query_row(
|
||||
+ "SELECT 1 FROM notes
|
||||
+ WHERE note_type = 'DiffNote'
|
||||
+ AND is_system = 0
|
||||
+ AND position_new_path = ?1
|
||||
+ AND (?2 IS NULL OR project_id = ?2)
|
||||
+ LIMIT 1",
|
||||
+ rusqlite::params![trimmed, project_id],
|
||||
+ |_| Ok(()),
|
||||
+ ).is_ok();
|
||||
+
|
||||
+ // Probe 2: directory prefix exists (scoped)
|
||||
+ let prefix_exists = if !forced_dir {
|
||||
+ let escaped = escape_like(trimmed);
|
||||
+ let pat = format!("{escaped}/%");
|
||||
+ conn.query_row(
|
||||
+ "SELECT 1 FROM notes
|
||||
+ WHERE note_type = 'DiffNote'
|
||||
+ AND is_system = 0
|
||||
+ AND position_new_path LIKE ?1 ESCAPE '\\'
|
||||
+ AND (?2 IS NULL OR project_id = ?2)
|
||||
+ LIMIT 1",
|
||||
+ rusqlite::params![pat, project_id],
|
||||
+ |_| Ok(()),
|
||||
+ ).is_ok()
|
||||
+ } else { false };
|
||||
|
||||
- let is_file = looks_like_file || exact_exists;
|
||||
+ // Forced directory always wins; otherwise: exact > prefix > heuristic
|
||||
+ let is_file = if forced_dir { false }
|
||||
+ else if exact_exists { true }
|
||||
+ else if prefix_exists { false }
|
||||
+ else { looks_like_file };
|
||||
|
||||
if is_file {
|
||||
Ok(PathQuery { value: trimmed.to_string(), is_prefix: false })
|
||||
} else {
|
||||
let escaped = escape_like(trimmed);
|
||||
Ok(PathQuery { value: format!("{escaped}/%"), is_prefix: true })
|
||||
}
|
||||
}
|
||||
@@
|
||||
- let pq = build_path_query(conn, path)?;
|
||||
+ let pq = build_path_query(conn, path, project_id)?;
|
||||
|
||||
|
||||
Add test coverage for the multi-project misclassification case:
|
||||
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/who-command-design.md b/who-command-design.md
|
||||
@@
|
||||
#[test]
|
||||
fn test_build_path_query_dotless_subdir_file_uses_db_probe() {
|
||||
@@
|
||||
- let pq = build_path_query(&conn, "src/Dockerfile").unwrap();
|
||||
+ let pq = build_path_query(&conn, "src/Dockerfile", None).unwrap();
|
||||
@@
|
||||
- let pq2 = build_path_query(&conn2, "src/Dockerfile").unwrap();
|
||||
+ let pq2 = build_path_query(&conn2, "src/Dockerfile", None).unwrap();
|
||||
}
|
||||
+
|
||||
+ #[test]
|
||||
+ fn test_build_path_query_probe_is_project_scoped() {
|
||||
+ // Path exists as a dotless file in project 1; project 2 should not
|
||||
+ // treat it as an exact file unless it exists there too.
|
||||
+ let conn = setup_test_db();
|
||||
+ insert_project(&conn, 1, "team/a");
|
||||
+ insert_project(&conn, 2, "team/b");
|
||||
+ insert_mr(&conn, 1, 1, 10, "author_a", "opened");
|
||||
+ insert_discussion(&conn, 1, 1, Some(1), None, true, false);
|
||||
+ insert_diffnote(&conn, 1, 1, 1, "rev", "infra/Makefile", "note");
|
||||
+
|
||||
+ let pq_scoped = build_path_query(&conn, "infra/Makefile", Some(2)).unwrap();
|
||||
+ assert!(pq_scoped.is_prefix); // should fall back to prefix in project 2
|
||||
+ }
|
||||
|
||||
2) Bound robot payload sizes for participants and mr_refs (with totals + truncation)
|
||||
Why
|
||||
|
||||
mr_refs and participants can become unbounded arrays in robot mode, which is a real operational hazard:
|
||||
|
||||
huge JSON → slow, noisy diffs, brittle downstream pipelines
|
||||
|
||||
potential SQLite group_concat truncation becomes invisible (and you can’t distinguish “no refs” vs “refs truncated”)
|
||||
|
||||
Revision
|
||||
|
||||
Introduce hard caps and explicit metadata:
|
||||
|
||||
participants_total, participants_truncated
|
||||
|
||||
mr_refs_total, mr_refs_truncated
|
||||
|
||||
This is not scope creep—it’s defensive output hygiene.
|
||||
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/who-command-design.md b/who-command-design.md
|
||||
@@
|
||||
pub struct ActiveDiscussion {
|
||||
@@
|
||||
pub participants: Vec<String>,
|
||||
+ pub participants_total: u32,
|
||||
+ pub participants_truncated: bool,
|
||||
}
|
||||
@@
|
||||
pub struct OverlapUser {
|
||||
@@
|
||||
pub mr_refs: Vec<String>,
|
||||
+ pub mr_refs_total: u32,
|
||||
+ pub mr_refs_truncated: bool,
|
||||
}
|
||||
|
||||
|
||||
Implementation sketch (Rust-side, deterministic):
|
||||
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/who-command-design.md b/who-command-design.md
|
||||
@@
|
||||
fn query_active(...) -> Result<ActiveResult> {
|
||||
+ const MAX_PARTICIPANTS: usize = 50;
|
||||
@@
|
||||
- participants.sort();
|
||||
+ participants.sort();
|
||||
+ let participants_total = participants.len() as u32;
|
||||
+ let participants_truncated = participants.len() > MAX_PARTICIPANTS;
|
||||
+ if participants_truncated {
|
||||
+ participants.truncate(MAX_PARTICIPANTS);
|
||||
+ }
|
||||
@@
|
||||
Ok(ActiveDiscussion {
|
||||
@@
|
||||
participants,
|
||||
+ participants_total,
|
||||
+ participants_truncated,
|
||||
})
|
||||
@@
|
||||
fn query_overlap(...) -> Result<OverlapResult> {
|
||||
+ const MAX_MR_REFS_PER_USER: usize = 50;
|
||||
@@
|
||||
.map(|a| {
|
||||
let mut mr_refs: Vec<String> = a.mr_refs.into_iter().collect();
|
||||
mr_refs.sort();
|
||||
+ let mr_refs_total = mr_refs.len() as u32;
|
||||
+ let mr_refs_truncated = mr_refs.len() > MAX_MR_REFS_PER_USER;
|
||||
+ if mr_refs_truncated {
|
||||
+ mr_refs.truncate(MAX_MR_REFS_PER_USER);
|
||||
+ }
|
||||
OverlapUser {
|
||||
@@
|
||||
mr_refs,
|
||||
+ mr_refs_total,
|
||||
+ mr_refs_truncated,
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
Update robot JSON accordingly:
|
||||
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/who-command-design.md b/who-command-design.md
|
||||
@@
|
||||
fn active_to_json(r: &ActiveResult) -> serde_json::Value {
|
||||
@@
|
||||
"participants": d.participants,
|
||||
+ "participants_total": d.participants_total,
|
||||
+ "participants_truncated": d.participants_truncated,
|
||||
}))
|
||||
@@
|
||||
fn overlap_to_json(r: &OverlapResult) -> serde_json::Value {
|
||||
@@
|
||||
"mr_refs": u.mr_refs,
|
||||
+ "mr_refs_total": u.mr_refs_total,
|
||||
+ "mr_refs_truncated": u.mr_refs_truncated,
|
||||
}))
|
||||
|
||||
|
||||
Also update robot-docs manifest schema snippet for who.active.discussions[] and who.overlap.users[].
|
||||
|
||||
3) Add truncation metadata to Workload sections (same LIMIT+1 pattern)
|
||||
Why
|
||||
|
||||
Workload is the mode most likely to be consumed by agents, and right now it has silent truncation (each section is LIMIT N with no signal). Your plan already treats truncation as a first-class contract elsewhere; Workload should match.
|
||||
|
||||
Revision
|
||||
|
||||
For each workload query:
|
||||
|
||||
request LIMIT + 1
|
||||
|
||||
set *_truncated booleans
|
||||
|
||||
trim to requested limit
|
||||
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/who-command-design.md b/who-command-design.md
|
||||
@@
|
||||
pub struct WorkloadResult {
|
||||
pub username: String,
|
||||
pub assigned_issues: Vec<WorkloadIssue>,
|
||||
pub authored_mrs: Vec<WorkloadMr>,
|
||||
pub reviewing_mrs: Vec<WorkloadMr>,
|
||||
pub unresolved_discussions: Vec<WorkloadDiscussion>,
|
||||
+ pub assigned_issues_truncated: bool,
|
||||
+ pub authored_mrs_truncated: bool,
|
||||
+ pub reviewing_mrs_truncated: bool,
|
||||
+ pub unresolved_discussions_truncated: bool,
|
||||
}
|
||||
|
||||
|
||||
And in JSON include the booleans (plus you already have summary.counts).
|
||||
|
||||
This is mechanically repetitive but extremely valuable for automation.
|
||||
|
||||
4) Rename “Last Active” → “Last Seen” for Expert/Overlap
|
||||
Why
|
||||
|
||||
For “author” rows, the timestamp is derived from review activity on their MR (via MAX(n.created_at)), not necessarily that person’s direct action. Calling that “active” is semantically misleading. “Last seen” is accurate across both reviewer+author branches.
|
||||
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/who-command-design.md b/who-command-design.md
|
||||
@@
|
||||
pub struct Expert {
|
||||
@@
|
||||
- pub last_active_ms: i64,
|
||||
+ pub last_seen_ms: i64,
|
||||
}
|
||||
@@
|
||||
pub struct OverlapUser {
|
||||
@@
|
||||
- pub last_touch_at: i64,
|
||||
+ pub last_seen_at: i64,
|
||||
@@
|
||||
fn print_expert_human(...) {
|
||||
@@
|
||||
- style("Last Active").bold(),
|
||||
+ style("Last Seen").bold(),
|
||||
@@
|
||||
- style(format_relative_time(expert.last_active_ms)).dim(),
|
||||
+ style(format_relative_time(expert.last_seen_ms)).dim(),
|
||||
|
||||
|
||||
(Keep internal SQL aliases consistent: last_seen_at everywhere.)
|
||||
|
||||
5) Make MR state filtering consistent in Expert/Overlap reviewer branches
|
||||
Why
|
||||
|
||||
You already restrict Overlap author branch to opened|merged, but reviewer branches can include closed/unmerged noise. Consistency improves signal quality and can reduce scan churn.
|
||||
|
||||
Low-risk revision: apply the same state filter to reviewer branches (Expert + Overlap). You can keep “closed” excluded by default without adding new flags.
|
||||
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/who-command-design.md b/who-command-design.md
|
||||
@@
|
||||
WHERE n.note_type = 'DiffNote'
|
||||
AND n.is_system = 0
|
||||
@@
|
||||
- AND n.created_at >= ?2
|
||||
+ AND m.state IN ('opened','merged')
|
||||
+ AND n.created_at >= ?2
|
||||
|
||||
|
||||
This is a semantic choice; if you later want archaeology across closed/unmerged, that belongs in a separate mode/flag, but I would not add it now.
|
||||
|
||||
6) Add a design principle for bounded outputs (aligns with robot-first reproducibility)
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/who-command-design.md b/who-command-design.md
|
||||
@@
|
||||
10. **Truncation transparency.** Result types carry a `truncated: bool` flag...
|
||||
+11. **Bounded payloads.** Robot JSON must never emit unbounded arrays (participants, refs).
|
||||
+ Large list fields are capped with `*_total` + `*_truncated` so agents can page/retry.
|
||||
|
||||
Consolidated plan metadata bump (Iteration 7)
|
||||
diff
|
||||
Copy code
|
||||
diff --git a/who-command-design.md b/who-command-design.md
|
||||
@@
|
||||
-iteration: 6
|
||||
+iteration: 7
|
||||
updated: 2026-02-07
|
||||
|
||||
Net effect (what you get)
|
||||
|
||||
Correct path classification under -p scoping (no cross-project probe leakage)
|
||||
|
||||
Deterministic + bounded robot payloads (no giant JSON surprises)
|
||||
|
||||
Uniform truncation contract across all modes (Workload no longer silently truncates)
|
||||
|
||||
Clearer semantics (“Last Seen” avoids misinterpretation)
|
||||
|
||||
Cleaner signals (reviewer branches ignore closed/unmerged by default)
|
||||
|
||||
If you want, I can also produce a second diff that updates the robot-docs schema block and the Verification EXPLAIN expectations to reflect the new probe queries and the state filter.
|
||||
10
migrations/018_fix_assignees_composite_index.sql
Normal file
10
migrations/018_fix_assignees_composite_index.sql
Normal file
@@ -0,0 +1,10 @@
|
||||
-- Migration 018: Fix composite index on issue_assignees
|
||||
-- Migration 005 created idx_issue_assignees_username(username) as single-column.
|
||||
-- Migration 017 attempted to recreate as (username, issue_id) but IF NOT EXISTS
|
||||
-- silently skipped it. Drop and recreate with the correct composite columns.
|
||||
|
||||
DROP INDEX IF EXISTS idx_issue_assignees_username;
|
||||
CREATE INDEX idx_issue_assignees_username ON issue_assignees(username, issue_id);
|
||||
|
||||
INSERT INTO schema_version (version, applied_at, description)
|
||||
VALUES (18, strftime('%s', 'now') * 1000, 'Fix composite index on issue_assignees');
|
||||
16
migrations/019_list_performance.sql
Normal file
16
migrations/019_list_performance.sql
Normal file
@@ -0,0 +1,16 @@
|
||||
-- Standalone updated_at DESC indexes for ORDER BY without temp B-tree sort.
|
||||
-- The existing composite indexes (project_id, updated_at) only help when
|
||||
-- filtering by project first.
|
||||
CREATE INDEX IF NOT EXISTS idx_issues_updated_at_desc
|
||||
ON issues(updated_at DESC);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_mrs_updated_at_desc
|
||||
ON merge_requests(updated_at DESC);
|
||||
|
||||
-- Covering index for correlated subquery: unresolved discussion count per issue.
|
||||
-- MRs already have idx_discussions_mr_resolved (migration 006).
|
||||
CREATE INDEX IF NOT EXISTS idx_discussions_issue_resolved
|
||||
ON discussions(issue_id, resolvable, resolved);
|
||||
|
||||
INSERT INTO schema_version (version, applied_at, description)
|
||||
VALUES (19, strftime('%s', 'now') * 1000, 'List performance indexes');
|
||||
7
migrations/020_mr_diffs_watermark.sql
Normal file
7
migrations/020_mr_diffs_watermark.sql
Normal file
@@ -0,0 +1,7 @@
|
||||
-- Migration 020: Watermark column for MR diffs sync
|
||||
-- Tracks which MRs have had their file changes fetched, same pattern as closes_issues_synced_for_updated_at
|
||||
|
||||
ALTER TABLE merge_requests ADD COLUMN diffs_synced_for_updated_at INTEGER;
|
||||
|
||||
INSERT INTO schema_version (version, applied_at, description)
|
||||
VALUES (20, strftime('%s', 'now') * 1000, 'MR diffs sync watermark');
|
||||
9
migrations/021_work_item_status.sql
Normal file
9
migrations/021_work_item_status.sql
Normal file
@@ -0,0 +1,9 @@
|
||||
ALTER TABLE issues ADD COLUMN status_name TEXT;
|
||||
ALTER TABLE issues ADD COLUMN status_category TEXT;
|
||||
ALTER TABLE issues ADD COLUMN status_color TEXT;
|
||||
ALTER TABLE issues ADD COLUMN status_icon_name TEXT;
|
||||
ALTER TABLE issues ADD COLUMN status_synced_at INTEGER;
|
||||
CREATE INDEX IF NOT EXISTS idx_issues_project_status_name ON issues(project_id, status_name);
|
||||
|
||||
INSERT INTO schema_version (version, applied_at, description)
|
||||
VALUES (21, strftime('%s', 'now') * 1000, 'Work item status columns for issues');
|
||||
21
migrations/022_notes_query_index.sql
Normal file
21
migrations/022_notes_query_index.sql
Normal file
@@ -0,0 +1,21 @@
|
||||
-- Migration 022: Composite query indexes for notes + author_id column
|
||||
-- Optimizes author-scoped and project-scoped date-range queries on notes.
|
||||
-- Adds discussion JOIN indexes and immutable author identity column.
|
||||
|
||||
-- Composite index for author-scoped queries (who command, notes --author)
|
||||
CREATE INDEX IF NOT EXISTS idx_notes_user_created
|
||||
ON notes(project_id, author_username COLLATE NOCASE, created_at DESC, id DESC)
|
||||
WHERE is_system = 0;
|
||||
|
||||
-- Composite index for project-scoped date-range queries
|
||||
CREATE INDEX IF NOT EXISTS idx_notes_project_created
|
||||
ON notes(project_id, created_at DESC, id DESC)
|
||||
WHERE is_system = 0;
|
||||
|
||||
-- Discussion JOIN indexes
|
||||
CREATE INDEX IF NOT EXISTS idx_discussions_issue_id ON discussions(issue_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_discussions_mr_id ON discussions(merge_request_id);
|
||||
|
||||
-- Immutable author identity column (GitLab numeric user ID)
|
||||
ALTER TABLE notes ADD COLUMN author_id INTEGER;
|
||||
CREATE INDEX IF NOT EXISTS idx_notes_author_id ON notes(author_id) WHERE author_id IS NOT NULL;
|
||||
5
migrations/023_issue_detail_fields.sql
Normal file
5
migrations/023_issue_detail_fields.sql
Normal file
@@ -0,0 +1,5 @@
|
||||
ALTER TABLE issues ADD COLUMN closed_at TEXT;
|
||||
ALTER TABLE issues ADD COLUMN confidential INTEGER NOT NULL DEFAULT 0;
|
||||
|
||||
INSERT INTO schema_version (version, applied_at, description)
|
||||
VALUES (23, strftime('%s', 'now') * 1000, 'Add closed_at and confidential to issues');
|
||||
153
migrations/024_note_documents.sql
Normal file
153
migrations/024_note_documents.sql
Normal file
@@ -0,0 +1,153 @@
|
||||
-- Migration 024: Add 'note' source_type to documents and dirty_sources
|
||||
-- SQLite does not support ALTER CONSTRAINT, so we use the table-rebuild pattern.
|
||||
|
||||
-- ============================================================
|
||||
-- 1. Rebuild dirty_sources with updated CHECK constraint
|
||||
-- ============================================================
|
||||
|
||||
CREATE TABLE dirty_sources_new (
|
||||
source_type TEXT NOT NULL CHECK (source_type IN ('issue','merge_request','discussion','note')),
|
||||
source_id INTEGER NOT NULL,
|
||||
queued_at INTEGER NOT NULL,
|
||||
attempt_count INTEGER NOT NULL DEFAULT 0,
|
||||
last_attempt_at INTEGER,
|
||||
last_error TEXT,
|
||||
next_attempt_at INTEGER,
|
||||
PRIMARY KEY(source_type, source_id)
|
||||
);
|
||||
|
||||
INSERT INTO dirty_sources_new SELECT * FROM dirty_sources;
|
||||
DROP TABLE dirty_sources;
|
||||
ALTER TABLE dirty_sources_new RENAME TO dirty_sources;
|
||||
CREATE INDEX idx_dirty_sources_next_attempt ON dirty_sources(next_attempt_at);
|
||||
|
||||
-- ============================================================
|
||||
-- 2. Rebuild documents with updated CHECK constraint
|
||||
-- ============================================================
|
||||
|
||||
-- 2a. Backup junction table data
|
||||
CREATE TEMP TABLE _doc_labels_backup AS SELECT * FROM document_labels;
|
||||
CREATE TEMP TABLE _doc_paths_backup AS SELECT * FROM document_paths;
|
||||
|
||||
-- 2b. Drop all triggers that reference documents
|
||||
DROP TRIGGER IF EXISTS documents_ai;
|
||||
DROP TRIGGER IF EXISTS documents_ad;
|
||||
DROP TRIGGER IF EXISTS documents_au;
|
||||
DROP TRIGGER IF EXISTS documents_embeddings_ad;
|
||||
|
||||
-- 2c. Drop junction tables (they have FK references to documents)
|
||||
DROP TABLE IF EXISTS document_labels;
|
||||
DROP TABLE IF EXISTS document_paths;
|
||||
|
||||
-- 2d. Create new documents table with 'note' in CHECK constraint
|
||||
CREATE TABLE documents_new (
|
||||
id INTEGER PRIMARY KEY,
|
||||
source_type TEXT NOT NULL CHECK (source_type IN ('issue','merge_request','discussion','note')),
|
||||
source_id INTEGER NOT NULL,
|
||||
project_id INTEGER NOT NULL REFERENCES projects(id),
|
||||
author_username TEXT,
|
||||
label_names TEXT,
|
||||
created_at INTEGER,
|
||||
updated_at INTEGER,
|
||||
url TEXT,
|
||||
title TEXT,
|
||||
content_text TEXT NOT NULL,
|
||||
content_hash TEXT NOT NULL,
|
||||
labels_hash TEXT NOT NULL DEFAULT '',
|
||||
paths_hash TEXT NOT NULL DEFAULT '',
|
||||
is_truncated INTEGER NOT NULL DEFAULT 0,
|
||||
truncated_reason TEXT CHECK (
|
||||
truncated_reason IN (
|
||||
'token_limit_middle_drop','single_note_oversized','first_last_oversized',
|
||||
'hard_cap_oversized'
|
||||
)
|
||||
OR truncated_reason IS NULL
|
||||
),
|
||||
UNIQUE(source_type, source_id)
|
||||
);
|
||||
|
||||
-- 2e. Copy all existing data
|
||||
INSERT INTO documents_new SELECT * FROM documents;
|
||||
|
||||
-- 2f. Swap tables
|
||||
DROP TABLE documents;
|
||||
ALTER TABLE documents_new RENAME TO documents;
|
||||
|
||||
-- 2g. Recreate all indexes on documents
|
||||
CREATE INDEX idx_documents_project_updated ON documents(project_id, updated_at);
|
||||
CREATE INDEX idx_documents_author ON documents(author_username);
|
||||
CREATE INDEX idx_documents_source ON documents(source_type, source_id);
|
||||
CREATE INDEX idx_documents_hash ON documents(content_hash);
|
||||
|
||||
-- 2h. Recreate junction tables
|
||||
CREATE TABLE document_labels (
|
||||
document_id INTEGER NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
|
||||
label_name TEXT NOT NULL,
|
||||
PRIMARY KEY(document_id, label_name)
|
||||
) WITHOUT ROWID;
|
||||
CREATE INDEX idx_document_labels_label ON document_labels(label_name);
|
||||
|
||||
CREATE TABLE document_paths (
|
||||
document_id INTEGER NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
|
||||
path TEXT NOT NULL,
|
||||
PRIMARY KEY(document_id, path)
|
||||
) WITHOUT ROWID;
|
||||
CREATE INDEX idx_document_paths_path ON document_paths(path);
|
||||
|
||||
-- 2i. Restore junction table data from backups
|
||||
INSERT INTO document_labels SELECT * FROM _doc_labels_backup;
|
||||
INSERT INTO document_paths SELECT * FROM _doc_paths_backup;
|
||||
|
||||
-- 2j. Recreate FTS triggers (from migration 008)
|
||||
CREATE TRIGGER documents_ai AFTER INSERT ON documents BEGIN
|
||||
INSERT INTO documents_fts(rowid, title, content_text)
|
||||
VALUES (new.id, COALESCE(new.title, ''), new.content_text);
|
||||
END;
|
||||
|
||||
CREATE TRIGGER documents_ad AFTER DELETE ON documents BEGIN
|
||||
INSERT INTO documents_fts(documents_fts, rowid, title, content_text)
|
||||
VALUES('delete', old.id, COALESCE(old.title, ''), old.content_text);
|
||||
END;
|
||||
|
||||
CREATE TRIGGER documents_au AFTER UPDATE ON documents
|
||||
WHEN old.title IS NOT new.title OR old.content_text != new.content_text
|
||||
BEGIN
|
||||
INSERT INTO documents_fts(documents_fts, rowid, title, content_text)
|
||||
VALUES('delete', old.id, COALESCE(old.title, ''), old.content_text);
|
||||
INSERT INTO documents_fts(rowid, title, content_text)
|
||||
VALUES (new.id, COALESCE(new.title, ''), new.content_text);
|
||||
END;
|
||||
|
||||
-- 2k. Recreate embeddings cleanup trigger (from migration 009)
|
||||
CREATE TRIGGER documents_embeddings_ad AFTER DELETE ON documents BEGIN
|
||||
DELETE FROM embeddings
|
||||
WHERE rowid >= old.id * 1000
|
||||
AND rowid < (old.id + 1) * 1000;
|
||||
END;
|
||||
|
||||
-- 2l. Rebuild FTS index to ensure consistency after table swap
|
||||
INSERT INTO documents_fts(documents_fts) VALUES('rebuild');
|
||||
|
||||
-- ============================================================
|
||||
-- 3. Defense triggers: clean up documents when notes are
|
||||
-- deleted or flipped to system notes
|
||||
-- ============================================================
|
||||
|
||||
CREATE TRIGGER notes_ad_cleanup AFTER DELETE ON notes
|
||||
WHEN old.is_system = 0
|
||||
BEGIN
|
||||
DELETE FROM documents WHERE source_type = 'note' AND source_id = old.id;
|
||||
END;
|
||||
|
||||
CREATE TRIGGER notes_au_system_cleanup AFTER UPDATE OF is_system ON notes
|
||||
WHEN NEW.is_system = 1 AND OLD.is_system = 0
|
||||
BEGIN
|
||||
DELETE FROM documents WHERE source_type = 'note' AND source_id = OLD.id;
|
||||
END;
|
||||
|
||||
-- ============================================================
|
||||
-- 4. Drop temp backup tables
|
||||
-- ============================================================
|
||||
|
||||
DROP TABLE IF EXISTS _doc_labels_backup;
|
||||
DROP TABLE IF EXISTS _doc_paths_backup;
|
||||
8
migrations/025_note_dirty_backfill.sql
Normal file
8
migrations/025_note_dirty_backfill.sql
Normal file
@@ -0,0 +1,8 @@
|
||||
-- Backfill existing non-system notes into dirty queue for document generation.
|
||||
-- Only seeds notes that don't already have documents and aren't already queued.
|
||||
INSERT INTO dirty_sources (source_type, source_id, queued_at)
|
||||
SELECT 'note', n.id, CAST(strftime('%s', 'now') AS INTEGER) * 1000
|
||||
FROM notes n
|
||||
LEFT JOIN documents d ON d.source_type = 'note' AND d.source_id = n.id
|
||||
WHERE n.is_system = 0 AND d.id IS NULL
|
||||
ON CONFLICT(source_type, source_id) DO NOTHING;
|
||||
20
migrations/026_scoring_indexes.sql
Normal file
20
migrations/026_scoring_indexes.sql
Normal file
@@ -0,0 +1,20 @@
|
||||
-- Indexes for time-decay expert scoring: dual-path matching and reviewer participation.
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_notes_old_path_author
|
||||
ON notes(position_old_path, author_username, created_at)
|
||||
WHERE note_type = 'DiffNote' AND is_system = 0 AND position_old_path IS NOT NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_mfc_old_path_project_mr
|
||||
ON mr_file_changes(old_path, project_id, merge_request_id)
|
||||
WHERE old_path IS NOT NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_mfc_new_path_project_mr
|
||||
ON mr_file_changes(new_path, project_id, merge_request_id);
|
||||
|
||||
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;
|
||||
|
||||
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;
|
||||
186
plans/lore-service.feedback-1.md
Normal file
186
plans/lore-service.feedback-1.md
Normal file
@@ -0,0 +1,186 @@
|
||||
1. **Isolate scheduled behavior from manual `sync`**
|
||||
Reasoning: Your current plan injects backoff into `handle_sync_cmd`, which affects all `lore sync` calls (including manual recovery runs). Scheduled behavior should be isolated so humans aren’t unexpectedly blocked by service backoff.
|
||||
|
||||
```diff
|
||||
@@ Context
|
||||
-`lore sync` runs a 4-stage pipeline (issues, MRs, docs, embeddings) that takes 2-4 minutes.
|
||||
+`lore sync` remains the manual/operator command.
|
||||
+`lore service run` (hidden/internal) is the scheduled execution entrypoint.
|
||||
|
||||
@@ Commands & User Journeys
|
||||
+### `lore service run` (hidden/internal)
|
||||
+**What it does:** Executes one scheduled sync attempt with service-only policy:
|
||||
+- applies service backoff policy
|
||||
+- records service run state
|
||||
+- invokes sync pipeline with configured profile
|
||||
+- updates retry state on success/failure
|
||||
+
|
||||
+**Invocation:** scheduler always runs:
|
||||
+`lore --robot service run --reason timer`
|
||||
|
||||
@@ Backoff Integration into `handle_sync_cmd`
|
||||
-Insert **after** config load but **before** the dry_run check:
|
||||
+Do not add backoff checks to `handle_sync_cmd`.
|
||||
+Backoff logic lives only in `handle_service_run`.
|
||||
```
|
||||
|
||||
2. **Use DB as source-of-truth for service state (not a standalone JSON status file)**
|
||||
Reasoning: You already have `sync_runs` in SQLite. A separate JSON status file creates split-brain and race/corruption risk. Keep JSON as optional cache/export only.
|
||||
|
||||
```diff
|
||||
@@ Status File
|
||||
-Location: `{get_data_dir()}/sync-status.json`
|
||||
+Primary state location: SQLite (`service_state` table) + existing `sync_runs`.
|
||||
+Optional mirror file: `{get_data_dir()}/sync-status.json` (best-effort export only).
|
||||
|
||||
@@ File-by-File Implementation Details
|
||||
-### `src/core/sync_status.rs` (NEW)
|
||||
+### `migrations/015_service_state.sql` (NEW)
|
||||
+CREATE TABLE service_state (
|
||||
+ id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
+ installed INTEGER NOT NULL DEFAULT 0,
|
||||
+ platform TEXT,
|
||||
+ interval_seconds INTEGER,
|
||||
+ profile TEXT NOT NULL DEFAULT 'balanced',
|
||||
+ consecutive_failures INTEGER NOT NULL DEFAULT 0,
|
||||
+ next_retry_at_ms INTEGER,
|
||||
+ last_error_code TEXT,
|
||||
+ last_error_message TEXT,
|
||||
+ updated_at_ms INTEGER NOT NULL
|
||||
+);
|
||||
+
|
||||
+### `src/core/service_state.rs` (NEW)
|
||||
+- read/write state row
|
||||
+- derive backoff/next_retry
|
||||
+- join with latest `sync_runs` for status output
|
||||
```
|
||||
|
||||
3. **Backoff policy should be configurable, jittered, and error-aware**
|
||||
Reasoning: Fixed hardcoded backoff (`base=1800`) is wrong when user sets another interval. Also permanent failures (bad token/config) should not burn retries forever; they should enter paused/error state.
|
||||
|
||||
```diff
|
||||
@@ Backoff Logic
|
||||
-// Exponential: base * 2^failures, capped at 4 hours
|
||||
+// Exponential with jitter: base * 2^(failures-1), capped, ±20% jitter
|
||||
+// Applies only to transient errors.
|
||||
+// Permanent errors set `paused_reason` and stop retries until user action.
|
||||
|
||||
@@ CLI Definition Changes
|
||||
+ServiceCommand::Resume, // clear paused state / failures
|
||||
+ServiceCommand::Run, // hidden
|
||||
|
||||
@@ Error Types
|
||||
+ServicePaused, // scheduler paused due to permanent error
|
||||
+ServiceCommandFailed, // OS command failure with stderr context
|
||||
```
|
||||
|
||||
4. **Add a pipeline-level single-flight lock**
|
||||
Reasoning: Current locking is in ingest stages; there’s still overlap risk across full sync pipelines (docs/embed can overlap with another run). Add a top-level lock for scheduled/manual sync pipeline execution.
|
||||
|
||||
```diff
|
||||
@@ Architecture
|
||||
+Add `sync_pipeline` lock at top-level sync execution.
|
||||
+Keep existing ingest lock (`sync`) for ingest internals.
|
||||
|
||||
@@ Backoff Integration into `handle_sync_cmd`
|
||||
+Before starting sync pipeline, acquire `AppLock` with:
|
||||
+name = "sync_pipeline"
|
||||
+stale_lock_minutes = config.sync.stale_lock_minutes
|
||||
+heartbeat_interval_seconds = config.sync.heartbeat_interval_seconds
|
||||
```
|
||||
|
||||
5. **Don’t embed token in service files by default**
|
||||
Reasoning: Embedding PAT into unit/plist is a high-risk secret leak path. Make secure storage explicit and default-safe.
|
||||
|
||||
```diff
|
||||
@@ `lore service install [--interval 30m]`
|
||||
+`lore service install [--interval 30m] [--token-source env-file|embedded]`
|
||||
+Default: `env-file` (0600 perms, user-owned)
|
||||
+`embedded` allowed only with explicit opt-in and warning
|
||||
|
||||
@@ Robot output
|
||||
- "token_embedded": true
|
||||
+ "token_source": "env_file"
|
||||
|
||||
@@ Human output
|
||||
- Note: Your GITLAB_TOKEN is embedded in the service file.
|
||||
+ Note: Token is stored in a user-private env file (0600).
|
||||
```
|
||||
|
||||
6. **Introduce a command-runner abstraction with timeout + stderr capture**
|
||||
Reasoning: `launchctl/systemctl/schtasks` calls are failure-prone; you need consistent error mapping and deterministic tests.
|
||||
|
||||
```diff
|
||||
@@ Platform Backends
|
||||
-exports free functions that dispatch via `#[cfg(target_os)]`
|
||||
+exports backend + shared `CommandRunner`:
|
||||
+- run(cmd, args, timeout)
|
||||
+- capture stdout/stderr/exit code
|
||||
+- map failure to `ServiceCommandFailed { cmd, exit_code, stderr }`
|
||||
```
|
||||
|
||||
7. **Persist install manifest to avoid brittle file parsing**
|
||||
Reasoning: Parsing timer/plist for interval/state is fragile and platform-format dependent. Persist a manifest with checksums and expected artifacts.
|
||||
|
||||
```diff
|
||||
@@ Platform Backends
|
||||
-Same pattern for ... `get_interval_seconds()`
|
||||
+Add manifest: `{data_dir}/service-manifest.json`
|
||||
+Stores platform, interval, profile, generated files, and command.
|
||||
+`service status` reads manifest first, then verifies platform state.
|
||||
|
||||
@@ Acceptance criteria
|
||||
+Install is idempotent:
|
||||
+- if manifest+files already match, report `no_change: true`
|
||||
+- if drift detected, reconcile and rewrite
|
||||
```
|
||||
|
||||
8. **Make schedule profile explicit (`fast|balanced|full`)**
|
||||
Reasoning: This makes the feature more useful and performance-tunable without requiring users to understand internal flags.
|
||||
|
||||
```diff
|
||||
@@ `lore service install [--interval 30m]`
|
||||
+`lore service install [--interval 30m] [--profile fast|balanced|full]`
|
||||
+
|
||||
+Profiles:
|
||||
+- fast: `sync --no-docs --no-embed`
|
||||
+- balanced (default): `sync --no-embed`
|
||||
+- full: `sync`
|
||||
```
|
||||
|
||||
9. **Upgrade `service status` to include scheduler health + recent run summary**
|
||||
Reasoning: Single last-sync snapshot is too shallow. Include recent attempts and whether scheduler is paused/backing off/running.
|
||||
|
||||
```diff
|
||||
@@ `lore service status`
|
||||
-What it does: Shows whether the service is installed, its configuration, last sync result, and next scheduled run.
|
||||
+What it does: Shows install state, scheduler state (running/backoff/paused), recent runs, and next run estimate.
|
||||
|
||||
@@ Robot output
|
||||
- "last_sync": { ... },
|
||||
- "backoff": null
|
||||
+ "scheduler_state": "running|backoff|paused|idle",
|
||||
+ "last_sync": { ... },
|
||||
+ "recent_runs": [{"run_id":"...","status":"...","started_at_iso":"..."}],
|
||||
+ "backoff": null,
|
||||
+ "paused_reason": null
|
||||
```
|
||||
|
||||
10. **Strengthen tests around determinism and cross-platform generation**
|
||||
Reasoning: Time-based backoff and shell quoting are classic flaky points. Add fake clock + fake command runner for deterministic tests.
|
||||
|
||||
```diff
|
||||
@@ Testing Strategy
|
||||
+Add deterministic test seams:
|
||||
+- `Clock` trait for backoff/now calculations
|
||||
+- `CommandRunner` trait for backend command execution
|
||||
+
|
||||
+Add tests:
|
||||
+- transient vs permanent error classification
|
||||
+- backoff schedule with jitter bounds
|
||||
+- manifest drift reconciliation
|
||||
+- quoting/escaping for paths with spaces and special chars
|
||||
+- `service run` does not modify manual `sync` behavior
|
||||
```
|
||||
|
||||
If you want, I can rewrite your full plan as a single clean revised document with these changes already integrated (instead of patch fragments).
|
||||
182
plans/lore-service.feedback-2.md
Normal file
182
plans/lore-service.feedback-2.md
Normal file
@@ -0,0 +1,182 @@
|
||||
**High-Impact Revisions (ordered by priority)**
|
||||
|
||||
1. **Make service identity project-scoped (avoid collisions across repos/users)**
|
||||
Analysis: Current fixed names (`com.gitlore.sync`, `LoreSync`, `lore-sync.timer`) will collide when users run multiple gitlore workspaces. This causes silent overwrites and broken uninstall/status behavior.
|
||||
Diff:
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@ Commands & User Journeys / install
|
||||
- lore service install [--interval 30m] [--profile balanced] [--token-source env-file]
|
||||
+ lore service install [--interval 30m] [--profile balanced] [--token-source auto] [--name <optional>]
|
||||
@@ Install Manifest Schema
|
||||
+ /// Stable per-install identity (default derived from project root hash)
|
||||
+ pub service_id: String,
|
||||
@@ Platform Backends
|
||||
- Label: com.gitlore.sync
|
||||
+ Label: com.gitlore.sync.{service_id}
|
||||
- Task name: LoreSync
|
||||
+ Task name: LoreSync-{service_id}
|
||||
- ~/.config/systemd/user/lore-sync.service
|
||||
+ ~/.config/systemd/user/lore-sync-{service_id}.service
|
||||
```
|
||||
|
||||
2. **Replace token model with secure per-OS defaults**
|
||||
Analysis: The current “env-file default” is not actually secure on macOS launchd (token still ends up in plist). On Windows, assumptions about inherited environment are fragile. Use OS-native secure stores by default and keep `embedded` as explicit opt-in only.
|
||||
Diff:
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@ Token storage strategies
|
||||
-| env-file (default) | ...
|
||||
+| auto (default) | macOS: Keychain, Linux: env-file (0600), Windows: Credential Manager |
|
||||
+| env-file | Linux/systemd only |
|
||||
| embedded | ... explicit warning ...
|
||||
@@ macOS launchd section
|
||||
- env-file strategy stores canonical token in service-env but embeds token in plist
|
||||
+ default strategy is Keychain lookup at runtime; no token persisted in plist
|
||||
+ env-file is not offered on macOS
|
||||
@@ Windows schtasks section
|
||||
- token must be in user's system environment
|
||||
+ default strategy stores token in Windows Credential Manager and injects at runtime
|
||||
```
|
||||
|
||||
3. **Version and atomically persist manifest/status**
|
||||
Analysis: `Option<Self>` on read hides corruption, and non-atomic writes risk truncated JSON on crashes. This will create false “not installed” and scheduler confusion.
|
||||
Diff:
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@ Install Manifest Schema
|
||||
+ pub schema_version: u32, // start at 1
|
||||
+ pub updated_at_iso: String,
|
||||
@@ Status File Schema
|
||||
+ pub schema_version: u32, // start at 1
|
||||
+ pub updated_at_iso: String,
|
||||
@@ Read/Write
|
||||
- read(path) -> Option<Self>
|
||||
+ read(path) -> Result<Option<Self>, LoreError>
|
||||
- write(...) -> std::io::Result<()>
|
||||
+ write_atomic(...) -> std::io::Result<()> // tmp file + fsync + rename
|
||||
```
|
||||
|
||||
4. **Persist `next_retry_at_ms` instead of recomputing jitter**
|
||||
Analysis: Deterministic jitter from timestamp modulo is predictable and can herd retries. Persisting `next_retry_at_ms` at failure time makes status accurate, stable, and cheap to compute.
|
||||
Diff:
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@ SyncStatusFile
|
||||
pub consecutive_failures: u32,
|
||||
+ pub next_retry_at_ms: Option<i64>,
|
||||
@@ Backoff Logic
|
||||
- compute backoff from last_run.timestamp_ms and deterministic jitter each read
|
||||
+ compute backoff once on failure, store next_retry_at_ms, read-only comparison afterward
|
||||
+ jitter algorithm: full jitter in [0, cap], injectable RNG for tests
|
||||
```
|
||||
|
||||
5. **Add circuit breaker for repeated transient failures**
|
||||
Analysis: Infinite transient retries can run forever on systemic failures (DB corruption, bad network policy). After N transient failures, pause with actionable reason.
|
||||
Diff:
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@ Scheduler states
|
||||
- backoff — transient failures, waiting to retry
|
||||
+ backoff — transient failures, waiting to retry
|
||||
+ paused — permanent error OR circuit breaker tripped after N transient failures
|
||||
@@ Service run flow
|
||||
- On transient failure: increment failures, compute backoff
|
||||
+ On transient failure: increment failures, compute backoff, if failures >= max_transient_failures -> pause
|
||||
```
|
||||
|
||||
6. **Stage-aware outcome policy (core freshness over all-or-nothing)**
|
||||
Analysis: Failing embeddings/docs should not block issues/MRs freshness. Split stage outcomes and only treat core stages as hard-fail by default. This improves reliability and practical usefulness.
|
||||
Diff:
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@ Context
|
||||
- lore sync runs a 4-stage pipeline ... treated as one run result
|
||||
+ lore service run records per-stage outcomes (issues, mrs, docs, embeddings)
|
||||
@@ Status File Schema
|
||||
+ pub stage_results: Vec<StageResult>,
|
||||
@@ service run flow
|
||||
- Execute sync pipeline with flags derived from profile
|
||||
+ Execute stage-by-stage and classify severity:
|
||||
+ - critical: issues, mrs
|
||||
+ - optional: docs, embeddings
|
||||
+ optional stage failures mark run as degraded, not failed
|
||||
```
|
||||
|
||||
7. **Replace cfg free-function backend with trait-based backend**
|
||||
Analysis: Current backend API is hard to test end-to-end without real OS commands. A `SchedulerBackend` trait enables deterministic integration tests and cleaner architecture.
|
||||
Diff:
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@ Platform Backends / Architecture
|
||||
- exports free functions dispatched via #[cfg]
|
||||
+ define trait SchedulerBackend { install, uninstall, state, file_paths, next_run }
|
||||
+ provide LaunchdBackend, SystemdBackend, SchtasksBackend implementations
|
||||
+ include FakeBackend for integration tests
|
||||
```
|
||||
|
||||
8. **Harden platform units and detect scheduler prerequisites**
|
||||
Analysis: systemd user timers often fail silently without user manager/linger; launchd context can be wrong in headless sessions. Add explicit diagnostics and unit hardening.
|
||||
Diff:
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@ Linux systemd unit
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=...
|
||||
+TimeoutStartSec=900
|
||||
+NoNewPrivileges=true
|
||||
+PrivateTmp=true
|
||||
+ProtectSystem=strict
|
||||
+ProtectHome=read-only
|
||||
@@ Linux install/status
|
||||
+ detect user manager availability and linger state; surface warning/action
|
||||
@@ macOS install/status
|
||||
+ detect non-GUI bootstrap context and return actionable error
|
||||
```
|
||||
|
||||
9. **Add operational commands: `trigger`, `doctor`, and non-interactive log tail**
|
||||
Analysis: `logs` opening an editor is weak for automation and incident response. Operators need a preflight and immediate controlled run.
|
||||
Diff:
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@ ServiceCommand
|
||||
+ Trigger, // run one attempt through service policy now
|
||||
+ Doctor, // validate scheduler, token, paths, permissions
|
||||
@@ logs
|
||||
- opens editor
|
||||
+ supports --tail <n> and --follow in human mode
|
||||
+ robot mode can return last_n lines optionally
|
||||
```
|
||||
|
||||
10. **Fix plan inconsistencies and edge-case correctness**
|
||||
Analysis: There are internal mismatches that will cause implementation drift.
|
||||
Diff:
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@ Interval Parsing
|
||||
- supports 's' suffix
|
||||
+ remove 's' suffix (acceptance only allows 5m..24h)
|
||||
@@ uninstall acceptance
|
||||
- removes ALL service files only
|
||||
+ explicitly also remove service-manifest and service-env (status/logs retained)
|
||||
@@ SyncStatusFile schema
|
||||
- pub last_run: SyncRunRecord
|
||||
+ pub last_run: Option<SyncRunRecord> // matches idle/no runs state
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**Recommended Architecture Upgrade Summary**
|
||||
|
||||
The strongest improvement set is: **(1) project-scoped IDs, (2) secure token defaults, (3) atomic/versioned state, (4) persisted retry schedule + circuit breaker, (5) stage-aware outcomes**. That combination materially improves correctness, multi-repo safety, security, operability, and real-world reliability without changing your core manual-vs-scheduled separation principle.
|
||||
174
plans/lore-service.feedback-3.md
Normal file
174
plans/lore-service.feedback-3.md
Normal file
@@ -0,0 +1,174 @@
|
||||
Below are the highest-impact revisions I’d make, ordered by severity/ROI. These focus on correctness first, then security, then operability and UX.
|
||||
|
||||
1. **Fix multi-install ambiguity (`service_id` exists, but commands can’t target one explicitly)**
|
||||
Analysis: The plan introduces `service-manifest-{service_id}.json`, but `status/uninstall/resume/logs` have no selector. In a multi-workspace or multi-name install scenario, behavior becomes ambiguous and error-prone. Add explicit targeting plus discovery.
|
||||
```diff
|
||||
@@ ## Commands & User Journeys
|
||||
+### `lore service list`
|
||||
+Lists installed services discovered from `{data_dir}/service-manifest-*.json`.
|
||||
+Robot output includes `service_id`, `platform`, `interval_seconds`, `profile`, `installed_at_iso`.
|
||||
|
||||
@@ ### `lore service uninstall`
|
||||
-### `lore service uninstall`
|
||||
+### `lore service uninstall [--service <service_id|name>] [--all]`
|
||||
@@
|
||||
-2. CLI reads install manifest to find `service_id`
|
||||
+2. CLI resolves target service via `--service` or current-project-derived default.
|
||||
+3. If multiple candidates and no selector, return actionable error.
|
||||
|
||||
@@ ### `lore service status`
|
||||
-### `lore service status`
|
||||
+### `lore service status [--service <service_id|name>]`
|
||||
```
|
||||
|
||||
2. **Make status state service-scoped (not global)**
|
||||
Analysis: A single `sync-status.json` for all services causes cross-service contamination (pause/backoff/outcome from one profile affecting another). Keep lock global, but state per service.
|
||||
```diff
|
||||
@@ ## Status File
|
||||
-### Location
|
||||
-`{get_data_dir()}/sync-status.json`
|
||||
+### Location
|
||||
+`{get_data_dir()}/sync-status-{service_id}.json`
|
||||
|
||||
@@ ## Paths Module Additions
|
||||
-pub fn get_service_status_path() -> PathBuf {
|
||||
- get_data_dir().join("sync-status.json")
|
||||
+pub fn get_service_status_path(service_id: &str) -> PathBuf {
|
||||
+ get_data_dir().join(format!("sync-status-{service_id}.json"))
|
||||
}
|
||||
@@
|
||||
-Note: `sync-status.json` is NOT scoped by `service_id`
|
||||
+Note: status is scoped by `service_id`; lock remains global (`sync_pipeline`) to prevent overlapping writes.
|
||||
```
|
||||
|
||||
3. **Stop classifying permanence via string matching**
|
||||
Analysis: Matching `"401 Unauthorized"` in strings is brittle and will misclassify edge cases. Carry machine codes through stage results and classify by `ErrorCode` only.
|
||||
```diff
|
||||
@@ pub struct StageResult {
|
||||
- pub error: Option<String>,
|
||||
+ pub error: Option<String>,
|
||||
+ pub error_code: Option<String>, // e.g., AUTH_FAILED, NETWORK_ERROR
|
||||
}
|
||||
@@ Error classification helpers
|
||||
-fn is_permanent_error_message(msg: Option<&str>) -> bool { ...string contains... }
|
||||
+fn is_permanent_error_code(code: Option<&str>) -> bool {
|
||||
+ matches!(code, Some("TOKEN_NOT_SET" | "AUTH_FAILED" | "CONFIG_NOT_FOUND" | "CONFIG_INVALID" | "MIGRATION_FAILED"))
|
||||
+}
|
||||
```
|
||||
|
||||
4. **Install should be transactional (manifest written last)**
|
||||
Analysis: Current order writes manifest before scheduler enable. If enable fails, you persist a false “installed” state. Use two-phase install with rollback.
|
||||
```diff
|
||||
@@ ### `lore service install` User journey
|
||||
-9. CLI writes install manifest ...
|
||||
-10. CLI runs the platform-specific enable command
|
||||
+9. CLI runs the platform-specific enable command
|
||||
+10. On success, CLI writes install manifest atomically
|
||||
+11. On failure, CLI removes generated files and returns `ServiceCommandFailed`
|
||||
```
|
||||
|
||||
5. **Fix launchd token security gap (env-file currently still embeds token)**
|
||||
Analysis: Current “env-file” on macOS still writes token into plist, defeating the main security goal. Generate a private wrapper script that reads env file at runtime and execs `lore`.
|
||||
```diff
|
||||
@@ ### macOS: launchd
|
||||
-<key>ProgramArguments</key>
|
||||
-<array>
|
||||
- <string>{binary_path}</string>
|
||||
- <string>--robot</string>
|
||||
- <string>service</string>
|
||||
- <string>run</string>
|
||||
-</array>
|
||||
+<key>ProgramArguments</key>
|
||||
+<array>
|
||||
+ <string>{data_dir}/service-run-{service_id}.sh</string>
|
||||
+</array>
|
||||
@@
|
||||
-`env-file`: ... token value must still appear in plist ...
|
||||
+`env-file`: token never appears in plist; wrapper loads `{data_dir}/service-env-{service_id}` at runtime.
|
||||
```
|
||||
|
||||
6. **Improve backoff math and add half-open circuit recovery**
|
||||
Analysis: Current jitter + min clamp makes first retry deterministic and can over-pause. Also circuit-breaker requires manual resume forever. Add cooldown + half-open probe to self-heal.
|
||||
```diff
|
||||
@@ Backoff Logic
|
||||
-let backoff_secs = ((base_backoff as f64) * jitter_factor) as u64;
|
||||
-let backoff_secs = backoff_secs.max(base_interval_seconds);
|
||||
+let max_backoff = base_backoff;
|
||||
+let min_backoff = base_interval_seconds;
|
||||
+let span = max_backoff.saturating_sub(min_backoff);
|
||||
+let backoff_secs = min_backoff + ((span as f64) * jitter_factor) as u64;
|
||||
|
||||
@@ Scheduler states
|
||||
-- `paused` — permanent error ... OR circuit breaker tripped ...
|
||||
+- `paused` — permanent error requiring intervention
|
||||
+- `half_open` — probe state after circuit cooldown; one trial run allowed
|
||||
|
||||
@@ Circuit breaker
|
||||
-... transitions to `paused` ... Run: lore service resume
|
||||
+... transitions to `half_open` after cooldown (default 30m). Successful probe closes breaker automatically; failed probe returns to backoff/paused.
|
||||
```
|
||||
|
||||
7. **Promote backend trait to v1 (not v2) for deterministic integration tests**
|
||||
Analysis: This is a reliability-critical feature spanning OS schedulers. A trait abstraction now gives true behavior tests and safer refactors.
|
||||
```diff
|
||||
@@ ### Platform Backends
|
||||
-> Future architecture note: A `SchedulerBackend` trait ... for v2.
|
||||
+Adopt `SchedulerBackend` trait in v1 with real backends (`launchd/systemd/schtasks`) and `FakeBackend` for tests.
|
||||
+This enables deterministic install/uninstall/status/run-path integration tests without touching host scheduler.
|
||||
```
|
||||
|
||||
8. **Harden `run_cmd` timeout behavior**
|
||||
Analysis: If timeout occurs, child process must be killed and reaped. Otherwise you leak processes and can wedge repeated runs.
|
||||
```diff
|
||||
@@ fn run_cmd(...)
|
||||
-// Wait with timeout
|
||||
-let output = wait_with_timeout(output, timeout_secs)?;
|
||||
+// Wait with timeout; on timeout kill child and wait to reap
|
||||
+let output = wait_with_timeout_kill_and_reap(child, timeout_secs)?;
|
||||
```
|
||||
|
||||
9. **Add manual control commands (`pause`, `trigger`, `repair`)**
|
||||
Analysis: These are high-utility operational controls. `trigger` helps immediate sync without waiting interval. `pause` supports maintenance windows. `repair` avoids manual file deletion for corrupt state.
|
||||
```diff
|
||||
@@ pub enum ServiceCommand {
|
||||
+ /// Pause scheduled execution without uninstalling
|
||||
+ Pause { #[arg(long)] reason: Option<String> },
|
||||
+ /// Trigger an immediate one-off run using installed profile
|
||||
+ Trigger { #[arg(long)] ignore_backoff: bool },
|
||||
+ /// Repair corrupt manifest/status by backing up and reinitializing
|
||||
+ Repair { #[arg(long)] service: Option<String> },
|
||||
}
|
||||
```
|
||||
|
||||
10. **Make `logs` default non-interactive and add rotation policy**
|
||||
Analysis: Opening editor by default is awkward for automation/SSH and slower for normal diagnosis. Defaulting to `tail` is more practical; `--open` can preserve editor behavior.
|
||||
```diff
|
||||
@@ ### `lore service logs`
|
||||
-By default, opens in the user's preferred editor.
|
||||
+By default, prints last 100 lines to stdout.
|
||||
+Use `--open` to open editor.
|
||||
@@
|
||||
+Log rotation: rotate `service-stdout.log` / `service-stderr.log` at 10 MB, keep 5 files.
|
||||
```
|
||||
|
||||
11. **Remove destructive/shell-unsafe suggested action**
|
||||
Analysis: `actions(): ["rm {path}", ...]` is unsafe (shell injection + destructive guidance). Replace with safe command path.
|
||||
```diff
|
||||
@@ LoreError::actions()
|
||||
-Self::ServiceCorruptState { path, .. } => vec![&format!("rm {path}"), "lore service install"],
|
||||
+Self::ServiceCorruptState { .. } => vec!["lore service repair", "lore service install"],
|
||||
```
|
||||
|
||||
12. **Tighten scheduler units for real-world reliability**
|
||||
Analysis: Add explicit working directory and success-exit handling to reduce environment drift and edge failures.
|
||||
```diff
|
||||
@@ systemd service unit
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart={binary_path} --robot service run
|
||||
+WorkingDirectory={data_dir}
|
||||
+SuccessExitStatus=0
|
||||
TimeoutStartSec=900
|
||||
```
|
||||
|
||||
If you want, I can produce a single consolidated “v3 plan” markdown with these revisions already merged into your original structure.
|
||||
190
plans/lore-service.feedback-4.md
Normal file
190
plans/lore-service.feedback-4.md
Normal file
@@ -0,0 +1,190 @@
|
||||
No `## Rejected Recommendations` section was present in the plan you shared, so the proposals below are all net-new.
|
||||
|
||||
1. **Make scheduled runs explicitly target a single service instance**
|
||||
Analysis: right now `service run` has no selector, but the plan supports multiple installed services. That creates ambiguity and incorrect manifest/status selection. This is the most important architectural fix.
|
||||
|
||||
```diff
|
||||
@@ `lore service install` What it does
|
||||
- runs `lore --robot service run` at the specified interval
|
||||
+ runs `lore --robot service run --service-id <service_id>` at the specified interval
|
||||
|
||||
@@ Robot output (`install`)
|
||||
- "sync_command": "/usr/local/bin/lore --robot service run",
|
||||
+ "sync_command": "/usr/local/bin/lore --robot service run --service-id a1b2c3d4",
|
||||
|
||||
@@ `ServiceCommand` enum
|
||||
- #[command(hide = true)]
|
||||
- Run,
|
||||
+ #[command(hide = true)]
|
||||
+ Run {
|
||||
+ /// Internal selector injected by scheduler backend
|
||||
+ #[arg(long, hide = true)]
|
||||
+ service_id: String,
|
||||
+ },
|
||||
|
||||
@@ `handle_service_run` signature
|
||||
-pub fn handle_service_run(start: std::time::Instant) -> Result<(), Box<dyn std::error::Error>>
|
||||
+pub fn handle_service_run(service_id: &str, start: std::time::Instant) -> Result<(), Box<dyn std::error::Error>>
|
||||
|
||||
@@ run flow step 1
|
||||
- Read install manifest
|
||||
+ Read install manifest for `service_id`
|
||||
```
|
||||
|
||||
2. **Strengthen `service_id` derivation to avoid cross-workspace collisions**
|
||||
Analysis: hashing config path alone can collide when many workspaces share one global config. Identity should represent what is being synced, not only where config lives.
|
||||
|
||||
```diff
|
||||
@@ Key Design Principles / Project-Scoped Service Identity
|
||||
- derive from a stable hash of the config file path
|
||||
+ derive from a stable fingerprint of:
|
||||
+ - canonical workspace root
|
||||
+ - normalized configured GitLab project URLs
|
||||
+ - canonical config path
|
||||
+ then take first 12 hex chars of SHA-256
|
||||
|
||||
@@ `compute_service_id`
|
||||
- Returns first 8 hex chars of SHA-256 of the canonical config path.
|
||||
+ Returns first 12 hex chars of SHA-256 of a canonical identity tuple
|
||||
+ (workspace_root + sorted project URLs + config_path).
|
||||
```
|
||||
|
||||
3. **Introduce a service-state machine with a dedicated admin lock**
|
||||
Analysis: install/uninstall/pause/resume/repair/status can race each other. A lock and explicit transition table prevents invalid states and file races.
|
||||
|
||||
```diff
|
||||
@@ New section: Service State Model
|
||||
+ All state mutations are serialized by `AppLock("service-admin-{service_id}")`.
|
||||
+ Legal transitions:
|
||||
+ - idle -> running -> success|degraded|backoff|paused
|
||||
+ - backoff -> running|paused
|
||||
+ - paused -> half_open|running (resume)
|
||||
+ - half_open -> running|paused
|
||||
+ Any invalid transition is rejected with `ServiceCorruptState`.
|
||||
|
||||
@@ `handle_install`, `handle_uninstall`, `handle_pause`, `handle_resume`, `handle_repair`
|
||||
+ Acquire `service-admin-{service_id}` before mutating manifest/status/service files.
|
||||
```
|
||||
|
||||
4. **Unify manual and scheduled sync execution behind one orchestrator**
|
||||
Analysis: the plan currently duplicates stage logic and error classification in `service run`, increasing drift risk. A shared orchestrator gives one authoritative pipeline behavior.
|
||||
|
||||
```diff
|
||||
@@ Key Design Principles
|
||||
+ #### 6. Single Sync Orchestrator
|
||||
+ Both `lore sync` and `lore service run` call `SyncOrchestrator`.
|
||||
+ Service mode adds policy (backoff/circuit-breaker); manual mode bypasses policy.
|
||||
|
||||
@@ Service Run Implementation
|
||||
- execute_sync_stages(&sync_args)
|
||||
+ SyncOrchestrator::run(SyncMode::Service { profile, policy })
|
||||
|
||||
@@ manual sync
|
||||
- separate pipeline path
|
||||
+ SyncOrchestrator::run(SyncMode::Manual { flags })
|
||||
```
|
||||
|
||||
5. **Add bounded in-run retries for transient core-stage failures**
|
||||
Analysis: single-shot failure handling will over-trigger backoff on temporary network blips. One short retry per core stage significantly improves freshness without much extra runtime.
|
||||
|
||||
```diff
|
||||
@@ Stage-aware execution
|
||||
+ Core stages (`issues`, `mrs`) get up to 1 immediate retry on transient errors
|
||||
+ (jittered 1-5s). Permanent errors are never retried.
|
||||
+ Optional stages keep best-effort semantics.
|
||||
|
||||
@@ Acceptance criteria (`service run`)
|
||||
+ Retries transient core stage failures once before counting run as failed.
|
||||
```
|
||||
|
||||
6. **Harden persistence with full crash-safety semantics**
|
||||
Analysis: current atomic write description is good but incomplete for power-loss durability. You should fsync parent directory after rename and include lightweight integrity metadata.
|
||||
|
||||
```diff
|
||||
@@ `write_atomic`
|
||||
- tmp file + fsync + rename
|
||||
+ tmp file + fsync(file) + rename + fsync(parent_dir)
|
||||
|
||||
@@ `ServiceManifest` and `SyncStatusFile`
|
||||
+ pub write_seq: u64,
|
||||
+ pub content_sha256: String, // optional integrity guard for repair/doctor
|
||||
```
|
||||
|
||||
7. **Fix token handling to avoid shell/env injection and add secure-store mode**
|
||||
Analysis: sourcing env files in shell is brittle if token contains special chars/newlines. Also, secure OS credential stores should be first-class for production reliability/security.
|
||||
|
||||
```diff
|
||||
@@ Token storage strategies
|
||||
-| `env-file` (default) ...
|
||||
+| `auto` (default) | use secure-store when available, else env-file |
|
||||
+| `secure-store` | macOS Keychain / libsecret / Windows Credential Manager |
|
||||
+| `env-file` | explicit fallback |
|
||||
|
||||
@@ macOS wrapper script
|
||||
-. "{data_dir}/service-env-{service_id}"
|
||||
-export {token_env_var}
|
||||
+TOKEN_VALUE="$(cat "{data_dir}/service-token-{service_id}" )"
|
||||
+export {token_env_var}="$TOKEN_VALUE"
|
||||
|
||||
@@ Acceptance criteria
|
||||
+ Reject token values containing `\0` or newline for env-file mode.
|
||||
+ Never eval/source untrusted token content.
|
||||
```
|
||||
|
||||
8. **Correct platform/runtime implementation hazards**
|
||||
Analysis: there are a few correctness risks that should be fixed in-plan now.
|
||||
|
||||
```diff
|
||||
@@ macOS install steps
|
||||
- Get UID via `unsafe { libc::getuid() }`
|
||||
+ Get UID via safe API (`nix::unistd::Uid::current()` or equivalent safe helper)
|
||||
|
||||
@@ Command Runner Helper
|
||||
- poll try_wait and read stdout/stderr after exit
|
||||
+ avoid potential pipe backpressure deadlock:
|
||||
+ use wait-with-timeout + concurrent stdout/stderr draining
|
||||
|
||||
@@ Linux timer
|
||||
- OnUnitActiveSec={interval_seconds}s
|
||||
+ OnUnitInactiveSec={interval_seconds}s
|
||||
+ AccuracySec=1min
|
||||
```
|
||||
|
||||
9. **Make logs fully service-scoped**
|
||||
Analysis: you already scoped manifest/status by `service_id`; logs are still global in several places. Multi-service installs will overwrite each other’s logs.
|
||||
|
||||
```diff
|
||||
@@ Paths Module Additions
|
||||
-pub fn get_service_log_path() -> PathBuf
|
||||
+pub fn get_service_log_path(service_id: &str, stream: LogStream) -> PathBuf
|
||||
|
||||
@@ log filenames
|
||||
- logs/service-stderr.log
|
||||
- logs/service-stdout.log
|
||||
+ logs/service-{service_id}-stderr.log
|
||||
+ logs/service-{service_id}-stdout.log
|
||||
|
||||
@@ `service logs`
|
||||
- default path: `{data_dir}/logs/service-stderr.log`
|
||||
+ default path: `{data_dir}/logs/service-{service_id}-stderr.log`
|
||||
```
|
||||
|
||||
10. **Resolve internal spec contradictions and rollback gaps**
|
||||
Analysis: there are a few contradictory statements and incomplete rollback behavior that will cause implementation churn.
|
||||
|
||||
```diff
|
||||
@@ `service logs` behavior
|
||||
- default (no flags): open in editor (human)
|
||||
+ default (no flags): print last 100 lines (human and robot metadata mode)
|
||||
+ `--open` is explicit opt-in
|
||||
|
||||
@@ install rollback
|
||||
- On failure: removes generated service files
|
||||
+ On failure: removes generated service files, env file, wrapper script, and temp manifest
|
||||
|
||||
@@ `handle_service_run` sample code
|
||||
- let manifest_path = get_service_manifest_path();
|
||||
+ let manifest_path = get_service_manifest_path(service_id);
|
||||
```
|
||||
|
||||
If you want, I can take these revisions and produce a single consolidated “Iteration 4” replacement plan block with all sections rewritten coherently so it’s ready to hand to an implementer.
|
||||
196
plans/lore-service.feedback-5.md
Normal file
196
plans/lore-service.feedback-5.md
Normal file
@@ -0,0 +1,196 @@
|
||||
I reviewed the full plan and avoided everything already listed in `## Rejected Recommendations`. These are the highest-impact revisions I’d make.
|
||||
|
||||
1. **Fix identity model inconsistency and prevent `--name` alias collisions**
|
||||
Why this improves the plan: your text says identity includes workspace root, but the current derivation code does not. Also, using `--name` as the actual `service_id` risks accidental cross-project collisions and destructive updates.
|
||||
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@ Key Design Principles / 2. Project-Scoped Service Identity
|
||||
- Each installed service gets a unique `service_id` derived from a canonical identity tuple: the config file path, sorted GitLab project URLs, and workspace root.
|
||||
+ Each installed service gets an immutable `identity_hash` derived from a canonical identity tuple:
|
||||
+ workspace root + canonical config path + sorted normalized project URLs.
|
||||
+ `service_id` remains the scheduler identifier; `--name` is a human alias only.
|
||||
+ If `--name` collides with an existing service that has a different `identity_hash`, install fails with an actionable error.
|
||||
|
||||
@@ Install Manifest / Schema
|
||||
+ /// Immutable identity hash for collision-safe matching across reinstalls
|
||||
+ pub identity_hash: String,
|
||||
+ /// Optional human-readable alias passed via --name
|
||||
+ #[serde(skip_serializing_if = "Option::is_none")]
|
||||
+ pub service_alias: Option<String>,
|
||||
+ /// Canonical workspace root used in identity derivation
|
||||
+ pub workspace_root: String,
|
||||
|
||||
@@ service_id derivation
|
||||
-pub fn compute_service_id(config_path: &Path, project_urls: &[&str]) -> String
|
||||
+pub fn compute_identity_hash(workspace_root: &Path, config_path: &Path, project_urls: &[&str]) -> String
|
||||
```
|
||||
|
||||
2. **Add lock protocol to eliminate uninstall/run race conditions**
|
||||
Why this improves the plan: today `service run` does not take admin lock, and admin commands do not take pipeline lock. `uninstall` can race with an active run and remove files mid-execution.
|
||||
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@ Key Design Principles / 6. Serialized Admin Mutations
|
||||
- The `service run` entrypoint does NOT acquire the admin lock — it only acquires the `sync_pipeline` lock
|
||||
+ The `service run` entrypoint acquires only `sync_pipeline`.
|
||||
+ Destructive admin operations (`install` overwrite, `uninstall`, `repair --regenerate`) must:
|
||||
+ 1) acquire `service-admin-{service_id}`
|
||||
+ 2) disable scheduler backend entrypoint
|
||||
+ 3) acquire `sync_pipeline` lock with timeout
|
||||
+ 4) mutate/remove files
|
||||
+ This lock ordering is mandatory to prevent deadlocks and run/delete races.
|
||||
|
||||
@@ lore service uninstall / User journey
|
||||
- 4. Runs platform-specific disable command
|
||||
- 5. Removes service files from disk
|
||||
+ 4. Acquires `sync_pipeline` lock (after disabling scheduler) with bounded wait
|
||||
+ 5. Removes service files from disk only after lock acquisition
|
||||
```
|
||||
|
||||
3. **Make transient handling `Retry-After` aware**
|
||||
Why this improves the plan: rate-limit and 503 responses often carry retry hints. Ignoring them causes useless retries and longer outages.
|
||||
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@ Transient vs permanent error classification
|
||||
-| Transient | Retry with backoff | Network timeout, rate limited, DB locked, 5xx from GitLab |
|
||||
+| Transient | Retry with adaptive backoff | Network timeout, DB locked, 5xx from GitLab |
|
||||
+| Transient (hinted) | Respect server retry hint | Rate limited with Retry-After/X-RateLimit-Reset |
|
||||
|
||||
@@ Backoff Logic
|
||||
+ If an error includes a retry hint (e.g., `Retry-After`), set:
|
||||
+ `next_retry_at_ms = max(computed_backoff, hinted_retry_at_ms)`.
|
||||
+ Persist `backoff_reason` for status visibility.
|
||||
```
|
||||
|
||||
4. **Decouple optional stage cadence from core sync interval**
|
||||
Why this improves the plan: running docs/embeddings every 5–30 minutes is expensive and unnecessary. Separate freshness windows reduce cost/latency while keeping core data fresh.
|
||||
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@ Sync profiles
|
||||
-| `balanced` (default) | `--no-embed` | Issues + MRs + doc generation |
|
||||
-| `full` | (none) | Full pipeline including embeddings |
|
||||
+| `balanced` (default) | core every interval, docs every 60m, no embeddings | Fast + useful docs |
|
||||
+| `full` | core every interval, docs every interval, embeddings every 6h (default) | Full freshness with bounded cost |
|
||||
|
||||
@@ Status File / StageResult
|
||||
+ /// true when stage intentionally skipped due freshness window
|
||||
+ #[serde(default)]
|
||||
+ pub skipped: bool,
|
||||
|
||||
@@ lore service run / Stage-aware execution
|
||||
+ Optional stages may be skipped when their last successful run is within configured freshness windows.
|
||||
+ Skipped optional stages do not count as failures and are recorded explicitly.
|
||||
```
|
||||
|
||||
5. **Give Windows parity for secure token handling (env-file + wrapper)**
|
||||
Why this improves the plan: current Windows path requires global/system env and has poor UX. A wrapper+env-file model gives platform parity and avoids global token exposure.
|
||||
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@ Token storage strategies
|
||||
-| On Windows, neither strategy applies — the token must be in the user's system environment
|
||||
+| On Windows, `env-file` is supported via a generated wrapper script (`service-run-{service_id}.cmd` or `.ps1`)
|
||||
+| that reads `{data_dir}/service-env-{service_id}` and launches `lore --robot service run ...`.
|
||||
+| `embedded` remains opt-in and warned as less secure.
|
||||
|
||||
@@ Windows: schtasks
|
||||
- Token handling on Windows: The env var must be set system-wide via `setx`
|
||||
+ Token handling on Windows:
|
||||
+ - `env-file` (default): wrapper script reads token from private file at runtime
|
||||
+ - `embedded`: token passed via wrapper-set environment variable
|
||||
+ - `system_env`: still supported as fallback
|
||||
```
|
||||
|
||||
6. **Add run heartbeat and stale-run detection**
|
||||
Why this improves the plan: `running` state can become misleading after crashes or stale locks. Heartbeat metadata makes status accurate and improves incident triage.
|
||||
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@ Status File / Schema
|
||||
+ /// In-flight run metadata for crash/stale detection
|
||||
+ #[serde(skip_serializing_if = "Option::is_none")]
|
||||
+ pub current_run: Option<CurrentRunState>,
|
||||
+
|
||||
+pub struct CurrentRunState {
|
||||
+ pub run_id: String,
|
||||
+ pub started_at_ms: i64,
|
||||
+ pub last_heartbeat_ms: i64,
|
||||
+ pub pid: u32,
|
||||
+}
|
||||
|
||||
@@ lore service status
|
||||
- - `running` — currently executing (sync_pipeline lock held)
|
||||
+ - `running` — currently executing with live heartbeat
|
||||
+ - `running_stale` — in-flight metadata exists but heartbeat exceeded stale threshold
|
||||
```
|
||||
|
||||
7. **Upgrade drift detection from “loaded/unloaded” to spec-level drift**
|
||||
Why this improves the plan: platform state alone misses manual edits to unit/plist/wrapper files. Spec-hash drift gives reliable “what changed?” diagnostics and safe regeneration.
|
||||
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@ Install Manifest / Schema
|
||||
+ /// Hash of generated scheduler artifacts and command spec
|
||||
+ pub spec_hash: String,
|
||||
|
||||
@@ lore service status
|
||||
- Detects manifest/platform drift and reports it
|
||||
+ Detects:
|
||||
+ - platform drift (loaded/unloaded mismatch)
|
||||
+ - spec drift (artifact content hash mismatch)
|
||||
+ - command drift (sync command differs from manifest)
|
||||
|
||||
@@ lore service repair
|
||||
+ Add `--regenerate` to rewrite scheduler artifacts from manifest when spec drift is detected.
|
||||
+ This is non-destructive and does not delete status/log history.
|
||||
```
|
||||
|
||||
8. **Add safe operational modes: `install --dry-run` and `doctor --fix`**
|
||||
Why this improves the plan: dry-run reduces risk before writing OS scheduler files; fix-mode improves operator ergonomics and lowers support burden.
|
||||
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@ lore service install
|
||||
+ Add `--dry-run`:
|
||||
+ - validates config/token/prereqs
|
||||
+ - renders service files and planned commands
|
||||
+ - writes nothing, executes nothing
|
||||
|
||||
@@ lore service doctor
|
||||
+ Add `--fix` for safe, non-destructive remediations:
|
||||
+ - create missing dirs
|
||||
+ - correct file permissions on env/wrapper files
|
||||
+ - run `systemctl --user daemon-reload` when applicable
|
||||
+ - report applied fixes in robot output
|
||||
```
|
||||
|
||||
9. **Define explicit schema migration behavior (not just `schema_version` fields)**
|
||||
Why this improves the plan: version fields without migration policy become operational risk during upgrades.
|
||||
|
||||
```diff
|
||||
--- a/plan.md
|
||||
+++ b/plan.md
|
||||
@@ ServiceManifest Read/Write
|
||||
- `ServiceManifest::read(path: &Path) -> Result<Option<Self>, LoreError>`
|
||||
+ `ServiceManifest::read_and_migrate(path: &Path) -> Result<Option<Self>, LoreError>`
|
||||
+ - Migrates known older schema versions to current in-memory model
|
||||
+ - Rewrites migrated file atomically
|
||||
+ - Fails with actionable `ServiceCorruptState` for unknown future major versions
|
||||
|
||||
@@ SyncStatusFile Read/Write
|
||||
- `SyncStatusFile::read(path: &Path) -> Result<Option<Self>, LoreError>`
|
||||
+ `SyncStatusFile::read_and_migrate(path: &Path) -> Result<Option<Self>, LoreError>`
|
||||
```
|
||||
|
||||
If you want, I can produce a fully rewritten v5 plan text that integrates all nine changes coherently section-by-section.
|
||||
3759
plans/lore-service.md
Normal file
3759
plans/lore-service.md
Normal file
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user