Files
floop/code/floop/stream.py
T
onibot d384a10a8d feat: flight recorder — events.jsonl for post-mortem debugging
Owner ruling (26/10): 'vull poder fer com un debug amb l'IDE de
programació, però a posteriori de l'execució' — see WHERE inside which
expert we are at every moment, and the input/output of every component,
LLM or not. This is the recorder half (PR A of the observability plan).

- floop/recorder.py: append-only JSONL, one event per line. LAWS:
  never breaks a run (emitting is swallowed; no run dir = TOTAL no-op,
  no buffer, no counters); every line self-describing (seq, ts, run_ts,
  event, payload); in/out carry structured data, the exact prompt text
  stays in prompts/NN-stage.txt (events stay small).
- Wired via RunStreams (every component already had streams):
  comp.start/comp.out (machine stages INIT/ROUTE/EXPERT/ANSWER/FINAL),
  state, llm.done (stage, dur_s, call_seq, prompt file link — from the
  dspy callback), run.final.
- Knowledge pipeline components (floop-internal nodes, not LLMs):
  probe.done (seeds, rows, tau, semantic adds), claims.done (the claim
  list), type.done (claim -> typed fact, one per claim as ruled),
  fact.merged / fact.rejected (one per fact — _ingest_candidate is
  called per fact; verdict + reason + page), prover.done (dsl, verdict:
  invalid_dsl/no_closed_path/closed/ambiguous, bindings), kg.snapshot
  (once at run end: every edge with temporal window + last_touch from
  this run's merge events).
- kg_snapshot(): rows annotated with their last-touch event (owner:
  'cada fila del kg podria tenir anotat quan s'afegeix o edita').

Live-checked: baseline run writes real events (comp.start, llm.done
dur_s=17.35, comp.out '4'). TDD: recorder 3/3; suite 31 files green.

Next (PR B): floop-inspect — the HTML debugger reading events.jsonl
(timeline Gantt, KG view, facts table, probe view).
2026-10-27 07:42:23 +01:00

114 lines
4.5 KiB
Python

"""Progress streams for a floop run: the log (complete, technical) and thinking
(the screen channel for CLI; the future "thinking" output of floop-as-LLM).
Design (SCOPE.md §4 / GAP-13): every event lands in runs/<ts>-<slug>/run.log with
explicit flush (tail -f-able). The screen shows ONLY the thinking subset, and only
with --verbose. log ⊇ thinking; they will diverge over time.
"""
from __future__ import annotations
import re
import sys
from datetime import datetime, timezone
from pathlib import Path
from .recorder import Recorder
def _slug(text: str, maxlen: int = 40) -> str:
s = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
return s[:maxlen].rstrip("-") or "run"
def now_hms() -> str:
return datetime.now(timezone.utc).astimezone().strftime("%H:%M:%S")
class RunStreams:
"""Two sinks, one class: log always (flushed); thinking to screen iff verbose."""
def __init__(self, question: str, verbose: bool = False,
runs_dir: str | None = None) -> None:
base = Path(runs_dir) if runs_dir else Path(__file__).resolve().parent.parent / "runs"
base.mkdir(parents=True, exist_ok=True)
ts = datetime.now(timezone.utc).astimezone().strftime("%Y%m%d-%H%M%S")
self.run_dir = base / f"{ts}-{_slug(question)}"
self.run_dir.mkdir(parents=True, exist_ok=True)
self.log_path = self.run_dir / "run.log"
self.verbose = verbose
self.prompt_seq = 0 # exact-prompt files: prompts/NN-stage.txt
self.recorder = Recorder(run_dir=self.run_dir, memory=True)
self._fh = open(self.log_path, "a", encoding="utf-8")
def bump_prompt_seq(self) -> int:
"""Next exact-prompt file number (mirrors the budget counter: the
charge precedes the Predict, so NN == budget llm_calls)."""
self.prompt_seq += 1
return self.prompt_seq
def close(self) -> None:
if self._fh and not self._fh.closed:
self._fh.close()
# ---- channels ----------------------------------------------------------
def log(self, text: str) -> None:
"""Technical detail: log only, never on screen."""
self._emit_log(f"LOG {text}")
def think(self, text: str | None) -> None:
"""Thinking: screen iff verbose (flushed); always to log as [T] lines."""
if text is None:
return
for line in text.rstrip(chr(10)).split(chr(10)):
self._emit_log(f"[T] {line}", screen=f"[T] {line}")
def think_line(self, text: str) -> None:
self.think(text)
# ---- structural events -------------------------------------------------
def call(self, stage: str, description: str, think: str | None = None) -> None:
"""An LLM call or engine step is starting."""
self._emit_log(f"CALL {stage}: {description}")
self.recorder.emit("comp.start", comp=stage, desc=description[:200])
if think is not None:
self.think_line(f"[{stage}] {think}")
def output(self, stage: str, text: str, think: bool = True) -> None:
"""Raw LLM (or engine) output as it lands."""
self._emit_log(f"OUTPUT {stage}: {text}")
self.recorder.emit("comp.out", comp=stage, out=text[:500])
if think:
self.think(text)
def state(self, text: str, think: bool = False) -> None:
"""State change: evidence appended, question status, budget."""
self._emit_log(f"STATE {text}")
self.recorder.emit("state", text=text[:300])
if think:
self.think_line(text)
def warn(self, text: str) -> None:
"""A machine judgement worth a human's eye even non-verbose:
the seed that auto-answered a question, a guard refusing an
ingest, a budget starvation. Self-improvement signal (META.md):
the offline analysis counts these first. Log always; screen
ALWAYS (unlike thinking, the [W] line is the point)."""
self._emit_log(f"WARNING {text}")
print(f"[W] {text}", flush=True)
def final(self, text: str) -> None:
self._emit_log(f"FINAL {text}")
self.recorder.emit("run.final", out=text[:2000])
self.think_line(f"[FINAL] {text}")
# ---- internals ---------------------------------------------------------
def _emit_log(self, log_payload: str, screen: str | None = None) -> None:
line = f"[{now_hms()}] {log_payload}"
self._fh.write(line + "\n")
self._fh.flush()
if screen is not None and self.verbose:
print(screen, flush=True)