sync-init — команда для Claude Code: что делает и как установить
Команда sync-init настраивает автоматическую синхронизацию проекта каждые 2 часа: ищет письма в Outlook, отслеживает файлы и обновляет документы через Claude CLI.
MIT ★ 328 обновлён 2026-10-29
.claude/commands/sync-init.mdЧто делает sync-init
Команда настраивает регулярную синхронизацию каталога через launchd. Она собирает параметры проекта, создаёт файл .sync-watch.json в корне и запускает обёртку для ~/.claude/scripts/project-sync-orchestrator.sh. Синхронизация работает только на macOS.
Пайплайн запускается каждые 2 часа в фоне. Сначала скрипт ищет письма в Outlook через AppleScript с лимитом в 2000 сообщений на папку или переходит на парсинг MIME и HxStore.hxd. Затем он фиксирует правки в отслеживаемых каталогах и формирует .sync-report.md. На последнем шаге Claude CLI с моделью Sonnet и лимитом затрат $2.00 вносит изменения в целевые файлы.
Какие задачи решает
- отслеживать письма по проекту в Outlook каждые 2 часа
- фиксировать новые заметки со встреч и файлы в рабочих папках
- обновлять PRD и презентации через Claude CLI с лимитом $2.00
- настроить фоновый демон launchd без ручной сборки plist-файлов
Примеры запросов агенту
- /sync-init
- Настрой синхронизацию проекта с письмами Outlook и обновлением PRD
- Инициализируй отслеживание рабочих файлов и почты через команду /sync-init
Как установить sync-init
Вручную: положить файлы
.claude/commands/sync-init.mdВызов — /sync-init. Для всех проектов — ~/.claude/commands/
Вручную: положить файлы
~/.codex/prompts/sync-init.mdВызов — /prompts:sync-init. В Codex этот формат помечен устаревшим, замена — скиллы
Вручную: положить файлы
.github/prompts/sync-init.prompt.mdВручную: положить файлы
.gemini/commands/sync-init.tomlGemini хранит команды в TOML: текст запроса — в поле prompt
Вопросы о sync-init
Как установить sync-init в Claude Code?
Сохраните файл команды по пути .claude/commands/sync-init.md. После этого вызов /sync-init станет доступен в интерфейсе Claude Code.
Что делает sync-init?
Команда генерирует конфиг .sync-watch.json и создаёт агент launchd для автоматического запуска оркестратора каждые 2 часа. Он собирает переписку из Outlook, проверяет локальные файлы и обновляет документацию с помощью модели Sonnet.
Как Outlook ищет письма проекта?
Основной поиск идёт через AppleScript по теме, отправителям и ключевым словам с просмотром до 2000 последних сообщений. Если этот метод недоступен, фолбэк считывает MIME-файлы и базу HxStore.hxd.
Исходный текст
sync-init.md · MIT
---
description: "Set up automated sync for a new project folder: email monitoring (Outlook), file change detection, and auto-update of all documents (PRD, presentations, etc.) every 2 hours via cron. Run this in any project folder to get the same automation as other projects."
allowed-tools:
- Read
- Write
- Edit
- Bash
- Glob
- Grep
- Agent
- Skill
- AskUserQuestion
---
# /pmstudio-sync-init — Set Up Automated Sync for a New Project Folder
Run it inside any project folder to set up automated sync. Execute the init process (Steps 1–6 below) directly — there is no separate `project-sync` skill; this command performs the setup and drives `~/.claude/scripts/project-sync-orchestrator.sh`. This sets up:
1. **Email extraction** — Searches Outlook via AppleScript (Legacy Outlook, primary) for project-specific emails by keywords, stakeholders, and subject patterns. Falls back to MIME cache + HxStore binary extraction if AppleScript fails (New Outlook).
2. **File monitoring** — Detects new meeting notes, research docs, source files in watched directories
3. **Sync report** — Generates `.sync-report.md` listing what changed and which docs need updating
4. **Auto-update** — Claude CLI (`claude -p`, Sonnet, $2 budget cap) reads new content and updates all structured documents (PRD, presentations, architecture, roadmap, etc.)
5. **Persistent cron job** — Runs every 2 hours in background, persists across terminal closes and reboots
## The 4-Step Pipeline (every 2 hours)
```
Step 1: Email Search (AppleScript → Outlook inbox/sent)
↓ new emails saved to project emails folder
Step 2: File Detection (scan watched dirs for new/modified files)
↓ changes detected
Step 3: Sync Report (.sync-report.md generated)
↓ lists changed files + which docs need updating
Step 4: Auto-Update (Claude CLI reads changes, updates all target docs)
↓ documents updated, sync report deleted
```
## What it creates
| File | Location | Purpose |
|------|----------|---------|
| `.sync-watch.json` | Project root | Config: keywords, senders, watch dirs, target docs, auto-update budget |
| `run-sync-<name>.sh` | `~/.claude/scripts/` | Wrapper script (avoids OneDrive `&` path issues in launchd XML) |
| `com.claude.project-sync.<name>.plist` | `~/Library/LaunchAgents/` | launchd cron job (every 2 hours) |
| State cache | `~/.claude/state/<project>/` | Timestamps, logs, cached config, auto-update logs |
## `.sync-watch.json` Full Schema
```json
{
"project_name": "Project Name",
"watch_dirs": ["emails", "docs", "Meeting-Notes"],
"target_docs": {
"tier1": [
{
"path": "docs/PRD.html",
"name": "PRD",
"update_from": ["emails", "Meeting-Notes"],
"what": "New requirements, stakeholder feedback, decisions"
}
],
"tier2": [
{
"path": "docs/Presentation.html",
"name": "Stakeholder Deck",
"update_from": ["PRD"],
"what": "Sync with PRD changes"
}
]
},
"email_search": {
"enabled": true,
"keywords": ["project name", "jira-id", "product name"],
"senders": ["stakeholder_name", "another_name"],
"subject_patterns": ["RE: Known Thread Subject"],
"dest_dir": "emails",
"format": "txt"
},
"auto_update": {
"enabled": true,
"model": "sonnet",
"max_budget_usd": 2.00
},
"ignore_patterns": [".*", "*.tmp", "~$*"],
"file_types": [".md", ".html", ".docx", ".xlsx", ".pdf", ".eml", ".txt"]
}
```
## Init Process
### Step 1: Gather project info
Ask the user for (or infer from existing files like CLAUDE.local.md, existing emails, folder structure):
1. **Project name**
2. **Email search keywords** — project-specific terms (product names, Jira IDs, codenames)
3. **Key stakeholders/senders** — names to filter emails by
4. **Subject patterns** — known email thread subjects
5. **Watch directories** — folders to monitor (emails, meeting notes, research, etc.)
6. **Target documents** — tier1 (critical) and tier2 (secondary) docs to auto-update
7. **Email destination folder** — where to save discovered emails
8. **Email format** — `txt` (default) or `eml`
9. **Auto-update settings** — model (`sonnet` default), budget ($2.00 default)
### Step 2: Create `.sync-watch.json` in project root
### Step 3: Create wrapper script
Write `~/.claude/scripts/run-sync-<safe-name>.sh`:
```bash
#!/bin/bash
exec /bin/bash $HOME/.claude/scripts/project-sync-orchestrator.sh "/full/path/to/project"
```
**CRITICAL:** Use absolute paths (no `~`), quote the path (handles `&` in OneDrive paths).
### Step 4: Create launchd plist
Write `~/Library/LaunchAgents/com.claude.project-sync.<safe-name>.plist` with:
- ProgramArguments pointing to the wrapper script (NOT the project dir directly)
- StartInterval: 7200 (2 hours)
- RunAtLoad: true
- HOME env var set explicitly
- Log paths under `~/.claude/logs/`
### Step 5: Activate & cache
```bash
mkdir -p ~/.claude/logs ~/.claude/state
launchctl load ~/Library/LaunchAgents/com.claude.project-sync.<safe-name>.plist
```
Then run manually once to cache config:
```bash
/bin/bash ~/.claude/scripts/run-sync-<safe-name>.sh
```
### Step 6: Verify
`launchctl list | grep project-sync` — expect exit code 0.
## Email Search Details
**Primary: AppleScript (Legacy Outlook)**
- Full inbox + sent items access
- Searches by sender name/address, subject keywords, subject patterns
- Saves matching emails as `.txt` files with headers (Subject, From, Date)
- Deduplicates by checking if message date already exists in file
- Searches last 2000 messages per folder (messages are date-sorted, stops at timestamp)
**Fallback: MIME + HxStore (New Outlook)**
- Parses `~/Library/Group Containers/UBF8T346G9.Office/Outlook/.../MimeFiles/` for clean email files
- Scans `HxStore.hxd` binary for subject awareness (logged, not dumped)
- Used automatically if AppleScript fails
## Email Commands (also available)
These `/email-*` commands work alongside the sync cron:
| Command | What it does |
|---------|-------------|
| `/email-read <name>` | Show latest emails from a person |
| `/email-unread` | Show unread emails (count + top 20) |
| `/email-search <keywords>` | Search by subject keywords |
| `/email-today` | Today's emails grouped by hour |
| `/email-summary` | AI summary — decisions, action items |
| `/email-thread <subject>` | Full thread by subject |
| `/email-save <query> to <folder>` | Save emails to project folder |
| `/email-reply <subject>` | Draft a reply |
## Managing After Setup
There is no `/project-sync` skill — manage the job directly:
- **Status** — `cat ~/.claude/state/<safe-name>/email-sync.log` and check `~/.claude/state/<safe-name>/.last-email-check`; run `/bin/bash ~/.claude/scripts/run-sync-<safe-name>.sh` to trigger now.
- **Configure** — edit `.sync-watch.json` in the project root, then re-cache by running the wrapper once.
- **List** — `launchctl list | grep project-sync` (all active sync jobs).
- **Teardown** — `launchctl unload ~/Library/LaunchAgents/com.claude.project-sync.<safe-name>.plist` then `rm` the plist + `~/.claude/scripts/run-sync-<safe-name>.sh`.
## Known Issues & Workarounds
1. **OneDrive `&` in path**: launchd XML chokes on `&` characters in folder names — solved by wrapper scripts
2. **launchd can't access OneDrive**: Config cached to `~/.claude/state/` — run manually once after config changes
3. **`~` doesn't expand in launchd**: All paths must be absolute
4. **HOME not set in launchd**: Must set HOME env var in plist
5. **Legacy Outlook sync delay**: After switching from New Outlook, full mailbox sync takes 30-60 min
6. **AppleScript sender access**: Use `set s to sender of msg` then `name of s` / `address of s` — NOT `name of sender of msg`
7. **Budget errors**: If Claude CLI says "Exceeded USD budget", increase `max_budget_usd` and re-cache config
---
Now execute the init process: run Steps 1–6 above (gather project info → write `.sync-watch.json` → create the wrapper script → create the launchd plist → activate & cache → verify). This command performs the setup itself; do not look for a separate `project-sync` skill.
© coco-research · MIT · coco-research/coco