# ggen - Rust Project Configuration (80/20 Edition)

## 🎯 Core Identity

**ggen**: Language-agnostic, deterministic code generation CLI. Ontologies + RDF → reproducible code projections.

**Tech Stack**: Rust (workspace), SPARC + Chicago TDD + DfLSS
**Philosophy**: Type-first thinking, zero-cost abstractions, memory safety, deterministic outputs

---

## 🚨 CRITICAL: THE VITAL FEW (20% that matters 80%)

### 1. CONCURRENT EXECUTION RULE

**Golden Rule**: "1 MESSAGE = ALL RELATED OPERATIONS"

```javascript
// ✅ CORRECT: Single message with ALL operations
[Single Message]:
  Task("Agent 1", "Full instructions...", "coder")
  Task("Agent 2", "Full instructions...", "tester")
  Task("Agent 3", "Full instructions...", "reviewer")

  TodoWrite { todos: [10+ todos in ONE call] }

  Write "file1.rs"
  Write "file2.rs"
  Write "file3.rs"

  Bash "cmd1 && cmd2 && cmd3"
```

**Why**: 2.8-4.4x speed improvement, prevents coordination failures

---

### 2. CARGO MAKE RULE

**NEVER USE DIRECT CARGO COMMANDS**

```bash
# ❌ WRONG
cargo check
cargo test
cargo clippy

# ✅ CORRECT
cargo make check     # <5s timeout
cargo make test      # All tests with timeouts
cargo make lint      # Clippy with timeouts
```

**Why**: Prevents hanging, enforces SLOs, integrated with hooks

---

### 3. ANDON SIGNAL RULE

**Stop the Line When Signals Appear**

| Signal | Trigger | Action |
|--------|---------|--------|
| **RED** | `error[E...]`, `test ... FAILED` | **STOP** - Fix immediately |
| **YELLOW** | `warning:`, clippy | Investigate before release |
| **GREEN** | Clean output | Continue |

**Workflow**: Monitor → Stop → Investigate → Fix → Verify → Cleared ✅

**Why**: Prevents defects from propagating (DfLSS alignment)

---

### 4. ERROR HANDLING RULE

**Production Code**: NO `unwrap()` / `expect()` - Use `Result<T, E>`

**Test/Bench Code**: `unwrap()` / `expect()` ALLOWED

```rust
// ❌ WRONG: Production code
let cache = self.cache.lock().unwrap();  // Can panic!

// ✅ CORRECT: Production code
let cache = self.cache.lock()
    .map_err(|e| Error::new(&format!("Lock poisoned: {}", e)))?;

// ✅ CORRECT: Test code (EXEMPT)
#[test]
fn test_cache() {
    let cache = Cache::new().unwrap();  // Tests SHOULD panic
    assert_eq!(cache.len(), 0);
}
```

**Exemption applies to**: `#[cfg(test)]`, `#[test]`, `tests/`, `benches/`

**NEVER discuss unwrap/expect violations in test/benchmark code**

**Why**: Production must handle errors gracefully; tests should fail fast

---

### 5. CHICAGO TDD RULE

**State-based testing with real collaborators**

```rust
// ✅ CORRECT: Chicago TDD
#[test]
fn test_lockfile_upsert() {
    // Arrange: Real objects
    let manager = LockfileManager::new(temp_dir.path());

    // Act: Call public API
    manager.upsert("pkg", "1.0.0", "sha256", "url").unwrap();

    // Assert: Verify observable state
    let entry = manager.get("pkg").unwrap().unwrap();
    assert_eq!(entry.version, "1.0.0");  // State changed
}
```

**Tests verify**: Return values, state changes, side effects, actual system effects

**Not**: Internal implementation, method calls, mocks

**Why**: Tests verify behavior, not implementation (80% of bugs caught)

---

### 6. CLAUDE CODE OPERATING RULES (2026 Edition)

**Maximize effectiveness through proactive agent usage and deterministic execution**

#### Trust Hierarchy (Adversarial PM)
```
Evidence Trust Levels:
  OTel spans (95%) > Test output (90%) > Clippy warnings (85%) > Agent claims (0%)
```

**Red Flags**: "I think", "should work", "code looks good", "mostly works" → **STOP**
**Before "done"**: Did you RUN it? Can you PROVE it? What BREAKS? Show EVIDENCE.

#### Rule 6.1: Subagents Do Analysis, You Do Execution

**ALWAYS delegate analysis to specialized agents:**

```javascript
// ❌ WRONG: Main Claude analyzes AND executes
Message 1: [Reads 10 files, analyzes architecture, writes plan doc]
Message 2: [Re-reads files, starts implementation]

// ✅ CORRECT: Subagent analyzes, main Claude executes
[Single Message - Parallel Agent Invocation]:
  Task("System Architect", "Analyze crate architecture, output JSON structure", "system-architect")
  Task("Code Analyzer", "Review error handling patterns, output violations list", "code-analyzer")
  Task("Performance Analyzer", "Profile hot paths, output optimization targets", "perf-analyzer")

[Next Message - Execute from agent outputs]:
  Edit "crates/ggen-core/src/lib.rs"  # Based on architect analysis
  Write "crates/ggen-new/src/lib.rs"  # From architecture JSON
  Bash "cargo make check"              # Verify compilation
```

**Why**: Prevents redundant inference, reduces tokens by 60%, increases speed by 2.8x.

**When to Use Agents** (PROACTIVE - Do NOT wait for user to ask):
- 🔍 **Need to understand codebase?** → Spawn `Explore` agent (NOT manual Read/Grep)
- 📐 **Need architecture design?** → Spawn `system-architect` agent (NOT your analysis)
- 🔬 **Need code review?** → Spawn `code-analyzer` agent (NOT manual inspection)
- ⚡ **Need performance analysis?** → Spawn `performance-benchmarker` agent
- 🏗️ **Need implementation plan?** → Spawn `Plan` agent (NOT your plan.md)
- 🧪 **Need test strategy?** → Spawn `tester` agent (NOT your test outline)

#### Rule 6.2: Load Skills Aggressively

**Skills auto-load by WHEN/WHEN_NOT patterns. Trust them.**

```rust
// ❌ WRONG: Re-explaining ggen constitution every time
"Remember, ggen uses Chicago TDD, cargo make, Result<T,E>..."

// ✅ CORRECT: Constitution skill auto-loads, reference it
"Following constitutional principle III (Chicago TDD)..."
// Skill already loaded via WHEN: ["cargo make", "Chicago TDD"]
```

**If skill doesn't auto-load**: Description is too generic. Fix skill, don't compensate.

#### Rule 6.3: Output Deterministically

**ALL outputs MUST be structured (JSON, YAML, markdown lists). NO PROSE.**

```markdown
# ❌ WRONG: Prose requiring interpretation
"We should probably create a new module for RDF parsing and maybe add some error handling..."

# ✅ CORRECT: Structured, deterministic output
## Tasks
1. [pending] Create crates/ggen-rdf/src/parser.rs
2. [pending] Implement Result<RdfTriple, ParseError>
3. [pending] Add tests/rdf/parser_tests.rs
4. [in_progress] Run cargo make test
```

**Why**: Eliminates ambiguity, enables automation, reduces rework cycles.

#### Rule 6.4: Fail Fast on Ambiguity

**Vague specification? STOP. Ask structured questions using AskUserQuestion tool.**

```rust
// ❌ WRONG: Guessing implementation details
// User: "Add validation"
// You: [Implements email regex without asking which fields]

// ✅ CORRECT: Structured clarification
// User: "Add validation"
// You: [Uses AskUserQuestion]
{
  questions: [
    {
      question: "Which fields require validation?",
      options: ["Email only", "Email + username", "All input fields"]
    },
    {
      question: "What validation library?",
      options: ["validator crate (recommended)", "regex", "custom"]
    }
  ]
}
```

**Why**: Guessing creates rework. Clarification takes 30 seconds, rework takes 30 minutes.

#### Rule 6.5: Batch Operations Aggressively

**Group ALL related operations in ONE message.**

```rust
// ❌ WRONG: Sequential messages
Message 1: Write "src/lib.rs"
Message 2: Write "src/error.rs"
Message 3: Bash "cargo make check"

// ✅ CORRECT: Batched operations
[Single Message]:
  Write "crates/ggen-core/src/lib.rs"
  Write "crates/ggen-core/src/error.rs"
  Write "crates/ggen-core/src/types.rs"
  Bash "cargo make check && cargo make test-unit"
  TodoWrite { todos: [5+ todos in ONE call] }
```

**Why**: 2.8-4.4x speed improvement, atomic transactions, better coordination.

#### Rule 6.6: Context Reuse Over Re-computation

**If analysis exists (skill, agent output, prior message), REUSE it. Do NOT re-analyze.**

```rust
// ❌ WRONG: Re-analyzing every time
Message 50: [Re-reads constitution, re-analyzes architecture, re-plans...]

// ✅ CORRECT: Reference existing analysis
Message 50: "Based on architect agent's JSON (Message 10), implementing..."
// OR: "Following constitutional principle IV (cargo make Protocol)..."
```

**Why**: Re-analysis wastes 500-1000 tokens per cycle. Multiply by 20 messages = 10K-20K wasted.

#### Token Efficiency Targets (Per Major Operation)

| Activity | Target Tokens | Method |
|----------|---------------|--------|
| Skill load | ~100 | Auto-invocation via WHEN patterns |
| Agent analysis | ~500 | Structured JSON/YAML output |
| Main execution | ~1000 | Deterministic Write/Edit/Bash |
| **Total** | **~1600** | One analysis + one execution pass |

**If exceeding 2000 tokens**: You're re-analyzing, re-explaining, or guessing. **STOP**.

#### Claude Self-Awareness (Limitations)

**Understanding your failure modes prevents defects:**

| Failure Mode | Probability | Mitigation |
|--------------|-------------|------------|
| Weak on exact counts | 70% error rate | Use `wc -l`, `grep -c`, test assertions |
| Nested logic >3 levels | 60% error rate | Spawn `code-analyzer` agent |
| "Not sure" statements | 70% uncertainty | STOP, clarify, or delegate |
| Confident tone | Often 60-80% actual | Verify with tests/evidence |
| After 15 messages | Coherence degrades | Summarize or restart |

**Why OTEL/Tests Critical**: You CANNOT validate your own execution. "Completion" ≠ correctness.

#### Pre-Action Checklist (MANDATORY)

Before ANY implementation action, verify:

1. ☑️ **Is there a skill for this?** Load explicitly if not auto-loaded.
2. ☑️ **Need analysis?** Spawn agent. Do NOT analyze yourself.
3. ☑️ **Executing?** Use Write/Edit/Bash directly. No additional planning.
4. ☑️ **Output structured?** Must be JSON/YAML/markdown lists. No prose.
5. ☑️ **Created ambiguity?** If yes, use AskUserQuestion immediately.

**Compliance Check**: If you write >500 tokens of explanation, you violated Rule 6.6 (context reuse).

---

## 📁 File Organization (Never Save to Root)

```
ggen/
├── crates/*/src/   # Source code (per crate)
├── crates/*/tests/ # Integration tests
├── tests/          # Workspace tests
├── docs/           # Documentation
├── scripts/        # Build scripts
├── benches/        # Benchmarks
└── templates/      # Code generation templates
```

**Never**: Save working files, text/mds, tests to root folder

---

## 🦀 Elite Rust Mindset (Type-First Thinking)

### The Questions to Ask:
1. **"What can I express in types?"** (before runtime values)
2. **"Is this abstraction zero-cost?"** (generics yes, trait objects no)
3. **"What are the ownership semantics?"** (explicit is better)
4. **"How can I make misuse impossible?"** (type safety > runtime checks)

### 80/20 Idea Generation:
Always generate 3 ideas:
1. **First**: Solve immediate problem
2. **Second**: Go bigger (80% of problems with 20% effort) **← Sweet spot**
3. **Third**: Maximum value (type-level solutions, compile-time guarantees)

**Quality-First 80/20**: Value = quality + consistency + maintainability (not optional)

---

## 🔧 Essential Commands

**Quick Feedback Loop**:
- `cargo make check` - Compilation (<5s)
- `cargo make test-unit` - Unit tests (<10s)
- `cargo make lint` - Clippy

**Full Validation**:
- `cargo make test` - All tests
- `cargo make pre-commit` - Format + lint + tests
- `cargo make ci` - Full CI pipeline

**Performance**:
- `cargo make slo-check` - Verify SLOs
- `cargo make bench` - Benchmarks

---

## 🚫 Prohibited Patterns (Zero Tolerance)

1. **Direct cargo commands** - ALWAYS use `cargo make`
2. **Unwrap/expect in production** - Use `Result<T, E>`
3. **Ignoring Andon signals** - Stop the line when RED
4. **Skipping timeout checks** - `cargo make timeout-check`
5. **Using --no-verify** - Never bypass git hooks
6. **Meaningless tests** - Must verify observable behavior
7. **Multiple messages** - Batch ALL operations in ONE message
8. **Saving to root** - Use proper subdirectories

---

## 🎯 SLOs (Service Level Objectives)

- First build ≤ 15s
- Incremental ≤ 2s
- RDF processing ≤ 5s for 1k+ triples
- Generation memory ≤ 100MB
- CLI scaffolding ≤ 3s end-to-end
- 100% reproducible outputs

---

## 🚀 Claude Code Task Tool (Primary Agent Execution)

**Claude Code's Task tool spawns ACTUAL agents that do work:**

```javascript
// ✅ CORRECT: Use Task tool for parallel execution
Task("Rust Coder", "Implement RDF parser with Result<T,E>", "coder")
Task("Test Engineer", "Write Chicago TDD tests with AAA pattern", "tester")
Task("Code Reviewer", "Review for type safety and Andon signals", "reviewer")
```

**MCP tools are ONLY for coordination setup:**
- `mcp__claude-flow__swarm_init` - Topology setup
- `mcp__claude-flow__agent_spawn` - Agent type definitions
- `mcp__claude-flow__task_orchestrate` - High-level planning

**KEY**: MCP coordinates strategy, Task tool executes with real agents

---

## 📋 Agent Coordination Protocol

**Every agent MUST run hooks:**

```bash
# 1️⃣ BEFORE Work
npx claude-flow@alpha hooks pre-task --description "[task]"

# 2️⃣ DURING Work
cargo make check          # Monitor Andon signals
cargo make test-unit      # Quick feedback
npx claude-flow@alpha hooks post-edit --file "[file]"

# 3️⃣ AFTER Work
cargo make test           # All tests must pass
npx claude-flow@alpha hooks post-task --task-id "[task]"
```

---

## 🚨 Definition of Done (Mandatory Validation)

**BEFORE marking complete:**

```bash
# 1. Check for compiler errors (RED signal)
cargo make check  # Must be clean

# 2. Check for test failures (RED signal)
cargo make test   # Must be 100% pass

# 3. Check for clippy warnings (YELLOW signal)
cargo make lint   # Must be clean

# 4. Verify SLOs
cargo make slo-check  # Must meet targets
```

**ONLY mark complete when ALL signals cleared**

---

## 🔗 Git Hooks System (80/20 Defect Detection)

**Pre-Commit Hook** (<5s, 62% defect detection):
- Cargo check (RED if errors)
- Format check (YELLOW, auto-fix)

**Pre-Push Hook** (<60s, 100% defect detection):
- Cargo check (RED)
- Clippy lint (RED)
- Format check (YELLOW)
- Unit tests (RED)
- Security audit (YELLOW)

**NEVER use `--no-verify`** - Defeats defect prevention

---

## 🎯 Key Associations (Mental Models)

- **Types = invariants = compile-time guarantees**
- **Zero-cost = generics/macros/const generics**
- **Performance = references/stack/minimize allocations**
- **Ownership = explicit = memory safety**
- **APIs = type-safe = ergonomic = composable**
- **Tests = observable outputs = behavior verification**
- **80/20 = second idea = sweet spot = maximum value**
- **Andon Signals = stop = fix = verify**
- **DfLSS = prevent defects AND waste from start**

---

## 📝 Speckit Workflow (Spec-First Development)

**MANDATORY**: NO implementation without spec. Integrated with GitHub Spec Kit.

### Commands Flow

```bash
/speckit.constitution  # Create/update project principles
/speckit.specify       # Define requirements and user stories
/speckit.clarify       # Optional: Structured requirement refinement
/speckit.plan          # Establish technical architecture
/speckit.tasks         # Generate actionable task breakdown
/speckit.implement     # Execute implementation according to plan
```

### Branch & Evidence

- **Branch naming**: `NNN-feature-name` (e.g., `001-rdf-validation`)
- **Evidence directory**: `.specify/specs/NNN-feature/evidence/`
- **Spec artifacts**: `.specify/specs/NNN-feature/{spec,plan,tasks,data-model}.md`

### Critical Paths

```
.specify/memory/constitution.md → Architectural law (supersedes CLAUDE.md for principles)
.specify/specs/NNN-feature/     → Feature specs, plans, tasks
```

### Workflow Integration

1. **Before feature**: Run `/speckit.specify "Feature description"`
2. **During planning**: Use `/speckit.plan` to establish architecture
3. **Before coding**: Run `/speckit.tasks` to break down work
4. **During implementation**: Follow `/speckit.implement` guidance
5. **Throughout**: Evidence in `.specify/specs/NNN-feature/evidence/`

### Integration with Cargo Make

```bash
# Validate specs exist before implementation
cargo make speckit-check  # Verifies spec files present for current branch

# Run full workflow validation
cargo make speckit-validate  # Checks spec → plan → tasks → evidence chain
```

---

## 📝 Remember

**Claude Flow coordinates, Claude Code creates!**

**Stop the line when Andon signals appear!**

**Always use `cargo make` - NEVER direct cargo!**

**TodoWrite always has 10+ todos in ONE call!**

**Tests verify behavior - code doesn't work if tests don't pass!**

**Spec before code - NO implementation without /speckit.specify!**

---

# important-instruction-reminders
Do what has been asked; nothing more, nothing less.
NEVER create files unless they're absolutely necessary.
ALWAYS prefer editing an existing file to creating a new one.
NEVER proactively create documentation files.
Never save working files, text/mds and tests to the root folder.
TODO LISTS ARE ALWAYS 10 ITEMS OR MORE. THEY ARE ALWAYS FULLY COMPLETED BEFORE PROGRESSING TO THE NEXT TASK.

## Active Technologies
- Rust 1.74+ (edition 2021) - existing ggen toolchain (003-optimize-aci-anthropic)
- Filesystem-based (003-optimize-aci-anthropic)
- Rust 1.75+ (edition 2021) (006-marketplace-fmea-poka-yoke)
- File system (package.toml, OWNERS files, generated files) (006-marketplace-fmea-poka-yoke)
- Rust 1.74+ (edition 2021) - existing ggen toolchain + ggen CLI (v4.0.0), cargo-make, existing workspace crates (007-cli-jtbd-audit)
- Filesystem-based (YAML audit results, markdown reports) in feature evidence directory (007-cli-jtbd-audit)
- Rust 1.75+ (edition 2021), existing ggen v4.0.0 workspace (008-n3-code-gen)
- File system (ggen.toml, .ttl ontologies, generated .rs files, audit.json) (008-n3-code-gen)
- Rust 1.75+ (ggen existing codebase) + LaTeX (pdflatex for output) + Oxigraph (RDF), Tera (templates), existing ggen-core/ggen-domain crates (010-thesis-gen-system)
- File system (TTL ontology files, Tera templates, generated LaTeX output) (010-thesis-gen-system)
- Rust 1.75+ (edition 2021), testcontainers 0.25, testcontainers-modules 0.13, assert_cmd, clnrm (011-e2e-testcontainers)
- File system (golden files, test fixtures), Docker containers, GitHub Actions workflows (011-e2e-testcontainers)
- Rust 1.75+ (ggen v5), LaTeX (pdflatex + biber) + ggen-core, Oxigraph (RDF), Tera (templates), memoir (LaTeX), amsthm, biblatex, algorithm2e (012-grand-unified-kgc-thesis)
- File system (RDF ontology .ttl files, generated .tex files) (012-grand-unified-kgc-thesis)

## Recent Changes
- 003-optimize-aci-anthropic: Added Rust 1.74+ (edition 2021) - existing ggen toolchain
