Files
claudetools/.claude/OFFLINE_MODE.md
Mike Swanson 25f3759ecc [Config] Add coding guidelines and code-fixer agent
Major additions:
- Add CODING_GUIDELINES.md with "NO EMOJIS" rule
- Create code-fixer agent for automated violation fixes
- Add offline mode v2 hooks with local caching/queue
- Add periodic context save with invisible Task Scheduler setup
- Add agent coordination rules and database connection docs

Infrastructure:
- Update hooks: task-complete-v2, user-prompt-submit-v2
- Add periodic_save_check.py for auto-save every 5min
- Add PowerShell scripts: setup_periodic_save.ps1, update_to_invisible.ps1
- Add sync-contexts script for queue synchronization

Documentation:
- OFFLINE_MODE.md, PERIODIC_SAVE_INVISIBLE_SETUP.md
- Migration procedures and verification docs
- Fix flashing window guide

Updates:
- Update agent configs (backup, code-review, coding, database, gitea, testing)
- Update claude.md with coding guidelines reference
- Update .gitignore for new cache/queue directories

Status: Pre-automated-fixer baseline commit

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-17 12:51:43 -07:00

481 lines
10 KiB
Markdown

# ClaudeTools - Offline Mode & Sync
**Version 2.0 - Offline-Capable Context Recall**
---
## Overview
ClaudeTools now supports fully offline operation with automatic synchronization when the API becomes available. Contexts are never lost - they're queued locally and uploaded when connectivity is restored.
---
## How It Works
### Online Mode (Normal Operation)
```
User Message
[user-prompt-submit hook]
Fetch context from API → Cache locally → Inject into conversation
Claude processes with context
Task completes
[task-complete hook]
Save context to API → Success
```
### Offline Mode (API Unavailable)
```
User Message
[user-prompt-submit hook]
API unavailable → Use local cache → Inject cached context
Claude processes with cached context
Task completes
[task-complete hook]
API unavailable → Queue locally in .claude/context-queue/pending/
```
### Sync Mode (When API Restored)
```
Next API interaction
Background sync triggered
Upload all queued contexts
Move to .claude/context-queue/uploaded/
```
---
## Directory Structure
```.claude/
├── context-cache/ # Downloaded contexts for offline reading
│ └── [project-id]/ # Per-project cache
│ ├── latest.json # Most recent contexts from API
│ └── last_updated # Cache timestamp
├── context-queue/ # Pending contexts to upload
│ ├── pending/ # Contexts waiting to upload
│ │ ├── [project]_[timestamp]_context.json
│ │ └── [project]_[timestamp]_state.json
│ ├── uploaded/ # Successfully uploaded (auto-cleaned)
│ └── failed/ # Failed uploads (manual review needed)
└── hooks/
├── user-prompt-submit-v2 # Enhanced hook with offline support
├── task-complete-v2 # Enhanced hook with queue support
└── sync-contexts # Manual/auto sync script
```
---
## Features
### 1. Context Caching
**What:**
- API responses are cached locally after each successful fetch
- Cache is stored per-project in `.claude/context-cache/[project-id]/`
**When Used:**
- API is unavailable
- Network is down
- Server is being maintained
**Benefits:**
- Continue working with most recent context
- No interruption to workflow
- Clear indication when using cached data
### 2. Context Queuing
**What:**
- Failed context saves are queued locally
- Stored as JSON files in `.claude/context-queue/pending/`
**When Used:**
- API POST fails
- Network is down
- Authentication expires
**Benefits:**
- No context loss
- Automatic retry
- Continues working offline
### 3. Automatic Sync
**What:**
- Background process uploads queued contexts
- Triggered on next successful API interaction
- Non-blocking (runs in background)
**When Triggered:**
- User message processed (user-prompt-submit)
- Task completed (task-complete)
- Manual sync command
**Benefits:**
- Seamless sync
- No manual intervention
- Transparent to user
---
## Usage
### Automatic Operation
No action needed - the system handles everything automatically:
1. **Working Online:**
- Context recalled from API
- Context saved to API
- Everything cached locally
2. **API Goes Offline:**
- Context recalled from cache (with warning)
- Context queued locally
- Work continues uninterrupted
3. **API Restored:**
- Next interaction triggers background sync
- Queued contexts uploaded
- Normal operation resumes
### Manual Sync
If you want to force a sync:
```bash
cd D:\ClaudeTools
bash .claude/hooks/sync-contexts
```
### Check Queue Status
```bash
# Count pending contexts
ls .claude/context-queue/pending/*.json | wc -l
# Count uploaded contexts
ls .claude/context-queue/uploaded/*.json | wc -l
# Check failed uploads
ls .claude/context-queue/failed/*.json 2>/dev/null
```
### View Cached Context
```bash
# View cached contexts for current project
PROJECT_ID=$(git config --local claude.projectid)
cat .claude/context-cache/$PROJECT_ID/latest.json | python -m json.tool
# Check cache age
cat .claude/context-cache/$PROJECT_ID/last_updated
```
---
## Migration from V1 to V2
### Step 1: Backup Current Hooks
```bash
cd .claude/hooks
cp user-prompt-submit user-prompt-submit.backup
cp task-complete task-complete.backup
```
### Step 2: Replace with V2 Hooks
```bash
# Replace hooks with offline-capable versions
mv user-prompt-submit-v2 user-prompt-submit
mv task-complete-v2 task-complete
# Make executable
chmod +x user-prompt-submit task-complete sync-contexts
```
### Step 3: Create Queue Directories
```bash
mkdir -p .claude/context-cache
mkdir -p .claude/context-queue/{pending,uploaded,failed}
```
### Step 4: Update .gitignore
Add to `.gitignore`:
```gitignore
# Context recall local storage
.claude/context-cache/
.claude/context-queue/
```
### Step 5: Test
```bash
# Test offline mode by stopping API
ssh guru@172.16.3.30
sudo systemctl stop claudetools-api
# Back on Windows - use Claude Code
# Should see "offline mode" message
# Contexts should queue in .claude/context-queue/pending/
# Restart API
sudo systemctl start claudetools-api
# Next Claude Code interaction should trigger sync
```
---
## Indicators & Messages
### Online Mode
```
<!-- Context Recall: Retrieved 3 relevant context(s) from API -->
## 📚 Previous Context
The following context has been automatically recalled:
...
```
### Offline Mode (Using Cache)
```
<!-- Context Recall: Retrieved 3 relevant context(s) from LOCAL CACHE (offline mode) -->
## 📚 Previous Context
⚠️ **Offline Mode** - Using cached context (API unavailable)
The following context has been automatically recalled:
...
*Context from local cache - new context will sync when API is available.*
```
### Context Saved (Online)
```stderr
✓ Context saved to database
```
### Context Queued (Offline)
```stderr
⚠ Context queued locally (API unavailable) - will sync when online
```
---
## Troubleshooting
### Issue: Contexts Not Syncing
**Check:**
```bash
# Verify JWT token is set
source .claude/context-recall-config.env
echo $JWT_TOKEN
# Manually run sync
bash .claude/hooks/sync-contexts
```
### Issue: Cache Too Old
**Solution:**
```bash
# Clear cache to force fresh fetch
PROJECT_ID=$(git config --local claude.projectid)
rm -rf .claude/context-cache/$PROJECT_ID
```
### Issue: Failed Uploads
**Check:**
```bash
# Review failed contexts
ls -la .claude/context-queue/failed/
# View specific failed context
cat .claude/context-queue/failed/[filename].json | python -m json.tool
# Retry manually
bash .claude/hooks/sync-contexts
```
### Issue: Queue Growing Too Large
**Solution:**
```bash
# Check queue size
du -sh .claude/context-queue/
# Clean up old uploaded contexts (keeps last 100)
find .claude/context-queue/uploaded/ -type f -name "*.json" -mtime +7 -delete
# Emergency: Clear all queues (data loss!)
rm -rf .claude/context-queue/{pending,uploaded,failed}/*
```
---
## Performance Considerations
### Cache Storage
- **Per-project cache:** ~10-50 KB per project
- **Storage impact:** Negligible (< 1 MB total)
- **Auto-cleanup:** No (caches remain until replaced)
### Queue Storage
- **Per-context:** ~1-2 KB per context
- **Growth rate:** 1-5 contexts per work session
- **Auto-cleanup:** Yes (keeps last 100 uploaded)
### Sync Performance
- **Upload speed:** ~0.5 seconds per context
- **Background:** Non-blocking
- **Network impact:** Minimal (POST requests only)
---
## Security Considerations
### Local Storage
- **Cache contents:** Context summaries (not sensitive)
- **Queue contents:** Context payloads with metadata
- **Access control:** File system permissions only
### Recommendations
1. **Add to .gitignore:**
```gitignore
.claude/context-cache/
.claude/context-queue/
```
2. **Backup exclusions:**
- Exclude `.claude/context-cache/` (can be re-downloaded)
- Include `.claude/context-queue/pending/` (unique data)
3. **Sensitive projects:**
- Review queued contexts before sync
- Clear cache when switching machines
---
## Advanced Usage
### Disable Offline Mode
Keep hooks but disable caching/queuing:
```bash
# In .claude/context-recall-config.env
CONTEXT_RECALL_ENABLED=false
```
### Force Online-Only Mode
Prevent local fallback:
```bash
# Remove cache and queue directories
rm -rf .claude/context-cache
rm -rf .claude/context-queue
```
### Pre-populate Cache
For offline work, cache contexts before disconnecting:
```bash
# Trigger context recall
# (Just start a Claude Code session - context is auto-cached)
```
### Batch Sync Script
Create a cron job or scheduled task:
```bash
# Sync every hour
0 * * * * cd /path/to/ClaudeTools && bash .claude/hooks/sync-contexts >> /var/log/context-sync.log 2>&1
```
---
## Comparison: V1 vs V2
| Feature | V1 (Original) | V2 (Offline-Capable) |
|---------|---------------|----------------------|
| API Recall | ✅ Yes | ✅ Yes |
| API Save | ✅ Yes | ✅ Yes |
| Offline Recall | ❌ Silent fail | ✅ Uses local cache |
| Offline Save | ❌ Data loss | ✅ Queues locally |
| Auto-sync | ❌ No | ✅ Background sync |
| Manual sync | ❌ No | ✅ sync-contexts script |
| Status indicators | ❌ Silent | ✅ Clear messages |
| Data resilience | ❌ Low | ✅ High |
---
## FAQ
**Q: What happens if I'm offline for days?**
A: All contexts queue locally and sync when online. No data loss.
**Q: How old can cached context get?**
A: Cache is updated on every successful API call. Age is shown in offline mode message.
**Q: Can I work on multiple machines offline?**
A: Yes, but contexts won't sync between machines until both are online.
**Q: What if sync fails repeatedly?**
A: Contexts move to `failed/` directory for manual review. Check API connectivity.
**Q: Does this slow down Claude Code?**
A: No - sync runs in background. Cache/queue operations are fast (~milliseconds).
**Q: Can I disable caching but keep queuing?**
A: Not currently - it's all-or-nothing via CONTEXT_RECALL_ENABLED.
---
## Support
For issues or questions:
1. Check queue status: `ls -la .claude/context-queue/pending/`
2. Run manual sync: `bash .claude/hooks/sync-contexts`
3. Review logs: Check stderr output from hooks
4. Verify API: `curl http://172.16.3.30:8001/health`
---
**Last Updated:** 2026-01-17
**Version:** 2.0 (Offline-Capable)