Approvals, New project and Plans now build on the ask-form live plugin, so
nothing creates frm_ forms any more. Per Gabriel's call ("retire
completely", no read-only viewer):
- backend: delete forms/ (routes, service, store, secrets), schemas/forms,
the /api/forms* routes and their authz lines, the worker outbox's `form`
kind, the frm_ scan in tree.py and the pending-forms check in auto-archive
- cli: drop notify wait frm_ / cancel / secret (ask-form secret replaces it)
- frontend: delete FormWidget, FormModal, FormPager, FormFields, formDraft,
formGroups, the Forms page (/forms now redirects to the ask-form plugin's
Forms page) and the generated form models; the dock keeps ask-form frames
only; SandboxedHtml stays
- merge fix-ups: a conflict marker left in cli/notify.py's docstring, the
BottomBar test's Files sub-links, an unused French string, and the
FormDock test now warms the lazy AskFormFrame chunk (its cold import
outlasted waitFor once FormModal stopped importing it statically)
- docs: CLAUDE.md and docs/clarifier.md no longer describe frm_ forms
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
345 lines
14 KiB
Python
345 lines
14 KiB
Python
"""Auto-archive: the conversations nobody needs to look at fold away by
|
|
themselves (``meta.archived`` — off the default list, still readable).
|
|
|
|
Two kinds, both stamped ``meta.autoArchived = {kind, at}`` when they go:
|
|
|
|
* **cron** — a run a cron job started (``meta.cron``), once it finished
|
|
*successfully*: its turn ended cleanly (the CLI's turn-end record, no API
|
|
error it gave up on, not interrupted), no question is left open on it
|
|
(an ask-form form, a hub form, a tappable ask) and it sent no ``error`` /
|
|
``warn`` push. A job opts out with ``archiveOnSuccess: false`` (Settings →
|
|
Cron).
|
|
* **test** — a conversation started to try something out: ``meta.test``
|
|
(``ai-agent new --test``, the MCP ``start_conversation`` ``test`` flag, or
|
|
stamped afterwards), or one whose working dir is a temp dir — another
|
|
session's scratchpad is where a nested ``claude -p`` runs. Archived once its
|
|
turn ends (or it was stopped), whatever the outcome: the session that ran it reads the result
|
|
with ``ai-agent wait`` / ``show``, which see archived conversations.
|
|
|
|
The sweep runs every ``SWEEP_S`` over the card list (memoized — the list
|
|
endpoint builds the same one) and only archives a conversation that has been
|
|
settled for ``SETTLE_S``. The rules apply to conversations started after the
|
|
feature first ran (``since``, kept in the store) — the past was archived once,
|
|
by hand (``POST /api/conversations/auto-archive`` with ``backfill``).
|
|
|
|
Unarchiving wins: an archived conversation the owner brings back (the card's
|
|
*Unarchive*, ``ai-agent archive --undo``) gets ``autoArchiveOff`` and is never
|
|
swept again. A new turn sent to an archived conversation unarchives it
|
|
(runs/service.py); a cron conversation someone continues is a conversation
|
|
now, so it opts out too, while a test one is swept again once that turn ends.
|
|
|
|
A swept **test** run's pushes go off the owner's home New list with it
|
|
(dismissed in the read ledger, as a manual archive does); a cron run's stay —
|
|
its push is the job's report (``DISMISS_KINDS``).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import datetime
|
|
import logging
|
|
import os
|
|
import re
|
|
import threading
|
|
import time
|
|
|
|
from conversations import catalog
|
|
from conversations.cards import _resolve_state, _subagent_activity
|
|
from conversations.tree import _conv_id, _is_sidechain_path
|
|
from core import liveruns
|
|
|
|
_ORIG_CONVERSATION_CARDS = catalog._conversation_cards
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
SWEEP_S = float(os.environ.get("AUTO_ARCHIVE_SWEEP_S", "30"))
|
|
SETTLE_S = float(os.environ.get("AUTO_ARCHIVE_SETTLE_S", "60"))
|
|
ENABLED = os.environ.get("AUTO_ARCHIVE", "1") != "0"
|
|
_SINCE_KEY = "auto_archive_since"
|
|
|
|
KINDS = ("cron", "test")
|
|
# A test run is done however it stopped; a cron run only counts when finished.
|
|
DONE_STATES = ("finished", "interrupted")
|
|
# A push of these types means the run wants a look (container-updates pushes
|
|
# only when something is left broken, encombrants-release on a failed build).
|
|
ALERT_TYPES = ("error", "warn")
|
|
# Whose pushes the sweep dismisses with the conversation (off the owner's New
|
|
# list, like a manual archive). Not a cron run's: its push *is* the job's
|
|
# report (radar's digest, pr-watch's news) and the run is folded away a minute
|
|
# after it lands — dismissing it would hide the report before it is read.
|
|
DISMISS_KINDS = ("test",)
|
|
# Where a nested `claude -p` / a throwaway run works: a Claude scratchpad
|
|
# (/tmp/claude-<uid>/<project>/<session>/scratchpad/…), any other temp dir, a
|
|
# Mac's $TMPDIR (/var/folders/…, /private/var/folders/…).
|
|
_TEMP_RE = re.compile(r"^(/private)?(/tmp|/var/tmp|/var/folders)(/|$)")
|
|
# The session whose scratchpad it is — the run that started it.
|
|
_SCRATCH_RE = re.compile(r"^/(?:private/)?tmp/claude-\d+/[^/]+/([0-9a-f-]{36})/scratchpad(/|$)")
|
|
|
|
|
|
def _now() -> str:
|
|
return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
|
|
|
|
def _epoch(iso: str | None) -> float | None:
|
|
try:
|
|
return datetime.datetime.fromisoformat((iso or "").replace("Z", "+00:00")).timestamp()
|
|
except ValueError:
|
|
return None
|
|
|
|
|
|
def temp_cwd(cwd: str | None) -> bool:
|
|
return bool(cwd) and bool(_TEMP_RE.match(cwd))
|
|
|
|
|
|
def scratch_parent(cwd: str | None) -> str | None:
|
|
"""The session whose scratchpad ``cwd`` is in, if it is one."""
|
|
m = _SCRATCH_RE.match(cwd or "")
|
|
return m.group(1) if m else None
|
|
|
|
|
|
def kind_of(m: dict, summary: dict, jobs: dict[str, dict]) -> str | None:
|
|
"""Which rule a conversation falls under, if any (before the outcome)."""
|
|
if m.get("archived") or m.get("autoArchiveOff") or m.get("owner"):
|
|
return None # a guest's conversations are theirs to tidy
|
|
if m.get("test") or temp_cwd(summary.get("cwd")):
|
|
return "test"
|
|
cron = m.get("cron") or {}
|
|
if cron.get("id"):
|
|
job = jobs.get(cron["id"])
|
|
if job is not None and job.get("archiveOnSuccess") is False:
|
|
return None
|
|
return "cron"
|
|
return None
|
|
|
|
|
|
def succeeded(summary: dict, m: dict, open_sessions: set[str], sid: str,
|
|
legacy: bool = False) -> bool:
|
|
"""A cron run's clean finish: its turn ended on its own, no API error, no
|
|
question left open, no alert pushed. ``legacy`` (the backfill) also takes
|
|
the end signals a transcript from before the turn-end record had — the
|
|
exit watcher's stamp, a DONE / COMPLETED sign-off."""
|
|
ended = summary.get("turnEnded") or (legacy and (
|
|
m.get("exitedAt") or summary.get("doneMarker") or summary.get("completedMarker")))
|
|
if not ended or summary.get("lastApiError"):
|
|
return False
|
|
if summary.get("interruptedByUser") or summary.get("pausedByUser") \
|
|
or summary.get("waitingForTrigger"):
|
|
return False
|
|
if sid in open_sessions:
|
|
return False
|
|
return not any((n.get("type") or "") in ALERT_TYPES
|
|
for n in m.get("notifications") or [])
|
|
|
|
|
|
def open_question_sessions(deps) -> set[str]:
|
|
"""Sessions with a question still waiting on someone — one pass per sweep."""
|
|
out: set[str] = set()
|
|
try:
|
|
iter_af = getattr(deps.askform_store, "iter_shallow", None)
|
|
if iter_af is not None:
|
|
out |= {f.get("sessionId") for f in iter_af()
|
|
if f.get("status") == "pending"}
|
|
else:
|
|
out |= {f.get("sessionId") for f in deps.askform_store.list(status="pending")}
|
|
except Exception:
|
|
log.exception("auto-archive: ask-form list failed")
|
|
try:
|
|
pending_asks = getattr(deps.notify_store, "pending_ask_sessions", None)
|
|
if pending_asks is not None:
|
|
out |= set(pending_asks())
|
|
else:
|
|
out |= {e.get("sessionId") for e in deps.notify_store.log(limit=500)
|
|
if e.get("kind") == "ask" and e.get("status") == "pending"}
|
|
except Exception:
|
|
log.exception("auto-archive: ask list failed")
|
|
try:
|
|
from plugins import waiting as plugin_waiting
|
|
out |= plugin_waiting.waiting_sessions(deps)
|
|
except Exception:
|
|
log.exception("auto-archive: plugin waiting failed")
|
|
out.discard(None)
|
|
out.discard("")
|
|
return out
|
|
|
|
|
|
def since(deps) -> str:
|
|
"""When the rules started applying (stored: a restart doesn't move it)."""
|
|
first = deps.store.get_meta(_SINCE_KEY)
|
|
if not first:
|
|
first = _now()
|
|
deps.store.set_meta(_SINCE_KEY, first)
|
|
return first
|
|
|
|
|
|
def due(deps, *, backfill: bool = False, now: float | None = None) -> list[dict]:
|
|
"""The conversations a sweep would archive now: ``{sessionId, id, kind,
|
|
title}``. ``backfill`` drops the ``since`` cutoff (the one-off pass over
|
|
the past).
|
|
|
|
Reads directly from ``deps.store.all_summaries()`` and ``deps.meta_store.peek()``
|
|
so the 30 s background sweep never triggers a full conversation-card rebuild."""
|
|
now = time.time() if now is None else now
|
|
cutoff = None if backfill else _epoch(since(deps))
|
|
jobs = {j["id"]: j for j in deps.cron_store.list()}
|
|
open_q: set[str] | None = None
|
|
out = []
|
|
|
|
if catalog._conversation_cards is not _ORIG_CONVERSATION_CARDS:
|
|
# Test hook: a unit test patched `_conversation_cards` with synthetic cards.
|
|
summaries = {}
|
|
for _, s in deps.store.all_summaries():
|
|
if not s.get("isSidechain") and s.get("sessionId"):
|
|
summaries[s["sessionId"]] = s
|
|
for card in catalog._conversation_cards(deps, False):
|
|
sid = card.get("sessionId")
|
|
cm = card.get("meta") or {}
|
|
if not sid or cm.get("archived") or cm.get("state") not in DONE_STATES:
|
|
continue
|
|
m = deps.meta_store.peek(sid)
|
|
s = summaries.get(sid) or {}
|
|
kind = kind_of(m, s, jobs)
|
|
if not kind or (kind == "cron" and cm.get("state") != "finished"):
|
|
continue
|
|
started = _epoch(s.get("startedAt") or card.get("startedAt"))
|
|
if cutoff and not m.get("test") and (started is None or started < cutoff):
|
|
continue
|
|
ended = _epoch(s.get("endedAt") or card.get("endedAt"))
|
|
if ended is None or now - ended < SETTLE_S:
|
|
continue
|
|
if kind == "cron":
|
|
if open_q is None:
|
|
open_q = open_question_sessions(deps)
|
|
if not succeeded(s, m, open_q, sid, legacy=backfill):
|
|
continue
|
|
out.append({"sessionId": sid, "id": card.get("id"), "kind": kind,
|
|
"title": card.get("title")})
|
|
return out
|
|
|
|
# Direct fast path: dedup non-sidechain summaries by sessionId and filter
|
|
# before resolving state so unchanged/non-candidate sessions pay almost nothing.
|
|
best: dict[str, tuple[str, dict]] = {}
|
|
for path, s in deps.store.all_summaries():
|
|
if s.get("isSidechain") or _is_sidechain_path(path):
|
|
continue
|
|
if "messages" in s and not s.get("messages"):
|
|
continue
|
|
sid = s.get("sessionId")
|
|
if not sid:
|
|
continue
|
|
cur = best.get(sid)
|
|
if cur is None or (
|
|
(s.get("endedAt") or "", s.get("messages") or 0, path)
|
|
> (cur[1].get("endedAt") or "", cur[1].get("messages") or 0, cur[0])
|
|
):
|
|
best[sid] = (path, s)
|
|
|
|
for sid, (path, s) in best.items():
|
|
m = deps.meta_store.peek(sid)
|
|
kind = kind_of(m, s, jobs)
|
|
if not kind:
|
|
continue
|
|
started = _epoch(s.get("startedAt"))
|
|
# An explicit test flag is the session's word for it, whenever it ran.
|
|
if cutoff and not m.get("test") and (started is None or started < cutoff):
|
|
continue
|
|
ended = _epoch(s.get("endedAt"))
|
|
if ended is None or now - ended < SETTLE_S:
|
|
continue
|
|
auto = s.get("lifecycleAuto") or {}
|
|
notified = m.get("notified") or auto.get("notified")
|
|
state = _resolve_state(
|
|
s, m, notified,
|
|
_subagent_activity(deps, s),
|
|
liveruns.alive(sid),
|
|
liveruns.held(sid) is not None,
|
|
)
|
|
if state not in DONE_STATES or (kind == "cron" and state != "finished"):
|
|
continue
|
|
if kind == "cron":
|
|
if open_q is None:
|
|
open_q = open_question_sessions(deps)
|
|
if not succeeded(s, m, open_q, sid, legacy=backfill):
|
|
continue
|
|
out.append({"sessionId": sid, "id": _conv_id(path), "kind": kind,
|
|
"title": m.get("title") or s.get("title")})
|
|
return out
|
|
|
|
|
|
def archive(deps, items: list[dict]) -> int:
|
|
if not items:
|
|
return 0
|
|
at = _now()
|
|
stamp_many = getattr(deps.meta_store, "stamp_many", None)
|
|
if stamp_many is not None:
|
|
patches = {
|
|
it["sessionId"]: {
|
|
"archived": True, "autoArchived": {"kind": it["kind"], "at": at}}
|
|
for it in items
|
|
}
|
|
stamp_many(patches)
|
|
for it in items:
|
|
deps.hub.publish({"type": "meta", "id": it["sessionId"]})
|
|
n = len(items)
|
|
else:
|
|
n = 0
|
|
for it in items:
|
|
deps.meta_store.update(it["sessionId"], {
|
|
"archived": True, "autoArchived": {"kind": it["kind"], "at": at}})
|
|
deps.hub.publish({"type": "meta", "id": it["sessionId"]})
|
|
n += 1
|
|
if n:
|
|
log.info("auto-archived %d conversation(s)", n)
|
|
_dismiss_pushes(deps, [it["sessionId"] for it in items if it["kind"] in DISMISS_KINDS])
|
|
return n
|
|
|
|
|
|
def _dismiss_pushes(deps, sids: list[str]) -> None:
|
|
"""A swept test run's pushes leave the owner's New list too, as a manual
|
|
archive's do (``notifications.routes.dismiss_archived``) — in the ledger
|
|
only: nobody acted, so what reached his phone stays there."""
|
|
if not sids or getattr(deps, "notif_read_store", None) is None:
|
|
return
|
|
try:
|
|
from notifications.routes import dismiss_archived
|
|
dismiss_archived(deps, sids, "auto-archive", clear=False)
|
|
except Exception:
|
|
log.exception("auto-archive: dismissing the pushes failed")
|
|
|
|
|
|
def sweep(deps, *, backfill: bool = False, dry_run: bool = False) -> list[dict]:
|
|
items = due(deps, backfill=backfill)
|
|
if not dry_run:
|
|
archive(deps, items)
|
|
return items
|
|
|
|
|
|
def on_unarchive(m: dict) -> dict:
|
|
"""The patch an owner's unarchive adds: never swept again."""
|
|
return {"autoArchiveOff": True} if m.get("autoArchived") or m.get("cron") \
|
|
or m.get("test") else {}
|
|
|
|
|
|
def on_resume(m: dict) -> dict:
|
|
"""The patch a new turn on an archived conversation adds: back on the list
|
|
— and a cron run continued by hand is off the sweep for good."""
|
|
if not m.get("archived"):
|
|
return {}
|
|
patch: dict = {"archived": False}
|
|
if m.get("cron") and not m.get("test"):
|
|
patch["autoArchiveOff"] = True
|
|
return patch
|
|
|
|
|
|
def start(deps, every_s: float = SWEEP_S) -> None:
|
|
if not ENABLED:
|
|
return
|
|
since(deps)
|
|
|
|
def loop():
|
|
while True:
|
|
time.sleep(every_s)
|
|
try:
|
|
sweep(deps)
|
|
except Exception:
|
|
log.exception("auto-archive sweep failed")
|
|
threading.Thread(target=loop, daemon=True, name="auto-archive").start()
|