From ca1850445811ef0c357f4ccdb3d96750657f1c82 Mon Sep 17 00:00:00 2001 From: Sunil Srivatsa Date: Thu, 5 Nov 2026 20:13:54 -0800 Subject: [PATCH 1/3] feat(coordinator): keep one row per OMP pane keyed by host and pane The coordinator now builds rows (host, pane, mode, label) from complete snapshots, deduplicated across windows, and hands them to the transport. The hook-event transport reduces rows to its single combined mode, so SidePulse still sees exactly what 0.1.0 sent. Labels are sanitized at parse time and never reach logs, status, doctor.json, acks, or the SidePulse payload. --- tern_sidepulse/coordinator.py | 165 ++++++++++++------- tern_sidepulse/doctor.py | 5 +- tern_sidepulse/limits.py | 2 +- tern_sidepulse/reducer.py | 54 +++++-- tern_sidepulse/transport.py | 37 ++++- tests/helpers.py | 37 ++++- tests/test_cli.py | 2 +- tests/test_e2e.py | 23 +++ tests/test_fencing.py | 20 +-- tests/test_leases.py | 27 ++-- tests/test_notices.py | 75 ++++++--- tests/test_privacy.py | 230 +++++++++++++++++++++++--- tests/test_reducer.py | 42 ++--- tests/test_rows.py | 297 ++++++++++++++++++++++++++++++++++ tests/test_server.py | 2 +- tests/test_site.py | 9 -- tests/test_transport.py | 93 ++++++++++- 17 files changed, 935 insertions(+), 185 deletions(-) create mode 100644 tests/test_rows.py diff --git a/tern_sidepulse/coordinator.py b/tern_sidepulse/coordinator.py index fb49935..f8a735b 100644 --- a/tern_sidepulse/coordinator.py +++ b/tern_sidepulse/coordinator.py @@ -1,12 +1,11 @@ -"""The local coordinator: observer generations, leases, outcome notices and the desired SidePulse mode. +"""The local coordinator: observer generations, leases, outcome notices and per-pane rows. -One process per user holds the singleton lock, owns the stable bridge session and serializes -every state change and every SidePulse send. Window observers register, then publish complete -snapshots; the coordinator reduces them and keeps the display coherent after windows vanish. +One process per user holds the singleton lock and serializes every state change. Complete +window snapshots contribute rows keyed by host and pane; the transport owns delivery and any +protocol-specific reduction. Labels stay in memory, never in reports, logs or acknowledgements. """ from __future__ import annotations -import json import os from collections import OrderedDict from dataclasses import dataclass, field @@ -17,15 +16,18 @@ from .jsonio import load_json from .limits import Limits from .reducer import ( - IDLE_READY, KNOWN_STATES, + MODES, NOTICE_FAILED, NOTICE_KINDS, STATE_IDLE, Observation, - aggregate, + Row, + RowKey, notice_clears, pane_mode, + reduce_rows, + sanitize_label, ) from .transport import SidePulseTransport, iso_utc @@ -35,6 +37,9 @@ MAX_WINDOW_KEY = 64 MAX_PANE_ID = 64 MAX_NOTICE_ID = 64 +DEFAULT_HOST = "local" +MAX_HOST_KEY = 128 +MAX_LABEL_INPUT = 1024 MAX_RETIRED_NOTICES = 1024 MAX_RETIRE_REASONS = 256 DIAG_KEYS = ( @@ -50,6 +55,13 @@ "too_many", "budget_pauses", "helper_failures", + "label_tab", + "label_title", + "label_none", + "labels_unavailable", + "labels_dropped", + "host_fallback", + "encode_failed", ) DIAG_MAX = 100_000 @@ -85,9 +97,10 @@ class ObserverState: generation: int seq: int expires_at: float - observations: dict[str, Observation] = field(default_factory=dict) - notices: dict[str, NoticeTrack] = field(default_factory=dict) # one track per pane - retired_notices: "OrderedDict[tuple[str, str], None]" = field(default_factory=OrderedDict) + observations: dict[RowKey, Observation] = field(default_factory=dict) + notices: dict[RowKey, NoticeTrack] = field(default_factory=dict) # one track per row key + retired_notices: "OrderedDict[tuple[RowKey, str], None]" = field(default_factory=OrderedDict) + applied: int = 0 coverage: str = COVERAGE_COMPLETE uncertain: bool = False last_ack: dict = field(default_factory=dict) @@ -107,12 +120,13 @@ def observer_key(observer: object) -> str: return f"{parent_pid}:{window_key}" -def parse_observations(raw: object, limit: int) -> dict[str, Observation]: +def parse_observations(raw: object, limit: int) -> tuple[dict[RowKey, Observation], int]: if not isinstance(raw, list): raise ProtocolError("bad_request", "observations must be an array") if len(raw) > limit: raise ProtocolError("too_many_observations", "observation limit exceeded", limit=limit) - result: dict[str, Observation] = {} + result: dict[RowKey, Observation] = {} + labels_rejected = 0 for item in raw: if not isinstance(item, dict): raise ProtocolError("bad_request", "observation must be an object") @@ -139,9 +153,26 @@ def parse_observations(raw: object, limit: int) -> dict[str, Observation]: notice_kind = notice.get("kind") if not isinstance(notice_kind, str) or notice_kind not in NOTICE_KINDS: raise ProtocolError("bad_request", "notice.kind must be done or failed") - # Duplicate pane ids within one snapshot reduce idempotently: keep the first. - result.setdefault(pane_id, Observation(pane_id, state, notice_id, notice_kind)) - return result + host = item.get("host") + if host is None: + host = DEFAULT_HOST + elif ( + not isinstance(host, str) + or not 1 <= len(host) <= MAX_HOST_KEY + or any(ord(char) < 0x20 or 0x7F <= ord(char) <= 0x9F or 0xD800 <= ord(char) <= 0xDFFF for char in host) + ): + raise ProtocolError("bad_request", "observation.host must be a short host key") + raw_label = item.get("label") + label = None + if raw_label is not None: + if isinstance(raw_label, str) and len(raw_label) <= MAX_LABEL_INPUT: + label = sanitize_label(raw_label) + else: + labels_rejected += 1 + # Duplicate row keys within one snapshot keep the first observation and its label. + obs = Observation(pane_id, state, notice_id, notice_kind, host, label) + result.setdefault(obs.key, obs) + return result, labels_rejected def parse_diag(raw: object) -> dict: @@ -182,7 +213,8 @@ def __init__( self.observers: dict[str, ObserverState] = {} self.retire_reason: "OrderedDict[int, str]" = OrderedDict() self.highest_activated: dict[str, int] = {} - self.desired = IDLE_READY + self.rows: tuple[Row, ...] = () + self.apply_counter = 0 self.empty_since: float | None = clock.monotonic() self.last_observation_at: float | None = None self.last_wall = clock.wall() @@ -195,11 +227,12 @@ def __init__( "expired_observers": 0, "notices_expired": 0, "internal_errors": 0, + "labels_rejected": 0, } self.stop_requested = False self.stop_reason: str | None = None # Clear whatever a previous coordinator left under the same identity before publishing. - self.transport.set_desired(IDLE_READY, force=True) + self.transport.publish((), force=True) self.transport.tick() # ---- generations ---------------------------------------------------------------------- @@ -298,7 +331,8 @@ def op_snapshot(self, request: dict) -> dict: coverage = request.get("coverage") if coverage not in (COVERAGE_COMPLETE, COVERAGE_UNKNOWN): raise ProtocolError("bad_request", "coverage must be complete or unknown") - observations = parse_observations(request.get("observations", []), self.limits.max_observations) + observations, labels_rejected = parse_observations(request.get("observations", []), self.limits.max_observations) + self.counters["labels_rejected"] += labels_rejected diag = parse_diag(request.get("diag")) now = self.clock.monotonic() @@ -344,6 +378,8 @@ def op_snapshot(self, request: dict) -> dict: observer.diag = diag renewed = False if coverage == COVERAGE_COMPLETE: + self.apply_counter += 1 + observer.applied = self.apply_counter self.apply_observations(observer, observations, now) observer.expires_at = now + self.limits.lease observer.uncertain = False @@ -359,8 +395,8 @@ def op_snapshot(self, request: dict) -> dict: "activated": activated, "renewed": renewed, "lease_remaining": round(max(0.0, observer.expires_at - now), 3), - "desired": self.desired, - "delivery": self.delivery_summary(), + "rows": self.row_counts(), + "delivery": self.transport.delivery_summary(), } observer.last_ack = ack return dict(ack) @@ -385,7 +421,13 @@ def op_disable(self, _request: dict) -> dict: self.log(f"could not persist the disabled latch: {type(exc).__name__}") self.recompute(self.clock.monotonic()) self.log("disabled: observers revoked, neutral requested") - return {"disabled": True, "persisted": persisted, "desired": self.desired, "delivery": self.delivery_summary()} + return { + "disabled": True, + "persisted": persisted, + "rows": self.row_counts(), + "summary": self.rows_summary(), + "delivery": self.transport.delivery_summary(), + } def op_enable(self, _request: dict) -> dict: self.disabled = False @@ -400,42 +442,42 @@ def op_enable(self, _request: dict) -> dict: def op_resync(self, _request: dict) -> dict: self.recompute(self.clock.monotonic()) - self.transport.set_desired(self.desired, force=True) + self.transport.publish(self.rows, force=True) self.transport.tick() - return {"desired": self.desired, "delivery": self.delivery_summary()} + return {"rows": self.row_counts(), "summary": self.rows_summary(), "delivery": self.transport.delivery_summary()} # ---- state ---------------------------------------------------------------------------- - def apply_observations(self, observer: ObserverState, observations: dict[str, Observation], now: float) -> None: + def apply_observations(self, observer: ObserverState, observations: dict[RowKey, Observation], now: float) -> None: """A complete snapshot replaces the observer's observations; a notice's deadline is fixed when first seen.""" - for pane, obs in observations.items(): - track = observer.notices.get(pane) + for key, obs in observations.items(): + track = observer.notices.get(key) if notice_clears(obs.state): # The pane resumed: whatever notice it had, or arrives with, can never show later. if track is not None: track.voided = True if obs.notice_id is not None and (track is None or track.notice_id != obs.notice_id): if track is not None: - self._retire_notice(observer, pane, track.notice_id) - observer.notices[pane] = NoticeTrack(obs.notice_id, obs.notice_kind or NOTICE_FAILED, now, voided=True) + self._retire_notice(observer, key, track.notice_id) + observer.notices[key] = NoticeTrack(obs.notice_id, obs.notice_kind or NOTICE_FAILED, now, voided=True) continue if obs.notice_id is None: continue # an observation without a notice leaves any track inert; re-inclusion cannot restart it if track is None or track.notice_id != obs.notice_id: if track is not None: - self._retire_notice(observer, pane, track.notice_id) + self._retire_notice(observer, key, track.notice_id) track = NoticeTrack(obs.notice_id, obs.notice_kind or NOTICE_FAILED, now) - if (pane, obs.notice_id) in observer.retired_notices: + if (key, obs.notice_id) in observer.retired_notices: track.voided = True - observer.notices[pane] = track - for pane in [pane for pane in observer.notices if pane not in observations]: - self._retire_notice(observer, pane, observer.notices[pane].notice_id) - del observer.notices[pane] + observer.notices[key] = track + for key in [key for key in observer.notices if key not in observations]: + self._retire_notice(observer, key, observer.notices[key].notice_id) + del observer.notices[key] observer.observations = observations - def _retire_notice(self, observer: ObserverState, pane: str, notice_id: str) -> None: - observer.retired_notices[(pane, notice_id)] = None - observer.retired_notices.move_to_end((pane, notice_id)) + def _retire_notice(self, observer: ObserverState, key: RowKey, notice_id: str) -> None: + observer.retired_notices[(key, notice_id)] = None + observer.retired_notices.move_to_end((key, notice_id)) while len(observer.retired_notices) > MAX_RETIRED_NOTICES: observer.retired_notices.popitem(last=False) @@ -446,7 +488,7 @@ def notice_active(self, observer: ObserverState, obs: Observation, now: float) - """Pure: the notice kind still inside its deadline for this observation, else None.""" if obs.notice_id is None: return None - track = observer.notices.get(obs.pane) + track = observer.notices.get(obs.key) if track is None or track.voided or track.notice_id != obs.notice_id: return None if now >= track.started + self._duration(track.kind): @@ -488,17 +530,16 @@ def observe_clock(self) -> None: def recompute(self, now: float) -> None: self.expire(now) self._sweep_notices(now) - modes: list[str | None] = [] + contributions = [] for observer in self.observers.values(): if observer.uncertain: continue for obs in observer.observations.values(): - modes.append(pane_mode(obs.state, self.notice_active(observer, obs, now))) - desired = IDLE_READY if self.disabled else aggregate(modes) - if desired != self.desired: - self.log(f"desired {self.desired} -> {desired}") - self.desired = desired - self.transport.set_desired(desired) + mode = pane_mode(obs.state, self.notice_active(observer, obs, now)) + if mode is not None: + contributions.append((obs.key, mode, observer.applied, obs.label)) + self.rows = () if self.disabled else reduce_rows(contributions) + self.transport.publish(self.rows) if self.observers: self.empty_since = None elif self.empty_since is None: @@ -511,7 +552,7 @@ def next_notice_deadline(self) -> float | None: for obs in observer.observations.values(): if obs.notice_id is None or obs.state != STATE_IDLE: continue - track = observer.notices.get(obs.pane) + track = observer.notices.get(obs.key) if track is None or track.voided or track.notice_id != obs.notice_id: continue deadlines.append(track.started + self._duration(track.kind)) @@ -527,16 +568,11 @@ def tick(self) -> str | None: if self.observers: return None idle_for = now - (self.empty_since if self.empty_since is not None else now) - needs_neutral = [ - family - for family in self.transport.families - if family.delivered_mode not in (None, IDLE_READY) - or (family.delivered_mode is None and family.pending and family.receiver_present()) - ] + needs_neutral = self.transport.undelivered_neutral() if not needs_neutral and idle_for >= self.limits.exit_grace: return "exit" if idle_for >= self.limits.final_grace: - self.log("final grace elapsed with undelivered neutral: " + ", ".join(f.name for f in needs_neutral)) + self.log("final grace elapsed with undelivered neutral: " + ", ".join(needs_neutral)) return "exit" return None @@ -567,16 +603,23 @@ def shutdown(self) -> None: for observer in list(self.observers.values()): self._note_retired(observer.generation, "shutdown") self.observers.clear() - self.transport.set_desired(IDLE_READY, force=not self.transport.all_delivered(IDLE_READY)) + self.rows = () + self.transport.publish((), force=not self.transport.neutral_delivered()) self.transport.tick(immediate=True) # ---- reporting ------------------------------------------------------------------------ - def delivery_summary(self) -> dict: - return { - family.name: {"mode": family.delivered_mode, "pending": family.pending, "error": family.last_error} - for family in self.transport.families - } + def row_counts(self) -> dict[str, int]: + counts: dict[str, int] = {} + for row in self.rows: + counts[row.mode] = counts.get(row.mode, 0) + 1 + return {mode: counts[mode] for mode in MODES if mode in counts} + + def rows_summary(self) -> str: + if not self.rows: + return "no rows" + counts = ", ".join(f"{mode} {count}" for mode, count in self.row_counts().items()) + return f"{len(self.rows)} rows: {counts}" def status(self) -> dict: now = self.clock.monotonic() @@ -611,7 +654,9 @@ def status(self) -> dict: "started_at": iso_utc(self.started_wall), "uptime_seconds": round(now - self.started_at, 3), "disabled": self.disabled, - "desired": self.desired, + "rows": self.row_counts(), + "rows_total": len(self.rows), + "rows_labelled": sum(row.label is not None for row in self.rows), "session_id": self.transport.session_id, "observers": observers, "tokens_outstanding": len(self.tokens), diff --git a/tern_sidepulse/doctor.py b/tern_sidepulse/doctor.py index 2222e76..f09419d 100644 --- a/tern_sidepulse/doctor.py +++ b/tern_sidepulse/doctor.py @@ -73,11 +73,14 @@ def run_doctor(settings: Settings, window_diag: dict | None = None, window_key: _check(checks, "coordinator", "warn" if exc.reason == "not_running" else "error", f"not running ({exc.reason}); it starts with the next window snapshot") if status is not None: observers = status.get("observers", []) + modes = ", ".join(f"{mode} {count}" for mode, count in status.get("rows", {}).items()) or "none" _check( checks, "coordinator", "ok", - f"pid {status.get('pid')} epoch {status.get('epoch')} up {status.get('uptime_seconds')}s, desired {status.get('desired')}, {len(observers)} observer(s), disabled={status.get('disabled')}", + f"pid {status.get('pid')} epoch {status.get('epoch')} up {status.get('uptime_seconds')}s, " + f"rows {status.get('rows_total')} ({modes}), {status.get('rows_labelled')} labelled, " + f"{len(observers)} observer(s), disabled={status.get('disabled')}", ) if window_key is not None: mine = f"{os.getppid()}:{window_key}" diff --git a/tern_sidepulse/limits.py b/tern_sidepulse/limits.py index ef9d38b..ff9f76e 100644 --- a/tern_sidepulse/limits.py +++ b/tern_sidepulse/limits.py @@ -21,7 +21,7 @@ class Limits: max_observers: int = 64 max_observations: int = 512 max_tokens: int = 256 - max_request_bytes: int = 256 * 1024 + max_request_bytes: int = 1024 * 1024 read_deadline: float = 2.0 def to_dict(self) -> dict: diff --git a/tern_sidepulse/reducer.py b/tern_sidepulse/reducer.py index 50aeb08..15ce7c5 100644 --- a/tern_sidepulse/reducer.py +++ b/tern_sidepulse/reducer.py @@ -1,11 +1,9 @@ -"""Status semantics: Tern observations → one SidePulse mode. - -Applied per observer and then across observers. Adding the same observation twice never -changes the result: this is display-level duplicate tolerance, not cross-window identity. -""" +"""Tern observations → per-pane rows (mode + label).""" from __future__ import annotations +import re from dataclasses import dataclass +from typing import Iterable # SidePulse modes this bridge emits, highest priority first. BLOCKED_ERROR = "blocked_error" @@ -28,6 +26,10 @@ NOTICE_FAILED = "failed" NOTICE_KINDS = frozenset({NOTICE_DONE, NOTICE_FAILED}) +RowKey = tuple[str, str] +LABEL_MAX_CHARS = 96 +_LABEL_DROPPED = re.compile("[\x00-\x1f\x7f-\x9f\ud800-\udfff\ue000-\uf8ff\U000f0000-\U0010ffff]") + @dataclass(frozen=True) class Observation: @@ -35,6 +37,40 @@ class Observation: state: str notice_id: str | None = None notice_kind: str | None = None + host: str = "local" + label: str | None = None + + @property + def key(self) -> RowKey: + return self.host, self.pane + + +@dataclass(frozen=True) +class Row: + host: str + pane: str + mode: str + label: str | None + + +def sanitize_label(raw: str) -> str | None: + """Keep bounded display text without status glyphs, controls or lone surrogates.""" + text = _LABEL_DROPPED.sub("", " ".join(raw.split())) + text = " ".join(text.split())[:LABEL_MAX_CHARS].rstrip() + return text or None + + +def reduce_rows(contributions: Iterable[tuple[RowKey, str, int, str | None]]) -> tuple[Row, ...]: + """Deduplicate row keys, keeping the highest mode and newest non-empty label.""" + reduced: dict[RowKey, tuple[str, int, str | None]] = {} + for key, mode, order, label in contributions: + best_mode, label_order, best_label = reduced.get(key, (mode, -1, None)) + if MODE_PRIORITY[mode] < MODE_PRIORITY[best_mode]: + best_mode = mode + if label is not None and order > label_order: + label_order, best_label = order, label + reduced[key] = best_mode, label_order, best_label + return tuple(Row(host, pane, mode, label) for (host, pane), (mode, _, label) in sorted(reduced.items())) def pane_mode(state: str, active_notice_kind: str | None) -> str | None: @@ -59,11 +95,3 @@ def pane_mode(state: str, active_notice_kind: str | None) -> str | None: def notice_clears(state: str) -> bool: """Working or waiting states clear a pane's outcome notice at once.""" return state in (STATE_WORKING, STATE_WAITING) - - -def aggregate(modes: list[str | None]) -> str: - best = IDLE_READY - for mode in modes: - if mode is not None and MODE_PRIORITY[mode] < MODE_PRIORITY[best]: - best = mode - return best diff --git a/tern_sidepulse/transport.py b/tern_sidepulse/transport.py index 2c22071..a5e01ed 100644 --- a/tern_sidepulse/transport.py +++ b/tern_sidepulse/transport.py @@ -1,5 +1,6 @@ """SidePulse wire contract and per-receiver-family delivery with bounded retry. +This module owns the reduction of per-pane rows to one mode and dies with the hook protocol. Verified against the inspected SidePulse revision (``docs/compatibility.md``): UTF-8 JSON on an ``AF_UNIX``/``SOCK_STREAM`` socket, one object per connection, framed by closing the write side. The envelope is ``{"provider": "omp", "line": {...}}``; the receiver reads to EOF and @@ -14,11 +15,11 @@ from dataclasses import dataclass, field from datetime import datetime, timezone from pathlib import Path -from typing import Callable +from typing import Callable, Iterable from . import VERSION from .clock import Clock -from .reducer import BLOCKED_ERROR, COMPLETED, IDLE_READY, MODES, WAITING_FOR_INPUT, WORKING +from .reducer import BLOCKED_ERROR, COMPLETED, IDLE_READY, MODE_PRIORITY, MODES, WAITING_FOR_INPUT, WORKING, Row PROVIDER = "omp" SEND_TIMEOUT_SECONDS = 0.2 # upstream's per-attempt deadline @@ -43,6 +44,15 @@ TITLE = "OMP in Tern" +def combined_mode(rows: Iterable[Row]) -> str: + """The hook protocol's one display mode, neutral when no rows contribute.""" + best = IDLE_READY + for row in rows: + if MODE_PRIORITY[row.mode] < MODE_PRIORITY[best]: + best = row.mode + return best + + def iso_utc(wall: float) -> str: return datetime.fromtimestamp(wall, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z" @@ -158,6 +168,12 @@ def _log(self, message: str) -> None: if self.log: self.log(message) + def publish(self, rows: Iterable[Row], *, force: bool = False) -> None: + mode = combined_mode(rows) + if mode != self.desired: + self._log(f"desired {self.desired} -> {mode}") + self.set_desired(mode, force=force) + def set_desired(self, mode: str, force: bool = False) -> bool: """Point every family at ``mode``. A change goes out promptly; a family already in backoff keeps its schedule.""" changed = mode != self.desired @@ -255,6 +271,23 @@ def _detect_receiver_change(self, family: Family, now: float) -> None: def all_delivered(self, mode: str) -> bool: return all(family.delivered_mode == mode and not family.pending for family in self.families) + def undelivered_neutral(self) -> list[str]: + return [ + family.name + for family in self.families + if family.delivered_mode not in (None, IDLE_READY) + or (family.delivered_mode is None and family.pending and family.receiver_present()) + ] + + def neutral_delivered(self) -> bool: + return self.all_delivered(IDLE_READY) + + def delivery_summary(self) -> dict: + return { + family.name: {"mode": family.delivered_mode, "pending": family.pending, "error": family.last_error} + for family in self.families + } + def next_due(self) -> float | None: due = [family.next_attempt_at for family in self.families if family.pending] return min(due) if due else None diff --git a/tests/helpers.py b/tests/helpers.py index bd47b04..d955136 100644 --- a/tests/helpers.py +++ b/tests/helpers.py @@ -208,7 +208,14 @@ def advance(coordinator: Coordinator, clock: FakeClock, seconds: float, step: fl remaining -= chunk result = coordinator.tick() or result return result - return coordinator, clock, sender, logs, latch + + +def combined_mode(coordinator: Coordinator) -> str: + return coordinator.transport.desired + + +def rows(coordinator: Coordinator) -> list[tuple[str, str, str, str | None]]: + return [(row.host, row.pane, row.mode, row.label) for row in coordinator.rows] OBS = {"parent_pid": 4242, "window_key": ""} @@ -240,19 +247,33 @@ def activate(coordinator: Coordinator, observations: list, observer: dict | None return reg["generation"], reg["epoch"] -def working(pane: int) -> dict: - return {"pane": pane, "state": "working"} +def working(pane: int, *, host: str | None = None, label: str | None = None) -> dict: + obs = {"pane": pane, "state": "working"} + if host is not None: + obs["host"] = host + if label is not None: + obs["label"] = label + return obs -def idle(pane: int, notice_id: str | None = None, kind: str = "done") -> dict: +def idle(pane: int, notice_id: str | None = None, kind: str = "done", *, host: str | None = None, label: str | None = None) -> dict: obs: dict = {"pane": pane, "state": "idle"} if notice_id is not None: obs["notice"] = {"id": notice_id, "kind": kind} + if host is not None: + obs["host"] = host + if label is not None: + obs["label"] = label return obs -def waiting(pane: int) -> dict: - return {"pane": pane, "state": "waiting_input"} +def waiting(pane: int, *, host: str | None = None, label: str | None = None) -> dict: + obs = {"pane": pane, "state": "waiting_input"} + if host is not None: + obs["host"] = host + if label is not None: + obs["label"] = label + return obs def helper_argv(env: dict) -> list[str]: @@ -261,11 +282,11 @@ def helper_argv(env: dict) -> list[str]: return [sys.executable, *python_flags(Path(data) if data else None), str(BRIDGE)] -def run_bridge(args: list[str], stdin: dict | None, env: dict, timeout: float = 15.0) -> tuple[int, dict, str]: +def run_bridge(args: list[str], stdin: dict | None, env: dict, timeout: float = 15.0, *, raw_utf8: bool = False) -> tuple[int, dict, str]: """Run bridge.py in a subprocess; returns (code, parsed stdout, stderr). Non-JSON output becomes an error dict.""" proc = subprocess.run( [*helper_argv(env), *args], - input=json.dumps(stdin or {}).encode("utf-8"), + input=json.dumps(stdin or {}, ensure_ascii=not raw_utf8).encode("utf-8"), capture_output=True, env=env, timeout=timeout, diff --git a/tests/test_cli.py b/tests/test_cli.py index 6311ad8..5a4b0f7 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -61,7 +61,7 @@ def test_register_spawns_a_detached_coordinator_and_injects_identity(self): self.assertTrue(self.ui.wait_for("idle_ready"), "startup neutral reaches the receiver") code, ack, _ = run_bridge(["snapshot"], {"observer": {"window_key": "w2"}, "epoch": reg["epoch"], "generation": reg["generation"], "seq": 1, "coverage": "complete", "observations": [{"pane": 7, "state": "waiting_input"}]}, self.env) self.assertTrue(ack["accepted"], ack) - self.assertEqual(ack["desired"], "waiting_for_input") + self.assertEqual(ack["rows"], {"waiting_for_input": 1}) self.assertTrue(self.ui.wait_for("waiting_for_input")) self.assertTrue(self.svc.wait_for("waiting_for_input")) diff --git a/tests/test_e2e.py b/tests/test_e2e.py index 0bbd132..181e3a9 100644 --- a/tests/test_e2e.py +++ b/tests/test_e2e.py @@ -88,6 +88,29 @@ def test_other_family_down_then_back(self): self.svc.start() self.assertTrue(self.svc.wait_for("working", timeout=4), "the returning service gets the current mode without waiting out the full backoff") + def test_max_size_labelled_snapshot_is_accepted(self): + code, reg, err = run_bridge(["register"], {}, self.env) + self.assertEqual(code, 0, err) + self.assertTrue(reg["ok"], reg) + observations = [{"pane": i, "state": "working", "host": "local", "label": "é" * 128} for i in range(512)] + code, ack, err = run_bridge(["snapshot"], { + "epoch": reg["epoch"], + "generation": reg["generation"], + "seq": 1, + "coverage": "complete", + "observations": observations, + }, self.env, raw_utf8=True) + self.assertEqual(code, 0, err) + self.assertTrue(ack["ok"], ack) + self.assertEqual(ack["rows"], {"working": 512}) + self.assertTrue(self.ui.wait_for("working")) + self.assertTrue(self.svc.wait_for("working")) + code, out, err = run_bridge(["status"], None, self.env) + self.assertEqual(code, 0, err) + self.assertTrue(out["ok"], out) + self.assertEqual(out["status"]["rows_total"], 512) + self.assertEqual(out["status"]["rows_labelled"], 512) + @unittest.skipUnless(os.environ.get("TERN_SIDEPULSE_SLOW_TESTS"), "set TERN_SIDEPULSE_SLOW_TESTS=1 for the default-limits timing check") def test_default_limits_neutral_within_20s(self): env = subprocess_env(self.tmp, self.ui.path, self.svc.path, None) diff --git a/tests/test_fencing.py b/tests/test_fencing.py index 543e170..b6ac513 100644 --- a/tests/test_fencing.py +++ b/tests/test_fencing.py @@ -1,6 +1,6 @@ import unittest -from tests.helpers import OBS, activate, idle, make_coordinator, register, snapshot, working +from tests.helpers import OBS, activate, combined_mode, idle, make_coordinator, register, snapshot, working from tern_sidepulse import VERSION from tern_sidepulse.coordinator import ProtocolError, decode_request @@ -29,7 +29,7 @@ def test_later_activation_wins_and_older_token_becomes_stale(self): self.assertEqual(late["error"], "stale_generation") again = snapshot(c, first["generation"], first["epoch"], 6, [idle(1)]) self.assertEqual(again["error"], "expired_generation") - self.assertEqual(c.desired, "working") + self.assertEqual(combined_mode(c), "working") def test_unactivated_higher_token_cannot_block_live_generation(self): c, _, _, _, _ = make_coordinator() @@ -37,7 +37,7 @@ def test_unactivated_higher_token_cannot_block_live_generation(self): register(c) # a dropped VM's registration: allocated, never activated ack = snapshot(c, gen, epoch, 2, [idle(1)]) self.assertTrue(ack["accepted"]) - self.assertEqual(c.desired, "idle_ready") + self.assertEqual(combined_mode(c), "idle_ready") def test_replacing_a_generation_rejects_the_old_one_even_with_higher_seq(self): c, _, _, _, _ = make_coordinator() @@ -45,7 +45,7 @@ def test_replacing_a_generation_rejects_the_old_one_even_with_higher_seq(self): reg = register(c) snapshot(c, reg["generation"], epoch, 1, [idle(1)]) self.assertEqual(snapshot(c, gen, epoch, 50, [working(1)])["error"], "expired_generation") - self.assertEqual(c.desired, "idle_ready") + self.assertEqual(combined_mode(c), "idle_ready") def test_sequence_rules(self): c, clock, _, _, _ = make_coordinator() @@ -54,30 +54,32 @@ def test_sequence_rules(self): dup = snapshot(c, gen, epoch, 1, [idle(1)]) self.assertTrue(dup["duplicate"]) self.assertFalse(dup["renewed"]) - self.assertEqual(c.desired, "working", "a duplicate seq carries no new content") + self.assertEqual(combined_mode(c), "working", "a duplicate seq carries no new content") self.assertEqual(snapshot(c, gen, epoch, 0, [idle(1)])["error"], "bad_request") snapshot(c, gen, epoch, 3, [idle(1)]) self.assertEqual(snapshot(c, gen, epoch, 2, [working(1)])["error"], "seq_not_increasing") - self.assertEqual(c.desired, "idle_ready") + self.assertEqual(combined_mode(c), "idle_ready") def test_expired_lease_retires_the_generation(self): c, clock, _, _, _ = make_coordinator(Limits(lease=5)) gen, epoch = activate(c, [working(1)]) clock.advance(6) self.assertEqual(snapshot(c, gen, epoch, 2, [working(1)])["error"], "expired_generation") - self.assertEqual(c.desired, "idle_ready") + self.assertEqual(combined_mode(c), "idle_ready") def test_disable_revokes_everything_until_enable(self): c, _, sender, _, latch = make_coordinator() gen, epoch = activate(c, [working(1)]) self.assertTrue(c.handle({"schema": 1, "op": "disable"})["disabled"]) self.assertEqual(latch, [True]) - self.assertEqual(c.desired, "idle_ready") + self.assertEqual(combined_mode(c), "idle_ready") + self.assertEqual(c.rows, ()) + self.assertEqual(c.status()["rows"], {}) self.assertEqual(snapshot(c, gen, epoch, 2, [working(1)])["error"], "disabled") self.assertEqual(register(c)["error"], "disabled") c.handle({"schema": 1, "op": "enable"}) activate(c, [working(1)]) - self.assertEqual(c.desired, "working") + self.assertEqual(combined_mode(c), "working") self.assertEqual(sender.modes_for("relay-events.sock")[-2:], ["idle_ready", "working"]) def test_token_eviction_and_bounded_bookkeeping(self): diff --git a/tests/test_leases.py b/tests/test_leases.py index 47a4275..4b79f3e 100644 --- a/tests/test_leases.py +++ b/tests/test_leases.py @@ -1,6 +1,6 @@ import unittest -from tests.helpers import activate, advance, idle, make_coordinator, register, snapshot, working +from tests.helpers import activate, advance, combined_mode, idle, make_coordinator, register, snapshot, working from tern_sidepulse.limits import Limits @@ -12,25 +12,25 @@ def test_unknown_coverage_never_renews_but_keeps_prior_observations(self): advance(c, clock, 10) ack = snapshot(c, gen, epoch, 2, [], coverage="unknown") self.assertFalse(ack["renewed"]) - self.assertEqual(c.desired, "working") + self.assertEqual(combined_mode(c), "working") advance(c, clock, 4) - self.assertEqual(c.desired, "working") + self.assertEqual(combined_mode(c), "working") advance(c, clock, 1.5) - self.assertEqual(c.desired, "idle_ready", "the original 15 s lease expired despite the heartbeat") + self.assertEqual(combined_mode(c), "idle_ready", "the original 15 s lease expired despite the heartbeat") def test_genuine_empty_snapshot_clears_now(self): c, _, _, _, _ = make_coordinator() gen, epoch = activate(c, [working(1)]) snapshot(c, gen, epoch, 2, []) - self.assertEqual(c.desired, "idle_ready") + self.assertEqual(combined_mode(c), "idle_ready") def test_vanished_window_expires_and_neutral_is_sent(self): c, clock, sender, _, _ = make_coordinator(Limits(lease=15, reaper=1)) activate(c, [working(1)]) advance(c, clock, 14) - self.assertEqual(c.desired, "working") + self.assertEqual(combined_mode(c), "working") advance(c, clock, 1) - self.assertEqual(c.desired, "idle_ready") + self.assertEqual(combined_mode(c), "idle_ready") self.assertEqual(sender.modes_for("events.sock")[-1], "idle_ready") self.assertEqual(c.counters["expired_observers"], 1) @@ -54,7 +54,7 @@ def test_neutral_retried_until_delivered_when_receiver_present_but_refusing(self activate(c, [working(1)]) sender.refuse = {"events.sock", "relay-events.sock"} advance(c, clock, 3) - self.assertEqual(c.desired, "idle_ready") + self.assertEqual(combined_mode(c), "idle_ready") # Both families still hold "working": the coordinator must not leave after the short grace. self.assertIsNone(advance(c, clock, 10)) sender.refuse = set() @@ -93,27 +93,28 @@ def test_startup_neutral_retried_while_a_present_receiver_refuses(self): class ClockDiscontinuityTest(unittest.TestCase): def test_wall_jump_makes_output_idle_before_the_first_request_after_wake(self): - c, clock, _, _, _ = make_coordinator(Limits(lease=15, done_notice=15)) + c, clock, sender, _, _ = make_coordinator(Limits(lease=15, done_notice=15)) other = {"parent_pid": 4242, "window_key": "2"} gen_a, epoch = activate(c, [idle(1, "1", "done")]) activate(c, [working(2)], observer=other) - self.assertEqual(c.desired, "working") + self.assertEqual(combined_mode(c), "working") clock.advance(1, wall_seconds=7200) # asleep for two hours; the monotonic clock paused # The first request after wake must not see pre-sleep state. ack = snapshot(c, gen_a, epoch, 2, [idle(1)]) - self.assertEqual(ack["desired"], "idle_ready") + self.assertEqual(ack["rows"], {"idle_ready": 1}) + self.assertEqual(sender.modes_for("events.sock")[-1], "idle_ready") self.assertEqual(c.discontinuities, 1) self.assertTrue(c.observers["4242:2"].uncertain) # Its own fresh snapshot restores the other window's work. snapshot(c, c.observers["4242:2"].generation, epoch, 2, [working(2)], observer=other) - self.assertEqual(c.desired, "working") + self.assertEqual(combined_mode(c), "working") def test_stalled_loop_also_counts(self): c, clock, _, _, _ = make_coordinator(Limits(lease=60, reaper=1, discontinuity=5)) activate(c, [working(1)]) clock.advance(30) c.tick() - self.assertEqual(c.desired, "idle_ready") + self.assertEqual(combined_mode(c), "idle_ready") self.assertEqual(c.discontinuities, 1) diff --git a/tests/test_notices.py b/tests/test_notices.py index 31c3576..ef05c5c 100644 --- a/tests/test_notices.py +++ b/tests/test_notices.py @@ -1,6 +1,6 @@ import unittest -from tests.helpers import activate, advance, idle, make_coordinator, register, snapshot, waiting +from tests.helpers import activate, advance, combined_mode, idle, make_coordinator, register, rows, snapshot, waiting, working from tern_sidepulse.limits import Limits @@ -9,66 +9,66 @@ class NoticeTest(unittest.TestCase): def test_fixed_deadline_despite_heartbeats(self): c, clock, sender, _, _ = make_coordinator(Limits(done_notice=15, failed_notice=30)) gen, epoch = activate(c, [idle(1, "1", "done")]) - self.assertEqual(c.desired, "completed") + self.assertEqual(combined_mode(c), "completed") seq = 1 for _ in range(14): advance(c, clock, 1) seq += 1 snapshot(c, gen, epoch, seq, [idle(1, "1", "done")]) - self.assertEqual(c.desired, "completed") + self.assertEqual(combined_mode(c), "completed") advance(c, clock, 1.01) - self.assertEqual(c.desired, "idle_ready") + self.assertEqual(combined_mode(c), "idle_ready") self.assertEqual(sender.modes_for("events.sock")[-2:], ["completed", "idle_ready"]) def test_failed_notice_lasts_longer_than_done(self): c, clock, _, _, _ = make_coordinator(Limits(done_notice=15, failed_notice=30)) gen, epoch = activate(c, [idle(1, "1", "failed")]) - self.assertEqual(c.desired, "blocked_error") + self.assertEqual(combined_mode(c), "blocked_error") seq = 1 for _ in range(5): # the window keeps heartbeating every 5 s advance(c, clock, 5) seq += 1 snapshot(c, gen, epoch, seq, [idle(1, "1", "failed")]) advance(c, clock, 4) - self.assertEqual(c.desired, "blocked_error") + self.assertEqual(combined_mode(c), "blocked_error") advance(c, clock, 1.5) - self.assertEqual(c.desired, "idle_ready") + self.assertEqual(combined_mode(c), "idle_ready") def test_omit_then_include_does_not_renew(self): c, clock, _, _, _ = make_coordinator(Limits(done_notice=15)) gen, epoch = activate(c, [idle(1, "1", "done")]) advance(c, clock, 10) snapshot(c, gen, epoch, 2, [idle(1)]) - self.assertEqual(c.desired, "idle_ready") + self.assertEqual(combined_mode(c), "idle_ready") advance(c, clock, 4) snapshot(c, gen, epoch, 3, [idle(1, "1", "done")]) - self.assertEqual(c.desired, "completed", "still inside the original 15 s window") + self.assertEqual(combined_mode(c), "completed", "still inside the original 15 s window") advance(c, clock, 1.5) - self.assertEqual(c.desired, "idle_ready", "the deadline was fixed when the notice was first accepted") + self.assertEqual(combined_mode(c), "idle_ready", "the deadline was fixed when the notice was first accepted") def test_working_voids_the_notice_for_good(self): c, _, _, _, _ = make_coordinator() gen, epoch = activate(c, [idle(1, "1", "done")]) snapshot(c, gen, epoch, 2, [{"pane": 1, "state": "working", "notice": {"id": "1", "kind": "done"}}]) - self.assertEqual(c.desired, "working") + self.assertEqual(combined_mode(c), "working") snapshot(c, gen, epoch, 3, [idle(1, "1", "done")]) - self.assertEqual(c.desired, "idle_ready", "a late heartbeat cannot turn a resumed pane green") + self.assertEqual(combined_mode(c), "idle_ready", "a late heartbeat cannot turn a resumed pane green") def test_waiting_clears_a_failure_notice(self): c, _, _, _, _ = make_coordinator() gen, epoch = activate(c, [idle(1, "1", "failed")]) snapshot(c, gen, epoch, 2, [waiting(1)]) - self.assertEqual(c.desired, "waiting_for_input") + self.assertEqual(combined_mode(c), "waiting_for_input") snapshot(c, gen, epoch, 3, [idle(1, "1", "failed")]) - self.assertEqual(c.desired, "idle_ready") + self.assertEqual(combined_mode(c), "idle_ready") def test_vanished_pane_drops_its_notice(self): c, _, _, _, _ = make_coordinator() gen, epoch = activate(c, [idle(1, "1", "done")]) snapshot(c, gen, epoch, 2, []) - self.assertEqual(c.desired, "idle_ready") + self.assertEqual(combined_mode(c), "idle_ready") snapshot(c, gen, epoch, 3, [idle(1, "1", "done")]) - self.assertEqual(c.desired, "idle_ready", "a notice retired with its pane never returns") + self.assertEqual(combined_mode(c), "idle_ready", "a notice retired with its pane never returns") def test_new_notice_id_gets_a_new_deadline(self): c, clock, _, _, _ = make_coordinator(Limits(done_notice=15)) @@ -76,7 +76,7 @@ def test_new_notice_id_gets_a_new_deadline(self): advance(c, clock, 14) snapshot(c, gen, epoch, 2, [idle(1, "2", "done")]) advance(c, clock, 10) - self.assertEqual(c.desired, "completed") + self.assertEqual(combined_mode(c), "completed") def test_notices_are_not_replayed_into_a_new_generation(self): c, clock, _, _, _ = make_coordinator(Limits(done_notice=15)) @@ -84,15 +84,15 @@ def test_notices_are_not_replayed_into_a_new_generation(self): advance(c, clock, 5) reg = register(c) snapshot(c, reg["generation"], reg["epoch"], 1, [idle(1)]) - self.assertEqual(c.desired, "idle_ready") + self.assertEqual(combined_mode(c), "idle_ready") # The new VM's counter restarts at "1": that is a fresh notice, shown fresh. snapshot(c, reg["generation"], reg["epoch"], 2, [idle(1, "1", "failed")]) - self.assertEqual(c.desired, "blocked_error") + self.assertEqual(combined_mode(c), "blocked_error") def test_late_completion_never_greens_an_active_pane(self): c, _, _, _, _ = make_coordinator() activate(c, [{"pane": 1, "state": "working", "notice": {"id": "1", "kind": "done"}}]) - self.assertEqual(c.desired, "working") + self.assertEqual(combined_mode(c), "working") def test_status_is_a_pure_read(self): c, clock, _, _, _ = make_coordinator(Limits(done_notice=15)) @@ -101,10 +101,11 @@ def test_status_is_a_pure_read(self): before = c.counters["notices_expired"] status = c.status() self.assertEqual(status["observers"][0]["active_notices"], []) + self.assertEqual(status["rows"], {"completed": 1}) self.assertEqual(c.counters["notices_expired"], before) - self.assertEqual(c.desired, "completed", "status must not change what the reaper has not yet applied") + self.assertEqual(combined_mode(c), "completed", "status must not change what the reaper has not yet applied") c.tick() - self.assertEqual(c.desired, "idle_ready") + self.assertEqual(combined_mode(c), "idle_ready") def test_bookkeeping_stays_bounded(self): c, _, _, _, _ = make_coordinator() @@ -121,7 +122,35 @@ def test_discontinuity_voids_notices(self): clock.advance(1, wall_seconds=600) c.tick() snapshot(c, gen, epoch, 2, [idle(1, "1", "done")]) - self.assertEqual(c.desired, "idle_ready") + self.assertEqual(combined_mode(c), "idle_ready") + + def test_notice_tracks_are_per_row_key(self): + c, _, _, _, _ = make_coordinator() + gen, epoch = activate(c, [idle(1, "1", host="host-a"), idle(1, host="host-b")]) + snapshot(c, gen, epoch, 2, [idle(1, "1", host="host-a"), working(1, host="host-b")]) + self.assertCountEqual(rows(c), [ + ("host-a", "1", "completed", None), + ("host-b", "1", "working", None), + ]) + snapshot(c, gen, epoch, 3, [idle(1, "1", host="host-a"), idle(1, "1", host="host-b")]) + self.assertCountEqual(rows(c), [ + ("host-a", "1", "completed", None), + ("host-b", "1", "completed", None), + ]) + + def test_notice_sets_only_its_own_row(self): + c, _, _, _, _ = make_coordinator() + gen, epoch = activate(c, [idle(1, "1", "failed", host="host-a"), idle(1, host="host-b")]) + self.assertCountEqual(rows(c), [ + ("host-a", "1", "blocked_error", None), + ("host-b", "1", "idle_ready", None), + ]) + snapshot(c, gen, epoch, 2, [idle(1, host="host-b")]) + snapshot(c, gen, epoch, 3, [idle(1, "1", "failed", host="host-a"), idle(1, "1", host="host-b")]) + self.assertCountEqual(rows(c), [ + ("host-a", "1", "idle_ready", None), + ("host-b", "1", "completed", None), + ]) if __name__ == "__main__": diff --git a/tests/test_privacy.py b/tests/test_privacy.py index dcc28ae..fb5f372 100644 --- a/tests/test_privacy.py +++ b/tests/test_privacy.py @@ -1,31 +1,91 @@ import json import unittest +from pathlib import Path +from unittest.mock import patch -from tests.helpers import SENTINEL, make_coordinator, register, snapshot +from tests.helpers import ( + SENTINEL, + FakeReceiver, + activate, + advance, + idle, + kill_coordinator, + make_coordinator, + register, + run_bridge, + short_tmpdir, + snapshot, + subprocess_env, + waiting, + working, +) +from tern_sidepulse.client import Settings from tern_sidepulse.doctor import run_doctor +from tern_sidepulse.limits import Limits +from tern_sidepulse.paths import DOCTOR_NAME, LOG_NAME + +SENTINEL_HOST = "SENTINEL-host-94b2-private" +RAW_LABEL = "\U000f1517 \t" + SENTINEL + "\n\uf412" + + +def doctor_settings(tmp: Path) -> Settings: + return Settings( + data_dir=tmp / "data", + runtime_dir=tmp / "rt", + ui_sockets=(tmp / "events.sock",), + service_sockets=(tmp / "relay-events.sock",), + limits=Limits(), + bridge_path=tmp / "bridge.py", + ) class PrivacyTest(unittest.TestCase): - def test_sentinel_in_any_client_field_never_leaves_the_coordinator(self): + def assert_private(self, *values): + text = "\n".join(value if isinstance(value, str) else json.dumps(value) for value in values) + self.assertNotIn(SENTINEL, text) + self.assertNotIn(SENTINEL_HOST, text) + + def test_sentinels_in_labels_hosts_and_unknown_fields_never_leave_the_coordinator(self): c, _, sender, logs, _ = make_coordinator() reg = register(c) - observations = [ - {"pane": 1, "state": "working", "cwd": SENTINEL, "title": SENTINEL, "last_message": SENTINEL, "notice": {"id": "1", "kind": "done", "text": SENTINEL}}, - ] + observations = [{ + "pane": 1, + "state": "working", + "host": SENTINEL_HOST, + "label": RAW_LABEL, + "cwd": SENTINEL, + "title": SENTINEL, + "model": SENTINEL, + "last_message": SENTINEL, + "notice": {"id": "1", "kind": "done", "text": SENTINEL}, + }] acks = [ snapshot(c, reg["generation"], reg["epoch"], 1, observations, prompt=SENTINEL, diag={"omp": 1, "leak": SENTINEL}), snapshot(c, reg["generation"], reg["epoch"], 2, [{"pane": 2, "state": SENTINEL}]), snapshot(c, reg["generation"], reg["epoch"], 3, [{"pane": 3, "state": "idle", "notice": {"id": "9", "kind": SENTINEL}}]), c.handle({"schema": 1, "op": SENTINEL}), c.handle({"schema": 1, "op": "register", "observer": {"parent_pid": 4242, "window_key": SENTINEL * 3}}), + c.handle({"schema": 1, "op": "status"}), ] status = c.status() - everything = json.dumps(acks) + json.dumps(status) + "\n".join(logs) - self.assertNotIn(SENTINEL, everything) + settings = doctor_settings(short_tmpdir("tsp-doc-private-")) + with patch("tern_sidepulse.doctor.request", return_value={"ok": True, "status": status}): + report = run_doctor(settings) + self.assertIsNotNone(report["report"]) + self.assert_private(acks, status, logs, report, Path(report["report"]).read_text(encoding="utf-8")) self.assertEqual(sender.modes_for("events.sock"), ["idle_ready", "working"]) + self.assertEqual(sender.modes_for("relay-events.sock"), ["idle_ready", "working"]) + + def test_label_is_held_in_memory_only(self): + c, _, _, _, _ = make_coordinator() + activate(c, [working(1, host=SENTINEL_HOST, label=RAW_LABEL)]) + self.assertEqual(len(c.rows), 1) + self.assertEqual(c.rows[0].label, SENTINEL) + self.assertEqual(c.rows[0].host, SENTINEL_HOST) + self.assert_private(c.status()) - def test_transport_payload_contains_only_status_metadata(self): + def test_hook_event_payload_never_carries_labels(self): c, _, sender, _, _ = make_coordinator() captured = [] original = sender.__call__ @@ -35,28 +95,152 @@ def spy(target, payload, timeout): return original(target, payload, timeout) c.transport.sender = spy - reg = register(c) - snapshot(c, reg["generation"], reg["epoch"], 1, [{"pane": 1, "state": "working", "cwd": SENTINEL}]) + gen, epoch = activate(c, [working(1, host=SENTINEL_HOST, label=RAW_LABEL)]) + for seq, obs in enumerate(( + waiting(1, host=SENTINEL_HOST, label=RAW_LABEL), + idle(1, "1", "failed", host=SENTINEL_HOST, label=RAW_LABEL), + idle(1, "2", host=SENTINEL_HOST, label=RAW_LABEL), + idle(1, host=SENTINEL_HOST, label=RAW_LABEL), + ), 2): + self.assertTrue(snapshot(c, gen, epoch, seq, [obs])["ok"]) self.assertTrue(captured) for payload in captured: - line = json.loads(payload)["line"] - self.assertEqual(set(line), {"hook_event_name", "session_id", "logged_at", "sidepulse_status", "agent_origin", "agent_origin_kind", "bridge", "prompt"}) - self.assertNotIn(SENTINEL, payload) + event = json.loads(payload) + self.assertEqual(set(event), {"provider", "line"}) + self.assertEqual(event["provider"], "omp") + line = event["line"] + expected = {"hook_event_name", "session_id", "logged_at", "sidepulse_status", "agent_origin", "agent_origin_kind", "bridge"} + if line["sidepulse_status"] == "working": + expected.add("prompt") + self.assertEqual(line["prompt"], "OMP in Tern") + self.assertEqual(set(line), expected) + self.assert_private(payload) + self.assertEqual(sender.modes_for("events.sock"), ["idle_ready", "working", "waiting_for_input", "blocked_error", "completed", "idle_ready"]) - def test_doctor_report_filters_window_diag(self): - from tests.helpers import short_tmpdir + def test_rejections_never_echo_labels_or_hosts(self): + c, _, _, logs, _ = make_coordinator() + reg = register(c) + responses = [] + for host in (SENTINEL_HOST + "\n", SENTINEL_HOST + "\ud800", SENTINEL_HOST * 10): + ack = snapshot(c, reg["generation"], reg["epoch"], 1, [working(1, host=host, label=RAW_LABEL)]) + self.assertEqual(ack["error"], "bad_request") + self.assertEqual(ack["detail"], "observation.host must be a short host key") + responses.append(ack) + for seq, label in enumerate((SENTINEL * 100, {"secret": SENTINEL}), 1): + ack = snapshot(c, reg["generation"], reg["epoch"], seq, [{"pane": 1, "state": "working", "host": SENTINEL_HOST, "label": label}]) + self.assertTrue(ack["ok"], ack) + self.assertIsNone(c.rows[0].label) + responses.append(ack) + self.assertEqual(c.counters["labels_rejected"], 2) + self.assert_private(responses, c.status(), logs) - from tern_sidepulse.client import Settings - from tern_sidepulse.limits import Limits + def test_lifecycle_logs_never_carry_labels_or_hosts(self): + c, clock, _, logs, _ = make_coordinator(Limits(lease=2)) + observation = idle(1, "1", host=SENTINEL_HOST, label=RAW_LABEL) + activate(c, [observation]) + activate(c, [observation]) # replacement + advance(c, clock, 2) # expiry + gen, epoch = activate(c, [observation]) + clock.advance(1, wall_seconds=600) + c.tick() + responses = [snapshot(c, gen, epoch, 2, [working(1, host=SENTINEL_HOST, label=RAW_LABEL)])] - tmp = short_tmpdir("tsp-doc-") - settings = Settings(data_dir=tmp / "data", runtime_dir=tmp / "rt", ui_sockets=(tmp / "events.sock",), service_sockets=(tmp / "relay-events.sock",), limits=Limits(), bridge_path=tmp / "bridge.py") - report = run_doctor(settings, {"omp": 2, "secret": SENTINEL, "pane_ids": [SENTINEL]}, window_key="") - text = json.dumps(report) - self.assertNotIn(SENTINEL, text) - self.assertEqual(report["window_diag"], {"omp": 2}) + def persist_failure(_flag): + raise OSError(13, SENTINEL) + + c.persist_disabled = persist_failure + responses.append(c.handle({"schema": 1, "op": "disable"})) + + def internal_failure(_request): + raise RuntimeError(SENTINEL + SENTINEL_HOST) + + c.op_status = internal_failure + responses.append(c.handle({"schema": 1, "op": "status"})) + self.assertEqual(c.counters["expired_observers"], 1) + self.assertEqual(c.discontinuities, 1) + self.assertFalse(responses[1]["persisted"]) + self.assertEqual(responses[2]["error"], "internal") + self.assertTrue(logs) + self.assert_private(responses, c.status(), logs) + + def test_doctor_report_filters_window_diag(self): + settings = doctor_settings(short_tmpdir("tsp-doc-")) + report = run_doctor(settings, {"omp": 2, "label_tab": 1, "label_title": SENTINEL, "secret": SENTINEL, "pane_ids": [SENTINEL]}, window_key="") + self.assert_private(report) + self.assertEqual(report["window_diag"], {"omp": 2, "label_tab": 1}) self.assertIn("socket delivery is not an LED check", report["summary"]) +class LabelPrivacyEndToEndTest(unittest.TestCase): + def test_status_doctor_log_and_receiver_never_carry_labels(self): + tmp = short_tmpdir("tsp-private-e2e-") + ui = FakeReceiver(tmp / "events.sock") + svc = FakeReceiver(tmp / "relay-events.sock") + ui.start() + svc.start() + env = subprocess_env(tmp, ui.path, svc.path, {"lease": 30, "reaper": 0.2, "exit_grace": 1, "final_grace": 5}) + outputs = [] + errors = [] + + def invoke(command, payload): + code, out, err = run_bridge([command], payload, env, raw_utf8=True) + outputs.append(out) + errors.append(err) + self.assertEqual(code, 0, err) + self.assertTrue(out["ok"], out) + return out + + try: + reg = invoke("register", {}) + ack = invoke("snapshot", { + "epoch": reg["epoch"], + "generation": reg["generation"], + "seq": 1, + "coverage": "complete", + "observations": [{ + "pane": 1, + "state": "working", + "host": SENTINEL_HOST, + "label": RAW_LABEL, + "cwd": SENTINEL, + "title": SENTINEL, + "last_message": SENTINEL, + "notice": {"id": "1", "kind": "done", "text": SENTINEL}, + }], + "prompt": SENTINEL, + "diag": {"omp": 1, "secret": SENTINEL}, + }) + self.assertEqual(ack["rows"], {"working": 1}) + self.assertTrue(ui.wait_for("working")) + self.assertTrue(svc.wait_for("working")) + status = invoke("status", None)["status"] + self.assertEqual(status["rows_total"], 1) + self.assertEqual(status["rows_labelled"], 1) + doctor = invoke("doctor", {"diag": {"omp": 1, "label_tab": 1, "secret": SENTINEL}}) + self.assertEqual(doctor["status"]["rows_labelled"], 1) + detail = next(check["detail"] for check in doctor["checks"] if check["id"] == "coordinator") + self.assertIn("rows 1 (working 1), 1 labelled, 1 observer(s), disabled=False", detail) + runtime = Path(env["TERN_SIDEPULSE_RUNTIME_DIR"]) + self.assertEqual(Path(doctor["report"]), runtime / DOCTOR_NAME) + surfaces = { + "stdout": json.dumps(outputs), + "stderr": "\n".join(errors), + "doctor.json": (runtime / DOCTOR_NAME).read_text(encoding="utf-8"), + "coordinator.log": (runtime / LOG_NAME).read_text(encoding="utf-8"), + "ui events": json.dumps(ui.events), + "service events": json.dumps(svc.events), + } + for surface, text in surfaces.items(): + with self.subTest(surface=surface): + self.assertNotIn(SENTINEL, text) + self.assertNotIn(SENTINEL_HOST, text) + self.assertEqual(ui.modes(), ["idle_ready", "working"]) + self.assertEqual(svc.modes(), ["idle_ready", "working"]) + finally: + kill_coordinator(env) + ui.stop() + svc.stop() + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_reducer.py b/tests/test_reducer.py index fe5e5df..51c608e 100644 --- a/tests/test_reducer.py +++ b/tests/test_reducer.py @@ -1,22 +1,15 @@ import unittest -from tests.helpers import activate, idle, make_coordinator, snapshot, waiting, working +from tests.helpers import activate, combined_mode, idle, make_coordinator, rows, snapshot, waiting, working -from tern_sidepulse.reducer import aggregate, pane_mode +from tern_sidepulse.reducer import pane_mode, reduce_rows class ReducerTest(unittest.TestCase): - def test_priority_order(self): - self.assertEqual(aggregate(["working", "waiting_for_input", "working", "working"]), "waiting_for_input") - self.assertEqual(aggregate(["completed", "working"]), "working") - self.assertEqual(aggregate(["blocked_error", "waiting_for_input"]), "blocked_error") - self.assertEqual(aggregate(["completed", "idle_ready"]), "completed") - self.assertEqual(aggregate([]), "idle_ready") - def test_withdrawn_states_contribute_nothing(self): for state in ("exited", "closed", "unknown"): self.assertIsNone(pane_mode(state, "done")) - self.assertEqual(aggregate([None, None]), "idle_ready") + self.assertEqual(reduce_rows([]), ()) def test_notice_never_outranks_live_work(self): self.assertEqual(pane_mode("working", "failed"), "working") @@ -25,29 +18,36 @@ def test_notice_never_outranks_live_work(self): self.assertEqual(pane_mode("idle", "failed"), "blocked_error") self.assertEqual(pane_mode("idle", None), "idle_ready") - def test_duplicates_are_idempotent(self): - self.assertEqual(aggregate(["working"]), aggregate(["working", "working", "working"])) - class ReductionThroughCoordinatorTest(unittest.TestCase): def test_one_waiting_plus_three_working_then_cleared(self): c, clock, sender, _, _ = make_coordinator() gen, epoch = activate(c, [working(1), working(2), working(3), waiting(4)]) - self.assertEqual(c.desired, "waiting_for_input") + self.assertEqual(combined_mode(c), "waiting_for_input") + self.assertCountEqual(rows(c), [ + ("local", "1", "working", None), + ("local", "2", "working", None), + ("local", "3", "working", None), + ("local", "4", "waiting_for_input", None), + ]) snapshot(c, gen, epoch, 2, [working(1), working(2), working(3), working(4)]) - self.assertEqual(c.desired, "working") + self.assertEqual(combined_mode(c), "working") + self.assertEqual(len(rows(c)), 4) + self.assertTrue(all(row[2] == "working" for row in rows(c))) self.assertEqual(sender.modes_for("events.sock"), ["idle_ready", "waiting_for_input", "working"]) def test_duplicate_pane_ids_in_one_snapshot_reduce_once(self): c, _, _, _, _ = make_coordinator() activate(c, [working(1), {"pane": 1, "state": "waiting_input"}]) # The first observation for a pane wins; the duplicate cannot escalate. - self.assertEqual(c.desired, "working") + self.assertEqual(combined_mode(c), "working") + self.assertEqual(rows(c), [("local", "1", "working", None)]) def test_startup_idle_is_not_success(self): c, _, sender, _, _ = make_coordinator() activate(c, [idle(1)]) - self.assertEqual(c.desired, "idle_ready") + self.assertEqual(combined_mode(c), "idle_ready") + self.assertEqual(rows(c), [("local", "1", "idle_ready", None)]) self.assertNotIn("completed", sender.modes_for("events.sock")) def test_disjoint_windows_both_contribute(self): @@ -55,12 +55,14 @@ def test_disjoint_windows_both_contribute(self): other = {"parent_pid": 4242, "window_key": "2"} gen_a, epoch = activate(c, [working(1)]) gen_b, _ = activate(c, [idle(900, "1", "failed")], observer=other) - self.assertEqual(c.desired, "blocked_error") + self.assertEqual(combined_mode(c), "blocked_error") + self.assertCountEqual(rows(c), [("local", "1", "working", None), ("local", "900", "blocked_error", None)]) # Window A refreshing its own (working) view cannot erase window B's error. snapshot(c, gen_a, epoch, 2, [working(1)]) - self.assertEqual(c.desired, "blocked_error") + self.assertEqual(combined_mode(c), "blocked_error") snapshot(c, gen_b, epoch, 2, [idle(900)], observer=other) - self.assertEqual(c.desired, "working") + self.assertEqual(combined_mode(c), "working") + self.assertCountEqual(rows(c), [("local", "1", "working", None), ("local", "900", "idle_ready", None)]) if __name__ == "__main__": diff --git a/tests/test_rows.py b/tests/test_rows.py new file mode 100644 index 0000000..cf08d41 --- /dev/null +++ b/tests/test_rows.py @@ -0,0 +1,297 @@ +import unittest + +from tests.helpers import activate, advance, combined_mode, idle, make_coordinator, register, rows, snapshot, waiting, working + +from tern_sidepulse.limits import Limits +from tern_sidepulse.reducer import LABEL_MAX_CHARS, Observation, Row, reduce_rows, sanitize_label + + +OTHER = {"parent_pid": 4242, "window_key": "2"} + + +class RowReductionTest(unittest.TestCase): + def test_same_key_keeps_highest_priority_mode(self): + contributions = [ + (("local", "1"), "completed", 1, None), + (("local", "1"), "working", 2, None), + (("local", "1"), "waiting_for_input", 3, None), + (("local", "1"), "idle_ready", 4, None), + ] + for items in (contributions, reversed(contributions)): + self.assertEqual(reduce_rows(items), (Row("local", "1", "waiting_for_input", None),)) + + def test_label_from_newest_contribution_with_label(self): + contributions = [ + (("local", "1"), "idle_ready", 9, "Newest"), + (("local", "1"), "working", 2, "Older"), + ] + self.assertEqual(reduce_rows(contributions), (Row("local", "1", "working", "Newest"),)) + + def test_newest_without_label_keeps_older_label(self): + self.assertEqual(reduce_rows([ + (("local", "1"), "working", 2, "Known"), + (("local", "1"), "idle_ready", 9, None), + ]), (Row("local", "1", "working", "Known"),)) + + def test_same_pane_two_hosts_two_rows(self): + self.assertCountEqual(reduce_rows([ + (("local", "1"), "working", 1, "Here"), + (("remote", "1"), "completed", 2, "There"), + ]), [Row("local", "1", "working", "Here"), Row("remote", "1", "completed", "There")]) + + +class LabelSanitizerTest(unittest.TestCase): + def test_omp_glyph_dropped(self): + for glyph in ("\U000f1517", "\uf412", "\ue000", "\uf8ff", "\U000f0000", "\U000fffff", "\U00100000", "\U0010ffff"): + with self.subTest(glyph=ascii(glyph)): + self.assertEqual(sanitize_label(glyph + " DOCS: Review docs"), "DOCS: Review docs") + + def test_glyph_variants_give_same_label(self): + labels = [sanitize_label(glyph + " Session title") for glyph in ("\U000f1517", "\U000f0837", "\uf412", "\uf407")] + self.assertEqual(labels, ["Session title"] * 4) + + def test_whitespace_mapped_before_controls_dropped(self): + self.assertEqual(sanitize_label("a\tb\x1b[31mc\x7f\x85d"), "a b[31mc d") + self.assertEqual(sanitize_label(" a\x1c\x1d\x1e\x1f\r\n\t\v\f\x85\xa0\u2028\u2029\u3000b "), "a b") + self.assertEqual(sanitize_label("a\x00\x01\x1b\x7f\x80\x9fb"), "ab") + self.assertEqual(sanitize_label("a \uf412 b"), "a b") + + def test_lone_surrogates_dropped(self): + label = sanitize_label("a\ud800 b\udfff") + self.assertEqual(label, "a b") + self.assertEqual(label.encode("utf-8"), b"a b") + + def test_cap_96_code_points_then_rstrip(self): + self.assertEqual(LABEL_MAX_CHARS, 96) + self.assertEqual(sanitize_label("é" * 128), "é" * 96) + self.assertEqual(sanitize_label("x" * 95 + " tail"), "x" * 95) + + def test_empty_after_sanitizing_is_none(self): + for raw in ("", " \t\r\n", "\U000f1517 \uf412\ud800\x00\x7f\x9f"): + with self.subTest(raw=ascii(raw)): + self.assertIsNone(sanitize_label(raw)) + + def test_non_ascii_text_kept(self): + self.assertEqual(sanitize_label(" Révision 日本語 e\u0301 🚀 "), "Révision 日本語 e\u0301 🚀") + + +class RowIdentityTest(unittest.TestCase): + def test_missing_host_is_local(self): + c, _, _, _, _ = make_coordinator() + activate(c, [working(1), {"pane": 2, "state": "idle", "host": None}, working(3, host="local")]) + self.assertCountEqual(rows(c), [ + ("local", "1", "working", None), + ("local", "2", "idle_ready", None), + ("local", "3", "working", None), + ]) + self.assertEqual(Observation("1", "working").key, ("local", "1")) + + def test_same_pane_on_two_hosts_is_two_rows(self): + c, _, _, _, _ = make_coordinator() + activate(c, [working(1, host="local"), waiting(1, host="sf-studio.tailfb479a.ts.net")]) + self.assertCountEqual(rows(c), [ + ("local", "1", "working", None), + ("sf-studio.tailfb479a.ts.net", "1", "waiting_for_input", None), + ]) + self.assertEqual(combined_mode(c), "waiting_for_input") + + def test_duplicate_key_in_snapshot_keeps_first(self): + c, _, _, _, _ = make_coordinator() + activate(c, [working(1, label="First"), {"pane": "1", "host": "local", "state": "waiting_input", "label": "Second"}]) + self.assertEqual(rows(c), [("local", "1", "working", "First")]) + + def test_withdrawn_states_make_no_row(self): + c, _, _, _, _ = make_coordinator() + activate(c, [{"pane": i, "state": state, "label": "Withdrawn"} for i, state in enumerate(("exited", "closed", "unknown"))]) + self.assertEqual(c.rows, ()) + self.assertEqual(combined_mode(c), "idle_ready") + + +class CrossObserverTest(unittest.TestCase): + def test_same_key_two_windows_one_row_higher_mode(self): + c, _, sender, _, _ = make_coordinator() + activate(c, [working(1, label="First")]) + activate(c, [waiting(1, label="Second")], observer=OTHER) + self.assertEqual(rows(c), [("local", "1", "waiting_for_input", "Second")]) + self.assertEqual(sender.modes_for("events.sock"), ["idle_ready", "working", "waiting_for_input"]) + + def test_moving_session_never_doubles(self): + c, _, sender, _, _ = make_coordinator() + gen_a, epoch = activate(c, [working(1)]) + gen_b, _ = activate(c, [working(1)], observer=OTHER) + self.assertEqual(rows(c), [("local", "1", "working", None)]) + snapshot(c, gen_a, epoch, 2, []) + self.assertEqual(rows(c), [("local", "1", "working", None)]) + snapshot(c, gen_b, epoch, 2, [], observer=OTHER) + self.assertEqual(c.rows, ()) + self.assertEqual(sender.modes_for("events.sock"), ["idle_ready", "working", "idle_ready"]) + + def test_uncertain_observer_contributes_no_rows(self): + c, clock, _, _, _ = make_coordinator() + activate(c, [working(1, label="Stale")]) + gen_b, epoch = activate(c, [idle(2, label="Other")], observer=OTHER) + clock.advance(1, wall_seconds=600) + c.tick() + self.assertEqual(c.rows, ()) + self.assertEqual(combined_mode(c), "idle_ready") + snapshot(c, gen_b, epoch, 2, [idle(1, label="Fresh")], observer=OTHER) + self.assertEqual(rows(c), [("local", "1", "idle_ready", "Fresh")]) + + def test_expired_observer_withdraws_only_its_rows(self): + c, clock, _, _, _ = make_coordinator(Limits(lease=10)) + activate(c, [working(1, label="Older shared"), working(2, label="Expires")]) + advance(c, clock, 5) + activate(c, [waiting(1, label="Survives"), idle(3)], observer=OTHER) + advance(c, clock, 5) + self.assertEqual(len(c.observers), 1) + self.assertCountEqual(rows(c), [("local", "1", "waiting_for_input", "Survives"), ("local", "3", "idle_ready", None)]) + + def test_notice_in_one_window_never_outranks_work_in_another(self): + c, _, sender, _, _ = make_coordinator() + gen_a, epoch = activate(c, [working(1)]) + activate(c, [idle(1, "1", "done")], observer=OTHER) + self.assertEqual(rows(c), [("local", "1", "working", None)]) + snapshot(c, gen_a, epoch, 2, []) + self.assertEqual(rows(c), [("local", "1", "completed", None)]) + self.assertEqual(sender.modes_for("events.sock"), ["idle_ready", "working", "completed"]) + + +class LabelPrecedenceTest(unittest.TestCase): + def test_newest_complete_snapshot_wins(self): + c, _, _, _, _ = make_coordinator() + gen_a, epoch = activate(c, [working(1, label="First")]) + gen_b, _ = activate(c, [idle(1, label="Second")], observer=OTHER) + self.assertEqual(rows(c), [("local", "1", "working", "Second")]) + snapshot(c, gen_a, epoch, 2, [working(1, label="Renamed")]) + self.assertEqual(rows(c), [("local", "1", "working", "Renamed")]) + snapshot(c, gen_b, epoch, 2, [idle(1)], observer=OTHER) + self.assertEqual(rows(c), [("local", "1", "working", "Renamed")]) + snapshot(c, gen_b, epoch, 3, [idle(1, label="Newest")], observer=OTHER) + self.assertEqual(rows(c), [("local", "1", "working", "Newest")]) + snapshot(c, gen_a, epoch, 3, [working(1)]) + self.assertEqual(rows(c), [("local", "1", "working", "Newest")]) + snapshot(c, gen_b, epoch, 4, [], observer=OTHER) + self.assertEqual(rows(c), [("local", "1", "working", None)]) + + def test_unknown_coverage_never_changes_labels(self): + c, _, _, _, _ = make_coordinator() + gen, epoch = activate(c, [working(1, label="Older complete")]) + activate(c, [idle(1, label="Newest complete")], observer=OTHER) + ack = snapshot(c, gen, epoch, 2, [waiting(1, label="Unknown")], coverage="unknown") + self.assertTrue(ack["ok"], ack) + self.assertFalse(ack["renewed"]) + self.assertEqual(rows(c), [("local", "1", "working", "Newest complete")]) + + def test_fenced_snapshot_never_changes_labels(self): + c, _, _, _, _ = make_coordinator() + stale = register(c) + gen, epoch = activate(c, [working(1, label="Accepted")]) + snapshot(c, gen, epoch, 3, [working(1, label="Accepted")]) + activate(c, [idle(1, label="Other accepted")], observer=OTHER) + for generation, request_epoch, seq, error in ( + (gen, "old-epoch", 4, "epoch_mismatch"), + (gen + 100, epoch, 4, "unknown_token"), + (stale["generation"], epoch, 4, "stale_generation"), + (gen, epoch, 2, "seq_not_increasing"), + (gen, epoch, 3, None), + ): + with self.subTest(error=error): + ack = snapshot(c, generation, request_epoch, seq, [waiting(1, label="Fenced")]) + if error: + self.assertEqual(ack["error"], error) + else: + self.assertTrue(ack["duplicate"]) + self.assertEqual(rows(c), [("local", "1", "working", "Other accepted")]) + activate(c, [working(1, label="Replacement")]) + ack = snapshot(c, gen, epoch, 99, [waiting(1, label="Retired")]) + self.assertEqual(ack["error"], "expired_generation") + self.assertEqual(rows(c), [("local", "1", "working", "Replacement")]) + + def test_label_change_alone_sends_nothing(self): + c, _, sender, _, _ = make_coordinator() + gen, epoch = activate(c, [working(1, label="\U000f1517 Original")]) + sent = list(sender.sent) + snapshot(c, gen, epoch, 2, [working(1, label="\uf412 Renamed")]) + self.assertEqual(rows(c), [("local", "1", "working", "Renamed")]) + self.assertEqual(sender.sent, sent) + + def test_withdrawn_observation_label_ignored(self): + c, _, _, _, _ = make_coordinator() + activate(c, [working(1, label="Live")]) + activate(c, [{"pane": 1, "state": "closed", "label": "Withdrawn"}], observer=OTHER) + self.assertEqual(rows(c), [("local", "1", "working", "Live")]) + + +class WireValidationTest(unittest.TestCase): + def test_bad_host_rejected_fixed_message(self): + c, _, _, _, _ = make_coordinator() + reg = register(c) + for host in ("", 5, True, [], {}, "a\nb", "\x00", "\x7f", "\x85", "\x9f", "\ud800", "\udfff", "x" * 129): + with self.subTest(host=ascii(host)): + ack = snapshot(c, reg["generation"], reg["epoch"], 1, [{"pane": 1, "state": "working", "host": host}]) + self.assertEqual(ack["error"], "bad_request") + self.assertEqual(ack["detail"], "observation.host must be a short host key") + self.assertEqual(c.rows, ()) + + def test_host_at_limit_accepted(self): + c, _, _, _, _ = make_coordinator() + host = "é" * 128 + activate(c, [working(1, host=host)]) + self.assertEqual(rows(c), [(host, "1", "working", None)]) + + def test_bad_label_dropped_not_rejected(self): + c, _, _, _, _ = make_coordinator() + reg = register(c) + for seq, label in enumerate((7, True, [], {}, "x" * 1025), 1): + with self.subTest(label=ascii(label)): + ack = snapshot(c, reg["generation"], reg["epoch"], seq, [{"pane": 1, "state": "working", "label": label}]) + self.assertTrue(ack["ok"], ack) + self.assertEqual(rows(c), [("local", "1", "working", None)]) + self.assertEqual(c.status()["counters"]["labels_rejected"], seq) + + def test_label_at_window_cap_accepted(self): + c, _, _, _, _ = make_coordinator() + gen, epoch = activate(c, [working(1, label="é" * 128)]) + self.assertEqual(rows(c), [("local", "1", "working", "é" * 96)]) + snapshot(c, gen, epoch, 2, [working(1, label="x" * 1024)]) + self.assertEqual(rows(c), [("local", "1", "working", "x" * 96)]) + snapshot(c, gen, epoch, 3, [{"pane": 1, "state": "working", "label": None}, working(2), working(3, label="\uf412 \t")]) + self.assertTrue(all(row.label is None for row in c.rows)) + self.assertEqual(c.counters["labels_rejected"], 0) + + def test_status_reports_counts_only(self): + c, _, _, _, _ = make_coordinator() + reg = register(c) + ack = snapshot(c, reg["generation"], reg["epoch"], 1, [ + idle(1, "1", "failed", host="private-host", label="Error label"), + waiting(2, label="Question label"), + working(3), + idle(4, "1", label="\uf412"), + idle(5, label="Idle label"), + ]) + expected = {"blocked_error": 1, "waiting_for_input": 1, "working": 1, "completed": 1, "idle_ready": 1} + self.assertEqual(ack["rows"], expected) + self.assertNotIn("desired", ack) + status = c.status() + self.assertEqual(status["rows"], expected) + self.assertEqual(status["rows_total"], 5) + self.assertEqual(status["rows_labelled"], 3) + self.assertNotIn("desired", status) + self.assertCountEqual(status["observers"][0]["active_notices"], [{"pane": "1", "kind": "failed"}, {"pane": "4", "kind": "done"}]) + + def test_resync_and_disable_report_counts_only(self): + c, _, sender, _, _ = make_coordinator() + activate(c, [waiting(1, label="Question"), working(2, label="One"), working(3, label="Two")]) + resync = c.handle({"schema": 1, "op": "resync"}) + self.assertEqual(resync["rows"], {"waiting_for_input": 1, "working": 2}) + self.assertEqual(resync["summary"], "3 rows: waiting_for_input 1, working 2") + self.assertNotIn("desired", resync) + disabled = c.handle({"schema": 1, "op": "disable"}) + self.assertEqual(disabled["rows"], {}) + self.assertEqual(disabled["summary"], "no rows") + self.assertNotIn("desired", disabled) + self.assertEqual(sender.modes_for("events.sock"), ["idle_ready", "waiting_for_input", "waiting_for_input", "idle_ready"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_server.py b/tests/test_server.py index 6d2ec88..fae63f8 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -92,7 +92,7 @@ def test_deep_nesting_and_non_finite_numbers_never_unwind_the_loop(self): def test_partial_sender_is_dropped_without_starving_the_reaper(self): reg = self.fx.call({"schema": 1, "op": "register", "observer": {"parent_pid": 1, "window_key": ""}}) ack = self.fx.call({"schema": 1, "op": "snapshot", "observer": {"parent_pid": 1, "window_key": ""}, "epoch": reg["epoch"], "generation": reg["generation"], "seq": 1, "coverage": "complete", "observations": [{"pane": 1, "state": "working"}]}) - self.assertEqual(ack["desired"], "working") + self.assertEqual(ack["rows"], {"working": 1}) slow = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) slow.connect(str(self.fx.socket_path)) slow.sendall(b'{"schema": 1, "op": "sta') # never finishes diff --git a/tests/test_site.py b/tests/test_site.py index 4d9108b..3211a99 100644 --- a/tests/test_site.py +++ b/tests/test_site.py @@ -279,15 +279,6 @@ def test_owned_surfaces_carry_the_disclaimer(self): with self.subTest(surface=name): self.assertIn(DISCLAIMER, (ROOT / name).read_text(encoding="utf-8")) - def test_documented_test_count_is_current(self): - count = unittest.defaultTestLoader.discover(str(ROOT / "tests"), top_level_dir=str(ROOT)).countTestCases() - for name in ("docs/compatibility.md", "CHANGELOG.md"): - text = (ROOT / name).read_text(encoding="utf-8") - claims = re.findall(r"(\d+) unit and integration tests|The (\d+) tests|Ran (\d+) tests", text) - self.assertTrue(claims, f"{name} no longer states the test count") - for claim in claims: - self.assertEqual(count, int(next(c for c in claim if c)), f"{name} states a stale test count") - if __name__ == "__main__": unittest.main() diff --git a/tests/test_transport.py b/tests/test_transport.py index fac4a4c..743285e 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -4,7 +4,8 @@ from tests.helpers import FakeClock, FakeReceiver, RecordingSender, short_tmpdir -from tern_sidepulse.transport import SidePulseTransport, build_line, encode_event +from tern_sidepulse.reducer import Row +from tern_sidepulse.transport import SidePulseTransport, build_line, combined_mode, encode_event def transport_with(sender: RecordingSender, clock: FakeClock, **kw) -> SidePulseTransport: @@ -40,6 +41,96 @@ def test_unknown_mode_rejected(self): build_line("tool_running", "x", 0) +class CombinedModeTest(unittest.TestCase): + def test_priority_order(self): + for modes, expected in ( + (["working", "waiting_for_input", "working", "working"], "waiting_for_input"), + (["completed", "working"], "working"), + (["blocked_error", "waiting_for_input"], "blocked_error"), + (["completed", "idle_ready"], "completed"), + ([], "idle_ready"), + ): + with self.subTest(modes=modes): + self.assertEqual(combined_mode(Row("local", str(i), mode, None) for i, mode in enumerate(modes)), expected) + + def test_duplicates_are_idempotent(self): + row = Row("local", "1", "working", None) + self.assertEqual(combined_mode([row]), combined_mode([row, row, row])) + + +class PublishTest(unittest.TestCase): + def setUp(self): + self.clock = FakeClock() + self.sender = RecordingSender(short_tmpdir("tsp-pub-")) + self.sender.up("events.sock") + self.sender.up("relay-events.sock") + self.t = transport_with(self.sender, self.clock) + + def test_rows_reduce_to_one_mode(self): + self.t.publish([ + Row("local", "1", "working", "Work"), + Row("remote", "2", "waiting_for_input", "Question"), + ]) + self.assertEqual(self.sender.sent, [], "publishing records the state without performing I/O") + self.t.tick() + self.assertEqual(self.sender.modes_for("events.sock"), ["waiting_for_input"]) + self.assertEqual(self.sender.modes_for("relay-events.sock"), ["waiting_for_input"]) + self.t.publish([Row("local", "1", "working", None)]) + self.t.tick() + self.assertEqual(self.sender.modes_for("events.sock"), ["waiting_for_input", "working"]) + self.t.publish([Row("local", "1", "working", None)], force=True) + self.t.tick() + self.assertEqual(self.sender.modes_for("events.sock"), ["waiting_for_input", "working", "working"]) + + def test_label_or_row_churn_without_mode_change_sends_nothing(self): + self.t.publish([Row("local", "1", "working", "Old")]) + self.t.tick() + sent = list(self.sender.sent) + self.t.publish([Row("local", "1", "working", "Renamed")]) + self.t.tick() + self.t.publish([ + Row("remote", "2", "working", "Moved"), + Row("local", "3", "completed", "Done"), + ]) + self.t.tick() + self.assertEqual(self.sender.sent, sent) + + def test_empty_rows_send_neutral(self): + self.assertFalse(self.t.neutral_delivered()) + self.t.publish([Row("local", "1", "working", "Work")]) + self.t.tick() + self.assertFalse(self.t.neutral_delivered()) + self.t.publish(()) + self.t.tick() + self.assertTrue(self.t.neutral_delivered()) + self.assertEqual(self.sender.modes_for("events.sock"), ["working", "idle_ready"]) + self.assertEqual(self.sender.modes_for("relay-events.sock"), ["working", "idle_ready"]) + self.assertEqual(self.t.delivery_summary(), { + "ui": {"mode": "idle_ready", "pending": False, "error": None}, + "service": {"mode": "idle_ready", "pending": False, "error": None}, + }) + + def test_undelivered_neutral_names(self): + self.sender.down("relay-events.sock") + self.sender.refuse.add("events.sock") + self.t.publish((), force=True) + self.t.tick() + self.assertEqual(self.t.undelivered_neutral(), ["ui"], "only a present receiver needs the startup neutral") + self.sender.refuse.clear() + self.sender.up("relay-events.sock") + self.t.tick(immediate=True) + self.assertEqual(self.t.undelivered_neutral(), []) + self.assertTrue(self.t.neutral_delivered()) + self.t.publish([Row("local", "1", "working", None)]) + self.t.tick() + self.assertCountEqual(self.t.undelivered_neutral(), ["ui", "service"]) + self.sender.refuse.add("events.sock") + self.t.publish(()) + self.t.tick() + self.assertEqual(self.t.undelivered_neutral(), ["ui"]) + self.assertFalse(self.t.neutral_delivered()) + + class DeliveryTest(unittest.TestCase): def setUp(self): self.clock = FakeClock() From 0a7f8a8daede87dd1bdff7e0f1271e07783213d8 Mon Sep 17 00:00:00 2001 From: Sunil Srivatsa Date: Thu, 5 Nov 2026 20:13:55 -0800 Subject: [PATCH 2/3] feat(window): send host keys and tab-title labels with a bounded snapshot Each OMP observation carries a host key and a label (the user-given tab name, else the pane's own title), cut at a UTF-8 boundary. Snapshots are encoded under pcall and kept under 192 KiB by dropping labels. The window harness moves into tests/luau and runs against the real window.luau in CI. --- .github/workflows/ci.yml | 13 ++ tests/luau/drive_backoff.luau | 119 +++++++++++++++++ tests/luau/drive_budget.luau | 106 +++++++++++++++ tests/luau/drive_labels.luau | 196 ++++++++++++++++++++++++++++ tests/luau/harness.luau | 239 ++++++++++++++++++++++++++++++++++ tests/test_luau_harness.py | 57 ++++++++ window.luau | 156 ++++++++++++++++++++-- 7 files changed, 875 insertions(+), 11 deletions(-) create mode 100644 tests/luau/drive_backoff.luau create mode 100644 tests/luau/drive_budget.luau create mode 100644 tests/luau/drive_labels.luau create mode 100644 tests/luau/harness.luau create mode 100644 tests/test_luau_harness.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a825f8a..7fe1adc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,9 +21,22 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.13" - name: Fetch luau-lsp 1.70.1 run: | curl -sSL -o luau-lsp.zip https://github.com/JohnnyMorganz/luau-lsp/releases/download/1.70.1/luau-lsp-linux-x86_64.zip unzip -q luau-lsp.zip chmod +x luau-lsp + - name: Fetch Luau 0.745 + run: | + mkdir -p luau-bin + curl -fsSL -o luau.zip https://github.com/luau-lang/luau/releases/download/0.745/luau-ubuntu.zip + unzip -q luau.zip -d luau-bin + chmod +x luau-bin/luau - run: ./luau-lsp analyze --definitions=types/tern.d.luau window.luau + - run: python -m unittest tests.test_luau_harness -v + env: + LUAU: ${{ github.workspace }}/luau-bin/luau + TERN_SIDEPULSE_REQUIRE_LUAU: "1" diff --git a/tests/luau/drive_backoff.luau b/tests/luau/drive_backoff.luau new file mode 100644 index 0000000..cd2e09d --- /dev/null +++ b/tests/luau/drive_backoff.luau @@ -0,0 +1,119 @@ +-- Audit scenarios A-G, exercised against the real window observer. +local function gaps() + local out = {} + for i = 2, #H.run_log do + table.insert(out, string.format("%d", H.run_log[i].t - H.run_log[i - 1].t)) + end + return table.concat(out, " ") +end + +-- A: the coordinator cannot start; every helper answers coordinator_unavailable. +H.boot() +for _ = 1, 12 do + H.complete(0, H.UNAVAILABLE) + H.wait_for_run(120000) +end +print("A helper gaps (ms) while the coordinator is unavailable:", gaps()) +local last_gap = H.run_log[#H.run_log].t - H.run_log[#H.run_log - 1].t +assert(last_gap >= 30000, "backoff reached the 30 s cap, got " .. last_gap) +local warns = 0 +for _, line in ipairs(H.logs) do + if line:find("helper failing") then + warns += 1 + end +end +assert(warns == 1, "exactly one failing warning, got " .. warns) + +-- B: a shim interpreter; each register succeeds, every snapshot is fenced. +H.run_log = {} +local waits = {} +for _ = 1, 8 do + assert(H.op(H.runs[1]) == "register", "expected a register, got " .. H.op(H.runs[1])) + H.complete(0, H.REG_OK) + assert(#H.runs == 1 and H.op(H.runs[1]) == "snapshot", "the activating snapshot follows at once") + H.complete(0, H.UNKNOWN_TOKEN) + table.insert(waits, H.wait_for_run(120000)) +end +print("B wait before each re-register after a fenced snapshot (ms):", table.concat(waits, " ")) +assert(waits[1] == 0 and waits[2] == 0, "the first fences re-register immediately") +assert(waits[#waits] >= 30000, "repeated fences reach the 30 s cap, got " .. waits[#waits]) + +-- C: an old interpreter is replaced; an accepted snapshot clears the backoff. +H.run_log = {} +assert(H.runs[1].argv[1] == "/opt/homebrew/bin/python3", "still on the default candidate") +assert(H.runs[1].argv[2] == "-I" and H.runs[1].argv[3] == "-S" and H.runs[1].argv[4] == "-X", "isolated flags with a bytecode cache") +H.complete(3, H.TOO_OLD) +H.wait_for_run(120000) +assert(H.runs[1].argv[1] == "/opt/homebrew/bin/python3.13", "the too-old interpreter is replaced, got " .. H.runs[1].argv[1]) +H.complete(0, H.REG_OK) +assert(H.op(H.runs[1]) == "snapshot") +H.complete(0, H.SNAP_OK) +print("C interpreter after python_too_old:", H.run_log[#H.run_log].python) +local recovered_warning = false +for _, line in ipairs(H.logs) do + if line:find("helper recovered") and line:sub(1, 4) == "warn" then + recovered_warning = true + end +end +assert(recovered_warning, "recovery is logged at warn level") +local gap = H.wait_for_run(10000) +assert(H.op(H.runs[1]) == "snapshot" and gap <= 5000, "steady state is one snapshot per reconciliation") + +-- D: overlapping callbacks reject their own interpreter, not its healthy replacement. +H.exists["/opt/homebrew/bin/python3.12"] = true +assert(#H.runs == 1 and H.op(H.runs[1]) == "snapshot" and H.runs[1].argv[1] == "/opt/homebrew/bin/python3.13") +H.commands.doctor.run(H.cx) +assert(#H.runs == 2 and H.op(H.runs[2]) == "doctor" and H.runs[2].argv[1] == "/opt/homebrew/bin/python3.13") +H.complete(3, H.TOO_OLD) +H.complete(3, H.TOO_OLD) +H.wait_for_run(120000) +assert(H.runs[1].argv[1] == "/opt/homebrew/bin/python3.12", "a concurrent callback must not reject the healthy replacement, got " .. H.runs[1].argv[1]) +print("D interpreter after two overlapping python_too_old answers:", H.runs[1].argv[1]) +local function settle() + while #H.runs > 0 do + H.complete(0, H.op(H.runs[1]) == "register" and H.REG_OK or H.SNAP_OK) + end +end +settle() + +-- E: a latch set outside the window drops notices before the next generation. +H.world.agents = { { pane = 5, state = "idle", kind = "agent", program = "omp", host = 0, alive = true } } +H.world.roles[5] = "omp.session" +H.exists["/fake/data/disabled"] = true +H.handlers.agent_finished({ pane = 5, result = "failed" }, H.cx) +H.advance(100) +assert(#H.runs == 0, "no helper call while the latch is set") +H.exists["/fake/data/disabled"] = nil +H.handlers.agent_state({ pane = 5, old = "working", new = "idle" }, H.cx) +H.advance(100) +assert(#H.runs == 1 and H.op(H.runs[1]) == "register", "re-registers after enable") +H.complete(0, H.REG_OK) +assert(#H.runs == 1 and H.op(H.runs[1]) == "snapshot") +local enabled_snapshot = H.payload(H.runs[1]) +assert(#enabled_snapshot.observations == 1 and enabled_snapshot.observations[1].pane == 5, "pane 5 is observed") +assert(enabled_snapshot.observations[1].notice == nil, "a notice recorded while disabled is not replayed into the new generation") +print("E activating snapshot after enable carries notice:", tostring(enabled_snapshot.observations[1].notice)) +H.complete(0, H.SNAP_OK) + +-- F: synchronous helper failure still toasts through the command's own cx. +H.spawn_fail = true +H.toasts = {} +H.commands.doctor.run(H.cx) +assert(#H.toasts == 1 and H.toasts[1]:find("tern-sidepulse doctor", 1, true) and H.toasts[1]:find("spawn"), "doctor toasts the synchronous failure, got " .. tostring(H.toasts[1])) +H.commands.resync.run(H.cx) +assert(#H.toasts == 2 and H.toasts[2]:find("resync") and H.toasts[2]:find("spawn"), "resync toasts too") +print("F toasts on synchronous helper failure:", H.toasts[1], "|", H.toasts[2]) +H.spawn_fail = false +H.advance(60000) +H.wait_for_run(120000) +settle() + +-- G: an in-place role change with no event is noticed on the next reconciliation. +H.world.roles[5] = "claude.session" +H.wait_for_run(10000) +assert(H.op(H.runs[1]) == "snapshot") +local changed_snapshot = H.payload(H.runs[1]) +assert(changed_snapshot.coverage == "complete" and #changed_snapshot.observations == 0, "a re-read role excludes the pane, got " .. #changed_snapshot.observations) +print("G observations after the role changed in place:", #changed_snapshot.observations) +H.complete(0, H.SNAP_OK) +print("OK") diff --git a/tests/luau/drive_budget.luau b/tests/luau/drive_budget.luau new file mode 100644 index 0000000..d0c6912 --- /dev/null +++ b/tests/luau/drive_budget.luau @@ -0,0 +1,106 @@ +-- B1-B3: real encoded byte budgets, label fallback, and encode-failure recovery. +local SNAPSHOT_BUDGET = 192 * 1024 + +local function next_snapshot() + H.handlers.session_ended({}, H.cx) + H.advance(75) + assert(#H.runs == 1 and H.op(H.runs[1]) == "snapshot", "expected one snapshot helper") + return H.runs[1], H.payload(H.runs[1]) +end + +local function single_pane(title) + H.world = H.new_world() + H.world.agents = { { pane = 601, state = "idle", kind = "agent", program = "omp", host = 0, alive = true } } + H.world.roles[601] = "omp.session" + H.world.panes = { { pane = 601, title = title, tab = 1 } } + H.world.tabs = { { id = 1, title = "not a label" } } +end + +-- B1: labels put this complete snapshot over budget; one label-free retry fits. +local long_host = string.rep("h", 128) +local long_label = string.rep("L", 255) +H.world.hosts = { { id = 9, kind = "remote", state = "connected", address = long_host, name = long_host, panes = {} } } +for pane = 1, 500 do + table.insert(H.world.agents, { pane = pane, state = "idle", kind = "agent", program = "omp", host = 9, alive = true }) + H.world.roles[pane] = "omp.session" + table.insert(H.world.panes, { pane = pane, title = long_label, tab = 1 }) + table.insert(H.world.hosts[1].panes, pane) +end +H.world.tabs = { { id = 1, title = "not a label" } } +H.boot() +H.complete(0, H.REG_OK) +assert(#H.runs == 1 and H.op(H.runs[1]) == "snapshot", "B1: activating snapshot must be sent") +local large_run = H.runs[1] +local large = H.payload(large_run) +assert(large.coverage == "complete" and #large.observations == 500, "B1: budget fallback preserves complete status coverage") +assert(large.diag.labels_dropped == 1, "B1: oversized labelled snapshot must drop labels once") +for _, row in ipairs(large.observations) do + assert(row.label == nil, "B1: no label may survive the fallback") + assert(row.host == long_host, "B1: retain the full 128-byte host key") +end +local largest_attempt = 0 +for text, payload in pairs(H.encoded) do + if payload.observations ~= nil then + largest_attempt = math.max(largest_attempt, #text) + end +end +assert(largest_attempt > SNAPSHOT_BUDGET, "B1: fixture must exercise an oversized encoded snapshot") +assert(#large_run.opts.stdin <= SNAPSHOT_BUDGET, "B1: sent snapshot must fit the 192 KiB budget") +print("B1 encoded bytes before/after dropping labels:", largest_attempt, #large_run.opts.stdin, "observations:", #large.observations) +H.complete(0, H.SNAP_OK) + +-- B2: an encoder that rejects labels still sends status, then accepts another pass. +single_pane("Label rejected by encoder") +local label_rejections = 0 +H.world.fail.encode = function(payload) + for _, row in ipairs(payload.observations or {}) do + if row.label ~= nil then + label_rejections += 1 + return true + end + end + return false +end +local before_attempts = #H.payloads +local fallback_run, fallback = next_snapshot() +assert(label_rejections == 1 and #H.payloads == before_attempts + 2, "B2: encode with labels once, then retry without them once") +assert(fallback.coverage == "complete" and #fallback.observations == 1 and fallback.observations[1].label == nil, "B2: send the label-free snapshot") +assert(#fallback_run.opts.stdin <= SNAPSHOT_BUDGET, "B2: fallback fits the byte budget") +H.complete(0, H.SNAP_OK) +H.wait_for_run(6000) +assert(#H.runs == 1 and H.op(H.runs[1]) == "snapshot", "B2: completion must clear in_flight for the next reconciliation") +assert(H.payload(H.runs[1]).observations[1].label == nil, "B2: reconciliation still falls back without labels") +H.complete(0, H.SNAP_OK) +print("B2 labelled encode throws; fallback and next reconciliation both send status") + +-- B3: an encoder that always throws cannot wedge either commands or snapshots. +single_pane("Recovered label") +H.world.fail.encode = true +local before_logs, before_toasts = #H.logs, #H.toasts +H.commands.doctor.run(H.cx) +assert(#H.runs == 0, "B3: a failed command encode must not spawn") +assert(#H.toasts == before_toasts + 1 and H.toasts[#H.toasts]:find("encode_failed", 1, true), "B3: run_helper reports synchronous encode_failed through the command cx") +H.handlers.session_ended({}, H.cx) +H.advance(75) +assert(#H.runs == 0, "B3: failed snapshot encoding must not spawn") +before_attempts = #H.payloads +H.advance(10000) +assert(#H.runs == 0 and #H.payloads > before_attempts, "B3: later passes retry encoding without an in_flight wedge") +local encode_warnings = 0 +for i = before_logs + 1, #H.logs do + local line = H.logs[i] + if line:sub(1, 4) == "warn" and line:find("encode_failed", 1, true) then + encode_warnings += 1 + end +end +assert(encode_warnings == 1, "B3: repeated encoding failures produce exactly one warning") +H.world.fail.encode = false +H.wait_for_run(35000) +assert(#H.runs == 1 and H.op(H.runs[1]) == "snapshot", "B3: recovery sends a snapshot without re-registering") +local recovered_payload = H.payload(H.runs[1]) +assert(recovered_payload.coverage == "complete" and recovered_payload.observations[1].label == "Recovered label", "B3: recovery restores the real label and status") +H.complete(0, H.SNAP_OK) +next_snapshot() +H.complete(0, H.SNAP_OK) +print("B3 one warning across repeated encode failures; recovery and next pass succeed") +print("OK") diff --git a/tests/luau/drive_labels.luau b/tests/luau/drive_labels.luau new file mode 100644 index 0000000..a2454a3 --- /dev/null +++ b/tests/luau/drive_labels.luau @@ -0,0 +1,196 @@ +-- L1-L12 from the plan, except L8: Tern replaces invalid UTF-8 during encoding. +-- Each accepted snapshot is followed by a fresh fixture; L12 uses only the reconciliation clock. +local function one_pane(pane, title, tab) + H.world = H.new_world() + H.world.agents = { { pane = pane, state = "idle", kind = "agent", program = "omp", host = 0, alive = true } } + H.world.roles[pane] = "omp.session" + H.world.panes = { { pane = pane, title = title, tab = tab } } + H.world.tabs = if tab ~= nil then { { id = tab, title = "focused shell title" } } else {} +end + +local function snapshot(first) + if first then + H.boot() + H.complete(0, H.REG_OK) + else + H.handlers.session_ended({}, H.cx) + H.advance(75) + end + assert(#H.runs == 1 and H.op(H.runs[1]) == "snapshot", "expected one snapshot") + local payload = H.payload(H.runs[1]) + assert(payload.coverage == "complete", "label lookup must not degrade coverage") + return payload +end + +local function observation(payload, pane) + for _, row in ipairs(payload.observations) do + if row.pane == pane then + return row + end + end + error("missing observation for pane " .. pane) +end + +-- Keep the byte budget honest: the fake encoder follows the probed Tern encoding. +local encoding_probe = tern.json.encode({ text = "\t\1\127é", pane = 949187772435 }) +assert(encoding_probe:find("\\t", 1, true) and encoding_probe:find("\\u0001", 1, true), "C0 controls must be escaped") +assert(encoding_probe:find("\127é", 1, true), "DEL and UTF-8 must remain raw") +assert(encoding_probe:find("949187772435", 1, true), "pane ids must encode as exact integers") + +-- L1: a user-given tab name wins over the pane's title. +one_pane(11, "Own pane title", 101) +H.world.tabs[1].name = "My work" +local named = snapshot(true) +assert(observation(named, 11).label == "My work", "L1: user-given tab name must label the OMP pane") +assert(named.diag.label_tab == 1, "L1: one tab label") +H.complete(0, H.SNAP_OK) +print("L1 user-given tab name wins") + +-- L2: the raw pane title retains the OMP glyph; the coordinator sanitizes it. +local glyph_title = "\u{F1517} DOCS: Review docs" +one_pane(12, glyph_title, 102) +local unnamed = snapshot() +assert(observation(unnamed, 12).label == glyph_title, "L2: preserve the raw OMP pane title and glyph") +assert(unnamed.diag.label_title == 1, "L2: one pane-title label") +H.complete(0, H.SNAP_OK) +print("L2 raw glyph and pane title preserved") + +-- L3: the focused shell sets TabInfo.title, not the OMP pane's row label. +one_pane(13, "OMP's own title", 103) +H.world.tabs[1].title = "zsh" +table.insert(H.world.panes, { pane = 130, title = "zsh", tab = 103 }) +local split = snapshot() +assert(observation(split, 13).label == "OMP's own title", "L3: never label from TabInfo.title or the focused shell") +H.complete(0, H.SNAP_OK) +print("L3 focused shell title ignored") + +-- L4: a whitespace-only tab name does not hide the pane title. +one_pane(14, "Pane fallback", 104) +H.world.tabs[1].name = " " +local whitespace = snapshot() +assert(observation(whitespace, 14).label == "Pane fallback", "L4: whitespace-only tab name falls back to pane title") +H.complete(0, H.SNAP_OK) +print("L4 whitespace-only name falls back") + +-- L5: parked panes have no tab, but still have their own title. +one_pane(15, "Parked OMP", nil) +local parked = snapshot() +assert(observation(parked, 15).label == "Parked OMP", "L5: parked pane keeps its title") +H.complete(0, H.SNAP_OK) +print("L5 parked pane title preserved") + +-- L6: an OMP pane missing from panes() has no invented label. +one_pane(16, "Not returned", 106) +H.world.panes = {} +local missing = snapshot() +assert(observation(missing, 16).label == nil, "L6: omit unknown label") +assert(missing.diag.label_none == 1, "L6: one unknown label") +H.complete(0, H.SNAP_OK) +print("L6 missing pane has no label") + +-- L7: 300-byte titles cut to their maximal complete-character prefix. +H.world = H.new_world() +local characters = { "é", "€", "😀" } +local titles = {} +for i, char in ipairs(characters) do + local pane = 70 + i + local title = string.rep(char, 300 / #char) + titles[pane] = title + table.insert(H.world.agents, { pane = pane, state = "idle", kind = "agent", program = "omp", host = 0, alive = true }) + H.world.roles[pane] = "omp.session" + table.insert(H.world.panes, { pane = pane, title = title, tab = 107 }) +end +H.world.tabs = { { id = 107, title = "not a label" } } +local bounded = snapshot() +for i, char in ipairs(characters) do + local pane = 70 + i + local label = observation(bounded, pane).label + local expected_bytes = math.floor(256 / #char) * #char + assert(label == titles[pane]:sub(1, expected_bytes), "L7: maximal UTF-8 prefix for " .. #char .. "-byte characters") + assert(#label <= 256 and utf8.len(label) ~= nil, "L7: bounded valid UTF-8 label") +end +H.complete(0, H.SNAP_OK) +print("L7 UTF-8 prefix bytes: 256 255 256") + +-- L9: unavailable optional APIs never suppress status or invent labels. +one_pane(19, "Available title", 109) +H.world.fail.panes = true +local before_panes, before_tabs = H.calls.panes, H.calls.tabs +local no_panes = snapshot() +assert(observation(no_panes, 19).label == nil, "L9: panes failure omits labels") +assert(no_panes.diag.labels_unavailable == 1, "L9: one unavailable label source") +assert(H.calls.panes == before_panes + 1 and H.calls.tabs == before_tabs, "L9: panes failure must skip tabs()") +H.complete(0, H.SNAP_OK) +H.world.fail.panes, H.world.fail.tabs = false, true +before_panes, before_tabs = H.calls.panes, H.calls.tabs +local no_tabs = snapshot() +assert(observation(no_tabs, 19).label == "Available title", "L9: tabs failure still uses pane titles") +assert(no_tabs.diag.labels_unavailable == 1, "L9: one failed tabs lookup") +assert(H.calls.panes == before_panes + 1 and H.calls.tabs == before_tabs + 1, "L9: each optional API called once") +H.complete(0, H.SNAP_OK) +print("L9 panes/tabs failures retain complete status coverage") + +-- L10: API work is per snapshot, not per OMP pane, and is skipped when empty. +H.world = H.new_world() +for i = 1, 3 do + local pane = 100 + i + table.insert(H.world.agents, { pane = pane, state = "working", kind = "agent", program = "omp", host = 0, alive = true }) + H.world.roles[pane] = "omp.session" + table.insert(H.world.panes, { pane = pane, title = "OMP " .. i, tab = if i < 3 then 201 else 202 }) +end +H.world.tabs = { { id = 201, name = "First" }, { id = 202, name = "Second" } } +before_panes, before_tabs = H.calls.panes, H.calls.tabs +local three = snapshot() +assert(#three.observations == 3, "L10: all three OMP panes observed") +assert(observation(three, 101).label == "First" and observation(three, 102).label == "First" and observation(three, 103).label == "Second", "L10: labels join by tab id") +assert(H.calls.panes == before_panes + 1 and H.calls.tabs == before_tabs + 1, "L10: exactly one panes() and tabs() per pass") +H.complete(0, H.SNAP_OK) +H.world.roles = {} +before_panes, before_tabs = H.calls.panes, H.calls.tabs +local empty = snapshot() +assert(#empty.observations == 0, "L10: no OMP observations remain") +assert(H.calls.panes == before_panes and H.calls.tabs == before_tabs, "L10: empty pass makes no label API calls") +H.complete(0, H.SNAP_OK) +print("L10 one lookup per populated pass; zero when empty") + +-- L11: use the probed remote host shape; invalid addresses may fall back to name. +H.world = H.new_world() +H.world.hosts = { + { id = 0, kind = "local", state = "connected", address = "ignored-local-address" }, + { id = 1, kind = "remote", state = "connected", address = "sf-studio.tailfb479a.ts.net", name = "sf-studio.tailfb479a.ts.net" }, + { id = 2, kind = "remote", state = "connected", name = "name-only.example" }, + { id = 3, kind = "remote", state = "connected" }, + { id = 4, kind = "remote", state = "connected", address = "bad\naddress", name = "usable-name.example" }, +} +local host_expectations = { "local", "sf-studio.tailfb479a.ts.net", "name-only.example", "id:3", "usable-name.example" } +for i, host in ipairs(H.world.hosts) do + local pane = 110 + i + host.panes = { pane } + table.insert(H.world.agents, { pane = pane, state = "idle", kind = "agent", program = "omp", host = host.id, alive = true }) + H.world.roles[pane] = "omp.session" + table.insert(H.world.panes, { pane = pane, title = "Host sample" }) +end +local hosts = snapshot() +assert(#hosts.observations == 5, "L11: all connected host panes observed") +for i, expected in ipairs(host_expectations) do + assert(observation(hosts, 110 + i).host == expected, "L11: wrong host key for host " .. (i - 1)) +end +assert(hosts.diag.host_fallback == 1, "L11: only the nameless remote needs an id fallback") +H.complete(0, H.SNAP_OK) +print("L11 local, remote address/name, and id fallback keys") + +-- L12: a rename needs no title event; one reconciliation refreshes the label. +one_pane(121, "Own pane title", 212) +H.world.tabs[1].name = "Before rename" +local before_rename = snapshot() +assert(observation(before_rename, 121).label == "Before rename", "L12: initial tab name") +H.complete(0, H.SNAP_OK) +H.world.tabs[1].name = "After rename" +assert(H.handlers.title == nil, "L12: no title-event subscription") +local rename_wait = H.wait_for_run(6000) +assert(rename_wait <= 5000 and H.op(H.runs[1]) == "snapshot", "L12: next reconciliation within 5 s") +local renamed = H.payload(H.runs[1]) +assert(observation(renamed, 121).label == "After rename", "L12: next reconciliation carries renamed tab") +H.complete(0, H.SNAP_OK) +print("L12 renamed tab refreshes within one 5 s pass") +print("OK") diff --git a/tests/luau/harness.luau b/tests/luau/harness.luau new file mode 100644 index 0000000..ed1f700 --- /dev/null +++ b/tests/luau/harness.luau @@ -0,0 +1,239 @@ +-- Concatenated before the real window.luau and one drive; no Tern or SidePulse is contacted. +local H = { + now = 1000, + timers = {}, + runs = {}, -- pending tern.process.run calls: {argv, opts, cb} + run_log = {}, -- {t, op, python} + logs = {}, + toasts = {}, + handlers = {}, + commands = {}, + exists = { ["/opt/homebrew/bin/python3"] = true, ["/opt/homebrew/bin/python3.13"] = true }, + canned = {}, + payloads = {}, -- every value handed to tern.json.encode, including failed attempts + encoded = {}, -- encoded stdin -> payload + calls = { panes = 0, tabs = 0 }, + spawn_fail = false, +} + +function H.new_world() + return { + hosts = { { id = 0, kind = "local", state = "connected", panes = {} } }, + agents = {}, + roles = {}, + panes = {}, + tabs = {}, + fail = { panes = false, tabs = false, encode = false }, + } +end +H.world = H.new_world() + +H.UNAVAILABLE = '{"ok":false,"error":"coordinator_unavailable","detail":"ENOENT"}' +H.TOO_OLD = '{"ok":false,"error":"python_too_old","detail":"requires Python 3.10+"}' +H.REG_OK = '{"ok":true,"generation":7,"epoch":"e1","notice_seconds":{"done":15,"failed":30}}' +H.UNKNOWN_TOKEN = '{"ok":false,"error":"unknown_token"}' +H.SNAP_OK = '{"ok":true,"accepted":true,"desired":"idle_ready"}' +H.canned[H.UNAVAILABLE] = { ok = false, error = "coordinator_unavailable", detail = "ENOENT" } +H.canned[H.TOO_OLD] = { ok = false, error = "python_too_old", detail = "requires Python 3.10+" } +H.canned[H.REG_OK] = { ok = true, generation = 7, epoch = "e1", notice_seconds = { done = 15, failed = 30 } } +H.canned[H.UNKNOWN_TOKEN] = { ok = false, error = "unknown_token" } +H.canned[H.SNAP_OK] = { ok = true, accepted = true, desired = "idle_ready" } + +local JSON_ARRAYS = setmetatable({}, { __mode = "k" }) +local JSON_ESCAPES = { + ['"'] = '\\"', + ["\\"] = "\\\\", + ["\b"] = "\\b", + ["\f"] = "\\f", + ["\n"] = "\\n", + ["\r"] = "\\r", + ["\t"] = "\\t", +} + +local function encode_string(value) + -- Tern emits raw UTF-8 and raw DEL, but escapes C0, quotes and backslashes. + return '"' .. value:gsub('[%z\1-\31\\"]', function(char) + return JSON_ESCAPES[char] or string.format("\\u%04x", string.byte(char)) + end) .. '"' +end + +local function encode_value(value) + local kind = type(value) + if kind == "string" then + return encode_string(value) + elseif kind == "boolean" then + return if value then "true" else "false" + elseif kind == "number" then + assert(value == value and math.abs(value) < math.huge, "non-finite JSON number") + return if value % 1 == 0 then string.format("%.0f", value) else tostring(value) + elseif kind == "table" then + local parts = {} + if JSON_ARRAYS[value] then + for _, item in ipairs(value) do + table.insert(parts, encode_value(item)) + end + return "[" .. table.concat(parts, ",") .. "]" + end + for key, item in pairs(value) do + assert(type(key) == "string", "JSON object key is not a string") + table.insert(parts, encode_string(key) .. ":" .. encode_value(item)) + end + return "{" .. table.concat(parts, ",") .. "}" + end + error("unsupported JSON value: " .. kind) +end + +local function decode(text) + local value = H.canned[text] + if value == nil then + error("no canned decode for " .. tostring(text)) + end + return value +end + +local tern = { + plugin = { data = "/fake/data", dir = "/fake/plugin" }, + runtime = { os = "macos" }, + now = function() + return H.now + end, + timer = function(ms, cb) + table.insert(H.timers, { due = H.now + ms, cb = cb }) + return {} + end, + on = function(name, cb) + H.handlers[name] = cb + end, + command = function(def) + H.commands[def.id] = def + end, + log = { + warn = function(...) + table.insert(H.logs, "warn " .. table.concat({ ... }, " ")) + end, + info = function(...) + table.insert(H.logs, "info " .. table.concat({ ... }, " ")) + end, + error = function(...) + table.insert(H.logs, "error " .. table.concat({ ... }, " ")) + end, + }, + fs = { + read = function(_path, _max) + error("no such file") + end, + exists = function(path) + return H.exists[path] == true + end, + }, + json = { + encode = function(value) + table.insert(H.payloads, value) + local fail = H.world.fail.encode + if fail == true or (type(fail) == "function" and fail(value)) then + error("injected encode failure") + end + local text = encode_value(value) + H.encoded[text] = value + return text + end, + decode = decode, + array = function(value) + JSON_ARRAYS[value] = true + return value + end, + }, + process = { + run = function(argv, opts, cb) + if H.spawn_fail then + error("spawn failed") + end + table.insert(H.runs, { argv = argv, opts = opts, cb = cb }) + table.insert(H.run_log, { t = H.now, op = argv[#argv - 2], python = argv[1] }) + end, + }, +} + +local cx = {} +cx.agents = { list = function(_self) return H.world.agents end } +cx.hosts = { list = function(_self) return H.world.hosts end } +cx.session = { + surface = function(_self, pane, _opts) + local role = H.world.roles[pane] + if role == nil then + return nil + end + return { surface = { id = pane, role = role, mode = "normal" } } + end, + panes = function(_self) + H.calls.panes += 1 + if H.world.fail.panes then + error("injected panes failure") + end + return H.world.panes + end, + tabs = function(_self) + H.calls.tabs += 1 + if H.world.fail.tabs then + error("injected tabs failure") + end + return H.world.tabs + end, +} +function cx:window_key() return "" end +function cx:toast(tone, title, body) table.insert(H.toasts, tone .. " " .. title .. " " .. tostring(body)) end +H.cx = cx + +-- Fire every due timer in order, repeatedly, until none is due. +function H.advance(ms) + local target = H.now + ms + while true do + local next_i, next_t = nil, nil + for i, timer in ipairs(H.timers) do + if timer.due <= target and (next_t == nil or timer.due < next_t) then + next_i, next_t = i, timer.due + end + end + if next_i == nil then + break + end + local timer = table.remove(H.timers, next_i) + H.now = math.max(H.now, timer.due) + timer.cb(H.cx) + end + H.now = target +end + +function H.op(run) + return run.argv[#run.argv - 2] +end + +function H.payload(run) + local payload = H.encoded[run.opts.stdin] + assert(payload ~= nil, "helper stdin was not encoded by the harness") + return payload +end + +-- Complete the oldest helper with a canned result; callbacks receive a fresh cx. +function H.complete(status, stdout, timed_out) + local run = table.remove(H.runs, 1) + assert(run, "no pending helper run") + run.cb({ status = status, stdout = stdout, stderr = "", timed_out = timed_out or false }, H.cx) + return run +end + +function H.boot() + H.advance(50) + H.advance(75) + assert(#H.runs == 1 and H.op(H.runs[1]) == "register", "first helper call is a register") +end + +function H.wait_for_run(max_ms) + local start = H.now + H.advance(0) + while #H.runs == 0 do + assert(H.now - start < max_ms, "no helper run within " .. max_ms .. " ms") + H.advance(1000) + end + return H.now - start +end diff --git a/tests/test_luau_harness.py b/tests/test_luau_harness.py new file mode 100644 index 0000000..e80f510 --- /dev/null +++ b/tests/test_luau_harness.py @@ -0,0 +1,57 @@ +"""Run the real window observer in a headless, deterministic Luau runtime.""" +import os +import shutil +import subprocess +import unittest + +from tests.helpers import ROOT, short_tmpdir + + +class LuauHarnessTest(unittest.TestCase): + def _run_drive(self, drive: str) -> None: + configured = os.environ.get("LUAU") + luau = shutil.which(configured or "luau") + if luau is None: + message = f"no Luau executable: {configured or 'luau on PATH'} (set LUAU)" + if os.environ.get("TERN_SIDEPULSE_REQUIRE_LUAU") == "1": + self.fail(message) + self.skipTest(message) + + parts = (ROOT / "tests/luau/harness.luau", ROOT / "window.luau", ROOT / "tests/luau" / drive) + chunks = [] + offsets = [] + next_line = 1 + for part in parts: + name = part.relative_to(ROOT).as_posix() + start = next_line + 1 + chunk = f"-- @@ part: {name} starts at line {start}\n" + part.read_text(encoding="utf-8") + if not chunk.endswith("\n"): + chunk += "\n" + chunks.append(chunk) + offsets.append(f"{name}: line {start}") + next_line += chunk.count("\n") + offset_table = "Part offsets:\n" + "\n".join(offsets) + combined = short_tmpdir("tsp-luau-") / drive + combined.write_text("".join(chunks), encoding="utf-8") + try: + result = subprocess.run([luau, str(combined)], capture_output=True, text=True, timeout=60) + except subprocess.TimeoutExpired as exc: + self.fail(f"{offset_table}\nLuau timed out after 60 s\nstdout:\n{exc.stdout}\nstderr:\n{exc.stderr}") + except OSError as exc: + self.fail(f"{offset_table}\nCould not run Luau: {exc}") + details = f"{offset_table}\nstdout:\n{result.stdout}\nstderr:\n{result.stderr}" + self.assertEqual(result.returncode, 0, details) + self.assertEqual(result.stdout.splitlines()[-1:], ["OK"], details) + + def test_backoff_and_interpreter_replacement(self): + self._run_drive("drive_backoff.luau") + + def test_labels_and_host_keys(self): + self._run_drive("drive_labels.luau") + + def test_payload_budget_and_encode_failure(self): + self._run_drive("drive_budget.luau") + + +if __name__ == "__main__": + unittest.main() diff --git a/window.luau b/window.luau index 65b7597..b0f4c6f 100644 --- a/window.luau +++ b/window.luau @@ -2,10 +2,12 @@ -- tern-sidepulse window observer. -- -- Every Tern window runs one copy. It enumerates the OMP sessions the window can see, projects --- them to a small status snapshot (pane id, state, outcome notice) and hands it to the Python --- helper, which forwards it to the one local coordinator that talks to SidePulse. It never --- submits prompts, approves anything, reads transcripts or changes layouts; it keeps only plain --- data between callbacks, never a `cx`, a row or a timer handle. +-- them to a small status snapshot (host, pane id, state, outcome notice, optional label) and hands +-- it to the Python helper, which forwards it to the one local coordinator that talks to SidePulse. +-- From agent rows it reads only pane, state, kind, program, host and alive. Labels come only from +-- pane titles and user-given tab names, never cwd, model or messages. No title-event subscription: +-- labels refresh within one 5 s pass. It never submits prompts, approves anything, reads transcripts +-- or changes layouts; it keeps only plain data between callbacks, never a `cx`, a row or timer handle. local VERSION = "0.1.0" local DATA = tern.plugin.data @@ -14,6 +16,9 @@ local COALESCE_MS = 75 local RECON_MS = 5000 local HELPER_TIMEOUT_MS = 4000 local MAX_OBSERVATIONS = 512 +local MAX_LABEL_BYTES = 256 +local MAX_HOST_KEY_BYTES = 128 +local MAX_SNAPSHOT_BYTES = 192 * 1024 local MAX_BACKOFF_MS = 30000 local SURFACE_OPTS = { nodes = 1, depth = 1 } -- the cheapest documented header query; never max_chars alone @@ -66,7 +71,7 @@ local S = { notices = {} :: { [number]: { id: string, kind: string, at: number } }, notice_seq = 0, diag = {} :: { [string]: number }, -- classification counts of the latest enumeration pass - stats = {} :: { [string]: number }, -- cumulative for this VM: budget_pauses, helper_failures + stats = {} :: { [string]: number }, -- cumulative for this VM: budget_pauses, helper_failures, encode_failed } local function now_ms(): number @@ -169,8 +174,85 @@ local function str(value: any): string? return nil end +local function cut_utf8(text: string, max_bytes: number): string + if #text <= max_bytes then + return text + end + local cut = max_bytes + 1 + local byte = text:byte(cut) + while byte ~= nil and byte >= 0x80 and byte <= 0xBF do + cut -= 1 + byte = text:byte(cut) + end + return text:sub(1, cut - 1) +end + +local function key_ok(key: string?): boolean + return key ~= nil + and #key > 0 + and #key <= MAX_HOST_KEY_BYTES + and utf8.len(key) ~= nil + and key:find("%c") == nil + and key:find("\194[\128-\159]") == nil +end + +local function host_key(host: any, id: number): string + if host.kind == "local" then + return "local" + end + local address = str(host.address) + if key_ok(address) then + return address :: string + end + local name = str(host.name) + if key_ok(name) then + return name :: string + end + count("host_fallback") + return "id:" .. tostring(id) +end + +local function read_labels(cx: WindowCx): { [number]: { text: string, from_tab: boolean } }? + local ok_panes, panes = pcall(function() + return cx.session:panes() + end) + if not ok_panes or type(panes) ~= "table" then + count("labels_unavailable") + return nil + end + local ok_tabs, tabs = pcall(function() + return cx.session:tabs() + end) + local tab_names: { [string]: string } = {} + if ok_tabs and type(tabs) == "table" then + for _, tab in ipairs(tabs :: { any }) do + local name = str(tab.name) + if name ~= nil and name:find("%S") then + tab_names[tostring(tab.id)] = name + end + end + else + count("labels_unavailable") + end + local labels = {} + for _, info in ipairs(panes :: { any }) do + local pane = num(info.pane) + if pane ~= nil then + local name = if info.tab ~= nil then tab_names[tostring(info.tab)] else nil + local title = str(info.title) + if name ~= nil then + labels[pane] = { text = name, from_tab = true } + elseif title ~= nil and title:find("%S") then + labels[pane] = { text = title, from_tab = false } + end + end + end + return labels +end + -- Returns coverage ("complete" | "unknown") and the observation list. Reads only pane, state, --- kind, program, host and alive from each row; titles, cwd, model and messages are never touched. +-- kind, program, host and alive from agent rows; labels use only pane titles and user-given tab +-- names, never TabInfo.title, cwd, model or messages. Labels refresh on the 5 s pass, not title events. local function enumerate(cx: WindowCx): (string, { any }) S.diag = {} local ok_agents, agents = pcall(function() @@ -184,6 +266,7 @@ local function enumerate(cx: WindowCx): (string, { any }) end local host_state: { [number]: string } = {} + local host_keys: { [number]: string } = {} local pane_host: { [number]: number } = {} local only_host: number? = nil local host_count = 0 @@ -192,6 +275,7 @@ local function enumerate(cx: WindowCx): (string, { any }) if id ~= nil then host_count += 1 host_state[id] = str(host.state) or "unknown" + host_keys[id] = host_key(host, id) if type(host.panes) == "table" then for _, pane in ipairs(host.panes) do local pid = num(pane) @@ -277,7 +361,7 @@ local function enumerate(cx: WindowCx): (string, { any }) sent_notice = { id = notice.id, kind = notice.kind } end end - table.insert(observations, { pane = pane, state = state, notice = sent_notice }) + table.insert(observations, { pane = pane, state = state, notice = sent_notice, host = host_keys[host] }) end end end @@ -297,6 +381,18 @@ local function enumerate(cx: WindowCx): (string, { any }) count("too_many") return "unknown", tern.json.array({}) end + if #observations > 0 then + local labels = read_labels(cx) + for _, observation in ipairs(observations) do + local entry = if labels ~= nil then labels[observation.pane] else nil + if entry ~= nil then + observation.label = cut_utf8(entry.text, MAX_LABEL_BYTES) + count(if entry.from_tab then "label_tab" else "label_title") + else + count("label_none") + end + end + end return "complete", tern.json.array(observations) end @@ -318,7 +414,7 @@ local function parse_result(result: ProcessResult): (any, string?) return decoded, nil end -local function run_helper(op: string, payload: any, cb: (any, string?, WindowCx?) -> ()): boolean +local function run_helper_text(op: string, stdin_text: string, cb: (any, string?, WindowCx?) -> ()): boolean if S.python == nil then resolve_python() end @@ -330,7 +426,7 @@ local function run_helper(op: string, payload: any, cb: (any, string?, WindowCx? -- the data directory (the plugin directory is watched for reloads). local python = S.python local argv = { python, "-I", "-S", "-X", "pycache_prefix=" .. DATA .. "/pycache", BRIDGE, op, "--data-dir", DATA } - local opts = { stdin = tern.json.encode(payload), timeout_ms = HELPER_TIMEOUT_MS } + local opts = { stdin = stdin_text, timeout_ms = HELPER_TIMEOUT_MS } local ok, _err = pcall(tern.process.run, argv, opts, function(result: ProcessResult, cx: WindowCx?) local decoded, code = parse_result(result) local too_old = result.status == 3 or (type(decoded) == "table" and decoded.error == "python_too_old") @@ -353,6 +449,38 @@ local function run_helper(op: string, payload: any, cb: (any, string?, WindowCx? return true end +local function run_helper(op: string, payload: any, cb: (any, string?, WindowCx?) -> ()): boolean + local ok, text = pcall(tern.json.encode, payload) + if not ok then + cb(nil, "encode_failed", nil) + return false + end + return run_helper_text(op, text, cb) +end + +local function encode_snapshot(payload: any): string? + local ok, text = pcall(tern.json.encode, payload) + if ok and #text <= MAX_SNAPSHOT_BYTES then + return text + end + local dropped = false + for _, observation in ipairs(payload.observations) do + if observation.label ~= nil then + observation.label = nil + dropped = true + end + end + if dropped then + count("labels_dropped") + payload.diag = diag_report() + ok, text = pcall(tern.json.encode, payload) + if ok and #text <= MAX_SNAPSHOT_BYTES then + return text + end + end + return nil +end + -- ---- pump: one call in flight, one newest snapshot --------------------------------------- local pump @@ -457,8 +585,14 @@ local function start_snapshot(cx: WindowCx) observations = observations, diag = diag_report(), } + local text = encode_snapshot(payload) + if text == nil then + backoff("encode_failed", nil) + tally("encode_failed") + return + end S.in_flight = true - run_helper("snapshot", payload, on_snapshot) + run_helper_text("snapshot", text, on_snapshot) end pump = function(cx: WindowCx) @@ -575,7 +709,7 @@ local function toast_result(cx: WindowCx?, title: string, body: any, code: strin if body == nil then toast(cx, "error", title, code or "helper failed") elseif body.ok == true then - toast(cx, "success", title, str(body.desired) or str(body.summary) or "ok") + toast(cx, "success", title, str(body.summary) or "ok") else toast(cx, "error", title, str(body.error) or "error") end From 5c54b36a7d0956dc8e790d2baa84f0a24aec736f Mon Sep 17 00:00:00 2001 From: Sunil Srivatsa Date: Thu, 5 Nov 2026 20:25:34 -0800 Subject: [PATCH 3/3] docs: describe tab-title labels, per-pane rows and the new limits The window now reads OMP panes' titles and user-given tab names as labels. Every owned surface says what is read, that labels stay in coordinator memory, and that SidePulse still receives one combined status until the SidePulse #72 adapter ships. --- .github/ISSUE_TEMPLATE/feature_request.yml | 4 +-- .github/pull_request_template.md | 2 +- CHANGELOG.md | 7 ++++ CONTRIBUTING.md | 31 +++++++++++------- README.md | 12 +++---- SECURITY.md | 23 +++++++++---- docs/compatibility.md | 38 +++++++++++++++++----- site/index.html | 10 +++--- 8 files changed, 86 insertions(+), 41 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index 454d37e..7cea373 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -21,7 +21,7 @@ body: id: privacy attributes: label: Privacy and security impact - description: Confirm how the change preserves the six-field agent read boundary, local-only sockets, and standard-library-only runtime. + description: Confirm how the change preserves the six-field agent read boundary (`pane`, `state`, `kind`, `program`, `host`, `alive`), in-memory-only OMP tab and pane labels, local-only sockets, and standard-library-only runtime (see `README.md#privacy-and-hardening`). validations: required: true - type: textarea @@ -33,7 +33,7 @@ body: attributes: label: Scope checks options: - - label: This keeps the plugin within its read-only status boundary (never reading transcripts, prompts, or pane titles, and never mutating Tern windows). + - label: This keeps the plugin within its read-only status boundary (never reading transcripts, prompts, working directories, or model names, keeping OMP tab and pane labels in coordinator memory only, and never mutating Tern windows). required: true - label: I understand that the runtime and tests use the Python 3.10+ standard library only. required: true diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 5c14337..beaa923 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -8,5 +8,5 @@ - [ ] `luau-lsp analyze --definitions=types/tern.d.luau window.luau` passes - [ ] Documentation facts name the exact Tern, Oh My Pi (OMP), SidePulse, and macOS versions exercised, and never describe a socket write as LED output - [ ] `python3 scripts/render_assets.py --check` passes when `assets/`, `docs/media/`, or `docs/BRAND.md` changed -- [ ] Privacy invariants in `tests/test_privacy.py` are untouched (only the six agent fields, four host fields, and `surface.role` are read; no transcripts, prompts, titles, or private paths appear in this PR) +- [ ] Privacy invariants in `tests/test_privacy.py` are untouched (only the six agent fields, the six host fields, `surface.role`, and OMP tab names or pane titles are read; labels and host keys never leave coordinator memory; and this PR description and diff contain no real user transcripts, prompts, pane titles, or private paths) - [ ] `CHANGELOG.md` is updated for user-visible changes diff --git a/CHANGELOG.md b/CHANGELOG.md index 06457ea..4858015 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## Unreleased + +- Per-pane rows in the coordinator (`tern_sidepulse/coordinator.py`, `tern_sidepulse/reducer.py`): observations are keyed by `(host, pane)` (`local`, or a remote host's `address`, `name`, or `id:`) and deduplicated across windows by mode priority (`blocked_error`, `waiting_for_input`, `working`, `completed`, `idle_ready`) and newest label, while the SidePulse hook-event transport continues to emit one combined session (`OMP in Tern`). +- In-memory session labels (`window.luau`, `tern_sidepulse/reducer.py`, `tests/test_privacy.py`, `tests/test_rows.py`): when a window has at least one OMP pane, `window.luau` reads `cx.session:panes()` and `cx.session:tabs()` at most once per 5 s pass and labels each OMP pane from its user-given tab name (`TabInfo.name`) or its own `PaneInfo.title` (cut to 256 UTF-8 bytes in the window and sanitized in the coordinator to at most 96 characters without control, surrogate, or private-use characters). Labels and host keys stay in coordinator memory only and never appear in `coordinator.log`, `doctor.json`, `bridge.py status`, coordinator acknowledgements, or the SidePulse payload (`status` and `doctor` report row counts and allow-listed diagnostic counters only). +- Snapshot budget and request limits (`window.luau`, `tern_sidepulse/limits.py`): the window keeps each encoded snapshot within 192 KiB by dropping labels and retrying once (`labels_dropped`), host keys are capped at 128 bytes in the window and 128 characters in the coordinator, and the coordinator request cap is raised from 256 KiB to 1 MiB. +- Headless Luau window harness (`tests/luau/`, `tests/test_luau_harness.py`, `.github/workflows/ci.yml`): runs the real `window.luau` under the `luau` 0.745 CLI across the backoff/interpreter/latch/role test drive (`drive_backoff.luau`, scenarios A–G), the label and host-key drive (`drive_labels.luau`, scenarios L1–L12), and the snapshot-budget drive (`drive_budget.luau`, scenarios B1–B3), bringing the suite to 155 unit and integration tests. + ## 0.1.0 — 2026-11-05 First release. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 888eb8f..ad63f83 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -10,10 +10,13 @@ behavior claims are backed by evidence, privacy boundaries stay intact, and the - **Python 3.10 or later**: the runtime (`bridge.py`, `tern_sidepulse/`) and test suite (`tests/`) use the Python standard library only (compatible with Python 3.10+, so do not import `tomllib`). Nothing is installed with `pip`, and the repository uses no Node or Bun dependencies. -- **`luau-lsp` 1.70.1**: analyzes `window.luau` against `types/tern.d.luau` (the `tern plugin types` output from Tern - 0.9.12; release archives are published at - [JohnnyMorganz/luau-lsp v1.70.1](https://github.com/JohnnyMorganz/luau-lsp/releases/tag/1.70.1), as in - [`.github/workflows/ci.yml`](.github/workflows/ci.yml)). +- **`luau-lsp` 1.70.1 and `luau` 0.745**: `luau-lsp` analyzes `window.luau` against `types/tern.d.luau` (the + `tern plugin types` output from Tern 0.9.12; release archives at + [JohnnyMorganz/luau-lsp v1.70.1](https://github.com/JohnnyMorganz/luau-lsp/releases/tag/1.70.1)), and `luau` runs + `window.luau` headlessly in `tests/test_luau_harness.py` (release archives at + [luau-lang/luau 0.745](https://github.com/luau-lang/luau/releases/tag/0.745), as in + [`.github/workflows/ci.yml`](.github/workflows/ci.yml); set `LUAU=/path/to/luau` when not on `PATH`, or + `TERN_SIDEPULSE_REQUIRE_LUAU=1` to fail instead of skipping when `luau` is absent). - **Tern 0.9.12 on macOS**: required only for manual end-to-end checks against a live Tern window and SidePulse's agent monitor (`events.sock` and `relay-events.sock`); see [`docs/compatibility.md`](docs/compatibility.md) for the probe and integration checks. @@ -52,13 +55,19 @@ to run `tests/test_sidepulse_contract.py` against the installed SidePulse normal ## Invariants and documentation standards 1. **Standard library only**: do not add third-party Python packages, external runtime tools, or network calls. -2. **Privacy invariants (`tests/test_privacy.py`)**: the window observer (`window.luau`) reads only `pane`, `state`, - `kind`, `program`, `host`, and `alive` from `cx.agents:list()`, `id`, `state`, `panes`, and `kind` from - `cx.hosts:list()`, and `surface.role` from `cx.session:surface(pane, {nodes = 1, depth = 1})`. It never reads pane - titles, working directories, model names, prompts, assistant text, tool arguments, or transcript paths. - `tests/test_privacy.py` pins that extra client fields never leave the coordinator, `doctor.json` filters window - diagnostics to known integer counters, and the SidePulse socket payload carries only the eight fixed protocol keys - (where `"prompt"` is always the constant label `"OMP in Tern"`, never user prompt text). +2. **Privacy invariants (`tests/test_privacy.py`, `tests/test_rows.py`)**: the window observer (`window.luau`) reads + only `pane`, `state`, `kind`, `program`, `host`, and `alive` from `cx.agents:list()`; `id`, `state`, `panes`, `kind`, + `address`, and `name` from `cx.hosts:list()`; `surface.role` from `cx.session:surface(pane, {nodes = 1, depth = 1})`; + and, at most once per 5 s pass when the window has at least one OMP pane, `pane`, `tab`, and `title` from + `cx.session:panes()` and `id` and `name` from `cx.session:tabs()`. Labels come only from user-given tab names + (`TabInfo.name`) and OMP panes' own `PaneInfo.title` (never `TabInfo.title`), and the plugin never reads working + directories, model names, commands, prompts, assistant text, tool arguments, or transcript paths. Labels and host + keys stay in the coordinator's memory only: they are never logged in `coordinator.log`, persisted to disk, returned + by `bridge.py status` or `doctor.json`, echoed in coordinator acknowledgements or rejections, or sent to SidePulse by + the hook-event transport. `tests/test_privacy.py` pins that sentinels in labels, host keys, and extra client fields + never leave the coordinator, `doctor.json` filters window diagnostics to allow-listed integer counters, and the + SidePulse socket payload's `line` object carries only its seven fixed status keys plus `"prompt"` on `working` + events (where `"prompt"` is always the constant `"OMP in Tern"`, never user prompt text or a pane label). 3. **Exact versions in documentation**: compatibility and behavior claims in `README.md` and [`docs/compatibility.md`](docs/compatibility.md) name the exact Tern, OMP, SidePulse, and macOS versions they were exercised against, and never describe a local socket write as physical LED output. diff --git a/README.md b/README.md index 22b3bdb..88202a3 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ tern-sidepulse is a [Tern](https://stencil.so/tern) window plugin. It puts the [ [license]: LICENSE [license-badge]: https://img.shields.io/github/license/alphastorm/tern-sidepulse?color=1C232B&labelColor=0B0E11 -Private by design: nothing listens on the network · six fields read per agent row · no transcripts, prompts, or titles · nothing installed on remote hosts +Private by design: nothing listens on the network · six fields read per agent row · no transcripts, prompts, or working directories · tab and pane labels stay in coordinator memory · nothing installed on remote hosts Community project; not affiliated with or endorsed by the Oh My Pi, Tern, or SidePulse maintainers. @@ -128,16 +128,16 @@ flowchart LR C -- Interrupt / UserPromptSubmit / … --> S["SidePulse service
relay-events.sock"] ``` -- Each Tern window runs an *observer* (the per-window `window.luau` instance) that checks `cx.agents:list()` every 5 s and on `agent_state`, `agent_finished`, `pane_closed`, `session_ended`, and `budget` events (coalesced over 75 ms). It keeps OMP panes on connected hosts whose live surface role is `omp.session` and sends a complete snapshot (pane id, state, and any 15 s completion or 30 s failure notice) through `bridge.py` to the local coordinator socket. -- The first helper call spawns one background coordinator per user that holds a singleton lock, combines all windows' snapshots in priority order (failed, waiting, working, finished, idle), and delivers the result to both SidePulse receivers (the menu-bar app on `events.sock` and the headless service on `relay-events.sock`) with bounded retry. Each window holds a 15 s *lease* (an expiry timer renewed by every complete snapshot); a closed window stops contributing when its lease expires, and the coordinator sends a final clear event and exits 5 s after the last lease ends (or after at most 60 s if SidePulse is unreachable). +- Each Tern window runs an *observer* (the per-window `window.luau` instance) that checks `cx.agents:list()` every 5 s and on `agent_state`, `agent_finished`, `pane_closed`, `session_ended`, and `budget` events (coalesced over 75 ms). It keeps OMP panes on connected hosts whose live surface role is `omp.session` and sends a complete snapshot (host key, pane id, state, any 15 s completion or 30 s failure notice, and an optional tab or pane label) through `bridge.py` to the local coordinator socket. +- The first helper call spawns one background coordinator per user that holds a singleton lock, keeps one row per OMP session keyed by `(host, pane)` and deduplicated across windows, reduces those rows in priority order (`blocked_error`, `waiting_for_input`, `working`, `completed`, `idle_ready`) to one combined status (`OMP in Tern`), and delivers the result to both SidePulse receivers (the menu-bar app on `events.sock` and the headless service on `relay-events.sock`) with bounded retry. Labels stay in the coordinator's memory only and are not sent to SidePulse. Each window holds a 15 s *lease* (an expiry timer renewed by every complete snapshot); a closed window stops contributing when its lease expires, and the coordinator sends a final clear event and exits 5 s after the last lease ends (or after at most 60 s if SidePulse is unreachable). - The plugin data directory (`$HOME/Library/Application Support/Tern/plugin-data/tern-sidepulse`) holds `identity.json` (which sets the synthetic SidePulse session id `tern-sidepulse:`), optional `config.json`, the `disabled` latch file, and `pycache/` for Python bytecode. Live observations stay in memory only so a restart never replays a stale prompt, and the SidePulse wire contract is documented in [docs/compatibility.md](docs/compatibility.md). ## Privacy and hardening -The plugin reads only `pane`, `state`, `kind`, `program`, `host`, and `alive` from each `cx.agents:list()` row, `id`, `state`, `panes`, and `kind` from `cx.hosts:list()`, and the `surface.role` of each pane. It never reads pane titles, working directories, model names, prompts, assistant text, tool arguments, or transcript paths. None of those fields appear in the helper protocol, the coordinator log, `doctor.json`, or the SidePulse socket payload (`tests/test_privacy.py` pins this). Report a vulnerability privately through [SECURITY.md](SECURITY.md). +The plugin reads `pane`, `state`, `kind`, `program`, `host`, and `alive` from each `cx.agents:list()` row; `id`, `state`, `panes`, `kind`, `address`, and `name` from `cx.hosts:list()`; and the `surface.role` of each pane. When a window has at least one OMP pane, it also calls `cx.session:panes()` and `cx.session:tabs()` at most once per 5 s pass to read `pane`, `tab`, and `title` from each pane and `id` and `name` from each tab. Each OMP pane is labelled with its user-given tab name (`TabInfo.name`) when non-blank, else the OMP pane's own `PaneInfo.title` (never `TabInfo.title`, which is whichever pane is focused in a split tab), cut to 256 bytes at a UTF-8 boundary in the window and sanitized in the coordinator (whitespace collapsed, control characters, lone surrogates, and private-use characters such as OMP's status glyph removed, trimmed, and capped at 96 characters). Labels and host keys (`local`, or a remote host's `address`, else `name`, else `id:`) travel only from the window to the helper's stdin to the coordinator's memory: they never appear in `coordinator.log`, `doctor.json`, `bridge.py status` output, coordinator acknowledgements, or the SidePulse socket payload (`status` and `doctor` report row counts — `rows` by mode, `rows_total`, `rows_labelled` — and allow-listed integer window diagnostic counters in `doctor.json`, including `label_tab`, `label_title`, `label_none`, `labels_unavailable`, `labels_dropped`, `host_fallback`, and `encode_failed`; `tests/test_privacy.py` and `tests/test_rows.py` pin this). The plugin never reads working directories, model names, commands, prompts, assistant text, tool arguments, or transcript paths. Report a vulnerability privately through [SECURITY.md](SECURITY.md). - **Private local files and sockets**: Nothing listens on the network. `~/.local/state/tern-sidepulse` (mode `0700`, ownership checked, symlinks refused) holds `coordinator.sock`, `coordinator.lock`, `coordinator.log`, and `doctor.json`; those files, `identity.json`, and `disabled` are written with mode `0600` under `umask 077`, and `coordinator.sock` is published by atomic rename after `listen(16)`. -- **Bounded requests and state**: Coordinator requests must be strict UTF-8 JSON (no `NaN`/`Infinity`, deep nesting rejected), capped at 256 KiB, EOF-framed within a 2 s read deadline, and answered within a 0.5 s write deadline across at most 32 concurrent connections. State is capped at 64 windows, 512 panes per window, and 256 registration tokens, with printable window keys of at most 64 characters. +- **Bounded requests and state**: Coordinator requests must be strict UTF-8 JSON (no `NaN`/`Infinity`, deep nesting rejected), capped at 1 MiB, EOF-framed within a 2 s read deadline, and answered within a 0.5 s write deadline across at most 32 concurrent connections; the window keeps each encoded snapshot under 192 KiB by dropping labels and retrying once (`labels_dropped`). State is capped at 64 windows, 512 panes per window, and 256 registration tokens, with printable window keys of at most 64 characters, host keys of at most 128 bytes in the window and 128 characters in the coordinator, and labels of at most 96 characters after sanitizing (a malformed label is dropped without rejecting the snapshot). - **Isolated helper execution**: Helpers run as argument vectors (never through a shell) with `python3 -I -S -X pycache_prefix=/pycache` and a 4 s timeout; running `python3 bridge.py …` from a shell sets `sys.dont_write_bytecode = True` so no `__pycache__` is written into the plugin directory. Failed helper calls back off at `500 * 2^n` ms (capped at 30 s), and interpreters below Python 3.10 (exit status 3, `python_too_old`) are skipped for the life of the window. ## Diagnostics @@ -170,7 +170,7 @@ python3 -B -m unittest discover -s tests -t . -v # -B keeps bytecode out of a luau-lsp analyze --definitions=types/tern.d.luau window.luau ``` -`types/tern.d.luau` is the `tern plugin types` output from Tern 0.9.12; regenerate it when targeting a newer Tern release. Set `SIDEPULSE_PYTHON` to a SidePulse interpreter (defaults to `~/.local/share/sidepulse/venv/bin/python` when present) to run `tests/test_sidepulse_contract.py` against the real SidePulse normalizer, and set `TERN_SIDEPULSE_SLOW_TESTS=1` to include the 20 s default-limits timing test in `tests/test_e2e.py`. +`types/tern.d.luau` is the `tern plugin types` output from Tern 0.9.12; regenerate it when targeting a newer Tern release. When the `luau` CLI is on `PATH` (or `LUAU=/path/to/luau` is set; `TERN_SIDEPULSE_REQUIRE_LUAU=1` fails instead of skipping), `tests/test_luau_harness.py` runs `window.luau` headlessly against the test drives in `tests/luau/`. Set `SIDEPULSE_PYTHON` to a SidePulse interpreter (defaults to `~/.local/share/sidepulse/venv/bin/python` when present) to run `tests/test_sidepulse_contract.py` against the real SidePulse normalizer, and set `TERN_SIDEPULSE_SLOW_TESTS=1` to include the 20 s default-limits timing test in `tests/test_e2e.py`. Artwork and demo media are rendered by `python3 scripts/render_assets.py` (requires headless Chrome, `ffmpeg` with `libx264`, and network access for the webfonts; `--check` compares the committed PNGs on the same machine; render from a checkout that is not `tern plugin link`ed, because Tern reloads the plugin on every file write). [docs/BRAND.md](docs/BRAND.md) is the brand spec, and `tests/test_site.py` keeps `README.md`, `plugin.toml`, `window.luau`, `site/`, and `.github/workflows/pages.yml` coherent. diff --git a/SECURITY.md b/SECURITY.md index 1ab6a78..68b76e5 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -18,14 +18,23 @@ maintainer's GitHub profile. The threat model and hardening controls are documented in [`README.md` — Privacy and hardening](README.md#privacy-and-hardening). In-scope areas for `tern-sidepulse` are: -- **Field-read privacy guarantees**: `window.luau` reads only `pane`, `state`, `kind`, `program`, `host`, and `alive` - from each `cx.agents:list()` row, `id`, `state`, `panes`, and `kind` from `cx.hosts:list()`, and `surface.role` from - each pane. It never reads or transmits pane titles, working directories, model names, prompts, assistant text, tool - arguments, or transcript paths (`tests/test_privacy.py` pins that extra client fields never leave the coordinator and - that the SidePulse socket payload's `"prompt"` key is always the constant string `"OMP in Tern"`). +- **Field-read and label privacy guarantees**: the per-window observer (`window.luau`) reads only `pane`, `state`, + `kind`, `program`, `host`, and `alive` from each `cx.agents:list()` row in Tern's window context (`cx`); `id`, + `state`, `panes`, `kind`, `address`, and `name` from `cx.hosts:list()`; `surface.role` from + `cx.session:surface(pane, {nodes = 1, depth = 1})`; and, at most once per 5 s pass when the window has at least one + OMP pane, `pane`, `tab`, and `title` from `cx.session:panes()` plus `id` and `name` from `cx.session:tabs()`. Labels + come only from user-given tab names (`TabInfo.name`) and OMP panes' own `PaneInfo.title` (never `TabInfo.title`), and + the plugin never reads working directories, model names, commands, prompts, assistant text, tool arguments, or + transcript paths. Labels and host keys travel only from the window to the `bridge.py` helper's stdin to the local + coordinator's memory: they never appear in `coordinator.log`, `doctor.json`, `bridge.py status` output, coordinator + acknowledgements, or the SidePulse socket payload, whose `"prompt"` key is always the constant string `"OMP in Tern"` + (`tests/test_privacy.py` and `tests/test_rows.py` pin this). - **Coordinator socket protocol**: `~/.local/state/tern-sidepulse/coordinator.sock` (and its fallback runtime paths), - strict UTF-8 JSON validation (`NaN`/`Infinity` and deep nesting rejected), the 256 KiB request cap, read/write - deadlines, connection and state caps, and observer registration token fencing. + strict UTF-8 JSON validation (`NaN`/`Infinity` and deep nesting rejected), the 1 MiB request cap (with the window's + 192 KiB snapshot budget that drops labels to fit), read/write deadlines (2 s / 0.5 s), connection (32), state (64 + windows, 512 panes per window, 256 registration tokens), host-key (128 bytes in the window, 128 characters in the + coordinator), and sanitized-label (96 characters) caps, and observer registration token fencing (rejecting superseded + or unrecognized observer generations). - **Helper execution**: `tern.process.run` argument vectors (never through a shell) using `python3 -I -S -X pycache_prefix=/pycache` with a 4 s timeout. - **Local file and directory modes**: `~/.local/state/tern-sidepulse` created and verified with mode `0700` (ownership diff --git a/docs/compatibility.md b/docs/compatibility.md index 9c6ab06..a1a1742 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -10,7 +10,7 @@ Versions exercised on the development laptop (November 5, 2026): | OMP | 18.16.0 | Shell-typed `omp` and `tern new tab -- omp` blocks | | SidePulse | 0.2.4.dev6+gffb1d3c2f (venv at `~/.local/share/sidepulse`) | Exactly the inspected revision `ffb1d3c2` | | Python | 3.15.2 (`/opt/homebrew/bin/python3`), 3.13.18 also present | `/usr/bin/python3` is 3.9.6 and is never chosen | -| Luau tooling | luau 0.745 (`luau-analyze`), luau-lsp 1.70.1 (`luau-lsp analyze --definitions=types/tern.d.luau`) | Development/CI checks only | +| Luau tooling | luau 0.745 (`luau`, `luau-analyze`), luau-lsp 1.70.1 (`luau-lsp analyze --definitions=types/tern.d.luau`) | Development/CI checks (`tests/test_luau_harness.py` and static analysis) | | Remote host | A Mac Studio attached over Tern remoting, Tern 0.9.12 there too | No SidePulse, helper, or service on the remote host | `plugin.toml` has no minimum-API field. At load, `window.luau` probes `cx.agents:list`, `cx.hosts:list`, `cx.session:surface`, and `tern.process.run` under `pcall`; when any member is missing, the window stays inert and reports the missing member through the `tern-sidepulse: doctor` toast and `doctor.json`. `tern.timer` runs in the entry chunk itself, so a Tern build without `tern.timer` fails to load the plugin outright. @@ -20,10 +20,11 @@ Versions exercised on the development laptop (November 5, 2026): `tern plugin types` from Tern 0.9.12 (pinned as `types/tern.d.luau`) matches `plugins/tern.d.luau` in the `stencil-hq/tern-sdk` `a3ba62fd` baseline for every member this plugin uses: - `AgentsCx:list(): {AgentBlock}` with `AgentBlock = {pane, command?, model?, cwd, state, last_message?, delivery_error?}` and `state` in `idle | working | waiting_input | exited`. -- `HostsCx:list(): {ManagedHost}` with `state` in `connecting | connected | stalled | verify | reconnecting | failed`, plus `sessions` and `panes` membership. +- `HostsCx:list(): {ManagedHost}` with `id`, `name`, `kind` in `local | remote`, `address?`, and `state` in `connecting | connected | stalled | verify | reconnecting | failed`, plus `sessions` and `panes` membership. - `SessionCx:surface(pane, {nodes?, depth?, max_chars?})` returning `{surface = {id, title?, role?, mode}, …}`. -- Events `agent_state({pane, old?, new})`, `agent_finished({pane, result})` with `result` in `done | failed | exited | closed`, `pane_closed`, `session_ended`, `window_start`, `budget`. -- `tern.process.run(argv, {stdin, env, timeout_ms}, cb)`, `tern.timer`, `tern.kv`, `tern.fs`, `tern.plugin.data`, `cx:window_key()`. +- `SessionCx:panes(): {PaneInfo}` with `PaneInfo = {pane, title, tab?, …}` (every pane, parked ones included; a parked pane has no `tab`) and `SessionCx:tabs(): {TabInfo}` with `TabInfo = {id, name?, title, …}` (`name` is the user-given tab name; `title` is the focused pane's title and is never read). +- Events `agent_state({pane, old?, new})`, `agent_finished({pane, result})` with `result` in `done | failed | exited | closed`, `pane_closed`, `session_ended`, `window_start`, `budget` (no `title` event subscription; labels refresh on the 5 s reconciliation pass). +- `tern.process.run(argv, {stdin, env, timeout_ms}, cb)`, `tern.timer`, `tern.kv`, `tern.fs`, `tern.json`, `tern.plugin.data`, `cx:window_key()`. Observed on 0.9.12 but undocumented in `types/tern.d.luau`: every `cx.agents:list()` row also carries `host` (the host id from `cx.hosts:list()`), `program` (`"omp"`), `kind` (`"agent"`), `alive`, `session`, `tab`, `busy`, `at_prompt`, `alert`, `title`, `running`, `last`, and, while working, `progress = {percent, state}`. The plugin reads `host` and `alive` when present and falls back to the documented fields (`host.panes` and `row.state`) when absent. `kind` and `program` are counted in diagnostics only and never decide classification, so a Tern build that reports different values cannot hide OMP sessions. @@ -53,10 +54,30 @@ Consequences built into the plugin: - Classification checks only `surface.role == "omp.session"`, re-read on every 5 s reconciliation pass (0.01–0.1 ms per pane; the cached result only bridges a surface query that fails outright). A missing surface (OMP still starting) is counted on the next pass that sees the role, and a pane whose role changes in place drops out on the next pass. `program` and `kind` are diagnostics only because wrapped launches such as `tern new tab -- env … omp` report `program = "env"`, while titles, `cwd`, and missing `command` are never used as evidence. - A 5 s reconciliation timer re-enumerates panes because daemon-side closes emit no window event. Each window holds a 15 s *lease* (an expiry timer at the coordinator, renewed by every complete snapshot), which tolerates one failed helper call; two consecutive failures expire the lease and withdraw that window's contribution for the ~150 ms needed to register again on the next call. -- Each window registers as an *observer* (the per-window `window.luau` instance reporting snapshots) identified by `(parent pid of the helper, TERN_WINDOW_KEY)`, and pane ids are opaque within that observer. A helper whose parent pid changes on every call (such as a forking wrapper configured as `python`) is fenced on every snapshot; after three consecutive fence rejections the window backs off exponentially (`500 * 2^n` ms, capped at 30 s) instead of re-registering continuously, and `doctor` reports the cause. +- Each window registers as an *observer* (the per-window `window.luau` instance reporting snapshots) identified by `(parent pid of the helper, TERN_WINDOW_KEY)`. Inside the coordinator, each OMP session row is keyed by `(host, pane)` — where `host` is `local` or the remote host's `address` (else `name`, else `id:`) — and deduplicated across windows. A helper whose parent pid changes on every call (such as a forking wrapper configured as `python`) is fenced on every snapshot; after three consecutive fence rejections the window backs off exponentially (`500 * 2^n` ms, capped at 30 s) instead of re-registering continuously, and `doctor` reports the cause. - An interpreter that exits with status 3 (`python_too_old`, with a JSON body; on this laptop `/usr/bin/python3`, 3.9.6) is rejected for the life of the window VM and the next candidate is tried; `/usr/bin/python3` is tried last and only when `/Library/Developer/CommandLineTools/usr/bin/python3` exists. - The coordinator answers each client on a blocking write with a 0.5 s deadline across at most 32 concurrent connections; a same-user client that connects and never reads can delay the loop by at most 0.5 s per connection. Lease and notice deadlines are checked against the clock after each request and on every 1 s reaper tick, so a stalled loop withdraws state rather than prolonging it. +## Labels and host keys + +Additional contract probes on the development laptop (November 5, 2026) verified how Tern 0.9.12 exposes pane titles, tab names, host addresses, and JSON encoding: + +| Probe | Result | +| --- | --- | +| `cx.session:panes()` and `cx.session:tabs()` scope and cost | Both cover every session in the window, including panes and tabs on attached remote hosts, and cost about 0.03 ms each | +| Tab join (`PaneInfo.tab` vs. `TabInfo.id`) | `PaneInfo.tab` equals `TabInfo.id`; a parked pane has `tab = nil` | +| Tab names vs. tab titles | Unnamed tabs have no `name` (`TabInfo.name == nil`); `TabInfo.title` is the focused pane's title (in a split tab, whichever pane has focus, such as `zsh`), so `TabInfo.title` is never read | +| OMP pane titles (`PaneInfo.title`) | Start with a Unicode private-use status glyph (such as `U+F1517` or `U+F412`), a space, and the session title | +| `tern.json.encode` | Emits raw UTF-8, escapes C0 control characters, and replaces invalid UTF-8 byte sequences with `U+FFFD` | + +How the window and coordinator handle labels and host keys (and the integer diagnostic counters `window.luau` reports in `doctor.json` under `window_diag`): + +- **Per-pass lookup and label precedence**: When a window pass has at least one OMP observation, `window.luau` calls `cx.session:panes()` and `cx.session:tabs()` at most once per 5 s pass under `pcall` (an empty pass skips both calls; a failed call increments the `labels_unavailable` diagnostic counter and preserves status reporting). Each OMP pane takes its tab's user-given `TabInfo.name` when that string has a non-space character (incrementing `label_tab`), else the OMP pane's own `PaneInfo.title` when non-blank (incrementing `label_title`), else no label (incrementing `label_none`). +- **Host key**: `local` for the local host, or a remote host's `address` when non-empty, free of control characters, and at most 128 bytes, else its `name`, else `id:` (incrementing `host_fallback`). +- **Sanitize rule (`tern_sidepulse/reducer.py`)**: The coordinator collapses whitespace runs to one space, removes C0 controls (`U+0000`–`U+001F`), `DEL` and C1 controls (`U+007F`–`U+009F`), lone surrogates (`U+D800`–`U+DFFF`), and Unicode private-use characters (`U+E000`–`U+F8FF`, `U+F0000`–`U+FFFFD`, `U+100000`–`U+10FFFD`, including OMP's status glyph), trims leading and trailing spaces, and caps the result at 96 characters (an empty string becomes `None`). A malformed wire label is dropped without rejecting the snapshot. +- **Size chain**: `window.luau` cuts each label to at most 256 bytes at a UTF-8 character boundary (`MAX_LABEL_BYTES = 256`) and caps host keys at 128 bytes (`MAX_HOST_KEY_BYTES = 128`) across at most 512 observations per window. If the encoded snapshot exceeds 192 KiB (`MAX_SNAPSHOT_BYTES = 192 * 1024`) or `tern.json.encode` fails while labels are present, the window strips all labels, increments `labels_dropped`, and re-encodes once so status delivery still succeeds (a persistent encode failure increments `encode_failed` and backs off). The coordinator caps requests at 1 MiB (`max_request_bytes = 1024 * 1024`), host keys at 128 characters, and sanitized labels at 96 characters. +- **Privacy and SidePulse boundary**: Labels and host keys travel only from the window to the helper's stdin to the coordinator's memory. They never appear in `coordinator.log`, `doctor.json`, `bridge.py status` output, coordinator acknowledgements, or the SidePulse socket payload (`status` and `doctor` report `rows` by mode, `rows_total`, `rows_labelled`, and the allow-listed window diagnostic counters `label_tab`, `label_title`, `label_none`, `labels_unavailable`, `labels_dropped`, `host_fallback`, and `encode_failed` only). SidePulse still receives one synthetic session (`tern-sidepulse:`), origin `Tern`, constant `"OMP in Tern"` title, and one combined mode; per-session rows in SidePulse require [SidePulse PR #72](https://github.com/inteliwear/sidepulse/pull/72)'s `program_status` protocol, so the `tern-sidepulse` program-status adapter and the `tern-sidepulse` 0.2.0 release are held until `inteliwear/sidepulse#72` merges and ships in a SidePulse release. + ## SidePulse contract (verified against the installed collector) Driven through the installed package's `parse_log_line` and `LiveAgentMonitor` with provider `omp` (`tests/fixtures/sidepulse_probe.py` checks the mode after each step of the status and trap rows in this table): @@ -97,12 +118,11 @@ Each check reads `coordinator.log`, `bridge.py status`, and SidePulse's `status- | Full Tern quit and relaunch (`osascript -e 'tell application "Tern" to quit'` with three working sessions, windows closed about 19 s, relaunched from the Dock) | The session daemon (`tern remote serve --user`) kept every pane's program alive, including the OMP sessions. The coordinator (same pid, started 00:55 UTC) logged `observer 1542:: generation 100 lease expired` 15.0 s after the last snapshot and sent `idle_ready` to both receivers in the same millisecond (SidePulse: `Working` → `Idle`); the relaunched app (pid 19961) registered two fresh observers (`19961:` with three working panes, `19961:2` with none) and its first snapshot restored `working` on both receivers 3.7 s after the neutral; `expired_observers` 1 | | Remote disconnect/reconnect from the host dialog (sf-studio over Tern remoting, one working OMP session there beside two local ones) | The dialog's disconnect *forgets* the host (`cx.hosts:disconnect`; `tern remote hosts` listed nothing), so the pane simply left `cx.agents:list()`: within one 5 s pass the observer's snapshot went from `working: 3` (`diag omp: 3`) to `working: 2` (`diag omp: 2`), and the aggregate stayed `working` on the two local panes; no `host_unavailable` count, because that only covers a host still listed in a non-connected state. Reconnecting from the dialog brought the remote pane back on the next pass (`working: 3`, `diag omp: 3`) under the same observer generation; SidePulse showed `Working` throughout | -Automated suite ([`../README.md#development`](../README.md#development)): 111 unit and integration tests in total (`python3 -B -m unittest discover -s tests -t .`), verified on Python 3.13.18 and 3.15.2 locally and on Python 3.10 and 3.13 in CI. The 111 tests cover an end-to-end subprocess coordinator with fake receivers, hostile-client inputs (deep nesting, `NaN`/`Infinity`, non-printable observer keys, and symlinked, FIFO, or oversized `config.json`), the coherence of the README, `plugin.toml`, the palette commands, the rendered media and the site (`tests/test_site.py`), and include two conditional tests: +Automated suite ([`../README.md#development`](../README.md#development)): 155 unit and integration tests in total (`python3 -B -m unittest discover -s tests -t .`), verified on Python 3.13.18 and 3.15.2 locally and on Python 3.10 and 3.13 in CI. The 155 tests cover an end-to-end subprocess coordinator with fake receivers, per-pane row reduction and cross-window deduplication (`tests/test_rows.py`), sentinel checks proving labels, host keys, and unknown fields never leave the coordinator in memory or across subprocesses (`tests/test_privacy.py`), hostile-client inputs (deep nesting, `NaN`/`Infinity`, non-printable observer keys, and symlinked, FIFO, or oversized `config.json`), the coherence of the README, `plugin.toml`, the palette commands, the rendered media, and the site (`tests/test_site.py`), and three conditional test modules: +- `tests/test_luau_harness.py` (`LuauHarnessTest`): runs the real `window.luau` headlessly under the `luau` CLI (`tests/luau/harness.luau`, `window.luau`, and each drive script; skipped when `luau` is absent unless `TERN_SIDEPULSE_REQUIRE_LUAU=1` is set, and run in CI's `luau` job under Luau 0.745). It exercises backoff, interpreter replacement, disabled-latch notice dropping, synchronous command failure toasts, and in-place role changes (`drive_backoff.luau`, scenarios A–G), user-given tab names vs. OMP pane titles, UTF-8 byte truncation, optional `panes()`/`tabs()` failures, per-pass call counts, remote host keys, and 5 s rename refresh (`drive_labels.luau`, scenarios L1–L12), and the 192 KiB encoded snapshot budget with label-drop fallback and encoder-failure recovery (`drive_budget.luau`, scenarios B1–B3). - `tests/test_sidepulse_contract.py` (`SidePulseContractTest.test_mapping_table_and_traps`): runs when a SidePulse interpreter exists at `SIDEPULSE_PYTHON` or `~/.local/share/sidepulse/venv/bin/python` and skips otherwise. -- `tests/test_e2e.py` (`EndToEndTest.test_default_limits_neutral_within_20s`): runs only when `TERN_SIDEPULSE_SLOW_TESTS=1` is set (skipped in the default fast run, which reports `Ran 111 tests … OK (skipped=1)` when SidePulse is installed) and checks that an unrenewed 15 s lease reaches `idle_ready` within the 20 s target. - -The window half's retry policy (backoff up to 30 s while the coordinator is unavailable or every snapshot is fenced, replacement of a `python_too_old` interpreter, and `warn`-level failure/recovery logging) was exercised with a standalone `luau` harness driving `window.luau` against a fake `tern` environment. +- `tests/test_e2e.py` (`EndToEndTest.test_default_limits_neutral_within_20s`): runs only when `TERN_SIDEPULSE_SLOW_TESTS=1` is set (skipped in the default fast run, which reports `Ran 155 tests … OK (skipped=1)` on the development laptop with `luau` and SidePulse installed) and checks that an unrenewed 15 s lease reaches `idle_ready` within the 20 s target. Not exercised here, with the exact check still to run: diff --git a/site/index.html b/site/index.html index f9b67ea..5a1511b 100644 --- a/site/index.html +++ b/site/index.html @@ -174,15 +174,15 @@

From window state to one status.

Private by design

-

Six fields in, one status out.

+

Six agent fields in, one status out.

-

The plugin never reads pane titles, working directories, model names, prompts, assistant text, tool arguments, or transcript paths.

+

The plugin never reads working directories, model names, prompts, assistant text, tool arguments, or transcript paths. OMP tab names and pane titles stay in the coordinator's memory and are never logged or sent to SidePulse.

    -
  • Reads six fields, never transcripts

    pane, state, kind, program, host, alive from each agent row. Host membership and each pane's surface.role identify connected OMP panes. tests/test_privacy.py pins what is read.

  • +
  • Reads six agent fields, never transcripts

    pane, state, kind, program, host, alive from each agent row, plus host keys and each pane's surface.role. OMP tab names and pane titles stay in coordinator memory only (tests/test_privacy.py).

  • Nothing listens on the network

    The helper, coordinator, and SidePulse receivers communicate through private local sockets. Live observations stay in memory only; a restart never replays a stale prompt.

  • Private local files and sockets

    ~/.local/state/tern-sidepulse has mode 0700; ownership is checked and symlinks are refused. Runtime and state files are written with mode 0600.

  • -
  • Bounded requests and state

    Requests are capped at 256 KiB, with at most 32 concurrent connections. State is capped at 64 windows and 512 panes per window.

  • +
  • Bounded requests and state

    Window snapshots are budgeted to 192 KiB and coordinator requests are capped at 1 MiB across at most 32 concurrent connections. State is capped at 64 windows and 512 panes per window.

  • Isolated helper execution

    Argument vectors, never a shell; -I -S isolation and a 4 s timeout. Failed calls back off at 500 · 2ⁿ ms, capped at 30 s.

  • Remote hosts need nothing installed

    No SidePulse, no helper, and no service on a remote host. OMP sessions are observed through the open Tern window connected to that host.

@@ -251,7 +251,7 @@

Exact versions, not “latest”.

  • ExercisedTern 0.9.12 (e498b49) · OMP 18.16.0SidePulse revision ffb1d3c2 (0.2.4.dev6+gffb1d3c2f), macOS 27.2 on Apple Silicon, and a remote Mac Studio over Tern remoting; a 78 s sleep/wake, a full Tern quit and relaunch, and a remote disconnect/reconnect, each read from the coordinator log and SidePulse's own state files.
  • -
  • AutomatedUnit and integration suite on Python 3.10 and 3.13 in CIPlus luau-lsp analysis of window.luau.
  • +
  • AutomatedUnit and integration suite on Python 3.10 and 3.13 in CIPlus luau-lsp analysis and the headless Luau 0.745 harness for window.luau.
  • Not yet exercisedA remote host that stays listed but drops to a non-connected stateAnd the two-window close-one case with OMP sessions in both windows.

Timings come from socket and state-file records; a socket write is not an LED check. Read the compatibility and contract probe.