S000: workflow scaffold

CLAUDE.md, ORCHESTRATOR.md, PLAN.md, Plans/ (index, template, category folders), docs/PROGRESS.md and
docs/DECISIONS.md (owner choices for network, image commands, security and deploy), and the tracker page.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-12 09:12:57 -06:00
commit 3132434aa1
8 changed files with 297 additions and 0 deletions

89
CLAUDE.md Normal file
View file

@ -0,0 +1,89 @@
# Dezio
Dezio is an all-in-one Discord bot written in Rust (twilight + songbird + axum) that runs on the owner's Chromebook
server, with a website and dashboard. The current goal is making it solid: network handling that never hangs or uploads
forever on the slow line, a security test of the website, media inputs and commands, and replacing the big `/image`
command with separate `/speechbubble` and `/caption` commands. Final deliverable: a deployed bot on the Chromebook with
those fixes, committed and pushed to Astar Hub. Vision: [PLAN.md](PLAN.md). Project history: [ROADMAP.md](ROADMAP.md).
## 0. Session rules — read first
1. You are started with **one plan**: `Plans/<NN Category>/SNNN-*.md`. Read only: this file, **your plan**, the **last 3 entries** of `docs/PROGRESS.md`, and the files/sections your plan names.
2. **Do not open other files in `Plans/`** (nor `ORCHESTRATOR.md`, nor all of `PLAN.md`).
3. **Tick each checkbox in your plan file the moment it is done**, one by one, never in batches. Right after each tick, sync the tracker (§Tracker). An interrupted plan resumes at its first unchecked box.
4. **Stay in scope.** Out-of-scope ideas go to `docs/PROGRESS.md` (“Later”), not into the code.
5. **Invent nothing**: check the code/docs; if a fact is still missing, ask — the **orchestrator** if you were started by one (never the user directly), otherwise the user.
6. **End of session**: (a) end criteria verified **by commands**, not memory; (b) `docs/PROGRESS.md` entry (≤ 15 lines: done, not done, later); (c) `docs/DECISIONS.md` if a decision binds later plans; (d) tick your line in `Plans/INDEX.md` (no commentary); (e) commit `SNNN: …` and push to `origin`; (f) short report: done, not done, what the user/orchestrator must do, and any instruction that cost more than it gave.
7. **Languages**: answer in English. Code, comments and user-facing text in English. Internal docs (`CLAUDE.md`, `Plans/`, `PROGRESS.md`) in English. Plain words, short sentences, like the existing commit messages.
## Tracker
Live checklist of every plan: https://claude.ai/artifact/PRAT4HSkqn44d6QFDJeovp (collection `plans`, one doc per plan id).
After ticking a box: `ArtifactData` `update` with `url` = the tracker, `collection: "plans"`, `doc_id: "SNNN"`, `data: {"status": "running" or "done" (all boxes ticked), "items": [{"text": "<step>", "done": true/false}, … every checkbox of the plan in order], "updated": "<ISO date-time>"}` and `if_version` = the version returned by your previous write (first time: `get` the doc once to read it; a doc that doesn't exist yet takes no `if_version`). Load the tool with ToolSearch `select:ArtifactData` once. If the tracker call fails, keep working and say so in the report: the plan file is the source of truth.
## 1. Repository layout
Root: `/home/astar76/Projects/Dezio`
```
src/main.rs startup, gateway loop, Discord HTTP client (timeout set here), interaction dispatch
src/state.rs shared state, the reqwest client used for web calls
src/cmd.rs command framework (D! prefix + slash)
src/hosted.rs files served from the website for a few hours (oversize results)
src/commands/media/ download/ (yt-dlp/ffmpeg/gallery-dl pipeline), images.rs (/image = D!fx), convert.rs, ffmpeg.rs, quote.rs, emoji.rs, mod.rs (upload_limit, safe_redirects)
src/commands/music/ voice, player, animated card upload
src/commands/… one file/folder per feature (games, fun, lastfm, logs, tools, moderation …)
src/web/ axum website, dashboard API, OAuth, Game Boy Activity
web/ website pages; assets/ fonts, images, emojis (copied to the server on deploy)
deploy/shape-upload.sh tc upload shaping on the server (dezio-shape.service)
docs/ PROGRESS.md, DECISIONS.md, topgg.md
Plans/ one plan per session (INDEX.md lists them)
```
Never modify: `data/` contents on the server (`/root/Dezio/data`, live user data: back up, never delete), `~/Projects/Discord Bot` (old Python bot), `assets/roms/`, `.env`.
## 2. Facts
- Build and test on this PC: `source ~/.cargo/env; cargo build --release` and `cargo test` (about 227 unit tests). Tests that need the internet are `#[ignore]`d (`cargo test live_ -- --ignored`).
- Without `DEZIO_LIVE=1` the binary only lists its commands and exits. **Never run it with the real token on this PC**: the live bot would answer twice.
- Local website for testing: `cargo build && DISCORD_BOT_TOKEN=dev-placeholder target/debug/dezio --web-dev` → http://127.0.0.1:8099 (also the `dezio-web-dev` entry in `.claude/launch.json`).
- Server: the Chromebook, `ssh [email protected]` (Arch Linux, x86_64). Bot in `/root/Dezio` (binary `dezio`, `assets/`, `web/`, `data/`, `.env`). `dezio-bot.service` runs `/root/Dezio/dezio --headless`, Restart=always; website on 127.0.0.1:8080, public at https://archlinux.tail7c4f5e.ts.net. Logs: `journalctl -u dezio-bot`.
- The server's line is slow: measured about 425 KB/s down and **114 KB/s (≈ 0.9 Mbit/s) up**, on `wlan0`. `dezio-shape.service` (deploy/shape-upload.sh, installed as `/usr/local/bin/dezio-shape`) caps internet-bound upload at 800 kbit with fq_codel so voice packets go first. Voice and every upload share that.
- Discord HTTP client: one twilight `Client` with a 180 s timeout for every call (`src/main.rs`). `/download` retries uploads 3 times (`UPLOAD_RETRIES`), so a file that can't finish in 180 s costs 9+ minutes (seen 2026-11-12: a 9.2 MB video, 3 timeouts, handler took 792 s).
- Discord's attachment limit for bots is 10 MiB unless the server is boosted (tier 2: 50 MiB, tier 3: 100 MiB). `media::upload_limit` reads the server's tier; `FALLBACK_UPLOAD_LIMIT` lives in `download/plan.rs`.
- **Deploying is allowed** (tell the orchestrator first): `cargo build --release`; `scp target/release/dezio [email protected]:/root/Dezio/dezio.new`; on the server `cp /root/Dezio/dezio /root/Dezio/dezio.bak-<date>` then `mv /root/Dezio/dezio.new /root/Dezio/dezio && systemctl restart dezio-bot`; copy `assets/` or `web/` changes with `rsync -a`; check `systemctl status dezio-bot` and `journalctl -u dezio-bot -n 50`. A restart drops music for a few seconds. Back up any server file before changing it.
## 3. Code rules
- Write like the neighbouring code. KISS, DRY, YAGNI; no abstraction without ≥ 2 uses.
- New pure logic gets a test; a bug fix gets a regression test when feasible.
- Limits, timeouts and retry counts are named constants next to the code that uses them, with a comment saying why the number.
- User-facing errors go through the existing error cards (`bail_user!`, `src/error.rs`), in plain words.
- Every command works as slash and `D!` prefix unless the plan says otherwise; `/help` pages must stay within Discord's limits (there is a test).
## 4. Domain pitfalls (all agents)
- Upload time, not file size, is what breaks: at ~100 KB/s a 10 MiB file needs ~105 s on an idle line and much longer with voice. Any upload path must think in seconds.
- Retrying a whole upload that timed out just repeats the timeout. Retry only on errors that can succeed the second time.
- yt-dlp, ffmpeg, gallery-dl and curl are child processes fed user links: never pass user text where it can become an option (`--`), keep the private-network check (`safe_redirects`, music's check) on every fetch.
- Security testing runs against a **local copy only** (`--web-dev` on 127.0.0.1). Never send attack traffic to https://archlinux.tail7c4f5e.ts.net or Discord. Never connect to Tor or proxies.
- Discord changes can't be tested on this PC; things only the owner checks in Discord are marked 🧑.
- `/help` pages and slash registration change when commands are added or removed: run the help-limits test.
## 5. Verification tools
| Tool | Role | Available after |
|---|---|---|
| `cargo test` | unit tests, help-page limits, command registry | now |
| `cargo build --release` | release binary for the server | now |
| `target/debug/dezio --web-dev` | local website/dashboard on 127.0.0.1:8099 with no Discord login | now |
| `ssh [email protected] journalctl -u dezio-bot` | live logs (slow command lines, upload attempts) | now |
| `ssh [email protected] tc -s qdisc show dev wlan0` | shaping state and drops | now |
Don't assume a tool exists: check first. When your plan creates a tool, add its row here.
## 6. Git
Remote `origin` = `forgejo:astar76/Dezio.git` (Astar Hub). Commit on `master` and push to `origin` after each plan. Never use GitHub or `gh`. One commit per logical step, message `SNNN: …` in English. No `reset --hard` / force push without an explicit request.
## 7. Definition of done
A plan is done when: all end criteria are **verified by command or test**; planned builds/tests are green; nothing regressed; `PROGRESS` / `DECISIONS` are up to date; the INDEX line and tracker are ticked; the work is committed and pushed. Say explicitly what was **not** done or verified.

36
ORCHESTRATOR.md Normal file
View file

@ -0,0 +1,36 @@
# Orchestrator — Dezio
You are the **orchestrator**. You do not do the plans' work yourself: you launch, unblock and validate the sessions that do. Read `CLAUDE.md`, then `Plans/INDEX.md`, then the last 3 entries of `docs/PROGRESS.md`. Start from the **first unchecked plan** in INDEX.
## Files
- Plans: `Plans/<NN Category>/SNNN-*.md`, one folder per category (header gives model, effort, dependencies, files touched, 🧑). Index: `Plans/INDEX.md`.
- Logs: `docs/PROGRESS.md`, `docs/DECISIONS.md`. Vision: `PLAN.md`.
- Tracker: https://claude.ai/artifact/PRAT4HSkqn44d6QFDJeovp — sessions update it themselves; you only check it matches the plan files (`ArtifactData list plans` vs. the plans' checkboxes; `update` to repair).
## Launching sessions
**Look-ahead rule (check it after EVERY event: start, GO, validation, answer to a session):** count the sessions you started that are *waiting for GO* (not running, not done). If fewer than **3** and unchecked plans remain in scope, start waiting sessions for the next plans in INDEX order right now, until the count is reached. Waiting sessions cost almost nothing and don't touch files: preparing them is never “running in parallel”, and dependencies only gate the GO, not the preparation. Say the count in each status line (`waiting: S014, S015, S016`).
1. Prepare each look-ahead plan as a nested session (`start_session`, `initiation: "user_asked"`, same folder) with the plan's model and effort. Brief: *“Read CLAUDE.md and Plans/<NN Category>/SNNN-xxx.md only. Do not start: wait for GO from the orchestrator.”* plus anything the plan cannot know (state of previous plans, tags, decisions taken since). Do not repeat CLAUDE.md rules.
2. Send **GO** (`SendMessage` to its `local_…` id) when its dependencies are validated.
3. **Parallel** only if the plans are consecutive, none depends on another, their “files touched” don't overlap. **For Dezio: never in parallel** — one Rust crate shares target/ and Cargo.lock; run plans one at a time.
## Answering sessions
Sessions talk to **you**, never to the user. Answer from the project goal, `PLAN.md`, `DECISIONS.md` and the code. Disturb the user only for a real necessity (🧑 steps, irreversible or outward-facing actions, a decision that changes the goal); then stop and tell them exactly what to look at, how, and what to answer. Record any decision you take in `docs/DECISIONS.md`.
## Validating a plan (when its session ends)
Check with commands, not its report: plan checkboxes all ticked; end criteria hold (rerun only **targeted** tests for what changed); PROGRESS entry present; INDEX line ticked; commit present; working tree clean; tracker doc matches. If something is missing, send it back to the same session. Then GO the next one and apply the look-ahead rule.
Relay to the user any remark that an instruction costs more than it gives, with an alternative.
## Context and stop
- Near ~300K context: finish validating the current plan, then tell the user to open a new session with `/orchestrate` (you resume from INDEX).
- If the user says **STOP**: stop the running sessions and your follow-up; on resume, message the same sessions to continue from their first unchecked box.
## End of a phase / project
Short report: what changed (before/after), what was verified, what remains, what the user must do.

24
PLAN.md Normal file
View file

@ -0,0 +1,24 @@
# Dezio — vision
## Goal
Make the deployed bot dependable on the Chromebook's slow line and safe to expose. Deliverable: the bot running on the
Chromebook with the fixes below, committed and pushed to Astar Hub; the owner checks the new image commands in Discord.
## Current state
The Rust port is complete and deployed (see ROADMAP.md). Problems seen on 2026-11-12: `/download` uploads of 7-9 MB
videos take minutes and can time out three times in a row (792 s handler). The upload is about 114 KB/s, shared with
voice and capped at 800 kbit by `dezio-shape`. Network calls have no shared policy for timeouts, retries and sizes. No
security test has been done beyond earlier spot fixes. `/image` (`D!fx`) bundles 10 effects and 14 filters.
## Phases
- Phase 1 — Network: every upload sized and timed by the measured upload speed (too-big results become a website
link), retries only when they can help, every outbound call with a timeout and clear errors, gateway/voice/music
recovering from drops, shaping tuned with the bot.
- Phase 2 — Image commands: `/image` and `D!fx` removed; `/speechbubble` and `/caption` (and their `D!` versions)
work like the well-known caption bots.
- Phase 3 — Security: website and dashboard, media inputs, commands and abuse, dependency audit; fixes for what is
found; tested on a local copy only.
- Phase 4 — Deploy and owner check in Discord.
## Out of scope
New features beyond the above, a faster internet line, moving off the Chromebook, attacks on the live site.

13
Plans/INDEX.md Normal file
View file

@ -0,0 +1,13 @@
# Plans — index
One session = one plan. Plans live in category folders `Plans/<NN Category>/SNNN-slug.md`; one `##` heading per folder below. Start: `Read CLAUDE.md then execute Plans/<NN Category>/SNNN-xxx.md (only that one).` — or let the orchestrator run them (`/orchestrate` in a new session). Sessions tick their line here, without commentary. 🧑 = needs the user.
Tracker: https://claude.ai/artifact/PRAT4HSkqn44d6QFDJeovp
## 01 Network
## 02 Image commands
## 03 Security
## 04 Deploy

24
Plans/_TEMPLATE.md Normal file
View file

@ -0,0 +1,24 @@
# SNNN — {{TITLE}}
> Category {{NN Category}} · Model: {{Sonnet|Opus}} · Effort: {{medium|high}} · Depends on: {{SNNN|—}} · Size: {{S|M|L}} · Human: {{no|🧑 what}}
> Files touched: {{paths/globs}}
## Goal
{{What, why, and the AUDIT/PLAN references it handles.}}
## Read
{{Exact files or sections to read — nothing more.}}
## Steps
- [ ] {{step}}
- [ ] {{step}}
- [ ] PROGRESS entry, INDEX line, commit `SNNN: …`
## End criteria
{{Each one checkable by a command or test.}}
## Pitfalls
{{Known traps.}}
## Handoff (→ PROGRESS.md)
{{What the next plans need to know.}}

11
docs/DECISIONS.md Normal file
View file

@ -0,0 +1,11 @@
# Decisions
`D-NNN — date — decision — why — plans affected`. Never rewrite an entry; supersede it with a new one.
- D-001 — 2026-11-12 — Uploads are sized by the measured upload speed: a file must upload in about 60-90 s, and stay under Discord's limit for that server; anything bigger is sent as a website link (hosted.rs). — Upload time, not Discord's size limit, is what fails on the ~114 KB/s line. — 01 Network.
- D-002 — 2026-11-12 — Network work covers Discord uploads, all outbound HTTP and child-process fetches, gateway/voice/music recovery and the upload shaping script, plus anything else found on the way. — Owner asked for all of it. — 01 Network.
- D-003 — 2026-11-12 — `/image` and `D!fx` are removed with every effect and filter. Only `/speechbubble` and `/caption` remain (plus `D!` versions), working like the well-known caption bots (Assyst-style: caption = white band with text above the picture; speech bubble = bubble shape cut into the top). `/convert` and `/petpet` stay. — Owner request. — 02 Image commands.
- D-004 — 2026-11-12 — Security test scope: website and dashboard, media inputs, commands and abuse, dependency audit (installing cargo-audit/cargo-deny is allowed). Attack traffic only against a local copy (127.0.0.1), never the live site. — Owner choice. — 03 Security.
- D-005 — 2026-11-12 — Plan sessions may use the Chromebook over ssh: read logs, measure, deploy the binary, restart dezio-bot and reinstall dezio-shape, after telling the orchestrator and backing up. — Owner choice. — all.
- D-006 — 2026-11-12 — The owner personally checks only /speechbubble and /caption in Discord. Everything else ends on local tests and server logs. One plan session at a time. — Owner choice. — all.
- D-007 — 2026-11-12 — `/speechbubble` follows the owner's reference screenshot: options `source-attachment` (attachment), `source-link` (link) and `solid` (boolean, "make the speech bubble solid"); with no source it uses the replied/latest chat picture like the other media commands. Default output cuts a **transparent** bubble shape out of the top of the picture (wide ellipse across the top edge with a tail pointing down, toward the right third), so the result needs an alpha-capable format (PNG, or GIF with transparency for animated input); `solid` fills the same shape white instead. `/caption` takes the same two source options plus `text`. — Owner reference image, 2026-11-12. — 02 Image commands.

6
docs/PROGRESS.md Normal file
View file

@ -0,0 +1,6 @@
# Progress
One entry per session, newest last, ≤ 15 lines: done, verified how, not done, later.
## Later
- (none yet)

View file

@ -0,0 +1,94 @@
<title>Dezio tracker</title>
<meta name="claude:viewport-fit-sides" content="cover">
<style>
/* Layout: header with overall bar, category tabs (each with its own bar), selected category's plans below */
:root{--bg:#f6f7f8;--card:#fff;--ink:#1b1f24;--muted:#66707a;--line:#dfe3e7;--accent:#2b6f8f;--done:#2f9e6b;--run:#d98a1c;--sel:#e8f1f5}
@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){--bg:#121518;--card:#1b1f24;--ink:#e8ecef;--muted:#98a2ab;--line:#2c3238;--accent:#6fb3d2;--done:#4cc38a;--run:#f0a640;--sel:#1d2a31;color-scheme:dark}}
:root[data-theme="dark"]{--bg:#121518;--card:#1b1f24;--ink:#e8ecef;--muted:#98a2ab;--line:#2c3238;--accent:#6fb3d2;--done:#4cc38a;--run:#f0a640;--sel:#1d2a31;color-scheme:dark}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.45 system-ui,-apple-system,"Segoe UI",sans-serif}
main{max-width:920px;margin:0 auto;padding-block:24px 48px;padding-left:max(16px,env(safe-area-inset-left,0px));padding-right:max(16px,env(safe-area-inset-right,0px))}
h1{font-size:22px;margin:0 0 4px}
.sub{color:var(--muted);margin:0 0 10px;font-size:13px;font-variant-numeric:tabular-nums}
.bar{height:6px;background:var(--line);border-radius:3px;overflow:hidden}
.bar i{display:block;height:100%;background:var(--accent);transition:width .3s}
.bar.big{height:10px;border-radius:5px}
.cats{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:8px;margin:20px 0}
.cat{all:unset;cursor:pointer;background:var(--card);border:1px solid var(--line);border-radius:10px;padding:10px 12px;display:grid;gap:6px;min-width:0}
.cat:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
.cat[aria-pressed="true"]{border-color:var(--accent);background:var(--sel)}
.cat b{font-size:14px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.cat span{font-size:12px;color:var(--muted);font-variant-numeric:tabular-nums}
.cat.full .bar i{background:var(--done)}
.head{display:flex;justify-content:space-between;align-items:baseline;gap:12px;margin:24px 0 6px}
h2{font-size:17px;margin:0;min-width:0}
details{background:var(--card);border:1px solid var(--line);border-radius:10px;margin:6px 0}
summary{list-style:none;cursor:pointer;padding:10px 12px;display:grid;grid-template-columns:auto 1fr auto;gap:10px;align-items:center}
summary::-webkit-details-marker{display:none}
summary:focus-visible{outline:2px solid var(--accent);border-radius:10px}
.id{font-weight:600;font-variant-numeric:tabular-nums}
.t{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.meta{color:var(--muted);font-size:12px;white-space:nowrap;font-variant-numeric:tabular-nums}
.dot{display:inline-block;width:8px;height:8px;border-radius:50%;margin-right:6px;background:var(--line)}
.running .dot{background:var(--run)}.done .dot{background:var(--done)}
summary .bar{grid-column:1/-1}
ul{margin:0;padding:4px 14px 12px;list-style:none}
li{padding:3px 0;display:flex;gap:8px;font-size:14px}
li span:last-child{min-width:0;overflow-wrap:anywhere}
li.ok{color:var(--muted);text-decoration:line-through}
.empty{color:var(--muted);padding:40px 0;text-align:center}
@media (prefers-reduced-motion:reduce){.bar i{transition:none}}
</style>
<main>
<h1>Dezio</h1>
<p class="sub" id="sub">Loading plans…</p>
<div class="bar big"><i id="total" style="width:0"></i></div>
<div class="cats" id="cats"></div>
<div id="panel"></div>
</main>
<script>
const esc=s=>String(s??'').replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
const pct=(a,b)=>b?Math.round(100*a/b):0;
const opened=new Set();
let plans=[],selected=null;
try{selected=localStorage.getItem('cat')}catch(e){}
function groups(){
const m=new Map();
for(const p of plans){const k=p.category||'Plans';if(!m.has(k))m.set(k,{name:k,order:p.categoryOrder??999,plans:[]});m.get(k).plans.push(p)}
const g=[...m.values()].sort((a,b)=>a.order-b.order||a.name.localeCompare(b.name,undefined,{numeric:true}));
for(const c of g){c.plans.sort((a,b)=>a.id.localeCompare(b.id,undefined,{numeric:true}));c.done=c.plans.filter(p=>p.status==='done').length}
return g;
}
function select(name){selected=name;try{localStorage.setItem('cat',name)}catch(e){}render()}
function render(){
const panel=document.getElementById('panel'),cats=document.getElementById('cats');
panel.querySelectorAll('details[open]').forEach(d=>opened.add(d.dataset.id));
if(!plans.length){cats.innerHTML='';panel.innerHTML='<p class="empty">No plans synced yet. Run /plan-generate to add them.</p>';document.getElementById('sub').textContent='';return}
const g=groups();
const done=plans.filter(p=>p.status==='done').length;
const last=plans.map(p=>p.updated||'').sort().pop();
document.getElementById('sub').textContent=`${done}/${plans.length} plans done (${pct(done,plans.length)} %)`+(last?` · updated ${new Date(last).toLocaleString()}`:'');
document.getElementById('total').style.width=pct(done,plans.length)+'%';
if(!g.some(c=>c.name===selected)){const cur=g.find(c=>c.done<c.plans.length);selected=(cur||g[g.length-1]).name}
cats.innerHTML=g.map(c=>`<button class="cat${c.done===c.plans.length?' full':''}" aria-pressed="${c.name===selected}" data-cat="${esc(c.name)}">
<b title="${esc(c.name)}">${esc(c.name)}</b><span>${c.done}/${c.plans.length} plans</span><div class="bar"><i style="width:${pct(c.done,c.plans.length)}%"></i></div></button>`).join('');
cats.querySelectorAll('.cat').forEach(b=>b.onclick=()=>select(b.dataset.cat));
const c=g.find(c=>c.name===selected);
panel.innerHTML=`<div class="head"><h2>${esc(c.name)}</h2><span class="meta">${c.done}/${c.plans.length} plans · ${pct(c.done,c.plans.length)} %</span></div>
<div class="bar big"><i style="width:${pct(c.done,c.plans.length)}%"></i></div>`+
c.plans.map(p=>{
const items=Array.isArray(p.items)?p.items:[];const n=items.filter(i=>i.done).length;
return `<details class="${esc(p.status)}" data-id="${esc(p.id)}"${opened.has(p.id)?' open':''}><summary>
<span class="id"><span class="dot"></span>${esc(p.id)}</span><span class="t" title="${esc(p.title)}">${esc(p.title)}${p.human?' 🧑':''}</span>
<span class="meta">${p.model?esc(p.model)+' · ':''}${n}/${items.length}</span><div class="bar"><i style="width:${pct(n,items.length)}%"></i></div></summary>
<ul>${items.map(i=>`<li class="${i.done?'ok':''}"><span>${i.done?'☑':'☐'}</span><span>${esc(i.text)}</span></li>`).join('')}</ul></details>`}).join('');
}
(async()=>{
const sub=document.getElementById('sub');
const timer=setTimeout(()=>{sub.textContent='Plans could not load. Open this page signed in to claude.ai.'},10000);
const db=await claude.use('db');
if(!db){clearTimeout(timer);sub.textContent='Plans are not available in this view.';return}
db.collection('plans').onSnapshot(s=>{clearTimeout(timer);plans=s.docs.map(d=>({id:d.id,...d.data()}));render()},
e=>{clearTimeout(timer);sub.textContent='Could not load plans: '+(e&&e.message||e)});
})();
</script>