# Automatic Context Loading System

## The Problem

Claude instances don't proactively review previous work before starting. User must say "review previous work first" which defeats the purpose of the context recovery system.

**Example failure:**
```
User: "Look at the Dataforth DFWDS folders"
Claude: "What work have we done on this?"  # WRONG - should check CONTEXT.md first
```

## The Solution: Tiered Hint System

### Tier 1: Quick Hints (CONTEXT.md)
- High-level overview (infrastructure, current state, anti-patterns)
- Fast to read (~30 seconds)
- Points to detailed resources
- **Location:** [project-root]/CONTEXT.md

### Tier 2: Detailed Resources
- Recent session logs (full commands, decisions)
- Implementation plans, technical specs
- Pointed to by CONTEXT.md

### Tier 3: Deep Archive
- Historical session logs
- Git history
- Full technical documentation

## Automatic Loading Rules

### Rule 1: Project Mention Detection

**When user message contains project keywords, auto-load CONTEXT.md:**

| Keywords | Load | Read Before Responding |
|----------|------|------------------------|
| "GuruRMM", "tunnel", "agents", "rmm-api" | projects/msp-tools/guru-rmm/CONTEXT.md | Yes |
| "Dataforth", "DFWDS", "testdatadb", "AD2", "VASLOG" | projects/dataforth-dos/CONTEXT.md | Yes |
| "ClaudeTools API", "work tracking" | CONTEXT.md (root) | Yes |

**Implementation:**
```python
import re

PROJECT_PATTERNS = {
    'gururmm': {
        'keywords': r'\b(GuruRMM|tunnel|rmm-api|gururmm|agent.*status)\b',
        'context_file': 'projects/msp-tools/guru-rmm/CONTEXT.md',
    },
    'dataforth': {
        'keywords': r'\b(Dataforth|DFWDS|testdatadb|AD2|AD1|VASLOG|SCMVAS|SCMHVAS)\b',
        'context_file': 'projects/dataforth-dos/CONTEXT.md',
    },
    'claudetools': {
        'keywords': r'\b(ClaudeTools API|work tracking|claudetools database)\b',
        'context_file': 'CONTEXT.md',
    },
}

def detect_project(user_message):
    for project, config in PROJECT_PATTERNS.items():
        if re.search(config['keywords'], user_message, re.IGNORECASE):
            return config['context_file']
    return None
```

### Rule 2: Continuation Context Detection

**When user says "continue", "let's work on", "back to", auto-check for active project:**

```
User: "Let's continue working on the tunnel"
Claude: [Detects "tunnel" → reads GuruRMM CONTEXT.md]
        "I see tunnel Phase 1 is complete (v0.6.0). Phase 2 is channel implementation..."
```

### Rule 3: Uncertainty Threshold

**When Claude's certainty < 95%, auto-check hints:**

```python
def should_check_hints(user_message, current_knowledge):
    """Check if we should read CONTEXT.md before responding"""

    # Rule 1: Project keyword mentioned
    if detect_project(user_message):
        return True

    # Rule 2: Continuation words
    if re.search(r'\b(continue|back to|work on|finish|resume)\b', user_message, re.I):
        return True

    # Rule 3: Infrastructure questions
    if re.search(r'\b(server|database|deploy|credentials|IP|password)\b', user_message, re.I):
        return True

    # Rule 4: Reference to past work
    if re.search(r'\b(last time|previous|recent|we did|earlier)\b', user_message, re.I):
        return True

    return False
```

## CONTEXT.md Standard Format

**Every project CONTEXT.md must have these sections:**

### Required Sections
1. **Quick Start - Infrastructure Overview** (table format)
2. **Current State (READ THIS FIRST)** - Recent work, versions deployed
3. **Anti-Patterns (DON'T DO THIS)** - Common mistakes to avoid
4. **Where to Find Things** - File structure, key paths
5. **Common Operations** - Copy-paste commands for frequent tasks
6. **Recent Session Logs** - Links to latest work

### Optional Sections
- Key Technical Decisions (ADRs)
- Troubleshooting (FAQ format)
- Roadmap
- Quick Reference (API endpoints, log formats, etc.)

## Implementation in .claude/CLAUDE.md

**Add this section to CLAUDE.md:**

```markdown
## Automatic Context Loading (MANDATORY)

**BEFORE responding to ANY user message, check these triggers:**

### Trigger 1: Project Keywords
If user mentions GuruRMM, Dataforth, tunnel, VASLOG, AD2, etc:
1. Identify project from keyword
2. Read [project]/CONTEXT.md ENTIRELY
3. Note current state, infrastructure, anti-patterns
4. THEN respond with full context

### Trigger 2: Continuation Words
If user says "continue", "let's work on", "back to", "resume":
1. Check for project in message
2. Read CONTEXT.md if found
3. Check recent session logs mentioned in CONTEXT.md
4. THEN proceed with work

### Trigger 3: Infrastructure Questions
If user asks about servers, databases, credentials, deployment:
1. Check root CONTEXT.md for project list
2. Read relevant project CONTEXT.md
3. Answer from CONTEXT.md (don't ask user)

### Trigger 4: Uncertainty
If you're <95% certain about infrastructure, recent work, or next steps:
1. Search for CONTEXT.md in current working directory
2. Search for CONTEXT.md in projects/*/
3. Read any found before asking user

**ANTI-PATTERN EXAMPLE:**
User: "Look at the Dataforth DFWDS folders"
You: "I don't recall what we've done with Dataforth"  # WRONG

**CORRECT PATTERN:**
User: "Look at the Dataforth DFWDS folders"
You: [Detects "Dataforth" → reads projects/dataforth-dos/CONTEXT.md]
     "I see from CONTEXT.md that recent work (2026-04-12) extended the SCMVAS/SCMHVAS
      pipeline. DFWDS folders are at C:\Shares\testdatadb\ on AD2 (192.168.0.6)..."
```

## Hook Integration

**Create .claude/hooks/pre-response:**

```bash
#!/bin/bash
# Pre-response hook: Check for CONTEXT.md

USER_MSG="$1"

# Check for project keywords
if echo "$USER_MSG" | grep -qi "GuruRMM\|tunnel\|rmm-api"; then
    echo "[HINT] Load projects/msp-tools/guru-rmm/CONTEXT.md"
    exit 0
fi

if echo "$USER_MSG" | grep -qi "Dataforth\|DFWDS\|testdatadb\|AD2\|VASLOG"; then
    echo "[HINT] Load projects/dataforth-dos/CONTEXT.md"
    exit 0
fi

# Check for continuation words
if echo "$USER_MSG" | grep -qi "continue\|back to\|work on\|resume"; then
    echo "[HINT] Check for active project CONTEXT.md"
    exit 0
fi

# Check for infrastructure questions
if echo "$USER_MSG" | grep -qi "server\|database\|deploy\|credentials"; then
    echo "[HINT] Check CONTEXT.md in current directory or projects/*/"
    exit 0
fi
```

## Session Start Protocol

**At the start of EVERY new session/conversation:**

1. Check current working directory for CONTEXT.md
2. If found, read it BEFORE asking user anything
3. If not found, check for projects/*/CONTEXT.md
4. List available projects from found CONTEXT.md files
5. Wait for user to specify what to work on
6. When they do, load that project's CONTEXT.md

**Example session start:**

```
[Claude starts, reads CONTEXT.md in /Users/azcomputerguru/ClaudeTools/]

Claude: "I've loaded context for ClaudeTools project. Available subprojects:
  - GuruRMM (tunnel Phase 2 pending)
  - Dataforth DOS (SCMVAS/SCMHVAS pipeline deployed)

  What would you like to work on?"

User: "GuruRMM tunnel"

[Claude reads projects/msp-tools/guru-rmm/CONTEXT.md]

Claude: "Loaded GuruRMM context:
  - Server: 172.16.3.30:3001
  - Phase 1 complete (v0.6.0)
  - 2/6 agents online
  - Next: Channel implementation

  Ready to proceed with Phase 2."
```

## Benefits

### For User
- ✅ Never repeat context ("What's the server IP?")
- ✅ Claude starts work immediately with full context
- ✅ No "let me check session logs" delays
- ✅ Consistent infrastructure knowledge

### For Claude
- ✅ Clear decision tree for when to load context
- ✅ Structured hints (CONTEXT.md) are fast to read
- ✅ Anti-patterns prevent repeated mistakes
- ✅ Recent session log pointers for deep-dive

### For System
- ✅ Scales to N projects (just add CONTEXT.md)
- ✅ Works across machines (Git-synced)
- ✅ Low overhead (only read when triggered)
- ✅ Degrades gracefully (if CONTEXT.md missing, ask user)

## Migration Path

### Phase 1: Create CONTEXT.md files (DONE ✅)
- [x] Root: CONTEXT.md
- [x] GuruRMM: projects/msp-tools/guru-rmm/CONTEXT.md
- [x] Dataforth: projects/dataforth-dos/CONTEXT.md

### Phase 2: Update CLAUDE.md with auto-load rules
```bash
# Add "Automatic Context Loading" section to .claude/CLAUDE.md
# Include triggers, anti-patterns, examples
```

### Phase 3: Train via /refresh-directives
```bash
# Every time Claude starts session:
# 1. Read CLAUDE.md (includes auto-load rules)
# 2. Apply triggers to user's first message
# 3. Load relevant CONTEXT.md before responding
```

### Phase 4: Create hook (optional)
```bash
# .claude/hooks/pre-response
# Automated hint detection, prints to stderr
```

## Validation

**Test cases to verify system works:**

| User Message | Expected Behavior | Pass/Fail |
|--------------|-------------------|-----------|
| "Look at Dataforth DFWDS" | Reads dataforth-dos/CONTEXT.md, knows AD2 IP | ✅ |
| "Continue GuruRMM tunnel" | Reads guru-rmm/CONTEXT.md, knows Phase 1 done | ✅ |
| "What's the database password?" | Checks CONTEXT.md, finds vault command | ✅ |
| "Deploy to AD2" | Reads dataforth/CONTEXT.md, knows deploy script | ✅ |
| "Check agent status" | Reads guru-rmm/CONTEXT.md, knows API endpoint | ✅ |

## Example: Before and After

### BEFORE (Current Problem)
```
User: "Look at the Dataforth DFWDS folders"

Claude: "I'm not sure what work we've done on Dataforth. Let me search session logs..."
        [Searches for 5 minutes]
        [Finds multiple sessions]
        "Can you tell me which server has the DFWDS folders?"

User: [Frustrated] "It's AD2 at 192.168.0.6, we just worked on this!"
```

### AFTER (With Auto-Context)
```
User: "Look at the Dataforth DFWDS folders"

Claude: [Detects "Dataforth" → reads projects/dataforth-dos/CONTEXT.md]
        "I see from CONTEXT.md that DFWDS folders are at C:\Shares\testdatadb\
         on AD2 (192.168.0.6). Recent work (2026-04-12) extended the SCMVAS/SCMHVAS
         pipeline. The testdatadb service is running on port 3000.

         What would you like me to check in those folders?"

User: [Happy] "Perfect, let's verify the Engineering-Tested files imported correctly"
```

## Rollout Plan

**Immediate (2026-04-14):**
- [x] Create CONTEXT.md for 3 main projects
- [ ] Update CLAUDE.md with auto-load rules
- [ ] Test with /refresh-directives

**Short-term (1 week):**
- [ ] Add CONTEXT.md for remaining projects
- [ ] Create pre-response hook
- [ ] Document in README

**Long-term (ongoing):**
- [ ] Update CONTEXT.md after major sessions
- [ ] Add new projects' CONTEXT.md as they start
- [ ] Refine triggers based on user feedback

---

**Implementation Status:** Phase 1 Complete (CONTEXT.md files created)
**Next Step:** Update .claude/CLAUDE.md with automatic loading rules
**Goal:** Claude is >95% certain before responding, never asks for context that's in CONTEXT.md
