This document outlines how MegaMemory (persistent knowledge graph) and GSD-OpenCode (spec-driven development system) can work together to create a powerful, memory-aware development workflow.
Complementary Strengths:
- MegaMemory: Fine-grained, semantically searchable knowledge about code concepts, patterns, and decisions
- GSD-OpenCode: Project-level planning, multi-agent orchestration, structured documentation, atomic execution
Integration Goal: Create a bidirectional knowledge flow where:
- GSD activities automatically populate MegaMemory with valuable insights
- MegaMemory knowledge informs and enhances GSD planning and execution
┌─────────────────────────────────────────────────────────────────┐
│ OpenCode Session │
└─────────────────────────┬───────────────────────────────────────┘
│
┌────────────────┴────────────────┐
│ │
┌────▼────┐ ┌────▼────┐
│ GSD │ │MegaMemory│
│Workflow │◄────────────────────►│ MCP │
└────┬────┘ Knowledge Flow └─────────┘
│
├─► /gsd-new-project ──► Create project concepts
├─► /gsd-map-codebase ──► Capture architecture
├─► /gsd-discuss-phase ──► Retrieve context
├─► /gsd-plan-phase ──► Research + Retrieve
├─► /gsd-execute-phase ──► Capture implementations
└─► /gsd-verify-work ──► Validate + Update
GSD Command: /gsd-new-project
Integration Actions:
## Step: Check for existing MegaMemory graph
1. Call `megamemory:list_roots` to see if knowledge exists
2. If graph exists:
- Present key concepts to user
- Ask: "Load this knowledge into GSD's context?"
- If yes: Populate PROJECT.md Context section with relevant concepts
- If no: Proceed with fresh project setup
Example mapping:
- MegaMemory "module" concepts → PROJECT.md architecture context
- MegaMemory "pattern" concepts → Constraints section
- MegaMemory "decision" concepts → Key Decisions table## Step: Create initial MegaMemory concepts
After GSD creates PROJECT.md, REQUIREMENTS.md, ROADMAP.md:
1. Create root concept for the project
- kind: "feature"
- summary: Project vision + core value (from PROJECT.md)
- why: Rationale from Core Value section
2. Create concepts for each major requirement
- kind: "feature"
- parent_id: project-root
- summary: What the requirement delivers
- file_refs: ["REQUIREMENTS.md"]
3. Create concept for technical stack decisions
- kind: "decision"
- summary: Tech stack choices with rationale
- file_refs: ["PROJECT.md"]Benefits:
- Preserves project vision across sessions
- Enables semantic search of project goals
- Provides foundation for knowledge-assisted planning
GSD Command: /gsd-map-codebase
Integration Actions:
## Step: Capture architecture knowledge
As GSD codebase mapper agents analyze the codebase:
1. When "architecture.md" is created:
- Parse the document
- Create "module" concepts for each major subsystem
- Link concepts with "connects_to" relationships
2. When "patterns.md" is created:
- Create "pattern" concepts for each discovered pattern
- Include file examples and usage contexts
3. When "conventions.md" is created:
- Create "pattern" concepts with kind="convention"
- Tag with "coding-standards"
Example transformation:
From patterns.md:
"Use Provider pattern for state management"
To MegaMemory concept:
- name: "provider-pattern-state"
- kind: "pattern"
- summary: "State management uses Provider pattern with ChangeNotifier. Located in lib/model/. Models inherit from ChangeNotifier, provide state to descendants via Provider.of() context."
- file_refs: ["lib/model/", "lib/main.dart"]Benefits:
- Captures institutional knowledge automatically
- Makes patterns discoverable via semantic search
- Reduces duplicate pattern research in future phases
GSD Command: /gsd-discuss-phase [N]
Integration Actions:
## Step: Retrieve relevant knowledge
Before discussing the phase:
1. Extract key terms from phase name and scope
2. Call `megamemory:understand` with these queries:
- Query: "[Phase domain] architecture"
- Query: "[Phase domain] patterns"
- Query: "[Phase domain] constraints"
3. Present findings to user:
- "MegaMemory found these relevant concepts:"
- Show top matches with summaries
- Ask: "Should I consider these during our discussion?"
Example:
Phase: "User Authentication"
Queries:
- "authentication architecture"
- "authentication patterns"
- "auth dependencies"
Found concepts:
- "jwt-auth-middleware" (similarity: 0.89)
- "session-management" (similarity: 0.84)
- "user-model" (similarity: 0.76)## Step: Enhance CONTEXT.md with knowledge
As discussion captures decisions:
1. If MegaMemory provided relevant concepts:
- Add to CONTEXT.md "MegaMemory Context" section
- Show which concepts were found
- Note which ones were applied vs. overridden
2. For each major decision made:
- Check if similar MegaMemory concept exists
- If yes: Offer to update existing concept
- If no: Plan to create new concept after phase execution
Example CONTEXT.md addition:
## MegaMemory Context
Relevant knowledge from graph:
- jwt-auth-middleware: RS256 JWT validation, 1h expiry, refresh tokens
→ Applied to our auth design
- user-model: Located in lib/model/user.dart, singleton gUserModel
→ Will integrate with our auth flowBenefits:
- Leverages existing knowledge during decision-making
- Prevents reinventing wheels
- Makes decisions more informed
GSD Command: /gsd-plan-phase [N]
Integration Actions:
## Step: Knowledge-assisted research
When gsd-phase-researcher agent runs:
1. Before researching:
- Call `megamemory:understand` with phase-specific queries
- Feed relevant concepts into researcher's context
2. During research:
- Researcher checks MegaMemory for:
- Similar features previously implemented
- Architectural patterns that apply
- Dependencies between modules
- Configuration requirements
3. After research:
- In RESEARCH.md, add "MegaMemory References" section
- Link to relevant concepts
Example RESEARCH.md:
## MegaMemory References
Similar implementations:
- "user-registration-flow" (Phase 1) → Use same validation pattern
- "email-service" (module) → Depends on this for email confirmations
Architecture patterns:
- "provider-pattern" → Apply to state management in this phase
- "middleware-pattern" → Use for auth interceptors## Step: Knowledge-informed planning
When gsd-planner creates plans:
1. Check MegaMemory for:
- Existing code patterns to follow
- Dependencies that need to be linked
- Configuration that must be set up
- File locations for related features
2. Add knowledge references to tasks:
<task type="auto">
<name>Create auth endpoint</name>
<files>src/api/auth/login/route.ts</files>
<action>
Follow pattern from "jwt-auth-middleware" concept:
- Use jose for JWT (not jsonwebtoken)
- RS256 signing keys from config
- 1-hour token expiry
Integrate with "user-model" concept:
- Singleton instance at lib/model/user.dart
- Call userModel.validateCredentials()
</action>
<verify>curl -X POST localhost:3000/api/auth/login returns 200</verify>
<done>Login returns JWT, invalid returns 401</done>
</task>Benefits:
- Plans leverage existing patterns automatically
- Reduces research time
- Improves consistency across phases
GSD Command: /gsd-execute-phase [N]
Integration Actions:
## Step: Capture implemented features
As gsd-executor agents implement plans:
1. After each task completion:
- Extract key features, modules, patterns implemented
- Create MegaMemory concepts for significant additions
Example automatic capture:
After implementing authentication flow:
→ Create concept:
- name: "authentication-flow"
- kind: "feature"
- parent_id: "user-management"
- summary: "JWT-based authentication with RS256, 1h expiry, refresh tokens. Login endpoint at /api/auth/login. Uses jose for JWT validation. Integrates with gUserModel singleton."
- file_refs: ["src/api/auth/login/route.ts", "src/middleware/auth.ts"]
- edges: [
{to: "jwt-auth-middleware", relation: "implements"},
{to: "user-model", relation: "calls"}
]
- created_by_task: "01-02-PLAN: Create login endpoint"## Step: Capture implementation decisions
When plans make technical choices:
1. Identify decisions made during implementation
2. Create "decision" concepts with rationale
Example:
→ Create concept:
- name: "use-jose-for-jwt"
- kind: "decision"
- summary: "Chose jose over jsonwebtoken for JWT handling"
- why: "jsonwebtoken is CommonJS, causes ESM build issues. jose is pure ESM, better maintenance, TypeScript support"
- file_refs: ["package.json", "src/api/auth/login/route.ts"]
- edges: [
{to: "authentication-flow", relation: "configured_by"}
]## Step: Capture discovered patterns
When new patterns emerge during implementation:
1. Identify reusable implementation patterns
2. Create "pattern" concepts
Example:
→ Create concept:
- name: "api-response-wrapper"
- kind: "pattern"
- summary: "All API responses wrapped in {success, data, error} structure. Ensures consistent error handling. Middleware logs all responses."
- file_refs: ["src/middleware/response.ts", "src/api/**/*.ts"]
- why: "Prevents inconsistent error formats, enables centralized error logging"Benefits:
- Knowledge captured automatically as work is done
- No separate "save memory" step required
- Comprehensive capture of decisions and patterns
GSD Command: /gsd-verify-work [N]
Integration Actions:
## Step: Verify knowledge completeness
Before presenting verification checklist to user:
1. Call `megamemory:list_roots` to see new concepts
2. Check if implementation is adequately documented:
- Are all major features captured?
- Are key decisions recorded?
- Are patterns identified?
- Are dependencies linked?
3. Present findings:
- "MegaMemory captured X concepts from this phase:"
- Show summary of captured knowledge
- Ask user: "Add or update any concepts?"## Step: Fix outdated knowledge
After verification identifies issues:
1. If concepts are incorrect or incomplete:
- Update MegaMemory concepts with corrections
- Update file_refs to current implementation
2. If features changed significantly:
- Remove outdated concepts with `megamemory:remove_concept`
- Create new concepts reflecting changes
Example update:
→ Update concept "authentication-flow":
- summary: "Now includes OAuth2 provider support (Google, GitHub)"
- file_refs: ["src/api/auth/login/route.ts", "src/api/auth/oauth.ts", ...]
- why: "OAuth2 added in Phase 3 to support social login"Benefits:
- Knowledge stays in sync with reality
- Catch outdated documentation early
- User can add context they noticed during verification
Scenario: User returns after closing OpenCode
Integration Actions:
## Step: Load MegaMemory context
On session start:
1. Check if MegaMemory graph exists
2. Call `megamemory:list_roots`
3. Present key information:
- "This project has X concepts in memory:"
- Show top-level modules/features
- Show recent changes (from `updated_at`)
4. Ask: "Load MegaMemory context for this session?"
- If yes: Inject relevant concepts into GSD's context
- If no: Proceed without MegaMemory
5. Check STATE.md for position
6. Suggest next actions based on both:
- GSD state (what phase/plan)
- MegaMemory knowledge (what's been learned)## Step: Inject knowledge into GSD workflow
When loading MegaMemory context:
1. Identify current phase/plan from STATE.md
2. Call `megamemory:understand` with domain-specific queries
3. Inject relevant concepts into GSD templates:
Example for /gsd-discuss-phase:
Add to CONTEXT.md template:
## MegaMemory Context
[Inject relevant concepts here]Benefits:
- Seamless session restoration
- No loss of institutional knowledge
- Faster ramp-up on resuming work
| GSD Workflow | MegaMemory Tool | Purpose | Trigger |
|---|---|---|---|
/gsd-new-project |
list_roots |
Check for existing knowledge | Before initialization |
/gsd-new-project |
create_concept |
Create project root concept | After PROJECT.md created |
/gsd-new-project |
create_concept |
Create requirement concepts | After REQUIREMENTS.md created |
/gsd-map-codebase |
create_concept |
Capture modules | After architecture.md created |
/gsd-map-codebase |
create_concept |
Capture patterns | After patterns.md created |
/gsd-discuss-phase |
understand |
Retrieve relevant context | Before discussion starts |
/gsd-discuss-phase |
create_concept |
Pre-plan decisions | During decision capture |
/gsd-plan-phase |
understand |
Research enhancement | Before research |
/gsd-plan-phase |
create_concept |
Update existing concepts | After research |
/gsd-execute-phase |
create_concept |
Capture implemented features | After each task |
/gsd-execute-phase |
create_concept |
Capture decisions | When choices made |
/gsd-execute-phase |
create_concept |
Capture patterns | When patterns emerge |
/gsd-execute-phase |
link |
Connect concepts | When relationships clear |
/gsd-execute-phase |
update_concept |
Fix outdated knowledge | When issues found |
/gsd-execute-phase |
remove_concept |
Remove obsolete concepts | When features removed |
/gsd-verify-work |
list_roots |
Validate knowledge completeness | Before UAT |
/gsd-verify-work |
understand |
Check for missing concepts | Before UAT |
/gsd-verify-work |
update_concept |
Fix issues found | After user feedback |
/gsd-resume-work |
list_roots |
Restore session | On session start |
/gsd-resume-work |
understand |
Load context | On session start |
When: GSD implements a user-facing feature
Kind: "feature"
Parent: Usually a module concept or project root
Summary: What the feature does + key implementation details
File refs: Main implementation files
Edges: depends_on (modules), implements (requirements)
Why: User value delivered by this featureWhen: GSD creates or discovers a major subsystem
Kind: "module"
Parent: Usually project root
Summary: What the module is responsible for + key files
File refs: Module directory or key files
Edges: connects_to (other modules), implements (decisions)
Why: Architectural rationale for this moduleWhen: GSD discovers or implements a reusable pattern
Kind: "pattern"
Parent: Module concept or project root
Summary: Pattern description + how it's used
File refs: Example implementations
Edges: used_in (features/modules)
Why: Why this pattern is usedWhen: GSD makes a significant technical choice
Kind: "decision"
Parent: Feature or module concept
Summary: What was chosen
Why: Rationale for the choice
File refs: Where decision is implemented
Edges: configures (implementation)
Why: Tradeoffs consideredWhen: GSD sets up configuration
Kind: "config"
Parent: Usually project root
Summary: What's configured + key settings
File refs: Config files
Edges: configures (modules/features)
Why: Why these settings// Format: [parent-id]/[kebab-case-name]
// Examples:
"user-management" // Feature (root)
"user-management/auth-flow" // Sub-feature
"user-management/auth-flow/jwt" // Decision
"api-layer/middleware/auth" // Module pattern
"state-management/provider" // Pattern| Relation | When to Use | Example |
|---|---|---|
depends_on |
A requires B to function | auth-flow → user-model |
implements |
A fulfills B | user-registration → requirement-user-signup |
calls |
A directly invokes B | auth-middleware → jwt-service |
connects_to |
A interfaces with B | frontend → api-layer |
configured_by |
A uses settings from B | auth-flow → use-jose-for-jwt |
# [Project Name]
## What This Is
[Description]
## Core Value
[One-liner]
## Requirements
[Standard GSD sections]
## Context
[Standard GSD sections]
## MegaMemory Integration
<!-- Added section -->
**Knowledge Graph Status**: [X concepts, Y modules, Z decisions]
**Key Concepts**:
- [Top 5-10 most important concepts]
**Last Synced**: [timestamp]
## Constraints
[Standard GSD sections]
## Key Decisions
[Standard GSD sections]
---
*Last updated: [date]*# Phase [X]: [Name] - Context
**Gathered:** [date]
**Status:** Ready for planning
<domain>
## Phase Boundary
[Clear statement of what this phase delivers — the scope anchor. This comes from ROADMAP.md and is fixed. Discussion clarifies implementation within this boundary.]
</domain>
<megamemory_context>
## MegaMemory Context
<!-- Added section -->
**Relevant Concepts Found**:
[Inject understand results here]
**Applied Concepts**:
- [concept-name]: How it was applied to this phase
**Overridden Concepts**:
- [concept-name]: Why we chose differently
</megamemory_context>
<decisions>
## Implementation Decisions
### [Area 1 that was discussed]
- [Specific decision made]
- [Another decision if applicable]
### [Area 2 that was discussed]
- [Specific decision made]
### OpenCode's Discretion
[Areas where user explicitly said "you decide" — OpenCode has flexibility here during planning/implementation]
</decisions>
<specifics>
## Specific Ideas
[Any particular references, examples, or "I want it like X" moments from discussion. Product references, specific behaviors, interaction patterns.]
</specifics>
<deferred>
## Deferred Ideas
[Ideas that came up during discussion but belong in other phases. Captured here so they're not lost, but explicitly out of scope for this phase.]
</deferred>
---
*Phase: XX-name*
*Context gathered: [date]*---
phase: XX-name
plan: NN
type: execute
wave: N
depends_on: []
files_modified: []
autonomous: true
user_setup: []
# Goal-backward verification (derived during planning, verified after execution)
must_haves:
truths: []
artifacts: []
key_links: []
---
<objective>
[What this plan accomplishes]
Purpose: [Why this matters for the project]
Output: [What artifacts will be created]
</objective>
<megamemory_references>
## MegaMemory References
<!-- Added section -->
**Knowledge Applied**:
- [concept-name]: How it informed this plan
**Patterns to Follow**:
- [pattern-concept]: Implementation guidance
</megamemory_references>
<execution_context>
@~/.config/opencode/get-shit-done/workflows/execute-plan.md
@~/.config/opencode/get-shit-done/templates/summary.md
[If plan contains checkpoint tasks (type="checkpoint:*"), add:]
@~/.config/opencode/get-shit-done/references/checkpoints.md
</execution_context>
<context>
@.planning/PROJECT.md
@.planning/ROADMAP.md
@.planning/STATE.md
<!-- Added reference -->
@.planning/phases/XX-name/megamemory-references.md
[Relevant source files:]
@src/path/to/relevant.ts
</context>
<tasks>
[Standard GSD tasks]
</tasks>Goal: Basic bidirectional flow working
Tasks:
-
Modify GSD templates to include MegaMemory sections
- Add MegaMemory section to PROJECT.md template
- Add MegaMemory section to CONTEXT.md template
- Add MegaMemory references to PLAN.md template
-
Add
list_rootscheck to/gsd-new-project- Check for existing graph before initialization
- Present existing concepts to user
- Ask user if they want to load context
-
Add concept creation to
/gsd-new-projectcompletion- Create project root concept after PROJECT.md created
- Create requirement concepts after REQUIREMENTS.md created
- Create tech stack decision concept
-
Add
understandcall to/gsd-discuss-phase- Extract key terms from phase name and scope
- Query MegaMemory for relevant concepts
- Present findings to user
-
Add context injection to CONTEXT.md generation
- Add "MegaMemory Context" section
- List relevant concepts found
- Track applied vs overridden concepts
-
Test end-to-end: new-project → discuss-phase
- Verify knowledge capture works
- Verify knowledge retrieval works
- Verify context injection works
Deliverables:
- Updated GSD templates with MegaMemory sections
- Working knowledge capture during project init
- Knowledge retrieval during phase discussion
- Test suite for Phase 1 features
Acceptance Criteria:
- Running
/gsd-new-projectcreates MegaMemory concepts - Running
/gsd-discuss-phaseretrieves relevant knowledge - CONTEXT.md includes MegaMemory context section
- All tests pass
Goal: Capture architecture knowledge automatically
Tasks:
-
Add concept creation to
/gsd-map-codebase- Hook into gsd-codebase-mapper agent workflow
- Parse architecture.md when created
- Parse patterns.md when created
- Parse conventions.md when created
-
Parse architecture.md
- Extract module names and descriptions
- Create "module" concepts for each subsystem
- Link modules with "connects_to" edges
-
Parse patterns.md
- Extract pattern names and descriptions
- Create "pattern" concepts
- Include file examples and usage contexts
-
Parse conventions.md
- Extract coding conventions
- Create "pattern" concepts with kind="convention"
- Tag with "coding-standards"
-
Create appropriate edges
- Link modules to each other based on dependencies
- Link patterns to modules that use them
- Link conventions to applicable areas
-
Test on existing codebase
- Run
/gsd-map-codebaseon sample project - Verify all modules captured
- Verify all patterns captured
- Verify edges are correct
- Run
Deliverables:
- Automatic architecture knowledge capture
- Pattern documentation in graph
- Module relationships documented
- Test suite for mapping integration
Acceptance Criteria:
- Running
/gsd-map-codebasecreates module concepts - Patterns are extracted and captured
- Conventions are documented
- Edges correctly represent relationships
- All tests pass
Goal: Knowledge-assisted research and planning
Tasks:
-
Add
understandto gsd-phase-researcher workflow- Before research starts, query MegaMemory
- Extract phase-specific queries from phase name
- Feed relevant concepts into researcher context
-
Enhance researcher with MegaMemory context
- Researcher checks MegaMemory for similar features
- Researcher checks for architectural patterns
- Researcher checks for dependencies
- Researcher checks for configuration requirements
-
Add MegaMemory section to RESEARCH.md
- List similar implementations found
- List architectural patterns applicable
- Link to relevant concepts
-
Modify gsd-planner to check for relevant concepts
- Before creating tasks, query MegaMemory
- Find existing patterns to follow
- Find dependencies that need linking
- Find configuration requirements
-
Add knowledge references to PLAN.md
- Add "MegaMemory References" section
- List knowledge applied in plan
- List patterns to follow
- Include specific implementation guidance
-
Test: plan-phase with existing MegaMemory graph
- Create sample MegaMemory graph
- Run
/gsd-plan-phase - Verify research is enhanced
- Verify plans reference knowledge
Deliverables:
- Knowledge-informed research workflow
- Knowledge references in RESEARCH.md
- Knowledge references in plans
- Test suite for planning enhancement
Acceptance Criteria:
- Research phase queries MegaMemory
- RESEARCH.md includes MegaMemory references
- Plans reference existing patterns
- Plans follow known architectural decisions
- Research time reduced by ~20%
- All tests pass
Goal: Automatic knowledge capture during execution
Tasks:
-
Add concept creation hooks to gsd-executor
- After each task completes, analyze what was created
- Extract features, modules, patterns from implementation
- Determine if significant enough for concept creation
-
Capture features as implemented
- Identify user-facing features
- Create "feature" concepts with summaries
- Link to parent modules/requirements
- Add file references
-
Capture modules as implemented
- Identify new subsystems
- Create "module" concepts
- Document responsibilities and key files
- Link to related modules
-
Capture patterns as implemented
- Identify reusable implementation patterns
- Create "pattern" concepts
- Document usage and examples
- Link to features/modules that use them
-
Capture decisions when choices made
- Identify significant technical choices
- Create "decision" concepts
- Document rationale and tradeoffs
- Link to implementations
-
Create appropriate edges
- Link features to modules they depend on
- Link modules to each other
- Link decisions to implementations
- Link patterns to usage
-
Update existing concepts when changes made
- Detect when concepts need updating
- Update summaries, file_refs
- Update embeddings automatically
-
Remove outdated concepts when needed
- Detect when features are removed/replaced
- Soft-remove concepts with reasons
- Preserve history
-
Test: execute-phase and verify knowledge capture
- Run
/gsd-execute-phase - Verify features captured
- Verify patterns captured
- Verify decisions captured
- Verify edges created
- Run
Deliverables:
- Automatic knowledge capture during execution
- Comprehensive decision logging
- Pattern discovery and documentation
- Test suite for execution capture
Acceptance Criteria:
- Features are automatically captured
- Modules are automatically captured
- Patterns are automatically captured
- Decisions are automatically captured
- Edges correctly represent relationships
- All tests pass
Goal: Knowledge validation during verification
Tasks:
-
Add knowledge completeness check to
/gsd-verify-work- Before UAT, call
list_roots - Check if implementation is adequately documented
- Validate all major features captured
- Validate key decisions recorded
- Validate patterns identified
- Before UAT, call
-
Present MegaMemory concepts to user
- Show summary of captured knowledge
- Show new concepts from this phase
- Show updated concepts
- Allow user to review
-
Allow user to add/update concepts
- Provide interface for concept edits
- Allow adding missing concepts
- Allow updating incomplete concepts
- Allow removing incorrect concepts
-
Update concepts based on verification findings
- If user provides feedback, update concepts
- Fix inaccuracies discovered during UAT
- Update file_refs to current implementation
-
Test: verify-work with knowledge updates
- Run
/gsd-verify-work - Provide user feedback
- Verify concepts are updated
- Verify accuracy improves
- Run
Deliverables:
- Knowledge validation workflow
- User feedback integration
- Knowledge accuracy improved
- Test suite for verification integration
Acceptance Criteria:
- Verification checks knowledge completeness
- User can review captured knowledge
- User can add/update concepts
- Knowledge accuracy improves based on feedback
- All tests pass
Goal: Seamless session restoration
Tasks:
-
Add MegaMemory check on session start
- Detect when new session starts
- Check if MegaMemory graph exists
- Load graph state
-
Present knowledge graph state
- Show total number of concepts
- Show top-level modules/features
- Show recent changes
- Show knowledge graph statistics
-
Inject relevant context into STATE.md
- Add "MegaMemory State" section
- List key concepts
- Show recent activity
-
Provide knowledge loading option
- Ask user if they want to load context
- If yes, inject relevant concepts
- If no, proceed without MegaMemory
-
Enhance
/gsd-resume-workcommand- Load MegaMemory graph
- Restore session state
- Present knowledge context
- Suggest next actions
-
Test: resume-work with MegaMemory context
- Start new session
- Verify graph state presented
- Verify context injected
- Verify seamless continuation
Deliverables:
- Session-aware knowledge loading
- Seamless continuation with knowledge intact
- Enhanced resume-work command
- Test suite for session continuity
Acceptance Criteria:
- New sessions detect MegaMemory graph
- Knowledge state is presented
- Context is injected into STATE.md
- User can opt-in to load knowledge
- Session restoration works seamlessly
- All tests pass
Goal: Refine and optimize integration
Tasks:
-
Performance testing with large knowledge graphs
- Create test graph with 1000+ concepts
- Measure tool call latencies
- Measure memory usage
- Identify bottlenecks
-
Optimize concept creation frequency
- Implement thresholding to reduce noise
- Only create significant concepts
- Batch concept creation where possible
- Cache concept lookups
-
Add duplicate detection and deduplication
- Before creating, check for similar concepts
- Use similarity matching to find duplicates
- Merge overlapping concepts
- Prevent redundant knowledge
-
Improve context relevance scoring
- Fine-tune similarity thresholds
- Improve query generation
- Better relevance ranking
- Reduce false positives
-
Add knowledge graph visualization to GSD reports
- Embed graph explorer in verification reports
- Interactive exploration of phase concepts
- Visual relationships between features and modules
-
Documentation and examples
- Write user guide for integrated workflow
- Create example projects demonstrating integration
- Document best practices
- Create troubleshooting guide
-
User guide for integrated workflow
- How to get started
- Common workflows
- Best practices
- Tips and tricks
Deliverables:
- Optimized performance
- Comprehensive documentation
- User guide
- Example projects
- Troubleshooting guide
Acceptance Criteria:
- Performance:
understand< 100ms with 1000 concepts - Performance:
create_concept< 50ms - Performance:
list_roots< 50ms - Duplicate detection reduces redundant concepts by 80%
- Memory overhead < 100MB
- Documentation is complete
- All tests pass
Knowledge Persistence:
- ✓ Every decision automatically captured
- ✓ Patterns discovered and documented
- ✓ No manual "save memory" step needed
- ✓ Knowledge accumulates across sessions
Knowledge Retrieval:
- ✓ Relevant knowledge presented before planning
- ✓ Similar implementations discovered automatically
- ✓ Pattern reuse encouraged
- ✓ Faster research cycles
Consistency:
- ✓ Patterns automatically identified
- ✓ Decisions tracked with rationale
- ✓ Architecture documented as built
- ✓ Conventions enforced through knowledge
Onboarding:
- ✓ New sessions instantly informed
- ✓ Historical context available via search
- ✓ Decision rationale preserved
- ✓ Architecture visible in graph
Automatic Population:
- ✓ No manual bootstrap step
- ✓ Knowledge grows naturally
- ✓ Comprehensive coverage
- ✓ Continuous updates
Quality:
- ✓ Concepts created by agents building code
- ✓ Accurate file references
- ✓ Precise summaries (builders know best)
- ✓ Real-time relevance
Graph Structure:
- ✓ Well-organized hierarchy
- ✓ Rich edge relationships
- ✓ Multi-level nesting
- ✓ Semantic clustering
Enhanced Research:
- ✓ Leverages existing knowledge
- ✓ Reduces research time
- ✓ Improves plan quality
- ✓ Avoids duplicate work
Better Planning:
- ✓ Informed by past decisions
- ✓ Follows established patterns
- ✓ Respects architecture constraints
- ✓ More accurate time estimates
Smarter Execution:
- ✓ Follows known patterns
- ✓ Integrates with existing code
- ✓ Respects configuration choices
- ✓ Fewer conflicts
Problem: Automatic capture could create too many concepts, making graph noisy.
Mitigations:
-
Thresholding: Only create concepts for significant additions
- Features: Always create
- Modules: Create if >3 files or >100 lines
- Patterns: Create if used >2 times
- Decisions: Only if non-trivial choice
-
Deduplication: Check for similar existing concepts before creating
- Use
understandto find similar concepts - Update existing rather than create new
- Merge overlapping concepts
- Use
-
User Approval: Ask user before creating low-confidence concepts
- "Found pattern X. Create concept?"
- Allow batch approvals
-
Pruning: Periodically review and clean graph
- Remove concepts with few connections
- Merge similar concepts
- Archive old patterns
Problem: Knowledge can become outdated as code evolves.
Mitigations:
-
File Watching: Update concepts when referenced files change
- On file edit: Check if concepts reference it
- If yes: Flag for review
- Auto-update trivial changes (file paths, comments)
-
Verification Integration: Check knowledge during
/gsd-verify-work- Validate file references still exist
- Confirm implementation matches description
- Update or flag mismatches
-
Explicit Updates: Require knowledge updates during refactoring
- Add knowledge update step to refactoring plans
- Mark refactored concepts as "needs review"
-
Version Tracking: Track when concepts were last verified
- Add
verified_attimestamp - Flag stale concepts in
list_roots
- Add
Problem: Too much knowledge presented could overwhelm GSD agents.
Mitigations:
-
Relevance Scoring: Only show highly relevant concepts
- Use similarity threshold (e.g., >0.75)
- Limit to top-K results (e.g., 5-10)
- Weight by recency and connection count
-
Phased Exposure: Reveal knowledge progressively
- Start with high-level concepts during discussion
- Add detail during planning
- Show implementation-specific during execution
-
Selective Loading: User controls what to load
- Ask: "Load all context or select areas?"
- Allow toggling specific concept types
-
Context Budgeting: Track token usage
- Limit knowledge context to X% of budget
- Prioritize by relevance score
Problem: Frequent MCP tool calls could slow down workflows.
Mitigations:
-
Caching: Cache concept lookups
- In-memory cache during workflow
- TTL-based invalidation
- Batch operations where possible
-
Selective Calls: Only call when necessary
- Don't create concepts for trivial changes
- Batch multiple creates into single call
- Lazy load references
-
Async Operations: Make non-critical calls async
- Background knowledge updates
- Don't block on concept creation
-
Performance Targets: Set acceptable overhead limits
- <5% additional time for workflows
- <100ms per understand call
- Monitor and optimize
Problem: Agent-generated concepts might be inaccurate or incomplete.
Mitigations:
-
Template Enforcement: Use strict templates for concept creation
- Required fields: name, kind, summary
- Encouraged: why, file_refs
- Format guidelines
-
Validation: Validate concepts before persisting
- Check required fields
- Validate parent exists
- Validate edge targets
- Check for duplicates
-
Review Workflow: Allow user review of significant concepts
- Present high-impact concepts for approval
- Allow edits before saving
- Reject incorrect concepts
-
Feedback Loop: Learn from user corrections
- Track which concepts are edited
- Identify patterns in corrections
- Improve creation templates
// Test concept creation patterns
describe('MegaMemory Integration', () => {
test('creates feature concept from GSD implementation', async () => {
const implementation = {
feature: 'user-authentication',
files: ['src/api/auth/login.ts'],
summary: 'JWT authentication with RS256'
};
const concept = await createConceptFromImplementation(implementation);
expect(concept.kind).toBe('feature');
expect(concept.summary).toContain('JWT');
expect(concept.file_refs).toContain('src/api/auth/login.ts');
});
test('finds similar existing concepts before creating', async () => {
const existingConcepts = [
{name: 'jwt-auth', summary: 'JWT authentication'}
];
const newConcept = {
name: 'jwt-authentication',
summary: 'JWT-based auth system'
};
const shouldUpdate = await shouldCreateOrUpdate(newConcept, existingConcepts);
expect(shouldUpdate.action).toBe('update');
expect(shouldUpdate.targetId).toBe('jwt-auth');
});
test('creates appropriate edges between concepts', async () => {
const sourceConcept = {id: 'auth-flow', kind: 'feature'};
const targetConcept = {id: 'user-model', kind: 'module'};
const edge = await createEdge('auth-flow', 'user-model', 'depends_on');
expect(edge.relation).toBe('depends_on');
expect(edge.from_id).toBe('auth-flow');
expect(edge.to_id).toBe('user-model');
});
});// Test full GSD workflow with MegaMemory
describe('GSD + MegaMemory Workflow', () => {
beforeEach(async () => {
await clearMegaMemoryGraph();
await clearGSDPlanning();
});
test('new-project creates MegaMemory concepts', async () => {
await runGSDCommand('/gsd-new-project', {
projectName: 'test-project',
requirements: ['feature-1', 'feature-2']
});
const roots = await callMCPTool('list_roots');
expect(roots.roots).toHaveLength(1);
expect(roots.roots[0].kind).toBe('feature');
expect(roots.roots[0].children).toHaveLength(2);
});
test('discuss-phase retrieves relevant knowledge', async () => {
await setupExistingKnowledge({
concept: 'authentication-pattern',
summary: 'JWT-based auth with refresh tokens'
});
const context = await runGSDCommand('/gsd-discuss-phase', {
phaseName: 'user-authentication'
});
expect(context.megaMemoryContext).toBeDefined();
expect(context.megaMemoryContext.appliedConcepts).toContain('authentication-pattern');
});
test('execute-phase captures implemented features', async () => {
await runGSDCommand('/gsd-execute-phase', {
phaseNumber: 1
});
const concepts = await callMCPTool('understand', {
query: 'user authentication'
});
expect(concepts.matches).toHaveLength(1);
expect(concepts.matches[0].kind).toBe('feature');
});
test('verify-work allows knowledge updates', async () => {
await runGSDCommand('/gsd-execute-phase', {phaseNumber: 1});
const verifyResult = await runGSDCommand('/gsd-verify-work', {
phaseNumber: 1,
feedback: 'Update auth concept to include OAuth2'
});
const updatedConcept = await callMCPTool('understand', {
query: 'authentication OAuth2'
});
expect(updatedConcept.matches).toHaveLength(1);
expect(updatedConcept.matches[0].summary).toContain('OAuth2');
});
});# E2E Test: Full project lifecycle with MegaMemory
## Setup
1. Clean slate: No MegaMemory graph
2. No GSD planning directory
## Test Flow
### 1. Initialize Project
Run: `/gsd-new-project`
Expect:
- PROJECT.md created
- MegaMemory has project root concept
- MegaMemory has requirement concepts
Validate:
```bash
# Check MegaMemory graph
megamemory:list_roots | jq '.roots | length' # Should be 1
megamemory:list_roots | jq '.roots[0].kind' # Should be "feature"
megamemory:list_roots | jq '.roots[0].children | length' # Should match requirementsRun: /gsd-map-codebase
Expect:
- architecture.md created
- MegaMemory has module concepts
- MegaMemory has pattern concepts
Validate:
# Check modules captured
megamemory:understand --query="architecture" | jq '.matches | map(.kind == "module")'
# Should have module concepts
# Check patterns captured
megamemory:understand --query="patterns" | jq '.matches | map(.kind == "pattern")'
# Should have pattern conceptsRun: /gsd-discuss-phase 1
Expect:
- CONTEXT.md created with MegaMemory section
- Relevant concepts retrieved and shown
Validate:
# Check CONTEXT.md has MegaMemory section
grep -q "MegaMemory Context" .planning/phases/01-*/01-*CONTEXT.mdRun: /gsd-plan-phase 1
Expect:
- RESEARCH.md has MegaMemory references
- Plans reference existing patterns
- No duplicate research
Validate:
# Check RESEARCH.md references MegaMemory
grep -q "MegaMemory References" .planning/phases/01-*/01-*RESEARCH.md
# Check PLAN.md references patterns
grep -q "pattern" .planning/phases/01-*/01-*-PLAN.mdRun: /gsd-execute-phase 1
Expect:
- Implementation complete
- MegaMemory has feature concepts
- MegaMemory has decision concepts
- Concepts properly linked
Validate:
# Check features captured
megamemory:understand --query="feature" | jq '.matches | map(.kind == "feature")'
# Should have feature concepts
# Check decisions captured
megamemory:understand --query="decision" | jq '.matches | map(.kind == "decision")'
# Should have decision concepts
# Check edges exist
# (Would need custom tool to check edge count)Run: /gsd-verify-work 1
Expect:
- User can review captured knowledge
- User can add/update concepts
- Knowledge reflects implementation
Run: /gsd-pause-work
Expect:
- Session state saved
- MegaMemory graph persisted
Validate:
# Check graph persisted
ls .megamemory/knowledge.db # Should existRestart OpenCode Expect:
- MegaMemory graph loaded
- Context presented
- Can resume work
Run: /gsd-discuss-phase 2
Expect:
- Previous phase knowledge available
- Context informed by MegaMemory
After each step, verify:
- MegaMemory tools called correctly
- Concepts created with correct structure
- Edges created appropriately
- No duplicate concepts
- Knowledge accurately reflects reality
---
## Success Metrics
### Knowledge Coverage
- [ ] 90% of features captured as concepts
- [ ] 80% of modules captured as concepts
- [ ] 70% of patterns captured as concepts
- [ ] 85% of decisions captured as concepts
### Knowledge Quality
- [ ] 95% of concepts have summaries
- [ ] 80% of concepts have "why" field
- [ ] 90% of concepts have file_refs
- [ ] <5% of concepts are duplicates
### Workflow Impact
- [ ] <5% additional time for GSD workflows
- [ ] 20% reduction in research time
- [ ] 30% reduction in duplicate pattern research
- [ ] 15% improvement in plan accuracy
### User Experience
- [ ] Session restore < 10 seconds
- [ ] Knowledge presentation < 3 concepts max
- [ ] User satisfaction > 4/5
- [ ] Knowledge accuracy > 90%
### Performance
- [ ] `understand` call < 100ms
- [ ] `create_concept` call < 50ms
- [ ] `list_roots` call < 50ms
- [ ] Memory overhead < 100MB
---
## Future Enhancements
### Short-Term (3-6 months)
1. **Graph Visualization in GSD Reports**
- Embed MegaMemory graph explorer in verification reports
- Interactive exploration of phase concepts
- Visual relationships between features and modules
2. **Knowledge-Aware Quick Mode**
- Enhance `/gsd-quick` to check MegaMemory
- Suggest relevant patterns for ad-hoc tasks
- Auto-link to existing concepts
3. **Smart Concept Updates**
- Detect file changes and flag related concepts
- Auto-update simple changes (file paths, comments)
- Notify user of potential updates needed
4. **Knowledge Export/Import**
- Export MegaMemory graph as JSON
- Share knowledge between projects
- Template knowledge for similar projects
### Medium-Term (6-12 months)
1. **Multi-Project Knowledge Sharing**
- Share patterns between projects
- Learn from past projects
- Organization-wide knowledge graph
2. **Knowledge-Assisted Debugging**
- Use MegaMemory to suggest bug locations
- Find similar issues in historical knowledge
- Pattern-based debugging suggestions
3. **Knowledge Metrics Dashboard**
- Track knowledge growth over time
- Identify knowledge gaps
- Visualize knowledge distribution
4. **Automated Refactoring Suggestions**
- Detect outdated patterns
- Suggest modernizations
- Link to current best practices
### Long-Term (12+ months)
1. **Machine Learning on Knowledge Graph**
- Predict next features based on patterns
- Identify architectural risks
- Suggest technical debt areas
2. **Knowledge-Aware Code Generation**
- Generate code following project patterns
- Consistent with decisions
- Integrated with existing architecture
3. **Cross-Project Learning**
- Learn what patterns work well
- Identify anti-patterns
- Recommend best practices
4. **Knowledge Collaboration**
- Share knowledge across teams
- Peer review of concepts
- Collaborative knowledge building
---
## Conclusion
This integration creates a powerful synergy between MegaMemory's knowledge persistence and GSD's structured development workflow:
**What Gets Better**:
- Knowledge captured automatically as you work
- Planning informed by past decisions and patterns
- Faster research cycles
- Better consistency across codebase
- Seamless session continuity
- Comprehensive documentation of decisions
**What Stays the Same**:
- GSD's workflow structure unchanged
- MegaMemory's tools unchanged
- User interactions unchanged
- Git commits unchanged
**What Changes**:
- Knowledge flows bidirectionally
- Agents are smarter with context
- Work is more informed
- Sessions are more productive
The integration is additive: it enhances both systems without breaking existing functionality. Users can adopt it incrementally or dive in with full integration.
**Next Steps**:
1. Review this plan with stakeholders
2. Prioritize features based on needs
3. Start Phase 1 implementation
4. Iterate based on feedback
5. Expand to full integration
The result: a development environment that remembers, learns, and gets smarter with every session.