Files
gabrielvidalandClaude Opus 5.5 c7c0c92fe4 fix(askform): past the 1000-form cap the mirror re-added evicted forms forever
Every sync re-added the oldest closed forms a machine still listed (new +
changed), the GC dropped others, and each read published dozens of askform
SSE events (~2/s since 12:50 on 2026-11-27). Every tab then refetched
/api/inbox/waiting + /api/ask-form/forms, the 40-thread pool sat at 40/40
and every request waited 30 s (phones gave up: Traefik 499s).

- store remembers what its GC dropped; skip_report() keeps the mirror from
  taking those back, or any closed form older than 30 days it doesn't hold
- cap 1000 -> 5000

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:13:52 +01:00

462 lines
21 KiB
Python

"""
The hub's mirror of the forms agents ask with the standalone **ask-form**
tool (github.com/GabrielVidal1/ask-form) — one record per form, across every
machine the hub reads (the lab host, the paired workers).
ask-form is the form engine: `ask-form serve` on each machine keeps the
forms, answers them on its own pages (https://ask-form.xyz/f/<id>) and hands
the answers to the agent's `ask-form wait`. The hub never stores a form of
its own here — it *mirrors* what each machine's serve reports (through the
sidecar's /ask-form proxy, or the serve's events webhook) so it can draw the
card in the thread, push the link to the phone, list open forms in *Waiting
for feedback* and badge the conversation. The mirror is read-mostly; revoke /
close go back to the machine.
A record is the Go `FormJSON` plus what the hub adds:
machine which runner reported it ("lab" or a worker id)
sessionId meta.session — the Claude session that created it (the link
back to the conversation; the CLI stamps CLAUDE_SESSION_ID)
url / publicUrl the respondent link, token included. The admin API never
returns it (only `ask-form create` prints it), so it comes from
the events webhook or from a transcript (the clarifier scan).
Kept so the push and the waiting card can open the form.
description from the events webhook (the admin API's list omits it)
fields the spec, fetched on demand for the answers recap
pushed the hub sent the "📋 title" push for it (once, ever)
seenAt when this hub first saw it
One JSON file, rewritten atomically; capped — the oldest closed records go
first. Ids are ask-form's (`<kebab-title>_<6 chars>`).
"""
from __future__ import annotations
import datetime
import json
import os
import pathlib
import re
import time
import sqlite3
import threading
from urllib.parse import urlsplit
_SCHEMA = """
CREATE TABLE IF NOT EXISTS askforms (
id TEXT PRIMARY KEY,
status TEXT,
session_id TEXT,
machine TEXT,
created_at TEXT,
data_json TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS askforms_status ON askforms (status);
CREATE INDEX IF NOT EXISTS askforms_session ON askforms (session_id);
CREATE TABLE IF NOT EXISTS _meta (
key TEXT PRIMARY KEY,
value TEXT
);
"""
ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,60}_[a-z0-9]{6}$")
OPEN = "pending"
_MAX = 5000
# A closed form the hub doesn't hold, closed longer ago than this, is the
# machine's history, not news: the mirror leaves it out (:meth:`skip_report`).
STALE_CLOSED_SECS = 30 * 86400
# What the mirror copies off a FormJSON as is.
_COPIED = ("title", "status", "createdAt", "expiresAt", "closedAt", "answers",
"reason", "reasonFiles", "multi", "maxAnswers", "hideCount", "answerCount",
"responses", "meta", "warning")
# Present only on some replies (create / the webhook / get?fields=1): never
# overwritten by a reply that lacks them.
_STICKY = ("url", "publicUrl", "description", "fields")
# A respondent link is a page of an `ask-form serve` (or its relay):
# ``https://ask-form.xyz/f/<id>?token=…`` or, on the machine itself,
# ``http://127.0.0.1:7462/f/<id>?token=…``. Anything else a machine or a
# transcript hands over is dropped: the app opens these links, frames them
# and pushes them to phones, so a ``javascript:`` or look-alike one is an
# attack, never a form (docs/security.md, 2026-11-15).
_LOOPBACK = ("127.0.0.1", "localhost", "::1")
_LINK_MAX = 2048
_LINK_BAD = re.compile(r"[\s\\\x00-\x1f\x7f<>\"'`]")
# …and a link read off a *transcript* (``learn``, ``adopt_link``) must also sit
# on a relay the hub knows or on loopback: a transcript holds whatever the
# agent read, and a look-alike page with the form's id in its path is exactly
# what a hostile web page would print. ``ASKFORM_LINK_HOSTS`` (comma-separated)
# adds a self-hosted relay.
RELAY_HOSTS = frozenset({"ask-form.xyz"} | {
h.strip().lower() for h in os.environ.get("ASKFORM_LINK_HOSTS", "").split(",") if h.strip()})
def clean_link(url, fid: str | None = None, *, relay_only: bool = False) -> str | None:
"""``url`` when it is a plausible respondent link — https (plain http
only on loopback, the machine's own serve), a bare host with no
credentials, and ``/f/<fid>`` in its path — else None. ``relay_only``:
its host must be a known relay (:data:`RELAY_HOSTS`) or loopback."""
if not isinstance(url, str) or not url or len(url) > _LINK_MAX or _LINK_BAD.search(url):
return None
try:
p = urlsplit(url)
host = (p.hostname or "").lower()
p.port # noqa: B018 — raises on a malformed port
except ValueError:
return None
if not host or "@" in p.netloc:
return None
if p.scheme != "https" and not (p.scheme == "http" and host in _LOOPBACK):
return None
if fid and f"/f/{fid}" not in p.path:
return None
if relay_only and host not in RELAY_HOSTS and host not in _LOOPBACK:
return None
return url
def _now_iso() -> str:
return datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
def parse_iso(s: str | None) -> float | None:
if not s:
return None
try:
return datetime.datetime.fromisoformat(str(s).replace("Z", "+00:00")).timestamp()
except ValueError:
return None
class AskFormStore:
def __init__(self, path: str):
self.path = pathlib.Path(path)
self.db_path = self.path.with_suffix(".db")
self.db_path.parent.mkdir(parents=True, exist_ok=True)
self._lock = threading.Lock()
self._forms: dict[str, dict] = {}
# Closed forms :meth:`_gc` dropped: a machine that still lists one
# must not bring it back (:meth:`skip_report`).
self._evicted: set[str] = set()
self._db = sqlite3.connect(str(self.db_path), check_same_thread=False)
self._db.execute("PRAGMA journal_mode=WAL")
self._db.execute("PRAGMA synchronous=NORMAL")
self._db.execute("PRAGMA busy_timeout=5000")
self._db.execute("PRAGMA journal_size_limit=16777216")
self._db.executescript(_SCHEMA)
self._db.commit()
self._load()
# ── persistence ───────────────────────────────────────────────────────
@staticmethod
def _vet_links(fid: str, rec: dict) -> None:
for k in ("url", "publicUrl"):
if rec.get(k) and not clean_link(rec[k], fid):
rec.pop(k)
def _load(self) -> None:
migrated = self._db.execute(
"SELECT value FROM _meta WHERE key='migrated_mtime'"
).fetchone()
count = self._db.execute("SELECT COUNT(*) FROM askforms").fetchone()[0]
if migrated is None and count == 0 and self.path.exists():
try:
st_mtime = self.path.stat().st_mtime
data = json.loads(self.path.read_text(encoding="utf-8"))
except (OSError, ValueError):
data = None
st_mtime = None
forms = data.get("forms") if isinstance(data, dict) else None
if isinstance(forms, dict):
rows = []
for fid, rec in forms.items():
if not (isinstance(rec, dict) and ID_RE.match(fid)):
continue
rec = dict(rec)
self._vet_links(fid, rec)
rows.append((
fid, rec.get("status") or "", rec.get("sessionId") or "",
rec.get("machine") or "", rec.get("createdAt") or "",
json.dumps(rec, ensure_ascii=False),
))
if rows:
self._db.executemany(
"INSERT OR REPLACE INTO askforms "
"(id, status, session_id, machine, created_at, data_json) "
"VALUES (?,?,?,?,?,?)",
rows,
)
if st_mtime is not None:
self._db.execute(
"INSERT INTO _meta (key, value) VALUES ('migrated_mtime', ?) "
"ON CONFLICT(key) DO UPDATE SET value=excluded.value",
(str(st_mtime),),
)
self._db.commit()
loaded: dict[str, dict] = {}
for fid, raw in self._db.execute("SELECT id, data_json FROM askforms").fetchall():
if not ID_RE.match(fid):
continue
try:
rec = json.loads(raw)
except (ValueError, TypeError):
continue
if isinstance(rec, dict):
self._vet_links(fid, rec)
loaded[fid] = rec
self._forms = loaded
def _put_row(self, fid: str, rec: dict) -> str:
"""Persist one record + GC oldest closed rows in one transaction (lock held)."""
raw = json.dumps(rec, ensure_ascii=False)
self._db.execute(
"INSERT INTO askforms (id, status, session_id, machine, created_at, data_json) "
"VALUES (?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET "
"status=excluded.status, session_id=excluded.session_id, "
"machine=excluded.machine, created_at=excluded.created_at, "
"data_json=excluded.data_json",
(fid, rec.get("status") or "", rec.get("sessionId") or "",
rec.get("machine") or "", rec.get("createdAt") or "", raw),
)
self._gc()
self._db.commit()
return raw
def _gc(self) -> None:
if len(self._forms) <= _MAX:
return
closed = sorted((r for r in self._forms.values() if r.get("status") != OPEN),
key=lambda r: r.get("createdAt") or "")
gone = [r["id"] for r in closed[: len(self._forms) - _MAX]]
for fid in gone:
self._forms.pop(fid, None)
self._evicted.add(fid)
if gone:
self._db.execute(
f"DELETE FROM askforms WHERE id IN ({','.join('?' * len(gone))})",
gone,
)
# ── reads ─────────────────────────────────────────────────────────────
def get(self, fid: str) -> dict | None:
with self._lock:
r = self._forms.get(fid)
return json.loads(json.dumps(r)) if r else None
def iter_shallow(self) -> list[dict]:
"""Shallow list of all records from memory (no JSON deep copy).
Callers must treat the returned dicts as read-only."""
with self._lock:
return list(self._forms.values())
def pending_unlinked(self) -> list[dict]:
"""Pending forms that have a sessionId but no respondent link yet."""
with self._lock:
return [dict(r) for r in self._forms.values()
if r.get("status") == OPEN and r.get("sessionId")
and not r.get("url") and not r.get("publicUrl")]
def list(self, *, status: str | None = None, session: str | None = None,
machine: str | None = None, limit: int = 0) -> list[dict]:
"""Newest first (by createdAt). Deep-copies only matching/returned items."""
with self._lock:
out = [r for r in self._forms.values()
if (not status or r.get("status") == status)
and (not session or r.get("sessionId") == session)
and (not machine or r.get("machine") == machine)]
out.sort(key=lambda r: r.get("createdAt") or "", reverse=True)
if limit:
out = out[:limit]
return json.loads(json.dumps(out))
def pending_machines(self) -> set[str]:
with self._lock:
return {r.get("machine") or "" for r in self._forms.values()
if r.get("status") == OPEN}
# ── writes ────────────────────────────────────────────────────────────
def skip_report(self, f: dict) -> bool:
"""True when a machine's read lists a closed form the hub doesn't
hold and shouldn't take back: one :meth:`_gc` dropped, or one closed
more than :data:`STALE_CLOSED_SECS` ago. A pending form, or one the
hub holds, is never skipped.
2026-11-27: past :data:`_MAX` forms in all, every sync re-added the
oldest closed forms as new + changed, the GC dropped others, and each
read published dozens of ``askform`` SSE events (~2/s for hours); each
made every tab refetch the inbox and the forms list, the 40-thread
pool sat at 40/40 and every request waited 30 s."""
fid = str(f.get("id") or "")
if not fid or f.get("status") in (None, "", OPEN):
return False
with self._lock:
if fid in self._forms:
return False
if fid in self._evicted:
return True
ts = parse_iso(f.get("closedAt") or f.get("createdAt"))
return ts is not None and time.time() - ts > STALE_CLOSED_SECS
def upsert(self, machine: str, f: dict, *, trusted: bool = True) -> tuple[dict, bool, bool]:
"""Merge one FormJSON reported by ``machine``. Returns ``(record, new,
changed)`` — ``changed`` is a status / answers / link change the
viewer should hear about (SSE), ``new`` a form no machine reported
before (unknown, or only a transcript placeholder).
``trusted`` is False for a guest's computer: it may then only report
forms of its own (:class:`ValueError` for a record another machine
filed, or one that sits in another conversation), and its links
never replace one the hub already holds. Whoever reports it, a link
that isn't a form's page is dropped (:func:`clean_link`)."""
fid = str(f.get("id") or "")
if not ID_RE.match(fid):
raise ValueError(f"not an ask-form id: {fid!r}")
meta = f.get("meta") if isinstance(f.get("meta"), dict) else None
session = str(meta["session"]) if meta and meta.get("session") else ""
with self._lock:
old = self._forms.get(fid)
if old and not trusted:
if old.get("machine") not in (None, "", machine):
raise ValueError(f"{fid} is another machine's form")
if old.get("sessionId") and old["sessionId"] != session:
raise ValueError(f"{fid} belongs to another conversation")
# A transcript's placeholder (``learn``) is no machine's form yet:
# this is the hub's first real sight of it, as for an unknown one —
# or the mirror's push (``new`` + pending) would never go out.
first = old is None or bool(old.get("placeholder"))
rec = dict(old) if old else {"id": fid, "seenAt": _now_iso(), "pushed": False}
rec.pop("placeholder", None)
rec["machine"] = machine
for k in _COPIED:
if k in f and f[k] is not None:
rec[k] = f[k]
elif k in ("answerCount", "responses") and k in rec and k not in f and f.get("multi") is None:
pass
for k in _STICKY:
v = f.get(k)
if k in ("url", "publicUrl"):
v = clean_link(v, fid)
if v and rec.get(k) and not trusted:
continue # a guest's computer never swaps a known link
if v:
rec[k] = v
if session:
rec["sessionId"] = session
rec.setdefault("sessionId", "")
rec.setdefault("status", OPEN)
rec.setdefault("title", fid)
changed = (not old or any(old.get(k) != rec.get(k) for k in
("status", "answers", "reason", "answerCount", "url",
"publicUrl", "title", "sessionId")))
self._forms[fid] = rec
if changed or first or old.get("fields") != rec.get("fields"):
raw = self._put_row(fid, rec)
return json.loads(raw), first, changed
return json.loads(json.dumps(rec)), first, changed
def learn(self, fid: str, *, url: str | None = None,
public_url: str | None = None, session: str | None = None) -> dict | None:
"""A link (or session) seen elsewhere — a transcript's `ask-form create`
output. Creates a placeholder when the mirror hasn't met the form yet
(its machine fills in on the next sync).
A transcript also holds whatever the agent read — a web page, a mail —
so it only ever *fills in*: a link the record already has stays, a
form already in a conversation stays there, a form of another
conversation takes nothing from this one, and only a form's page
counts as a link (:func:`clean_link`)."""
if not ID_RE.match(fid or ""):
return None
url = clean_link(url, fid, relay_only=True)
public_url = clean_link(public_url, fid, relay_only=True)
with self._lock:
existing = self._forms.get(fid)
if existing is None:
if not (url or public_url):
return None # nothing worth a placeholder
rec = {"id": fid, "machine": "", "title": fid, "status": OPEN,
"sessionId": "", "seenAt": _now_iso(), "pushed": False,
"placeholder": True}
elif session and existing.get("sessionId") and existing["sessionId"] != session:
return json.loads(json.dumps(existing))
else:
rec = dict(existing)
changed = False
for k, v in (("url", url), ("publicUrl", public_url), ("sessionId", session)):
if v and not rec.get(k):
rec[k] = v
changed = True
if changed or existing is None:
self._forms[fid] = rec
raw = self._put_row(fid, rec)
return json.loads(raw)
return json.loads(json.dumps(rec))
def adopt_link(self, fid: str, *, url: str | None = None,
public_url: str | None = None,
session: str | None = None) -> dict | None:
"""Fill in the link of a form some machine already reported, from a
transcript that printed it (``askform/links.py``). Unlike ``learn`` it
never creates a record, never moves a form to another conversation and
never replaces a link the events webhook gave: a transcript is the
agent's own output, so it is trusted only for a form of its own
session. Returns the record when something changed, else None."""
with self._lock:
existing = self._forms.get(fid)
if not existing:
return None
if session and existing.get("sessionId") and existing["sessionId"] != session:
return None
rec = dict(existing)
changed = False
for k, v in (("url", clean_link(url, fid, relay_only=True)),
("publicUrl", clean_link(public_url, fid, relay_only=True))):
if v and not rec.get(k):
rec[k] = v
changed = True
if not changed:
return None
self._forms[fid] = rec
raw = self._put_row(fid, rec)
return json.loads(raw)
def claim_push(self, fid: str) -> bool:
"""True exactly once per form: whoever gets it sends the push."""
with self._lock:
existing = self._forms.get(fid)
if not existing or existing.get("pushed"):
return False
rec = dict(existing)
rec["pushed"] = True
self._forms[fid] = rec
self._put_row(fid, rec)
return True
def claim_event(self, fid: str, flag: str) -> bool:
"""True at most once per ``(fid, flag)`` — guards plugin event dispatch
against webhook + mirror + recheck races."""
with self._lock:
existing = self._forms.get(fid)
if not existing or existing.get(flag):
return False
rec = dict(existing)
rec[flag] = True
self._forms[fid] = rec
self._put_row(fid, rec)
return True
def set_fields(self, fid: str, fields: list) -> dict | None:
with self._lock:
existing = self._forms.get(fid)
if not existing:
return None
rec = dict(existing)
rec["fields"] = fields
self._forms[fid] = rec
raw = self._put_row(fid, rec)
return json.loads(raw)