Command Palette

Search for a command to run...

Назад к скиллам
скилл № 31429

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от 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 a task_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:

  1. Lock the source thread's lifecycle + writer.
  2. Persist any pending items in the source.
  3. Resolve the source's RolloutLineage.
  4. Materialize each ancestor segment to SQLite (if not already).
  5. Load the ModelContext for the chosen boundary.
  6. Return a PreparedFork ready 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:

  1. Lock lifecycle + writer + writer_lock_coordinator.
  2. Resolve the current rollout from SQLite (expected_sqlite_path is the CAS anchor).
  3. Read SessionMeta from the current rollout, verify id == thread_id and history_mode == Paginated.
  4. Materialize any compressed lineage segments.
  5. Create a new immutable rollout file referencing the retained prefix.
  6. CAS the SQLite rollout_path to 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):

  1. Lock active_turn and verify task.kind == TaskKind::Regular.
  2. Snapshot descendants (not a seal; best-effort).
  3. live_thread.flush() — persistence first; if it fails, leave the turn running.
  4. Re-lock and re-verify kind (flush can yield).
  5. Take the turn and task; cancel the cancellation token; cancel git enrichment.
  6. task.handle.detach() with a GRACEFULL_INTERRUPTION_TIMEOUT_MS timeout.
  7. session.input_queue.clear_pending(&turn) — pending input is NOT persisted.
  8. shutdown_session_runtime(session) + live_thread.flush() + live_thread.shutdown().
  9. Emit ShutdownComplete event 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_
Полный SKILL.md на GitHub

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

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), без исполняемых скриптов.

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

Сравнить session-branch-fork с