From f70896d16306f2fbd19afcd2f63e8f7bb874976b Mon Sep 17 00:00:00 2001 From: Sallvainian <171521906+Sallvainian@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:01:52 -0500 Subject: [PATCH] feat(tui): show each story's worked time in the task table Add a `time` column between `tokens` and `info`. It counts up each second while a task is worked, holds while the run is paused or stopped and while the task's session waits out a usage-limit reset, stops when the task ends, and starts over when the task restarts. The clocks are folded from journal.jsonl as the dashboard reads it (StoryClocks in tui/data.py), so no engine, state.json or --json change is needed, and reopening the TUI rebuilds the same times. Besides stories it times sweep bundles, standalone unit replays and a sweep's triage and migration legs; a resume that carries work on reopens a stopped clock, and the downtime before a resume after an engine death is left out. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 + docs/tui-guide.md | 1 + src/bmad_loop/tui/data.py | 215 ++++++++++++++++- src/bmad_loop/tui/screens/dashboard.py | 27 ++- src/bmad_loop/tui/widgets.py | 8 + tests/test_tui_app.py | 80 +++++++ tests/test_tui_data.py | 316 ++++++++++++++++++++++++- 7 files changed, 645 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6eb59b78c..5097d51fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,10 @@ breaking changes may land in a minor release. ### Added +- Show each story's worked time in the TUI task table's `time` column, between `tokens` + and `info`: it counts up each second while the story is worked, holds while the run is + paused or stopped and while a session waits out a usage-limit reset, stops when the + story ends, and starts over when the story restarts. - Add the experimental `tickets` work source for BMAD v7 initiative ticket trees (`[stories] source = "tickets"`): dispatch `bmad-build-auto ticket ` in initiative build order, verify each plan at `built`, and mark it `done` through `tickets.py mark` diff --git a/docs/tui-guide.md b/docs/tui-guide.md index c0c6da7b6..0d4a8cca7 100644 --- a/docs/tui-guide.md +++ b/docs/tui-guide.md @@ -275,6 +275,7 @@ One row per story (or sweep bundle and triage task) in the selected run: | `dev` | dev attempt counter, `×N`; `↻M` follows when M of them were uncharged usage-limit relaunches | | `review` | review cycle counter, `×N`; `↻M` follows when M of them were uncharged usage-limit relaunches | | `tokens` | cost-weighted token total (cache reads at `limits.cache_read_weight`), the total budgets judge; `-` until known | +| `time` | worked time, `H:MM:SS`: counts up while the story is worked, holds while the run is paused or stopped and while its session waits out a usage-limit reset, stops when the story ends, and starts over when it restarts; `-` until it starts | | `info` | defer reason, or the first 12 characters of the commit SHA once committed | | `raw` | unweighted token total, cache reads at full price | diff --git a/src/bmad_loop/tui/data.py b/src/bmad_loop/tui/data.py index 07c0936da..2fbfac2d5 100644 --- a/src/bmad_loop/tui/data.py +++ b/src/bmad_loop/tui/data.py @@ -255,6 +255,15 @@ def __init__(self, run_dir: Path): # FAULT keeps the offset — only genuine absence or a shrink (truncation / # rewrite) restarts from zero — so recovering re-reads nothing twice. self.fault: str | None = None + # How many times the reader has gone back to the start after reading + # something: a fold over every row (`StoryClocks`) must start over when + # this moves, or the rows read again are folded twice. + self.restarts = 0 + + def _restart(self) -> None: + if self._offset: + self.restarts += 1 + self._offset = 0 def read_new(self, *, pin: RunState | None = None) -> list[dict[str, Any]]: entries = self._read_new() @@ -292,11 +301,11 @@ def _read_new(self) -> list[dict[str, Any]]: return [] self.fault = None if sig is None: - self._offset = 0 + self._restart() return [] size = sig[1] if size < self._offset: - self._offset = 0 + self._restart() if size == self._offset: return [] try: @@ -304,7 +313,7 @@ def _read_new(self) -> list[dict[str, Any]]: f.seek(self._offset) chunk = f.read(size - self._offset) except (FileNotFoundError, NotADirectoryError): - self._offset = 0 # gone between the stat and the open: absence + self._restart() # gone between the stat and the open: absence return [] except OSError as e: self.fault = f"journal.jsonl unreadable ({_describe(e)})" @@ -331,6 +340,206 @@ def _read_new(self) -> list[dict[str, Any]]: return entries +# ------------------------------------------------------------- story clocks + +# Journal kinds that start a task's clock from zero: a fresh pick, a sweep bundle, +# or a standalone replay of a kept unit (`unitreplay`, which picks no story). +_CLOCK_START_KINDS = frozenset({"story-start", "bundle-start", "unit-replay-start"}) +# A resume that restarts a task's work from scratch: it starts over a clock the +# task already has, and starts none of its own; a task with no clock yet (a sweep's +# triage or migration leg, or a blocked task re-run through `resolve`, none of +# which gets a start row) gets one at its first `session-start` instead. +_CLOCK_RESTART_KIND = "resume-restart" +# Kinds that stop a task's clock for good, unless later work on it reopens it. +_CLOCK_END_KINDS = frozenset( + { + "story-done", + "story-escalated", + "story-deferred", + "story-skipped", + "story-awaiting-operator", + # worktree isolation defers a unit it cannot mount without a story-deferred + "worktree-open-failed", + } +) +# A sweep's triage and migration legs end with a row that names no task: the +# leg's task key (`sweep.TRIAGE_KEY`, plus `-` from the second triage +# cycle on, and `sweep.MIGRATE_KEY`) by the kind that ends it. Spelled out +# rather than imported: `sweep` is heavy and this module stays import-light. +_SWEEP_LEG_END_KINDS = {"sweep-triage-result": "sweep-triage", "sweep-migrated": "sweep-migrate"} +# Kinds after which an ended task is being worked again (a resume that carries on +# rather than restarting): its clock carries on from the time it already showed. +_CLOCK_REOPEN_KINDS = frozenset( + { + "session-start", + "resume-review", + "resume-verify", + "resume-reverify", + "resume-commit", + "resume-env-dispatch", + } +) +# Kinds that hold every clock until the next `run-resume`. +_RUN_HOLD_KINDS = frozenset({"run-paused", "run-stop"}) +# Rows the resuming process writes ahead of its `run-resume` (`cli.cmd_resume`): +# not a sign the previous engine was alive, so they never move the cutoff a +# resume after an unrecorded engine death holds the clocks from. +_RESUME_PRELUDE_KINDS = frozenset( + {"root-identity-recorded", "root-identity-rebound", "rearm-code-root-restamped"} +) + + +def _entry_ts(entry: Mapping[str, Any]) -> float | None: + """An entry's finite numeric `ts`, or None (a malformed or unreadable row).""" + raw = entry.get("ts") + if not isinstance(raw, (int, float)) or isinstance(raw, bool): + return None + try: + stamp = float(raw) + except OverflowError: + return None + return stamp if math.isfinite(stamp) else None + + +@dataclass +class _Clock: + """One task's clock: `worked` seconds banked, and the wall time the current + counting stretch began (`since`), None while the clock is held.""" + + worked: float = 0.0 + since: float | None = None + ended: bool = False + quota_wait: bool = False + + +class StoryClocks: + """Wall time each task in a run has spent being worked, folded from its + journal one batch at a time, for the task table's `time` column. + + A clock starts at zero on `story-start` / `bundle-start` / + `unit-replay-start`, or at the first `session-start` of a task that has + none (a sweep's triage or migration leg, a blocked task re-run through + `resolve`), and starts over on a `resume-restart` of a task that has one, + since the work starts over. + + It holds while the run is paused or stopped (`run-paused` / `run-stop` + until `run-resume`) and while the task's own session waits out a usage-limit + reset (`quota-wait-started` until `quota-wait-ended`, or until a + `run-resume`: a wait the engine died in is never closed). A `run-resume` + with no hold before it follows an engine that died without a record: the + clocks are held from the last entry before it, the run's last sign of life + (the resuming process's own prelude rows excepted). + + A clock stops on the task's terminal kind (done, escalated, deferred, + skipped, awaiting-operator, worktree-open-failed, or the triage / migration + leg's result row); a later session or carry-on resume for that task reopens + it where it stopped. + + Fed every journal entry from the start (the dashboard keeps only a bounded + tail, so this folds as it goes). Pure: no I/O, never raises on a malformed + entry; an entry without a finite `ts` or a string `kind` is skipped.""" + + def __init__(self) -> None: + self._clocks: dict[str, _Clock] = {} + self._task_story: dict[str, str] = {} # session task_id -> story key + self._held = False + self._last_ts: float | None = None + + def feed(self, entries: list[dict[str, Any]]) -> None: + for entry in entries: + ts = _entry_ts(entry) + kind = entry.get("kind") + if ts is None or not isinstance(kind, str): + continue + self._apply(entry, kind, ts) + if kind not in _RESUME_PRELUDE_KINDS: + self._last_ts = ts if self._last_ts is None else max(self._last_ts, ts) + + def elapsed(self, now: float | None) -> dict[str, float]: + """Seconds per task key. `now` is the wall time a running clock counts + up to; None (a run with no live engine) stops running clocks at the last + journal entry instead.""" + until = now if now is not None else self._last_ts + out: dict[str, float] = {} + for key, clock in self._clocks.items(): + total = clock.worked + if clock.since is not None and until is not None: + total += max(0.0, until - clock.since) + out[key] = total + return out + + def _counting(self, clock: _Clock) -> bool: + return not (clock.ended or clock.quota_wait or self._held) + + @staticmethod + def _hold(clock: _Clock, ts: float) -> None: + if clock.since is not None: + clock.worked += max(0.0, ts - clock.since) + clock.since = None + + def _release(self, clock: _Clock, ts: float) -> None: + if clock.since is None and self._counting(clock): + clock.since = ts + + def _apply(self, entry: dict[str, Any], kind: str, ts: float) -> None: + raw_key = entry.get("story_key") + key = raw_key if isinstance(raw_key, str) and raw_key else None + if kind in _CLOCK_START_KINDS or kind == _CLOCK_RESTART_KIND: + if key is not None and (kind in _CLOCK_START_KINDS or key in self._clocks): + clock = self._clocks[key] = _Clock() + self._release(clock, ts) + return + if kind == "session-start": + task_id = entry.get("task_id") + if key is None and isinstance(task_id, str) and task_id: + key = _story_key_from_task_id(task_id, str(entry.get("role") or "")) + if isinstance(task_id, str) and task_id and key is not None: + self._task_story[task_id] = key + if key is not None and key not in self._clocks: + clock = self._clocks[key] = _Clock() + self._release(clock, ts) + if kind in _SWEEP_LEG_END_KINDS: + leg = _SWEEP_LEG_END_KINDS[kind] + for name, clock in self._clocks.items(): + if name == leg or name.startswith(leg + "-"): + self._hold(clock, ts) + clock.ended = True + elif kind in _CLOCK_END_KINDS: + clock = self._clocks.get(key) if key is not None else None + if clock is not None: + self._hold(clock, ts) + clock.ended = True + elif kind in _CLOCK_REOPEN_KINDS: + clock = self._clocks.get(key) if key is not None else None + if clock is not None and clock.ended: + clock.ended = False + clock.quota_wait = False + self._release(clock, ts) + elif kind in ("quota-wait-started", "quota-wait-ended"): + task_id = entry.get("task_id") + story = self._task_story.get(task_id) if isinstance(task_id, str) else None + clock = self._clocks.get(story) if story is not None else None + if clock is not None: + self._hold(clock, ts) + clock.quota_wait = kind == "quota-wait-started" + self._release(clock, ts) + elif kind in _RUN_HOLD_KINDS: + for clock in self._clocks.values(): + self._hold(clock, ts) + self._held = True + elif kind == "run-resume": + if not self._held and self._last_ts is not None: + for clock in self._clocks.values(): + self._hold(clock, self._last_ts) + self._held = False + for clock in self._clocks.values(): + # A quota wait still open here belonged to a session of the engine + # that stopped; it never writes its `quota-wait-ended`, and a wait + # the resumed engine meets is journaled afresh. + clock.quota_wait = False + self._release(clock, ts) + + # Pane geometry mirrors adapters.generic PANE_COLUMNS/PANE_LINES (not # imported: that module drags in Policy/SignalWatcher, and this layer stays # a pure observer). diff --git a/src/bmad_loop/tui/screens/dashboard.py b/src/bmad_loop/tui/screens/dashboard.py index 799101634..9ce95c166 100644 --- a/src/bmad_loop/tui/screens/dashboard.py +++ b/src/bmad_loop/tui/screens/dashboard.py @@ -55,6 +55,7 @@ StoriesTable, TicketsTable, agent_label, + format_elapsed, pause_tag, status_cell, stopping_tag, @@ -154,6 +155,9 @@ def __init__(self, run_dir: Path): self.watcher = data.RunWatcher(run_dir) self.journal = data.JournalTail(run_dir) self.entries: list[dict[str, Any]] = [] + # every journal entry, folded as read: `entries` keeps only a bounded tail + self.clocks = data.StoryClocks() + self.journal_restarts = 0 # `journal.restarts` the clocks were folded from self.log: data.LogView | None = None self.log_task: str | None = None # (parked, answerable, fault) of the parked-prompt note the Log pane last @@ -194,6 +198,7 @@ class _Snapshot: tickets_mode: bool = False # selected run is tickets mode (its loader gave a TicketsBoard) tickets: data.TicketsBoard | None = None # tickets board, when tickets_mode new_entries: list[dict[str, Any]] = field(default_factory=list) + elapsed: dict[str, float] = field(default_factory=dict) # task key -> worked seconds log_task: str | None = None log_reset: bool = False log_lines: Text | None = None # full re-render; None = unchanged this tick @@ -364,6 +369,7 @@ def on_mount(self) -> None: tasks.add_column("dev", key="dev", width=6) # room for `×NN ↻M` tasks.add_column("review", key="review", width=6) tasks.add_column("tokens", key="tokens", width=12) + tasks.add_column("time", key="time", width=9) # `H:MM:SS`, room for 10h+ tasks.add_column("info", key="info") tasks.add_column("raw", key="raw", width=13) self.query_one("#runheader", RunHeader).show_empty(self.project) @@ -925,6 +931,15 @@ def _poll( snap.new_entries = ctx.journal.read_new(pin=snap.state) ctx.entries.extend(snap.new_entries) del ctx.entries[:-_MAX_ENTRIES] + if ctx.journal.restarts != ctx.journal_restarts: + # the reader went back to the start: fold the re-read rows afresh + ctx.journal_restarts = ctx.journal.restarts + ctx.clocks = data.StoryClocks() + ctx.clocks.feed(snap.new_entries) + # A run with a live engine counts up to now; any other run's clocks + # stop at its last journal entry (UNKNOWN liveness honored as live). + live_engine = snap.status in (data.RUNNING, data.UNKNOWN) + snap.elapsed = ctx.clocks.elapsed(time.time() if live_engine else None) snap.decision = data.pending_decision(ctx.entries) if snap.decision is not None and ctx.decision_toasted != snap.decision[0]: snap.toast_decision = True @@ -1055,7 +1070,7 @@ def _apply(self, snap: _Snapshot) -> None: self._apply_board(snap) if snap.state is not None: live = snap.agent if isinstance(snap.agent, data.ActiveAgent) else None - self._apply_tasks(snap.state, live) + self._apply_tasks(snap.state, live, snap.elapsed) if snap.toast_decision and snap.decision is not None: self.notify( snap.decision[1] or snap.decision[0], @@ -1192,7 +1207,12 @@ def _apply_runs(self, runs: list[data.RunInfo], fault: str | None = None) -> Non # just appeared — bring the cursor to it table.move_cursor(row=self._run_rows.index(self.selected_run_id)) - def _apply_tasks(self, state: RunState, agent: data.ActiveAgent | None = None) -> None: + def _apply_tasks( + self, + state: RunState, + agent: data.ActiveAgent | None = None, + elapsed: dict[str, float] | None = None, + ) -> None: table = self.query_one("#tasks", DataTable) weight = state.cache_read_weight() for key, task in state.tasks.items(): @@ -1204,12 +1224,15 @@ def _apply_tasks(self, state: RunState, agent: data.ActiveAgent | None = None) - tokens = f"{weighted:,}" if has_tokens else "-" raw = f"{task.tokens.total:,}" if has_tokens else "-" info = task.defer_reason or (task.commit_sha or "")[:12] + worked = (elapsed or {}).get(key) + clock = format_elapsed(worked) if worked is not None else "-" cells = { "phase": str(task.phase), "agent": self._agent_cell(task, key, agent), "dev": _counter_cell(task.attempt, task.dev_usage_relaunches), "review": _counter_cell(task.review_cycle, task.review_usage_relaunches), "tokens": tokens, + "time": clock, "info": info, "raw": raw, # must be last — matches add_column order } diff --git a/src/bmad_loop/tui/widgets.py b/src/bmad_loop/tui/widgets.py index 82873caf6..b76ced75d 100644 --- a/src/bmad_loop/tui/widgets.py +++ b/src/bmad_loop/tui/widgets.py @@ -148,6 +148,14 @@ def _format_age(seconds: float) -> str: return f"{minutes // 60}h{minutes % 60:02d}m" +def format_elapsed(seconds: float) -> str: + """A task's worked time for the task table's `time` column, as `H:MM:SS` + (`0:52:22`, `12:04:05`): whole seconds, so a running clock visibly ticks on + every poll. A negative value (a clock stepped backward) reads as `0:00:00`.""" + whole = max(0, int(seconds)) + return f"{whole // 3600}:{whole % 3600 // 60:02d}:{whole % 60:02d}" + + def _format_countdown(seconds: float) -> str: """A parked prompt's remaining auto-deny time for the header's `· auto-denies in M:SS` text (#855): whole seconds, so it reads like the diff --git a/tests/test_tui_app.py b/tests/test_tui_app.py index 84d479462..aca929537 100644 --- a/tests/test_tui_app.py +++ b/tests/test_tui_app.py @@ -833,6 +833,86 @@ async def test_task_table_marks_usage_relaunch_refunds(project_tree): assert tasks_table.get_cell("1-2-logout", "review") == "×3 ↻1" +def _write_journal(run_dir: Path, rows: list[dict[str, object]]) -> None: + with (run_dir / "journal.jsonl").open("a", encoding="utf-8") as f: + for row in rows: + f.write(json.dumps(row) + "\n") + + +async def test_task_table_shows_each_story_worked_time(project_tree): + """The `time` column sits between `tokens` and `info`: a finished story's + clock is frozen at its worked time (the run's pause left out), a story the + live engine is working counts up to now, and a task with no start reads `-`.""" + root = project_tree.project + done = StoryTask(story_key="1-1-login", epic=1, phase=Phase.DONE) + working = StoryTask(story_key="1-2-logout", epic=1, phase=Phase.DEV_RUNNING) + waiting = StoryTask(story_key="1-3-reset", epic=1, phase=Phase.PENDING) + run_dir = make_run( + root, + "20260611-100000-aaaa", + alive=True, + tasks={"1-1-login": done, "1-2-logout": working, "1-3-reset": waiting}, + ) + now = time.time() + _write_journal( + run_dir, + [ + {"ts": now - 9000, "kind": "story-start", "story_key": "1-1-login"}, + {"ts": now - 8000, "kind": "run-paused", "story_key": "1-1-login"}, + {"ts": now - 5000, "kind": "run-resume"}, + {"ts": now - 4858, "kind": "story-done", "story_key": "1-1-login"}, + {"ts": now - 3600, "kind": "story-start", "story_key": "1-2-logout"}, + ], + ) + app = BmadLoopApp(root) + async with app.run_test() as pilot: + await until(pilot, lambda: isinstance(app.screen, DashboardScreen)) + screen = dashboard(app) + tasks_table = screen.query_one("#tasks", DataTable) + await until(pilot, lambda: screen.selected_run_id == "20260611-100000-aaaa") + await until(pilot, lambda: tasks_table.row_count == 3) + await until(pilot, lambda: tasks_table.get_cell("1-1-login", "time") != "-") + keys = [column.key.value for column in tasks_table.ordered_columns] + assert keys[keys.index("tokens") + 1 : keys.index("info")] == ["time"] + assert tasks_table.get_cell("1-1-login", "time") == "0:19:02" # 1000s + 142s + assert tasks_table.get_cell("1-2-logout", "time").startswith("1:00:") + assert tasks_table.get_cell("1-3-reset", "time") == "-" + + +async def test_task_table_time_refolds_when_the_journal_is_rewritten(project_tree): + """A journal that shrinks is re-read from the start; the clocks are folded + afresh rather than replaying the re-read rows over the old fold, so a story + held by a pause keeps its time. + + ABLATION: drop the `ctx.journal.restarts` reset in `_poll` and the cell reads + 0:00:00 — the replayed `story-start` lands while the old fold is held.""" + root = project_tree.project + task = StoryTask(story_key="1-1-login", epic=1, phase=Phase.DEV_RUNNING) + run_dir = make_run(root, "20260611-100000-aaaa", alive=True, tasks={"1-1-login": task}) + now = time.time() + rows: list[dict[str, object]] = [ + {"ts": now - 1000, "kind": "story-start", "story_key": "1-1-login"}, + {"ts": now - 900, "kind": "run-paused", "story_key": "1-1-login"}, + ] + _write_journal(run_dir, [dict(row, pad="x" * 64) for row in rows]) + app = BmadLoopApp(root) + async with app.run_test() as pilot: + await until(pilot, lambda: isinstance(app.screen, DashboardScreen)) + screen = dashboard(app) + tasks_table = screen.query_one("#tasks", DataTable) + await until(pilot, lambda: screen.selected_run_id == "20260611-100000-aaaa") + await until(pilot, lambda: tasks_table.row_count == 1) + await until(pilot, lambda: tasks_table.get_cell("1-1-login", "time") == "0:01:40") + (run_dir / "journal.jsonl").write_text("", encoding="utf-8") + _write_journal(run_dir, rows) # the same rows, shorter: the reader restarts + ctx = screen._ctx + assert ctx is not None + await until(pilot, lambda: ctx.journal.restarts == 1) + await until(pilot, lambda: ctx.journal_restarts == 1) + await pilot.pause(1.5) + assert tasks_table.get_cell("1-1-login", "time") == "0:01:40" + + async def test_zero_weighted_tokens_shows_zero_not_dash(project_tree): """With cache_read_weight=0 a cache-read-only task has weighted==0 but nonzero raw. The tokens cell must render "0" (a real value), not "-" — which reads as missing diff --git a/tests/test_tui_data.py b/tests/test_tui_data.py index 0ad1268b1..a68f70ef5 100644 --- a/tests/test_tui_data.py +++ b/tests/test_tui_data.py @@ -33,7 +33,7 @@ from bmad_loop.model import RunState from bmad_loop.runs import RUNS_DIR from bmad_loop.tickettree import TicketsTimeout -from bmad_loop.tui import data +from bmad_loop.tui import data, widgets def make_run(root: Path, run_id: str, **state_kwargs) -> Path: @@ -2669,3 +2669,317 @@ def test_journal_tail_flags_a_link_on_a_no_record_run(tmp_path, linked): tail = data.JournalTail(run_dir) assert [e["kind"] for e in tail.read_new(pin=state)] == ["foreign-row"] assert tail.fault is not None and "is a link" in tail.fault + + +# ------------------------------------------------------------- story clocks + + +def _clock_rows(*rows: tuple[float, str, dict[str, object]]) -> list[dict[str, object]]: + return [{"ts": ts, "kind": kind, **fields} for ts, kind, fields in rows] + + +def test_story_clock_counts_from_start_and_stops_at_done(): + """A started task counts up to `now`; its terminal kind freezes it, whatever + `now` is later. A task with no start has no clock. + + ABLATION: drop the `_CLOCK_END_KINDS` arm and the frozen value follows `now`.""" + clocks = data.StoryClocks() + clocks.feed(_clock_rows((1000.0, "story-start", {"story_key": "1-1-a"}))) + assert clocks.elapsed(1030.0) == {"1-1-a": 30.0} + clocks.feed(_clock_rows((1100.0, "story-done", {"story_key": "1-1-a"}))) + assert clocks.elapsed(5000.0) == {"1-1-a": 100.0} + assert "1-2-b" not in clocks.elapsed(5000.0) + + +def test_story_clock_holds_while_the_run_is_paused_or_stopped(): + """`run-paused` and `run-stop` hold every open clock until `run-resume`. + + ABLATION: drop the `_RUN_HOLD_KINDS` arm and the paused stretch is counted.""" + for hold in ("run-paused", "run-stop"): + clocks = data.StoryClocks() + clocks.feed( + _clock_rows( + (0.0, "story-start", {"story_key": "1-1-a"}), + (100.0, hold, {"story_key": "1-1-a"}), + ) + ) + assert clocks.elapsed(900.0) == {"1-1-a": 100.0} # held, not counting + clocks.feed(_clock_rows((1000.0, "run-resume", {}))) + assert clocks.elapsed(1050.0) == {"1-1-a": 150.0} + + +def test_story_clock_holds_only_its_own_task_through_a_quota_wait(): + """A usage-limit wait holds the clock of the task whose session waits (mapped + through that session's `session-start`), and no other. + + ABLATION: drop the quota arm and both waits' 500s are counted.""" + clocks = data.StoryClocks() + clocks.feed( + _clock_rows( + (0.0, "story-start", {"story_key": "1-1-a"}), + (0.0, "story-start", {"story_key": "1-2-b"}), + (10.0, "session-start", {"story_key": "1-1-a", "task_id": "1-1-a-dev-1"}), + (100.0, "quota-wait-started", {"task_id": "1-1-a-dev-1"}), + (600.0, "quota-wait-ended", {"task_id": "1-1-a-dev-1"}), + ) + ) + assert clocks.elapsed(700.0) == {"1-1-a": 200.0, "1-2-b": 700.0} + # an unstamped session-start maps through its task id + clocks.feed( + _clock_rows( + (700.0, "session-start", {"task_id": "1-2-b-review-1", "role": "review"}), + (800.0, "quota-wait-started", {"task_id": "1-2-b-review-1"}), + ) + ) + assert clocks.elapsed(1300.0) == {"1-1-a": 800.0, "1-2-b": 800.0} + + +def test_story_clock_resume_clears_a_quota_wait_the_engine_died_in(): + """An engine that dies mid quota wait never writes its `quota-wait-ended`; the + `run-resume` clears that orphaned hold, so carry-on work after it counts. + + ABLATION: drop the `quota_wait = False` on `run-resume` and it reads 100.""" + clocks = data.StoryClocks() + clocks.feed( + _clock_rows( + (0.0, "story-start", {"story_key": "1-1-a"}), + (10.0, "session-start", {"story_key": "1-1-a", "task_id": "1-1-a-review-1"}), + (100.0, "quota-wait-started", {"task_id": "1-1-a-review-1"}), + (5000.0, "run-resume", {}), + (5000.0, "resume-reverify", {"story_key": "1-1-a"}), + (5010.0, "session-start", {"story_key": "1-1-a", "task_id": "1-1-a-review-2"}), + (5300.0, "story-done", {"story_key": "1-1-a"}), + ) + ) + assert clocks.elapsed(9000.0) == {"1-1-a": 400.0} + + +def test_story_clock_stops_when_the_worktree_cannot_open(): + """Worktree isolation defers a unit it cannot mount with only + `worktree-open-failed`: the clock stops there, not at the end of the run. + + ABLATION: drop `worktree-open-failed` from `_CLOCK_END_KINDS` and it reads 900.""" + clocks = data.StoryClocks() + clocks.feed( + _clock_rows( + (0.0, "story-start", {"story_key": "1-1-a"}), + (5.0, "worktree-open-failed", {"story_key": "1-1-a", "error": "branch held"}), + (6.0, "story-start", {"story_key": "1-2-b"}), + ) + ) + assert clocks.elapsed(900.0) == {"1-1-a": 5.0, "1-2-b": 894.0} + + +def test_story_clock_starts_on_a_standalone_unit_replay(): + """A replay run (`unitreplay`) picks no story, so its `unit-replay-start` is + the clock's start. + + ABLATION: drop `unit-replay-start` from `_CLOCK_START_KINDS` and it reads `{}`.""" + clocks = data.StoryClocks() + clocks.feed( + _clock_rows( + (0.0, "unit-replay-start", {"story_key": "1-1-a", "replay_of": "r1"}), + (5.0, "resume-reverify", {"story_key": "1-1-a"}), + (300.0, "story-done", {"story_key": "1-1-a"}), + ) + ) + assert clocks.elapsed(900.0) == {"1-1-a": 300.0} + + +def test_story_clock_restarts_from_zero_when_the_work_restarts(): + """A second `story-start`, or a `resume-restart`, starts the clock over. + + ABLATION: keep the old clock on a start kind and the earlier time carries over.""" + for restart in ("story-start", "resume-restart"): + clocks = data.StoryClocks() + clocks.feed( + _clock_rows( + (0.0, "story-start", {"story_key": "1-1-a"}), + (500.0, "story-escalated", {"story_key": "1-1-a"}), + (900.0, restart, {"story_key": "1-1-a"}), + ) + ) + assert clocks.elapsed(960.0) == {"1-1-a": 60.0} + + +def test_story_clock_reopens_where_it_stopped_when_work_carries_on(): + """An escalated task resumed without a restart (a later session for it) carries + on from the time it showed; the pause between is not counted. + + ABLATION: drop the `_CLOCK_REOPEN_KINDS` arm and the clock stays at 300.""" + clocks = data.StoryClocks() + clocks.feed( + _clock_rows( + (0.0, "story-start", {"story_key": "1-1-a"}), + (300.0, "story-escalated", {"story_key": "1-1-a"}), + (301.0, "run-paused", {"story_key": "1-1-a"}), + (5000.0, "run-resume", {}), + (5010.0, "session-start", {"story_key": "1-1-a", "task_id": "1-1-a-review-1"}), + ) + ) + assert clocks.elapsed(5110.0) == {"1-1-a": 400.0} + + +def test_story_clock_reopens_on_a_reverify_resume(): + """A deferred or escalated task resumed through `resume-reverify` re-runs its + verification before any new session: that work counts. + + ABLATION: drop `resume-reverify` from `_CLOCK_REOPEN_KINDS` and it reads 300.""" + clocks = data.StoryClocks() + clocks.feed( + _clock_rows( + (0.0, "story-start", {"story_key": "1-1-a"}), + (300.0, "story-deferred", {"story_key": "1-1-a"}), + (301.0, "run-paused", {}), + (5000.0, "run-resume", {}), + (5000.0, "resume-reverify", {"story_key": "1-1-a"}), + (5120.0, "story-done", {"story_key": "1-1-a"}), + ) + ) + assert clocks.elapsed(9000.0) == {"1-1-a": 420.0} + + +def test_story_clock_restart_starts_no_clock_of_its_own(): + """A `resume-restart` for a task no start row opened starts no clock by + itself: the task's first `session-start` does. + + ABLATION: let `resume-restart` create clocks and a `sweep-triage` clock appears.""" + clocks = data.StoryClocks() + clocks.feed( + _clock_rows( + (0.0, "resume-restart", {"story_key": "sweep-triage", "phase": "triage-running"}), + (50.0, "bundle-start", {"story_key": "dw-a"}), + ) + ) + assert clocks.elapsed(100.0) == {"dw-a": 50.0} + + +def test_story_clock_gap_cutoff_ignores_the_resume_prelude(): + """The resuming process can write root-identity and code-root rows ahead of its + `run-resume` (after a reboot, say): they are not the dead engine's last sign of + life, so the downtime before them stays out. + + ABLATION: let prelude rows move `_last_ts` and the 10000s gap is counted.""" + clocks = data.StoryClocks() + clocks.feed( + _clock_rows( + (0.0, "story-start", {"story_key": "1-1-a"}), + (200.0, "session-start", {"story_key": "1-1-a", "task_id": "1-1-a-dev-1"}), + (10190.0, "root-identity-rebound", {"root": "run-dir"}), + (10195.0, "rearm-code-root-restamped", {"code_root_changed": True}), + (10196.0, "root-identity-recorded", {"root": "project"}), + (10200.0, "run-resume", {}), + ) + ) + assert clocks.elapsed(10250.0) == {"1-1-a": 250.0} + + +def test_story_clock_excludes_the_gap_before_a_resume_after_an_engine_death(): + """An engine that died leaves no hold record; the `run-resume` that follows + holds the clocks from the last entry before it. + + ABLATION: drop the unheld-resume backfill and the 10000s gap is counted.""" + clocks = data.StoryClocks() + clocks.feed( + _clock_rows( + (0.0, "story-start", {"story_key": "1-1-a"}), + (200.0, "session-start", {"story_key": "1-1-a", "task_id": "1-1-a-dev-1"}), + (10200.0, "run-resume", {}), + ) + ) + assert clocks.elapsed(10250.0) == {"1-1-a": 250.0} + + +def test_story_clock_stops_at_the_last_entry_without_a_live_engine(): + """`now=None` (no live engine) stops a running clock at the run's last entry.""" + clocks = data.StoryClocks() + clocks.feed( + _clock_rows( + (0.0, "story-start", {"story_key": "1-1-a"}), + (420.0, "session-start", {"story_key": "1-1-a", "task_id": "1-1-a-dev-1"}), + ) + ) + assert clocks.elapsed(None) == {"1-1-a": 420.0} + + +def test_story_clock_skips_malformed_entries(): + """An entry without a finite numeric `ts`, or with an ill-typed key, is skipped + without raising or disturbing an open clock.""" + clocks = data.StoryClocks() + clocks.feed(_clock_rows((0.0, "story-start", {"story_key": "1-1-a"}))) + clocks.feed( + [ + {"kind": "story-done", "story_key": "1-1-a"}, # no ts + {"ts": "soon", "kind": "story-done", "story_key": "1-1-a"}, + {"ts": True, "kind": "run-paused"}, + {"ts": float("nan"), "kind": "run-paused"}, + {"ts": 10.0, "kind": "story-done", "story_key": 7}, + {"ts": 10.0, "kind": "quota-wait-started", "task_id": None}, + {"ts": 10.0, "kind": "session-start", "task_id": 3}, + {"ts": 10.0, "kind": []}, # unhashable kinds: a set test would raise + {"ts": 10.0, "kind": {"story-done": 1}, "story_key": "1-1-a"}, + ] + ) + assert clocks.elapsed(60.0) == {"1-1-a": 60.0} + + +def test_story_clock_times_the_sweep_triage_and_migration_legs(): + """A sweep's triage and migration legs get no start row and end on a result + row that names no task: their clocks run from their first session to it, a + later triage cycle's `sweep-triage-` key included. + + ABLATION: drop the `_SWEEP_LEG_END_KINDS` arm and all three count to `now`.""" + clocks = data.StoryClocks() + clocks.feed( + _clock_rows( + (0.0, "session-start", {"story_key": "sweep-migrate", "task_id": "m-1"}), + (40.0, "sweep-migrated", {"converted": 3, "delivery_id": "d1"}), + (50.0, "session-start", {"story_key": "sweep-triage", "task_id": "t-1"}), + (110.0, "sweep-triage-result", {"bundles": 2}), + (120.0, "bundle-start", {"story_key": "dw-a"}), + (500.0, "session-start", {"story_key": "sweep-triage-2", "task_id": "t-2"}), + (520.0, "sweep-triage-result", {"bundles": 0}), + ) + ) + assert clocks.elapsed(1000.0) == { + "sweep-migrate": 40.0, + "sweep-triage": 60.0, + "dw-a": 880.0, + "sweep-triage-2": 20.0, + } + + +def test_story_clock_sweep_leg_keys_match_the_sweep(): + """The leg keys spelled out in `_SWEEP_LEG_END_KINDS` are the sweep's own.""" + from bmad_loop import sweep + + assert set(data._SWEEP_LEG_END_KINDS.values()) == {sweep.TRIAGE_KEY, sweep.MIGRATE_KEY} + + +def test_format_elapsed_reads_hours_minutes_seconds(): + assert [widgets.format_elapsed(s) for s in (0, 59.9, 3142.2, 43445, -5)] == [ + "0:00:00", + "0:00:59", + "0:52:22", + "12:04:05", + "0:00:00", + ] + + +def test_journal_tail_counts_restarts_from_zero(tmp_path): + """`restarts` moves only when the reader goes back to the start after reading + something — a shrink or the file going away — never on an ordinary append.""" + path = tmp_path / "journal.jsonl" + tail = data.JournalTail(tmp_path) + assert (tail.read_new(), tail.restarts) == ([], 0) # absent before any read + path.write_text('{"kind": "a", "pad": "xxxxxxxxxxxxxxxx"}\n', encoding="utf-8") + tail.read_new() + with path.open("a", encoding="utf-8") as f: + f.write('{"kind": "b"}\n') + assert [e["kind"] for e in tail.read_new()] == ["b"] + assert tail.restarts == 0 + path.write_text('{"kind": "a"}\n', encoding="utf-8") # rewritten shorter + assert [e["kind"] for e in tail.read_new()] == ["a"] + assert tail.restarts == 1 + path.unlink() + assert (tail.read_new(), tail.restarts) == ([], 2)