An always-on second brain you talk to. Voice notes in Telegram → typed, linked knowledge in your Obsidian vault. Runs 24/7 on the Claude subscription you already have.
Python ai-agentsai-automationclaudeclaude-codeebbinghausknowledge-graphllmmemory-systemobsidianpersonal-assistantpkmproductivitypythonsecond-braintelegram-botvoice-assistant
feat(session): add tmux pane output parser
smixsff5ab325d186
diff --git a/src/d_brain/services/tmux_parse.py b/src/d_brain/services/tmux_parse.pynew file mode 100644index 0000000..0e70dbf--- /dev/null+++ b/src/d_brain/services/tmux_parse.py@@ -0,0 +1,136 @@+"""Pure parsing of `tmux capture-pane -p` output from an interactive+Claude Code session. No subprocess/tmux access — text in, value out.++Kept separate from claude_session.py so the fragile parsing logic is+fully unit-testable against real capture fixtures.++Design invariants (from live spikes + adversarial review):+* The model's answer markers are LINE-ANCHORED (each on its own line).+ The input echo shows the markers INLINE (mid-sentence), and the model+ quoting the marker syntax also appears inline. So matching only+ line-anchored markers distinguishes the real answer from the echo and+ from inline self-references — no fragile occurrence-counting needed.+* State signatures are matched only against the CHROME region (the bottom+ of the pane: footer/banner/idle line), never the whole transcript, so a+ reply that *mentions* "usage limit" or "/login" cannot be misclassified.++The rate-limit / logged-out signatures are not yet confirmed against a+live session and may need adjustment per CLI version (see tests, open Q #2).+"""++import re+from enum import Enum++# How many trailing lines count as "chrome" (footer/banner/idle region).+# State signatures are matched only here, not against the transcript body.+_CHROME_LINES = 18+++class PaneState(str, Enum):+ """Coarse state of the interactive session, read from the pane text."""++ TRUST_PROMPT = "trust_prompt" # "Is this a project you trust?" — needs Enter+ STARTING = "starting" # welcome box visible, not yet idle+ READY = "ready" # idle prompt / bypass-permissions footer+ RATE_LIMITED = "rate_limited" # usage limit hit — do NOT kill, wait for reset+ LOGGED_OUT = "logged_out" # auth lost — needs re-login+ UNKNOWN = "unknown"+++def _require_rid(rid: str) -> None:+ if not rid:+ raise ValueError("rid must be a non-empty string")+++def _line_anchored(rid: str, kind: str) -> re.Pattern[str]:+ # Own line, tolerating leading/trailing whitespace and a trailing CR.+ return re.compile(rf"(?m)^[ \t]*<<<{kind}:{re.escape(rid)}>>>[ \t]*\r?$")+++def extract_reply(text: str, rid: str) -> str | None:+ """Return the text of the last well-formed, line-anchored+ ``<<<R:rid>>> .. <<<E:rid>>>`` pair, stripped, or ``None``.++ Only line-anchored markers are considered (the input echo and inline+ self-references are mid-line and thus ignored). The chosen span must not+ contain another line-anchored marker of either kind, so a stray end+ marker cannot make the span swallow chrome.+ """+ _require_rid(rid)+ opens = list(_line_anchored(rid, "R").finditer(text))+ ends = list(_line_anchored(rid, "E").finditer(text))+ if not opens or not ends:+ return None++ # Walk end markers from last to first; pair each with the nearest+ # preceding open marker and accept the first span with no inner marker.+ open_starts = [m.start() for m in opens]+ for end_m in reversed(ends):+ end_pos = end_m.start()+ preceding = [s for s in open_starts if s < end_pos]+ if not preceding:+ continue+ start_m = next(m for m in opens if m.start() == preceding[-1])+ inner = text[start_m.end() : end_pos]+ # Reject if another line-anchored marker hides inside the span.+ if _line_anchored(rid, "E").search(inner) or _line_anchored(rid, "R").search(+ inner+ ):+ continue+ return inner.strip()+ return None+++def is_complete(text: str, rid: str) -> bool:+ """True iff a complete line-anchored answer pair is present.++ Replaces the fragile "count >= 2" heuristic: because the echo is inline,+ a single line-anchored pair already means the model's answer is done.+ """+ _require_rid(rid)+ return extract_reply(text, rid) is not None+++# Signature tables. Order of checks in classify_state encodes priority.+# TRUST anchors on the numbered menu (structural), not the prose sentence,+# so the model describing the trust prompt cannot trigger it.+_TRUST_MENU_RE = re.compile(r"(?m)^\s*(?:❯\s*)?1\.\s+Yes, I trust this folder")+_RATE_RE = re.compile(+ r"usage limit|rate limit|limit reached|resets at|5-hour limit|weekly limit",+ re.I,+)+_LOGGED_OUT_RE = re.compile(+ r"invalid api key|please run /login|logged out|please log ?in|"+ r"authentication (failed|required|expired)|session expired",+ re.I,+)+# READY: idle prompt (allow ghost suggestions after ❯) or the bypass footer.+_READY_RE = re.compile(r"(?m)^\s*❯|bypass permissions on")+_STARTING_RE = re.compile(r"Claude Code v\d", re.I)+++def _chrome(text: str) -> str:+ return "\n".join(text.splitlines()[-_CHROME_LINES:])+++def classify_state(text: str) -> PaneState:+ """Classify the pane into a coarse state.++ State signatures are matched against the chrome region only; STARTING is+ matched against the whole text (its banner can sit above the fold during+ boot). Priority: TRUST > RATE_LIMITED > LOGGED_OUT > READY > STARTING.+ """+ if not text.strip():+ return PaneState.UNKNOWN+ chrome = _chrome(text)+ if _TRUST_MENU_RE.search(chrome):+ return PaneState.TRUST_PROMPT+ if _RATE_RE.search(chrome):+ return PaneState.RATE_LIMITED+ if _LOGGED_OUT_RE.search(chrome):+ return PaneState.LOGGED_OUT+ if _READY_RE.search(chrome):+ return PaneState.READY+ if _STARTING_RE.search(text):+ return PaneState.STARTING+ return PaneState.UNKNOWNdiff --git a/tests/test_tmux_parse.py b/tests/test_tmux_parse.pynew file mode 100644index 0000000..2d2681d--- /dev/null+++ b/tests/test_tmux_parse.py@@ -0,0 +1,259 @@+"""Tests for tmux pane output parsing (pure functions).++Fixtures are real capture-pane excerpts from live spikes against+Claude Code 2.1.168. These functions must NOT touch tmux/subprocess —+they only parse text, so they are fully unit-testable.++Key invariant (from blind review + spikes): the model's answer markers are+LINE-ANCHORED (on their own line); the input echo shows the markers inline+(mid-sentence). So line-anchored matching alone distinguishes answer from+echo and from the model quoting the marker syntax inside its reply.+"""++import pytest++from d_brain.services.tmux_parse import (+ PaneState,+ classify_state,+ extract_reply,+ is_complete,+)++# ── Real capture excerpts (claude 2.1.168) ──────────────────────────────++READY_CAPTURE = """\+╭─── Claude Code v2.1.168 ──────────────────────────────────────╮+│ Welcome back Majento! │+╰───────────────────────────────────────────────────────────────╯+────────────────────────────────────────────────────────────────+❯+────────────────────────────────────────────────────────────────+ hello | Opus 4.8 (1M context) | ~/T/dbrain_spk+ ⏵⏵ bypass permissions on (shift+tab to cycle) · ← for agents+"""++# READY but in a normal permission mode (no "bypass permissions" footer);+# only the idle ❯ with a ghost suggestion is present. Exercises the ❯ branch.+READY_NO_BYPASS_CAPTURE = """\+────────────────────────────────────────────────────────────────+❯ Try "fix the failing test"+────────────────────────────────────────────────────────────────+ hello | Opus 4.8 (1M context) | ~/project+"""++TRUST_CAPTURE = """\+ Accessing workspace:+ /private/tmp+ Quick safety check: Is this a project you created or one you trust?+ Claude Code'll be able to read, edit, and execute files here.+ ❯ 1. Yes, I trust this folder+ 2. No, exit+ Enter to confirm · Esc to cancel+"""++STARTING_CAPTURE = """\+╭─── Claude Code v2.1.168 ──────────────────────────────────────╮+│ Loading... │+╰───────────────────────────────────────────────────────────────╯+"""++# NOTE: rate-limit / logged-out strings NOT yet observed live — synthetic,+# based on known Claude Code wording. Must be verified on the VPS (open Q #2).+RATE_LIMIT_CAPTURE = """\+ You've reached your usage limit. Your limit resets at 3:00 PM.+❯+ ⏵⏵ bypass permissions on (shift+tab to cycle)+"""++LOGGED_OUT_CAPTURE = """\+ Invalid API key · Please run /login to authenticate.+❯+"""+++# ── extract_reply ───────────────────────────────────────────────────────+++def test_extract_reply_takes_line_anchored_pair_not_inline_echo():+ """Input echo has markers inline (mid-line); the answer has them on+ their own lines. Only the line-anchored pair is the real reply."""+ rid = "911e06a2"+ text = (+ f"> Reply PONG, put <<<R:{rid}>>> before and <<<E:{rid}>>> after\n" # echo+ " ... transcript ...\n"+ f"<<<R:{rid}>>>\n"+ "PONG\n"+ f"<<<E:{rid}>>>\n"+ "❯\n"+ )+ assert extract_reply(text, rid) == "PONG"+++def test_extract_reply_multiline_answer():+ rid = "abc12345"+ text = f"<<<R:{rid}>>>\nline one\nline two\n<<<E:{rid}>>>\n"+ assert extract_reply(text, rid) == "line one\nline two"+++def test_extract_reply_marker_quoted_inline_inside_answer():+ """CRITICAL (blind review): the model quotes the marker syntax inside+ its answer (inline). The inline quote must be ignored; the real+ line-anchored pair still yields the full answer."""+ rid = "deadbeef"+ text = (+ f"<<<R:{rid}>>>\n"+ f"To finish I print <<<E:{rid}>>> on its own line.\n" # inline quote+ "Here is the real answer.\n"+ f"<<<E:{rid}>>>\n"+ "❯\n"+ )+ got = extract_reply(text, rid)+ assert got is not None+ assert "Here is the real answer." in got+ assert got.startswith("To finish I print")+++def test_extract_reply_stray_end_marker_does_not_corrupt():+ """HIGH (blind review): a stray line-anchored end marker after a complete+ pair must not produce a span that swallows the real end marker + chrome."""+ rid = "cafe1234"+ text = (+ f"<<<R:{rid}>>>\n"+ "PONG\n"+ f"<<<E:{rid}>>>\n"+ "❯\n"+ f"<<<E:{rid}>>>\n" # stray, no preceding R+ )+ got = extract_reply(text, rid)+ assert got == "PONG"+++def test_extract_reply_none_when_no_markers():+ assert extract_reply("just some text\n❯\n", "deadbeef") is None+++def test_extract_reply_none_when_only_open_marker():+ rid = "feedface"+ assert extract_reply(f"<<<R:{rid}>>>\nPONG (still typing)", rid) is None+++def test_extract_reply_ignores_other_rid():+ text = "<<<R:aaaa1111>>>\nPONG\n<<<E:aaaa1111>>>\n"+ assert extract_reply(text, "bbbb2222") is None+++def test_extract_reply_empty_rid_raises():+ with pytest.raises(ValueError):+ extract_reply("anything", "")+++# ── is_complete ─────────────────────────────────────────────────────────+++def test_is_complete_true_on_line_anchored_pair():+ rid = "11112222"+ assert is_complete(f"<<<R:{rid}>>>\nPONG\n<<<E:{rid}>>>\n", rid) is True+++def test_is_complete_false_on_inline_echo_only():+ """The echo of the typed prompt (inline markers) is NOT a complete reply."""+ rid = "33334444"+ text = f"> do thing, wrap in <<<R:{rid}>>> .. <<<E:{rid}>>>\n❯\n"+ assert is_complete(text, rid) is False+++def test_is_complete_false_when_answer_still_streaming():+ rid = "55556666"+ assert is_complete(f"<<<R:{rid}>>>\npartial...", rid) is False+++# ── classify_state ──────────────────────────────────────────────────────+++def test_classify_trust_prompt():+ assert classify_state(TRUST_CAPTURE) == PaneState.TRUST_PROMPT+++def test_classify_ready_with_bypass_footer():+ assert classify_state(READY_CAPTURE) == PaneState.READY+++def test_classify_ready_without_bypass_footer():+ """READY must be detected via the idle ❯ alone (bypass footer is+ permission-mode specific and may be absent)."""+ assert classify_state(READY_NO_BYPASS_CAPTURE) == PaneState.READY+++def test_classify_starting():+ assert classify_state(STARTING_CAPTURE) == PaneState.STARTING+++def test_classify_rate_limited():+ assert classify_state(RATE_LIMIT_CAPTURE) == PaneState.RATE_LIMITED+++def test_classify_logged_out():+ assert classify_state(LOGGED_OUT_CAPTURE) == PaneState.LOGGED_OUT+++def test_classify_unknown_on_empty():+ assert classify_state("") == PaneState.UNKNOWN+++def test_rate_limit_takes_priority_over_ready_idle():+ """A rate-limit banner co-existing with idle must classify as+ RATE_LIMITED so the watchdog does NOT treat it as healthy."""+ assert classify_state(RATE_LIMIT_CAPTURE) == PaneState.RATE_LIMITED+++# ── classify_state false positives (transcript body mentions triggers) ───+++def _long_transcript(mention: str) -> str:+ """A long transcript whose BODY mentions a trigger word, but whose+ chrome region (bottom) is a healthy idle pane."""+ body = f"❯ explain something\nThe model says: {mention}\n" + "filler line\n" * 25+ footer = (+ "────────────────────────────────────────────\n"+ "❯\n"+ "────────────────────────────────────────────\n"+ " hello | Opus 4.8 (1M context) | ~/project\n"+ " ⏵⏵ bypass permissions on (shift+tab to cycle)\n"+ )+ return body + footer+++def test_classify_no_false_positive_rate_limit_in_body():+ assert (+ classify_state(_long_transcript("you will hit your usage limit soon"))+ == PaneState.READY+ )+++def test_classify_no_false_positive_login_in_body():+ assert (+ classify_state(_long_transcript("just run /login to authenticate"))+ == PaneState.READY+ )+++def test_classify_no_false_positive_trust_in_body():+ assert (+ classify_state(+ _long_transcript("Is this a project you trust? appears on first run")+ )+ == PaneState.READY+ )+++def test_classify_priority_stack_trust_first():+ """When several signatures co-occur in the chrome, TRUST wins (it must be+ answered before anything else is meaningful)."""+ stacked = (+ " Is this a project you created or one you trust?\n"+ " ❯ 1. Yes, I trust this folder\n"+ " 2. No, exit\n"+ " usage limit resets at 3:00 PM\n"+ " ❯\n"+ )+ assert classify_state(stacked) == PaneState.TRUST_PROMPT