К основному содержанию
скилл CX Codex

session-management · josstei — скилл для Claude Code: управление сессиями

Скилл session-management для Claude Code ведёт состояние сессий оркестрации. Он подключается при создании, обновлении, возобновлении и архивировании сессии.

Apache-2.0 ★ 489 обновлён 2026-10-26

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add josstei/maestro-orchestrate --skill session-management -a claude-code
Открыть на GitHub

Что делает session-management

Скилл создаёт и обновляет состояние сессии оркестрации: фиксирует этапы, изменения файлов, ошибки, контекст для следующих этапов и расход токенов. При возобновлении он помогает восстановить ход работы по сохранённому состоянию.

Для операций с состоянием скилл предпочитает MCP-инструменты; если они недоступны, использует write_file и replace. Путь к состоянию берётся из MAESTRO_STATE_DIR, по умолчанию это docs/maestro. После успешного завершения сессия архивируется автоматически, если MAESTRO_AUTO_ARCHIVE не отключён.

Какие задачи решает

  • создать состояние новой сессии оркестрации
  • зафиксировать переходы между этапами и изменения файлов
  • сохранить ошибки и контекст для следующих этапов
  • возобновить сессию по сохранённому состоянию
  • архивировать завершённую сессию

Примеры запросов агенту

  • Создай состояние сессии для этой оркестрации.
  • Обнови состояние: этап завершён, создан файл src/app.ts.
  • Возобнови оркестрацию по активной сессии.

Как установить session-management

1Через Skills CLI (Vercel)

npx skills add josstei/maestro-orchestrate --skill session-management -a claude-code

2Вручную: положить файлы

~/.claude/skills/session-management/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/session-management/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о session-management

Как установить session-management в Claude Code?

Выполни npx skills add josstei/maestro-orchestrate --skill session-management -a claude-code. Файл скилла устанавливается в ~/.claude/skills/session-management/SKILL.md.

Что делает session-management?

Скилл ведёт состояние сессии оркестрации: отмечает этапы и изменения, сохраняет ошибки и контекст, а также поддерживает возобновление и архивирование.

Как session-management работает без MCP-инструментов?

Если MCP-инструменты для состояния недоступны, скилл использует write_file и replace для работы с файлами состояния.

Исходный текст

SKILL.md · Apache-2.0
---
name: session-management
description: Manages orchestration session state, tracking, and resumption
---

# Session Management Skill

Activate this skill for all session state operations during Maestro orchestration. This skill defines the protocols for creating, updating, resuming, and archiving orchestration sessions.

## State Access Protocol

When MCP state tools are available, prefer them for state operations:
- **Preferred**: MCP tools (`initialize_workspace`, `create_session`, `update_session`, `transition_phase`, `get_session_status`, `archive_session`) — structured I/O, atomic operations.
- **Fallback**: `write_file`/`replace` directly on state files — when MCP tools are not in the available tool list.
- **Legacy**: `node <runtime-script-root>/read-active-session.js` (used by command shell blocks to inject state before the first turn) / `read-state.js <relative-path>` — not the recommended path.

Detection: check whether MCP state tools appear in your available tools. If they do, use them. If they do not, use `write_file`/`replace`.

## Hook-Level Session State

Maestro hooks keep a separate, ephemeral per-session directory (`${MAESTRO_HOOKS_DIR:-<os.tmpdir()>/maestro-hooks-<uid>}/<session-id>/`, holding only the `active-agent` file). The orchestrator never reads or writes it and interacts only with `<MAESTRO_STATE_DIR>` paths.

## Session Creation Protocol

### When to Create
For Standard workflow, create a new session at execution setup after the design document and implementation plan are approved and the execution mode gate has resolved. For Express workflow, create a session after the structured brief is approved (see EXPRESS WORKFLOW step 34 in `orchestration-steps`).

### Session ID Format
`YYYY-MM-DD-<topic-slug>`

Where:
- `YYYY-MM-DD` is the orchestration start date
- `<topic-slug>` is a lowercase, hyphenated summary matching the design document topic

### File Location
`<MAESTRO_STATE_DIR>/state/active-session.md`

All state paths in this skill use `<MAESTRO_STATE_DIR>` as their base directory (default: `docs/maestro`). In procedural steps, `<state_dir>` represents the resolved value of this variable.

### Initialization Steps
1. Resolve state directory from `MAESTRO_STATE_DIR`
2. Create `<state_dir>/state/` directory if it does not exist (defense-in-depth fallback — workspace readiness startup check is the primary mechanism)
3. Verify no existing `active-session.md` — if one exists, alert the user and offer to archive or resume
4. Generate session state from the `session-state` template (load it with `get_skill_content(["session-state"])` if not already loaded), setting `workflow_mode` to `standard` or `express` and `task_complexity` from the design document frontmatter
5. Initialize all phases as `pending`
6. Set overall status to `in_progress`
7. Set `current_phase` to 1
8. Record design document and implementation plan paths
9. Initialize empty token_usage, file manifests, downstream_context, and errors sections

## State Update Protocol

### Update Triggers
Update session state on every meaningful state change:
- Phase status transitions
- File manifest changes
- Downstream context extraction from completed phases
- Error occurrences
- Token usage increments
- Phase completion or failure

### Update Rules

1. **Timestamp**: Update `updated` field on every state change
2. **Phase Status**: Transition phase status following valid transitions:
   - `pending` -> `in_progress`
   - `in_progress` -> `completed`
   - `in_progress` -> `failed`
   - `failed` -> `in_progress` (retry)
   - `pending` -> `skipped` (user decision only)
3. **Current Phase**: Update `current_phase` to the ID of the currently executing phase
4. **File Manifest**: Append to `files_created`, `files_modified`, or `files_deleted` as subagents report changes
5. **Downstream Context**: Persist parsed Handoff Report Part 2 fields into phase `downstream_context`
6. **Token Usage**: Aggregate token counts from subagent responses into both `total_*` and `by_agent` sections
7. **Error Recording**: Append to phase `errors` array with complete metadata

### Error Recording Format

```yaml
errors:
  - agent: "<agent-name>"
    timestamp: "<ISO 8601>"
    type: "<validation|timeout|file_conflict|runtime|dependency|recovery>"
    message: "<full error description>"
    resolution: "<what was done to resolve, or 'pending'>"
    resolved: false
```

### Retry Tracking
- Increment `retry_count` on each retry attempt
- Maximum `MAESTRO_MAX_RETRIES` retries per phase (default `2`) before escalating to user — see execution → Retry Logic
- Record each retry as a separate error entry with resolution details

### Markdown Body Updates
After updating YAML frontmatter, append to the Markdown body:

```markdown
## Phase N: <Phase Name> <status indicator>

### <Agent Name> Output
[Summary of agent output or full content]

### Files Changed
- Created: [list]
- Modified: [list]
- Deleted: [list]

### Downstream Context
- Key Interfaces Introduced: [list]
- Patterns Established: [list]
- Integration Points: [list]
- Assumptions: [list]
- Warnings: [list]

### Validation Result
[Pass/Fail with details]
```

Status indicators:
- Completed: checkmark
- In Progress: circle
- Failed: cross
- Pending: square
- Skipped: dash

## Archive Protocol

### When to Archive
Archive session state when:
- All phases are completed successfully AND `MAESTRO_AUTO_ARCHIVE` is `true` (default)
- User explicitly requests archival (regardless of `MAESTRO_AUTO_ARCHIVE` setting)
- User starts a new orchestration (previous session must be archived first, regardless of setting)

When `MAESTRO_AUTO_ARCHIVE` is `false`, prompt the user after successful completion: "Session complete. Auto-archive is disabled. Would you like to archive this session?"

### Archive Steps
If `archive_session` appears in your available tools, use it — a single call handles all archival:

1. Call `archive_session` with the session ID. The MCP tool atomically:
   - Updates session status to `completed`
   - Moves `active-session.md` to `<state_dir>/state/archive/<session-id>.md`
   - Moves design document to `<state_dir>/plans/archive/` (if it exists and is non-null)
   - Moves implementation plan to `<state_dir>/plans/archive/` (if it exists and is non-null)
2. Confirm archival to user with summary of what was archived (use the `archived_files` array in the response)

If `archive_session` is not available, fall back to manual file operations:
1. Create `<state_dir>/plans/archive/` directory if it does not exist
2. Create `<state_dir>/state/archive/` directory if it does not exist
3. **MOVE** (not copy) design document from `<state_dir>/plans/` to `<state_dir>/plans/archive/` — the original MUST be deleted. Use the shell-command tool from runtime context with `mv` or read+write+delete. Do NOT leave the file in both locations. **Skip this step if `design_document` is `null` (Express sessions).**
4. **MOVE** (not copy) implementation plan from `<state_dir>/plans/` to `<state_dir>/plans/archive/` — same: delete the original. **Skip this step if `implementation_plan` is `null` (Express sessions).**
5. Update session state `status` to `completed`
6. Update `updated` timestamp
7. **MOVE** (not copy) `active-session.md` from `<state_dir>/state/` to `<state_dir>/state/archive/<session-id>.md` — delete the original.
8. Confirm archival to user with summary of what was archived

### Archive Verification
After archival, verify ALL of the following (archive is incomplete if any check fails):
- No `active-session.md` exists in `<state_dir>/state/`
- No plan files remain in `<state_dir>/plans/` (only the `archive/` subdirectory should be present)
- Archived files are readable at their new locations in `archive/`
- If files still exist in the original locations, delete them now — the archive step used copy instead of move

## Resume Protocol

### When to Resume
Resume is triggered by the `/maestro:resume` command or when `/maestro:orchestrate` detects an existing active session.

### Resume Steps

1. **Read State**: If session state was already injected into the prompt (e.g., via `/maestro:resume`), use that injected content instead of calling `get_session_status`. Otherwise, if `get_session_status` appears in your available tools, call it to read the active session. Otherwise, read state via `run_shell_command`: `node <runtime-script-root>/read-active-session.js` (resolves `MAESTRO_STATE_DIR` internally)
2. **Parse Frontmatter**: Extract YAML frontmatter for session metadata
3. **Identify Position**: Determine:
   - Last completed phase (highest ID with `status: completed`)
   - Current active phase (first phase with `status: in_progress` or `pending`)
   - Any failed phases with unresolved errors
4. **Check Errors**: Identify unresolved errors from previous execution
5. **Present Summary**: Display a status summary to the user covering the position and errors identified in steps 3-4
6. **Handle Errors**: If unresolved errors exist:
   - Present each error with context
   - Offer options: retry, skip, abort, or adjust parameters
   - Wait for user guidance before proceeding
7. **Continue Execution**: Resume from the first pending or failed phase
8. **Update State**: Mark resumed phase as `in_progress` and update timestamps

### Express Resume Branch

When resuming a session with `workflow_mode: "express"` (read from session state via `get_session_status`), follow the Express workflow's resume protocol instead of the standard resume steps above:

- If phase status is `pending`: re-generate and present the structured brief for approval. On approval, proceed to delegation.
- If phase status is `in_progress`: the implementing agent was interrupted. Re-delegate with the same scope. Use the `agents` array to identify which agent was running.
- If phase status is `completed` but session status is `in_progress`: code review or archival was interrupted. Run the code review step, then archive.

Express sessions have a single phase. The phase status combined with the `agents` array contents determines the resume position.

### Conflict Detection
When resuming, check for potential conflicts:
- Files that were partially modified (phase started but not completed)
- External modifications to files in the manifest since last session
- Changes to the implementation plan since last execution

Report any detected conflicts to the user before proceeding.

## Token Usage Tracking

### Collection
After each subagent invocation, record:
- Input tokens consumed
- Output tokens generated
- Cached tokens used (if available)

### Aggregation
Maintain two levels of aggregation:
1. **Total**: Sum across all agents and phases
2. **By Agent**: Per-agent totals across all their invocations

### Format

```yaml
token_usage:
  total_input: 15000
  total_output: 8000
  total_cached: 3000
  by_agent:
    coder:
      input: 8000
      output: 4000
      cached: 2000
    tester:
      input: 7000
      output: 4000
      cached: 1000
```

© josstei · Apache-2.0 · josstei/maestro-orchestrate

Похожие скиллы

Все скиллы по теме «Настройка агента: память, контекст, субагенты» →

Сначала — session-management от других авторов.

session-management alinaqi Скилл session-management ведёт файлы состояния, решений и ориентиров в коде, чтобы работа продолжалась с того же места после перерыва или упора в лимит контекста. CX Codex +1 310установок session-management secondsky Скилл session-management для Claude Code помогает настроить JWT-сессии, хранение в Redis и обновление токенов. Подключается при работе над аутентификацией, пользовательскими сессиями или выходом из аккаунта. CX Codex +1 436установок Session Management hedera-dev Скилл Session Management ведёт журнал работ и техдолга между сессиями агента, чтобы после перезапуска было видно, что сделано и что осталось. CX Codex +1 666установок durable-session-state ZaxbyHub Скилл durable-session-state сохраняет планы, решения, результаты проверок и вердикты ревью в файлах проекта. Он помогает продолжить долгую задачу после сжатия контекста или передачи работы. CX Codex +1 ★ 539звёзд репо codex-session-manager sugarforever Скилл codex-session-manager для работы с локальными транскриптами сессий Codex. Экспортирует сессии в структурированный Markdown с временной шкалой, вызовами инструментов и архивными данными. CX Codex +1 199установок session-handoff SethGammon Скилл session-handoff собирает итоги текущей сессии в блок HANDOFF, чтобы следующая сессия сразу продолжила работу без повторного аудита. CX Codex +1 ★ 937звёзд репо session-guard Adit Jain Скилл session-guard следит за длинными сессиями и дрейфом правил агента. Подходит для многошаговых задач и работы после сжатия контекста. CX Codex +1 2 800установок session-orchestrator hashgraph-online session-orchestrator — хук для Claude Code и Codex, который структурирует сессию агента: планирование, поэтапное выполнение, контроль качества и закрытие с трекингом задач. CX Codex ★ 1 596звёзд репо

Из того же набора40

Весь набор →
ux-designer Субагент ux-designer проектирует пользовательские пути, интерфейсные паттерны и схемы экранов без написания фронтенд-кода. CX Codex ★ 489звёзд репо accessibility-specialist Субагент accessibility-specialist проверяет интерфейс по критериям WCAG, разбирает клавиатурную навигацию и ARIA. Подключайте его для аудита доступности веб-приложения. CX Codex ★ 489звёзд репо analytics-engineer Субагент analytics-engineer для проектирования схем событий, реализации трекинга и планирования экспериментов. Помогает добавить отслеживание в фичи, спроектировать воронки конверсии и настроить A/B-тесты. CX Codex ★ 489звёзд репо execution Скилл execution управляет запуском фаз реализации в оркестраторе Maestro через нативных субагентов с проверкой конфликтов файлов. CX Codex +1 ★ 489звёзд репо i18n-specialist Субагент i18n-specialist для полной локализации: извлекает жёсткие строки, настраивает структуру locale-файлов, реализует правила множественных форм, поддержку RTL и форматирование дат, чисел и валют по локали. CX Codex ★ 489звёзд репо design-system-engineer Субагент design-system-engineer проектирует иерархию дизайн-токенов, строит контракты API для компонентов и настраивает переключение тем без прямого указания цветов и отступов в коде. CX Codex ★ 489звёзд репо implementation-planning Скилл implementation-planning превращает утверждённый дизайн в подробный план реализации с этапами и назначениями субагентам. Он запускается на второй фазе стандартного процесса Maestro. CX Codex +1 ★ 489звёзд репо compliance-reviewer Субагент compliance-reviewer для проверки соответствия данных и кода правилам GDPR, CCPA, cookie consent и open-source лицензиям. Ищет щели в обработке данных, согласии пользователей и атрибуции зависимостей. CX Codex ★ 489звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой