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/replacedirectly 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-DDis 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
- Resolve state directory from
MAESTRO_STATE_DIR - Create
<state_dir>/state/directory if it does not exist (defense-in-depth fallback — workspace readiness startup check is the primary mechanism) - Verify no existing
active-session.md— if one exists, alert the user and offer to archive or resume - Generate session state from the
session-statetemplate (load it withget_skill_content(["session-state"])if not already loaded), settingworkflow_modetostandardorexpressandtask_complexityfrom the design document frontmatter - Initialize all phases as
pending - Set overall status to
in_progress - Set
current_phaseto 1 - Record design document and implementation plan paths
- 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
- Timestamp: Update
updatedfield on every state change - Phase Status: Transition phase status following valid transitions:
pending->in_progressin_progress->completedin_progress->failedfailed->in_progress(retry)pending->skipped(user decision only)
- Current Phase: Update
current_phaseto the ID of the currently executing phase - File Manifest: Append to
files_created,files_modified, orfiles_deletedas subagents report changes - Downstream Context: Persist parsed Handoff Report Part 2 fields into phase
downstream_context - Token Usage: Aggregate token counts from subagent responses into both
total_*andby_agentsections - Error Recording: Append to phase
errorsarray with complete metadata
Error Recording Format
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_counton each retry attempt - Maximum
MAESTRO_MAX_RETRIESretries per phase (default2) 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:
## 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_ARCHIVEistrue(default) - User explicitly requests archival (regardless of
MAESTRO_AUTO_ARCHIVEsetting) - 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:
- Call
archive_sessionwith the session ID. The MCP tool atomically:
- Updates session status to
completed - Moves
active-session.mdto<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)
- Confirm archival to user with summary of what was archived (use the
archived_filesarray in the response)
If archive_session is not available, fall back to manual file operations:
- Create
<state_dir>/plans/archive/directory if it does not exist - Create
<state_dir>/state/archive/directory if it does not exist - 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 withmvor read+write+delete. Do NOT leave the file in both locations. Skip this step ifdesign_documentisnull(Express sessions). - MOVE (not copy) implementation plan from
<state_dir>/plans/to<state_dir>/plans/archive/— same: delete the original. Skip this step ifimplementation_planisnull(Express sessions). - Update session state
statustocompleted - Update
updatedtimestamp - MOVE (not copy)
active-session.mdfrom<state_dir>/state/to<state_dir>/state/archive/<session-id>.md— delete the original. - 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.mdexists in<state_dir>/state/ - No plan files remain in
<state_dir>/plans/(only thearchive/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
- Read State: If session state was already injected into the prompt (e.g., via
/maestro:resume), use that injected content instead of callingget_session_status. Otherwise, ifget_session_statusappears in your available tools, call it to read the active session. Otherwise, read state viarun_shell_command:node <runtime-script-root>/read-active-session.js(resolvesMAESTRO_STATE_DIRinternally) - Parse Frontmatter: Extract YAML frontmatter for session metadata
- Identify Position: Determine:
- Last completed phase (highest ID with
status: completed) - Current active phase (first phase with
status: in_progressorpending) - Any failed phases with unresolved errors
- Check Errors: Identify unresolved errors from previous execution
- Present Summary: Display a status summary to the user covering the position and errors identified in steps 3-4
- 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
- Continue Execution: Resume from the first pending or failed phase
- Update State: Mark resumed phase as
in_progressand 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 theagentsarray to identify which agent was running. - If phase status is
completedbut session status isin_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:
- Total: Sum across all agents and phases
- By Agent: Per-agent totals across all their invocations
Format
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