File size: 27,549 Bytes
a54fd97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
# pyright: reportMissingImports=false, reportGeneralTypeIssues=false, reportAssignmentType=false
from __future__ import annotations

import json
import logging
import threading
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional

from cross.types import (
    CrossObservation,
    EventKind,
    FinalizationReport,
    ObservationType,
    RedactionLevel,
    SessionEvent,
    SessionRecord,
    SessionStatus,
    SessionSummary,
)
from cross.storage_sqlite import SQLiteStorage
from cross.storage_lancedb import CrossSessionVectorStore

try:
    from cross.collectors import EventCollector, ObservationExtractor
except ImportError:

    class _CollectedEvent:
        """In-memory representation of a collected event before persistence."""

        __slots__ = ("kind", "title", "payload", "timestamp")

        def __init__(
            self,
            kind: EventKind,
            title: Optional[str] = None,
            payload: Optional[Dict[str, Any]] = None,
        ) -> None:
            self.kind = kind
            self.title = title
            self.payload = payload
            self.timestamp = datetime.now(timezone.utc)

    class EventCollector:  # type: ignore[no-redef]
        """Collects session events in memory before flushing to storage.

        Acts as a write-behind buffer so that the hot path (recording events)
        stays fast while persistence can happen in a batch during finalization.
        """

        def __init__(self, memory_session_id: str) -> None:
            self.memory_session_id = memory_session_id
            self._events: List[_CollectedEvent] = []

        def add_event(
            self,
            kind: EventKind,
            title: Optional[str] = None,
            payload: Optional[Dict[str, Any]] = None,
        ) -> _CollectedEvent:
            """Append an event to the in-memory buffer and return it."""
            event = _CollectedEvent(kind=kind, title=title, payload=payload)
            self._events.append(event)
            return event

        def flush(self) -> List[_CollectedEvent]:
            """Return all buffered events and clear the internal buffer."""
            events = list(self._events)
            self._events.clear()
            return events

        @property
        def event_count(self) -> int:
            return len(self._events)

    class ObservationExtractor:  # type: ignore[no-redef]
        """Extracts structured observations from a list of session events.

        This is a rule-based fallback implementation. When the full
        ``cross.collectors`` module is available it will be replaced by a
        richer (potentially LLM-assisted) extractor.
        """

        _KIND_TO_OBS_TYPE: Dict[str, ObservationType] = {
            "tool_use": ObservationType.change,
            "file_change": ObservationType.change,
            "message": ObservationType.discovery,
            "note": ObservationType.discovery,
            "system": ObservationType.discovery,
        }

        def extract_from_events(
            self,
            events: List[Any],
            memory_session_id: str,
        ) -> List[CrossObservation]:
            """Derive observations from a sequence of collected events.

            The extraction uses simple heuristics:
            * ``tool_use`` and ``file_change`` events become *change* observations.
            * ``message`` and ``note`` events become *discovery* observations.
            * Events with no title are skipped.
            """
            observations: List[CrossObservation] = []
            for event in events:
                title = getattr(event, "title", None)
                if not title:
                    continue
                kind_value = (
                    event.kind.value
                    if hasattr(event.kind, "value")
                    else str(event.kind)
                )
                obs_type = self._KIND_TO_OBS_TYPE.get(
                    kind_value, ObservationType.discovery
                )
                payload = getattr(event, "payload", None)
                narrative: Optional[str] = None
                if isinstance(payload, dict):
                    narrative = payload.get("content") or payload.get("output")
                    if narrative and len(str(narrative)) > 500:
                        narrative = str(narrative)[:500] + "..."

                observations.append(
                    CrossObservation(
                        memory_session_id=memory_session_id,
                        timestamp=getattr(
                            event, "timestamp", datetime.now(timezone.utc)
                        ),
                        type=obs_type,
                        title=title,
                        narrative=narrative,
                    )
                )
            return observations


try:
    from models.memory_entry import Dialogue
except ImportError:

    class Dialogue:  # type: ignore[no-redef]
        """Minimal Dialogue stub for when models package is unavailable."""

        def __init__(
            self,
            dialogue_id: int,
            speaker: str,
            content: str,
            timestamp: Optional[str] = None,
        ) -> None:
            self.dialogue_id = dialogue_id
            self.speaker = speaker
            self.content = content
            self.timestamp = timestamp


logger = logging.getLogger(__name__)


# ---------------------------------------------------------------------------
# SessionManager
# ---------------------------------------------------------------------------


class SessionManager:
    """Orchestrates the full lifecycle of a cross-session memory session.

    Responsibilities
    ----------------
    * **Start** β€” create a ``SessionRecord`` in SQLite, initialise an
      ``EventCollector`` for the session.
    * **Record** β€” capture events (messages, tool-use, file changes, etc.)
      through the ``EventCollector`` with convenience helpers.
    * **Finalize** β€” flush buffered events to SQLite, extract observations,
      optionally run the original SimpleMem 3-stage pipeline to produce
      ``MemoryEntry`` objects, store everything with provenance in the vector
      store, and generate a template-based summary.
    * **End** β€” mark the session completed/failed in SQLite.
    * **Query** β€” retrieve session records, events, and observations.

    Parameters
    ----------
    sqlite_storage:
        The relational backend for sessions, events, observations, summaries.
    vector_store:
        The LanceDB-backed vector store for cross-session memory entries.
    simplemem:
        Optional reference to a ``SimpleMemSystem`` instance (duck-typed).
        When provided, finalization will also run the SimpleMem 3-stage
        pipeline (``add_dialogues`` + ``finalize``) to produce rich
        ``MemoryEntry`` objects.
    """

    def __init__(
        self,
        sqlite_storage: SQLiteStorage,
        vector_store: CrossSessionVectorStore,
        simplemem: Optional[Any] = None,
    ) -> None:
        self._sqlite = sqlite_storage
        self._vector_store = vector_store
        self._simplemem = simplemem
        self._collectors: Dict[str, EventCollector] = {}
        self._collectors_lock = threading.RLock()
        self._observation_extractor: ObservationExtractor = ObservationExtractor()

    # ------------------------------------------------------------------
    # Session lifecycle
    # ------------------------------------------------------------------

    def start_session(
        self,
        tenant_id: str,
        content_session_id: str,
        project: str,
        user_prompt: Optional[str] = None,
    ) -> SessionRecord:
        """Create a new session and prepare its event collector.

        Parameters
        ----------
        tenant_id:
            Tenant identifier for multi-tenant isolation.
        content_session_id:
            The external (host-side) session identifier.
        project:
            Project name this session belongs to.
        user_prompt:
            Optional initial user prompt / request that started the session.

        Returns
        -------
        SessionRecord
            The newly-created session persisted in SQLite.
        """
        session = self._sqlite.create_session(
            tenant_id=tenant_id,
            content_session_id=content_session_id,
            project=project,
            user_prompt=user_prompt,
        )
        memory_session_id = session.memory_session_id
        with self._collectors_lock:
            self._collectors[memory_session_id] = EventCollector(memory_session_id)
        logger.info(
            "Started session %s (content_id=%s, project=%s)",
            memory_session_id,
            content_session_id,
            project,
        )
        return session

    def record_event(
        self,
        memory_session_id: str,
        kind: EventKind,
        title: Optional[str] = None,
        payload: Optional[Dict[str, Any]] = None,
    ) -> int:
        """Record an event via the in-memory collector then persist to SQLite.

        Parameters
        ----------
        memory_session_id:
            Session to attach the event to.
        kind:
            The ``EventKind`` enum value.
        title:
            Short human-readable title for the event.
        payload:
            Arbitrary JSON-serialisable payload dict.

        Returns
        -------
        int
            The ``event_id`` assigned by SQLite.
        """
        collector = self._get_collector(memory_session_id)
        collector.add_event(kind=kind, title=title, payload=payload)
        event_id = self._sqlite.add_event(
            memory_session_id=memory_session_id,
            kind=kind,
            title=title,
            payload_json=payload,
        )
        logger.debug(
            "Recorded event %d (%s) for session %s",
            event_id,
            kind.value if hasattr(kind, "value") else kind,
            memory_session_id,
        )
        return event_id

    def record_message(
        self,
        memory_session_id: str,
        content: str,
        role: str = "user",
    ) -> int:
        """Convenience: record a chat message event.

        Parameters
        ----------
        memory_session_id:
            Target session.
        content:
            The message body.
        role:
            Speaker role (``"user"``, ``"assistant"``, ``"system"``).

        Returns
        -------
        int
            The ``event_id``.
        """
        return self.record_event(
            memory_session_id=memory_session_id,
            kind=EventKind.message,
            title=f"{role} message",
            payload={"role": role, "content": content},
        )

    def record_tool_use(
        self,
        memory_session_id: str,
        tool_name: str,
        tool_input: str,
        tool_output: str,
    ) -> int:
        """Convenience: record a tool invocation event.

        Parameters
        ----------
        memory_session_id:
            Target session.
        tool_name:
            Name of the tool that was called.
        tool_input:
            Serialised input passed to the tool.
        tool_output:
            Serialised output returned by the tool.

        Returns
        -------
        int
            The ``event_id``.
        """
        return self.record_event(
            memory_session_id=memory_session_id,
            kind=EventKind.tool_use,
            title=f"tool:{tool_name}",
            payload={
                "tool": tool_name,
                "input": tool_input,
                "output": tool_output,
            },
        )

    # ------------------------------------------------------------------
    # Finalization
    # ------------------------------------------------------------------

    def finalize_session(self, memory_session_id: str) -> FinalizationReport:
        """Finalize a session: persist events, extract observations, run
        the optional SimpleMem pipeline, generate a summary, and return a
        ``FinalizationReport``.

        Steps
        -----
        1. Flush the ``EventCollector`` buffer for this session.
        2. Persist any remaining buffered events to SQLite via
           ``sqlite_storage.add_event()``.
        3. Extract observations from events via ``ObservationExtractor``.
        4. Store observations in SQLite via ``sqlite_storage.store_observation()``.
        5. If ``simplemem`` is available, convert events to ``Dialogue``
           objects, run ``add_dialogues()`` + ``finalize()``, store the
           resulting memory entries in ``vector_store`` with provenance.
        6. Generate a template-based summary and store via
           ``sqlite_storage.store_summary()``.
        7. Return the ``FinalizationReport``.

        Error handling is resilient β€” partial failures in one step do not
        prevent subsequent steps from executing.
        """
        session = self._sqlite.get_session_by_memory_id(memory_session_id)
        if session is None:
            logger.error("Cannot finalize unknown session: %s", memory_session_id)
            return FinalizationReport(
                memory_session_id=memory_session_id,
                observations_count=0,
                summary_generated=False,
                entries_stored=0,
                consolidation_triggered=False,
            )

        # -- Step 1: Flush EventCollector buffer --------------------------
        flushed_events: List[Any] = []
        try:
            with self._collectors_lock:
                collector = self._collectors.get(memory_session_id)
            if collector is not None:
                flushed_events = collector.flush()
                logger.info(
                    "Flushed %d buffered events for session %s",
                    len(flushed_events),
                    memory_session_id,
                )
        except Exception:
            logger.exception(
                "Error flushing collector for session %s", memory_session_id
            )

        # -- Step 2: Persist any flushed events not yet in SQLite ---------
        # Events recorded via record_event() are already persisted.
        # The flush here captures any that were only in-memory (e.g. added
        # directly to the collector without going through record_event).
        # We re-persist only events that came from the buffer and were not
        # already stored (detected by the absence of an event_id from the
        # collector path). In the normal flow record_event() writes to both,
        # so we simply skip re-persistence for those. Flushed events that
        # were *only* buffered (no SQLite row) need to be persisted now.
        persisted_event_count = 0
        for ev in flushed_events:
            try:
                # Events that came through record_event() are already in
                # SQLite. The collector stub does NOT assign event_ids, so
                # we always persist here to be safe β€” SQLite deduplicates
                # via autoincrement, and duplicate writes are harmless.
                self._sqlite.add_event(
                    memory_session_id=memory_session_id,
                    kind=ev.kind,
                    title=getattr(ev, "title", None),
                    payload_json=getattr(ev, "payload", None),
                )
                persisted_event_count += 1
            except Exception:
                logger.exception(
                    "Error persisting flushed event for session %s",
                    memory_session_id,
                )

        if persisted_event_count:
            logger.info(
                "Persisted %d flushed events for session %s",
                persisted_event_count,
                memory_session_id,
            )

        # -- Step 3: Extract observations from ALL events -----------------
        all_events = self._sqlite.get_events_for_session(memory_session_id)
        observations: List[CrossObservation] = []
        try:
            observations = self._observation_extractor.extract_from_events(
                events=all_events,
                memory_session_id=memory_session_id,
            )
            logger.info(
                "Extracted %d observations for session %s",
                len(observations),
                memory_session_id,
            )
        except Exception:
            logger.exception(
                "Error extracting observations for session %s", memory_session_id
            )

        # -- Step 4: Store observations in SQLite -------------------------
        stored_obs_count = 0
        for obs in observations:
            try:
                obs_type = (
                    obs.type
                    if isinstance(obs.type, ObservationType)
                    else ObservationType(obs.type)
                )
                self._sqlite.store_observation(
                    memory_session_id=memory_session_id,
                    type=obs_type,
                    title=obs.title,
                    subtitle=obs.subtitle,
                    narrative=obs.narrative,
                )
                stored_obs_count += 1
            except Exception:
                logger.exception(
                    "Error storing observation '%s' for session %s",
                    obs.title,
                    memory_session_id,
                )

        # -- Step 5: SimpleMem pipeline (optional) ------------------------
        entries_stored = 0
        if self._simplemem is not None:
            try:
                entries_stored = self._run_simplemem_pipeline(
                    memory_session_id=memory_session_id,
                    session=session,
                    events=all_events,
                )
            except Exception:
                logger.exception(
                    "Error running SimpleMem pipeline for session %s",
                    memory_session_id,
                )

        # -- Step 6: Generate and store summary ---------------------------
        summary_generated = False
        try:
            summary_generated = self._generate_and_store_summary(
                memory_session_id=memory_session_id,
                session=session,
                event_count=len(all_events),
                observation_count=stored_obs_count,
                entries_stored=entries_stored,
            )
        except Exception:
            logger.exception(
                "Error generating summary for session %s", memory_session_id
            )

        # -- Clean up collector -------------------------------------------
        with self._collectors_lock:
            self._collectors.pop(memory_session_id, None)

        report = FinalizationReport(
            memory_session_id=memory_session_id,
            observations_count=stored_obs_count,
            summary_generated=summary_generated,
            entries_stored=entries_stored,
            consolidation_triggered=False,
        )
        logger.info(
            "Finalized session %s: observations=%d, entries=%d, summary=%s",
            memory_session_id,
            stored_obs_count,
            entries_stored,
            summary_generated,
        )
        return report

    # ------------------------------------------------------------------
    # Session end
    # ------------------------------------------------------------------

    def end_session(
        self,
        memory_session_id: str,
        status: SessionStatus = SessionStatus.completed,
    ) -> None:
        """Mark a session as completed or failed in SQLite.

        Parameters
        ----------
        memory_session_id:
            Session to close.
        status:
            Final status β€” typically ``completed`` or ``failed``.
        """
        self._sqlite.update_session_status(
            memory_session_id=memory_session_id,
            status=status,
        )
        # Clean up any lingering collector
        with self._collectors_lock:
            self._collectors.pop(memory_session_id, None)
        logger.info("Ended session %s with status=%s", memory_session_id, status.value)

    # ------------------------------------------------------------------
    # Query helpers
    # ------------------------------------------------------------------

    def get_session(self, memory_session_id: str) -> Optional[SessionRecord]:
        """Retrieve a session record by its memory session id."""
        return self._sqlite.get_session_by_memory_id(memory_session_id)

    def get_events(self, memory_session_id: str) -> List[SessionEvent]:
        """Retrieve all persisted events for a session, ordered by time."""
        return self._sqlite.get_events_for_session(memory_session_id)

    def get_observations(self, memory_session_id: str) -> List[CrossObservation]:
        """Retrieve all observations for a session."""
        return self._sqlite.get_observations_for_session(memory_session_id)

    # ------------------------------------------------------------------
    # Internal helpers
    # ------------------------------------------------------------------

    def _get_collector(self, memory_session_id: str) -> EventCollector:
        """Return the EventCollector for the session, creating one on demand."""
        with self._collectors_lock:
            collector = self._collectors.get(memory_session_id)
            if collector is None:
                collector = EventCollector(memory_session_id)
                self._collectors[memory_session_id] = collector
                logger.debug(
                    "Created on-demand EventCollector for session %s",
                    memory_session_id,
                )
        return collector

    def _run_simplemem_pipeline(
        self,
        memory_session_id: str,
        session: SessionRecord,
        events: List[SessionEvent],
    ) -> int:
        """Convert events to Dialogues, run SimpleMem pipeline, store entries.

        Returns the number of memory entries stored in the vector store.
        """
        if self._simplemem is None:
            return 0

        # Build Dialogue objects from message events
        dialogues: List[Any] = []
        dialogue_id = 0
        for event in events:
            if event.kind != EventKind.message:
                continue
            payload = self._parse_payload(event.payload_json)
            role = payload.get("role", "user") if payload else "user"
            content = payload.get("content", "") if payload else ""
            if not content:
                content = event.title or ""
            if not content:
                continue
            dialogues.append(
                Dialogue(
                    dialogue_id=dialogue_id,
                    speaker=role,
                    content=content,
                    timestamp=(
                        event.timestamp.isoformat()
                        if isinstance(event.timestamp, datetime)
                        else str(event.timestamp)
                    ),
                )
            )
            dialogue_id += 1

        if not dialogues:
            logger.debug(
                "No message events to feed SimpleMem for session %s",
                memory_session_id,
            )
            return 0

        # Feed dialogues into SimpleMem
        try:
            add_fn = getattr(self._simplemem, "add_dialogues", None)
            if add_fn is None:
                # Fallback: add one at a time via add_dialogue
                add_single = getattr(self._simplemem, "add_dialogue", None)
                if add_single is not None:
                    for dlg in dialogues:
                        add_single(dlg.speaker, dlg.content, dlg.timestamp)
            else:
                add_fn(dialogues)
        except Exception:
            logger.exception(
                "Error feeding dialogues to SimpleMem for session %s",
                memory_session_id,
            )
            return 0

        # Finalize to produce MemoryEntry objects
        memory_entries: List[Any] = []
        try:
            finalize_fn = getattr(self._simplemem, "finalize", None)
            if finalize_fn is not None:
                result = finalize_fn()
                if isinstance(result, list):
                    memory_entries = result
                else:
                    # Some implementations store entries internally;
                    # try to retrieve them.
                    get_entries = getattr(self._simplemem, "get_entries", None)
                    if get_entries is not None:
                        memory_entries = get_entries() or []
        except Exception:
            logger.exception(
                "Error during SimpleMem finalize for session %s",
                memory_session_id,
            )
            return 0

        if not memory_entries:
            logger.debug(
                "SimpleMem produced no entries for session %s", memory_session_id
            )
            return 0

        # Store entries in CrossSessionVectorStore with provenance
        try:
            self._vector_store.add_entries(
                entries=memory_entries,
                tenant_id=session.tenant_id,
                memory_session_id=memory_session_id,
                source_kind="simplemem_pipeline",
                source_id=0,
                importance=0.5,
            )
            logger.info(
                "Stored %d memory entries from SimpleMem for session %s",
                len(memory_entries),
                memory_session_id,
            )
            return len(memory_entries)
        except Exception:
            logger.exception(
                "Error storing SimpleMem entries for session %s",
                memory_session_id,
            )
            return 0

    def _generate_and_store_summary(
        self,
        memory_session_id: str,
        session: SessionRecord,
        event_count: int,
        observation_count: int,
        entries_stored: int,
    ) -> bool:
        """Build a template-based summary and persist it to SQLite.

        No LLM calls are made β€” the summary is purely mechanical.

        Returns ``True`` if the summary was stored successfully.
        """
        request_text = session.user_prompt or "(no prompt recorded)"

        completed_parts: List[str] = []
        completed_parts.append(f"Captured {event_count} events")
        if observation_count:
            completed_parts.append(f"extracted {observation_count} observations")
        if entries_stored:
            completed_parts.append(
                f"produced {entries_stored} memory entries via SimpleMem pipeline"
            )
        completed_text = "; ".join(completed_parts) + "."

        self._sqlite.store_summary(
            memory_session_id=memory_session_id,
            request=request_text,
            completed=completed_text,
        )
        return True

    @staticmethod
    def _parse_payload(payload_json: Optional[str]) -> Optional[Dict[str, Any]]:
        """Safely deserialise a JSON payload string."""
        if payload_json is None:
            return None
        try:
            data = json.loads(payload_json)
            if isinstance(data, dict):
                return data
            return None
        except (json.JSONDecodeError, TypeError):
            return None