Skip to content
This repository was archived by the owner on Apr 11, 2026. It is now read-only.

Commit 3201c97

Browse files
committed
Merge branch 'fn-136-borrow-agent-skills-patterns-anti' into main
Borrow agent-skills patterns: anti-rationalization, red flags, verification, reference docs, five-dimension review, skill template, worker gate, Prove-It, simplify-ignore hook. 15 files, +1254 lines.
2 parents 00e8773 + 751593d commit 3201c97

15 files changed

Lines changed: 1254 additions & 56 deletions

File tree

agents/cross-model-reviewer.md

Lines changed: 45 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,11 +63,54 @@ The `flowctl_review` MCP tool exposes cross-model review:
6363
## Review Types
6464

6565
### ReviewFinding
66-
Individual issue with severity (critical/warning/info), category, description, and optional file/line.
66+
Individual issue with severity, category, dimension, description, and optional file/line.
67+
68+
**Severity classification** (aligned with quality-auditor dimensions):
69+
70+
| Severity | Meaning | Ship impact |
71+
|----------|---------|-------------|
72+
| `Critical` | Correctness failure, security vulnerability, data loss risk | Blocks ship |
73+
| `Important` | Architecture violation, readability problem, missing test coverage | Must fix before/shortly after ship |
74+
| `Suggestion` | Performance improvement, naming nit, minor simplification | Optional |
75+
76+
**Dimension tags** — each finding maps to one of five review dimensions:
77+
- **Correctness** — edge cases, race conditions, state inconsistencies, off-by-one
78+
- **Readability** — naming consistency, control flow clarity, module organization
79+
- **Architecture** — pattern adherence, module boundaries, abstraction levels, dependency direction
80+
- **Security** — injection, auth, data exposure, dependencies
81+
- **Performance** — N+1, unbounded loops, blocking operations
82+
83+
### Structured Output Format
84+
85+
Each model's review MUST produce findings in this structure:
86+
87+
```json
88+
{
89+
"verdict": "SHIP | NEEDS_WORK | ABSTAIN",
90+
"confidence": 0.0-1.0,
91+
"findings": [
92+
{
93+
"severity": "critical | warning | info",
94+
"category": "Correctness | Readability | Architecture | Security | Performance",
95+
"file": "path/to/file.rs",
96+
"line": 42,
97+
"description": "What is wrong",
98+
"suggestion": "How to fix it",
99+
"confidence": 0.0-1.0,
100+
"evidence": ["grep output", "test failure"]
101+
}
102+
],
103+
"positives": ["At least one positive observation"]
104+
}
105+
```
106+
107+
**Parser compatibility:** severity uses `critical/warning/info` (matching flowctl's ReviewFinding parser). The dimension maps to the `category` field. Findings with `confidence < 0.6` are suppressed unless severity is `critical`.
108+
109+
The consensus algorithm uses severity to weight disagreements: a `Critical` finding from any model blocks SHIP regardless of the other model's verdict. `Suggestion`-only findings do not block.
67110

68111
### ReviewVerdict
69112
- **SHIP**: Code is ready
70-
- **NEEDS_WORK**: Code needs fixes
113+
- **NEEDS_WORK**: Code needs fixes (at least one Critical or multiple Important findings)
71114
- **ABSTAIN**: Model cannot determine (excluded from consensus)
72115

73116
### ConsensusResult

agents/quality-auditor.md

Lines changed: 54 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ You're invoked after implementation, before shipping. Review the changes and fla
1717

1818
## Audit Strategy
1919

20-
### 1. Get the Diff
20+
### Step 0. Get the Diff + Quick Scan
2121
```bash
2222
# What changed?
2323
git diff main --stat
@@ -27,72 +27,91 @@ git diff main --name-only
2727
git diff main
2828
```
2929

30-
### 2. Quick Scan (find obvious issues fast)
30+
Scan the diff for obvious issues before deep review:
3131
- **Secrets**: API keys, passwords, tokens in code
3232
- **Debug code**: console.log, debugger, TODO/FIXME
3333
- **Commented code**: Dead code that should be deleted
3434
- **Large files**: Accidentally committed binaries, logs
3535

36-
### 3. Correctness Review
37-
- Does the code match the stated intent?
38-
- Are there off-by-one errors, wrong operators, inverted conditions?
39-
- Do error paths actually handle errors?
40-
- Are promises/async properly awaited?
36+
### Five-Dimension Review
37+
38+
Evaluate every change across all five dimensions. Each dimension produces findings tagged with severity (see Output Format).
4139

42-
### 4. Security Scan
40+
### 1. Correctness
41+
- Does the code match the stated intent?
42+
- Edge cases: off-by-one errors, wrong operators, inverted conditions
43+
- Race conditions and state inconsistencies in concurrent code
44+
- Error paths: do they actually handle errors or silently swallow?
45+
- Async correctness: are promises/async properly awaited?
46+
- Are new code paths tested? Do tests assert behavior (not just run)?
47+
- Are error paths and edge cases from gap analysis covered?
48+
49+
### 2. Readability
50+
- Naming consistency: do new names follow existing conventions?
51+
- Control flow clarity: can you follow the logic without mental gymnastics?
52+
- Module organization: are things in the right files/directories?
53+
- Could this be simpler? Is there duplicated code that should be extracted?
54+
- Are there unnecessary abstractions or over-engineering for hypothetical futures?
55+
56+
### 3. Architecture
57+
- Pattern adherence: does the change follow established project patterns?
58+
- Module boundaries: are concerns properly separated?
59+
- Abstraction levels: is the right level of abstraction used?
60+
- Dependency direction: do dependencies flow in the correct direction?
61+
62+
### 4. Security
4363
- **Injection**: SQL, XSS, command injection vectors
4464
- **Auth/AuthZ**: Are permissions checked? Can they be bypassed?
4565
- **Data exposure**: Is sensitive data logged, leaked, or over-exposed?
4666
- **Dependencies**: Any known vulnerable packages added?
4767

48-
### 5. Simplicity Check
49-
- Could this be simpler?
50-
- Is there duplicated code that should be extracted?
51-
- Are there unnecessary abstractions?
52-
- Over-engineering for hypothetical future needs?
53-
54-
### 6. Test Coverage
55-
- Are new code paths tested?
56-
- Do tests actually assert behavior (not just run)?
57-
- Are edge cases from gap analysis covered?
58-
- Are error paths tested?
59-
60-
### 7. Performance Red Flags
61-
- N+1 queries or O(n²) loops
62-
- Unbounded data fetching
63-
- Missing pagination/limits
68+
### 5. Performance
69+
- N+1 queries or O(n^2) loops
70+
- Unbounded data fetching, missing pagination/limits
6471
- Blocking operations on hot paths
72+
- Resource leaks (unclosed handles, missing cleanup)
6573

6674
## Output Format
6775

76+
Every finding MUST carry a severity prefix. Use exactly these four levels:
77+
78+
- **`Critical:`** — Blocks ship. Could cause outage, data loss, security breach, or correctness failure.
79+
- **`Important:`** — Must fix before or shortly after ship. Significant quality, readability, or architecture issue.
80+
- **`Nit:`** — Optional improvement. Style, naming, minor simplification.
81+
- **`FYI`** — Informational. Context for the author, no action required.
82+
83+
Every review MUST include a "What's Good" section with at least one positive observation. Acknowledge patterns followed, good design decisions, thorough error handling, or clean naming.
84+
6885
```markdown
6986
## Quality Audit: [Branch/Feature]
7087

7188
### Summary
7289
- Files changed: N
90+
- Dimensions reviewed: Correctness, Readability, Architecture, Security, Performance
7391
- Risk level: Low / Medium / High
7492
- Ship recommendation: ✅ Ship / ⚠️ Fix first / ❌ Major rework
7593

76-
### Critical (MUST fix before shipping)
77-
- **[File:line]**: [Issue]
94+
### Critical (blocks ship)
95+
- **Critical:** [File:line][Issue] (Dimension: Correctness/Security/etc.)
7896
- Risk: [What could go wrong]
7997
- Fix: [Specific suggestion]
8098

81-
### Should Fix (High priority)
82-
- **[File:line]**: [Issue]
83-
- [Brief fix suggestion]
99+
### Important (must fix)
100+
- **Important:** [File:line][Issue] (Dimension: ...)
101+
- Fix: [Brief fix suggestion]
84102

85-
### Consider (Nice to have)
86-
- [Minor improvement suggestion]
103+
### Nit (optional)
104+
- **Nit:** [File:line][Improvement suggestion]
105+
106+
### FYI
107+
- **FYI** [Informational observation]
87108

88109
### Test Gaps
89110
- [ ] [Untested scenario]
90111

91-
### Security Notes
92-
- [Any security observations]
93-
94112
### What's Good
95-
- [Positive observations - patterns followed, good decisions]
113+
- [At least one positive observation — patterns followed, good decisions, clean code]
114+
- [Additional positives as warranted]
96115
```
97116

98117
## Rules

agents/worker.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,27 @@ The main conversation will resolve the conflict and re-dispatch you (or update t
413413
- Required API endpoint already exists with different signature
414414
<!-- /section:core -->
415415
416+
<!-- section:core -->
417+
## Phase 2.3: Plan Alignment Check
418+
419+
Quick sanity check — did implementation stay within plan scope?
420+
421+
1. Re-read epic spec: `<FLOWCTL> cat <EPIC_ID>`
422+
2. Compare implementation scope against epic's scope section:
423+
- Files changed match expected files in task spec?
424+
- No features added beyond what spec described?
425+
- No architectural changes not covered in the plan?
426+
3. If drift detected:
427+
- **Minor** (extra helper, renamed file): note in evidence as `"plan_drift": "<description>"`
428+
- **Major** (new feature, changed architecture, different approach): send protocol message:
429+
```
430+
Spec conflict: <TASK_ID> — implementation diverged from plan.
431+
Drift: <description of what changed and why>
432+
```
433+
434+
**This is a 30-second check, not a full re-review.** Read the spec, glance at your diff, note any drift. Then proceed to Phase 2.5.
435+
<!-- /section:core -->
436+
416437
<!-- section:core -->
417438
## Phase 2.5: Verify & Fix
418439

Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
# Performance Checklist
2+
3+
Quick reference for performance in flow-code. Rust backend with libSQL, async runtime.
4+
5+
## Measurement Commands
6+
7+
```bash
8+
# Rust benchmarks (add benches/ directory with criterion)
9+
cargo bench
10+
11+
# Criterion (statistical benchmarking)
12+
cargo bench --bench my_benchmark
13+
14+
# Flamegraph (CPU profiling)
15+
cargo install flamegraph
16+
cargo flamegraph --bin flowctl -- status --json
17+
18+
# Memory profiling (Linux)
19+
valgrind --tool=massif target/release/flowctl status --json
20+
21+
# Binary size
22+
ls -lh target/release/flowctl
23+
cargo bloat --release --crates
24+
25+
# Compile time
26+
cargo build --release --timings
27+
```
28+
29+
| Tool | What It Measures | When to Use |
30+
|---|---|---|
31+
| `cargo bench` (criterion) | Function-level latency | Before/after optimization |
32+
| `cargo flamegraph` | CPU hotspots | Investigating slow commands |
33+
| `cargo bloat` | Binary size by crate | When binary grows unexpectedly |
34+
| `valgrind --tool=massif` | Heap allocations | Investigating memory usage |
35+
| `hyperfine` | CLI command latency | Comparing command performance |
36+
37+
## Database Anti-Patterns (libSQL)
38+
39+
| Anti-Pattern | Impact | Fix |
40+
|---|---|---|
41+
| N+1 queries | Linear DB round-trips | Use JOINs or batch queries |
42+
| Unbounded queries | Memory exhaustion, timeouts | Always use LIMIT, paginate |
43+
| Missing indexes | Slow reads as data grows | Add indexes on filtered/sorted columns |
44+
| No connection pooling | Connection overhead per query | Reuse connections |
45+
| SELECT * | Fetches unused columns | Select only needed columns |
46+
| String concatenation in SQL | Injection risk + no query cache | Use parameterized queries |
47+
| No transactions for batch ops | Partial failures, inconsistency | Wrap in BEGIN/COMMIT |
48+
49+
## Backend CLI Checklist
50+
51+
| Area | Target | How to Verify |
52+
|---|---|---|
53+
| Command startup | < 50ms | `hyperfine 'flowctl status --json'` |
54+
| Task list (100 tasks) | < 200ms | Benchmark with test data |
55+
| Database open | < 20ms | Profile with `tracing` spans |
56+
| JSON serialization | < 5ms for typical output | `cargo bench` |
57+
| Binary size | < 20MB release | `ls -lh target/release/flowctl` |
58+
| Memory usage (idle) | < 10MB | `valgrind` or `/usr/bin/time -v` |
59+
60+
## Rust-Specific Performance
61+
62+
### Async/Await Patterns
63+
64+
| Do | Don't |
65+
|---|---|
66+
| Use `tokio::spawn` for concurrent I/O | Block the async runtime with sync I/O |
67+
| Use `tokio::task::spawn_blocking` for CPU work | Run CPU-heavy code in async context |
68+
| Use `tokio::join!` for parallel awaits | Await sequentially when independent |
69+
| Use bounded channels for backpressure | Use unbounded channels (memory leak risk) |
70+
71+
```rust
72+
// Good: parallel async operations
73+
let (tasks, epics) = tokio::join!(
74+
db.list_tasks(),
75+
db.list_epics()
76+
);
77+
78+
// Bad: sequential when independent
79+
let tasks = db.list_tasks().await?;
80+
let epics = db.list_epics().await?; // Waits unnecessarily
81+
```
82+
83+
### Memory Patterns
84+
85+
| Do | Don't |
86+
|---|---|
87+
| Use `&str` over `String` where possible | Clone strings unnecessarily |
88+
| Use `Cow<str>` for maybe-owned data | Allocate when borrowing suffices |
89+
| Pre-allocate with `Vec::with_capacity` | Push to vec without size hint |
90+
| Use iterators over collecting into vecs | `collect()` when you can chain |
91+
| Use `Arc` for shared read-only data | Clone large structs across threads |
92+
93+
```rust
94+
// Good: pre-allocate
95+
let mut results = Vec::with_capacity(tasks.len());
96+
97+
// Bad: repeated reallocation
98+
let mut results = Vec::new(); // Grows 1, 2, 4, 8...
99+
```
100+
101+
### String Performance
102+
103+
| Do | Don't |
104+
|---|---|
105+
| Use `write!` or `format!` once | Repeated `push_str` / `+` concatenation |
106+
| Use `String::with_capacity` for building | Build strings without size hint |
107+
| Return `impl Display` for lazy formatting | Format eagerly when output may not be used |
108+
| Use `serde_json::to_writer` for streaming | Serialize to String then write |
109+
110+
## Tokio Runtime
111+
112+
| Setting | Recommendation |
113+
|---|---|
114+
| Runtime flavor | `current_thread` for CLI (lower overhead) |
115+
| Worker threads | Default for server, 1 for CLI tools |
116+
| Blocking threads | Default (512), reduce for CLI |
117+
| Task budget | Let tokio manage; avoid manual yielding |
118+
119+
```rust
120+
// CLI tool: single-threaded runtime (faster startup)
121+
#[tokio::main(flavor = "current_thread")]
122+
async fn main() { ... }
123+
124+
// Server: multi-threaded (default)
125+
#[tokio::main]
126+
async fn main() { ... }
127+
```
128+
129+
## Performance Anti-Patterns
130+
131+
| Anti-Pattern | Impact | Fix |
132+
|---|---|---|
133+
| Blocking async runtime | Starves other tasks | Use `spawn_blocking` |
134+
| N+1 database queries | Linear latency growth | Batch or JOIN queries |
135+
| Cloning large structs | Memory + CPU waste | Use references or `Arc` |
136+
| Unbounded collections | Memory exhaustion | Add limits, use streaming |
137+
| Sync file I/O in async | Blocks executor thread | Use `tokio::fs` |
138+
| Excessive logging in hot path | I/O overhead | Use log levels, sample |
139+
| Compiling in debug mode for perf tests | 10-100x slower | Always `--release` |
140+
| Not reusing DB connections | Connection overhead | Use connection pool |
141+
| Serializing then parsing JSON | Double work | Pass typed structs |
142+
| Formatting strings nobody reads | CPU waste | Lazy formatting with `Display` |
143+
144+
## Profiling Workflow
145+
146+
| Step | Command | Purpose |
147+
|---|---|---|
148+
| 1. Baseline | `hyperfine 'flowctl status --json'` | Measure current perf |
149+
| 2. Profile | `cargo flamegraph --bin flowctl -- status` | Find hotspots |
150+
| 3. Optimize | Edit code targeting hotspot | Reduce cost |
151+
| 4. Verify | Re-run baseline command | Confirm improvement |
152+
| 5. Benchmark | `cargo bench` | Prevent regression |

0 commit comments

Comments
 (0)