From a18fa5f93a4ebf8ced2c97f065d0f8c3f601b543 Mon Sep 17 00:00:00 2001 From: Mike Swanson Date: Fri, 1 May 2026 18:33:46 -0700 Subject: [PATCH] ClaudeTools cleanup: drop dead context-recall layer, unify /save + /sync MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Deletions (~1,500 lines of dead docs): - .claude/hooks/ — docs-only directory, no executables. Referenced scripts setup-context-recall.sh / test-context-recall.sh did not exist. Hooks would have POSTed to localhost:8000; the API actually ran at 172.16.3.30:8001 and is no longer in use. - .claude/AUTO_CONTEXT_SYSTEM.md — 347-line duplicate spec of CLAUDE.md's Automatic Context Loading section, referencing unimplemented hooks. - .claude/URGENT-vault-path-bug.md — 217-line urgency note for a fix that already shipped weeks ago. - .claude/context-recall-config.env.example — config template for the same dead system. Refactors (~500 lines net removed): - /save and /sync now wrap bash .claude/scripts/sync.sh as the single source of truth for git ops. /save adds a session-log-writing step in front; /sync invokes the script directly. - Dropped /sync's manual git phases that contradicted sync.sh. - Dropped the cp -r ~/ClaudeTools/.claude/commands/* ~/.claude/commands/ step (clobbered per-user customization in the multi-user model). - Dropped auto-invoke of /refresh-directives (command does not exist). - Dropped references to directives.md (file does not exist). - /save now documents the rm -f save_narrative_prompt.txt step, fixing the stale-prompt bug Howard documented in feedback_tmp_path_windows.md. Fixes: - CLAUDE.md SESSION_STATE.md reference replaced with the canonical PROJECT_STATE.md (per-project, with protocol at .claude/PROJECT_STATE_PROTOCOL.md). 16 client folders already use PROJECT_STATE.md; SESSION_STATE.md was only a stale reference. Co-Authored-By: Claude Opus 4.7 (1M context) --- .claude/AUTO_CONTEXT_SYSTEM.md | 347 --------------- .claude/CLAUDE.md | 4 +- .claude/URGENT-vault-path-bug.md | 217 --------- .claude/commands/save.md | 234 ++++------ .claude/commands/sync.md | 517 ++-------------------- .claude/context-recall-config.env.example | 11 - .claude/hooks/.gitkeep | 2 - .claude/hooks/EXAMPLES.md | 390 ---------------- .claude/hooks/INSTALL.md | 223 ---------- .claude/hooks/README.md | 323 -------------- 10 files changed, 127 insertions(+), 2141 deletions(-) delete mode 100644 .claude/AUTO_CONTEXT_SYSTEM.md delete mode 100644 .claude/URGENT-vault-path-bug.md delete mode 100644 .claude/context-recall-config.env.example delete mode 100644 .claude/hooks/.gitkeep delete mode 100644 .claude/hooks/EXAMPLES.md delete mode 100644 .claude/hooks/INSTALL.md delete mode 100644 .claude/hooks/README.md diff --git a/.claude/AUTO_CONTEXT_SYSTEM.md b/.claude/AUTO_CONTEXT_SYSTEM.md deleted file mode 100644 index c382b24..0000000 --- a/.claude/AUTO_CONTEXT_SYSTEM.md +++ /dev/null @@ -1,347 +0,0 @@ -# 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 diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md index 14b4bf4..118cf02 100644 --- a/.claude/CLAUDE.md +++ b/.claude/CLAUDE.md @@ -186,9 +186,9 @@ This applies to ALL session logs pulled during sync, not just the most recent on ## Context Recovery When user references previous work, use `/context` command. Never ask for info in: -- `credentials.md` — Infrastructure reference (being migrated to SOPS vault at D:\vault) +- `credentials.md` — Infrastructure reference (being migrated to SOPS vault) - `session-logs/` — Daily work logs (also in `projects/*/session-logs/` and `clients/*/session-logs/`) -- `SESSION_STATE.md` — Project history +- `projects/*/PROJECT_STATE.md` and `clients/*/PROJECT_STATE.md` — per-project state (active locks, current state, recent changes). Loaded automatically per Trigger 2 above; protocol at `.claude/PROJECT_STATE_PROTOCOL.md` ### Credential Access (SOPS Vault) diff --git a/.claude/URGENT-vault-path-bug.md b/.claude/URGENT-vault-path-bug.md deleted file mode 100644 index 238c7ba..0000000 --- a/.claude/URGENT-vault-path-bug.md +++ /dev/null @@ -1,217 +0,0 @@ -# URGENT: Vault Path Variable Collision Bug - -**Date:** 2026-04-21 -**Severity:** CRITICAL - Blocks all remediation-tool usage -**Affected:** All machines (DESKTOP-0O8A1RL, ACG-Tech03L, Mikes-MacBook-Air) -**Discovered on:** Mikes-MacBook-Air during vault wrapper testing - ---- - -## TL;DR for Windows Laptop - -**BEFORE doing Howard's vault sync task, fix this bug first:** - -The recent vault portability changes introduced a variable name collision in `get-token.sh` that breaks token acquisition on all machines. - -**Quick fix (2 minutes):** -1. Open `.claude/skills/remediation-tool/scripts/get-token.sh` -2. Rename the `VAULT_PATH` environment variable to `VAULT_ROOT_ENV` -3. Test: `./get-token.sh grabblaw.com investigator` -4. If working, commit fix and push -5. THEN proceed with Howard's vault sync task - ---- - -## Bug Details - -### Root Cause - -**Variable name collision in get-token.sh around line 87-95:** - -```bash -# PROBLEM: VAULT_PATH is used for TWO different things - -# Line ~40-70: VAULT_PATH stores the SOPS file relative path -case "$TIER" in - investigator) - CLIENT_ID="bfbc12a4-f0dd-4e12-b06d-997e7271e10c" - VAULT_PATH="msp-tools/computerguru-security-investigator.sops.yaml" # <-- SOPS file path - SCOPE_URL="https://graph.microsoft.com/.default" - ;; - ... -esac - -# Line ~87-95: VAULT_PATH is ALSO used as environment variable for vault root -VAULT_ROOT="${VAULT_PATH:-}" # <-- BUG: This gets the SOPS path, not the vault root! -if [[ -z "$VAULT_ROOT" && -f "$IDENTITY_FILE" ]]; then - for py in py python3 python; do - if command -v "$py" >/dev/null 2>&1; then - VAULT_ROOT=$("$py" -c "import json; print(json.load(open('$IDENTITY_FILE')).get('vault_path',''))" 2>/dev/null) && break - fi - done -fi -``` - -**Result:** `VAULT_ROOT` gets set to `msp-tools/computerguru-security-investigator.sops.yaml` instead of the vault directory path. - -### Observed Failure - -```bash -$ ./get-token.sh cascadestucson.com investigator - -ERROR: vault not found at msp-tools/computerguru-security-investigator.sops.yaml - (check vault_path in /Users/azcomputerguru/ClaudeTools/.claude/identity.json) -``` - -The script is checking if `msp-tools/computerguru-security-investigator.sops.yaml` exists as a directory, which fails. - ---- - -## Remediation Steps - -### Step 1: Fix Variable Name Collision - -**File:** `.claude/skills/remediation-tool/scripts/get-token.sh` - -**Find (around line 87):** -```bash -VAULT_ROOT="${VAULT_PATH:-}" -``` - -**Replace with:** -```bash -VAULT_ROOT="${VAULT_ROOT_ENV:-}" -``` - -**And update the error message (around line 95):** -```bash -[[ -z "$VAULT_ROOT" ]] && { echo "ERROR: vault_path not set in $IDENTITY_FILE and VAULT_ROOT_ENV env var not set" >&2; exit 3; } -``` - -**Purpose:** Separates the SOPS file path variable (`VAULT_PATH`) from the vault root override environment variable (now `VAULT_ROOT_ENV`). - -### Step 2: Add vault_path to identity.json - -**File:** `.claude/identity.json` (on DESKTOP-0O8A1RL) - -**Add this field:** -```json -{ - "user": "mike", - "full_name": "Mike Swanson", - "email": "mike@azcomputerguru.com", - "role": "admin", - "machine": "DESKTOP-0O8A1RL", - "vault_path": "D:/vault" -} -``` - -**On ACG-Tech03L (Howard's machine), the path is likely:** -```json -"vault_path": "D:/vault" -``` - -**On Mikes-MacBook-Air (if vault is cloned later):** -```json -"vault_path": "/Users/azcomputerguru/vault" -``` - -### Step 3: Test the Fix - -**On DESKTOP-0O8A1RL:** -```bash -cd D:\ClaudeTools\.claude\skills\remediation-tool\scripts - -# Test with a fully onboarded tenant -bash get-token.sh grabblaw.com investigator - -# Should output a JWT token (long string starting with eyJ...) -# Or at least get past the vault path error -``` - -**Expected success output:** -``` -eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6... -``` - -**If still failing, check:** -1. Is `D:/vault/scripts/vault.sh` present? -2. Does `D:/vault/msp-tools/computerguru-security-investigator.sops.yaml` exist? -3. Is SOPS configured with the correct age key? - -### Step 4: Commit and Sync - -```bash -cd D:\ClaudeTools - -git add .claude/skills/remediation-tool/scripts/get-token.sh -git commit -m "fix: vault path variable collision in get-token.sh - -Renamed VAULT_PATH env var to VAULT_ROOT_ENV to avoid collision with -the SOPS file path variable. Fixes token acquisition on all machines. - -Bug discovered during Mac testing 2026-04-21. - -Co-Authored-By: Claude Sonnet 4.5 " - -git push origin main -``` - -### Step 5: Notify Howard - -Once fixed and pushed, tell Howard to: -1. Pull ClaudeTools: `cd C:\ClaudeTools && git pull` -2. Add `vault_path` to his `.claude/identity.json` -3. Test: `bash get-token.sh grabblaw.com investigator` - ---- - -## After This Fix - Original Vault Sync Task - -**THEN proceed with Howard's vault sync request:** - -1. Navigate to `D:\vault` -2. Verify 5 new-tier SOPS files exist in `D:\vault\msp-tools\` -3. Git add, commit, push to vault repo -4. Notify Howard to pull vault on ACG-Tech03L - ---- - -## Why This Happened - -The recent portability improvements (commits 0a7cd6b and a86df11) added per-machine vault path support via `identity.json`. The implementation correctly updated `.claude/scripts/vault.sh` but inadvertently created a variable name collision in `get-token.sh` by reusing `VAULT_PATH` for both: -- The SOPS file relative path (existing usage) -- The environment variable override (new usage) - -This is a regression introduced in the last 2 commits from DESKTOP-0O8A1RL. - ---- - -## Testing Checklist - -After applying the fix: - -- [ ] Token acquisition works on DESKTOP-0O8A1RL: `get-token.sh grabblaw.com investigator` -- [ ] Token acquisition works on DESKTOP-0O8A1RL: `get-token.sh grabblaw.com investigator-exo` -- [ ] All 5 tiers work: investigator, investigator-exo, user-manager, tenant-admin, defender -- [ ] Vault wrapper works: `bash .claude/scripts/vault.sh list` -- [ ] Howard can pull and test on ACG-Tech03L (after vault sync) -- [ ] Mac can test once vault is cloned there - ---- - -## Impact Assessment - -**Blocked operations until fixed:** -- All remediation-tool token acquisition -- All breach checks via remediation-tool skill -- Howard's Cascades spoofing hunt (double-blocked: this bug + missing SOPS files) -- Any tenant investigation work - -**Urgency:** Fix immediately before attempting vault sync task. - ---- - -**Created:** 2026-04-21 19:10 (Mac session) -**Status:** URGENT - Needs Windows laptop remediation -**Next session:** Read this file first, apply fix, test, commit, then do vault sync diff --git a/.claude/commands/save.md b/.claude/commands/save.md index a141dae..16b2c86 100644 --- a/.claude/commands/save.md +++ b/.claude/commands/save.md @@ -1,25 +1,44 @@ -Save a COMPREHENSIVE session log to appropriate session-logs/ directory. This is critical for context recovery. +Save a comprehensive session log to the appropriate `session-logs/` directory, then sync the repo. -## Ollama drafting (documentation engine) +`/save` and `/sync` share `bash .claude/scripts/sync.sh` as the canonical driver for git operations. The only difference: `/save` writes a session log first, then calls sync. `/sync` calls sync directly (no log). -Narrative sections are drafted by Ollama (qwen3:14b), then assembled with Claude-generated factual sections. Claude reviews the full document before writing. +--- -**Ollama drafts:** Session Summary, Key Decisions, Problems Encountered -**Claude owns (verbatim, never delegated):** Credentials, infrastructure IPs/hostnames, command outputs, file paths, pending tasks +## Phase 1 — Generate the narrative -### Draft call +Ollama drafts the prose sections (qwen3:14b at `localhost:11434` or Tailscale `100.92.127.64:11434`). Claude owns the factual sections — never delegate facts to Ollama. + +| Author | Sections | +|---|---| +| Ollama | Session Summary, Key Decisions, Problems Encountered | +| Claude (verbatim) | User block, Configuration Changes, Credentials, Infrastructure, Commands & Outputs, Pending Tasks, References | + +### Resolve Ollama endpoint ```bash -# Check Ollama (reuse $OLLAMA across the save operation) -if curl -s -m 2 http://localhost:11434/api/tags >/dev/null 2>&1; then OLLAMA="http://localhost:11434" -elif curl -s -m 3 http://100.92.127.64:11434/api/tags >/dev/null 2>&1; then OLLAMA="http://100.92.127.64:11434" -else OLLAMA=""; fi +if curl -s -m 2 http://localhost:11434/api/tags >/dev/null 2>&1; then + OLLAMA="http://localhost:11434" +elif curl -s -m 3 http://100.92.127.64:11434/api/tags >/dev/null 2>&1; then + OLLAMA="http://100.92.127.64:11434" +else + OLLAMA="" # Claude drafts narrative directly +fi +``` -# Write narrative prompt to temp file -cat > "C:/Users/guru/AppData/Local/Temp/save_narrative_prompt.txt" << 'ENDPROMPT' -You are a technical session log writer for an MSP (managed service provider). -Write three sections of a session log in markdown. Be concise, factual, and technical. -No filler phrases. Use past tense. +### Draft via Ollama + +**Always delete the prompt file first** — prior `/save` runs leave a stale `save_narrative_prompt.txt` in `%LOCALAPPDATA%/Temp`, and the Write tool refuses to overwrite without a Read. The silent fallback is `py` reading the leftover file and Ollama producing a perfectly-coherent narrative about *the previous session's work*. Documented in `.claude/memory/feedback_tmp_path_windows.md`. + +```bash +PROMPT_FILE="$LOCALAPPDATA/Temp/save_narrative_prompt.txt" +rm -f "$PROMPT_FILE" # critical — see above +# ... then Write the prompt with this session's WORK DONE bullets ... +``` + +Prompt template: + +``` +You are a technical session log writer for an MSP (Arizona Computer Guru). Write three sections in markdown. Be concise, factual, technical. No filler phrases. Use past tense. No emojis. WORK DONE THIS SESSION: @@ -27,157 +46,94 @@ WORK DONE THIS SESSION: Write these three sections only: ## Session Summary -<2-4 paragraph narrative: what was accomplished, in what order, why> +<3-5 paragraph narrative: what was accomplished, in what order, why> ## Key Decisions - + ## Problems Encountered -ENDPROMPT - -NARRATIVE=$(py -c " -import urllib.request, json -prompt = open('C:/Users/guru/AppData/Local/Temp/save_narrative_prompt.txt', encoding='utf-8').read() -body = json.dumps({'model':'qwen3:14b','messages':[{'role':'user','content':prompt}],'stream':False,'think':False}).encode() -res = json.loads(urllib.request.urlopen(urllib.request.Request('$OLLAMA/api/chat', body), timeout=120).read()) -print(res['message']['content']) -") - -# Fallback: if OLLAMA empty, Claude writes narrative directly ``` -Claude reviews the narrative output before assembling the final document. +Run via Python (PyJWT-free path): + +```bash +py -c " +import urllib.request, json +prompt = open('$PROMPT_FILE', encoding='utf-8').read() +body = json.dumps({'model':'qwen3:14b','messages':[{'role':'user','content':prompt}],'stream':False,'think':False}).encode() +res = json.loads(urllib.request.urlopen(urllib.request.Request('$OLLAMA/api/chat', body), timeout=300).read()) +print(res['message']['content']) +" +``` + +Claude reviews the output before assembling. Common Ollama issues to fix on review: invented compliance/risk language, hallucinated reasoning, off-task content if the prompt file was stale. --- -## Determine Correct Location +## Phase 2 — Write to disk -**IMPORTANT: Save to project-specific or general session-logs based on work context** +### Location -### Project-Specific Logs -If working on a specific project, save to project folder: -- Dataforth DOS work → `projects/dataforth-dos/session-logs/YYYY-MM-DD-session.md` -- ClaudeTools API work → `projects/claudetools-api/session-logs/YYYY-MM-DD-session.md` -- Client-specific work → `clients/[client-name]/session-logs/YYYY-MM-DD-session.md` +| Work scope | Path | +|---|---| +| Single project | `projects//session-logs/YYYY-MM-DD-session.md` | +| Client | `clients//session-logs/YYYY-MM-DD-session.md` | +| Multi-project / general | `session-logs/YYYY-MM-DD-session.md` | -### General/Mixed Work -If working across multiple projects or general tasks: -- Use root `session-logs/YYYY-MM-DD-session.md` +### Filename + append behavior -## Filename -Use format `YYYY-MM-DD-session.md` (today's date) in appropriate folder +- Filename: `YYYY-MM-DD-session.md` (today's local date) +- If file exists, **append** a `## Update: HH:MM PT — ` section. Do not overwrite. +- If two users worked on the same date, namespace: `YYYY-MM-DD--.md` (e.g. `2026-05-01-howard-syncro-billing-batch.md`) -## If file exists -Append a new section with timestamp header (## Update: HH:MM), don't overwrite +### Required sections (in order) -## MANDATORY Content to Include +1. **User block** — name, machine, role, session span. Pull from `.claude/identity.json` + git config. +2. **Session Summary** (Ollama) +3. **Key Decisions** (Ollama) +4. **Problems Encountered** (Ollama) +5. **Configuration Changes** — files modified / created / deleted (with paths) +6. **Credentials & Secrets** — UNREDACTED if newly discovered or created. Vault paths if vaulted. Never half-redact a value future-Claude might need. +7. **Infrastructure & Servers** — IPs, hostnames, ports, tenant IDs, container names, DNS, certs +8. **Commands & Outputs** — important one-liners, key outputs, error messages with resolution +9. **Pending / Incomplete Tasks** — what's left, blockers, next steps +10. **Reference Information** — URLs, endpoints, commit SHAs, ticket IDs, routine IDs, file paths -### 1. Session Summary -- What was accomplished in this session -- Key decisions made and rationale -- Problems encountered and how they were solved +When in doubt, include MORE detail — future sessions search these logs to recover context. -### 2. ALL Credentials & Secrets (UNREDACTED) -**CRITICAL: Store credentials completely - these are needed for future sessions** -- API keys and tokens (full values) -- Usernames and passwords -- Database credentials -- JWT secrets -- SSH keys/passphrases if relevant -- Any authentication information used or discovered +--- -Format credentials as: -``` -### Credentials -- Service Name: username / password -- API Token: full_token_value +## Phase 3 — Sync + +```bash +bash .claude/scripts/sync.sh ``` -### 3. Infrastructure & Servers -- All IPs, hostnames, ports used -- Container names and configurations -- DNS records added or modified -- SSL certificates created -- Any network/firewall changes +`sync.sh` handles: stage tracked changes by name (never `git add -A`), auto-commit, fetch + rebase, push, then the same flow for the vault repo, then surface cross-user `## Note for ` blocks. -### 4. Commands & Outputs -- Important commands run (especially complex ones) -- Key outputs and results -- Error messages and their resolutions - -### 5. Configuration Changes -- Files created or modified (with paths) -- Settings changed -- Environment variables set - -### 6. Pending/Incomplete Tasks -- What still needs to be done -- Blockers or issues awaiting resolution -- Next steps for future sessions - -### 7. Reference Information -- URLs, endpoints, ports -- File paths that may be needed again -- Any technical details that might be forgotten - -## After Saving - -Before committing, emit a **Change Summary** block for the user to review: +After sync, emit a **Post-commit Summary**: ``` -## Change Summary (this session) -User: (from .claude/identity.json) -Machine: - -Files changed: - - -Stats: - +## Post-commit Summary +Commit: +Author: <> +Push: .. main -> main (origin) +File: (+N lines, appended/created) ``` -Then: -1. Commit with message: "Session log: [brief description of work done]" -2. Push to gitea remote (if configured) -3. After push, emit a **Post-commit Summary**: - - New commit SHA + message - - Author (from `git log -1 --format='%an <%ae>'`) - - Files in the commit (from `git show --stat HEAD`) -4. Confirm push was successful +--- -### Why the summary +## Cross-user note handling (CRITICAL) -In the multi-user setup, commits can land in `main` from either team member. Always attributing author + files makes it obvious who made what change when someone else pulls the repo. Saves re-reading diffs to figure out "wait, when did that happen?" +If `sync.sh` surfaces a `## Note for ` or `## Message for ` block from an incoming session log, display it **prominently at the top of the response, before the sync summary**: -## Purpose +``` +============================================================ +MESSAGE FROM () +============================================================ + +============================================================ +``` -This log MUST contain enough detail to fully restore context if this conversation is summarized or a new session starts. When in doubt, include MORE information rather than less. Future Claude instances will search these logs to find credentials and context. - -## Project-Specific Requirements - -### Dataforth DOS Project -Save to: `projects/dataforth-dos/session-logs/` -Include: -- DOS batch file changes and versions -- Deployment script updates -- Infrastructure changes (AD2, D2TESTNAS) -- Test results from TS-XX machines -- Documentation files created - -### ClaudeTools API Project -Save to: `projects/claudetools-api/session-logs/` -Include: -- Database connection details (172.16.3.30:3306/claudetools) -- API endpoints created or modified -- Migration files created -- Test results and coverage -- Any infrastructure changes (servers, networks, clients) - -### Client Work -Save to: `clients/[client-name]/session-logs/` -Include: -- Issues resolved -- Services provided -- Support tickets/cases -- Client-specific infrastructure changes +Explicitly address each action item or question before moving on. diff --git a/.claude/commands/sync.md b/.claude/commands/sync.md index b28b31a..5ff8944 100644 --- a/.claude/commands/sync.md +++ b/.claude/commands/sync.md @@ -1,504 +1,47 @@ -# /sync - Bidirectional ClaudeTools Sync +Sync the ClaudeTools and vault repos with Gitea. -Synchronize ClaudeTools configuration, session data, and context bidirectionally with Gitea. Ensures all machines stay perfectly in sync for seamless cross-machine workflow. +## What this does + +Invokes `bash .claude/scripts/sync.sh`, which: + +1. Stages tracked local changes **by name** (never `git add -A` — avoids picking up `.env`, generated files, etc.) +2. Auto-commits any local changes with `sync: auto-sync from at ` +3. Fetches from origin, rebases local commits onto remote +4. Pushes to origin +5. Repeats 1-4 for the **vault** repo (path read from `.claude/identity.json` `vault_path` field) +6. Surfaces any `## Note for ` / `## Message for ` blocks from incoming session logs + +The script is the single source of truth for git operations. Both `/sync` and `/save` invoke it. --- -## IMPORTANT: Use Automated Sync Script +## Cross-user note handling (CRITICAL) -**CRITICAL:** When user invokes `/sync`, execute the automated sync script instead of manual steps. +If sync surfaces a note from another user, display it **prominently at the top of the response, before the sync summary**, formatted as: -**Windows:** -```bash -bash .claude/scripts/sync.sh ``` -OR -```cmd -.claude\scripts\sync.bat +============================================================ +MESSAGE FROM () +============================================================ + +============================================================ ``` -**Mac/Linux:** -```bash -bash .claude/scripts/sync.sh -``` - -**Why use the script:** -- Ensures PULL happens BEFORE PUSH (prevents missing remote changes) -- Consistent behavior across all machines -- Proper error handling and conflict detection -- Automated timestamping and machine identification -- No steps can be accidentally skipped - -**The script automatically:** -1. Checks for local changes -2. Commits local changes (if any) -3. **Fetches and pulls remote changes FIRST** -4. Pushes local changes -5. Reports sync status +Address each action item or question explicitly before moving on. Do not bury cross-user notes in the sync summary or skip them because other work is in progress. --- -## What Gets Synced +## Output format -**FROM Local TO Gitea (PUSH):** -- Session logs: `session-logs/*.md` -- Project session logs: `projects/*/session-logs/*.md` -- Credentials: `credentials.md` (private repo - safe to sync) -- Project state: `SESSION_STATE.md` -- Commands: `.claude/commands/*.md` -- Directives: `directives.md` -- File placement guide: `.claude/FILE_PLACEMENT_GUIDE.md` -- Behavioral guidelines: - - `.claude/CODING_GUIDELINES.md` (NO EMOJIS, ASCII markers, standards) - - `.claude/AGENT_COORDINATION_RULES.md` (delegation guidelines) - - `.claude/agents/*.md` (agent-specific documentation) - - `.claude/CLAUDE.md` (project context and instructions) - - Any other `.claude/*.md` operational files -- Any other tracked changes - -**FROM Gitea TO Local (PULL):** -- All of the above from other machines -- Latest commands and configurations -- Updated session logs from other sessions -- Project-specific work and documentation +Report: +- Pulled commits — count + authors + one-line summaries +- Pushed commits — count + your commits + outgoing SHAs +- Vault sync status — pulled/pushed/clean +- Cross-user notes addressed (if any) +- Final HEAD + status --- -## Execution Steps +## Companion: `/save` -### Phase 1: Prepare Local Changes - -1. **Navigate to ClaudeTools repo:** - ```bash - cd ~/ClaudeTools # or D:\ClaudeTools on Windows - ``` - -2. **Check repository status:** - ```bash - git status - ``` - Report number of changed/new files to user - -3. **Stage all changes:** - ```bash - git add -A - ``` - This includes: - - New/modified session logs - - Updated credentials.md - - SESSION_STATE.md changes - - Command updates - - Directive changes - - Behavioral guidelines (CODING_GUIDELINES.md, AGENT_COORDINATION_RULES.md, etc.) - - Agent documentation - - Project documentation - -4. **Auto-commit local changes with timestamp:** - ```bash - git commit -m "sync: Auto-sync from [machine-name] at [timestamp] - - Synced files: - - Session logs updated - - Latest context and credentials - - Command/directive updates - - Machine: [hostname] - Timestamp: [YYYY-MM-DD HH:MM:SS] - - Co-Authored-By: Claude Sonnet 4.5 " - ``` - - **Note:** Only commit if there are changes. If working tree is clean, skip to Phase 2. - ---- - -### Phase 2: Sync with Gitea - -5. **Pull latest changes from Gitea:** - ```bash - git pull origin main --rebase - ``` - - **Handle conflicts if any:** - - Session logs: Keep both versions (rename conflicting file with timestamp) - - credentials.md: Manual merge required - report to user - - Other files: Use standard git conflict resolution - - Report what was pulled from remote - -6. **Push local changes to Gitea:** - ```bash - git push origin main - ``` - - Confirm push succeeded - ---- - -### Phase 3: Apply Configuration Locally - -7. **Copy commands to global Claude directory:** - ```bash - mkdir -p ~/.claude/commands - cp -r ~/ClaudeTools/.claude/commands/* ~/.claude/commands/ - ``` - These slash commands are now available globally - -8. **Apply global settings if available:** - ```bash - if [ -f ~/ClaudeTools/.claude/settings.json ]; then - cp ~/ClaudeTools/.claude/settings.json ~/.claude/settings.json - fi - ``` - -9. **Sync project settings:** - ```bash - if [ -f ~/ClaudeTools/.claude/settings.local.json ]; then - # Read and note any project-specific settings - fi - ``` - ---- - -### Phase 4: Context Recovery - -10. **Find and read most recent session logs:** - - Check all locations: - - `~/ClaudeTools/session-logs/*.md` (general) - - `~/ClaudeTools/projects/*/session-logs/*.md` (project-specific) - - Report the 3 most recent logs found: - - File name and location - - Last modified date - - Brief summary of what was worked on (from first 5 lines) - -11. **Read behavioral guidelines and directives:** - ```bash - cat ~/ClaudeTools/directives.md - cat ~/ClaudeTools/.claude/CODING_GUIDELINES.md - cat ~/ClaudeTools/.claude/AGENT_COORDINATION_RULES.md - ``` - Internalize operational directives and behavioral rules to ensure: - - Proper coordination mode (delegate vs execute) - - NO EMOJIS rule enforcement - - Agent delegation patterns - - Coding standards compliance - ---- - -### Phase 5: Report Sync Status - -12. **Summarize what was synced:** - - ``` - ## Sync Complete - - [OK] Local changes pushed to Gitea: - - X session logs updated - - credentials.md synced - - SESSION_STATE.md updated - - Y command files - - [OK] Remote changes pulled from Gitea: - - Z files updated from other machines - - Latest session: [most recent log] - - [OK] Configuration applied: - - Commands available: /checkpoint, /context, /save, /sync, etc. - - Directives internalized (coordination mode, delegation rules) - - Behavioral guidelines internalized (NO EMOJIS, ASCII markers, coding standards) - - Agent coordination rules applied - - Global settings applied - - Recent work (last 3 sessions): - 1. [date] - [project] - [brief summary] - 2. [date] - [project] - [brief summary] - 3. [date] - [project] - [brief summary] - - **Status:** All machines in sync. Ready to continue work. - ``` - -13. **Refresh directives (auto-invoke):** - - Automatically invoke `/refresh-directives` to internalize all synced behavioral guidelines: - - Re-read directives.md - - Re-read CODING_GUIDELINES.md - - Re-read AGENT_COORDINATION_RULES.md - - Perform self-assessment for violations - - Commit to following all behavioral rules - - **Why this is critical:** - - Ensures latest behavioral rules are active - - Prevents shortcut-taking after sync - - Maintains coordination discipline - - Enforces NO EMOJIS and ASCII marker rules - - Ensures proper agent delegation - ---- - -## Conflict Resolution - -### Session Log Conflicts -If both machines created session logs with same date: -1. Keep both versions -2. Rename to: `YYYY-MM-DD-session-[machine].md` -3. Report conflict to user - -### credentials.md Conflicts -If credentials.md has conflicts: -1. Do NOT auto-merge -2. Report conflict to user -3. Show conflicting sections -4. Ask user which version to keep or how to merge - -### Other File Conflicts -Standard git conflict markers: -1. Report files with conflicts -2. Show conflict sections -3. Ask user to resolve manually or provide guidance - ---- - -## Machine Detection - -Automatically detect machine name for commit messages: - -**Windows:** -```powershell -$env:COMPUTERNAME -``` - -**Mac/Linux:** -```bash -hostname -``` - -**Timestamp format:** -```bash -date "+%Y-%m-%d %H:%M:%S" -``` - ---- - -## Benefits - -### Seamless Multi-Machine Workflow -- Start work on one machine, continue on another -- All session context automatically synchronized -- Credentials available everywhere (private repo) -- Commands and directives stay consistent -- Behavioral rules enforced identically (NO EMOJIS, delegation patterns, coding standards) - -### Complete Context Preservation -- Never lose session data -- Full history across all machines -- Searchable via git log -- Rollback capability if needed - -### Zero Manual Sync -- One command syncs everything -- Auto-commit prevents forgotten changes -- Push/pull happens automatically -- Conflicts handled gracefully - ---- - -## Usage Examples - -### Standard Sync (Most Common) -``` -User: /sync - -Claude: -[Commits local changes] -[Pulls from Gitea] -[Pushes to Gitea] -[Applies configuration] -[Reports status] -[Auto-invokes /refresh-directives] - -Sync complete. 3 session logs pushed, 2 updates pulled. -Directives refreshed. Ready to continue work. -``` - -### Sync Before Important Work -``` -User: "I'm switching to my other machine. /sync" - -Claude: -[Syncs everything] -Report: Latest work on Dataforth DOS dashboard pushed to Gitea. -All session logs and credentials synced. -You can now pull on the other machine to continue. -``` - -### Daily Morning Sync -``` -User: /sync - -Claude: -[Pulls overnight changes from other machines] -[Auto-invokes /refresh-directives] -Report: Found 2 new sessions from yesterday evening. -Latest: GuruRMM dashboard redesign completed. -Context recovered. Directives refreshed. Ready for today's work. -``` - ---- - -## Error Handling - -### Network Issues -If git pull/push fails: -1. Report connection error -2. Show what was committed locally -3. Suggest retry or manual sync -4. Changes are safe (committed locally) - -### Authentication Issues -If Gitea authentication fails: -1. Report auth error -2. Check SSH keys or credentials -3. Provide troubleshooting steps -4. Manual push may be needed - -### Merge Conflicts -If automatic merge fails: -1. Report which files have conflicts -2. Show conflict markers -3. Ask for user guidance -4. Offer to abort merge if needed - ---- - -## Security Notes - -**credentials.md Syncing:** -- Private repository on Gitea (https://git.azcomputerguru.com) -- Only accessible to authorized user -- Encrypted in transit (HTTPS/SSH) -- Safe to sync sensitive credentials -- Enables cross-machine access - -**What's NOT synced:** -- `.env` files (gitignored) -- API virtual environment (api/venv/) -- Database files (local development) -- Temporary files (*.tmp, *.log) -- node_modules/ directories - ---- - -## Integration with Other Commands - -### After /checkpoint -User can run `/sync` after `/checkpoint` to push the checkpoint to Gitea: -``` -User: /checkpoint -Claude: [Creates git commit] - -User: /sync -Claude: [Pushes checkpoint to Gitea] -``` - -### Before /save -User can sync first to see latest context: -``` -User: /sync -Claude: [Shows latest session logs] - -User: /save -Claude: [Creates session log with full context] -``` - -### With /context -Syncing ensures `/context` has complete history: -``` -User: /sync -Claude: [Syncs all session logs] - -User: /context Dataforth -Claude: [Searches complete session log history including other machines] -``` - -### Auto-invokes /refresh-directives -**IMPORTANT:** `/sync` automatically invokes `/refresh-directives` at the end: -``` -User: /sync -Claude: -[Phase 1: Commits local changes] -[Phase 2: Pulls/pushes to Gitea] -[Phase 3: Applies configuration] -[Phase 4: Recovers context] -[Phase 5: Reports status] -[Auto-invokes /refresh-directives] -[Confirms directives internalized] - -Sync complete. Directives refreshed. Ready to coordinate. -``` - -**Why automatic:** -- Ensures latest behavioral rules are active after pulling changes -- Prevents using outdated directives from previous sync -- Maintains coordination discipline across all machines -- Enforces NO EMOJIS rule after any directive updates -- Critical after conversation compaction or multi-machine sync - ---- - -## Frequency Recommendations - -**Daily:** Start of work day -- Pull overnight changes -- See what was done on other machines -- Recover latest context - -**After Major Work:** End of coding session -- Push session logs -- Share context across machines -- Backup to Gitea - -**Before Switching Machines:** -- Push all local changes -- Ensure other machine can pull -- Seamless transition - -**Weekly:** General maintenance -- Keep repos in sync -- Review session log history -- Clean up if needed - ---- - -## Troubleshooting - -### "Already up to date" but files seem out of sync -```bash -# Force status check -cd ~/ClaudeTools -git fetch origin -git status -``` - -### "Divergent branches" error -```bash -# Rebase local changes on top of remote -git pull origin main --rebase -``` - -### Lost uncommitted changes -```bash -# Check stash -git stash list - -# Recover if needed -git stash pop -``` - ---- - -**Created:** 2026-01-21 -**Purpose:** Bidirectional sync for seamless multi-machine ClaudeTools workflow -**Repository:** https://git.azcomputerguru.com/azcomputerguru/claudetools.git -**Status:** Active - comprehensive sync with context preservation +`/save` writes a comprehensive session log first, then invokes the same `sync.sh`. Use `/save` after substantive work to capture context for future sessions. Use `/sync` for routine repo sync without writing a log (start of day, switching machines, mid-session check-in). diff --git a/.claude/context-recall-config.env.example b/.claude/context-recall-config.env.example deleted file mode 100644 index cf3993f..0000000 --- a/.claude/context-recall-config.env.example +++ /dev/null @@ -1,11 +0,0 @@ -# Claude Context Import Configuration -# Copy this file to context-recall-config.env and update with your actual values - -# JWT Token for API Authentication -# Generate this token using the ClaudeTools API /auth endpoint -# Example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... -JWT_TOKEN=your-jwt-token-here - -# API Base URL (default: http://localhost:8000) -# Change this if your API is running on a different host/port -API_BASE_URL=http://localhost:8000 diff --git a/.claude/hooks/.gitkeep b/.claude/hooks/.gitkeep deleted file mode 100644 index 98fb81a..0000000 --- a/.claude/hooks/.gitkeep +++ /dev/null @@ -1,2 +0,0 @@ -# This directory contains Claude Code hooks for Context Recall -# See README.md for documentation diff --git a/.claude/hooks/EXAMPLES.md b/.claude/hooks/EXAMPLES.md deleted file mode 100644 index a194d01..0000000 --- a/.claude/hooks/EXAMPLES.md +++ /dev/null @@ -1,390 +0,0 @@ -# Context Recall Examples - -Real-world examples of how the Context Recall System works. - -## Example 1: Continuing Previous Work - -### Session 1 (Monday) - -**User:** "Add authentication endpoints to the API" - -**Claude:** Creates `/api/auth/login` and `/api/auth/register` endpoints - -**System:** Saves context: -```json -{ - "title": "Session: 2025-01-13T14:30:00Z", - "context_type": "session_summary", - "dense_summary": "Created authentication endpoints including login and register. Implemented JWT token generation with 24-hour expiry. Added password hashing with bcrypt.", - "relevance_score": 8.5, - "metadata": { - "files_modified": "api/auth.py,api/models.py", - "git_branch": "feature/auth" - } -} -``` - -### Session 2 (Tuesday) - -**User:** "Add password reset functionality" - -**System:** Automatically recalls context: -```markdown -## [DOCS] Previous Context - -### 1. Session: 2025-01-13T14:30:00Z (Score: 8.5/10) -*Type: session_summary* - -Created authentication endpoints including login and register. -Implemented JWT token generation with 24-hour expiry. -Added password hashing with bcrypt. - -Modified files: api/auth.py,api/models.py -Branch: feature/auth -``` - -**Claude:** (with context) "I'll add password reset to the existing authentication system. Based on the previous session, I can see we're using JWT tokens and bcrypt..." - -## Example 2: Technical Decision Recall - -### Session 1 - -**User:** "Why did we choose PostgreSQL over MongoDB?" - -**Claude:** "We chose PostgreSQL because: 1) Strong ACID guarantees, 2) Complex relationships in data model, 3) Team familiarity..." - -**System:** Saves context: -```json -{ - "title": "Database Technology Decision", - "context_type": "technical_decision", - "dense_summary": "Chose PostgreSQL over MongoDB for: ACID guarantees, complex relationships, team familiarity, excellent tooling ecosystem. Decision made after evaluating both options.", - "relevance_score": 9.0 -} -``` - -### Session 2 (Weeks Later) - -**User:** "Should we use MongoDB for the logging service?" - -**System:** Recalls context: -```markdown -## [DOCS] Previous Context - -### 1. Database Technology Decision (Score: 9.0/10) -*Type: technical_decision* - -Chose PostgreSQL over MongoDB for: ACID guarantees, complex relationships, -team familiarity, excellent tooling ecosystem. Decision made after -evaluating both options. -``` - -**Claude:** "Given our previous decision to use PostgreSQL for its ACID guarantees and relational features, let's consider if logging has different requirements..." - -## Example 3: Bug Fix History - -### Session 1 - -**User:** "Fix the authentication timeout issue" - -**Claude:** Fixes bug in JWT token validation - -**System:** Saves: -```json -{ - "title": "Bug Fix: Authentication Timeouts", - "context_type": "bug_fix", - "dense_summary": "Fixed authentication timeout issue caused by incorrect JWT expiry validation. Changed from server time to UTC. Added timezone handling.", - "relevance_score": 8.0, - "metadata": { - "bug_type": "authentication", - "fix_type": "timezone_handling" - } -} -``` - -### Session 2 - -**User:** "Users are getting logged out randomly" - -**System:** Recalls: -```markdown -## [DOCS] Previous Context - -### 1. Bug Fix: Authentication Timeouts (Score: 8.0/10) -*Type: bug_fix* - -Fixed authentication timeout issue caused by incorrect JWT expiry -validation. Changed from server time to UTC. Added timezone handling. -``` - -**Claude:** "This might be related to the previous timeout issue. Let me check the JWT timezone handling..." - -## Example 4: Multi-Session Feature Development - -### Session 1: Planning - -**User:** "Plan a user dashboard feature" - -**Claude:** Creates architecture plan - -**System:** Saves: -```json -{ - "title": "User Dashboard Architecture", - "context_type": "architecture_decision", - "dense_summary": "Planned user dashboard with: Real-time metrics, customizable widgets, role-based access. Tech stack: React frontend, WebSocket for real-time, Redis for caching.", - "relevance_score": 9.5 -} -``` - -### Session 2: Frontend Implementation - -**User:** "Implement the dashboard frontend" - -**System:** Recalls planning context, Claude implements according to plan - -**System:** Saves: -```json -{ - "title": "Dashboard Frontend Implementation", - "context_type": "session_summary", - "dense_summary": "Implemented React dashboard with widget system. Created: DashboardContainer, WidgetGrid, individual widget components. Used WebSocket hook for real-time updates.", - "relevance_score": 8.0 -} -``` - -### Session 3: Backend Implementation - -**User:** "Add the backend API for the dashboard" - -**System:** Recalls both previous contexts - -**Claude:** "Based on the architecture plan and frontend implementation, I'll create the WebSocket endpoints and Redis caching layer..." - -### Session 4: Testing - -**User:** "Write tests for the dashboard" - -**System:** Recalls all three previous contexts - -**Claude:** "I'll write tests covering the complete dashboard flow: frontend widgets, WebSocket connections, Redis caching, and API endpoints..." - -## Example 5: Context Filtering - -### Query with High Threshold - -```bash -MIN_RELEVANCE_SCORE=7.5 -``` - -Result: Only highly relevant contexts (major decisions, current feature work) - -```markdown -### 1. User Authentication Refactor (Score: 9.0/10) -### 2. Database Schema Changes (Score: 8.5/10) -### 3. API Rate Limiting Implementation (Score: 7.8/10) -``` - -### Query with Low Threshold - -```bash -MIN_RELEVANCE_SCORE=3.0 -``` - -Result: More historical context (includes older sessions, minor changes) - -```markdown -### 1. User Authentication Refactor (Score: 9.0/10) -### 2. Database Schema Changes (Score: 8.5/10) -### 3. API Rate Limiting Implementation (Score: 7.8/10) -### 4. Update README documentation (Score: 6.5/10) -### 5. Fix typo in comment (Score: 4.2/10) -### 6. Add gitignore entry (Score: 3.5/10) -``` - -## Example 6: Project State Tracking - -### After Each Session - -**task-complete hook** saves project state: - -```json -{ - "project_id": "abc123...", - "state_data": { - "last_task_completion": "2025-01-15T10:30:00Z", - "last_git_commit": "a1b2c3d", - "last_git_branch": "feature/dashboard", - "recent_files": "src/Dashboard.tsx,api/dashboard.py" - }, - "state_type": "task_completion" -} -``` - -This enables Claude to answer questions like: -- "What was I working on last?" -- "What files did I modify recently?" -- "What branch am I on?" - -## Example 7: Cross-Feature Context - -### Session 1: Feature A - -**User:** "Add user roles system" - -**System:** Saves context about role implementation (Admin, User, Guest) - -### Session 2: Feature B - -**User:** "Add permissions to the API endpoints" - -**System:** Recalls role system context - -**Claude:** "I'll add permissions using the existing role system (Admin, User, Guest) that we implemented..." - -This shows how context from one feature automatically informs work on related features. - -## Example 8: Onboarding New Team Members - -### New Developer's First Session - -**New Dev:** "How does authentication work in this project?" - -**System:** Recalls all authentication-related contexts: -```markdown -### 1. User Authentication Refactor (Score: 9.0/10) -Implemented JWT-based authentication with bcrypt password hashing... - -### 2. Session Management Design (Score: 8.5/10) -Added Redis-backed session storage with 24-hour expiry... - -### 3. OAuth Integration (Score: 8.0/10) -Integrated Google and GitHub OAuth providers... -``` - -**Claude:** (with full context) "Our authentication system uses JWT tokens with bcrypt hashing. We also have OAuth integration with Google and GitHub..." - -## Example 9: Debugging with Context - -### Session 1: Implementation - -**User:** "Add email notification system" - -**System:** Saves implementation details (SMTP config, template system, queuing) - -### Session 2: Bug Report - -**User:** "Emails aren't being sent" - -**System:** Recalls implementation context - -**Claude:** "Let me check the email system we implemented. Based on the previous session, we're using SMTP with a queue system. Common issues could be..." - -## Example 10: Evolving Requirements - -### Month 1 - -**User:** "Build simple user profile page" - -**System:** Saves initial implementation - -### Month 2 - -**User:** "Add social features to profiles" - -**System:** Recalls original implementation - -**Claude:** "I'll extend the existing profile system to include social features..." - -### Month 3 - -**User:** "Make profiles customizable" - -**System:** Recalls both previous implementations - -**Claude:** "Building on the profile and social features, I'll add customization options..." - -Each session builds on previous work with full context. - -## Real Output Example - -Here's what you actually see in Claude Code when context is recalled: - -```markdown - - -## [DOCS] Previous Context - -The following context has been automatically recalled from previous sessions: - -### 1. API Authentication Implementation (Score: 8.5/10) -*Type: session_summary* - -Task completed on branch 'feature/auth' (commit: a1b2c3d). - -Summary: Implemented JWT-based authentication system with login/register -endpoints. Added password hashing using bcrypt. Created middleware for -protected routes. Token expiry set to 24 hours. - -Modified files: api/auth.py,api/middleware.py,api/models.py - -Timestamp: 2025-01-15T14:30:00Z - ---- - -### 2. Database Schema for Users (Score: 7.8/10) -*Type: technical_decision* - -Added User model with fields: id, username, email, password_hash, -created_at, last_login. Decided to use UUID for user IDs instead of -auto-increment integers for better security and scalability. - ---- - -### 3. Security Best Practices Discussion (Score: 7.2/10) -*Type: session_summary* - -Discussed security considerations: password hashing (bcrypt), token -storage (httpOnly cookies), CORS configuration, rate limiting. Decided -to implement rate limiting in next session. - ---- - -*This context was automatically injected to help maintain continuity across sessions.* -``` - -This gives Claude complete awareness of your previous work without you having to explain it! - -## Benefits Demonstrated - -1. **Continuity** - Work picks up exactly where you left off -2. **Consistency** - Decisions made previously are remembered -3. **Efficiency** - No need to re-explain project details -4. **Learning** - New team members get instant project knowledge -5. **Debugging** - Past implementations inform current troubleshooting -6. **Evolution** - Features build naturally on previous work - -## Configuration Tips - -**For focused work (single feature):** -```bash -MIN_RELEVANCE_SCORE=7.0 -MAX_CONTEXTS=5 -``` - -**For comprehensive context (complex projects):** -```bash -MIN_RELEVANCE_SCORE=5.0 -MAX_CONTEXTS=15 -``` - -**For debugging (need full history):** -```bash -MIN_RELEVANCE_SCORE=3.0 -MAX_CONTEXTS=20 -``` - -## Next Steps - -See `CONTEXT_RECALL_SETUP.md` for setup instructions and `README.md` for technical details. diff --git a/.claude/hooks/INSTALL.md b/.claude/hooks/INSTALL.md deleted file mode 100644 index b7c5c84..0000000 --- a/.claude/hooks/INSTALL.md +++ /dev/null @@ -1,223 +0,0 @@ -# Hook Installation Verification - -This document helps verify that Claude Code hooks are properly installed. - -## Quick Check - -Run this command to verify installation: - -```bash -bash scripts/test-context-recall.sh -``` - -Expected output: **15/15 tests passed** - -## Manual Verification - -### 1. Check Hook Files Exist - -```bash -ls -la .claude/hooks/ -``` - -Expected files: -- `user-prompt-submit` (executable) -- `task-complete` (executable) -- `README.md` -- `EXAMPLES.md` -- `INSTALL.md` (this file) - -### 2. Check Permissions - -```bash -ls -l .claude/hooks/user-prompt-submit -ls -l .claude/hooks/task-complete -``` - -Both should show: `-rwxr-xr-x` (executable) - -If not executable: -```bash -chmod +x .claude/hooks/user-prompt-submit -chmod +x .claude/hooks/task-complete -``` - -### 3. Check Configuration Exists - -```bash -cat .claude/context-recall-config.env -``` - -Should show: -- `CLAUDE_API_URL=http://localhost:8000` -- `JWT_TOKEN=...` (should have a value) -- `CONTEXT_RECALL_ENABLED=true` - -If file missing, run setup: -```bash -bash scripts/setup-context-recall.sh -``` - -### 4. Test Hooks Manually - -**Test user-prompt-submit:** -```bash -source .claude/context-recall-config.env -bash .claude/hooks/user-prompt-submit -``` - -Expected: Either context output or silent success (if no contexts exist) - -**Test task-complete:** -```bash -source .claude/context-recall-config.env -export TASK_SUMMARY="Test task" -bash .claude/hooks/task-complete -``` - -Expected: Silent success or "✓ Context saved to database" - -### 5. Check API Connectivity - -```bash -curl http://localhost:8000/health -``` - -Expected: `{"status":"healthy"}` or similar - -If fails: Start API with `uvicorn api.main:app --reload` - -### 6. Verify Git Config - -```bash -git config --local claude.projectid -``` - -Expected: A UUID value - -If empty, run setup: -```bash -bash scripts/setup-context-recall.sh -``` - -## Common Issues - -### Hooks Not Executing - -**Problem:** Hooks don't run when using Claude Code - -**Solutions:** -1. Verify Claude Code supports hooks (see docs) -2. Check hook permissions: `chmod +x .claude/hooks/*` -3. Test hooks manually (see above) - -### Context Not Appearing - -**Problem:** No context injected in Claude Code - -**Solutions:** -1. Check API is running: `curl http://localhost:8000/health` -2. Check JWT token is valid: Run setup again -3. Enable debug: `echo "DEBUG_CONTEXT_RECALL=true" >> .claude/context-recall-config.env` -4. Check if contexts exist: Run a few tasks first - -### Context Not Saving - -**Problem:** Contexts not persisted to database - -**Solutions:** -1. Check project ID: `git config --local claude.projectid` -2. Test manually: `bash .claude/hooks/task-complete` -3. Check API logs for errors -4. Verify JWT token: Run setup again - -### Permission Denied - -**Problem:** `Permission denied` when running hooks - -**Solution:** -```bash -chmod +x .claude/hooks/user-prompt-submit -chmod +x .claude/hooks/task-complete -``` - -### API Connection Refused - -**Problem:** `Connection refused` errors - -**Solutions:** -1. Start API: `uvicorn api.main:app --reload` -2. Check API URL in config -3. Verify firewall settings - -## Troubleshooting Commands - -```bash -# Full system test -bash scripts/test-context-recall.sh - -# Check all permissions -ls -la .claude/hooks/ scripts/ - -# Re-run setup -bash scripts/setup-context-recall.sh - -# Enable debug mode -echo "DEBUG_CONTEXT_RECALL=true" >> .claude/context-recall-config.env - -# Test API -curl http://localhost:8000/health -curl -H "Authorization: Bearer $JWT_TOKEN" http://localhost:8000/api/projects - -# View configuration -cat .claude/context-recall-config.env - -# Test hooks with debug -bash -x .claude/hooks/user-prompt-submit -bash -x .claude/hooks/task-complete -``` - -## Expected Workflow - -When properly installed: - -1. **You start Claude Code** → `user-prompt-submit` runs -2. **Hook queries database** → Retrieves relevant contexts -3. **Context injected** → You see previous work context -4. **You work normally** → Claude has full context -5. **Task completes** → `task-complete` runs -6. **Context saved** → Available for next session - -All automatic, zero user action required! - -## Documentation - -- **Quick Start:** `.claude/CONTEXT_RECALL_QUICK_START.md` -- **Full Setup:** `CONTEXT_RECALL_SETUP.md` -- **Architecture:** `.claude/CONTEXT_RECALL_ARCHITECTURE.md` -- **Hook Details:** `.claude/hooks/README.md` -- **Examples:** `.claude/hooks/EXAMPLES.md` - -## Support - -If issues persist after following this guide: - -1. Review full documentation (see above) -2. Run full test suite: `bash scripts/test-context-recall.sh` -3. Check API logs for errors -4. Enable debug mode for verbose output - -## Success Checklist - -- [ ] Hook files exist in `.claude/hooks/` -- [ ] Hooks are executable (`chmod +x`) -- [ ] Configuration file exists (`.claude/context-recall-config.env`) -- [ ] JWT token is set in configuration -- [ ] Project ID detected or set -- [ ] API is running (`curl http://localhost:8000/health`) -- [ ] Test script passes (`bash scripts/test-context-recall.sh`) -- [ ] Hooks execute manually without errors - -If all items checked: **Installation is complete!** [OK] - -Start using Claude Code and enjoy automatic context recall! diff --git a/.claude/hooks/README.md b/.claude/hooks/README.md deleted file mode 100644 index c4fb96b..0000000 --- a/.claude/hooks/README.md +++ /dev/null @@ -1,323 +0,0 @@ -# Claude Code Context Recall Hooks - -Automatically inject and save relevant context from the ClaudeTools database into Claude Code conversations. - -## Overview - -This system provides seamless context continuity across Claude Code sessions by: - -1. **Recalling context** - Automatically inject relevant context from previous sessions before each message -2. **Saving context** - Automatically save conversation summaries after task completion -3. **Project awareness** - Track project state and maintain context across sessions - -## Hooks - -### `user-prompt-submit` - -**Runs:** Before each user message is processed - -**Purpose:** Injects relevant context from the database into the conversation - -**What it does:** -- Detects the current project ID (from git config or remote URL) -- Calls `/api/conversation-contexts/recall` to fetch relevant contexts -- Injects context as a formatted markdown section -- Falls back gracefully if API is unavailable - -**Example output:** -```markdown -## [DOCS] Previous Context - -The following context has been automatically recalled from previous sessions: - -### 1. Database Schema Updates (Score: 8.5/10) -*Type: technical_decision* - -Updated the Project model to include new fields for MSP integration... - ---- -``` - -### `task-complete` - -**Runs:** After a task is completed - -**Purpose:** Saves conversation context to the database for future recall - -**What it does:** -- Gathers task information (git branch, commit, modified files) -- Creates a compressed summary of the task -- POST to `/api/conversation-contexts` to save context -- Updates project state via `/api/project-states` - -**Saved information:** -- Task summary -- Git branch and commit hash -- Modified files -- Timestamp -- Metadata for future retrieval - -## Configuration - -### Quick Setup - -Run the automated setup script: - -```bash -bash scripts/setup-context-recall.sh -``` - -This will: -1. Create a JWT token -2. Detect or create your project -3. Configure environment variables -4. Make hooks executable -5. Test the system - -### Manual Setup - -1. **Get JWT Token** - -```bash -curl -X POST http://localhost:8000/api/auth/login \ - -H "Content-Type: application/json" \ - -d '{"username": "admin", "password": "your-password"}' -``` - -2. **Get/Create Project** - -```bash -curl -X POST http://localhost:8000/api/projects \ - -H "Authorization: Bearer YOUR_JWT_TOKEN" \ - -H "Content-Type: application/json" \ - -d '{ - "name": "ClaudeTools", - "description": "Your project description" - }' -``` - -3. **Configure `.claude/context-recall-config.env`** - -```bash -CLAUDE_API_URL=http://localhost:8000 -CLAUDE_PROJECT_ID=your-project-uuid-here -JWT_TOKEN=your-jwt-token-here -CONTEXT_RECALL_ENABLED=true -MIN_RELEVANCE_SCORE=5.0 -MAX_CONTEXTS=10 -``` - -4. **Make hooks executable** - -```bash -chmod +x .claude/hooks/user-prompt-submit -chmod +x .claude/hooks/task-complete -``` - -### Configuration Options - -| Variable | Default | Description | -|----------|---------|-------------| -| `CLAUDE_API_URL` | `http://localhost:8000` | API base URL | -| `CLAUDE_PROJECT_ID` | Auto-detect | Project UUID | -| `JWT_TOKEN` | Required | Authentication token | -| `CONTEXT_RECALL_ENABLED` | `true` | Enable/disable system | -| `MIN_RELEVANCE_SCORE` | `5.0` | Minimum score (0-10) | -| `MAX_CONTEXTS` | `10` | Max contexts per query | -| `AUTO_SAVE_CONTEXT` | `true` | Save after completion | -| `DEBUG_CONTEXT_RECALL` | `false` | Enable debug logs | - -## Project ID Detection - -The system automatically detects your project ID using: - -1. **Git config** - `git config --local claude.projectid` -2. **Git remote URL hash** - Consistent ID from remote URL -3. **Environment variable** - `CLAUDE_PROJECT_ID` - -To manually set project ID in git config: - -```bash -git config --local claude.projectid "your-project-uuid" -``` - -## Testing - -Run the test script: - -```bash -bash scripts/test-context-recall.sh -``` - -This will: -- Test API connectivity -- Test context recall endpoint -- Test context saving -- Verify hooks are working - -## Usage - -Once configured, the system works automatically: - -1. **Start Claude Code** - Context is automatically recalled -2. **Work normally** - All your conversations happen as usual -3. **Complete tasks** - Context is automatically saved -4. **Next session** - Previous context is automatically available - -## Troubleshooting - -### Context not appearing? - -1. Enable debug mode: - ```bash - echo "DEBUG_CONTEXT_RECALL=true" >> .claude/context-recall-config.env - ``` - -2. Check API is running: - ```bash - curl http://localhost:8000/health - ``` - -3. Verify JWT token: - ```bash - curl -H "Authorization: Bearer $JWT_TOKEN" http://localhost:8000/api/projects - ``` - -4. Check hooks are executable: - ```bash - ls -la .claude/hooks/ - ``` - -### Context not saving? - -1. Check task-complete hook output: - ```bash - bash -x .claude/hooks/task-complete - ``` - -2. Verify project ID: - ```bash - source .claude/context-recall-config.env - echo $CLAUDE_PROJECT_ID - ``` - -3. Check API logs for errors - -### Hooks not running? - -1. Verify hook permissions: - ```bash - chmod +x .claude/hooks/* - ``` - -2. Test hook manually: - ```bash - bash .claude/hooks/user-prompt-submit - ``` - -3. Check Claude Code hook documentation: - https://docs.claude.com/claude-code/hooks - -### API connection errors? - -1. Verify API is running: - ```bash - curl http://localhost:8000/health - ``` - -2. Check firewall/port blocking - -3. Verify API URL in config - -## How It Works - -### Context Recall Flow - -``` -User sends message - ↓ -[user-prompt-submit hook runs] - ↓ -Detect project ID - ↓ -Call /api/conversation-contexts/recall - ↓ -Format and inject context - ↓ -Claude processes message with context -``` - -### Context Save Flow - -``` -Task completes - ↓ -[task-complete hook runs] - ↓ -Gather task information - ↓ -Create context summary - ↓ -POST to /api/conversation-contexts - ↓ -Update /api/project-states - ↓ -Context saved for future recall -``` - -## API Endpoints Used - -- `GET /api/conversation-contexts/recall` - Retrieve relevant contexts -- `POST /api/conversation-contexts` - Save new context -- `POST /api/project-states` - Update project state -- `GET /api/projects` - Get project information -- `POST /api/auth/login` - Get JWT token - -## Security Notes - -- JWT tokens are stored in `.claude/context-recall-config.env` -- This file should be in `.gitignore` (DO NOT commit tokens!) -- Tokens expire after 24 hours (configurable) -- Hooks fail gracefully if authentication fails - -## Advanced Usage - -### Custom Context Types - -Modify `task-complete` hook to create custom context types: - -```bash -CONTEXT_TYPE="bug_fix" # or "feature", "refactor", etc. -RELEVANCE_SCORE=9.0 # Higher for important contexts -``` - -### Filtering Contexts - -Adjust recall parameters in config: - -```bash -MIN_RELEVANCE_SCORE=7.0 # Only high-quality contexts -MAX_CONTEXTS=5 # Fewer contexts per query -``` - -### Manual Context Injection - -You can manually trigger context recall: - -```bash -bash .claude/hooks/user-prompt-submit -``` - -## References - -- [Claude Code Hooks Documentation](https://docs.claude.com/claude-code/hooks) -- [ClaudeTools API Documentation](.claude/API_SPEC.md) -- [Database Schema](.claude/SCHEMA_CORE.md) - -## Support - -For issues or questions: -1. Check troubleshooting section above -2. Review API logs: `tail -f api/logs/app.log` -3. Test with `scripts/test-context-recall.sh` -4. Check hook output with `bash -x .claude/hooks/[hook-name]`