# Use Cases

Real-world scenarios showing how KOGRAL solves common development challenges.

## Use Case 1: Onboarding New Team Members

### Problem

New developer joins the team. Needs to understand:
- Why we chose SurrealDB over PostgreSQL
- How error handling works in this project
- What coding patterns we follow
- Recent architectural decisions

### Solution with KOGRAL

**Team lead**:

```bash
# Export project knowledge to Logseq for visual exploration
kogral export logseq ~/onboarding-docs
```

**New developer** (with Claude Code):

```text
Summarize our architectural decisions from the last 6 months
```

**Claude** (via MCP):

```text
Found 8 decisions:

1. **Use SurrealDB for Storage** (accepted, 3 months ago)
   - Context: Need graph database for knowledge relationships
   - Consequences: Better queries, additional infrastructure

2. **Adopt Rust for Core Logic** (accepted, 5 months ago)
   - Context: Type safety and performance critical
   - Consequences: Steeper learning curve, excellent reliability

... [6 more decisions]
```

**New developer**:

```text
What are our error handling guidelines?
```

**Claude** (via `kogral/get_guidelines`):

```text
## Rust Error Handling Guidelines

### Project Guidelines (priority: 150)
- Use thiserror for custom error types
- Never unwrap() in production
- Propagate with ? operator

### Shared Guidelines (priority: 50)
- Always use Result<T> for fallible operations
- Add context with .context()

[Links to full guideline documents]
```

**Result**: New developer productive in days, not weeks.

---

## Use Case 2: Architectural Decision Records (ADR)

### Problem

Team discussing whether to add Redis caching. Multiple opinions, need to document the decision for future reference.

### Solution with KOGRAL

**During meeting**:

```text
Document decision: Add Redis caching for API responses

Context:
- Current database queries average 200ms
- 80% of queries are repeated within 5 minutes
- Need sub-50ms response times for user experience

Decision:
- Add Redis with 5-minute TTL for GET endpoints
- Cache invalidation on POST/PUT/DELETE

Consequences:
- ✅ Expected 80% reduction in database load
- ✅ Sub-50ms response times achieved
- ❌ Additional infrastructure (Redis server)
- ❌ Cache consistency challenges
- ❌ Debugging complexity increases

Status: proposed (pending infrastructure setup)
```

**Claude** (creates ADR):

```text
Created: decision-add-redis-caching
Type: decision
Status: proposed

Added relationships:
  - Relates to: note-performance-requirements
  - Depends on: decision-use-docker-compose (infrastructure)

Decision documented and linked to related knowledge.
```

**Two months later**, someone asks "Why Redis?":

```text
kogral show decision-add-redis-caching
```

Full context available instantly.

---

## Use Case 3: Pattern Library

### Problem

Team solves the same problems repeatedly:
- How to structure error types
- Database connection patterns
- Testing strategies

Each developer rediscovers solutions.

### Solution with KOGRAL

**First time** solving error handling:

```bash
kogral add pattern "Error Handling with thiserror" \
  --tags rust,error-handling,pattern \
  --content "$(cat docs/error-pattern.md)"
```

**Next time** someone needs error handling:

```text
I'm implementing a new module with errors. What's our standard pattern?
```

**Claude** (via `kogral/search`):

```text
Found pattern: Error Handling with thiserror

## Pattern: Error Handling with thiserror

### Problem
Need structured, type-safe error handling with good error messages.

### Solution
```rust

use thiserror::Error;

#[derive(Error, Debug)]
pub enum ModuleError {
    #[error("Database connection failed: {0}")]
    Database(#[from] sqlx::Error),

    #[error("Validation failed: {0}")]
    Validation(String),
}

```text

### Usage
```rust

fn do_work() -> Result<(), ModuleError> {
    let conn = connect_db()?; // Auto-converts via #[from]
    validate_input()?;
    Ok(())
}

```text

[Full pattern with examples]

Would you like me to create a new error module following this pattern?
```

**Result**: Consistent error handling across codebase, zero time wasted rediscovering patterns.

---

## Use Case 4: Daily Development Journal

### Problem

Developer wants to track:
- What they worked on each day
- Blockers encountered
- Solutions discovered
- Ideas for future work

### Solution with KOGRAL

**End of each day**:

```bash
kogral add journal "2026-01-17" --content "
## Progress
- Implemented user authentication
- Fixed race condition in cache layer
- Started work on API rate limiting

## Blockers
- SurrealDB migration tool not working with nested objects
- Need to discuss API versioning strategy with team

## Learnings
- tokio::select! is perfect for timeout patterns
- serde_json::Value useful for dynamic JSON handling

## Tomorrow
- Finish rate limiting implementation
- Review PR #234
- Team meeting: discuss API versioning
"
```

**With Claude Code** (even easier):

```text
End of day journal:

Implemented authentication, fixed cache race condition, started rate limiting.
Blocked on SurrealDB migrations and need API versioning discussion.
Learned about tokio::select! for timeouts.
Tomorrow: finish rate limiting, review PR #234, versioning meeting.
```

**Claude** (creates journal entry):

```text
Created journal entry: 2026-01-17

Tags auto-detected: authentication, cache, rate-limiting, surrealdb

Linked to:
  - pattern-timeout-handling (implements)
  - decision-use-surrealdb (relates_to)

Journal entry saved.
```

**Two weeks later** (forgot how you solved that race condition):

```text
How did I fix the cache race condition?
```

**Claude** (semantic search):

```text
From your journal entry on 2026-01-17:

"Fixed race condition in cache layer by using DashMap instead of
RwLock<HashMap>. DashMap provides lock-free concurrent access."

[Link to full journal entry]
```

**Result**: Development history preserved, solutions easy to recall.

---

## Use Case 5: Code Review Preparation

### Problem

Preparing for code review. Need to:
- Document why certain decisions were made
- Link implementation to requirements
- Explain trade-offs to reviewers

### Solution with KOGRAL

**Before creating PR**:

```text
I just implemented the caching layer.
Add a note documenting the implementation and link it to our caching decision.
```

**Claude** (via `kogral/add_note` + `kogral/link`):

```text
Created note: note-caching-layer-implementation

Content:
# Caching Layer Implementation

## Approach
- Redis with 5-minute TTL
- Cache-aside pattern
- Invalidation on mutations

## Trade-offs
- Chose simplicity over advanced features (no LRU eviction)
- 5-minute TTL balances freshness vs cache hit rate
- Cache-aside pattern chosen over write-through (simpler)

## Testing
- Unit tests for cache logic
- Integration tests with real Redis
- Load test: 1000 req/s sustained

Links:
  - Implements: decision-add-redis-caching
  - Follows: pattern-cache-aside
  - Tests: guideline-integration-testing

Note added and linked to decision-add-redis-caching.
```

**In PR description**:

```markdown
## Implementation

Implements caching layer per decision-add-redis-caching.

See note-caching-layer-implementation for detailed rationale.

## Trade-offs

[Copy from note]
```

**Reviewers**:

```text
kogral show decision-add-redis-caching
kogral show note-caching-layer-implementation
```

Full context available, review focuses on code quality not "why this approach?"

---

## Use Case 6: Cross-Project Guidelines

### Problem

Organization has 10 projects. Each should follow:
- Same Rust error handling patterns
- Same security guidelines
- Same testing standards

Currently: duplicated wikis, inconsistent practices.

### Solution with KOGRAL

**Setup shared KOGRAL**:

```bash
# Create organization-wide shared KOGRAL
mkdir -p ~/org/.kogral-shared
cd ~/org/.kogral-shared
kogral init --name "Organization Guidelines"

# Add shared guidelines
kogral add guideline "Rust Error Handling" \
  --language rust \
  --category error-handling \
  --content "$(cat org-rust-errors.md)"

kogral add guideline "Security Best Practices" \
  --category security \
  --content "$(cat org-security.md)"
```

**In each project**:

```nickel
# project/.kogral/config.ncl
{
  inheritance = {
    base = "~/org/.kogral-shared",
    priority = 100,  # Project overrides shared
  },
}
```

**Developer in Project A**:

```text
What are our error handling guidelines?
```

**Claude** (via `kogral/get_guidelines` with inheritance):

```text
## Rust Error Handling Guidelines

### Shared Guidelines (priority: 50)
From ~/org/.kogral-shared:
- Use thiserror for custom errors
- Never unwrap() in production
- Always propagate with ?

### Project Guidelines (priority: 100)
From project .kogral/:
- Additionally: log all errors with tracing
- Use anyhow for application-level errors

[Combined effective guidelines]
```

**Result**:
- Consistent practices across organization
- Projects can specialize where needed
- Single source of truth for shared knowledge

---

## Use Case 7: Bug Investigation

### Problem

Bug in production. Developer needs to:
- Understand relevant decisions
- Find related code patterns
- Check if similar issues were solved before

### Solution with KOGRAL

**Developer**:

```text
We have a race condition in the cache layer.
What past decisions or patterns might be relevant?
```

**Claude** (semantic search):

```text
Found 4 relevant items:

1. **Decision: Use DashMap for Concurrent Access** (accepted, 1 month ago)
   "Chose DashMap over RwLock<HashMap> to avoid race conditions in cache"

2. **Pattern: Safe Concurrent Cache Access**
   "Always use lock-free data structures for high-contention caches"

3. **Note: Cache Race Condition Fix** (from 2026-01-17 journal)
   "Fixed race in cache by switching to DashMap"

4. **Guideline: Concurrency Safety**
   "Use atomic operations and lock-free structures where possible"

It looks like we've seen this before! Check the journal entry from 2026-01-17.
```

**Developer reads journal**:

```bash
kogral show journal-2026-01-17
```

**Finds**:
- Exact same issue
- Solution: switch to DashMap
- Code example included
- Performance benchmarks

**Applies fix** in 10 minutes instead of 2 hours of debugging.

---

## Use Case 8: API Design Collaboration

### Problem

Team discussing new API design. Multiple approaches:
- REST vs GraphQL
- Versioning strategy
- Authentication method

Need to capture discussion and decision.

### Solution with KOGRAL

**During design meeting** (using Claude Code):

```text
We're designing the new API. Let me capture this discussion:

Approaches discussed:
1. REST with versioned endpoints (/v1/, /v2/)
2. GraphQL with schema versioning
3. gRPC for internal services

Team consensus:
- REST for public API (easier for partners)
- GraphQL for internal admin tools (flexibility)
- gRPC for service-to-service (performance)

Create a decision record for each, linking them together.
```

**Claude** (creates 3 linked ADRs):

```text
Created 3 decisions:

1. decision-rest-public-api
   Status: accepted
   Context: Public API needs broad compatibility
   Decision: REST with /v1/, /v2/ versioning

2. decision-graphql-admin
   Status: accepted
   Context: Admin tools need flexible queries
   Decision: GraphQL with schema evolution

3. decision-grpc-internal
   Status: accepted
   Context: Service-to-service needs performance
   Decision: gRPC with protobuf

Linked:
  decision-rest-public-api --[relates_to]--> decision-graphql-admin
  decision-rest-public-api --[relates_to]--> decision-grpc-internal
  decision-graphql-admin --[relates_to]--> decision-grpc-internal

All decisions documented and interconnected.
```

**Two months later**, someone asks "Why REST not GraphQL for public API?":

```bash
kogral show decision-rest-public-api
```

Full context preserved, including relationship to GraphQL decision.

---

## Summary

Knowledge Base excels at:

✅ **Onboarding**: Historical context instantly available
✅ **Decision Making**: ADRs preserve rationale
✅ **Pattern Reuse**: Solutions documented once, used forever
✅ **Daily Tracking**: Development journal with semantic search
✅ **Code Review**: Implementation rationale linked to decisions
✅ **Cross-Project**: Shared guidelines with project overrides
✅ **Bug Investigation**: Past solutions easily discovered
✅ **Collaboration**: Discussions captured and interconnected

**Common Theme**: Knowledge captured during work, queryable when needed, connected to related concepts.

---

## Next Steps

- **Start simple**: [Quick Start Guide](quickstart.md)
- **Integrate AI**: [MCP Quick Guide](../apps/mcp-quickguide.md)
- **Advanced features**: [Configuration Reference](../config/overview.md)
