feat(persistence): PostgreSQL assistant store, chat persist fixes, gateway scripts

- Add SQLAlchemy Core repos, pg adapter/compat, assistant_store factory, Alembic bootstrap and migration/cutover scripts.

- Harden chat_message writes (NUL scrub for PG), turn_uuid on attempt failure, WS turn_runner fallbacks and gateway executed_turn_uuid init.

- start_gateway: log paths, PS7 stderr handling via cmd, background stdout/stderr redirect; runtime assistant_runtime_log_dir export.

- Ops: clear_all_chat_sessions with PG-only --postgresql and env-gated wipe; clear_postgres_chat_sessions.ps1.

- Tests: SA repos, pg compat, persist fallback, smoke env isolation; CI and docs touch-ups.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
oliver 2026-05-14 09:33:50 +08:00
parent 2b32d11f43
commit d14e9d3596
103 changed files with 7574 additions and 1641 deletions

View file

@ -0,0 +1,46 @@
"""When the model run produced visible text but no ``chat_message`` row for this ``turn_uuid``."""
from __future__ import annotations
import logging
from typing import Any
_LOG = logging.getLogger(__name__)
def persist_assistant_text_if_turn_missing(
*,
store: Any,
session_id: str,
turn_uuid: str,
final_text: str,
log_prefix: str,
) -> bool:
"""Insert one ``assistant_text`` row if none exists for ``turn_uuid``. Return True if inserted."""
tu = str(turn_uuid or "").strip()
body = str(final_text or "").strip()
if not tu or not body:
return False
try:
rows = store.get_messages(session_id=str(session_id), limit=400)
if any(
str(getattr(m, "role", "") or "").lower() == "assistant"
and str(getattr(m, "turn_uuid", "") or "").strip() == tu
for m in (rows or [])
):
return False
store.add_message(
session_id=str(session_id),
role="assistant",
content=body,
turn_uuid=tu,
event_type="assistant_text",
)
_LOG.warning("%s session_id=%s turn_uuid=%s chars=%d", log_prefix, str(session_id), tu, len(body))
return True
except Exception:
_LOG.exception("%s_failed session_id=%s turn_uuid=%s", log_prefix, str(session_id), tu)
return False
__all__ = ["persist_assistant_text_if_turn_missing"]