From 5ec72f8723d795d0b02d7e9ebb9f555f0c7e6a2e Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 2 Aug 2026 23:43:08 -0300 Subject: rebrand to notevi: one CLI over the jj sidecar vr and vrsite become a single binary. vrsite/ folds into a web package in one module (0x4200.cafe/notevi); "notevi web" serves and exports exactly what vrsite did, and "notevi read/grep/note/query" is unchanged. The sidecar is renamed with it: notevi_log, notevi-log.jsonl, and the description "private: notevi log". The pre-rebrand names are still recognized, so an old repository opens and reads; it is renamed in place on the first write, or up front with "notevi migrate DIR...". That rename cannot be a single mv inside jj run. jj only auto-tracks a *new* file in the run working copy below a size limit it does not take from the command line, so writing a whole log under a name the change has never held is silently dropped while jj reports success. ensureLogFile creates the file empty first and lets every later byte be a modification of a tracked file, which snapshots at any size; that also fixes the same latent bug when importing a large legacy vr-log.jsonl. Adds a bem-te-vi mark (favicon and nav brand) and a README. Co-Authored-By: Claude Opus 5 (1M context) --- .gitignore | 3 +- README.md | 125 +++++ constrain/AGENTS.md | 14 +- constrain/README.txt | 57 +- constrain/claude-headless-settings.json | 4 +- constrain/claude-settings.json | 4 +- constrain/notevi-only-guard.sh | 19 + constrain/notevi-only.rules | 44 ++ constrain/vr-only-guard.sh | 19 - constrain/vr-only.rules | 44 -- doc.txt | 36 +- go.mod | 24 +- go.sum | 46 ++ main.go | 84 ++- query-doc.txt | 18 +- sidecar/store.go | 295 ++++++++--- sidecar/store_test.go | 134 ++++- vrsite/app_test.go | 912 -------------------------------- vrsite/assets/app.js | 461 ---------------- vrsite/assets/bash.scm | 21 - vrsite/assets/c.scm | 36 -- vrsite/assets/cpp.scm | 25 - vrsite/assets/go.scm | 34 -- vrsite/assets/htmx.min.js | 2 - vrsite/assets/javascript-params.scm | 12 - vrsite/assets/javascript.scm | 52 -- vrsite/assets/json.scm | 13 - vrsite/assets/jsx.scm | 16 - vrsite/assets/one.json | 112 ---- vrsite/assets/python.scm | 50 -- vrsite/assets/rust.scm | 48 -- vrsite/assets/style.css.tmpl | 590 --------------------- vrsite/assets/typescript.scm | 15 - vrsite/assets/zig.scm | 65 --- vrsite/bench-browser.mjs | 135 ----- vrsite/bench_test.go | 328 ------------ vrsite/css.go | 157 ------ vrsite/go.mod | 26 - vrsite/go.sum | 46 -- vrsite/highlight_test.go | 184 ------- vrsite/jj.go | 298 ----------- vrsite/log.go | 56 -- vrsite/main.go | 237 --------- vrsite/main_test.go | 57 -- vrsite/markdown.go | 259 --------- vrsite/markdown_test.go | 245 --------- vrsite/model.go | 621 ---------------------- vrsite/page.go | 348 ------------ vrsite/permalink_test.go | 210 -------- vrsite/projects.go | 698 ------------------------ vrsite/projects_test.go | 315 ----------- vrsite/render.go | 462 ---------------- vrsite/serve.go | 765 --------------------------- vrsite/static.go | 247 --------- vrsite/templates/frag-activity.tmpl | 36 -- vrsite/templates/frag-change.tmpl | 41 -- vrsite/templates/frag-jj.tmpl | 33 -- vrsite/templates/frag-note.tmpl | 105 ---- vrsite/templates/layout.tmpl | 93 ---- vrsite/templates/page-change.tmpl | 38 -- vrsite/templates/page-file.tmpl | 20 - vrsite/templates/page-files.tmpl | 13 - vrsite/templates/page-index.tmpl | 56 -- vrsite/templates/page-jj.tmpl | 25 - vrsite/templates/page-note.tmpl | 54 -- vrsite/templates/page-notes.tmpl | 52 -- vrsite/templates/page-session.tmpl | 70 --- vrsite/templates/projects.tmpl | 112 ---- vrsite/theme.go | 341 ------------ vrsite/themes.go | 445 ---------------- vrsite/themes_test.go | 294 ---------- vrsite/transcript.go | 602 --------------------- vrsite/transcript_test.go | 333 ------------ vrsite/tree.go | 115 ---- web/app_test.go | 912 ++++++++++++++++++++++++++++++++ web/assets/app.js | 461 ++++++++++++++++ web/assets/bash.scm | 21 + web/assets/bemtevi.svg | 31 ++ web/assets/c.scm | 36 ++ web/assets/cpp.scm | 25 + web/assets/go.scm | 34 ++ web/assets/htmx.min.js | 2 + web/assets/javascript-params.scm | 12 + web/assets/javascript.scm | 52 ++ web/assets/json.scm | 13 + web/assets/jsx.scm | 16 + web/assets/one.json | 112 ++++ web/assets/python.scm | 50 ++ web/assets/rust.scm | 48 ++ web/assets/style.css.tmpl | 592 +++++++++++++++++++++ web/assets/typescript.scm | 15 + web/assets/zig.scm | 65 +++ web/bench-browser.mjs | 135 +++++ web/bench_test.go | 328 ++++++++++++ web/css.go | 157 ++++++ web/highlight_test.go | 184 +++++++ web/jj.go | 298 +++++++++++ web/log.go | 56 ++ web/markdown.go | 259 +++++++++ web/markdown_test.go | 245 +++++++++ web/model.go | 621 ++++++++++++++++++++++ web/page.go | 348 ++++++++++++ web/permalink_test.go | 210 ++++++++ web/projects.go | 715 +++++++++++++++++++++++++ web/projects_test.go | 315 +++++++++++ web/render.go | 462 ++++++++++++++++ web/serve.go | 774 +++++++++++++++++++++++++++ web/static.go | 247 +++++++++ web/templates/frag-activity.tmpl | 36 ++ web/templates/frag-change.tmpl | 41 ++ web/templates/frag-jj.tmpl | 33 ++ web/templates/frag-note.tmpl | 105 ++++ web/templates/layout.tmpl | 94 ++++ web/templates/page-change.tmpl | 38 ++ web/templates/page-file.tmpl | 20 + web/templates/page-files.tmpl | 13 + web/templates/page-index.tmpl | 56 ++ web/templates/page-jj.tmpl | 25 + web/templates/page-note.tmpl | 54 ++ web/templates/page-notes.tmpl | 52 ++ web/templates/page-session.tmpl | 70 +++ web/templates/projects.tmpl | 113 ++++ web/theme.go | 341 ++++++++++++ web/themes.go | 445 ++++++++++++++++ web/themes_test.go | 294 ++++++++++ web/transcript.go | 602 +++++++++++++++++++++ web/transcript_test.go | 333 ++++++++++++ web/tree.go | 115 ++++ web/web.go | 245 +++++++++ web/web_test.go | 57 ++ 130 files changed, 11790 insertions(+), 11249 deletions(-) create mode 100644 README.md create mode 100755 constrain/notevi-only-guard.sh create mode 100644 constrain/notevi-only.rules delete mode 100755 constrain/vr-only-guard.sh delete mode 100644 constrain/vr-only.rules create mode 100644 go.sum delete mode 100644 vrsite/app_test.go delete mode 100644 vrsite/assets/app.js delete mode 100644 vrsite/assets/bash.scm delete mode 100644 vrsite/assets/c.scm delete mode 100644 vrsite/assets/cpp.scm delete mode 100644 vrsite/assets/go.scm delete mode 100644 vrsite/assets/htmx.min.js delete mode 100644 vrsite/assets/javascript-params.scm delete mode 100644 vrsite/assets/javascript.scm delete mode 100644 vrsite/assets/json.scm delete mode 100644 vrsite/assets/jsx.scm delete mode 100644 vrsite/assets/one.json delete mode 100644 vrsite/assets/python.scm delete mode 100644 vrsite/assets/rust.scm delete mode 100644 vrsite/assets/style.css.tmpl delete mode 100644 vrsite/assets/typescript.scm delete mode 100644 vrsite/assets/zig.scm delete mode 100644 vrsite/bench-browser.mjs delete mode 100644 vrsite/bench_test.go delete mode 100644 vrsite/css.go delete mode 100644 vrsite/go.mod delete mode 100644 vrsite/go.sum delete mode 100644 vrsite/highlight_test.go delete mode 100644 vrsite/jj.go delete mode 100644 vrsite/log.go delete mode 100644 vrsite/main.go delete mode 100644 vrsite/main_test.go delete mode 100644 vrsite/markdown.go delete mode 100644 vrsite/markdown_test.go delete mode 100644 vrsite/model.go delete mode 100644 vrsite/page.go delete mode 100644 vrsite/permalink_test.go delete mode 100644 vrsite/projects.go delete mode 100644 vrsite/projects_test.go delete mode 100644 vrsite/render.go delete mode 100644 vrsite/serve.go delete mode 100644 vrsite/static.go delete mode 100644 vrsite/templates/frag-activity.tmpl delete mode 100644 vrsite/templates/frag-change.tmpl delete mode 100644 vrsite/templates/frag-jj.tmpl delete mode 100644 vrsite/templates/frag-note.tmpl delete mode 100644 vrsite/templates/layout.tmpl delete mode 100644 vrsite/templates/page-change.tmpl delete mode 100644 vrsite/templates/page-file.tmpl delete mode 100644 vrsite/templates/page-files.tmpl delete mode 100644 vrsite/templates/page-index.tmpl delete mode 100644 vrsite/templates/page-jj.tmpl delete mode 100644 vrsite/templates/page-note.tmpl delete mode 100644 vrsite/templates/page-notes.tmpl delete mode 100644 vrsite/templates/page-session.tmpl delete mode 100644 vrsite/templates/projects.tmpl delete mode 100644 vrsite/theme.go delete mode 100644 vrsite/themes.go delete mode 100644 vrsite/themes_test.go delete mode 100644 vrsite/transcript.go delete mode 100644 vrsite/transcript_test.go delete mode 100644 vrsite/tree.go create mode 100644 web/app_test.go create mode 100644 web/assets/app.js create mode 100644 web/assets/bash.scm create mode 100644 web/assets/bemtevi.svg create mode 100644 web/assets/c.scm create mode 100644 web/assets/cpp.scm create mode 100644 web/assets/go.scm create mode 100644 web/assets/htmx.min.js create mode 100644 web/assets/javascript-params.scm create mode 100644 web/assets/javascript.scm create mode 100644 web/assets/json.scm create mode 100644 web/assets/jsx.scm create mode 100644 web/assets/one.json create mode 100644 web/assets/python.scm create mode 100644 web/assets/rust.scm create mode 100644 web/assets/style.css.tmpl create mode 100644 web/assets/typescript.scm create mode 100644 web/assets/zig.scm create mode 100644 web/bench-browser.mjs create mode 100644 web/bench_test.go create mode 100644 web/css.go create mode 100644 web/highlight_test.go create mode 100644 web/jj.go create mode 100644 web/log.go create mode 100644 web/markdown.go create mode 100644 web/markdown_test.go create mode 100644 web/model.go create mode 100644 web/page.go create mode 100644 web/permalink_test.go create mode 100644 web/projects.go create mode 100644 web/projects_test.go create mode 100644 web/render.go create mode 100644 web/serve.go create mode 100644 web/static.go create mode 100644 web/templates/frag-activity.tmpl create mode 100644 web/templates/frag-change.tmpl create mode 100644 web/templates/frag-jj.tmpl create mode 100644 web/templates/frag-note.tmpl create mode 100644 web/templates/layout.tmpl create mode 100644 web/templates/page-change.tmpl create mode 100644 web/templates/page-file.tmpl create mode 100644 web/templates/page-files.tmpl create mode 100644 web/templates/page-index.tmpl create mode 100644 web/templates/page-jj.tmpl create mode 100644 web/templates/page-note.tmpl create mode 100644 web/templates/page-notes.tmpl create mode 100644 web/templates/page-session.tmpl create mode 100644 web/templates/projects.tmpl create mode 100644 web/theme.go create mode 100644 web/themes.go create mode 100644 web/themes_test.go create mode 100644 web/transcript.go create mode 100644 web/transcript_test.go create mode 100644 web/tree.go create mode 100644 web/web.go create mode 100644 web/web_test.go diff --git a/.gitignore b/.gitignore index 2a686c7..6dada09 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,2 @@ -/vr -/vrsite/vrsite +/notevi /site diff --git a/README.md b/README.md new file mode 100644 index 0000000..3ca6eff --- /dev/null +++ b/README.md @@ -0,0 +1,125 @@ + + +# notevi + +A code reader that remembers. Read files and grep through `notevi`, pin notes to +line ranges, and every one of those calls is appended as a single JSON line to +an **append-only JSONL log** kept in a **private jj commit**. Not your working +copy. Not your history. + +Two front ends over that one log — a CLI and a local web app. Both read it, both +write to it. Use either. Use only one. + +The bem-te-vi calls all day and keeps a bright crown patch hidden under a plain +black cap. Same idea: the notes are always there, never in the way. + +## Install + +```sh +go build -o ~/.local/bin/notevi . +``` + +Needs `jj` (the repo must be a jj workspace) and `rg` for working-copy greps. + +## From the shell + +```sh +notevi read src/lib.rs # whole file, line-numbered +notevi read src/lib.rs:120-180 # just the range +notevi grep 'fn resolve' src/ # regex over the working copy + +notevi note -f src/lib.rs:143 -t invariant "holds only under the bank lock" +notevi note -reply 12 "no — see the early return above" + +notevi query -op note # replay the log, oldest first +notevi query -file accounts_db # everything touching a path +``` + +Add `-r REV` to any of them to work at another revision — any jj revset, default +`@`. Every entry records the full change **and** commit id, so a note stays +pinned to the exact bytes it was about even after the change is rewritten. +Notes take an optional `-t KIND` (`fn`, `struct`, `invariant`, whatever you +want) and can reply to each other by number. + +## From the browser + +```sh +notevi web # dashboard: every sidecar under ~ +notevi web -repo . # one repo, http://127.0.0.1:4200 +``` + +**This is not a viewer.** Click a line, type, and the note is appended to the +same JSONL log `notevi note` writes to — same numbering, same permalinks, at the +exact change and commit you are looking at, attributed to your username. Reply +to notes, thread them, filter by file, text, kind, author, model, session, +change or date range. Never open the CLI and you lose nothing. + +What it shows: + +- the repo tree with per-reader coverage, and sources highlighted by tree-sitter + with coverage-tinted line numbers — the colors mix where readers overlap +- every note pinned to its lines, plus a notes-only mode across the whole repo +- who is reading right now, refreshed every few seconds +- ad-hoc jj queries over the repo +- every Zed and Helix theme installed on the machine, previewed live as you + arrow through the picker + +The dashboard scans `~` for repositories, and can start a sidecar in a jj repo +or add colocated jj to a Git one — so a project can begin in the browser too. +It writes no registry and no scan cache. + +```sh +notevi web -repo . -out site # static export: hand it to someone +``` + +The export is a plain directory of HTML. Tree, coverage, highlighting, notes, +filters and the file finder all still work with no server; writing notes, live +activity and jj queries do not, because there is nothing running. + +## The log + +One file, `notevi-log.jsonl`, only ever appended to. Lines are never edited and +never deleted: a note you got wrong is superseded by a later note, not rewritten, +so the trace stays a faithful record of what was believed when. Which also means +you can skip the tooling entirely: + +```sh +jj file show -r 'exactly(notevi_log, 1)' -- notevi-log.jsonl | + jq -c 'select(.op == "note") | {file, start, text}' +``` + +That file lives in one anonymous commit whose parent is `root()`, described +`private: notevi log`. The repo-local revset alias `notevi_log` names it and +`git.private-commits` keeps it from being pushed. Each append is a new revision +of that commit, so the evolog is the log's own history: + +```sh +jj evolog -r 'exactly(notevi_log, 1)' --reversed -p --git +``` + +Appends are serialized and go through an isolated `jj run`; your `@` is never +snapshotted or moved. There is no bookmark and no push — **a fresh clone will +not have your notes.** Back up the jj repo, or export the site. + +## If a coding agent is the one running it + +`notevi` notices. It reads the harness environment (Claude Code, Codex, Hermes), +falling back to walking the process tree, and adds session id, model and +reasoning effort to every entry it writes. Nothing to configure; a human at a +shell just gets entries without those fields. + +That turns the trace into a record of what an agent actually looked at before it +told you something. The web view colors coverage per reader, so overlapping +work is visible, and each note links to the conversation turn it came from. + +`constrain/` goes further and makes `notevi` the *only* way to read: a Claude +Code `PreToolUse` hook and a codex execpolicy ruleset that deny +`cat`/`rg`/`sed`/`jj file show`/`git show`/… and point the agent at +`notevi -doc`. Agents converge on it with zero instructions. See +`constrain/README.txt`. + +## Coming from `vr` / `vrsite` + +Same tool, one binary. Old sidecars (`vr_log`, `vr-log.jsonl`) are still +recognized and renamed in place on first write; `notevi migrate DIR...` does it +up front. diff --git a/constrain/AGENTS.md b/constrain/AGENTS.md index 871fc6c..93df43b 100644 --- a/constrain/AGENTS.md +++ b/constrain/AGENTS.md @@ -1,14 +1,14 @@ # Reading code here -Files are read with the `vr` tool — run `vr -doc` once for full usage. +Files are read with the `notevi` tool — run `notevi -doc` once for full usage. -`vr` stores the trace in the repo's private local jj sidecar named `vr_log`. -Do not set `VR_LOG`, pass `-log`, or create a working-tree `vr-log.jsonl`. +`notevi` stores the trace in the repo's private local jj sidecar named +`notevi_log`. Do not create a working-tree log file; there is no path to set. -- `vr read FILE:START-END` — line-numbered read; prefer ranges over whole files -- `vr grep PATTERN [PATH]` — regex search; scope with a path -- `vr read -r REV FILE`, `vr grep -r REV PATTERN PATH` — at another jj change -- `vr note -f FILE:10-42 -t struct TEXT...` — record observations as you read +- `notevi read FILE:START-END` — line-numbered read; prefer ranges over whole files +- `notevi grep PATTERN [PATH]` — regex search; scope with a path +- `notevi read -r REV FILE`, `notevi grep -r REV PATTERN PATH` — at another jj change +- `notevi note -f FILE:10-42 -t struct TEXT...` — record observations as you read Navigate top-down: grep for the symbol, read the enclosing range, note what you learn. Every entry records the full current jj change and commit IDs; the diff --git a/constrain/README.txt b/constrain/README.txt index 4da2733..6d4b882 100644 --- a/constrain/README.txt +++ b/constrain/README.txt @@ -1,4 +1,4 @@ -Constrain agents to read files only through vr — enforcement comes from +Constrain agents to read files only through notevi — enforcement comes from harness config; AGENTS.md is navigation guidance only, never the constraint. ── files here ────────────────────────────────────────────────────────────── @@ -6,26 +6,28 @@ claude-settings.json project install: /.claude/settings.json (hook path uses $CLAUDE_PROJECT_DIR) claude-headless-settings.json no-install variant for `claude -p --settings` (hook path is absolute into this dir) -vr-only-guard.sh PreToolUse hook: blocks cat/rg/sed/... and +notevi-only-guard.sh PreToolUse hook: blocks cat/rg/sed/... and jj/git content reads; its error message points - the agent at `vr -doc`, so agents converge + the agent at `notevi -doc`, so agents converge even with zero instructions -vr-only.rules codex execpolicy rules (allow vr, forbid readers) -AGENTS.md how-to-navigate-with-vr guidance for the repo +notevi-only.rules codex execpolicy rules (allow notevi, forbid + readers) +AGENTS.md how-to-navigate-with-notevi guidance for the repo ── one-time setup ────────────────────────────────────────────────────────── -put both on PATH: go build -o ~/.local/bin/vr . (repo root) - cd vrsite && go build -o ~/.local/bin/vrsite . - (vr is what agents call; vrsite is how you read the trace) +put it on PATH: go build -o ~/.local/bin/notevi . (repo root) + + one binary now: agents call `notevi read/grep/note`, and you + read the trace back with `notevi web` ── running a constrained CLAUDE investigation ────────────────────────────── From the target jj repo dir: - claude -p --settings /constrain/claude-headless-settings.json \ - --allowedTools 'Bash(vr)' 'Bash(vr:*)' \ + claude -p --settings /constrain/claude-headless-settings.json \ + --allowedTools 'Bash(notevi)' 'Bash(notevi:*)' \ < prompt.txt > report.md - ( is wherever this repo lives; the settings file's hook path is + ( is wherever this repo lives; the settings file's hook path is absolute into this directory, so it must be spelled out in full) - --allowedTools on the CLI is required headless: allow rules inside @@ -36,42 +38,45 @@ From the target jj repo dir: eaten by the flag's list parsing. ── running a constrained CODEX investigation ─────────────────────────────── - cp vr-only.rules ~/.codex/rules/ # activate (GLOBAL: constrains - # every codex session while there) + cp notevi-only.rules ~/.codex/rules/ # activate (GLOBAL: constrains + # every codex session while there) codex exec -s danger-full-access "$(cat prompt.txt)" > report.md - rm ~/.codex/rules/vr-only.rules # deactivate when done + rm ~/.codex/rules/notevi-only.rules # deactivate when done - danger-full-access is required: workspace-write blocks jj metadata writes, - including the sidecar rewrite and `vr read`'s working-copy snapshot. + including the sidecar rewrite and `notevi read`'s working-copy snapshot. - enforcement is pre-exec by codex's execpolicy engine, even through `zsh -lc` wrappers; validate rules with: - codex execpolicy check --rules vr-only.rules -- cat foo.txt + codex execpolicy check --rules notevi-only.rules -- cat foo.txt ── shared trace + rendering ──────────────────────────────────────────────── - - vr creates one anonymous sidecar change directly under jj's root() on the - first append. The repo-local alias vr_log names it; git.private-commits - protects it from accidental pushes. No path or environment setup exists. + - notevi creates one anonymous sidecar change directly under jj's root() on + the first append. The repo-local alias notevi_log names it; + git.private-commits protects it from accidental pushes. No path or + environment setup exists. + - A repository last written by the older `vr` tool is renamed in place the + first time notevi touches it; `notevi migrate ...` does it up front. - Multiple agents in the repo share that sidecar. Rewrites are serialized, note ids are assigned under the same lock, and the project @ is untouched. - The sidecar has no bookmark and is local-only. It does not survive a fresh clone; include the jj repository in backups when the trace matters. - In the prompt, tell the agent to leave pinned notes - (vr note -f FILE:START-END -t kind "...") — that is the payload. - - Read traces afterwards from one process. Bare `vrsite` scans below ~ at + (notevi note -f FILE:START-END -t kind "...") — that is the payload. + - Read traces afterwards from one process. Bare `notevi web` scans below ~ at startup and when Refresh is pressed, then offers every repo with a sidecar: - vrsite + notevi web Its explicit buttons can start an empty private sidecar in a discovered jj repo or initialize colocated jj in a discovered Git repo. The project index is only in memory; those two requested metadata changes are the only writes. - To bypass the dashboard and serve one repository directly: - vrsite -repo -title "..." + notevi web -repo -title "..." or take a static copy to hand around (one change, no server features): - vrsite -repo -out site -title "..." - `vrsite -h` explains both, and what a log needs to be worth reading. + notevi web -repo -out site -title "..." + `notevi web -h` explains both, and what a log needs to be worth reading. ── known holes (accepted) ────────────────────────────────────────────────── Scripting runtimes (python/node/perl) can still open files — uncomment their -rules in vr-only.rules / extend the hook to close, at the cost of breaking +rules in notevi-only.rules / extend the hook to close, at the cost of breaking legitimate scripts. Neither harness constrains its own non-shell internals beyond what the deny rules cover. Codex's rules file is global-only; there is no per-project rules mechanism (probed, none exists as of codex 0.145). diff --git a/constrain/claude-headless-settings.json b/constrain/claude-headless-settings.json index 30aff9b..b22704c 100644 --- a/constrain/claude-headless-settings.json +++ b/constrain/claude-headless-settings.json @@ -1,7 +1,7 @@ { "permissions": { "deny": ["Read", "Grep", "Glob"], - "allow": ["Bash(vr)", "Bash(vr:*)"] + "allow": ["Bash(notevi)", "Bash(notevi:*)"] }, "hooks": { "PreToolUse": [ @@ -10,7 +10,7 @@ "hooks": [ { "type": "command", - "command": "/home/goblin/00-projects/01-tools/vr-agent-logger/constrain/vr-only-guard.sh" + "command": "/home/goblin/00-projects/01-tools/notevi/constrain/notevi-only-guard.sh" } ] } diff --git a/constrain/claude-settings.json b/constrain/claude-settings.json index 524ccbd..639befb 100644 --- a/constrain/claude-settings.json +++ b/constrain/claude-settings.json @@ -1,7 +1,7 @@ { "permissions": { "deny": ["Read", "Grep", "Glob"], - "allow": ["Bash(vr)", "Bash(vr:*)"] + "allow": ["Bash(notevi)", "Bash(notevi:*)"] }, "hooks": { "PreToolUse": [ @@ -10,7 +10,7 @@ "hooks": [ { "type": "command", - "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/vr-only-guard.sh" + "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/notevi-only-guard.sh" } ] } diff --git a/constrain/notevi-only-guard.sh b/constrain/notevi-only-guard.sh new file mode 100755 index 0000000..729f4d4 --- /dev/null +++ b/constrain/notevi-only-guard.sh @@ -0,0 +1,19 @@ +#!/bin/sh +# Claude Code PreToolUse hook (matcher: Bash): deny shell commands that read +# files without going through notevi. A guardrail, not a jail — it catches the +# common readers at command position, not every conceivable bypass. +cmd=$(jq -r '.tool_input.command // empty') + +readers='cat|head|tail|less|more|sed|awk|cut|rg|grep|egrep|fgrep|find|fd|strings|xxd|hexdump|od|tac|nl' +pattern='(^|[;&|(`]|\$\()[[:space:]]*('$readers')([[:space:]]|$)' + +if printf '%s' "$cmd" | grep -qE "$pattern"; then + echo "blocked: read/search files only through notevi (run 'notevi -doc' for usage)" >&2 + exit 2 +fi +vcs='jj[[:space:]]+(file[[:space:]]+show|diff)|git[[:space:]]+(show|diff|grep|cat-file|blame|log)' +if printf '%s' "$cmd" | grep -qE "(^|[;&|(\`])[[:space:]]*($vcs)"; then + echo "blocked: use 'notevi read -r REV FILE' / 'notevi grep -r REV' instead of raw jj/git reads" >&2 + exit 2 +fi +exit 0 diff --git a/constrain/notevi-only.rules b/constrain/notevi-only.rules new file mode 100644 index 0000000..f618f18 --- /dev/null +++ b/constrain/notevi-only.rules @@ -0,0 +1,44 @@ +# codex execpolicy: force file reading through notevi (which logs every read). +# Activate: cp notevi-only.rules ~/.codex/rules/ +# Deactivate: rm ~/.codex/rules/notevi-only.rules +# The engine parses through `/bin/zsh -lc '...'` wrappers, so these match the +# inner command. Editing tools (apply_patch) are unaffected — this only +# constrains reading. Known hole: scripting runtimes can still open files; +# uncomment the last block to close it at the cost of breaking legit scripts. + +prefix_rule(pattern=["notevi"], decision="allow") + +prefix_rule(pattern=["cat"], decision="forbidden") +prefix_rule(pattern=["head"], decision="forbidden") +prefix_rule(pattern=["tail"], decision="forbidden") +prefix_rule(pattern=["less"], decision="forbidden") +prefix_rule(pattern=["more"], decision="forbidden") +prefix_rule(pattern=["sed"], decision="forbidden") +prefix_rule(pattern=["awk"], decision="forbidden") +prefix_rule(pattern=["cut"], decision="forbidden") +prefix_rule(pattern=["rg"], decision="forbidden") +prefix_rule(pattern=["grep"], decision="forbidden") +prefix_rule(pattern=["egrep"], decision="forbidden") +prefix_rule(pattern=["fgrep"], decision="forbidden") +prefix_rule(pattern=["find"], decision="forbidden") +prefix_rule(pattern=["fd"], decision="forbidden") +prefix_rule(pattern=["strings"], decision="forbidden") +prefix_rule(pattern=["xxd"], decision="forbidden") +prefix_rule(pattern=["hexdump"], decision="forbidden") +prefix_rule(pattern=["od"], decision="forbidden") +prefix_rule(pattern=["tac"], decision="forbidden") +prefix_rule(pattern=["nl"], decision="forbidden") +prefix_rule(pattern=["jj", "file", "show"], decision="forbidden") +prefix_rule(pattern=["jj", "diff"], decision="forbidden") +prefix_rule(pattern=["git", "show"], decision="forbidden") +prefix_rule(pattern=["git", "diff"], decision="forbidden") +prefix_rule(pattern=["git", "grep"], decision="forbidden") +prefix_rule(pattern=["git", "cat-file"], decision="forbidden") +prefix_rule(pattern=["git", "blame"], decision="forbidden") +prefix_rule(pattern=["git", "log"], decision="forbidden") + +# prefix_rule(pattern=["python3"], decision="forbidden") +# prefix_rule(pattern=["python"], decision="forbidden") +# prefix_rule(pattern=["node"], decision="forbidden") +# prefix_rule(pattern=["perl"], decision="forbidden") +# prefix_rule(pattern=["ruby"], decision="forbidden") diff --git a/constrain/vr-only-guard.sh b/constrain/vr-only-guard.sh deleted file mode 100755 index 0de698f..0000000 --- a/constrain/vr-only-guard.sh +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/sh -# Claude Code PreToolUse hook (matcher: Bash): deny shell commands that read -# files without going through vr. A guardrail, not a jail — it catches the -# common readers at command position, not every conceivable bypass. -cmd=$(jq -r '.tool_input.command // empty') - -readers='cat|head|tail|less|more|sed|awk|cut|rg|grep|egrep|fgrep|find|fd|strings|xxd|hexdump|od|tac|nl' -pattern='(^|[;&|(`]|\$\()[[:space:]]*('$readers')([[:space:]]|$)' - -if printf '%s' "$cmd" | grep -qE "$pattern"; then - echo "blocked: read/search files only through vr (run 'vr -doc' for usage)" >&2 - exit 2 -fi -vcs='jj[[:space:]]+(file[[:space:]]+show|diff)|git[[:space:]]+(show|diff|grep|cat-file|blame|log)' -if printf '%s' "$cmd" | grep -qE "(^|[;&|(\`])[[:space:]]*($vcs)"; then - echo "blocked: use 'vr read -r REV FILE' / 'vr grep -r REV' instead of raw jj/git reads" >&2 - exit 2 -fi -exit 0 diff --git a/constrain/vr-only.rules b/constrain/vr-only.rules deleted file mode 100644 index 54d3392..0000000 --- a/constrain/vr-only.rules +++ /dev/null @@ -1,44 +0,0 @@ -# codex execpolicy: force file reading through vr (which logs every read). -# Activate: cp vr-only.rules ~/.codex/rules/ -# Deactivate: rm ~/.codex/rules/vr-only.rules -# The engine parses through `/bin/zsh -lc '...'` wrappers, so these match the -# inner command. Editing tools (apply_patch) are unaffected — this only -# constrains reading. Known hole: scripting runtimes can still open files; -# uncomment the last block to close it at the cost of breaking legit scripts. - -prefix_rule(pattern=["vr"], decision="allow") - -prefix_rule(pattern=["cat"], decision="forbidden") -prefix_rule(pattern=["head"], decision="forbidden") -prefix_rule(pattern=["tail"], decision="forbidden") -prefix_rule(pattern=["less"], decision="forbidden") -prefix_rule(pattern=["more"], decision="forbidden") -prefix_rule(pattern=["sed"], decision="forbidden") -prefix_rule(pattern=["awk"], decision="forbidden") -prefix_rule(pattern=["cut"], decision="forbidden") -prefix_rule(pattern=["rg"], decision="forbidden") -prefix_rule(pattern=["grep"], decision="forbidden") -prefix_rule(pattern=["egrep"], decision="forbidden") -prefix_rule(pattern=["fgrep"], decision="forbidden") -prefix_rule(pattern=["find"], decision="forbidden") -prefix_rule(pattern=["fd"], decision="forbidden") -prefix_rule(pattern=["strings"], decision="forbidden") -prefix_rule(pattern=["xxd"], decision="forbidden") -prefix_rule(pattern=["hexdump"], decision="forbidden") -prefix_rule(pattern=["od"], decision="forbidden") -prefix_rule(pattern=["tac"], decision="forbidden") -prefix_rule(pattern=["nl"], decision="forbidden") -prefix_rule(pattern=["jj", "file", "show"], decision="forbidden") -prefix_rule(pattern=["jj", "diff"], decision="forbidden") -prefix_rule(pattern=["git", "show"], decision="forbidden") -prefix_rule(pattern=["git", "diff"], decision="forbidden") -prefix_rule(pattern=["git", "grep"], decision="forbidden") -prefix_rule(pattern=["git", "cat-file"], decision="forbidden") -prefix_rule(pattern=["git", "blame"], decision="forbidden") -prefix_rule(pattern=["git", "log"], decision="forbidden") - -# prefix_rule(pattern=["python3"], decision="forbidden") -# prefix_rule(pattern=["python"], decision="forbidden") -# prefix_rule(pattern=["node"], decision="forbidden") -# prefix_rule(pattern=["perl"], decision="forbidden") -# prefix_rule(pattern=["ruby"], decision="forbidden") diff --git a/doc.txt b/doc.txt index 87b0db4..e3fe5fc 100644 --- a/doc.txt +++ b/doc.txt @@ -1,28 +1,30 @@ -vr — read code and take notes; every call is logged in a private jj sidecar. +notevi — read code and take notes; every call is logged in a private jj sidecar. read a file (line-numbered, relative to a jj revision): - vr read FILE whole file - vr read FILE:120-180 line range (or FILE:120 for one line) - vr read -r REV FILE the file as it is in another jj change + notevi read FILE whole file + notevi read FILE:120-180 line range (or FILE:120 for one line) + notevi read -r REV FILE the file as it is in another jj change search (regex): - vr grep PATTERN [PATH] search the working copy - vr grep -r REV PATTERN PATH search another change (scope with PATH) + notevi grep PATTERN [PATH] search the working copy + notevi grep -r REV PATTERN PATH search another change (scope with PATH) take a note while reading (ids count up from 1 per session): - vr note -f FILE:10-42 TEXT... about a line range - vr note -t struct -f FILE:10-42 TEXT... about a struct/enum/const/fn/... - vr note -r REV -f FILE TEXT... about code in another change - vr note -reply 12 TEXT... reply to log-wide note #12 + notevi note -f FILE:10-42 TEXT... about a line range + notevi note -t struct -f FILE:10-42 TEXT... about a struct/enum/const/fn/... + notevi note -r REV -f FILE TEXT... about code in another change + notevi note -reply 12 TEXT... reply to log-wide note #12 -vr query -op note shows both the session-local id and the log-wide id used by --reply and vrsite /note/N permalinks. +notevi query -op note shows both the session-local id and the log-wide id used +by -reply and by the /note/N permalinks in `notevi web`. REV is any jj revset; default @ (the working copy). -The repo-local revset alias vr_log names the log change. vr creates it lazily -as an anonymous child of root(); it never appears in the project working copy. -Every new entry records the full target change id and exact target commit id. -An existing repo-root vr-log.jsonl is read and imported on the first append; -vr leaves that legacy working-tree file for you to remove after migration. +The repo-local revset alias notevi_log names the log change. notevi creates it +lazily as an anonymous child of root(); it never appears in the project working +copy. Every new entry records the full target change id and exact target commit +id. A sidecar left by the older vr tool is renamed in place the first time +notevi writes to it, and an existing repo-root vr-log.jsonl is read and imported +on the first append; notevi leaves that legacy working-tree file for you to +remove after migration. The sidecar has no bookmark and is deliberately local-only: a fresh clone will not contain it, so include the jj repository in backups when notes matter. diff --git a/go.mod b/go.mod index 4510dd8..aabed6d 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,23 @@ -module 0x4200.cafe/vr +module 0x4200.cafe/notevi -go 1.26 +go 1.26.5 + +require ( + github.com/BurntSushi/toml v1.6.0 + github.com/tree-sitter/go-tree-sitter v0.25.0 + github.com/tree-sitter/tree-sitter-bash v0.25.1 + github.com/tree-sitter/tree-sitter-c v0.24.2 + github.com/tree-sitter/tree-sitter-cpp v0.23.4 + github.com/tree-sitter/tree-sitter-go v0.25.0 + github.com/tree-sitter/tree-sitter-javascript v0.25.0 + github.com/tree-sitter/tree-sitter-json v0.24.8 + github.com/tree-sitter/tree-sitter-python v0.25.0 + github.com/tree-sitter/tree-sitter-rust v0.24.2 + github.com/tree-sitter/tree-sitter-typescript v0.23.2 + github.com/yuin/goldmark v1.8.5 +) + +require ( + github.com/mattn/go-pointer v0.0.1 // indirect + github.com/tree-sitter-grammars/tree-sitter-zig v1.1.2 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..fd75698 --- /dev/null +++ b/go.sum @@ -0,0 +1,46 @@ +github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= +github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= +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-grammars/tree-sitter-zig v1.1.2 h1:j8JARutysdxMwBEfVLGx9us7cdSzD1TTui/pPLGCFDk= +github.com/tree-sitter-grammars/tree-sitter-zig v1.1.2/go.mod h1:ekWQEqj2e/gQal396f5rKJ6L14/a4bMPMqSRzmf8OZE= +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-bash v0.25.1 h1:ZD3MK4oDB5lAsFztqbdcyYEd24pxDtx3g9UOWA062rE= +github.com/tree-sitter/tree-sitter-bash v0.25.1/go.mod h1:AksQ6zE+sP9hnp7mKTMT7Q+CwpthV7VGQLXvweVXz9U= +github.com/tree-sitter/tree-sitter-c v0.24.2 h1:nW+M6BnPUa/fBwks8nqf1NiVvu7nltaC+5bR/lTtJCs= +github.com/tree-sitter/tree-sitter-c v0.24.2/go.mod h1:/SpJlv2BuiCgFA5xvtgukFGi51WxctByPUGDxPl60fc= +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.25.0 h1:cEB0Q3LHgZtS+ECHx9wcP7AwzoOddJFQCVmytX42cVU= +github.com/tree-sitter/tree-sitter-go v0.25.0/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.25.0 h1:ZkWETb66/w8cc13yhfnNuHOLDQWl3BnKlH6f9AdR88c= +github.com/tree-sitter/tree-sitter-javascript v0.25.0/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.25.0 h1:O6XD9v8U1LOcRc3cNj9nM7XufrtEBezE6VrpRrHZDf0= +github.com/tree-sitter/tree-sitter-python v0.25.0/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= +github.com/tree-sitter/tree-sitter-typescript v0.23.2 h1:/Odvphn18PniVixb9e97X0DbNVsU6Qocv9mfkyzdXwU= +github.com/tree-sitter/tree-sitter-typescript v0.23.2/go.mod h1:zjzMXT/Ulffel2xfOcAkQQkiAkmgnbtPGlFQw/5X4xA= +github.com/yuin/goldmark v1.8.5 h1:r6N5afV5qj/5S4UTch8agZHJ8UxNCMwX7WjkkJam2NA= +github.com/yuin/goldmark v1.8.5/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg= +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/main.go b/main.go index 1d263cb..2924d1c 100644 --- a/main.go +++ b/main.go @@ -1,9 +1,14 @@ -// vr — file reader / note taker for coding agents, logging every call. +// notevi — read code, take notes, read the trace back; every call is logged. // -// Each operation appends one JSON line to a private jj sidecar recording who read what: +// Named for the bem-te-vi, the kiskadee that announces itself all day and keeps +// a bright crown patch hidden under plain feathers: the notes are there the +// whole time, tucked out of the project's way in a private jj sidecar. +// +// Each operation appends one JSON line to that sidecar recording who read what: // session id, agent, model, reasoning effort, working dir, full jj change and // commit ids, file and line range. Reads and greps are relative to a jj // revision (default @, the working copy) — the tool assumes a jj repo. +// "notevi web" serves the same log as a browsable site. // // Agent identity comes from the caller's environment (Claude Code exports // CLAUDE_CODE_SESSION_ID, AI_AGENT, CLAUDE_EFFORT into tool subprocesses); when @@ -29,7 +34,8 @@ import ( "strings" "time" - "0x4200.cafe/vr/sidecar" + "0x4200.cafe/notevi/sidecar" + "0x4200.cafe/notevi/web" ) type Entry struct { @@ -76,6 +82,11 @@ func main() { fmt.Print(queryDoc) return } + // web serves the log rather than appending to it, and brings its own flags. + if os.Args[1] == "web" { + web.Main(os.Args[2:]) + return + } detect() switch os.Args[1] { case "read": @@ -86,36 +97,43 @@ func main() { cmdNote(os.Args[2:]) case "query": cmdQuery(os.Args[2:]) + case "migrate": + cmdMigrate(os.Args[2:]) default: usage() } } func usage() { - fmt.Fprint(os.Stderr, `vr — file reader / note taker for coding agents; logs every call. + fmt.Fprint(os.Stderr, `notevi — read code and take notes; logs every call, hides them in a sidecar. usage: - vr read [-r REV] FILE[:START[-END]] + notevi read [-r REV] FILE[:START[-END]] print a file line-numbered, whole or a line range, at a jj revision - vr grep [-r REV] PATTERN [PATH] + notevi grep [-r REV] PATTERN [PATH] search the working copy (rg) or another revision (jj file list/show); scope non-@ greps with PATH, they read every file through jj - vr note [-r REV] [-f FILE[:START[-END]]] [-t KIND] [-reply NOTE] TEXT... + notevi note [-r REV] [-f FILE[:START[-END]]] [-t KIND] [-reply NOTE] TEXT... record a note about a file range or a kind of thing (struct, enum, const, ...), optionally replying to a log-wide note number; ids count up from 1 per session - vr query [-session S] [-op OP] [-file SUBSTR] [-n N] + notevi query [-session S] [-op OP] [-file SUBSTR] [-n N] print logged entries, oldest first + notevi web [-repo DIR] [-out DIR] ... + browse the trace: repo tree, coverage, notes; "notevi web -h" for more + notevi migrate [DIR...] + rename a pre-notevi sidecar in place; run once per old repository REV is any jj revset, default @ (working copy). The JSONL log lives in the -private jj sidecar named by the repo-local revset alias vr_log. -"vr -doc" prints the short agent-facing usage doc; "vr -doc-query" the query one. +private jj sidecar named by the repo-local revset alias notevi_log. +"notevi -doc" prints the short agent-facing usage doc; "notevi -doc-query" the +query one. `) os.Exit(2) } func fatal(format string, a ...any) { - fmt.Fprintf(os.Stderr, "vr: "+format+"\n", a...) + fmt.Fprintf(os.Stderr, "notevi: "+format+"\n", a...) os.Exit(1) } @@ -252,7 +270,7 @@ func jjOut(args ...string) string { } // --ignore-working-copy skips the snapshot: change ids are stable across -// snapshots, and this keeps `vr note`/`vr grep` working in sandboxes that +// snapshots, and this keeps `notevi note`/`notevi grep` working in sandboxes that // block .git writes (codex workspace-write). read/grep -r snapshot anyway // via their own jj file show/list calls. func revisionIDs(rev string) (change, commit string) { @@ -290,7 +308,7 @@ func cmdRead(args []string) { rev := fs.String("r", "@", "jj revision to read at") fs.Parse(args) if fs.NArg() != 1 { - fatal("usage: vr read [-r REV] FILE[:START[-END]]") + fatal("usage: notevi read [-r REV] FILE[:START[-END]]") } file, start, end := parseFileRange(fs.Arg(0)) @@ -320,7 +338,7 @@ func cmdGrep(args []string) { rev := fs.String("r", "@", "jj revision to search at") fs.Parse(args) if fs.NArg() < 1 || fs.NArg() > 2 { - fatal("usage: vr grep [-r REV] PATTERN [PATH]") + fatal("usage: notevi grep [-r REV] PATTERN [PATH]") } pattern, path := fs.Arg(0), fs.Arg(1) @@ -372,7 +390,7 @@ func cmdNote(args []string) { fs.Parse(args) text := strings.Join(fs.Args(), " ") if text == "" { - fatal("usage: vr note [-r REV] [-f FILE[:START[-END]]] [-t KIND] [-reply NOTE] TEXT...") + fatal("usage: notevi note [-r REV] [-f FILE[:START[-END]]] [-t KIND] [-reply NOTE] TEXT...") } if *reply < 0 { fatal("reply note must be positive") @@ -392,7 +410,7 @@ func cmdNote(args []string) { fmt.Printf("note %d\n", e.NoteID) } -// hasNote uses the same numbering as vrsite permalinks: note operations count +// hasNote uses the same numbering as the web permalinks: note operations count // from one over the append-only log, independent of their writers' sessions. func hasNote(entries []Entry, id int) bool { n := 0 @@ -486,6 +504,40 @@ func cmdQuery(args []string) { } } +// cmdMigrate renames pre-notevi sidecars. It takes directories rather than only +// working on the current one so that a machine full of old repositories can be +// brought over in one run. +func cmdMigrate(args []string) { + fs := flag.NewFlagSet("migrate", flag.ExitOnError) + fs.Parse(args) + dirs := fs.Args() + if len(dirs) == 0 { + dirs = []string{gDir} + } + failed := false + for _, dir := range dirs { + s, err := sidecar.Open(dir) + if err != nil { + fmt.Fprintf(os.Stderr, "notevi: %s: %v\n", dir, err) + failed = true + continue + } + migrated, err := s.Migrate() + switch { + case err != nil: + fmt.Fprintf(os.Stderr, "notevi: %s: %v\n", s.Root(), err) + failed = true + case migrated: + fmt.Printf("%s: renamed to %s\n", s.Root(), s) + default: + fmt.Printf("%s: nothing to rename\n", s.Root()) + } + } + if failed { + os.Exit(1) + } +} + func fileRange(e Entry) string { s := e.File if e.Start > 0 { diff --git a/query-doc.txt b/query-doc.txt index 8d4f58a..f3f4b97 100644 --- a/query-doc.txt +++ b/query-doc.txt @@ -1,14 +1,14 @@ -vr query — inspect this jj repo's read/note sidecar (oldest first). +notevi query — inspect this jj repo's read/note sidecar (oldest first). - vr query everything - vr query -n 20 last 20 entries - vr query -op note only notes (or: read, grep) - vr query -file accounts_db entries touching a file path substring - vr query -session fa7cb1bf one session (id substring is enough) + notevi query everything + notevi query -n 20 last 20 entries + notevi query -op note only notes (or: read, grep) + notevi query -file accounts_db entries touching a file path substring + notevi query -session fa7cb1bf one session (id substring is enough) Filters combine. The sidecar content is JSON lines and can also be read with: - jj file show -r 'exactly(vr_log, 1)' -- vr-log.jsonl + jj file show -r 'exactly(notevi_log, 1)' -- notevi-log.jsonl Its append history is: - jj evolog -r 'exactly(vr_log, 1)' --reversed -p --git + jj evolog -r 'exactly(notevi_log, 1)' --reversed -p --git Note rows show the session-local id first and the log-wide id used by -`vr note -reply N` and vrsite permalinks in brackets. +`notevi note -reply N` and by `notevi web` permalinks in brackets. diff --git a/sidecar/store.go b/sidecar/store.go index 76e626f..ce6c56f 100644 --- a/sidecar/store.go +++ b/sidecar/store.go @@ -1,4 +1,4 @@ -// Package sidecar stores vr's append-only JSONL log in a private jj change. +// Package sidecar stores notevi's append-only JSONL log in a private jj change. // // The change is an anonymous direct child of root(), so it is visible and // durable in the jj repository without becoming part of project history or the @@ -18,18 +18,34 @@ import ( ) const ( - Alias = "vr_log" - LogFile = "vr-log.jsonl" - Description = "private: vr log" + Alias = "notevi_log" + LogFile = "notevi-log.jsonl" + Description = "private: notevi log" + lockFile = "notevi.lock" ) -var ErrNoLog = errors.New("vr log has not been initialized") +// naming is the set of repo-visible names one generation of the tool gave the +// sidecar: the revset alias, the file inside the change, and the change's own +// description. +type naming struct{ alias, logFile, description string } -// Store is a repository's vr log. Open is read-only with respect to jj; the +var current = naming{Alias, LogFile, Description} + +// legacy is what the tool called itself before the notevi rebrand. Every read +// path still recognizes it so an un-migrated repository opens; Migrate renames +// it in place so nothing in the repository keeps the old name. +var legacy = naming{"vr_log", "vr-log.jsonl", "private: vr log"} + +const legacyLockFile = "vr-agent-logger.lock" + +var ErrNoLog = errors.New("notevi log has not been initialized") + +// Store is a repository's notevi log. Open is read-only with respect to jj; the // sidecar change and its config are created lazily by Append. type Store struct { - root string - lockPath string + root string + configDir string + lockPath string } // Open finds the jj workspace containing dir. @@ -43,32 +59,40 @@ func Open(dir string) (*Store, error) { if err != nil { return nil, err } + configDir := filepath.Dir(strings.TrimSpace(configPath)) return &Store{ - root: root, - lockPath: filepath.Join(filepath.Dir(strings.TrimSpace(configPath)), "vr-agent-logger.lock"), + root: root, + configDir: configDir, + lockPath: filepath.Join(configDir, lockFile), }, nil } +// Descriptions lists every change subject that has ever named a notevi sidecar, +// current first. Callers that discover sidecars by description need the older +// ones too, so an un-migrated repository is still recognized as having a log. +func Descriptions() []string { return []string{current.description, legacy.description} } + func (s *Store) Root() string { return s.root } func (s *Store) String() string { return fmt.Sprintf("jj sidecar %s:%s", Alias, LogFile) } -// Read returns the current log. Before the first sidecar write it falls back -// to a repo-root legacy log, which makes migration transparent. +// Read returns the current log. It reads a sidecar that still carries the +// pre-rebrand names without migrating it, and before the first sidecar write it +// falls back to a repo-root legacy log, which makes migration transparent. func (s *Store) Read() ([]byte, error) { var data []byte err := s.withLock(syscall.LOCK_SH, func() error { - rev, found, _, err := s.resolveExisting() + rev, n, found, _, err := s.locate() if err != nil { return err } if found { - data, err = s.readRevision(rev) + data, err = s.readRevision(rev, n.logFile) return err } - data, err = os.ReadFile(filepath.Join(s.root, LogFile)) + data, err = os.ReadFile(filepath.Join(s.root, legacy.logFile)) if errors.Is(err, os.ErrNotExist) { return ErrNoLog } @@ -77,12 +101,12 @@ func (s *Store) Read() ([]byte, error) { return data, err } -// Generation is a cheap identity for the current contents, used by vrsite to -// notice appends. A sidecar rewrite gets a new commit id. +// Generation is a cheap identity for the current contents, used by the web app +// to notice appends. A sidecar rewrite gets a new commit id. func (s *Store) Generation() (string, error) { var generation string err := s.withLock(syscall.LOCK_SH, func() error { - rev, found, _, err := s.resolveExisting() + rev, _, found, _, err := s.locate() if err != nil { return err } @@ -90,7 +114,7 @@ func (s *Store) Generation() (string, error) { generation, err = s.logValue(rev, "commit_id") return err } - info, err := os.Stat(filepath.Join(s.root, LogFile)) + info, err := os.Stat(filepath.Join(s.root, legacy.logFile)) if errors.Is(err, os.ErrNotExist) { generation = "empty" return nil @@ -104,7 +128,7 @@ func (s *Store) Generation() (string, error) { return generation, err } -// Append serializes sidecar rewrites across vr processes. makePayload runs +// Append serializes sidecar rewrites across notevi processes. makePayload runs // while holding that lock and receives the complete current log, allowing note // numbering and reply validation to be atomic with the append. func (s *Store) Append(makePayload func(current []byte) ([]byte, error)) error { @@ -113,17 +137,17 @@ func (s *Store) Append(makePayload func(current []byte) ([]byte, error)) error { if err != nil { return err } - sidecarData, err := s.readRevision(rev) + sidecarData, err := s.readRevision(rev, LogFile) if err != nil { return err } current := sidecarData if len(current) == 0 { - legacy, legacyErr := os.ReadFile(filepath.Join(s.root, LogFile)) - if legacyErr == nil { - current = legacy - } else if !errors.Is(legacyErr, os.ErrNotExist) { - return legacyErr + old, oldErr := os.ReadFile(filepath.Join(s.root, legacy.logFile)) + if oldErr == nil { + current = old + } else if !errors.Is(oldErr, os.ErrNotExist) { + return oldErr } } payload, err := makePayload(current) @@ -131,7 +155,7 @@ func (s *Store) Append(makePayload func(current []byte) ([]byte, error)) error { return err } if len(payload) == 0 { - return errors.New("refusing to append an empty vr log payload") + return errors.New("refusing to append an empty notevi log payload") } var appendData []byte @@ -145,10 +169,97 @@ func (s *Store) Append(makePayload func(current []byte) ([]byte, error)) error { if appendData[len(appendData)-1] != '\n' { appendData = append(appendData, '\n') } - return s.runAppend(appendData) + return s.runAppend(rev, appendData) }) } +// Migrate renames a pre-rebrand sidecar in place: the file inside the change, +// the change description, the repo-local revset alias, and the alias mentioned +// in git.private-commits. It reports whether anything was renamed and is a +// no-op on a repository that is already current or has no sidecar at all. +func (s *Store) Migrate() (migrated bool, err error) { + err = s.withLock(syscall.LOCK_EX, func() error { + rev, n, found, configured, err := s.locate() + if err != nil { + return err + } + if !found || n != legacy { + // Still adopt an unconfigured current sidecar, so that a repo whose + // jj config was lost (moving a workspace orphans it) is repaired. + if found && !configured { + return s.configure(rev) + } + return nil + } + if err := s.rename(rev); err != nil { + return err + } + migrated = true + return nil + }) + return migrated, err +} + +// rename performs the legacy -> current renaming for an already-located sidecar. +// The move is two runs, not one `mv`: see ensureLogFile. +func (s *Store) rename(rev string) error { + listed, err := s.jj("file", "list", "-r", rev, "--", legacy.logFile) + if err != nil { + return err + } + if strings.TrimSpace(listed) != "" { + if err := s.ensureLogFile(rev); err != nil { + return err + } + if _, err := s.jjRun(rev, "cat "+legacy.logFile+" >> "+LogFile+" && rm "+legacy.logFile); err != nil { + return err + } + } + if _, err := s.jj("describe", "-r", rev, "-m", Description); err != nil { + return err + } + if err := s.configure(rev); err != nil { + return err + } + if _, err := s.jj("config", "get", "revset-aliases."+legacy.alias); err == nil { + if _, err := s.jj("config", "unset", "--repo", "revset-aliases."+legacy.alias); err != nil { + return err + } + } + os.Remove(filepath.Join(s.configDir, legacyLockFile)) //nolint:errcheck + return nil +} + +// configure points the repo-local alias at rev and refreshes the push guard. +func (s *Store) configure(rev string) error { + if _, err := s.jj("config", "set", "--repo", "revset-aliases."+Alias, strconv.Quote(rev)); err != nil { + return err + } + return s.guard() +} + +// guard keeps git.private-commits naming the current alias, rewriting a legacy +// mention rather than leaving both names in the expression. +func (s *Store) guard() error { + private, err := s.jj("config", "get", "git.private-commits") + if err != nil { + return err + } + expr := strings.TrimSpace(private) + next := expr + if containsRevsetName(next, legacy.alias) { + next = replaceRevsetName(next, legacy.alias, Alias) + } + if !containsRevsetName(next, Alias) { + next = fmt.Sprintf("(%s) | %s", next, Alias) + } + if next == expr { + return nil + } + _, err = s.jj("config", "set", "--repo", "git.private-commits", strconv.Quote(next)) + return err +} + func (s *Store) withLock(kind int, fn func() error) error { if err := os.MkdirAll(filepath.Dir(s.lockPath), 0o755); err != nil { return err @@ -166,57 +277,64 @@ func (s *Store) withLock(kind int, fn func() error) error { } func (s *Store) ensure() (string, error) { - rev, found, configured, err := s.resolveExisting() + rev, n, found, configured, err := s.locate() if err != nil { return "", err } + if found && n == legacy { + // The first append to a pre-rebrand repository renames it, so no + // repository keeps writing under the old name once notevi touches it. + return rev, s.rename(rev) + } if !found { if _, err := s.jj("new", "--no-edit", "root()", "-m", Description); err != nil { return "", err } - ids, err := s.descriptionMatches() + ids, err := s.descriptionMatches(Description) if err != nil { return "", err } if len(ids) != 1 { return "", fmt.Errorf("created %q sidecar but found %d matching root children", Description, len(ids)) } - rev = ids[0] + rev, configured = ids[0], false } if !configured { - if _, err := s.jj("config", "set", "--repo", "revset-aliases."+Alias, strconv.Quote(rev)); err != nil { - return "", err - } + return rev, s.configure(rev) } - private, err := s.jj("config", "get", "git.private-commits") - if err != nil { - return "", err + return rev, s.guard() +} + +// locate finds this repository's sidecar under the current names, falling back +// to the pre-rebrand ones, and reports which generation named it. +func (s *Store) locate() (rev string, n naming, found, configured bool, err error) { + rev, found, configured, err = s.resolveExisting(current) + if err != nil || found { + return rev, current, found, configured, err } - if !containsRevsetName(private, Alias) { - expr := fmt.Sprintf("(%s) | %s", strings.TrimSpace(private), Alias) - if _, err := s.jj("config", "set", "--repo", "git.private-commits", strconv.Quote(expr)); err != nil { - return "", err - } + rev, found, configured, err = s.resolveExisting(legacy) + if !found { + return rev, current, false, false, err } - return rev, nil + return rev, legacy, found, configured, err } -func (s *Store) resolveExisting() (rev string, found, configured bool, err error) { - configuredValue, configErr := s.jj("config", "get", "revset-aliases."+Alias) +func (s *Store) resolveExisting(n naming) (rev string, found, configured bool, err error) { + configuredValue, configErr := s.jj("config", "get", "revset-aliases."+n.alias) if configErr == nil { - rev, err = s.logValue("exactly("+Alias+", 1)", "change_id") + rev, err = s.logValue("exactly("+n.alias+", 1)", "change_id") if err != nil { - return "", false, true, fmt.Errorf("repo-local revset alias %s is invalid: %w", Alias, err) + return "", false, true, fmt.Errorf("repo-local revset alias %s is invalid: %w", n.alias, err) } - valid := fmt.Sprintf("exactly(%s & root()+ & subject(exact:%s), 1)", Alias, strconv.Quote(Description)) + valid := fmt.Sprintf("exactly(%s & root()+ & subject(exact:%s), 1)", n.alias, strconv.Quote(n.description)) if _, err := s.logValue(valid, "change_id"); err != nil { - return "", false, true, fmt.Errorf("repo-local revset alias %s=%q does not name vr's sidecar: %w", - Alias, strings.TrimSpace(configuredValue), err) + return "", false, true, fmt.Errorf("repo-local revset alias %s=%q does not name notevi's sidecar: %w", + n.alias, strings.TrimSpace(configuredValue), err) } return rev, true, true, nil } - ids, err := s.descriptionMatches() + ids, err := s.descriptionMatches(n.description) if err != nil { return "", false, false, err } @@ -226,12 +344,12 @@ func (s *Store) resolveExisting() (rev string, found, configured bool, err error case 1: return ids[0], true, false, nil default: - return "", false, false, fmt.Errorf("found %d root children described %q; cannot choose a vr sidecar", len(ids), Description) + return "", false, false, fmt.Errorf("found %d root children described %q; cannot choose a notevi sidecar", len(ids), n.description) } } -func (s *Store) descriptionMatches() ([]string, error) { - revset := fmt.Sprintf("root()+ & subject(exact:%s)", strconv.Quote(Description)) +func (s *Store) descriptionMatches(description string) ([]string, error) { + revset := fmt.Sprintf("root()+ & subject(exact:%s)", strconv.Quote(description)) out, err := s.jj("log", "-G", "-r", revset, "-T", "change_id ++ \"\\n\"") if err != nil { return nil, err @@ -255,20 +373,44 @@ func (s *Store) logValue(revset, template string) (string, error) { return value, nil } -func (s *Store) readRevision(rev string) ([]byte, error) { - listed, err := s.jj("file", "list", "-r", rev, "--", LogFile) +func (s *Store) readRevision(rev, logFile string) ([]byte, error) { + listed, err := s.jj("file", "list", "-r", rev, "--", logFile) if err != nil { return nil, err } if strings.TrimSpace(listed) == "" { return nil, nil } - out, err := s.jj("file", "show", "-r", rev, "--", LogFile) + out, err := s.jj("file", "show", "-r", rev, "--", logFile) return []byte(out), err } -func (s *Store) runAppend(data []byte) error { - f, err := os.CreateTemp(filepath.Dir(s.lockPath), "vr-log-append-*") +// ensureLogFile creates the log file, empty, if the sidecar does not have it. +// +// This is load-bearing, not tidiness. jj only auto-tracks a *new* file in the +// run working copy while it is under snapshot.max-new-file-size, and the run +// working copy does not take that limit from the command line, so writing a +// whole log under a name the change has never held is silently dropped — the +// commit is rewritten with the file missing and jj reports success. Writing the +// file empty first is always under the limit; from then on every byte is a +// modification of a tracked file, which snapshots at any size. +func (s *Store) ensureLogFile(rev string) error { + listed, err := s.jj("file", "list", "-r", rev, "--", LogFile) + if err != nil { + return err + } + if strings.TrimSpace(listed) != "" { + return nil + } + _, err = s.jjRun(rev, ": > "+LogFile) + return err +} + +func (s *Store) runAppend(rev string, data []byte) error { + if err := s.ensureLogFile(rev); err != nil { + return err + } + f, err := os.CreateTemp(s.configDir, "notevi-log-append-*") if err != nil { return err } @@ -281,13 +423,20 @@ func (s *Store) runAppend(data []byte) error { if err := f.Close(); err != nil { return err } - _, err = s.jj("--config", "snapshot.auto-track=\"all()\"", - "--config", "snapshot.max-new-file-size=\"1GiB\"", - "run", "--clean", "--root", "-r", "exactly("+Alias+", 1)", "--", - "sh", "-c", "cat \"$1\" >> "+LogFile, "sh", tmp) + _, err = s.jjRun(rev, "cat \"$1\" >> "+LogFile, tmp) return err } +// jjRun rewrites the sidecar change by running script against a clean checkout +// of it. rev is a change id or alias; the working copy is never involved. +func (s *Store) jjRun(rev, script string, scriptArgs ...string) (string, error) { + args := []string{"--config", "snapshot.auto-track=\"all()\"", + "--config", "snapshot.max-new-file-size=\"1GiB\"", + "run", "--clean", "--root", "-r", "exactly((" + rev + "), 1)", "--", + "sh", "-c", script, "sh"} + return s.jj(append(args, scriptArgs...)...) +} + func (s *Store) jj(args ...string) (string, error) { return jjOutput(s.root, args...) } @@ -324,6 +473,26 @@ func containsRevsetName(expr, name string) bool { return false } +// replaceRevsetName swaps whole revset names, so that rewriting an expression +// mentioning vr_log cannot corrupt an unrelated name that merely contains it. +func replaceRevsetName(expr, name, replacement string) string { + var b strings.Builder + for i := 0; i < len(expr); { + if expr[i:min(i+len(name), len(expr))] == name { + before := i == 0 || !isNameByte(expr[i-1]) + after := i+len(name) == len(expr) || !isNameByte(expr[i+len(name)]) + if before && after { + b.WriteString(replacement) + i += len(name) + continue + } + } + b.WriteByte(expr[i]) + i++ + } + return b.String() +} + func isNameByte(b byte) bool { return b == '_' || b == '-' || b >= 'a' && b <= 'z' || b >= 'A' && b <= 'Z' || b >= '0' && b <= '9' } diff --git a/sidecar/store_test.go b/sidecar/store_test.go index 85f50e1..8ce3192 100644 --- a/sidecar/store_test.go +++ b/sidecar/store_test.go @@ -5,6 +5,7 @@ import ( "os" "os/exec" "path/filepath" + "strconv" "strings" "sync" "testing" @@ -72,19 +73,19 @@ func TestAppendCreatesPrivateUnrelatedSidecar(t *testing.T) { func TestLegacyLogIsReadThenImportedOnFirstAppend(t *testing.T) { repo := testRepo(t) - legacy := []byte("legacy\n") - if err := os.WriteFile(filepath.Join(repo, LogFile), legacy, 0o644); err != nil { + data := []byte("legacy\n") + if err := os.WriteFile(filepath.Join(repo, legacy.logFile), data, 0o644); err != nil { t.Fatal(err) } store, err := Open(repo) if err != nil { t.Fatal(err) } - if got, err := store.Read(); err != nil || string(got) != string(legacy) { + if got, err := store.Read(); err != nil || string(got) != string(data) { t.Fatalf("pre-migration read = %q, %v", got, err) } if err := store.Append(func(current []byte) ([]byte, error) { - if string(current) != string(legacy) { + if string(current) != string(data) { t.Fatalf("migration callback saw %q", current) } return []byte("sidecar\n"), nil @@ -96,6 +97,131 @@ func TestLegacyLogIsReadThenImportedOnFirstAppend(t *testing.T) { } } +// A repository written by the pre-rebrand tool must keep working, and must stop +// carrying the old name once notevi has touched it. +func TestPreRebrandSidecarIsRenamedInPlace(t *testing.T) { + repo := testRepo(t) + rev := writeLegacySidecar(t, repo, "old\n") + + store, err := Open(repo) + if err != nil { + t.Fatal(err) + } + if got, err := store.Read(); err != nil || string(got) != "old\n" { + t.Fatalf("read of an un-migrated sidecar = %q, %v", got, err) + } + + migrated, err := store.Migrate() + if err != nil { + t.Fatal(err) + } + if !migrated { + t.Fatal("Migrate reported nothing to do for a legacy sidecar") + } + + if got := strings.TrimSpace(testJJ(t, repo, "config", "get", "revset-aliases."+Alias)); got != rev { + t.Fatalf("alias %s = %q, want the original change %q", Alias, got, rev) + } + if out, err := exec.Command("jj", "--ignore-working-copy", "-R", repo, + "config", "get", "revset-aliases."+legacy.alias).CombinedOutput(); err == nil { + t.Fatalf("legacy alias %s survived: %s", legacy.alias, out) + } + private := testJJ(t, repo, "config", "get", "git.private-commits") + if !containsRevsetName(private, Alias) || containsRevsetName(private, legacy.alias) { + t.Fatalf("private commits = %q, want %s and not %s", private, Alias, legacy.alias) + } + files := testJJ(t, repo, "file", "list", "-r", "exactly("+Alias+", 1)") + if !strings.Contains(files, LogFile) || strings.Contains(files, legacy.logFile) { + t.Fatalf("sidecar files = %q, want only %s", files, LogFile) + } + subject := strings.TrimSpace(testJJ(t, repo, "log", "-G", + "-r", "exactly("+Alias+", 1)", "-T", "description")) + if subject != Description { + t.Fatalf("sidecar description = %q, want %q", subject, Description) + } + + // The trace survived the rename and the store keeps appending to it. + if err := store.Append(func(current []byte) ([]byte, error) { + if string(current) != "old\n" { + t.Fatalf("append after migration saw %q", current) + } + return []byte("new\n"), nil + }); err != nil { + t.Fatal(err) + } + if got, err := store.Read(); err != nil || string(got) != "old\nnew\n" { + t.Fatalf("migrated log = %q, %v", got, err) + } + if again, err := store.Migrate(); err != nil || again { + t.Fatalf("second Migrate = %v, %v; want no-op", again, err) + } +} + +// A real trace is hundreds of KB. jj silently declines to auto-track a *new* +// file in the run working copy past a size limit it does not take from the +// command line, so a rename that writes the whole log under a name the change +// has never held loses it — with jj reporting success. Small fixtures do not +// catch that; this one does. +func TestLargeLogSurvivesRenameAndAppend(t *testing.T) { + repo := testRepo(t) + var seed strings.Builder + for i := range 5000 { + fmt.Fprintf(&seed, `{"time":"2026-07-26T10:00:00Z","op":"read","file":"src/%d.rs","start":1,"end":400}`+"\n", i) + } + if seed.Len() < 256<<10 { + t.Fatalf("fixture is only %d bytes; too small to exercise the limit", seed.Len()) + } + writeLegacySidecar(t, repo, seed.String()) + + store, err := Open(repo) + if err != nil { + t.Fatal(err) + } + if _, err := store.Migrate(); err != nil { + t.Fatal(err) + } + got, err := store.Read() + if err != nil { + t.Fatal(err) + } + if string(got) != seed.String() { + t.Fatalf("renamed log is %d bytes, want %d", len(got), seed.Len()) + } + if err := store.Append(func([]byte) ([]byte, error) { return []byte(`{"op":"note"}`), nil }); err != nil { + t.Fatal(err) + } + if got, err = store.Read(); err != nil || len(got) <= seed.Len() { + t.Fatalf("append after a large rename left %d bytes, %v", len(got), err) + } +} + +// writeLegacySidecar builds the sidecar exactly as the pre-rebrand tool did and +// returns its change id. +func writeLegacySidecar(t *testing.T, repo, content string) string { + t.Helper() + testJJ(t, repo, "new", "--no-edit", "root()", "-m", legacy.description) + rev := strings.TrimSpace(testJJ(t, repo, "log", "-G", "-T", "change_id", + "-r", fmt.Sprintf("root()+ & subject(exact:%q)", legacy.description))) + tmp := filepath.Join(t.TempDir(), "seed") + if err := os.WriteFile(tmp, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + // Touch first, then fill: the same two steps the store uses, so a large + // fixture really lands in the sidecar instead of quietly seeding nothing. + testJJ(t, repo, "--config", `snapshot.auto-track="all()"`, + "run", "--clean", "--root", "-r", "exactly("+rev+", 1)", "--", + "sh", "-c", ": > "+legacy.logFile) + testJJ(t, repo, "--config", `snapshot.auto-track="all()"`, + "run", "--clean", "--root", "-r", "exactly("+rev+", 1)", "--", + "sh", "-c", "cat \"$1\" >> "+legacy.logFile, "sh", tmp) + if got := testJJ(t, repo, "file", "show", "-r", "exactly("+rev+", 1)", "--", legacy.logFile); got != content { + t.Fatalf("legacy fixture is %d bytes in the sidecar, want %d", len(got), len(content)) + } + testJJ(t, repo, "config", "set", "--repo", "revset-aliases."+legacy.alias, strconv.Quote(rev)) + testJJ(t, repo, "config", "set", "--repo", "git.private-commits", strconv.Quote("(none()) | "+legacy.alias)) + return rev +} + func TestConcurrentAppendsAreSerialized(t *testing.T) { repo := testRepo(t) store, err := Open(repo) diff --git a/vrsite/app_test.go b/vrsite/app_test.go deleted file mode 100644 index 876e253..0000000 --- a/vrsite/app_test.go +++ /dev/null @@ -1,912 +0,0 @@ -package main - -import ( - "crypto/sha256" - "fmt" - "net/http" - "net/http/httptest" - "net/url" - "os" - "os/exec" - "path/filepath" - "regexp" - "strings" - "testing" - "time" - - "0x4200.cafe/vr/sidecar" -) - -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 -} - -// testThemes stands in for whatever themes this machine happens to have, so -// the picker's two files are the same in every test run. -func testThemes(dark, light *Theme) *themeSet { - return themesFrom([]*Theme{dark, light}, dark, light) -} - -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") - } -} - -func TestNoteThreadRecursesThroughRepliesAndMentions(t *testing.T) { - entries := parseLog([]byte(logLines( - `{"op":"note","session":"s","agent":"a","change":"aaa","note_id":1,"text":"root"}`, - `{"op":"note","session":"s","agent":"a","change":"aaa","note_id":2,"reply_to":1,"text":"child"}`, - `{"op":"note","session":"s","agent":"a","change":"aaa","note_id":3,"reply_to":2,"text":"grandchild"}`, - `{"op":"note","session":"s","agent":"a","change":"aaa","note_id":4,"text":"[mentions root](../note/1.html)"}`, - `{"op":"note","session":"s","agent":"a","change":"aaa","note_id":5,"reply_to":3,"text":"[also mentions child](note/2)"}`, - `{"op":"note","session":"s","agent":"a","change":"aaa","note_id":6,"reply_to":5,"text":"arbitrarily deeper"}`, - ))) - s := buildModel("test", entries, "") - root, child := s.NoteByID(1), s.NoteByID(2) - if len(root.Replies) != 1 || root.Replies[0].ID != 2 || len(root.Mentions) != 1 || root.Mentions[0].ID != 4 { - t.Fatalf("root edges = replies %+v, mentions %+v", root.Replies, root.Mentions) - } - if len(child.Mentions) != 1 || child.Mentions[0].ID != 5 { - t.Fatalf("child mentions = %+v", child.Mentions) - } - - thread := s.NoteThread(1) - if thread == nil || len(thread.Children) != 2 || thread.Children[0].Via != "reply" || thread.Children[1].Via != "mention" { - t.Fatalf("root thread = %+v", thread) - } - // 1 → 2 → 3 → 5 → 6 proves the renderer's data is recursive rather - // than a fixed parent/child pair. - deep := thread.Children[0].Children[0].Children[0] - if deep.Note.ID != 5 || len(deep.Children) != 1 || deep.Children[0].Note.ID != 6 { - t.Fatalf("deep reply branch = %+v", deep) - } - // Note 5 also mentions note 2. It is fully rendered under note 3, then left - // as a DAG reference on the second path instead of recursing twice. - join := thread.Children[0].Children[1] - if join.Note.ID != 5 || !join.Reference || join.Via != "mention" { - t.Errorf("DAG join = %+v", join) - } -} - -// 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< setMode(b.dataset.mode)); -setMode(root.dataset.mode || "trace"); - -const typing = e => - /^(INPUT|TEXTAREA|SELECT)$/.test(e.target.tagName) || e.target.isContentEditable; - -// The project hub is fully server-derived; filtering is deliberately local so -// choosing a project does not create another piece of server state. -const projectFind = document.getElementById("projectfind"); -if (projectFind) { - const apply = () => { - const q = projectFind.value.trim().toLowerCase(); - for (const card of document.querySelectorAll(".project-card")) - card.hidden = !!q && !(card.dataset.project || "").toLowerCase().includes(q); - }; - projectFind.addEventListener("input", apply); - projectFind.addEventListener("search", apply); - projectFind.addEventListener("keydown", e => { - if (e.key === "Escape") { projectFind.value = ""; apply(); projectFind.blur(); } - if (e.key === "Enter") { - const first = document.querySelector(".project-card:not([hidden]) a.project-action"); - if (first) first.click(); - } - }); -} - -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 ───────────────────────────────────────────────────────────────── -// Every theme this machine has is a :root block in themes.css, so wearing one -// is a single attribute — and the menu can therefore preview as it moves. -// Arrow through it or hover and the page changes under you; enter keeps what -// you are wearing, escape puts back the one you came with. -// -// themes.css and themes.js are fetched the first time the menu opens (the -// stylesheet earlier than that, from the head, when a theme is already -// chosen), so a reader who never switches pays nothing for them. -const pick = document.getElementById("themepick"); -if (pick) { - const btn = document.getElementById("themebtn"), - menu = document.getElementById("thememenu"), - find = document.getElementById("themefind"), - list = document.getElementById("themelist"); - const builtin = [ - {id: "system", name: "system", src: "follows the browser"}, - {id: "dark", name: pick.dataset.dark, src: "built with · dark"}, - {id: "light", name: pick.dataset.light, src: "built with · light"}, - ]; - let cur = localStorage.getItem("vrsite-theme") || "system"; - let active = null, filled = false, pending = null; - - const wear = id => { - if (id === "system") delete root.dataset.theme; - else root.dataset.theme = id; - }; - // the name of a theme we may not have the menu for yet: kept beside the id - // so the button says something true before themes.js has loaded - const label = id => { - const b = builtin.find(t => t.id === id); - if (b) return b.name; - const t = (window.VRSITE_THEMES || []).find(t => t.id === id); - return t ? t.name : localStorage.getItem("vrsite-theme-name") || - id.replace(/^[^/]*\//, "").replace(/[-_]/g, " "); - }; - btn.textContent = label(cur); - - // themes.css is a link and themes.js a script, not a fetch: the static - // export is opened from the filesystem, where fetch() is not allowed - const ensure = () => { - if (!document.getElementById("themescss")) { - const l = document.createElement("link"); - l.rel = "stylesheet"; l.id = "themescss"; l.href = pick.dataset.css; - document.head.append(l); - } - if (window.VRSITE_THEMES) return Promise.resolve(); - if (!pending) pending = new Promise(done => { - const s = document.createElement("script"); - s.src = pick.dataset.js; - s.onload = s.onerror = done; - document.head.append(s); - }); - return pending; - }; - - const row = t => { - const li = document.createElement("li"); - li.setAttribute("role", "option"); - li.id = "themeopt-" + list.children.length; - li.dataset.id = t.id; - li.dataset.q = (t.name + " " + t.src + " " + t.id).toLowerCase(); - const sw = document.createElement("span"); - sw.className = t.sw ? "sw" : "sw none"; // empty, but the names still line up - for (const c of t.sw || []) { - const chip = document.createElement("i"); - chip.style.background = c; - sw.append(chip); - } - li.append(sw); - const nm = document.createElement("span"); - nm.className = "nm"; - nm.textContent = t.name; - const src = document.createElement("span"); - src.className = "src"; - src.textContent = t.src; - li.append(nm, src); - return li; - }; - - const fill = () => { - if (filled) return; - filled = true; - // the two the site was built with are usually in the menu as well, so the - // rows for them can wear the same swatch — and "system", both at once - const all = window.VRSITE_THEMES || []; - const swOf = id => (all.find(t => t.id === id) || {}).sw; - const dsw = swOf(pick.dataset.darkid), lsw = swOf(pick.dataset.lightid); - builtin[0].sw = dsw && lsw && [...dsw.slice(0, 3), ...lsw.slice(0, 3)]; - builtin[1].sw = dsw; - builtin[2].sw = lsw; - for (const t of builtin) list.append(row(t)); - for (const t of window.VRSITE_THEMES || []) - list.append(row({...t, src: t.src + (t.dark ? " · dark" : " · light")})); - if (list.children.length === builtin.length) { - const p = document.createElement("li"); - p.className = "meta"; - p.textContent = "no zed or helix themes found on this machine"; - list.append(p); - } - }; - - const setActive = (li, preview = true) => { - if (!li || li === active) return; - if (active) { - active.classList.remove("on"); - active.removeAttribute("aria-selected"); - } - active = li; - li.classList.add("on"); - li.setAttribute("aria-selected", "true"); - find.setAttribute("aria-activedescendant", li.id); - li.scrollIntoView({block: "nearest"}); - if (preview) wear(li.dataset.id); - }; - - const rows = () => [...list.querySelectorAll("li[data-id]:not([hidden])")]; - const rowFor = id => list.querySelector('li[data-id="' + CSS.escape(id) + '"]'); - - const filter = () => { - const q = find.value.trim().toLowerCase(); - for (const li of list.children) - li.hidden = !!q && !(li.dataset.q || "").includes(q); - if (!active || active.hidden) setActive(rows()[0]); - }; - find.addEventListener("input", filter); - - const open = () => { - if (!menu.hidden) return; - menu.hidden = false; - btn.setAttribute("aria-expanded", "true"); - find.value = ""; - find.focus(); - ensure().then(() => { - fill(); - filter(); - for (const li of list.querySelectorAll("li.cur")) li.classList.remove("cur"); - const here = rowFor(cur); - if (here) here.classList.add("cur"); - setActive(here || rows()[0], false); - }); - }; - - // leaving the menu either keeps what is on screen or puts back what was - // there before it opened — nothing is stored until it is kept - const close = keep => { - if (menu.hidden) return; - if (keep && active) { - cur = active.dataset.id; - localStorage.setItem("vrsite-theme", cur); - localStorage.setItem("vrsite-theme-name", label(cur)); - btn.textContent = label(cur); - for (const li of list.querySelectorAll("li.cur")) li.classList.remove("cur"); - active.classList.add("cur"); - } - wear(cur); - menu.hidden = true; - btn.setAttribute("aria-expanded", "false"); - }; - - btn.addEventListener("click", () => (menu.hidden ? open() : close(false))); - // mousemove, not mouseover: arrowing scrolls rows under a still pointer, - // and the pointer must not then take the selection back - list.addEventListener("mousemove", e => { - const li = e.target.closest("li[data-id]"); - if (li) setActive(li); - }); - list.addEventListener("click", e => { - const li = e.target.closest("li[data-id]"); - if (li) { setActive(li); close(true); } - }); - find.addEventListener("keydown", e => { - if (e.key === "ArrowDown" || e.key === "ArrowUp") { - e.preventDefault(); - const all = rows(); - if (!all.length) return; - const i = all.indexOf(active), step = e.key === "ArrowDown" ? 1 : -1; - setActive(all[(i + step + all.length) % all.length]); - } else if (e.key === "Enter") { - e.preventDefault(); - close(true); - btn.focus(); - } else if (e.key === "Escape") { - e.preventDefault(); - close(false); - btn.focus(); - } - }); - document.addEventListener("click", e => { - if (!menu.hidden && !pick.contains(e.target)) close(false); - }); - document.addEventListener("keydown", e => { - if (e.key === "Escape") close(false); - if (e.key === "T" && !e.metaKey && !e.ctrlKey && !e.altKey && !typing(e)) { - e.preventDefault(); // or the T lands in the filter we just focused - open(); - } - }); -} - -// ── nav tree ────────────────────────────────────────────────────────────── -const nav = document.getElementById("nav"); -const tree = document.getElementById("tree"); -const state = JSON.parse(localStorage.getItem("vrsite-tree") || "{}"); - -// The file tree can get out of the way without losing repository context or -// the navigation footer. Keep the choice across page loads in this browser. -const fileList = document.getElementById("filelist"); -const fileToggle = document.getElementById("filetoggle"); -if (fileList && fileToggle) { - const setFilesHidden = hidden => { - root.dataset.files = hidden ? "hidden" : "shown"; - fileToggle.setAttribute("aria-expanded", String(!hidden)); - fileToggle.textContent = hidden ? "show files" : "hide files"; - localStorage.setItem("vrsite-files-hidden", hidden ? "1" : "0"); - }; - setFilesHidden(localStorage.getItem("vrsite-files-hidden") === "1"); - fileToggle.addEventListener("click", () => setFilesHidden(root.dataset.files !== "hidden")); -} - -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 = '

tree needs http — use the file index

'; - }); -} - -// ── 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(); - }); - -// ── conversation ────────────────────────────────────────────────────────── -// A session page opened from a note lands on that note, flashed the same way -// clicking a noted line flashes it. -const conv = document.querySelector(".conv[data-anchor]"); -if (conv && conv.dataset.anchor) { - const here = document.getElementById(conv.dataset.anchor); - if (here) { - here.scrollIntoView({block: "start"}); - here.classList.remove("flash"); void here.offsetWidth; here.classList.add("flash"); - } -} - -// The trip back: a note in a conversation opens the code it was written -// about. The card is the target, so aim anywhere on it — except at the links -// it already carries. -const goTo = w => { location.href = w.dataset.href; }; -for (const w of document.querySelectorAll(".notewrap[data-href]")) { - w.addEventListener("click", e => { if (!e.target.closest("a")) goTo(w); }); - w.addEventListener("keydown", e => { - if (e.key === "Enter" || e.key === " ") { e.preventDefault(); goTo(w); } - }); -} - -// ── arriving at a note ──────────────────────────────────────────────────── -// ?note=N means someone followed a note here rather than opening the file: -// show what they came for — notes focus (coverage hides the note), the card -// flashed in the pane, the lines it covers marked. -// A permalink is the same arrival with nothing to scroll to: the page is the -// note, so it only needs the focus that shows notes at all. -if (document.body.dataset.kind === "note") setMode("notes"); - -const want = new URLSearchParams(location.search).get("note"); -if (want && document.body.dataset.kind === "file" && /^\d+$/.test(want)) { - setMode("notes"); - const card = document.getElementById("note-" + want); - if (card) { - // the card's own range, not the lines' data-note: a line belongs to the - // first note that claimed it, so overlapping notes would mark nothing - const from = +card.dataset.start, to = +card.dataset.end || +card.dataset.start; - let first = null; - for (let n = from; n > 0 && n <= to; n++) { - const li = document.getElementById("L" + n); - if (!li) continue; - li.classList.add("focus"); - first = first || li; - } - // after the browser has had its own go at the #L anchor - if (first) requestAnimationFrame(() => first.scrollIntoView({block: "center"})); - card.scrollIntoView({block: "nearest"}); - card.classList.remove("flash"); void card.offsetWidth; card.classList.add("flash"); - } -} - -// ── 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")) { - // the whole rendered body, not its first

: a note is markdown, so it - // may open with a list or a code fence and run to several blocks - const d = art.dataset, el = art.querySelector(".body"); - const body = (el ? el.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/bash.scm b/vrsite/assets/bash.scm deleted file mode 100644 index 4c7926a..0000000 --- a/vrsite/assets/bash.scm +++ /dev/null @@ -1,21 +0,0 @@ -; Bash highlights, from tree-sitter/tree-sitter-bash v0.25.1 -; queries/highlights.scm (MIT). Reordered so expansions stay visible inside the -; strings that contain them, and capture names mapped onto zed syntax keys. -; Upstream's @embedded captures are dropped: zed paints `embedded` as plain -; foreground, so they only cost query time. - -["$" "&&" "||" ">" ">>" "<" "|" ";" "=" "!"] @operator - -["case" "do" "done" "elif" "else" "esac" "export" "fi" "for" "function" "if" - "in" "local" "readonly" "select" "then" "unset" "until" "while"] @keyword - -[(string) (raw_string) (heredoc_body) (heredoc_start)] @string -(variable_name) @property -(file_descriptor) @number - -(command_name) @function -(function_definition name: (word) @function) -((command (_) @constant) - (#match? @constant "^-")) - -(comment) @comment diff --git a/vrsite/assets/c.scm b/vrsite/assets/c.scm deleted file mode 100644 index 789bf93..0000000 --- a/vrsite/assets/c.scm +++ /dev/null @@ -1,36 +0,0 @@ -; C highlights, from tree-sitter/tree-sitter-c v0.24.2 queries/highlights.scm -; (MIT). Reordered for later-patterns-win, capture names mapped onto zed syntax -; keys (preprocessor directives get @preproc rather than upstream's @keyword, -; which zed themes colour separately). Also loaded ahead of cpp.scm, the way -; upstream composes the C++ highlights. - -["(" ")" "[" "]" "{" "}"] @punctuation.bracket -[";" "," "."] @punctuation.delimiter -["--" "-" "-=" "->" "=" "!=" "*" "&" "&&" "+" "++" "+=" "<" "==" ">" - "||"] @operator - -["break" "case" "const" "continue" "default" "do" "else" "enum" "extern" - "for" "if" "inline" "return" "sizeof" "static" "struct" "switch" "typedef" - "union" "volatile" "while"] @keyword - -["#define" "#elif" "#else" "#endif" "#if" "#ifdef" "#ifndef" - "#include"] @preproc -(preproc_directive) @preproc - -[(type_identifier) (primitive_type) (sized_type_specifier)] @type -(field_identifier) @property -(statement_identifier) @label -((identifier) @constant - (#match? @constant "^[A-Z][A-Z0-9_]*$")) - -(call_expression function: (identifier) @function) -(call_expression function: (field_expression - field: (field_identifier) @function.method)) -(function_declarator declarator: (identifier) @function) -(preproc_function_def name: (identifier) @function) - -(number_literal) @number -(null) @constant -[(string_literal) (char_literal) (system_lib_string)] @string -(escape_sequence) @string.escape -(comment) @comment diff --git a/vrsite/assets/cpp.scm b/vrsite/assets/cpp.scm deleted file mode 100644 index e939a7a..0000000 --- a/vrsite/assets/cpp.scm +++ /dev/null @@ -1,25 +0,0 @@ -; C++ highlights, from tree-sitter/tree-sitter-cpp v0.23.4 -; queries/highlights.scm (MIT). A supplement loaded after c.scm, as upstream -; composes it, so these patterns win. Capture names mapped onto zed syntax -; keys; `this` gets @variable.special to match what rust.scm does for `self`. - -["catch" "class" "co_await" "co_return" "co_yield" "constexpr" "constinit" - "consteval" "delete" "explicit" "final" "friend" "mutable" "namespace" - "noexcept" "new" "override" "private" "protected" "public" "template" - "throw" "try" "typename" "using" "concept" "requires" "virtual"] @keyword - -(auto) @type -((namespace_identifier) @type - (#match? @type "^[A-Z]")) - -(call_expression function: (qualified_identifier - name: (identifier) @function)) -(template_function name: (identifier) @function) -(template_method name: (field_identifier) @function.method) -(function_declarator declarator: (qualified_identifier - name: (identifier) @function)) -(function_declarator declarator: (field_identifier) @function.method) - -(raw_string_literal) @string -(this) @variable.special -(null "nullptr" @constant) diff --git a/vrsite/assets/go.scm b/vrsite/assets/go.scm deleted file mode 100644 index 56f676c..0000000 --- a/vrsite/assets/go.scm +++ /dev/null @@ -1,34 +0,0 @@ -; Go highlights, from tree-sitter/tree-sitter-go v0.25.0 queries/highlights.scm -; (MIT). Reordered — upstream is written first-pattern-wins, this engine paints -; later patterns over earlier ones — capture names mapped onto zed syntax keys, -; and the builtin-function #match? turned into #any-of?, which needs no regex. - -["(" ")" "[" "]" "{" "}"] @punctuation.bracket -[";" "," "." ":"] @punctuation.delimiter -["--" "-" "-=" ":=" "!" "!=" "..." "*" "*=" "/" "/=" "&" "&&" "&=" "%" "%=" - "^" "^=" "+" "++" "+=" "<-" "<" "<<" "<<=" "<=" "=" "==" ">" ">=" ">>" ">>=" - "|" "|=" "||" "~"] @operator - -["break" "case" "chan" "const" "continue" "default" "defer" "else" - "fallthrough" "for" "func" "go" "goto" "if" "import" "interface" "map" - "package" "range" "return" "select" "struct" "switch" "type" "var"] @keyword - -(type_identifier) @type -(field_identifier) @property -(label_name) @label - -(function_declaration name: (identifier) @function) -(method_declaration name: (field_identifier) @function.method) -(call_expression function: (identifier) @function) -(call_expression function: (selector_expression - field: (field_identifier) @function.method)) -((call_expression function: (identifier) @function.builtin) - (#any-of? @function.builtin "append" "cap" "clear" "close" "complex" "copy" - "delete" "imag" "len" "make" "max" "min" "new" "panic" "print" "println" - "real" "recover")) - -[(int_literal) (float_literal) (imaginary_literal)] @number -[(true) (false) (nil) (iota)] @constant -[(interpreted_string_literal) (raw_string_literal) (rune_literal)] @string -(escape_sequence) @string.escape -(comment) @comment diff --git a/vrsite/assets/htmx.min.js b/vrsite/assets/htmx.min.js deleted file mode 100644 index c62505f..0000000 --- a/vrsite/assets/htmx.min.js +++ /dev/null @@ -1,2 +0,0 @@ -/* 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(/]*)?>[\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('");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=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"){t--}}if(n0){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=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;e0){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","

");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(n0}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;t0){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;e0){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;e0){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", "+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;eQ.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=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;en.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;e0?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;t0){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"," ."+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;} ")}}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/javascript-params.scm b/vrsite/assets/javascript-params.scm deleted file mode 100644 index db300e3..0000000 --- a/vrsite/assets/javascript-params.scm +++ /dev/null @@ -1,12 +0,0 @@ -; JavaScript parameters, from tree-sitter/tree-sitter-javascript v0.25.0 -; queries/highlights-params.scm (MIT), verbatim. Its own file because upstream -; keeps it out of the TypeScript composition: there a formal_parameters child -; is always a required_parameter or optional_parameter, so these patterns are -; not merely dead but rejected by the query compiler as impossible. - -(formal_parameters [ - (identifier) @variable.parameter - (array_pattern (identifier) @variable.parameter) - (object_pattern [ - (pair_pattern value: (identifier) @variable.parameter) - (shorthand_property_identifier_pattern) @variable.parameter])]) diff --git a/vrsite/assets/javascript.scm b/vrsite/assets/javascript.scm deleted file mode 100644 index a5c8f01..0000000 --- a/vrsite/assets/javascript.scm +++ /dev/null @@ -1,52 +0,0 @@ -; JavaScript highlights, from tree-sitter/tree-sitter-javascript v0.25.0 -; queries/highlights.scm (MIT). Reordered for later-patterns-win and capture -; names mapped onto zed syntax keys. Upstream's @variable.builtin and require() -; patterns are gone: they lean on (#is-not? local), which no query engine -; outside nvim evaluates. Also loaded ahead of typescript.scm, the way upstream -; composes the TypeScript highlights. - -["(" ")" "[" "]" "{" "}"] @punctuation.bracket -[";" (optional_chain) "." ","] @punctuation.delimiter -["-" "--" "-=" "+" "++" "+=" "*" "*=" "**" "**=" "/" "/=" "%" "%=" "<" "<=" - "<<" "<<=" "=" "==" "===" "!" "!=" "!==" "=>" ">" ">=" ">>" ">>=" ">>>" - ">>>=" "~" "^" "&" "|" "^=" "&=" "|=" "&&" "||" "??" "&&=" "||=" - "??="] @operator - -["as" "async" "await" "break" "case" "catch" "class" "const" "continue" - "debugger" "default" "delete" "do" "else" "export" "extends" "finally" "for" - "from" "function" "get" "if" "import" "in" "instanceof" "let" "new" "of" - "return" "set" "static" "switch" "target" "throw" "try" "typeof" "var" - "void" "while" "with" "yield"] @keyword - -[(property_identifier) (shorthand_property_identifier)] @property - -((identifier) @constructor - (#match? @constructor "^[A-Z]")) -([(identifier) (shorthand_property_identifier) - (shorthand_property_identifier_pattern)] @constant - (#match? @constant "^[A-Z_][A-Z0-9_]+$")) - -(function_expression name: (identifier) @function) -(function_declaration name: (identifier) @function) -(method_definition name: (property_identifier) @function.method) -(pair key: (property_identifier) @function.method - value: [(function_expression) (arrow_function)]) -(assignment_expression - left: (member_expression property: (property_identifier) @function.method) - right: [(function_expression) (arrow_function)]) -(variable_declarator name: (identifier) @function - value: [(function_expression) (arrow_function)]) -(assignment_expression left: (identifier) @function - right: [(function_expression) (arrow_function)]) -(call_expression function: (identifier) @function) -(call_expression function: (member_expression - property: (property_identifier) @function.method)) - -[(this) (super)] @variable.special -(number) @number -[(true) (false) (null) (undefined)] @constant -[(string) (template_string)] @string -(escape_sequence) @string.escape -(regex) @string.regex -(template_substitution "${" @punctuation.special "}" @punctuation.special) -(comment) @comment diff --git a/vrsite/assets/json.scm b/vrsite/assets/json.scm deleted file mode 100644 index e82e125..0000000 --- a/vrsite/assets/json.scm +++ /dev/null @@ -1,13 +0,0 @@ -; JSON highlights, from tree-sitter/tree-sitter-json v0.24.8 -; queries/highlights.scm (MIT). Reordered so object keys repaint the string -; they are; capture names are already zed syntax keys but for @escape. - -["{" "}" "[" "]"] @punctuation.bracket -[":" ","] @punctuation.delimiter - -(number) @number -[(null) (true) (false)] @constant -(string) @string -(pair key: (string) @string.special.key) -(escape_sequence) @string.escape -(comment) @comment diff --git a/vrsite/assets/jsx.scm b/vrsite/assets/jsx.scm deleted file mode 100644 index 708eba2..0000000 --- a/vrsite/assets/jsx.scm +++ /dev/null @@ -1,16 +0,0 @@ -; JSX highlights, from tree-sitter/tree-sitter-javascript v0.25.0 -; queries/highlights-jsx.scm (MIT), verbatim but for the capture rename. -; Loaded last for .jsx and .tsx; the plain typescript grammar has no JSX nodes, -; so .ts must not get this file. - -(jsx_opening_element ["<" ">"] @punctuation.bracket) -(jsx_closing_element [""] @punctuation.bracket) -(jsx_self_closing_element ["<" "/>"] @punctuation.bracket) - -(jsx_attribute (property_identifier) @attribute) - -; lowercase names are html elements, capitalized ones are components and keep -; the @constructor javascript.scm gave them -((jsx_opening_element (identifier) @tag) (#match? @tag "^[a-z][^.]*$")) -((jsx_closing_element (identifier) @tag) (#match? @tag "^[a-z][^.]*$")) -((jsx_self_closing_element (identifier) @tag) (#match? @tag "^[a-z][^.]*$")) diff --git a/vrsite/assets/one.json b/vrsite/assets/one.json deleted file mode 100644 index 69ff0de..0000000 --- a/vrsite/assets/one.json +++ /dev/null @@ -1,112 +0,0 @@ -{ - "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/python.scm b/vrsite/assets/python.scm deleted file mode 100644 index f64e673..0000000 --- a/vrsite/assets/python.scm +++ /dev/null @@ -1,50 +0,0 @@ -; Python highlights, from tree-sitter/tree-sitter-python v0.25.0 -; queries/highlights.scm (MIT). Reordered for later-patterns-win, capture names -; mapped onto zed syntax keys, and the builtin-function #match? turned into -; #any-of?. The two casing heuristics stay regexes: nothing else can express -; "CONST_CASE" and "ClassName" over bare identifiers. - -["(" ")" "[" "]" "{" "}"] @punctuation.bracket -[";" "," "." ":"] @punctuation.delimiter -["-" "-=" "!=" "*" "**" "**=" "*=" "/" "//" "//=" "/=" "&" "&=" "%" "%=" - "^" "^=" "+" "->" "+=" "<" "<<" "<<=" "<=" "<>" "=" ":=" "==" ">" ">=" - ">>" ">>=" "|" "|=" "~" "@=" "and" "in" "is" "not" "or" "is not" - "not in"] @operator - -["as" "assert" "async" "await" "break" "class" "continue" "def" "del" "elif" - "else" "except" "exec" "finally" "for" "from" "global" "if" "import" "lambda" - "nonlocal" "pass" "print" "raise" "return" "try" "while" "with" "yield" - "match" "case"] @keyword - -((identifier) @constructor - (#match? @constructor "^[A-Z]")) -((identifier) @constant - (#match? @constant "^[A-Z][A-Z_0-9]*$")) -((identifier) @variable.special - (#any-of? @variable.special "self" "cls")) - -(type (identifier) @type) -(attribute attribute: (identifier) @property) -(function_definition name: (identifier) @function) -(call function: (identifier) @function) -(call function: (attribute attribute: (identifier) @function.method)) -((call function: (identifier) @function.builtin) - (#any-of? @function.builtin "abs" "all" "any" "ascii" "bin" "bool" - "breakpoint" "bytearray" "bytes" "callable" "chr" "classmethod" "compile" - "complex" "delattr" "dict" "dir" "divmod" "enumerate" "eval" "exec" "filter" - "float" "format" "frozenset" "getattr" "globals" "hasattr" "hash" "help" - "hex" "id" "input" "int" "isinstance" "issubclass" "iter" "len" "list" - "locals" "map" "max" "memoryview" "min" "next" "object" "oct" "open" "ord" - "pow" "print" "property" "range" "repr" "reversed" "round" "set" "setattr" - "slice" "sorted" "staticmethod" "str" "sum" "super" "tuple" "type" "vars" - "zip" "__import__")) - -[(integer) (float)] @number -[(none) (true) (false)] @constant -(string) @string -(escape_sequence) @string.escape -(interpolation "{" @punctuation.special "}" @punctuation.special) - -(decorator "@" @attribute) -(decorator [(identifier) (attribute)] @attribute) -(comment) @comment diff --git a/vrsite/assets/rust.scm b/vrsite/assets/rust.scm deleted file mode 100644 index d23fa2c..0000000 --- a/vrsite/assets/rust.scm +++ /dev/null @@ -1,48 +0,0 @@ -; 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 deleted file mode 100644 index 5ea2a40..0000000 --- a/vrsite/assets/style.css.tmpl +++ /dev/null @@ -1,590 +0,0 @@ -/* 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; } -#filetoggle { - display: block; margin: 0 0 6px auto; - background: none; color: var(--muted); border: 0; - font: inherit; font-size: 11px; padding: 1px 3px; cursor: pointer; -} -#filetoggle:hover { color: var(--fg); } -:root[data-files="hidden"] #filelist { display: none; } - -/* ── the current change ──────────────────────────────────────── - Everything on screen is read at one change: the tree, the code, the - coverage, the notes, and anything you write. It says so, always. */ -.changebar { - margin-bottom: 10px; padding: 7px 8px; - border: 1px solid var(--border); border-left: 3px solid var(--accent); - border-radius: 6px; background: var(--bg); -} -.changebar.away { border-left-color: var(--note); } -.changebar .cid { display: flex; align-items: baseline; gap: 6px; } -.changebar .lbl { color: var(--muted); font-size: 10px; text-transform: uppercase; letter-spacing: 0.06em; } -.changebar .cid code { font-size: 13px; font-weight: 600; color: var(--fg); } -.changebar .cid a code { color: var(--accent); } -.changebar .flags { color: var(--note); font-size: 10px; font-style: italic; margin-left: auto; } -.changebar .desc { - margin: 3px 0 0; font-size: 11.5px; color: var(--muted); - overflow: hidden; text-overflow: ellipsis; white-space: nowrap; -} -.changebar .counts { margin: 5px 0 0; font-size: 11px; color: var(--muted); } -.changebar .counts b { color: var(--fg); font-weight: 600; } -.changebar .away { color: var(--note); } -.changebar .scope { display: flex; gap: 0; margin-top: 7px; border: 1px solid var(--border); border-radius: 5px; overflow: hidden; } -.changebar .scope a { - flex: 1; text-align: center; padding: 2px 4px; - font-size: 11px; color: var(--muted); text-decoration: none; -} -.changebar .scope a:hover { background: var(--hover); color: var(--fg); } -.changebar .scope a.on { background: var(--hover); color: var(--fg); font-weight: 600; } -.changebar .revjump { margin-top: 6px; } -.changebar .revjump input { width: 100%; font-family: ui-monospace, Menlo, monospace; font-size: 11px; } -.changebar .back { margin: 6px 0 0; font-size: 11px; } - -/* a note written at another change: it pins to line numbers that have moved */ -.note.away { border-style: dashed; opacity: 0.82; } -.note.away:hover { opacity: 1; } -.atchg.away { color: var(--note); } -.atchg.away code { color: inherit; } -.find, .filters input, .filters select, .notform input, .notform textarea, .jjform input, .thememenu 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; -} - -/* ── the theme picker ────────────────────────────────────────── - Every theme on the machine, previewed as you move through it. The - menu is fixed rather than absolute so the scrolling tree above it - cannot clip it. */ -#themebtn { - background: var(--panel); color: var(--muted); - border: 1px solid var(--border); border-radius: 4px; - font: inherit; font-size: 11px; padding: 1px 6px; cursor: pointer; - max-width: 130px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; -} -#themebtn:hover, #themebtn[aria-expanded="true"] { color: var(--fg); background: var(--hover); } -.thememenu { - position: fixed; left: 8px; bottom: 8px; z-index: 20; - width: 264px; max-height: min(60vh, 520px); - display: flex; flex-direction: column; gap: 6px; - background: var(--panel); border: 1px solid var(--border); - border-radius: 7px; padding: 8px; - box-shadow: 0 8px 30px rgb(0 0 0 / 0.35); -} -.thememenu input { width: 100%; } -.thememenu ul { list-style: none; margin: 0; padding: 0; overflow: auto; flex: 1; } -.thememenu li { - display: flex; align-items: center; gap: 7px; - padding: 3px 5px; border-radius: 4px; cursor: pointer; - font-size: 12px; color: var(--fg); -} -/* the menu is hidden until it is opened and the filter hides rows: both are - the hidden attribute, which a display of our own would otherwise outrank */ -.thememenu[hidden], .thememenu li[hidden] { display: none; } -.thememenu li.on { background: var(--hover); } -.thememenu li .nm { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.thememenu li .src { margin-left: auto; color: var(--muted); font-size: 10px; white-space: nowrap; } -.thememenu li.cur .nm::after { content: " ✓"; color: var(--accent); } -.thememenu .sw { display: flex; flex: none; border: 1px solid var(--border); border-radius: 3px; overflow: hidden; } -.thememenu .sw i { display: block; width: 7px; height: 14px; } -.thememenu .sw.none { width: 42px; border-color: transparent; } -.thememenu .hint { margin: 0; font-size: 10px; } - -/* 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; - /* a #L42 jump must clear the sticky header, or the line lands under it */ - scroll-margin-top: 76px; -} -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; } - -/* A note body is markdown. It is prose about code inside a card that is - itself only ~320px wide in the columns, so every block here is tuned down - from document scale: headings barely outrank the text, rules and quotes are - hairlines, and nothing may push the card wider than its column. The - selectors carry .body so they outrank .turn p in the conversation view, - where notes are cards too. */ -.note .body > :first-child { margin-top: 6px; } -.note .body p, -.note .body ul, .note .body ol, .note .body blockquote, -.note .body pre, .note .body table { margin: 6px 0 0; } -.note .body p { line-height: 1.45; white-space: normal; } -.note .body :is(h1, h2, h3, h4, h5, h6) { - margin: 10px 0 0; font-size: 1em; font-weight: 600; line-height: 1.3; -} -.note .body h1, .note .body h2 { color: var(--fg); font-size: 1.05em; } -.note .body ul, .note .body ol { padding-left: 1.3em; } -.note .body li { margin: 2px 0; line-height: 1.45; } -.note .body li > p { margin: 0; } -.note .body li::marker { color: var(--muted); } -.note .body blockquote { - border-left: 2px solid var(--border); padding-left: 8px; color: var(--muted); -} -.note .body hr { border: none; border-top: 1px solid var(--border); margin: 10px 0 0; } -.note .body code { background: var(--hover); border-radius: 3px; padding: 0 3px; } -.note .body a { overflow-wrap: anywhere; } -.note .body img { max-width: 100%; height: auto; } -/* a fenced block: the code view's spans without its line-number scaffolding */ -.note .body pre.mdcode { - background: var(--panel); border: 1px solid var(--border); border-radius: 4px; - padding: 6px 8px; overflow-x: auto; - font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.92em; - line-height: 1.4; tab-size: 4; -} -.note .body pre.mdcode code { background: none; padding: 0; font-size: inherit; } -.note .body table { border-collapse: collapse; display: block; overflow-x: auto; font-size: 0.95em; } -.note .body :is(th, td) { border: 1px solid var(--border); padding: 2px 6px; text-align: left; } -.note .body th { color: var(--muted); font-weight: 600; } -.note .body input[type="checkbox"] { margin-right: 4px; vertical-align: -1px; } -@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; } -.note .conv { margin-left: auto; } -.note .parent { color: var(--muted); } -.note .relations { - color: var(--note); text-decoration: none; - background: var(--note-bg); border-radius: 3px; padding: 0 4px; -} -.note .relations:hover { color: var(--accent); text-decoration: underline; } -.notecols { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 0 14px; } - -/* the permalink: the one link on a card that names nothing but the note, so - it is the one to hand someone else. Quiet until wanted. */ -.note .perma { color: var(--ln); font-variant-numeric: tabular-nums; text-decoration: none; } -.note .perma:hover { color: var(--accent); text-decoration: underline; } -.note .perma.self { color: var(--muted); } - -/* ── one note, on its own page ───────────────────────────────── - What a shared link opens: the note, then the lines it is about. Wider - than a card in a list — nothing is competing for the room here. */ -.notepage { padding-bottom: 30vh; } -.notepage .onenote .note { margin: 0 0 14px; max-width: 760px; } -.notepage .exhead { margin: 0 0 6px; } -.notepage .excerpt { border: 1px solid var(--border); border-radius: 6px; background: var(--panel); } -.notepage .excerpt ol.code { padding: 6px 0; } -.notepage .excerpt ol.code:last-of-type { padding-bottom: 6px; } -.notepage .more { margin-top: 20px; } -.filehead h1 .lns { color: var(--muted); font-weight: 400; } -.filehead .kind { color: var(--note); font-style: normal; border: 1px solid var(--note); border-radius: 3px; padding: 0 4px; font-size: 11px; } -.filehead .ago { color: var(--muted); } -/* the excerpt exists to show what the note is about, so its lines stay - marked in either focus — the toggle is about reading a whole file */ -:root[data-mode="trace"] .excerpt ol.code li.noted { background: var(--note-bg); cursor: default; } -:root[data-mode="trace"] .excerpt ol.code li.noted::before { color: color-mix(in srgb, var(--note) 55%, var(--ln)); } - -/* Incoming reply and mention edges share one recursively nested discussion. - The narrow rail is intentionally HN-like: enough hierarchy to scan without - turning the existing cards into a second design system. */ -.discussion { max-width: 820px; margin-top: 24px; scroll-margin-top: 16px; } -.discussion h2 { margin-bottom: 6px; } -.discussion h2 .meta { font-size: 11px; font-weight: 400; margin-left: 6px; } -.threadnode { - display: grid; grid-template-columns: 20px minmax(0, 1fr); - align-items: stretch; -} -.threadedge { position: relative; color: var(--muted); text-align: center; font-size: 11px; } -.threadedge::after { - content: ""; position: absolute; top: 20px; bottom: 0; left: 50%; - border-left: 1px solid var(--border); -} -.threadedge span { position: relative; z-index: 1; background: var(--bg); } -.via-mention > .threadedge { color: var(--note); } -.via-mention > .threadedge::after { border-left-style: dashed; border-left-color: var(--note); } -.threadcontent { min-width: 0; } -.threadcontent > .note { margin: 7px 0; } -.threadchildren { min-width: 0; } -.threadref { - margin: 8px 0; padding: 5px 8px; border: 1px dashed var(--border); - border-radius: 5px; background: var(--panel); -} -.replybox { max-width: 760px; margin: 4px 0 10px; } -.replybox > summary { cursor: pointer; color: var(--muted); font-size: 11px; } -.replybox[open] > summary { color: var(--accent); } -.replyform { margin: 5px 0 10px; padding-left: 8px; border-left: 2px solid var(--border); } -.replyform textarea { width: 100%; box-sizing: border-box; } -.threadnode .replybox { margin-left: 1px; } - -/* ── conversation ──────────────────────────────────────────── */ -.convpage { padding: 0 16px 40vh; max-width: 1100px; } -.turn { - display: grid; grid-template-columns: 12ch 8ch minmax(0, 1fr); - gap: 0 10px; align-items: baseline; - padding: 2px 0 2px 8px; border-left: 2px solid transparent; -} -.turn .role { - color: var(--muted); font-size: 11px; text-align: right; - overflow: hidden; text-overflow: ellipsis; white-space: nowrap; -} -.turn time { color: var(--ln); font-size: 11px; font-variant-numeric: tabular-nums; } -.turn p { margin: 0; line-height: 1.5; white-space: pre-wrap; } -.turn .what { - font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; - overflow: hidden; text-overflow: ellipsis; white-space: nowrap; -} -.t-say { padding: 8px 0 8px 8px; } -.t-user { border-left-color: var(--accent); } -.t-user .role, .t-user p { color: var(--fg); } -.t-assistant .role { color: var(--cov); } -.t-thinking p { color: var(--muted); font-style: italic; } -.t-tool .role { color: var(--note); } -.t-result .what { color: var(--muted); } -.t-result.bad .what { color: var(--note); } -.t-vr { border-left-color: var(--cov); background: color-mix(in srgb, var(--cov) 7%, transparent); } -.t-vr .role { color: var(--cov); font-weight: 600; } -/* A note is what you came to the conversation to find, so it breaks the run - of log lines: the note color's rail, a tinted band, a card instead of a - line. scroll-margin clears the sticky header — the anchored one is - scrolled to on load. */ -.t-note { - padding: 8px 0 8px 8px; - border-left-color: var(--note); - background: color-mix(in srgb, var(--note) 7%, transparent); -} -.t-note .role { color: var(--note); font-weight: 600; } -.t-note .role::before { content: "◆ "; font-size: 9px; vertical-align: 1px; } -.t-note .note { max-width: 640px; margin: 0; scroll-margin-top: 96px; } -.t-note.here { background: color-mix(in srgb, var(--accent) 12%, transparent); } -.t-note.here .note { border-color: var(--accent); border-left-color: var(--accent); } -/* the whole card is the way back to the code; the links inside still work */ -.notewrap { cursor: pointer; } -.notewrap:hover .note, .notewrap:focus-visible .note { - border-color: var(--accent); background: var(--hover); -} -.notewrap:focus-visible { outline: none; } -.notewrap[data-href] .note::after { - content: "open in source →"; display: block; - margin-top: 6px; color: var(--accent); font-size: 11px; opacity: 0; -} -.notewrap:hover .note::after, .notewrap:focus-visible .note::after { opacity: 1; } - -/* ── 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; } - -/* lines picked to comment on, and lines you arrived at from a note */ -ol.code li.sel, ol.code li.focus { background: color-mix(in srgb, var(--accent) 16%, transparent); } -ol.code li.sel::before, ol.code li.focus::before { color: var(--accent); } -ol.code li.focus { box-shadow: inset 3px 0 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); } - -/* ── project hub ───────────────────────────────────────────── */ -.projects-main { padding-bottom: 20vh; } -.projects-main > section { max-width: 1200px; } -.project-refresh { margin: 10px 0; } -.project-refresh button, .project-card button, .project-action { - display: inline-block; background: var(--panel); color: var(--fg); - border: 1px solid var(--border); border-radius: 5px; - font: inherit; font-size: 12px; padding: 5px 10px; cursor: pointer; -} -.project-refresh button:hover, .project-card button:hover, .project-action:hover { - background: var(--hover); text-decoration: none; -} -.project-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 10px; } -.project-card { min-width: 0; padding: 12px; border: 1px solid var(--border); border-radius: 7px; background: var(--panel); } -.project-card > header { display: flex; align-items: center; justify-content: space-between; gap: 8px; } -.project-card h3 { min-width: 0; margin: 0; font: 600 14px/1.3 ui-monospace, Menlo, monospace; overflow: hidden; text-overflow: ellipsis; } -.project-path { margin: 8px 0; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.project-state { flex: none; padding: 1px 6px; border: 1px solid var(--border); border-radius: 99px; color: var(--muted); font-size: 10px; text-transform: uppercase; } -.project-state.active { border-color: var(--accent); color: var(--accent); } -.project-state.git { color: var(--note); } -.project-card form, .project-card .project-action { margin-top: 10px; } -.project-message { max-width: 1168px; } -.ok { margin: 12px 16px; padding: 8px 10px; border: 1px solid var(--accent); border-radius: 6px; color: var(--accent); } -.project-card[hidden] { display: none; } - -/* ── agent coverage colors ────────────────────────────────── - A bitmask is its agents' colors averaged. The blend is left to the - browser so these rules hold for any theme: a theme only has to name - --ag0..7, which every theme in themes.css does. */ -{{range .Masks}}.am{{.Mask}} { --cov: {{.Mix}}; } -{{end}} -/* ── syntax (theme colors, italics and weights are vars too, so - switching theme switches those with the colors) ─────────── */ -{{range .Syntax}}.s-{{.Class}} { color: var(--s-{{.Class}}, inherit); font-style: var(--s-{{.Class}}-fs, inherit); font-weight: var(--s-{{.Class}}-fw, inherit); } -{{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); } -} -@media (max-width: 620px) { - .threadnode { grid-template-columns: 14px minmax(0, 1fr); } - .discussion h2 .meta { display: block; margin: 2px 0 0; } - .replyform { padding-left: 5px; } -} diff --git a/vrsite/assets/typescript.scm b/vrsite/assets/typescript.scm deleted file mode 100644 index 96cf9c3..0000000 --- a/vrsite/assets/typescript.scm +++ /dev/null @@ -1,15 +0,0 @@ -; TypeScript highlights, from tree-sitter/tree-sitter-typescript v0.23.2 -; queries/highlights.scm (MIT). A supplement loaded after javascript.scm, as -; upstream composes it, so these patterns win. Upstream's -; ((identifier) @type (#match? "^[A-Z]")) is dropped: javascript.scm already -; paints capitalized identifiers as @constructor, and repainting every one of -; them as a type costs a second regex per identifier for a worse answer. - -["abstract" "declare" "enum" "implements" "interface" "keyof" "namespace" - "private" "protected" "public" "type" "readonly" "override" - "satisfies"] @keyword - -[(type_identifier) (predefined_type)] @type -(type_arguments "<" @punctuation.bracket ">" @punctuation.bracket) -(required_parameter (identifier) @variable.parameter) -(optional_parameter (identifier) @variable.parameter) diff --git a/vrsite/assets/zig.scm b/vrsite/assets/zig.scm deleted file mode 100644 index a85383a..0000000 --- a/vrsite/assets/zig.scm +++ /dev/null @@ -1,65 +0,0 @@ -; Zig highlights, from tree-sitter-grammars/tree-sitter-zig v1.1.2 -; queries/highlights.scm (MIT). Reordered for later-patterns-win, capture names -; mapped onto zed syntax keys — upstream's keyword.* split collapses to -; @keyword, which zed themes colour as one — and the #lua-match? identifier -; heuristics rewritten as #match?, which this engine evaluates. - -["(" ")" "[" "]" "{" "}"] @punctuation.bracket -(payload "|" @punctuation.bracket) -[";" "," "." ":" "=>" "->"] @punctuation.delimiter -["=" "==" "!=" "<" ">" "<=" ">=" "+" "+%" "+|" "-" "-%" "-|" "*" "*%" "*|" - "**" "/" "%" "&" "|" "^" "~" "!" "||" "<<" "<<|" ">>" ".." ".*" ".?" "?" - "+=" "+%=" "+|=" "-=" "-%=" "-|=" "*=" "*%=" "*|=" "/=" "%=" "&=" "|=" "^=" - "<<=" "<<|=" ">>="] @operator - -["addrspace" "align" "allowzero" "and" "asm" "async" "await" "break" - "callconv" "catch" "comptime" "const" "continue" "defer" "else" "enum" - "errdefer" "error" "export" "extern" "fn" "for" "if" "inline" "linksection" - "noalias" "noinline" "nosuspend" "opaque" "or" "orelse" "packed" "pub" - "resume" "return" "struct" "suspend" "switch" "test" "threadlocal" "try" - "union" "usingnamespace" "var" "volatile" "while"] @keyword - -(builtin_type) @type -["anyframe" "anytype"] @type -(parameter type: (identifier) @type) -(variable_declaration (identifier) @type "=" - [(struct_declaration) (enum_declaration) (union_declaration) - (opaque_declaration)]) - -["null" "undefined" "unreachable"] @constant -(boolean) @constant -; an enum literal — .ok — is a member with nothing to its left -(field_expression . member: (identifier) @constant) -(enum_declaration (container_field type: (identifier) @constant)) - -(container_field name: (identifier) @property) -(field_initializer . (identifier) @property) -(field_expression (_) member: (identifier) @property) -; .x = 1 inside a Point{...} is a field, not the enum literal above -(initializer_list - (assignment_expression - left: (field_expression . member: (identifier) @property))) -(parameter name: (identifier) @variable.parameter) -(block_label (identifier) @label) -(break_label (identifier) @label) - -(function_declaration name: (identifier) @function) -(call_expression function: (identifier) @function) -(call_expression function: (field_expression member: (identifier) @function.method)) -(builtin_identifier) @function.builtin - -; Zig has no type-identifier node, only the TitleCase convention, and these -; land after the call patterns so that the convention wins the way upstream's -; first-pattern-wins order has it: std.ArrayList(u8) is a type, not a call. -((identifier) @type - (#match? @type "^[A-Z][a-zA-Z0-9_]*$")) -((identifier) @constant - (#match? @constant "^[A-Z][A-Z0-9_]+$")) - -[(integer) (float)] @number -[(string) (multiline_string) (character)] @string -(escape_sequence) @string.escape - -(comment) @comment -((comment) @comment.doc - (#match? @comment.doc "^//[/!]")) diff --git a/vrsite/bench-browser.mjs b/vrsite/bench-browser.mjs deleted file mode 100644 index 97b3a86..0000000 --- a/vrsite/bench-browser.mjs +++ /dev/null @@ -1,135 +0,0 @@ -#!/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 deleted file mode 100644 index babf3d4..0000000 --- a/vrsite/bench_test.go +++ /dev/null @@ -1,328 +0,0 @@ -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, - hits: u64, - tags: HashMap>, -} - -pub enum LookupResult { - Hit(Arc), - 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 { - match keys.iter().position(|k| *k == self.key) { - Some(_) => LookupResult::Hit(self.value.clone()), - None => LookupResult::Miss { reason: "absent ", code: -1 }, - } - } -} - -const MAX_ENTRIES: usize = 4096; -static GREETING: &str = "hello \"quoted\" & friends"; -`) - -// One chunk per language whose query leans on a predicate, to keep an eye on -// what predicates cost: go's builtin list is an #any-of? (a byte compare per -// call), while python, javascript and C run a casing regex over every -// identifier they see — and zig, which names its types by casing alone, runs -// two. -var langChunks = []struct { - path string - src []byte -}{ - {"bench.go", []byte(`// Package cache keeps entries with hit counts. -package cache - -import ( - "fmt" - "sync" -) - -// Entry is one cached value and its hit count. -type Entry struct { - Key string - Value []byte - hits uint64 - tags map[string][]byte -} - -const MaxEntries = 4096 - -func NewEntry(key string, value []byte) *Entry { - return &Entry{Key: key, Value: value, tags: make(map[string][]byte)} -} - -// Touch records a hit and returns the running total. -func (e *Entry) Touch(mu *sync.Mutex) uint64 { - mu.Lock() - defer mu.Unlock() - e.hits++ - if e.hits%100 == 0 { - fmt.Printf("entry %q hit %d times \"escaped\"\n", e.Key, e.hits) - } - return e.hits -} - -func (e *Entry) Lookup(keys []string) ([]byte, bool) { - for _, k := range keys { - if v, ok := e.tags[k]; ok && len(v) > 0 { - return v, true - } - } - return nil, false -} -`)}, - {"bench.py", []byte(`"""Module documentation with some text.""" -import sys -from collections import OrderedDict - -MAX_ENTRIES = 4096 - - -class CacheEntry: - """A cached entry with a hit count.""" - - def __init__(self, key, value): - self.key = key - self.value = value - self.hits = 0 - self.tags = OrderedDict() - - @property - def stale(self): - return self.hits > MAX_ENTRIES - - def touch(self): - self.hits += 1 - if self.hits % 100 == 0: - print(f"entry {self.key} hit {self.hits} times \"escaped\"", file=sys.stderr) - return self.hits - - def lookup(self, keys): - for k in keys: - if k in self.tags: - return self.tags[k], True - return None, False -`)}, - {"bench.js", []byte(`// Cache entries with hit counts. -import { EventEmitter } from "node:events"; - -const MAX_ENTRIES = 4096; - -export class CacheEntry extends EventEmitter { - constructor(key, value) { - super(); - this.key = key; - this.value = value; - this.hits = 0; - this.tags = new Map(); - } - - get stale() { - return this.hits > MAX_ENTRIES; - } - - touch() { - this.hits += 1; - if (this.hits % 100 === 0) { - console.log(` + "`entry ${this.key} hit ${this.hits} times \"escaped\"`" + `); - } - return this.hits; - } - - lookup(keys) { - return keys.map((k) => this.tags.get(k)).find((v) => v !== undefined) ?? null; - } -} -`)}, - {"bench.c", []byte(`/* Cache entries with hit counts. */ -#include -#include - -#define MAX_ENTRIES 4096 - -struct cache_entry { - const char *key; - unsigned char *value; - unsigned long hits; -}; - -static struct cache_entry *entry_new(const char *key, unsigned char *value) { - static struct cache_entry e; - e.key = key; - e.value = value; - e.hits = 0; - return &e; -} - -unsigned long entry_touch(struct cache_entry *e) { - e->hits++; - if (e->hits % 100 == 0) { - fprintf(stderr, "entry %s hit %lu times \"escaped\"\n", e->key, e->hits); - } - return e->hits; -} - -int entry_lookup(struct cache_entry *e, const char *key) { - return e->key != NULL && strcmp(e->key, key) == 0; -} -`)}, - {"bench.zig", []byte(`// Cache entries with hit counts. -const std = @import("std"); - -const MAX_ENTRIES: usize = 4096; - -const CacheEntry = struct { - key: []const u8, - value: []u8, - hits: u64 = 0, - - fn init(key: []const u8, value: []u8) CacheEntry { - return CacheEntry{ .key = key, .value = value }; - } - - fn stale(self: CacheEntry) bool { - return self.hits > MAX_ENTRIES; - } - - fn touch(self: *CacheEntry) u64 { - self.hits += 1; - if (self.hits % 100 == 0) { - std.debug.print("entry {s} hit {d} times \"escaped\"\n", .{ self.key, self.hits }); - } - return self.hits; - } - - fn lookup(self: CacheEntry, keys: []const []const u8) ?[]u8 { - for (keys) |k| { - if (std.mem.eql(u8, k, self.key)) return self.value; - } - return null; - } -}; -`)}, -} - -func synth(chunk []byte, size int) []byte { - var b bytes.Buffer - for b.Len() < size { - b.Write(chunk) - } - return b.Bytes() -} - -func synthRust(size int) []byte { return synth(rustChunk, size) } - -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) - } - }) - } -} - -// the same work for the languages whose queries evaluate predicates -func BenchmarkClassifyLangs(b *testing.B) { - hl := benchHL(b) - for _, c := range langChunks { - src := synth(c.src, 1<<20) - b.Run(c.path, func(b *testing.B) { - b.SetBytes(int64(len(src))) - b.ReportAllocs() - for i := 0; i < b.N; i++ { - hl.classify(c.path, 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(hl) - 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 deleted file mode 100644 index f1df936..0000000 --- a/vrsite/css.go +++ /dev/null @@ -1,157 +0,0 @@ -// css.go — the stylesheet is generated per site: theme colors become custom -// properties, one block per scheme, and the per-agent coverage colors are -// blended from them in the browser so any theme can supply them. -// -// Everything switchable is a custom property on :root. That is what lets -// themes.css hold nothing but one block per theme (writeThemesCSS) and the -// picker repaint the page by setting a single attribute. -package main - -import ( - "encoding/json" - "fmt" - "io" - "strings" - texttemplate "text/template" -) - -type cssVar struct{ K, V string } - -type synCSS struct{ Class string } - -type maskCSS struct { - Mask uint8 - Mix string -} - -func renderCSS(w io.Writer, site *Site) error { - css, err := texttemplate.ParseFS(tfs, "assets/style.css.tmpl") - if err != nil { - return err - } - keys := syntaxKeys(site.Theme, site.Light) - var syn []synCSS - for _, k := range keys { - syn = append(syn, synCSS{Class: cssKey(k)}) - } - var masks []maskCSS - for _, m := range site.masks() { - masks = append(masks, maskCSS{Mask: m, Mix: site.maskMix(m)}) - } - return css.Execute(w, map[string]any{ - "DarkName": site.Theme.Name, "LightName": site.Light.Name, - "DarkVars": themeVars(site.Theme, keys), "LightVars": themeVars(site.Light, keys), - "Syntax": syn, "Masks": masks, - }) -} - -// themeVars is one theme as custom properties: its own colors, the syntax -// colors under the keys the site paints with (resolved along their dots, so a -// theme that only names "punctuation" still colors brackets), and the agent -// colors every coverage blend is mixed from. -func themeVars(t *Theme, keys []string) []cssVar { - // bg and panel are what everything else is read against, so they are the - // two that may not carry a theme's alpha channel through - vars := []cssVar{ - {"--bg", hex6(t.Bg)}, {"--fg", t.Fg}, {"--panel", hex6(t.Panel)}, {"--border", t.Border}, - {"--ln", t.LineNo}, {"--muted", t.Muted}, {"--accent", t.Accent}, - {"--note", t.Note}, {"--hover", t.Hover}, - } - for _, k := range keys { - key := resolveKey(t, k) - if key == "" { - continue - } - s, c := t.Syntax[key], cssKey(k) - vars = append(vars, cssVar{"--s-" + c, s.Color}) - if s.FontStyle != nil && *s.FontStyle != "" && *s.FontStyle != "normal" { - vars = append(vars, cssVar{"--s-" + c + "-fs", *s.FontStyle}) - } - if s.FontWeight != nil && *s.FontWeight > 0 { - vars = append(vars, cssVar{"--s-" + c + "-fw", fmt.Sprintf("%.0f", *s.FontWeight)}) - } - } - for i := 0; i < maxAgents; i++ { - vars = append(vars, cssVar{fmt.Sprintf("--ag%d", i), hex6(t.Player(i))}) - } - return vars -} - -// maskMix is the color of a coverage bitmask: the agent colors it stands for, -// averaged. The average is written as nested color-mix rather than mixed here, -// so the same rule holds for every theme the browser can switch to. -func (s *Site) maskMix(mask uint8) string { - var idx []int - for i, a := range s.Agents { - if a.Bit != 0 && mask&a.Bit != 0 { - idx = append(idx, i) - } - } - return mixExpr(idx) -} - -func mixExpr(idx []int) string { - switch len(idx) { - case 0: - return "var(--fg)" - case 1: - return fmt.Sprintf("var(--ag%d)", idx[0]) - } - return fmt.Sprintf("color-mix(in srgb, var(--ag%d) %.3f%%, %s)", - idx[0], 100/float64(len(idx)), mixExpr(idx[1:])) -} - -// ── the switchable themes ───────────────────────────────────────────────── - -// writeThemesCSS writes one block per theme found on this machine. It is only -// fetched once a theme has been picked (or the picker opened), so the page -// costs nothing for the reader who never switches. -func writeThemesCSS(w io.Writer, themes []*Theme, keys []string) { - fmt.Fprintf(w, "/* %d themes, found on this machine — set data-theme on :root to wear one */\n", len(themes)) - for _, t := range themes { - fmt.Fprintf(w, ":root[data-theme=%q] {\n", t.ID) - for _, v := range themeVars(t, keys) { - fmt.Fprintf(w, " %s: %s;\n", v.K, v.V) - } - scheme := "dark" - if t.Appearance == "light" { - scheme = "light" - } - fmt.Fprintf(w, " color-scheme: %s;\n}\n", scheme) - } -} - -// themeCard is a theme as the picker shows it: a name, where it came from, and -// the few colors that make it recognizable at a glance. -type themeCard struct { - ID string `json:"id"` - Name string `json:"name"` - Src string `json:"src"` - Dark bool `json:"dark"` - Sw []string `json:"sw"` -} - -// writeThemesJS is the picker's menu. It is a script, not JSON, because the -// static export is opened from the filesystem, where fetch() is not allowed -// but a is quoted from [the file](https://go.dev)"}, - } - for _, c := range cases { - t.Run(c.name, func(t *testing.T) { - got := string(m.render(c.in)) - if strings.Contains(got, "
") || strings.Contains(got, " -{{if .Live}}{{end}} - - - - - - -
-{{if .Err}}

{{.Err}}

{{end}} -{{if eq .Kind "file"}}{{template "page-file" .}} -{{else if eq .Kind "notes"}}{{template "page-notes" .}} -{{else if eq .Kind "note"}}{{template "page-note" .}} -{{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 if eq .Kind "session"}}{{template "page-session" .}} -{{else}}{{template "page-index" .}}{{end}} -
- -{{if eq .Kind "file"}} - -{{end}} - - - diff --git a/vrsite/templates/page-change.tmpl b/vrsite/templates/page-change.tmpl deleted file mode 100644 index 8641da7..0000000 --- a/vrsite/templates/page-change.tmpl +++ /dev/null @@ -1,38 +0,0 @@ -{{define "page-change"}} -{{$c := .Change}} -{{$p := .}} -
-

{{$c.Row.Short}} {{$c.Row.Flags}}

-

- commit {{$c.Row.CommitShort}} · {{$c.Row.Author}} · {{$c.Row.When}} - {{if $c.Row.Refs}} · {{$c.Row.Refs}}{{end}} · - browse the tree here -

-
- -
- {{if $c.Desc}}
{{$c.Desc}}
{{else}}

(no description set)

{{end}} - - {{if $c.Parents}} -

parents: - {{range $c.Parents}}{{.Short}} {{.Desc}} {{end}} -

- {{end}} - -

Changed files {{$c.Stat}}

- {{if $c.Files}} - - - {{range $c.Files}} - - - {{end}} - -
{{.Status}}{{.Path}}
- {{else}}

no file changes

{{end}} - -

Notes recorded at this change {{len .Notes}}

-
{{range .Notes}}{{template "note" (dict "N" . "P" $)}}{{end}}
- {{if not .Notes}}

nothing in the log was written while this change was checked out

{{end}} -
-{{end}} diff --git a/vrsite/templates/page-file.tmpl b/vrsite/templates/page-file.tmpl deleted file mode 100644 index 39a8c44..0000000 --- a/vrsite/templates/page-file.tmpl +++ /dev/null @@ -1,20 +0,0 @@ -{{define "page-file"}} -
-

{{.File.Path}}

-

- {{if .File.Traced}} - {{range .Site.Agents}}{{if band $.File.Mask .Bit}}{{.Short}} {{end}}{{end}} - {{.File.Pct}}% read · - {{.File.Reads}} reads · {{.File.Greps}} greps · - {{len .File.Notes}} note{{if ne (len .File.Notes) 1}}s{{end}} · - {{else}}not traced · {{end}}change - {{if .Live}}{{short .File.Change}}{{else}}{{short .File.Change}}{{end}} -

- {{if .File.Patterns}}

grepped: {{range .File.Patterns}}{{.}} {{end}}

{{end}} -
-{{if .File.Stub}} -

{{.File.Stub}}

-{{else}} -
{{.File.Body}}
-{{end}} -{{end}} diff --git a/vrsite/templates/page-files.tmpl b/vrsite/templates/page-files.tmpl deleted file mode 100644 index 3f158fe..0000000 --- a/vrsite/templates/page-files.tmpl +++ /dev/null @@ -1,13 +0,0 @@ -{{define "page-files"}} -
-

Files

-

- everything at change {{short .ChangeID}} · - traced files carry a coverage bar{{if eq .Scope "change"}}, from reads at this change{{end}} - ◆ marks files with notes -

-
-
-{{.Tree}} -
-{{end}} diff --git a/vrsite/templates/page-index.tmpl b/vrsite/templates/page-index.tmpl deleted file mode 100644 index 93cad6b..0000000 --- a/vrsite/templates/page-index.tmpl +++ /dev/null @@ -1,56 +0,0 @@ -{{define "page-index"}} -
-

{{.Site.Title}}

-

- {{len .Files}} files at {{short .ChangeID}} · - {{len .Site.Order}} traced, {{len .Site.Notes}} notes - {{if or (eq .Scope "all") .ScopeEmpty}}across every change{{else}}here{{end}} · - theme {{.Site.Theme.Name}} -

-
- -{{if .Live}} -
-

Live — agents reading this codebase

-
-

…

-
-
-{{end}} - -
-

Agents

- - - - {{range .Site.Agents}} - - - - - {{end}} - -
agentmodeleffortsessionreadsgrepsnotes
{{.Short}}{{.Model}}{{.Reason}}{{if and $.Live .Session}}{{short .Session}} - {{else}}{{short .Session}}{{end}}{{.Reads}}{{.Greps}}{{.Notes}}
-
- -
-

Coverage

- - - - {{range .Site.Order}}{{with index $.Site.Files .}} - - - - {{end}}{{end}} - -
filereadlinesnotes
{{.Path}}{{.Pct}}%{{.Covered}}/{{.Total}}{{len .Notes}}
-
- -
-

Latest notes — all {{len .Site.Notes}}, with filters

-
{{range .Notes}}{{template "note" (dict "N" . "P" $)}}{{end}}
- {{if not .Notes}}

no notes in the log yet

{{end}} -
-{{end}} diff --git a/vrsite/templates/page-jj.tmpl b/vrsite/templates/page-jj.tmpl deleted file mode 100644 index 24df596..0000000 --- a/vrsite/templates/page-jj.tmpl +++ /dev/null @@ -1,25 +0,0 @@ -{{define "page-jj"}} -
-

jj

-

- read-only queries against the repo — --ignore-working-copy, inline templates, nothing written to disk -

-
- -
-
- - - - - - · -
-

- change ids open the change · descriptions browse the tree at that change · - op ids re-run the query --at-operation, which is how you see the repo as it was -

-
{{template "jjrows" .JJ}}
-
-{{end}} diff --git a/vrsite/templates/page-note.tmpl b/vrsite/templates/page-note.tmpl deleted file mode 100644 index 8cd0e64..0000000 --- a/vrsite/templates/page-note.tmpl +++ /dev/null @@ -1,54 +0,0 @@ -{{/* One note, on its own — the page a shared permalink opens. - - It has to stand up for a reader who has never seen this site: what was - said, about which lines of which file, at which change, and the code - itself, right there. Everything else on the page is a way further in. */}} -{{define "page-note"}} -{{$n := .Note}} -
-

{{if $n.File}}{{base $n.File}}{{lines $n}}{{else}}Note{{end}}

-

- note #{{$n.ID}} by {{$n.Agent.Short}}{{if $n.Kind}} · {{$n.Kind}}{{end}} - {{if not $n.At.IsZero}} · - ({{$n.Ago}}){{end}} - {{if $n.Change}} · read at - {{if .Live}}{{short $n.Change}} - {{else}}{{short $n.Change}}{{end}} - {{end}} -

- {{if ne $n.File (base $n.File)}}

{{$n.File}}

{{end}} -
- -
-
{{template "note" (dict "N" $n "P" $)}}
- - {{$open := .HasCode $n.File}} - {{if .Excerpt}} -

lines {{.ExFrom}}–{{.ExTo}} of {{$n.File}}{{if $open}} · - open the whole file →{{end}}

-
{{.Excerpt}}
- {{else if .ExErr}} -

{{.ExErr}}

- {{else if $n.File}} -

this note is about the whole file{{if $open}} — - open {{base $n.File}} →{{end}}

- {{else}} -

this note is not pinned to a file

- {{end}} - - {{if .Live}}{{template "replyform" (dict "N" $n "P" $)}}{{end}} - -
-

Replies & mentions - {{len $n.Replies}} repl{{if eq (len $n.Replies) 1}}y{{else}}ies{{end}} · {{len $n.Mentions}} mention{{if ne (len $n.Mentions) 1}}s{{end}} -

- {{if .Thread.Children}} -
{{range .Thread.Children}}{{template "threadnode" (dict "Node" . "P" $)}}{{end}}
- {{else}} -

no notes reply to or mention this one yet

- {{end}} -
- -

← every note in the log

-
-{{end}} diff --git a/vrsite/templates/page-notes.tmpl b/vrsite/templates/page-notes.tmpl deleted file mode 100644 index ebd5865..0000000 --- a/vrsite/templates/page-notes.tmpl +++ /dev/null @@ -1,52 +0,0 @@ -{{define "facet"}}{{end}} - -{{define "page-notes"}} -
-

Notes

-

- {{if eq .Scope "all"}} - all {{.Site.NotesTotal}} in the log, every change - {{else if .ScopeEmpty}} - all {{.Site.NotesTotal}} in the log — nothing was recorded at {{short .ChangeID}} - {{else}} - {{len .Site.Notes}} written at {{short .ChangeID}}{{if .Elsewhere}} · - {{if .Live}}{{.Elsewhere}} more at other changes - {{else}}{{.Elsewhere}} more at other changes are not in this export{{end}}{{end}} - {{end}} - {{if .Live}} · anything you add here is appended to the private log sidecar at this change — the project working copy is never touched{{end}} -

-
- -
- {{if .Live}} -
- add a note - {{template "noteform" .}} -
- {{end}} - -
- - - {{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)}} - - - - - - -
- {{range .Facets.Files}} - -

·{{len .Notes}} notes shown

-
{{template "notelist" .}}
-
-{{end}} diff --git a/vrsite/templates/page-session.tmpl b/vrsite/templates/page-session.tmpl deleted file mode 100644 index 9a35e8d..0000000 --- a/vrsite/templates/page-session.tmpl +++ /dev/null @@ -1,70 +0,0 @@ -{{/* One session's conversation, with its vr log woven in by time. */}} -{{define "page-session"}} -{{$c := .Conv}} -
-

- {{if $c.Agent}}{{$c.Agent}} {{end}} - {{short $c.Session}} -

-

- {{if $c.Model}}{{$c.Model}} · {{end}}{{$c.Reads}} reads · {{$c.Greps}} greps · {{$c.Notes}} notes - {{if $c.Dir}} · {{base $c.Dir}}{{end}} - {{if $c.Harness}} · {{$c.Harness}}{{end}} -

- {{if $c.Path}} -

{{$c.Path}}

- {{else}} -

no transcript found for this session — searched - {{if $c.Roots}}{{range $i, $r := $c.Roots}}{{if $i}}, {{end}}{{$r}}{{end}}{{else}}nowhere: -transcripts is empty{{end}} · - showing the vr log alone

- {{end}} - {{if $c.Err}}

{{$c.Err}}

{{end}} -
- -
- {{if $c.Windowed}} -

- moments {{$c.From}}–{{$c.To}} of {{$c.Total}}{{if $c.Anchor}}, around the note{{end}} · - {{if $c.Incomplete}}the rest is beyond what one page renders{{else}}show the whole conversation{{end}} -

- {{end}} - -
- {{range $c.Turns}} - {{if .Note}} -
- note - {{if .Note.File}} -
{{template "note" (dict "N" .Note "P" $)}}
- {{else}} -
{{template "note" (dict "N" .Note "P" $)}}
- {{end}} -
- {{else if eq .Role "vr"}} -
- vr - {{if .File}}{{.Text}} - {{else}}{{.Text}}{{end}} -
- {{else if eq .Role "tool"}} -
- {{.Tool}} - {{.Detail}} -
- {{else if eq .Role "result"}} -
- →{{if .Tool}} {{.Tool}}{{end}} - {{.Detail}} -
- {{else}} -
- {{.Role}} -

{{.Text}}

-
- {{end}} - {{end}} - {{if not $c.Turns}}

nothing recorded for this session

{{end}} -
-
-{{end}} diff --git a/vrsite/templates/projects.tmpl b/vrsite/templates/projects.tmpl deleted file mode 100644 index 3e3c670..0000000 --- a/vrsite/templates/projects.tmpl +++ /dev/null @@ -1,112 +0,0 @@ -{{define "projects"}} - - - - -{{.Title}} - - - - - - - -
-
-

Projects

-

Choose a vr log, start one in a jj repository, or colocate jj with an existing Git repository.

-
- {{if .Message}}

{{.Message}}

{{end}} - {{if .Err}}

{{.Err}}

{{end}} - -
-

Logs — {{len .Active}} repositories with a private sidecar

-
- {{range .Active}} -
-

{{.Name}}

log
-

{{.Relative}}

-

{{.Entries}} entries · {{.Notes}} notes · {{.Agents}} agents · {{.Updated}}

- {{if gt (len .Workspaces) 1}}

{{len .Workspaces}} jj workspaces share this log

{{end}} - {{if .Err}}

{{.Err}}

{{end}} - open project -
- {{end}} - {{if not .Active}}

no vr sidecars found yet

{{end}} -
-
- -
-

Ready to start — {{len .Ready}} jj repositories without a vr sidecar

-
- {{range .Ready}} -
-

{{.Name}}

jj
-

{{.Relative}}

- {{if gt (len .Workspaces) 1}}

{{len .Workspaces}} workspaces

{{end}} - {{if .Err}}

{{.Err}}

{{end}} -
- -
-
- {{end}} - {{if not .Ready}}

every detected jj repository already has a sidecar

{{end}} -
-
- -
-

Git repositories — {{len .Git}} without jj metadata

-

Initializing adds colocated .jj metadata; it does not create a sidecar until you choose “start private sidecar”.

-
- {{range .Git}} -
-

{{.Name}}

git
-

{{.Relative}}

-
- -
-
- {{end}} - {{if not .Git}}

no Git-only repositories detected

{{end}} -
-
-
- -{{end}} diff --git a/vrsite/theme.go b/vrsite/theme.go deleted file mode 100644 index 91eedbe..0000000 --- a/vrsite/theme.go +++ /dev/null @@ -1,341 +0,0 @@ -// theme.go — Zed theme JSON in, CSS custom properties out. Per-agent colors -// come from the theme's player (collaborator) palette. -// -// The two themes named on the command line are what the site is built with; -// themes.go finds the rest of this machine's themes for the picker, and they -// arrive here as the same *Theme. -package main - -import ( - "encoding/json" - "errors" - "fmt" - "os" - "sort" - "strings" -) - -type SyntaxStyle struct { - Color string `json:"color"` - FontStyle *string `json:"font_style"` - FontWeight *float64 `json:"font_weight"` -} - -type Theme struct { - ID, Source string // "zed/one-dark", "zed" | "helix" - 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 { - for _, path := range globAll(zedThemeGlobs()) { - b, err := os.ReadFile(path) - if err != nil { - continue - } - fam, err := parseZedFamily(b) - if err != nil { - continue - } - for _, t := range fam { - 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) - } - fam, err := parseZedFamily(b) - if err != nil { - fatal("bad zed theme %s: %v", path, err) - } - t := fam[0] - if name != "" { - for _, c := range fam { - if c.Name == name { - t = c - } - } - } else { - for _, c := range fam { - if c.Appearance == appearance { - t = c - break - } - } - } - return t -} - -// parseZedFamily reads a zed theme file: one file is a family, and every theme -// in it is one the picker can offer. -func parseZedFamily(b []byte) ([]*Theme, error) { - 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 { - return nil, err - } - if len(family.Themes) == 0 { - return nil, errors.New("no themes in it") - } - var out []*Theme - for _, th := range family.Themes { - get := func(keys ...string) string { - for _, k := range keys { - var s string - if raw, ok := th.Style[k]; ok && json.Unmarshal(raw, &s) == nil && okColor(s) != "" { - return s - } - } - return "" - } - t := &Theme{ID: "zed/" + slug(th.Name), Source: "zed", - 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) - for k, s := range t.Syntax { // a theme in the wild does drop the odd "#" - if okColor(s.Color) == "" { - delete(t.Syntax, k) - } - } - t.fill() - var players []struct { - Cursor string `json:"cursor"` - } - json.Unmarshal(th.Style["players"], &players) - var cursors []string - for _, p := range players { - cursors = append(cursors, p.Cursor) - } - t.setPlayers(cursors, t.syntaxColors()) - out = append(out, t) - } - return out, nil -} - -// setPlayers picks the per-agent colors out of the theme's own palette. A zed -// theme has one meant for exactly this — the collaborator cursors — and it is -// asked first; when it runs short, or the theme is a helix one with no such -// palette at all, the code's own colors stand in, since those are what the -// reader is already telling apart on the page. -// -// Within each tier, colors that vanish against fg/bg, collide with the note -// color, or sit on top of one already taken are dropped, and the rest ordered -// greedily for mutual distance, so the first few agents contrast most. -func (t *Theme) setPlayers(tiers ...[]string) { - t.Players = nil - taken := func(c string, of []string) bool { - for _, p := range of { - if colorDist(c, p) <= 60 { - return true - } - } - return false - } - for _, tier := range tiers { - var usable []string - for _, c := range tier { - c = hex6(c) - if len(c) != 7 || taken(c, usable) || taken(c, t.Players) || - colorDist(c, hex6(t.Fg)) <= 60 || colorDist(c, hex6(t.Bg)) <= 60 || - colorDist(c, hex6(t.Note)) <= 60 { - continue - } - usable = append(usable, c) - } - for len(usable) > 0 && len(t.Players) < maxAgents { - best, bestScore := 0, -1 - for i, c := range usable { - score := 1 << 24 // first pick of the first tier: 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:]...) - } - } -} - -// fill supplies whatever a theme does not say. Editors leave gaps a web page -// cannot — a zed theme need not name a muted text color, a helix theme has no -// notion of a panel — so every gap is closed with a shade mixed from the -// theme's own background and foreground, or with a color out of its syntax. -// A theme with three colors in it still dresses a whole page. -func (t *Theme) fill() { - bg, fg := hex6(t.Bg), t.Fg - // panel and hover are backgrounds the page writes on, so a theme that - // offers one the text would be lost in does not get to keep it - t.Panel = first(readable(t.Panel, fg, ""), blend(bg, fg, 0.05)) - t.Hover = first(readable(t.Hover, fg, ""), blend(bg, fg, 0.12)) - t.Border = first(t.Border, blend(bg, fg, 0.2)) - t.LineNo = first(t.LineNo, blend(bg, fg, 0.4)) - t.Muted = first(readable(t.Muted, t.Panel, ""), blend(bg, fg, 0.55)) - t.Accent = first(t.Accent, t.syn("function"), t.syn("keyword"), t.syn("type"), fg) - t.Note = first(t.Note, t.syn("warning"), t.syn("number"), t.Accent) -} - -// syn is the theme's color for a syntax key, resolved along its dots. -func (t *Theme) syn(key string) string { - if k := resolveKey(t, key); k != "" { - return t.Syntax[k].Color - } - return "" -} - -// syntaxColors are the theme's own code colors, in the order they stand out -// from one another: what a theme offers when its palette runs short. -func (t *Theme) syntaxColors() []string { - var out []string - for _, k := range []string{"keyword", "function", "string", "type", "constant", - "variable.parameter", "attribute", "constructor", "number", "tag", "property", - "label", "namespace", "operator", "boolean"} { - if c := t.syn(k); c != "" { - out = append(out, c) - } - } - return out -} - -// readable keeps a color only if text in `on` can be seen against it. -func readable(c, on, fallback string) string { - if c == "" || colorDist(hex6(c), hex6(on)) < 2000 { - return fallback - } - return c -} - -// syntaxKeys is every syntax key the site paints, and so every one a theme is -// asked to fill: the union of what the two built-with themes name. -func syntaxKeys(themes ...*Theme) []string { - var keys []string - seen := map[string]bool{} - for _, t := range themes { - for k := range t.Syntax { - if !seen[k] { - seen[k] = true - keys = append(keys, k) - } - } - } - sort.Strings(keys) - return keys -} - -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)] -} - -// okColor keeps a color only if it is one a browser will take: #rgb, #rrggbb -// or #rrggbbaa. Whatever else a theme file says is treated as unsaid, and -// fill() supplies it. -func okColor(c string) string { - if len(c) != 4 && len(c) != 7 && len(c) != 9 || c[0] != '#' { - return "" - } - for _, r := range c[1:] { - if !(r >= '0' && r <= '9' || r >= 'a' && r <= 'f' || r >= 'A' && r <= 'F') { - return "" - } - } - return c -} - -// hex6 strips an alpha channel from #rrggbbaa. -func hex6(c string) string { - if len(c) == 9 && c[0] == '#' { - return c[:7] - } - if len(c) == 4 && c[0] == '#' { // #rgb - return "#" + string([]byte{c[1], c[1], c[2], c[2], c[3], c[3]}) - } - return c -} - -func rgb(c string) (r, g, b int, ok bool) { - c = hex6(c) - if len(c) != 7 || c[0] != '#' { - return 0, 0, 0, false - } - if n, _ := fmt.Sscanf(c[1:], "%02x%02x%02x", &r, &g, &b); n != 3 { - return 0, 0, 0, false - } - return r, g, b, true -} - -// lum is perceived brightness, 0..1 — enough to tell a light theme from a -// dark one when the theme does not say which it is. -func lum(c string) float64 { - r, g, b, ok := rgb(c) - if !ok { - return 0 - } - return (0.299*float64(r) + 0.587*float64(g) + 0.114*float64(b)) / 255 -} - -// blend mixes frac of b into a — for the shades a theme leaves unsaid. -func blend(a, b string, frac float64) string { - ar, ag, ab, ok := rgb(a) - br, bg, bb, ok2 := rgb(b) - if !ok || !ok2 { - return a - } - mix := func(x, y int) int { return int(float64(x) + (float64(y)-float64(x))*frac) } - return fmt.Sprintf("#%02x%02x%02x", mix(ar, br), mix(ag, bg), mix(ab, bb)) -} - -// cssKey is a syntax key as it appears in class and property names. -func cssKey(k string) string { return strings.ReplaceAll(k, ".", "-") } diff --git a/vrsite/themes.go b/vrsite/themes.go deleted file mode 100644 index f185fab..0000000 --- a/vrsite/themes.go +++ /dev/null @@ -1,445 +0,0 @@ -// themes.go — the themes this machine already has. Zed keeps families of them -// in JSON, Helix keeps one TOML each with a palette and single inheritance; -// both are read into the same *Theme, so the browser can wear either. -// -// Discovery is best-effort: a theme that will not parse is skipped, never -// fatal. What the site is built with stays what -theme and -light-theme say — -// these only widen what the picker can offer. -package main - -import ( - "bytes" - "os" - "os/exec" - "path/filepath" - "sort" - "strings" - - "github.com/BurntSushi/toml" -) - -// themeSet is those themes plus the two files the browser switches with: one -// CSS block per theme, and the list the picker draws from. -type themeSet struct { - List []*Theme - CSS []byte // themes.css — one :root[data-theme="…"] block per theme - JS []byte // themes.js — window.VRSITE_THEMES, the picker's menu -} - -func newThemeSet(dark, light *Theme) *themeSet { - return themesFrom(discoverThemes(), dark, light) -} - -// themesFrom writes the two files for a given list of themes. The keys the -// site paints with come from the themes it was built with, since those are the -// ones the stylesheet has classes for. -func themesFrom(list []*Theme, dark, light *Theme) *themeSet { - ts := &themeSet{List: list} - keys := syntaxKeys(dark, light) - var css, js bytes.Buffer - writeThemesCSS(&css, ts.List, keys) - writeThemesJS(&js, ts.List) - ts.CSS, ts.JS = css.Bytes(), js.Bytes() - return ts -} - -func (ts *themeSet) count(source string) int { - n := 0 - for _, t := range ts.List { - if t.Source == source { - n++ - } - } - return n -} - -// discoverThemes reads every theme both editors can see, user directories -// first so a theme you installed wins the id over one that merely ships. -func discoverThemes() []*Theme { - var out []*Theme - seen := map[string]bool{} - add := func(t *Theme) { - if t == nil || t.ID == "" || t.Bg == "" || t.Fg == "" || seen[t.ID] { - return - } - seen[t.ID] = true - out = append(out, t) - } - for _, path := range globAll(zedThemeGlobs()) { - b, err := os.ReadFile(path) - if err != nil { - continue - } - fam, err := parseZedFamily(b) - if err != nil { - continue - } - for _, t := range fam { - add(t) - } - } - dirs := helixThemeDirs() - for _, dir := range dirs { - for _, path := range globAll([]string{filepath.Join(dir, "*.toml")}) { - add(loadHelixTheme(path, dirs)) - } - } - sort.Slice(out, func(i, j int) bool { - if out[i].Source != out[j].Source { - return out[i].Source < out[j].Source - } - return strings.ToLower(out[i].Name) < strings.ToLower(out[j].Name) - }) - return out -} - -func globAll(pats []string) []string { - var out []string - for _, p := range pats { - m, _ := filepath.Glob(p) - sort.Strings(m) - out = append(out, m...) - } - return out -} - -func configHome() string { - if d := os.Getenv("XDG_CONFIG_HOME"); d != "" { - return d - } - home, _ := os.UserHomeDir() - return filepath.Join(home, ".config") -} - -func dataHome() string { - if d := os.Getenv("XDG_DATA_HOME"); d != "" { - return d - } - home, _ := os.UserHomeDir() - return filepath.Join(home, ".local", "share") -} - -// zedThemeGlobs: themes you dropped in yourself, then the ones extensions -// brought. Zed's own built-ins live inside the binary, so they are not here. -func zedThemeGlobs() []string { - home, _ := os.UserHomeDir() - mac := filepath.Join(home, "Library", "Application Support", "Zed") - return []string{ - filepath.Join(configHome(), "zed", "themes", "*.json"), - filepath.Join(mac, "themes", "*.json"), - filepath.Join(dataHome(), "zed", "extensions", "installed", "*", "themes", "*.json"), - filepath.Join(mac, "extensions", "installed", "*", "themes", "*.json"), - } -} - -// helixThemeDirs: yours first, then whichever runtime the installed hx uses — -// found the way helix itself looks, by walking out from the binary. -func helixThemeDirs() []string { - home, _ := os.UserHomeDir() - dirs := []string{filepath.Join(configHome(), "helix", "themes")} - var runtimes []string - if r := os.Getenv("HELIX_RUNTIME"); r != "" { - runtimes = append(runtimes, r) - } - runtimes = append(runtimes, - filepath.Join(configHome(), "helix", "runtime"), - filepath.Join(dataHome(), "helix", "runtime")) - if bin, err := exec.LookPath("hx"); err == nil { - if bin, err = filepath.EvalSymlinks(bin); err == nil { - dir := filepath.Dir(bin) - runtimes = append(runtimes, - filepath.Join(dir, "runtime"), - filepath.Join(filepath.Dir(dir), "lib", "helix", "runtime"), - filepath.Join(filepath.Dir(dir), "share", "helix", "runtime")) - } - } - runtimes = append(runtimes, - "/usr/lib/helix/runtime", "/usr/share/helix/runtime", - "/usr/local/lib/helix/runtime", "/opt/homebrew/opt/helix/libexec/runtime", - filepath.Join(home, ".cargo", "share", "helix", "runtime")) - seen := map[string]bool{} - for _, r := range runtimes { - d := filepath.Join(r, "themes") - if seen[d] { - continue - } - seen[d] = true - if fi, err := os.Stat(d); err == nil && fi.IsDir() { - dirs = append(dirs, d) - } - } - return dirs -} - -// ── helix ───────────────────────────────────────────────────────────────── -// -// A helix theme is scope -> style, with colors named out of a [palette] at the -// bottom, and may inherit one other theme by name. Inheritance merges both -// halves before anything resolves, which is what lets a child theme restate -// the palette alone (catppuccin_latte is catppuccin_mocha with new colors). - -type helixStyle struct { - fg, bg string // palette names, hex, or one of the sixteen terminal names - italic bool - bold bool -} - -type helixRaw struct { - scopes map[string]helixStyle - palette map[string]string -} - -func loadHelixTheme(path string, dirs []string) *Theme { - raw := readHelixRaw(path, dirs, 0) - if raw == nil { - return nil - } - name := strings.TrimSuffix(filepath.Base(path), ".toml") - return helixTheme(name, raw) -} - -func readHelixRaw(path string, dirs []string, depth int) *helixRaw { - b, err := os.ReadFile(path) - if err != nil { - return nil - } - var doc map[string]any - if err := toml.Unmarshal(b, &doc); err != nil { - return nil - } - raw := &helixRaw{scopes: map[string]helixStyle{}, palette: map[string]string{}} - if parent, _ := doc["inherits"].(string); parent != "" && depth < 8 { - if p := findHelixTheme(parent, dirs); p != "" { - if base := readHelixRaw(p, dirs, depth+1); base != nil { - raw = base - } - } - } - if pal, ok := doc["palette"].(map[string]any); ok { - for k, v := range pal { - if s, ok := v.(string); ok { - raw.palette[k] = s - } - } - } - delete(doc, "palette") - delete(doc, "inherits") - flattenHelix("", doc, raw.scopes) - return raw -} - -func findHelixTheme(name string, dirs []string) string { - if name == "" || strings.ContainsAny(name, "/\\.") { - return "" - } - for _, d := range dirs { - p := filepath.Join(d, name+".toml") - if _, err := os.Stat(p); err == nil { - return p - } - } - return "" -} - -// flattenHelix walks the decoded document into scope -> style. A table is a -// style when it holds only style keys; anything else is a dotted scope name -// someone wrote out as a table, so it keeps descending. -func flattenHelix(prefix string, m map[string]any, into map[string]helixStyle) { - for k, v := range m { - key := k - if prefix != "" { - key = prefix + "." + k - } - switch v := v.(type) { - case string: - into[key] = helixStyle{fg: v} - case map[string]any: - if st, ok := helixStyleOf(v); ok { - into[key] = st - } else { - flattenHelix(key, v, into) - } - } - } -} - -func helixStyleOf(m map[string]any) (helixStyle, bool) { - var st helixStyle - for k, v := range m { - switch k { - case "fg": - st.fg, _ = v.(string) - case "bg": - st.bg, _ = v.(string) - case "modifiers": - mods, _ := v.([]any) - for _, mod := range mods { - switch mod { - case "italic": - st.italic = true - case "bold": - st.bold = true - } - } - case "underline", "underline_style", "underline_color": - // decoration we have no use for, but still a style - default: - return helixStyle{}, false - } - } - return st, true -} - -// the sixteen names a helix theme may use without a palette entry -var termHex = map[string]string{ - "black": "#000000", "red": "#cd3131", "green": "#0dbc79", "yellow": "#e5e510", - "blue": "#2472c8", "magenta": "#bc3fbc", "cyan": "#11a8cd", "gray": "#8a8a8a", - "light-red": "#f14c4c", "light-green": "#23d18b", "light-yellow": "#f5f543", - "light-blue": "#3b8eea", "light-magenta": "#d670d6", "light-cyan": "#29b8db", - "light-gray": "#c0c0c0", "white": "#e5e5e5", -} - -func (r *helixRaw) color(name string) string { - if name == "" || name == "default" { - return "" - } - if c, ok := r.palette[name]; ok { - name = c - } - if strings.HasPrefix(name, "#") { - return hex6(okColor(name)) - } - return termHex[name] -} - -// fg / bg take the first of several scopes that names one, so a theme that -// skips a scope is answered by whatever it does say. Scope names fall back -// along their dots the way helix resolves them. -func (r *helixRaw) fg(scopes ...string) string { return r.pick(true, scopes) } -func (r *helixRaw) bg(scopes ...string) string { return r.pick(false, scopes) } - -func (r *helixRaw) pick(wantFg bool, scopes []string) string { - for _, scope := range scopes { - for key := scope; key != ""; { - if st, ok := r.scopes[key]; ok { - c := st.bg - if wantFg { - c = st.fg - } - if c := r.color(c); c != "" { - return c - } - } - i := strings.LastIndex(key, ".") - if i < 0 { - break - } - key = key[:i] - } - } - return "" -} - -// zed syntax keys helix spells differently; everything else either matches or -// falls back along its dots (punctuation.bracket -> punctuation). -var helixAlias = map[string]string{ - "number": "constant.numeric", - "boolean": "constant.builtin.boolean", - "property": "variable.other.member", - "preproc": "keyword.directive", - "primary": "variable", - "enum": "type.enum", - "string.escape": "constant.character.escape", - "string.regex": "string.regexp", - "variable.special": "variable.builtin", - "comment.doc": "comment.block.documentation", - "link_uri": "markup.link.url", - "link_text": "markup.link.text", - "title": "markup.heading", - "emphasis": "markup.italic", - "emphasis.strong": "markup.bold", -} - -func helixTheme(name string, raw *helixRaw) *Theme { - bg := raw.bg("ui.background", "ui.window") - fg := raw.fg("ui.text", "ui.window") - if bg == "" || fg == "" { - return nil // a theme that paints on the terminal's colors, not ours - } - t := &Theme{ - ID: "helix/" + slug(name), Source: "helix", Name: name, - Appearance: "dark", Bg: bg, Fg: fg, - Syntax: map[string]SyntaxStyle{}, - } - if lum(bg) > 0.5 { - t.Appearance = "light" - } - // A helix theme dresses an editor, not a web page, so it is read for what - // the page needs and fill() closes the rest. The quiet backgrounds come - // first: a selected menu row is often the theme's loudest color. - t.Panel = raw.bg("ui.statusline", "ui.menu", "ui.popup") - t.Hover = raw.bg("ui.cursorline.primary", "ui.selection", "ui.menu.selected") - t.Border = raw.fg("ui.window") - t.LineNo = raw.fg("ui.linenr") - t.Muted = raw.fg("comment", "ui.linenr") - t.Accent = raw.fg("function", "keyword", "type") - t.Note = raw.fg("warning", "diagnostic.warning", "constant.numeric") - - for scope, st := range raw.scopes { - if strings.HasPrefix(scope, "ui.") { - continue - } - if c := raw.color(st.fg); c != "" { - t.Syntax[scope] = syntaxStyle(c, st.italic, st.bold) - } - } - for key, scope := range helixAlias { - if _, ok := t.Syntax[key]; ok { - continue - } - if st, ok := t.Syntax[resolveKey(t, scope)]; ok { - t.Syntax[key] = st - } - } - t.fill() - t.setPlayers(t.syntaxColors()) - return t -} - -func syntaxStyle(color string, italic, bold bool) SyntaxStyle { - s := SyntaxStyle{Color: color} - if italic { - it := "italic" - s.FontStyle = &it - } - if bold { - w := 700.0 - s.FontWeight = &w - } - return s -} - -func first(vals ...string) string { - for _, v := range vals { - if v != "" { - return v - } - } - return "" -} - -// slug is a theme's id in an attribute and a URL: ascii, lowercase, dashed. -func slug(s string) string { - var b strings.Builder - dash := false - for _, r := range strings.ToLower(s) { - if r >= 'a' && r <= 'z' || r >= '0' && r <= '9' { - b.WriteRune(r) - dash = false - } else if !dash && b.Len() > 0 { - b.WriteByte('-') - dash = true - } - } - return strings.Trim(b.String(), "-") -} diff --git a/vrsite/themes_test.go b/vrsite/themes_test.go deleted file mode 100644 index 4ef1cca..0000000 --- a/vrsite/themes_test.go +++ /dev/null @@ -1,294 +0,0 @@ -package main - -import ( - "os" - "path/filepath" - "strings" - "testing" -) - -// everything a helix theme reader has to survive: quoted scope keys, a -// palette, one of the terminal color names, modifiers, and an inline table -// broken over lines the way a formatter leaves it -const helixSrc = ` -# a comment -"ui.background" = { bg = "base" } -"ui.text" = { fg = "text" } -"ui.linenr" = { fg = "muted" } -"ui.statusline" = { fg = "text", bg = "surface" } -"ui.cursorline.primary" = { bg = "highlight" } -"ui.menu.selected" = { fg = "base", bg = "rose" } -"ui.window" = { fg = "muted" } -comment = { fg = "muted", modifiers = ["italic"] } -keyword = { fg = "pine", modifiers = [ - "bold", -] } -string = "gold" -function = { fg = "rose" } -"constant.numeric" = { fg = "iris" } -"variable.other.member" = { fg = "foam" } -"punctuation" = { fg = "muted" } -warning = { fg = "gold" } -type = "white" - -[palette] -base = "#191724" -text = "#e0def4" -muted = "#6e6a86" -surface = "#1f1d2e" -highlight = "#21202e" -pine = "#31748f" -gold = "#f6c177" -rose = "#ebbcba" -iris = "#c4a7e7" -foam = "#9ccfd8" -` - -func writeTheme(t *testing.T, dir, name, body string) string { - t.Helper() - if err := os.MkdirAll(dir, 0o755); err != nil { - t.Fatal(err) - } - path := filepath.Join(dir, name) - if err := os.WriteFile(path, []byte(body), 0o644); err != nil { - t.Fatal(err) - } - return path -} - -func TestHelixTheme(t *testing.T) { - dir := t.TempDir() - path := writeTheme(t, dir, "rose_pine.toml", helixSrc) - th := loadHelixTheme(path, []string{dir}) - if th == nil { - t.Fatal("theme did not load") - } - for _, tc := range []struct{ what, got, want string }{ - {"id", th.ID, "helix/rose-pine"}, - {"source", th.Source, "helix"}, - {"name", th.Name, "rose_pine"}, - {"appearance", th.Appearance, "dark"}, - {"bg", th.Bg, "#191724"}, - {"fg", th.Fg, "#e0def4"}, - {"panel", th.Panel, "#1f1d2e"}, - {"line numbers", th.LineNo, "#6e6a86"}, - {"border", th.Border, "#6e6a86"}, - {"accent", th.Accent, "#ebbcba"}, // function - {"note", th.Note, "#f6c177"}, // warning - {"hover", th.Hover, "#21202e"}, // cursorline, not the loud menu row - {"muted", th.Muted, "#6e6a86"}, // comment - } { - if tc.got != tc.want { - t.Errorf("%s = %q, want %q", tc.what, tc.got, tc.want) - } - } - // syntax keys the site paints with, spelled the way helix spells them - for _, tc := range []struct{ key, want string }{ - {"comment", "#6e6a86"}, - {"keyword", "#31748f"}, - {"string", "#f6c177"}, - {"type", "#e5e5e5"}, // a terminal color name, not a palette one - {"number", "#c4a7e7"}, // zed's name for constant.numeric - {"property", "#9ccfd8"}, // zed's name for variable.other.member - {"punctuation.bracket", "#6e6a86"}, // falls back along its dots - } { - if got := th.syn(tc.key); got != tc.want { - t.Errorf("syntax %s = %q, want %q", tc.key, got, tc.want) - } - } - if s := th.Syntax["comment"]; s.FontStyle == nil || *s.FontStyle != "italic" { - t.Errorf("comment is not italic: %+v", s) - } - if s := th.Syntax["keyword"]; s.FontWeight == nil || *s.FontWeight != 700 { - t.Errorf("keyword is not bold: %+v", s) - } - // agent colors: from the code's own colors, and none of them invisible - if len(th.Players) < 3 { - t.Fatalf("agent colors = %v, want at least 3", th.Players) - } - for _, p := range th.Players { - if colorDist(p, hex6(th.Bg)) <= 60 || colorDist(p, hex6(th.Fg)) <= 60 { - t.Errorf("agent color %s vanishes against the theme", p) - } - } -} - -// A child theme restating only the palette is how helix ships most of its -// families: the parent's scopes have to resolve against the child's colors. -func TestHelixInherits(t *testing.T) { - dir := t.TempDir() - writeTheme(t, dir, "parent.toml", helixSrc) - path := writeTheme(t, dir, "child.toml", ` -inherits = "parent" -comment = { fg = "muted" } - -[palette] -base = "#eff1f5" -text = "#4c4f69" -muted = "#7c7f93" -surface = "#e6e9ef" -highlight = "#dce0e8" -pine = "#1e66f5" -gold = "#df8e1d" -rose = "#ea76cb" -iris = "#8839ef" -foam = "#04a5e5" -`) - th := loadHelixTheme(path, []string{dir}) - if th == nil { - t.Fatal("child theme did not load") - } - if th.Bg != "#eff1f5" || th.Fg != "#4c4f69" { - t.Errorf("inherited scopes kept the parent's palette: bg=%s fg=%s", th.Bg, th.Fg) - } - if th.Appearance != "light" { - t.Errorf("appearance = %q, want light for a pale background", th.Appearance) - } - if got := th.syn("keyword"); got != "#1e66f5" { - t.Errorf("inherited keyword = %q, want the child's pine", got) - } - // the child's own entry wins over the parent's, modifiers and all - if s := th.Syntax["comment"]; s.FontStyle != nil { - t.Errorf("child comment kept the parent's italics: %+v", s) - } -} - -// A theme that names almost nothing still has to dress a whole page. -func TestFillClosesTheGaps(t *testing.T) { - th := &Theme{Bg: "#101010", Fg: "#f0f0f0", Syntax: map[string]SyntaxStyle{ - "function": {Color: "#88c0d0"}, - }} - th.fill() - for _, tc := range []struct{ what, got string }{ - {"panel", th.Panel}, {"border", th.Border}, {"line numbers", th.LineNo}, - {"muted", th.Muted}, {"accent", th.Accent}, {"note", th.Note}, {"hover", th.Hover}, - } { - if okColor(tc.got) == "" { - t.Errorf("%s = %q, want a color", tc.what, tc.got) - } - } - if th.Accent != "#88c0d0" { - t.Errorf("accent = %q, want the theme's own function color", th.Accent) - } - if th.Panel == th.Bg || th.Hover == th.Bg { - t.Errorf("panel %q and hover %q must lift off the background %q", th.Panel, th.Hover, th.Bg) - } - // a panel the text would be lost in is not kept - lost := &Theme{Bg: "#f7f3ee", Fg: "#605a52", Panel: "#605a52"} - lost.fill() - if lost.Panel == "#605a52" { - t.Error("kept a panel the foreground disappears into") - } -} - -func TestZedFamily(t *testing.T) { - fam, err := parseZedFamily([]byte(`{"name":"Fake","themes":[ - {"name":"Fake Dark","appearance":"dark","style":{ - "editor.background":"#101010","editor.foreground":"#e0e0e0", - "text.accent":"0f4b6e","warning":"#e0af68", - "players":[{"cursor":"#7aa2f7"},{"cursor":"#9ece6a"}], - "syntax":{"keyword":{"color":"#bb9af7","font_style":"italic"}, - "string":{"color":"9ece6a"}}}}, - {"name":"Fake Light","appearance":"light","style":{ - "editor.background":"#fafafa","editor.foreground":"#383a42"}}]}`)) - if err != nil { - t.Fatal(err) - } - if len(fam) != 2 { - t.Fatalf("themes = %d, want 2", len(fam)) - } - dark, light := fam[0], fam[1] - if dark.ID != "zed/fake-dark" || light.ID != "zed/fake-light" { - t.Errorf("ids = %q, %q", dark.ID, light.ID) - } - // a theme in the wild does drop the odd "#": what is not a color is - // treated as unsaid, and filled in rather than emitted as nonsense - if dark.Accent == "0f4b6e" { - t.Error("kept a color with no #") - } - if _, ok := dark.Syntax["string"]; ok { - t.Error("kept a syntax color with no #") - } - if dark.syn("keyword") != "#bb9af7" { - t.Errorf("keyword = %q", dark.syn("keyword")) - } - if len(dark.Players) < 2 || dark.Players[0] != "#7aa2f7" { - t.Errorf("agent colors = %v, want the player palette first", dark.Players) - } - // nothing to work from but bg and fg, and still a whole theme - if okColor(light.Muted) == "" || okColor(light.Hover) == "" { - t.Errorf("light theme left gaps: %+v", light) - } -} - -// The picker's two files: a block per theme, and a menu that names them. -func TestThemeFiles(t *testing.T) { - dark, light := loadTheme("", "", "dark"), loadTheme("", "", "light") - helix := loadHelixTheme(writeTheme(t, t.TempDir(), "rose_pine.toml", helixSrc), nil) - ts := themesFrom([]*Theme{dark, light, helix}, dark, light) - - css := string(ts.CSS) - for _, th := range ts.List { - if !strings.Contains(css, `:root[data-theme="`+th.ID+`"]`) { - t.Errorf("no css block for %s", th.ID) - } - if !strings.Contains(string(ts.JS), th.ID) { - t.Errorf("%s is not in the menu", th.ID) - } - } - for _, want := range []string{"--bg:", "--fg:", "--ag0:", "color-scheme: dark", "color-scheme: light"} { - if !strings.Contains(css, want) { - t.Errorf("themes.css never says %q", want) - } - } - // every declaration has to be worth something to the browser - for _, line := range strings.Split(css, "\n") { - if l := strings.TrimSpace(line); strings.HasPrefix(l, "--") && strings.HasSuffix(l, ": ;") { - t.Errorf("empty declaration: %s", l) - } - } - if n := strings.Count(string(ts.JS), `"id":`); n != len(ts.List) { - t.Errorf("menu has %d themes, want %d", n, len(ts.List)) - } -} - -// The two editors' theme directories, as they are on a machine that has them. -func TestDiscoverFindsBothEditors(t *testing.T) { - home := t.TempDir() - t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, "config")) - t.Setenv("XDG_DATA_HOME", filepath.Join(home, "data")) - writeTheme(t, filepath.Join(home, "config", "zed", "themes"), "mine.json", - `{"name":"Mine","themes":[{"name":"Mine Dark","appearance":"dark","style":{ - "editor.background":"#101010","editor.foreground":"#e0e0e0"}}]}`) - writeTheme(t, filepath.Join(home, "data", "zed", "extensions", "installed", "ext", "themes"), - "ext.json", `{"name":"Ext","themes":[{"name":"Ext Light","appearance":"light","style":{ - "editor.background":"#fafafa","editor.foreground":"#383a42"}}]}`) - writeTheme(t, filepath.Join(home, "config", "helix", "themes"), "mine_helix.toml", helixSrc) - - found := map[string]*Theme{} - for _, th := range discoverThemes() { - found[th.ID] = th - } - for _, want := range []string{"zed/mine-dark", "zed/ext-light", "helix/mine-helix"} { - if found[want] == nil { - t.Errorf("did not find %s", want) - } - } -} - -// Coverage colors are mixed in the browser so every theme can supply them. -func TestMaskMix(t *testing.T) { - s := &Site{Agents: []*Agent{{Bit: 1}, {Bit: 2}, {Bit: 4}}} - for _, tc := range []struct { - mask uint8 - want string - }{ - {1, "var(--ag0)"}, - {5, "color-mix(in srgb, var(--ag0) 50.000%, var(--ag2))"}, - {7, "color-mix(in srgb, var(--ag0) 33.333%, color-mix(in srgb, var(--ag1) 50.000%, var(--ag2)))"}, - } { - if got := s.maskMix(tc.mask); got != tc.want { - t.Errorf("mask %d = %q, want %q", tc.mask, got, tc.want) - } - } -} diff --git a/vrsite/transcript.go b/vrsite/transcript.go deleted file mode 100644 index 713fe36..0000000 --- a/vrsite/transcript.go +++ /dev/null @@ -1,602 +0,0 @@ -// transcript.go — the conversation a session's reading happened inside. -// -// The vr log says a session read a file at 10:04; the harness that ran that -// session kept the whole conversation on disk, in its own format. Here we find -// that file by session id and flatten both known formats into Turns, so a note -// can be opened at the moment it was written. -// -// Two rules keep this cheap and safe. Tool calls and their output are reduced -// to a line each — transcripts reach megabytes and none of that belongs in a -// page — and nothing outside a configured root is ever opened, with session -// ids checked before they touch the filesystem. -package main - -import ( - "encoding/json" - "fmt" - "os" - "path/filepath" - "sort" - "strings" - "sync" - "time" -) - -const ( - maxTranscript = 32 << 20 // refuse to parse more than this in one file - transcriptCacheMax = 8 // parsed transcripts are large; keep few - briefLine = 160 // one line of a tool call or its output - maxText = 6000 // one message - convWindow = 80 // turns rendered around the anchored moment - convMax = 1500 // turns rendered by "show all" -) - -// A Turn is one moment in a session: something said, a tool called or answered, -// or — woven in from the vr log — a read, a grep, a note. -type Turn struct { - Role string // user | assistant | thinking | tool | result | vr - Kind string // qualifies Role: the vr op, or "error" on a failed tool - When time.Time - Text string // what was said - Tool string // tool name, on tool and result turns - Detail string // one compact line: the call's arguments, or its output - File string // vr turns: the file the op touched - Note *Note // vr note turns: the note itself, rendered as a card - Here bool // the anchored moment -} - -func (t Turn) Clock() string { - if t.When.IsZero() { - return "" - } - return t.When.Local().Format("15:04:05") -} - -// A Transcript is one harness conversation, already normalized. -type Transcript struct { - Path string - Harness string // claude-code | codex - Turns []Turn - Err string -} - -// transcripts finds and parses harness transcripts, remembering what it has -// already parsed. Roots are the only places it will look. -type transcripts struct { - roots []string - - mu sync.Mutex - cache map[string]*Transcript // path|mtime|size -> parsed -} - -func newTranscripts(roots []string) *transcripts { - tx := &transcripts{cache: map[string]*Transcript{}} - for _, r := range roots { - r = strings.TrimSpace(r) - if r == "" { - continue - } - if abs, err := filepath.Abs(r); err == nil { - r = abs - } - tx.roots = append(tx.roots, filepath.Clean(r)) - } - return tx -} - -// defaultTranscriptRoots are where the two harnesses we know about keep their -// conversations. -func defaultTranscriptRoots() []string { - home, err := os.UserHomeDir() - if err != nil { - return nil - } - return []string{filepath.Join(home, ".claude", "projects"), filepath.Join(home, ".codex", "sessions")} -} - -// safeSession refuses ids that could name something we did not mean to open: -// the id goes into a filesystem path, so it must be one plain component. -func safeSession(id string) error { - if id == "" { - return fmt.Errorf("no session id") - } - if len(id) > 128 { - return fmt.Errorf("session id is too long") - } - for _, r := range id { - ok := r == '-' || r == '_' || r == ':' || r == '.' || - '0' <= r && r <= '9' || 'a' <= r && r <= 'z' || 'A' <= r && r <= 'Z' - if !ok { - return fmt.Errorf("session id contains %q", r) - } - } - if strings.Contains(id, "..") { - return fmt.Errorf("session id contains %q", "..") - } - return nil -} - -// mangleDir is how Claude Code names a project directory after its cwd: -// /home/u/0x4200.cafe -> -home-u-0x4200-cafe. -func mangleDir(dir string) string { - return strings.NewReplacer("/", "-", ".", "-").Replace(dir) -} - -// under states the rule the globs below already obey: a transcript we open -// lies inside a configured root. It is checked anyway, so the rule has one -// place to fail rather than living in the shape of two patterns. -func under(root, path string) bool { - rel, err := filepath.Rel(root, path) - if err != nil { - return false - } - return rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) -} - -// find locates a session's transcript. Claude Code writes -// //.jsonl; codex writes -// /YYYY/MM/DD/rollout-