Skip to content

Instantly share code, notes, and snippets.

@mikaelj
Created February 7, 2026 09:28
Show Gist options
  • Select an option

  • Save mikaelj/70551a4d6885fea08fa4f1fe5726c42d to your computer and use it in GitHub Desktop.

Select an option

Save mikaelj/70551a4d6885fea08fa4f1fe5726c42d to your computer and use it in GitHub Desktop.

MegaMemory × GSD-OpenCode Deep Integration Plan

Executive Summary

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:

  1. GSD activities automatically populate MegaMemory with valuable insights
  2. MegaMemory knowledge informs and enhances GSD planning and execution

Integration Architecture

┌─────────────────────────────────────────────────────────────────┐
│                        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

Integration Points Across GSD Workflow

1. Project Initialization Phase

GSD Command: /gsd-new-project

Integration Actions:

Before: Knowledge Preload

## 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

After: Knowledge Capture

## 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

2. Codebase Mapping (Brownfield Projects)

GSD Command: /gsd-map-codebase

Integration Actions:

Automatic Knowledge Capture

## 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

3. Phase Discussion

GSD Command: /gsd-discuss-phase [N]

Integration Actions:

Context Retrieval Before Discussion

## 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)

Context Integration in Discussion

## 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 flow

Benefits:

  • Leverages existing knowledge during decision-making
  • Prevents reinventing wheels
  • Makes decisions more informed

4. Phase Planning

GSD Command: /gsd-plan-phase [N]

Integration Actions:

Research Enhancement

## 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

Plan Enhancement

## 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

5. Phase Execution

GSD Command: /gsd-execute-phase [N]

Integration Actions:

Automatic Knowledge Capture

## 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"

Decision Capture

## 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"}
    ]

Pattern Capture

## 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

6. Work Verification

GSD Command: /gsd-verify-work [N]

Integration Actions:

Knowledge Validation

## 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?"

Knowledge Updates

## 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

7. Session Continuation

Scenario: User returns after closing OpenCode

Integration Actions:

Session Restore

## 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)

Context Injection

## 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

Detailed Integration Specification

MCP Tool Usage in GSD Workflows

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

Concept Creation Patterns

Pattern 1: Feature Concepts

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 feature

Pattern 2: Module Concepts

When: 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 module

Pattern 3: Pattern Concepts

When: 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 used

Pattern 4: Decision Concepts

When: 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 considered

Pattern 5: Config Concepts

When: 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

Concept Naming Convention

// 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

Edge Relationship Usage

Relation When to Use Example
depends_on A requires B to function auth-flowuser-model
implements A fulfills B user-registrationrequirement-user-signup
calls A directly invokes B auth-middlewarejwt-service
connects_to A interfaces with B frontendapi-layer
configured_by A uses settings from B auth-flowuse-jose-for-jwt

Enhanced GSD Templates

Modified PROJECT.md Template

# [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]*

Modified CONTEXT.md Template

# 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]*

Modified PLAN.md Template

---
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>

Implementation Roadmap

Phase 1: Foundation (Week 1-2)

Goal: Basic bidirectional flow working

Tasks:

  1. 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
  2. Add list_roots check to /gsd-new-project

    • Check for existing graph before initialization
    • Present existing concepts to user
    • Ask user if they want to load context
  3. Add concept creation to /gsd-new-project completion

    • Create project root concept after PROJECT.md created
    • Create requirement concepts after REQUIREMENTS.md created
    • Create tech stack decision concept
  4. Add understand call to /gsd-discuss-phase

    • Extract key terms from phase name and scope
    • Query MegaMemory for relevant concepts
    • Present findings to user
  5. Add context injection to CONTEXT.md generation

    • Add "MegaMemory Context" section
    • List relevant concepts found
    • Track applied vs overridden concepts
  6. 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-project creates MegaMemory concepts
  • Running /gsd-discuss-phase retrieves relevant knowledge
  • CONTEXT.md includes MegaMemory context section
  • All tests pass

Phase 2: Codebase Mapping Integration (Week 3)

Goal: Capture architecture knowledge automatically

Tasks:

  1. 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
  2. Parse architecture.md

    • Extract module names and descriptions
    • Create "module" concepts for each subsystem
    • Link modules with "connects_to" edges
  3. Parse patterns.md

    • Extract pattern names and descriptions
    • Create "pattern" concepts
    • Include file examples and usage contexts
  4. Parse conventions.md

    • Extract coding conventions
    • Create "pattern" concepts with kind="convention"
    • Tag with "coding-standards"
  5. Create appropriate edges

    • Link modules to each other based on dependencies
    • Link patterns to modules that use them
    • Link conventions to applicable areas
  6. Test on existing codebase

    • Run /gsd-map-codebase on sample project
    • Verify all modules captured
    • Verify all patterns captured
    • Verify edges are correct

Deliverables:

  • Automatic architecture knowledge capture
  • Pattern documentation in graph
  • Module relationships documented
  • Test suite for mapping integration

Acceptance Criteria:

  • Running /gsd-map-codebase creates module concepts
  • Patterns are extracted and captured
  • Conventions are documented
  • Edges correctly represent relationships
  • All tests pass

Phase 3: Planning Enhancement (Week 4)

Goal: Knowledge-assisted research and planning

Tasks:

  1. Add understand to gsd-phase-researcher workflow

    • Before research starts, query MegaMemory
    • Extract phase-specific queries from phase name
    • Feed relevant concepts into researcher context
  2. 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
  3. Add MegaMemory section to RESEARCH.md

    • List similar implementations found
    • List architectural patterns applicable
    • Link to relevant concepts
  4. 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
  5. Add knowledge references to PLAN.md

    • Add "MegaMemory References" section
    • List knowledge applied in plan
    • List patterns to follow
    • Include specific implementation guidance
  6. 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

Phase 4: Execution Capture (Week 5-6)

Goal: Automatic knowledge capture during execution

Tasks:

  1. 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
  2. Capture features as implemented

    • Identify user-facing features
    • Create "feature" concepts with summaries
    • Link to parent modules/requirements
    • Add file references
  3. Capture modules as implemented

    • Identify new subsystems
    • Create "module" concepts
    • Document responsibilities and key files
    • Link to related modules
  4. Capture patterns as implemented

    • Identify reusable implementation patterns
    • Create "pattern" concepts
    • Document usage and examples
    • Link to features/modules that use them
  5. Capture decisions when choices made

    • Identify significant technical choices
    • Create "decision" concepts
    • Document rationale and tradeoffs
    • Link to implementations
  6. Create appropriate edges

    • Link features to modules they depend on
    • Link modules to each other
    • Link decisions to implementations
    • Link patterns to usage
  7. Update existing concepts when changes made

    • Detect when concepts need updating
    • Update summaries, file_refs
    • Update embeddings automatically
  8. Remove outdated concepts when needed

    • Detect when features are removed/replaced
    • Soft-remove concepts with reasons
    • Preserve history
  9. Test: execute-phase and verify knowledge capture

    • Run /gsd-execute-phase
    • Verify features captured
    • Verify patterns captured
    • Verify decisions captured
    • Verify edges created

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

Phase 5: Verification Integration (Week 7)

Goal: Knowledge validation during verification

Tasks:

  1. 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
  2. Present MegaMemory concepts to user

    • Show summary of captured knowledge
    • Show new concepts from this phase
    • Show updated concepts
    • Allow user to review
  3. Allow user to add/update concepts

    • Provide interface for concept edits
    • Allow adding missing concepts
    • Allow updating incomplete concepts
    • Allow removing incorrect concepts
  4. Update concepts based on verification findings

    • If user provides feedback, update concepts
    • Fix inaccuracies discovered during UAT
    • Update file_refs to current implementation
  5. Test: verify-work with knowledge updates

    • Run /gsd-verify-work
    • Provide user feedback
    • Verify concepts are updated
    • Verify accuracy improves

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

Phase 6: Session Continuity (Week 8)

Goal: Seamless session restoration

Tasks:

  1. Add MegaMemory check on session start

    • Detect when new session starts
    • Check if MegaMemory graph exists
    • Load graph state
  2. Present knowledge graph state

    • Show total number of concepts
    • Show top-level modules/features
    • Show recent changes
    • Show knowledge graph statistics
  3. Inject relevant context into STATE.md

    • Add "MegaMemory State" section
    • List key concepts
    • Show recent activity
  4. Provide knowledge loading option

    • Ask user if they want to load context
    • If yes, inject relevant concepts
    • If no, proceed without MegaMemory
  5. Enhance /gsd-resume-work command

    • Load MegaMemory graph
    • Restore session state
    • Present knowledge context
    • Suggest next actions
  6. 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

Phase 7: Optimization & Polish (Week 9-10)

Goal: Refine and optimize integration

Tasks:

  1. Performance testing with large knowledge graphs

    • Create test graph with 1000+ concepts
    • Measure tool call latencies
    • Measure memory usage
    • Identify bottlenecks
  2. Optimize concept creation frequency

    • Implement thresholding to reduce noise
    • Only create significant concepts
    • Batch concept creation where possible
    • Cache concept lookups
  3. Add duplicate detection and deduplication

    • Before creating, check for similar concepts
    • Use similarity matching to find duplicates
    • Merge overlapping concepts
    • Prevent redundant knowledge
  4. Improve context relevance scoring

    • Fine-tune similarity thresholds
    • Improve query generation
    • Better relevance ranking
    • Reduce false positives
  5. Add knowledge graph visualization to GSD reports

    • Embed graph explorer in verification reports
    • Interactive exploration of phase concepts
    • Visual relationships between features and modules
  6. Documentation and examples

    • Write user guide for integrated workflow
    • Create example projects demonstrating integration
    • Document best practices
    • Create troubleshooting guide
  7. 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

Benefits Analysis

For Development Workflow

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

For MegaMemory

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

For GSD

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

Potential Challenges & Mitigations

Challenge 1: Concept Proliferation

Problem: Automatic capture could create too many concepts, making graph noisy.

Mitigations:

  1. 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
  2. Deduplication: Check for similar existing concepts before creating

    • Use understand to find similar concepts
    • Update existing rather than create new
    • Merge overlapping concepts
  3. User Approval: Ask user before creating low-confidence concepts

    • "Found pattern X. Create concept?"
    • Allow batch approvals
  4. Pruning: Periodically review and clean graph

    • Remove concepts with few connections
    • Merge similar concepts
    • Archive old patterns

Challenge 2: Knowledge Staleness

Problem: Knowledge can become outdated as code evolves.

Mitigations:

  1. 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)
  2. Verification Integration: Check knowledge during /gsd-verify-work

    • Validate file references still exist
    • Confirm implementation matches description
    • Update or flag mismatches
  3. Explicit Updates: Require knowledge updates during refactoring

    • Add knowledge update step to refactoring plans
    • Mark refactored concepts as "needs review"
  4. Version Tracking: Track when concepts were last verified

    • Add verified_at timestamp
    • Flag stale concepts in list_roots

Challenge 3: Context Overload

Problem: Too much knowledge presented could overwhelm GSD agents.

Mitigations:

  1. 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
  2. Phased Exposure: Reveal knowledge progressively

    • Start with high-level concepts during discussion
    • Add detail during planning
    • Show implementation-specific during execution
  3. Selective Loading: User controls what to load

    • Ask: "Load all context or select areas?"
    • Allow toggling specific concept types
  4. Context Budgeting: Track token usage

    • Limit knowledge context to X% of budget
    • Prioritize by relevance score

Challenge 4: Tool Call Overhead

Problem: Frequent MCP tool calls could slow down workflows.

Mitigations:

  1. Caching: Cache concept lookups

    • In-memory cache during workflow
    • TTL-based invalidation
    • Batch operations where possible
  2. Selective Calls: Only call when necessary

    • Don't create concepts for trivial changes
    • Batch multiple creates into single call
    • Lazy load references
  3. Async Operations: Make non-critical calls async

    • Background knowledge updates
    • Don't block on concept creation
  4. Performance Targets: Set acceptable overhead limits

    • <5% additional time for workflows
    • <100ms per understand call
    • Monitor and optimize

Challenge 5: Knowledge Quality

Problem: Agent-generated concepts might be inaccurate or incomplete.

Mitigations:

  1. Template Enforcement: Use strict templates for concept creation

    • Required fields: name, kind, summary
    • Encouraged: why, file_refs
    • Format guidelines
  2. Validation: Validate concepts before persisting

    • Check required fields
    • Validate parent exists
    • Validate edge targets
    • Check for duplicates
  3. Review Workflow: Allow user review of significant concepts

    • Present high-impact concepts for approval
    • Allow edits before saving
    • Reject incorrect concepts
  4. Feedback Loop: Learn from user corrections

    • Track which concepts are edited
    • Identify patterns in corrections
    • Improve creation templates

Testing Strategy

Unit Tests

// 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');
  });
});

Integration Tests

// 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');
  });
});

End-to-End Tests

# 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 requirements

2. Map Codebase

Run: /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 concepts

3. Discuss Phase

Run: /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.md

4. Plan Phase

Run: /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.md

5. Execute Phase

Run: /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)

6. Verify Work

Run: /gsd-verify-work 1 Expect:

  • User can review captured knowledge
  • User can add/update concepts
  • Knowledge reflects implementation

7. Pause Session

Run: /gsd-pause-work Expect:

  • Session state saved
  • MegaMemory graph persisted

Validate:

# Check graph persisted
ls .megamemory/knowledge.db  # Should exist

8. Resume Session

Restart OpenCode Expect:

  • MegaMemory graph loaded
  • Context presented
  • Can resume work

9. Next Phase

Run: /gsd-discuss-phase 2 Expect:

  • Previous phase knowledge available
  • Context informed by MegaMemory

Validation After Each Step

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment