The core still hard-coded links into plugin pages (Files → Goals / Skills / Agents / Forms cards and drawer links, Dashboards → Performance, Settings → What's new and its editor, the home Analytics icon, skill/agent pills) and ~25 old addresses that forwarded to them (/goals, /skills, /dashboards/plan, /whats-new, /memories/<slug>…). On a hub without those plugins (raw-hub) they opened 404 pages. Now every link to a plugin page comes from its manifest: - bottom-bar drawers: every `files` / `dashboards` plugin page joins its section's drawer (past five slots into the stash), key `<section>/p:<plugin>:<page>`; saved slots of the core's old links map to the plugins' (SUB_RENAMED); - Files landing: the plugins' Files pages are its cards; Files panel: the hard-coded Goals row is gone; - What's new + editor leave the settings registry (the plugin's own `nav: "settings"` pages); - new optional page fields (written only when set — `ui` is in the approval fingerprint): `perm` (the page reaches its holders only), `header: "home"` (a button in the home page's head — Analytics), `tag` (the tag kind whose pills open the page at <page>/<slug> — skill, agent), `feature` (the App usage id its visits count under, so a former core page keeps its history; else plugin.<plugin>.<page>, in the frontend and telemetry/views.registry); - the old addresses and their redirect components are dropped; the owner's usage rings, the burn gauge and the Stats redirect link nowhere into a plugin; the plan-usage and /tmp-full pushes open /dashboards. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
490 lines
22 KiB
Python
490 lines
22 KiB
Python
"""What agent sessions keep on disk — agent-probe's storage records (and
|
|
claude-probe's before it), pulled with the calls (``/callmeta``, calls.py):
|
|
every Claude Code session's scratchpad and background-task output
|
|
(``/tmp/claude-<uid>/<cwd>/<session>/`` — a RAM tmpfs on Linux), the git
|
|
worktrees sessions made, the transcripts of Claude Code, opencode, Codex and
|
|
pi, opencode's snapshots and command output, extra roots a runner tracks
|
|
(``~/worktrees``), and each filesystem under them. An item's ``agent`` (in its
|
|
``data``) says whose kind of session it belongs to.
|
|
|
|
Tables (in ``perf.db``):
|
|
|
|
- ``perf_storage`` — one row per item and runner, the newest version wins:
|
|
kind, owner session, ``bytes`` (allocated, like du) and ``own`` (only this
|
|
item's blocks: what removing it would free — a hardlink-copied
|
|
node_modules costs ~nothing), its git state when a worktree. An item that
|
|
disappears is kept ``GONE_KEEP_S`` with ``gone_at``.
|
|
- ``perf_disks`` — each filesystem now (size, avail, tmpfs = RAM) and the
|
|
tracked items' share of it; ``perf_disk_history`` a sample every
|
|
``HISTORY_EVERY_S`` (30 days).
|
|
- ``perf_storage_grow`` — what one Bash call added to (or removed from) its
|
|
session's scratchpad and worktrees (``+1.9 GB``), keyed by tool_use_id.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import time
|
|
|
|
GONE_KEEP_S = 30 * 86400
|
|
HISTORY_EVERY_S = 600
|
|
HISTORY_KEEP_S = 30 * 86400
|
|
STALE_DAYS = 3.0
|
|
|
|
SCHEMA = """
|
|
CREATE TABLE IF NOT EXISTS perf_storage (
|
|
runner TEXT NOT NULL,
|
|
path TEXT NOT NULL,
|
|
kind TEXT NOT NULL, -- scratchpad | worktree | transcript | root | snapshot | output
|
|
sid TEXT, -- the session it belongs to / that made it
|
|
bytes INTEGER DEFAULT 0,
|
|
own INTEGER DEFAULT 0,
|
|
files INTEGER DEFAULT 0,
|
|
newest REAL,
|
|
mount TEXT, ram INTEGER DEFAULT 0,
|
|
gone_at REAL,
|
|
scanned REAL,
|
|
data TEXT,
|
|
PRIMARY KEY (runner, path)
|
|
);
|
|
CREATE INDEX IF NOT EXISTS perf_storage_sid ON perf_storage (sid);
|
|
CREATE TABLE IF NOT EXISTS perf_storage_sessions (
|
|
runner TEXT NOT NULL, path TEXT NOT NULL, sid TEXT NOT NULL,
|
|
PRIMARY KEY (runner, path, sid)
|
|
);
|
|
CREATE INDEX IF NOT EXISTS perf_storage_sessions_sid ON perf_storage_sessions (sid);
|
|
CREATE TABLE IF NOT EXISTS perf_disks (
|
|
runner TEXT NOT NULL, mount TEXT NOT NULL,
|
|
fstype TEXT, ram INTEGER DEFAULT 0,
|
|
total INTEGER, avail INTEGER, at REAL,
|
|
data TEXT,
|
|
PRIMARY KEY (runner, mount)
|
|
);
|
|
CREATE TABLE IF NOT EXISTS perf_disk_history (
|
|
runner TEXT NOT NULL, mount TEXT NOT NULL, t REAL NOT NULL,
|
|
total INTEGER, avail INTEGER, claude INTEGER,
|
|
PRIMARY KEY (runner, mount, t)
|
|
);
|
|
CREATE TABLE IF NOT EXISTS perf_storage_grow (
|
|
tool_use_id TEXT PRIMARY KEY,
|
|
runner TEXT NOT NULL, sid TEXT NOT NULL, at REAL,
|
|
delta INTEGER DEFAULT 0,
|
|
data TEXT
|
|
);
|
|
CREATE INDEX IF NOT EXISTS perf_storage_grow_sid ON perf_storage_grow (sid);
|
|
CREATE TABLE IF NOT EXISTS perf_storage_alerts (
|
|
runner TEXT NOT NULL, mount TEXT NOT NULL,
|
|
pushed_at REAL, used REAL,
|
|
PRIMARY KEY (runner, mount)
|
|
);
|
|
"""
|
|
|
|
# A RAM filesystem (/tmp as a tmpfs) this full pushes once; it re-arms once
|
|
# it is back under REARM_AT.
|
|
ALERT_AT = 0.85
|
|
REARM_AT = 0.80
|
|
|
|
_UPSERT = """
|
|
INSERT INTO perf_storage VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)
|
|
ON CONFLICT (runner, path) DO UPDATE SET
|
|
kind = excluded.kind, sid = excluded.sid, bytes = excluded.bytes, own = excluded.own,
|
|
files = excluded.files, newest = excluded.newest, mount = excluded.mount, ram = excluded.ram,
|
|
gone_at = excluded.gone_at, scanned = excluded.scanned, data = excluded.data
|
|
"""
|
|
|
|
|
|
def records(runner: str, recs: list[dict], now: float) -> list[tuple[str, list[tuple]]]:
|
|
"""The statements one page of ``/callmeta`` records needs (storage, disk,
|
|
grow; the rest is calls.py's)."""
|
|
items, sess_del, sess, disks, hist, grows = [], [], [], [], [], []
|
|
for r in recs:
|
|
kind, d = r.get("kind"), r.get("data") or {}
|
|
if kind == "storage" and d.get("path"):
|
|
gone = d.get("goneAt") if d.get("gone") else None
|
|
items.append((runner, d["path"], d.get("kind") or "?", d.get("sessionId") or None,
|
|
d.get("bytes") or 0, d.get("own") or 0, d.get("files") or 0,
|
|
d.get("newestAt"), d.get("mount"), 1 if d.get("ram") else 0,
|
|
gone, d.get("scannedAt") or now, json.dumps(d, separators=(",", ":"))))
|
|
sess_del.append((runner, d["path"]))
|
|
for sid in {*(d.get("sessions") or []), *([d["sessionId"]] if d.get("sessionId") else [])}:
|
|
sess.append((runner, d["path"], sid))
|
|
elif kind == "disk" and d.get("mount"):
|
|
at = d.get("at") or now
|
|
# agent-probe's per-kind totals (claude-probe called them ``claude``)
|
|
claude = sum((v or {}).get("own") or 0 for v in _agents(d).values())
|
|
disks.append((runner, d["mount"], d.get("fsType"), 1 if d.get("ram") else 0,
|
|
d.get("total"), d.get("avail"), at, json.dumps(d, separators=(",", ":"))))
|
|
hist.append((runner, d["mount"], at, d.get("total"), d.get("avail"), claude))
|
|
elif kind == "grow" and d.get("toolUseId"):
|
|
delta = sum(i.get("delta") or 0 for i in d.get("items") or [])
|
|
grows.append((d["toolUseId"], runner, d.get("sessionId") or "", d.get("at"), delta,
|
|
json.dumps(d, separators=(",", ":"))))
|
|
out: list[tuple[str, list[tuple]]] = []
|
|
if items:
|
|
out += [(_UPSERT, items),
|
|
("DELETE FROM perf_storage_sessions WHERE runner = ? AND path = ?", sess_del),
|
|
("INSERT OR IGNORE INTO perf_storage_sessions VALUES (?,?,?)", sess)]
|
|
if disks:
|
|
out.append(("INSERT OR REPLACE INTO perf_disks VALUES (?,?,?,?,?,?,?,?)", disks))
|
|
# a history sample per HISTORY_EVERY_S (the newest of the window wins)
|
|
out.append(("INSERT OR REPLACE INTO perf_disk_history VALUES (?,?,?,?,?,?)",
|
|
[(r, m, int(t // HISTORY_EVERY_S * HISTORY_EVERY_S), tot, av, c)
|
|
for r, m, t, tot, av, c in hist]))
|
|
if grows:
|
|
out.append(("INSERT OR REPLACE INTO perf_storage_grow VALUES (?,?,?,?,?,?)", grows))
|
|
return out
|
|
|
|
|
|
def _agents(d: dict) -> dict:
|
|
"""A disk record's per-kind totals of the agents' items."""
|
|
return d.get("agents") or d.get("claude") or {}
|
|
|
|
|
|
def prune(store, now: float | None = None) -> None:
|
|
now = now or time.time()
|
|
store.write([
|
|
("DELETE FROM perf_storage WHERE gone_at IS NOT NULL AND gone_at < ?", [(now - GONE_KEEP_S,)]),
|
|
("DELETE FROM perf_storage_sessions WHERE NOT EXISTS (SELECT 1 FROM perf_storage s"
|
|
" WHERE s.runner = perf_storage_sessions.runner AND s.path = perf_storage_sessions.path)", [()]),
|
|
("DELETE FROM perf_disk_history WHERE t < ?", [(now - HISTORY_KEEP_S,)]),
|
|
])
|
|
|
|
|
|
# ── reads ────────────────────────────────────────────────────────────────────
|
|
|
|
def _idle_s(d: dict, now: float) -> float | None:
|
|
g = d.get("git") or {}
|
|
if g.get("idleS") is not None and g.get("at"):
|
|
return g["idleS"] + max(0.0, now - g["at"])
|
|
return (now - d["newestAt"]) if d.get("newestAt") else None
|
|
|
|
|
|
def verdict(d: dict, now: float, running: bool) -> str:
|
|
"""What the item is, for the cleanup: ``live`` (its session runs),
|
|
``stale`` (safe to remove — a merged clean worktree or a scratch dir idle
|
|
``STALE_DAYS``), ``work`` (a worktree holding commits or changes main
|
|
doesn't have), ``keep`` (transcripts, roots, recent)."""
|
|
kind = d.get("kind")
|
|
if running:
|
|
return "live"
|
|
idle = _idle_s(d, now) or 0
|
|
if kind == "worktree":
|
|
g = d.get("git") or {}
|
|
if g.get("dirty") or g.get("merged") is False:
|
|
return "work"
|
|
if g.get("merged") and g.get("dirty") == 0 and idle >= STALE_DAYS * 86400:
|
|
return "stale"
|
|
return "keep"
|
|
if kind == "scratchpad":
|
|
return "stale" if idle >= STALE_DAYS * 86400 else "keep"
|
|
return "keep"
|
|
|
|
|
|
def item_view(d: dict, runner: str, now: float, running: set[str]) -> dict:
|
|
sids = [s for s in [d.get("sessionId"), *(d.get("sessions") or [])] if s]
|
|
live = any(s in running for s in sids)
|
|
return {
|
|
"runner": runner, "path": d.get("path"), "kind": d.get("kind"), "label": d.get("label"),
|
|
"agent": d.get("agent"),
|
|
"sessionId": d.get("sessionId"), "sessions": list(dict.fromkeys(sids)),
|
|
"project": d.get("project"), "bytes": d.get("bytes") or 0, "own": d.get("own") or 0,
|
|
"files": d.get("files") or 0, "newestAt": d.get("newestAt"), "idleS": _idle_s(d, now),
|
|
"mount": d.get("mount"), "ram": bool(d.get("ram")), "partial": bool(d.get("partial")),
|
|
"top": d.get("top") or [], "git": d.get("git"), "createdBy": d.get("createdBy"),
|
|
"scannedAt": d.get("scannedAt"), "gone": bool(d.get("gone")), "goneAt": d.get("goneAt"),
|
|
"running": live, "verdict": verdict(d, now, live),
|
|
}
|
|
|
|
|
|
def _rows(store, where: str, args: tuple) -> list[tuple[str, dict]]:
|
|
out = []
|
|
for runner, raw in store.query(f"SELECT runner, data FROM perf_storage WHERE {where}", args):
|
|
try:
|
|
out.append((runner, json.loads(raw)))
|
|
except (TypeError, ValueError):
|
|
continue
|
|
return out
|
|
|
|
|
|
def overview(store, running: set[str], now: float | None = None, limit: int = 300,
|
|
scope=None) -> dict:
|
|
"""Every runner's filesystems, totals per kind and the biggest items
|
|
(scratchpads, worktrees and roots all; transcripts only in the totals and
|
|
their top few — they are many and Claude Code prunes them itself).
|
|
|
|
``scope`` (perf/scope.py, the profile switch): only the items of its
|
|
conversations — an item no session claims is its machine's — and the
|
|
machines it shows or that hold one of those items."""
|
|
now = now or time.time()
|
|
runners: dict[str, dict] = {}
|
|
if scope is not None and not scope.all:
|
|
return _scoped_overview(store, running, now, limit, scope)
|
|
|
|
def rv(r: str) -> dict:
|
|
return runners.setdefault(r, {"runner": r, "disks": [], "kinds": {}, "items": [],
|
|
"emptyScratch": 0, "stale": {"items": 0, "own": 0}})
|
|
|
|
for runner, raw in store.query("SELECT runner, data FROM perf_disks ORDER BY mount"):
|
|
try:
|
|
d = json.loads(raw)
|
|
except (TypeError, ValueError):
|
|
continue
|
|
d["agents"] = _agents(d)
|
|
d.pop("claude", None)
|
|
rv(runner)["disks"].append(d)
|
|
rv(runner)["emptyScratch"] += d.get("emptyScratch") or 0
|
|
for runner, kind, n, b, o in store.query(
|
|
"SELECT runner, kind, COUNT(*), SUM(bytes), SUM(own) FROM perf_storage"
|
|
" WHERE gone_at IS NULL GROUP BY runner, kind"):
|
|
rv(runner)["kinds"][kind] = {"items": n, "bytes": b or 0, "own": o or 0}
|
|
for runner, d in _rows(store, "gone_at IS NULL AND kind != 'transcript' ORDER BY own DESC LIMIT ?", (limit,)) + \
|
|
_rows(store, "gone_at IS NULL AND kind = 'transcript' ORDER BY own DESC LIMIT 10", ()):
|
|
v = item_view(d, runner, now, running)
|
|
rv(runner)["items"].append(v)
|
|
if v["verdict"] == "stale":
|
|
rv(runner)["stale"]["items"] += 1
|
|
rv(runner)["stale"]["own"] += v["own"]
|
|
for r in runners.values():
|
|
r["items"].sort(key=lambda v: -v["own"])
|
|
return {"at": now, "runners": sorted(runners.values(), key=lambda r: r["runner"] != "lab")}
|
|
|
|
|
|
def _scoped_overview(store, running: set[str], now: float, limit: int, scope) -> dict:
|
|
""":func:`overview` for one profile — the same shape, filtered in Python
|
|
(a few thousand rows: the kinds by session, the items by their sessions)."""
|
|
runners: dict[str, dict] = {}
|
|
held: set[str] = set()
|
|
|
|
def rv(r: str) -> dict:
|
|
return runners.setdefault(r, {"runner": r, "disks": [], "kinds": {}, "items": [],
|
|
"emptyScratch": 0, "stale": {"items": 0, "own": 0}})
|
|
|
|
for runner, kind, sid, n, b, o in store.query(
|
|
"SELECT runner, kind, sid, COUNT(*), SUM(bytes), SUM(own) FROM perf_storage"
|
|
" WHERE gone_at IS NULL GROUP BY runner, kind, sid"):
|
|
if not scope.conv(runner, sid):
|
|
continue
|
|
held.add(runner)
|
|
k = rv(runner)["kinds"].setdefault(kind, {"items": 0, "bytes": 0, "own": 0})
|
|
k["items"] += n
|
|
k["bytes"] += b or 0
|
|
k["own"] += o or 0
|
|
rows = _rows(store, "gone_at IS NULL AND kind != 'transcript' ORDER BY own DESC", ()) + \
|
|
_rows(store, "gone_at IS NULL AND kind = 'transcript' ORDER BY own DESC LIMIT 500", ())
|
|
shown = {"transcript": 0, "other": 0}
|
|
for runner, d in rows:
|
|
bucket = "transcript" if d.get("kind") == "transcript" else "other"
|
|
if shown[bucket] >= (10 if bucket == "transcript" else limit):
|
|
continue
|
|
if not scope.item(runner, [d.get("sessionId"), *(d.get("sessions") or [])]):
|
|
continue
|
|
shown[bucket] += 1
|
|
held.add(runner)
|
|
v = item_view(d, runner, now, running)
|
|
rv(runner)["items"].append(v)
|
|
if v["verdict"] == "stale":
|
|
rv(runner)["stale"]["items"] += 1
|
|
rv(runner)["stale"]["own"] += v["own"]
|
|
for runner, raw in store.query("SELECT runner, data FROM perf_disks ORDER BY mount"):
|
|
if not (scope.machine(runner) or runner in held):
|
|
continue
|
|
try:
|
|
d = json.loads(raw)
|
|
except (TypeError, ValueError):
|
|
continue
|
|
d["agents"] = _agents(d)
|
|
d.pop("claude", None)
|
|
rv(runner)["disks"].append(d)
|
|
rv(runner)["emptyScratch"] += d.get("emptyScratch") or 0
|
|
for r in runners.values():
|
|
r["items"].sort(key=lambda v: -v["own"])
|
|
return {"at": now, "runners": sorted(runners.values(), key=lambda r: r["runner"] != "lab")}
|
|
|
|
|
|
def history(store, runner: str, mount: str, since: float) -> list[dict]:
|
|
return [{"t": t, "total": tot, "avail": av, "claude": c} for t, tot, av, c in store.query(
|
|
"SELECT t, total, avail, claude FROM perf_disk_history WHERE runner = ? AND mount = ?"
|
|
" AND t >= ? ORDER BY t", (runner, mount, since))]
|
|
|
|
|
|
def conversation(store, sid: str, running: set[str], now: float | None = None) -> dict:
|
|
"""One conversation's items (it owns them or worked in them) and what each
|
|
of its calls added."""
|
|
now = now or time.time()
|
|
rows = store.query(
|
|
"SELECT s.runner, s.data FROM perf_storage s JOIN perf_storage_sessions x"
|
|
" ON x.runner = s.runner AND x.path = s.path WHERE x.sid = ?"
|
|
" AND (s.gone_at IS NULL OR s.gone_at > ?) ORDER BY s.own DESC", (sid, now - 7 * 86400))
|
|
items = []
|
|
for runner, raw in rows:
|
|
try:
|
|
items.append(item_view(json.loads(raw), runner, now, running))
|
|
except (TypeError, ValueError):
|
|
continue
|
|
left = sum(i["own"] for i in items if not i["gone"] and i["kind"] != "transcript")
|
|
n, w, f = store.query(
|
|
"SELECT COUNT(*), SUM(json_extract(data, '$.files.written')), SUM(json_extract(data, '$.files.freed'))"
|
|
" FROM perf_calls WHERE sid = ? AND disk_net IS NOT NULL", (sid,))[0]
|
|
return {"sessionId": sid, "items": items, "left": left,
|
|
"writes": {"calls": n or 0, "written": int(w or 0), "freed": int(f or 0),
|
|
"net": int((w or 0) - (f or 0))},
|
|
"transcript": sum(i["own"] for i in items if i["kind"] == "transcript" and not i["gone"]),
|
|
"grows": grows(store, sid)}
|
|
|
|
|
|
def of_sessions(store, sids, running: set[str], now: float | None = None,
|
|
limit: int = 20, within=None) -> dict:
|
|
"""What a set of sessions keeps on disk now (a guest's Stats,
|
|
dashboards/guest_perf.py): the items one of them owns — its scratchpad,
|
|
its transcript, a worktree it made — or, when no session owns it, that
|
|
only they worked in; totals per kind over all of them, the ``limit``
|
|
biggest as items. An item another session owns, or that another session
|
|
also worked in without an owner, is left out: it is not only theirs.
|
|
``within`` (a subset of ``sids``) keeps only the items of those sessions
|
|
— the period's."""
|
|
now = now or time.time()
|
|
out = {"at": None, "totals": {"items": 0, "bytes": 0, "own": 0}, "kinds": {}, "items": []}
|
|
if not sids:
|
|
return out
|
|
js = json.dumps(sorted(sids))
|
|
inside = "SELECT value FROM json_each(?)"
|
|
rows = store.query(
|
|
"SELECT s.runner, s.data FROM perf_storage s WHERE s.gone_at IS NULL AND ("
|
|
f" s.sid IN ({inside})"
|
|
" OR (s.sid IS NULL"
|
|
" AND EXISTS (SELECT 1 FROM perf_storage_sessions x WHERE x.runner = s.runner"
|
|
f" AND x.path = s.path AND x.sid IN ({inside}))"
|
|
" AND NOT EXISTS (SELECT 1 FROM perf_storage_sessions x WHERE x.runner = s.runner"
|
|
f" AND x.path = s.path AND x.sid NOT IN ({inside}))))"
|
|
" ORDER BY s.own DESC", (js, js, js))
|
|
items = []
|
|
for runner, raw in rows:
|
|
try:
|
|
it = item_view(json.loads(raw), runner, now, running)
|
|
except (TypeError, ValueError):
|
|
continue
|
|
if within is None or any(s in within for s in it["sessions"]):
|
|
items.append(it)
|
|
for it in items:
|
|
k = out["kinds"].setdefault(it["kind"], {"items": 0, "bytes": 0, "own": 0})
|
|
for t in (k, out["totals"]):
|
|
t["items"] += 1
|
|
t["bytes"] += it["bytes"]
|
|
t["own"] += it["own"]
|
|
if it["scannedAt"] and (out["at"] is None or it["scannedAt"] > out["at"]):
|
|
out["at"] = it["scannedAt"]
|
|
out["items"] = items[:limit]
|
|
return out
|
|
|
|
|
|
def grows(store, sid: str) -> dict[str, dict]:
|
|
out = {}
|
|
for tid, raw in store.query("SELECT tool_use_id, data FROM perf_storage_grow WHERE sid = ?", (sid,)):
|
|
try:
|
|
out[tid] = json.loads(raw)
|
|
except (TypeError, ValueError):
|
|
continue
|
|
return out
|
|
|
|
|
|
def left_by_session(store, sids: list[str]) -> dict[str, int]:
|
|
"""Own bytes each session still keeps (scratchpad + worktrees it made) —
|
|
the conversation list's chip."""
|
|
if not sids:
|
|
return {}
|
|
q = ",".join("?" * len(sids))
|
|
return {sid: own or 0 for sid, own in store.query(
|
|
f"SELECT sid, SUM(own) FROM perf_storage WHERE gone_at IS NULL AND kind IN"
|
|
f" ('scratchpad', 'worktree') AND sid IN ({q}) GROUP BY sid", tuple(sids))}
|
|
|
|
|
|
def tmp_alerts(store, threshold: float) -> list[dict]:
|
|
"""Filesystems in RAM (tmpfs) — or any tracked one — past ``threshold``
|
|
used: what a push should say."""
|
|
out = []
|
|
for runner, mount, ram, total, avail, raw in store.query(
|
|
"SELECT runner, mount, ram, total, avail, data FROM perf_disks"):
|
|
if not total:
|
|
continue
|
|
used = 1 - (avail or 0) / total
|
|
if used >= threshold:
|
|
try:
|
|
d = json.loads(raw)
|
|
except (TypeError, ValueError):
|
|
d = {}
|
|
out.append({"runner": runner, "mount": mount, "ram": bool(ram), "used": used,
|
|
"avail": avail, "total": total, "agents": _agents(d)})
|
|
return out
|
|
|
|
|
|
def is_safe_path(p: str) -> bool:
|
|
return bool(p) and os.path.isabs(p) and ".." not in p.split("/")
|
|
|
|
|
|
def due_alerts(store, now: float | None = None) -> list[dict]:
|
|
"""The RAM filesystems that just went past ``ALERT_AT``: each is booked
|
|
(one push per crossing — INSERT OR IGNORE, so the blue-green cutover's two
|
|
backends can't both push), and the ones back under ``REARM_AT`` re-armed."""
|
|
now = now or time.time()
|
|
over = [a for a in tmp_alerts(store, REARM_AT) if a["ram"]]
|
|
still = {(a["runner"], a["mount"]) for a in over}
|
|
booked = {(r, m) for r, m in store.query("SELECT runner, mount FROM perf_storage_alerts")}
|
|
rearm = [k for k in booked if k not in still]
|
|
if rearm:
|
|
store.write([("DELETE FROM perf_storage_alerts WHERE runner = ? AND mount = ?", rearm)])
|
|
fresh = []
|
|
for a in over:
|
|
if a["used"] < ALERT_AT or (a["runner"], a["mount"]) in booked:
|
|
continue
|
|
if store.insert_once("INSERT OR IGNORE INTO perf_storage_alerts VALUES (?,?,?,?)",
|
|
(a["runner"], a["mount"], now, a["used"])):
|
|
fresh.append(a)
|
|
return fresh
|
|
|
|
|
|
def alert_push(a: dict, runner_name: str) -> dict:
|
|
scratch = ((a.get("agents") or {}).get("scratchpad") or {}).get("own") or 0
|
|
held = f" — session scratchpads hold {_fmt(scratch)}" if scratch else ""
|
|
return {
|
|
"title": f"💾 {a['mount']} on {runner_name} is {round(a['used'] * 100)}% full",
|
|
"message": f"It is RAM (a tmpfs): {_fmt(a.get('avail') or 0)} left{held}. "
|
|
"When it fills, every session's command output fails. Clean up the stale ones.",
|
|
"type": "warn",
|
|
"url": "/dashboards",
|
|
}
|
|
|
|
|
|
def _fmt(n: int) -> str:
|
|
v, u = float(n), ["B", "KB", "MB", "GB", "TB"]
|
|
i = 0
|
|
while v >= 1024 and i < len(u) - 1:
|
|
v /= 1024
|
|
i += 1
|
|
return f"{v:.0f} {u[i]}" if v >= 100 or i < 2 else f"{v:.1f} {u[i]}"
|
|
|
|
|
|
def writers(store, since: float, limit: int = 20, keep=None) -> list[dict]:
|
|
"""The calls that left the most on disk (net, exact) since ``since`` —
|
|
``keep(runner, sid)``: only those calls (the profile switch)."""
|
|
out = []
|
|
for tid, runner, sid, tool, label, cmd, started, net, raw in store.query(
|
|
"SELECT tool_use_id, runner, sid, tool, label, command, started, disk_net,"
|
|
" json_extract(data, '$.files') FROM perf_calls WHERE disk_net IS NOT NULL"
|
|
" AND started >= ? ORDER BY disk_net DESC LIMIT ?",
|
|
(since, limit if keep is None else max(limit * 50, 1000))):
|
|
if keep is not None and not keep(runner, sid):
|
|
continue
|
|
if len(out) >= limit:
|
|
break
|
|
try:
|
|
files = json.loads(raw) if raw else {}
|
|
except (TypeError, ValueError):
|
|
files = {}
|
|
out.append({"toolUseId": tid, "runner": runner, "sessionId": sid, "tool": tool,
|
|
"label": label, "command": (cmd or "")[:300], "startedAt": started,
|
|
"net": net, "written": files.get("written") or 0, "freed": files.get("freed") or 0,
|
|
"files": files.get("files") or 0, "top": (files.get("top") or [])[:3],
|
|
"dirs": (files.get("dirs") or [])[:3]})
|
|
return out
|