
Knowledge Graph
- 1.4k installs
- 311 repo stars
- Updated June 22, 2026
- giuseppe-trisciuoglio/developer-kit
knowledge-graph provides documented workflows for Manage persistent Knowledge Graph for specifications. Provides read, query, update, and validation capabilities for codebase analysis caching. Use when: spec-to
About
The knowledge-graph skill manage persistent Knowledge Graph for specifications. Provides read, query, update, and validation capabilities for codebase analysis caching. Use when: spec-to-tasks needs to cache/reuse codebase analysis, task-implementation needs to validate task dependencies or contracts, spec-quality needs to synchronize provides, or any command needs to query existing patterns/components/APIs. Reduces redundant codebase exploration by caching agent discoveries. # Knowledge Graph Skill ## Overview The Knowledge Graph (KG) is a persistent JSON file that stores discoveries from codebase analysis, eliminating redundant exploration and enabling task validation. **Location**: `docs/specs/[ID-feature]/knowledge-graph.json` **Key Benefits:** - ✅ Avoid re-exploring already-analyzed codebases - ✅ Validate task dependencies against actual codebase state - ✅ Share discoveries across team members - ✅ Accelerate task generation with cached context ## When to Use Use this skill when: 1. **spec-to-tasks needs to cache/reuse codebase analysis** - Store agent discoveries for future reuse 2. **task-implementation needs to validate task dependencies and contracts** - Check if required.
- ✅ Avoid re-exploring already-analyzed codebases
- ✅ Validate task dependencies against actual codebase state
- ✅ Share discoveries across team members
- ✅ Accelerate task generation with cached context
- **spec-to-tasks needs to cache/reuse codebase analysis** - Store agent discoveries for future reuse
Knowledge Graph by the numbers
- 1,368 all-time installs (skills.sh)
- +61 installs in the week ending Jul 28, 2026 (Skillselion tracking)
- Ranked #65 of 923 Databases skills by installs in the Skillselion catalog
- Security screen: LOW risk (skills.sh audit)
- Data as of Jul 28, 2026 (Skillselion catalog sync)
knowledge-graph capabilities & compatibility
- Capabilities
- ✅ avoid re exploring already analyzed codebases · ✅ validate task dependencies against actual code · ✅ share discoveries across team members · ✅ accelerate task generation with cached context · **spec to tasks needs to cache/reuse codebase an
- Use cases
- documentation
What knowledge-graph says it does
# Knowledge Graph Skill ## Overview The Knowledge Graph (KG) is a persistent JSON file that stores discoveries from codebase analysis, eliminating redundant exploration and enabling task validation.
**spec-to-tasks needs to cache/reuse codebase analysis** - Store agent discoveries for future reuse 2.
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill knowledge-graphAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 1.4k |
|---|---|
| repo stars | ★ 311 |
| Security audit | 3 / 3 scanners passed |
| Last updated | June 22, 2026 |
| Repository | giuseppe-trisciuoglio/developer-kit ↗ |
How do I use knowledge-graph for the task described in its SKILL.md triggers?
Manage persistent Knowledge Graph for specifications. Provides read, query, update, and validation capabilities for codebase analysis caching. Use when: spec-to-tasks needs to cache/reuse codebase an.
Who is it for?
Teams invoking knowledge-graph when the user request matches documented triggers and prerequisites.
Skip if: Skip when cached docs are missing, the request is a negative trigger, or another sibling skill owns the workflow.
When should I use this skill?
Manage persistent Knowledge Graph for specifications. Provides read, query, update, and validation capabilities for codebase analysis caching. Use when: spec-to-tasks needs to cache/reuse codebase analysis, task-implemen
What you get
Step-by-step guidance grounded in knowledge-graph documentation and reference files.
- Knowledge graph JSON file
- Updated patterns and tech stack records
By the numbers
- Knowledge graph schema version 1.0
- Empty graph includes 3 top-level sections: metadata, codebase_context, patterns
Files
Knowledge Graph Skill
Overview
The Knowledge Graph (KG) is a persistent JSON file that stores discoveries from codebase analysis, eliminating redundant exploration and enabling task validation.
Location: docs/specs/[ID-feature]/knowledge-graph.json
Key Benefits:
- ✅ Avoid re-exploring already-analyzed codebases
- ✅ Validate task dependencies against actual codebase state
- ✅ Share discoveries across team members
- ✅ Accelerate task generation with cached context
When to Use
Use this skill when:
1. spec-to-tasks needs to cache/reuse codebase analysis - Store agent discoveries for future reuse 2. task-implementation needs to validate task dependencies and contracts - Check if required components exist before implementing 3. Any command needs to query existing patterns/components/APIs - Retrieve cached codebase context 4. Reducing redundant codebase exploration - Avoid re-analyzing already-explored code
Trigger phrases:
- "Load knowledge graph"
- "Query knowledge graph"
- "Update knowledge graph"
- "Validate against knowledge graph"
- "Check if component exists"
- "Find existing patterns"
Instructions
Available Operations
1. read-knowledge-graph - Load and parse KG for a specification
- Input: Path to spec folder (e.g.,
docs/specs/001-feature/) - Output: KG object with metadata, patterns, components, APIs
2. query-knowledge-graph - Query specific sections (components, patterns, APIs)
- Input: Spec folder, query type, optional filters
- Output: Filtered results matching criteria
3. update-knowledge-graph - Update KG with new discoveries
- Input: Spec folder, updates (partial KG), source description
- Output: Merged KG with new findings
4. validate-against-knowledge-graph - Validate task dependencies against KG
- Input: Spec folder, requirements (components, APIs, patterns)
- Output: Validation report with errors/warnings
5. validate-contract - Validate provides/expects between tasks
- Input: Spec folder, expects (files + symbols), completed dependencies
- Output: Satisfied/unsatisfied expectations report
6. extract-provides - Extract symbols from implemented files
- Input: Array of file paths
- Output: Array of provides with file, symbols, type
7. aggregate-knowledge-graphs - Merge patterns from all specs
- Input: Project root path
- Output: Global KG with deduplicated patterns
See references/query-examples.md for detailed usage examples.
Examples
Input/Output Examples
Read Knowledge Graph:
Input: /knowledge-graph read docs/specs/001-hotel-search/
Output: {
metadata: { spec_id: "001-hotel-search", version: "1.0" },
patterns: { architectural: [...], conventions: [...] },
components: { controllers: [...], services: [...]}
}Query Components:
Input: /knowledge-graph query docs/specs/001-hotel-search/ components {"category": "services"}
Output: [{ id: "comp-svc-001", name: "HotelSearchService", type: "service"}]Update Knowledge Graph:
Input: /knowledge-graph update docs/specs/001-hotel-search/ {
patterns: { architectural: [{ name: "Repository Pattern"}] }
}
Output: "Added 1 pattern to knowledge graph"Validate Dependencies:
Input: /knowledge-graph validate docs/specs/001-hotel-search/ {
components: ["comp-repo-001"]
}
Output: { valid: true, errors: [], warnings: [] }See references/examples.md for comprehensive workflow examples.
KG Schema Reference
See references/schema.md for complete JSON schema with examples.
Integration Patterns
See references/integration-patterns.md for detailed integration with Developer Kit commands.
Error Handling
See references/error-handling.md for comprehensive error handling strategies and recovery procedures.
Performance Considerations
See references/performance.md for optimization strategies and performance characteristics.
Security
See references/security.md for security considerations, threat mitigation, and best practices.
Best Practices
When to Query KG: Before codebase analysis, task generation, dependency validation
When to Update KG: After agent discoveries, component implementation, pattern discovery
KG Freshness:
- < 7 days: Fresh
- 7-30 days: Stale, warn user
- > 30 days: Very stale, offer regeneration
See references/performance.md and references/security.md for detailed best practices.
Constraints and Warnings
Critical Constraints
- Source-Code Safe Operations: Does NOT modify source code files. Only creates/updates
knowledge-graph.jsonfiles. - Path Validation: Only reads/writes KG files from
docs/specs/[ID]/paths. - No Automatic Code Generation: Caches analysis results, does NOT generate implementation code.
Limitations
- Validation Scope: Checks components exist in KG, but cannot verify if they exist in actual codebase if KG is outdated
- Freshness Dependency: KG accuracy depends on how recently it was updated
- Single-Spec First: Each KG is primarily specific to a single specification
- File Size: KG files can grow large (>1MB) for complex specifications
See references/error-handling.md and references/security.md for complete constraints and warnings.
Reference Files
- schema.md - Complete JSON schema
- query-examples.md - Query patterns
- integration-patterns.md - Command integration
- error-handling.md - Error handling guide
- performance.md - Performance optimization
- security.md - Security considerations
- examples.md - Practical examples
Error Handling - Knowledge Graph
Comprehensive error handling strategies and behaviors for Knowledge Graph operations.
Error Types
1. File Not Found
Scenario: KG file doesn't exist at expected path.
Behavior:
- Return empty KG structure
- Message: "No existing knowledge graph, will create new"
- Action: Continue with empty KG, will be created on first update
Empty KG Structure:
{
"metadata": {
"spec_id": null,
"feature_name": null,
"created_at": null,
"updated_at": null,
"version": "1.0",
"analysis_sources": []
},
"codebase_context": {
"project_structure": {},
"technology_stack": []
},
"patterns": {
"architectural": [],
"conventions": []
},
"components": {
"controllers": [],
"services": [],
"repositories": [],
"entities": [],
"dtos": []
},
"provides": [],
"apis": {
"internal": [],
"external": []
},
"integration_points": []
}When this occurs:
- First time running spec-to-tasks for a spec
- KG was deleted
- Incorrect path provided
User impact: None (normal operation)
---
2. Invalid JSON
Scenario: KG file exists but contains invalid JSON.
Behavior:
- Raise error
- Message: "Knowledge graph corrupted at {path}"
- Action: Ask user: "Recreate from codebase analysis?"
Detection:
try:
kg_data = json.load(kg_file)
except json.JSONDecodeError as e:
raise KnowledgeGraphError(
f"Knowledge graph corrupted at {path}: {str(e)}"
)Recovery options: 1. Recreate from codebase analysis 2. Restore from backup (if available) 3. Manual repair (advanced users)
User impact: High (cannot use existing KG)
---
3. Merge Conflicts
Scenario: Concurrent updates to KG cause merge conflicts.
Behavior:
- Preserve existing values, add new with timestamps
- Message: "Merged X new findings into existing knowledge graph"
Merge Strategy:
- Arrays: Append new items (check for duplicates by ID)
- Objects: Deep merge, preserve existing keys
- Metadata: Always update timestamps and sources
Example merge:
def merge_kg(existing, updates):
# Arrays: append if not duplicate
for key in ['patterns', 'components', 'apis']:
for item in updates[key]:
if item not in existing[key]:
existing[key].append(item)
# Objects: deep merge
for key in ['codebase_context']:
existing[key].update(updates[key])
# Metadata: always update
existing['metadata']['updated_at'] = datetime.now().isoformat()
return existingDetection:
- Duplicate IDs in arrays
- Conflicting values for same key
Prevention:
- Use atomic file writes
- Add source tracking to updates
- Use optimistic locking
---
4. Write Failure
Scenario: Cannot write KG file (permissions, disk full, etc.).
Behavior:
- Log error, continue without caching
- Message: "Cannot write knowledge graph, continuing without cache"
Detection:
try:
with open(kg_path, 'w') as f:
json.dump(kg_data, f, indent=2)
except (IOError, OSError) as e:
logger.error(f"Cannot write knowledge graph: {str(e)}")
# Continue without caching
return NoneImpact:
- No caching benefits
- Must re-explore codebase next time
- Performance degradation
Recovery:
- Fix permissions
- Free disk space
- Retry write operation
---
5. Path Validation Errors
Scenario: Invalid path provided for KG operations.
Behavior:
- Raise error
- Message: "Invalid knowledge graph path: {path}"
Validation rules:
- Path must start with
docs/specs/ - Path must not contain
..(parent directory) - Path must be within project root
Example:
def validate_kg_path(path):
# Must start with docs/specs/
if not path.startswith("docs/specs/"):
raise ValueError(f"Invalid KG path: {path}")
# No path traversal
if ".." in path:
raise ValueError(f"Path traversal not allowed: {path}")
# Must resolve within project
real_path = Path(path).resolve()
project_root = Path.cwd()
if not str(real_path).startswith(str(project_root)):
raise ValueError(f"Path outside project: {path}")
return real_path---
6. Validation Errors
Scenario: Validation requirements reference non-existent components.
Behavior:
- Return validation report with errors
- Message: "Validation failed: {errors}"
Error types:
- Component missing (Error)
- API missing (Warning)
- Pattern mismatch (Warning)
- Convention violation (Warning)
Example:
{
"errors": [
"Component comp-svc-missing not found in codebase"
],
"warnings": [
"API api-int-001 not found, may need implementation"
],
"valid": false
}Recovery:
- Implement missing components
- Update requirements to match existing code
- Update KG with new components after implementation
---
7. Contract Validation Errors
Scenario: Expected symbols not found in completed dependencies.
Behavior:
- Return validation report with unsatisfied expectations
- Message: "Contract validation failed: N unsatisfied expectations"
Example:
{
"satisfied": [
{
"expectation": "Search entity with symbols [Search, SearchStatus]",
"provided_by": "TASK-001"
}
],
"unsatisfied": [
{
"expectation": "SearchId value object",
"provided_by": "None",
"reason": "No completed dependency provides SearchId"
}
],
"valid": false
}Recovery:
- Implement missing provides in current task
- Reorder tasks to satisfy dependencies
- Update expectations to match actual provides
---
8. Extraction Errors
Scenario: Cannot extract symbols from source files.
Behavior:
- Log warning, continue with partial extraction
- Message: "Could not extract symbols from {file}: {error}"
Causes:
- Unsupported file type
- Parse errors (malformed code)
- File permission issues
Example:
try:
symbols = extract_symbols_from_file(file_path)
except ParseError as e:
logger.warning(f"Could not extract symbols from {file_path}: {e}")
symbols = []Impact:
- Incomplete provides extraction
- May miss dependencies
- Manual intervention may be needed
---
Error Recovery Strategies
Retry Logic
When to retry:
- Transient failures (network, file locks)
- Write failures
- Temporary permission issues
Retry configuration:
MAX_RETRIES = 3
RETRY_DELAY = 1 # seconds
def retry_on_failure(func):
for attempt in range(MAX_RETRIES):
try:
return func()
except TransientError as e:
if attempt == MAX_RETRIES - 1:
raise
time.sleep(RETRY_DELAY * (2 ** attempt)) # Exponential backoffFallback Behavior
When KG is unavailable: 1. Log warning 2. Continue without caching 3. Inform user of degraded performance 4. Offer to recreate KG
Example:
⚠️ Warning: Knowledge graph unavailable
Continuing without caching (performance may be degraded)
Would you like to recreate the knowledge graph from codebase analysis?Graceful Degradation
Principle: Fail gracefully, don't block workflow.
Examples:
- Context7 unavailable → Use codebase patterns
- KG stale → Warn user, continue with verification
- Validation fails → Report errors, don't stop workflow
- Write fails → Continue without caching
---
Error Messages
User-Friendly Messages
| Error | Message | Action |
|---|---|---|
| File not found | "No existing knowledge graph, will create new" | Continue (normal) |
| Invalid JSON | "Knowledge graph corrupted at {path}. Recreate from codebase?" | Ask user |
| Write failed | "Cannot write knowledge graph, continuing without cache" | Log and continue |
| Invalid path | "Invalid knowledge graph path: {path}" | Raise error |
| Validation failed | "Validation failed: N errors, M warnings" | Report and continue |
| Contract failed | "N unsatisfied expectations" | Report and continue |
| Extraction failed | "Could not extract symbols from {file}" | Log warning |
Error Severity Levels
| Level | When to Use | Example |
|---|---|---|
| Info | Normal operation | "Created new knowledge graph" |
| Warning | Non-critical issue | "Knowledge graph is stale (30 days old)" |
| Error | Operation failed | "Cannot write knowledge graph" |
| Critical | System broken | "Knowledge graph corrupted beyond repair" |
---
Logging Strategy
What to Log
Always log:
- All errors with context
- File operations (read, write, update)
- Validation results
- Merge operations
Sometimes log:
- Debug info in verbose mode
- Performance metrics
- Cache hit/miss ratios
Never log:
- Sensitive data (shouldn't be in KG anyway)
- User credentials
- Internal system details
Log Format
logger.info(f"Knowledge graph operation: {operation} on {path}")
logger.warning(f"Stale knowledge graph: {days} days old")
logger.error(f"Failed to write KG: {error}", exc_info=True)
logger.debug(f"KG validation result: {validation}")---
Error Prevention
Input Validation
Validate paths:
- Must start with
docs/specs/ - No path traversal (
..) - Within project root
Validate data:
- JSON structure valid
- Required fields present
- Data types correct
- Arrays don't have duplicates
Validate operations:
- User has read permissions
- User has write permissions (for updates)
- Disk space available
Atomic Operations
File writes:
- Write to temporary file first
- Rename to actual path (atomic on Unix)
- Cleanup temp files on failure
Example:
import tempfile
import os
def atomic_write(path, data):
# Write to temp file
temp_fd, temp_path = tempfile.mkstemp(
dir=os.path.dirname(path)
)
try:
with os.fdopen(temp_fd, 'w') as f:
json.dump(data, f, indent=2)
# Atomic rename
os.replace(temp_path, path)
except:
# Cleanup on failure
os.unlink(temp_path)
raiseIdempotent Operations
Design operations to be idempotent:
- Running update twice should not duplicate data
- Reading non-existent file returns empty KG (not error)
- Validation can be run multiple times safely
Example:
def update_kg(path, updates):
kg = read_kg(path) # Returns empty KG if not exists
merged = merge(kg, updates) # Idempotent merge
write_kg(path, merged)---
Error Handling Best Practices
1. Fail Fast, Fail Gracefully
- Detect errors early (input validation)
- Provide clear error messages
- Offer recovery options
- Don't crash the workflow
2. Log Context
- Always include context in error messages
- Log what operation was attempted
- Log what input was provided
- Log system state if relevant
3. Provide Recovery Options
- For transient errors: retry
- For user errors: provide guidance
- For system errors: offer workaround
- For data errors: suggest repair
4. Preserve Data
- Never lose existing data on error
- Use atomic writes
- Create backups before destructive operations
- Validate before overwriting
5. Inform User
- Always inform user of errors
- Explain impact of error
- Suggest next steps
- Don't hide errors silently
---
Testing Error Handling
Test Cases
1. File not found: Read non-existent KG → Returns empty KG 2. Invalid JSON: Read corrupted KG → Raises error 3. Write failure: Mock write failure → Continues without caching 4. Invalid path: Provide ../../etc/passwd → Raises error 5. Validation failure: Validate missing components → Returns errors 6. Concurrent updates: Simulate merge conflict → Merges correctly
Error Injection
def test_write_failure():
# Mock file write to fail
with mock.patch('builtins.open', side_effect=IOError):
result = write_kg(path, data)
# Should return None, not raise
assert result is None---
Summary
Error handling principles: 1. Validate inputs early 2. Provide clear error messages 3. Fail gracefully, don't block workflow 4. Offer recovery options 5. Log all errors with context 6. Use atomic operations 7. Preserve user data 8. Inform user of all errors
Key behaviors:
- File not found → Return empty KG (normal)
- Invalid JSON → Raise error, offer recovery
- Write failure → Log and continue
- Merge conflict → Deep merge, preserve both
- Validation failure → Report errors, continue
- Contract failure → Report unsatisfied expectations
Examples - Knowledge Graph
Practical examples of Knowledge Graph operations and workflows.
Example 1: Cache Agent Discoveries
Scenario: spec-to-tasks Phase 3.5 - Agent discovers Repository Pattern
Agent output:
Found Repository Pattern with JpaRepository convention
All repositories extend JpaRepository<Entity, ID>
Located in: src/main/java/com/example/repository/Update KG:
/knowledge-graph update docs/specs/001-hotel-search/ {
patterns: {
architectural: [
{
id: "pat-001",
name: "Repository Pattern",
category: "data-access",
convention: "All repositories extend JpaRepository<Entity, ID>",
location: "src/main/java/com/example/repository/",
discovered_at: "2026-03-14T10:30:00Z"
}
]
}
} "general-software-architect agent"Result:
docs/specs/001-hotel-search/knowledge-graph.jsonupdated with pattern discovery- Metadata updated with new analysis source
- Pattern can be queried in future operations
---
Example 2: Validate Task Dependencies
Scenario: task-implementation Task Mode - Task requires HotelRepository
Task: "Use HotelRepository to search hotels"
Validate:
/knowledge-graph validate docs/specs/001-hotel-search/ {
components: ["comp-repo-001"]
}Result:
{
"valid": true,
"errors": [],
"warnings": [],
"found": [
{
"id": "comp-repo-001",
"name": "HotelRepository",
"type": "repository",
"location": "src/main/java/com/hotels/search/repository/HotelRepository.java"
}
]
}Outcome: Task validated, proceed with implementation
---
Example 3: Query for Context
Scenario: spec-to-tasks Phase 4 - Generate tasks for new feature
Need: Generate tasks for "Add booking feature" using existing patterns
Query KG:
/knowledge-graph query docs/specs/001-hotel-search/ patternsResult:
[
{
"name": "Repository Pattern",
"convention": "Extend JpaRepository with Entity and ID types"
},
{
"name": "Service Layer",
"convention": "@Service classes with business logic"
},
{
"name": "DTO Pattern",
"convention": "Data Transfer Objects for API layer"
}
]Usage: Generate tasks following discovered patterns
---
Example 4: Contract Validation Failure
Scenario: Task expects SearchId value object, but no dependency provides it
Task Expects:
{
"expects": [
{
"file": "src/main/java/com/hotels/search/domain/valueobject/SearchId.java",
"symbols": ["SearchId"]
}
]
}Completed Dependencies:
[
{
"task_id": "TASK-001",
"provides": [
{
"file": "src/main/java/com/hotels/search/domain/entity/Search.java",
"symbols": ["Search", "SearchStatus", "SearchCriteria"]
}
]
}
]Validate Contract:
/knowledge-graph validate-contract docs/specs/001-hotel-search/ expects completed_dependenciesResult:
{
"satisfied": [
{
"expectation": "Search entity with symbols [Search, SearchStatus]",
"provided_by": "TASK-001"
}
],
"unsatisfied": [
{
"expectation": "SearchId value object",
"provided_by": "None",
"reason": "No completed dependency provides SearchId"
}
],
"valid": false
}Action: Implement SearchId in current task or reorder dependencies
---
Example 5: Extract Provides from Implementation
Scenario: Task completed, extract what was implemented
Files implemented:
[
"src/main/java/com/hotels/search/domain/entity/Search.java",
"src/main/java/com/hotels/search/domain/valueobject/SearchId.java"
]Extract:
/knowledge-graph extract-provides filesResult:
{
"provides": [
{
"file": "src/main/java/com/hotels/search/domain/entity/Search.java",
"symbols": ["Search", "SearchStatus"],
"type": "entity"
},
{
"file": "src/main/java/com/hotels/search/domain/valueobject/SearchId.java",
"symbols": ["SearchId"],
"type": "value-object"
}
]
}Usage: Persist to KG for future contract validation
---
Example 6: Aggregate Multiple KGs
Scenario: Create project-wide knowledge graph from all specs
Aggregate:
/knowledge-graph aggregate /path/to/project/rootProcess: 1. Scan all docs/specs/*/knowledge-graph.json files 2. Extract patterns.architectural and patterns.conventions 3. Deduplicate by pattern name 4. Write to docs/specs/.global-knowledge-graph.json
Result:
{
"metadata": {
"aggregated_at": "2026-03-14T15:00:00Z",
"project_root": "/path/to/project",
"contributing_specs": ["001-hotel-search", "002-booking", "003-payment"],
"total_patterns": 15
},
"patterns": {
"architectural": [
{
"name": "Repository Pattern",
"sources": ["001-hotel-search", "002-booking"],
"frequency": 2,
"first_seen": "2026-03-01T10:00:00Z",
"convention": "Extend JpaRepository<Entity, ID>"
},
{
"name": "Service Layer",
"sources": ["001-hotel-search", "002-booking", "003-payment"],
"frequency": 3,
"first_seen": "2026-03-01T10:00:00Z",
"convention": "@Service classes with @Transactional methods"
}
],
"conventions": [
{
"name": "Naming Convention",
"sources": ["001-hotel-search"],
"frequency": 1,
"examples": ["Repository suffix for repositories", "Service suffix for services"]
}
]
}
}---
Example 7: Query Specific Component Types
Scenario: Find all services in the codebase
Query:
/knowledge-graph query docs/specs/001-hotel-search/ components {"category": "services"}Result:
[
{
"id": "comp-svc-001",
"name": "HotelSearchService",
"type": "service",
"location": "src/main/java/com/hotels/search/service/HotelSearchService.java",
"annotations": ["@Service"],
"methods": ["searchHotels", "getHotelById"]
},
{
"id": "comp-svc-002",
"name": "BookingService",
"type": "service",
"location": "src/main/java/com/hotels/booking/service/BookingService.java",
"annotations": ["@Service"],
"methods": ["createBooking", "cancelBooking"]
}
]---
Example 8: Validate API Existence
Scenario: Task needs to call internal API /api/v1/hotels
Validate:
/knowledge-graph query docs/specs/001-hotel-search/ apis {
"type": "internal",
"path": "/api/v1/hotels"
}Result:
[
{
"id": "api-int-001",
"path": "/api/v1/hotels",
"method": "GET",
"type": "internal",
"controller": "HotelController",
"description": "Search hotels by criteria"
}
]Outcome: API exists, task can proceed
---
Example 9: Full Workflow Integration
Scenario: Complete spec-to-tasks workflow with KG
Phase 1: Exploration
Agent: Explore codebase for "hotel search aggregation"
Discovers:
- Repository Pattern
- Service Layer Pattern
- DTO PatternPhase 2: Update KG (after exploration)
/knowledge-graph update docs/specs/001-hotel-search/ {
patterns: {
architectural: [
{ "name": "Repository Pattern", "convention": "..." },
{ "name": "Service Layer", "convention": "..." },
{ "name": "DTO Pattern", "convention": "..." }
]
}
} "general-software-architect agent"Phase 3: Generate Tasks
Query KG for patterns → Generate tasks following patternsPhase 4: Validate Task Dependencies
/knowledge-graph validate docs/specs/001-hotel-search/ {
components: ["comp-repo-001", "comp-svc-001"]
}Phase 5: Implement Task
Implement feature following discovered patternsPhase 6: Extract Provides
/knowledge-graph extract-provides [
"src/main/java/.../HotelAggregateService.java",
"src/main/java/.../HotelAggregateRepository.java"
]Phase 7: Update KG with New Components
/knowledge-graph update docs/specs/001-hotel-search/ {
components: {
services: [...],
repositories: [...]
},
provides: [...]
} "task-implementation agent"---
Example 10: Stale Knowledge Detection
Scenario: KG is 45 days old, may be stale
Check:
/knowledge-graph read docs/specs/001-hotel-search/Result:
{
"metadata": {
"updated_at": "2026-02-01T10:00:00Z"
}
}Calculate age: 45 days old (> 30 day threshold)
Warning:
⚠️ Warning: Knowledge graph is stale (45 days old)
Codebase may have changed since last analysis.
Recommend regenerating from codebase.
Would you like to:
1. Proceed with stale knowledge (may have outdated info)
2. Regenerate knowledge graph from codebase (recommended)---
Example 11: Merge Conflict Resolution
Scenario: Two agents update KG concurrently
Agent A updates:
{
"patterns": {
"architectural": [
{ "name": "Repository Pattern", "convention": "JpaRepository" }
]
}
}Agent B updates:
{
"patterns": {
"architectural": [
{ "name": "Service Layer", "convention": "@Service" }
]
}
}Merge result (deep merge):
{
"patterns": {
"architectural": [
{ "name": "Repository Pattern", "convention": "JpaRepository" },
{ "name": "Service Layer", "convention": "@Service" }
]
},
"metadata": {
"updated_at": "2026-03-14T15:30:00Z",
"analysis_sources": [
{ "agent": "Agent A", "timestamp": "2026-03-14T15:00:00Z" },
{ "agent": "Agent B", "timestamp": "2026-03-14T15:30:00Z" }
]
}
}Message: "Merged 2 new findings into existing knowledge graph"
---
Example 12: Incremental Learning
Scenario: KG grows as project evolves
Day 1 (Initial):
{
"patterns": {
"architectural": [
{ "name": "Repository Pattern" }
]
}
}Day 7 (After feature additions):
{
"patterns": {
"architectural": [
{ "name": "Repository Pattern" },
{ "name": "Service Layer" },
{ "name": "DTO Pattern" }
]
}
}Day 30 (After new features):
{
"patterns": {
"architectural": [
{ "name": "Repository Pattern" },
{ "name": "Service Layer" },
{ "name": "DTO Pattern" },
{ "name": "Factory Pattern" },
{ "name": "Strategy Pattern" }
]
}
}Benefit: KG becomes more comprehensive over time, improving task generation and validation.
---
Example 13: Cross-Spec Learning
Scenario: Learn patterns across multiple specifications
Spec 001 (Hotel Search):
- Uses Repository Pattern
- Uses Service Layer
Spec 002 (Booking):
- Uses Repository Pattern
- Uses Service Layer
- Uses Unit of Work Pattern
Aggregated:
{
"patterns": {
"architectural": [
{
"name": "Repository Pattern",
"sources": ["001-hotel-search", "002-booking"],
"frequency": 2
},
{
"name": "Service Layer",
"sources": ["001-hotel-search", "002-booking"],
"frequency": 2
},
{
"name": "Unit of Work Pattern",
"sources": ["002-booking"],
"frequency": 1
}
]
}
}Usage: When generating tasks for Spec 003, recommend following most common patterns (Repository, Service Layer).
---
Example 14: Error Recovery
Scenario: KG file corrupted
Read attempt:
/knowledge-graph read docs/specs/001-hotel-search/Error:
❌ Error: Knowledge graph corrupted at docs/specs/001-hotel-search/knowledge-graph.json
Invalid JSON: Expecting ',' delimiter: line 42 column 5 (char 1023)Recovery options:
🔧 Recovery options:
1. Recreate from codebase analysis
- Re-run codebase exploration
- Generate new KG from scratch
- Estimated time: 2-5 minutes
2. Restore from backup (if available)
- Check git history for previous version
- Restore last known good version
3. Manual repair
- Edit JSON file to fix syntax
- Advanced users only
Which option would you like?---
Example 15: Performance Optimization
Scenario: KG file is 1.5 MB (too large)
Detection:
⚠️ Warning: Knowledge graph is large (1.5 MB)
Recommend splitting by feature area for better performance.
Current structure:
docs/specs/001-hotel-search/knowledge-graph.json (1.5 MB)
Suggested split:
docs/specs/001-hotel-search/kg-auth.json (300 KB)
docs/specs/001-hotel-search/kg-database.json (400 KB)
docs/specs/001-hotel-search/kg-api.json (500 KB)
docs/specs/001-hotel-search/kg-services.json (300 KB)
Would you like to split the knowledge graph?---
Summary
Common operations: 1. Cache discoveries: Update KG with agent findings 2. Validate dependencies: Check if components exist 3. Query patterns: Retrieve conventions for task generation 4. Validate contracts: Check if dependencies provide what's needed 5. Extract provides: Analyze implementation to capture what was built 6. Aggregate KGs: Create project-wide pattern summary 7. Detect staleness: Check if KG needs refresh
Key workflows:
- spec-to-tasks: Explore → Update KG → Query KG for patterns
- task-implementation: Validate dependencies → Implement → Extract provides → Update KG
- spec-quality: Sync provides from completed tasks
Error handling:
- File not found → Create new KG
- Invalid JSON → Offer to recreate
- Stale KG → Warn user, offer refresh
- Validation failure → Report errors, continue
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)
Performance Considerations - Knowledge Graph
Optimization strategies and performance characteristics for Knowledge Graph operations.
Performance Characteristics
Read Operations (read-knowledge-graph, query-knowledge-graph)
Time Complexity:
- JSON parsing: O(n) where n = file size
- Query filtering: O(m) where m = number of items in section
- Overall: O(n + m)
Typical Performance:
| KG Size | Read Time | Query Time |
|---|---|---|
| < 100 KB | < 10ms | < 5ms |
| 100-500 KB | 10-50ms | 5-20ms |
| 500 KB - 1 MB | 50-200ms | 20-100ms |
| > 1 MB | > 200ms | > 100ms |
Optimization:
- Cache parsed JSON in memory for session
- Use streaming JSON parser for large files
- Index frequently queried fields
---
Write Operations (update-knowledge-graph)
Time Complexity:
- Read existing KG: O(n)
- Deep merge: O(m) where m = size of updates
- JSON serialization: O(n + m)
- File write: O(n + m)
- Overall: O(n + m)
Typical Performance:
| Update Size | Write Time |
|---|---|
| < 10 KB | < 50ms |
| 10-50 KB | 50-200ms |
| 50-100 KB | 200-500ms |
| > 100 KB | > 500ms |
Optimization:
- Use atomic writes (temp file + rename)
- Compress JSON if very large
- Batch updates when possible
---
Validation Operations (validate-against-knowledge-graph, validate-contract)
Time Complexity:
- Load KG: O(n)
- Check components: O(c) where c = components to check
- Check APIs: O(a) where a = APIs to check
- File system checks: O(f) where f = files to verify
- Overall: O(n + c + a + f)
Typical Performance:
| Validation Type | Time |
|---|---|
| Component validation (10 items) | < 20ms |
| API validation (5 items) | < 15ms |
| Contract validation (5 files) | < 100ms |
| Full validation (100 items) | < 500ms |
Optimization:
- Batch file system checks
- Use glob patterns for file checks
- Cache file existence checks
---
Extraction Operations (extract-provides)
Time Complexity:
- Read files: O(f) where f = number of files
- Parse files: O(s) where s = total file size
- Extract symbols: O(s)
- Overall: O(f + s)
Typical Performance:
| Files | Total Size | Time |
|---|---|---|
| 1-5 files | < 100 KB | < 100ms |
| 5-20 files | 100-500 KB | 100-500ms |
| 20-50 files | 500 KB - 1 MB | 500ms-2s |
| > 50 files | > 1 MB | > 2s |
Optimization:
- Parallel file reading
- Use language-specific parsers (not regex)
- Cache extraction results
---
Optimization Strategies
1. Lazy Loading
Strategy: Only load KG when explicitly requested.
Implementation:
- Don't auto-load KG on skill invocation
- Load only when
read-knowledge-graphcalled - Close file handle immediately after reading
Benefit: Reduces memory usage and I/O for operations that don't need KG.
Example:
# Bad: Load KG on skill init
class KnowledgeGraphSkill:
def __init__(self):
self.kg = self.load_kg() # Always loads
# Good: Load on demand
class KnowledgeGraphSkill:
def read(self, path):
return self.load_kg(path) # Only loads when called---
2. Incremental Updates
Strategy: Merge changes, don't rewrite entire file.
Implementation:
- Use deep merge for updates
- Only write changed sections
- Track what changed
Benefit: Reduces I/O for small updates.
Example:
# Bad: Replace entire KG
def update(path, updates):
kg = {"metadata": {}, ...} # New empty KG
kg.update(updates) # Only updates
write(path, kg) # Writes everything
# Good: Merge into existing
def update(path, updates):
kg = read(path) # Read existing
merged = deep_merge(kg, updates) # Merge
write(path, merged) # Write merged---
3. Cache Invalidation
Strategy: Check timestamp, re-explore if KG is stale.
Freshness thresholds:
- < 7 days: Consider KG fresh, use cached analysis
- 7-30 days: KG getting stale, warn user
- > 30 days: KG very stale, offer to regenerate
Implementation:
def is_kg_fresh(kg_path):
kg = read_kg(kg_path)
if not kg['metadata']['updated_at']:
return False
updated = datetime.fromisoformat(kg['metadata']['updated_at'])
age = (datetime.now() - updated).days
if age < 7:
return True # Fresh
elif age < 30:
logger.warning(f"KG is {age} days old, consider updating")
return True # Still usable
else:
logger.error(f"KG is very stale ({age} days)")
return False # Should regenerateBenefit: Prevents using outdated analysis.
---
4. File Size Monitoring
Strategy: Monitor KG size, split if too large.
Thresholds:
- < 500 KB: Normal size, no action needed
- 500 KB - 1 MB: Consider optimization
- > 1 MB: Should split by feature area
Implementation:
def check_kg_size(kg_path):
size_kb = os.path.getsize(kg_path) / 1024
if size_kb > 1024: # > 1 MB
logger.warning(f"KG is large ({size_kb:.0f} KB), consider splitting")
return False
return TrueSplitting strategy:
- Split by feature area
- Create sub-KGs for each area
- Use aggregation for cross-feature queries
---
5. Memory Management
Strategy: Don't keep KG in memory when not needed.
Implementation:
- Load KG, process, unload
- Don't cache between operations
- Use streaming for large files
Example:
# Bad: Keep KG in memory
class KnowledgeGraphSkill:
def __init__(self):
self.cached_kg = None
def get_kg(self, path):
if not self.cached_kg:
self.cached_kg = load(path)
return self.cached_kg
# Good: Load on demand, don't cache
class KnowledgeGraphSkill:
def get_kg(self, path):
return load(path) # Always fresh---
6. Parallel Processing
Strategy: Use parallel operations for independent tasks.
Use cases:
- Extract provides from multiple files
- Validate multiple components
- Aggregate multiple KGs
Implementation:
from concurrent.futures import ThreadPoolExecutor
def extract_provides_parallel(files):
with ThreadPoolExecutor(max_workers=4) as executor:
results = executor.map(extract_provides, files)
return list(results)Benefit: Reduces wall-clock time for multi-file operations.
---
Performance Monitoring
Metrics to Track
| Metric | How to Measure | Target |
|---|---|---|
| Read latency | Time from request to parsed KG | < 100ms |
| Write latency | Time from update to disk write | < 500ms |
| Query latency | Time for filtered query | < 50ms |
| Validation time | Time for full validation | < 1s |
| File size | KB on disk | < 1000 KB |
| Cache hit rate | Queries served from cache | > 80% |
Monitoring Implementation
import time
from functools import wraps
def timed(operation):
@wraps(operation)
def wrapper(*args, **kwargs):
start = time.time()
result = operation(*args, **kwargs)
elapsed = (time.time() - start) * 1000 # ms
logger.info(f"{operation.__name__} took {elapsed:.0f}ms")
return result
return wrapper
@timed
def read_knowledge_graph(path):
# ... implementation
pass---
Performance Best Practices
1. Choose the Right Operation
| Need | Best Operation |
|---|---|
| Get everything | read-knowledge-graph |
| Get specific items | query-knowledge-graph |
| Add findings | update-knowledge-graph |
| Check dependencies | validate-against-knowledge-graph |
| Get what code provides | extract-provides |
2. Batch Operations
Bad:
for component in components:
kg = query_kg(path, "components", component) # N readsGood:
kg = read_kg(path) # 1 read
for component in components:
result = find_in_kg(kg, component) # Memory lookup3. Use Appropriate Granularity
Too coarse: Read entire KG for one component (slow) Too fine: Query KG 100 times for 100 components (slow) Just right: Read KG once, filter in memory
4. Optimize File I/O
- Use buffered I/O
- Minimize file system calls
- Use atomic writes
- Cache file reads when appropriate
5. Profile Before Optimizing
Don't guess, measure:
import cProfile
def profile_operation():
cProfile.run('knowledge_graph.update(path, data)')---
Performance Anti-Patterns
❌ Reading KG Multiple Times
# Bad: Read KG in a loop
for component in components:
kg = read_kg(path) # N reads
process(kg, component)✅ Read Once, Process Many
# Good: Read once, process many
kg = read_kg(path) # 1 read
for component in components:
process(kg, component) # Memory operations---
❌ Writing KG on Every Change
# Bad: Write after every small update
for item in items:
update_kg(path, item) # N writes✅ Batch Updates
# Good: Collect updates, write once
updates = collect_updates(items)
update_kg(path, updates) # 1 write---
❌ Not Caching File Checks
# Bad: Check file existence every time
def validate(file_path):
if not os.path.exists(file_path): # System call
raise Error(f"File not found: {file_path}")✌ Cache File Checks
# Good: Cache existence checks
_file_cache = {}
def validate(file_path):
if file_path not in _file_cache:
_file_cache[file_path] = os.path.exists(file_path)
if not _file_cache[file_path]:
raise Error(f"File not found: {file_path}")---
Scaling Considerations
When KG Grows Large
Symptoms:
- Read/write operations > 1s
- Memory usage high
- File size > 1 MB
Solutions: 1. Split by feature: Create separate KGs per feature area 2. Compress data: Use JSON compression 3. Use database: Move to SQLite/PostgreSQL 4. Incremental loading: Load only needed sections
Splitting Strategy
# Instead of one large KG:
docs/specs/001-feature/knowledge-graph.json # 2 MB
# Split into feature-specific KGs:
docs/specs/001-feature/kg-auth.json # 300 KB
docs/specs/001-feature/kg-database.json # 400 KB
docs/specs/001-feature/kg-api.json # 500 KBAggregation for Cross-Feature Queries
Use aggregate-knowledge-graphs to create project-wide summary:
# Creates: docs/specs/.global-knowledge-graph.json
# Contains: Patterns and conventions from all specs
# Updates: Run periodically (daily/weekly)---
Performance Testing
Test Cases
1. Cold read: Read KG from disk (not cached) 2. Warm read: Read KG from memory cache 3. Small update: Update < 10 items 4. Large update: Update > 100 items 5. Query: Filter 1000 items to 10 6. Validate: Check 100 components 7. Extract: Parse 50 files
Performance Benchmarks
Target performance:
- Read: < 100ms
- Write: < 500ms
- Query: < 50ms
- Validate: < 1s
- Extract: < 2s (50 files)
---
Summary
Key performance principles: 1. Lazy load KG (don't auto-load) 2. Incremental updates (merge, don't replace) 3. Cache invalidation (check freshness) 4. Monitor file size (split if > 1 MB) 5. Memory management (don't keep in memory) 6. Parallel processing (for independent tasks) 7. Batch operations (reduce I/O) 8. Profile before optimizing
Performance targets:
- Read: < 100ms
- Write: < 500ms
- Query: < 50ms
- Validate: < 1s
- Extract: < 2s (50 files)
- File size: < 1 MB
When to optimize:
- Operations exceed targets
- KG size > 1 MB
- User reports slowness
- Memory usage high
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
Security - Knowledge Graph
Security considerations and best practices for Knowledge Graph operations.
Core Security Principles
1. Path Validation
Principle: Only read KG from docs/specs/[ID]/ paths.
Why: Prevents path traversal attacks and unauthorized file access.
Implementation:
def validate_kg_path(path):
"""
Validate that KG path is within docs/specs/ directory.
"""
# Must start with docs/specs/
if not path.startswith("docs/specs/"):
raise ValueError(f"Invalid KG path: {path}")
# No path traversal allowed
if ".." in path:
raise ValueError(f"Path traversal not allowed: {path}")
# Resolve to absolute path
real_path = Path(path).resolve()
project_root = Path.cwd()
# Must be within project root
if not str(real_path).startswith(str(project_root)):
raise ValueError(f"Path outside project: {path}")
return real_pathWhat this prevents:
- Path traversal:
../../etc/passwd - Absolute path escape:
/etc/passwd - Symbolic link attacks:
symlink-to-sensitive-file
---
2. JSON Injection Prevention
Principle: Validate all updates before merging into KG.
Why: Prevents malicious JSON from corrupting KG or causing unexpected behavior.
Implementation:
import json
def validate_json_structure(data):
"""
Validate that data matches expected KG structure.
"""
# Must be a dict
if not isinstance(data, dict):
raise ValueError("KG data must be a dictionary")
# Must have required top-level keys
required_keys = ['metadata', 'patterns', 'components', 'apis']
for key in required_keys:
if key not in data:
raise ValueError(f"Missing required key: {key}")
# Validate metadata structure
if 'version' in data['metadata']:
# Version should be a string like "1.0"
if not isinstance(data['metadata']['version'], str):
raise ValueError("Version must be a string")
# Validate arrays are arrays
array_keys = ['patterns', 'components', 'apis', 'provides']
for key in array_keys:
if key in data and key != 'metadata':
if not isinstance(data[key], dict):
raise ValueError(f"{key} must be a dictionary")
return TrueWhat this prevents:
- Malformed JSON structures
- Unexpected data types
- Missing required fields
- Invalid nested structures
---
3. Secrets Exclusion
Principle: KG should NOT contain passwords, API keys, tokens, or other sensitive data.
Why: KG files are committed to git and should not contain secrets.
What to exclude:
- Passwords
- API keys
- Access tokens
- Session IDs
- Private keys
- Database connection strings
- Credentials of any kind
Implementation:
import re
SENSITIVE_PATTERNS = [
r'password\s*[:=]\s*\S+', # password: secret, password=secret
r'api[_-]?key\s*[:=]\s*\S+', # api_key: xxx
r'token\s*[:=]\s*\S+', # token: xxx
r'secret\s*[:=]\s*\S+', # secret: xxx
r'-----BEGIN\s+(PRIVATE\s+KEY|RSA\s+PRIVATE)-----', # Private keys
]
def contains_secrets(text):
"""
Check if text contains potential secrets.
"""
for pattern in SENSITIVE_PATTERNS:
if re.search(pattern, text, re.IGNORECASE):
return True
return False
def validate_no_secrets(data):
"""
Validate that KG data doesn't contain secrets.
"""
# Convert to JSON string for checking
json_str = json.dumps(data)
if contains_secrets(json_str):
raise ValueError("KG data appears to contain secrets")
return TrueWhat to store instead:
- Component names (not passwords)
- API endpoints (not keys)
- Configuration structure (not values)
- Schema definitions (not data)
---
4. Git Safety
Principle: KG files are designed to be committed to git (no sensitive data by design).
What's safe to commit:
- Architecture patterns
- Component names and locations
- API endpoint definitions
- Conventions and best practices
- Technology stack information
What's NOT safe to commit:
- Credentials (already prevented by secrets exclusion)
- User data
- Sensitive configuration values
- Production secrets
Verification:
# Check if KG would add sensitive data to git
git add docs/specs/*/knowledge-graph.json
git diff --cached --check # Fails if sensitive data detected---
5. Source Code Safety
Principle: Knowledge Graph skill does NOT modify source code files.
What it DOES:
- Create/update
knowledge-graph.jsonfiles - Read source files for analysis
- Query source files for validation
What it does NOT do:
- Modify
.java,.ts,.pyfiles - Write to source directories
- Delete source files
- Execute code in source files
Enforcement:
SAFE_EXTENSIONS = {'.json', '.md'} # Only safe file extensions
def validate_operation(target_file):
"""
Validate that operation only targets safe files.
"""
ext = Path(target_file).suffix.lower()
if ext not in SAFE_EXTENSIONS:
raise PermissionError(
f"Cannot modify {ext} files. "
f"Knowledge Graph only creates JSON and Markdown files."
)
# Must be knowledge-graph.json or similar
if 'knowledge-graph' not in target_file:
raise PermissionError(
f"Can only create knowledge-graph files, not {target_file}"
)
return True---
Security Threats and Mitigations
Threat 1: Path Traversal
Attack: User provides path like ../../etc/passwd to access system files.
Mitigation:
- Validate paths start with
docs/specs/ - Disallow
..in paths - Resolve to absolute path and check it's within project root
Example:
# Attack attempt
update_kg("../../../etc/passwd", malicious_data)
# Defense
validate_kg_path("../../../etc/passwd")
# Raises: ValueError("Path traversal not allowed")---
Threat 2: JSON Injection
Attack: Malicious JSON with unexpected structure causes exploit.
Mitigation:
- Validate JSON structure before parsing
- Use schema validation
- Reject unexpected keys or types
Example:
# Attack attempt
malicious_json = '{"__proto__": {"polluted": true}}'
# Defense
validate_json_structure(json.loads(malicious_json))
# Raises: ValueError("Invalid JSON structure")---
Threat 3: Secrets Leakage
Attack: User tries to store passwords/tokens in KG.
Mitigation:
- Scan for secret patterns before writing
- Reject updates containing secrets
- Warn user about sensitive data
Example:
# Attack attempt
data = {"api": {"credentials": {"password": "secret123"}}}
# Defense
validate_no_secrets(data)
# Raises: ValueError("KG data appears to contain secrets")---
Threat 4: Code Execution
Attack: User tries to make KG skill execute arbitrary code.
Mitigation:
- KG skill never executes source code
- Only reads files for analysis
- Never writes to source directories
Example:
# Attack attempt
extract_and_execute("malicious.java")
# Defense
# KG skill doesn't have execute capability
# Only has Read, Write, Edit, Grep, Glob, Bash tools
# Write tool validates it only creates .json files---
Threat 5: Data Exfiltration
Attack: Use KG to extract sensitive codebase information.
Mitigation:
- KG only stores structural information (patterns, components)
- Doesn't store actual code
- Doesn't store sensitive configuration values
- Validate no secrets before writing
What's stored:
- ✅ "UserService class exists in src/auth/UserService.ts"
- ❌ "UserService contains password validation logic with secret key: abc123"
---
Secure Implementation Guidelines
1. Input Validation
Always validate:
- File paths (must be within docs/specs/)
- JSON structure (must match schema)
- Data types (must be expected types)
- Array lengths (prevent DoS via huge arrays)
Example:
def validate_update(updates):
# Validate structure
validate_json_structure(updates)
# Validate no secrets
validate_no_secrets(updates)
# Validate array sizes (prevent DoS)
for key in updates:
if isinstance(updates[key], list):
if len(updates[key]) > 10000:
raise ValueError(f"Array too large: {key}")
return True---
2. Principle of Least Privilege
KG skill capabilities:
- ✅ Read source files for analysis
- ✅ Create/update KG JSON files
- ✅ Query KG for information
- ❌ Modify source code
- ❌ Execute arbitrary code
- ❌ Access files outside project
---
3. Defense in Depth
Multiple layers of security: 1. Path validation (prevent path traversal) 2. JSON validation (prevent injection) 3. Secrets detection (prevent leakage) 4. File type restrictions (prevent code modification) 5. Operation scope (prevent unintended actions)
---
4. Fail Securely
On error:
- Don't write partial/corrupted data
- Don't reveal internal paths
- Don't expose error details that aid attacks
- Log security events for audit
Example:
try:
update_kg(path, data)
except ValueError as e:
# Log detailed error internally
logger.error(f"KG update failed: {e}", exc_info=True)
# Return generic error to user
raise ValueError("Invalid KG data provided")---
Security Best Practices
1. Never Store Credentials
Bad:
{
"database": {
"password": "secret123"
}
}Good:
{
"database": {
"host": "localhost",
"port": 5432,
"name": "mydb"
}
}---
2. Validate All Inputs
Bad:
def update_kg(path, data):
write(path, data) # No validation!Good:
def update_kg(path, data):
validate_path(path)
validate_json_structure(data)
validate_no_secrets(data)
write(path, data)---
3. Use Whitelists, Not Blacklists
Bad:
# Blacklist approach (misses new threats)
if path not in ['etc/passwd', 'etc/shadow']:
process(path)Good:
# Whitelist approach (only allows safe paths)
if path.startswith('docs/specs/'):
process(path)---
4. Log Security Events
What to log:
- Invalid path attempts
- Secret detection events
- JSON validation failures
- Unusual operations
Example:
logger.warning(f"Security: Invalid path attempt: {path}")
logger.error(f"Security: Secrets detected in KG update")
logger.info(f"Security: KG update validated successfully")---
Security Checklist
Before writing to KG:
- [ ] Path validated (starts with docs/specs/)
- [ ] JSON structure validated
- [ ] No secrets detected
- [ ] File type validated (.json only)
- [ ] Operation within scope (read/create/update KG)
- [ ] Size reasonable (< 1 MB)
- [ ] Arrays not suspiciously large
- [ ] No executable code in data
---
Security Auditing
Regular Audits
What to check: 1. All KG files in git contain no secrets 2. No KG files outside docs/specs/ 3. No KG files with suspicious content 4. All KG operations follow security rules
Audit script:
#!/bin/bash
# Audit KG files for security
echo "Auditing Knowledge Graph files..."
# Find all KG files
find docs/specs -name "knowledge-graph.json" | while read file; do
echo "Checking: $file"
# Check for secrets
if grep -iE "password|api[_-]?key|token|secret" "$file"; then
echo "⚠️ WARNING: Possible secrets in $file"
fi
# Check file location
if [[ ! "$file" == docs/specs/*/knowledge-graph.json ]]; then
echo "⚠️ WARNING: Unusual KG location: $file"
fi
# Check file size
size=$(stat -f%z "$file" 2>/dev/null || stat -c%s "$file")
if [ $size -gt 1048576 ]; then
echo "⚠️ WARNING: Large KG file (>1MB): $file"
fi
done
echo "Audit complete."---
Summary
Core security principles: 1. Path validation (only docs/specs/) 2. JSON injection prevention (validate structure) 3. Secrets exclusion (no credentials) 4. Git safety (no sensitive data) 5. Source code safety (no modifications)
Key threats mitigated:
- Path traversal attacks
- JSON injection
- Secrets leakage
- Code execution
- Data exfiltration
Security best practices:
- Validate all inputs
- Use whitelists over blacklists
- Fail securely
- Log security events
- Regular security audits
Remember: Knowledge Graph stores structural information only, never credentials or sensitive data.
Related skills
How it compares
Pick knowledge-graph over flat MEMORY.md notes when codebase structure and patterns need structured JSON that agents can query and incrementally update.
FAQ
What does knowledge-graph do?
Manage persistent Knowledge Graph for specifications. Provides read, query, update, and validation capabilities for codebase analysis caching. Use when: spec-to-tasks needs to cache/reuse codebase analysis, task-implemen
When should I use knowledge-graph?
Manage persistent Knowledge Graph for specifications. Provides read, query, update, and validation capabilities for codebase analysis caching. Use when: spec-to-tasks needs to cache/reuse codebase analysis, task-implemen
What are common prerequisites?
--- name: knowledge-graph description: "Manage persistent Knowledge Graph for specifications.
Is Knowledge Graph safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.