free-claude-code/messaging/transcript/buffer.py
Ali Khokhar 85b601884d
Some checks are pending
CI / Ban suppressions and legacy annotations (push) Waiting to run
CI / pytest (push) Waiting to run
CI / ruff-check (push) Waiting to run
CI / ruff-format (push) Waiting to run
CI / ty (push) Waiting to run
Remove legacy future annotation imports (#982)
## Problem

Python 3.14 provides native lazy annotations, but the codebase still
relied on legacy future annotation imports. Those imports also made
type-only import cycles easier to hide instead of fixing ownership
boundaries.

## Changes

| Before | After |
| --- | --- |
| Python files used `from __future__ import annotations`. | Python files
rely on Python 3.14 native lazy annotations. |
| Some runtime modules used `TYPE_CHECKING` or local imports for
required dependencies. | Runtime modules use top-level owner-module
imports with explicit boundaries. |
| Local and GitHub guardrails only rejected type ignore suppressions. |
Local and GitHub guardrails reject type ignore suppressions and legacy
future annotation imports. |
| Agent docs only documented the no-type-ignore rule. | Agent docs
document the Python 3.14 annotation and import-boundary rules. |

<!-- greptile_comment -->

<details open><summary><h3>Greptile Summary</h3></summary>

This PR moves the codebase to Python 3.14 native lazy annotations. The
main changes are:

- Removed legacy `from __future__ import annotations` imports across
Python modules.
- Promoted selected runtime dependencies from `TYPE_CHECKING` or local
imports to explicit owner-module imports.
- Added local, GitHub, and contract-test guardrails to reject legacy
future annotation imports.
- Updated agent docs with the annotation and import-boundary rules.
- Bumped the package patch version for production-file changes.
</details>

<h3>Confidence Score: 5/5</h3>

Safe to merge with low risk.

The changes are mostly mechanical annotation cleanup with matching CI
and contract-test guardrails. Reviewed import-boundary updates did not
show a confirmed runtime cycle or dependency break.

No files require special attention.

<details><summary><h3><a href="https://www.greptile.com/trex"><img
alt="T-Rex"
src="https://greptile-static-assets.s3.amazonaws.com/trex/trex_green.svg"
height="20" align="absmiddle"></a> T-Rex Logs</h3></summary>

**What T-Rex did**
- Performed an end-to-end validation of the guardrail contract suite: an
environment check confirmed uv availability, a guardrail pytest run used
CPython 3.14.0 with 5 passing contract tests, 3 focused CI-script tests
passed, and the direct CI suppressions guardrail command (including the
legacy future-annotations grep) also passed.

<a
href="https://app.greptile.com/trex/runs/13303335/artifacts"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewAllArtifactsDark.svg?v=4"><source
media="(prefers-color-scheme: light)"
srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewAllArtifacts.svg?v=4"><img
alt="View all artifacts"
src="https://greptile-static-assets.s3.amazonaws.com/badges/ViewAllArtifacts.svg?v=4"></picture></a>

<sub><a href="https://www.greptile.com/trex"><img alt="T-Rex"
src="https://greptile-static-assets.s3.amazonaws.com/trex/trex_green.svg"
height="14" align="absmiddle"></a> Ran code and verified through
T-Rex</sub>
</details>

<details open><summary><h3>Important Files Changed</h3></summary>

| Filename | Overview |
|----------|----------|
| api/runtime.py | Moves messaging, CLI manager, session, limiter, and
tree dependencies from local/type-checking imports to explicit top-level
owner-module imports. |
| messaging/platforms/telegram.py | Removes future annotations and
promotes Telegram SDK type imports into the existing availability guard.
|
| messaging/platforms/telegram_inbound.py | Removes future annotations
and imports Telegram SDK types at module scope for inbound
normalization. |
| tests/contracts/test_import_boundaries.py | Adds an AST contract that
rejects legacy future annotation imports across Python files. |
| scripts/ci.sh | Extends the local suppression check to reject legacy
future annotation imports alongside type-ignore suppressions. |
| scripts/ci.ps1 | Mirrors the local PowerShell CI suppression check for
legacy future annotations. |
| .github/workflows/tests.yml | Renames and broadens the GitHub
guardrail job to reject both type suppressions and legacy future
annotations. |
| pyproject.toml | Bumps the patch version for production-file changes.
|

</details>

<details open><summary><h3>Sequence Diagram</h3></summary>

<a href="#gh-light-mode-only">

```mermaid
%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
participant Dev as Developer/CI
participant Guard as Suppression guard
participant AST as Import-boundary contract test
participant Py as Python modules

Dev->>Guard: Run local/GitHub suppression check
Guard->>Py: "Scan *.py for type ignores and future annotations"
Guard-->>Dev: Fail if legacy annotation import remains
Dev->>AST: Run pytest contract tests
AST->>Py: Parse imports with ast
AST-->>Dev: Assert no future annotations/import-boundary violations
Py-->>Dev: Use Python 3.14 native lazy annotations
```

</a>
<a href="#gh-dark-mode-only">

```mermaid
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
participant Dev as Developer/CI
participant Guard as Suppression guard
participant AST as Import-boundary contract test
participant Py as Python modules

Dev->>Guard: Run local/GitHub suppression check
Guard->>Py: "Scan *.py for type ignores and future annotations"
Guard-->>Dev: Fail if legacy annotation import remains
Dev->>AST: Run pytest contract tests
AST->>Py: Parse imports with ast
AST-->>Dev: Assert no future annotations/import-boundary violations
Py-->>Dev: Use Python 3.14 native lazy annotations
```

</a>
</details>

<sub>Reviews (2): Last reviewed commit: ["Remove legacy future
annotations
import"](6e6cda69da)
| [Re-trigger
Greptile](https://app.greptile.com/api/retrigger?id=41875785)</sub>

<!-- /greptile_comment -->
2026-07-04 21:41:51 -07:00

220 lines
7.3 KiB
Python

"""Transcript event application and open-block tracking."""
from typing import Any
from .context import RenderCtx
from .renderer import render_segments
from .segments import (
ErrorSegment,
Segment,
SubagentSegment,
TextSegment,
ThinkingSegment,
ToolCallSegment,
ToolResultSegment,
)
from .subagents import SubagentState, task_heading_from_input
_SUBAGENT_SUPPRESSED_EVENTS = frozenset(
{
"thinking_start",
"thinking_delta",
"thinking_chunk",
"text_start",
"text_delta",
"text_chunk",
}
)
class TranscriptBuffer:
"""Maintains an ordered, truncatable transcript of parsed CLI events."""
def __init__(
self,
*,
show_tool_results: bool = True,
debug_subagent_stack: bool = False,
) -> None:
self._segments: list[Segment] = []
self._open_thinking_by_index: dict[int, ThinkingSegment] = {}
self._open_text_by_index: dict[int, TextSegment] = {}
self._open_tools_by_index: dict[int, ToolCallSegment] = {}
self._tool_name_by_id: dict[str, str] = {}
self._show_tool_results = bool(show_tool_results)
self._subagents = SubagentState(debug=debug_subagent_stack)
def apply(self, event: dict[str, Any]) -> None:
"""Apply a parsed CLI transcript event."""
event_type = event.get("type")
if self._subagents.in_subagent() and event_type in _SUBAGENT_SUPPRESSED_EVENTS:
return
if event_type == "thinking_start":
self._start_thinking(_event_index(event))
return
if event_type in ("thinking_delta", "thinking_chunk"):
self._append_thinking(_event_index(event), str(event.get("text", "")))
return
if event_type == "thinking_stop":
self._open_thinking_by_index.pop(_event_index(event), None)
return
if event_type == "text_start":
self._start_text(_event_index(event))
return
if event_type in ("text_delta", "text_chunk"):
self._append_text(_event_index(event), str(event.get("text", "")))
return
if event_type == "text_stop":
self._open_text_by_index.pop(_event_index(event), None)
return
if event_type == "tool_use_start":
self._start_tool_use(event)
return
if event_type == "tool_use_delta":
return
if event_type == "tool_use_stop":
segment = self._open_tools_by_index.pop(_event_index(event), None)
if segment is not None:
segment.closed = True
return
if event_type == "block_stop":
self._close_block(_event_index(event))
return
if event_type == "tool_use":
self._append_complete_tool_use(event)
return
if event_type == "tool_result":
self._append_tool_result(event)
return
if event_type == "error":
self._segments.append(ErrorSegment(str(event.get("message", ""))))
def render(self, ctx: RenderCtx, *, limit_chars: int, status: str | None) -> str:
return render_segments(
self._segments,
ctx,
limit_chars=limit_chars,
status=status,
)
def _start_thinking(self, index: int) -> None:
if index >= 0:
self._close_block(index)
segment = ThinkingSegment()
self._segments.append(segment)
if index >= 0:
self._open_thinking_by_index[index] = segment
def _append_thinking(self, index: int, text: str) -> None:
segment = self._open_thinking_by_index.get(index)
if segment is None:
segment = ThinkingSegment()
self._segments.append(segment)
if index >= 0:
self._open_thinking_by_index[index] = segment
segment.append(text)
def _start_text(self, index: int) -> None:
if index >= 0:
self._close_block(index)
segment = TextSegment()
self._segments.append(segment)
if index >= 0:
self._open_text_by_index[index] = segment
def _append_text(self, index: int, text: str) -> None:
segment = self._open_text_by_index.get(index)
if segment is None:
segment = TextSegment()
self._segments.append(segment)
if index >= 0:
self._open_text_by_index[index] = segment
segment.append(text)
def _start_tool_use(self, event: dict[str, Any]) -> None:
index = _event_index(event)
if index >= 0:
self._close_block(index)
tool_id = _event_tool_id(event, "id")
name = str(event.get("name", "") or "tool")
if tool_id:
self._tool_name_by_id[tool_id] = name
if name == "Task":
segment = SubagentSegment(task_heading_from_input(event.get("input")))
self._segments.append(segment)
self._subagents.push(tool_id, segment)
return
segment = self._append_tool_call(tool_id, name)
if index >= 0:
self._open_tools_by_index[index] = segment
def _append_complete_tool_use(self, event: dict[str, Any]) -> None:
tool_id = _event_tool_id(event, "id")
name = str(event.get("name", "") or "tool")
if tool_id:
self._tool_name_by_id[tool_id] = name
if name == "Task":
segment = SubagentSegment(task_heading_from_input(event.get("input")))
self._segments.append(segment)
self._subagents.push(tool_id, segment)
return
segment = self._append_tool_call(tool_id, name)
segment.closed = True
def _append_tool_call(self, tool_id: str, name: str) -> ToolCallSegment:
if self._subagents.in_subagent():
parent = self._subagents.current_segment()
if parent is not None:
return parent.set_current_tool_call(tool_id, name)
segment = ToolCallSegment(tool_id, name)
self._segments.append(segment)
return segment
def _append_tool_result(self, event: dict[str, Any]) -> None:
tool_id = _event_tool_id(event, "tool_use_id")
name = self._tool_name_by_id.get(tool_id)
if self._subagents.in_subagent():
self._subagents.close_for_tool_result(tool_id, tool_name=name)
if not self._show_tool_results:
return
self._segments.append(
ToolResultSegment(
tool_id,
event.get("content"),
name=name,
is_error=bool(event.get("is_error", False)),
)
)
def _close_block(self, index: int) -> None:
if index in self._open_tools_by_index:
segment = self._open_tools_by_index.pop(index, None)
if segment is not None:
segment.closed = True
return
if index in self._open_thinking_by_index:
self._open_thinking_by_index.pop(index, None)
return
if index in self._open_text_by_index:
self._open_text_by_index.pop(index, None)
def _event_index(event: dict[str, Any]) -> int:
return int(event.get("index", -1))
def _event_tool_id(event: dict[str, Any], key: str) -> str:
return str(event.get(key, "") or "").strip()