@@ -410,21 +410,127 @@ def auto_clean_zombies() -> None:
410410 )
411411
412412
413+ def record_harness_export_check (state : dict ) -> None :
414+ """Record whether pi exported this session to the sessions database.
415+
416+ pi exports its own transcript from a ``session_shutdown`` extension
417+ (``agents/pi/extensions/studyloop-session-export.ts`` runs
418+ ``session-export --pi-only``), and pi 1.1.0 awaits that handler before its
419+ process exits -- so when the tmux wrapper runs :func:`cleanup_on_exit` the
420+ export has either landed or failed, and this is the one moment StudyLoop
421+ can tell which (review 2026-10-21, lane O's design for F#5 / plan-5 D).
422+
423+ No-op unless ``state["agent"] == "pi"``. The database is opened read-only
424+ (``mode=ro``): a missing file, a database without a ``sessions`` table or
425+ any other read failure is a ``missing`` verdict, never an exception -- the
426+ caller is about to tear the session down and must not be stopped. A row
427+ counts when ``source='pi'``, its ``project_path`` resolves to the same
428+ directory as the session's ``session_dir`` (node's ``process.cwd()`` is the
429+ physical path; the sessions dir may be a symlink) and its ``updated_at`` --
430+ the last message's stamp, in ``Z`` -- is not before this session's
431+ ``started_at`` (a row for the same directory from an earlier run is last
432+ time's export). An empty session the exporter wrote no row for reads as
433+ ``missing`` too; the line the dashboard shows is advice, not an error.
434+
435+ Writes ``export_check`` into the session state, which survives the tmux
436+ kill and is what the dashboard's ended view reads.
437+ """
438+ if state .get ("agent" ) != "pi" :
439+ return
440+ import contextlib
441+ from datetime import UTC , datetime
442+
443+ from studyloop .session_state import write_session_state
444+
445+ status = "ok" if _pi_export_row_exists (state ) else "missing"
446+ with contextlib .suppress (Exception ):
447+ write_session_state (
448+ {
449+ "export_check" : {
450+ "harness" : "pi" ,
451+ "status" : status ,
452+ "checked_at" : datetime .now (UTC ).isoformat (),
453+ }
454+ }
455+ )
456+
457+
458+ def _pi_export_row_exists (state : dict ) -> bool :
459+ """Whether the sessions database holds pi's export of this session. Never raises."""
460+ import sqlite3
461+ from datetime import UTC , datetime
462+ from pathlib import Path
463+
464+ from studyloop .settings import get_db_path
465+
466+ def _utc (stamp : str ) -> datetime :
467+ # Both writers stamp UTC: StudyLoop as ``+00:00``, pi (node's
468+ # ``toISOString``) as ``Z``. A naive stamp is read as UTC too.
469+ parsed = datetime .fromisoformat (stamp )
470+ return parsed .astimezone (UTC ) if parsed .tzinfo else parsed .replace (tzinfo = UTC )
471+
472+ session_dir = state .get ("session_dir" )
473+ started_at = state .get ("started_at" )
474+ if not session_dir or not isinstance (started_at , str ):
475+ return False
476+ try :
477+ started = _utc (started_at )
478+ wanted = Path (session_dir ).resolve ()
479+ except (ValueError , OSError ):
480+ return False
481+
482+ # The SQL bound is a conservative prefix -- ``started_at`` in UTC to the
483+ # second, no offset -- which compares correctly as text against both
484+ # ``...Z`` and ``...+00:00`` stamps. The exact comparison is Python's.
485+ lower_bound = started .strftime ("%Y-%m-%dT%H:%M:%S" )
486+ try :
487+ conn = sqlite3 .connect (f"file:{ get_db_path ()} ?mode=ro" , uri = True )
488+ except sqlite3 .Error :
489+ return False
490+ try :
491+ rows = conn .execute (
492+ "SELECT project_path, updated_at FROM sessions "
493+ "WHERE source = 'pi' AND updated_at IS NOT NULL AND updated_at >= ?" ,
494+ (lower_bound ,),
495+ ).fetchall ()
496+ except sqlite3 .Error :
497+ return False
498+ finally :
499+ conn .close ()
500+
501+ for project_path , updated_at in rows :
502+ if not project_path or not isinstance (updated_at , str ):
503+ continue
504+ try :
505+ if Path (project_path ).resolve () == wanted and _utc (updated_at ) >= started :
506+ return True
507+ except (ValueError , OSError ):
508+ continue
509+ return False
510+
511+
413512def cleanup_on_exit () -> None :
414513 """Auto-cleanup when the agent process exits.
415514
416515 Called by the wrapper shell command in the main tmux pane. This runs
417516 inside the tmux session, so tmux will SIGHUP us when sessions are
418- killed -- all operations are wrapped in contextlib.suppress via
419- end_session_common().
517+ killed -- all operations are wrapped in contextlib.suppress.
518+
519+ Order matters: :func:`teardown_session` kills this pane's own tmux
520+ session, so anything after it never executes. The session is saved first,
521+ then the harness export check is recorded, then the teardown runs.
420522 """
421523 import contextlib
422524
423525 from studyloop .session_state import read_session_state
424526
425527 with contextlib .suppress (Exception ):
426528 state = read_session_state ()
529+ if not state .get ("study_session_id" ):
530+ return
427531 # Best effort, as before: the agent has already exited and nothing is
428532 # left to retry the end, so a failed DB write must not leave the tmux
429533 # session and IPC files behind.
430- end_session_common (state , raise_if_not_persisted = False )
534+ persist_session_end (state , raise_if_not_persisted = False )
535+ record_harness_export_check (state ) # BEFORE teardown: it kills this pane
536+ teardown_session (state )
0 commit comments