Ops bot: remember the last exchanges so follow-ups have context

Each message started a fresh claude -p with only the database snapshot, so
«да, поправь» had nothing to refer to. Keep the last 6 exchanges (2 h, in
memory, shared by Telegram and BroV) and put them into the prompt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
maksarsanjeev
2026-10-28 21:54:19 +03:00
parent 0f4e110512
commit 977665806f
2 changed files with 57 additions and 2 deletions
+36 -2
View File
@@ -5,6 +5,8 @@ import json
import os
import subprocess
import tempfile
import time
from collections import deque
from .core import Ops, OpsError, client_name, ru_day
@@ -45,6 +47,8 @@ INSTRUCTIONS = """Ты — помощник-менеджер системног
- После pay_sub добавляй repeat_sub, только если пользователь сам сказал, продлевать или нет
(«оплатил и продлеваем», «больше не нужна»); иначе в reply спроси, повторять ли.
- reply — 1–3 строки, без markdown-заголовков.
- Ниже может быть «Недавний разговор»: короткие ответы вроде «да», «поправь», «не надо»,
«перенеси на пятницу» относятся к нему. Не повторяй действия, которые там уже сделаны.
"""
ALLOWED = {"add_task", "update_task", "complete_task", "reopen_task", "start_timer", "stop_timer",
@@ -172,14 +176,44 @@ def _only(d: dict, *keys) -> dict:
return {k: d[k] for k in keys if k in d}
# Recent exchanges, shared by Telegram and BroV (one owner): each `claude -p` call starts
# from scratch, so without this «да, поправь» has nothing to refer to. Memory only — a
# restart forgets the conversation, not the data.
HISTORY_TURNS = 6
HISTORY_TTL = 2 * 3600
_history: deque = deque(maxlen=HISTORY_TURNS)
def history_text(now: float | None = None) -> str:
now = time.time() if now is None else now
recent = [h for h in _history if now - h[0] <= HISTORY_TTL]
if not recent:
return ""
lines = ["Недавний разговор (старое сверху):"]
for _, said, answered in recent:
lines.append("Пользователь: " + said[:500])
lines.append("Ты: " + answered[:700])
return "\n".join(lines)
def remember(said: str, answered: str, now: float | None = None):
_history.append((time.time() if now is None else now, said.strip(), answered.strip()))
def handle_text(ops: Ops, text: str, lock, claude_bin: str = "claude", model: str = "haiku",
paid: list | None = None) -> str:
"""One message in, one answer out (actions taken + Claude's reply). The database lock
is held only while reading the state and applying the actions, not while Claude thinks."""
with lock:
prompt = snapshot(ops) + "\n\nСообщение пользователя:\n" + text.strip()
prompt = snapshot(ops)
past = history_text()
if past:
prompt += "\n\n" + past
prompt += "\n\nСообщение пользователя:\n" + text.strip()
plan = parse_plan(ask_claude(prompt, claude_bin, model))
with lock:
lines = apply_plan(ops, plan, paid)
reply = str(plan.get("reply", "")).strip()
return "\n".join(([reply] if reply else []) + lines) or "Готово."
answer = "\n".join(([reply] if reply else []) + lines) or "Готово."
remember(text, answer)
return answer
+21
View File
@@ -174,5 +174,26 @@ class Company(unittest.TestCase):
os.remove(path)
class HistoryTest(unittest.TestCase):
def test_follow_up_sees_previous_exchange(self):
brain._history.clear()
o = Ops(connect(":memory:"))
seen = []
def fake(prompt, *a, **k):
seen.append(prompt)
return '{"actions":[],"reply":"Ок"}'
brain.ask_claude = fake
brain.handle_text(o, "задача посмотреть бегущий по лезвию 2033", threading.Lock())
brain.handle_text(o, "да, поправь", threading.Lock())
self.assertNotIn("Недавний разговор", seen[0])
self.assertIn("бегущий по лезвию 2033", seen[1])
self.assertLess(seen[1].index("Недавний разговор"), seen[1].index("да, поправь"))
def test_old_history_expires(self):
brain._history.clear()
brain.remember("старое", "ответ", now=0)
self.assertEqual(brain.history_text(now=brain.HISTORY_TTL + 1), "")
if __name__ == "__main__":
unittest.main()