/ CLAUDE.md
CLAUDE.md
  1  # CLAUDE.md
  2  
  3  This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
  4  
  5  ## Project Overview
  6  
  7  **The InterBrain** is an innovative knowledge management system that transcends traditional "Second Brain" paradigms. It's evolving from a standalone Electron app to a native Obsidian plugin, ultimately forming the foundation for DreamOS - a decentralized, AI-powered operating system for collective sensemaking.
  8  
  9  ### Core Concepts
 10  - **Dream Nodes**: Git repositories representing either ideas (Dreams) or people (Dreamers)
 11  - **Dream Talk**: Concise, symbolic representations of ideas
 12  - **Dream Song**: Elaborate explanations with references to other Dream Talks
 13  - **Liminal Web**: Self-organizing knowledge based on social relationships
 14  
 15  ### ⚠️ CRITICAL: .udd File Structure
 16  **IMPORTANT**: The `.udd` file is a **SINGLE JSON FILE**, NOT a directory.
 17  - **Correct**: `DreamNode/.udd` (single file containing all metadata)
 18  - **Wrong**: `DreamNode/.udd/metadata.json` (directory structure - OBSOLETE)
 19  
 20  This file contains the complete UDD (Universal Dream Description) schema including:
 21  - `uuid`, `title`, `type`, `dreamTalk`
 22  - `liminalWebRelationships`, `submodules`, `supermodules`
 23  - `email`, `phone`, `radicleId` (contact fields for dreamer-type nodes)
 24  
 25  ## Current Development Status
 26  
 27  **Current Branch**: `main`
 28  **Phase**: Epic 8 Completion - Soft Beta Launch Preparation
 29  
 30  **Epic Progress Summary**:
 31  - ✅ **Epics 1-7 Complete**: Foundation through Conversational Copilot (see CHANGELOG.md for details)
 32  - 🚧 **Epic 8 In Progress**: Coherence Beacon System + Soft Beta readiness (#258)
 33  
 34  **Three-Phase Launch Strategy**:
 35  1. **Soft Beta Launch** (~2 weeks) - Small closed group of tech-savvy peers, core functionality working end-to-end, acceptable rough edges
 36  2. **Hard Beta Launch** - Broader testing across diverse machines, refined UX, comprehensive robustness
 37  3. **Public Stable Release** - Full public announcement, polished experience, production-ready
 38  
 39  **Note**: For detailed achievement history of completed epics, see CHANGELOG.md
 40  
 41  ## Known Issues & Technical Debt
 42  
 43  ### Edit Mode Layout Issues
 44  **Status**: Deferred - Requires architectural analysis
 45  **Issue**: When exiting edit-search mode, all search results remain in ring layout instead of intelligently differentiating between:
 46  - **Glowing nodes** (pending relationships) - Should stay in ring
 47  - **Non-glowing nodes** (unrelated search results) - Should fly away to sphere
 48  
 49  **Context**: 
 50  - Escape navigation system works correctly (edit-search → edit → liminal-web)
 51  - Store correctly filters `searchResults` to only pending relationships when exiting edit-search
 52  - SpatialOrchestrator maintains separate `relatedNodesList` and `unrelatedSearchResultsList`
 53  - Canvas attempts to call `reorderEditModeSearchResults()` fail due to state coordination issues
 54  
 55  **Attempted Solutions** (August 26, 2025):
 56  - Direct filtering in canvas layout handler
 57  - Detection logic for edit-search transitions  
 58  - Multiple `showEditModeSearchResults` vs `reorderEditModeSearchResults` approaches
 59  
 60  **Next Steps**: 
 61  - Consider orchestrator state management refactor
 62  - May require unified layout state coordination between store and orchestrator
 63  - Alternative: Accept current behavior as "close enough" for MVP
 64  
 65  ### Liminal-Web Mode Toggle Issues
 66  **Status**: Deferred - Command queuing complexity  
 67  **Issue**: Quality-of-life toggles from liminal-web mode are unreliable:
 68  - **Search mode toggle**: Sometimes stops at constellation, doesn't complete transition to search
 69  - **Animation conflicts**: Dream node scaling and other effects interrupted by rushed transitions
 70  
 71  **Attempted Solutions** (August 26, 2025):
 72  - Sequential command queuing with 300ms delay
 73  - Proper animation timing with 1100ms delay (1000ms + 100ms buffer)
 74  - Fresh store references to prevent stale state
 75  
 76  **Root Cause**: Complex interaction between constellation settlement timing, animation states, and command queuing. The transitions work sometimes but are not consistently reliable.
 77  
 78  **Next Steps**: 
 79  - Consider simpler approach: disable toggles from liminal-web, require manual constellation return
 80  - Or: Deeper investigation into animation state coordination
 81  - Current workaround: Users can manually go constellation → search/creation
 82  
 83  ### Copilot Mode Transcript Refocus Polish
 84  **Status**: Deferred - Works but needs reliability improvement (October 3, 2025)
 85  **Issue**: After closing DreamSong/DreamTalk overlay with X button in copilot mode, transcript refocus is not 100% reliable in windowed mode (works fine in fullscreen):
 86  - **Current behavior**: Multiple refocus mechanisms trigger (event-driven, periodic check, overlay close handler)
 87  - **Expected**: Transcript should regain focus immediately for seamless dictation
 88  - **Workaround**: User can click anywhere in dreamspace or on transcript pane to restore focus
 89  
 90  **Attempted Solutions**:
 91  - Window focus listeners (browser window.focus())
 92  - Electron BrowserWindow.focus() via remote API
 93  - Programmatic click simulation on editor element
 94  - Multiple timing delays and refocus strategies
 95  
 96  **Root Cause**: In windowed mode, clicking X button causes Electron window to lose focus. Multiple refocus attempts trigger but dictation doesn't immediately resume. Likely macOS-specific input activation state issue.
 97  
 98  **Next Steps**:
 99  - Consider accepting current behavior as "good enough" - foundation works
100  - Or: Investigate macOS accessibility APIs for input state activation
101  - Current workaround is acceptable for MVP
102  
103  ### Progressive Loading for URI Clones
104  **Status**: Deferred - Future enhancement (October 17, 2025)
105  **Issue**: GitHub/Radicle clone links block UI during clone operation instead of showing immediate placeholder
106  
107  **Conceptual Design - Disk-Based Placeholder Approach**:
108  The key insight is to use **disk as single source of truth** rather than coordinating store-only placeholders:
109  
110  1. **Immediate Placeholder Creation**:
111     - Create directory + minimal `.udd` file BEFORE clone operation
112     - Trigger `scanVault()` immediately → shows placeholder in DreamSpace
113     - `.udd` contains: uuid, title (normalized from repo name), type, source URL/ID, empty relationships
114  
115  2. **Background Clone**:
116     - Use `git init + remote + fetch + reset --hard` instead of `git clone` (merge-friendly)
117     - Allows existing `.udd` file to persist during git operations
118     - Clone completes in background without blocking UI
119  
120  3. **Observation-First Approach**:
121     - Test what happens automatically when clone completes (existing code may handle it)
122     - Only add custom refresh logic if needed based on observation
123     - Simpler than coordinating complex state updates
124  
125  **Benefits**:
126  - Single source of truth (disk) eliminates state coordination complexity
127  - Leverages existing `scanVault()` infrastructure
128  - Git-native workflow with merge-friendly operations
129  - No React state synchronization issues
130  
131  **Implementation Notes**:
132  - `createMinimalUDD(destinationPath, repoName, sourceUrl, sourceType)` helper method
133  - Apply to both GitHub and Radicle clone flows
134  - Revert all store-only placeholder attempts (too complex)
135  
136  **Next Steps** (when prioritized):
137  - Implement for GitHub first, then map to Radicle
138  - Test placeholder appearance and clone completion behavior
139  - Document what automatic behavior occurs vs custom logic needed
140  
141  ### Incomplete DreamNode Metadata
142  **Status**: Known Limitation - Not a Bug (October 18, 2025)
143  **Issue**: DreamNodes cloned from repositories not fully initialized for InterBrain may exhibit constellation positioning issues:
144  - **Symptom**: Node may not return to proper constellation position when deselected after auto-focus
145  - **Root Cause**: Repository missing `.udd` file or has incomplete InterBrain metadata
146  - **Occurs**: When cloning external/legacy repositories not created through InterBrain
147  - **Both Radicle and GitHub**: Not specific to one clone method
148  
149  **Workaround**: Run "Scan vault for dream song relationships" command to refresh constellation layout
150  
151  **Fixes Applied**:
152  - ✅ File system timing issue for GitHub clones (async `.udd` write - commit 34658da)
153  - ✅ Branch selection optimization (clone only `main`, not `gh-pages` - commit 7a7fa2f)
154  
155  **Resolution**: Acceptable for MVP
156  - InterBrain-created DreamNodes work correctly out of the box
157  - Legacy/external repos have simple manual workaround
158  - Future: Consider auto-detection and repair of incomplete DreamNode metadata
159  
160  ### Proto Node Fly-In Animation Issues
161  **Status**: Deferred - Animation system complexity (August 26, 2025)
162  **Issue**: Proto node creation animation system needs refinement:
163  - **Desired behavior**: Fly-in animation when entering creation mode (like SearchNode3D)
164  - **Cancel/Escape**: Fly-out animation when canceling creation
165  - **Save**: Preserve existing save animation (move to final position, fade UI)
166  
167  **Attempted Solutions**:
168  - Multiple animation state system with spawn/save/cancel types
169  - Component mount animation triggers
170  - Animation timing coordination with useFrame hooks
171  
172  **Root Cause**: Complex interaction between component lifecycle, animation state management, and useFrame timing. Animation states conflict and create unwanted side effects.
173  
174  **Next Steps**:
175  - Consider simpler animation approach focusing only on essential transitions
176  - May require rethinking animation architecture for creation components
177  - Alternative: Accept current immediate appearance/disappearance as sufficient for MVP
178  - **Current Status**: Reverted to stable state (commit 3402622) with working core functionality
179  
180  ### Epic 1 Achievements (July 13, 2025)
181  - ✅ Obsidian plugin boilerplate with Vite dual workflow
182  - ✅ Zustand state management with 6 core commands
183  - ✅ Service layer abstraction (UI, Git, DreamNode, Vault)
184  - ✅ Vitest testing framework (47 tests passing)
185  - ✅ Command palette infrastructure established
186  
187  ### Epic 2 Achievements (July 18, 2025)
188  **All Features Complete**: #253 - 3D Spatial Visualization System | Spec: #265
189  
190  **✅ Completed Features**:
191  - ✅ #278 React Three Fiber Integration - Canvas in Obsidian workspace
192  - ✅ #306 DreamNode 3D Component - Star rendering with decoupled architecture
193  - ✅ #307 Layout State Management - Integrated with Zustand store
194  - ✅ #308 Rotatable Sphere Interaction - Google Earth style virtual trackball
195  - ✅ #279 Fibonacci Sphere Layout - Golden ratio node distribution
196  - ✅ #281 Dynamic View Scaling - Apple Watch style distance-based scaling
197  
198  **✅ Integration Complete**:
199  - 84 unit tests passing (100% coverage for new components)
200  - Zero lint warnings or errors
201  - Full TypeScript type safety
202  - Documentation updated
203  
204  ### ✅ Major Technical Achievement: Google Earth Style Rotation
205  
206  **Implementation**: `/src/dreamspace/SphereRotationControls.tsx`
207  **Documentation**: `/docs/technical-patterns.md` - Complete virtual trackball documentation with academic attribution
208  **Key Innovation**: Unified rotation mathematics eliminates momentum distortion while maintaining natural physics feel
209  
210  **Foundation Established**: Epic 2 now has solid foundation for all remaining features. The rotatable sphere interaction provides the core architecture for:
211  - Static camera + rotatable world pattern
212  - Unified layout management system 
213  - Performance-optimized Group transformations
214  - Debug tooling infrastructure via Obsidian commands
215  
216  ### GitHub Infrastructure
217  - **Repository**: [InterBrain](https://github.com/ProjectLiminality/InterBrain)
218  - **Project Board**: [InterBrain Development](https://github.com/users/ProjectLiminality/projects/2)
219  - **Issue Tracking**: [GitHub Issues](https://github.com/ProjectLiminality/InterBrain/issues)
220  - **Prototype Archive**: [InterBrain-Prototype](https://github.com/ProjectLiminality/InterBrain-Prototype)
221  
222  ## Architecture Philosophy: AI-First Development
223  
224  This project follows a **Pragmatic Hybrid Architecture** designed for optimal AI collaboration:
225  
226  ### Core Principle
227  **AI Readability >= Human Readability** - Code organization prioritizes context locality for AI assistants over traditional human-centric patterns.
228  
229  ### Architectural Pattern
230  Combines **Vertical Slice Architecture** (organize by feature) with **Atomic Design Principles** (shared UI components).
231  
232  ### Recommended Project Structure
233  
234  ```
235  interbrain-plugin/
236  ├── main.ts                     # Plugin entry point - registers all commands
237  ├── manifest.json               # Plugin metadata for Obsidian
238  ├── package.json               # Dependencies and build scripts
239  ├── src/
240  │   ├── commands/               # Command palette command definitions
241  │   ├── services/               # Service layer for business logic
242  │   ├── dreamspace/             # Core 3D/spatial domain logic
243  │   ├── features/               # Self-contained features (Vertical Slices)
244  │   ├── components/             # Shared UI (Atomic Design)
245  │   └── types/                  # TypeScript type definitions
246  └── styles.css                  # Plugin-specific styles
247  ```
248  
249  ### Development Rules
250  
251  1. **Commands Before UI**: Create command palette commands before building UI components
252  2. **Service Layer Abstraction**: Commands delegate to services, never direct git operations
253  3. **Mock/Real Service Swapping**: Use service interface pattern with MockDreamNodeService and GitDreamNodeService for fast UI iteration
254  4. **Default to Feature Slice**: New components go inside their feature folder first
255  5. **Promote to Shared Only on Second Use**: Move to `/components` only when needed by multiple features
256  6. **Dreamspace is Core Engine**: `/dreamspace` contains fundamental 3D/spatial logic only
257  7. **UI Calls Commands**: UI components use `executeCommandById()`, never call services directly
258  8. **Document for AI**: Every feature folder needs a `README.md` with high-level summary
259  9. **Testing Before Commits**: Use Playwright MCP to validate features work in browser before any git operations
260  10. **Node.js fs Preferred**: Use Node.js fs API directly for file operations, with VaultService as thin wrapper for path resolution
261  11. **❌ ANTI-PATTERN: Never use CSS transforms for 3D positioning** - Always use native React Three Fiber 3D positioning (groups, position props, rotation props) instead of CSS 2D hacks like `translateZ()` or `rotateY()`. CSS transforms are fundamentally 2D and break true 3D depth in R3F space.
262  
263  ### Epic 3 Service Layer Pattern
264  ```typescript
265  interface DreamNodeService {
266    create(title: string, type: NodeType, dreamTalk?: File): Promise<DreamNode>
267    update(id: string, changes: Partial<DreamNode>): Promise<void>
268    delete(id: string): Promise<void>
269    list(): Promise<DreamNode[]>
270  }
271  
272  // Runtime switching for development:
273  // - MockDreamNodeService: Fast UI iteration, no file system
274  // - GitDreamNodeService: Real git operations with DreamNode template
275  // - Command palette toggle: "Switch to Mock Data" / "Switch to Real Data"
276  ```
277  
278  ## Technology Stack
279  
280  ### Current Implementation (Epic 1 Complete)
281  - **Build System**: Vite with dual workflow (browser dev + plugin build)
282  - **Plugin Architecture**: Obsidian Plugin API with TypeScript
283  - **State Management**: Zustand reactive store
284  - **Testing**: Vitest with comprehensive mocking
285  - **Services**: UI, Git, DreamNode, and Vault service layers
286  - **Commands**: 6 core commands via Obsidian command palette
287  - **File System**: Node.js fs API (preferred) with VaultService as thin wrapper
288  
289  ### Epic 3 Implementation (COMPLETE - Ready for Main Merge)
290  - **Service Layer**: Interface-based architecture with mock/real implementations ✅
291  - **DreamNode Template**: Git template system stored in plugin directory with hooks ✅
292  - **Creator Mode Pattern**: Workspace isolation via automatic git stash operations ✅
293  - **DreamNode Selection**: Click-to-select infrastructure with visual feedback ✅
294  - **Visual Git States**: Red (work-in-progress), blue (unpushed), clean state indicators ✅
295  - **Mock Development**: Dynamic Zustand store for fast UI iteration without git complexity ✅
296  - **Git Operations**: `git init --template` for clean DreamNode repo creation ✅
297  
298  ### Planned Technologies (Future Epics)
299  - **Frontend**: React + React Three Fiber (R3F) for 3D visualization
300  - **File System**: Obsidian Vault API + shell git commands
301  - **Storage**: Git repositories as data structure
302  - **UI**: Atomic Design with shared component library
303  - **AI Integration**: Aider, Claude, and other AI pair-programming tools
304  
305  ## Development Workflow
306  
307  **Core Development Commands**: Use slash commands for systematic workflow execution:
308  - `/epic-start` - Begin new epic with specification clarity and branch setup
309  - `/feature-start` - Start feature with knowledge transfer and issue refinement
310  - `/feature-complete` - Complete feature with mandatory user testing and integration
311  - `/epic-complete` - Finalize epic with quality assurance, documentation, and release
312  
313  **Key Principles**:
314  - **Issue Clarity Before Implementation**: Always refine issues through knowledge transfer interviews
315  - **User Testing Protocol**: Never commit without user validation
316  - **Issue Hierarchy**: Epic → Features (simplified from previous 3-tier Epic → Spec → Feature model)
317  - **Branch Strategy**: `main → epic/N-name → feature/name-from-issue`
318  
319  **GitHub Issue Hierarchy Decision** (October 2025):
320  - Simplified from 3-tier (Epic → Specification → Feature) to 2-tier (Epic → Feature)
321  - Rationale: Specifications added unnecessary layer for this project's workflow
322  - Existing spec issues remain open for future epics, new issues follow 2-tier model
323  
324  ## Epic Quick Reference
325  
326  **Completed Epics**:
327  - **Epic 1**: #252 - Plugin Infrastructure ✅ Complete
328  - **Epic 2**: #253 - 3D Spatial Visualization System ✅ Complete
329  - **Epic 3**: #254 - DreamNode Management System ✅ Complete
330  - **Epic 4**: #255 - Liminal Web Layout System ✅ Complete
331  - **Epic 5**: #256 - Semantic Search System ✅ Complete
332  - **Epic 6**: #259 - DreamWeaving Operations ✅ Complete
333  - **Epic 7**: #257 - Conversational Copilot System ✅ Complete
334  
335  **Active Epic**:
336  - **Epic 8**: #258 - Coherence Beacon System + Soft Beta Launch 🚧 In Progress
337  
338  **Current Project Status**:
339  - **7 major epics completed** with comprehensive feature sets
340  - **Epic 8 in progress** - Final collaboration layer + polish for soft beta
341  - **Soft Beta Launch target**: ~2 weeks (small closed group testing)
342  
343  ## Technical Documentation References
344  
345  For detailed technical information, see:
346  
347  - **[Technical Patterns](docs/technical-patterns.md)**: Proven algorithms, spatial layouts, and code patterns from prototype
348  - **[UX Specifications](docs/ux-specifications.md)**: Detailed interaction flows, search functionality, and user experience design
349  - **[Architecture Details](docs/architecture-details.md)**: DreamNode lifecycle, git operations, coherence beacon system, and technical implementation
350  
351  ## GitHub CLI Commands Reference
352  
353  **List All Open Epics**:
354  ```bash
355  gh issue list --repo ProjectLiminality/InterBrain --label epic --state open
356  ```
357  
358  **List All Open Specifications**:
359  ```bash
360  gh issue list --repo ProjectLiminality/InterBrain --label specification --state open
361  ```
362  
363  **List All Open Features**:
364  ```bash
365  gh issue list --repo ProjectLiminality/InterBrain --label feature --state open
366  ```
367  
368  **View Issue Details**:
369  ```bash
370  gh issue view ISSUE_NUMBER
371  ```
372  
373  **Check Your Assigned Issues**:
374  ```bash
375  gh issue list --assignee @me --state open
376  ```
377  
378  **Feature Branch Completion Workflow** (NOT Epic Completion):
379  1. **Complete Implementation**: All acceptance criteria met (no version bumping or CHANGELOG updates)
380  2. **Update Issue Body**: Edit issue to check off `[x]` all completed criteria  
381  3. **Close with Session Summary**: `gh issue close ISSUE_NUMBER --comment "session summary"`
382  4. **Merge to Epic Branch**: Merge feature branch to epic branch
383  5. **Clean Up**: Delete feature branch after epic integration
384  
385  **CRITICAL**: Feature branch completion does NOT include:
386  - Version bumping (happens in Epic completion only)
387  - CHANGELOG updates (happens in Epic completion only)  
388  - Documentation updates (happens in Epic completion only)
389  - Release creation (happens in Epic completion only)
390  
391  ## Advanced GitHub CLI & Project Board Management
392  
393  ### Issue Creation Commands
394  
395  **Create Epic Issue**:
396  ```bash
397  gh issue create --repo ProjectLiminality/InterBrain \
398    --title "Epic N: Title" \
399    --label epic \
400    --body "## Vision\n\nDescription\n\n## Success Criteria\n\n- [ ] All child specifications completed\n- [ ] Features integrated and tested\n- [ ] Epic goals achieved\n\n## Development Status\n\nReady for specification"
401  ```
402  
403  **Create Specification Issue**:
404  ```bash
405  gh issue create --repo ProjectLiminality/InterBrain \
406    --title "Title Specification" \
407    --label specification \
408    --body "## Overview\n\nTechnical specification\n\n## Architecture\n\nDetails\n\n## Implementation Plan\n\nPlan\n\n## User Experience\n\nUX details\n\n## Feature Breakdown\n\nWill be populated as features are created\n\n## Definition of Done\n\n- [ ] All child Features completed\n- [ ] Integration tested\n- [ ] Documentation complete"
409  ```
410  
411  **Create Feature Issue**:
412  ```bash
413  gh issue create --repo ProjectLiminality/InterBrain \
414    --title "Feature Title" \
415    --label feature \
416    --body "## Description\n\nFeature description\n\n## Acceptance Criteria\n\n- [ ] Feature implementation meets specification requirements\n- [ ] User interactions work as designed\n- [ ] Performance meets expected thresholds\n\n## Dependencies\n\n- Parent specification must be approved\n- Any prerequisite features completed\n\n## Definition of Done\n\n- [ ] Implementation complete\n- [ ] Tests passing\n- [ ] Documentation updated\n- [ ] Code reviewed and merged"
417  ```
418  
419  ### Project Board Management (GraphQL API)
420  
421  **CRITICAL**: Parent-child relationships and project board status are managed via GraphQL API, not basic GitHub CLI.
422  
423  **Project Board IDs**:
424  - InterBrain Development: `PVT_kwHOC0_fLc4A9SR1`
425  - Status Field ID: `PVTSSF_lAHOC0_fLc4A9SR1zgxCErc`
426  - Status Options: `f75ad846` (Planning), `47fc9ee4` (Active), `98236657` (Integration), `e1f23fa9` (Complete)
427  
428  **Find Issue Project Item ID**:
429  ```bash
430  gh api graphql -f query='
431  {
432    repository(owner: "ProjectLiminality", name: "InterBrain") {
433      issue(number: ISSUE_NUMBER) {
434        id
435        projectItems(first: 10) {
436          nodes {
437            id
438            project {
439              id
440              title
441            }
442          }
443        }
444      }
445    }
446  }'
447  ```
448  
449  **Move Issue to Complete Status**:
450  ```bash
451  gh api graphql -f query='
452  mutation {
453    updateProjectV2ItemFieldValue(
454      input: {
455        projectId: "PVT_kwHOC0_fLc4A9SR1"
456        itemId: "PROJECT_ITEM_ID_FROM_ABOVE"
457        fieldId: "PVTSSF_lAHOC0_fLc4A9SR1zgxCErc"
458        value: {
459          singleSelectOptionId: "e1f23fa9"
460        }
461      }
462    ) {
463      projectV2Item {
464        id
465      }
466    }
467  }'
468  ```
469  
470  ### Parent-Child Issue Relationships
471  
472  **IMPORTANT**: GitHub CLI does not directly support parent-child relationships. These are managed through:
473  
474  1. **Issue Body References**: Include in issue body:
475     ```markdown
476     **Parent Epic**: #255
477     **Parent Specification**: #267
478     **Child Features**: #287, #288, #289
479     ```
480  
481  2. **GitHub's Web Interface**: Use "Development" section in issue sidebar to link related issues
482  
483  3. **Project Board Hierarchy**: Use custom fields in project board to track relationships
484  
485  ### Issue Management Workflow
486  
487  **Standard Epic Creation Workflow**:
488  1. Create Epic issue with basic template
489  2. Add Epic to project board (auto-assigned to Planning status)
490  3. Create Specification issue with parent reference in body
491  4. Create Feature issues with parent spec reference
492  5. Use GraphQL to move issues through project board states as work progresses
493  
494  **Epic Completion Protocol** (3-Tier Issue Hierarchy):
495  1. **Complete ALL Implementation Work First**: Code, tests, documentation, merge to main, cleanup
496  2. **ONLY AFTER Work is Complete**: Update and close issues (Specification first, then Epic)
497  3. **CHANGELOG Analysis**: Review relevant git commit history (not just project memory) for precise documentation
498  4. **Pristine Code Requirement**: `npm run check-all` must show zero warnings/errors at any level
499  
500  **CRITICAL: Never update issue bodies or close issues until all work is merged and complete**
501  
502  ### Critical Commands Reference
503  
504  **When creating issues**: ALWAYS use the templates above to maintain consistency
505  **When managing project board**: ALWAYS use GraphQL API for status changes
506  **When closing epics**: ALWAYS update project board status first, then close issue
507  
508  **If unsure about any GitHub CLI commands**: Refer to this section FIRST, then use `gh help <command>` for detailed syntax.
509  
510  ## AI Assistant Integration
511  
512  This project is designed for AI-first development:
513  
514  ### Workflow
515  - Use AI assistants (Claude, Aider) as primary development partners
516  - Maintain high context locality for token efficiency
517  - Document features with AI-readable summaries
518  - Leverage git-based architecture for AI tool integration
519  
520  ### Context Management
521  - Each feature slice contains complete context for AI understanding
522  - Avoid scattering related functionality across multiple directories
523  - Use descriptive folder and file names for AI comprehension
524  
525  ### Playwright MCP Testing Integration
526  - **Dev Server Management**: User starts dev server (`npm run dev`) - AI never starts it to avoid breaking agentic loop
527  - **Browser Testing**: Use Playwright MCP to validate functionality at `http://localhost:5173`
528  - **Validation Protocol**: Test features in actual browser environment before commits
529  - **Console Monitoring**: Ensure clean console logs (no errors/warnings)
530  - **Screenshot Documentation**: Capture visual proof of working features
531  - **Testing-First Completion**: No git operations until browser testing confirms functionality works
532  
533  ## Obsidian Plugin Integration Approach
534  
535  **Custom View Type Registration**:
536  - Register "dreamspace" as a new view type in Obsidian
537  - Implement WorkspaceLeaf with React Three Fiber canvas
538  - Support fullscreen mode via CSS transforms
539  
540  **File System Integration**:
541  - Use Obsidian's Vault API for file operations
542  - Shell out to git commands for repository management
543  - Parse .canvas files using Obsidian's built-in canvas functionality
544  
545  **Canvas Integration**:
546  - Leverage existing Obsidian canvas files for DreamSong content
547  - Watch for changes to .canvas files via Obsidian's file events
548  - Parse canvas topology on git commits to update DreamSong UI
549  
550  ## Epic 3 Git Workflow Patterns
551  
552  ### DreamNode Template System
553  ```bash
554  # Template stored in plugin directory (outside vault)
555  DreamNode-template/
556  ├── .udd                  # Single JSON file: UUID, title, type, dreamTalk, relationships
557  ├── hooks/
558  │   ├── pre-commit        # Template initialization + canvas validation
559  │   ├── post-commit       # Bidirectional supermodule tracking
560  │   └── hook-helper.js    # Node.js utilities for hook operations
561  └── README.md            # DreamNode documentation
562  
563  # DreamNode creation:
564  git init --template=${pluginPath}/DreamNode-template
565  ```
566  
567  ### Git Hooks System (Coherence Beacon Foundation)
568  
569  **Pre-Commit Hook** - Initialization & Validation:
570  - **First commit only**: Moves template files (.udd, README.md, LICENSE) from `.git/` to working directory
571  - **Canvas validation**: Warns when committing `.canvas` files, reminds user to run "Sync Canvas Submodules"
572  - **Non-blocking**: Always allows commit to proceed (just provides helpful reminders)
573  
574  **Post-Commit Hook** - Bidirectional Relationship Tracking:
575  - **Detects submodule changes**: Compares `.gitmodules` between HEAD and HEAD~1
576  - **Added submodules**:
577    - Initializes submodule to ensure `.udd` is readable
578    - Adds child UUID to parent's `submodules` array
579    - Adds parent UUID to child's `supermodules` array
580    - Commits relationship in child repo
581  - **Removed submodules**:
582    - Removes child UUID from parent's `submodules` array
583    - Child's `supermodules` becomes stale (acceptable - will sync on next use)
584  - **Automatic commits**: Creates "Update submodule relationships" commit in parent repo
585  
586  **Hook Helper Script** (`hook-helper.js`):
587  - **UDD operations**: Read, write, add/remove supermodule/submodule relationships
588  - **Git operations**: Parse `.gitmodules`, compare commits, execute git commands
589  - **Callable from shell**: Provides CLI interface for hook scripts
590  - **Reusable logic**: Shared utilities for both pre-commit and post-commit hooks
591  
592  **Key Design Decisions**:
593  - Git natively tracks submodules via `.gitmodules`, BUT `.udd` also tracks them for:
594    - UUID-based relationships (git uses paths, we use UUIDs)
595    - Coherence Beacon discovery (who uses this DreamNode?)
596    - Symmetry with `supermodules` array
597  - Bidirectional tracking: Parent tracks children (`submodules`), children track parents (`supermodules`)
598  - Hooks use Node.js for complex logic (JSON parsing, file I/O)
599  - All hook output goes to stderr (keeps stdout clean for git)
600  - Hooks never fail - log errors but allow operations to complete
601  
602  ### Creator Mode Workflow (Feature #310 Complete)
603  ```bash
604  # Enter Creator Mode (restore work-in-progress):
605  git stash pop || true  # Handle empty stash gracefully
606  
607  # Exit Creator Mode (preserve work-in-progress):
608  git add -A && git stash push -m "InterBrain creator mode"
609  
610  # Save Action (commit and exit creator mode):
611  git add -A && git commit -m "User commit message"
612  ```
613  
614  **Visual Git State Hierarchy**:
615  - **Red Glow**: Uncommitted OR stashed changes (work-in-progress takes priority)
616  - **Blue Glow**: Committed but unpushed changes (ready to share)
617  - **Clean**: No glow for synchronized repositories
618  - **Detection**: `git status --porcelain=v1 --branch` with regex parsing for unpushed commits
619  
620  ### Development Mode Switching
621  ```typescript
622  // Command palette commands for development:
623  // "InterBrain: Switch to Mock Data" - Fast UI iteration
624  // "InterBrain: Switch to Real Data" - Full git integration
625  // "InterBrain: Reset Mock Store" - Clean slate for testing
626  ```
627  
628  ## Testing Best Practices
629  
630  **Comprehensive Validation Command**:
631  - Always use `npm run check-all` for complete code validation
632  - This single command runs tests, linting, and type checking
633  - Replaces the need to run separate npm commands
634  - Run this before committing changes or completing features
635  
636  **VaultService Testing Decision**:
637  - **DO NOT create unit tests for VaultService** - Deliberate architectural decision
638  - **Rationale**: VaultService is a thin wrapper around Node.js fs operations (migrated from hybrid Obsidian API in commit 753c260)
639  - **Why no tests**: Testing direct filesystem operations in unit tests is complex, brittle, and provides little value
640  - **Coverage strategy**: Integration tests and real-world usage provide sufficient validation
641  - **Previous attempt**: Epic 6 cleanup revealed obsolete tests testing non-existent hybrid API - removed entirely
642  - **Future**: If VaultService grows business logic beyond fs wrappers, add tests for that logic only, not fs operations
643  
644  **Epic Completion Workflow**:
645  - **MANDATORY**: Comprehensive quality assurance and documentation updates before merging to main
646  - **NO RELEASE BRANCHES**: All updates happen directly on the epic branch
647  - **Philosophy**: Bring work to completion with all quality housekeeping addressed
648  
649  ### Phase 1: Quality Assurance & Testing
650  1. Fix any lint errors, warnings, or type errors
651  2. Run `npm run check-all` to ensure all tests pass
652  3. Review test coverage - ensure all new functions have appropriate tests
653  4. Write any missing tests for edge cases or uncovered code paths
654  
655  ### Phase 2: Documentation Updates
656  **Follow Documentation Architecture Pattern**:
657  - **Root level files** (README.md, CHANGELOG.md): High-level updates and cross-references
658  - **docs/ directory**: Detailed technical documentation updates
659  
660  **Required Updates**:
661  1. **README.md**: Update project status, roadmap checkmarks, epic completion notes
662  2. **CHANGELOG.md**: Add new version section with comprehensive epic details:
663     - All completed features with issue numbers
664     - Technical achievements and innovations
665     - Architecture changes and patterns introduced
666     - Any breaking changes or migration notes
667  3. **Technical Documentation** (docs/):
668     - Update relevant files in docs/technical-patterns.md, docs/architecture-details.md, etc.
669     - Add new patterns discovered during epic implementation
670     - Document any new architectural decisions or patterns
671     - Ensure cross-references between docs are accurate
672  4. **Project CLAUDE.md**: Update epic status, current development phase, any new patterns
673  
674  ### Phase 3: Version Release
675  1. On epic branch: Bump version in package.json
676  2. On epic branch: Commit all changes with message "Release vX.Y.Z: Epic N - Title"
677  3. Final `npm run check-all` to ensure everything still passes
678  
679  ### Phase 4: Merge to Main
680  1. Switch to main branch locally
681  2. Merge epic branch locally (no GitHub PR)
682  3. Push main to remote
683  
684  ### Phase 5: Release & Cleanup
685  1. Create and push git tag vX.Y.Z
686  2. Create GitHub release with comprehensive notes from CHANGELOG.md
687  3. Close epic issue with completion summary
688  4. Delete epic branch (local and remote)
689  5. Update CLAUDE.md to reflect next epic as active
690  
691  ## Key Files
692  
693  - `README.md`: Comprehensive project documentation with features and vision
694  - `docs/development/roadmap.md`: 3-month development plan for Obsidian plugin
695  - `docs/architecture/overview.md`: Architectural guidelines for AI-first development
696  - `docs/technical-patterns.md`: Proven algorithms and code patterns
697  - `docs/ux-specifications.md`: Detailed user experience specifications
698  - `docs/architecture-details.md`: Technical implementation details
699  
700  ## Media Storage Architecture (Future Implementation)
701  
702  ### Problem: localStorage Quota Exceeded with Large Media Files
703  When dropping large media files (videos, podcasts) into DreamNodes, the app stores entire file content in localStorage via dreamTalkMedia field, quickly exceeding the 5-10MB browser limit.
704  
705  ### Solution: Obsidian-Native File Streaming
706  **Path of Least Resistance**: Store only file paths in localStorage, use Obsidian's file:// protocol for instant streaming.
707  
708  **Key Insights**:
709  - Obsidian provides direct file:// URL access to vault files
710  - Browsers handle local files with near-zero latency (10-50ms to first frame)
711  - HTML5 video element supports byte-range requests for instant playback without full load
712  - Local SSD performance (3-7 GB/s) makes streaming seamless
713  
714  **Implementation Strategy**:
715  1. **Immediate**: Store only vault paths in `dreamTalkMedia`, not file content
716  2. **Lazy Loading**: Use Intersection Observer to preload media as nodes approach viewport
717  3. **Progressive Enhancement**: Show thumbnail instantly, stream full media on interaction
718  4. **Optional Future**: IndexedDB for generated thumbnails/preview clips
719  
720  **Performance Approach**:
721  ```typescript
722  // Instant playback pattern
723  videoElement.src = vault.adapter.getResourcePath(file); // file:// URL
724  videoElement.preload = "metadata"; // Load just headers
725  videoElement.play(); // Starts in <50ms
726  ```
727  
728  This achieves the desired immediate, responsive preview experience without storage limitations.
729  
730  ## License
731  
732  GNU AFFERO GENERAL PUBLIC LICENSE - This project is open source with copyleft requirements.