
Knowledge Graph
- 3 installs
- 318 repo stars
- Updated June 22, 2026
- giuseppe-trisciuoglio/developer-kit-claude-code
Persist a JSON knowledge graph of codebase analysis and agent discoveries so findings, patterns, and APIs are reused across sessions.
About
Maintains a persistent JSON knowledge graph that caches agent discoveries and codebase analysis to avoid redundant exploration. A developer uses it to remember patterns, components, and APIs and validate task dependencies across sessions.
- Stores discoveries at docs/specs/[ID-feature]/knowledge-graph.json
- Caches results, validates task contracts, and queries existing patterns/components/APIs
Knowledge Graph by the numbers
- 3 all-time installs (skills.sh)
- Ranked #13,657 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit-claude-code --skill knowledge-graphAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 3 |
|---|---|
| repo stars | ★ 318 |
| Last updated | June 22, 2026 |
| Repository | giuseppe-trisciuoglio/developer-kit-claude-code ↗ |
What it does
Persist a JSON knowledge graph of codebase analysis and agent discoveries so findings, patterns, and APIs are reused across sessions.
Files
Knowledge Graph Skill
Overview
Persistent JSON storage that caches agent discoveries and codebase analysis. Remember findings across sessions, validate task dependencies, query patterns/components/APIs, skip redundant exploration.
Location: docs/specs/[ID-feature]/knowledge-graph.json
---
When to Use
1. Cache results - Before launching expensive codebase analysis, check if findings are already stored 2. Remember findings - After agent exploration, persist discoveries for future use 3. Reuse discoveries - Query existing context to maintain consistency across tasks 4. Validate dependencies - Check if required components/APIs exist before implementing 5. Look up previous work - Find what patterns, components, or APIs were already discovered
---
Instructions
read-knowledge-graph
Read existing Knowledge Graph or initialize empty structure:
Read file_path="docs/specs/001/knowledge-graph.json"Returns full KG content. If file missing, returns empty structure and creates on first update.
---
query-knowledge-graph
Query specific sections: components, patterns, apis, integration-points, all
Read file_path="docs/specs/001/knowledge-graph.json"Filter results by section and process in-memory.
---
update-knowledge-graph
# 1. Read existing
Read file_path="docs/specs/001/knowledge-graph.json"
# 2. Deep-merge updates (arrays append by ID, objects preserve existing)
# 3. Update timestamp
Write file_path="docs/specs/001/knowledge-graph.json" content="<merged JSON>"Deep-merge rules:
- Arrays: append new items, deduplicate by
idfield - Objects: preserve existing keys, add/update new keys
- Always update
metadata.updated_atto current ISO timestamp
Complete JSON example for update:
{
"metadata": {
"spec_id": "001-hotel-search",
"created_at": "2026-03-14T10:30:00Z",
"updated_at": "2026-03-23T10:00:00Z",
"version": "1.0.0"
},
"patterns": {
"architectural": [
{
"id": "pat-001",
"name": "Repository Pattern",
"convention": "Extend JpaRepository<Entity, ID>",
"files": ["src/main/java/**/repository/*Repository.java"]
}
]
},
"components": {
"services": [
{
"id": "comp-svc-001",
"name": "HotelService",
"location": "src/main/java/com/example/hotel/service/HotelService.java",
"type": "service",
"methods": [{"name": "searchHotels", "returns": "List<HotelDTO>"}]
}
]
}
}---
validate-against-knowledge-graph
# 1. Read KG
Read file_path="docs/specs/001/knowledge-graph.json"
# 2. Check KG contains required IDs
# 3. Verify actual files exist
Grep pattern="src/**/HotelRepository.java"Report satisfied dependencies and missing components.
---
validate-contract
# 1. Read KG and task expectations
Read file_path="docs/specs/001/knowledge-graph.json"
Glob pattern="src/**/ExpectedFile.java"
Grep pattern="class ExpectedClass|interface ExpectedInterface"
# 2. Match expectations against KG.provides
# 3. Report satisfied/unsatisfied contracts---
extract-provides
# 1. Find implementation files
Glob pattern="src/**/*.java"
# 2. Extract symbols
Grep pattern="^(public|protected)? (class|interface|enum) " output_mode="content"
# 3. Classify by directory: /entity/ → entity, /service/ → service, /repository/ → repository
# 4. Update KG.provides with {task_id, file, symbols, type, implemented_at}---
aggregate-knowledge-graphs
# 1. Find all KG files
Glob pattern="docs/specs/*/knowledge-graph.json"
# 2. Read each, extract patterns.architectural and patterns.conventions
# 3. Write merged .global-knowledge-graph.json
Write file_path="docs/specs/.global-knowledge-graph.json" content="<aggregated>"---
Schema Structure
knowledge-graph.json
├── metadata (spec_id, created_at, updated_at, version, analysis_sources)
├── codebase_context (project_structure, technology_stack)
├── patterns (architectural[], conventions[])
├── components (controllers[], services[], repositories[], entities[], dtos[])
├── provides[] ({ task_id, file, symbols[], type, implemented_at })
├── apis (internal[], external[])
└── integration_points[]Complete schema with field definitions: See references/schema.md
---
Error Handling
| Scenario | Handling |
|---|---|
| File not found | Return empty KG; creates on first update |
| Invalid JSON | Raise error; offer to recreate from analysis |
| Merge conflicts | Deep-merge preserves existing, adds new with timestamps |
| Write failure | Log error; continue without caching (non-blocking) |
Update workflow: 1. Read: Read → docs/specs/[ID]/knowledge-graph.json 2. Validate update JSON structure 3. Deep-merge updates into KG object 4. Write: Write → same path 5. Verify write succeeded
---
Best Practices
Before expensive operations:
- Query KG first to check for cached analysis
- If fresh (< 7 days), skip redundant exploration
- Offer user choice: use cached or re-explore
After discoveries:
- Update KG immediately after agent analysis completes
- Include source agent/timestamp in metadata
- Batch similar updates, avoid per-operation writes
Freshness guidelines:
- < 7 days: Fresh, safe to use
- 7-30 days: Consider regenerating
- > 30 days: Stale, re-analysis recommended
---
Examples
Cache Agent Discoveries (Complete Workflow)
# Step 1: Check existing KG
Read file_path="docs/specs/001/knowledge-graph.json"
# Step 2: Analyze codebase (agent task)
Glob pattern="src/main/java/**/*.java"
Grep pattern="public (class|interface) " output_mode="content"
# Step 3: Build update with discoveries
Write file_path="docs/specs/001/knowledge-graph.json" content="{
\"metadata\": {
\"spec_id\": \"001-hotel-search\",
\"created_at\": \"2026-03-14T10:30:00Z\",
\"updated_at\": \"2026-03-23T10:00:00Z\",
\"version\": \"1.0.0\",
\"analysis_sources\": [{\"agent\": \"general-code-explorer\", \"timestamp\": \"2026-03-23T10:00:00Z\"}]
},
\"patterns\": {
\"architectural\": [{
\"id\": \"pat-001\",
\"name\": \"Repository Pattern\",
\"convention\": \"Extend JpaRepository<Entity, ID>\"
}]
},
\"components\": {
\"services\": [{
\"id\": \"comp-svc-001\",
\"name\": \"HotelService\",
\"location\": \"src/main/java/com/example/hotel/service/HotelService.java\",
\"type\": \"service\"
}],
\"repositories\": [{
\"id\": \"comp-repo-001\",
\"name\": \"HotelRepository\",
\"location\": \"src/main/java/com/example/hotel/repository/HotelRepository.java\",
\"type\": \"repository\"
}]
}
}"Validate Task Dependencies
# Read KG and task requirements
Read file_path="docs/specs/001/knowledge-graph.json"
# Verify components exist in codebase
Grep pattern="src/main/java/com/example/hotel/repository/HotelRepository.java"
Grep pattern="src/main/java/com/example/hotel/service/HotelService.java"
# Report validation result
# If all found: "All dependencies satisfied, proceed with implementation"
# If missing: "Warning: HotelService not found. Create it first?"Query for Context Before Task Generation
# Load KG to get cached context
Read file_path="docs/specs/001/knowledge-graph.json"
# Present summary to user:
# "Found cached analysis (2 days old):
# - Patterns: Repository Pattern, Service Layer
# - Components: HotelService, HotelController
# - Conventions: naming with *Controller/*Service/*Repository
# Use cached context for task generation?"More examples: See references/query-examples.md
---
Constraints and Warnings
Critical Constraints:
- Read-only on source code; only creates/updates
knowledge-graph.json - Only reads/writes KG files from
docs/specs/[ID]/paths - Does NOT generate implementation code automatically
Limitations:
- Validation checks KG only; cannot verify actual codebase if KG outdated
- KG accuracy depends on freshness; re-explore if > 7 days old
- Cross-spec learning only via
aggregateoperation
Warnings:
- KG > 30 days old may not reflect current codebase state
- Validator may report false negatives if KG predates implementation
- Merge strategy preserves existing values; explicit overwrite required to replace
---
See Also
references/schema.md- Complete JSON schema with field definitionsreferences/query-examples.md- Query patterns and integration examplesreferences/integration-patterns.md- Command integration details
Knowledge Graph Integration Patterns
This document describes how to integrate the Knowledge Graph with Developer Kit commands.
Pattern 1: spec-to-tasks Integration
Phase 2.5: Check Knowledge Graph
Location: After Phase 2 (Requirement Extraction), Before Phase 3 (Codebase Analysis)
Goal: Check if cached codebase analysis exists from previous runs
Implementation:
1. Check if knowledge-graph.json exists in spec folder
2. If exists and recent (< 7 days old):
- Load patterns, components, APIs from KG
- Ask user via AskUserQuestion:
"Found cached analysis from X days ago:
- Y architectural patterns
- Z components (N controllers, M services, K repositories)
Use cached analysis or re-explore codebase?"
3. If user chooses cached:
- Load full KG into context
- Skip Phase 3 (Codebase Analysis)
- Proceed directly to Phase 4 (Task Decomposition) with KG context
4. If user chooses re-explore or KG doesn't exist:
- Proceed to Phase 3 (launch agents)
- After agents complete, update KG (see Phase 3.5 below)User Interaction Example:
Found cached codebase analysis from 3 days ago:
- 2 architectural patterns (Repository, Service Layer)
- 5 components (1 controller, 2 services, 2 repositories)
- 3 REST endpoints documented
The analysis is fresh and reliable.
Options:
- "Use cached analysis" (recommended - faster)
- "Re-explore codebase" (always get latest)Phase 3.5: Update Knowledge Graph
Location: After Phase 3 (Codebase Analysis), Before Phase 4 (Task Decomposition)
Goal: Persist agent discoveries into the Knowledge Graph for future reuse
Implementation:
1. Extract structured findings from agent analysis output:
- Parse agent's comprehensive analysis
- Map findings to KG schema sections:
* patterns.architectural: Design patterns discovered
* patterns.conventions: Coding conventions identified
* components: Code components (controllers, services, repositories, etc.)
* apis.internal: REST endpoints and API structure
* apis.external: External service integrations
* integration_points: Databases, caches, message queues, etc.
2. Construct KG update object following the schema:
{
"metadata": {
"spec_id": "[from spec folder]",
"updated_at": "[current ISO timestamp]",
"analysis_sources": [
{
"agent": "[agent-type-used]",
"timestamp": "[current ISO timestamp]",
"focus": "codebase analysis for task generation"
}
]
},
"patterns": { /* ... */ },
"components": { /* ... */ },
"apis": { /* ... */ }
}
3. Call knowledge-graph skill to update:
/knowledge-graph update [spec-folder] [update-object] "[agent-name]"
4. Log and report:
"Knowledge Graph updated:
- X architectural patterns documented
- Y coding conventions identified
- Z components catalogued (N controllers, M services, K repositories)
- Q API endpoints documented
- R integration points mapped
Saved to: docs/specs/[ID]/knowledge-graph.json"
5. Verify update:
- Read back updated KG to confirm write succeeded
- Check metadata was updated correctly
- If write failed, log warning but continue (non-blocking)Example Agent Output → KG Mapping:
Agent Analysis:
"Found Repository Pattern: All repositories extend JpaRepository<EntityType, ID>
Found Service Layer: Business logic in @Service classes
Found: HotelService at src/main/java/.../HotelService.java
Found: HotelRepository at src/main/java/.../HotelRepository.java
Found: HotelController with 2 endpoints"
→ KG Update:
{
"patterns": {
"architectural": [
{
"id": "pat-001",
"name": "Repository Pattern",
"convention": "Extend JpaRepository<EntityType, ID>",
"files": ["**/repository/*Repository.java"]
},
{
"id": "pat-002",
"name": "Service Layer",
"convention": "@Service annotation on business logic"
}
]
},
"components": {
"services": [
{
"id": "comp-svc-001",
"name": "HotelService",
"location": "src/main/java/.../HotelService.java"
}
],
"repositories": [
{
"id": "comp-repo-001",
"name": "HotelRepository",
"location": "src/main/java/.../HotelRepository.java"
}
]
}
}Important Note: If user chose to use cached KG in Phase 2.5, skip this phase entirely and proceed directly to Phase 4.
---
Pattern 2: task-implementation Integration
T-3.5: Pre-load from Knowledge Graph
Location: After dependency checks, before implementation work starts
Goal: Check if existing specification has cached analysis to inform implementation
For task execution (`--task=` parameter):
1. Load task file → extract spec_id from task frontmatter
2. Check if knowledge-graph.json exists in spec folder
3. If KG exists:
a. Query KG for task-relevant information:
/knowledge-graph query [spec-folder] components
/knowledge-graph query [spec-folder] apis
/knowledge-graph query [spec-folder] patterns
b. Validate task dependencies against KG:
/knowledge-graph validate [spec-folder] {
components: [/* from task Technical Context */],
apis: [/* from task Technical Context */]
}
c. Present validation results to user:
"From previous analysis of related feature:
- X services available
- Y endpoints documented
- Z patterns established
Task validation: ✅ All dependencies exist
Proceed with implementation?"
d. Load KG context into working memory for implementation phaseFor spec-driven task generation (`devkit.spec-to-tasks`):
1. Resolve the spec folder
2. Check if knowledge-graph.json exists
3. If KG exists:
a. Load and summarize key findings
b. Reuse it automatically if fresh; ask only if borderline stale
c. Feed patterns/components/APIs into task decomposition
4. If no KG exists or it is stale:
- Run fresh codebase explorationUser Interaction Example:
Found related specification '001-hotel-search' with cached analysis:
- Repository Pattern (extend JpaRepository)
- Service Layer (@Service classes)
- 2 existing services
- 1 existing repository
Use these patterns for consistency?
Options:
- "Yes, use patterns" (recommended - consistency)
- "No, explore fresh" (different approach needed)Phase 3.5 / T-6.5: Update Knowledge Graph
Location:
- After
spec-to-taskscodebase analysis - After
task-implementation, viaspec-quality
Goal: Persist new discoveries from exploration into Knowledge Graph
When to Execute:
- During
spec-to-taskswhen a spec folder is being analyzed - During
task-implementationonce files are implemented andprovidescan be extracted
Implementation:
1. Resolve the spec folder from the current command context
- If no spec folder is available, skip this phase
2. Extract new findings from agent exploration:
- Patterns discovered that weren't in KG
- New components identified
- New integration points found
- Updates to existing patterns/conventions
3. Update Knowledge Graph:
/knowledge-graph update [spec-folder] [update-object] "spec-to-tasks explorer agent"
Map agent findings to KG schema sections
4. Log update:
"Knowledge Graph updated with exploration findings:
- X new patterns documented
- Y new components catalogued
- Z integration points mapped
Updated: docs/specs/[ID]/knowledge-graph.json"
5. Handle failures gracefully:
- If write fails: Log warning but continue (non-blocking)
- Note: "Failed to update Knowledge Graph, continuing without caching"Example: New Discovery → KG Update:
Agent Discovery:
"Found new PaymentController with 2 endpoints: /api/v1/payments, /api/v1/refunds
Found new integration: Stripe API for payment processing"
→ KG Update:
{
"components": {
"controllers": [
{
"id": "comp-ctrl-002",
"name": "PaymentController",
"location": "src/main/java/.../PaymentController.java",
"endpoints": [
{ "method": "POST", "path": "/api/v1/payments" },
{ "method": "POST", "path": "/api/v1/refunds" }
]
}
]
},
"apis": {
"internal": [
{ "id": "api-int-003", "path": "/api/v1/payments", "method": "POST" },
{ "id": "api-int-004", "path": "/api/v1/refunds", "method": "POST" }
],
"external": [
{
"id": "api-ext-002",
"name": "Stripe API",
"base_url": "https://api.stripe.com/v1",
"authentication": "API Key"
}
]
},
"integration_points": [
{
"id": "int-003",
"name": "Stripe Integration",
"type": "external-api",
"technology": "Stripe",
"used_by_components": ["PaymentController"]
}
]
}---
Complete Data Flow
Full Workflow: New Feature Development
1. User creates specification via devkit.brainstorm
↓
2. spec-to-tasks Phase 1-2: Analyze specification
↓
3. spec-to-tasks Phase 2.5: Check Knowledge Graph
├─ KG exists? → Load and present summary
└─ KG missing/expired → Proceed to Phase 3
↓
4. spec-to-tasks Phase 3: Launch architect/explorer agents
↓
5. Agent Analysis → Structured Output
↓
6. spec-to-tasks Phase 3.5: Update Knowledge Graph
├─ Parse agent findings
├─ Map to KG schema
└─ Write to docs/specs/[ID]/knowledge-graph.json
↓
7. spec-to-tasks Phase 4: Generate tasks with KG context
↓
8. Task files created with Technical Context from KG
↓
9. User runs: /devkit.task-implementation --task="docs/specs/[id]/tasks/TASK-001.md"
↓
10. task-implementation T-3.5: Pre-load from Knowledge Graph
├─ Load task dependencies
├─ Query KG for components/APIs
└─ Validate: "UserService exists? API endpoint available?"
↓
11. task-implementation T-4: Implementation
↓
12. task-implementation T-6.5: spec-quality updates Knowledge Graph
├─ Extract provides from implemented files
└─ Persist them to KG
↓
13. Implementation Complete---
Query Flow Examples
Example 1: Task Validation
Task file says: "Use HotelRepository for database access"
task-implementation T-3.5: Validate against KG
→ Query: "components.repositories.HotelRepository"
KG Response:
{
"id": "comp-repo-001",
"name": "HotelRepository",
"location": ".../HotelRepository.java",
"extends": "JpaRepository<Hotel, Long>"
}
Validation: ✅ Component exists
→ Proceed with implementationExample 2: Pattern Discovery for Task Generation
spec-to-tasks Phase 4: Generate tasks for "Add booking feature"
Query KG: "patterns.architectural"
KG Response:
[
{ "name": "Repository Pattern", "convention": "Extend JpaRepository" },
{ "name": "Service Layer", "convention": "@Service classes" }
]
→ Generated Tasks:
- TASK-001: Create BookingRepository (extend JpaRepository)
- TASK-002: Create BookingService (@Service annotation)Example 3: API Integration
Task: "Integrate with payment gateway"
Query KG: "apis.external"
KG Response:
[
{
"name": "Stripe Integration",
"base_url": "https://api.stripe.com/v1",
"authentication": "API Key",
"endpoints": [...]
}
]
→ Technical Context in task:
"Use existing Stripe integration pattern from PaymentService
Follow same authentication: API Key in header
Use endpoint: /v1/charges for creating payments"---
Error Handling and Edge Cases
KG Not Found
User runs: /knowledge-graph query docs/specs/001/ components
Response: Empty result (graceful degradation)
Log: "No existing knowledge graph, will create on first update"
Action: Continue with empty KG structureInvalid JSON
User runs: /knowledge-graph read docs/specs/001/
Error: "Knowledge graph corrupted at docs/specs/001/knowledge-graph.json"
Ask User: "Recreate from codebase analysis?"
Options:
- "Yes, recreate" (run agent analysis)
- "No, cancel" (abort operation)Validation Failures
Query: /knowledge-graph validate ... {
components: ["UserService"]
}
Response:
{
"valid": false,
"errors": ["Component UserService not found"],
"suggestions": ["Available: HotelService, BookingService"]
}
Action: Present to user, ask how to proceedStale Knowledge Graph
Check: metadata.updated_at = "2026-02-01"
Current date: "2026-03-14"
Age: 41 days (> 30 day threshold)
Warning: "Knowledge graph is 41 days old and may be stale.
Consider refreshing with fresh codebase analysis."---
Performance Considerations
Load Once, Query Multiple Times
Bad Pattern: Load KG for each query
/kg query ... components (Reads file)
/kg query ... patterns (Reads file again)
/kg query ... apis (Reads file again)Good Pattern: Load once, cache in memory
/kg read ... (Reads file once)
→ Use cached KG for multiple queriesUse Specific Filters
Bad Pattern: Query all, filter manually
/kg query ... all
→ Manually filter through 100 componentsGood Pattern: Query with specific filter
/kg query ... components { category: "services" }
→ Returns only services (faster)Check Freshness Before Use
1. Read metadata.updated_at
2. Calculate age: now - updated_at
3. If > 7 days: Warn user "KG may be stale"
4. Offer: "Refresh analysis or proceed with cache?"---
Best Practices
1. Always validate requirements against KG before implementation 2. Update KG incrementally after each significant analysis 3. Log all KG operations for debugging and audit trail 4. Handle failures gracefully - never block on KG errors 5. Document new discoveries clearly when updating KG 6. Review KG age before relying on it for critical decisions
---
Migration from Manual Documentation
Before Knowledge Graph
Task File (manual):
## Technical Context
Based on codebase analysis:
- Use Repository pattern
- Extend JpaRepository
- Follow existing service structureAfter Knowledge Graph
Task File (KG-powered):
## Technical Context
From Knowledge Graph (docs/specs/001/knowledge-graph.json):
- Components: HotelRepository (exists), BookingService (exists)
- Patterns: Repository Pattern (extend JpaRepository), Service Layer (@Service)
- APIs: GET /api/v1/hotels (available)
- Validation: ✅ All dependencies verified---
Troubleshooting
Issue: KG Not Loading
Symptom: Commands report "Knowledge graph not found"
Diagnosis: 1. Check file exists: ls docs/specs/[ID]/knowledge-graph.json 2. Check file is valid JSON: cat docs/specs/[ID]/knowledge-graph.json | python3 -m json.tool
Solution: If file doesn't exist, first update will create it. If invalid, recreate from analysis.
Issue: Validation False Positives
Symptom: Validator reports component missing but it exists
Diagnosis: 1. Check KG age: metadata.updated_at 2. If KG is old (> 7 days), it may be outdated
Solution: Refresh KG by re-running codebase analysis
Issue: Update Failures
Symptom: "Cannot write knowledge graph" error
Diagnosis: 1. Check file permissions: ls -la docs/specs/[ID]/ 2. Check disk space: df -h
Solution: Fix permissions or free disk space. Operation continues without caching.
---
See Also
../SKILL.md- Main skill definitionschema.md- Complete JSON schema referencequery-examples.md- Query patterns and usage examples
For command integration, see:
/plugins/developer-kit-core/commands/specs/devkit.spec-to-tasks.md(Phase 2.5, 3.5)/plugins/developer-kit-core/commands/specs/devkit.task-implementation.md(T-3.5, T-6.5)/plugins/developer-kit-core/commands/specs/devkit.spec-quality.md(Phase 4)
Knowledge Graph Query Examples
This document provides practical examples of querying the Knowledge Graph for common use cases.
Query Patterns
Pattern 1: Find All Components by Type
Use Case: Need to know what services exist in the codebase.
Query: /knowledge-graph query docs/specs/001-hotel-search/ components
Filter: { category: "services" }
Result:
[
{
"id": "comp-svc-001",
"name": "HotelService",
"location": "src/main/java/.../HotelService.java",
"methods": [
{ "name": "searchHotels", "returns": "List<HotelDTO>" }
],
"dependencies": ["HotelRepository"]
},
{
"id": "comp-svc-002",
"name": "BookingService",
"location": "src/main/java/.../BookingService.java",
"dependencies": ["BookingRepository", "HotelService"]
}
]
Usage in task generation:
"Use existing HotelService.searchHotels() method for searching"Pattern 2: Find Architectural Patterns
Use Case: Generate tasks following existing patterns.
Query: /knowledge-graph query docs/specs/001-hotel-search/ patterns
Filter: { category: "architectural" }
Result:
[
{
"id": "pat-001",
"name": "Repository Pattern",
"convention": "All repositories extend JpaRepository<EntityType, ID>",
"examples": [
{
"file": "src/main/java/.../HotelRepository.java",
"line": 8,
"snippet": "public interface HotelRepository extends JpaRepository<Hotel, Long>"
}
]
},
{
"id": "pat-002",
"name": "Service Layer Pattern",
"convention": "Business logic in @Service classes",
"files": ["src/main/java/**/service/*Service.java"]
}
]
Usage in task generation:
Generate tasks:
- TASK-001: Create BookingRepository extending JpaRepository
- TASK-002: Create BookingService with @Service annotationPattern 3: Find REST Endpoints
Use Case: Need to integrate with existing API.
Query: /knowledge-graph query docs/specs/001-hotel-search/ apis
Filter: { type: "internal" }
Result:
[
{
"id": "api-int-001",
"path": "/api/v1/hotels",
"method": "GET",
"controller": "HotelController",
"parameters": [
{ "name": "city", "type": "String", "required": true }
],
"response": "List<HotelDTO>"
},
{
"id": "api-int-002",
"path": "/api/v1/hotels/{id}",
"method": "GET",
"controller": "HotelController",
"response": "HotelDTO"
}
]
Usage in task:
"Integration: Call GET /api/v1/hotels?city={city} to search hotels"Pattern 4: Validate Component Existence
Use Case: Task references a component, verify it exists.
Query: /knowledge-graph validate docs/specs/001-hotel-search/
Requirements: {
components: ["comp-repo-001", "comp-svc-missing"],
apis: ["api-int-001"]
}
Result:
{
"valid": false,
"errors": [
"Component comp-svc-missing not found in codebase"
],
"warnings": [
"API api-int-001 not found, may need implementation"
]
}
Action: Alert user before implementing task
"Warning: Task references UserService but it doesn't exist. Create first?"Pattern 5: Find Naming Conventions
Use Case: Generate code following project conventions.
Query: /knowledge-graph query docs/specs/001-hotel-search/ patterns
Filter: { category: "conventions", subcategory: "naming" }
Result:
[
{
"id": "conv-001",
"category": "naming",
"rule": "Controller classes end with 'Controller'",
"examples": ["HotelController", "BookingController"]
},
{
"id": "conv-002",
"category": "naming",
"rule": "Service classes end with 'Service'",
"examples": ["HotelService", "BookingService"]
},
{
"id": "conv-003",
"category": "naming",
"rule": "Repository interfaces end with 'Repository'",
"examples": ["HotelRepository", "BookingRepository"]
}
]
Usage in task:
"Create PaymentService (naming convention: *Service)"
"Create PaymentRepository interface (naming convention: *Repository)"Pattern 6: Find Integration Points
Use Case: Need to know external systems integrated.
Query: /knowledge-graph query docs/specs/001-hotel-search/ integration-points
Result:
[
{
"id": "int-001",
"name": "Database Integration",
"type": "database",
"technology": "PostgreSQL",
"used_by_components": ["HotelRepository", "BookingRepository"]
},
{
"id": "int-002",
"name": "Cache Layer",
"type": "cache",
"technology": "Redis",
"purpose": "Cache hotel search results",
"used_by_components": ["HotelService"]
}
]
Usage in task:
"Store search results in Redis cache (existing integration)"
"Use PostgreSQL for persistence (existing integration)"Pattern 7: Find External APIs
Use Case: Task needs to call external service.
Query: /knowledge-graph query docs/specs/001-hotel-search/ apis
Filter: { type: "external" }
Result:
[
{
"id": "api-ext-001",
"name": "Supplier Integration API",
"base_url": "https://api.supplier.com/v1",
"authentication": "API Key",
"endpoints": [
{
"method": "POST",
"path": "/hotels/availability",
"purpose": "Check real-time availability",
"used_by": "SupplierService"
}
]
}
]
Usage in task:
"Use existing SupplierService pattern for payment gateway integration"
"Follow same authentication pattern: API Key in header"Integration Examples
Example 1: spec-to-tasks - Load Cached Analysis
# Phase 2.5 of spec-to-tasks
Action: Check if knowledge graph exists
Command: /knowledge-graph read docs/specs/001-hotel-search/
If KG exists and recent (< 7 days):
Present to user:
"Found cached analysis from 3 days ago:
- 3 services discovered
- 2 architectural patterns
- 5 REST endpoints
Use cached analysis or re-explore codebase?"
If user chooses cached:
Query KG for all patterns and components
Skip Phase 3 (Codebase Analysis)
Proceed directly to Phase 4 (Task Decomposition)
If user chooses re-explore or KG doesn't exist:
Proceed to Phase 3 (launch agents)Example 2: spec-to-tasks - Update After Analysis
# Phase 3.5 of spec-to-tasks
Agent completed analysis:
"Found Repository Pattern: All repositories extend JpaRepository
Found Service Layer: Business logic in @Service classes
Components: HotelService, HotelRepository, HotelController"
Action: Update knowledge graph
Command: /knowledge-graph update docs/specs/001-hotel-search/ {
patterns: {
architectural: [
{
id: "pat-001",
name: "Repository Pattern",
convention: "Extend JpaRepository<Entity, ID>"
},
{
id: "pat-002",
name: "Service Layer",
convention: "@Service annotation on business logic"
}
]
},
components: {
services: [
{
id: "comp-svc-001",
name": "HotelService",
location: "src/main/java/.../HotelService.java"
}
],
repositories: [
{
id: "comp-repo-001",
name": "HotelRepository",
location: "src/main/java/.../HotelRepository.java"
}
],
controllers: [
{
id: "comp-ctrl-001",
name": "HotelController",
location: "src/main/java/.../HotelController.java"
}
]
}
} "general-software-architect agent"
Result: knowledge-graph.json updated with discoveries
Log: "Knowledge graph updated: 2 patterns, 3 components added"Example 3: task-implementation - Validate Task
# T-3.5 of task-implementation
Task file specifies:
Technical Context:
- Use HotelRepository for database access
- Call HotelService.searchHotels()
- Follow Repository pattern
Action: Validate against knowledge graph
Command: /knowledge-graph validate docs/specs/001-hotel-search/ {
components: ["comp-repo-001", "comp-svc-001"],
patterns: [{ name: "Repository Pattern" }]
}
Result:
{
valid: true,
errors: [],
warnings: []
}
→ Proceed with implementation, all dependencies exist
Alternative if validation fails:
{
valid: false,
errors: ["Component comp-svc-001 not found"],
warnings: []
}
→ Alert user: "HotelService not found in codebase. Create it first or update task?"Example 4: spec-to-tasks - Enrich Task Generation Context
# Phase 2.5 of spec-to-tasks
Spec folder: `docs/specs/001-hotel-search/`
Action: Check if existing spec has KG
Query: /knowledge-graph query docs/specs/001-hotel-search/ all
Result summary:
"From previous analysis of hotel-search:
Components: 2 controllers, 3 services, 2 repositories
Patterns: Repository, Service Layer, DTO
APIs: 5 endpoints, 1 external integration
Conventions: Naming, testing with JUnit, Mockito for mocks"
Use this summary to enrich task generation:
"Found related feature 'hotel-search' with cached analysis.
Use existing patterns (Repository, Service) for consistency?"
If yes:
Generate tasks following discovered patterns
Technical Context: "Follow HotelService pattern for BookingService"
If no:
Proceed with full codebase explorationQuery Syntax Reference
Basic Syntax
/knowledge-graph [action] [spec-folder] [parameters]
Actions:
read - Load entire KG
query - Search KG with filters
update - Add/merge findings
validate - Check requirements against KGQuery Parameters
Query Types:
components - Search for code components
patterns - Search for patterns and conventions
apis - Search for API endpoints
integration-points - Search for integrations
all - Search everything
Filters: JSON object with key-value pairs
{ category: "services" }
{ type: "internal" }
{ name: "Hotel*" } (wildcard search)Update Parameters
Updates: Partial KG object to merge
{
patterns: { architectural: [...] }
}
Source: Description of what provided updates
"general-code-explorer agent"
"Manual update after implementation"Performance Tips
1. Load Once, Query Multiple Times
Bad: Load KG for each query
/kg query ... components
/kg query ... patterns
/kg query ... apis
Good: Load KG once, query in-memory
/kg read ...
→ Use cached KG for multiple queries2. Use Specific Filters
Bad: Query all then filter manually
/kg query ... all
→ Manually filter through 100 components
Good: Query with specific filter
/kg query ... components { category: "services" }
→ Returns only services3. Check Freshness First
Before using KG:
1. Read metadata.updated_at
2. Calculate age: now - updated_at
3. If > 7 days: Warn user "KG may be stale"
4. Offer to refresh analysisError Handling
File Not Found
Query: /knowledge-graph read docs/specs/999-missing/
Result:
{
error: "Knowledge graph not found",
message: "No existing knowledge graph at docs/specs/999-missing/knowledge-graph.json",
action: "Will create new KG on first update"
}
Handling: Continue with empty KG, will be created on updateInvalid JSON
Query: /knowledge-graph read docs/specs/001-corrupted/
Result:
{
error: "Invalid JSON",
message: "Knowledge graph file is corrupted",
action: "Offer to recreate from codebase analysis"
}
Handling: Ask user "Recreate KG from codebase analysis?"Validation Failures
Query: /knowledge-graph validate ... { components: ["missing-id"] }
Result:
{
valid: false,
errors: ["Component missing-id not found"],
warnings: [],
suggestions: [
"Available components: comp-001, comp-002, comp-003"
]
}
Handling: Alert user, suggest available alternativesAdvanced Queries
Pattern 8: Find Component Dependencies
Goal: Find all components that depend on a specific component.
Query: /knowledge-graph query docs/specs/001-hotel-search/ components
Filter: { depends_on: "HotelRepository" }
Result:
[
{
"id": "comp-svc-001",
"name": "HotelService",
"dependencies": ["HotelRepository"]
},
{
"id": "comp-svc-002",
"name": "BookingService",
"dependencies": ["HotelRepository"]
}
]
Usage: "If modifying HotelRepository, also update HotelService and BookingService"Pattern 9: Find Similar Features
Goal: Find other features that used similar patterns.
Query: /knowledge-graph query docs/specs/001-hotel-search/ patterns
Filter: { name: "Repository Pattern" }
Result: Pattern found in hotel-search spec
Then: Search other specs for same pattern
For each spec in docs/specs/*/:
/knowledge-graph query docs/specs/[ID]/ patterns
Filter: { name: "Repository Pattern" }
Usage: "See how other features implemented Repository Pattern"Pattern 10: Trace API Usage
Goal: Find which components use a specific API.
Query: /knowledge-graph query docs/specs/001-hotel-search/ apis
Filter: { path: "/api/v1/hotels" }
Result: API endpoint found
Then: Find components using it
/kg query ... components
Filter: { uses_apis: ["api-int-001"] }
Usage: "If changing /api/v1/hotels endpoint, update HotelController"Best Practices
1. Always check freshness before using KG for critical decisions 2. Validate requirements against KG before implementation 3. Query specific sections rather than loading entire KG 4. Update KG incrementally after each analysis, not in one batch 5. Log all KG operations for debugging and audit trail
Troubleshooting
KG Returns Empty Results
Cause: KG not yet populated or query too specific
Solution: 1. Check if KG exists: /knowledge-graph read [spec-folder] 2. If empty, run codebase analysis first 3. If query-specific, try broader filter
Validation Shows False Positives
Cause: KG out of sync with actual codebase
Solution: 1. Check KG age: metadata.updated_at 2. If > 7 days old, refresh with agent analysis 3. After code changes, update KG
KG Too Large
Cause: Accumulated too much data over time
Solution: 1. Archive old KG versions 2. Split by feature area 3. Remove outdated/discovered components
Knowledge Graph JSON Schema
This document describes the complete JSON schema for the Knowledge Graph file.
File Location
docs/specs/[ID-feature]/knowledge-graph.jsonComplete Schema
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Knowledge Graph",
"description": "Persistent storage for codebase analysis discoveries",
"type": "object",
"required": ["metadata"],
"properties": {
"metadata": {
"type": "object",
"description": "Metadata about the knowledge graph",
"required": ["spec_id", "created_at", "updated_at", "version"],
"properties": {
"spec_id": {
"type": "string",
"description": "Specification identifier (e.g., '001-hotel-search-aggregation')"
},
"feature_name": {
"type": "string",
"description": "Feature name in kebab-case"
},
"created_at": {
"type": "string",
"format": "date-time",
"description": "ISO 8601 timestamp when KG was created"
},
"updated_at": {
"type": "string",
"format": "date-time",
"description": "ISO 8601 timestamp when KG was last updated"
},
"version": {
"type": "string",
"description": "Semantic version of the KG format (e.g., '1.0.0')"
},
"analysis_sources": {
"type": "array",
"description": "List of agents/sources that contributed to this KG",
"items": {
"type": "object",
"properties": {
"agent": {
"type": "string",
"description": "Agent name (e.g., 'general-code-explorer')"
},
"timestamp": {
"type": "string",
"format": "date-time"
},
"focus": {
"type": "string",
"description": "What the agent analyzed (e.g., 'similar features')"
}
}
}
}
}
},
"codebase_context": {
"type": "object",
"description": "High-level context about the codebase",
"properties": {
"project_structure": {
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": ["layered", "modular", "hexagonal", "clean"],
"description": "Architecture type"
},
"root_directories": {
"type": "array",
"items": { "type": "string" }
},
"build_system": {
"type": "string",
"enum": ["maven", "gradle", "npm", "pip", "composer"]
},
"test_framework": {
"type": "string"
}
}
},
"technology_stack": {
"type": "object",
"properties": {
"language": {
"type": "string",
"enum": ["java", "typescript", "python", "php", "javascript"]
},
"framework": {
"type": "string"
},
"version": {
"type": "string"
},
"dependencies": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": { "type": "string" },
"version": { "type": "string" }
}
}
}
}
}
}
},
"patterns": {
"type": "object",
"properties": {
"architectural": {
"type": "array",
"description": "Architectural patterns found in codebase",
"items": {
"type": "object",
"required": ["id", "name"],
"properties": {
"id": {
"type": "string",
"description": "Unique pattern identifier (e.g., 'pat-001')"
},
"name": {
"type": "string",
"description": "Pattern name (e.g., 'Repository Pattern')"
},
"description": {
"type": "string"
},
"files": {
"type": "array",
"items": { "type": "string" },
"description": "Glob patterns for files using this pattern"
},
"convention": {
"type": "string",
"description": "How the pattern is implemented in this codebase"
},
"examples": {
"type": "array",
"items": {
"type": "object",
"properties": {
"file": { "type": "string" },
"line": { "type": "integer" },
"snippet": { "type": "string" }
}
}
}
}
}
},
"conventions": {
"type": "array",
"description": "Coding conventions and standards",
"items": {
"type": "object",
"required": ["id", "category", "rule"],
"properties": {
"id": {
"type": "string"
},
"category": {
"type": "string",
"enum": ["naming", "testing", "documentation", "error-handling"]
},
"rule": {
"type": "string",
"description": "The convention rule"
},
"examples": {
"type": "array",
"items": { "type": "string" }
}
}
}
}
}
},
"components": {
"type": "object",
"properties": {
"controllers": {
"type": "array",
"items": { "$ref": "#/definitions/component" }
},
"services": {
"type": "array",
"items": { "$ref": "#/definitions/component" }
},
"repositories": {
"type": "array",
"items": { "$ref": "#/definitions/component" }
},
"entities": {
"type": "array",
"items": { "$ref": "#/definitions/component" }
},
"dtos": {
"type": "array",
"items": { "$ref": "#/definitions/component" }
}
}
},
"provides": {
"type": "array",
"description": "What tasks provide after implementation (for contract validation)",
"items": {
"type": "object",
"required": ["task_id", "file", "symbols", "type"],
"properties": {
"task_id": {
"type": "string",
"description": "Task identifier (e.g., 'TASK-001')"
},
"file": {
"type": "string",
"description": "Full file path relative to project root"
},
"symbols": {
"type": "array",
"items": { "type": "string" },
"description": "Symbols (classes, interfaces, functions) provided by this file"
},
"type": {
"type": "string",
"enum": ["entity", "value-object", "service", "repository", "controller", "function", "module", "class", "interface", "dto"],
"description": "Type of component"
},
"implemented_at": {
"type": "string",
"format": "date-time",
"description": "ISO 8601 timestamp when this was implemented"
}
}
}
},
"apis": {
"type": "object",
"properties": {
"internal": {
"type": "array",
"description": "Internal REST/API endpoints",
"items": {
"type": "object",
"required": ["id", "path", "method"],
"properties": {
"id": { "type": "string" },
"name": { "type": "string" },
"type": { "type": "string", "enum": ["rest", "graphql", "grpc"] },
"path": { "type": "string" },
"method": {
"type": "string",
"enum": ["GET", "POST", "PUT", "DELETE", "PATCH"]
},
"controller": { "type": "string" },
"line": { "type": "integer" },
"parameters": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": { "type": "string" },
"type": { "type": "string" },
"required": { "type": "boolean" }
}
}
},
"response": { "type": "string" },
"errors": {
"type": "array",
"items": {
"type": "object",
"properties": {
"status": { "type": "integer" },
"condition": { "type": "string" }
}
}
}
}
}
},
"external": {
"type": "array",
"description": "External APIs/integrations",
"items": {
"type": "object",
"required": ["id", "base_url"],
"properties": {
"id": { "type": "string" },
"name": { "type": "string" },
"type": { "type": "string", "enum": ["rest", "soap", "graphql"] },
"base_url": { "type": "string" },
"authentication": { "type": "string" },
"endpoints": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": { "type": "string" },
"method": { "type": "string" },
"path": { "type": "string" },
"purpose": { "type": "string" },
"used_by": { "type": "string" }
}
}
}
}
}
}
}
},
"integration_points": {
"type": "array",
"description": "Integration points with external systems",
"items": {
"type": "object",
"required": ["id", "name", "type"],
"properties": {
"id": { "type": "string" },
"name": { "type": "string" },
"type": {
"type": "string",
"enum": ["database", "cache", "message-queue", "external-api"]
},
"technology": { "type": "string" },
"purpose": { "type": "string" },
"configuration": { "type": "string" },
"used_by_components": {
"type": "array",
"items": { "type": "string" }
}
}
}
},
"testing": {
"type": "object",
"properties": {
"framework": { "type": "string" },
"structure": { "type": "string" },
"conventions": {
"type": "array",
"items": { "type": "string" }
},
"examples": {
"type": "array",
"items": {
"type": "object",
"properties": {
"file": { "type": "string" },
"tests": {
"type": "array",
"items": { "type": "string" }
}
}
}
}
}
},
"architecture_decisions": {
"type": "object",
"description": "Key architectural decisions with rationale",
"additionalProperties": {
"type": "object",
"properties": {
"decision": { "type": "string" },
"rationale": { "type": "string" },
"alternatives_considered": {
"type": "array",
"items": { "type": "string" }
}
}
}
},
"validation_rules": {
"type": "array",
"description": "Custom validation rules for this codebase",
"items": {
"type": "object",
"required": ["id", "rule", "severity"],
"properties": {
"id": { "type": "string" },
"rule": { "type": "string" },
"checker": { "type": "string" },
"severity": {
"type": "string",
"enum": ["error", "warning", "info"]
}
}
}
},
"quality_metrics": {
"type": "object",
"properties": {
"code_coverage": { "type": "string" },
"test_count": { "type": "integer" },
"component_count": { "type": "integer" },
"last_analysis": {
"type": "string",
"format": "date-time"
}
}
}
},
"definitions": {
"component": {
"type": "object",
"required": ["id", "name", "location", "type"],
"properties": {
"id": {
"type": "string",
"description": "Unique component identifier (e.g., 'comp-ctrl-001')"
},
"name": {
"type": "string",
"description": "Component class/file name"
},
"location": {
"type": "string",
"description": "Full file path relative to project root"
},
"type": {
"type": "string",
"enum": ["controller", "service", "repository", "entity", "dto", "config"]
},
"responsibilities": {
"type": "array",
"items": { "type": "string" }
},
"endpoints": {
"type": "array",
"description": "For controllers: list of endpoints",
"items": {
"type": "object",
"properties": {
"method": { "type": "string" },
"path": { "type": "string" },
"line": { "type": "integer" },
"description": { "type": "string" }
}
}
},
"methods": {
"type": "array",
"description": "For services: list of key methods",
"items": {
"type": "object",
"properties": {
"name": { "type": "string" },
"line": { "type": "integer" },
"description": { "type": "string" },
"returns": { "type": "string" }
}
}
},
"dependencies": {
"type": "array",
"items": { "type": "string" },
"description": "Component names this component depends on"
},
"uses_components": {
"type": "array",
"items": { "type": "string" },
"description": "Component IDs this component uses"
}
}
}
}
}Example: Complete Knowledge Graph
See the complete example in the architect's output (available in the command history). Here's a minimal example:
{
"metadata": {
"spec_id": "001-hotel-search-aggregation",
"feature_name": "hotel-search-aggregation",
"created_at": "2026-03-14T10:30:00Z",
"updated_at": "2026-03-14T15:45:00Z",
"version": "1.0.0",
"analysis_sources": [
{
"agent": "general-code-explorer",
"timestamp": "2026-03-14T10:30:00Z",
"focus": "similar features analysis"
}
]
},
"patterns": {
"architectural": [
{
"id": "pat-001",
"name": "Repository Pattern",
"convention": "All repositories extend JpaRepository",
"files": ["src/main/java/**/repository/*Repository.java"]
}
],
"conventions": [
{
"id": "conv-001",
"category": "naming",
"rule": "Controller classes end with 'Controller'"
}
]
},
"components": {
"controllers": [
{
"id": "comp-ctrl-001",
"name": "HotelController",
"location": "src/main/java/com/example/hotel/controller/HotelController.java",
"type": "controller"
}
],
"services": [],
"repositories": [],
"entities": [],
"dtos": []
},
"apis": {
"internal": [],
"external": []
}
}Schema Evolution
This schema may evolve over time. The version field in metadata tracks the format version.
Versioning rules:
- MAJOR: Breaking changes to schema structure
- MINOR: New optional fields added
- PATCH: Bug fixes to documentation
When evolving the schema: 1. Update the version field 2. Document changes in CHANGELOG 3. Provide migration path for existing KGs 4. Maintain backwards compatibility when possible