项目文件夹

文件
Ali Khokhar 3fba1c6fc3 Give messaging clear exact subtree semantics (#1072)
## Problem

Messaging `/clear` did not follow the selected platform message
boundary. Reply clears preserved the selected user prompt, while
standalone clears preserved user-authored messages and could reset FCC
state outside the invoking chat.

## Changes

| Before | After |
| --- | --- |
| Reply `/clear` removed a logical conversation branch but retained the
selected message. | Reply `/clear` deletes the selected message and its
literal reply subtree, including the clear command. |
| Standalone `/clear` retained user prompts and voice notes while
resetting global messaging state. | Standalone `/clear` deletes every
tracked message and resets FCC state only in the invoking platform and
chat. |
| Trees recorded only logical execution parentage. | Trees separately
persist logical execution ancestry and exact prompt/status reply
ownership. |
| Clear coordination used one global admission boundary. | Per-chat
clear generations coordinate admission, voice cancellation, persistence,
and best-effort platform deletion. |
| Persistence tracked only FCC-authored clearable output. | Persistence
tracks managed inbound and outbound messages and migrates legacy
entries. |

<!-- greptile_comment -->

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

This PR gives messaging `/clear` exact per-chat and reply-subtree
behavior. The main changes are:

- Per-chat clear generations for admission and startup-notice cleanup.
- Managed inbound and outbound message tracking for deletion.
- Exact prompt/status reply ownership in message trees.
- Scoped voice cancellation and clear persistence updates.
- Updated docs, smoke coverage, and messaging tests.
</details>

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

The clear flow is mostly well-contained, with one upgrade-path issue in
legacy tree restoration.

Newly created prompt/status subtrees use the new exact reference fields
consistently, and legacy snapshots can map old status replies to prompt
references. However, reply `/clear` on an upgraded status can miss
descendants and leave stale state/messages.

src/free_claude_code/messaging/trees/snapshot.py

<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**
- T-Rex attempted to prepare and run a focused legacy snapshot
reproduction harness for legacy status replies detach, but tool access
was blocked before execution.
- A messaging clear smoke test harness was executed and reported a
passing result: 20 items collected and 20 passed in 1.69 seconds, with
traces for test\_reply\_clear\_uses\_literal and related paths shown in
the log.

<a
href="https://app.greptile.com/trex/runs/14131337/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 |
|----------|----------|
| src/free_claude_code/messaging/workflow.py | Adds per-chat clear
generations, managed inbound recording, scoped clears, and
startup-notice invalidation. |
| src/free_claude_code/messaging/trees/graph.py | Adds exact
prompt/status reference resolution and literal reply-subtree traversal.
|
| src/free_claude_code/messaging/trees/runtime.py | Adds exact
message-subtree removal and status-only clearing behavior. |
| src/free_claude_code/messaging/trees/snapshot.py | Adds
parent_reference_id persistence and legacy fallback; the fallback can
miss legacy status-reply descendants. |
| src/free_claude_code/messaging/session/managed_message_log.py |
Replaces the clearable output log with managed inbound and outbound
message tracking. |
| src/free_claude_code/messaging/commands.py | Routes reply and
standalone `/clear` through the new exact deletion ID flows. |

</details>

<details open><summary><h3>Flowchart</h3></summary>

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

```mermaid
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Incoming message] --> B{Standalone /clear?}
B -- yes --> C[Clear invoking chat]
C --> D[Cancel scoped voice work]
C --> E[Collect managed and tree message IDs]
C --> F[Advance chat clear generation]
F --> G[Detach scoped trees]
G --> H[Clear scoped session store]
H --> I[Best-effort platform deletes]
B -- no --> J[Record managed inbound message]
J --> K[Admit with stop and clear token]
K --> L{Reply /clear?}
L -- yes --> M[Resolve exact prompt or status reference]
M --> N[Remove literal reference subtree]
N --> I
L -- no --> O[Queue or run tree node]
```

</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"}}}%%
flowchart TD
A[Incoming message] --> B{Standalone /clear?}
B -- yes --> C[Clear invoking chat]
C --> D[Cancel scoped voice work]
C --> E[Collect managed and tree message IDs]
C --> F[Advance chat clear generation]
F --> G[Detach scoped trees]
G --> H[Clear scoped session store]
H --> I[Best-effort platform deletes]
B -- no --> J[Record managed inbound message]
J --> K[Admit with stop and clear token]
K --> L{Reply /clear?}
L -- yes --> M[Resolve exact prompt or status reference]
M --> N[Remove literal reference subtree]
N --> I
L -- no --> O[Queue or run tree node]
```

</a>
</details>

<a
href="https://app.greptile.com/api/ide/codex?prompt=IMPORTANT%3A%20Work%20in%20the%20repository%20%22alishahryar1%2Ffree-claude-code%22%20on%20the%20existing%20branch%20%22ali%2Fclear-message-subtree%22.%20Checkout%20that%20branch%20%E2%80%94%20do%20NOT%20create%20a%20new%20branch%20or%20open%20a%20new%20PR.%20Push%20your%20changes%20to%20%22ali%2Fclear-message-subtree%22.%0A%0AFix%20the%20following%201%20code%20review%20issue.%20Work%20through%20them%20one%20at%20a%20time%2C%20proposing%20concise%20fixes.%0A%0A---%0A%0A%23%23%23%20Issue%201%20of%201%0Asrc%2Ffree_claude_code%2Fmessaging%2Ftrees%2Fsnapshot.py%3A192-193%0A**Legacy%20Status%20Replies%20Detach**%0A%0AWhen%20an%20upgraded%20legacy%20snapshot%20contains%20a%20child%20that%20originally%20replied%20to%20its%20parent%20status%2C%20this%20fallback%20rewrites%20the%20missing%20exact%20reference%20to%20the%20parent%20prompt.%20A%20later%20reply%20%60%2Fclear%60%20on%20that%20status%20traverses%20from%20the%20status%20ID%2C%20finds%20no%20migrated%20child%20edge%2C%20and%20leaves%20the%20old%20status-reply%20descendants%20and%20their%20managed%20messages%20behind.%0A%0A&repo=alishahryar1%2Ffree-claude-code&pr=1072&platform=github"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://greptile-static-assets.s3.amazonaws.com/badges/FixAllInCodexDark.svg?v=6"><source
media="(prefers-color-scheme: light)"
srcset="https://greptile-static-assets.s3.amazonaws.com/badges/FixAllInCodex.svg?v=6"><img
alt="Fix All in Codex"
src="https://greptile-static-assets.s3.amazonaws.com/badges/FixAllInCodex.svg?v=6"></picture></a>

<sub>Reviews (1): Last reviewed commit: ["Give messaging clear exact
subtree
seman..."](https://github.com/alishahryar1/free-claude-code/commit/0a3baecf9470da4bb866c864c1d1f01abd517085)
| [Re-trigger
Greptile](https://app.greptile.com/api/retrigger?id=43593126)</sub>

> Greptile also left **1 inline comment** on this PR.

<!-- /greptile_comment -->
2026-07-11 22:26:16 -07:00

188 行
6.5 KiB
Python

"""Focused tests for the tree package's private graph and queue values."""
import pytest
from free_claude_code.messaging.models import MessageScope
from free_claude_code.messaging.trees.graph import MessageTreeGraph
from free_claude_code.messaging.trees.node import MessageNode, MessageState
from free_claude_code.messaging.trees.queue import MessageNodeQueue
from free_claude_code.messaging.trees.snapshot import (
TreeSnapshot,
node_from_snapshot,
node_to_snapshot,
)
_SCOPE = MessageScope(platform="telegram", chat_id="chat")
def _root() -> MessageNode:
return MessageNode(
node_id="root",
scope=_SCOPE,
prompt="prompt root",
status_message_id="status-root",
)
def _add(
graph: MessageTreeGraph,
node_id: str,
status_message_id: str,
parent_id: str,
) -> MessageNode:
return graph.add_node(
node_id=node_id,
scope=_SCOPE,
prompt=f"prompt {node_id}",
status_message_id=status_message_id,
parent_id=parent_id,
parent_reference_id=parent_id,
)
def test_node_snapshot_round_trip_preserves_execution_state_only() -> None:
node = _root()
node.children_ids.extend(["child-a", "child-b"])
node.update_state(MessageState.ERROR)
node.update_state(MessageState.COMPLETED, session_id="session-root")
snapshot = node_to_snapshot(node)
restored = node_from_snapshot(snapshot, _SCOPE)
assert restored.node_id == "root"
assert restored.scope == _SCOPE
assert restored.prompt == ""
assert restored.status_message_id == "status-root"
assert restored.state is MessageState.COMPLETED
assert restored.session_id == "session-root"
assert restored.parent_reference_id is None
assert restored.children_ids == []
assert "children_ids" not in snapshot
assert "created_at" not in snapshot
assert "completed_at" not in snapshot
assert "error_message" not in snapshot
def test_graph_snapshot_round_trip_preserves_links_and_status_lookup() -> None:
graph = MessageTreeGraph(_root())
child = _add(graph, "child", "status-child", "root")
_add(graph, "grandchild", "status-grandchild", "child")
child.update_state(MessageState.COMPLETED, session_id="session-child")
restored = MessageTreeGraph.from_snapshot(graph.snapshot())
parent = restored.get_parent("grandchild")
status_child = restored.find_node_by_status_message("status-child")
assert restored.root_id == "root"
assert parent is not None
assert parent.node_id == "child"
assert restored.get_parent_session_id("grandchild") == "session-child"
assert status_child is not None
assert status_child.node_id == "child"
assert restored.get_descendants("root") == ["root", "child", "grandchild"]
def test_graph_restore_normalizes_numeric_ids_to_string_references() -> None:
graph = MessageTreeGraph(_root())
_add(graph, "child", "status-child", "root")
snapshot = graph.snapshot()
snapshot.nodes["child"]["node_id"] = 2
snapshot.nodes["child"]["status_message_id"] = 123
snapshot.nodes["child"]["parent_id"] = "root"
snapshot.nodes["2"] = snapshot.nodes.pop("child")
restored = MessageTreeGraph.from_snapshot(snapshot)
child = restored.find_node_by_status_message("123")
assert child is not None and child.node_id == "2"
def test_graph_restore_normalizes_legacy_parent_to_prompt_reference() -> None:
graph = MessageTreeGraph(_root())
_add(graph, "child", "status-child", "root")
snapshot = graph.snapshot()
snapshot.nodes["child"].pop("parent_reference_id")
restored = MessageTreeGraph.from_snapshot(snapshot)
child = restored.get_node("child")
assert child is not None
assert child.parent_reference_id == "root"
assert restored.snapshot().nodes["child"]["parent_reference_id"] == "root"
def test_cleared_status_round_trip_preserves_prompt_anchor() -> None:
graph = MessageTreeGraph(_root())
graph.clear_status("root")
restored = MessageTreeGraph.from_snapshot(graph.snapshot())
root = restored.get_root()
assert root.status_message_id is None
assert root.state is MessageState.ERROR
assert restored.resolve_reference("root") is not None
assert restored.resolve_reference("status-root") is None
def test_snapshot_rejects_runnable_node_without_status() -> None:
snapshot = MessageTreeGraph(_root()).snapshot()
snapshot.nodes["root"]["status_message_id"] = None
with pytest.raises(ValueError, match="requires a status"):
MessageTreeGraph.from_snapshot(snapshot)
def test_graph_rejects_duplicate_node_and_status_identity() -> None:
graph = MessageTreeGraph(_root())
_add(graph, "child", "status-child", "root")
with pytest.raises(ValueError, match="already exists"):
_add(graph, "child", "status-other", "root")
with pytest.raises(ValueError, match="already exists"):
_add(graph, "other", "status-child", "root")
with pytest.raises(ValueError, match="must be distinct"):
_add(graph, "same", "same", "root")
def test_graph_reference_subtree_can_remove_exact_nodes_and_status_lookups() -> None:
graph = MessageTreeGraph(_root())
_add(graph, "branch", "status-branch", "root")
_add(graph, "leaf", "status-leaf", "branch")
_add(graph, "sibling", "status-sibling", "root")
references = graph.get_reference_descendants("branch")
graph.remove_nodes(
{reference for reference in references if not reference.startswith("status-")}
)
assert graph.get_node("branch") is None
assert graph.get_node("leaf") is None
assert graph.find_node_by_status_message("status-branch") is None
assert graph.find_node_by_status_message("status-leaf") is None
assert graph.get_descendants("root") == ["root", "sibling"]
def test_tree_snapshot_rejects_invalid_wire_shapes() -> None:
assert TreeSnapshot.from_json(None) is None
assert TreeSnapshot.from_json({"root_id": "root", "nodes": []}) is None
assert TreeSnapshot.from_json({"nodes": {}}) is None
def test_node_queue_is_unique_fifo_and_supports_atomic_removal() -> None:
queue = MessageNodeQueue()
assert queue.put("a") is True
assert queue.put("b") is True
assert queue.put("a") is False
assert queue.items() == ("a", "b")
assert queue.remove("a") is True
assert queue.remove("a") is False
assert queue.items() == ("b",)
assert queue.pop() == "b"
assert queue.pop() is None
assert queue.put("c") is True
assert queue.put("d") is True
assert queue.drain() == ("c", "d")
assert queue.items() == ()