session-branch-fork
Design a session-level fork / revert / recover / suspend mechanism over a paginated history with lineage tracking, immutable segments, global lock…
от MiniMax-AI★ 30 звёзд на GitHub
Установить session-branch-fork в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
Session Branch / Fork
Conceptual reference only. The mcode 0.2.4 public surface has no parameters for session fork / revert / suspend / paginated history / ModelContext reconstruction. The only documented mcode 0.2.4 tool for sub-agent lifecycle is
task(...), which returns atask_id(string); any deeper structure (thread_id,rollout_id, sqlite path, lineage segment, ModelContext reconstruction algorithm) is host-internal. Every Rust block, SQLite CAS anchor, lease helper, and op name below is Codex-internal pseudocode (codex-rs/thread-store/), NOT a mcode 0.2.4 design. The actual implementation must follow the host's verified APIs.
Design a session-level fork / revert / recover / suspend system over a paginated
history. Mirrors codex-rs/thread-store/.
When to use
Activate when designing:
- A "fork this session from turn N" feature.
- A "undo the last N turns" feature.
- A "suspend the running session, recover it later" feature.
- A paginated history with cross-segment cursors.
- A model-context reconstruction algorithm that doesn't re-read the entire history.
When NOT to use
- Single-session task state → use
world-state-tracking. - No undo, no fork, no suspend needed → standard append-only history is enough.
Process
1. Pick a ThreadHistoryMode
pub enum ThreadHistoryMode {
Legacy, // entire thread in one JSONL
Paginated, // immutable segments, supports fork/revert
}
Default to Legacy for backward compatibility, but use Paginated for any new thread. Paginated is what makes fork / revert / lineage work.
2. Define the immutable segment model
pub struct RolloutLineageSegment {
pub rollout_id: ThreadId,
pub rollout_path: PathBuf,
pub start_ordinal: u64,
pub end: Option<HistoryPosition>, // byte offset
}
pub struct RolloutLineage {
pub segments: Vec<RolloutLineageSegment>,
}
Key invariants:
- Segments are immutable. A new segment is created for any change.
- The lineage is a list of segments ordered from oldest to newest.
- Each segment knows its start ordinal and (optionally) its end offset.
3. Implement fork with ForkBoundary
pub enum ForkBoundary {
Latest, // inherit source's latest durable state
ThroughTurn(String), // include this turn
BeforeTurn(String), // exclude this turn
}
pub struct PrepareForkParams {
pub thread_id: ThreadId,
pub boundary: ForkBoundary,
}
pub struct PreparedFork {
pub source_thread_id: ThreadId,
pub model_context: Arc<ModelContext>,
}
Fork flow:
- Lock the source thread's lifecycle + writer.
- Persist any pending items in the source.
- Resolve the source's
RolloutLineage. - Materialize each ancestor segment to SQLite (if not already).
- Load the
ModelContextfor the chosen boundary. - Return a
PreparedForkready to be turned into a new thread.
4. Implement revert with CAS
pub struct RevertThreadParams {
pub thread_id: ThreadId,
pub before_turn_id: String, // first turn EXCLUDED from retained history
}
Revert flow:
- Lock lifecycle + writer + writer_lock_coordinator.
- Resolve the current rollout from SQLite (
expected_sqlite_pathis the CAS anchor). - Read
SessionMetafrom the current rollout, verifyid == thread_idandhistory_mode == Paginated. - Materialize any compressed lineage segments.
- Create a new immutable rollout file referencing the retained prefix.
- CAS the SQLite
rollout_pathto the new file.
Critical contract: revert only rolls back in-memory context. It does not undo filesystem changes. The client is responsible for undoing edits on disk.
5. Implement suspend + recover
Op::SuspendTurnAndShutdown { reply: oneshot::Sender<...> }
Op::RecoverTurn { thread_settings, reply: oneshot::Sender<...> }
Suspend flow (9 steps):
- Lock
active_turnand verifytask.kind == TaskKind::Regular. - Snapshot descendants (not a seal; best-effort).
live_thread.flush()— persistence first; if it fails, leave the turn running.- Re-lock and re-verify kind (flush can yield).
- Take the turn and task; cancel the cancellation token; cancel git enrichment.
task.handle.detach()with aGRACEFULL_INTERRUPTION_TIMEOUT_MStimeout.session.input_queue.clear_pending(&turn)— pending input is NOT persisted.shutdown_session_runtime(session)+live_thread.flush()+live_thread.shutdown().- Emit
ShutdownCompleteevent only after the writer is closed.
Critical contract: do NOT record a terminal turn event on suspend. This
intentionally leaves the turn's ID reclaimable, so Op::RecoverTurn can resume it.
6. Use a global lock for multi-process safety
When two Codexes might fork / revert the same thread, use a DB-level lease:
try_claim_global_phase2_job(thread_id, JOB_LEASE_SECONDS)— single-writer.- `heartbeat_
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл session-branch-fork?
Design a session-level fork / revert / recover / suspend mechanism over a paginated history with lineage tracking, immutable segments, global lock, ModelContext reconstruction, and bounded replay. USE WHEN: designing session persistence, building a "fork this conversation" feature, building "undo last N turns", building "suspend and resume later", implementing a paginated history with segment-level cursor, reconstructing ModelContext from disk, or any task involving "session as a git-like object graph". TRIGGER PHRASES: "session fork", "session branch", "thread fork", "thread rollback", "revert thread", "ThreadRollback", "SuspendTurnAndShutdown", "Op::RecoverTurn", "paginated history", "RolloutLineage", "ForkBoundary", "RolloutReferenceIndex", "ModelContext reconstruction", "ReverseJsonlScanner", "bounded replay", "git baseline", "writer lock", "subagent lineage". SKIP WHEN: single-session task state (use `world-state-tracking`), no need to undo, no need to fork.
Как установить скилл session-branch-fork?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл session-branch-fork запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
docx
AnthropicUse this skill whenever the user wants to create, read, edit, or manipulate Word documents (.docx files) or Word templates (.dotx files). Triggers include…
AnthropicUse this skill whenever the user wants to do anything with PDF files. This includes reading or extracting text/tables from PDFs, combining or merging multiple…
xlsx
AnthropicUse this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing…
pptx
AnthropicUse this skill any time a .pptx or .potx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or…