project-directory-migration — скилл для Claude Code
Скилл project-directory-migration переносит сессии, историю и контекст Claude Code, когда вы переименовываете или перемещаете папку проекта. Работает в интерактивном режиме с dry-run проверкой и откатом.
MIT 119 установок ★ 3 обновлён 2026-10-25
npx skills add terrylica/cc-skills --skill project-directory-migration -a claude-codeЧто делает project-directory-migration
Когда проект переезжает в новую папку, Claude Code теряет связь со старыми сессиями — они остаются привязаны к старому пути. Этот скилл переписывает метаданные в ~/.claude/projects/ и ~/.claude/history.jsonl, перекодирует пути (слэши заменяются на дефисы) и создаёт symlink для обратной совместимости.
Он работает в четыре этапа: сначала спрашивает старый и новый пути, показывает сухой запуск с числом найденных сессий и записей истории, затем предлагает выбрать, что мигрировать (сессии, MEMORY.md, symlink, пересоздание venv), и наконец выполняет или экспортирует команды для ручного запуска. Скрипт создаёт timestamped бэкап перед изменениями и может откатиться, если что-то пошло не так.
Требует доступ к Bash, Read, Glob, Grep и умеет спрашивать вопросы. Работает во всех упомянутых платформах; на некоторых может потребоваться указать явный путь к файлу SKILL.md после установки.
Какие задачи решает
- найти и перенести сессии Claude Code при переименовании директории
- восстановить доступ к истории разговоров после перемещения проекта
- пересоздать виртуальное окружение с новым путём
- избежать потери контекста и памяти при реорганизации рабочей папки
- откатиться на бэкап, если миграция прошла неправильно
Примеры запросов агенту
- Переименуй проект с
my-old-nameнаmy-app, и скилл перенесёт все сессии - После перемещения папки проекта в новую директорию запусти миграцию, чтобы вернуть сессии
- Экспортируй команды миграции и запусти их вручную, пока Claude Code закрыт
Как установить project-directory-migration
1Через Skills CLI (Vercel)
npx skills add terrylica/cc-skills --skill project-directory-migration -a claude-code2Вручную: положить файлы
~/.claude/skills/project-directory-migration/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/project-directory-migration/
1Через Skills CLI (Vercel)
npx skills add terrylica/cc-skills --skill project-directory-migration -a codex2Вручную: положить файлы
.agents/skills/project-directory-migration/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add terrylica/cc-skills --skill project-directory-migration -a cursor2Вручную: положить файлы
.cursor/skills/project-directory-migration/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install terrylica/cc-skills plugins/devops-tools/skills/project-directory-migration2Вручную: положить файлы
.github/skills/project-directory-migration/SKILL.md1Через Skills CLI (Vercel)
npx skills add terrylica/cc-skills --skill project-directory-migration -a gemini-cli2Командой платформы
gemini skills install https://github.com/terrylica/cc-skills --path plugins/devops-tools/skills/project-directory-migrationВручную: положить файлы
.devin/skills/project-directory-migration/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add terrylica/cc-skills --skill project-directory-migration -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы о project-directory-migration
Как установить project-directory-migration в Claude Code?
Выполни npx skills add terrylica/cc-skills --skill project-directory-migration -a claude-code, затем открой ~/.claude/skills/project-directory-migration/SKILL.md.
Что делает project-directory-migration?
Переносит сессии, историю и контекст Claude Code, когда вы переименовываете или перемещаете папку проекта. Показывает сухой запуск, спрашивает, что мигрировать, создаёт бэкап и может откатиться.
Нужно ли закрывать Claude Code перед миграцией?
Скилл проверяет, нет ли запущенных сессий в фазе валидации. Если хочешь максимум безопасности, экспортируй команды и запусти их вручную в терминале, пока Claude Code закрыт.
Исходный текст
SKILL.md · MIT
---
name: project-directory-migration
description: Migrate Claude Code project sessions when renaming directories. TRIGGERS - directory rename, move project, migrate sessions
allowed-tools: Read, Bash, Glob, Grep, AskUserQuestion
---
# Project Directory Migration
> Safely migrate Claude Code project context (sessions, memory, history) when renaming a project directory.
> **Self-Evolving Skill**: This skill improves through use. If instructions are wrong, parameters drifted, or a workaround was needed — fix this file immediately, don't defer. Only update for real, reproducible issues.
## When to Use This Skill
Use this skill when:
- Renaming a project directory (e.g., `my-old-name/` to `my-new-name/`)
- Moving a project to a different path
- User says "No conversations found" after a directory rename
- Reorganizing workspace directories
- Package rename requires matching directory name to GitHub repo name
- Recovering sessions that became orphaned after a directory move
## Interactive Workflow
### Phase 1: Gather Facts
Use AskUserQuestion to collect source and target paths.
```
Question 1 (header: "Source"): "What is the current project directory path?"
Options:
- "Use current directory: $PWD" (Recommended)
- "Specify a different path"
Question 2 (header: "Target"): "What should the new directory path be?"
Options:
- (User provides via "Other" free text)
```
### Phase 2: Dry-Run Audit
Run the migration script in `--dry-run` mode to discover what needs migrating:
```bash
bash "<skill-scripts>/claude-code-migrate.sh" --dry-run "$OLD_PATH" "$NEW_PATH"
```
Present findings to user:
- Number of session files found
- Number of history.jsonl entries to rewrite
- Whether auto-memory (MEMORY.md) exists
- Environment tooling detected (uv, direnv, asdf; a leftover mise config is flagged as retired)
### Phase 3: Scope and Confirm
```
Question 3 (header: "Scope", multiSelect: true):
"What should be included in migration?"
Options:
- "Claude Code sessions + history (Recommended)"
- "Auto-memory (MEMORY.md) (Recommended)"
- "Backward-compatibility symlink (Recommended)"
- "Auto-fix environment: venv recreate (Recommended)"
Question 4 (header: "Execute"):
"Ready to migrate? The script creates a timestamped backup first."
Options:
- "Execute migration now (Recommended)"
- "Export copy-paste commands for manual execution"
- "Cancel"
```
**If user chooses "Export copy-paste commands"**: Generate the exact commands they can paste into their terminal after closing Claude Code. This is the safest option since Claude Code won't be accessing the project files during migration.
### Phase 4: Post-Migration Report
After migration completes, report:
- Sessions migrated, history entries rewritten
- Environment fixups applied (venv recreated)
- Remaining manual steps (git remote update, etc.)
- Rollback command if anything goes wrong
---
## Quick Reference
### Claude Code Path Encoding
Claude Code encodes directory paths by replacing `/` with `-`:
```
/Users/alice/projects/my-app --> -Users-alice-projects-my-app
```
### Storage Locations
| Asset | Location |
| ------------- | ----------------------------------------------------------- |
| Sessions | `~/.claude/projects/{encoded-path}/*.jsonl` |
| Memory | `~/.claude/projects/{encoded-path}/memory/MEMORY.md` |
| Session index | `~/.claude/projects/{encoded-path}/sessions-index.json` |
| History | `~/.claude/history.jsonl` |
| Subagents | `~/.claude/projects/{encoded-path}/{session-id}/subagents/` |
### What Contains Path References
| File | Fields with paths | Needs rewriting? |
| ---------------------- | ------------------------------------------------------------- | ---------------- |
| `sessions-index.json` | `originalPath`, `entries[].projectPath`, `entries[].fullPath` | **Yes** |
| `history.jsonl` | `project` field per entry | **Yes** |
| Session `.jsonl` files | None | No |
| `MEMORY.md` | None (content only) | No |
---
## Migration Script
Located at `scripts/claude-code-migrate.sh`.
### Usage
```bash
# Dry run (preview what would happen)
bash scripts/claude-code-migrate.sh --dry-run /old/path /new/path
# Execute migration
bash scripts/claude-code-migrate.sh /old/path /new/path
# Rollback from most recent backup
bash scripts/claude-code-migrate.sh --rollback
# Show help
bash scripts/claude-code-migrate.sh --help
```
### 9-Phase Execution
1. **Pre-flight validation** — 7 checks (paths, Claude Code dir, python3, no running sessions)
2. **Backup** — Timestamped copy to `~/.claude/migration-backup-YYYYMMDD-HHMMSS/`
3. **Move project directory** — Rename in `~/.claude/projects/`
4. **Rewrite sessions-index.json** — Update projectPath, fullPath, originalPath
5. **Rewrite history.jsonl** — Update project field (JSON-safe, preserves Unicode)
6. **Backward-compatibility symlink** — Old encoded path symlinks to new
7. **Rename repo directory** — `mv /old/path /new/path`
8. **Environment fixups** — venv recreate, direnv/asdf warnings, leftover-mise-config warning
9. **Post-flight verification** — Sessions count, memory, symlink, env health
---
## Reference Documentation
- [Session Storage Anatomy](./references/session-storage-anatomy.md) — How Claude Code stores project data
- [Troubleshooting Guide](./references/troubleshooting.md) — Common post-migration issues and fixes
- [Evolution Log](./references/evolution-log.md) — Skill improvement history
---
## Troubleshooting
| Issue | Auto-fixed? | Manual Solution |
| ----------------------------- | -------------------- | -------------------------------------- |
| `(old-name)` in shell prompt | **Yes** (Phase 8) | Restart terminal or `uv sync` |
| VIRTUAL_ENV path mismatch | **Yes** (Phase 8) | `uv sync --dev` recreates venv |
| "No conversations found" | **Yes** (Phase 4) | Re-run migration script |
| `.envrc` not allowed | **Warned** (Phase 8) | `direnv allow` |
| Git push auth fails | No | Update credential helper or remote URL |
| Session subdirs missing | No | Use `--rollback`, retry |
## Post-Execution Reflection
After this skill completes, reflect before closing the task:
0. **Locate yourself.** — Find this SKILL.md's canonical path before editing.
1. **What failed?** — Fix the instruction that caused it.
2. **What worked better than expected?** — Promote to recommended practice.
3. **What drifted?** — Fix any script, reference, or dependency that no longer matches reality.
4. **Log it.** — Evolution-log entry with trigger, fix, and evidence.
Do NOT defer. The next invocation inherits whatever you leave behind.
© terrylica · MIT · terrylica/cc-skills