clarifier-gains.py prints a second table per cohort: the brief and report parts of the footprint, answer rate, median answer time, fields, mockups and the `--timeout 270` retries, plus a combined `· since 11-01` cohort. Measured on 2026-11-09 (177 forms since Nov 1): the brief went 3.3k → 1.6k tokens and the footprint 5.0k → 3.0k. Since Nov 4 (with no CLAUDE.md and medium effort) a form costs $0.25 / 0.418 plan units, against $0.35 / 0.681 inline. The 270 retry is gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
718 lines
34 KiB
Python
718 lines
34 KiB
Python
#!/usr/bin/env python3
|
||
"""What a form really costs — asked inline by the main thread vs handed to the
|
||
``clarifier`` subagent (docs/clarifier.md → "Measured: eleven days on").
|
||
|
||
Walks the transcript archive for every form a main thread asked:
|
||
|
||
* **inline** — the thread ran ``ask-form create`` / ``ask-form --title`` /
|
||
``notify form`` itself. Its footprint is everything it put in its own context
|
||
to get there: the ask-form skill text, the ToolSearch that loaded Monitor, the
|
||
spec it wrote, the create call, the wait (Monitor or Bash) and its events.
|
||
* **clarifier** — the thread called ``Agent(subagent_type="clarifier")``. Its
|
||
footprint is the brief, the launch result and the report that came back (the
|
||
task-notification of a background run). The subagent's own transcript is
|
||
priced separately — it is a separate context, read once.
|
||
|
||
Per form it measures, from the transcripts' own usage blocks:
|
||
|
||
* **footprint** — tokens the form left in the main context. Each API call's
|
||
context growth (next call's prompt − this call's prompt) is split between the
|
||
blocks that caused it in proportion to their characters, the call's own
|
||
output counted at its ``output_tokens``.
|
||
* **ask** — the main-thread calls that did nothing but the form (load the
|
||
skill, write the spec, create, wait…), at their full price: each one re-reads
|
||
the whole context.
|
||
* **carry** — every later call of the thread until a compaction, the footprint
|
||
priced as a cache read, or as a cache write on a call whose cached prefix
|
||
stopped before it (TTL expiry, model switch).
|
||
* **subagent** — the clarifier's whole transcript.
|
||
|
||
Costs are list price and plan units (``conversations.pricing``). A call shared
|
||
by a fork and its original is counted once (keyed on the message id).
|
||
|
||
scripts/clarifier-gains.py [--archive DIR] [--since 2026-08-01] [--json OUT]
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import glob
|
||
import json
|
||
import os
|
||
import re
|
||
import statistics as st
|
||
import subprocess
|
||
import sys
|
||
from collections import Counter, defaultdict
|
||
from datetime import datetime
|
||
|
||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "backend"))
|
||
from conversations import pricing # noqa: E402
|
||
|
||
ARCHIVE = os.path.expanduser("~/homelab/services/ai-agent/data/transcripts")
|
||
# Every main thread is also priced as this model, so cohorts with a different
|
||
# model mix compare (the clarifier's months are nearly all Opus 5.5).
|
||
REF_MODEL = "claude-opus-5-5"
|
||
# The clarifier's first deploy (ai-agent 1721713, 2026-10-21 11:25 CEST).
|
||
SHIPPED = "2026-10-21T09:30:00Z"
|
||
# Its later changes, each a cohort of its own (--cut): the ~200-word brief
|
||
# (a00b6c8, Nov 1 22:38 CET) and no CLAUDE.md + medium effort (5ce89d6,
|
||
# deployed + host sidecar restarted Nov 4 12:56 CET).
|
||
CUTS = ["2026-11-01T21:38:00Z", "2026-11-04T11:56:00Z"]
|
||
|
||
PREFILTER = ["ask-form create", "ask-form --title", "ask-form wait", "notify form",
|
||
"notify wait", '"subagent_type":"clarifier"']
|
||
SEG = r"(?:^|&&|;|\n|\|\||\(|\$\()\s*"
|
||
CREATE_RE = re.compile(SEG + r"(?:ask-form\s+(?:create\b|--title)|notify\s+form\b)")
|
||
WAIT_RE = re.compile(SEG + r"(?:while true; do out=\$\()?\s*(?:ask-form|notify)\s+wait\b")
|
||
FETCH_RE = re.compile(SEG + r"(?:ask-form|notify)\s+(?:get|show|answers|status|ls)\b")
|
||
FIELDS_RE = re.compile(r"--fields(?:-file)?[ =]+(?:@)?['\"]?([^\s'\"]+\.json)")
|
||
FORM_ID_RE = re.compile(r"\b(frm_[0-9a-f]{12}|ask_[0-9a-f]{8,}|[a-z0-9][a-z0-9-]{2,80}_[a-z0-9]{6})\b")
|
||
NOTIF_TOOL_RE = re.compile(r"<tool-use-id>(toolu_[A-Za-z0-9]+)</tool-use-id>")
|
||
ANSWERS_RE = re.compile(r'"answers"\s*:\s*\{\s*"')
|
||
REPORT_RE = re.compile(r"FORM_ID:\s*(\S+)\s*[—-]+\s*(\w+)")
|
||
TIMEOUT_BUG = 'invalid value "270" for flag -timeout'
|
||
# A skill read or spec written more than this many calls before the create
|
||
# wasn't part of asking the form (a conversation *about* forms reads the skill).
|
||
PRE_WINDOW = 10
|
||
# What a tool_use's result / notification is called in the footprint.
|
||
RESULT_LABEL = {"brief": "report", "create": "create", "wait": "events", "skill": "skill",
|
||
"spec": "spec", "toolsearch": "toolsearch"}
|
||
|
||
|
||
def ts(s: str | None) -> float:
|
||
return datetime.fromisoformat(s.replace("Z", "+00:00")).timestamp() if s else 0.0
|
||
|
||
|
||
def text_of(c) -> str:
|
||
if c is None:
|
||
return ""
|
||
if isinstance(c, str):
|
||
return c
|
||
if isinstance(c, list):
|
||
return "".join(text_of(b) for b in c)
|
||
if isinstance(c, dict):
|
||
t = c.get("type")
|
||
if t == "text":
|
||
return c.get("text") or ""
|
||
if t == "tool_use":
|
||
return json.dumps(c.get("input") or {}, ensure_ascii=False)
|
||
if t == "tool_result":
|
||
return text_of(c.get("content"))
|
||
if t == "thinking":
|
||
return c.get("thinking") or ""
|
||
if t == "image":
|
||
return "x" * 4000 # ~1.5k tokens, never form-related
|
||
return json.dumps(c, ensure_ascii=False)
|
||
return str(c)
|
||
|
||
|
||
def ctx(u: dict) -> int:
|
||
return (u.get("input_tokens") or 0) + (u.get("cache_read_input_tokens") or 0) \
|
||
+ (u.get("cache_creation_input_tokens") or 0)
|
||
|
||
|
||
def write_mult(u: dict) -> float:
|
||
cc = u.get("cache_creation") or {}
|
||
return 2.0 if (cc.get("ephemeral_1h_input_tokens") or 0) else 1.25
|
||
|
||
|
||
def price(tokens: float, kind: str, model: str, mult: float = 2.0) -> tuple[float, float, float, float]:
|
||
"""(list $, plan units, list $ and plan units at REF_MODEL) of `tokens`
|
||
read from or written to the cache."""
|
||
u = pricing.zero_usage()
|
||
if kind == "read":
|
||
u["cacheRead"] = tokens
|
||
else:
|
||
u["cacheWriteTokens"], u["cacheWriteUnits"] = tokens, tokens * mult
|
||
return pricing.usage_cost(u, model), pricing.plan_units(u, model), \
|
||
pricing.usage_cost(u, REF_MODEL), pricing.plan_units(u, REF_MODEL)
|
||
|
||
|
||
def call_price(u: dict, model: str, speed: str | None = None) -> tuple[float, float]:
|
||
n = pricing.norm_usage(u)
|
||
return pricing.usage_cost(n, model, speed), pricing.plan_units(n, model, speed)
|
||
|
||
|
||
def extra_call_price(u: dict, prev_prompt: int, model: str) -> tuple[float, float, float, float]:
|
||
"""What one more call costs on a warm thread: its existing prefix read from
|
||
the cache, what is new since the previous call written, its output. A
|
||
form-only call that happened to be the first after a cache expiry would
|
||
otherwise carry a rewrite the next call would have paid anyway."""
|
||
n = pricing.zero_usage()
|
||
n["cacheRead"] = min(prev_prompt, ctx(u))
|
||
n["cacheWriteTokens"] = ctx(u) - n["cacheRead"]
|
||
n["cacheWriteUnits"] = n["cacheWriteTokens"] * write_mult(u)
|
||
n["output"] = u.get("output_tokens") or 0
|
||
speed = u.get("speed")
|
||
return pricing.usage_cost(n, model, speed), pricing.plan_units(n, model, speed), \
|
||
pricing.usage_cost(n, REF_MODEL), pricing.plan_units(n, REF_MODEL)
|
||
|
||
|
||
# ── one transcript → an ordered list of calls and the context between them ──
|
||
|
||
def load(path: str):
|
||
"""Main-thread records → [call…], each with the blocks the call emitted
|
||
and the user-side items that reached the context before the next call."""
|
||
calls, cur, by_id = [], None, {}
|
||
for line in open(path, errors="replace"):
|
||
try:
|
||
r = json.loads(line)
|
||
except ValueError:
|
||
continue
|
||
if r.get("isSidechain"):
|
||
continue
|
||
t = r.get("type")
|
||
if t == "system" and r.get("subtype") == "compact_boundary":
|
||
if cur is not None:
|
||
cur["compactAfter"] = True
|
||
continue
|
||
if t == "assistant":
|
||
m = r.get("message") or {}
|
||
mid = m.get("id") or r.get("uuid")
|
||
call = by_id.get(mid)
|
||
if call is None:
|
||
call = {"id": mid, "model": m.get("model") or "", "usage": m.get("usage") or {},
|
||
"ts": r.get("timestamp"), "blocks": [], "after": [], "compactAfter": False}
|
||
if call["model"] == "<synthetic>":
|
||
continue
|
||
by_id[mid] = call
|
||
calls.append(call)
|
||
cur = call
|
||
for b in m.get("content") or []:
|
||
call["blocks"].append(b)
|
||
call["endTs"] = r.get("timestamp")
|
||
continue
|
||
if cur is None: # before the first call: nothing to attribute it to
|
||
continue
|
||
if t == "user":
|
||
c = (r.get("message") or {}).get("content")
|
||
for b in c if isinstance(c, list) else [{"type": "text", "text": c or ""}]:
|
||
cur["after"].append((b, r.get("timestamp")))
|
||
elif t == "attachment":
|
||
# a background task's notification arrives as a queued command
|
||
a = r.get("attachment") or {}
|
||
body = a.get("prompt") if a.get("type") == "queued_command" else a
|
||
text = body if isinstance(body, str) else json.dumps(body, ensure_ascii=False)
|
||
cur["after"].append(({"type": "text", "text": text}, r.get("timestamp")))
|
||
return calls
|
||
|
||
|
||
# ── which blocks belong to a form ──
|
||
|
||
class Form:
|
||
def __init__(self, key, kind, path, call, when):
|
||
self.key, self.kind, self.path = key, kind, path
|
||
self.ts = when
|
||
self.model = call["model"]
|
||
self.formIds: set[str] = set()
|
||
self.parts = Counter() # footprint tokens per component
|
||
self.askCalls = 0
|
||
self.ask = [0.0] * 4 # list $, plan units, both again at REF_MODEL
|
||
self.carryCalls = 0
|
||
self.carryWrites = 0
|
||
self.carry = [0.0] * 4
|
||
self.sub = [0.0] * 4 # list $, plan units, both again as Haiku 5.5
|
||
self.subModel = None
|
||
self.subCalls = 0
|
||
self.subPrompt = 0
|
||
self.outcome = None
|
||
self.answeredAt = None
|
||
self.created = None
|
||
self.fields = None
|
||
self.mockups = None
|
||
self.timeoutBug = 0
|
||
self.storeStatus = None
|
||
self.askSeconds = 0.0
|
||
|
||
@property
|
||
def footprint(self) -> float:
|
||
return sum(self.parts.values())
|
||
|
||
|
||
def spec_stats(content: str) -> tuple[int | None, int | None]:
|
||
"""(questions, mockups) of a field spec — a JSON array or ``{"fields": […]}``."""
|
||
try:
|
||
spec = json.loads(content)
|
||
except ValueError:
|
||
return None, None
|
||
fields = spec.get("fields") if isinstance(spec, dict) else spec
|
||
if not isinstance(fields, list):
|
||
return None, None
|
||
n = sum(1 for f in fields if isinstance(f, dict) and f.get("type") not in ("markdown", "html"))
|
||
mock = sum(1 for f in fields if isinstance(f, dict) and f.get("type") == "html")
|
||
for f in fields:
|
||
for o in (f.get("options") or []) if isinstance(f, dict) else []:
|
||
if isinstance(o, dict) and o.get("html"):
|
||
mock += 1
|
||
return n, mock
|
||
|
||
|
||
def subagent(path: str, tool_id: str) -> dict | None:
|
||
"""The clarifier transcript launched by `tool_id`, priced."""
|
||
base = path[:-len(".jsonl")]
|
||
for meta in glob.glob(os.path.join(base, "subagents", "*.meta.json")):
|
||
try: # the archive's copy can carry a second object appended after the first
|
||
m = json.JSONDecoder().raw_decode(open(meta).read())[0]
|
||
except (OSError, ValueError):
|
||
continue
|
||
if m.get("toolUseId") != tool_id:
|
||
continue
|
||
jl = meta[:-len(".meta.json")] + ".jsonl"
|
||
if not os.path.exists(jl):
|
||
return None
|
||
seen = set()
|
||
out = {"list": 0.0, "plan": 0.0, "haiku": 0.0, "haikuPlan": 0.0, "calls": 0, "model": None,
|
||
"prompt0": 0, "fields": None, "mockups": None, "outcome": None, "created": None,
|
||
"answered": None, "timeoutBug": 0, "formIds": set()}
|
||
for line in open(jl, errors="replace"):
|
||
try:
|
||
r = json.loads(line)
|
||
except ValueError:
|
||
continue
|
||
msg = r.get("message") or {}
|
||
if r.get("type") == "assistant":
|
||
for b in msg.get("content") or []:
|
||
if b.get("type") == "tool_use" and b.get("name") == "Write":
|
||
inp = b.get("input") or {}
|
||
if str(inp.get("file_path", "")).endswith(".json"):
|
||
n, mk = spec_stats(inp.get("content") or "")
|
||
if n is not None:
|
||
out["fields"], out["mockups"] = n, mk
|
||
if b.get("type") == "tool_use" and b.get("name") == "Bash":
|
||
cmd = (b.get("input") or {}).get("command") or ""
|
||
if CREATE_RE.search(cmd) and out["created"] is None:
|
||
out["created"] = r.get("timestamp")
|
||
mid = msg.get("id")
|
||
if not mid or mid in seen or msg.get("model") == "<synthetic>":
|
||
continue
|
||
seen.add(mid)
|
||
u = msg.get("usage") or {}
|
||
lp, pu = call_price(u, msg.get("model") or "", u.get("speed"))
|
||
out["list"] += lp
|
||
out["plan"] += pu
|
||
hl, hp = call_price(u, "claude-haiku-5-5")
|
||
out["haiku"] += hl
|
||
out["haikuPlan"] += hp
|
||
out["calls"] += 1
|
||
out["model"] = out["model"] or msg.get("model")
|
||
if out["calls"] == 1:
|
||
out["prompt0"] = ctx(u)
|
||
for b in msg.get("content") or []:
|
||
mo = b.get("type") == "text" and REPORT_RE.search(b.get("text") or "")
|
||
if mo:
|
||
out["formIds"].add(mo.group(1))
|
||
out["outcome"] = mo.group(2)
|
||
elif r.get("type") == "user":
|
||
s = text_of(msg.get("content"))
|
||
if TIMEOUT_BUG in s:
|
||
out["timeoutBug"] += 1
|
||
if out["answered"] is None and ANSWERS_RE.search(s):
|
||
out["answered"] = r.get("timestamp")
|
||
return out
|
||
return None
|
||
|
||
|
||
def classify(block: dict, specs: set[str], next_monitor_is_form: bool) -> str | None:
|
||
"""The footprint component a main-thread tool_use is, or None."""
|
||
name, inp = block.get("name"), block.get("input") or {}
|
||
if name == "Agent" and inp.get("subagent_type") == "clarifier":
|
||
return "brief"
|
||
if name in ("Bash", "Monitor"):
|
||
cmd = inp.get("command") or ""
|
||
if CREATE_RE.search(cmd):
|
||
return "create"
|
||
if WAIT_RE.search(cmd) or FETCH_RE.search(cmd):
|
||
return "wait"
|
||
if "ask-form/SKILL.md" in cmd:
|
||
return "skill"
|
||
if name == "Skill" and (inp.get("skill") or "").split(":")[-1] == "ask-form":
|
||
return "skill"
|
||
if name == "Read" and str(inp.get("file_path", "")).endswith("ask-form/SKILL.md"):
|
||
return "skill"
|
||
if name == "Write" and inp.get("file_path") in specs:
|
||
return "spec"
|
||
if name == "ToolSearch" and "monitor" in (inp.get("query") or "").lower() and next_monitor_is_form:
|
||
return "toolsearch"
|
||
return None
|
||
|
||
|
||
def file_hints(calls: list[dict]) -> tuple[set[str], list[bool]]:
|
||
"""Spec paths the file's creates read, and for each call whether the next
|
||
Monitor started from it on is a form wait (what a Monitor ToolSearch was for)."""
|
||
specs = set()
|
||
for c in calls:
|
||
for b in c["blocks"]:
|
||
if b.get("type") == "tool_use" and b.get("name") == "Bash":
|
||
cmd = (b.get("input") or {}).get("command") or ""
|
||
if CREATE_RE.search(cmd):
|
||
specs |= set(FIELDS_RE.findall(cmd))
|
||
flags, nxt = [], False
|
||
for c in reversed(calls):
|
||
for b in reversed(c["blocks"]):
|
||
if b.get("type") == "tool_use" and b.get("name") == "Monitor":
|
||
nxt = bool(WAIT_RE.search((b.get("input") or {}).get("command") or ""))
|
||
flags.append(nxt)
|
||
return specs, flags[::-1]
|
||
|
||
|
||
def analyse(paths: list[str]) -> list[Form]:
|
||
forms: dict[str, Form] = {}
|
||
counted: set[str] = set() # message ids already priced (forks copy their parent)
|
||
for path in sorted(paths, key=os.path.getmtime):
|
||
calls = load(path)
|
||
if not calls:
|
||
continue
|
||
specs, monitor_next = file_hints(calls)
|
||
open_forms: list[Form] = [] # forms riding this chain
|
||
pos: dict[str, list] = defaultdict(list) # form key → [(tokens, end position)] in this file
|
||
tool_form: dict[str, Form] = {} # tool_use id → its form
|
||
tool_kind: dict[str, str] = {}
|
||
created_at: dict[str, int] = {} # form key → index of its create call in this file
|
||
pre: list[tuple[str, float, int, int]] = [] # skill/ToolSearch/spec before their create
|
||
pre_ask: list[tuple] = [] # (call #, list $, plan, ref $, ref plan, seconds)
|
||
pre_spec = (None, None)
|
||
prev_end = None
|
||
for i, c in enumerate(calls):
|
||
new = c["id"] not in counted
|
||
counted.add(c["id"])
|
||
u = c["usage"]
|
||
nxt = calls[i + 1] if i + 1 < len(calls) else None
|
||
uses = [b for b in c["blocks"] if b.get("type") == "tool_use"]
|
||
for b in uses:
|
||
k = classify(b, specs, monitor_next[i])
|
||
if k:
|
||
tool_kind[b["id"]] = k
|
||
if k == "spec":
|
||
pre_spec = spec_stats((b.get("input") or {}).get("content") or "")
|
||
# new forms, and the waits that belong to one
|
||
for b in uses:
|
||
k = tool_kind.get(b["id"])
|
||
if k in ("create", "brief"):
|
||
f = forms.get(b["id"])
|
||
if f is None:
|
||
f = forms[b["id"]] = Form(b["id"], "clarifier" if k == "brief" else "inline",
|
||
path, c, c.get("ts"))
|
||
if k == "create":
|
||
f.fields, f.mockups = pre_spec
|
||
cmd = (b.get("input") or {}).get("command") or ""
|
||
if f.fields is None and "--fields" in cmd and "--fields-file" not in cmd:
|
||
m = re.search(r"--fields\s+'(\[.*?\])'", cmd, re.S)
|
||
if m:
|
||
f.fields, f.mockups = spec_stats(m.group(1))
|
||
pre_spec = (None, None)
|
||
if f not in open_forms:
|
||
open_forms.append(f)
|
||
created_at.setdefault(f.key, i)
|
||
tool_form[b["id"]] = f
|
||
elif k in ("toolsearch", "skill") and open_forms \
|
||
and i - created_at.get(open_forms[-1].key, -99) <= 3:
|
||
# loaded right after the create, for its wait
|
||
tool_form[b["id"]] = open_forms[-1]
|
||
elif k == "wait":
|
||
cmd = (b.get("input") or {}).get("command") or ""
|
||
hit = [f for f in open_forms if any(x in cmd for x in f.formIds)]
|
||
f = (hit or open_forms or [None])[-1]
|
||
if f is not None:
|
||
tool_form[b["id"]] = f
|
||
# ── what this call's output and the user turn after it added ──
|
||
out_tok = u.get("output_tokens") or 0
|
||
out_chars = {b.get("id") or f"#{j}": len(text_of(b)) for j, b in enumerate(c["blocks"])}
|
||
tot_out = sum(out_chars.values()) or 1
|
||
items = [] # (owning form tool_use id | None, chars)
|
||
for b, when in c["after"]:
|
||
s = text_of(b)
|
||
tid = b.get("tool_use_id") if isinstance(b, dict) else None
|
||
owner = tid if tid in tool_kind else next(
|
||
(m for m in NOTIF_TOOL_RE.findall(s) if m in tool_form), None)
|
||
items.append((owner, len(s)))
|
||
f = tool_form.get(owner)
|
||
if f is None:
|
||
continue
|
||
if TIMEOUT_BUG in s:
|
||
f.timeoutBug += 1
|
||
f.formIds |= {x for x in FORM_ID_RE.findall(s) if x.startswith(("frm_", "ask_"))
|
||
or (f.kind == "inline" and tool_kind.get(owner) == "create")}
|
||
mo = REPORT_RE.search(s)
|
||
if mo and tool_kind.get(owner) == "brief":
|
||
f.formIds.add(mo.group(1))
|
||
f.outcome = mo.group(2)
|
||
if f.kind == "inline" and f.answeredAt is None and ANSWERS_RE.search(s):
|
||
f.answeredAt, f.outcome = when, "submitted"
|
||
c["afterOwners"] = [o for o, _ in items]
|
||
tot_user = sum(n for _, n in items) or 1
|
||
if nxt is not None and not c["compactAfter"] and ctx(nxt["usage"]) >= ctx(u):
|
||
delta = ctx(nxt["usage"]) - ctx(u)
|
||
a = min(out_tok, delta)
|
||
ut = delta - a
|
||
else:
|
||
a, ut = out_tok, tot_user / 3.0
|
||
end_pos = ctx(nxt["usage"]) if nxt is not None else ctx(u) + int(a + ut)
|
||
shares: list[tuple[str, str, float]] = [] # (tool id, label, tokens)
|
||
for tid, k in tool_kind.items():
|
||
if tid in out_chars:
|
||
shares.append((tid, k, a * out_chars[tid] / tot_out))
|
||
for owner, n in items:
|
||
if owner:
|
||
shares.append((owner, RESULT_LABEL[tool_kind[owner]], ut * n / tot_user))
|
||
# ── a call that only served the form is part of the ask, at its marginal price ──
|
||
if uses:
|
||
pure = all(b["id"] in tool_kind for b in uses)
|
||
else:
|
||
trig = calls[i - 1].get("afterOwners") if i else None
|
||
pure = bool(trig) and all(trig) and len(text_of(c["blocks"])) < 800
|
||
# generation time: from the request (the last thing the call answered) to its end
|
||
secs = max(0.0, ts(c.get("endTs")) - ts(prev_end)) if prev_end else 0.0
|
||
prev_end = max([c.get("endTs") or ""] + [w or "" for _, w in c["after"]])
|
||
# (the first call of a file or after a compaction: its whole prompt counts as read)
|
||
warm = i and not calls[i - 1]["compactAfter"]
|
||
prev_prompt = ctx(calls[i - 1]["usage"]) if warm else ctx(u)
|
||
lp, pu, lr, pr = extra_call_price(u, prev_prompt, c["model"])
|
||
# ── attribute the footprint ──
|
||
for tid, label, tok in shares:
|
||
f = tool_form.get(tid)
|
||
if f is None:
|
||
pre.append((label, tok, end_pos, i))
|
||
continue
|
||
pos[f.key].append((tok, end_pos))
|
||
if new:
|
||
f.parts[label] += tok
|
||
if pure and new:
|
||
owners = [tool_form[t] for t in tool_kind if t in out_chars and t in tool_form]
|
||
if not uses:
|
||
owners = [tool_form[o] for o in calls[i - 1]["afterOwners"] if o in tool_form]
|
||
if owners:
|
||
f = owners[0]
|
||
f.askCalls += 1
|
||
f.ask[0] += lp
|
||
f.ask[1] += pu
|
||
f.ask[2] += lr
|
||
f.ask[3] += pr
|
||
f.askSeconds += secs
|
||
else:
|
||
pre_ask.append((i, lp, pu, lr, pr, secs))
|
||
created = [tool_form[t] for t in tool_kind
|
||
if t in out_chars and tool_kind[t] in ("create", "brief") and t in tool_form]
|
||
if created:
|
||
# what led to the form: loaded or written in the PRE_WINDOW calls before it
|
||
f = created[0]
|
||
for label, tok, p, j in pre:
|
||
if i - j > PRE_WINDOW:
|
||
continue
|
||
pos[f.key].append((tok, p))
|
||
if new:
|
||
f.parts[label] += tok
|
||
for j, lpp, ppu, lrr, prr, sec in pre_ask:
|
||
if new and i - j <= PRE_WINDOW:
|
||
f.askCalls += 1
|
||
f.ask[0] += lpp
|
||
f.ask[1] += ppu
|
||
f.ask[2] += lrr
|
||
f.ask[3] += prr
|
||
f.askSeconds += sec
|
||
pre, pre_ask = [], []
|
||
# ── carry: what every open form costs this call ──
|
||
if new and not pure:
|
||
rd = u.get("cache_read_input_tokens") or 0
|
||
for f in open_forms:
|
||
riding = [(tok, p) for tok, p in pos[f.key] if p <= ctx(u)]
|
||
if not riding:
|
||
continue
|
||
f.carryCalls += 1
|
||
if any(rd < p for _, p in riding):
|
||
f.carryWrites += 1
|
||
for tok, p in riding:
|
||
for k, v in enumerate(price(tok, "read" if rd >= p else "write", c["model"],
|
||
write_mult(u))):
|
||
f.carry[k] += v
|
||
# a compaction, or a context that shrank (tool results cleared), ends the ride
|
||
if c["compactAfter"] or (nxt is not None and ctx(nxt["usage"]) < ctx(u) * 0.7):
|
||
open_forms = []
|
||
pos.clear()
|
||
out = list(forms.values())
|
||
for f in out:
|
||
if f.kind != "clarifier":
|
||
f.created = f.ts
|
||
continue
|
||
s = subagent(f.path, f.key)
|
||
if not s:
|
||
continue
|
||
f.sub = [s["list"], s["plan"], s["haiku"], s["haikuPlan"]]
|
||
f.subModel, f.subCalls, f.subPrompt = s["model"], s["calls"], s["prompt0"]
|
||
f.fields, f.mockups = s["fields"], s["mockups"]
|
||
f.created, f.answeredAt = s["created"], s["answered"]
|
||
f.timeoutBug += s["timeoutBug"]
|
||
f.outcome = f.outcome or s["outcome"]
|
||
f.formIds |= s["formIds"]
|
||
return out
|
||
|
||
|
||
# ── the form stores: what was asked and when it was answered ──
|
||
|
||
DATA = os.path.expanduser("~/homelab/services/ai-agent/data")
|
||
GO_DATA = os.path.expanduser("~/.local/share/ask-form")
|
||
|
||
|
||
def stores() -> dict[str, dict]:
|
||
"""form id → {created, answered, status, fields, mockups}: the hub's own
|
||
forms (``notify form`` / the old ``ask-form``, until 2026-10-28) and the Go
|
||
tool's (its data dir on the lab, the hub mirror for the Macs)."""
|
||
out: dict[str, dict] = {}
|
||
try:
|
||
for f in json.load(open(os.path.join(DATA, "forms.json")))["forms"]:
|
||
n, mk = spec_stats(json.dumps(f.get("fields") or []))
|
||
out[f["id"]] = {"created": f.get("at"), "answered": f.get("submittedAt"),
|
||
"status": f.get("status"), "fields": n, "mockups": mk}
|
||
except (OSError, ValueError, KeyError):
|
||
pass
|
||
try:
|
||
for f in json.load(open(os.path.join(DATA, "askform.json")))["forms"].values():
|
||
out[f["id"]] = {"created": f.get("createdAt"), "status": f.get("status"),
|
||
"answered": f.get("closedAt") if f.get("status") == "submitted" else None,
|
||
"fields": None, "mockups": None}
|
||
except (OSError, ValueError, KeyError):
|
||
pass
|
||
for p in glob.glob(os.path.join(GO_DATA, "forms", "*.json")):
|
||
try:
|
||
f = json.load(open(p))
|
||
except (OSError, ValueError):
|
||
continue
|
||
rec = out.setdefault(f["id"], {"created": f.get("createdAt"), "status": None, "answered": None})
|
||
rec["fields"], rec["mockups"] = spec_stats(json.dumps(f.get("fields") or []))
|
||
resp = os.path.join(GO_DATA, "responses", f["id"] + ".jsonl")
|
||
if os.path.exists(resp):
|
||
for line in open(resp):
|
||
try:
|
||
r = json.loads(line)
|
||
except ValueError:
|
||
continue
|
||
rec["status"] = rec.get("status") or r.get("type")
|
||
if r.get("type") == "submitted" and not rec.get("answered"):
|
||
rec["answered"] = r.get("at")
|
||
return out
|
||
|
||
|
||
def enrich(forms: list[Form]) -> None:
|
||
known = stores()
|
||
for f in forms:
|
||
hits = [known[i] for i in sorted(f.formIds) if i in known]
|
||
if not hits:
|
||
continue
|
||
h = hits[0]
|
||
f.storeStatus = h.get("status")
|
||
f.created = h.get("created") or f.created
|
||
f.answeredAt = h.get("answered") or f.answeredAt
|
||
if h.get("fields") is not None:
|
||
f.fields, f.mockups = h["fields"], h["mockups"]
|
||
|
||
|
||
# ── report ──
|
||
|
||
def row(f: Form) -> dict:
|
||
lat = ts(f.answeredAt) - ts(f.created) if f.answeredAt and f.created else None
|
||
return {
|
||
"key": f.key, "kind": f.kind, "ts": f.ts, "file": os.path.relpath(f.path, ARCHIVE),
|
||
"model": f.model, "formIds": sorted(f.formIds), "footprint": round(f.footprint),
|
||
"parts": {k: round(v) for k, v in f.parts.items()},
|
||
"askCalls": f.askCalls, "askSeconds": f.askSeconds,
|
||
"askList": f.ask[0], "askPlan": f.ask[1], "askRef": f.ask[2], "askRefPlan": f.ask[3],
|
||
"carryCalls": f.carryCalls, "carryWrites": f.carryWrites,
|
||
"carryList": f.carry[0], "carryPlan": f.carry[1],
|
||
"carryRef": f.carry[2], "carryRefPlan": f.carry[3],
|
||
"subModel": f.subModel, "subCalls": f.subCalls, "subPrompt": f.subPrompt,
|
||
"subList": f.sub[0], "subPlan": f.sub[1], "subHaiku": f.sub[2], "subHaikuPlan": f.sub[3],
|
||
"fields": f.fields, "mockups": f.mockups, "outcome": f.outcome, "status": f.storeStatus,
|
||
"latencyMin": round(lat / 60, 1) if lat and lat > 0 else None,
|
||
"timeoutBug": f.timeoutBug,
|
||
}
|
||
|
||
|
||
def prefilter(archive: str) -> list[str]:
|
||
cmd = ["grep", "-rlF", "--include=*.jsonl"] + sum((["-e", p] for p in PREFILTER), []) + [archive]
|
||
out = subprocess.run(cmd, capture_output=True, text=True).stdout.split()
|
||
return [p for p in out if "/subagents/" not in p]
|
||
|
||
|
||
def main() -> None:
|
||
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
||
ap.add_argument("--archive", default=ARCHIVE)
|
||
ap.add_argument("--since", default="2026-08-01")
|
||
ap.add_argument("--shipped", default=SHIPPED, help="clarifier deploy time (cohort split)")
|
||
ap.add_argument("--cut", action="append",
|
||
help="split the clarifier forms at this time too (repeatable; "
|
||
f"default: {', '.join(CUTS)})")
|
||
ap.add_argument("--json", help="write one row per form here")
|
||
a = ap.parse_args()
|
||
paths = prefilter(a.archive)
|
||
forms = [f for f in analyse(paths) if (f.ts or "") >= a.since]
|
||
enrich(forms)
|
||
rows = [row(f) for f in forms]
|
||
if a.json:
|
||
json.dump(rows, open(a.json, "w"), indent=1, default=list)
|
||
cohorts = {
|
||
"inline, before": [r for r in rows if r["kind"] == "inline" and r["ts"] < a.shipped],
|
||
"inline, after": [r for r in rows if r["kind"] == "inline" and r["ts"] >= a.shipped],
|
||
"clarifier": [r for r in rows if r["kind"] == "clarifier"],
|
||
}
|
||
for sub in sorted({r["subModel"] for r in cohorts["clarifier"] if r["subModel"]}):
|
||
cohorts[" · " + sub.removeprefix("claude-")] = [r for r in cohorts["clarifier"] if r["subModel"] == sub]
|
||
edges = [a.shipped] + sorted(a.cut or CUTS) + ["9999"]
|
||
for lo, hi in zip(edges, edges[1:]):
|
||
rs = [r for r in cohorts["clarifier"] if lo <= r["ts"] < hi]
|
||
cohorts[f" · from {lo[5:10]}"] = rs
|
||
first = sorted(a.cut or CUTS)[0]
|
||
cohorts[f" · since {first[5:10]}"] = [r for r in cohorts["clarifier"] if r["ts"] >= first]
|
||
print(f"{len(paths)} transcripts, {len(rows)} forms since {a.since}\n")
|
||
# Carry depends on how long the thread goes on after the form, not on how
|
||
# it was asked: price every cohort's footprint on the same conversation
|
||
# shapes — the inline forms' carry per footprint token.
|
||
base = [r for r in cohorts["inline, before"] if r["footprint"] > 0]
|
||
rate = st.mean([r["carryRef"] / r["footprint"] for r in base]) if base else 0.0
|
||
prate = st.mean([r["carryRefPlan"] / r["footprint"] for r in base]) if base else 0.0
|
||
print(f"{'':34}{'── list $ per form ──':^41} {'── plan units per form ──':^34}")
|
||
print(f"{'cohort':22} {'n':>4} {'footprint':>9} {'calls':>5} {'ask':>6} {'carry':>6} {'sub':>6} "
|
||
f"{'total':>6} {'Haiku':>6} {'raw':>6} {'ask':>6} {'carry':>6} {'sub':>6} {'total':>6} {'Haiku':>6}")
|
||
for name, rs in cohorts.items():
|
||
if not rs:
|
||
continue
|
||
mean = lambda k: st.mean([r[k] for r in rs]) # noqa: E731
|
||
fp = mean("footprint")
|
||
ask, carry, sub, haiku = mean("askRef"), fp * rate, mean("subList"), mean("subHaiku")
|
||
pask, pcarry = mean("askRefPlan"), fp * prate
|
||
psub, phaiku = mean("subPlan"), mean("subHaikuPlan")
|
||
raw = ask + mean("carryRef") + sub
|
||
print(f"{name:22} {len(rs):>4} {fp:>9.0f} {mean('askCalls'):>5.1f} {ask:>6.3f} {carry:>6.3f} "
|
||
f"{sub:>6.3f} {ask + carry + sub:>6.3f} {ask + carry + haiku:>6.3f} {raw:>6.3f} "
|
||
f"{pask:>6.3f} {pcarry:>6.3f} {psub:>6.3f} {pask + pcarry + psub:>6.3f} "
|
||
f"{pask + pcarry + phaiku:>6.3f}")
|
||
# The second table: where the footprint sits, and how the forms went.
|
||
print(f"\n{'cohort':22} {'n':>4} {'brief':>6} {'report':>6} {'other':>6} {'answered':>8} "
|
||
f"{'median min':>10} {'fields':>6} {'mockups':>7} {'270 retry':>9}")
|
||
for name, rs in cohorts.items():
|
||
if not rs:
|
||
continue
|
||
part = lambda k: st.mean([r["parts"].get(k, 0) for r in rs]) # noqa: E731
|
||
brief, report = part("brief"), part("report")
|
||
other = st.mean([r["footprint"] for r in rs]) - brief - report
|
||
known = [r for r in rs if (r["status"] or r["outcome"])]
|
||
answered = sum(1 for r in known if (r["status"] or r["outcome"]) == "submitted")
|
||
lat = [r["latencyMin"] for r in rs if r["latencyMin"]]
|
||
fl = [r["fields"] for r in rs if r["fields"] is not None]
|
||
mk = [r["mockups"] for r in rs if r["mockups"] is not None]
|
||
mkp = f"{100 * sum(1 for m in mk if m) / len(mk):.0f} %" if mk else "—"
|
||
print(f"{name:22} {len(rs):>4} {brief:>6.0f} {report:>6.0f} {other:>6.0f} "
|
||
f"{(f'{100 * answered / len(known):.0f} %') if known else '—':>8} "
|
||
f"{(f'{st.median(lat):.1f}') if lat else '—':>10} "
|
||
f"{(f'{st.mean(fl):.1f}') if fl else '—':>6} "
|
||
f"{mkp:>7} "
|
||
f"{sum(1 for r in rs if r['timeoutBug']):>9}")
|
||
print(f"""
|
||
Means per form. footprint: tokens the form left in the main context; calls: main-thread
|
||
calls that only served it. Every main thread is priced as {REF_MODEL} (the cohorts' model
|
||
mix differs) and carry is the footprint on the inline forms' conversation shapes; raw:
|
||
the total with each cohort's own carry. sub: the clarifier as it ran; Haiku: the total
|
||
with its tokens priced as claude-haiku-5-5. Plan units: the plan meter's legacy prices.""")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|