summaryrefslogtreecommitdiff
path: root/vrsite
diff options
context:
space:
mode:
Diffstat (limited to 'vrsite')
-rw-r--r--vrsite/app_test.go456
-rw-r--r--vrsite/assets/app.js181
-rw-r--r--vrsite/assets/htmx.min.js2
-rw-r--r--vrsite/assets/one.json112
-rw-r--r--vrsite/assets/rust.scm48
-rw-r--r--vrsite/assets/style.css.tmpl321
-rw-r--r--vrsite/bench-browser.mjs135
-rw-r--r--vrsite/bench_test.go129
-rw-r--r--vrsite/css.go68
-rw-r--r--vrsite/go.mod10
-rw-r--r--vrsite/go.sum36
-rw-r--r--vrsite/jj.go275
-rw-r--r--vrsite/main.go169
-rw-r--r--vrsite/main_test.go57
-rw-r--r--vrsite/model.go507
-rw-r--r--vrsite/page.go172
-rw-r--r--vrsite/render.go289
-rw-r--r--vrsite/serve.go522
-rw-r--r--vrsite/static.go181
-rw-r--r--vrsite/templates/frag-activity.tmpl34
-rw-r--r--vrsite/templates/frag-jj.tmpl33
-rw-r--r--vrsite/templates/frag-note.tmpl52
-rw-r--r--vrsite/templates/layout.tmpl71
-rw-r--r--vrsite/templates/page-change.tmpl37
-rw-r--r--vrsite/templates/page-file.tmpl20
-rw-r--r--vrsite/templates/page-files.tmpl13
-rw-r--r--vrsite/templates/page-index.tmpl52
-rw-r--r--vrsite/templates/page-jj.tmpl25
-rw-r--r--vrsite/templates/page-notes.tmpl43
-rw-r--r--vrsite/theme.go194
-rw-r--r--vrsite/tree.go115
31 files changed, 4359 insertions, 0 deletions
diff --git a/vrsite/app_test.go b/vrsite/app_test.go
new file mode 100644
index 0000000..c56fb0d
--- /dev/null
+++ b/vrsite/app_test.go
@@ -0,0 +1,456 @@
+package main
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+func logLines(lines ...string) string { return strings.Join(lines, "\n") + "\n" }
+
+const (
+ noteA = `{"time":"2026-07-20T10:00:00Z","op":"note","session":"s1","agent":"codex","model":"gpt-5.6-sol","reasoning":"max","dir":"/repo","change":"aaa","file":"src/lib.rs","start":10,"end":20,"note_id":1,"type":"struct","text":"Cache is a two-level map"}`
+ noteB = `{"time":"2026-07-25T10:00:00Z","op":"note","session":"s2","agent":"claude","model":"claude-fable-5","reasoning":"xhigh","dir":"/repo","change":"aaa","file":"src/main.rs","note_id":1,"text":"entry point does too much"}`
+ readA = `{"time":"2026-07-20T09:59:00Z","op":"read","session":"s1","agent":"codex","model":"gpt-5.6-sol","dir":"/repo","change":"aaa","file":"src/lib.rs","start":1,"end":30}`
+ grepA = `{"time":"2026-07-20T09:58:00Z","op":"grep","session":"s1","agent":"codex","dir":"/repo","change":"aaa","file":"src/lib.rs","pattern":"Cache","matches":3}`
+)
+
+func testSite(t *testing.T) *Site {
+ t.Helper()
+ s := buildModel("test", parseLog([]byte(logLines(grepA, readA, noteA, noteB))))
+ s.Theme, s.Light = loadTheme("", "", "dark"), loadTheme("", "", "light")
+ return s
+}
+
+func TestBuildModel(t *testing.T) {
+ s := testSite(t)
+ if s.Change != "aaa" {
+ t.Errorf("site change = %q, want aaa", s.Change)
+ }
+ if len(s.Agents) != 2 || s.Agents[0].Bit != 1 || s.Agents[1].Bit != 2 {
+ t.Errorf("agents = %+v", s.Agents)
+ }
+ f := s.Files["src/lib.rs"]
+ if f == nil || f.Reads != 1 || f.Greps != 1 || len(f.Notes) != 1 {
+ t.Fatalf("src/lib.rs = %+v", f)
+ }
+ if f.Cov[15] != 1 || f.Mask != 1 {
+ t.Errorf("coverage = %v mask %d", f.Cov, f.Mask)
+ }
+ if got := s.Notes[0].When; got == "" {
+ t.Error("note has no rendered timestamp")
+ }
+}
+
+// A ninth agent gets no color instead of overflowing the uint8 mask (and the
+// per-mask CSS it would generate).
+func TestAgentColorsAreBounded(t *testing.T) {
+ var lines []string
+ for i := 0; i < maxAgents+3; i++ {
+ lines = append(lines, `{"time":"2026-07-20T10:00:00Z","op":"note","agent":"a`+string(rune('a'+i))+`","change":"aaa","note_id":1,"text":"x"}`)
+ }
+ s := buildModel("t", parseLog([]byte(logLines(lines...))))
+ if len(s.Agents) != maxAgents+3 {
+ t.Fatalf("agents = %d", len(s.Agents))
+ }
+ for i, a := range s.Agents {
+ if i < maxAgents && a.Bit == 0 {
+ t.Errorf("agent %d has no bit", i)
+ }
+ if i >= maxAgents && a.Bit != 0 {
+ t.Errorf("agent %d got bit %d, want none", i, a.Bit)
+ }
+ }
+ if n := len(s.masks()); n != 1<<maxAgents-1 {
+ t.Errorf("masks = %d, want %d", n, 1<<maxAgents-1)
+ }
+}
+
+func TestFilterNotes(t *testing.T) {
+ s := testSite(t)
+ for _, tc := range []struct {
+ name string
+ f NoteFilter
+ want []string
+ }{
+ {"all", NoteFilter{}, []string{"src/main.rs", "src/lib.rs"}}, // newest first
+ {"text", NoteFilter{Text: "two-level"}, []string{"src/lib.rs"}},
+ {"text is case-insensitive", NoteFilter{Text: "CACHE"}, []string{"src/lib.rs"}},
+ {"file substring", NoteFilter{File: "main"}, []string{"src/main.rs"}},
+ {"agent", NoteFilter{Agent: "claude"}, []string{"src/main.rs"}},
+ {"model", NoteFilter{Model: "gpt-5.6-sol"}, []string{"src/lib.rs"}},
+ {"session", NoteFilter{Session: "s2"}, []string{"src/main.rs"}},
+ {"kind", NoteFilter{Kind: "struct"}, []string{"src/lib.rs"}},
+ {"from", NoteFilter{From: "2026-07-21"}, []string{"src/main.rs"}},
+ {"to", NoteFilter{To: "2026-07-21"}, []string{"src/lib.rs"}},
+ {"range", NoteFilter{From: "2026-07-19", To: "2026-07-26"}, []string{"src/main.rs", "src/lib.rs"}},
+ {"combined", NoteFilter{Agent: "codex", Text: "map"}, []string{"src/lib.rs"}},
+ {"no match", NoteFilter{Agent: "codex", Text: "nothing"}, nil},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ var got []string
+ for _, n := range s.FilterNotes(tc.f) {
+ got = append(got, n.File)
+ }
+ if strings.Join(got, ",") != strings.Join(tc.want, ",") {
+ t.Errorf("got %v, want %v", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestFacetsAreDistinctAndSorted(t *testing.T) {
+ fa := testSite(t).Facets()
+ if strings.Join(fa.Agents, ",") != "claude,codex" {
+ t.Errorf("agents = %v", fa.Agents)
+ }
+ if strings.Join(fa.Kinds, ",") != "struct" {
+ t.Errorf("kinds = %v", fa.Kinds)
+ }
+ if strings.Join(fa.Sessions, ",") != "s1,s2" {
+ t.Errorf("sessions = %v", fa.Sessions)
+ }
+}
+
+func TestSessionsReportWhatIsRunning(t *testing.T) {
+ now := time.Date(2026, 7, 25, 10, 1, 0, 0, time.UTC)
+ ss := testSite(t).Sessions(now, liveWindow, 10)
+ if len(ss) != 2 {
+ t.Fatalf("sessions = %d", len(ss))
+ }
+ if ss[0].ID != "s2" || !ss[0].Live {
+ t.Errorf("newest session = %+v, want s2 live", ss[0])
+ }
+ if ss[1].ID != "s1" || ss[1].Live {
+ t.Errorf("older session = %+v, want s1 not live", ss[1])
+ }
+ if ss[1].LastOp != "note on src/lib.rs" || ss[1].Reads != 1 || ss[1].Greps != 1 {
+ t.Errorf("s1 activity = %q %d/%d", ss[1].LastOp, ss[1].Reads, ss[1].Greps)
+ }
+}
+
+func TestNextNoteIDCountsPerSession(t *testing.T) {
+ entries := parseLog([]byte(logLines(noteA, noteB)))
+ if got := nextNoteID(entries, "s1"); got != 2 {
+ t.Errorf("s1 next = %d, want 2", got)
+ }
+ if got := nextNoteID(entries, "web:me"); got != 1 {
+ t.Errorf("fresh session next = %d, want 1", got)
+ }
+}
+
+// The graph art in front of a templated row must not end up inside a field.
+func TestParseRows(t *testing.T) {
+ out := "@ \x1eabc123\x1fabc1\x1fdef456\x1fdef4\x1fme@x\x1f2026-07-20 10:00\x1fmain\x1fworking copy\x1ffix the thing\n" +
+ "│\n" +
+ "~\n"
+ rows := parseRows([]byte(out), false)
+ if len(rows) != 3 {
+ t.Fatalf("rows = %d", len(rows))
+ }
+ r := rows[0]
+ if r.Graph != "@ " || r.ID != "abc123" || r.Short != "abc1" || r.CommitShort != "def4" ||
+ r.Author != "me@x" || r.Refs != "main" || r.Flags != "working copy" || r.Desc != "fix the thing" {
+ t.Errorf("row = %+v", r)
+ }
+ if !rows[1].Blank() || rows[1].Graph != "│" {
+ t.Errorf("graph-only row = %+v", rows[1])
+ }
+ op := parseRows([]byte("@ \x1eopid\x1fopid1\x1f\x1f\x1fme@host\x1f2026-07-20 10:00:00\x1f\x1f10:00:05\x1fsnapshot\n"), true)
+ if len(op) != 1 || op[0].End != "10:00:05" || op[0].Flags != "" || op[0].Desc != "snapshot" {
+ t.Errorf("op row = %+v", op)
+ }
+}
+
+func TestCheckRevsetRejectsFlags(t *testing.T) {
+ if err := checkRevset("--config=x"); err == nil {
+ t.Error("a leading dash must be refused, jj would read it as a flag")
+ }
+ if err := checkRevset("all() & file(x)"); err != nil {
+ t.Errorf("plain revset refused: %v", err)
+ }
+}
+
+func TestHrefModes(t *testing.T) {
+ live := &page{Live: true, Root: "/"}
+ if got := live.Href("code", "src/a b.rs"); got != "/code/src/a%20b.rs" {
+ t.Errorf("live code href = %q", got)
+ }
+ live.Rev = "xyz"
+ if got := live.Href("code", "src/a.rs"); got != "/code/src/a.rs?rev=xyz" {
+ t.Errorf("live code href with rev = %q", got)
+ }
+ if got := live.Href("notes"); got != "/notes" {
+ t.Errorf("live notes href = %q", got)
+ }
+ static := &page{Root: "../"}
+ if got := static.Href("code", "src/a.rs"); got != "../code/src/a.rs.html" {
+ t.Errorf("static code href = %q", got)
+ }
+ if got := static.Href("change", "abc"); got != "" {
+ t.Errorf("static change href = %q, want none", got)
+ }
+}
+
+// ── the web app, end to end ───────────────────────────────────────────────
+
+// testRepo makes a one-commit jj repo and returns its path plus the change id.
+func testRepo(t *testing.T) (string, string) {
+ t.Helper()
+ if _, err := exec.LookPath("jj"); err != nil {
+ t.Skip("jj not installed")
+ }
+ dir := t.TempDir()
+ env := append(os.Environ(), "JJ_USER=test", "[email protected]", "HOME="+dir)
+ runJJ := func(args ...string) {
+ t.Helper()
+ cmd := exec.Command("jj", args...)
+ cmd.Dir, cmd.Env = dir, env
+ if out, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("jj %s: %v\n%s", strings.Join(args, " "), err, out)
+ }
+ }
+ runJJ("git", "init")
+ if err := os.WriteFile(filepath.Join(dir, "hello.txt"), []byte("one\ntwo\nthree\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ runJJ("describe", "-m", "first change")
+ change, err := resolveChange(dir, "@")
+ if err != nil {
+ t.Fatal(err)
+ }
+ return dir, change
+}
+
+func testServer(t *testing.T) (*server, string, string) {
+ t.Helper()
+ repo, change := testRepo(t)
+ logPath := filepath.Join(t.TempDir(), "trace.jsonl")
+ entry := `{"time":"2026-07-20T10:00:00Z","op":"read","session":"s1","agent":"codex","model":"gpt-5.6-sol","dir":"` +
+ repo + `","change":"` + change + `","file":"hello.txt","start":1,"end":2}`
+ note := `{"time":"2026-07-20T10:01:00Z","op":"note","session":"s1","agent":"codex","model":"gpt-5.6-sol","dir":"` +
+ repo + `","change":"` + change + `","file":"hello.txt","start":2,"end":2,"note_id":1,"text":"second line matters"}`
+ if err := os.WriteFile(logPath, []byte(logLines(entry, note)), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ sv := newServer(logPath, repo, "test", "tester", loadTheme("", "", "dark"), loadTheme("", "", "light"))
+ return sv, logPath, change
+}
+
+func get(t *testing.T, h http.Handler, path string, hx bool) *httptest.ResponseRecorder {
+ t.Helper()
+ r := httptest.NewRequest("GET", path, nil)
+ if hx {
+ r.Header.Set("HX-Request", "true")
+ }
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, r)
+ return w
+}
+
+func TestServerPages(t *testing.T) {
+ sv, _, change := testServer(t)
+ h := sv.handler()
+ for _, tc := range []struct{ path, want string }{
+ {"/", "second line matters"},
+ {"/files", "hello.txt"},
+ {"/tree", `class="file`},
+ {"/notes", "second line matters"},
+ {"/code/hello.txt", "three"},
+ {"/jj", "revset"},
+ {"/change/" + change, "first change"},
+ {"/style.css", "--am1"},
+ {"/app.js", "vrsite-mode"},
+ {"/htmx.min.js", "htmx"},
+ } {
+ w := get(t, h, tc.path, false)
+ if w.Code != 200 {
+ t.Errorf("GET %s = %d", tc.path, w.Code)
+ continue
+ }
+ if !strings.Contains(w.Body.String(), tc.want) {
+ t.Errorf("GET %s does not mention %q", tc.path, tc.want)
+ }
+ }
+}
+
+func TestNotesFilterOverHTTP(t *testing.T) {
+ sv, _, _ := testServer(t)
+ h := sv.handler()
+ if b := get(t, h, "/notes/list?text=second", true).Body.String(); !strings.Contains(b, "second line matters") {
+ t.Error("matching filter dropped the note")
+ }
+ b := get(t, h, "/notes/list?text=absent", true).Body.String()
+ if strings.Contains(b, "second line matters") || !strings.Contains(b, "no notes match") {
+ t.Errorf("non-matching filter kept the note: %s", b)
+ }
+ if !strings.Contains(b, `id="notecount" hx-swap-oob`) {
+ t.Error("list fragment does not carry the out-of-band count")
+ }
+}
+
+// A comment posted from the browser lands in the log, shows up in the model,
+// and leaves the repository alone.
+func TestAddNoteAppendsToLog(t *testing.T) {
+ sv, logPath, change := testServer(t)
+ h := sv.handler()
+ before, err := jjRun(sv.repo, "status")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ form := url.Values{"file": {"hello.txt"}, "start": {"3"}, "end": {"3"},
+ "kind": {"line"}, "text": {"written from the browser"}, "rev": {"@"}}
+ r := httptest.NewRequest("POST", "/notes", strings.NewReader(form.Encode()))
+ r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ r.Header.Set("HX-Request", "true")
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, r)
+ if w.Code != 200 {
+ t.Fatalf("POST /notes = %d: %s", w.Code, w.Body)
+ }
+ if !strings.Contains(w.Body.String(), "written from the browser") {
+ t.Errorf("response does not contain the new note: %s", w.Body)
+ }
+
+ b, err := os.ReadFile(logPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ entries := parseLog(b)
+ last := entries[len(entries)-1]
+ if last.Op != "note" || last.Agent != "tester" || last.Session != "web:tester" ||
+ last.File != "hello.txt" || last.Start != 3 || last.Text != "written from the browser" {
+ t.Errorf("appended entry = %+v", last)
+ }
+ if last.Change != change {
+ t.Errorf("note change = %q, want %q", last.Change, change)
+ }
+ if last.NoteID != 1 {
+ t.Errorf("note id = %d, want 1 (first of this session)", last.NoteID)
+ }
+ if last.Time == "" {
+ t.Error("appended entry has no timestamp")
+ }
+
+ // visible without a restart, and the line is now marked as noted
+ if body := get(t, h, "/code/hello.txt", false).Body.String(); !strings.Contains(body, "written from the browser") {
+ t.Error("the new note is not on the file page")
+ }
+ after, err := jjRun(sv.repo, "status")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(before) != string(after) {
+ t.Errorf("the repository changed:\nbefore %s\nafter %s", before, after)
+ }
+}
+
+func TestAddNoteRejectsCrossOriginAndEmptyText(t *testing.T) {
+ sv, _, _ := testServer(t)
+ h := sv.handler()
+
+ form := url.Values{"text": {"hi"}, "rev": {"@"}}
+ r := httptest.NewRequest("POST", "/notes", strings.NewReader(form.Encode()))
+ r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ r.Header.Set("Origin", "http://evil.example")
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, r)
+ if w.Code != http.StatusForbidden {
+ t.Errorf("cross-origin POST = %d, want 403", w.Code)
+ }
+
+ r = httptest.NewRequest("POST", "/notes", strings.NewReader(url.Values{"text": {" "}}.Encode()))
+ r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ w = httptest.NewRecorder()
+ h.ServeHTTP(w, r)
+ if w.Code != http.StatusBadRequest {
+ t.Errorf("empty note = %d, want 400", w.Code)
+ }
+}
+
+func TestJJQueries(t *testing.T) {
+ sv, _, change := testServer(t)
+ h := sv.handler()
+
+ b := get(t, h, "/jj/log?revset="+url.QueryEscape("all()"), true).Body.String()
+ if !strings.Contains(b, `href="/change/`+change) {
+ t.Errorf("jj log has no link to the change: %s", b)
+ }
+ if !strings.Contains(b, "first change") {
+ t.Error("jj log does not show the description")
+ }
+ b = get(t, h, "/jj/op?limit=5", true).Body.String()
+ if !strings.Contains(b, "at_op=") {
+ t.Errorf("op log has no --at-operation links: %s", b)
+ }
+ b = get(t, h, "/jj/log?revset="+url.QueryEscape("bogusfn(")+"", true).Body.String()
+ if !strings.Contains(b, `class="err"`) {
+ t.Errorf("a bad revset should report jj's error: %s", b)
+ }
+ b = get(t, h, "/jj/log?revset="+url.QueryEscape("--config=ui.paginate=never"), true).Body.String()
+ if !strings.Contains(b, "must not start with") {
+ t.Errorf("flag-like revset was not refused: %s", b)
+ }
+}
+
+// Model files are shared across requests and cloned per render; run the
+// handlers hard in parallel so -race can complain about it.
+func TestConcurrentRequests(t *testing.T) {
+ sv, _, change := testServer(t)
+ h := sv.handler()
+ paths := []string{"/", "/code/hello.txt", "/notes", "/notes/list?text=second",
+ "/tree", "/files", "/activity?compact=1", "/change/" + change,
+ "/code/hello.txt?rev=" + change}
+ done := make(chan struct{})
+ for i := 0; i < len(paths)*3; i++ {
+ go func(p string) {
+ defer func() { done <- struct{}{} }()
+ if w := get(t, h, p, false); w.Code != 200 {
+ t.Errorf("GET %s = %d", p, w.Code)
+ }
+ }(paths[i%len(paths)])
+ }
+ for i := 0; i < len(paths)*3; i++ {
+ <-done
+ }
+}
+
+func TestCodePageAtMissingRevision(t *testing.T) {
+ sv, _, _ := testServer(t)
+ w := get(t, sv.handler(), "/code/nope.txt", false)
+ if w.Code != 200 || !strings.Contains(w.Body.String(), "not present at this change") {
+ t.Errorf("missing file = %d: %s", w.Code, w.Body)
+ }
+}
+
+func TestServerPicksUpLogAppendsFromOtherProcesses(t *testing.T) {
+ sv, logPath, change := testServer(t)
+ h := sv.handler()
+ if strings.Contains(get(t, h, "/notes", false).Body.String(), "from another process") {
+ t.Fatal("note exists before it was written")
+ }
+ f, err := os.OpenFile(logPath, os.O_APPEND|os.O_WRONLY, 0o644)
+ if err != nil {
+ t.Fatal(err)
+ }
+ line := `{"time":"2026-07-26T10:00:00Z","op":"note","session":"s9","agent":"vr","change":"` +
+ change + `","file":"hello.txt","note_id":1,"text":"from another process"}`
+ if _, err := f.WriteString(line + "\n"); err != nil {
+ t.Fatal(err)
+ }
+ f.Close()
+ // the poll is stat-based; make sure the mtime moved
+ future := time.Now().Add(time.Second)
+ os.Chtimes(logPath, future, future)
+
+ if !strings.Contains(get(t, h, "/notes", false).Body.String(), "from another process") {
+ t.Error("an append by vr was not picked up")
+ }
+}
diff --git a/vrsite/assets/app.js b/vrsite/assets/app.js
new file mode 100644
index 0000000..79dc190
--- /dev/null
+++ b/vrsite/assets/app.js
@@ -0,0 +1,181 @@
+// app.js — the client half of vrsite. Everything here works in the static
+// export too; htmx only takes over the parts that need a server (filters,
+// comments, live activity, jj queries).
+"use strict";
+
+const root = document.documentElement;
+const live = root.dataset.live === "1";
+
+// ── focus: trace or notes, never both ─────────────────────────────────────
+// Coverage and notes want the same pixels (line background, gutter color,
+// tree markers), so the whole UI switches between them instead of layering.
+function setMode(m) {
+ root.dataset.mode = m;
+ localStorage.setItem("vrsite-mode", m);
+ for (const b of document.querySelectorAll(".mode"))
+ b.setAttribute("aria-pressed", String(b.dataset.mode === m));
+}
+for (const b of document.querySelectorAll(".mode"))
+ b.addEventListener("click", () => setMode(b.dataset.mode));
+setMode(root.dataset.mode || "trace");
+
+const typing = e =>
+ /^(INPUT|TEXTAREA|SELECT)$/.test(e.target.tagName) || e.target.isContentEditable;
+
+document.addEventListener("keydown", e => {
+ if (e.metaKey || e.ctrlKey || e.altKey || typing(e)) return;
+ if (e.key === "t") setMode(root.dataset.mode === "notes" ? "trace" : "notes");
+ if (e.key === "/") {
+ const f = document.getElementById("filefind");
+ if (f) { e.preventDefault(); f.focus(); f.select(); }
+ }
+});
+
+// ── theme ─────────────────────────────────────────────────────────────────
+const themesel = document.getElementById("themesel");
+if (themesel) {
+ themesel.value = localStorage.getItem("vrsite-theme") || "system";
+ themesel.addEventListener("change", () => {
+ localStorage.setItem("vrsite-theme", themesel.value);
+ if (themesel.value === "system") delete root.dataset.theme;
+ else root.dataset.theme = themesel.value;
+ });
+}
+
+// ── nav tree ──────────────────────────────────────────────────────────────
+const nav = document.getElementById("nav");
+const tree = document.getElementById("tree");
+const state = JSON.parse(localStorage.getItem("vrsite-tree") || "{}");
+
+if (nav && tree) {
+ const base = nav.dataset.root, cur = nav.dataset.current;
+ fetch(nav.dataset.tree).then(r => r.text()).then(t => {
+ tree.innerHTML = t.replaceAll('href="@@', 'href="' + base);
+ for (const d of tree.querySelectorAll("details"))
+ if (d.dataset.path in state) d.open = !!state[d.dataset.path];
+ if (cur)
+ for (const a of tree.querySelectorAll("a.file"))
+ if (a.dataset.path === cur) {
+ a.setAttribute("aria-current", "page");
+ for (let e = a.parentElement; e && e !== tree; e = e.parentElement)
+ if (e.tagName === "DETAILS") e.open = true;
+ a.scrollIntoView({block: "center"});
+ break;
+ }
+ tree.addEventListener("toggle", e => {
+ if (tree.classList.contains("filtering")) return; // filter drives open state
+ state[e.target.dataset.path] = e.target.open ? 1 : 0;
+ localStorage.setItem("vrsite-tree", JSON.stringify(state));
+ }, true);
+ }).catch(() => {
+ tree.innerHTML = '<p class="meta">tree needs http — use the <a href="' +
+ base + 'files.html">file index</a></p>';
+ });
+}
+
+// ── find a file ───────────────────────────────────────────────────────────
+const find = document.getElementById("filefind");
+if (find && tree) {
+ const apply = () => {
+ const q = find.value.trim().toLowerCase();
+ tree.classList.toggle("filtering", q !== "");
+ for (const a of tree.querySelectorAll("a.file")) {
+ const hit = !q || a.dataset.path.toLowerCase().includes(q);
+ a.closest("li").hidden = !hit;
+ a.classList.toggle("hit", !!q && hit);
+ }
+ for (const d of tree.querySelectorAll("details")) {
+ const any = d.querySelector("li:not([hidden])");
+ d.hidden = !!q && !any;
+ d.open = q ? !!any : !!state[d.dataset.path];
+ }
+ };
+ find.addEventListener("input", apply);
+ find.addEventListener("search", apply);
+ find.addEventListener("keydown", e => {
+ if (e.key === "Escape") { find.value = ""; apply(); find.blur(); }
+ if (e.key === "Enter") {
+ const first = tree.querySelector("li:not([hidden]) a.file");
+ if (first) first.click();
+ }
+ });
+}
+
+// ── code lines: jump to a note, pick a range to comment on ────────────────
+const codeLines = document.querySelectorAll("ol.code li");
+const nstart = document.getElementById("nstart"), nend = document.getElementById("nend");
+let anchor = 0;
+
+function lineNo(li) { return parseInt(li.id.slice(1), 10) || 0; }
+
+function markSelection(a, b) {
+ const lo = Math.min(a, b), hi = Math.max(a, b);
+ for (const li of codeLines) {
+ const n = lineNo(li);
+ li.classList.toggle("sel", n >= lo && n <= hi);
+ }
+ if (nstart) nstart.value = lo;
+ if (nend) nend.value = hi > lo ? hi : "";
+}
+
+for (const li of codeLines) {
+ li.addEventListener("click", e => {
+ const note = li.dataset.note && document.getElementById(li.dataset.note);
+ if (note && root.dataset.mode === "notes") {
+ note.scrollIntoView({behavior: "smooth", block: "center"});
+ note.classList.remove("flash"); void note.offsetWidth; note.classList.add("flash");
+ }
+ if (!live || root.dataset.mode !== "notes") return;
+ const n = lineNo(li);
+ if (e.shiftKey && anchor) markSelection(anchor, n);
+ else { anchor = n; markSelection(n, n); }
+ });
+}
+
+// ⌘/ctrl+enter posts the note form from inside the textarea
+for (const ta of document.querySelectorAll(".notform textarea"))
+ ta.addEventListener("keydown", e => {
+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) ta.form.requestSubmit();
+ });
+
+// ── note filters ──────────────────────────────────────────────────────────
+// Live pages let the server filter (htmx); the static export filters the
+// rendered list in place, so the same form works either way.
+const filters = document.getElementById("notefilters");
+if (filters) {
+ const count = document.getElementById("notecount");
+ const val = n => (filters.elements[n] ? filters.elements[n].value.trim().toLowerCase() : "");
+ const applyLocal = () => {
+ const text = val("text"), file = val("file"), agent = val("agent"),
+ model = val("model"), session = val("session"), kind = val("kind"),
+ from = val("from"), to = val("to");
+ let shown = 0;
+ for (const art of document.querySelectorAll("#notelist .note")) {
+ const d = art.dataset, body = art.querySelector("p").textContent.toLowerCase();
+ const ok =
+ (!text || body.includes(text)) &&
+ (!file || (d.file || "").toLowerCase().includes(file)) &&
+ (!agent || d.agent === filters.elements.agent.value) &&
+ (!model || d.model === filters.elements.model.value) &&
+ (!session || d.session === filters.elements.session.value) &&
+ (!kind || d.kind === filters.elements.kind.value) &&
+ (!from || (d.date && d.date >= from)) &&
+ (!to || (d.date && d.date <= to));
+ art.hidden = !ok;
+ if (ok) shown++;
+ }
+ if (count) count.textContent = shown;
+ };
+ if (!live) {
+ filters.addEventListener("input", applyLocal);
+ filters.addEventListener("change", applyLocal);
+ filters.addEventListener("submit", e => { e.preventDefault(); applyLocal(); });
+ }
+ const clear = document.getElementById("clearfilters");
+ if (clear) clear.addEventListener("click", () => {
+ filters.reset();
+ for (const el of filters.elements) if (el.name) el.value = "";
+ if (live) window.htmx && htmx.trigger(filters, "change");
+ else applyLocal();
+ });
+}
diff --git a/vrsite/assets/htmx.min.js b/vrsite/assets/htmx.min.js
new file mode 100644
index 0000000..c62505f
--- /dev/null
+++ b/vrsite/assets/htmx.min.js
@@ -0,0 +1,2 @@
+/* htmx 2.0.4 — https://htmx.org — Zero-Clause BSD — vendored so the app has no network deps */
+var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=cn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true},parseInterval:null,_:null,version:"2.0.4"};Q.onLoad=j;Q.process=kt;Q.on=ye;Q.off=be;Q.trigger=he;Q.ajax=Rn;Q.find=u;Q.findAll=x;Q.closest=g;Q.remove=z;Q.addClass=K;Q.removeClass=G;Q.toggleClass=W;Q.takeClass=Z;Q.swap=$e;Q.defineExtension=Fn;Q.removeExtension=Bn;Q.logAll=V;Q.logNone=_;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:le,canAccessLocalStorage:B,findThisElement:Se,filterValues:hn,swap:$e,hasAttribute:s,getAttributeValue:te,getClosestAttributeValue:re,getClosestMatch:o,getExpressionVars:En,getHeaders:fn,getInputValues:cn,getInternalData:ie,getSwapSpecification:gn,getTriggerSpecs:st,getTarget:Ee,makeFragment:P,mergeObjects:ce,makeSettleInfo:xn,oobSwap:He,querySelectorExt:ae,settleImmediately:Kt,shouldCancel:ht,triggerEvent:he,triggerErrorEvent:fe,withExtensions:Ft};const r=["get","post","put","delete","patch"];const H=r.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function te(e,t){return ee(e,t)||ee(e,"data-"+t)}function c(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function ne(){return document}function m(e,t){return e.getRootNode?e.getRootNode({composed:t}):ne()}function o(e,t){while(e&&!t(e)){e=c(e)}return e||null}function i(e,t,n){const r=te(t,n);const o=te(t,"hx-disinherit");var i=te(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function re(t,n){let r=null;o(t,function(e){return!!(r=i(t,ue(e),n))});if(r!=="unset"){return r}}function h(e,t){const n=e instanceof Element&&(e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector);return!!n&&n.call(e,t)}function T(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function q(e){const t=new DOMParser;return t.parseFromString(e,"text/html")}function L(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function A(e){const t=ne().createElement("script");se(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function N(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function I(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(N(e)){const t=A(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){O(e)}finally{e.remove()}}})}function P(e){const t=e.replace(/<head(\s[^>]*)?>[\s\S]*?<\/head>/i,"");const n=T(t);let r;if(n==="html"){r=new DocumentFragment;const i=q(e);L(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=q(t);L(r,i.body);r.title=i.title}else{const i=q('<body><template class="internal-htmx-wrapper">'+t+"</template></body>");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){I(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function oe(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function k(e){return typeof e==="function"}function D(e){return t(e,"Object")}function ie(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function M(t){const n=[];if(t){for(let e=0;e<t.length;e++){n.push(t[e])}}return n}function se(t,n){if(t){for(let e=0;e<t.length;e++){n(t[e])}}}function X(e){const t=e.getBoundingClientRect();const n=t.top;const r=t.bottom;return n<window.innerHeight&&r>=0}function le(e){return e.getRootNode({composed:true})===document}function F(e){return e.trim().split(/\s+/)}function ce(e,t){for(const n in t){if(t.hasOwnProperty(n)){e[n]=t[n]}}return e}function S(e){try{return JSON.parse(e)}catch(e){O(e);return null}}function B(){const e="htmx:localStorageTest";try{localStorage.setItem(e,e);localStorage.removeItem(e);return true}catch(e){return false}}function U(t){try{const e=new URL(t);if(e){t=e.pathname+e.search}if(!/^\/$/.test(t)){t=t.replace(/\/+$/,"")}return t}catch(e){return t}}function e(e){return vn(ne().body,function(){return eval(e)})}function j(t){const e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function V(){Q.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function _(){Q.logger=null}function u(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return u(ne(),e)}}function x(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return x(ne(),e)}}function E(){return window}function z(e,t){e=y(e);if(t){E().setTimeout(function(){z(e);e=null},t)}else{c(e).removeChild(e)}}function ue(e){return e instanceof Element?e:null}function $(e){return e instanceof HTMLElement?e:null}function J(e){return typeof e==="string"?e:null}function f(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function K(e,t,n){e=ue(y(e));if(!e){return}if(n){E().setTimeout(function(){K(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function G(e,t,n){let r=ue(y(e));if(!r){return}if(n){E().setTimeout(function(){G(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function W(e,t){e=y(e);e.classList.toggle(t)}function Z(e,t){e=y(e);se(e.parentElement.children,function(e){G(e,t)});K(ue(e),t)}function g(e,t){e=ue(y(e));if(e&&e.closest){return e.closest(t)}else{do{if(e==null||h(e,t)){return e}}while(e=e&&ue(c(e)));return null}}function l(e,t){return e.substring(0,t.length)===t}function Y(e,t){return e.substring(e.length-t.length)===t}function ge(e){const t=e.trim();if(l(t,"<")&&Y(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function p(t,r,n){if(r.indexOf("global ")===0){return p(t,r.slice(7),true)}t=y(t);const o=[];{let t=0;let n=0;for(let e=0;e<r.length;e++){const l=r[e];if(l===","&&t===0){o.push(r.substring(n,e));n=e+1;continue}if(l==="<"){t++}else if(l==="/"&&e<r.length-1&&r[e+1]===">"){t--}}if(n<r.length){o.push(r.substring(n))}}const i=[];const s=[];while(o.length>0){const r=ge(o.shift());let e;if(r.indexOf("closest ")===0){e=g(ue(t),ge(r.substr(8)))}else if(r.indexOf("find ")===0){e=u(f(t),ge(r.substr(5)))}else if(r==="next"||r==="nextElementSibling"){e=ue(t).nextElementSibling}else if(r.indexOf("next ")===0){e=pe(t,ge(r.substr(5)),!!n)}else if(r==="previous"||r==="previousElementSibling"){e=ue(t).previousElementSibling}else if(r.indexOf("previous ")===0){e=me(t,ge(r.substr(9)),!!n)}else if(r==="document"){e=document}else if(r==="window"){e=window}else if(r==="body"){e=document.body}else if(r==="root"){e=m(t,!!n)}else if(r==="host"){e=t.getRootNode().host}else{s.push(r)}if(e){i.push(e)}}if(s.length>0){const e=s.join(",");const c=f(m(t,!!n));i.push(...M(c.querySelectorAll(e)))}return i}var pe=function(t,e,n){const r=f(m(t,n)).querySelectorAll(e);for(let e=0;e<r.length;e++){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_PRECEDING){return o}}};var me=function(t,e,n){const r=f(m(t,n)).querySelectorAll(e);for(let e=r.length-1;e>=0;e--){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_FOLLOWING){return o}}};function ae(e,t){if(typeof e!=="string"){return p(e,t)[0]}else{return p(ne().body,e)[0]}}function y(e,t){if(typeof e==="string"){return u(f(t)||document,e)}else{return e}}function xe(e,t,n,r){if(k(t)){return{target:ne().body,event:J(e),listener:t,options:n}}else{return{target:y(e),event:J(t),listener:n,options:r}}}function ye(t,n,r,o){Vn(function(){const e=xe(t,n,r,o);e.target.addEventListener(e.event,e.listener,e.options)});const e=k(n);return e?n:r}function be(t,n,r){Vn(function(){const e=xe(t,n,r);e.target.removeEventListener(e.event,e.listener)});return k(n)?n:r}const ve=ne().createElement("output");function we(e,t){const n=re(e,t);if(n){if(n==="this"){return[Se(e,t)]}else{const r=p(e,n);if(r.length===0){O('The selector "'+n+'" on '+t+" returned no matches!");return[ve]}else{return r}}}}function Se(e,t){return ue(o(e,function(e){return te(ue(e),t)!=null}))}function Ee(e){const t=re(e,"hx-target");if(t){if(t==="this"){return Se(e,"hx-target")}else{return ae(e,t)}}else{const n=ie(e);if(n.boosted){return ne().body}else{return e}}}function Ce(t){const n=Q.config.attributesToSettle;for(let e=0;e<n.length;e++){if(t===n[e]){return true}}return false}function Oe(t,n){se(t.attributes,function(e){if(!n.hasAttribute(e.name)&&Ce(e.name)){t.removeAttribute(e.name)}});se(n.attributes,function(e){if(Ce(e.name)){t.setAttribute(e.name,e.value)}})}function Re(t,e){const n=Un(e);for(let e=0;e<n.length;e++){const r=n[e];try{if(r.isInlineSwap(t)){return true}}catch(e){O(e)}}return t==="outerHTML"}function He(e,o,i,t){t=t||ne();let n="#"+ee(o,"id");let s="outerHTML";if(e==="true"){}else if(e.indexOf(":")>0){s=e.substring(0,e.indexOf(":"));n=e.substring(e.indexOf(":")+1)}else{s=e}o.removeAttribute("hx-swap-oob");o.removeAttribute("data-hx-swap-oob");const r=p(t,n,false);if(r){se(r,function(e){let t;const n=o.cloneNode(true);t=ne().createDocumentFragment();t.appendChild(n);if(!Re(s,e)){t=f(n)}const r={shouldSwap:true,target:e,fragment:t};if(!he(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){qe(t);_e(s,e,e,t,i);Te()}se(i.elts,function(e){he(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);fe(ne().body,"htmx:oobErrorNoTarget",{content:o})}return e}function Te(){const e=u("#--htmx-preserve-pantry--");if(e){for(const t of[...e.children]){const n=u("#"+t.id);n.parentNode.moveBefore(t,n);n.remove()}e.remove()}}function qe(e){se(x(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=te(e,"id");const n=ne().getElementById(t);if(n!=null){if(e.moveBefore){let e=u("#--htmx-preserve-pantry--");if(e==null){ne().body.insertAdjacentHTML("afterend","<div id='--htmx-preserve-pantry--'></div>");e=u("#--htmx-preserve-pantry--")}e.moveBefore(n,null)}else{e.parentNode.replaceChild(n,e)}}})}function Le(l,e,c){se(e.querySelectorAll("[id]"),function(t){const n=ee(t,"id");if(n&&n.length>0){const r=n.replace("'","\\'");const o=t.tagName.replace(":","\\:");const e=f(l);const i=e&&e.querySelector(o+"[id='"+r+"']");if(i&&i!==e){const s=t.cloneNode();Oe(t,i);c.tasks.push(function(){Oe(t,s)})}}})}function Ae(e){return function(){G(e,Q.config.addedClass);kt(ue(e));Ne(f(e));he(e,"htmx:load")}}function Ne(e){const t="[autofocus]";const n=$(h(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function a(e,t,n,r){Le(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;K(ue(o),Q.config.addedClass);e.insertBefore(o,t);if(o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE){r.tasks.push(Ae(o))}}}function Ie(e,t){let n=0;while(n<e.length){t=(t<<5)-t+e.charCodeAt(n++)|0}return t}function Pe(t){let n=0;if(t.attributes){for(let e=0;e<t.attributes.length;e++){const r=t.attributes[e];if(r.value){n=Ie(r.name,n);n=Ie(r.value,n)}}}return n}function ke(t){const n=ie(t);if(n.onHandlers){for(let e=0;e<n.onHandlers.length;e++){const r=n.onHandlers[e];be(t,r.event,r.listener)}delete n.onHandlers}}function De(e){const t=ie(e);if(t.timeout){clearTimeout(t.timeout)}if(t.listenerInfos){se(t.listenerInfos,function(e){if(e.on){be(e.on,e.trigger,e.listener)}})}ke(e);se(Object.keys(t),function(e){if(e!=="firstInitCompleted")delete t[e]})}function b(e){he(e,"htmx:beforeCleanupElement");De(e);if(e.children){se(e.children,function(e){b(e)})}}function Me(t,e,n){if(t instanceof Element&&t.tagName==="BODY"){return Ve(t,e,n)}let r;const o=t.previousSibling;const i=c(t);if(!i){return}a(i,t,e,n);if(o==null){r=i.firstChild}else{r=o.nextSibling}n.elts=n.elts.filter(function(e){return e!==t});while(r&&r!==t){if(r instanceof Element){n.elts.push(r)}r=r.nextSibling}b(t);if(t instanceof Element){t.remove()}else{t.parentNode.removeChild(t)}}function Xe(e,t,n){return a(e,e.firstChild,t,n)}function Fe(e,t,n){return a(c(e),e,t,n)}function Be(e,t,n){return a(e,null,t,n)}function Ue(e,t,n){return a(c(e),e.nextSibling,t,n)}function je(e){b(e);const t=c(e);if(t){return t.removeChild(e)}}function Ve(e,t,n){const r=e.firstChild;a(e,r,t,n);if(r){while(r.nextSibling){b(r.nextSibling);e.removeChild(r.nextSibling)}b(r);e.removeChild(r)}}function _e(t,e,n,r,o){switch(t){case"none":return;case"outerHTML":Me(n,r,o);return;case"afterbegin":Xe(n,r,o);return;case"beforebegin":Fe(n,r,o);return;case"beforeend":Be(n,r,o);return;case"afterend":Ue(n,r,o);return;case"delete":je(n);return;default:var i=Un(e);for(let e=0;e<i.length;e++){const s=i[e];try{const l=s.handleSwap(t,n,r,o);if(l){if(Array.isArray(l)){for(let e=0;e<l.length;e++){const c=l[e];if(c.nodeType!==Node.TEXT_NODE&&c.nodeType!==Node.COMMENT_NODE){o.tasks.push(Ae(c))}}}return}}catch(e){O(e)}}if(t==="innerHTML"){Ve(n,r,o)}else{_e(Q.config.defaultSwapStyle,e,n,r,o)}}}function ze(e,n,r){var t=x(e,"[hx-swap-oob], [data-hx-swap-oob]");se(t,function(e){if(Q.config.allowNestedOobSwaps||e.parentElement===null){const t=te(e,"hx-swap-oob");if(t!=null){He(t,e,n,r)}}else{e.removeAttribute("hx-swap-oob");e.removeAttribute("data-hx-swap-oob")}});return t.length>0}function $e(e,t,r,o){if(!o){o={}}e=y(e);const i=o.contextElement?m(o.contextElement,false):ne();const n=document.activeElement;let s={};try{s={elt:n,start:n?n.selectionStart:null,end:n?n.selectionEnd:null}}catch(e){}const l=xn(e);if(r.swapStyle==="textContent"){e.textContent=t}else{let n=P(t);l.title=n.title;if(o.selectOOB){const u=o.selectOOB.split(",");for(let t=0;t<u.length;t++){const a=u[t].split(":",2);let e=a[0].trim();if(e.indexOf("#")===0){e=e.substring(1)}const f=a[1]||"true";const h=n.querySelector("#"+e);if(h){He(f,h,l,i)}}}ze(n,l,i);se(x(n,"template"),function(e){if(e.content&&ze(e.content,l,i)){e.remove()}});if(o.select){const d=ne().createDocumentFragment();se(n.querySelectorAll(o.select),function(e){d.appendChild(e)});n=d}qe(n);_e(r.swapStyle,o.contextElement,e,n,l);Te()}if(s.elt&&!le(s.elt)&&ee(s.elt,"id")){const g=document.getElementById(ee(s.elt,"id"));const p={preventScroll:r.focusScroll!==undefined?!r.focusScroll:!Q.config.defaultFocusScroll};if(g){if(s.start&&g.setSelectionRange){try{g.setSelectionRange(s.start,s.end)}catch(e){}}g.focus(p)}}e.classList.remove(Q.config.swappingClass);se(l.elts,function(e){if(e.classList){e.classList.add(Q.config.settlingClass)}he(e,"htmx:afterSwap",o.eventInfo)});if(o.afterSwapCallback){o.afterSwapCallback()}if(!r.ignoreTitle){kn(l.title)}const c=function(){se(l.tasks,function(e){e.call()});se(l.elts,function(e){if(e.classList){e.classList.remove(Q.config.settlingClass)}he(e,"htmx:afterSettle",o.eventInfo)});if(o.anchor){const e=ue(y("#"+o.anchor));if(e){e.scrollIntoView({block:"start",behavior:"auto"})}}yn(l.elts,r);if(o.afterSettleCallback){o.afterSettleCallback()}};if(r.settleDelay>0){E().setTimeout(c,r.settleDelay)}else{c()}}function Je(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=S(r);for(const i in o){if(o.hasOwnProperty(i)){let e=o[i];if(D(e)){n=e.target!==undefined?e.target:n}else{e={value:e}}he(n,i,e)}}}else{const s=r.split(",");for(let e=0;e<s.length;e++){he(n,s[e].trim(),[])}}}const Ke=/\s/;const v=/[\s,]/;const Ge=/[_$a-zA-Z]/;const We=/[_$a-zA-Z0-9]/;const Ze=['"',"'","/"];const w=/[^\s]/;const Ye=/[{(]/;const Qe=/[})]/;function et(e){const t=[];let n=0;while(n<e.length){if(Ge.exec(e.charAt(n))){var r=n;while(We.exec(e.charAt(n+1))){n++}t.push(e.substring(r,n+1))}else if(Ze.indexOf(e.charAt(n))!==-1){const o=e.charAt(n);var r=n;n++;while(n<e.length&&e.charAt(n)!==o){if(e.charAt(n)==="\\"){n++}n++}t.push(e.substring(r,n+1))}else{const i=e.charAt(n);t.push(i)}n++}return t}function tt(e,t,n){return Ge.exec(e.charAt(0))&&e!=="true"&&e!=="false"&&e!=="this"&&e!==n&&t!=="."}function nt(r,o,i){if(o[0]==="["){o.shift();let e=1;let t=" return (function("+i+"){ return (";let n=null;while(o.length>0){const s=o[0];if(s==="]"){e--;if(e===0){if(n===null){t=t+"true"}o.shift();t+=")})";try{const l=vn(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){fe(ne().body,"htmx:syntax:error",{error:e,source:t});return null}}}else if(s==="["){e++}if(tt(s,n,i)){t+="(("+i+"."+s+") ? ("+i+"."+s+") : (window."+s+"))"}else{t=t+s}n=o.shift()}}}function C(e,t){let n="";while(e.length>0&&!t.test(e[0])){n+=e.shift()}return n}function rt(e){let t;if(e.length>0&&Ye.test(e[0])){e.shift();t=C(e,Qe).trim();e.shift()}else{t=C(e,v)}return t}const ot="input, textarea, select";function it(e,t,n){const r=[];const o=et(t);do{C(o,w);const l=o.length;const c=C(o,/[,\[\s]/);if(c!==""){if(c==="every"){const u={trigger:"every"};C(o,w);u.pollInterval=d(C(o,/[,\[\s]/));C(o,w);var i=nt(e,o,"event");if(i){u.eventFilter=i}r.push(u)}else{const a={trigger:c};var i=nt(e,o,"event");if(i){a.eventFilter=i}C(o,w);while(o.length>0&&o[0]!==","){const f=o.shift();if(f==="changed"){a.changed=true}else if(f==="once"){a.once=true}else if(f==="consume"){a.consume=true}else if(f==="delay"&&o[0]===":"){o.shift();a.delay=d(C(o,v))}else if(f==="from"&&o[0]===":"){o.shift();if(Ye.test(o[0])){var s=rt(o)}else{var s=C(o,v);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const h=rt(o);if(h.length>0){s+=" "+h}}}a.from=s}else if(f==="target"&&o[0]===":"){o.shift();a.target=rt(o)}else if(f==="throttle"&&o[0]===":"){o.shift();a.throttle=d(C(o,v))}else if(f==="queue"&&o[0]===":"){o.shift();a.queue=C(o,v)}else if(f==="root"&&o[0]===":"){o.shift();a[f]=rt(o)}else if(f==="threshold"&&o[0]===":"){o.shift();a[f]=C(o,v)}else{fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}r.push(a)}}if(o.length===l){fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function st(e){const t=te(e,"hx-trigger");let n=[];if(t){const r=Q.config.triggerSpecsCache;n=r&&r[t]||it(e,t,r)}if(n.length>0){return n}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,ot)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function lt(e){ie(e).cancelled=true}function ct(e,t,n){const r=ie(e);r.timeout=E().setTimeout(function(){if(le(e)&&r.cancelled!==true){if(!gt(n,e,Mt("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ct(e,t,n)}},n.pollInterval)}function ut(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function at(e){return g(e,Q.config.disableSelector)}function ft(t,n,e){if(t instanceof HTMLAnchorElement&&ut(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"&&String(ee(t,"method")).toLowerCase()!=="dialog"){n.boosted=true;let r,o;if(t.tagName==="A"){r="get";o=ee(t,"href")}else{const i=ee(t,"method");r=i?i.toLowerCase():"get";o=ee(t,"action");if(o==null||o===""){o=ne().location.href}if(r==="get"&&o.includes("?")){o=o.replace(/\?[^#]+/,"")}}e.forEach(function(e){pt(t,function(e,t){const n=ue(e);if(at(n)){b(n);return}de(r,o,n,t)},n,e,true)})}}function ht(e,t){const n=ue(t);if(!n){return false}if(e.type==="submit"||e.type==="click"){if(n.tagName==="FORM"){return true}if(h(n,'input[type="submit"], button')&&(h(n,"[form]")||g(n,"form")!==null)){return true}if(n instanceof HTMLAnchorElement&&n.href&&(n.getAttribute("href")==="#"||n.getAttribute("href").indexOf("#")!==0)){return true}}return false}function dt(e,t){return ie(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function gt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;fe(ne().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function pt(l,c,e,u,a){const f=ie(l);let t;if(u.from){t=p(l,u.from)}else{t=[l]}if(u.changed){if(!("lastValue"in f)){f.lastValue=new WeakMap}t.forEach(function(e){if(!f.lastValue.has(u)){f.lastValue.set(u,new WeakMap)}f.lastValue.get(u).set(e,e.value)})}se(t,function(i){const s=function(e){if(!le(l)){i.removeEventListener(u.trigger,s);return}if(dt(l,e)){return}if(a||ht(e,l)){e.preventDefault()}if(gt(u,l,e)){return}const t=ie(e);t.triggerSpec=u;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(l)<0){t.handledFor.push(l);if(u.consume){e.stopPropagation()}if(u.target&&e.target){if(!h(ue(e.target),u.target)){return}}if(u.once){if(f.triggeredOnce){return}else{f.triggeredOnce=true}}if(u.changed){const n=event.target;const r=n.value;const o=f.lastValue.get(u);if(o.has(n)&&o.get(n)===r){return}o.set(n,r)}if(f.delayed){clearTimeout(f.delayed)}if(f.throttle){return}if(u.throttle>0){if(!f.throttle){he(l,"htmx:trigger");c(l,e);f.throttle=E().setTimeout(function(){f.throttle=null},u.throttle)}}else if(u.delay>0){f.delayed=E().setTimeout(function(){he(l,"htmx:trigger");c(l,e)},u.delay)}else{he(l,"htmx:trigger");c(l,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:u.trigger,listener:s,on:i});i.addEventListener(u.trigger,s)})}let mt=false;let xt=null;function yt(){if(!xt){xt=function(){mt=true};window.addEventListener("scroll",xt);window.addEventListener("resize",xt);setInterval(function(){if(mt){mt=false;se(ne().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){bt(e)})}},200)}}function bt(e){if(!s(e,"data-hx-revealed")&&X(e)){e.setAttribute("data-hx-revealed","true");const t=ie(e);if(t.initHash){he(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){he(e,"revealed")},{once:true})}}}function vt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;he(e,"htmx:trigger");t(e)}};if(r>0){E().setTimeout(o,r)}else{o()}}function wt(t,n,e){let i=false;se(r,function(r){if(s(t,"hx-"+r)){const o=te(t,"hx-"+r);i=true;n.path=o;n.verb=r;e.forEach(function(e){St(t,e,n,function(e,t){const n=ue(e);if(g(n,Q.config.disableSelector)){b(n);return}de(r,o,n,t)})})}});return i}function St(r,e,t,n){if(e.trigger==="revealed"){yt();pt(r,n,t,e);bt(ue(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=ae(r,e.root)}if(e.threshold){o.threshold=parseFloat(e.threshold)}const i=new IntersectionObserver(function(t){for(let e=0;e<t.length;e++){const n=t[e];if(n.isIntersecting){he(r,"intersect");break}}},o);i.observe(ue(r));pt(ue(r),n,t,e)}else if(!t.firstInitCompleted&&e.trigger==="load"){if(!gt(e,r,Mt("load",{elt:r}))){vt(ue(r),n,t,e.delay)}}else if(e.pollInterval>0){t.polling=true;ct(ue(r),n,e)}else{pt(r,n,t,e)}}function Et(e){const t=ue(e);if(!t){return false}const n=t.attributes;for(let e=0;e<n.length;e++){const r=n[e].name;if(l(r,"hx-on:")||l(r,"data-hx-on:")||l(r,"hx-on-")||l(r,"data-hx-on-")){return true}}return false}const Ct=(new XPathEvaluator).createExpression('.//*[@*[ starts-with(name(), "hx-on:") or starts-with(name(), "data-hx-on:") or'+' starts-with(name(), "hx-on-") or starts-with(name(), "data-hx-on-") ]]');function Ot(e,t){if(Et(e)){t.push(ue(e))}const n=Ct.evaluate(e);let r=null;while(r=n.iterateNext())t.push(ue(r))}function Rt(e){const t=[];if(e instanceof DocumentFragment){for(const n of e.childNodes){Ot(n,t)}}else{Ot(e,t)}return t}function Ht(e){if(e.querySelectorAll){const n=", [hx-boost] a, [data-hx-boost] a, a[hx-boost], a[data-hx-boost]";const r=[];for(const i in Mn){const s=Mn[i];if(s.getSelectors){var t=s.getSelectors();if(t){r.push(t)}}}const o=e.querySelectorAll(H+n+", form, [type='submit'],"+" [hx-ext], [data-hx-ext], [hx-trigger], [data-hx-trigger]"+r.flat().map(e=>", "+e).join(""));return o}else{return[]}}function Tt(e){const t=g(ue(e.target),"button, input[type='submit']");const n=Lt(e);if(n){n.lastButtonClicked=t}}function qt(e){const t=Lt(e);if(t){t.lastButtonClicked=null}}function Lt(e){const t=g(ue(e.target),"button, input[type='submit']");if(!t){return}const n=y("#"+ee(t,"form"),t.getRootNode())||g(t,"form");if(!n){return}return ie(n)}function At(e){e.addEventListener("click",Tt);e.addEventListener("focusin",Tt);e.addEventListener("focusout",qt)}function Nt(t,e,n){const r=ie(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){vn(t,function(){if(at(t)){return}if(!o){o=new Function("event",n)}o.call(t,e)})};t.addEventListener(e,i);r.onHandlers.push({event:e,listener:i})}function It(t){ke(t);for(let e=0;e<t.attributes.length;e++){const n=t.attributes[e].name;const r=t.attributes[e].value;if(l(n,"hx-on")||l(n,"data-hx-on")){const o=n.indexOf("-on")+3;const i=n.slice(o,o+1);if(i==="-"||i===":"){let e=n.slice(o+1);if(l(e,":")){e="htmx"+e}else if(l(e,"-")){e="htmx:"+e.slice(1)}else if(l(e,"htmx-")){e="htmx:"+e.slice(5)}Nt(t,e,r)}}}}function Pt(t){if(g(t,Q.config.disableSelector)){b(t);return}const n=ie(t);const e=Pe(t);if(n.initHash!==e){De(t);n.initHash=e;he(t,"htmx:beforeProcessNode");const r=st(t);const o=wt(t,n,r);if(!o){if(re(t,"hx-boost")==="true"){ft(t,n,r)}else if(s(t,"hx-trigger")){r.forEach(function(e){St(t,e,n,function(){})})}}if(t.tagName==="FORM"||ee(t,"type")==="submit"&&s(t,"form")){At(t)}n.firstInitCompleted=true;he(t,"htmx:afterProcessNode")}}function kt(e){e=y(e);if(g(e,Q.config.disableSelector)){b(e);return}Pt(e);se(Ht(e),function(e){Pt(e)});se(Rt(e),It)}function Dt(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}function Mt(e,t){let n;if(window.CustomEvent&&typeof window.CustomEvent==="function"){n=new CustomEvent(e,{bubbles:true,cancelable:true,composed:true,detail:t})}else{n=ne().createEvent("CustomEvent");n.initCustomEvent(e,true,true,t)}return n}function fe(e,t,n){he(e,t,ce({error:t},n))}function Xt(e){return e==="htmx:afterProcessNode"}function Ft(e,t){se(Un(e),function(e){try{t(e)}catch(e){O(e)}})}function O(e){if(console.error){console.error(e)}else if(console.log){console.log("ERROR: ",e)}}function he(e,t,n){e=y(e);if(n==null){n={}}n.elt=e;const r=Mt(t,n);if(Q.logger&&!Xt(t)){Q.logger(e,t,n)}if(n.error){O(n.error);he(e,"htmx:error",{errorInfo:n})}let o=e.dispatchEvent(r);const i=Dt(t);if(o&&i!==t){const s=Mt(i,r.detail);o=o&&e.dispatchEvent(s)}Ft(ue(e),function(e){o=o&&(e.onEvent(t,r)!==false&&!r.defaultPrevented)});return o}let Bt=location.pathname+location.search;function Ut(){const e=ne().querySelector("[hx-history-elt],[data-hx-history-elt]");return e||ne().body}function jt(t,e){if(!B()){return}const n=_t(e);const r=ne().title;const o=window.scrollY;if(Q.config.historyCacheSize<=0){localStorage.removeItem("htmx-history-cache");return}t=U(t);const i=S(localStorage.getItem("htmx-history-cache"))||[];for(let e=0;e<i.length;e++){if(i[e].url===t){i.splice(e,1);break}}const s={url:t,content:n,title:r,scroll:o};he(ne().body,"htmx:historyItemCreated",{item:s,cache:i});i.push(s);while(i.length>Q.config.historyCacheSize){i.shift()}while(i.length>0){try{localStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(ne().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Vt(t){if(!B()){return null}t=U(t);const n=S(localStorage.getItem("htmx-history-cache"))||[];for(let e=0;e<n.length;e++){if(n[e].url===t){return n[e]}}return null}function _t(e){const t=Q.config.requestClass;const n=e.cloneNode(true);se(x(n,"."+t),function(e){G(e,t)});se(x(n,"[data-disabled-by-htmx]"),function(e){e.removeAttribute("disabled")});return n.innerHTML}function zt(){const e=Ut();const t=Bt||location.pathname+location.search;let n;try{n=ne().querySelector('[hx-history="false" i],[data-hx-history="false" i]')}catch(e){n=ne().querySelector('[hx-history="false"],[data-hx-history="false"]')}if(!n){he(ne().body,"htmx:beforeHistorySave",{path:t,historyElt:e});jt(t,e)}if(Q.config.historyEnabled)history.replaceState({htmx:true},ne().title,window.location.href)}function $t(e){if(Q.config.getCacheBusterParam){e=e.replace(/org\.htmx\.cache-buster=[^&]*&?/,"");if(Y(e,"&")||Y(e,"?")){e=e.slice(0,-1)}}if(Q.config.historyEnabled){history.pushState({htmx:true},"",e)}Bt=e}function Jt(e){if(Q.config.historyEnabled)history.replaceState({htmx:true},"",e);Bt=e}function Kt(e){se(e,function(e){e.call(undefined)})}function Gt(o){const e=new XMLHttpRequest;const i={path:o,xhr:e};he(ne().body,"htmx:historyCacheMiss",i);e.open("GET",o,true);e.setRequestHeader("HX-Request","true");e.setRequestHeader("HX-History-Restore-Request","true");e.setRequestHeader("HX-Current-URL",ne().location.href);e.onload=function(){if(this.status>=200&&this.status<400){he(ne().body,"htmx:historyCacheMissLoad",i);const e=P(this.response);const t=e.querySelector("[hx-history-elt],[data-hx-history-elt]")||e;const n=Ut();const r=xn(n);kn(e.title);qe(e);Ve(n,t,r);Te();Kt(r.tasks);Bt=o;he(ne().body,"htmx:historyRestore",{path:o,cacheMiss:true,serverResponse:this.response})}else{fe(ne().body,"htmx:historyCacheMissLoadError",i)}};e.send()}function Wt(e){zt();e=e||location.pathname+location.search;const t=Vt(e);if(t){const n=P(t.content);const r=Ut();const o=xn(r);kn(t.title);qe(n);Ve(r,n,o);Te();Kt(o.tasks);E().setTimeout(function(){window.scrollTo(0,t.scroll)},0);Bt=e;he(ne().body,"htmx:historyRestore",{path:e,item:t})}else{if(Q.config.refreshOnHistoryMiss){window.location.reload(true)}else{Gt(e)}}}function Zt(e){let t=we(e,"hx-indicator");if(t==null){t=[e]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.classList.add.call(e.classList,Q.config.requestClass)});return t}function Yt(e){let t=we(e,"hx-disabled-elt");if(t==null){t=[]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","");e.setAttribute("data-disabled-by-htmx","")});return t}function Qt(e,t){se(e.concat(t),function(e){const t=ie(e);t.requestCount=(t.requestCount||1)-1});se(e,function(e){const t=ie(e);if(t.requestCount===0){e.classList.remove.call(e.classList,Q.config.requestClass)}});se(t,function(e){const t=ie(e);if(t.requestCount===0){e.removeAttribute("disabled");e.removeAttribute("data-disabled-by-htmx")}})}function en(t,n){for(let e=0;e<t.length;e++){const r=t[e];if(r.isSameNode(n)){return true}}return false}function tn(e){const t=e;if(t.name===""||t.name==null||t.disabled||g(t,"fieldset[disabled]")){return false}if(t.type==="button"||t.type==="submit"||t.tagName==="image"||t.tagName==="reset"||t.tagName==="file"){return false}if(t.type==="checkbox"||t.type==="radio"){return t.checked}return true}function nn(t,e,n){if(t!=null&&e!=null){if(Array.isArray(e)){e.forEach(function(e){n.append(t,e)})}else{n.append(t,e)}}}function rn(t,n,r){if(t!=null&&n!=null){let e=r.getAll(t);if(Array.isArray(n)){e=e.filter(e=>n.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);se(e,e=>r.append(t,e))}}function on(t,n,r,o,i){if(o==null||en(t,o)){return}else{t.push(o)}if(tn(o)){const s=ee(o,"name");let e=o.value;if(o instanceof HTMLSelectElement&&o.multiple){e=M(o.querySelectorAll("option:checked")).map(function(e){return e.value})}if(o instanceof HTMLInputElement&&o.files){e=M(o.files)}nn(s,e,n);if(i){sn(o,r)}}if(o instanceof HTMLFormElement){se(o.elements,function(e){if(t.indexOf(e)>=0){rn(e.name,e.value,n)}else{t.push(e)}if(i){sn(e,r)}});new FormData(o).forEach(function(e,t){if(e instanceof File&&e.name===""){return}nn(t,e,n)})}}function sn(e,t){const n=e;if(n.willValidate){he(n,"htmx:validation:validate");if(!n.checkValidity()){t.push({elt:n,message:n.validationMessage,validity:n.validity});he(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})}}}function ln(n,e){for(const t of e.keys()){n.delete(t)}e.forEach(function(e,t){n.append(t,e)});return n}function cn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=ie(e);if(s.lastButtonClicked&&!le(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||te(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){on(n,o,i,g(e,"form"),l)}on(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&ee(e,"type")==="submit"){const u=s.lastButtonClicked||e;const a=ee(u,"name");nn(a,u.value,o)}const c=we(e,"hx-include");se(c,function(e){on(n,r,i,ue(e),l);if(!h(e,"form")){se(f(e).querySelectorAll(ot),function(e){on(n,r,i,e,l)})}});ln(r,o);return{errors:i,formData:r,values:An(r)}}function un(e,t,n){if(e!==""){e+="&"}if(String(n)==="[object Object]"){n=JSON.stringify(n)}const r=encodeURIComponent(n);e+=encodeURIComponent(t)+"="+r;return e}function an(e){e=qn(e);let n="";e.forEach(function(e,t){n=un(n,t,e)});return n}function fn(e,t,n){const r={"HX-Request":"true","HX-Trigger":ee(e,"id"),"HX-Trigger-Name":ee(e,"name"),"HX-Target":te(t,"id"),"HX-Current-URL":ne().location.href};bn(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(ie(e).boosted){r["HX-Boosted"]="true"}return r}function hn(n,e){const t=re(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){se(t.slice(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;se(t.split(","),function(t){t=t.trim();if(n.has(t)){n.getAll(t).forEach(function(e){r.append(t,e)})}});return r}}else{return n}}function dn(e){return!!ee(e,"href")&&ee(e,"href").indexOf("#")>=0}function gn(e,t){const n=t||re(e,"hx-swap");const r={swapStyle:ie(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&ie(e).boosted&&!dn(e)){r.show="top"}if(n){const s=F(n);if(s.length>0){for(let e=0;e<s.length;e++){const l=s[e];if(l.indexOf("swap:")===0){r.swapDelay=d(l.slice(5))}else if(l.indexOf("settle:")===0){r.settleDelay=d(l.slice(7))}else if(l.indexOf("transition:")===0){r.transition=l.slice(11)==="true"}else if(l.indexOf("ignoreTitle:")===0){r.ignoreTitle=l.slice(12)==="true"}else if(l.indexOf("scroll:")===0){const c=l.slice(7);var o=c.split(":");const u=o.pop();var i=o.length>0?o.join(":"):null;r.scroll=u;r.scrollTarget=i}else if(l.indexOf("show:")===0){const a=l.slice(5);var o=a.split(":");const f=o.pop();var i=o.length>0?o.join(":"):null;r.show=f;r.showTarget=i}else if(l.indexOf("focus-scroll:")===0){const h=l.slice("focus-scroll:".length);r.focusScroll=h=="true"}else if(e==0){r.swapStyle=l}else{O("Unknown modifier in hx-swap: "+l)}}}}return r}function pn(e){return re(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function mn(t,n,r){let o=null;Ft(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(pn(n)){return ln(new FormData,qn(r))}else{return an(r)}}}function xn(e){return{tasks:[],elts:[e]}}function yn(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=ue(ae(n,t.scrollTarget))}if(t.scroll==="top"&&(n||o)){o=o||n;o.scrollTop=0}if(t.scroll==="bottom"&&(r||o)){o=o||r;o.scrollTop=o.scrollHeight}}if(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=ue(ae(n,e))}if(t.show==="top"&&(n||o)){o=o||n;o.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(r||o)){o=o||r;o.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function bn(r,e,o,i){if(i==null){i={}}if(r==null){return i}const s=te(r,e);if(s){let e=s.trim();let t=o;if(e==="unset"){return null}if(e.indexOf("javascript:")===0){e=e.slice(11);t=true}else if(e.indexOf("js:")===0){e=e.slice(3);t=true}if(e.indexOf("{")!==0){e="{"+e+"}"}let n;if(t){n=vn(r,function(){return Function("return ("+e+")")()},{})}else{n=S(e)}for(const l in n){if(n.hasOwnProperty(l)){if(i[l]==null){i[l]=n[l]}}}}return bn(ue(c(r)),e,o,i)}function vn(e,t,n){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return n}}function wn(e,t){return bn(e,"hx-vars",true,t)}function Sn(e,t){return bn(e,"hx-vals",false,t)}function En(e){return ce(wn(e),Sn(e))}function Cn(t,n,r){if(r!==null){try{t.setRequestHeader(n,r)}catch(e){t.setRequestHeader(n,encodeURIComponent(r));t.setRequestHeader(n+"-URI-AutoEncoded","true")}}}function On(t){if(t.responseURL&&typeof URL!=="undefined"){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(ne().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function R(e,t){return t.test(e.getAllResponseHeaders())}function Rn(t,n,r){t=t.toLowerCase();if(r){if(r instanceof Element||typeof r==="string"){return de(t,n,null,null,{targetOverride:y(r)||ve,returnPromise:true})}else{let e=y(r.target);if(r.target&&!e||r.source&&!e&&!y(r.source)){e=ve}return de(t,n,y(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:e,swapOverride:r.swap,select:r.select,returnPromise:true})}}else{return de(t,n,null,null,{returnPromise:true})}}function Hn(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function Tn(e,t,n){let r;let o;if(typeof URL==="function"){o=new URL(t,document.location.href);const i=document.location.origin;r=i===o.origin}else{o=t;r=l(t,document.location.origin)}if(Q.config.selfRequestsOnly){if(!r){return false}}return he(e,"htmx:validateUrl",ce({url:o,sameHost:r},n))}function qn(e){if(e instanceof FormData)return e;const t=new FormData;for(const n in e){if(e.hasOwnProperty(n)){if(e[n]&&typeof e[n].forEach==="function"){e[n].forEach(function(e){t.append(n,e)})}else if(typeof e[n]==="object"&&!(e[n]instanceof Blob)){t.append(n,JSON.stringify(e[n]))}else{t.append(n,e[n])}}}return t}function Ln(r,o,e){return new Proxy(e,{get:function(t,e){if(typeof e==="number")return t[e];if(e==="length")return t.length;if(e==="push"){return function(e){t.push(e);r.append(o,e)}}if(typeof t[e]==="function"){return function(){t[e].apply(t,arguments);r.delete(o);t.forEach(function(e){r.append(o,e)})}}if(t[e]&&t[e].length===1){return t[e][0]}else{return t[e]}},set:function(e,t,n){e[t]=n;r.delete(o);e.forEach(function(e){r.append(o,e)});return true}})}function An(o){return new Proxy(o,{get:function(e,t){if(typeof t==="symbol"){const r=Reflect.get(e,t);if(typeof r==="function"){return function(){return r.apply(o,arguments)}}else{return r}}if(t==="toJSON"){return()=>Object.fromEntries(o)}if(t in e){if(typeof e[t]==="function"){return function(){return o[t].apply(o,arguments)}}else{return e[t]}}const n=o.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Ln(e,t,n)}},set:function(t,n,e){if(typeof n!=="string"){return false}t.delete(n);if(e&&typeof e.forEach==="function"){e.forEach(function(e){t.append(n,e)})}else if(typeof e==="object"&&!(e instanceof Blob)){t.append(n,JSON.stringify(e))}else{t.append(n,e)}return true},deleteProperty:function(e,t){if(typeof t==="string"){e.delete(t)}return true},ownKeys:function(e){return Reflect.ownKeys(Object.fromEntries(e))},getOwnPropertyDescriptor:function(e,t){return Reflect.getOwnPropertyDescriptor(Object.fromEntries(e),t)}})}function de(t,n,r,o,i,D){let s=null;let l=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var e=new Promise(function(e,t){s=e;l=t})}if(r==null){r=ne().body}const M=i.handler||Dn;const X=i.select||null;if(!le(r)){oe(s);return e}const c=i.targetOverride||ue(Ee(r));if(c==null||c==ve){fe(r,"htmx:targetError",{target:te(r,"hx-target")});oe(l);return e}let u=ie(r);const a=u.lastButtonClicked;if(a){const L=ee(a,"formaction");if(L!=null){n=L}const A=ee(a,"formmethod");if(A!=null){if(A.toLowerCase()!=="dialog"){t=A}}}const f=re(r,"hx-confirm");if(D===undefined){const K=function(e){return de(t,n,r,o,i,!!e)};const G={target:c,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:f};if(he(r,"htmx:confirm",G)===false){oe(s);return e}}let h=r;let d=re(r,"hx-sync");let g=null;let F=false;if(d){const N=d.split(":");const I=N[0].trim();if(I==="this"){h=Se(r,"hx-sync")}else{h=ue(ae(r,I))}d=(N[1]||"drop").trim();u=ie(h);if(d==="drop"&&u.xhr&&u.abortable!==true){oe(s);return e}else if(d==="abort"){if(u.xhr){oe(s);return e}else{F=true}}else if(d==="replace"){he(h,"htmx:abort")}else if(d.indexOf("queue")===0){const W=d.split(" ");g=(W[1]||"last").trim()}}if(u.xhr){if(u.abortable){he(h,"htmx:abort")}else{if(g==null){if(o){const P=ie(o);if(P&&P.triggerSpec&&P.triggerSpec.queue){g=P.triggerSpec.queue}}if(g==null){g="last"}}if(u.queuedRequests==null){u.queuedRequests=[]}if(g==="first"&&u.queuedRequests.length===0){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="all"){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="last"){u.queuedRequests=[];u.queuedRequests.push(function(){de(t,n,r,o,i)})}oe(s);return e}}const p=new XMLHttpRequest;u.xhr=p;u.abortable=F;const m=function(){u.xhr=null;u.abortable=false;if(u.queuedRequests!=null&&u.queuedRequests.length>0){const e=u.queuedRequests.shift();e()}};const B=re(r,"hx-prompt");if(B){var x=prompt(B);if(x===null||!he(r,"htmx:prompt",{prompt:x,target:c})){oe(s);m();return e}}if(f&&!D){if(!confirm(f)){oe(s);m();return e}}let y=fn(r,c,x);if(t!=="get"&&!pn(r)){y["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){y=ce(y,i.headers)}const U=cn(r,t);let b=U.errors;const j=U.formData;if(i.values){ln(j,qn(i.values))}const V=qn(En(r));const v=ln(j,V);let w=hn(v,r);if(Q.config.getCacheBusterParam&&t==="get"){w.set("org.htmx.cache-buster",ee(c,"id")||"true")}if(n==null||n===""){n=ne().location.href}const S=bn(r,"hx-request");const _=ie(r).boosted;let E=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:_,useUrlParams:E,formData:w,parameters:An(w),unfilteredFormData:v,unfilteredParameters:An(v),headers:y,target:c,verb:t,errors:b,withCredentials:i.credentials||S.credentials||Q.config.withCredentials,timeout:i.timeout||S.timeout||Q.config.timeout,path:n,triggeringEvent:o};if(!he(r,"htmx:configRequest",C)){oe(s);m();return e}n=C.path;t=C.verb;y=C.headers;w=qn(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){he(r,"htmx:validation:halted",C);oe(s);m();return e}const z=n.split("#");const $=z[0];const O=z[1];let R=n;if(E){R=$;const Z=!w.keys().next().done;if(Z){if(R.indexOf("?")<0){R+="?"}else{R+="&"}R+=an(w);if(O){R+="#"+O}}}if(!Tn(r,R,C)){fe(r,"htmx:invalidPath",C);oe(l);return e}p.open(t.toUpperCase(),R,true);p.overrideMimeType("text/html");p.withCredentials=C.withCredentials;p.timeout=C.timeout;if(S.noHeaders){}else{for(const k in y){if(y.hasOwnProperty(k)){const Y=y[k];Cn(p,k,Y)}}}const H={xhr:p,target:c,requestConfig:C,etc:i,boosted:_,select:X,pathInfo:{requestPath:n,finalRequestPath:R,responsePath:null,anchor:O}};p.onload=function(){try{const t=Hn(r);H.pathInfo.responsePath=On(p);M(r,H);if(H.keepIndicators!==true){Qt(T,q)}he(r,"htmx:afterRequest",H);he(r,"htmx:afterOnLoad",H);if(!le(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(le(n)){e=n}}if(e){he(e,"htmx:afterRequest",H);he(e,"htmx:afterOnLoad",H)}}oe(s);m()}catch(e){fe(r,"htmx:onLoadError",ce({error:e},H));throw e}};p.onerror=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendError",H);oe(l);m()};p.onabort=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendAbort",H);oe(l);m()};p.ontimeout=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:timeout",H);oe(l);m()};if(!he(r,"htmx:beforeRequest",H)){oe(s);m();return e}var T=Zt(r);var q=Yt(r);se(["loadstart","loadend","progress","abort"],function(t){se([p,p.upload],function(e){e.addEventListener(t,function(e){he(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});he(r,"htmx:beforeSend",H);const J=E?null:mn(p,r,w);p.send(J);return e}function Nn(e,t){const n=t.xhr;let r=null;let o=null;if(R(n,/HX-Push:/i)){r=n.getResponseHeader("HX-Push");o="push"}else if(R(n,/HX-Push-Url:/i)){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(R(n,/HX-Replace-Url:/i)){r=n.getResponseHeader("HX-Replace-Url");o="replace"}if(r){if(r==="false"){return{}}else{return{type:o,path:r}}}const i=t.pathInfo.finalRequestPath;const s=t.pathInfo.responsePath;const l=re(e,"hx-push-url");const c=re(e,"hx-replace-url");const u=ie(e).boosted;let a=null;let f=null;if(l){a="push";f=l}else if(c){a="replace";f=c}else if(u){a="push";f=s||i}if(f){if(f==="false"){return{}}if(f==="true"){f=s||i}if(t.pathInfo.anchor&&f.indexOf("#")===-1){f=f+"#"+t.pathInfo.anchor}return{type:a,path:f}}else{return{}}}function In(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function Pn(e){for(var t=0;t<Q.config.responseHandling.length;t++){var n=Q.config.responseHandling[t];if(In(n,e.status)){return n}}return{swap:false}}function kn(e){if(e){const t=u("title");if(t){t.innerHTML=e}else{window.document.title=e}}}function Dn(o,i){const s=i.xhr;let l=i.target;const e=i.etc;const c=i.select;if(!he(o,"htmx:beforeOnLoad",i))return;if(R(s,/HX-Trigger:/i)){Je(s,"HX-Trigger",o)}if(R(s,/HX-Location:/i)){zt();let e=s.getResponseHeader("HX-Location");var t;if(e.indexOf("{")===0){t=S(e);e=t.path;delete t.path}Rn("get",e,t).then(function(){$t(e)});return}const n=R(s,/HX-Refresh:/i)&&s.getResponseHeader("HX-Refresh")==="true";if(R(s,/HX-Redirect:/i)){i.keepIndicators=true;location.href=s.getResponseHeader("HX-Redirect");n&&location.reload();return}if(n){i.keepIndicators=true;location.reload();return}if(R(s,/HX-Retarget:/i)){if(s.getResponseHeader("HX-Retarget")==="this"){i.target=o}else{i.target=ue(ae(o,s.getResponseHeader("HX-Retarget")))}}const u=Nn(o,i);const r=Pn(s);const a=r.swap;let f=!!r.error;let h=Q.config.ignoreTitle||r.ignoreTitle;let d=r.select;if(r.target){i.target=ue(ae(o,r.target))}var g=e.swapOverride;if(g==null&&r.swapOverride){g=r.swapOverride}if(R(s,/HX-Retarget:/i)){if(s.getResponseHeader("HX-Retarget")==="this"){i.target=o}else{i.target=ue(ae(o,s.getResponseHeader("HX-Retarget")))}}if(R(s,/HX-Reswap:/i)){g=s.getResponseHeader("HX-Reswap")}var p=s.response;var m=ce({shouldSwap:a,serverResponse:p,isError:f,ignoreTitle:h,selectOverride:d,swapOverride:g},i);if(r.event&&!he(l,r.event,m))return;if(!he(l,"htmx:beforeSwap",m))return;l=m.target;p=m.serverResponse;f=m.isError;h=m.ignoreTitle;d=m.selectOverride;g=m.swapOverride;i.target=l;i.failed=f;i.successful=!f;if(m.shouldSwap){if(s.status===286){lt(o)}Ft(o,function(e){p=e.transformResponse(p,s,o)});if(u.type){zt()}var x=gn(o,g);if(!x.hasOwnProperty("ignoreTitle")){x.ignoreTitle=h}l.classList.add(Q.config.swappingClass);let n=null;let r=null;if(c){d=c}if(R(s,/HX-Reselect:/i)){d=s.getResponseHeader("HX-Reselect")}const y=re(o,"hx-select-oob");const b=re(o,"hx-select");let e=function(){try{if(u.type){he(ne().body,"htmx:beforeHistoryUpdate",ce({history:u},i));if(u.type==="push"){$t(u.path);he(ne().body,"htmx:pushedIntoHistory",{path:u.path})}else{Jt(u.path);he(ne().body,"htmx:replacedInHistory",{path:u.path})}}$e(l,p,x,{select:d||b,selectOOB:y,eventInfo:i,anchor:i.pathInfo.anchor,contextElement:o,afterSwapCallback:function(){if(R(s,/HX-Trigger-After-Swap:/i)){let e=o;if(!le(o)){e=ne().body}Je(s,"HX-Trigger-After-Swap",e)}},afterSettleCallback:function(){if(R(s,/HX-Trigger-After-Settle:/i)){let e=o;if(!le(o)){e=ne().body}Je(s,"HX-Trigger-After-Settle",e)}oe(n)}})}catch(e){fe(o,"htmx:swapError",i);oe(r);throw e}};let t=Q.config.globalViewTransitions;if(x.hasOwnProperty("transition")){t=x.transition}if(t&&he(o,"htmx:beforeTransition",i)&&typeof Promise!=="undefined"&&document.startViewTransition){const v=new Promise(function(e,t){n=e;r=t});const w=e;e=function(){document.startViewTransition(function(){w();return v})}}if(x.swapDelay>0){E().setTimeout(e,x.swapDelay)}else{e()}}if(f){fe(o,"htmx:responseError",ce({error:"Response Status Error Code "+s.status+" from "+i.pathInfo.requestPath},i))}}const Mn={};function Xn(){return{init:function(e){return null},getSelectors:function(){return null},onEvent:function(e,t){return true},transformResponse:function(e,t,n){return e},isInlineSwap:function(e){return false},handleSwap:function(e,t,n,r){return false},encodeParameters:function(e,t,n){return null}}}function Fn(e,t){if(t.init){t.init(n)}Mn[e]=ce(Xn(),t)}function Bn(e){delete Mn[e]}function Un(e,n,r){if(n==undefined){n=[]}if(e==undefined){return n}if(r==undefined){r=[]}const t=te(e,"hx-ext");if(t){se(t.split(","),function(e){e=e.replace(/ /g,"");if(e.slice(0,7)=="ignore:"){r.push(e.slice(7));return}if(r.indexOf(e)<0){const t=Mn[e];if(t&&n.indexOf(t)<0){n.push(t)}}})}return Un(ue(c(e)),n,r)}var jn=false;ne().addEventListener("DOMContentLoaded",function(){jn=true});function Vn(e){if(jn||ne().readyState==="complete"){e()}else{ne().addEventListener("DOMContentLoaded",e)}}function _n(){if(Q.config.includeIndicatorStyles!==false){const e=Q.config.inlineStyleNonce?` nonce="${Q.config.inlineStyleNonce}"`:"";ne().head.insertAdjacentHTML("beforeend","<style"+e+"> ."+Q.config.indicatorClass+"{opacity:0} ."+Q.config.requestClass+" ."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ."+Q.config.requestClass+"."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} </style>")}}function zn(){const e=ne().querySelector('meta[name="htmx-config"]');if(e){return S(e.content)}else{return null}}function $n(){const e=zn();if(e){Q.config=ce(Q.config,e)}}Vn(function(){$n();_n();let e=ne().body;kt(e);const t=ne().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.target;const n=ie(t);if(n&&n.xhr){n.xhr.abort()}});const n=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){Wt();se(t,function(e){he(e,"htmx:restored",{document:ne(),triggerEvent:he})})}else{if(n){n(e)}}};E().setTimeout(function(){he(e,"htmx:load",{});e=null},0)});return Q}(); \ No newline at end of file
diff --git a/vrsite/assets/one.json b/vrsite/assets/one.json
new file mode 100644
index 0000000..69ff0de
--- /dev/null
+++ b/vrsite/assets/one.json
@@ -0,0 +1,112 @@
+{
+ "name": "One",
+ "author": "Zed Industries (vendored subset for vrsite fallback)",
+ "themes": [
+ {
+ "name": "One Dark",
+ "appearance": "dark",
+ "style": {
+ "editor.background": "#282c33ff",
+ "editor.foreground": "#acb2beff",
+ "background": "#3b414dff",
+ "panel.background": "#2f343eff",
+ "surface.background": "#2f343eff",
+ "border": "#464b57ff",
+ "editor.line_number": "#4e5a5f",
+ "text": "#dce0e5ff",
+ "text.muted": "#a9afbcff",
+ "text.accent": "#74ade8ff",
+ "warning": "#dec184ff",
+ "element.hover": "#363c46ff",
+ "players": [
+ {"cursor": "#74ade8ff"}, {"cursor": "#be5046ff"}, {"cursor": "#bf956aff"},
+ {"cursor": "#b477cfff"}, {"cursor": "#6eb4bfff"}, {"cursor": "#d07277ff"},
+ {"cursor": "#dec184ff"}, {"cursor": "#a1c181ff"}
+ ],
+ "syntax": {
+ "attribute": {"color": "#74ade8ff"},
+ "boolean": {"color": "#bf956aff"},
+ "comment": {"color": "#5d636fff"},
+ "comment.doc": {"color": "#878e98ff"},
+ "constant": {"color": "#dfc184ff"},
+ "constructor": {"color": "#73ade9ff"},
+ "embedded": {"color": "#dce0e5ff"},
+ "enum": {"color": "#6eb4bfff"},
+ "function": {"color": "#73ade9ff"},
+ "keyword": {"color": "#b477cfff"},
+ "label": {"color": "#74ade8ff"},
+ "number": {"color": "#bf956aff"},
+ "operator": {"color": "#6eb4bfff"},
+ "preproc": {"color": "#b477cfff"},
+ "primary": {"color": "#acb2beff"},
+ "property": {"color": "#d07277ff"},
+ "punctuation": {"color": "#acb2beff"},
+ "punctuation.bracket": {"color": "#b2b9c6ff"},
+ "punctuation.delimiter": {"color": "#b2b9c6ff"},
+ "punctuation.special": {"color": "#b1574bff"},
+ "string": {"color": "#a1c181ff"},
+ "string.escape": {"color": "#878e98ff"},
+ "string.regex": {"color": "#bf956aff"},
+ "string.special": {"color": "#bf956aff"},
+ "type": {"color": "#6eb4bfff"},
+ "variable": {"color": "#acb2beff"},
+ "variable.parameter": {"color": "#d07277ff"},
+ "variable.special": {"color": "#bf956aff"}
+ }
+ }
+ },
+ {
+ "name": "One Light",
+ "appearance": "light",
+ "style": {
+ "editor.background": "#fafafaff",
+ "editor.foreground": "#242529ff",
+ "background": "#dcdcddff",
+ "panel.background": "#ebebecff",
+ "surface.background": "#ebebecff",
+ "border": "#c9c9caff",
+ "editor.line_number": "#b4b4bb",
+ "text": "#242529ff",
+ "text.muted": "#58585aff",
+ "text.accent": "#5c78e2ff",
+ "warning": "#a48819ff",
+ "element.hover": "#dfdfe0ff",
+ "players": [
+ {"cursor": "#5c78e2ff"}, {"cursor": "#984ea5ff"}, {"cursor": "#ad6e26ff"},
+ {"cursor": "#a349abff"}, {"cursor": "#3a82b7ff"}, {"cursor": "#d36151ff"},
+ {"cursor": "#a48819ff"}, {"cursor": "#669f59ff"}
+ ],
+ "syntax": {
+ "attribute": {"color": "#5c78e2ff"},
+ "boolean": {"color": "#ad6e25ff"},
+ "comment": {"color": "#a2a3a7ff"},
+ "comment.doc": {"color": "#7c7e86ff"},
+ "constant": {"color": "#c18401ff"},
+ "constructor": {"color": "#5c78e2ff"},
+ "embedded": {"color": "#242529ff"},
+ "enum": {"color": "#3882b7ff"},
+ "function": {"color": "#5b79e3ff"},
+ "keyword": {"color": "#a449abff"},
+ "label": {"color": "#5c78e2ff"},
+ "number": {"color": "#ad6e25ff"},
+ "operator": {"color": "#3882b7ff"},
+ "preproc": {"color": "#a449abff"},
+ "primary": {"color": "#242529ff"},
+ "property": {"color": "#d3604fff"},
+ "punctuation": {"color": "#242529ff"},
+ "punctuation.bracket": {"color": "#4d4f52ff"},
+ "punctuation.delimiter": {"color": "#4d4f52ff"},
+ "punctuation.special": {"color": "#b92b46ff"},
+ "string": {"color": "#649f57ff"},
+ "string.escape": {"color": "#7c7e86ff"},
+ "string.regex": {"color": "#ad6e26ff"},
+ "string.special": {"color": "#ad6e26ff"},
+ "type": {"color": "#3882b7ff"},
+ "variable": {"color": "#242529ff"},
+ "variable.parameter": {"color": "#d3604fff"},
+ "variable.special": {"color": "#ad6e25ff"}
+ }
+ }
+ }
+ ]
+}
diff --git a/vrsite/assets/rust.scm b/vrsite/assets/rust.scm
new file mode 100644
index 0000000..d23fa2c
--- /dev/null
+++ b/vrsite/assets/rust.scm
@@ -0,0 +1,48 @@
+; Minimal rust highlights. Capture names double as zed syntax theme keys.
+; Order matters: later patterns paint over earlier ones.
+
+["(" ")" "[" "]" "{" "}"] @punctuation.bracket
+[";" "," "." ":" "::"] @punctuation.delimiter
+["=" "==" "!=" "<" ">" "<=" ">=" "+" "-" "*" "/" "%" "&" "|" "^" "!" "&&" "||"
+ "->" "=>" ".." "..=" "+=" "-=" "*=" "/=" "?" "@" "<<" ">>"] @operator
+
+["as" "async" "await" "break" "const" "continue" "dyn" "else" "enum"
+ "extern" "fn" "for" "if" "impl" "in" "let" "loop" "match" "mod" "move"
+ "pub" "ref" "return" "static" "struct" "trait" "type" "union"
+ "unsafe" "use" "where" "while"] @keyword
+(crate) @keyword
+(super) @keyword
+(mutable_specifier) @keyword
+
+(type_identifier) @type
+(primitive_type) @type
+(field_identifier) @property
+(shorthand_field_initializer (identifier) @property)
+(enum_variant name: (identifier) @constructor)
+(const_item name: (identifier) @constant)
+(static_item name: (identifier) @constant)
+(boolean_literal) @constant
+
+(function_item name: (identifier) @function)
+(function_signature_item name: (identifier) @function)
+(call_expression function: (identifier) @function)
+(call_expression function: (scoped_identifier name: (identifier) @function))
+(call_expression function: (field_expression field: (field_identifier) @function))
+(generic_function function: (identifier) @function)
+(generic_function function: (scoped_identifier name: (identifier) @function))
+(macro_invocation macro: (identifier) @function)
+(macro_invocation macro: (scoped_identifier name: (identifier) @function))
+
+(integer_literal) @number
+(float_literal) @number
+(char_literal) @string
+(string_literal) @string
+(raw_string_literal) @string
+(escape_sequence) @string.escape
+(lifetime) @label
+(self) @variable.special
+
+(attribute_item) @attribute
+(inner_attribute_item) @attribute
+(line_comment) @comment
+(block_comment) @comment
diff --git a/vrsite/assets/style.css.tmpl b/vrsite/assets/style.css.tmpl
new file mode 100644
index 0000000..a808203
--- /dev/null
+++ b/vrsite/assets/style.css.tmpl
@@ -0,0 +1,321 @@
+/* generated from zed themes "{{.DarkName}}" (dark) + "{{.LightName}}" (light) */
+:root {
+{{range .DarkVars}} {{.K}}: {{.V}};
+{{end}} color-scheme: dark;
+ --note-bg: color-mix(in srgb, var(--note) 4%, transparent);
+}
+@media (prefers-color-scheme: light) {
+ :root:not([data-theme="dark"]) {
+{{range .LightVars}} {{.K}}: {{.V}};
+{{end}} color-scheme: light;
+ }
+}
+:root[data-theme="light"] {
+{{range .LightVars}} {{.K}}: {{.V}};
+{{end}} color-scheme: light;
+}
+
+* { box-sizing: border-box; }
+body {
+ margin: 0;
+ display: grid;
+ grid-template-columns: 280px minmax(0, 1fr);
+ background: var(--bg);
+ color: var(--fg);
+ font: 15px/1.5 ui-sans-serif, system-ui, sans-serif;
+}
+:root[data-mode="notes"] body.with-aside,
+body.with-aside { grid-template-columns: 280px minmax(0, 1fr) 380px; }
+:root[data-mode="trace"] body.with-aside { grid-template-columns: 280px minmax(0, 1fr); }
+
+/* ── focus: trace or notes ─────────────────────────────────────
+ The two views compete for the same pixels — line background, gutter
+ color, tree markers — so the interface shows one at a time. */
+:root[data-mode="trace"] .notes-only { display: none !important; }
+:root[data-mode="notes"] .trace-only { display: none !important; }
+:root[data-mode="notes"] ol.code li.cov { box-shadow: none; }
+:root[data-mode="notes"] ol.code li.cov::before { color: var(--ln); font-weight: 400; }
+:root[data-mode="notes"] nav a.file::after,
+:root[data-mode="notes"] .filetree a.file::after { display: none; }
+:root[data-mode="trace"] ol.code li.noted { background: none; cursor: default; }
+:root[data-mode="trace"] ol.code li.noted::before { color: var(--ln); }
+:root[data-mode="trace"] nav a.file.has-notes::before,
+:root[data-mode="trace"] .filetree a.file.has-notes::before { content: none; }
+:root[data-mode="notes"] nav a.file { color: var(--muted); }
+:root[data-mode="notes"] nav a.file.has-notes { color: var(--fg); }
+
+.modes { display: flex; gap: 0; border: 1px solid var(--border); border-radius: 5px; overflow: hidden; }
+.modes .mode {
+ background: none; border: 0; color: var(--muted);
+ font: inherit; font-size: 11px; padding: 2px 8px; cursor: pointer;
+}
+.modes .mode:hover { background: var(--hover); color: var(--fg); }
+.modes .mode[aria-pressed="true"] { background: var(--hover); color: var(--fg); font-weight: 600; }
+
+a { color: var(--accent); text-decoration: none; }
+a:hover { text-decoration: underline; }
+code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.92em; }
+h1 { font-size: 1.1rem; margin: 0; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
+h2 { font-size: 0.95rem; margin: 1.4em 0 0.5em; }
+
+/* ── left tree ─────────────────────────────────────────────── */
+nav {
+ border-right: 1px solid var(--border);
+ background: var(--panel);
+ padding: 10px 8px;
+ position: sticky; top: 0;
+ height: 100vh; overflow: auto;
+ font-size: 13px;
+}
+nav > header {
+ font-weight: 600; margin-bottom: 10px;
+ display: flex; align-items: center; justify-content: space-between; gap: 8px;
+}
+nav > header a { color: var(--fg); }
+nav .brand { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+nav .atrev { margin: 0 0 8px; }
+.find, .filters input, .filters select, .notform input, .notform textarea, .jjform input {
+ background: var(--bg); color: var(--fg);
+ border: 1px solid var(--border); border-radius: 5px;
+ font: inherit; font-size: 12px; padding: 3px 6px;
+}
+.find { width: 100%; margin-bottom: 6px; }
+.find:focus, .filters input:focus, .notform textarea:focus, .jjform input:focus {
+ outline: 1px solid var(--accent); border-color: var(--accent);
+}
+#tree.filtering a.file.hit { background: color-mix(in srgb, var(--accent) 14%, transparent); }
+nav details { padding-left: 10px; }
+nav summary { cursor: pointer; color: var(--muted); user-select: none; }
+nav summary:hover { color: var(--fg); }
+nav ul { list-style: none; margin: 0; padding-left: 10px; }
+nav a.file {
+ display: block; position: relative;
+ padding: 1px 6px 3px; border-radius: 4px;
+ color: var(--fg);
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px;
+}
+nav a.file:hover { background: var(--hover); text-decoration: none; }
+nav a.file[aria-current] { background: var(--hover); }
+nav a.file::after {
+ content: ""; position: absolute; left: 6px; bottom: 1px; height: 2px;
+ width: calc(var(--pct) - 12px); max-width: calc(100% - 12px);
+ background: var(--cov); border-radius: 1px;
+}
+nav a.file.has-notes::before { content: "◆ "; color: var(--note); font-size: 9px; vertical-align: 2px; }
+nav a.file.plain { color: var(--muted); }
+nav a.file.plain::after { display: none; }
+#tree { margin-top: 8px; }
+#tree > details { padding-left: 0; }
+summary .dot {
+ display: inline-block; width: 7px; height: 7px; border-radius: 99px;
+ background: var(--cov); margin-left: 6px;
+}
+summary .nmark { color: var(--note); font-size: 9px; margin-left: 4px; vertical-align: 1px; }
+nav details.t > summary, .filetree details.t > summary { color: var(--fg); }
+nav > footer {
+ margin-top: 14px; border-top: 1px solid var(--border); padding-top: 8px;
+ display: flex; justify-content: space-between; align-items: center; gap: 8px;
+}
+nav > footer select {
+ background: var(--panel); color: var(--muted);
+ border: 1px solid var(--border); border-radius: 4px;
+ font: inherit; font-size: 11px; padding: 1px 2px;
+}
+
+/* files.html full tree */
+.filetree { font: 13px/1.6 ui-monospace, SFMono-Regular, Menlo, monospace; padding-bottom: 40vh; }
+.filetree details { padding-left: 18px; }
+.filetree summary { cursor: pointer; color: var(--muted); }
+.filetree summary:hover { color: var(--fg); }
+.filetree ul { list-style: none; margin: 0; padding-left: 18px; }
+.filetree a.file { display: inline-block; position: relative; padding: 0 6px 2px; border-radius: 4px; color: var(--fg); }
+.filetree a.file.plain { color: var(--muted); }
+.filetree a.file:not(.plain)::after {
+ content: ""; position: absolute; left: 6px; bottom: 0; height: 2px;
+ width: calc(var(--pct) - 12px); max-width: calc(100% - 12px);
+ background: var(--cov); border-radius: 1px;
+}
+.filetree a.file.has-notes::before { content: "◆ "; color: var(--note); font-size: 9px; vertical-align: 2px; }
+.stub { padding: 24px 16px; }
+
+/* ── main ──────────────────────────────────────────────────── */
+main { min-width: 0; }
+.filehead {
+ position: sticky; top: 0; z-index: 2;
+ background: color-mix(in srgb, var(--bg) 88%, transparent);
+ backdrop-filter: blur(6px);
+ border-bottom: 1px solid var(--border);
+ padding: 10px 16px;
+}
+.meta { margin: 4px 0 0; color: var(--muted); font-size: 12.5px; }
+.meta code { color: var(--fg); }
+.greps code { margin-right: 8px; }
+.chip {
+ display: inline-block; padding: 0 8px; border-radius: 99px;
+ background: color-mix(in srgb, var(--cov) 22%, transparent);
+ border: 1px solid var(--cov); color: var(--fg); font-size: 12px;
+}
+main > section, .notegroup { padding: 0 16px; max-width: 1100px; }
+table { border-collapse: collapse; width: 100%; font-size: 13.5px; }
+th { text-align: left; color: var(--muted); font-weight: 500; }
+th, td { padding: 4px 12px 4px 0; border-bottom: 1px solid var(--border); }
+data.bar {
+ display: inline-block; min-width: 140px; padding-left: 4px;
+ font-size: 12px; color: var(--muted);
+ background: linear-gradient(90deg, color-mix(in srgb, var(--cov) 35%, transparent) var(--pct), transparent var(--pct));
+ border-radius: 3px;
+}
+
+/* ── code view ─────────────────────────────────────────────── */
+.codewrap { overflow-x: auto; }
+ol.code {
+ list-style: none; margin: 0; padding: 0;
+ font: 12.5px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace;
+ counter-reset: ln;
+ tab-size: 4;
+ content-visibility: auto;
+ contain-intrinsic-size: auto var(--h, auto);
+}
+ol.code:first-of-type { padding-top: 8px; }
+ol.code:last-of-type { padding-bottom: 40vh; }
+ol.code li {
+ counter-increment: ln;
+ white-space: pre;
+ min-height: 1lh;
+ padding-right: 16px;
+}
+ol.code li::before {
+ content: counter(ln);
+ display: inline-block; width: 5ch; margin-right: 1.5ch;
+ text-align: right; color: var(--ln);
+ user-select: none;
+}
+ol.code li.cov { box-shadow: inset 3px 0 var(--cov); }
+ol.code li.cov::before { color: var(--cov); font-weight: 700; }
+ol.code li.noted { background: var(--note-bg); cursor: pointer; }
+ol.code li.noted::before { color: color-mix(in srgb, var(--note) 55%, var(--ln)); }
+ol.code li:target { background: color-mix(in srgb, var(--accent) 18%, transparent); }
+
+/* ── notes ─────────────────────────────────────────────────── */
+aside {
+ border-left: 1px solid var(--border);
+ background: var(--panel);
+ position: sticky; top: 0; height: 100vh; overflow: auto;
+ padding: 10px 12px; font-size: 13px;
+}
+aside summary { cursor: pointer; color: var(--muted); }
+.note {
+ border: 1px solid var(--border);
+ border-left: 3px solid var(--cov);
+ border-radius: 6px;
+ padding: 8px 10px; margin: 10px 0;
+ background: var(--bg);
+}
+.note header { display: flex; gap: 8px; align-items: baseline; font-size: 12px; }
+.note header a { font-family: ui-monospace, Menlo, monospace; }
+.note header em { color: var(--note); font-style: normal; border: 1px solid var(--note); border-radius: 3px; padding: 0 4px; font-size: 11px; }
+.note header b { margin-left: auto; color: var(--cov); font-weight: 600; }
+.note p { margin: 6px 0 0; line-height: 1.45; }
+.note.flash { animation: flash 1.2s ease-out; }
+@keyframes flash { 0% { background: color-mix(in srgb, var(--cov) 30%, var(--bg)); } 100% { background: var(--bg); } }
+
+.note footer { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 6px; font-size: 11px; }
+.note footer code { color: var(--muted); }
+.note .model { opacity: 0.85; }
+.notecols { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 0 14px; }
+
+/* ── live activity ─────────────────────────────────────────── */
+.activity { margin-bottom: 10px; }
+.actlist { display: flex; flex-direction: column; gap: 3px; }
+.act {
+ display: grid; grid-template-columns: auto minmax(0, 1fr) auto;
+ gap: 6px; align-items: baseline; font-size: 11px; color: var(--muted);
+ opacity: 0.55;
+}
+.act.on { opacity: 1; }
+.act .what, .acttable .what {
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ font-family: ui-monospace, Menlo, monospace;
+}
+.acttable tr.on td { color: var(--fg); }
+.acttable .pulse { color: var(--accent); font-size: 9px; margin-left: 5px; animation: pulse 2s ease-in-out infinite; }
+@keyframes pulse { 50% { opacity: 0.25; } }
+.acttable .dir { max-width: 18ch; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+
+/* ── filters / forms ───────────────────────────────────────── */
+.filters {
+ display: flex; flex-wrap: wrap; gap: 6px; align-items: center;
+ padding: 10px 0; position: sticky; top: 0; z-index: 1;
+ background: var(--bg);
+}
+.filters input[type="search"] { min-width: 15ch; flex: 1 1 18ch; }
+.filters .dates { display: flex; gap: 6px; align-items: center; }
+.filters .datef { font-size: 11px; color: var(--muted); display: flex; gap: 4px; align-items: center; }
+.filters button, .jjform button, .notform button {
+ background: var(--panel); color: var(--fg);
+ border: 1px solid var(--border); border-radius: 5px;
+ font: inherit; font-size: 12px; padding: 3px 10px; cursor: pointer;
+}
+.filters button:hover, .jjform button:hover, .notform button:hover { background: var(--hover); }
+.count { margin: 0 0 8px; }
+.busy { visibility: hidden; color: var(--accent); margin-right: 6px; }
+.busy.htmx-request { visibility: visible; animation: pulse 1s linear infinite; }
+.notespage, .jjpage { padding: 0 16px 40vh; max-width: 1100px; }
+.err {
+ margin: 12px 16px; padding: 8px 10px; border-radius: 6px;
+ border: 1px solid var(--note); color: var(--note);
+ font-family: ui-monospace, Menlo, monospace; font-size: 12.5px; white-space: pre-wrap;
+}
+
+/* ── add a note ────────────────────────────────────────────── */
+.addnote { margin: 10px 0; }
+.addnote > summary { cursor: pointer; color: var(--muted); font-size: 13px; }
+.notform { display: flex; flex-direction: column; gap: 6px; margin: 8px 0 14px; }
+.notform .row { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; }
+.notform .row.end { justify-content: space-between; }
+.notform input[type="number"] { width: 8ch; }
+.notform textarea { resize: vertical; font-family: inherit; }
+.notform .on code { color: var(--fg); }
+.asidehead { display: flex; justify-content: space-between; align-items: baseline; gap: 8px; }
+aside .meta { font-size: 11px; }
+
+/* selection while picking lines to comment on */
+ol.code li.sel { background: color-mix(in srgb, var(--accent) 16%, transparent); }
+ol.code li.sel::before { color: var(--accent); }
+
+/* ── jj ────────────────────────────────────────────────────── */
+.jjform { display: flex; gap: 6px; align-items: center; padding: 10px 0; }
+.jjform input[type="search"] { flex: 1; font-family: ui-monospace, Menlo, monospace; }
+.jjform input[type="number"] { width: 8ch; }
+.jjlog { font: 12.5px/1.7 ui-monospace, SFMono-Regular, Menlo, monospace; }
+.jjrow { display: flex; gap: 8px; align-items: baseline; white-space: pre; }
+.jjrow:hover { background: var(--hover); }
+.jjrow .graph { color: var(--muted); white-space: pre; }
+.jjrow .id { font-weight: 600; }
+.jjrow .commit { color: var(--muted); }
+.jjrow .when, .jjrow .who { color: var(--muted); }
+.jjrow .refs { color: var(--note); }
+.jjrow .flags { color: var(--note); font-style: italic; }
+.jjrow .desc { color: var(--fg); overflow: hidden; text-overflow: ellipsis; }
+.jjrow.blank { color: var(--muted); }
+pre.desc {
+ margin: 0 0 12px; padding: 10px 12px; border-radius: 6px;
+ border: 1px solid var(--border); background: var(--panel);
+ font: 12.5px/1.5 ui-monospace, Menlo, monospace; white-space: pre-wrap;
+}
+table.changed { width: auto; }
+table.changed td { border: none; padding: 1px 12px 1px 0; }
+table.changed .st { color: var(--muted); font-size: 11px; width: 7ch; }
+table.changed .st-added { color: var(--accent); }
+table.changed .st-deleted { color: var(--note); }
+
+/* ── agent coverage colors (bitmask -> per-scheme mixed color) */
+{{range .MaskList}}.am{{.}} { --cov: var(--am{{.}}); }
+{{end}}
+/* ── syntax (zed theme, colors are per-scheme vars) ────────── */
+{{range .Syntax}}.s-{{.Class}} { color: var(--s-{{.Class}}, inherit);{{if eq .Style "italic"}} font-style: italic;{{end}}{{if .Weight}} font-weight: {{.Weight}};{{end}} }
+{{end}}
+@media (max-width: 1100px) {
+ body, body.with-aside { grid-template-columns: 1fr; }
+ nav, aside { position: static; height: auto; border: none; border-bottom: 1px solid var(--border); }
+}
diff --git a/vrsite/bench-browser.mjs b/vrsite/bench-browser.mjs
new file mode 100644
index 0000000..97b3a86
--- /dev/null
+++ b/vrsite/bench-browser.mjs
@@ -0,0 +1,135 @@
+#!/usr/bin/env node
+// Browser render benchmark for vrsite pages: drives headless Chrome over CDP
+// (no npm deps; node >= 22 for native WebSocket). Serves the site dir, loads
+// each page N times, reports parse/paint/load timings, node count, and the
+// cost of jumping to the bottom of the file.
+//
+// node bench-browser.mjs SITE_DIR PAGE [PAGE...] [--shot DIR]
+
+import { spawn } from "node:child_process";
+import { createReadStream, existsSync, mkdirSync, writeFileSync } from "node:fs";
+import http from "node:http";
+import path from "node:path";
+import { tmpdir } from "node:os";
+
+const CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
+const RUNS = 3;
+
+const args = process.argv.slice(2);
+const shotIdx = args.indexOf("--shot");
+let shotDir = null;
+if (shotIdx >= 0) {
+ shotDir = args[shotIdx + 1];
+ args.splice(shotIdx, 2);
+ mkdirSync(shotDir, { recursive: true });
+}
+const [siteDir, ...pages] = args;
+if (!siteDir || pages.length === 0) {
+ console.error("usage: node bench-browser.mjs SITE_DIR PAGE [PAGE...] [--shot DIR]");
+ process.exit(2);
+}
+
+// ── tiny static server ────────────────────────────────────────────────────
+const types = { html: "text/html", css: "text/css", js: "text/javascript" };
+const server = http.createServer((req, res) => {
+ const file = path.join(siteDir, decodeURIComponent(new URL(req.url, "http://x").pathname));
+ if (!existsSync(file)) { res.writeHead(404).end(); return; }
+ res.writeHead(200, { "content-type": types[path.extname(file).slice(1)] ?? "text/plain" });
+ createReadStream(file).pipe(res);
+});
+await new Promise(r => server.listen(0, r));
+const port = server.address().port;
+
+// ── chrome + CDP ──────────────────────────────────────────────────────────
+const profile = path.join(tmpdir(), "vrsite-bench-profile");
+const chrome = spawn(CHROME, [
+ "--headless=new", "--remote-debugging-port=0", `--user-data-dir=${profile}`,
+ "--no-first-run", "--disable-extensions", "--window-size=1600,1000", "about:blank",
+], { stdio: ["ignore", "ignore", "pipe"] });
+const wsUrl = await new Promise((resolve, reject) => {
+ let buf = "";
+ chrome.stderr.on("data", d => {
+ buf += d;
+ const m = buf.match(/DevTools listening on (ws:\/\/\S+)/);
+ if (m) resolve(m[1]);
+ });
+ chrome.on("exit", () => reject(new Error("chrome exited")));
+});
+const debugPort = new URL(wsUrl).port;
+const targets = await (await fetch(`http://127.0.0.1:${debugPort}/json/list`)).json();
+const pageTarget = targets.find(t => t.type === "page");
+
+const ws = new WebSocket(pageTarget.webSocketDebuggerUrl);
+await new Promise(r => (ws.onopen = r));
+let msgId = 0;
+const pending = new Map();
+const eventWaiters = new Map();
+ws.onmessage = e => {
+ const msg = JSON.parse(e.data);
+ if (msg.id && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); }
+ if (msg.method && eventWaiters.has(msg.method)) {
+ eventWaiters.get(msg.method)(msg.params);
+ eventWaiters.delete(msg.method);
+ }
+};
+const cdp = (method, params = {}) => new Promise(resolve => {
+ const id = ++msgId;
+ pending.set(id, m => resolve(m.result));
+ ws.send(JSON.stringify({ id, method, params }));
+});
+const waitEvent = method => new Promise(r => eventWaiters.set(method, r));
+const evaluate = async expr => {
+ const r = await cdp("Runtime.evaluate", { expression: expr, returnByValue: true, awaitPromise: true });
+ return r.result?.value;
+};
+
+await cdp("Page.enable");
+await cdp("Runtime.enable");
+
+const median = a => [...a].sort((x, y) => x - y)[a.length >> 1];
+
+console.log("page kB nodes parse FCP DCL load toBottom");
+for (const p of pages) {
+ const url = `http://127.0.0.1:${port}/${p}`;
+ const runs = [];
+ for (let i = 0; i < RUNS; i++) {
+ const loaded = waitEvent("Page.loadEventFired");
+ await cdp("Page.navigate", { url });
+ await loaded;
+ const m = await evaluate(`(async () => {
+ await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)));
+ const nav = performance.getEntriesByType("navigation")[0];
+ const fcp = performance.getEntriesByType("paint").find(e => e.name === "first-contentful-paint");
+ const t0 = performance.now();
+ window.scrollTo(0, document.body.scrollHeight);
+ await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)));
+ const toBottom = performance.now() - t0;
+ return JSON.stringify({
+ kb: Math.round(nav.transferSize / 1024),
+ nodes: document.getElementsByTagName("*").length,
+ parse: Math.round(nav.domInteractive),
+ fcp: Math.round(fcp?.startTime ?? -1),
+ dcl: Math.round(nav.domContentLoadedEventEnd),
+ load: Math.round(nav.loadEventEnd),
+ toBottom: Math.round(toBottom),
+ });
+ })()`);
+ runs.push(JSON.parse(m));
+ }
+ const med = k => median(runs.map(r => r[k]));
+ console.log(
+ p.padEnd(38) + String(med("kb")).padStart(6) + String(med("nodes")).padStart(8) +
+ String(med("parse")).padStart(9) + String(med("fcp")).padStart(8) +
+ String(med("dcl")).padStart(8) + String(med("load")).padStart(8) +
+ String(med("toBottom")).padStart(10));
+ if (shotDir) {
+ await evaluate(`window.scrollTo(0, 0)`);
+ await evaluate(`new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))`);
+ const shot = await cdp("Page.captureScreenshot", { format: "png" });
+ writeFileSync(path.join(shotDir, p.replaceAll("/", "_") + ".png"), Buffer.from(shot.data, "base64"));
+ }
+}
+
+chrome.kill();
+server.close();
+process.exit(0);
diff --git a/vrsite/bench_test.go b/vrsite/bench_test.go
new file mode 100644
index 0000000..8950b8f
--- /dev/null
+++ b/vrsite/bench_test.go
@@ -0,0 +1,129 @@
+package main
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "testing"
+)
+
+// A realistic Rust chunk (~1.2KB): doc comments, generics, lifetimes, attrs,
+// strings with escapes, macros — the constructs the highlighter works hardest
+// on. Repetition parses fine; tree-sitter is not a compiler.
+var rustChunk = []byte(`//! Module documentation with some text.
+use std::{collections::HashMap, sync::Arc};
+
+/// A cached entry with generics and lifetimes.
+#[derive(Debug, Clone, PartialEq)]
+pub struct CacheEntry<'a, T: Clone + Send> {
+ pub key: &'a str,
+ pub value: Arc<T>,
+ hits: u64,
+ tags: HashMap<String, Vec<u8>>,
+}
+
+pub enum LookupResult<T> {
+ Hit(Arc<T>),
+ Miss { reason: &'static str, code: i32 },
+ Tombstone,
+}
+
+impl<'a, T: Clone + Send> CacheEntry<'a, T> {
+ pub fn new(key: &'a str, value: T) -> Self {
+ let tags = HashMap::new();
+ Self { key, value: Arc::new(value), hits: 0, tags }
+ }
+
+ /// Record a hit and return the running total.
+ pub fn touch(&mut self) -> u64 {
+ self.hits = self.hits.saturating_add(1);
+ if self.hits % 100 == 0 {
+ println!("entry {} hit {} times \"escaped\"", self.key, self.hits);
+ }
+ self.hits
+ }
+
+ pub fn lookup(&self, keys: &[&str]) -> LookupResult<T> {
+ match keys.iter().position(|k| *k == self.key) {
+ Some(_) => LookupResult::Hit(self.value.clone()),
+ None => LookupResult::Miss { reason: "absent <key>", code: -1 },
+ }
+ }
+}
+
+const MAX_ENTRIES: usize = 4096;
+static GREETING: &str = "hello \"quoted\" <world> & friends";
+`)
+
+func synthRust(size int) []byte {
+ var b bytes.Buffer
+ for b.Len() < size {
+ b.Write(rustChunk)
+ }
+ return b.Bytes()
+}
+
+var sizes = []int{128 << 10, 1 << 20, 4 << 20}
+
+func benchHL(b *testing.B) *highlighter {
+ b.Helper()
+ return newHighlighter(loadTheme("", "", "dark"), loadTheme("", "", "light"))
+}
+
+// tree-sitter parse + query + paint only
+func BenchmarkClassify(b *testing.B) {
+ hl := benchHL(b)
+ for _, size := range sizes {
+ src := synthRust(size)
+ b.Run(fmt.Sprintf("%dKB", size>>10), func(b *testing.B) {
+ b.SetBytes(int64(len(src)))
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ hl.classify("bench.rs", src)
+ }
+ })
+ }
+}
+
+// classify + full per-line HTML emit
+func BenchmarkRender(b *testing.B) {
+ hl := benchHL(b)
+ for _, size := range sizes {
+ src := synthRust(size)
+ b.Run(fmt.Sprintf("%dKB", size>>10), func(b *testing.B) {
+ b.SetBytes(int64(len(src)))
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ f := &File{Path: "bench.rs", NoteAt: map[int]int{}}
+ f.render(src, hl)
+ }
+ })
+ }
+}
+
+// template execution for an already-rendered file page
+func BenchmarkExecute(b *testing.B) {
+ hl := benchHL(b)
+ tpl := newTemplates()
+ site := &Site{
+ Title: "bench", Files: map[string]*File{},
+ Theme: loadTheme("", "", "dark"), Light: loadTheme("", "", "light"),
+ Agents: []*Agent{{Name: "bench", Short: "bench", Bit: 1}},
+ }
+ for _, size := range sizes {
+ src := synthRust(size)
+ f := &File{Path: "bench.rs", NoteAt: map[int]int{}, Traced: true, Change: "zzzzzzzz"}
+ f.cover(1, bytes.Count(src, []byte("\n"))/2, 1)
+ f.render(src, hl)
+ p := &page{Site: site, Kind: "file", Title: "bench", Root: "", Current: f.Path, File: f}
+ b.Run(fmt.Sprintf("%dKB", size>>10), func(b *testing.B) {
+ b.SetBytes(int64(len(src)))
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ if err := tpl.Execute(io.Discard, p); err != nil {
+ b.Fatal(err)
+ }
+ }
+ })
+ }
+}
diff --git a/vrsite/css.go b/vrsite/css.go
new file mode 100644
index 0000000..a2ca377
--- /dev/null
+++ b/vrsite/css.go
@@ -0,0 +1,68 @@
+// css.go — the stylesheet is generated per site: theme colors and the mixed
+// per-agent coverage colors become custom properties, one block per scheme.
+package main
+
+import (
+ "fmt"
+ "io"
+ "sort"
+ "strings"
+ texttemplate "text/template"
+)
+
+type cssVar struct{ K, V string }
+
+type synCSS struct{ Class, Style, Weight string }
+
+func renderCSS(w io.Writer, site *Site) error {
+ css, err := texttemplate.ParseFS(tfs, "assets/style.css.tmpl")
+ if err != nil {
+ return err
+ }
+ var unionKeys []string
+ seen := map[string]bool{}
+ for _, t := range []*Theme{site.Theme, site.Light} {
+ for k := range t.Syntax {
+ if !seen[k] {
+ seen[k] = true
+ unionKeys = append(unionKeys, k)
+ }
+ }
+ }
+ sort.Strings(unionKeys)
+ masks := site.masks()
+ themeVars := func(t *Theme) []cssVar {
+ vars := []cssVar{
+ {"--bg", t.Bg}, {"--fg", t.Fg}, {"--panel", t.Panel}, {"--border", t.Border},
+ {"--ln", t.LineNo}, {"--muted", t.Muted}, {"--accent", t.Accent},
+ {"--note", t.Note}, {"--hover", t.Hover},
+ }
+ for _, k := range unionKeys {
+ if s, ok := t.Syntax[k]; ok && s.Color != "" {
+ vars = append(vars, cssVar{"--s-" + strings.ReplaceAll(k, ".", "-"), s.Color})
+ }
+ }
+ for _, m := range masks {
+ vars = append(vars, cssVar{fmt.Sprintf("--am%d", m), site.maskColor(t, m)})
+ }
+ return vars
+ }
+ var syn []synCSS
+ for _, k := range unionKeys {
+ s := synCSS{Class: strings.ReplaceAll(k, ".", "-")}
+ if v, ok := site.Theme.Syntax[k]; ok {
+ if v.FontStyle != nil {
+ s.Style = *v.FontStyle
+ }
+ if v.FontWeight != nil {
+ s.Weight = fmt.Sprintf("%.0f", *v.FontWeight)
+ }
+ }
+ syn = append(syn, s)
+ }
+ return css.Execute(w, map[string]any{
+ "DarkName": site.Theme.Name, "LightName": site.Light.Name,
+ "DarkVars": themeVars(site.Theme), "LightVars": themeVars(site.Light),
+ "Syntax": syn, "MaskList": masks,
+ })
+}
diff --git a/vrsite/go.mod b/vrsite/go.mod
new file mode 100644
index 0000000..bf04dfe
--- /dev/null
+++ b/vrsite/go.mod
@@ -0,0 +1,10 @@
+module 0x4200.cafe/vrsite
+
+go 1.26.5
+
+require (
+ github.com/tree-sitter/go-tree-sitter v0.25.0
+ github.com/tree-sitter/tree-sitter-rust v0.24.2
+)
+
+require github.com/mattn/go-pointer v0.0.1 // indirect
diff --git a/vrsite/go.sum b/vrsite/go.sum
new file mode 100644
index 0000000..b2466d9
--- /dev/null
+++ b/vrsite/go.sum
@@ -0,0 +1,36 @@
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/mattn/go-pointer v0.0.1 h1:n+XhsuGeVO6MEAp7xyEukFINEa+Quek5psIR/ylA6o0=
+github.com/mattn/go-pointer v0.0.1/go.mod h1:2zXcozF6qYGgmsG+SeTZz3oAbFLdD3OWqnUbNvJZAlc=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
+github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
+github.com/tree-sitter/go-tree-sitter v0.25.0 h1:sx6kcg8raRFCvc9BnXglke6axya12krCJF5xJ2sftRU=
+github.com/tree-sitter/go-tree-sitter v0.25.0/go.mod h1:r77ig7BikoZhHrrsjAnv8RqGti5rtSyvDHPzgTPsUuU=
+github.com/tree-sitter/tree-sitter-c v0.23.4 h1:nBPH3FV07DzAD7p0GfNvXM+Y7pNIoPenQWBpvM++t4c=
+github.com/tree-sitter/tree-sitter-c v0.23.4/go.mod h1:MkI5dOiIpeN94LNjeCp8ljXN/953JCwAby4bClMr6bw=
+github.com/tree-sitter/tree-sitter-cpp v0.23.4 h1:LaWZsiqQKvR65yHgKmnaqA+uz6tlDJTJFCyFIeZU/8w=
+github.com/tree-sitter/tree-sitter-cpp v0.23.4/go.mod h1:doqNW64BriC7WBCQ1klf0KmJpdEvfxyXtoEybnBo6v8=
+github.com/tree-sitter/tree-sitter-embedded-template v0.23.2 h1:nFkkH6Sbe56EXLmZBqHHcamTpmz3TId97I16EnGy4rg=
+github.com/tree-sitter/tree-sitter-embedded-template v0.23.2/go.mod h1:HNPOhN0qF3hWluYLdxWs5WbzP/iE4aaRVPMsdxuzIaQ=
+github.com/tree-sitter/tree-sitter-go v0.23.4 h1:yt5KMGnTHS+86pJmLIAZMWxukr8W7Ae1STPvQUuNROA=
+github.com/tree-sitter/tree-sitter-go v0.23.4/go.mod h1:Jrx8QqYN0v7npv1fJRH1AznddllYiCMUChtVjxPK040=
+github.com/tree-sitter/tree-sitter-html v0.23.2 h1:1UYDV+Yd05GGRhVnTcbP58GkKLSHHZwVaN+lBZV11Lc=
+github.com/tree-sitter/tree-sitter-html v0.23.2/go.mod h1:gpUv/dG3Xl/eebqgeYeFMt+JLOY9cgFinb/Nw08a9og=
+github.com/tree-sitter/tree-sitter-java v0.23.5 h1:J9YeMGMwXYlKSP3K4Us8CitC6hjtMjqpeOf2GGo6tig=
+github.com/tree-sitter/tree-sitter-java v0.23.5/go.mod h1:NRKlI8+EznxA7t1Yt3xtraPk1Wzqh3GAIC46wxvc320=
+github.com/tree-sitter/tree-sitter-javascript v0.23.1 h1:1fWupaRC0ArlHJ/QJzsfQ3Ibyopw7ZfQK4xXc40Zveo=
+github.com/tree-sitter/tree-sitter-javascript v0.23.1/go.mod h1:lmGD1EJdCA+v0S1u2fFgepMg/opzSg/4pgFym2FPGAs=
+github.com/tree-sitter/tree-sitter-json v0.24.8 h1:tV5rMkihgtiOe14a9LHfDY5kzTl5GNUYe6carZBn0fQ=
+github.com/tree-sitter/tree-sitter-json v0.24.8/go.mod h1:F351KK0KGvCaYbZ5zxwx/gWWvZhIDl0eMtn+1r+gQbo=
+github.com/tree-sitter/tree-sitter-php v0.23.11 h1:iHewsLNDmznh8kgGyfWfujsZxIz1YGbSd2ZTEM0ZiP8=
+github.com/tree-sitter/tree-sitter-php v0.23.11/go.mod h1:T/kbfi+UcCywQfUNAJnGTN/fMSUjnwPXA8k4yoIks74=
+github.com/tree-sitter/tree-sitter-python v0.23.6 h1:qHnWFR5WhtMQpxBZRwiaU5Hk/29vGju6CVtmvu5Haas=
+github.com/tree-sitter/tree-sitter-python v0.23.6/go.mod h1:cpdthSy/Yoa28aJFBscFHlGiU+cnSiSh1kuDVtI8YeM=
+github.com/tree-sitter/tree-sitter-ruby v0.23.1 h1:T/NKHUA+iVbHM440hFx+lzVOzS4dV6z8Qw8ai+72bYo=
+github.com/tree-sitter/tree-sitter-ruby v0.23.1/go.mod h1:kUS4kCCQloFcdX6sdpr8p6r2rogbM6ZjTox5ZOQy8cA=
+github.com/tree-sitter/tree-sitter-rust v0.24.2 h1:NL4nF67ib21RMzzfvkmXlVwe45vvhW10DVyO+D0z/W0=
+github.com/tree-sitter/tree-sitter-rust v0.24.2/go.mod h1:hfeGWic9BAfgTrc7Xf6FaOAguCFJRo3RBbs7QJ6D7MI=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/vrsite/jj.go b/vrsite/jj.go
new file mode 100644
index 0000000..55f4795
--- /dev/null
+++ b/vrsite/jj.go
@@ -0,0 +1,275 @@
+// jj.go — every read of the repository goes through here.
+//
+// Two rules hold everywhere: the repo is never modified (no edit, no new, no
+// checkout; --ignore-working-copy on every call so we never even snapshot),
+// and nothing is written to disk — templates are passed inline with -T, so a
+// query leaves no trace behind, it just renders once and is sent to the page.
+package main
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "os/exec"
+ "strings"
+ "time"
+)
+
+// Field separator inside a templated line, record marker at its start. Both
+// are ASCII control characters that cannot appear in ids, names or a
+// description's first line, so parsing stays trivial even under a graph.
+const (
+ jjRec = "\x1e" // as jj prints it
+ jjSep = "\x1f"
+ // as it is written inside a jj template string literal
+ jjRecEsc = `\x1e`
+ jjSepEsc = `\x1f`
+)
+
+const jjTimeout = 30 * time.Second
+
+// jjRun executes jj read-only in repo. stderr comes back inside the error so
+// the page can show what jj complained about.
+func jjRun(repo string, args ...string) ([]byte, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), jjTimeout)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, "jj", append([]string{"--ignore-working-copy"}, args...)...)
+ cmd.Dir = repo
+ var errb strings.Builder
+ cmd.Stderr = &errb
+ out, err := cmd.Output()
+ if err != nil {
+ msg := strings.TrimSpace(errb.String())
+ if msg == "" {
+ msg = err.Error()
+ }
+ return out, fmt.Errorf("jj %s: %s", strings.Join(args, " "), msg)
+ }
+ return out, nil
+}
+
+// mustJJ is the static-build path: a jj failure there is fatal.
+func mustJJ(repo string, args ...string) []byte {
+ out, err := jjRun(repo, args...)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ fatal("repository read failed")
+ }
+ return out
+}
+
+// checkRevset rejects input that jj would read as a flag; revsets themselves
+// are a query language, not a shell, and are passed as one argv entry.
+func checkRevset(r string) error {
+ r = strings.TrimSpace(r)
+ if strings.HasPrefix(r, "-") {
+ return fmt.Errorf("revset must not start with %q", "-")
+ }
+ if len(r) > 512 {
+ return fmt.Errorf("revset too long")
+ }
+ return nil
+}
+
+func resolveChange(repo, rev string) (string, error) {
+ if rev == "" {
+ rev = "@"
+ }
+ if err := checkRevset(rev); err != nil {
+ return "", err
+ }
+ out, err := jjRun(repo, "log", "-r", rev, "--no-graph", "-n", "1", "-T", "change_id")
+ if err != nil {
+ return "", err
+ }
+ id := strings.TrimSpace(string(out))
+ if id == "" {
+ return "", fmt.Errorf("revset %q matches no change", rev)
+ }
+ return id, nil
+}
+
+func fileList(repo, rev string) ([]string, error) {
+ out, err := jjRun(repo, "file", "list", "-r", rev)
+ if err != nil {
+ return nil, err
+ }
+ return strings.Split(strings.TrimRight(string(out), "\n"), "\n"), nil
+}
+
+func fileShow(repo, rev, path string) ([]byte, error) {
+ return jjRun(repo, "file", "show", "-r", rev, "--", path)
+}
+
+// ── log / op log rows ─────────────────────────────────────────────────────
+
+// A Row is one line of jj output: the graph art it was drawn with, plus the
+// fields the inline template produced. Graph-only lines (│, ~) carry Graph
+// alone and render as decoration.
+type Row struct {
+ Graph string
+ ID, Short string
+ Commit, CommitShort string
+ Author, When, End string
+ Refs, Flags, Desc string
+ Op bool
+}
+
+func (r Row) Blank() bool { return r.ID == "" }
+
+// tmplFields builds `"\x1e" ++ f1 ++ "\x1f" ++ f2 ... ++ "\n"`: one line per
+// row, record-marked so the graph art in front of it is separable.
+func tmplFields(fields ...string) string {
+ return `"` + jjRecEsc + `" ++ ` + strings.Join(fields, ` ++ "`+jjSepEsc+`" ++ `) + ` ++ "\n"`
+}
+
+var (
+ commitTmpl = tmplFields(
+ "change_id",
+ "change_id.short(8)",
+ "commit_id",
+ "commit_id.short(8)",
+ "author.email()",
+ `committer.timestamp().format("%Y-%m-%d %H:%M")`,
+ `bookmarks.join(" ")`,
+ `separate(" ", if(current_working_copy, "working copy"), if(empty, "empty"), if(conflict, "conflict"), if(divergent, "divergent"))`,
+ "description.first_line()",
+ )
+ opTmpl = tmplFields(
+ "id",
+ "id.short(12)",
+ `""`,
+ `""`,
+ "user",
+ `time.start().format("%Y-%m-%d %H:%M:%S")`,
+ `""`,
+ `time.end().format("%H:%M:%S")`,
+ "description.first_line()",
+ )
+)
+
+func parseRows(out []byte, op bool) []Row {
+ var rows []Row
+ for _, line := range strings.Split(strings.TrimRight(string(out), "\n"), "\n") {
+ i := strings.Index(line, jjRec)
+ if i < 0 {
+ if strings.TrimSpace(line) != "" {
+ rows = append(rows, Row{Graph: line, Op: op})
+ }
+ continue
+ }
+ f := strings.Split(line[i+len(jjRec):], jjSep)
+ for len(f) < 9 {
+ f = append(f, "")
+ }
+ r := Row{Graph: line[:i], ID: f[0], Short: f[1], Commit: f[2], CommitShort: f[3],
+ Author: f[4], When: f[5], Refs: f[6], Flags: f[7], Desc: f[8], Op: op}
+ if op {
+ r.End, r.Flags = r.Flags, ""
+ }
+ rows = append(rows, r)
+ }
+ return rows
+}
+
+// LogRows runs `jj log -r REVSET` with the inline template. atOp, when set,
+// runs the query as of that operation — the debugging view.
+func LogRows(repo, revset, atOp string, limit int) ([]Row, error) {
+ if err := checkRevset(revset); err != nil {
+ return nil, err
+ }
+ args := []string{"log", "-T", commitTmpl}
+ if strings.TrimSpace(revset) != "" {
+ args = append(args, "-r", revset)
+ }
+ if atOp != "" {
+ if err := checkRevset(atOp); err != nil {
+ return nil, err
+ }
+ args = append(args, "--at-operation", atOp)
+ }
+ if limit > 0 {
+ args = append(args, "-n", fmt.Sprint(limit))
+ }
+ out, err := jjRun(repo, args...)
+ if err != nil {
+ return nil, err
+ }
+ return parseRows(out, false), nil
+}
+
+func OpRows(repo string, limit int) ([]Row, error) {
+ args := []string{"op", "log", "-T", opTmpl}
+ if limit > 0 {
+ args = append(args, "-n", fmt.Sprint(limit))
+ }
+ out, err := jjRun(repo, args...)
+ if err != nil {
+ return nil, err
+ }
+ return parseRows(out, true), nil
+}
+
+// ── one change ────────────────────────────────────────────────────────────
+
+type ChangeFile struct {
+ Status, Path string
+}
+
+type Change struct {
+ Row Row
+ Desc string
+ Files []ChangeFile
+ Stat string
+ Parents []Row
+}
+
+var statusName = map[string]string{"A": "added", "M": "modified", "D": "deleted", "R": "renamed", "C": "copied"}
+
+func LoadChange(repo, rev string) (*Change, error) {
+ rows, err := LogRows(repo, rev, "", 1)
+ if err != nil {
+ return nil, err
+ }
+ var row Row
+ for _, r := range rows {
+ if !r.Blank() {
+ row = r
+ break
+ }
+ }
+ if row.Blank() {
+ return nil, fmt.Errorf("no change matches %q", rev)
+ }
+ c := &Change{Row: row}
+ // full description separately: it is multi-line, so it cannot ride along
+ // in the one-line-per-row template
+ if out, err := jjRun(repo, "log", "-r", row.ID, "--no-graph", "-n", "1", "-T", "description"); err == nil {
+ c.Desc = strings.TrimRight(string(out), "\n")
+ }
+ if out, err := jjRun(repo, "diff", "-r", row.ID, "--summary"); err == nil {
+ for _, line := range strings.Split(strings.TrimRight(string(out), "\n"), "\n") {
+ if len(line) > 2 {
+ st := statusName[line[:1]]
+ if st == "" {
+ st = line[:1]
+ }
+ c.Files = append(c.Files, ChangeFile{Status: st, Path: line[2:]})
+ }
+ }
+ }
+ if out, err := jjRun(repo, "diff", "-r", row.ID, "--stat"); err == nil {
+ lines := strings.Split(strings.TrimRight(string(out), "\n"), "\n")
+ if n := len(lines); n > 0 {
+ c.Stat = strings.TrimSpace(lines[n-1])
+ }
+ }
+ if rows, err := LogRows(repo, "parents("+row.ID+")", "", 8); err == nil {
+ for _, r := range rows {
+ if !r.Blank() {
+ c.Parents = append(c.Parents, r)
+ }
+ }
+ }
+ return c, nil
+}
diff --git a/vrsite/main.go b/vrsite/main.go
new file mode 100644
index 0000000..0a525be
--- /dev/null
+++ b/vrsite/main.go
@@ -0,0 +1,169 @@
+// vrsite — the reading room for vr trace logs.
+//
+// A vr log records who read what, where, and what they thought about it. This
+// program projects that log onto the jj change the code was read at: the repo
+// tree with per-agent coverage colors, tree-sitter highlighted sources with
+// coverage-tinted line numbers (colors mix where agents overlap), and notes —
+// both the ones agents left and the ones you write in the browser.
+//
+// It runs as a live web app (default) or writes a static export (-out).
+// Either way the log is the only state: notes are appended to it, and the
+// repository is only ever read, never modified.
+//
+// Theme comes from a Zed theme JSON; per-agent colors come from the theme's
+// player (collaborator) palette.
+package main
+
+import (
+ "embed"
+ "flag"
+ "fmt"
+ "os"
+ "os/user"
+ "path/filepath"
+ "time"
+)
+
+//go:embed templates assets
+var tfs embed.FS
+
+func fatal(format string, a ...any) {
+ fmt.Fprintf(os.Stderr, "vrsite: "+format+"\n", a...)
+ os.Exit(1)
+}
+
+func main() {
+ logPath := flag.String("log", "", "vr trace log (jsonl)")
+ repo := flag.String("repo", "", "jj repo the trace was recorded in")
+ addr := flag.String("addr", "127.0.0.1:4200", "address to serve on")
+ who := flag.String("user", "", "name your browser notes are logged under (default: $USER)")
+ out := flag.String("out", "", "write a static site here instead of serving")
+ themePath := flag.String("theme", defaultTheme("dark"), "zed theme json for the dark scheme (default: discovered, else embedded One Dark)")
+ themeName := flag.String("theme-name", "", "theme name inside the family")
+ lightPath := flag.String("light-theme", defaultTheme("light"), "zed theme json for the light scheme (default: discovered, else embedded One Light)")
+ lightName := flag.String("light-theme-name", "", "theme name inside the light family")
+ title := flag.String("title", "vr trace", "site title")
+ watch := flag.Bool("watch", false, "with -out: watch the trace log and rebuild after changes settle")
+ debounce := flag.Duration("debounce", 10*time.Minute, "quiet period before a watched rebuild")
+ flag.Parse()
+ if *logPath == "" || *repo == "" {
+ fatal("usage: vrsite -log FILE -repo DIR [-addr HOST:PORT] [-user NAME]\n" +
+ " vrsite -log FILE -repo DIR -out DIR [-watch] [-debounce 10m]\n" +
+ " shared: [-theme zed.json] [-theme-name N] [-light-theme f] [-title T]")
+ }
+ repoAbs, err := filepath.Abs(*repo)
+ if err != nil {
+ fatal("%v", err)
+ }
+ if *debounce < 0 {
+ fatal("debounce must not be negative")
+ }
+ theme := loadTheme(*themePath, *themeName, "dark")
+ light := loadTheme(*lightPath, *lightName, "light")
+
+ if *out == "" {
+ if *watch {
+ fatal("-watch is for -out builds; the served app already follows the log")
+ }
+ serve(*addr, *logPath, repoAbs, *title, username(*who), theme, light)
+ return
+ }
+ build := func() { buildSite(*logPath, repoAbs, *out, *title, theme, light) }
+ build()
+ if !*watch {
+ return
+ }
+ fmt.Printf("vrsite: watching %s (rebuild after %s without changes)\n", *logPath, *debounce)
+ watchLog(*logPath, *debounce, build)
+}
+
+func username(flagValue string) string {
+ if flagValue != "" {
+ return flagValue
+ }
+ if u := os.Getenv("USER"); u != "" {
+ return u
+ }
+ if u, err := user.Current(); err == nil && u.Username != "" {
+ return u.Username
+ }
+ return "web"
+}
+
+// ── watching the log (static export only) ─────────────────────────────────
+
+type logState struct {
+ size int64
+ modTime time.Time
+}
+
+func statLog(path string) (logState, error) {
+ info, err := os.Stat(path)
+ if err != nil {
+ return logState{}, err
+ }
+ return logState{size: info.Size(), modTime: info.ModTime()}, nil
+}
+
+func watchLog(path string, debounce time.Duration, rebuild func()) {
+ watchLogUntil(path, debounce, time.Second, nil, rebuild)
+}
+
+func watchLogUntil(path string, debounce, poll time.Duration, done <-chan struct{}, rebuild func()) {
+ state, err := statLog(path)
+ if err != nil {
+ fatal("watch %s: %v", path, err)
+ }
+
+ ticker := time.NewTicker(poll)
+ defer ticker.Stop()
+ var timer *time.Timer
+ var timerC <-chan time.Time
+ defer func() {
+ if timer != nil {
+ timer.Stop()
+ }
+ }()
+ lastStatErr := ""
+
+ for {
+ select {
+ case <-done:
+ return
+
+ case <-ticker.C:
+ next, err := statLog(path)
+ if err != nil {
+ if msg := err.Error(); msg != lastStatErr {
+ fmt.Fprintf(os.Stderr, "vrsite: watch %s: %v\n", path, err)
+ lastStatErr = msg
+ }
+ continue
+ }
+ lastStatErr = ""
+ if next == state {
+ continue
+ }
+ state = next
+ if timer == nil {
+ timer = time.NewTimer(debounce)
+ timerC = timer.C
+ } else {
+ if !timer.Stop() {
+ select {
+ case <-timer.C:
+ default:
+ }
+ }
+ timer.Reset(debounce)
+ }
+ fmt.Printf("vrsite: change detected; rebuild scheduled after %s without changes\n", debounce)
+
+ case <-timerC:
+ fmt.Println("vrsite: rebuilding after trace changes settled")
+ timer = nil
+ timerC = nil
+ rebuild()
+ }
+ }
+}
diff --git a/vrsite/main_test.go b/vrsite/main_test.go
new file mode 100644
index 0000000..7e715b9
--- /dev/null
+++ b/vrsite/main_test.go
@@ -0,0 +1,57 @@
+package main
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+)
+
+func TestWatchLogDebouncesChanges(t *testing.T) {
+ logPath := filepath.Join(t.TempDir(), "trace.jsonl")
+ if err := os.WriteFile(logPath, []byte("initial\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ done := make(chan struct{})
+ stopped := make(chan struct{})
+ rebuilt := make(chan struct{}, 2)
+ go func() {
+ defer close(stopped)
+ watchLogUntil(logPath, 60*time.Millisecond, 5*time.Millisecond, done, func() {
+ rebuilt <- struct{}{}
+ })
+ }()
+ time.Sleep(20 * time.Millisecond)
+
+ if err := os.WriteFile(logPath, []byte("first change\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ time.Sleep(30 * time.Millisecond)
+ if err := os.WriteFile(logPath, []byte("second change\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ select {
+ case <-rebuilt:
+ t.Fatal("rebuilt before the debounce interval elapsed")
+ case <-time.After(40 * time.Millisecond):
+ }
+ select {
+ case <-rebuilt:
+ case <-time.After(200 * time.Millisecond):
+ t.Fatal("did not rebuild after changes settled")
+ }
+ select {
+ case <-rebuilt:
+ t.Fatal("multiple changes produced more than one rebuild")
+ case <-time.After(40 * time.Millisecond):
+ }
+
+ close(done)
+ select {
+ case <-stopped:
+ case <-time.After(time.Second):
+ t.Fatal("watcher did not stop")
+ }
+}
diff --git a/vrsite/model.go b/vrsite/model.go
new file mode 100644
index 0000000..2cafd75
--- /dev/null
+++ b/vrsite/model.go
@@ -0,0 +1,507 @@
+// model.go — the log projected into a browsable model.
+//
+// Everything the site shows is derived here from the vr log alone: agents and
+// their colors, per-file coverage bitmasks, notes, and live session activity.
+// The repo is never written to; the log is the only state.
+package main
+
+import (
+ "encoding/json"
+ "fmt"
+ "html/template"
+ "os"
+ "sort"
+ "strings"
+ "time"
+)
+
+// Coverage is a uint8 bitmask, so only the first maxAgents agents get a color;
+// later ones fall back to the muted "no bit" rendering.
+const maxAgents = 8
+
+type Entry struct {
+ Time string `json:"time,omitempty"`
+ Op string `json:"op"`
+ Session string `json:"session,omitempty"`
+ Agent string `json:"agent,omitempty"`
+ Model string `json:"model,omitempty"`
+ Reason string `json:"reasoning,omitempty"`
+ Dir string `json:"dir,omitempty"`
+ Rev string `json:"rev,omitempty"`
+ Change string `json:"change,omitempty"`
+ File string `json:"file,omitempty"`
+ Start int `json:"start,omitempty"`
+ End int `json:"end,omitempty"`
+ Pattern string `json:"pattern,omitempty"`
+ Matches int `json:"matches,omitempty"`
+ NoteID int `json:"note_id,omitempty"`
+ Type string `json:"type,omitempty"`
+ Text string `json:"text,omitempty"`
+}
+
+type Agent struct {
+ Name, Short, Session, Model, Reason string
+ Bit uint8
+ Reads, Greps, Notes int
+}
+
+type Note struct {
+ ID int // position in the log, for anchors
+ NoteID int // the agent's own per-session number
+ Agent *Agent
+ Session, Model, Reason string
+ File, Kind, Text, Change, Rev string
+ Start, End int
+ At time.Time
+ When, Ago string
+}
+
+type File struct {
+ Path, Change string
+ Traced bool
+ Stub string // set when content is not rendered (binary, huge)
+ Cov []uint8 // 1-based line -> agent bitmask
+ NoteAt map[int]int // line -> index into Notes
+ Reads, Greps int
+ Patterns []string
+ Notes []*Note
+ Total, Covered, Pct int
+ Mask uint8
+ Body template.HTML
+}
+
+type Site struct {
+ Title string
+ Repo string
+ Change string // the change most entries were logged at
+ Agents []*Agent
+ Files map[string]*File // traced files
+ Order []string // traced paths, sorted
+ All []*File // every file in the repo at the site change
+ Notes []*Note
+ Entries []Entry
+ Theme *Theme // dark
+ Light *Theme
+}
+
+// buildModel projects log entries onto agents, files and notes. It never
+// touches the repo, so it is cheap enough to redo on every log change.
+func buildModel(title string, entries []Entry) *Site {
+ s := &Site{Title: title, Files: map[string]*File{}, Entries: entries}
+ agents := map[string]*Agent{}
+ changeVotes := map[string]int{}
+ for _, e := range entries {
+ if e.Agent == "" {
+ e.Agent = "unknown"
+ }
+ a := agents[e.Agent]
+ if a == nil {
+ a = &Agent{Name: e.Agent, Short: strings.SplitN(e.Agent, "_", 2)[0],
+ Session: e.Session, Model: e.Model, Reason: e.Reason}
+ if len(s.Agents) < maxAgents {
+ a.Bit = 1 << len(s.Agents)
+ }
+ agents[e.Agent] = a
+ s.Agents = append(s.Agents, a)
+ }
+ if e.Change != "" {
+ changeVotes[e.Change]++
+ }
+ switch e.Op {
+ case "read":
+ a.Reads++
+ f := s.file(e.File, e.Change)
+ f.Reads++
+ f.cover(e.Start, e.End, a.Bit)
+ case "grep":
+ a.Greps++
+ if f, ok := s.Files[e.File]; ok || e.File != "" {
+ if f == nil { // grep on a file we later read
+ f = s.file(e.File, e.Change)
+ }
+ f.Greps++
+ f.Patterns = append(f.Patterns, fmt.Sprintf("%s (%d)", e.Pattern, e.Matches))
+ }
+ case "note":
+ a.Notes++
+ at := parseTime(e.Time)
+ n := &Note{ID: len(s.Notes) + 1, NoteID: e.NoteID, Agent: a, Session: e.Session,
+ Model: e.Model, Reason: e.Reason, File: e.File, Change: e.Change,
+ Rev: e.Rev, Start: e.Start, End: e.End, Kind: e.Type, Text: e.Text,
+ At: at, When: stamp(at), Ago: ago(at)}
+ s.Notes = append(s.Notes, n)
+ if e.File != "" {
+ f := s.file(e.File, e.Change)
+ f.Notes = append(f.Notes, n)
+ }
+ }
+ }
+ for c, n := range changeVotes {
+ if s.Change == "" || n > changeVotes[s.Change] {
+ s.Change = c
+ }
+ }
+ // drop grep-only "files" that are really path filters (dirs, non-files)
+ for p, f := range s.Files {
+ if f.Reads == 0 && len(f.Notes) == 0 {
+ delete(s.Files, p)
+ }
+ }
+ for p := range s.Files {
+ s.Order = append(s.Order, p)
+ }
+ sort.Strings(s.Order)
+ return s
+}
+
+func (s *Site) file(path, change string) *File {
+ f := s.Files[path]
+ if f == nil {
+ f = &File{Path: path, NoteAt: map[int]int{}, Traced: true}
+ s.Files[path] = f
+ }
+ if change != "" {
+ f.Change = change
+ }
+ return f
+}
+
+func (f *File) cover(start, end int, bit uint8) {
+ if start < 1 {
+ return
+ }
+ if end < start {
+ end = start
+ }
+ for len(f.Cov) <= end {
+ f.Cov = append(f.Cov, 0)
+ }
+ for i := start; i <= end; i++ {
+ f.Cov[i] |= bit
+ }
+ f.Mask |= bit
+}
+
+// clone copies the per-render state so one *File from the model can be
+// rendered concurrently at several revisions. Cov is read-only during render.
+func (f *File) clone() *File {
+ c := *f
+ c.NoteAt = map[int]int{}
+ c.Notes = append([]*Note(nil), f.Notes...)
+ return &c
+}
+
+// filesAt joins a revision's path list with the traced files, so untraced
+// files still appear in the tree. Traced *File values are shared read-only.
+func (s *Site) filesAt(paths []string, change string) []*File {
+ var all []*File
+ for _, p := range paths {
+ if p == "" {
+ continue
+ }
+ f := s.Files[p]
+ if f == nil {
+ f = &File{Path: p, Change: change, NoteAt: map[int]int{}}
+ } else {
+ f.Traced = true
+ }
+ all = append(all, f)
+ }
+ sort.Slice(all, func(i, j int) bool { return all[i].Path < all[j].Path })
+ return all
+}
+
+// maskColor mixes the theme's agent colors for a coverage bitmask.
+func (s *Site) maskColor(t *Theme, mask uint8) string {
+ var cols []string
+ for i, a := range s.Agents {
+ if a.Bit != 0 && mask&a.Bit != 0 {
+ cols = append(cols, t.Player(i))
+ }
+ }
+ return mixColors(cols)
+}
+
+// masks lists every bitmask combination the colored agents can produce.
+func (s *Site) masks() []uint8 {
+ n := len(s.Agents)
+ if n > maxAgents {
+ n = maxAgents
+ }
+ var out []uint8
+ for m := 1; m < 1<<n; m++ {
+ out = append(out, uint8(m))
+ }
+ return out
+}
+
+// ── notes: filtering and facets ───────────────────────────────────────────
+
+type NoteFilter struct {
+ Text string // substring of the note body
+ File string // substring of the file path
+ Agent string
+ Model string
+ Session string
+ Kind string
+ Change string
+ From string // YYYY-MM-DD, inclusive
+ To string // YYYY-MM-DD, inclusive
+}
+
+func (f NoteFilter) empty() bool { return f == NoteFilter{} }
+
+func (f NoteFilter) match(n *Note) bool {
+ has := func(hay, needle string) bool {
+ return needle == "" || strings.Contains(strings.ToLower(hay), strings.ToLower(needle))
+ }
+ if !has(n.Text, f.Text) || !has(n.File, f.File) {
+ return false
+ }
+ eq := func(got, want string) bool { return want == "" || got == want }
+ if !eq(n.Agent.Name, f.Agent) || !eq(n.Model, f.Model) || !eq(n.Session, f.Session) ||
+ !eq(n.Kind, f.Kind) || !eq(n.Change, f.Change) {
+ return false
+ }
+ if f.From != "" && (n.At.IsZero() || n.At.Format(dateFmt) < f.From) {
+ return false
+ }
+ if f.To != "" && (n.At.IsZero() || n.At.Format(dateFmt) > f.To) {
+ return false
+ }
+ return true
+}
+
+const dateFmt = "2006-01-02"
+
+// FilterNotes returns matching notes, newest first (undated notes last).
+func (s *Site) FilterNotes(f NoteFilter) []*Note {
+ var out []*Note
+ for _, n := range s.Notes {
+ if f.match(n) {
+ out = append(out, n)
+ }
+ }
+ sort.SliceStable(out, func(i, j int) bool { return out[i].At.After(out[j].At) })
+ return out
+}
+
+// Facets are the distinct values the note filters can select, so the form
+// only ever offers choices that exist in the log.
+type Facets struct {
+ Agents, Models, Sessions, Kinds, Changes, Files []string
+}
+
+func (s *Site) Facets() *Facets {
+ fa := &Facets{}
+ add := func(dst *[]string, seen map[string]bool, v string) {
+ if v != "" && !seen[v] {
+ seen[v] = true
+ *dst = append(*dst, v)
+ }
+ }
+ ag, mo, se, ki, ch, fi := map[string]bool{}, map[string]bool{}, map[string]bool{}, map[string]bool{}, map[string]bool{}, map[string]bool{}
+ for _, n := range s.Notes {
+ add(&fa.Agents, ag, n.Agent.Name)
+ add(&fa.Models, mo, n.Model)
+ add(&fa.Sessions, se, n.Session)
+ add(&fa.Kinds, ki, n.Kind)
+ add(&fa.Changes, ch, n.Change)
+ add(&fa.Files, fi, n.File)
+ }
+ for _, s := range [][]string{fa.Agents, fa.Models, fa.Sessions, fa.Kinds, fa.Changes, fa.Files} {
+ sort.Strings(s)
+ }
+ return fa
+}
+
+// nextNoteID mirrors vr's numbering: ids count up from 1 within a session.
+func nextNoteID(entries []Entry, session string) int {
+ max := 0
+ for _, e := range entries {
+ if e.Op == "note" && e.Session == session && e.NoteID > max {
+ max = e.NoteID
+ }
+ }
+ return max + 1
+}
+
+// ── live activity ─────────────────────────────────────────────────────────
+
+// A Session is one agent run seen in the log: who it is, what it last did,
+// and whether it is still going. This is what "live" shows.
+type Session struct {
+ ID, Agent, Short, Model, Reason, Dir string
+ Bit uint8
+ Last time.Time
+ Ago, LastOp, File string
+ Change string
+ Reads, Greps, Notes int
+ Live bool
+}
+
+// Sessions groups the log by session (falling back to agent+dir for logs
+// without one), newest activity first. Sessions touched within window are
+// reported as live.
+func (s *Site) Sessions(now time.Time, window time.Duration, limit int) []*Session {
+ byKey := map[string]*Session{}
+ var order []*Session
+ byName := map[string]*Agent{}
+ for _, a := range s.Agents {
+ byName[a.Name] = a
+ }
+ for _, e := range s.Entries {
+ name := e.Agent
+ if name == "" {
+ name = "unknown"
+ }
+ key := e.Session
+ if key == "" {
+ key = name + "\x00" + e.Dir
+ }
+ v := byKey[key]
+ if v == nil {
+ a := byName[name]
+ v = &Session{ID: e.Session, Agent: name, Dir: e.Dir}
+ if a != nil {
+ v.Short, v.Bit = a.Short, a.Bit
+ }
+ byKey[key] = v
+ order = append(order, v)
+ }
+ if e.Model != "" {
+ v.Model, v.Reason = e.Model, e.Reason
+ }
+ if e.Dir != "" {
+ v.Dir = e.Dir
+ }
+ if e.Change != "" {
+ v.Change = e.Change
+ }
+ switch e.Op {
+ case "read":
+ v.Reads++
+ case "grep":
+ v.Greps++
+ case "note":
+ v.Notes++
+ }
+ if at := parseTime(e.Time); !at.IsZero() && at.After(v.Last) {
+ v.Last, v.File, v.LastOp = at, e.File, describe(e)
+ }
+ }
+ for _, v := range order {
+ v.Ago = agoFrom(now, v.Last)
+ v.Live = !v.Last.IsZero() && now.Sub(v.Last) < window
+ }
+ sort.SliceStable(order, func(i, j int) bool { return order[i].Last.After(order[j].Last) })
+ if limit > 0 && len(order) > limit {
+ order = order[:limit]
+ }
+ return order
+}
+
+func describe(e Entry) string {
+ switch e.Op {
+ case "read":
+ if e.Start > 0 {
+ if e.End > e.Start {
+ return fmt.Sprintf("read %s:%d-%d", e.File, e.Start, e.End)
+ }
+ return fmt.Sprintf("read %s:%d", e.File, e.Start)
+ }
+ return "read " + e.File
+ case "grep":
+ if e.File != "" {
+ return fmt.Sprintf("grep %q in %s (%d)", e.Pattern, e.File, e.Matches)
+ }
+ return fmt.Sprintf("grep %q (%d)", e.Pattern, e.Matches)
+ case "note":
+ if e.File != "" {
+ return "note on " + e.File
+ }
+ return "note"
+ }
+ return e.Op
+}
+
+// ── log file ──────────────────────────────────────────────────────────────
+
+func parseLog(b []byte) []Entry {
+ var entries []Entry
+ for _, line := range strings.Split(string(b), "\n") {
+ if line == "" {
+ continue
+ }
+ var e Entry
+ if json.Unmarshal([]byte(line), &e) == nil {
+ entries = append(entries, e)
+ }
+ }
+ return entries
+}
+
+func readLog(path string) []Entry {
+ b, err := os.ReadFile(path)
+ if err != nil {
+ fatal("%v", err)
+ }
+ return parseLog(b)
+}
+
+// appendEntry adds one line to the log. O_APPEND plus a single write keeps it
+// interleaving safely with vr processes writing the same file.
+func appendEntry(path string, e Entry) error {
+ b, err := json.Marshal(e)
+ if err != nil {
+ return err
+ }
+ f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ _, err = f.Write(append(b, '\n'))
+ return err
+}
+
+// ── time ──────────────────────────────────────────────────────────────────
+
+func parseTime(s string) time.Time {
+ if s == "" {
+ return time.Time{}
+ }
+ t, err := time.Parse(time.RFC3339, s)
+ if err != nil {
+ return time.Time{}
+ }
+ return t
+}
+
+func stamp(t time.Time) string {
+ if t.IsZero() {
+ return ""
+ }
+ return t.Local().Format("2006-01-02 15:04")
+}
+
+func ago(t time.Time) string { return agoFrom(time.Now(), t) }
+
+func agoFrom(now, t time.Time) string {
+ if t.IsZero() {
+ return ""
+ }
+ d := now.Sub(t)
+ switch {
+ case d < 0:
+ return "just now"
+ case d < time.Minute:
+ return fmt.Sprintf("%ds ago", int(d.Seconds()))
+ case d < time.Hour:
+ return fmt.Sprintf("%dm ago", int(d.Minutes()))
+ case d < 24*time.Hour:
+ return fmt.Sprintf("%dh ago", int(d.Hours()))
+ default:
+ return fmt.Sprintf("%dd ago", int(d.Hours())/24)
+ }
+}
diff --git a/vrsite/page.go b/vrsite/page.go
new file mode 100644
index 0000000..71a8343
--- /dev/null
+++ b/vrsite/page.go
@@ -0,0 +1,172 @@
+// page.go — what a template gets, and how links are formed.
+//
+// The same templates render two ways: as a static export (relative links,
+// ".html" suffixes, no server-side features) and as the live web app
+// (absolute routes, htmx-driven filters, comments and jj queries). Pages carry
+// Live so a template can ask for the difference in one place.
+package main
+
+import (
+ "html/template"
+ "net/url"
+ "strconv"
+ "strings"
+)
+
+type page struct {
+ Site *Site
+ Title string
+ Kind string // index | file | files | notes | jj | change
+ Root string // static: relative prefix; live: "/"
+ Live bool
+ Rev string // revision being browsed ("" = the site change)
+ ChangeID string // resolved change id for Rev
+ Current string // current file path, for the tree
+ User string // who web comments are attributed to
+
+ Tree template.HTML
+ File *File
+
+ Notes []*Note
+ Filter NoteFilter
+ Facets *Facets
+ Sessions []*Session
+ Compact bool
+ Window string
+
+ JJ *JJView
+ Change *Change
+ Err string
+}
+
+// JJView is one rendered jj query: what was asked, and what came back.
+type JJView struct {
+ Kind string // log | op
+ Revset string
+ AtOp string
+ Limit int
+ Rows []Row
+ Err string
+}
+
+func (p *page) revQuery(first bool) string {
+ if p.Rev == "" || p.Rev == "@" {
+ return ""
+ }
+ sep := "&"
+ if first {
+ sep = "?"
+ }
+ return sep + "rev=" + url.QueryEscape(p.Rev)
+}
+
+// Href maps a logical destination to a URL for this page's mode. Kinds the
+// static export has no page for return "", and templates guard on .Live.
+func (p *page) Href(kind string, arg ...string) string {
+ a := ""
+ if len(arg) > 0 {
+ a = arg[0]
+ }
+ if p.Live {
+ switch kind {
+ case "":
+ return "/" + p.revQuery(true)
+ case "notes":
+ return "/notes"
+ case "files":
+ return "/files" + p.revQuery(true)
+ case "tree":
+ return "/tree" + p.revQuery(true)
+ case "jj":
+ return "/jj"
+ case "code":
+ return "/code/" + escPath(a) + p.revQuery(true)
+ case "change":
+ return "/change/" + a
+ case "asset":
+ return "/" + a
+ }
+ return "/"
+ }
+ switch kind {
+ case "":
+ return p.Root + "index.html"
+ case "notes":
+ return p.Root + "notes.html"
+ case "files":
+ return p.Root + "files.html"
+ case "tree":
+ return p.Root + "tree.html"
+ case "code":
+ return p.Root + "code/" + a + ".html"
+ case "asset":
+ return p.Root + a
+ }
+ return ""
+}
+
+// codeLink is the tree's per-file linker for this page's mode.
+func (p *page) codeLink() func(string) string {
+ return func(path string) string { return p.Href("code", path) }
+}
+
+func escPath(p string) string {
+ parts := strings.Split(p, "/")
+ for i, s := range parts {
+ parts[i] = url.PathEscape(s)
+ }
+ return strings.Join(parts, "/")
+}
+
+// NoteHref points at the noted line, or the note list when it is unpinned.
+func (p *page) NoteHref(n *Note) string {
+ if n.File == "" {
+ return p.Href("notes")
+ }
+ h := p.Href("code", n.File)
+ if n.Start > 0 {
+ h += "#L" + strconv.Itoa(n.Start)
+ }
+ return h
+}
+
+func newTemplates() *template.Template {
+ funcs := template.FuncMap{
+ "short": short,
+ "band": func(a, b uint8) bool { return b != 0 && a&b != 0 },
+ "lines": func(n *Note) string {
+ if n.Start <= 0 {
+ return "whole file"
+ }
+ if n.End > n.Start {
+ return ":" + strconv.Itoa(n.Start) + "-" + strconv.Itoa(n.End)
+ }
+ return ":" + strconv.Itoa(n.Start)
+ },
+ "base": func(p string) string {
+ if i := strings.LastIndex(p, "/"); i >= 0 {
+ return p[i+1:]
+ }
+ return p
+ },
+ "dict": func(kv ...any) map[string]any {
+ m := map[string]any{}
+ for i := 0; i+1 < len(kv); i += 2 {
+ m[kv[i].(string)] = kv[i+1]
+ }
+ return m
+ },
+ }
+ tpl, err := template.New("layout.tmpl").Funcs(funcs).ParseFS(tfs, "templates/*.tmpl")
+ if err != nil {
+ fatal("%v", err)
+ }
+ return tpl
+}
+
+func short(s string) string {
+ if len(s) > 8 {
+ return s[:8]
+ }
+ return s
+}
diff --git a/vrsite/render.go b/vrsite/render.go
new file mode 100644
index 0000000..de21fc5
--- /dev/null
+++ b/vrsite/render.go
@@ -0,0 +1,289 @@
+// render.go — source to HTML: tree-sitter highlighting, coverage classes and
+// note anchors baked into one <ol> per chunk.
+package main
+
+import (
+ "bytes"
+ "html/template"
+ "sort"
+ "strconv"
+ "strings"
+
+ sitter "github.com/tree-sitter/go-tree-sitter"
+ tsrust "github.com/tree-sitter/tree-sitter-rust/bindings/go"
+)
+
+// Lines per content-visibility chunk: the browser skips layout and paint of
+// offscreen chunks wholesale, instead of managing one containment context
+// per line.
+const chunkLines = 800
+
+// approximate rendered line height, for contain-intrinsic-size placeholders
+const lineHeightPx = 19
+
+// render builds the code HTML: <ol> chunks of chunkLines lines, each line an
+// <li> with syntax spans, coverage classes and note anchors. One pre-sized
+// builder, no fmt, minimal escaping — large files are browser-bound, so the
+// output is kept as small and flat as possible.
+func (f *File) render(src []byte, hl *highlighter) {
+ classes := hl.classify(f.Path, src)
+ f.Total = bytes.Count(src, []byte{'\n'})
+ if len(src) > 0 && src[len(src)-1] != '\n' {
+ f.Total++
+ }
+ f.Covered = 0
+ for i := 1; i < len(f.Cov) && i <= f.Total; i++ {
+ if f.Cov[i] != 0 {
+ f.Covered++
+ }
+ }
+ if f.Total > 0 {
+ f.Pct = f.Covered * 100 / f.Total
+ }
+ sort.Slice(f.Notes, func(i, j int) bool { return f.Notes[i].Start < f.Notes[j].Start })
+ for ni, n := range f.Notes {
+ for l := n.Start; l <= n.End && l > 0; l++ {
+ if _, taken := f.NoteAt[l]; !taken {
+ f.NoteAt[l] = ni
+ }
+ }
+ }
+
+ var b strings.Builder
+ b.Grow(len(src) + len(src)/2 + f.Total*48)
+ var num []byte
+ writeInt := func(n int) { num = strconv.AppendInt(num[:0], int64(n), 10); b.Write(num) }
+ start := 0
+ for ln := 1; ln <= f.Total; ln++ {
+ end := start
+ for end < len(src) && src[end] != '\n' {
+ end++
+ }
+ if (ln-1)%chunkLines == 0 {
+ if ln > 1 {
+ b.WriteString("</ol>")
+ }
+ rem := f.Total - (ln - 1)
+ if rem > chunkLines {
+ rem = chunkLines
+ }
+ b.WriteString(`<ol class="code" style="counter-reset: ln `)
+ writeInt(ln - 1)
+ b.WriteString(`; --h: `)
+ writeInt(rem * lineHeightPx)
+ b.WriteString(`px">`)
+ }
+ b.WriteString(`<li id="L`)
+ writeInt(ln)
+ b.WriteByte('"')
+ mask := uint8(0)
+ if ln < len(f.Cov) {
+ mask = f.Cov[ln]
+ }
+ ni, noted := f.NoteAt[ln]
+ if mask != 0 || noted {
+ b.WriteString(` class="`)
+ if mask != 0 {
+ b.WriteString("cov am")
+ writeInt(int(mask))
+ if noted {
+ b.WriteString(" noted")
+ }
+ } else {
+ b.WriteString("noted")
+ }
+ b.WriteByte('"')
+ }
+ if noted {
+ b.WriteString(` data-note="note-`)
+ writeInt(f.Notes[ni].ID)
+ b.WriteByte('"')
+ }
+ b.WriteByte('>')
+ emitLine(&b, src[start:end], classes[start:end], hl.classNames)
+ b.WriteString("</li>")
+ start = end + 1
+ }
+ if f.Total > 0 {
+ b.WriteString("</ol>")
+ }
+ f.Body = template.HTML(b.String())
+}
+
+// emitLine writes one line's spans, merging runs of the same class across
+// whitespace-only gaps ("pub fn" is one span, not two) to keep the DOM flat.
+func emitLine(b *strings.Builder, line []byte, cls []int16, names []string) {
+ open := int16(0)
+ i := 0
+ for i < len(line) {
+ j := i
+ c := cls[i]
+ for j < len(line) && cls[j] == c {
+ j++
+ }
+ if c == 0 {
+ allSpace := true
+ for k := i; k < j; k++ {
+ if line[k] != ' ' && line[k] != '\t' {
+ allSpace = false
+ break
+ }
+ }
+ if !(allSpace && open != 0 && j < len(line) && cls[j] == open) {
+ if open != 0 {
+ b.WriteString("</span>")
+ open = 0
+ }
+ }
+ escapeTo(b, line[i:j])
+ } else {
+ if open != c {
+ if open != 0 {
+ b.WriteString("</span>")
+ }
+ b.WriteString(`<span class="s-`)
+ b.WriteString(names[c])
+ b.WriteString(`">`)
+ open = c
+ }
+ escapeTo(b, line[i:j])
+ }
+ i = j
+ }
+ if open != 0 {
+ b.WriteString("</span>")
+ }
+}
+
+// escapeTo escapes the three characters that matter in text content.
+func escapeTo(b *strings.Builder, s []byte) {
+ last := 0
+ for i, c := range s {
+ var rep string
+ switch c {
+ case '&':
+ rep = "&amp;"
+ case '<':
+ rep = "&lt;"
+ case '>':
+ rep = "&gt;"
+ default:
+ continue
+ }
+ b.Write(s[last:i])
+ b.WriteString(rep)
+ last = i + 1
+ }
+ b.Write(s[last:])
+}
+
+// ── highlighting ──────────────────────────────────────────────────────────
+
+type highlighter struct {
+ lang *sitter.Language
+ query *sitter.Query
+ captureCls []int16 // capture index -> class id
+ classNames []string
+}
+
+// resolveKey finds the theme syntax key for a capture name by stripping dot
+// segments; "" when the theme has no entry at all.
+func resolveKey(t *Theme, name string) string {
+ for key := name; key != ""; {
+ if s, ok := t.Syntax[key]; ok && s.Color != "" {
+ return key
+ }
+ if i := strings.LastIndex(key, "."); i >= 0 {
+ key = key[:i]
+ } else {
+ break
+ }
+ }
+ return ""
+}
+
+// nearFg reports whether a capture would render indistinguishably from plain
+// foreground text in the theme. Spans for such captures are pure DOM weight.
+func nearFg(t *Theme, name string) bool {
+ key := resolveKey(t, name)
+ if key == "" {
+ return true // no color -> falls through to fg anyway
+ }
+ return colorDist(hex6(t.Syntax[key].Color), hex6(t.Fg)) < 2000
+}
+
+func newHighlighter(dark, light *Theme) *highlighter {
+ h := &highlighter{classNames: []string{""}}
+ h.lang = sitter.NewLanguage(tsrust.Language())
+ scm, _ := tfs.ReadFile("assets/rust.scm")
+ q, qerr := sitter.NewQuery(h.lang, string(scm))
+ if qerr != nil {
+ fatal("rust query: %v", qerr)
+ }
+ h.query = q
+ for _, name := range q.CaptureNames() {
+ // skip captures that both themes paint (nearly) as foreground —
+ // punctuation and friends are the bulk of all spans
+ if nearFg(dark, name) && nearFg(light, name) {
+ h.captureCls = append(h.captureCls, 0)
+ continue
+ }
+ key := resolveKey(dark, name)
+ if key == "" {
+ key = resolveKey(light, name)
+ }
+ cls := strings.ReplaceAll(key, ".", "-")
+ id := int16(0)
+ for i, n := range h.classNames {
+ if n == cls {
+ id = int16(i)
+ }
+ }
+ if id == 0 {
+ h.classNames = append(h.classNames, cls)
+ id = int16(len(h.classNames) - 1)
+ }
+ h.captureCls = append(h.captureCls, id)
+ }
+ return h
+}
+
+type paint struct {
+ start, end uint
+ pattern uint
+ cls int16
+}
+
+// classify is safe for concurrent use: the shared query is immutable, and
+// parser and cursor are per-call.
+func (h *highlighter) classify(path string, src []byte) []int16 {
+ classes := make([]int16, len(src))
+ if !strings.HasSuffix(path, ".rs") {
+ return classes
+ }
+ parser := sitter.NewParser()
+ defer parser.Close()
+ parser.SetLanguage(h.lang)
+ tree := parser.Parse(src, nil)
+ defer tree.Close()
+
+ qc := sitter.NewQueryCursor()
+ defer qc.Close()
+ matches := qc.Matches(h.query, tree.RootNode(), src)
+ var paints []paint
+ for m := matches.Next(); m != nil; m = matches.Next() {
+ for _, c := range m.Captures {
+ if cls := h.captureCls[c.Index]; cls != 0 {
+ paints = append(paints, paint{c.Node.StartByte(), c.Node.EndByte(), m.PatternIndex, cls})
+ }
+ }
+ }
+ // later patterns in the query paint over earlier ones
+ sort.Slice(paints, func(i, j int) bool { return paints[i].pattern < paints[j].pattern })
+ for _, p := range paints {
+ for i := p.start; i < p.end && int(i) < len(classes); i++ {
+ classes[i] = p.cls
+ }
+ }
+ return classes
+}
diff --git a/vrsite/serve.go b/vrsite/serve.go
new file mode 100644
index 0000000..c73630c
--- /dev/null
+++ b/vrsite/serve.go
@@ -0,0 +1,522 @@
+// serve.go — vrsite as a live web application.
+//
+// The log is the only state: it is re-read whenever it grows, notes written
+// from the browser are appended to it, and the repository is only ever read
+// (see jj.go). Pages are rendered per request from the same templates the
+// static export uses; htmx swaps the parts that change on their own —
+// filtered note lists, the activity of agents currently reading, jj queries.
+package main
+
+import (
+ "bytes"
+ "fmt"
+ "html/template"
+ "net/http"
+ "net/url"
+ "os"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+)
+
+// liveWindow is how recently a session must have logged something to count as
+// still running.
+const liveWindow = 5 * time.Minute
+
+// renderCacheMax bounds the rendered-file cache; it is dropped wholesale
+// whenever the log changes, since coverage is baked into the HTML.
+const renderCacheMax = 64
+
+type server struct {
+ logPath, repo, title, user, session string
+ tpl *template.Template
+ hl *highlighter
+ theme, light *Theme
+
+ mu sync.Mutex
+ site *Site
+ entries []Entry
+ off int64
+ state logState
+ gen int
+ def string // resolved change the log points at
+ trees map[string][]*File // change -> file list
+ rendered map[string]*File // gen|change|path -> rendered file
+}
+
+func newServer(logPath, repo, title, user string, theme, light *Theme) *server {
+ sv := &server{logPath: logPath, repo: repo, title: title, user: user,
+ session: "web:" + user, theme: theme, light: light,
+ tpl: newTemplates(), trees: map[string][]*File{}, rendered: map[string]*File{}}
+ sv.hl = newHighlighter(theme, light)
+ sv.reload(true)
+ return sv
+}
+
+// reload re-reads the log if it changed. It appends from the last offset when
+// the file only grew — the common case, since vr and the web app both append.
+func (sv *server) reload(force bool) {
+ st, err := statLog(sv.logPath)
+ if err == nil && st == sv.state && !force {
+ return
+ }
+ if err != nil {
+ if sv.site == nil {
+ sv.site = buildModel(sv.title, nil)
+ sv.site.Theme, sv.site.Light = sv.theme, sv.light
+ }
+ return
+ }
+ if st.size < sv.off {
+ sv.off, sv.entries = 0, nil // truncated or rewritten
+ }
+ f, err := os.Open(sv.logPath)
+ if err != nil {
+ return
+ }
+ defer f.Close()
+ buf := make([]byte, st.size-sv.off)
+ n, _ := f.ReadAt(buf, sv.off)
+ buf = buf[:n]
+ if i := bytes.LastIndexByte(buf, '\n'); i >= 0 { // ignore a partial last line
+ sv.off += int64(i + 1)
+ sv.entries = append(sv.entries, parseLog(buf[:i+1])...)
+ }
+ sv.state = st
+ sv.site = buildModel(sv.title, sv.entries)
+ sv.site.Theme, sv.site.Light, sv.site.Repo = sv.theme, sv.light, sv.repo
+ sv.gen++
+ sv.def = ""
+ sv.trees = map[string][]*File{}
+ sv.rendered = map[string]*File{}
+}
+
+// snap returns the current model, its generation, and the change the log
+// points at (falling back to the working copy when that change is unknown to
+// this repo).
+func (sv *server) snap() (*Site, int, string) {
+ sv.mu.Lock()
+ defer sv.mu.Unlock()
+ sv.reload(false)
+ if sv.def == "" {
+ def := sv.site.Change
+ if def == "" {
+ def = "@"
+ }
+ if id, err := resolveChange(sv.repo, def); err == nil {
+ sv.def = id
+ } else if id, err := resolveChange(sv.repo, "@"); err == nil {
+ sv.def = id
+ } else {
+ sv.def = def
+ }
+ sv.site.All = sv.filesLocked(sv.site, sv.def)
+ }
+ return sv.site, sv.gen, sv.def
+}
+
+func (sv *server) filesLocked(site *Site, change string) []*File {
+ if f, ok := sv.trees[change]; ok {
+ return f
+ }
+ paths, err := fileList(sv.repo, change)
+ if err != nil {
+ return nil
+ }
+ f := site.filesAt(paths, change)
+ sv.trees[change] = f
+ return f
+}
+
+func (sv *server) files(site *Site, change string) []*File {
+ sv.mu.Lock()
+ defer sv.mu.Unlock()
+ return sv.filesLocked(site, change)
+}
+
+// fileAt renders one file at a change: model coverage and notes, source from
+// jj, highlighted. Results are cached per log generation.
+func (sv *server) fileAt(site *Site, gen int, change, path string) *File {
+ key := fmt.Sprintf("%d|%s|%s", gen, change, path)
+ sv.mu.Lock()
+ if f, ok := sv.rendered[key]; ok {
+ sv.mu.Unlock()
+ return f
+ }
+ sv.mu.Unlock()
+
+ var f *File
+ if base, ok := site.Files[path]; ok {
+ f = base.clone()
+ } else {
+ f = &File{Path: path, Change: change, NoteAt: map[int]int{}}
+ }
+ if f.Change == "" {
+ f.Change = change
+ }
+ src, err := fileShow(sv.repo, change, path)
+ switch {
+ case err != nil:
+ f.Stub = "not present at this change"
+ case bytes.IndexByte(src, 0) >= 0:
+ f.Stub = "binary file — not rendered"
+ case len(src) > 2<<20:
+ f.Stub = fmt.Sprintf("file too large to render (%d KB)", len(src)/1024)
+ default:
+ f.render(src, sv.hl)
+ }
+
+ sv.mu.Lock()
+ if len(sv.rendered) > renderCacheMax {
+ sv.rendered = map[string]*File{}
+ }
+ sv.rendered[key] = f
+ sv.mu.Unlock()
+ return f
+}
+
+// ── request plumbing ──────────────────────────────────────────────────────
+
+// newPage resolves ?rev= and fills in everything the layout needs.
+func (sv *server) newPage(r *http.Request, kind, title string) (*page, *Site, error) {
+ site, _, def := sv.snap()
+ p := &page{Site: site, Kind: kind, Title: title, Root: "/", Live: true,
+ User: sv.user, ChangeID: def, Facets: site.Facets()}
+ rev := strings.TrimSpace(r.URL.Query().Get("rev"))
+ if rev != "" && rev != def {
+ id, err := resolveChange(sv.repo, rev)
+ if err != nil {
+ return p, site, err
+ }
+ p.Rev, p.ChangeID = rev, id
+ }
+ return p, site, nil
+}
+
+func (sv *server) render(w http.ResponseWriter, p *page) {
+ var b bytes.Buffer
+ if err := sv.tpl.Execute(&b, p); err != nil {
+ http.Error(w, "render: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ b.WriteTo(w)
+}
+
+func (sv *server) frag(w http.ResponseWriter, name string, data any) {
+ var b bytes.Buffer
+ if err := sv.tpl.ExecuteTemplate(&b, name, data); err != nil {
+ http.Error(w, "render: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ b.WriteTo(w)
+}
+
+func htmxReq(r *http.Request) bool { return r.Header.Get("HX-Request") != "" }
+
+func atoiDefault(s string, def int) int {
+ if n, err := strconv.Atoi(strings.TrimSpace(s)); err == nil {
+ return n
+ }
+ return def
+}
+
+func (sv *server) handler() http.Handler {
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /{$}", sv.index)
+ mux.HandleFunc("GET /files", sv.filesPage)
+ mux.HandleFunc("GET /tree", sv.treeFrag)
+ mux.HandleFunc("GET /code/{path...}", sv.codePage)
+ mux.HandleFunc("GET /notes", sv.notesPage)
+ mux.HandleFunc("GET /notes/list", sv.notesList)
+ mux.HandleFunc("POST /notes", sv.addNote)
+ mux.HandleFunc("GET /activity", sv.activity)
+ mux.HandleFunc("GET /jj", sv.jjPage)
+ mux.HandleFunc("GET /jj/log", sv.jjLog)
+ mux.HandleFunc("GET /jj/op", sv.jjOp)
+ mux.HandleFunc("GET /change/{id}", sv.changePage)
+ mux.HandleFunc("GET /style.css", sv.styleCSS)
+ mux.HandleFunc("GET /app.js", sv.asset)
+ mux.HandleFunc("GET /htmx.min.js", sv.asset)
+ return mux
+}
+
+// ── pages ─────────────────────────────────────────────────────────────────
+
+func (sv *server) index(w http.ResponseWriter, r *http.Request) {
+ p, site, err := sv.newPage(r, "index", sv.title)
+ if err != nil {
+ p.Err = err.Error()
+ }
+ p.Notes = site.FilterNotes(NoteFilter{})
+ if len(p.Notes) > 24 {
+ p.Notes = p.Notes[:24]
+ }
+ sv.render(w, p)
+}
+
+func (sv *server) filesPage(w http.ResponseWriter, r *http.Request) {
+ p, site, err := sv.newPage(r, "files", "files — "+sv.title)
+ if err != nil {
+ p.Err = err.Error()
+ sv.render(w, p)
+ return
+ }
+ p.Tree = template.HTML(renderTree(sv.files(site, p.ChangeID), p.codeLink()))
+ sv.render(w, p)
+}
+
+func (sv *server) treeFrag(w http.ResponseWriter, r *http.Request) {
+ p, site, err := sv.newPage(r, "files", "")
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ fmt.Fprint(w, renderTree(sv.files(site, p.ChangeID), p.codeLink()))
+}
+
+func (sv *server) codePage(w http.ResponseWriter, r *http.Request) {
+ path := strings.TrimPrefix(r.PathValue("path"), "/")
+ p, site, err := sv.newPage(r, "file", path+" — "+sv.title)
+ if err != nil {
+ p.Err = err.Error()
+ sv.render(w, p)
+ return
+ }
+ _, gen, _ := sv.snap()
+ p.Current = path
+ p.File = sv.fileAt(site, gen, p.ChangeID, path)
+ sv.render(w, p)
+}
+
+func (sv *server) notesPage(w http.ResponseWriter, r *http.Request) {
+ p, site, err := sv.newPage(r, "notes", "notes — "+sv.title)
+ if err != nil {
+ p.Err = err.Error()
+ }
+ p.Filter = filterFrom(r)
+ p.Notes = site.FilterNotes(p.Filter)
+ sv.render(w, p)
+}
+
+func (sv *server) notesList(w http.ResponseWriter, r *http.Request) {
+ p, site, _ := sv.newPage(r, "notes", "")
+ p.Filter = filterFrom(r)
+ p.Notes = site.FilterNotes(p.Filter)
+ sv.frag(w, "notelist-oob", p)
+}
+
+func filterFrom(r *http.Request) NoteFilter {
+ q := r.URL.Query()
+ return NoteFilter{
+ Text: q.Get("text"), File: q.Get("file"), Agent: q.Get("agent"),
+ Model: q.Get("model"), Session: q.Get("session"), Kind: q.Get("kind"),
+ Change: q.Get("change"), From: q.Get("from"), To: q.Get("to"),
+ }
+}
+
+// addNote appends a comment written in the browser to the log — the only
+// write this program does, and it never touches the repository.
+func (sv *server) addNote(w http.ResponseWriter, r *http.Request) {
+ // the app writes to a file on your disk, so refuse posts a page on
+ // another origin sent here
+ if o := r.Header.Get("Origin"); o != "" {
+ if u, err := url.Parse(o); err != nil || u.Host != r.Host {
+ http.Error(w, "cross-origin post refused", http.StatusForbidden)
+ return
+ }
+ }
+ if err := r.ParseForm(); err != nil {
+ http.Error(w, "bad form", http.StatusBadRequest)
+ return
+ }
+ text := strings.TrimSpace(r.FormValue("text"))
+ if text == "" {
+ http.Error(w, "a note needs text", http.StatusBadRequest)
+ return
+ }
+ rev := strings.TrimSpace(r.FormValue("rev"))
+ if rev == "" {
+ rev = "@"
+ }
+ change, err := resolveChange(sv.repo, rev)
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+ start := atoiDefault(r.FormValue("start"), 0)
+ end := atoiDefault(r.FormValue("end"), 0)
+ if end < start {
+ end = start
+ }
+ e := Entry{
+ Time: time.Now().Format(time.RFC3339), Op: "note",
+ Session: sv.session, Agent: sv.user, Dir: sv.repo,
+ Rev: rev, Change: change, File: strings.TrimSpace(r.FormValue("file")),
+ Start: start, End: end, Type: strings.TrimSpace(r.FormValue("kind")), Text: text,
+ }
+
+ sv.mu.Lock()
+ e.NoteID = nextNoteID(sv.entries, sv.session)
+ err = appendEntry(sv.logPath, e)
+ if err == nil {
+ sv.reload(true)
+ }
+ site := sv.site
+ sv.mu.Unlock()
+ if err != nil {
+ http.Error(w, "write log: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ if !htmxReq(r) {
+ back := r.FormValue("back")
+ if back == "" {
+ back = "/notes"
+ }
+ http.Redirect(w, r, back, http.StatusSeeOther)
+ return
+ }
+ p := &page{Site: site, Kind: "file", Root: "/", Live: true, User: sv.user, Facets: site.Facets()}
+ if e.File != "" {
+ p.File = site.Files[e.File]
+ }
+ // the note just written is the last one carrying our session and id
+ for i := len(site.Notes) - 1; i >= 0; i-- {
+ if n := site.Notes[i]; n.Session == sv.session && n.NoteID == e.NoteID {
+ p.Notes = []*Note{n}
+ break
+ }
+ }
+ sv.frag(w, "note-added", p)
+}
+
+func (sv *server) activity(w http.ResponseWriter, r *http.Request) {
+ site, _, _ := sv.snap()
+ limit := 6
+ compact := r.URL.Query().Get("compact") != ""
+ if !compact {
+ limit = 20
+ }
+ p := &page{Site: site, Live: true, Compact: compact, Window: "5 min",
+ Sessions: site.Sessions(time.Now(), liveWindow, limit)}
+ sv.frag(w, "activity", p)
+}
+
+// ── jj ────────────────────────────────────────────────────────────────────
+
+const defaultLimit = 50
+
+func (sv *server) jjView(r *http.Request) *JJView {
+ q := r.URL.Query()
+ v := &JJView{Kind: q.Get("kind"), Revset: strings.TrimSpace(q.Get("revset")),
+ AtOp: strings.TrimSpace(q.Get("at_op")), Limit: atoiDefault(q.Get("limit"), defaultLimit)}
+ if v.Limit < 1 || v.Limit > 1000 {
+ v.Limit = defaultLimit
+ }
+ if v.Kind != "op" {
+ v.Kind = "log"
+ }
+ var err error
+ if v.Kind == "op" {
+ v.Rows, err = OpRows(sv.repo, v.Limit)
+ } else {
+ v.Rows, err = LogRows(sv.repo, v.Revset, v.AtOp, v.Limit)
+ }
+ if err != nil {
+ v.Err = err.Error()
+ }
+ return v
+}
+
+func (sv *server) jjPage(w http.ResponseWriter, r *http.Request) {
+ p, _, err := sv.newPage(r, "jj", "jj — "+sv.title)
+ if err != nil {
+ p.Err = err.Error()
+ }
+ p.JJ = sv.jjView(r)
+ sv.render(w, p)
+}
+
+func (sv *server) jjLog(w http.ResponseWriter, r *http.Request) {
+ v := sv.jjView(r)
+ if !htmxReq(r) {
+ sv.jjPage(w, r)
+ return
+ }
+ sv.frag(w, "jjrows", v)
+}
+
+func (sv *server) jjOp(w http.ResponseWriter, r *http.Request) {
+ q := r.URL.Query()
+ v := &JJView{Kind: "op", Limit: atoiDefault(q.Get("limit"), defaultLimit)}
+ if v.Limit < 1 || v.Limit > 1000 {
+ v.Limit = defaultLimit
+ }
+ var err error
+ if v.Rows, err = OpRows(sv.repo, v.Limit); err != nil {
+ v.Err = err.Error()
+ }
+ if !htmxReq(r) {
+ p, _, _ := sv.newPage(r, "jj", "jj op log — "+sv.title)
+ p.JJ = v
+ sv.render(w, p)
+ return
+ }
+ sv.frag(w, "jjrows", v)
+}
+
+func (sv *server) changePage(w http.ResponseWriter, r *http.Request) {
+ id := r.PathValue("id")
+ p, site, _ := sv.newPage(r, "change", id+" — "+sv.title)
+ c, err := LoadChange(sv.repo, id)
+ if err != nil {
+ p.Err = err.Error()
+ sv.render(w, p)
+ return
+ }
+ p.Change = c
+ p.Rev, p.ChangeID = c.Row.ID, c.Row.ID
+ p.Title = c.Row.Short + " — " + sv.title
+ p.Notes = site.FilterNotes(NoteFilter{Change: c.Row.ID})
+ sv.render(w, p)
+}
+
+// ── assets ────────────────────────────────────────────────────────────────
+
+func (sv *server) styleCSS(w http.ResponseWriter, r *http.Request) {
+ site, _, _ := sv.snap()
+ var b bytes.Buffer
+ if err := renderCSS(&b, site); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ w.Header().Set("Content-Type", "text/css; charset=utf-8")
+ b.WriteTo(w)
+}
+
+func (sv *server) asset(w http.ResponseWriter, r *http.Request) {
+ name := strings.TrimPrefix(r.URL.Path, "/")
+ b, err := tfs.ReadFile("assets/" + name)
+ if err != nil {
+ http.NotFound(w, r)
+ return
+ }
+ w.Header().Set("Content-Type", "text/javascript; charset=utf-8")
+ w.Header().Set("Cache-Control", "max-age=300")
+ w.Write(b)
+}
+
+func serve(addr, logPath, repo, title, user string, theme, light *Theme) {
+ sv := newServer(logPath, repo, title, user, theme, light)
+ site, _, def := sv.snap()
+ fmt.Printf("vrsite: http://%s — %d notes, %d agents, repo %s at %s\n",
+ addr, len(site.Notes), len(site.Agents), repo, short(def))
+ fmt.Printf("vrsite: comments are appended to %s; the repo is never written to\n", logPath)
+ if err := http.ListenAndServe(addr, sv.handler()); err != nil {
+ fatal("%v", err)
+ }
+}
diff --git a/vrsite/static.go b/vrsite/static.go
new file mode 100644
index 0000000..e4970c6
--- /dev/null
+++ b/vrsite/static.go
@@ -0,0 +1,181 @@
+// static.go — the offline export: the same pages written out as files.
+//
+// Everything that needs a server (comments, live activity, jj queries) is
+// omitted; the trace/notes toggle, the file finder and the note filters all
+// keep working, since they run in the browser.
+package main
+
+import (
+ "bytes"
+ "fmt"
+ "html/template"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "sync"
+ "time"
+)
+
+func run(dir string, name string, args ...string) []byte {
+ cmd := exec.Command(name, args...)
+ cmd.Dir = dir
+ out, err := cmd.Output()
+ if err != nil {
+ if ee, ok := err.(*exec.ExitError); ok {
+ os.Stderr.Write(ee.Stderr)
+ }
+ fatal("%s %s: %v", name, strings.Join(args, " "), err)
+ }
+ return out
+}
+
+func buildSite(logPath, repoAbs, out, title string, theme, light *Theme) {
+ start := time.Now()
+ site := buildModel(title, readLog(logPath))
+ site.Theme, site.Light, site.Repo = theme, light, repoAbs
+ if site.Change == "" {
+ fatal("log has no jj change ids")
+ }
+
+ // every file in the repo at the site change; content comes from one
+ // git archive of the commit instead of a jj spawn per file
+ list, err := jjRun(repoAbs, "file", "list", "-r", site.Change)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ fatal("change %s is not in %s — logs are per repository; point -repo at the one the trace was recorded in", short(site.Change), repoAbs)
+ }
+ site.All = site.filesAt(strings.Split(strings.TrimRight(string(list), "\n"), "\n"), site.Change)
+
+ commit := strings.TrimSpace(string(mustJJ(repoAbs, "log", "-r", site.Change, "--no-graph", "-T", "commit_id")))
+ tmp, err := os.MkdirTemp("", "vrsite-")
+ if err != nil {
+ fatal("%v", err)
+ }
+ defer os.RemoveAll(tmp)
+ archive := exec.Command("git", "-C", repoAbs, "archive", commit)
+ untar := exec.Command("tar", "-x", "-C", tmp)
+ untar.Stdin, _ = archive.StdoutPipe()
+ untar.Stderr = os.Stderr
+ if err := untar.Start(); err != nil {
+ fatal("tar: %v", err)
+ }
+ if err := archive.Run(); err != nil {
+ fatal("git archive %s: %v", short(commit), err)
+ }
+ if err := untar.Wait(); err != nil {
+ fatal("tar: %v", err)
+ }
+
+ writeSite(site, out, tmp)
+ stubs := 0
+ for _, f := range site.All {
+ if f.Stub != "" {
+ stubs++
+ }
+ }
+ fmt.Printf("vrsite: %d files (%d traced, %d not rendered), %d notes, %d agents in %s -> %s\n",
+ len(site.All), len(site.Order), stubs, len(site.Notes), len(site.Agents),
+ time.Since(start).Round(time.Millisecond), out)
+}
+
+func writeSite(site *Site, out, srcDir string) {
+ tpl := newTemplates()
+ if err := os.MkdirAll(out, 0o755); err != nil {
+ fatal("%v", err)
+ }
+
+ each := func(fn func(f *File)) {
+ sem := make(chan struct{}, runtime.NumCPU())
+ var wg sync.WaitGroup
+ for _, f := range site.All {
+ wg.Add(1)
+ sem <- struct{}{}
+ go func(f *File) {
+ defer func() { <-sem; wg.Done() }()
+ fn(f)
+ }(f)
+ }
+ wg.Wait()
+ }
+ // phase A: content — coverage percentages must exist before any tree
+ // or index below is written
+ hl := newHighlighter(site.Theme, site.Light)
+ each(func(f *File) {
+ src, err := os.ReadFile(filepath.Join(srcDir, f.Path))
+ switch {
+ case err != nil:
+ f.Stub = "not present in the archived commit"
+ case bytes.IndexByte(src, 0) >= 0:
+ f.Stub = "binary file — not rendered"
+ case len(src) > 2<<20:
+ f.Stub = fmt.Sprintf("file too large to render (%d KB)", len(src)/1024)
+ default:
+ f.render(src, hl)
+ }
+ })
+
+ cf := mustCreate(filepath.Join(out, "style.css"))
+ if err := renderCSS(cf, site); err != nil {
+ fatal("css: %v", err)
+ }
+ cf.Close()
+ for _, name := range []string{"app.js"} {
+ b, err := tfs.ReadFile("assets/" + name)
+ if err != nil {
+ fatal("%v", err)
+ }
+ if err := os.WriteFile(filepath.Join(out, name), b, 0o644); err != nil {
+ fatal("%v", err)
+ }
+ }
+
+ // shared tree fragment: the only nav tree, fetched by every page; "@@" is
+ // replaced with the page root by app.js, since the fragment is fetched
+ // from any page depth
+ treeFrag := renderTree(site.All, func(p string) string { return "@@code/" + p + ".html" })
+ if err := os.WriteFile(filepath.Join(out, "tree.html"), []byte(treeFrag), 0o644); err != nil {
+ fatal("%v", err)
+ }
+
+ facets := site.Facets()
+ render := func(path string, p *page) {
+ p.Site, p.Facets, p.ChangeID = site, facets, site.Change
+ f := mustCreate(path)
+ if err := tpl.Execute(f, p); err != nil {
+ fatal("render %s: %v", path, err)
+ }
+ f.Close()
+ }
+
+ latest := site.FilterNotes(NoteFilter{})
+ if len(latest) > 24 {
+ latest = latest[:24]
+ }
+ render(filepath.Join(out, "index.html"), &page{Kind: "index", Title: site.Title, Notes: latest})
+
+ fullTree := renderTree(site.All, func(p string) string { return "code/" + p + ".html" })
+ render(filepath.Join(out, "files.html"), &page{Kind: "files", Title: "files — " + site.Title,
+ Tree: template.HTML(fullTree)})
+
+ render(filepath.Join(out, "notes.html"), &page{Kind: "notes", Title: "notes — " + site.Title,
+ Notes: site.FilterNotes(NoteFilter{})})
+
+ // phase B: every file page, in parallel
+ each(func(f *File) {
+ dst := filepath.Join(out, "code", f.Path+".html")
+ os.MkdirAll(filepath.Dir(dst), 0o755)
+ depth := strings.Count(f.Path, "/") + 1
+ render(dst, &page{Kind: "file", Title: f.Path + " — " + site.Title,
+ Root: strings.Repeat("../", depth), Current: f.Path, File: f})
+ })
+}
+
+func mustCreate(path string) *os.File {
+ f, err := os.Create(path)
+ if err != nil {
+ fatal("%v", err)
+ }
+ return f
+}
diff --git a/vrsite/templates/frag-activity.tmpl b/vrsite/templates/frag-activity.tmpl
new file mode 100644
index 0000000..8c15de7
--- /dev/null
+++ b/vrsite/templates/frag-activity.tmpl
@@ -0,0 +1,34 @@
+{{/* Who is reading the codebase right now, straight off the log tail. */}}
+{{define "activity"}}
+{{if .Compact}}
+ <div class="actlist">
+ {{range .Sessions}}
+ <div class="act{{if .Live}} on{{end}}" title="{{.Agent}} · {{.Model}} · {{.Dir}}">
+ <span class="chip am{{.Bit}}">{{.Short}}</span>
+ <span class="what">{{.LastOp}}</span>
+ <span class="when">{{.Ago}}</span>
+ </div>
+ {{end}}
+ {{if not .Sessions}}<p class="meta hint">nothing logged yet</p>{{end}}
+ </div>
+{{else}}
+ <table class="acttable">
+ <thead><tr><th>agent</th><th>model</th><th>session</th><th>last op</th><th>when</th><th>r/g/n</th><th>dir</th></tr></thead>
+ <tbody>
+ {{range .Sessions}}
+ <tr class="{{if .Live}}on{{end}}">
+ <td><span class="chip am{{.Bit}}">{{.Short}}</span>{{if .Live}}<span class="pulse" title="active">●</span>{{end}}</td>
+ <td>{{.Model}}{{if .Reason}}<span class="meta">/{{.Reason}}</span>{{end}}</td>
+ <td><code title="{{.ID}}">{{short .ID}}</code></td>
+ <td class="what">{{.LastOp}}</td>
+ <td>{{.Ago}}</td>
+ <td class="meta">{{.Reads}}/{{.Greps}}/{{.Notes}}</td>
+ <td class="meta dir" title="{{.Dir}}">{{base .Dir}}</td>
+ </tr>
+ {{end}}
+ </tbody>
+ </table>
+ {{if not .Sessions}}<p class="meta hint">nothing logged yet</p>{{end}}
+ <p class="meta">live = active in the last {{.Window}}</p>
+{{end}}
+{{end}}
diff --git a/vrsite/templates/frag-jj.tmpl b/vrsite/templates/frag-jj.tmpl
new file mode 100644
index 0000000..b31af53
--- /dev/null
+++ b/vrsite/templates/frag-jj.tmpl
@@ -0,0 +1,33 @@
+{{/* jj query results. Live-only, so routes are absolute. */}}
+{{define "jjrows"}}
+{{if .Err}}<p class="err">{{.Err}}</p>{{end}}
+{{if .Rows}}
+<div class="jjlog">
+ {{range .Rows}}
+ {{if .Blank}}<div class="jjrow blank"><span class="graph">{{.Graph}}</span></div>
+ {{else if .Op}}
+ <div class="jjrow">
+ <span class="graph">{{.Graph}}</span>
+ <a class="id" href="/jj?at_op={{.ID}}" title="run the commit log as of this operation">{{.Short}}</a>
+ <span class="when">{{.When}}</span>
+ <span class="who">{{.Author}}</span>
+ <span class="desc">{{.Desc}}</span>
+ <span class="flags">{{.End}}</span>
+ </div>
+ {{else}}
+ <div class="jjrow">
+ <span class="graph">{{.Graph}}</span>
+ <a class="id" href="/change/{{.ID}}" title="{{.ID}}">{{.Short}}</a>
+ <code class="commit">{{.CommitShort}}</code>
+ <span class="when">{{.When}}</span>
+ <span class="who">{{.Author}}</span>
+ {{if .Refs}}<span class="refs">{{.Refs}}</span>{{end}}
+ {{if .Flags}}<span class="flags">{{.Flags}}</span>{{end}}
+ <a class="desc" href="/files?rev={{.ID}}" title="browse the tree at this change">{{if .Desc}}{{.Desc}}{{else}}(no description){{end}}</a>
+ </div>
+ {{end}}
+ {{end}}
+</div>
+{{else if not .Err}}<p class="meta hint">no revisions matched</p>{{end}}
+{{if .AtOp}}<p class="meta">as of operation <code>{{short .AtOp}}</code> · <a href="/jj?kind=op">back to the op log</a></p>{{end}}
+{{end}}
diff --git a/vrsite/templates/frag-note.tmpl b/vrsite/templates/frag-note.tmpl
new file mode 100644
index 0000000..56f7a8f
--- /dev/null
+++ b/vrsite/templates/frag-note.tmpl
@@ -0,0 +1,52 @@
+{{define "note"}}{{$n := .N}}{{$p := .P}}
+<article class="note am{{$n.Agent.Bit}}" id="note-{{$n.ID}}"
+ data-agent="{{$n.Agent.Name}}" data-model="{{$n.Model}}" data-session="{{$n.Session}}"
+ data-kind="{{$n.Kind}}" data-file="{{$n.File}}" data-date="{{if not $n.At.IsZero}}{{$n.At.Format "2006-01-02"}}{{end}}">
+ <header>
+ {{if $n.File}}<a href="{{$p.NoteHref $n}}" title="{{$n.File}}">{{base $n.File}}{{lines $n}}</a>{{end}}
+ {{if $n.Kind}}<em>{{$n.Kind}}</em>{{end}}
+ <b class="who">{{$n.Agent.Short}}</b>
+ </header>
+ <p>{{$n.Text}}</p>
+ <footer class="meta">
+ {{if not $n.At.IsZero}}<time datetime="{{$n.At.Format "2006-01-02T15:04:05Z07:00"}}" title="{{$n.Ago}}">{{$n.When}}</time>{{end}}
+ {{if $n.Model}}<span class="model">{{$n.Model}}{{if $n.Reason}}/{{$n.Reason}}{{end}}</span>{{end}}
+ {{if $n.Session}}<code class="sess" title="{{$n.Session}}">{{short $n.Session}}</code>{{end}}
+ {{if $n.Change}}{{if $p.Live}}<a href="{{$p.Href "change" $n.Change}}"><code>{{short $n.Change}}</code></a>{{else}}<code>{{short $n.Change}}</code>{{end}}{{end}}
+ </footer>
+</article>
+{{end}}
+
+{{define "notelist"}}{{range .Notes}}{{template "note" (dict "N" . "P" $)}}{{end}}{{if not .Notes}}<p class="meta hint empty">no notes match these filters</p>{{end}}{{end}}
+
+{{/* htmx responses: the list plus an out-of-band count update */}}
+{{define "notelist-oob"}}<span id="notecount" hx-swap-oob="true">{{len .Notes}}</span>{{template "notelist" .}}{{end}}
+
+{{define "note-added"}}{{if .File}}<span id="notecount" hx-swap-oob="true">{{len .File.Notes}}</span>{{end}}{{range .Notes}}{{template "note" (dict "N" . "P" $)}}{{end}}{{end}}
+
+{{/* the add-a-comment form; live pages only, since it writes to the log */}}
+{{define "noteform"}}
+<form class="notform" hx-post="{{.Href "notes"}}" hx-target="#notelist" hx-swap="afterbegin"
+ hx-on::after-request="if(event.detail.successful){this.reset();{{if eq .Kind "notes"}}htmx.trigger('#notefilters','change');{{end}}}"
+ method="post" action="{{.Href "notes"}}">
+ <input type="hidden" name="rev" value="{{.Rev}}">
+ <input type="hidden" name="back" value="{{if .File}}{{.Href "code" .File.Path}}{{else}}{{.Href "notes"}}{{end}}">
+ <div class="row">
+ {{if .File}}
+ <input type="hidden" name="file" value="{{.File.Path}}">
+ <span class="meta on">on <code>{{base .File.Path}}</code></span>
+ {{else}}
+ <input type="search" name="file" placeholder="file (optional)" list="filelist" autocomplete="off">
+ {{end}}
+ <input type="number" id="nstart" name="start" min="1" placeholder="from" aria-label="first line">
+ <input type="number" id="nend" name="end" min="1" placeholder="to" aria-label="last line">
+ <input type="text" name="kind" placeholder="kind" aria-label="kind" list="kindlist" size="6">
+ </div>
+ <textarea name="text" rows="3" placeholder="comment… (⌘/ctrl+enter to post)" required></textarea>
+ <div class="row end">
+ <span class="meta">as <b>{{.User}}</b> → the log</span>
+ <button type="submit">add note</button>
+ </div>
+</form>
+<datalist id="kindlist">{{range .Facets.Kinds}}<option value="{{.}}">{{end}}</datalist>
+{{end}}
diff --git a/vrsite/templates/layout.tmpl b/vrsite/templates/layout.tmpl
new file mode 100644
index 0000000..c3fe250
--- /dev/null
+++ b/vrsite/templates/layout.tmpl
@@ -0,0 +1,71 @@
+<!doctype html>
+<html lang="en"{{if .Live}} data-live="1"{{end}}>
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>{{.Title}}</title>
+<script>
+{const d = document.documentElement, t = localStorage.getItem("vrsite-theme");
+ if (t && t !== "system") d.dataset.theme = t;
+ d.dataset.mode = localStorage.getItem("vrsite-mode") || "trace";}
+</script>
+<link rel="stylesheet" href="{{.Href "asset" "style.css"}}">
+{{if .Live}}<script src="{{.Href "asset" "htmx.min.js"}}"></script>{{end}}
+<script src="{{.Href "asset" "app.js"}}" defer></script>
+</head>
+<body{{if eq .Kind "file"}} class="with-aside"{{end}} data-kind="{{.Kind}}">
+
+<nav aria-label="repository files" id="nav" data-root="{{.Root}}" data-current="{{.Current}}" data-tree="{{.Href "tree"}}">
+ <header>
+ <a class="brand" href="{{.Href ""}}">{{.Site.Title}}</a>
+ <div class="modes" role="group" aria-label="focus">
+ <button type="button" class="mode" data-mode="trace" title="reading coverage (t)">trace</button>
+ <button type="button" class="mode" data-mode="notes" title="notes and comments (t)">notes</button>
+ </div>
+ </header>
+ {{if and .Live .Rev}}
+ <p class="meta atrev">browsing <a href="{{.Href "change" .ChangeID}}"><code>{{short .ChangeID}}</code></a> · <a href="/">back to @</a></p>
+ {{end}}
+ {{if .Live}}
+ <div id="activity" class="activity" hx-get="/activity?compact=1" hx-trigger="load, every 3s" hx-swap="innerHTML"></div>
+ {{end}}
+ <input id="filefind" class="find" type="search" placeholder="find file…" aria-label="find file" autocomplete="off" spellcheck="false">
+ <div id="tree"><p class="meta hint">loading tree…</p></div>
+ <footer>
+ <span>
+ <a href="{{.Href "notes"}}">notes ({{len .Site.Notes}})</a> ·
+ <a href="{{.Href "files"}}">files</a>{{if .Live}} ·
+ <a href="{{.Href "jj"}}">jj</a>{{end}}
+ </span>
+ <select id="themesel" aria-label="color scheme">
+ <option value="system">system</option>
+ <option value="dark">dark</option>
+ <option value="light">light</option>
+ </select>
+ </footer>
+</nav>
+
+<main>
+{{if .Err}}<p class="err">{{.Err}}</p>{{end}}
+{{if eq .Kind "file"}}{{template "page-file" .}}
+{{else if eq .Kind "notes"}}{{template "page-notes" .}}
+{{else if eq .Kind "files"}}{{template "page-files" .}}
+{{else if eq .Kind "jj"}}{{template "page-jj" .}}
+{{else if eq .Kind "change"}}{{template "page-change" .}}
+{{else}}{{template "page-index" .}}{{end}}
+</main>
+
+{{if eq .Kind "file"}}
+<aside aria-label="notes" class="notes-only">
+ <header class="asidehead">
+ <b>Notes (<span id="notecount">{{len .File.Notes}}</span>)</b>
+ {{if .Live}}<span class="meta">click a line to attach</span>{{end}}
+ </header>
+ {{if .Live}}{{template "noteform" .}}{{end}}
+ <div id="notelist">{{range .File.Notes}}{{template "note" (dict "N" . "P" $)}}{{end}}</div>
+ {{if not .File.Notes}}<p class="meta hint">no notes on this file yet</p>{{end}}
+</aside>
+{{end}}
+
+</body>
+</html>
diff --git a/vrsite/templates/page-change.tmpl b/vrsite/templates/page-change.tmpl
new file mode 100644
index 0000000..08310e5
--- /dev/null
+++ b/vrsite/templates/page-change.tmpl
@@ -0,0 +1,37 @@
+{{define "page-change"}}
+{{$c := .Change}}
+<header class="filehead">
+ <h1>{{$c.Row.Short}} <span class="meta">{{$c.Row.Flags}}</span></h1>
+ <p class="meta">
+ commit <code>{{$c.Row.CommitShort}}</code> · {{$c.Row.Author}} · {{$c.Row.When}}
+ {{if $c.Row.Refs}} · <span class="refs">{{$c.Row.Refs}}</span>{{end}} ·
+ <a href="{{.Href "files" }}">browse the tree here</a>
+ </p>
+</header>
+
+<section>
+ {{if $c.Desc}}<pre class="desc">{{$c.Desc}}</pre>{{else}}<p class="meta hint">(no description set)</p>{{end}}
+
+ {{if $c.Parents}}
+ <p class="meta">parents:
+ {{range $c.Parents}}<a href="/change/{{.ID}}"><code>{{.Short}}</code></a> {{.Desc}} {{end}}
+ </p>
+ {{end}}
+
+ <h2>Changed files <span class="meta">{{$c.Stat}}</span></h2>
+ {{if $c.Files}}
+ <table class="changed">
+ <tbody>
+ {{range $c.Files}}
+ <tr><td class="st st-{{.Status}}">{{.Status}}</td>
+ <td><a href="/code/{{.Path}}?rev={{$c.Row.ID}}">{{.Path}}</a></td></tr>
+ {{end}}
+ </tbody>
+ </table>
+ {{else}}<p class="meta hint">no file changes</p>{{end}}
+
+ <h2>Notes recorded at this change <span class="meta">{{len .Notes}}</span></h2>
+ <div class="notecols">{{range .Notes}}{{template "note" (dict "N" . "P" $)}}{{end}}</div>
+ {{if not .Notes}}<p class="meta hint">nothing in the log was written while this change was checked out</p>{{end}}
+</section>
+{{end}}
diff --git a/vrsite/templates/page-file.tmpl b/vrsite/templates/page-file.tmpl
new file mode 100644
index 0000000..39a8c44
--- /dev/null
+++ b/vrsite/templates/page-file.tmpl
@@ -0,0 +1,20 @@
+{{define "page-file"}}
+<header class="filehead">
+ <h1>{{.File.Path}}</h1>
+ <p class="meta">
+ {{if .File.Traced}}
+ {{range .Site.Agents}}{{if band $.File.Mask .Bit}}<span class="chip am{{.Bit}}">{{.Short}}</span> {{end}}{{end}}
+ <span class="trace-only"><data value="{{.File.Pct}}">{{.File.Pct}}% read</data> ·
+ {{.File.Reads}} reads · {{.File.Greps}} greps · </span>
+ <span class="notes-only">{{len .File.Notes}} note{{if ne (len .File.Notes) 1}}s{{end}} · </span>
+ {{else}}not traced · {{end}}change
+ {{if .Live}}<a href="{{.Href "change" .File.Change}}"><code>{{short .File.Change}}</code></a>{{else}}<code>{{short .File.Change}}</code>{{end}}
+ </p>
+ {{if .File.Patterns}}<p class="meta greps trace-only">grepped: {{range .File.Patterns}}<code>{{.}}</code> {{end}}</p>{{end}}
+</header>
+{{if .File.Stub}}
+<p class="meta stub">{{.File.Stub}}</p>
+{{else}}
+<div class="codewrap">{{.File.Body}}</div>
+{{end}}
+{{end}}
diff --git a/vrsite/templates/page-files.tmpl b/vrsite/templates/page-files.tmpl
new file mode 100644
index 0000000..53757ea
--- /dev/null
+++ b/vrsite/templates/page-files.tmpl
@@ -0,0 +1,13 @@
+{{define "page-files"}}
+<header class="filehead">
+ <h1>Files</h1>
+ <p class="meta">
+ everything at change <code>{{short .ChangeID}}</code> ·
+ <span class="trace-only">traced files carry a coverage bar</span>
+ <span class="notes-only">◆ marks files with notes</span>
+ </p>
+</header>
+<section class="filetree">
+{{.Tree}}
+</section>
+{{end}}
diff --git a/vrsite/templates/page-index.tmpl b/vrsite/templates/page-index.tmpl
new file mode 100644
index 0000000..2c115cc
--- /dev/null
+++ b/vrsite/templates/page-index.tmpl
@@ -0,0 +1,52 @@
+{{define "page-index"}}
+<header class="filehead">
+ <h1>{{.Site.Title}}</h1>
+ <p class="meta">
+ {{len .Site.All}} files, {{len .Site.Order}} traced · {{len .Site.Notes}} notes ·
+ change <code>{{short .Site.Change}}</code> · theme {{.Site.Theme.Name}}
+ </p>
+</header>
+
+{{if .Live}}
+<section>
+ <h2>Live <span class="meta">— agents reading this codebase</span></h2>
+ <div id="activity-full" hx-get="/activity" hx-trigger="load, every 3s" hx-swap="innerHTML">
+ <p class="meta hint">…</p>
+ </div>
+</section>
+{{end}}
+
+<section class="trace-only">
+ <h2>Agents</h2>
+ <table>
+ <thead><tr><th>agent</th><th>model</th><th>effort</th><th>session</th><th>reads</th><th>greps</th><th>notes</th></tr></thead>
+ <tbody>
+ {{range .Site.Agents}}
+ <tr><td><span class="chip am{{.Bit}}">{{.Short}}</span></td>
+ <td>{{.Model}}</td><td>{{.Reason}}</td><td><code>{{short .Session}}</code></td>
+ <td>{{.Reads}}</td><td>{{.Greps}}</td><td>{{.Notes}}</td></tr>
+ {{end}}
+ </tbody>
+ </table>
+</section>
+
+<section class="trace-only">
+ <h2>Coverage</h2>
+ <table>
+ <thead><tr><th>file</th><th>read</th><th>lines</th><th>notes</th></tr></thead>
+ <tbody>
+ {{range .Site.Order}}{{with index $.Site.Files .}}
+ <tr><td><a href="{{$.Href "code" .Path}}">{{.Path}}</a></td>
+ <td><data class="bar am{{.Mask}}" value="{{.Pct}}" style="--pct:{{.Pct}}%">{{.Pct}}%</data></td>
+ <td>{{.Covered}}/{{.Total}}</td><td>{{len .Notes}}</td></tr>
+ {{end}}{{end}}
+ </tbody>
+ </table>
+</section>
+
+<section class="notes-only">
+ <h2>Latest notes <span class="meta">— <a href="{{.Href "notes"}}">all {{len .Site.Notes}}, with filters</a></span></h2>
+ <div class="notecols">{{range .Notes}}{{template "note" (dict "N" . "P" $)}}{{end}}</div>
+ {{if not .Notes}}<p class="meta hint">no notes in the log yet</p>{{end}}
+</section>
+{{end}}
diff --git a/vrsite/templates/page-jj.tmpl b/vrsite/templates/page-jj.tmpl
new file mode 100644
index 0000000..5c1381c
--- /dev/null
+++ b/vrsite/templates/page-jj.tmpl
@@ -0,0 +1,25 @@
+{{define "page-jj"}}
+<header class="filehead">
+ <h1>jj</h1>
+ <p class="meta">
+ read-only queries against the repo — <code>--ignore-working-copy</code>, inline templates, nothing written to disk
+ </p>
+</header>
+
+<section class="jjpage">
+ <form class="jjform" method="get" action="{{.Href "jj"}}"
+ hx-get="/jj/log" hx-target="#jjout" hx-swap="innerHTML" hx-indicator="#jjbusy">
+ <input type="hidden" name="kind" value="log">
+ <input type="search" name="revset" value="{{.JJ.Revset}}" placeholder="revset — e.g. @ | ancestors(trunk(), 10) | description(glob:'*fix*')" autocomplete="off" spellcheck="false">
+ <input type="number" name="limit" value="{{.JJ.Limit}}" min="1" max="1000" aria-label="limit" title="limit">
+ <button type="submit">jj log</button>
+ <button type="button" hx-get="/jj/op" hx-target="#jjout" hx-include="closest form" hx-indicator="#jjbusy" title="operation log">op log</button>
+ <span id="jjbusy" class="busy">·</span>
+ </form>
+ <p class="meta hint">
+ change ids open the change · descriptions browse the tree at that change ·
+ op ids re-run the query <code>--at-operation</code>, which is how you see the repo as it was
+ </p>
+ <div id="jjout">{{template "jjrows" .JJ}}</div>
+</section>
+{{end}}
diff --git a/vrsite/templates/page-notes.tmpl b/vrsite/templates/page-notes.tmpl
new file mode 100644
index 0000000..974dc64
--- /dev/null
+++ b/vrsite/templates/page-notes.tmpl
@@ -0,0 +1,43 @@
+{{define "facet"}}<select name="{{.Name}}" aria-label="{{.Label}}">
+ <option value="">{{.Label}}</option>
+ {{range .Values}}<option value="{{.}}"{{if eq . $.Sel}} selected{{end}}>{{if $.Short}}{{short .}}…{{else}}{{.}}{{end}}</option>
+ {{end}}</select>{{end}}
+
+{{define "page-notes"}}
+<header class="filehead">
+ <h1>Notes</h1>
+ <p class="meta">
+ {{len .Site.Notes}} in the log{{if .Live}} · anything you add here is appended to the log — the repo is never touched{{end}}
+ </p>
+</header>
+
+<section class="notespage">
+ {{if .Live}}
+ <details class="addnote">
+ <summary>add a note</summary>
+ {{template "noteform" .}}
+ </details>
+ {{end}}
+
+ <form class="filters" id="notefilters" method="get" action="{{.Href "notes"}}"
+ {{if .Live}}hx-get="/notes/list" hx-target="#notelist" hx-swap="innerHTML"
+ hx-trigger="input delay:250ms, change, search" hx-indicator="#notesbusy"{{end}}>
+ <input type="search" name="text" value="{{.Filter.Text}}" placeholder="search note text…" autocomplete="off">
+ <input type="search" name="file" value="{{.Filter.File}}" placeholder="file path…" list="filelist" autocomplete="off">
+ {{template "facet" (dict "Name" "agent" "Label" "any agent" "Values" .Facets.Agents "Sel" .Filter.Agent)}}
+ {{template "facet" (dict "Name" "model" "Label" "any model" "Values" .Facets.Models "Sel" .Filter.Model)}}
+ {{template "facet" (dict "Name" "session" "Label" "any session" "Values" .Facets.Sessions "Sel" .Filter.Session "Short" true)}}
+ {{template "facet" (dict "Name" "kind" "Label" "any kind" "Values" .Facets.Kinds "Sel" .Filter.Kind)}}
+ <span class="dates">
+ <label class="datef">from <input type="date" name="from" value="{{.Filter.From}}"></label>
+ <label class="datef">to <input type="date" name="to" value="{{.Filter.To}}"></label>
+ </span>
+ <button type="submit" class="nohx">filter</button>
+ <button type="button" id="clearfilters">clear</button>
+ </form>
+ <datalist id="filelist">{{range .Facets.Files}}<option value="{{.}}">{{end}}</datalist>
+
+ <p class="meta count"><span id="notesbusy" class="busy">·</span><span id="notecount">{{len .Notes}}</span> notes shown</p>
+ <div id="notelist">{{template "notelist" .}}</div>
+</section>
+{{end}}
diff --git a/vrsite/theme.go b/vrsite/theme.go
new file mode 100644
index 0000000..fc63de1
--- /dev/null
+++ b/vrsite/theme.go
@@ -0,0 +1,194 @@
+// theme.go — Zed theme JSON in, CSS custom properties out. Per-agent colors
+// come from the theme's player (collaborator) palette.
+package main
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+)
+
+type SyntaxStyle struct {
+ Color string `json:"color"`
+ FontStyle *string `json:"font_style"`
+ FontWeight *float64 `json:"font_weight"`
+}
+
+type Theme struct {
+ Name, Appearance string
+ Bg, Fg, Panel, Border, LineNo, Muted, Accent string
+ Note, Hover string
+ Syntax map[string]SyntaxStyle
+ Players []string
+}
+
+// defaultTheme finds a zed theme file containing a theme of the wanted
+// appearance; "" means fall back to the embedded One family.
+func defaultTheme(appearance string) string {
+ home, _ := os.UserHomeDir()
+ m, _ := filepath.Glob(filepath.Join(home, ".config", "zed", "themes", "*.json"))
+ for _, path := range m {
+ b, err := os.ReadFile(path)
+ if err != nil {
+ continue
+ }
+ var family struct {
+ Themes []struct {
+ Appearance string `json:"appearance"`
+ } `json:"themes"`
+ }
+ if json.Unmarshal(b, &family) != nil {
+ continue
+ }
+ for _, t := range family.Themes {
+ if t.Appearance == appearance {
+ return path
+ }
+ }
+ }
+ return ""
+}
+
+func loadTheme(path, name, appearance string) *Theme {
+ var b []byte
+ var err error
+ if path == "" {
+ b, err = tfs.ReadFile("assets/one.json")
+ } else {
+ b, err = os.ReadFile(path)
+ }
+ if err != nil {
+ fatal("%v", err)
+ }
+ var family struct {
+ Name string `json:"name"`
+ Themes []struct {
+ Name string `json:"name"`
+ Appearance string `json:"appearance"`
+ Style map[string]json.RawMessage `json:"style"`
+ } `json:"themes"`
+ }
+ if err := json.Unmarshal(b, &family); err != nil || len(family.Themes) == 0 {
+ fatal("bad zed theme %s: %v", path, err)
+ }
+ th := family.Themes[0]
+ if name != "" {
+ for _, t := range family.Themes {
+ if t.Name == name {
+ th = t
+ }
+ }
+ } else {
+ for _, t := range family.Themes {
+ if t.Appearance == appearance {
+ th = t
+ break
+ }
+ }
+ }
+ get := func(keys ...string) string {
+ for _, k := range keys {
+ var s string
+ if raw, ok := th.Style[k]; ok && json.Unmarshal(raw, &s) == nil && s != "" {
+ return s
+ }
+ }
+ return ""
+ }
+ t := &Theme{Name: th.Name, Appearance: th.Appearance,
+ Bg: get("editor.background", "background"),
+ Fg: get("editor.foreground", "text"),
+ Panel: get("panel.background", "surface.background", "background"),
+ Border: get("border", "border.variant"),
+ LineNo: get("editor.line_number"),
+ Muted: get("text.muted", "text.disabled"),
+ Accent: get("text.accent", "info"),
+ Note: get("warning", "conflict", "modified"),
+ Hover: get("element.hover", "ghost_element.hover"),
+ }
+ json.Unmarshal(th.Style["syntax"], &t.Syntax)
+ var players []struct {
+ Cursor string `json:"cursor"`
+ }
+ json.Unmarshal(th.Style["players"], &players)
+ // agent colors: drop player colors that vanish against fg/bg or collide
+ // with the note color, then order greedily for mutual distance so the
+ // first few agents contrast most
+ var usable []string
+ for _, p := range players {
+ c := hex6(p.Cursor)
+ if c != "" && colorDist(c, hex6(t.Fg)) > 60 && colorDist(c, hex6(t.Bg)) > 60 && colorDist(c, hex6(t.Note)) > 60 {
+ usable = append(usable, c)
+ }
+ }
+ for len(usable) > 0 {
+ best, bestScore := 0, -1
+ for i, c := range usable {
+ score := 1 << 24 // first pick: keep theme order
+ for _, p := range t.Players {
+ if d := colorDist(c, p); d < score {
+ score = d
+ }
+ }
+ if score > bestScore {
+ best, bestScore = i, score
+ }
+ }
+ t.Players = append(t.Players, usable[best])
+ usable = append(usable[:best], usable[best+1:]...)
+ }
+ return t
+}
+
+func colorDist(a, b string) int {
+ var ar, ag, ab, br, bg, bb int
+ if len(a) != 7 || len(b) != 7 {
+ return 1 << 24
+ }
+ fmt.Sscanf(a[1:], "%02x%02x%02x", &ar, &ag, &ab)
+ fmt.Sscanf(b[1:], "%02x%02x%02x", &br, &bg, &bb)
+ d := func(x, y int) int { return (x - y) * (x - y) }
+ return int(float64(d(ar, br)+d(ag, bg)+d(ab, bb)) / 3)
+}
+
+var fallbackPalette = []string{"#7aa2f7", "#e0af68", "#9ece6a", "#f7768e", "#bb9af7", "#2ac3de"}
+
+func (t *Theme) Player(i int) string {
+ if i < len(t.Players) {
+ return t.Players[i]
+ }
+ return fallbackPalette[i%len(fallbackPalette)]
+}
+
+// hex6 strips an alpha channel from #rrggbbaa.
+func hex6(c string) string {
+ if len(c) == 9 && c[0] == '#' {
+ return c[:7]
+ }
+ return c
+}
+
+func mixColors(cols []string) string {
+ if len(cols) == 1 {
+ return cols[0]
+ }
+ var r, g, b int
+ n := 0
+ for _, c := range cols {
+ c = hex6(c)
+ if len(c) != 7 {
+ continue
+ }
+ var cr, cg, cb int
+ fmt.Sscanf(c[1:], "%02x%02x%02x", &cr, &cg, &cb)
+ r += cr
+ g += cg
+ b += cb
+ n++
+ }
+ if n == 0 {
+ return "#888888"
+ }
+ return fmt.Sprintf("#%02x%02x%02x", r/n, g/n, b/n)
+}
diff --git a/vrsite/tree.go b/vrsite/tree.go
new file mode 100644
index 0000000..e7891c6
--- /dev/null
+++ b/vrsite/tree.go
@@ -0,0 +1,115 @@
+// tree.go — the repository tree, one fragment shared by every page.
+package main
+
+import (
+ "fmt"
+ "html"
+ "path/filepath"
+ "strings"
+)
+
+type treeNode struct {
+ Name string
+ Dirs []*treeNode
+ Files []*File
+ Mask uint8 // union of traced masks underneath
+ HasNotes bool
+ HasTraced bool
+}
+
+func aggregate(n *treeNode) {
+ for _, f := range n.Files {
+ if f.Traced {
+ n.HasTraced = true
+ n.Mask |= f.Mask
+ if len(f.Notes) > 0 {
+ n.HasNotes = true
+ }
+ }
+ }
+ for _, d := range n.Dirs {
+ aggregate(d)
+ n.Mask |= d.Mask
+ n.HasNotes = n.HasNotes || d.HasNotes
+ n.HasTraced = n.HasTraced || d.HasTraced
+ }
+}
+
+func buildTree(files []*File) *treeNode {
+ root := &treeNode{}
+ for _, f := range files {
+ parts := strings.Split(f.Path, "/")
+ node := root
+ for _, d := range parts[:len(parts)-1] {
+ var next *treeNode
+ for _, c := range node.Dirs {
+ if c.Name == d {
+ next = c
+ }
+ }
+ if next == nil {
+ next = &treeNode{Name: d}
+ node.Dirs = append(node.Dirs, next)
+ }
+ node = next
+ }
+ node.Files = append(node.Files, f)
+ }
+ return root
+}
+
+// treeHTML renders one unified tree: traced files carry coverage bars, dirs
+// with traced content underneath get a mixed-color dot (and ◆ for notes) and
+// default open. prefix is the dir path so far, used for state persistence;
+// link maps a repo path to the href for that file's page.
+func treeHTML(b *strings.Builder, n *treeNode, link func(path string) string, prefix string) {
+ for _, d := range n.Dirs {
+ dp := d.Name
+ if prefix != "" {
+ dp = prefix + "/" + d.Name
+ }
+ openAttr, cls := "", ""
+ if d.HasTraced {
+ openAttr, cls = " open", ` class="t"`
+ }
+ fmt.Fprintf(b, `<details%s%s data-path="%s"><summary>%s`, cls, openAttr, html.EscapeString(dp), html.EscapeString(d.Name))
+ if d.HasTraced {
+ fmt.Fprintf(b, `<span class="dot trace-only am%d"></span>`, d.Mask)
+ }
+ if d.HasNotes {
+ b.WriteString(`<span class="nmark notes-only">◆</span>`)
+ }
+ b.WriteString(`</summary>`)
+ treeHTML(b, d, link, dp)
+ b.WriteString(`</details>`)
+ }
+ if len(n.Files) == 0 {
+ return
+ }
+ b.WriteString("<ul>")
+ for _, f := range n.Files {
+ name := html.EscapeString(filepath.Base(f.Path))
+ path := html.EscapeString(f.Path)
+ if !f.Traced {
+ fmt.Fprintf(b, `<li><a class="file plain" data-path="%s" href="%s">%s</a></li>`, path, html.EscapeString(link(f.Path)), name)
+ continue
+ }
+ noted := ""
+ if len(f.Notes) > 0 {
+ noted = " has-notes"
+ }
+ fmt.Fprintf(b,
+ `<li><a class="file am%d%s" data-path="%s" href="%s" style="--pct:%d%%" title="%d%% read, %d notes">%s</a></li>`,
+ f.Mask, noted, path, html.EscapeString(link(f.Path)), f.Pct, f.Pct, len(f.Notes), name)
+ }
+ b.WriteString("</ul>")
+}
+
+// renderTree is the whole fragment for a file set.
+func renderTree(files []*File, link func(string) string) string {
+ root := buildTree(files)
+ aggregate(root)
+ var b strings.Builder
+ treeHTML(&b, root, link, "")
+ return b.String()
+}