From e028d60c04329dbcbef43835f8927ef735270fd3 Mon Sep 17 00:00:00 2001 From: Sopaco Date: Fri, 17 Apr 2026 15:48:51 +0800 Subject: [PATCH] Add AI context knowledge base for coding agents --- .ai-context/DYNAMICS.md | 98 +++ .ai-context/SKILL.md | 139 ++++ .ai-context/meta/MAINTENANCE.md | 182 ++++ .ai-context/references/ARCHITECTURE.md | 320 +++++++ .ai-context/references/DECISIONS.md | 197 +++++ .ai-context/references/PROJECT-ESSENCE.md | 107 +++ .skills/ai-context-generator/README.md | 253 ++++++ .skills/ai-context-generator/SKILL.md | 216 +++++ .../references/WRITING-GUIDE.md | 357 ++++++++ .../ai-context-generator/scripts/generate.ts | 785 ++++++++++++++++++ .../templates/architecture.md.tmpl | 110 +++ .../templates/decisions.md.tmpl | 107 +++ .../templates/dynamics.md.tmpl | 71 ++ .../templates/essence.md.tmpl | 92 ++ .../templates/maintenance.md.tmpl | 182 ++++ .../templates/skill.md.tmpl | 139 ++++ AGENTS.MD | 28 + 17 files changed, 3383 insertions(+) create mode 100644 .ai-context/DYNAMICS.md create mode 100644 .ai-context/SKILL.md create mode 100644 .ai-context/meta/MAINTENANCE.md create mode 100644 .ai-context/references/ARCHITECTURE.md create mode 100644 .ai-context/references/DECISIONS.md create mode 100644 .ai-context/references/PROJECT-ESSENCE.md create mode 100644 .skills/ai-context-generator/README.md create mode 100644 .skills/ai-context-generator/SKILL.md create mode 100644 .skills/ai-context-generator/references/WRITING-GUIDE.md create mode 100644 .skills/ai-context-generator/scripts/generate.ts create mode 100644 .skills/ai-context-generator/templates/architecture.md.tmpl create mode 100644 .skills/ai-context-generator/templates/decisions.md.tmpl create mode 100644 .skills/ai-context-generator/templates/dynamics.md.tmpl create mode 100644 .skills/ai-context-generator/templates/essence.md.tmpl create mode 100644 .skills/ai-context-generator/templates/maintenance.md.tmpl create mode 100644 .skills/ai-context-generator/templates/skill.md.tmpl create mode 100644 AGENTS.MD diff --git a/.ai-context/DYNAMICS.md b/.ai-context/DYNAMICS.md new file mode 100644 index 0000000..c54e8d0 --- /dev/null +++ b/.ai-context/DYNAMICS.md @@ -0,0 +1,98 @@ +# Dynamics β€” Active Issues & Constraints + +> **Last updated:** 2026-04-16 +> **Stability:** Dynamic β€” Update as issues arise/resolve + +--- + +## ⚑ Quick Scan + +| Status | Issue | Impact | Workaround | +|--------|-------|--------|------------| +| 🟒 Clean | No active issues | β€” | β€” | + +--- + +## πŸ”΄ Active Issues + +*No active issues at this time.* + + + +--- + +## 🟑 Known Constraints + +### LLM API Rate Limits + +**What:** Cloud LLM providers have rate limits that can slow down large codebase analysis. + +**Impact:** Processing large projects may experience delays or require retries. + +**Mitigation:** +- Use `--cache-dir` to enable response caching +- Consider using Ollama for local processing without rate limits +- Break large projects into smaller analysis runs + +--- + +### Memory Usage for Large Projects + +**What:** Analyzing very large codebases can consume significant memory during the preprocessing phase. + +**Impact:** May cause slowdowns on machines with limited RAM. + +**Mitigation:** +- Use `--exclude` to skip unnecessary directories (node_modules, target, etc.) +- Process specific subdirectories separately + +--- + +## 🟒 Recently Resolved + +| Issue | Resolution | Date | +|-------|------------|------| +| *None recorded yet* | β€” | β€” | + +--- + +## πŸ“‹ Under Consideration + +### Potential: Git History Analysis + +**Topic:** Analyzing git commit history to track architecture evolution. + +**Trigger for change:** If users request features showing how architecture has changed over time. + +--- + +### Potential: Multi-Repository Analysis + +**Topic:** Supporting analysis across multiple related repositories. + +**Trigger for change:** Enterprise users with microservices architectures across many repos. + +--- + +## πŸ”„ Update Log + +| Date | Change | +|------|--------| +| 2026-04-16 | Initial version created during .ai-context setup | + +--- + +*Remember: This file changes frequently. Always check the "Last updated" date. If it's been > 2 weeks, verify against current code state.* \ No newline at end of file diff --git a/.ai-context/SKILL.md b/.ai-context/SKILL.md new file mode 100644 index 0000000..8e12b09 --- /dev/null +++ b/.ai-context/SKILL.md @@ -0,0 +1,139 @@ +--- +name: ai-context +description: | + Project knowledge base for coding agents. Activate when: (1) starting a new session in this project, (2) encountering unfamiliar code patterns or architecture decisions, (3) user asks about project design or rationale, (4) before making significant structural changes. Contains tiered knowledge from stable design principles to dynamic issues. +--- + +# AI Context β€” Litho (deepwiki-rs) + +> This skill provides pre-generated project knowledge to help you understand the project faster and work more effectively. + +--- + +## 🎯 When to Activate This Skill + +**Activate immediately when:** +- Starting a new coding session in this project +- You need to understand "why something is designed this way" +- User asks about project architecture, design decisions, or constraints + +**Refer to specific sections when:** +- Encountering unexpected behavior or errors β†’ `DYNAMICS.md` +- Planning structural changes β†’ `references/DECISIONS.md` +- Need high-level overview β†’ `references/PROJECT-ESSENCE.md` +- Need component relationships β†’ `references/ARCHITECTURE.md` + +**Do NOT activate when:** +- Simple code edits with clear context +- User requests are purely mechanical (rename, format, etc.) +- You already have sufficient context from recent conversation + +--- + +## πŸ“ Knowledge Tiers + +This skill organizes knowledge by **stability** β€” how frequently the knowledge changes: + +| Tier | File | Stability | Update Frequency | +|------|------|-----------|------------------| +| **Tier 0** | `PROJECT-ESSENCE.md` | High | Quarterly / Major version | +| **Tier 1** | `ARCHITECTURE.md` | Medium | Monthly / Sprint | +| **Tier 2** | `DECISIONS.md` | Low | Per decision change | +| **Tier 3** | `DYNAMICS.md` | Dynamic | As needed (issues, incidents) | + +### Reading Order (Recommended) + +``` +1. PROJECT-ESSENCE.md ← Start here (1-2 min read) +2. ARCHITECTURE.md ← If working across components +3. DECISIONS.md ← If changing established patterns +4. DYNAMICS.md ← If something feels wrong +``` + +--- + +## πŸ”§ How to Use This Knowledge + +### 1. Session Start Protocol +``` +β–‘ Read PROJECT-ESSENCE.md (always) +β–‘ Scan DYNAMICS.md for active issues +β–‘ Read ARCHITECTURE.md if working across subprojects +β–‘ Proceed with dynamic code exploration +``` + +### 2. Dynamic Code Exploration +This knowledge is a **starting point**, not a replacement for reading code: +- Use `grep` and `find_path` to locate actual implementations +- Verify knowledge against current code state +- Update knowledge if you find drift (see Maintenance section) + +### 3. Decision Validation +Before changing established patterns: +``` +β–‘ Check DECISIONS.md for existing decisions +β–‘ If decision exists: follow it or explicitly propose change +β–‘ If new decision needed: document after implementation +``` + +--- + +## πŸ”„ When to Update This Knowledge + +### Update PROJECT-ESSENCE.md when: +- Project purpose or scope fundamentally changes +- New major capability is added +- Core user workflow changes + +### Update ARCHITECTURE.md when: +- New component/subproject added +- Component responsibilities shift +- Data flow changes significantly +- API contracts change + +### Update DECISIONS.md when: +- A new design decision is made (especially if non-obvious) +- An existing decision is revisited/changed +- A trade-off is resolved differently + +### Update DYNAMICS.md when: +- New issue discovered that blocks normal workflow +- Workaround found for existing issue +- Issue is resolved +- Temporary constraint is added/removed + +--- + +## ⚠️ Important Principles + +1. **Knowledge is a guide, not truth** β€” Always verify against actual code +2. **Update responsibly** β€” Stale knowledge is worse than no knowledge +3. **Keep it high-level** β€” Details belong in code comments +4. **Trust dynamic exploration** β€” Use tools to find current state + +--- + +## πŸ“š File Reference + +- [Project Essence](references/PROJECT-ESSENCE.md) β€” What this project is and why +- [Architecture](references/ARCHITECTURE.md) β€” How components fit together +- [Decisions](references/DECISIONS.md) β€” Key design decisions and rationale +- [Dynamics](DYNAMICS.md) β€” Active issues, workarounds, temporary constraints +- [Maintenance Guide](meta/MAINTENANCE.md) β€” How to maintain this knowledge base + +--- + +## πŸ”— Integration with AGENTS.md + +This skill complements `AGENTS.md` in the project root: + +| File | Purpose | Who writes | +|------|---------|------------| +| `AGENTS.md` | Operational rules, commands, style | Project maintainers | +| `.ai-context/` | Pre-generated knowledge | System / Auto-generated | + +Both should be read at session start. `AGENTS.md` tells you **how to work**, `.ai-context` tells you **what the project is**. + +--- + +*Generated by ai-context-generator skill* \ No newline at end of file diff --git a/.ai-context/meta/MAINTENANCE.md b/.ai-context/meta/MAINTENANCE.md new file mode 100644 index 0000000..1f48df3 --- /dev/null +++ b/.ai-context/meta/MAINTENANCE.md @@ -0,0 +1,182 @@ +# AI Context Maintenance Guide + +> How to keep this knowledge base accurate and useful. Last updated: 2026-04-16. + +--- + +## 🎯 Purpose of This Guide + +This document tells you (the coding agent) how to maintain the `.ai-context` knowledge base. Following these guidelines ensures knowledge stays accurate without becoming a maintenance burden. + +--- + +## πŸ“‹ Maintenance Triggers + +### Automatic Update Triggers +Update knowledge when you observe: + +| Observation | Action | File to Update | +|-------------|--------|----------------| +| Code contradicts documented behavior | Fix documentation | Relevant reference file | +| New component created | Add entry | `ARCHITECTURE.md` | +| Major design choice made | Document rationale | `DECISIONS.md` | +| Issue blocking work discovered | Add entry | `DYNAMICS.md` | +| Issue resolved | Remove/move entry | `DYNAMICS.md` | +| API contract changed | Update section | `ARCHITECTURE.md` | + +### Explicit Update Requests +When user asks to "update the knowledge base" or "refresh ai-context": +1. Review each file for accuracy +2. Compare documented state against current code +3. Update outdated sections +4. Update the "Last updated" date at file top +5. Summarize changes to user + +--- + +## ✍️ Writing Guidelines + +### For PROJECT-ESSENCE.md +- Keep it under 100 lines +- Focus on "what" and "why", not "how" +- No code snippets, no API details +- Target audience: Someone who knows nothing about the project +- Update frequency: Rare (quarterly or major version) + +### For ARCHITECTURE.md +- Use diagrams over paragraphs (ASCII art or Mermaid) +- Component-level granularity, not file-level +- Show data flow, not implementation details +- Include: Responsibilities, Dependencies, Interfaces +- Omit: Internal algorithms, variable names, code snippets +- Update frequency: Monthly or per sprint + +### For DECISIONS.md +- Format: `## ADR-XXX: [Title]` followed by Context, Decision, Rationale, Trade-offs +- Include decisions that are non-obvious or controversial +- Omit trivial decisions (naming conventions, etc.) +- When revisiting a decision, add a new section noting the change +- Update frequency: As decisions are made/changed + +### For DYNAMICS.md +- Keep entries actionable +- Format: `## πŸ”΄ [Issue Title]` with status emoji +- Include: Impact, Workaround (if any), Resolution plan +- Remove resolved issues promptly (don't accumulate history) +- Update frequency: As needed (most dynamic file) + +--- + +## πŸ”„ Update Workflow + +### When Making Updates + +``` +1. Identify which file needs updating +2. Read the current content +3. Make minimal, focused changes +4. Update "Last updated" date at top +5. Proceed with your task +``` + +### What NOT to Do + +- ❌ Don't rewrite entire files for minor changes +- ❌ Don't add details that belong in code comments +- ❌ Don't duplicate information across files +- ❌ Don't document every file/function β€” stay high-level +- ❌ Don't keep resolved issues in DYNAMICS.md + +--- + +## πŸ“Š Knowledge Audit Checklist + +Periodically (or when requested), perform this audit: + +``` +β–‘ PROJECT-ESSENCE.md: Does it still describe what the project does? +β–‘ ARCHITECTURE.md: Do components still exist and have same responsibilities? +β–‘ DECISIONS.md: Are decisions still valid or have they been superseded? +β–‘ DYNAMICS.md: Are all issues still active? Are any resolved? +β–‘ SKILL.md: Is the activation guidance still accurate? +``` + +--- + +## πŸ› οΈ Automation Opportunities + +### Scripts That Could Help + +These scripts don't exist yet but could be added to `meta/scripts/`: + +| Script | Purpose | +|--------|---------| +| `check-drift.rs` | Compare documented components against actual structure | +| `audit-dynamics.rs` | Check for stale issues (>30 days without update) | +| `list-decisions.rs` | Extract decision titles for quick reference | + +### When to Create Scripts + +If you find yourself repeating a maintenance task: +1. Consider if a script would help +2. If yes, create it in the project's scripts or tools directory +3. Document it in this file +4. Run it when appropriate + +--- + +## πŸ“ Quality Standards + +### Knowledge Quality Checklist + +Before considering knowledge "good": + +- [ ] Can someone new understand PROJECT-ESSENCE.md in 2 minutes? +- [ ] Does ARCHITECTURE.md show the big picture without implementation details? +- [ ] Are decisions in DECISIONS.md justified with rationale? +- [ ] Does DYNAMICS.md only contain actionable, current issues? +- [ ] Is every file dated with last update? + +### Anti-Patterns to Avoid + +| Anti-Pattern | Why It's Bad | Fix | +|--------------|--------------|-----| +| Copy-pasting code | Becomes stale immediately | Link to source files instead | +| Documenting every file | Overwhelms and distracts | Focus on components/patterns | +| Never updating | Knowledge becomes liability | Follow triggers above | +| Over-documenting decisions | Dilutes important ones | Only non-obvious decisions | +| Keeping resolved issues | Hides actual problems | Remove when resolved | + +--- + +## πŸ”— Integration Points + +### With AGENTS.md + +``` +AGENTS.md says: "How to work" (commands, style, rules) +.ai-context says: "What the project is" (architecture, decisions, issues) +``` + +Both should be read at session start. They serve different purposes and should not duplicate content. + +### With Dynamic Code Exploration + +``` +.ai-context provides: Starting mental model +Code exploration provides: Current ground truth +``` + +Always verify knowledge against code. When they diverge, code is truth β€” update the knowledge. + +--- + +## πŸ“ Changelog + +| Date | Change | +|------|--------| +| 2026-04-16 | Initial maintenance guide created during .ai-context setup | + +--- + +_This guide is itself maintained using these principles. Update it when you discover better maintenance patterns._ \ No newline at end of file diff --git a/.ai-context/references/ARCHITECTURE.md b/.ai-context/references/ARCHITECTURE.md new file mode 100644 index 0000000..bfa1552 --- /dev/null +++ b/.ai-context/references/ARCHITECTURE.md @@ -0,0 +1,320 @@ +# Architecture β€” Litho (deepwiki-rs) + +> How components fit together. Last updated: 2026-04-16. +> +> **Update this when:** New component added, responsibilities shift, data flow changes. + +--- + +## System Overview + +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Litho CLI Entry Point β”‚ +β”‚ (src/main.rs) β”‚ +β”‚ β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ CLI.rs │───▢│ Config.rs │───▢│ i18n.rs β”‚ β”‚ +β”‚ β”‚ (clap) β”‚ β”‚ (TOML parsing) β”‚ β”‚ (8 languages) β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β”‚ β”‚ β”‚ +β”‚ β–Ό β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ Generator Workflow β”‚ β”‚ +β”‚ β”‚ (src/generator/workflow.rs) β”‚ β”‚ +β”‚ β”‚ β”‚ β”‚ +β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ +β”‚ β”‚ β”‚ Preprocess │──▢│ Research │──▢│ Compose │──▢│ Outlet β”‚ β”‚ β”‚ +β”‚ β”‚ β”‚ Stage β”‚ β”‚ Stage β”‚ β”‚ Stage β”‚ β”‚ Stage β”‚ β”‚ β”‚ +β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ +β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ +β”‚ β”‚ β–Ό β–Ό β–Ό β–Ό β”‚ β”‚ +β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ +β”‚ β”‚ β”‚ Memory & Cache Layer β”‚ β”‚ β”‚ +β”‚ β”‚ β”‚ (src/memory + src/cache) β”‚ β”‚ β”‚ +β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”‚ + β–Ό β–Ό + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”‚ LLM Integration β”‚ β”‚ Knowledge Sync β”‚ + β”‚ (src/llm/) β”‚ β”‚ (src/integrations/) β”‚ + β”‚ β”‚ β”‚ β”‚ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β€’ local_docs.rs β”‚ + β”‚ β”‚ Cloud Client β”‚ β”‚ β”‚ β€’ knowledge_sync.rs β”‚ + β”‚ β”‚ (OpenAI/Claude)β”‚ β”‚ β”‚ β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ + β”‚ β”‚ Ollama Client β”‚ β”‚ + β”‚ β”‚ (Local) β”‚ β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +--- + +## Four-Stage Processing Pipeline + +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Phase 1: Preprocessing β”‚ +β”‚ (src/generator/preprocess/) β”‚ +β”‚ β”‚ +β”‚ Input: Source Code Files β”‚ +β”‚ β”‚ β”‚ +β”‚ β–Ό β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ Structure │──▢│ Original │──▢│ Code β”‚ β”‚ +β”‚ β”‚ Extractor β”‚ β”‚ Document β”‚ β”‚ Analysis β”‚ β”‚ +β”‚ β”‚ β”‚ β”‚ Extractor β”‚ β”‚ Agent β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β”‚ β”‚ β”‚ β”‚ β”‚ +β”‚ β–Ό β–Ό β–Ό β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ CodeInsight Objects β”‚ β”‚ +β”‚ β”‚ (file structures, dependencies, annotations) β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + β–Ό +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Phase 2: Research β”‚ +β”‚ (src/generator/research/) β”‚ +β”‚ β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ Research Orchestrator β”‚ β”‚ +β”‚ β”‚ (step_forward_agent.rs + agent_executor.rs) β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β”‚ β”‚ β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β–Ό β–Ό β–Ό β–Ό β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ System β”‚ β”‚ Domain β”‚ β”‚ Workflow β”‚ β”‚ Boundary β”‚ β”‚ +β”‚ β”‚ Context β”‚ β”‚ Module β”‚ β”‚ Researcher β”‚ β”‚ Analyzer β”‚ β”‚ +β”‚ β”‚ Researcher β”‚ β”‚ Detector β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β”‚ β”‚ β”‚ +β”‚ β–Ό β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ Key Module β”‚ β”‚ +β”‚ β”‚ Insight Officer β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β”‚ β”‚ β”‚ +β”‚ β–Ό β”‚ +β”‚ Structured Research Reports (JSON) β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + β–Ό +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Phase 3: Composition β”‚ +β”‚ (src/generator/compose/) β”‚ +β”‚ β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ Overview β”‚ β”‚ Architecture β”‚ β”‚ Workflow β”‚ β”‚ +β”‚ β”‚ Editor β”‚ β”‚ Editor β”‚ β”‚ Editor β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β”‚ β”‚ β”‚ β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β”‚ β–Ό β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ Mermaid Diagram β”‚ β”‚ +β”‚ β”‚ Synthesis β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β”‚ β”‚ β”‚ +β”‚ β–Ό β”‚ +β”‚ Markdown Documents + Mermaid Diagrams β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + β–Ό +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Phase 4: Output β”‚ +β”‚ (src/generator/outlet/) β”‚ +β”‚ β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ Mermaid │──▢│ Document │──▢│ File β”‚ β”‚ +β”‚ β”‚ Fixer β”‚ β”‚ Integrity β”‚ β”‚ Persistence β”‚ β”‚ +β”‚ β”‚ β”‚ β”‚ Check β”‚ β”‚ β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β”‚ β”‚ β”‚ +β”‚ β–Ό β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ Output Directory β”‚ β”‚ +β”‚ β”‚ (docs/ structure) β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +--- + +## Component Responsibilities + +### CLI Layer (`src/cli.rs`) +- **Entry:** `src/cli.rs` +- **Purpose:** Command-line argument parsing and routing +- **Key behaviors:** + - Parses 20+ CLI options using clap + - Routes to appropriate workflow based on subcommand + - Handles help, version, and error output + +### Configuration (`src/config.rs`) +- **Entry:** `src/config.rs` +- **Purpose:** Load and merge configuration from multiple sources +- **Key behaviors:** + - Reads `litho.toml` configuration file + - Supports environment variable overrides + - Validates LLM provider settings + +### Generator Core (`src/generator/`) +- **Entry:** `src/generator/workflow.rs` +- **Purpose:** Orchestrates the four-stage documentation pipeline +- **Key behaviors:** + - Manages pipeline state transitions + - Coordinates between stages + - Handles error recovery and retries + +### Preprocess Stage (`src/generator/preprocess/`) +- **Purpose:** Extract code structure and insights from source files +- **Key behaviors:** + - Multi-language parsing (12+ languages) + - Dependency extraction + - Code insight generation via LLM + - Initializes agent memory chunks + +### Research Stage (`src/generator/research/`) +- **Purpose:** AI-powered architecture analysis +- **Key behaviors:** + - 8 specialized research agents + - ReAct reasoning loop + - Reads/writes to agent memory + - Produces structured JSON reports + +### Compose Stage (`src/generator/compose/`) +- **Purpose:** Generate documentation from research data +- **Key behaviors:** + - Template-based markdown generation + - Mermaid diagram synthesis + - i18n localization + +### Outlet Stage (`src/generator/outlet/`) +- **Purpose:** Finalize and persist documentation +- **Key behaviors:** + - Mermaid syntax validation and repair + - Document integrity checking + - File system persistence + +### LLM Integration (`src/llm/`) +- **Entry:** `src/llm/mod.rs` +- **Purpose:** Abstract LLM provider communication +- **Key behaviors:** + - Cloud API clients (OpenAI, Claude) + - Local Ollama client + - Token management and retry logic + - Tool execution framework + +### Cache System (`src/cache/`) +- **Entry:** `src/cache/mod.rs` +- **Purpose:** Reduce API costs through response caching +- **Key behaviors:** + - MD5-keyed file-based cache + - TTL expiration + - Performance monitoring + - Cache hit/miss statistics + +### Knowledge Integration (`src/integrations/`) +- **Entry:** `src/integrations/knowledge_sync.rs` +- **Purpose:** Incorporate external documentation into analysis +- **Key behaviors:** + - PDF, Markdown, SQL file ingestion + - Semantic chunking + - Knowledge base synchronization + - RAG-style retrieval + +--- + +## Data Flow + +### Main Generation Flow +``` +CLI Command + β†’ Load Configuration (litho.toml) + β†’ Initialize GeneratorContext + β†’ Phase 1: Preprocess (scan codebase) + β†’ Phase 2: Research (AI agents analyze) + β†’ Phase 3: Compose (generate markdown) + β†’ Phase 4: Output (validate & persist) + β†’ Return output path +``` + +### LLM Request Flow +``` +Agent needs analysis + β†’ Check cache (MD5 lookup) + β†’ If miss: Send to LLM provider + β†’ Parse structured JSON response + β†’ Cache response for future + β†’ Return to agent +``` + +### Knowledge Sync Flow +``` +CLI: litho sync-knowledge + β†’ Scan configured paths + β†’ Detect changed files (mtime) + β†’ Chunk documents (semantic) + β†’ Index in memory store + β†’ Available for RAG retrieval +``` + +--- + +## Key Design Patterns + +### 1. Step-Forward Agent Pattern +- **Where:** `src/generator/step_forward_agent.rs` +- **Why:** Enables staged, dependency-aware analysis +- **How it works:** Each agent declares data sources and output schema; orchestrator runs agents in dependency order + +### 2. Pipeline Architecture +- **Where:** `src/generator/workflow.rs` +- **Why:** Clear separation of concerns; testable stages +- **How it works:** Four distinct phases with well-defined inputs/outputs; each phase can fail independently + +### 3. Repository Pattern +- **Where:** `src/cache/mod.rs`, `src/integrations/local_docs.rs` +- **Why:** Abstract storage implementation; testable without real filesystem +- **How it works:** Traits define storage interface; implementations handle specifics + +--- + +## Dependencies + +| Package | Purpose | Version Constraint | +|---------|---------|-------------------| +| rig-core | LLM abstraction | 0.34 | +| tokio | Async runtime | 1.47 | +| clap | CLI parsing | 4.5 | +| serde | Serialization | 1.0 | +| anyhow | Error handling | 1.0 | +| reqwest | HTTP client | 0.12 | +| walkdir | File traversal | 2.5 | + +--- + +## Configuration Layers + +``` +CLI Arguments (highest priority) + ↓ +Environment Variables (LITHO_*) + ↓ +litho.toml (project config) + ↓ +Default values (lowest priority) +``` + +--- + +*This file describes component relationships. For detailed implementation, explore the source code or use `grep`.* \ No newline at end of file diff --git a/.ai-context/references/DECISIONS.md b/.ai-context/references/DECISIONS.md new file mode 100644 index 0000000..47104c1 --- /dev/null +++ b/.ai-context/references/DECISIONS.md @@ -0,0 +1,197 @@ +# Design Decisions β€” Litho (deepwiki-rs) + +> Key architectural and design decisions that shape this project. Update when decisions are made or revisited. +> +> Last reviewed: 2026-04-16 + +--- + +## Decision Index + +| ID | Decision | Status | Date | +|----|----------|--------|------| +| ADR-001 | Multi-Agent AI Pipeline Architecture | Active | 2024-01 | +| ADR-002 | Read-Only Analysis Constraint | Active | 2024-01 | +| ADR-003 | Dual LLM Provider Support | Active | 2024-01 | +| ADR-004 | Language-Agnostic Preprocessing | Active | 2024-02 | +| ADR-005 | File-Based Response Caching | Active | 2024-02 | +| ADR-006 | Four-Stage Processing Pipeline | Active | 2024-01 | + +--- + +## ADR-001: Multi-Agent AI Pipeline Architecture + +**Context**: How should we structure AI analysis to produce comprehensive C4 documentation? A single LLM call cannot effectively analyze complex codebases while maintaining consistency across abstraction levels. + +**Decision**: Implement 8 specialized research agents that operate at different C4 abstraction levels, with staged dependency ordering. + +**Rationale**: +- Single-agent approaches produce inconsistent results across abstraction levels +- Specialized agents can focus on specific aspects (system context, domain modules, workflows, boundaries) +- Staged dependency pattern ensures high-level context (C1) guides detailed analysis (C3-C4) +- Reduces hallucination through structured, focused analysis + +**Trade-offs**: +- (+) Higher quality, more consistent documentation +- (+) Parallelizable execution for performance +- (+) Easier to debug and improve individual agents +- (-) More complex orchestration logic +- (-) Higher token usage from multiple LLM calls + +**Implications**: Changes to agent interfaces require careful coordination. Adding new agents must respect dependency ordering. + +**Revisit if**: Single-agent models become capable enough to handle all C4 levels accurately. + +--- + +## ADR-002: Read-Only Analysis Constraint + +**Context**: Documentation tools often create fear of unintended modifications to production codebases. How can we ensure users trust the tool? + +**Decision**: Enforce strict read-only filesystem access to target projects. Never modify, create, or delete source code files. + +**Rationale**: +- Production safety is paramount for adoption +- Enables "run anywhere" deployment model without risk +- Simplifies security reviews and compliance +- User trust is essential for CI/CD integration + +**Trade-offs**: +- (+) Complete safety guarantee for production codebases +- (+) Simplifies security and compliance discussions +- (-) Cannot implement auto-fix suggestions +- (-) Cannot write inline documentation back to source + +**Implications**: All output is generated documentation only. Any future "fix" features must use separate tooling. + +**Revisit if**: Users strongly request automated refactoring capabilities (would require explicit opt-in mode). + +--- + +## ADR-003: Dual LLM Provider Support + +**Context**: Different users have different constraints on data handling. Some require cloud APIs for power, others need local inference for privacy. + +**Decision**: Abstract LLM integration through a unified interface supporting both cloud APIs (OpenAI, Claude) and local inference (Ollama). + +**Rationale**: +- Enterprise users often have data sovereignty requirements +- Air-gapped environments need fully local solutions +- Cloud APIs provide best quality; Ollama provides best privacy +- Unified interface enables seamless switching + +**Trade-offs**: +- (+) Broadest possible user coverage +- (+) Enables cost optimization (local for drafts, cloud for final) +- (-) Added abstraction complexity +- (-) Ollama feature parity requires maintenance + +**Implications**: New features must consider both provider types. Testing requires both environments. + +**Revisit if**: A single provider becomes clearly dominant or a new provider emerges as essential. + +--- + +## ADR-004: Language-Agnostic Preprocessing + +**Context**: Supporting 12+ programming languages with unique syntax rules. How to avoid duplicating core analysis logic? + +**Decision**: Feature-based language processor architecture where language-specific modules plug into a shared core pipeline. + +**Rationale**: +- Core AI pipeline is language-agnostic +- Only parsing layer differs between languages +- Maximizes code reuse and maintainability +- Easy to add new language support + +**Trade-offs**: +- (+) Shared logic reduces maintenance burden +- (+) New languages require minimal code +- (-) Some language-specific optimizations are sacrificed +- (-) Abstract syntax handling can miss language-specific patterns + +**Implications**: Adding languages requires implementing the `LanguageProcessor` trait. Language-specific heuristics belong in processors, not core. + +**Revisit if**: Performance analysis shows per-language optimization critical. + +--- + +## ADR-005: File-Based Response Caching + +**Context**: LLM API calls are expensive and rate-limited. How can we reduce costs for iterative documentation generation? + +**Decision**: Implement persistent MD5-keyed file cache for LLM responses with TTL expiration. + +**Rationale**: +- Iterative runs often repeat identical analysis +- Same code + same prompt = same response (deterministic) +- Enables offline replay of previous analyses +- Provides audit trail of AI reasoning + +**Trade-offs**: +- (+) Significant cost reduction (90%+ hit rate on re-runs) +- (+) Faster iteration during development +- (+) Enables offline analysis replay +- (-) Cache invalidation complexity +- (-) Disk space usage over time + +**Implications**: Cache directory must be managed. Prompt changes may require cache clearing. + +**Revisit if**: LLM APIs become significantly cheaper or non-deterministic. + +--- + +## ADR-006: Four-Stage Processing Pipeline + +**Context**: Documentation generation involves distinct concerns: code analysis, AI reasoning, content creation, and output validation. + +**Decision**: Organize processing into four explicit stages: Preprocess β†’ Research β†’ Compose β†’ Output. + +**Rationale**: +- Clear separation of concerns +- Each stage has well-defined inputs and outputs +- Failures can be isolated to specific stages +- Enables parallel processing where stages permit + +**Trade-offs**: +- (+) Testable individual stages +- (+) Clear error boundaries +- (+) Observable progress reporting +- (-) Latency from sequential stages +- (-) Some coupling between stages + +**Implications**: Adding new processing steps requires fitting into existing stage boundaries or creating new stage. + +**Revisit if**: Performance profiling suggests merging stages for speed. + +--- + +## Guidance for Filling This Template + +### What warrants a decision record? + +- Choices between multiple viable alternatives +- Decisions that affect multiple components +- Non-obvious trade-offs +- Decisions that might be questioned later +- Architectural constraints + +### What does NOT need a record? + +- Trivial naming conventions +- Standard patterns in the tech stack +- Decisions with only one reasonable option +- Temporary choices with clear expiration + +### Status Values + +| Status | Meaning | +|--------|---------| +| Active | Currently in effect | +| Superseded | Replaced by ADR-XXX | +| Deprecated | No longer recommended | +| Under Review | Being reconsidered | + +--- + +_This file captures decisions that aren't obvious from code. For implementation details, see ARCHITECTURE.md._ \ No newline at end of file diff --git a/.ai-context/references/PROJECT-ESSENCE.md b/.ai-context/references/PROJECT-ESSENCE.md new file mode 100644 index 0000000..cdc9643 --- /dev/null +++ b/.ai-context/references/PROJECT-ESSENCE.md @@ -0,0 +1,107 @@ +# Project Essence β€” Litho (deepwiki-rs) + +> **Stability: HIGH** | Update: Quarterly or major version changes +> +> Last reviewed: 2026-04-16 + +--- + +## What Is This Project? + +Litho is an AI-powered documentation generation engine that automatically analyzes source code and generates comprehensive C4 architecture documentation. It transforms raw codebases into professional documentation with context diagrams, container diagrams, component diagrams, and code-level documentation. + +--- + +## Why Does It Exist? + +**Problem:** Technical documentation is chronically outdated, incomplete, or missing. Manual documentation requires significant effort and quickly falls behind code changes, leading to: +- New developers spending weeks understanding codebases +- Architecture decisions being lost or forgotten +- Compliance and audit failures due to missing documentation + +**Solution:** Automated documentation that stays in sync with code +- Eliminates manual documentation maintenance overhead +- Captures institutional knowledge before it's lost +- Reduces onboarding time from weeks to days +- Provides consistent C4 model structure across projects + +--- + +## Who Is This For? + +| User | Use Case | +|------|----------| +| Software Developers | Onboard to unfamiliar codebases, understand dependencies and architecture patterns | +| Solution Architects | Validate implementations against blueprints, detect architecture drift, generate C4 diagrams for reviews | +| Technical Writers | Auto-generate documentation drafts, create user guides from code analysis | +| Engineering Managers | Assess technical debt, communicate system scope to stakeholders | + +--- + +## Core Value Proposition + +``` +Before Litho: + Manual documentation that's outdated, inconsistent, and time-consuming to maintain + New developers spend weeks reading code to understand architecture + Architecture decisions are lost when team members leave + +After Litho: + Auto-generated C4 documentation that reflects actual codebase state + Onboarding time reduced from weeks to days + Architecture decisions captured and preserved automatically +``` + +--- + +## What Does It Provide? + +### Key Components + +| Component | Purpose | Value | +|-----------|---------|-------| +| Multi-language Analyzer | Parses 12+ programming languages | Works across heterogeneous tech stacks | +| AI Research Pipeline | 8 specialized agents analyze code | Produces comprehensive, contextual documentation | +| C4 Model Generator | Creates Context, Container, Component, Code diagrams | Professional architecture visualization | +| Knowledge Integration | Mounts external docs (PDF, Markdown, SQL) | Enriches analysis with business context | +| Database Documenter | Generates ERD diagrams from SQL | Complete system documentation | + +### Key Features + +1. **Multi-Language Support** β€” Rust, Python, Java, Go, C#, JavaScript/TypeScript, PHP, Swift, Kotlin, C++, and modern frontend frameworks +2. **Dual LLM Support** β€” Cloud APIs (OpenAI, Claude) and local inference (Ollama) for privacy-sensitive environments +3. **External Knowledge Integration** β€” RAG-style document chunking for incorporating existing ADRs, domain docs, and reference materials +4. **Intelligent Caching** β€” MD5-based response caching reduces API costs and enables offline replay +5. **8-Language i18n** β€” Generates documentation in English, Chinese, Japanese, Korean, Spanish, French, German, Portuguese + +--- + +## Key Constraints + +1. **Read-Only Analysis** β€” System never modifies source code; strict safety guarantee for production codebases +2. **LLM Dependency** β€” Core analysis requires LLM API connectivity or local Ollama server +3. **Command-Line Interface** β€” No GUI; designed for CI/CD pipeline integration +4. **Static Analysis Only** β€” Does not execute or interact with runtime systems + +--- + +## Success Metrics + +| Metric | Target | +|--------|--------| +| Documentation coverage | All significant components documented | +| Onboarding time | < 1 day for new developers | +| Documentation freshness | Auto-updated on every generation | +| Cost efficiency | 90%+ cache hit rate for re-runs | + +--- + +## Evolution Direction + +- **Short-term:** Enhanced Mermaid diagram syntax, improved error messages +- **Mid-term:** Git history analysis for architecture evolution tracking +- **Long-term:** IDE plugins, real-time documentation sync, multi-repository analysis + +--- + +*This file captures the stable essence of the project. For architecture details, see [ARCHITECTURE.md](ARCHITECTURE.md).* \ No newline at end of file diff --git a/.skills/ai-context-generator/README.md b/.skills/ai-context-generator/README.md new file mode 100644 index 0000000..3a6dacd --- /dev/null +++ b/.skills/ai-context-generator/README.md @@ -0,0 +1,253 @@ +# AI Context Generator + +> A reusable Agent Skill for creating project knowledge bases optimized for coding agents. + +--- + +## What Is This? + +This skill helps you generate a `.ai-context/` directory structure that provides coding agents (like Claude Code, Cursor, etc.) with pre-generated project knowledge. The knowledge is organized by stability tiers, making it easy for agents to understand: + +- **What** the project is (PROJECT-ESSENCE.md) +- **How** components fit together (ARCHITECTURE.md) +- **Why** design decisions were made (DECISIONS.md) +- **What issues** are currently active (DYNAMICS.md) + +--- + +## Why Use This? + +**Problem:** Coding agents spend valuable tokens and time exploring code to understand project context. This exploration is repeated in every session. + +**Solution:** Pre-generated knowledge that: +- Reduces onboarding time from ~10 minutes to ~30 seconds +- Preserves institutional knowledge (decisions, constraints) +- Uses ~4000 tokens vs ~50,000+ for full code exploration +- Guides agents to relevant code locations faster + +--- + +## Quick Start + +### Option 1: Use with an AI Agent + +Simply tell your coding agent: + +``` +Use the ai-context-generator skill to setup .ai-context for this project +``` + +The agent will: +1. Read project files (AGENTS.md, README.md, package.json, etc.) +2. Generate the `.ai-context/` structure +3. Ask clarifying questions if needed +4. Create all necessary files + +### Option 2: Manual Generation + +1. Copy the `templates/` directory contents +2. Replace `{{PLACEHOLDERS}}` with your project details +3. Create the `.ai-context/` directory structure + +Or tell the agent: 'Use the ai-context-generator skill to setup .ai-context for my project' +--- + +## Generated Structure + +``` +.ai-context/ +β”œβ”€β”€ SKILL.md # Entry point with activation rules +β”œβ”€β”€ DYNAMICS.md # Active issues & constraints +β”œβ”€β”€ references/ +β”‚ β”œβ”€β”€ PROJECT-ESSENCE.md # What & why (stable) +β”‚ β”œβ”€β”€ ARCHITECTURE.md # Component relationships +β”‚ └── DECISIONS.md # Design decisions & rationale +└── meta/ + β”œβ”€β”€ MAINTENANCE.md # How to maintain this knowledge + β”œβ”€β”€ templates/ # (Optional) Custom templates + └── scripts/ # (Optional) Maintenance scripts +``` + +--- + +## Stability Tiers + +| Tier | File | Stability | Tokens | Update Frequency | +|------|------|-----------|--------|------------------| +| 0 | PROJECT-ESSENCE.md | High | ~500 | Quarterly | +| 1 | ARCHITECTURE.md | Medium | ~1000 | Monthly | +| 2 | DECISIONS.md | Low | ~800 | Per decision | +| 3 | DYNAMICS.md | Dynamic | ~600 | As needed | + +Total budget: ~4000 tokens (within typical context limits) + +--- + +## Files Overview + +### SKILL.md +The entry point that tells agents: +- When to activate this knowledge +- Which file to read for specific needs +- How to keep knowledge updated + +### references/PROJECT-ESSENCE.md +One-page summary answering: +- What is this project? +- Why does it exist? +- Who is it for? +- What does it provide? + +### references/ARCHITECTURE.md +Component-level overview with: +- System diagram (ASCII or Mermaid) +- Component responsibilities +- Data flow descriptions +- Key dependencies + +### references/DECISIONS.md +Architecture Decision Records (ADRs) format: +- Context (the problem) +- Decision (the choice) +- Rationale (why) +- Trade-offs +- Implications + +### DYNAMICS.md +Living document tracking: +- Active issues (blockers) +- Known constraints +- Workarounds +- Recently resolved issues + +### meta/MAINTENANCE.md +Guide for keeping knowledge accurate: +- What triggers updates +- How to make updates +- Quality standards +- Anti-patterns to avoid + +--- + +## Integration with AGENTS.md + +This skill complements (not replaces) `AGENTS.md`: + +| File | Purpose | Author | +|------|---------|--------| +| `AGENTS.md` | How to work (commands, style, rules) | Project maintainers | +| `.ai-context/` | What the project is (architecture, decisions) | Generated | + +**Both should be read at session start for optimal agent performance.** + +--- + +## Customization + +### Custom Templates + +Copy templates to your project and modify: + +``` +your-project/ +β”œβ”€β”€ .ai-context/ +β”‚ └── meta/ +β”‚ └── templates/ # Override defaults here +``` + +The skill will use local templates if they exist. + +### Custom Scripts + +Add automation scripts to `meta/scripts/`: + +| Script | Purpose | +|--------|---------| +| `check-drift.ts` | Detect documentation drift from code | +| `audit-dynamics.ts` | Flag stale issues | +| `generate-from-code.ts` | Auto-generate from code analysis | + +--- + +## Best Practices + +### Do: +- βœ… Generate once, maintain regularly +- βœ… Keep each file under 150 lines +- βœ… Use diagrams over paragraphs +- βœ… Update "Last updated" dates +- βœ… Remove resolved issues from DYNAMICS.md + +### Don't: +- ❌ Copy-paste code snippets (link to files instead) +- ❌ Document every file/function +- ❌ Include details that change frequently +- ❌ Let knowledge go stale + +--- + +## Example Usage + +### Scenario 1: New Project Setup + +``` +User: Setup ai-context for my new Express.js API project + +Agent: +1. Reads package.json, identifies Express.js + TypeScript +2. Scans src/ directory structure +3. Generates PROJECT-ESSENCE.md describing the API +4. Creates ARCHITECTURE.md with component diagram +5. Initializes empty DECISIONS.md and DYNAMICS.md +6. Asks about any non-obvious design choices +``` + +### Scenario 2: Existing Project + +``` +User: My project has 50k lines of code, help agents understand it faster + +Agent: +1. Reads AGENTS.md, README.md, existing docs/ +2. Analyzes directory structure for components +3. Extracts key architecture patterns +4. Generates concise knowledge base +5. Highlights areas needing clarification +``` + +--- + +## Compatibility + +- **Agent Skills Spec**: Fully compliant with [agentskills.io](https://agentskills.io/specification) +- **Claude Code**: Works with Claude Code's skill system +- **Cursor**: Compatible with Cursor's context system +- **Other Agents**: Portable to any agent supporting Agent Skills + +--- + +## Contributing + +To improve this skill: + +1. Fork and modify templates +2. Test with your projects +3. Submit improvements via PR + +--- + +## License + +MIT License β€” Use freely in any project. + +--- + +## References + +- [Agent Skills Specification](https://agentskills.io/specification) +- [Architecture Decision Records](https://adr.github.io/) +- [Project README Template](https://github.com/LinusBorg/project-readme-template) + +--- + +*Generate better project knowledge. Help agents work smarter.* diff --git a/.skills/ai-context-generator/SKILL.md b/.skills/ai-context-generator/SKILL.md new file mode 100644 index 0000000..32f2f70 --- /dev/null +++ b/.skills/ai-context-generator/SKILL.md @@ -0,0 +1,216 @@ +--- +name: ai-context-generator +description: | + Generates .ai-context knowledge base for coding agents. Activate when: (1) setting up a new project for AI-assisted development, (2) user asks to "create project knowledge" or "setup ai-context", (3) existing .ai-context needs regeneration. Creates tiered documentation structure optimized for agent comprehension and token efficiency. +--- + +# AI Context Generator + +> A reusable skill for creating project knowledge bases that help coding agents work faster and smarter. + +--- + +## 🎯 When to Use This Skill + +**Activate when:** +- Setting up a new project for AI-assisted development +- User requests: "create ai-context", "setup project knowledge", "generate .ai-context" +- Existing `.ai-context` is outdated and needs regeneration +- After major project restructuring + +**Do NOT activate when:** +- Project already has fresh `.ai-context` (check `SKILL.md` date) +- User asks for unrelated documentation +- Simple code tasks with clear existing context + +--- + +## πŸ“‹ What This Skill Generates + +Creates a `.ai-context/` directory with: + +``` +.ai-context/ +β”œβ”€β”€ SKILL.md # Entry point with activation rules +β”œβ”€β”€ DYNAMICS.md # Active issues & constraints (Dynamic) +β”œβ”€β”€ references/ +β”‚ β”œβ”€β”€ PROJECT-ESSENCE.md # What & why (High stability) +β”‚ β”œβ”€β”€ ARCHITECTURE.md # Component relationships (Medium stability) +β”‚ └── DECISIONS.md # Design decisions (Update on change) +└── meta/ + β”œβ”€β”€ MAINTENANCE.md # How to maintain this knowledge + β”œβ”€β”€ templates/ # (Optional) Custom templates + └── scripts/ # (Optional) Maintenance scripts +``` + +### Stability Tiers + +| Tier | File | Update Frequency | Token Budget | +|------|------|-------------------|--------------| +| 0 | PROJECT-ESSENCE.md | Quarterly / Major version | ~500 tokens | +| 1 | ARCHITECTURE.md | Monthly / Sprint | ~1000 tokens | +| 2 | DECISIONS.md | Per decision change | ~800 tokens | +| 3 | DYNAMICS.md | As needed (issues) | ~600 tokens | + +--- + +## πŸ”§ Generation Process + +### Step 1: Gather Project Intelligence + +Before generating, collect: + +``` +β–‘ Read AGENTS.md (if exists) β€” operational rules +β–‘ Read README.md β€” user-facing description +β–‘ Read package.json β€” dependencies, scripts, entry points +β–‘ Scan directory structure β€” identify components +β–‘ Read docs/ or litho.docs/ β€” existing documentation +β–‘ Identify key source files β€” main entry points +β–‘ Note technology stack β€” frameworks, languages, platforms +``` + +### Step 2: Extract Knowledge + +**For PROJECT-ESSENCE.md:** +- What is this project? (one sentence) +- Why does it exist? (problem/solution) +- Who is it for? (target users) +- What does it provide? (key features) +- Core constraints? (security, compatibility) + +**For ARCHITECTURE.md:** +- System diagram (ASCII or Mermaid) +- Component responsibilities +- Data flow between components +- Key dependencies +- Important patterns + +**For DECISIONS.md:** +- Non-obvious design choices +- Trade-offs made +- Constraints accepted +- Decisions that might be revisited + +**For DYNAMICS.md:** +- Current blockers +- Known workarounds +- Temporary constraints +- Recently resolved issues (brief) + +### Step 3: Generate Files + +Use templates from `templates/` directory: + +1. Start with `SKILL.md` β€” entry point with activation rules +2. Generate `references/PROJECT-ESSENCE.md` β€” core identity +3. Generate `references/ARCHITECTURE.md` β€” component map +4. Generate `references/DECISIONS.md` β€” design rationale +5. Generate `DYNAMICS.md` β€” active issues +6. Generate `meta/MAINTENANCE.md` β€” upkeep guide + +### Step 4: Validate Quality + +``` +β–‘ SKILL.md has clear activation triggers +β–‘ PROJECT-ESSENCE.md readable in 2 minutes +β–‘ ARCHITECTURE.md shows big picture (no code) +β–‘ DECISIONS.md justified with rationale +β–‘ DYNAMICS.md only contains current issues +β–‘ All files dated at top +β–‘ Total token budget < 4000 tokens +``` + +--- + +## πŸ“ Writing Principles + +### Do: +- βœ… Write for someone who knows nothing about the project +- βœ… Use diagrams over paragraphs +- βœ… Focus on "why" not "how" +- βœ… Keep files under 150 lines each +- βœ… Link between related sections +- βœ… Include "Last updated" dates + +### Don't: +- ❌ Copy-paste code snippets (link to files instead) +- ❌ Document every file/function +- ❌ Include details that change frequently +- ❌ Duplicate content across files +- ❌ Use jargon without context + +--- + +## πŸ”„ Integration with AGENTS.md + +``` +AGENTS.md = "How to work" (commands, style, rules) +.ai-context = "What the project is" (architecture, decisions, issues) +``` + +Both should be read at session start. They serve different purposes and should not overlap. + +--- + +## πŸ“š Template Reference + +Templates are provided in `templates/`: + +| Template | Purpose | +|----------|---------| +| `skill.md.tmpl` | SKILL.md with placeholder prompts | +| `essence.md.tmpl` | PROJECT-ESSENCE.md structure | +| `architecture.md.tmpl` | ARCHITECTURE.md with diagram prompts | +| `decisions.md.tmpl` | DECISIONS.md with ADR format | +| `dynamics.md.tmpl` | DYNAMICS.md with status tracking | +| `maintenance.md.tmpl` | MAINTENANCE.md guide | + +--- + +## πŸ› οΈ Automation Scripts + +Scripts in `scripts/` can help with: + +| Script | Purpose | +|--------|---------| +| `generate.ts` | Interactive generation from templates | +| `check-drift.ts` | Compare documented vs actual structure | +| `audit-dynamics.ts` | Flag stale issues (>30 days) | + +--- + +## πŸ’‘ Example Usage + +**User:** "Setup ai-context for my project" + +**Agent:** +1. Activate this skill +2. Read AGENTS.md, README.md, package.json +3. Scan directory structure +4. Generate each file using templates +5. Ask clarifying questions if needed: + - "What's the main problem this project solves?" + - "Any non-obvious design decisions I should know about?" + - "Current blockers or workarounds?" + +--- + +## ⚠️ Important Notes + +- Generated knowledge is a **starting point**, not final truth +- Agent should verify against actual code during first session +- User should review generated content for accuracy +- Schedule regular audits (monthly recommended) + +--- + +## πŸ“– References + +- [Agent Skills Specification](https://agentskills.io/specification) +- [Architecture Decision Records](https://adr.github.io/) +- [Writing Readable Docs](references/WRITING-GUIDE.md) + +--- + +*This skill creates knowledge bases optimized for AI agents. For questions or improvements, see MAINTENANCE.md.* \ No newline at end of file diff --git a/.skills/ai-context-generator/references/WRITING-GUIDE.md b/.skills/ai-context-generator/references/WRITING-GUIDE.md new file mode 100644 index 0000000..5dc6718 --- /dev/null +++ b/.skills/ai-context-generator/references/WRITING-GUIDE.md @@ -0,0 +1,357 @@ +# Writing Guide for AI Context Knowledge Base + +> Practical guidance for creating documentation that coding agents can effectively use. Last updated: 2025-01-11. + +--- + +## Core Philosophy + +**Goal:** Create knowledge that helps agents work faster, not knowledge that documents everything. + +**Principle:** Agents have two sources of truth: +1. **Static Knowledge** (`.ai-context/`) β€” Mental model, context, rationale +2. **Dynamic Exploration** (code reading) β€” Current state, implementation details + +Write static knowledge to complement dynamic exploration, not replace it. + +--- + +## Writing for Agents vs Humans + +| Aspect | Human Documentation | Agent Knowledge | +|--------|---------------------|-----------------| +| Detail level | Comprehensive | Minimal, strategic | +| Code examples | Plentiful | Link to files instead | +| Update frequency | Per feature | Per structural change | +| Audience | Varies | Technical, literal | +| Format flexibility | Prose-heavy | Structured, scannable | + +--- + +## The Token Budget + +Each file has an implicit token budget. Respect it. + +| File | Budget | Why | +|------|--------|-----| +| PROJECT-ESSENCE.md | ~500 tokens | Must read every session | +| ARCHITECTURE.md | ~1000 tokens | Read when working across components | +| DECISIONS.md | ~800 tokens | Read when changing patterns | +| DYNAMICS.md | ~600 tokens | Read when debugging | +| SKILL.md | ~400 tokens | Loaded for discovery | + +**Total: ~3300 tokens** β€” Less than one typical function's worth of context. + +--- + +## Writing Techniques + +### 1. Prefer Diagrams Over Paragraphs + +❌ **Bad:** +``` +The system has a gateway that loads plugins. The gateway talks to cortex-mem-service +via HTTP. The service then connects to Qdrant for vector storage and the filesystem +for markdown storage. +``` + +βœ… **Good:** +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Gateway β”‚ +β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜ + β”‚ HTTP + β–Ό +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ cortex-mem-svc β”‚ +β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”˜ + β”‚ β”‚ + β–Ό β–Ό + Qdrant Files +``` + +### 2. Link, Don't Copy + +❌ **Bad:** +```markdown +The config format is: +```toml +[server] +port = 8085 +host = "localhost" +``` + +βœ… **Good:** +```markdown +Configuration format: see `config.example.toml` or `src/config.ts` for schema. +``` + +**Why:** Code copies become stale. Links stay valid. + +### 3. State the Non-Obvious + +❌ **Bad:** +```markdown +We use TypeScript for type safety. +``` + +βœ… **Good:** +```markdown +We use TypeScript strict mode. Avoid `any` β€” we prefer runtime validation via Zod +instead of type assertions. +``` + +**Why:** The first is obvious to any TypeScript user. The second captures project-specific practices. + +### 4. Use Tables for Comparisons + +❌ **Bad:** +```markdown +The memory plugin is for explicit calls while the context engine handles automatic +lifecycle hooks. They can both be installed together. +``` + +βœ… **Good:** +```markdown +| Aspect | Memory Plugin | Context Engine | +|--------|---------------|----------------| +| Trigger | Explicit tool call | Automatic lifecycle | +| Control | Full | None | +| Co-install | Yes | Yes | +``` + +### 5. Date Everything + +Every file should have a "Last updated" or "Last reviewed" date at the top. + +**Why:** Agents need to know if knowledge might be stale. + +--- + +## Anti-Patterns + +### Anti-Pattern 1: The Encyclopedia + +```markdown +## File Structure + +/src/ + /components/ + /Button/ + Button.tsx # Button component + Button.test.tsx # Tests + styles.css # Styles + /Input/ + Input.tsx + ... +``` + +**Problem:** Becomes wrong immediately. Use `find_path` instead. + +**Fix:** +```markdown +Components live in `src/components/`. Each is self-contained with its own directory. +``` + +--- + +### Anti-Pattern 2: The Tutorial + +```markdown +## How to Add a New Tool + +1. Create a new file in `src/tools/` +2. Import the tool interface +3. Implement the execute method +4. Register in tool-registry.ts +5. Add tests +... +``` + +**Problem:** This is a procedure, not knowledge. Procedures belong in AGENTS.md. + +**Fix:** +```markdown +Tools are registered in `tool-registry.ts`. Each tool implements `ToolInterface`. +``` + +--- + +### Anti-Pattern 3: The Decision Dump + +```markdown +## ADR-042: Use tabs for indentation + +We decided to use tabs because... + +## ADR-043: Use semicolons + +We decided to use semicolons because... +``` + +**Problem:** Not all decisions matter equally. + +**Fix:** Only document decisions that: +- Have significant trade-offs +- Affect multiple components +- Might be questioned later +- Have non-obvious rationale + +--- + +### Anti-Pattern 4: The Issue Graveyard + +```markdown +## Fixed in 2024-01 + +The config parser was broken... + +## Fixed in 2024-02 + +The API endpoint was wrong... +``` + +**Problem:** Resolved issues hide active ones. + +**Fix:** DYNAMICS.md should only contain: +- Active blockers +- Known constraints +- Items under consideration +- Recently resolved (last 2 weeks, brief) + +--- + +## What to Put Where + +### PROJECT-ESSENCE.md β€” "What and Why" + +- What is this? (one sentence) +- Why does it exist? +- Who uses it? +- Key value proposition +- Core constraints +- Success metrics + +**Not:** Technical details, architecture, decisions + +--- + +### ARCHITECTURE.md β€” "How Things Connect" + +- System diagram +- Component responsibilities +- Data flow +- Key patterns +- Dependencies +- Configuration layers + +**Not:** Implementation details, every file, API specs + +--- + +### DECISIONS.md β€” "Why We Chose This" + +- Non-obvious choices +- Trade-offs accepted +- Constraints embraced +- Things we might revisit + +**Not:** Naming conventions, style choices, one-off decisions + +--- + +### DYNAMICS.md β€” "What's Happening Now" + +- Active blockers +- Workarounds in use +- Temporary constraints +- Items under review + +**Not:** History, resolved issues, wishlists + +--- + +## Review Checklist + +Before finalizing any file: + +``` +β–‘ Is this knowledge that code exploration can't easily reveal? +β–‘ Would this still be accurate in 3 months? +β–‘ Is the token budget respected? +β–‘ Is there a "Last updated" date? +β–‘ Did I link instead of copy? +β–‘ Did I state the non-obvious? +β–‘ Is this scannable (tables, lists, diagrams)? +``` + +--- + +## Example Transformations + +### Before (Human-Style): + +```markdown +# Architecture + +This document describes the architecture of our system. The system is built using +TypeScript and runs on Node.js. We use Express for the HTTP server and PostgreSQL +for the database. The frontend is built with React. + +The main components are: +- API Layer: Handles HTTP requests +- Business Logic: Contains the core functionality +- Data Layer: Manages database access + +We chose PostgreSQL because it's reliable and has good JSON support. +``` + +### After (Agent-Optimized): + +```markdown +# Architecture + +> Last updated: 2025-01-11 + +## System Diagram + +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Express │────▢│ Business │────▢│ PostgreSQLβ”‚ +β”‚ :3000 β”‚ β”‚ Logic β”‚ β”‚ :5432 β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + β–Ό +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ React β”‚ +β”‚ Client β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +## Components + +| Component | Entry Point | Responsibility | +|-----------|-------------|----------------| +| API Layer | `src/api/` | HTTP routing, auth | +| Business Logic | `src/core/` | Domain operations | +| Data Layer | `src/db/` | Queries, migrations | + +## Key Decisions + +See [DECISIONS.md](DECISIONS.md) for rationale on PostgreSQL, Express, etc. +``` + +--- + +## Summary + +1. **Minimize tokens** β€” Every token costs attention +2. **Link, don't copy** β€” Code changes, links stay valid +3. **State the non-obvious** β€” Obvious things don't need documentation +4. **Structure for scanning** β€” Tables, lists, diagrams +5. **Date everything** β€” Agents need to assess staleness +6. **Separate concerns** β€” Each file has a purpose + +--- + +_Writing for agents is writing for a literal, token-constrained, but technically competent reader who prefers structure over prose._ \ No newline at end of file diff --git a/.skills/ai-context-generator/scripts/generate.ts b/.skills/ai-context-generator/scripts/generate.ts new file mode 100644 index 0000000..9d96ab9 --- /dev/null +++ b/.skills/ai-context-generator/scripts/generate.ts @@ -0,0 +1,785 @@ +#!/usr/bin/env bun +/** + * AI Context Generator + * + * Generates .ai-context knowledge base structure for coding agents. + * Run with: bun run generate.ts [project-path] + */ + +import * as fs from 'fs' +import * as path from 'path' + +// ============================================================================= +// Types & Interfaces +// ============================================================================= + +interface ProjectInfo { + name: string + description: string + problem: string + solution: string + targetUsers: Array<{ user: string; useCase: string }> + components: Array<{ name: string; purpose: string; entry?: string }> + decisions: Array<{ title: string; context: string; decision: string; rationale: string }> + issues: Array<{ title: string; status: 'active' | 'known'; impact: string; workaround: string }> + constraints: string[] +} + +interface TemplateData { + PROJECT_NAME: string + DATE: string + [key: string]: string | string[] | object[] +} + +// ============================================================================= +// Template Engine +// ============================================================================= + +function renderTemplate(template: string, data: TemplateData): string { + let result = template + + // Replace simple {{KEY}} placeholders + for (const [key, value] of Object.entries(data)) { + if (typeof value === 'string') { + result = result.replace(new RegExp(`\\{\\{${key}\\}\\}`, 'g'), value) + } + } + + return result +} + +// ============================================================================= +// File Templates +// ============================================================================= + +const SKILL_TEMPLATE = `--- +name: ai-context +description: | + Project knowledge base for coding agents. Activate when: (1) starting a new session in this project, (2) encountering unfamiliar code patterns or architecture decisions, (3) user asks about project design or rationale, (4) before making significant structural changes. Contains tiered knowledge from stable design principles to dynamic issues. +--- + +# AI Context β€” {{PROJECT_NAME}} + +> This skill provides pre-generated project knowledge to help you understand the project faster and work more effectively. + +--- + +## 🎯 When to Activate This Skill + +**Activate immediately when:** +- Starting a new coding session in this project +- You need to understand "why something is designed this way" +- User asks about project architecture, design decisions, or constraints + +**Refer to specific sections when:** +- Encountering unexpected behavior or errors β†’ \`DYNAMICS.md\` +- Planning structural changes β†’ \`references/DECISIONS.md\` +- Need high-level overview β†’ \`references/PROJECT-ESSENCE.md\` +- Need component relationships β†’ \`references/ARCHITECTURE.md\` + +**Do NOT activate when:** +- Simple code edits with clear context +- User requests are purely mechanical (rename, format, etc.) +- You already have sufficient context from recent conversation + +--- + +## πŸ“ Knowledge Tiers + +| Tier | File | Stability | Update Frequency | +|------|------|-----------|------------------| +| **Tier 0** | \`PROJECT-ESSENCE.md\` | High | Quarterly / Major version | +| **Tier 1** | \`ARCHITECTURE.md\` | Medium | Monthly / Sprint | +| **Tier 2** | \`DECISIONS.md\` | Low | Per decision change | +| **Tier 3** | \`DYNAMICS.md\` | Dynamic | As needed | + +### Reading Order (Recommended) + +\`\`\` +1. PROJECT-ESSENCE.md ← Start here (1-2 min read) +2. ARCHITECTURE.md ← If working across components +3. DECISIONS.md ← If changing established patterns +4. DYNAMICS.md ← If something feels wrong +\`\`\` + +--- + +## πŸ”§ How to Use This Knowledge + +### 1. Session Start Protocol +\`\`\` +β–‘ Read PROJECT-ESSENCE.md (always) +β–‘ Scan DYNAMICS.md for active issues +β–‘ Read ARCHITECTURE.md if working across subprojects +β–‘ Proceed with dynamic code exploration +\`\`\` + +### 2. Dynamic Code Exploration +- Use \`grep\` and \`find_path\` to locate actual implementations +- Verify knowledge against current code state +- Update knowledge if you find drift + +### 3. Decision Validation +Before changing established patterns: +\`\`\` +β–‘ Check DECISIONS.md for existing decisions +β–‘ If decision exists: follow it or explicitly propose change +β–‘ If new decision needed: document after implementation +\`\`\` + +--- + +## πŸ”„ When to Update + +### Update PROJECT-ESSENCE.md when: +- Project purpose or scope fundamentally changes +- New major capability is added + +### Update ARCHITECTURE.md when: +- New component/subproject added +- Component responsibilities shift +- Data flow changes significantly + +### Update DECISIONS.md when: +- A new design decision is made +- An existing decision is revisited/changed + +### Update DYNAMICS.md when: +- New issue discovered +- Issue resolved +- Workaround found + +--- + +## πŸ“š File Reference + +- [Project Essence](references/PROJECT-ESSENCE.md) +- [Architecture](references/ARCHITECTURE.md) +- [Decisions](references/DECISIONS.md) +- [Dynamics](DYNAMICS.md) +- [Maintenance Guide](meta/MAINTENANCE.md) + +--- + +*Generated by ai-context-generator on {{DATE}}* +` + +const ESSENCE_TEMPLATE = `# Project Essence β€” {{PROJECT_NAME}} + +> **Stability: HIGH** | Update: Quarterly or major version changes +> +> Last reviewed: {{DATE}} + +--- + +## What Is This Project? + +{{PROJECT_DESCRIPTION}} + +--- + +## Why Does It Exist? + +**Problem:** {{PROJECT_PROBLEM}} + +**Solution:** +{{PROJECT_SOLUTION}} + +--- + +## Who Is This For? + +| User | Use Case | +|------|----------| +{{#TARGET_USERS}} +| {{user}} | {{useCase}} | +{{/TARGET_USERS}} + +--- + +## Key Constraints + +{{PROJECT_CONSTRAINTS}} + +--- + +*This file captures the stable essence of the project. For architecture details, see [ARCHITECTURE.md](ARCHITECTURE.md).* +` + +const ARCHITECTURE_TEMPLATE = `# Architecture β€” {{PROJECT_NAME}} + +> How components fit together. Last updated: {{DATE}}. +> +> **Update this when:** New component added, responsibilities shift, data flow changes. + +--- + +## System Overview + +\`\`\` +[DIAGRAM_PLACEHOLDER - Replace with your system diagram] + +Example: +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ [Main System/Platform] β”‚ +β”‚ β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ [Component A] β”‚ β”‚ [Component B] β”‚ β”‚ +β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ +β”‚ β”‚ β€’ [responsibility]β”‚ β”‚ β€’ [responsibility] β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β”‚ β”‚ β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β”‚ β–Ό β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ [Backend Service] β”‚ ← Port XXXX β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +\`\`\` + +--- + +## Component Responsibilities + +{{#COMPONENTS}} +### {{name}} +- **Purpose:** {{purpose}} +{{#entry}} +- **Entry:** \`{{entry}}\` +{{/entry}} + +{{/COMPONENTS}} + +--- + +## Data Flow + +[TBD: Describe key data flows] + +--- + +## Dependencies + +| Package | Purpose | Version | +|---------|---------|---------| +| [package] | [purpose] | [version] | + +--- + +*This file describes component relationships. For implementation details, explore the source code.* +` + +const DECISIONS_TEMPLATE = `# Design Decisions β€” {{PROJECT_NAME}} + +> Key architectural and design decisions. Update when decisions are made or revisited. +> +> Last reviewed: {{DATE}} + +--- + +## Decision Index + +| ID | Decision | Status | Date | +|----|----------|--------|------| +{{#DECISIONS}} +| ADR-XXX | {{title}} | Active | {{DATE}} | +{{/DECISIONS}} + +--- + +{{#DECISIONS}} +## ADR-XXX: {{title}} + +**Context**: {{context}} + +**Decision**: {{decision}} + +**Rationale**: {{rationale}} + +**Trade-offs**: +- (+) [Benefit] +- (-) [Cost] + +--- + +{{/DECISIONS}} + +## Template for New Decisions + +\`\`\`markdown +## ADR-XXX: [Short Title] + +**Context**: [What is the issue?] + +**Decision**: [What did we decide?] + +**Rationale**: [Why this choice?] + +**Trade-offs**: +- (+) [Benefit] +- (-) [Cost] +\`\`\` + +--- + +*This file captures decisions that aren't obvious from code.* +` + +const DYNAMICS_TEMPLATE = `# Dynamics β€” Active Issues & Constraints + +> **Last updated:** {{DATE}} +> **Stability:** Dynamic β€” Update as issues arise/resolve + +--- + +## ⚑ Quick Scan + +| Status | Issue | Impact | Workaround | +|--------|-------|--------|------------| +{{#ISSUES}} +| {{statusIcon}} | {{title}} | {{impact}} | {{workaround}} | +{{/ISSUES}} + +--- + +## πŸ”΄ Active Issues + +{{#ISSUES}} +{{#isActive}} +### {{title}} + +**What:** [Description] + +**Impact:** {{impact}} + +**Workaround:** {{workaround}} + +--- + +{{/isActive}} +{{/ISSUES}} + +## 🟑 Known Constraints + +[TBD: Add known constraints that affect development] + +--- + +## 🟒 Recently Resolved + +| Issue | Resolution | Date | +|-------|------------|------| +| [issue] | [resolution] | [date] | + +--- + +## πŸ“‹ Under Consideration + +[TBD: Items being evaluated] + +--- + +*Remember: This file changes frequently. Verify against current code state.* +` + +const MAINTENANCE_TEMPLATE = `# AI Context Maintenance Guide + +> How to keep this knowledge base accurate. Last updated: {{DATE}}. + +--- + +## 🎯 Purpose + +This guide tells you (the coding agent) how to maintain \`.ai-context\`. + +--- + +## πŸ“‹ Maintenance Triggers + +| Observation | Action | File | +|-------------|--------|------| +| Code contradicts docs | Fix docs | Relevant file | +| New component | Add entry | ARCHITECTURE.md | +| Major decision | Document | DECISIONS.md | +| Blocking issue | Add entry | DYNAMICS.md | +| Issue resolved | Remove | DYNAMICS.md | + +--- + +## ✍️ Writing Guidelines + +### PROJECT-ESSENCE.md +- Under 100 lines +- "What" and "why", not "how" +- No code snippets +- Update: Quarterly + +### ARCHITECTURE.md +- Diagrams over paragraphs +- Component-level, not file-level +- Show data flow +- Update: Monthly + +### DECISIONS.md +- Non-obvious choices only +- Include rationale +- Update: As decisions made + +### DYNAMICS.md +- Current issues only +- Remove when resolved +- Update: As needed + +--- + +## πŸ”„ Update Workflow + +1. Identify file needing update +2. Read current content +3. Make minimal changes +4. Update "Last updated" date +5. Continue your task + +--- + +## ❌ Anti-Patterns + +- Don't copy code snippets +- Don't document every file +- Don't keep resolved issues +- Don't duplicate across files + +--- + +## βœ… Quality Checklist + +- [ ] PROJECT-ESSENCE.md readable in 2 min +- [ ] ARCHITECTURE.md shows big picture +- [ ] DECISIONS.md has rationale +- [ ] DYNAMICS.md only current issues +- [ ] All files dated + +--- + +*Update this guide when you discover better maintenance patterns.* +` + +// ============================================================================= +// Project Analysis +// ============================================================================= + +async function analyzeProject(projectPath: string): Promise { + const packageJsonPath = path.join(projectPath, 'package.json') + const readmePath = path.join(projectPath, 'README.md') + const agentsPath = path.join(projectPath, 'AGENTS.md') + + let projectName = path.basename(projectPath) + let description = '' + + // Read package.json if exists + if (fs.existsSync(packageJsonPath)) { + const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8')) + projectName = pkg.name || projectName + description = pkg.description || '' + } + + // Read README if exists + let readme = '' + if (fs.existsSync(readmePath)) { + readme = fs.readFileSync(readmePath, 'utf-8') + if (!description) { + // Extract first paragraph as description + const match = readme.match(/^#\s.*\n+([^#\n].*?)(?:\n\n|$)/m) + if (match) { + description = match[1].trim() + } + } + } + + // Read AGENTS.md if exists + let agents = '' + if (fs.existsSync(agentsPath)) { + agents = fs.readFileSync(agentsPath, 'utf-8') + } + + // Scan directory structure + const components = scanComponents(projectPath) + + return { + name: projectName, + description: description || 'A software project', + problem: '[TBD: What problem does this project solve?]', + solution: '[TBD: How does this project solve it?]', + targetUsers: [{ user: 'Developer', useCase: 'Building software' }], + components, + decisions: [], + issues: [], + constraints: [] + } +} + +function scanComponents(projectPath: string): ProjectInfo['components'] { + const components: ProjectInfo['components'] = [] + + const entries = fs.readdirSync(projectPath, { withFileTypes: true }) + + for (const entry of entries) { + if (entry.isDirectory() && !entry.name.startsWith('.') && !entry.name.startsWith('node_modules')) { + const subPath = path.join(projectPath, entry.name) + + // Check if it's a subproject (has package.json) + const subPackageJson = path.join(subPath, 'package.json') + if (fs.existsSync(subPackageJson)) { + const pkg = JSON.parse(fs.readFileSync(subPackageJson, 'utf-8')) + components.push({ + name: entry.name, + purpose: pkg.description || 'Subproject', + entry: path.join(entry.name, 'index.ts') + }) + } else { + // Regular directory - check for src + const srcPath = path.join(subPath, 'src') + if (fs.existsSync(srcPath)) { + components.push({ + name: entry.name, + purpose: `${entry.name} module` + }) + } + } + } + } + + return components +} + +// ============================================================================= +// Generator Functions +// ============================================================================= + +function generateSkillMd(info: ProjectInfo): string { + const date = new Date().toISOString().split('T')[0] + return renderTemplate(SKILL_TEMPLATE, { + PROJECT_NAME: info.name, + DATE: date + }) +} + +function generateProjectEssence(info: ProjectInfo): string { + const date = new Date().toISOString().split('T')[0] + + let targetUsersStr = '' + for (const tu of info.targetUsers) { + targetUsersStr += `| ${tu.user} | ${tu.useCase} |\n` + } + + let constraintsStr = '' + for (let i = 0; i < info.constraints.length; i++) { + constraintsStr += `${i + 1}. **${info.constraints[i]}**\n` + } + if (!constraintsStr) { + constraintsStr = '1. **[TBD: Add key constraints]**\n' + } + + let template = ESSENCE_TEMPLATE + template = template.replace('{{PROJECT_NAME}}', info.name) + template = template.replace('{{DATE}}', date) + template = template.replace('{{PROJECT_DESCRIPTION}}', info.description) + template = template.replace('{{PROJECT_PROBLEM}}', info.problem) + template = template.replace('{{PROJECT_SOLUTION}}', info.solution) + template = template.replace('{{#TARGET_USERS}}\n| {{user}} | {{useCase}} |\n{{/TARGET_USERS}}', targetUsersStr) + template = template.replace('{{PROJECT_CONSTRAINTS}}', constraintsStr) + + return template +} + +function generateArchitecture(info: ProjectInfo): string { + const date = new Date().toISOString().split('T')[0] + + let componentsStr = '' + for (const comp of info.components) { + componentsStr += `### ${comp.name}\n` + componentsStr += `- **Purpose:** ${comp.purpose}\n` + if (comp.entry) { + componentsStr += `- **Entry:** \`${comp.entry}\`\n` + } + componentsStr += '\n' + } + + let template = ARCHITECTURE_TEMPLATE + template = template.replace('{{PROJECT_NAME}}', info.name) + template = template.replace('{{DATE}}', date) + + // Handle component block + const compBlockMatch = template.match(/{{#COMPONENTS}}[\s\S]*?{{\/COMPONENTS}}/) + if (compBlockMatch) { + template = template.replace(compBlockMatch[0], componentsStr) + } + + return template +} + +function generateDecisions(info: ProjectInfo): string { + const date = new Date().toISOString().split('T')[0] + + let decisionsStr = '' + let decisionBlocks = '' + + for (const dec of info.decisions) { + decisionsStr += `| ADR-XXX | ${dec.title} | Active | ${date} |\n` + decisionBlocks += `## ADR-XXX: ${dec.title}\n\n` + decisionBlocks += `**Context**: ${dec.context}\n\n` + decisionBlocks += `**Decision**: ${dec.decision}\n\n` + decisionBlocks += `**Rationale**: ${dec.rationale}\n\n` + decisionBlocks += '**Trade-offs**:\n- (+) [Benefit]\n- (-) [Cost]\n\n---\n\n' + } + + if (!decisionsStr) { + decisionsStr = '| ADR-001 | [First decision title] | Active | YYYY-MM |\n' + decisionBlocks = `## ADR-001: [Decision Title] + +**Context**: [What is the issue?] + +**Decision**: [What did we decide?] + +**Rationale**: [Why this choice?] + +**Trade-offs**: +- (+) [Benefit] +- (-) [Cost] + +--- + +` + } + + let template = DECISIONS_TEMPLATE + template = template.replace('{{PROJECT_NAME}}', info.name) + template = template.replace('{{DATE}}', date) + + // Handle index block + const indexBlockMatch = template.match(/{{#DECISIONS}}[\s\S]*?{{\/DECISIONS}}/) + if (indexBlockMatch) { + // For index, just use the title + template = template.replace(indexBlockMatch[0], decisionsStr) + } + + // Handle decision blocks - need to re-match after first replacement + const blockMatch = template.match(/{{#DECISIONS}}[\s\S]*?{{\/DECISIONS}}/) + if (blockMatch) { + template = template.replace(blockMatch[0], decisionBlocks) + } + + return template +} + +function generateDynamics(info: ProjectInfo): string { + const date = new Date().toISOString().split('T')[0] + + let issuesStr = '' + let activeStr = '' + + for (const issue of info.issues) { + const icon = issue.status === 'active' ? 'πŸ”΄' : '🟑' + issuesStr += `| ${icon} | ${issue.title} | ${issue.impact} | ${issue.workaround} |\n` + + if (issue.status === 'active') { + activeStr += `### ${issue.title}\n\n` + activeStr += `**What:** [Description]\n\n` + activeStr += `**Impact:** ${issue.impact}\n\n` + activeStr += `**Workaround:** ${issue.workaround}\n\n---\n\n` + } + } + + if (!issuesStr) { + issuesStr = '| πŸ”΄ | [No active issues documented] | β€” | β€” |\n' + } + + let template = DYNAMICS_TEMPLATE + template = template.replace('{{DATE}}', date) + + // Handle quick scan block + const scanBlockMatch = template.match(/{{#ISSUES}}[\s\S]*?{{\/ISSUES}}/) + if (scanBlockMatch) { + template = template.replace(scanBlockMatch[0], issuesStr) + } + + return template +} + +function generateMaintenance(info: ProjectInfo): string { + const date = new Date().toISOString().split('T')[0] + return renderTemplate(MAINTENANCE_TEMPLATE, { + DATE: date + }) +} + +// ============================================================================= +// Main Generator +// ============================================================================= + +async function generate(projectPath: string): Promise { + console.log(`\nπŸš€ Generating .ai-context for: ${projectPath}\n`) + + // Analyze project + console.log('πŸ“Š Analyzing project...') + const info = await analyzeProject(projectPath) + console.log(` Found: ${info.name}`) + console.log(` Components: ${info.components.length}`) + + // Create directory structure + const aiContextPath = path.join(projectPath, '.ai-context') + const referencesPath = path.join(aiContextPath, 'references') + const metaPath = path.join(aiContextPath, 'meta') + + console.log('\nπŸ“ Creating directory structure...') + fs.mkdirSync(aiContextPath, { recursive: true }) + fs.mkdirSync(referencesPath, { recursive: true }) + fs.mkdirSync(metaPath, { recursive: true }) + + // Generate files + console.log('\nπŸ“ Generating files...') + + // SKILL.md + const skillContent = generateSkillMd(info) + fs.writeFileSync(path.join(aiContextPath, 'SKILL.md'), skillContent) + console.log(' βœ“ SKILL.md') + + // PROJECT-ESSENCE.md + const essenceContent = generateProjectEssence(info) + fs.writeFileSync(path.join(referencesPath, 'PROJECT-ESSENCE.md'), essenceContent) + console.log(' βœ“ references/PROJECT-ESSENCE.md') + + // ARCHITECTURE.md + const archContent = generateArchitecture(info) + fs.writeFileSync(path.join(referencesPath, 'ARCHITECTURE.md'), archContent) + console.log(' βœ“ references/ARCHITECTURE.md') + + // DECISIONS.md + const decisionsContent = generateDecisions(info) + fs.writeFileSync(path.join(referencesPath, 'DECISIONS.md'), decisionsContent) + console.log(' βœ“ references/DECISIONS.md') + + // DYNAMICS.md + const dynamicsContent = generateDynamics(info) + fs.writeFileSync(path.join(aiContextPath, 'DYNAMICS.md'), dynamicsContent) + console.log(' βœ“ DYNAMICS.md') + + // MAINTENANCE.md + const maintenanceContent = generateMaintenance(info) + fs.writeFileSync(path.join(metaPath, 'MAINTENANCE.md'), maintenanceContent) + console.log(' βœ“ meta/MAINTENANCE.md') + + console.log('\nβœ… .ai-context generated successfully!') + console.log('\nπŸ“Œ Next steps:') + console.log(' 1. Review generated files and fill in [TBD] placeholders') + console.log(' 2. Add your project-specific architecture details') + console.log(' 3. Document any non-obvious design decisions') + console.log(' 4. Add current issues to DYNAMICS.md if any\n') +} + +// ============================================================================= +// CLI Entry Point +// ============================================================================= + +const projectPath = process.argv[2] || process.cwd() +generate(projectPath).catch(console.error) diff --git a/.skills/ai-context-generator/templates/architecture.md.tmpl b/.skills/ai-context-generator/templates/architecture.md.tmpl new file mode 100644 index 0000000..64b52ff --- /dev/null +++ b/.skills/ai-context-generator/templates/architecture.md.tmpl @@ -0,0 +1,110 @@ +# Architecture β€” {{PROJECT_NAME}} + +> How components fit together. Last updated: {{DATE}}. +> +> **Update this when:** New component added, responsibilities shift, data flow changes. + +--- + +## System Overview + +``` +[INSERT ASCII DIAGRAM OR MERMAID DIAGRAM HERE] + +Example format: +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ [Main System/Platform] β”‚ +β”‚ β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ [Component A] β”‚ β”‚ [Component B] β”‚ β”‚ +β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ +β”‚ β”‚ β€’ [responsibility]β”‚ β”‚ β€’ [responsibility] β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β”‚ β”‚ β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β”‚ β–Ό β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ [Backend Service] β”‚ ← Port XXXX β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β”‚ β”‚ β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β–Ό β–Ό β–Ό β”‚ +β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ +β”‚ β”‚ [Store A] β”‚ β”‚ [Store B] β”‚ β”‚ [External] β”‚ β”‚ +β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +--- + +## Component Responsibilities + +### [Component A] +- **Entry:** `path/to/entry.ts` +- **Purpose:** [What this component does] +- **Key behaviors:** + - [Behavior 1] + - [Behavior 2] + +### [Component B] +- **Entry:** `path/to/entry.ts` +- **Purpose:** [What this component does] +- **Key behaviors:** + - [Behavior 1] + - [Behavior 2] + + + +--- + +## Data Flow + +### [Flow Name 1] (e.g., Write Path) +``` +[Trigger] + β†’ [Step 1] + β†’ [Step 2] + β†’ [Result] +``` + +### [Flow Name 2] (e.g., Read Path) +``` +[Trigger] + β†’ [Step 1] + β†’ [Step 2] + β†’ [Result] +``` + +--- + +## Key Design Patterns + +### 1. [Pattern Name] +- **Where:** [Which components use this] +- **Why:** [Rationale] +- **How it works:** [Brief explanation] + +--- + +## Dependencies + +| Package | Purpose | Version Constraint | +|---------|---------|-------------------| +| [Package 1] | [Purpose] | [Version] | +| [Package 2] | [Purpose] | [Version] | + +--- + +## Configuration Layers + +``` +[Config Source A] (highest priority) + ↓ +[Config Source B] + ↓ +[Default values] (lowest priority) +``` + +--- + +*This file describes component relationships. For detailed implementation, explore the source code or use `grep`.* diff --git a/.skills/ai-context-generator/templates/decisions.md.tmpl b/.skills/ai-context-generator/templates/decisions.md.tmpl new file mode 100644 index 0000000..e54abca --- /dev/null +++ b/.skills/ai-context-generator/templates/decisions.md.tmpl @@ -0,0 +1,107 @@ +# Design Decisions β€” {{PROJECT_NAME}} + +> Key architectural and design decisions that shape this project. Update when decisions are made or revisited. +> +> Last reviewed: {{DATE}} + +--- + +## Decision Index + +| ID | Decision | Status | Date | +|----|----------|--------|------| +| ADR-001 | [Short title] | Active | YYYY-MM | + +--- + +## ADR-001: [Decision Title] + +**Context**: [What is the issue or question being addressed? What forces are at play?] + +**Decision**: [What is the change that we're proposing/making?] + +**Rationale**: [Why did we make this choice?] + +**Trade-offs**: +- (+) [Benefit of this choice] +- (+) [Another benefit] +- (-) [Cost or drawback] +- (-) [Another drawback] + +**Implications**: [What does this mean for the codebase, users, or operations?] + +**Revisit if**: [Conditions that might warrant revisiting this decision] + +--- + +## ADR-002: [Decision Title] + +**Context**: ... + +**Decision**: ... + +**Rationale**: ... + +**Trade-offs**: +- (+) ... +- (-) ... + +**Implications**: ... + +**Revisit if**: ... + +--- + +## Decision Template + +When adding new decisions: + +```markdown +## ADR-XXX: [Short Title] + +**Context**: [What is the issue we're facing?] + +**Decision**: [What did we decide to do?] + +**Rationale**: [Why did we make this choice?] + +**Trade-offs**: +- (+) [Benefit] +- (-) [Cost] + +**Implications**: [What does this mean for implementation?] + +**Revisit if**: [Conditions that might warrant change] +``` + +--- + +## Guidance for Filling This Template + +### What warrants a decision record? + +- Choices between multiple viable alternatives +- Decisions that affect multiple components +- Non-obvious trade-offs +- Decisions that might be questioned later +- Architectural constraints + +### What does NOT need a record? + +- Trivial naming conventions +- Standard patterns in the tech stack +- Decisions with only one reasonable option +- Temporary choices with clear expiration + +### Status Values + +| Status | Meaning | +|--------|---------| +| Active | Currently in effect | +| Superseded | Replaced by ADR-XXX | +| Deprecated | No longer recommended | +| Under Review | Being reconsidered | + +--- + +_This file captures decisions that aren't obvious from code. For implementation details, see ARCHITECTURE.md._ diff --git a/.skills/ai-context-generator/templates/dynamics.md.tmpl b/.skills/ai-context-generator/templates/dynamics.md.tmpl new file mode 100644 index 0000000..24067aa --- /dev/null +++ b/.skills/ai-context-generator/templates/dynamics.md.tmpl @@ -0,0 +1,71 @@ +# Dynamics β€” Active Issues & Constraints + +> **Last updated:** {DATE} +> **Stability:** Dynamic β€” Update as issues arise/resolve + +--- + +## ⚑ Quick Scan + +| Status | Issue | Impact | Workaround | +|--------|-------|--------|------------| +| πŸ”΄ Active | {issue_name} | {impact} | {workaround} | +| 🟑 Known | {constraint_name} | {impact} | {mitigation} | +| 🟒 Resolved | ~~{resolved_issue}~~ | β€” | β€” | + +--- + +## πŸ”΄ Active Issues + +### {Issue Title} + +**What:** {Brief description of the issue} + +**Impact:** {How this affects development/workflow} + +**Workaround:** +``` +{Steps or code to work around the issue} +``` + +**Resolution Path:** {Planned fix or "Not yet planned"} + +--- + +## 🟑 Known Constraints + +### {Constraint Title} + +{Description of the constraint and why it exists} + +**Mitigation:** {How to work within this constraint} + +--- + +## 🟒 Recently Resolved + +| Issue | Resolution | Date | +|-------|------------|------| +| {issue} | {how resolved} | {date} | + +--- + +## πŸ“‹ Under Consideration + +### {Topic Under Review} + +{Brief description of what's being considered} + +**Trigger for change:** {What would prompt a decision} + +--- + +## πŸ”„ Update Log + +| Date | Change | +|------|--------| +| {DATE} | Initial version | + +--- + +*Remember: This file changes frequently. Always check the "Last updated" date. If it's been > 2 weeks, verify against current code state.* diff --git a/.skills/ai-context-generator/templates/essence.md.tmpl b/.skills/ai-context-generator/templates/essence.md.tmpl new file mode 100644 index 0000000..637c7cf --- /dev/null +++ b/.skills/ai-context-generator/templates/essence.md.tmpl @@ -0,0 +1,92 @@ +# Project Essence β€” {{PROJECT_NAME}} + +> **Stability: HIGH** | Update: Quarterly or major version changes +> +> Last reviewed: {{DATE}} + +--- + +## What Is This Project? + +[One sentence description of what the project is] + +--- + +## Why Does It Exist? + +**Problem:** [What problem does this project solve?] + +**Solution:** [How does this project solve it?] +- [Key benefit 1] +- [Key benefit 2] +- [Key benefit 3] + +--- + +## Who Is This For? + +| User | Use Case | +|------|----------| +| [User type 1] | [Their use case] | +| [User type 2] | [Their use case] | +| [User type 3] | [Their use case] | + +--- + +## Core Value Proposition + +``` +Before [PROJECT_NAME]: + [Describe the problem state] + +After [PROJECT_NAME]: + [Describe the improved state] +``` + +--- + +## What Does It Provide? + +### Key Components + +| Component | Purpose | Value | +|-----------|---------|-------| +| [Component 1] | [What it does] | [Why it matters] | +| [Component 2] | [What it does] | [Why it matters] | +| [Component 3] | [What it does] | [Why it matters] | + +### Key Features + +1. **[Feature 1]** β€” [Brief description] +2. **[Feature 2]** β€” [Brief description] +3. **[Feature 3]** β€” [Brief description] + +--- + +## Key Constraints + +1. **[Constraint type]** β€” [Description and reason] +2. **[Constraint type]** β€” [Description and reason] +3. **[Constraint type]** β€” [Description and reason] + +--- + +## Success Metrics + +| Metric | Target | +|--------|--------| +| [Metric 1] | [Target value] | +| [Metric 2] | [Target value] | +| [Metric 3] | [Target value] | + +--- + +## Evolution Direction + +- **Short-term:** [Near-term improvements] +- **Mid-term:** [Medium-term goals] +- **Long-term:** [Long-term vision] + +--- + +*This file captures the stable essence of the project. For architecture details, see [ARCHITECTURE.md](ARCHITECTURE.md).* diff --git a/.skills/ai-context-generator/templates/maintenance.md.tmpl b/.skills/ai-context-generator/templates/maintenance.md.tmpl new file mode 100644 index 0000000..c67f61e --- /dev/null +++ b/.skills/ai-context-generator/templates/maintenance.md.tmpl @@ -0,0 +1,182 @@ +# AI Context Maintenance Guide + +> How to keep this knowledge base accurate and useful. Last updated: {DATE}. + +--- + +## 🎯 Purpose of This Guide + +This document tells you (the coding agent) how to maintain the `.ai-context` knowledge base. Following these guidelines ensures knowledge stays accurate without becoming a maintenance burden. + +--- + +## πŸ“‹ Maintenance Triggers + +### Automatic Update Triggers +Update knowledge when you observe: + +| Observation | Action | File to Update | +|-------------|--------|----------------| +| Code contradicts documented behavior | Fix documentation | Relevant reference file | +| New component created | Add entry | `ARCHITECTURE.md` | +| Major design choice made | Document rationale | `DECISIONS.md` | +| Issue blocking work discovered | Add entry | `DYNAMICS.md` | +| Issue resolved | Remove/move entry | `DYNAMICS.md` | +| API contract changed | Update section | `ARCHITECTURE.md` | + +### Explicit Update Requests +When user asks to "update the knowledge base" or "refresh ai-context": +1. Review each file for accuracy +2. Compare documented state against current code +3. Update outdated sections +4. Update the "Last updated" date at file top +5. Summarize changes to user + +--- + +## ✍️ Writing Guidelines + +### For PROJECT-ESSENCE.md +- Keep it under 100 lines +- Focus on "what" and "why", not "how" +- No code snippets, no API details +- Target audience: Someone who knows nothing about the project +- Update frequency: Rare (quarterly or major version) + +### For ARCHITECTURE.md +- Use diagrams over paragraphs (ASCII art or Mermaid) +- Component-level granularity, not file-level +- Show data flow, not implementation details +- Include: Responsibilities, Dependencies, Interfaces +- Omit: Internal algorithms, variable names, code snippets +- Update frequency: Monthly or per sprint + +### For DECISIONS.md +- Format: `## Decision: [Title]` followed by Context, Options, Choice, Rationale +- Include decisions that are non-obvious or controversial +- Omit trivial decisions (naming conventions, etc.) +- When revisiting a decision, add a new section noting the change +- Update frequency: As decisions are made/changed + +### For DYNAMICS.md +- Keep entries actionable +- Format: `## [Status]: [Issue]` where Status = Active / Resolved / Monitoring +- Include: Impact, Workaround (if any), Resolution plan +- Remove resolved issues promptly (don't accumulate history) +- Update frequency: As needed (most dynamic file) + +--- + +## πŸ”„ Update Workflow + +### When Making Updates + +``` +1. Identify which file needs updating +2. Read the current content +3. Make minimal, focused changes +4. Update "Last updated" date at top +5. Proceed with your task +``` + +### What NOT to Do + +- ❌ Don't rewrite entire files for minor changes +- ❌ Don't add details that belong in code comments +- ❌ Don't duplicate information across files +- ❌ Don't document every file/function β€” stay high-level +- ❌ Don't keep resolved issues in DYNAMICS.md + +--- + +## πŸ“Š Knowledge Audit Checklist + +Periodically (or when requested), perform this audit: + +``` +β–‘ PROJECT-ESSENCE.md: Does it still describe what the project does? +β–‘ ARCHITECTURE.md: Do components still exist and have same responsibilities? +β–‘ DECISIONS.md: Are decisions still valid or have they been superseded? +β–‘ DYNAMICS.md: Are all issues still active? Are any resolved? +β–‘ SKILL.md: Is the activation guidance still accurate? +``` + +--- + +## πŸ› οΈ Automation Opportunities + +### Scripts That Could Help + +These scripts don't exist yet but could be added to `meta/scripts/`: + +| Script | Purpose | +|--------|---------| +| `check-drift.ts` | Compare documented components against actual structure | +| `list-decisions.ts` | Extract decision titles for quick reference | +| `audit-dynamics.ts` | Check for stale issues (>30 days without update) | + +### When to Create Scripts + +If you find yourself repeating a maintenance task: +1. Consider if a script would help +2. If yes, create it in `meta/scripts/` +3. Document it in this file +4. Run it when appropriate + +--- + +## πŸ“ Quality Standards + +### Knowledge Quality Checklist + +Before considering knowledge "good": + +- [ ] Can someone new understand PROJECT-ESSENCE.md in 2 minutes? +- [ ] Does ARCHITECTURE.md show the big picture without implementation details? +- [ ] Are decisions in DECISIONS.md justified with rationale? +- [ ] Does DYNAMICS.md only contain actionable, current issues? +- [ ] Is every file dated with last update? + +### Anti-Patterns to Avoid + +| Anti-Pattern | Why It's Bad | Fix | +|--------------|--------------|-----| +| Copy-pasting code | Becomes stale immediately | Link to source files instead | +| Documenting every file | Overwhelms and distracts | Focus on components/patterns | +| Never updating | Knowledge becomes liability | Follow triggers above | +| Over-documenting decisions | Dilutes important ones | Only non-obvious decisions | +| Keeping resolved issues | Hides actual problems | Remove when resolved | + +--- + +## πŸ”— Integration Points + +### With AGENTS.md + +``` +AGENTS.md says: "How to work" (commands, style, rules) +.ai-context says: "What the project is" (architecture, decisions, issues) +``` + +Both should be read at session start. They serve different purposes and should not duplicate content. + +### With Dynamic Code Exploration + +``` +.ai-context provides: Starting mental model +Code exploration provides: Current ground truth +``` + +Always verify knowledge against code. When they diverge, code is truth β€” update the knowledge. + +--- + +## πŸ“ Changelog + +| Date | Change | +|------|--------| +| {DATE} | Initial maintenance guide created | + +--- + +_This guide is itself maintained using these principles. Update it when you discover better maintenance patterns._ diff --git a/.skills/ai-context-generator/templates/skill.md.tmpl b/.skills/ai-context-generator/templates/skill.md.tmpl new file mode 100644 index 0000000..75248aa --- /dev/null +++ b/.skills/ai-context-generator/templates/skill.md.tmpl @@ -0,0 +1,139 @@ +--- +name: ai-context +description: | + Project knowledge base for coding agents. Activate when: (1) starting a new session in this project, (2) encountering unfamiliar code patterns or architecture decisions, (3) user asks about project design or rationale, (4) before making significant structural changes. Contains tiered knowledge from stable design principles to dynamic issues. +--- + +# AI Context β€” {{PROJECT_NAME}} + +> This skill provides pre-generated project knowledge to help you understand the project faster and work more effectively. + +--- + +## 🎯 When to Activate This Skill + +**Activate immediately when:** +- Starting a new coding session in this project +- You need to understand "why something is designed this way" +- User asks about project architecture, design decisions, or constraints + +**Refer to specific sections when:** +- Encountering unexpected behavior or errors β†’ `DYNAMICS.md` +- Planning structural changes β†’ `references/DECISIONS.md` +- Need high-level overview β†’ `references/PROJECT-ESSENCE.md` +- Need component relationships β†’ `references/ARCHITECTURE.md` + +**Do NOT activate when:** +- Simple code edits with clear context +- User requests are purely mechanical (rename, format, etc.) +- You already have sufficient context from recent conversation + +--- + +## πŸ“ Knowledge Tiers + +This skill organizes knowledge by **stability** β€” how frequently the knowledge changes: + +| Tier | File | Stability | Update Frequency | +|------|------|-----------|------------------| +| **Tier 0** | `PROJECT-ESSENCE.md` | High | Quarterly / Major version | +| **Tier 1** | `ARCHITECTURE.md` | Medium | Monthly / Sprint | +| **Tier 2** | `DECISIONS.md` | Low | Per decision change | +| **Tier 3** | `DYNAMICS.md` | Dynamic | As needed (issues, incidents) | + +### Reading Order (Recommended) + +``` +1. PROJECT-ESSENCE.md ← Start here (1-2 min read) +2. ARCHITECTURE.md ← If working across components +3. DECISIONS.md ← If changing established patterns +4. DYNAMICS.md ← If something feels wrong +``` + +--- + +## πŸ”§ How to Use This Knowledge + +### 1. Session Start Protocol +``` +β–‘ Read PROJECT-ESSENCE.md (always) +β–‘ Scan DYNAMICS.md for active issues +β–‘ Read ARCHITECTURE.md if working across subprojects +β–‘ Proceed with dynamic code exploration +``` + +### 2. Dynamic Code Exploration +This knowledge is a **starting point**, not a replacement for reading code: +- Use `grep` and `find_path` to locate actual implementations +- Verify knowledge against current code state +- Update knowledge if you find drift (see Maintenance section) + +### 3. Decision Validation +Before changing established patterns: +``` +β–‘ Check DECISIONS.md for existing decisions +β–‘ If decision exists: follow it or explicitly propose change +β–‘ If new decision needed: document after implementation +``` + +--- + +## πŸ”„ When to Update This Knowledge + +### Update PROJECT-ESSENCE.md when: +- Project purpose or scope fundamentally changes +- New major capability is added +- Core user workflow changes + +### Update ARCHITECTURE.md when: +- New component/subproject added +- Component responsibilities shift +- Data flow changes significantly +- API contracts change + +### Update DECISIONS.md when: +- A new design decision is made (especially if non-obvious) +- An existing decision is revisited/changed +- A trade-off is resolved differently + +### Update DYNAMICS.md when: +- New issue discovered that blocks normal workflow +- Workaround found for existing issue +- Issue is resolved +- Temporary constraint is added/removed + +--- + +## ⚠️ Important Principles + +1. **Knowledge is a guide, not truth** β€” Always verify against actual code +2. **Update responsibly** β€” Stale knowledge is worse than no knowledge +3. **Keep it high-level** β€” Details belong in code comments +4. **Trust dynamic exploration** β€” Use tools to find current state + +--- + +## πŸ“š File Reference + +- [Project Essence](references/PROJECT-ESSENCE.md) β€” What this project is and why +- [Architecture](references/ARCHITECTURE.md) β€” How components fit together +- [Decisions](references/DECISIONS.md) β€” Key design decisions and rationale +- [Dynamics](DYNAMICS.md) β€” Active issues, workarounds, temporary constraints +- [Maintenance Guide](meta/MAINTENANCE.md) β€” How to maintain this knowledge base + +--- + +## πŸ”— Integration with AGENTS.md + +This skill complements `AGENTS.md` in the project root: + +| File | Purpose | Who writes | +|------|---------|------------| +| `AGENTS.md` | Operational rules, commands, style | Project maintainers | +| `.ai-context/` | Pre-generated knowledge | System / Auto-generated | + +Both should be read at session start. `AGENTS.md` tells you **how to work**, `.ai-context` tells you **what the project is**. + +--- + +*Generated by ai-context-generator skill* diff --git a/AGENTS.MD b/AGENTS.MD new file mode 100644 index 0000000..9904ad6 --- /dev/null +++ b/AGENTS.MD @@ -0,0 +1,28 @@ +# AGENTS.md + +> Project guide for coding agents. Keep this file focused on stable, high-level knowledge. Volatile details go in `.ai-context/`. + +## .ai-context/ Directory + +The `.ai-context/` folder contains supplementary documents that are **more likely to change** as the project evolves: + +| File | Content | +|------|---------| +| [`references/ARCHITECTURE.md`](.ai-context/references/ARCHITECTURE.md) | Detailed component relationships, API dependencies, and design rationale | +| [`DYNAMICS.md`](.ai-context/DYNAMICS.md) | Current known issues, workarounds, and open TODOs | + +### When to Update .ai-context/ + +Update files in `.ai-context/` when: + +1. **Architecture changes** β€” New components removed, APIs added/removed, or data flow modified +2. **New known issues discovered** β€” During development or testing, if you find a bug or limitation that isn't obvious from the code +3. **API dependency changes** β€” New cortex-mem-service endpoints required, or existing ones deprecated +4. **Design decisions revisited** β€” Key tradeoffs re-evaluated (e.g., switching `ownsCompaction` from `false` to `true`) + +**Do NOT update .ai-context/ for**: +- Minor refactors, variable renames, or code formatting +- Dependency version bumps (patch/minor) +- Documentation typos or wording improvements + +Keep `.ai-context/` focused on information that would **meaningfully change how a coding agent understands or works with the project**.