# /sync - Bidirectional ClaudeTools Sync

Synchronize ClaudeTools configuration, session data, and context bidirectionally with Gitea. Ensures all machines stay perfectly in sync for seamless cross-machine workflow.

---

## IMPORTANT: Use Automated Sync Script

**CRITICAL:** When user invokes `/sync`, execute the automated sync script instead of manual steps.

**Windows:**
```bash
bash .claude/scripts/sync.sh
```
OR
```cmd
.claude\scripts\sync.bat
```

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

---

## What Gets Synced

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

---

## Execution Steps

### 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 <noreply@anthropic.com>"
   ```

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