Skip to content

chain

Class info

🛈 DocStrings

Reconstruct conversation threads from the parentUuid chain of a transcript.

Every entry that takes part in the chain derives from :class:ClaudeEntryBase (user, assistant, attachment, system, progress, saved-hook-context). The chain regularly runs through non-message entries, so walks index all of them.

A turn that runs tools in parallel forks the chain: Claude Code writes one assistant entry per content block (all sharing the API message.id), and each tool-result entry's parent is the assistant entry holding its own tool_use. A plain walk from the leaf only follows the branch the next turn continued from and loses the other calls and results; :func:resolve_chain puts them back (as upstream's get_session_messages and Claude Code itself do).

For a single walk over a large transcript, validating every entry costs far more than the walk. The raw functions walk the parsed JSON instead (as upstream does) and :func:validate_chain_entries types only the entries actually needed.

RawEntry module-attribute

RawEntry = dict[str, Any]

A transcript line as parsed JSON, not validated.

find_leaf

find_leaf(entries: Iterable[ClaudeJSONLEntry]) -> ClaudeChainEntry | None

The last main-thread user/assistant entry in file order.

Sidechain, meta and team entries are skipped unless nothing else is there.

Source code in src/clawd_code_sdk/storage/chain.py
def find_leaf(entries: Iterable[ClaudeJSONLEntry]) -> ClaudeChainEntry | None:
    """The last main-thread user/assistant entry in file order.

    Sidechain, meta and team entries are skipped unless nothing else is there.
    """
    last: ClaudeChainEntry | None = None
    last_main: ClaudeChainEntry | None = None
    for entry in entries:
        if not isinstance(entry, ClaudeUserEntry | ClaudeAssistantEntry):
            continue
        last = entry
        if not entry.is_sidechain and not entry.is_meta and not entry.team_name:
            last_main = entry
    return last_main or last

index_chain_entries

index_chain_entries(entries: Iterable[ClaudeJSONLEntry]) -> dict[str, ClaudeChainEntry]

Index all chain entries by uuid, in file order.

Source code in src/clawd_code_sdk/storage/chain.py
def index_chain_entries(entries: Iterable[ClaudeJSONLEntry]) -> dict[str, ClaudeChainEntry]:
    """Index all chain entries by ``uuid``, in file order."""
    return {entry.uuid: entry for entry in entries if isinstance(entry, ClaudeChainEntry)}

read_raw_chain_entries

read_raw_chain_entries(session_path: Path) -> dict[str, RawEntry]

The chain entries of a transcript as parsed JSON, by uuid, in file order.

Only parses JSON: about as fast as reading the file, much faster than :func:~clawd_code_sdk.storage.helpers.read_session on large transcripts. Corrupt lines are skipped.

Source code in src/clawd_code_sdk/storage/chain.py
def read_raw_chain_entries(session_path: Path) -> dict[str, RawEntry]:
    """The chain entries of a transcript as parsed JSON, by ``uuid``, in file order.

    Only parses JSON: about as fast as reading the file, much faster than
    :func:`~clawd_code_sdk.storage.helpers.read_session` on large transcripts.
    Corrupt lines are skipped.
    """
    from clawd_code_sdk.storage.helpers import _gc_paused

    types = chain_entry_types()
    index: dict[str, RawEntry] = {}
    if not session_path.exists():
        return index
    with _gc_paused(), session_path.open("rb") as f:
        for line in f:
            if not line.strip():
                continue
            try:
                data = anyenv.load_json(line, return_type=dict)
            except anyenv.JsonLoadError, TypeError:  # TypeError: valid JSON, not an object
                continue
            uuid = data.get("uuid")
            if data.get("type") in types and isinstance(uuid, str):
                index[uuid] = data
    return index

resolve_chain

resolve_chain(
    entries: Iterable[ClaudeJSONLEntry],
    leaf_uuid: str | None = None,
    *,
    recover_parallel_tool_calls: bool = True,
) -> list[ClaudeChainEntry]

The thread ending at leaf_uuid (default: :func:find_leaf), root first.

The result contains every chain entry on the thread, including attachments and system entries; filter by type for messages only. Messages a model refusal withdrew (model_refusal_fallback entries' retracted_message_uuids) are left out; the walk still passes through them.

Parameters:

Name Type Description Default
entries Iterable[ClaudeJSONLEntry]

Entries of one transcript, in file order.

required
leaf_uuid str | None

Entry to end the thread at.

None
recover_parallel_tool_calls bool

Put back the tool calls and results of parallel tool turns that the parentUuid walk skips.

True
Source code in src/clawd_code_sdk/storage/chain.py
def resolve_chain(
    entries: Iterable[ClaudeJSONLEntry],
    leaf_uuid: str | None = None,
    *,
    recover_parallel_tool_calls: bool = True,
) -> list[ClaudeChainEntry]:
    """The thread ending at ``leaf_uuid`` (default: :func:`find_leaf`), root first.

    The result contains every chain entry on the thread, including attachments
    and system entries; filter by type for messages only. Messages a model refusal
    withdrew (``model_refusal_fallback`` entries' ``retracted_message_uuids``) are left
    out; the walk still passes through them.

    Args:
        entries: Entries of one transcript, in file order.
        leaf_uuid: Entry to end the thread at.
        recover_parallel_tool_calls: Put back the tool calls and results of
            parallel tool turns that the ``parentUuid`` walk skips.
    """
    entry_list = list(entries)
    index = index_chain_entries(entry_list)
    if leaf_uuid is None:
        leaf = find_leaf(entry_list)
        if leaf is None:
            return []
        leaf_uuid = leaf.uuid
    chain = walk_ancestry(index, leaf_uuid)
    chain.reverse()
    if recover_parallel_tool_calls:
        chain = _recover_parallel_tool_calls(index, chain)
    if retracted := _retracted_uuids(entry_list):
        chain = [entry for entry in chain if entry.uuid not in retracted]
    return chain

validate_chain_entries

validate_chain_entries(raw_entries: Iterable[RawEntry]) -> list[ClaudeChainEntry]

Validate parsed entries into their models, keeping the chain entries that pass.

Source code in src/clawd_code_sdk/storage/chain.py
def validate_chain_entries(raw_entries: Iterable[RawEntry]) -> list[ClaudeChainEntry]:
    """Validate parsed entries into their models, keeping the chain entries that pass."""
    from clawd_code_sdk.storage.helpers import _entry_adapter

    adapter = _entry_adapter()
    entries: list[ClaudeChainEntry] = []
    for raw in raw_entries:
        try:
            entry = adapter.validate_python(raw)
        except ValidationError:
            continue
        if isinstance(entry, ClaudeChainEntry):
            entries.append(entry)
    return entries

walk_ancestry

walk_ancestry(
    index: dict[str, ClaudeChainEntry], uuid: str, *, include_start: bool = True
) -> list[ClaudeChainEntry]

Entries from uuid back to the root (leaf first), following parent_uuid.

Stops at a missing parent or a cycle. logical_parent_uuid (set across compaction boundaries) is not followed.

Source code in src/clawd_code_sdk/storage/chain.py
def walk_ancestry(
    index: dict[str, ClaudeChainEntry], uuid: str, *, include_start: bool = True
) -> list[ClaudeChainEntry]:
    """Entries from ``uuid`` back to the root (leaf first), following ``parent_uuid``.

    Stops at a missing parent or a cycle. ``logical_parent_uuid`` (set across
    compaction boundaries) is not followed.
    """
    chain: list[ClaudeChainEntry] = []
    seen: set[str] = set()
    current = index.get(uuid)
    while current is not None and current.uuid not in seen:
        seen.add(current.uuid)
        chain.append(current)
        current = index.get(current.parent_uuid) if current.parent_uuid else None
    return chain if include_start else chain[1:]

walk_raw_ancestry

walk_raw_ancestry(
    index: dict[str, RawEntry], uuid: str, *, include_start: bool = True
) -> list[RawEntry]

Like :func:walk_ancestry, over parsed JSON: leaf first, stops at a cycle.

Source code in src/clawd_code_sdk/storage/chain.py
def walk_raw_ancestry(
    index: dict[str, RawEntry], uuid: str, *, include_start: bool = True
) -> list[RawEntry]:
    """Like :func:`walk_ancestry`, over parsed JSON: leaf first, stops at a cycle."""
    chain: list[RawEntry] = []
    seen: set[str] = set()
    current = index.get(uuid)
    while current is not None and current["uuid"] not in seen:  # indexed: uuid is a str
        seen.add(current["uuid"])
        chain.append(current)
        parent = current.get("parentUuid")
        current = index.get(parent) if isinstance(parent, str) else None
    return chain if include_start else chain[1:]