aboutsummaryrefslogtreecommitdiff
path: root/mcp/senia/diary.py
blob: 1cd15f8ed3adabee1cc550a91c7815687724ae6b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""Diary log tool implementations.

Raw, granular, agent-authored entries. Compaction (not in this module) will
later distill these into daily/monthly markdown summaries; raw entries remain
in sqlite as the lossless archive.
"""

from datetime import datetime, timedelta, timezone
from db import get_conn


def _now() -> str:
    return datetime.now(timezone.utc).astimezone().isoformat(timespec="seconds")


def _row(r):
    return dict(r) if r else None


def log(content: str) -> dict:
    with get_conn() as conn:
        cur = conn.execute(
            "INSERT INTO diary_logs (ts, content) VALUES (?, ?)",
            (_now(), content),
        )
        return _row(conn.execute("SELECT * FROM diary_logs WHERE id=?", (cur.lastrowid,)).fetchone())


def today() -> list[dict]:
    now = datetime.now(timezone.utc).astimezone()
    start = now.replace(hour=0, minute=0, second=0, microsecond=0).isoformat()
    with get_conn() as conn:
        return [dict(r) for r in conn.execute(
            "SELECT * FROM diary_logs WHERE ts >= ? ORDER BY ts", (start,)
        ).fetchall()]


def recent(hours: int = 24) -> list[dict]:
    cutoff = (datetime.now(timezone.utc) - timedelta(hours=hours)).isoformat()
    with get_conn() as conn:
        return [dict(r) for r in conn.execute(
            "SELECT * FROM diary_logs WHERE ts >= ? ORDER BY ts DESC", (cutoff,)
        ).fetchall()]


def range_query(start_ts: str, end_ts: str) -> list[dict]:
    with get_conn() as conn:
        return [dict(r) for r in conn.execute(
            "SELECT * FROM diary_logs WHERE ts >= ? AND ts < ? ORDER BY ts",
            (start_ts, end_ts),
        ).fetchall()]