docs: add comprehensive sync and reference guides

- Add SYNC_GUIDE.md: Complete guide for keeping code synchronized
  - Git workflow best practices
  - How to handle merge conflicts
  - Security guidelines (no secrets in code)
  - Multi-machine synchronization

- Add QUICK_REFERENCE.md: One-page cheat sheet
  - Essential commands for daily work
  - Common troubleshooting
  - Secrets management
  - Links to full documentation

- Add deploy/sync-dev.sh: Automated sync script
  - Interactive fetch and merge
  - Shows diffs before merging
  - Detects merge conflicts
  - Updates from branch: claude/hostinger-remote-deployment-TGVof

- Update Makefile with 'make sync-dev' target

Usage:
  make sync-dev              # Auto-sync with dev branch
  make setup-telegram        # Setup Telegram bot
  make setup-tailscale       # Setup Tailscale security
  make build && make run     # Test locally

Documentation structure:
  QUICK_REFERENCE.md         ← Start here (1 page)
  SETUP_COMPLETE.md          ← Setup guide (detailed)
  SYNC_GUIDE.md              ← Git & sync guide
  TELEGRAM_QUICKSTART.md     ← Telegram in 3 steps
  docs/TELEGRAM_SETUP.md     ← Full Telegram reference

https://claude.ai/code/session_019vXaqxGmkdCjM8m3jp6rYj
This commit is contained in:
Claude 2026-02-17 19:11:52 +00:00
parent e727907bf8
commit 0585fd32d6
No known key found for this signature in database
4 changed files with 661 additions and 0 deletions

View file

@ -176,6 +176,10 @@ setup-telegram:
setup-tailscale:
@bash deploy/hostinger/setup-tailscale.sh
## sync-dev: Sync with development branch (claude/hostinger-remote-deployment-TGVof)
sync-dev:
@bash deploy/sync-dev.sh
## deploy-hostinger: Deploy PicoClaw to Hostinger VPS
deploy-hostinger:
@bash deploy/hostinger/deploy.sh \

164
QUICK_REFERENCE.md Normal file
View file

@ -0,0 +1,164 @@
# ⚡ PicoClaw Quick Reference
## 🚀 Setup (One-Time Only)
```bash
# 1. Secure VPS with Tailscale
make setup-tailscale
# 2. Configure Telegram Bot
make setup-telegram
# Done! 🎉
```
---
## 🔄 Daily Updates
```bash
# Sync with latest code
make sync-dev
# Check status
git status
```
---
## 🐛 Common Commands
```bash
# Build locally
make build
# Run locally (development)
make run
# Run tests
make test
# Check code quality
make check
# View logs on server
ssh root@YOUR_IP 'docker compose logs picoclaw | tail -50'
# Restart bot (if needed)
ssh root@YOUR_IP 'docker compose restart picoclaw'
```
---
## 📁 Important Files
```
picoclaw/
├── deploy/hostinger/
│ ├── setup-telegram.sh ← Run: make setup-telegram
│ ├── setup-tailscale.sh ← Run: make setup-tailscale
│ ├── setup-server.sh ← Runs on VPS initial setup
│ └── docker-compose.production.yml
├── .github/workflows/
│ └── deploy-hostinger.yml ← Auto-deploys on git push
├── config/
│ ├── config.json ← Edit on VPS (nano)
│ └── .env ← Edit on VPS (nano)
└── docs/
└── TELEGRAM_SETUP.md ← Full guide with troubleshooting
```
---
## 🔐 Secrets Management
```bash
# Add/update GitHub Secret
gh secret set PICOCLAW_TELEGRAM_BOT_TOKEN -b "YOUR_TOKEN"
# List secrets (values hidden)
gh secret list
# Secrets used in deploy:
# - PICOCLAW_TELEGRAM_BOT_TOKEN
# - ANTHROPIC_API_KEY
# - HOSTINGER_HOST
# - HOSTINGER_SSH_USER
# - HOSTINGER_SSH_PASSWORD
# - HOSTINGER_SSH_PORT
```
---
## 📱 Telegram Bot
```bash
# Create bot: https://t.me/botfather
# Commands: /start, /help, /show, /list
# Get your Telegram user ID (check logs):
ssh root@YOUR_IP 'docker compose logs picoclaw | grep user_id'
# Add to whitelist (config/config.json):
"allow_from": ["123456789", "987654321"]
```
---
## 🔗 Tailscale
```bash
# Get your Tailnet IP
ssh root@YOUR_IP 'tailscale ip -4'
# Access via Tailnet
http://100.x.x.x:18790
# Or via hostname
https://picoclaw.YOUR-TAILNET.ts.net
```
---
## 🚨 If Something Breaks
```bash
# 1. Check logs
ssh root@YOUR_IP 'docker compose logs --tail=100 picoclaw'
# 2. Restart container
ssh root@YOUR_IP 'docker compose restart picoclaw'
# 3. Check if port is open
ssh root@YOUR_IP 'netstat -tuln | grep 18790'
# 4. Verify GitHub Secrets are set
gh secret list
# 5. Force redeploy
git commit --allow-empty -m "chore: trigger redeploy"
git push origin claude/hostinger-remote-deployment-TGVof
```
---
## 📚 Full Guides
- **Setup Complete Guide**: [SETUP_COMPLETE.md](SETUP_COMPLETE.md)
- **Sync & Git Guide**: [SYNC_GUIDE.md](SYNC_GUIDE.md)
- **Telegram Setup**: [docs/TELEGRAM_SETUP.md](docs/TELEGRAM_SETUP.md)
- **Telegram Quickstart**: [TELEGRAM_QUICKSTART.md](TELEGRAM_QUICKSTART.md)
---
## 💡 Tips
1. **Always `make sync-dev` before starting work**
2. **Use `make check` to verify code before pushing**
3. **GitHub Actions deploys automatically on push**
4. **Keep bot token in GitHub Secrets, never in code**
5. **Test locally with `make build && make run` first**
---
**Need help?** Check the full guides or open an issue! 🚀

352
SYNC_GUIDE.md Normal file
View file

@ -0,0 +1,352 @@
# 🔄 Mantendo PicoClaw Atualizado Localmente
Guia para sincronizar mudanças com a branch de desenvolvimento.
---
## 📋 Quick Commands
### Atualizar tudo (recomendado):
```bash
make sync-dev
# OR
git fetch origin claude/hostinger-remote-deployment-TGVof
git merge origin/claude/hostinger-remote-deployment-TGVof
```
### Ver mudanças antes de aplicar:
```bash
git fetch origin claude/hostinger-remote-deployment-TGVof
git diff origin/claude/hostinger-remote-deployment-TGVof
```
### Resetar para a branch remota (se fez muitas mudanças locais):
```bash
git fetch origin claude/hostinger-remote-deployment-TGVof
git reset --hard origin/claude/hostinger-remote-deployment-TGVof
```
---
## 🔍 Entendendo o Fluxo de Trabalho
```
Local (seu computador)
├─ Branch: claude/hostinger-remote-deployment-TGVof
│ (sua branch de trabalho)
Remote (GitHub)
├─ Branch: claude/hostinger-remote-deployment-TGVof
│ (repositório central)
Hostinger VPS
├─ /opt/picoclaw (aplicação rodando)
│ (sincronizado via GitHub Actions)
```
---
## 📝 Cenários Comuns
### Cenário 1: Sincronizar após fazer mudanças locais
```bash
# 1. Ver status
git status
# 2. Fazer commit das mudanças
git add .
git commit -m "chore: my local changes"
# 3. Puxar mudanças do repositório remoto
git pull origin claude/hostinger-remote-deployment-TGVof
# 4. Se tiver conflitos:
# - Editar os arquivos com conflito
# - Resolver manualmente
git add <arquivo-resolvido>
git commit -m "resolve merge conflicts"
# 5. Enviar suas mudanças
git push origin claude/hostinger-remote-deployment-TGVof
```
---
### Cenário 2: Sincronizar SEM fazer mudanças
```bash
# Simples: puxar tudo
git pull origin claude/hostinger-remote-deployment-TGVof
# Ou de forma mais segura:
git fetch origin claude/hostinger-remote-deployment-TGVof
git merge origin/claude/hostinger-remote-deployment-TGVof
```
---
### Cenário 3: Voltar para versão anterior (se algo deu errado)
```bash
# Ver histórico
git log --oneline -10
# Voltar para um commit específico (CUIDADO: descarta mudanças recentes)
git reset --hard <COMMIT_HASH>
# Ou simplesmente resetar para a versão remota
git reset --hard origin/claude/hostinger-remote-deployment-TGVof
```
---
## ⚙️ Arquivos Importantes (Não Edite Diretamente)
Esses arquivos são gerenciados automaticamente pelo Claude Code. **Edite apenas via scripts**:
| Arquivo | Como Editar |
|---------|-------------|
| `.github/workflows/deploy-hostinger.yml` | `make setup-telegram` / `make setup-tailscale` |
| `deploy/hostinger/setup-server.sh` | `make setup-tailscale` |
| `deploy/hostinger/setup-telegram.sh` | `make setup-telegram` |
| `deploy/hostinger/docker-compose.production.yml` | Manual via SSH |
| `Makefile` | `make` targets são auto-gerenciados |
---
## 🚨 Evite Fazer Isso
### ❌ NÃO edite arquivos manualmente que podem ter conflitos:
```bash
# RUIM: Editar workflow manualmente
nano .github/workflows/deploy-hostinger.yml
# BOM: Usar os scripts
make setup-telegram
make setup-tailscale
```
### ❌ NÃO faça force push para main:
```bash
# MUITO RUIM - pode apagar trabalho de outros!
git push --force-with-lease origin main
# OK para sua branch de dev
git push --force-with-lease origin claude/hostinger-remote-deployment-TGVof
# (só se tiver certeza)
```
### ❌ NÃO commit .env ou secrets:
```bash
# Se acidentalmente fez commit de secrets:
git rm --cached .env config/.env
git commit -m "remove secrets (they were already in GitHub Secrets anyway)"
git push origin claude/hostinger-remote-deployment-TGVof
```
---
## ✅ Workflow Recomendado
### Diariamente:
```bash
# Ao iniciar o dia
git fetch origin
git status
# Se houver mudanças remotas
git pull origin claude/hostinger-remote-deployment-TGVof
```
### Antes de Fazer Mudanças:
```bash
# Garantir que está atualizado
git pull origin claude/hostinger-remote-deployment-TGVof
# Criar sua mudança
# ... editar arquivos ...
# Commitar
git add .
git commit -m "feat: descrição da mudança"
# Enviar
git push origin claude/hostinger-remote-deployment-TGVof
```
### Após Deploy no Hostinger:
```bash
# Verificar se o deploy funcionou
git log --oneline -5
# Ver status do deploy
# (GitHub Actions mostra o status automaticamente)
```
---
## 🔧 Comandos Git Úteis
```bash
# Ver qual branch está
git branch -v
# Ver mudanças não commitadas
git diff
# Ver histórico
git log --oneline -10
# Ver diferenças com remoto
git diff origin/claude/hostinger-remote-deployment-TGVof
# Limpar arquivos não rastreados
git clean -fd
# Descartar mudanças em um arquivo
git checkout -- <arquivo>
# Descartar todas mudanças locais
git reset --hard HEAD
```
---
## 📊 Monitorando Deploy
Após fazer push, o deploy automático começa. Monitore em:
**GitHub Actions:**
```
https://github.com/agenciaspace/picoclaw/actions
```
**Ou via terminal:**
```bash
gh run list -b claude/hostinger-remote-deployment-TGVof --limit 5
# Ver logs de um deploy específico
gh run view <RUN_ID>
```
---
## 🐛 Resolving Merge Conflicts
Se tiver conflitos ao fazer pull:
```bash
# 1. Ver quais arquivos têm conflito
git status
# 2. Editar os arquivos com conflito
# Procurar por:
# <<<<<<< HEAD (sua versão local)
# =======
# >>>>>>> origin/... (versão remota)
# 3. Decidir qual versão manter ou combinar
# 4. Marcar como resolvido
git add <arquivo-resolvido>
# 5. Completar merge
git commit -m "resolve merge conflicts"
```
---
## 📦 Atualizar Dependências
```bash
# Ver dependências desatualizadas
make check
# Atualizar todas
make update-deps
# Commitar mudanças
git add go.mod go.sum
git commit -m "chore: update dependencies"
git push origin claude/hostinger-remote-deployment-TGVof
```
---
## 🔐 Segurança
### NUNCA commit secrets:
- ❌ Bot tokens de Telegram
- ❌ API keys
- ❌ Passwords
- ❌ Private keys
### Use GitHub Secrets:
```bash
# Adicionar secret
gh secret set PICOCLAW_TELEGRAM_BOT_TOKEN -b "sua_token"
# Ver secrets (valores não aparecem)
gh secret list
```
---
## 📱 Sincronizar em Múltiplas Máquinas
Se trabalhar em vários computadores:
```bash
# Máquina A: Fazer mudanças e push
git add .
git commit -m "feat: minha mudança"
git push origin claude/hostinger-remote-deployment-TGVof
# Máquina B: Puxar mudanças
git pull origin claude/hostinger-remote-deployment-TGVof
```
---
## 🎯 Checklist de Atualização
- [ ] `git pull origin claude/hostinger-remote-deployment-TGVof`
- [ ] `git status` (verifica se há conflitos)
- [ ] Testar localmente: `make build && make run`
- [ ] Conferir arquivos: `git diff HEAD~1` (mudanças do último commit)
- [ ] `git push origin claude/hostinger-remote-deployment-TGVof`
- [ ] Monitorar GitHub Actions (deploy automático)
- [ ] Testar no Hostinger após deploy
---
## ❓ FAQ
**P: Como saber se está desatualizado?**
R: `git fetch` e depois `git status` mostra se há mudanças remotas.
**P: Posso fazer push diretamente para main?**
R: Tecnicamente sim, mas evite. Use a branch claude/hostinger-* para segurança.
**P: O que fazer se acidentalmente editei arquivo importante?**
R: `git checkout -- <arquivo>` para descartar mudanças.
**P: Como reverter um commit já feito?**
R: `git revert <COMMIT_HASH>` (cria novo commit que desfaz as mudanças).
**P: Preciso fazer pull toda vez?**
R: Sim, para manter sincronizado. Especialmente antes de fazer push.
---
**Dica:** Faça `git pull` regularmente para evitar conflitos grandes! 🚀

141
deploy/sync-dev.sh Executable file
View file

@ -0,0 +1,141 @@
#!/usr/bin/env bash
# ============================================================
# Sync Development Branch Script
# ============================================================
# Automatically sync with the development branch
#
# Usage:
# bash deploy/sync-dev.sh
# OR
# make sync-dev
# ============================================================
set -euo pipefail
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'
log() { echo -e "${GREEN}${NC} $*"; }
warn() { echo -e "${YELLOW}${NC} $*"; }
error() { echo -e "${RED}${NC} $*"; exit 1; }
info() { echo -e "${BLUE}${NC} $*"; }
# ── Get current directory ──────────────────────────────
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PICOCLAW_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$PICOCLAW_DIR"
# ── Configuration ──────────────────────────────────────
BRANCH="claude/hostinger-remote-deployment-TGVof"
REMOTE="origin"
# ── Functions ──────────────────────────────────────────
check_git() {
if ! command -v git &>/dev/null; then
error "git is not installed"
fi
}
check_unstaged() {
if ! git diff-index --quiet HEAD --; then
warn "You have unstaged changes:"
git status --short
echo ""
read -p "Continue anyway? (y/n): " continue
[ "$continue" != "y" ] && error "Aborted"
fi
}
fetch_latest() {
info "Fetching latest changes from $REMOTE/$BRANCH..."
if ! git fetch "$REMOTE" "$BRANCH" 2>/dev/null; then
error "Failed to fetch from $REMOTE"
fi
log "Fetched latest changes"
}
show_diff() {
info "Checking for differences..."
DIFF_COUNT=$(git diff --stat origin/"$BRANCH" | tail -1 | awk '{print $1}')
if [ -z "$DIFF_COUNT" ] || [ "$DIFF_COUNT" = "0" ]; then
log "Already up to date!"
return 1
fi
echo ""
info "Changes to merge:"
git diff --stat origin/"$BRANCH"
echo ""
read -p "View full diff? (y/n): " show_full
if [ "$show_full" = "y" ]; then
git diff origin/"$BRANCH" | head -100
echo "... (showing first 100 lines)"
fi
return 0
}
merge_changes() {
info "Merging changes from $REMOTE/$BRANCH..."
if git merge origin/"$BRANCH" --no-edit 2>&1 | grep -q "Merge made"; then
log "Changes merged successfully"
return 0
elif git merge origin/"$BRANCH" --no-edit 2>&1 | grep -q "Already up to date"; then
log "Already up to date"
return 1
else
warn "Merge completed (but may have conflicts)"
git status
return 2
fi
}
check_conflicts() {
if git diff --name-only --diff-filter=U | grep -q .; then
warn "Merge conflicts detected!"
echo ""
echo "Conflicting files:"
git diff --name-only --diff-filter=U
echo ""
error "Please resolve conflicts manually and run: git add . && git commit"
fi
}
show_status() {
echo ""
info "Sync complete!"
echo ""
git log --oneline -5
echo ""
}
# ── Main ───────────────────────────────────────────────
main() {
echo ""
info "🔄 Syncing with $BRANCH"
echo ""
check_git
check_unstaged
fetch_latest
if show_diff; then
read -p "Merge changes? (y/n): " merge_ok
[ "$merge_ok" != "y" ] && error "Aborted"
merge_changes
check_conflicts
fi
show_status
log "Done!"
}
# ── Run ────────────────────────────────────────────────
main