Skip to content
quarry Artifact [dc0e3fe8b0]
Login

Artifact [dc0e3fe8b0]

Artifact dc0e3fe8b0ddd52fe47070787f67ad6f5451266978d28650c10228efebfc0b25:


// Package web is the HTML consumer of the registry (0001 §9). Pages are
// server-rendered html/template over op results — the same ops the API
// serves, so every page capability is API-visible by construction.
// Repo-scoped pages live under /r/{repo}/; the home page is the fleet.
package web

import (
	"runtime/debug"

	"bytes"
	"context"
	"crypto/sha256"
	_ "embed"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"hash/crc32"
	"html/template"
	"io"
	"log"
	"net/http"
	"net/url"
	"reflect"
	"regexp"
	"slices"
	"sort"
	"strconv"
	"strings"
	"time"

	"craftdesign.group/quarry/internal/api"
	"craftdesign.group/quarry/internal/ci"
	"craftdesign.group/quarry/internal/diff"
	"craftdesign.group/quarry/internal/errlog"
	"craftdesign.group/quarry/internal/evt"
	"craftdesign.group/quarry/internal/highlight"
	"craftdesign.group/quarry/internal/idn"
	"craftdesign.group/quarry/internal/index"
	"craftdesign.group/quarry/internal/legal"
	"craftdesign.group/quarry/internal/obs"
	"craftdesign.group/quarry/internal/oltp"
	"craftdesign.group/quarry/internal/ops"
	"craftdesign.group/quarry/internal/timing"
)

// datastarJS is the vendored Datastar bundle (MIT; see the provenance
// ledger) — the one allowed frontend framework (0001 Principle 2),
// served self-contained. Everything works without it (Principle 3);
// it only adds live updates.
//
//go:embed assets/datastar.js
var datastarJS []byte

//go:embed assets/composer.js
var composerJS []byte

//go:embed assets/wiki.js
var wikiJS []byte

// The mark, embedded like everything else quarry serves: the privacy
// page states that these pages load nothing from another host, and an
// icon fetched from a CDN would make that untrue.
//
// favicon.ico carries 16, 32 and 48 in one file so the browser's
// unprompted /favicon.ico request is answered properly rather than
// 404ing and falling back to a letter.
//
//go:embed assets/favicon.ico
var faviconICO []byte

//go:embed assets/apple-touch-icon.png
var appleTouchIcon []byte

//go:embed assets/quarry.png
var markPNG []byte

// Notifier is the change signal live pages subscribe to. The
// composition root supplies an events-backed implementation; web never
// touches the event plane directly. nil disables liveness. repo "*"
// watches every repo (the fleet page's signal).
type Notifier interface {
	Watch(repo string) (<-chan struct{}, func())
}

// ChatMessage is one rendered chat line (mirrors chat.Message without
// importing the data plane into a view type).
type ChatMessage struct {
	Seq  uint64 `json:"seq"`
	Kind string `json:"kind"`
	Ref  uint64 `json:"ref,omitempty"`
	User string `json:"user"`
	Text string `json:"text"`
	// HTML is server-rendered, sanitizer-gated markup (0002 §2: the
	// sanitizer is the gate) — the trusted injection point, same
	// pattern as WikiHTML/FileHTML elsewhere on pageData.
	HTML    template.HTML `json:"html"`
	At      string        `json:"at"`
	Edited  bool          `json:"edited,omitempty"`
	Deleted bool          `json:"deleted,omitempty"`
	// Refs are the canonical reference tokens the message carries;
	// Replies counts what answered it; RefUser and RefLine are the
	// quote of the message it answers (RFC 0011 §14). All four come
	// from the op — the page renders them, it does not derive them.
	Refs    []string `json:"refs,omitempty"`
	Replies int      `json:"replies,omitempty"`
	RefUser string   `json:"refUser,omitempty"`
	RefLine string   `json:"refLine,omitempty"`
	// Grouped says this row continues the run above it — same author,
	// same minute — so it is drawn as a body alone under the header
	// that run already has. Derived by the renderer from the rows
	// around it, never carried on the wire.
	Grouped bool `json:"-"`
	// RefQuotes are the diminished quotes for the #seq references the
	// TEXT carries, as distinct from Ref's formal reply. Derived, like
	// Grouped, from the rows around this one: a quote is only ever
	// shown for a message the same page can also show in full, so an
	// aged-out or off-page seq keeps its link and loses only the words.
	RefQuotes []ChatQuote `json:"-"`
}

// ChatQuote is one diminished quote: which message, who wrote it, and
// its first line. The same shape a reply's own quote is drawn from,
// because it is the same block.
type ChatQuote struct {
	Seq  uint64
	User string
	Line string
}

// chatUnreadView mirrors chat.unread's output (op-invoke boundary, not a
// direct import of the api package's private types).
type chatUnreadView struct {
	Repos map[string]struct {
		Unread int    `json:"unread"`
		Since  uint64 `json:"since"`
	} `json:"repos"`
}

// ChatLive delivers a repo channel's live messages to the SSE handler,
// resumable from a seq (RFC 0011 §2 — the never-drops Tail, not the
// tick-style Subscribe). nil disables the live chat stream (history +
// form still work). The composition root's adapter maps the repo name
// to its project code.
type ChatLive interface {
	Tail(repo string, from uint64) (<-chan ChatMessage, func())
}

// base is the layout every page renders through. Both themes come from
// prefers-color-scheme; no JavaScript anywhere (0001 Principle 3 — the
// no-JS baseline is the baseline). The header carries the fleet crumb
// and, inside a repo, that repo's nav and search.
// pathesc escapes one path segment — wiki titles carry slashes in real
// stores (tcl's "(Initi/Fin)alize"), which must ride as %2F to stay one
// segment for the mux.
// artifactTimeLayouts are the shapes a D card's timestamp arrives in.
// Fossil writes UTC with millisecond precision and no zone; imported
// corpora also carry the second-precision form, and quarry's own OLTP
// stamps are RFC3339. All are UTC, so none carries an offset to honour.
var artifactTimeLayouts = []string{
	"2006-01-02T15:04:05.000",
	"2006-01-02T15:04:05",
	time.RFC3339,
	"2006-01-02 15:04:05",
	"2006-01-02",
}

func parseArtifactTime(s string) (time.Time, bool) {
	for _, l := range artifactTimeLayouts {
		if t, err := time.Parse(l, s); err == nil {
			return t.UTC(), true
		}
	}
	return time.Time{}, false
}

// ago renders a timestamp the way a person reads one. Recent times go
// relative ("3 hours ago"), older ones go to a plain date; the exact
// value is kept in the title attribute either way, because a relative
// time is friendlier but an absolute one is what you quote in a bug
// report.
//
// An unparseable stamp is returned VERBATIM rather than blanked or
// guessed at: it came out of a real artifact, and showing it is how the
// layout gap gets noticed.
// weekday is the UTC day-of-week of a stored date — the same
// convention zit's --weekday prints (zit#111), computed from the same
// UTC timestamps, so the CLI and the forge always name the same day.
func weekday(s string) string {
	for _, layout := range []string{"2006-01-02T15:04:05.000", "2006-01-02T15:04:05",
		"2006-01-02T15:04:05.999999999", "2006-01-02"} {
		if t, err := time.Parse(layout, s); err == nil {
			return t.UTC().Format("Mon")
		}
	}
	return ""
}

func ago(s string) template.HTML {
	if s == "" {
		return ""
	}
	t, ok := parseArtifactTime(s)
	if !ok {
		return template.HTML(template.HTMLEscapeString(s))
	}
	return template.HTML(fmt.Sprintf(`<time datetime="%s" title="%s">%s</time>`,
		template.HTMLEscapeString(t.Format(time.RFC3339)),
		template.HTMLEscapeString(t.Format("2006-01-02 15:04:05 UTC")),
		template.HTMLEscapeString(relative(t, time.Now().UTC()))))
}

// relative words a duration at one significant unit. Fossil's forum uses
// the same shape ("2.0 hours ago", "13.4 days ago"); this rounds to
// whole units instead, because a tenth of a day is not a quantity anyone
// reasons in.
func relative(t, now time.Time) string {
	d := now.Sub(t)
	if d < 0 {
		// Clock skew between a writer and this server. "in 3 minutes" is
		// noise; the timestamp itself is the honest answer.
		return t.Format("2006-01-02 15:04")
	}
	switch {
	case d < time.Minute:
		return "just now"
	case d < time.Hour:
		return plural(int(d.Minutes()), "minute") + " ago"
	case d < 24*time.Hour:
		return plural(int(d.Hours()), "hour") + " ago"
	case d < 30*24*time.Hour:
		// Once the day is no longer today, NAMING it adds what the
		// count alone cannot — "Thu · 3 days ago" answers "which day
		// was that" in place. The zit#111 convention, forge-wide: UTC
		// weekday, so the CLI and these pages never disagree.
		//
		// The count is CALENDAR days, not elapsed-hours/24: naming the
		// weekday exposed the rounding — a Tuesday event 55 hours before
		// a Friday page read "Tue · 2 days ago", and Tuesday is not two
		// days before Friday in any human's reckoning.
		day := func(x time.Time) time.Time {
			return time.Date(x.Year(), x.Month(), x.Day(), 0, 0, 0, 0, time.UTC)
		}
		days := int(day(now).Sub(day(t)).Hours() / 24)
		if days < 1 {
			days = 1
		}
		return t.Format("Mon") + " · " + plural(days, "day") + " ago"
	default:
		// Past a month, a date is more useful than a count of days, and
		// past a year the year is the part that matters.
		if t.Year() == now.Year() {
			return t.Format("Mon · 2 Jan")
		}
		return t.Format("Mon · 2 Jan 2006")
	}
}

func plural(n int, unit string) string {
	if n == 1 {
		return "1 " + unit
	}
	return fmt.Sprintf("%d %ss", n, unit)
}

// agoShort words a duration for a badge: "34m", "12h", "3d", "2y".
//
// The long form belongs in prose. In a column of numbers it is the
// thing that breaks alignment, which is the whole reason the stats are
// badges rather than a sentence.
func agoShort(s string) template.HTML {
	t, ok := parseArtifactTime(s)
	if !ok {
		return ""
	}
	d := time.Since(t)
	var out string
	switch {
	case d < time.Minute:
		out = "now"
	case d < time.Hour:
		out = fmt.Sprintf("%dm", int(d.Minutes()))
	case d < 24*time.Hour:
		out = fmt.Sprintf("%dh", int(d.Hours()))
	case d < 365*24*time.Hour:
		out = fmt.Sprintf("%dd", int(d.Hours()/24))
	default:
		out = fmt.Sprintf("%dy", int(d.Hours()/24/365))
	}
	return template.HTML(fmt.Sprintf(`<time datetime="%s" title="%s">%s</time>`,
		template.HTMLEscapeString(t.Format(time.RFC3339)),
		template.HTMLEscapeString(t.Format("2006-01-02 15:04:05 UTC")),
		out))
}

// boardColumn is one board lane: the label as the tracker spells it,
// and the tickets currently in it.
// boardMove is one card move as the board reports it afterwards: what
// moved, where, and where it came from so undo is one post.
type boardMove struct {
	ID, Title, Field, From, To string
}

type boardColumn struct {
	Status  string
	Tickets []ticketSummary
	// Expanded: drawn at full width; otherwise a strip. Folding is the
	// reader's choice, carried in the URL (?fold=A,B) so it survives a
	// reload and can be linked; with no choice yet, empty columns fold.
	// ToggleURL is this view with this column's fold flipped — the
	// chevron in the header, both ways.
	Expanded  bool
	ToggleURL string
}

// boardFields are the ticket fields a board may be grouped by. The
// WORDS for each come from the repository's vocabulary (ticket.config:
// .quarry/tickets.json over fossil's defaults), passed in by the
// handler — the vocabulary is the project's, not this table's.
//
// The vocabulary draws lanes that hold NO tickets. A board whose
// columns are only the values already in use is a report, not a board:
// quarry's own tracker had only ever written "Open", so it drew one
// column and the move control could only move a ticket to where it
// already was. Observed values outside the vocabulary still get their
// own lanes rather than being dropped.
var boardFields = []struct {
	Key, Label string
}{
	{"status", "status"},
	{"priority", "priority"},
	{"severity", "severity"},
	{"type", "type"},
	{"subsystem", "subsystem"},
}

func boardAxis(key string) bool {
	for _, f := range boardFields {
		if f.Key == key {
			return true
		}
	}
	return false
}

// fieldOf reads one groupable field off a summary.
func fieldOf(t ticketSummary, key string) string {
	switch key {
	case "priority":
		return t.Priority
	case "severity":
		return t.Severity
	case "type":
		return t.Type
	case "subsystem":
		return t.Subsystem
	default:
		return t.Status
	}
}

// ticketState reads the tracker's state axis out of a URL. A value the
// op would reject folds back to the default instead of 400ing a page
// somebody reached by editing the address bar, and "open" normalises to
// empty so the one default state has exactly one URL.
// ticketAxes are the fields a report may narrow on. The URL IS the
// report: these six keys plus state, view and sort reproduce any
// listing exactly, which is why saved reports need no new storage and
// no new query language — just a link.
var ticketAxes = []string{"type", "severity", "priority", "subsystem", "status", "author"}

// ticketAxesAcross adds the axis that only the cross-repository listing
// has. Repository is addressing on a tracker page and a facet here, so
// it belongs to this list alone.
var ticketAxesAcross = append(append([]string{}, ticketAxes...), "repo")

// acrossLimit bounds the merged listing. K trackers merged in memory
// cannot be paged by a cursor that encodes one tracker's position, so
// the page takes a bounded slice and says when there is more.
const acrossLimit = 100

// ticketTokens are the query box's field prefixes. "is" spells state
// the way every forge's search box does; the rest name their axis
// outright. Both spellings reach the same URL parameters, which is the
// whole point: the box is INPUT SUGAR over the report, not a second
// query system with its own semantics to keep in step.
var ticketTokens = map[string]string{
	"is": "state", "state": "state",
	"type": "type", "severity": "severity", "priority": "priority",
	"subsystem": "subsystem", "status": "status", "author": "author",
}

// splitQuery breaks a query box into words, honouring double quotes so
// a value with a space in it survives (subsystem:"web ui").
func splitQuery(q string) []string {
	var out []string
	var cur strings.Builder
	quoted := false
	flush := func() {
		if cur.Len() > 0 {
			out = append(out, cur.String())
			cur.Reset()
		}
	}
	for _, r := range q {
		switch {
		case r == '"':
			quoted = !quoted
		case !quoted && (r == ' ' || r == '\t'):
			flush()
		default:
			cur.WriteRune(r)
		}
	}
	flush()
	return out
}

// ticketParseQuery turns a query box into the URL parameters that ARE
// the report. Recognised prefixes become their axis; everything else is
// free text matched against titles. An unknown prefix is not an error
// and not silently dropped either — it stays part of the text, because
// a reader who types "fix:later" meant those characters.
func ticketParseQuery(q string) url.Values {
	v := url.Values{}
	var text []string
	for _, w := range splitQuery(q) {
		key, val, ok := strings.Cut(w, ":")
		axis, known := ticketTokens[strings.ToLower(key)]
		if ok && known && val != "" {
			if axis == "state" {
				val = strings.ToLower(val)
			}
			v.Set(axis, val)
			continue
		}
		text = append(text, w)
	}
	if t := strings.Join(text, " "); t != "" {
		v.Set("title", t)
	}
	return v
}

// ticketQueryString is ticketParseQuery run backwards: the report as a
// reader would have typed it, so the box shows the listing they are
// looking at however they got there — dropdown, link, or typing.
func ticketQueryString(state string, report url.Values, title string) string {
	var out []string
	if state != "" && state != "open" {
		out = append(out, "is:"+state)
	}
	for _, k := range ticketAxes {
		if v := report.Get(k); v != "" {
			if strings.ContainsAny(v, " \t") {
				v = `"` + v + `"`
			}
			out = append(out, k+":"+v)
		}
	}
	if title != "" {
		out = append(out, title)
	}
	return strings.Join(out, " ")
}

// ticketReport pulls the report axes out of a URL, ignoring everything
// else, so a link may carry fold state or a cursor without those ever
// reaching the query as a filter.
func ticketReport(q url.Values) url.Values { return ticketReportOf(q, ticketAxes) }

// ticketReportAcross reads the cross-repository listing's report, which
// is the tracker's axes plus the repository.
func ticketReportAcross(q url.Values) url.Values { return ticketReportOf(q, ticketAxesAcross) }

func ticketReportOf(q url.Values, axes []string) url.Values {
	r := url.Values{}
	for _, k := range axes {
		if v := strings.TrimSpace(q.Get(k)); v != "" {
			r.Set(k, v)
		}
	}
	return r
}

func ticketState(q url.Values) string {
	switch s := q.Get("state"); s {
	case "closed", "all":
		return s
	default:
		return ""
	}
}

// boardData fetches the tickets and lays out the board. The page and the
// move endpoint share it so a drag and a reload cannot disagree about
// what the board looks like.
// boardData takes the nav the caller has already assembled and returns
// it completed — the axes in, the counts filled. One parameter object
// rather than six positional strings, because every one of them is an
// axis of the same view and they were drifting apart at the call sites.
func boardData(r *ops.Registry, req *http.Request, nav ticketNav) (pageData, error) {
	repo, group, lane := nav.Repo, nav.Group, nav.Lane
	vals := url.Values{"repo": {repo}, "limit": {strconv.Itoa(boardLimit)}}
	if nav.State != "" {
		vals.Set("state", nav.State)
	}
	if nav.Title != "" {
		vals.Set("title", nav.Title)
	}
	for k, vs := range nav.Report {
		vals[k] = vs
	}
	out, err := invoke(req.Context(), r, "ticket.list", vals)
	if err != nil {
		return pageData{}, err
	}
	var tl struct {
		Tickets    []ticketSummary `json:"tickets"`
		Open       int             `json:"open"`
		Closed     int             `json:"closed"`
		Subsystems []ticketFacet   `json:"subsystems"`
		Authors    []ticketFacet   `json:"authors"`
	}
	remarshal(out, &tl)
	if !boardAxis(group) {
		group = "status"
	}
	// An explicit lane choice is honoured, including "none". Otherwise
	// pick one that actually cuts this set: a board whose lane field
	// every ticket shares spends a row of chrome saying nothing.
	switch {
	case lane == "none":
		lane = ""
	case lane == "":
		// No lanes unless asked: a board that opens with four priority
		// swimlanes nobody chose is logic the reader cannot see.
		lane = ""
	default:
		if !boardAxis(lane) {
			lane = ""
		}
	}
	vocab := ticketVocabFor(r, req, repo)
	board := buildBoard(tl.Tickets, group, lane, vocab)
	// Which columns are folded is the reader's choice, carried in the
	// URL so it survives a reload and can be linked. Before any choice
	// is made the empty columns fold, which is what keeps seven status
	// columns inside the window on the default (open) view. Each column
	// gets the URL that flips its own state, for the chevron.
	q := req.URL.Query()
	folded := map[string]bool{}
	explicit := q.Has("fold")
	for _, c := range strings.Split(q.Get("fold"), ",") {
		if c = strings.TrimSpace(c); c != "" {
			folded[strings.ToLower(c)] = true
		}
	}
	base := url.Values{"view": {"board"}, "group": {group}}
	if nav.State != "" {
		base.Set("state", nav.State)
	}
	if nav.Title != "" {
		base.Set("title", nav.Title)
	}
	for k, vs := range nav.Report {
		base[k] = vs
	}
	if lane != "" {
		base.Set("lane", lane)
	} else {
		base.Set("lane", "none")
	}
	for li := range board {
		for ci := range board[li].Columns {
			col := &board[li].Columns[ci]
			key := strings.ToLower(col.Status)
			if explicit {
				col.Expanded = !folded[key]
			} else {
				col.Expanded = len(col.Tickets) > 0
			}
			// The fold list after flipping this column; when nothing was
			// explicit yet, the implicit folds become explicit so the
			// other columns keep their state.
			next := map[string]bool{}
			for _, l := range board[li].Columns {
				k := strings.ToLower(l.Status)
				if explicit {
					next[k] = folded[k]
				} else {
					next[k] = len(l.Tickets) == 0
				}
			}
			next[key] = col.Expanded
			var list []string
			for _, l := range board[li].Columns {
				if next[strings.ToLower(l.Status)] {
					list = append(list, l.Status)
				}
			}
			v := url.Values{}
			for k, vs := range base {
				v[k] = vs
			}
			v.Set("fold", strings.Join(list, ","))
			col.ToggleURL = "?" + v.Encode()
		}
	}
	data := pageData{Title: "tickets", Repo: repo,
		BoardView: true, GroupBy: group, LaneBy: lane, Vocab: vocab,
		Nav: ticketNav{Repo: repo, State: nav.State, View: "board",
			Open: tl.Open, Closed: tl.Closed, Group: group, Lane: lane,
			Report: nav.Report, Title: nav.Title},
		Filters: ticketFilters(vocab, tl.Subsystems, tl.Authors, req.URL.Query()),
		Shown:   len(tl.Tickets), Truncated: len(tl.Tickets) >= boardLimit,
		Board:        board,
		ColumnLabels: columnLabels(tl.Tickets, group, vocab),
	}
	for _, f := range boardFields {
		data.AxisFields = append(data.AxisFields,
			struct{ Key, Label string }{f.Key, f.Label})
	}
	return data, nil
}

// ticketVocabFor asks ticket.config for this repository's vocabulary.
// On ANY failure it answers with the defaults: the vocabulary shapes
// ordering and suggestions, so the wrong words are an inconvenience
// while an error page here would make a typo in .quarry/tickets.json
// take the whole tracker surface down.
func ticketVocabFor(r *ops.Registry, req *http.Request, repo string) map[string][]string {
	out, err := invoke(req.Context(), r, "ticket.config", url.Values{"repo": {repo}})
	if err != nil {
		return api.DefaultTicketVocabulary
	}
	var cfg struct {
		Vocab []struct {
			Field string   `json:"field"`
			Words []string `json:"words"`
		} `json:"vocab"`
		Problem string `json:"problem"`
	}
	remarshal(out, &cfg)
	if cfg.Problem != "" {
		log.Printf("web: %s: %s ignored: %s", repo, ".quarry/tickets.json", cfg.Problem)
	}
	if len(cfg.Vocab) == 0 {
		return api.DefaultTicketVocabulary
	}
	vocab := make(map[string][]string, len(cfg.Vocab))
	for _, f := range cfg.Vocab {
		vocab[f.Field] = f.Words
	}
	return vocab
}

// boardLimit bounds what one board draws. It is the op's own ceiling:
// a board is a working surface, not the tracker's archive, and 729 open
// tickets in seven columns is a scroll, not a plan.
const boardLimit = 200

// triageRank orders a vocabulary word by its position in the board
// field's word list; words the vocabulary does not know sort after it,
// and an unset value after those — triage you have not done yet is not
// more urgent than triage you have.
func triageRank(vocabAll map[string][]string, field, value string) int {
	vocab := vocabAll[field]
	v := strings.TrimSpace(value)
	if v == "" {
		return len(vocab) + 1
	}
	for i, w := range vocab {
		if strings.EqualFold(w, v) {
			return i
		}
	}
	return len(vocab)
}

// byTriage sorts a page of summaries priority-first, severity as the
// tiebreak, then OLDEST first. It sorts the PAGE, not the tracker: the
// list op pages by updated, so this is only offered on the first page,
// where it covers everything up to the op's limit.
//
// Recency is deliberately not in the key. A ticket's position in the
// priority view should change only when a human changes its triage —
// with updated as the tiebreak, commenting on any ticket reshuffled its
// whole tier, and a bulk edit scrambled every tier at once. Equal triage
// is instead a queue: the ticket that has waited longest is first, so
// the tail of each tier is not a race to have been touched last.
func byTriage(ts []ticketSummary, vocab map[string][]string) {
	sort.SliceStable(ts, func(i, j int) bool {
		if a, b := triageRank(vocab, "priority", ts[i].Priority), triageRank(vocab, "priority", ts[j].Priority); a != b {
			return a < b
		}
		if a, b := triageRank(vocab, "severity", ts[i].Severity), triageRank(vocab, "severity", ts[j].Severity); a != b {
			return a < b
		}
		if ts[i].Created != ts[j].Created {
			return ts[i].Created < ts[j].Created
		}
		return ts[i].ID < ts[j].ID
	})
}

// byTriageRows is byTriage over decorated rows: the same vocabulary
// ordering, applied where the cross-repository listing has already
// merged K trackers into one slice.
func byTriageRows(rows []ticketRow, vocab map[string][]string) {
	sort.SliceStable(rows, func(i, j int) bool {
		if a, b := triageRank(vocab, "priority", rows[i].Priority), triageRank(vocab, "priority", rows[j].Priority); a != b {
			return a < b
		}
		if a, b := triageRank(vocab, "severity", rows[i].Severity), triageRank(vocab, "severity", rows[j].Severity); a != b {
			return a < b
		}
		if rows[i].Created != rows[j].Created {
			return rows[i].Created < rows[j].Created
		}
		return rows[i].ID < rows[j].ID
	})
}

// unsetLane labels the column or lane for tickets the tracker left
// blank. It is not a value any tracker writes, so it cannot collide.
const unsetLane = "unset"

// boardLane is one horizontal swimlane: a label and the same column set
// every other lane has, so the board reads as a grid.
type boardLane struct {
	Label   string
	Count   int
	Columns []boardColumn
}

// buildBoard arranges tickets into columns (the workflow, read left to
// right) crossed by swimlanes (the cut, read top to bottom).
//
// A kanban with only columns answers "what stage is this in". The lane
// is what makes it answer "and which of these actually matters" without
// filtering anything out of view — the reason a board beats a list.
//
// laneKey == "" means one implicit lane holding everything.
func buildBoard(tickets []ticketSummary, groupKey, laneKey string, vocab map[string][]string) []boardLane {
	if !boardAxis(groupKey) {
		groupKey = "status"
	}
	if groupKey == laneKey {
		laneKey = "" // crossing a field with itself yields a diagonal
	}
	// Every lane gets the SAME columns, including columns that are empty
	// in that lane: a grid whose rows have different columns is not a
	// grid, and a card cannot be dropped into a lane that isn't drawn.
	labels := columnLabels(tickets, groupKey, vocab)
	if laneKey == "" {
		return []boardLane{{Count: len(tickets), Columns: fill(tickets, groupKey, labels)}}
	}
	byLane := map[string][]ticketSummary{}
	var order []string
	for _, want := range laneValues(tickets, laneKey, vocab) {
		byLane[want] = nil
		order = append(order, want)
	}
	for _, t := range tickets {
		v := strings.TrimSpace(fieldOf(t, laneKey))
		if v == "" {
			v = unsetLane
		}
		byLane[v] = append(byLane[v], t)
	}
	out := make([]boardLane, 0, len(order))
	for _, lane := range order {
		ts := byLane[lane]
		// A lane nothing is in is noise, not an affordance: cards move
		// between COLUMNS, so an empty lane can never be a drop target.
		if len(ts) == 0 {
			continue
		}
		out = append(out, boardLane{Label: lane, Count: len(ts),
			Columns: fill(ts, groupKey, labels)})
	}
	return out
}

// laneValues orders the lane labels: vocabulary order for words the
// tracker's vocabulary knows, then the rest by size, unset last.
func laneValues(tickets []ticketSummary, key string, vocabAll map[string][]string) []string {
	vocab := vocabAll[key]
	rank, count := map[string]int{}, map[string]int{}
	label := map[string]string{}
	for i, w := range vocab {
		rank[strings.ToLower(w)] = i
	}
	for _, t := range tickets {
		v := strings.TrimSpace(fieldOf(t, key))
		if v == "" {
			v = unsetLane
		}
		k := strings.ToLower(v)
		count[k]++
		if label[k] == "" || v < label[k] {
			label[k] = v
		}
	}
	keys := make([]string, 0, len(count))
	for k := range count {
		keys = append(keys, k)
	}
	sort.Slice(keys, func(i, j int) bool {
		ui, uj := keys[i] == unsetLane, keys[j] == unsetLane
		if ui != uj {
			return uj
		}
		ri, ok1 := rank[keys[i]]
		rj, ok2 := rank[keys[j]]
		if ok1 != ok2 {
			return ok1
		}
		if ok1 && ri != rj {
			return ri < rj
		}
		if count[keys[i]] != count[keys[j]] {
			return count[keys[i]] > count[keys[j]]
		}
		return keys[i] < keys[j]
	})
	out := make([]string, len(keys))
	for i, k := range keys {
		out[i] = label[k]
	}
	return out
}

// columnLabels is the column set, in the order the board draws it.
//
// Grouping is case-folded because a tracker's vocabulary drifts: quarry's
// own store holds both "Open" and "open", which ungrouped would draw two
// columns where there is one. The label shown is the spelling that
// appears most often, so the board reads the way the tracker writes —
// except for a column that is empty, which can only be spelled the way
// the vocabulary spells it.
func columnLabels(tickets []ticketSummary, key string, vocabAll map[string][]string) []string {
	vocab := vocabAll[key]
	spellings := map[string]map[string]int{}
	rank, count := map[string]int{}, map[string]int{}
	add := func(v string) map[string]int {
		k := strings.ToLower(strings.TrimSpace(v))
		if spellings[k] == nil {
			spellings[k] = map[string]int{}
			rank[k] = len(vocab)
		}
		return spellings[k]
	}
	for i, w := range vocab {
		add(w)[w]++
		rank[strings.ToLower(w)] = i
	}
	for _, t := range tickets {
		v := strings.TrimSpace(fieldOf(t, key))
		if v == "" {
			v = unsetLane
		}
		add(v)[v]++
		count[strings.ToLower(v)]++
	}
	keys := make([]string, 0, len(spellings))
	for k := range spellings {
		keys = append(keys, k)
	}
	sort.Slice(keys, func(i, j int) bool {
		ui, uj := keys[i] == unsetLane, keys[j] == unsetLane
		if ui != uj {
			return uj
		}
		if rank[keys[i]] != rank[keys[j]] {
			return rank[keys[i]] < rank[keys[j]]
		}
		if count[keys[i]] != count[keys[j]] {
			return count[keys[i]] > count[keys[j]]
		}
		return keys[i] < keys[j]
	})
	out := make([]string, len(keys))
	for i, k := range keys {
		best := -1
		for spelling, n := range spellings[k] {
			if n > best || (n == best && spelling < out[i]) {
				out[i], best = spelling, n
			}
		}
	}
	return out
}

// fill drops tickets into a fixed column set.
func fill(tickets []ticketSummary, key string, labels []string) []boardColumn {
	at := map[string]int{}
	cols := make([]boardColumn, len(labels))
	for i, l := range labels {
		cols[i] = boardColumn{Status: l}
		at[strings.ToLower(strings.TrimSpace(l))] = i
	}
	for _, t := range tickets {
		v := strings.TrimSpace(fieldOf(t, key))
		if v == "" {
			v = unsetLane
		}
		if i, ok := at[strings.ToLower(v)]; ok {
			cols[i].Tickets = append(cols[i].Tickets, t)
		}
	}
	return cols
}

// statusClass sorts a ticket status into resolved or not. Fossil's
// status vocabulary is per-repository — a ticket schema can define any
// words it likes — so this recognizes the conventional resolved words
// and treats everything else as open. Getting it wrong tints a badge;
// it never hides a ticket.
func statusClass(status string) string {
	switch strings.ToLower(strings.TrimSpace(status)) {
	case "closed", "fixed", "verified", "resolved", "deferred", "rejected", "duplicate":
		return "st-done"
	}
	return "st-open"
}

// tagStrip removes markup from a title used as a LABEL.
//
// Fossil technote and forum titles carry HTML — "<b>Design Note:</b>
// About the Irreversible Schema Change" is a real one. Escaping it is
// correct and safe, but it then reads as literal markup in a list. This
// strips the tags and the caller still escapes the result, so nothing
// is rendered as HTML: safe and readable rather than safe and ugly.
var tagRE = regexp.MustCompile(`<[^>]{0,200}>`)

// firstLine is a commit message's subject: everything before the first
// newline. A feed row is one line, and rendering the whole message
// there turns a list into a wall.
func firstLine(s string) string {
	first, _, _ := strings.Cut(strings.TrimSpace(s), "\n")
	return plainTitle(first)
}

// clip shortens s to at most n characters, breaking on a word boundary
// and marking the cut.
//
// A landing's title is the first line of the message its author wrote,
// and authors write long first lines — one in this forge runs to 96
// characters. That is fine on the landing's own page, where the title
// IS the page; on a timeline row it is a decoration, and a decoration
// that wraps to three lines has stopped decorating the row and started
// competing with it.
// unmarkTitle strips the inline markup a heading cannot render. The
// record's title is a fossil H card — plain text by definition, drawn
// in an h1 — but the message it was cut from was written as Markdown,
// so an author's *emphasis* arrives as literal asterisks and reads as
// a rendering bug. The marks come off for the heading only; the body
// below renders the same text properly, emphasis and all.
//
// Asterisks and backticks only. Underscores are NOT stripped: _x_ in
// prose and my_file_name in a path are the same three characters, and
// mangling every identifier in a title to italicise a rare one is the
// worse trade.
var (
	titleBold = regexp.MustCompile(`\*\*([^*]+)\*\*`)
	titleEm   = regexp.MustCompile(`\*([^*\s][^*]*)\*`)
	titleCode = regexp.MustCompile("`([^`]+)`")
)

func unmarkTitle(s string) string {
	s = titleBold.ReplaceAllString(s, "$1")
	s = titleEm.ReplaceAllString(s, "$1")
	return titleCode.ReplaceAllString(s, "$1")
}

func clip(n int, s string) string {
	if n <= 0 || len(s) <= n {
		return s
	}
	cut := s[:n]
	// Prefer the last space, unless that throws away most of the room.
	if i := strings.LastIndex(cut, " "); i > n/2 {
		cut = cut[:i]
	}
	return strings.TrimRight(cut, " ,.;:—-") + "…"
}

// clock is the HH:MM of an index timestamp, or empty if there is none.
// A day's worth of edits all render the same date; the time is what
// separates them.
func clock(ts string) string {
	_, t, ok := strings.Cut(ts, "T")
	if !ok || len(t) < 5 {
		return ""
	}
	return t[:5]
}

// chatDay names the calendar day a chat message belongs to. It is the
// separator's LABEL and its key at once: the string is unique per day,
// so the log compares one against the last to decide where a line goes,
// and there is no second format to drift away from the first.
func chatDay(at string) string {
	t, ok := parseArtifactTime(at)
	if !ok {
		return ""
	}
	return t.UTC().Format("Mon 2 Jan 2006")
}

// dtLocal is an index timestamp as a <input type="datetime-local">
// value: YYYY-MM-DDTHH:MM, which is the only shape the control accepts.
// Seconds and fractions are dropped rather than rejected, because a
// stored E card carries them and the field would otherwise come up
// empty on every edit.
func dtLocal(ts string) string {
	if len(ts) < 16 {
		return ""
	}
	return ts[:16]
}

func plainTitle(s string) string {
	return strings.TrimSpace(tagRE.ReplaceAllString(s, ""))
}

// initials is an avatar without an avatar store. quarry keeps no images
// for people and fetching a gravatar would send every reader's identity
// to a third party on every page, so the account button shows one or two
// letters from the name it already has.
func initials(name string) string {
	fields := strings.FieldsFunc(name, func(r rune) bool {
		return r == ' ' || r == '.' || r == '-' || r == '_' || r == '@'
	})
	switch len(fields) {
	case 0:
		return "?"
	case 1:
		r := []rune(fields[0])
		if len(r) == 1 {
			return strings.ToUpper(string(r))
		}
		return strings.ToUpper(string(r[:2]))
	default:
		return strings.ToUpper(string([]rune(fields[0])[:1]) + string([]rune(fields[1])[:1]))
	}
}

// tipcol is one icon column header. Deliberately NOT a popover: the
// Popover API is click-driven, so using it as a tooltip meant a click
// target that also carried a native title, giving two competing
// tooltips and a question-mark cursor. There is no standard hover
// tooltip primitive — popover="hint" is Chrome-only — so this does the
// thing that needs no primitive: the label is VISIBLE wherever the
// table has room for it, and the icon carries the native title where it
// does not. Nothing is hidden behind a hover a touch reader cannot do.
func tipcol(icon, label string) template.HTML {
	return template.HTML(fmt.Sprintf(
		`<th scope="col" class="n"><span class="colhead" data-tip="%s">`+
			`<svg class="ic" aria-hidden="true"><use href="#i-%s"/></svg>`+
			`<span class="collabel">%s</span></span></th>`,
		label, icon, template.HTMLEscapeString(label)))
}

// countTag renders a count compactly with its exact value in a title,
// so a column's width comes from its shape rather than its largest
// repository.
func countTag(n int) template.HTML {
	if n == 0 {
		return ""
	}
	return template.HTML(fmt.Sprintf(`<span title="%d">%s</span>`, n, compactCount(n)))
}

// compactCount bounds a count to four characters: 0, 19, 503, 1.1K,
// 26K, 1.2M.
//
// The nav's width was a function of its numbers, so a repository with
// 25,557 check-ins and 5,809 tickets rendered a visibly different nav
// from one with none — on a phone it wrapped to three lines. Exact
// figures belong on the page the tab leads to; the tab needs an order of
// magnitude.
// thousands renders 54108 as 54,108 — a position in a diff wants the
// exact number, not the compact one the counts use.
// changeStat is the "+N -N" a reader scans to size a change before
// opening it. Empty when nothing changed on either side, so a
// pure-rename or a mode-only change does not print a meaningless "+0
// -0". Tabular numerals keep the pairs in a file list from jittering.
func changeStat(added, deleted int) template.HTML {
	if added == 0 && deleted == 0 {
		return ""
	}
	var b strings.Builder
	b.WriteString(`<span class="ci-stat">`)
	if added > 0 {
		b.WriteString(`<span class="ci-add">+` + thousands(added) + `</span>`)
	}
	if added > 0 && deleted > 0 {
		b.WriteString(" ")
	}
	if deleted > 0 {
		b.WriteString(`<span class="ci-del">&minus;` + thousands(deleted) + `</span>`)
	}
	b.WriteString(`</span>`)
	return template.HTML(b.String())
}

func thousands(n int) string {
	s := strconv.Itoa(n)
	if len(s) <= 3 {
		return s
	}
	var b strings.Builder
	for i, c := range s {
		if i > 0 && (len(s)-i)%3 == 0 {
			b.WriteByte(',')
		}
		b.WriteRune(c)
	}
	return b.String()
}

// dur renders an interval in the unit it was meant in: 3600 is "1h",
// 86400 is "24h", 90 is "90s".
func dur(seconds int) string {
	switch {
	case seconds%86400 == 0 && seconds >= 86400*2:
		return strconv.Itoa(seconds/86400) + "d"
	case seconds%3600 == 0 && seconds >= 3600:
		return strconv.Itoa(seconds/3600) + "h"
	case seconds%60 == 0 && seconds >= 60:
		return strconv.Itoa(seconds/60) + "m"
	}
	return strconv.Itoa(seconds) + "s"
}

// hostOf is the host of a URL, for a table that has no room for more.
func hostOf(u string) string {
	if p, err := url.Parse(u); err == nil && p.Host != "" {
		return p.Host
	}
	return u
}

func compactCount(n int) string {
	switch {
	case n < 0:
		return "0"
	case n < 1000:
		return strconv.Itoa(n)
	case n < 10000:
		// One decimal only where it distinguishes: 1.1K reads, 26.4K is
		// a character longer for precision nobody is using here.
		v := float64(n) / 1000
		out := strconv.FormatFloat(v, 'f', 1, 64)
		return strings.TrimSuffix(out, ".0") + "K"
	case n < 1000000:
		return strconv.Itoa(n/1000) + "K"
	case n < 10000000:
		v := float64(n) / 1000000
		out := strconv.FormatFloat(v, 'f', 1, 64)
		return strings.TrimSuffix(out, ".0") + "M"
	default:
		return strconv.Itoa(n/1000000) + "M"
	}
}

// navlink renders one repository-nav entry. It is a function rather
// than inline template markup because an entry carries two independent
// classes — "here" and "empty" — and expressing that inline produced
// two class attributes on the same anchor, of which a browser honours
// only the first.
//
// count is `any` so a section with nothing to count (files, ci, chat)
// can pass false and get no badge, rather than a misleading zero.
func navlink(repo, section, label, current string, hasCounts bool, count any, aux ...int) template.HTML {
	var class []string
	if section == current {
		class = append(class, "here")
	}
	// aux is a fold TIER: tier-1 tabs fold into the "…" menu first as
	// the bar narrows, tier-3 last; untiered tabs never fold. Graduated
	// rather than all-at-once, so a landscape phone keeps six tabs and
	// hides two instead of losing five to a single breakpoint.
	if len(aux) > 0 && aux[0] > 0 && aux[0] < 9 {
		class = append(class, fmt.Sprintf("aux%d", aux[0]))
	}
	// Tier 9 never folds by width, but YIELDS its place when a drawer
	// tab surfaces as the active section on the narrowest rows.
	if len(aux) > 0 && aux[0] == 9 {
		class = append(class, "yield")
	}
	n, counted := count.(int)
	if hasCounts && counted && n == 0 {
		// Dimmed, never hidden: a nav whose SHAPE changes per repository
		// makes a reader relearn it on every store. An honest dead end
		// costs one click; a moving nav costs orientation.
		class = append(class, "empty")
	}
	var b strings.Builder
	fmt.Fprintf(&b, `<a href="/r/%s/%s"`, url.PathEscape(repo), section)
	if len(class) > 0 {
		fmt.Fprintf(&b, ` class="%s"`, strings.Join(class, " "))
	}
	if section == current {
		b.WriteString(` aria-current="page"`)
	}
	fmt.Fprintf(&b, `>%s`, template.HTMLEscapeString(label))
	if section == current {
		// The underline is its own element so the view transition can
		// morph IT alone: naming the whole tab morphed the text, and
		// two different-sized labels scale-zoomed into each other. Two
		// 2px bars morph as a clean sideways slide.
		b.WriteString(`<span class="ink" aria-hidden="true"></span>`)
	}
	if hasCounts && counted {
		// title carries the exact figure; the badge carries the shape.
		fmt.Fprintf(&b, ` <span class="n" title="%d">%s</span>`, n, compactCount(n))
	}
	b.WriteString(`</a>`)
	// Every part is escaped or generated above; section and label are
	// compile-time constants from the template.
	return template.HTML(b.String())
}

// paletteCSS is every colour the site uses, in one place so the
// contrast tests can find them all. A colour defined anywhere else
// escapes those tests, which is how the highlight and the danger red
// came to be wrong in one of the three theme states.
const paletteCSS = `/* Gruvbox, after craftdesign.group: a warm cream rather than white and a
   soft near-black rather than pure black, because a forge is read for
   long stretches and maximum contrast is tiring rather than legible.
   --accent carries links and focus. Every pair here is contrast-checked
   against both the page ground and --code-bg, the secondary surface
   links also sit on; see TestPaletteContrast, which fails the build
   rather than letting a nicer-looking colour quietly drop below AA.

   Three states, not two. An explicit choice stamps data-theme on the
   root; the default "system" stamps nothing, so only the media query
   separates light from dark. Each set is therefore declared three times:
   once bare, once under the media query GUARDED against an explicit
   light choice, and once under the explicit dark choice — otherwise
   picking light on a dark-mode phone would do nothing. */
:root {
  --fg: #282828; --bg: #f3ecda; --muted: #665c54; --code-bg: #e6dcc0;
  --rule: #d5c4a1; --accent: #a04412; --uname-l: 32%;
  --mark: #f7dd9a; --add: #116329; --del: #a40e26;
  --add-row: #dafbe1; --del-row: #ffebe9; --add-mark: #aceebb; --del-mark: #ffcecb;
  /* --surface is the neutral wash under cards and the top bar. It is a
     warm grey at 10% alpha rather than a colour per theme: one value,
     and it tints whatever ground it lands on instead of fighting it.
     --code-bg stays opaque, because code needs a solid block. */
  --surface: #a899841a;
  /* What the browser paints the parts of a control it draws itself:
     the datetime picker's calendar glyph, spinners, scrollbars. Absent,
     every one of them is drawn for a light page, and on the dark ground
     the calendar icon is near-black on near-black. */
  color-scheme: light;
}
@media (prefers-color-scheme: dark) {
  :root:not([data-theme="light"]) {
    --fg: #f0ece4; --bg: #1d2021; --muted: #bdb6ab; --code-bg: #32302f;
    --rule: #504945; --accent: #d99058; --uname-l: 70%;
    color-scheme: dark;
  --mark: #665418; --add: #56d364; --del: #ff7b72;
  --add-row: #203326; --del-row: #3e2727; --add-mark: #22492c; --del-mark: #5f2f2d;
  --surface: #a899841a;
    --mark: #665418; --add: #56d364; --del: #ff7b72;
  --add-row: #203326; --del-row: #3e2727; --add-mark: #22492c; --del-mark: #5f2f2d;
    --surface: #a899841a;
  }
}
:root[data-theme="dark"] {
  --fg: #f0ece4; --bg: #1d2021; --muted: #bdb6ab; --code-bg: #32302f;
  --rule: #504945; --accent: #d99058; --uname-l: 70%;
  color-scheme: dark;
}
/* An explicit LIGHT choice has to beat a dark OS, native controls
   included — the media block above already lost that fight on tokens
   via :root:not([data-theme="light"]), and this is its other half. */
:root[data-theme="light"] { color-scheme: light; }
/* The page paints its own ground: a transparent body borrows whatever
   the browser decided, which is the white flash this palette exists to
   avoid. */
html { background: var(--bg); }
/* The rubber-band area past the top of the page painted --bg while the
   bar above it is --surface, so overscrolling showed a stripe of the
   wrong colour behind the header. Refusing the scroll chain is the
   direct fix and does not require painting html a colour that would
   then be wrong at the other end. */
html, body { overscroll-behavior: none; }
/* iOS Safari "text autosizing" inflates text inside wide scrollable
   blocks — code in a phone-width pre rendered LARGER than the prose
   around it. 100% keeps every font at its declared size; this is the
   documented opt-out, not a workaround. */
html { -webkit-text-size-adjust: 100%; text-size-adjust: 100%; }`

var base = template.Must(template.New("base").Funcs(template.FuncMap{
	"chatMsgHTML": chatMsgHTML,
	// ciState folds the engine's status vocabulary to the three words a
	// chip can hold (RFC 0009): pass, fail, running.
	"ciState": func(status string) string {
		switch status {
		case "completed", "succeeded", "success":
			return "pass"
		case "failed", "error":
			return "fail"
		case "cancelled", "canceled":
			return "cancelled"
		}
		return "running"
	},
	"ciStates":  func() []string { return []string{"pass", "fail", "running", "cancelled"} },
	"pathesc":   url.PathEscape,
	"splitrows": splitRows,
	"plural": func(n int, one, many string) string {
		if n == 1 {
			return one
		}
		return many
	},
	"navlink": navlink,
	// syncurl is the one definition of "swap the body and correct the
	// address bar". See syncURLAttr for why it is a Go helper and not
	// literal text in each template.
	"syncurl": syncURLAttr,
	"ago":     ago,
	// agoTime is ago for a real time.Time. The event log's timestamps
	// come from JetStream metadata, not from an artifact's date card, so
	// they never went through a string in the first place.
	"agoTime": func(t time.Time) template.HTML {
		if t.IsZero() {
			return ""
		}
		return ago(t.UTC().Format("2006-01-02T15:04:05.000"))
	},
	"weekday":   weekday,
	"identicon": identicon,
	// chatrefs draws the window-bounded "chat" row an artifact page
	// shows beside its durable mentions.
	"chatrefs": chatRefsHTML,
	// who renders a person as ONE link: their mark and their name,
	// pointing at everything they have done here. Fossil routes every
	// surface through one helper (hyperlink_to_user) for the same
	// reason — thirty-two places rendering a name is thirty-two places
	// to disagree about whether it is clickable.
	//
	// y=all because "what did they do" includes their wiki edits and
	// ticket changes, not just their check-ins; fossil pairs u= with
	// y=a for exactly that.
	"who": func(repo, user string) template.HTML {
		if user == "" {
			return ""
		}
		return template.HTML(`<a class="who" href="/r/` + template.HTMLEscapeString(repo) +
			`/timeline?user=` + url.QueryEscape(user) + `&amp;y=all" title="everything by ` +
			template.HTMLEscapeString(user) + `">` + string(identicon(user)) + ` ` +
			template.HTMLEscapeString(user) + `</a>`)
	},
	"spark":    sparkSVG,
	"userhue":  userHue,
	"spectrum": spectrumSVG,
	"votectx": func(repo, root, hash string, score, yourVote int) voteCtx {
		return voteCtx{Repo: repo, Root: root, Hash: hash, Score: score, YourVote: yourVote}
	},
	"composerctx": func(repo string, rows int, placeholder string) composerCtx {
		return composerCtx{Repo: repo, Rows: rows, Placeholder: placeholder}
	},
	"composerfocus": func(repo string, rows int, placeholder string, focus bool) composerCtx {
		return composerCtx{Repo: repo, Rows: rows, Placeholder: placeholder, Autofocus: focus}
	},
	"descctx": func(repo string, rows int, value string) composerCtx {
		return composerCtx{Repo: repo, Rows: rows, Placeholder: "Describe the ticket (Markdown)", Name: "description", Value: value}
	},
	"landingctx": func(repo string, rows int, placeholder string) composerCtx {
		// A landing's remark is optional: a reject or an accept may be
		// the whole statement, and demanding prose to settle a record
		// would make the decision harder than the discussion.
		return composerCtx{Repo: repo, Rows: rows, Placeholder: placeholder,
			Name: "message", Optional: true}
	},
	"remarkctx": func(repo string, rows int, placeholder string) composerCtx {
		return composerCtx{Repo: repo, Rows: rows, Placeholder: placeholder, Name: "comment", Optional: true}
	},
	"clock":   clock,
	"chatday": chatDay,
	// pctOf is a width for the phase bar, clamped so a miscount can
	// never draw outside its track.
	"pctOf": func(n, total int) int {
		if total <= 0 {
			return 0
		}
		p := n * 100 / total
		if p < 0 {
			return 0
		}
		if p > 100 {
			return 100
		}
		return p
	},
	"dtlocal":     dtLocal,
	"agoShort":    agoShort,
	"plain":       plainTitle,
	"firstline":   firstLine,
	"unmark":      unmarkTitle,
	"statusClass": statusClass,
	"initials":    initials,
	"tipcol":      tipcol,
	"count":       countTag,
	"kindLabel":   kindLabel,
	"thousands":   thousands,
	"fieldOf":     fieldOf,
	"unsetLane":   func() string { return unsetLane },
	"dur":         dur,
	"hostOf":      hostOf,
	"add":         func(a, b int) int { return a + b },
	"signClass": func(s string) string {
		switch s {
		case "+":
			return "add"
		case "-":
			return "del"
		default:
			return "prop"
		}
	},
	"signWord": func(s string) string {
		switch s {
		case "+":
			return "set"
		case "-":
			return "cancelled"
		default:
			return "propagates to descendants"
		}
	},
	"filestat": func(f diff.FileDiff) template.HTML { return changeStat(f.Added, f.Deleted) },
	"diffstat": func(fs []diff.FileDiff) template.HTML {
		var added, deleted int
		for _, f := range fs {
			added += f.Added
			deleted += f.Deleted
		}
		return changeStat(added, deleted)
	},
	"commentFirst": func(s string) string {
		first, _, _ := strings.Cut(strings.TrimSpace(s), "\n")
		return commentText(first)
	},
	"sub":  func(a, b int) int { return a - b },
	"clip": clip,
	// rest names the time a render spent OUTSIDE a measured category,
	// so a reader does not have to do the subtraction in their head to
	// find the part nothing timed. Clamped at zero: the two numbers are
	// sampled separately and a negative remainder would read as a bug
	// in the thing being measured rather than in the measurement.
	"rest": func(total, part int64) int64 {
		if total < part {
			return 0
		}
		return total - part
	},
	"docIcon": func(label string) string {
		switch strings.ToLower(label) {
		case "readme":
			return "i-book"
		case "license", "copying":
			return "i-law"
		case "security":
			return "i-shield"
		case "contributing":
			return "i-people"
		}
		return "i-file"
	},
	"docRowLabel": func(label, license string) string {
		if strings.EqualFold(label, "license") && license != "" {
			return license + " license"
		}
		return label
	},
	"scopes": func() any { return searchScopes },
}).Parse(baseHTML))

var baseHTML = `<!doctype html>
<html lang="en"{{if .Theme}} data-theme="{{.Theme}}"{{end}}>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
{{- /* This page's own address, stated rather than inferred.

       A page reached with credentials in the URL (http://user:pw@host/,
       which is how a LAN deployment behind basic auth gets opened)
       keeps them in document.baseURI — location is cleaned, the base is
       not — and fetch() REFUSES any URL carrying credentials. Every
       enhancement on the site failed there at once: the diff toggle,
       the unread poll, the diff sentinel, while the page itself looked
       perfectly fine.

       The server knows this URL from its own routing and never from
       userinfo, so writing it down is enough; no script, and it holds
       with scripting off. It is the PAGE's URL and not the bare origin
       on purpose — a relative link like ?view=split has to keep
       resolving against the current path, and a base of "/" would have
       quietly sent every one of them to the site root.

       The href is marked volatile for the same reason og:url is: it
       carries the port, and the disposability harness compares two
       servers that cannot share one. */ -}}
<base href="{{.Origin}}{{.Path}}" data-volatile="href">
{{- /* "quarry — quarry" was what the aggregate page called itself. */ -}}
<title{{with .AttnTitleAttr}} {{.}}{{end}}>{{.Title}}{{if ne .Title "quarry"}} — quarry{{end}}</title>
<link rel="icon" href="/favicon.ico" sizes="any">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
{{- /* The mark at 512px, absolute because a scraper fetches it from its
       own machine. summary, not summary_large_image: the Q is a square
       logo, and the wide card would letterbox it into a thin band. */ -}}
<meta property="og:site_name" content="quarry">
<meta property="og:type" content="website">
{{- /* "timeline" alone names no repository; a shared link has to say
       which one. The repo landing page titles itself with the repo,
       which would otherwise read "sqlite — sqlite". */ -}}
<meta property="og:title" content="{{if and .Repo (ne .Repo .Title)}}{{.Repo}} — {{end}}{{.Title}}">
<meta property="og:url" content="{{.Origin}}{{.Path}}" data-volatile="content">
{{if .OGDesc}}<meta property="og:description" content="{{.OGDesc}}">{{end}}
<meta property="og:image" content="{{.Origin}}/assets/quarry.png" data-volatile="content">
<meta property="og:image:width" content="512">
<meta property="og:image:height" content="512">
<meta property="og:image:alt" content="quarry">
<meta name="twitter:card" content="summary">
<style>
` + paletteCSS + `
body { color: var(--fg); background: var(--bg); font: 16px/1.5 system-ui, sans-serif;
       margin: 0; padding: 0; }
/* The bars span the viewport; their contents, and the page below them,
   share one column. --page is the single place that column's width is
   decided. */
:root { --page: 76rem; }
/* The measure the newer surfaces are drawn on: one spacing scale, one
   radius scale, one shadow, one transition. Written once here so that
   "a bit tighter" is an edit to a number rather than a sweep through
   forty rules, and so two surfaces cannot disagree about what "the
   small gap" is. No colour lives here — colour is the palette's. */
:root {
  --sp-1: 4px; --sp-2: 8px; --sp-3: 12px; --sp-4: 16px; --sp-5: 24px; --sp-6: 32px;
  --r-1: 4px; --r-2: 8px; --r-3: 12px; --r-4: 999px;
  /* The in-between radius the rows and their toolbar share: smaller
     than a card, larger than a code span. */
  --r-row: 6px;
  --shadow-1: 0 2px 8px rgba(0, 0, 0, 0.2);
  --t-fast: 150ms;
}
main { max-width: var(--page); margin: 0 auto; padding-left: 1rem; padding-right: 1rem; }
/* Room for the fixed footer, so the last line of a page is readable. */
/* One source for the footer's height, so the space reserved for it and
   the bar itself cannot disagree. The gap is deliberate: clearing the
   footer by a hair still reads as content running into it. */
:root { --footer-h: 2.25rem; }
body { padding-bottom: calc(var(--footer-h) + 2rem + env(safe-area-inset-bottom)); }
/* Centred rather than baseline-aligned, so the two halves sit on one
   optical line inside a bar of fixed height. */
footer { font-size: 0.78rem; }
/* One line, never two: the page reserves a fixed height for this bar, so
   a bar that wraps overlaps the content it was supposed to sit below.
   The left half truncates instead — version and render time are
   diagnostics, and they are what a narrow screen can best afford to
   lose. The links never shrink. */
footer .bar { display: flex; flex-wrap: nowrap; gap: 1rem; align-items: center;
  min-height: var(--footer-h); padding-top: 0.2rem; padding-bottom: 0.2rem; }
.foot-l { min-width: 0; display: flex; white-space: nowrap; }
/* The timing never shrinks and never truncates; the two ahead of it do,
   and drop out entirely when even truncated they would crowd it.
   The per-store BREAKDOWN is not in that protected set. On a phone the
   whole string outruns the viewport on its own, and being flex:none it
   then printed straight over the links rather than giving way — so the
   detail drops at the same width the brand does, and the total, which
   is what the footer is for, survives. */
.f-time { flex: none; }
.f-brand, .f-ver { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
@media (max-width: 34rem) { .f-brand, .f-ops { display: none; } }
@media (max-width: 26rem) { .f-ver { display: none; } }
.foot-r { flex: none; }
.foot-r { margin-left: auto; display: flex; gap: 0.9rem; white-space: nowrap; }
details > summary { cursor: pointer; padding: 0.4rem 0; }
pre.licence { max-height: 24rem; overflow: auto; font-size: 0.8rem; white-space: pre-wrap; }
/* The bars use the viewport, not the content column: forgejo puts the
   forge name at the far left and the account at the far right, which
   reads as chrome. Content stays in the column below them. */
.bar { padding-left: 1rem; padding-right: 1rem; }
.repobar .bar { max-width: var(--page); margin: 0 auto; }
main { padding-top: 1rem; }
/* Present to the document and to a screen reader, absent to the eye:
   a page still needs one h1 even when repeating it on screen would say
   nothing a reader cannot already see. */
/* Explore tabs: the same pill vocabulary as the repo nav, so the two
   navigations do not look like different systems. */
nav.tabs { display: flex; flex-wrap: wrap; gap: 0.3rem; margin: 0 0 1rem; }
nav.tabs a { display: inline-flex; align-items: center; gap: 0.35rem;
  padding: 0.3rem 0.7rem; border-radius: 999px; text-decoration: none;
  border: 1px solid transparent; color: var(--fg); }
nav.tabs a:hover { border-color: var(--rule); }
nav.tabs a.here { background: var(--surface); border-color: var(--rule); font-weight: 600; }
nav.tabs .n { color: var(--muted); font-size: 0.75rem; font-variant-numeric: tabular-nums; }
ul.people { list-style: none; margin: 0; padding: 0; }
ul.people li { display: flex; align-items: center; gap: 0.6rem;
  padding: 0.5rem 0; border-bottom: 1px solid var(--code-bg); }
.avatar.sm { width: 1.75rem; height: 1.75rem; font-size: 0.65rem; margin: 0; flex: none; }
.p-main { min-width: 0; }
.p-meta { color: var(--muted); font-size: 0.85rem; }
.person-head { display: flex; align-items: center; gap: 0.9rem; margin-bottom: 1rem; }
.person-head h1 { margin: 0; }
.avatar.lg { width: 3rem; height: 3rem; font-size: 1rem; margin: 0; flex: none; }
/* Headings SCALE. The browser default is 2em at every width, which on a
   phone turns a real subject line into three lines of shouting and made
   clipping look necessary — it was not: the clip only hid the words. A
   heading that fits can say the whole thing, and the pathological case
   (a message with no subject line at all, where the title IS the body)
   is already handled by dropping the visible heading entirely. */
h1 { font-size: clamp(1.35rem, 5vw, 2rem); line-height: 1.2;
  overflow-wrap: break-word; }
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
  overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; }
.topbar { background: var(--surface); border-bottom: 1px solid var(--rule); }
/* Three columns rather than a flex row: the search belongs in the
   middle of the bar, and centring it with auto margins fights the
   avatar's own push to the right. The side columns take equal width so
   the box is centred on the VIEWPORT, not on whatever is left after the
   forge name — which would move it every time the name changed. */
.topbar .bar { display: grid; grid-template-columns: 1fr minmax(7rem, 34rem) 1fr;
  gap: 0.75rem; align-items: center; padding-top: 0.75rem; padding-bottom: 0.75rem; }
.topbar .site { justify-self: start; }
.bar-acts { justify-self: end; display: flex; align-items: center; gap: 0.5rem; }
.topbar .find { justify-self: stretch; }
.repobar { border-bottom: 1px solid var(--rule); }
/* One row, always: the collapse exists precisely so the bar never has
   to wrap. The repository name yields (truncating with an ellipsis)
   before the tabs do — the tabs are where the reader is going. */
.repobar .bar { display: flex; gap: 0.75rem; align-items: baseline; flex-wrap: nowrap;
  padding-top: 0.6rem; padding-bottom: 0.4rem; min-width: 0; overflow: clip; }
/* Fixed and full width, like the bar at the top: the page scrolls under
   it. body carries matching bottom padding so the last line of content
   is never hidden behind it. */
footer { position: fixed; bottom: 0; left: 0; right: 0; z-index: 5;
         background: var(--surface); backdrop-filter: blur(6px);
         color: var(--muted); border-top: 1px solid var(--rule); margin: 0;
         /* .bar owns the inner padding. The bottom inset is the iPhone
            home-indicator strip: with Safari's chrome collapsed it
            overlays a bottom:0 bar, and the render time sat under it.
            viewport-fit=cover (the meta tag) is what makes the env()
            non-zero there; everywhere else it is 0 and inert. */
         padding: 0 0 env(safe-area-inset-bottom) 0; }
table { border-collapse: collapse; width: 100%; }
th, td { text-align: left; padding: 0.35rem 0.75rem 0.35rem 0; vertical-align: top; }
/* An action cell is a row of buttons, not a stack of forms. */
td.acts { display: flex; gap: 0.4rem; align-items: center; padding-top: 0.25rem; }
td.acts form { display: contents; }
/* A link dressed as the buttons beside it, for actions that are a
   page (edit) rather than a post. */
td.acts a.btn { display: inline-block; background: var(--code-bg); font-weight: 600; font: inherit; font-weight: 600;
  color: var(--fg); text-decoration: none; border: 1px solid var(--rule); border-radius: 6px;
  padding: 0.3rem 0.6rem; line-height: 1.2; }
td.acts a.btn:hover { border-color: var(--fg); }
td.acts button, td.acts a.btn { white-space: nowrap; }
/* The mirrors table: host-only upstream, one-line truncated error, and
   a kebab disclosure for the actions that are not "pull". */
.m-up a { text-decoration: none; }
.m-state .m-err { display: block; max-width: 22rem; overflow: hidden; text-overflow: ellipsis;
  white-space: nowrap; color: var(--muted); }
tr.m-failing .m-state strong { color: var(--accent); }
.kebab-btn { font-weight: 700; line-height: 1.2; padding: 0.3rem 0.55rem; }
/* Without anchor positioning the row menu falls back to the account
   menu's corner; with it, it hangs off its own button. */
@supports (anchor-name: --a) {
  .menu.km { top: anchor(bottom); right: anchor(right); margin-top: 0.3rem; }
}
form.confirm { margin-top: 1rem; }
/* The rows list: GitHub's list-row shape. Wide, a row is a grid of
   main | actions with the meta line under the name; narrow, the same
   row stacks and the actions drop beneath. Problems get a left rule
   in the failure colour so they read before they are read. */
.fleet-head { display: flex; flex-wrap: wrap; align-items: center; gap: 0.6rem 1rem; margin: 0.2rem 0 0.8rem; }
.fleet-sum { margin: 0; flex: 1 1 14rem; }
.fleet-bulk { display: flex; gap: 0.4rem; }
.ci-fail-text { color: var(--accent); }
ul.rows { list-style: none; margin: 0 0 1rem; padding: 0; border-top: 1px solid var(--rule); }
ul.rows > li.row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 0.3rem 1rem;
  align-items: start; padding: 0.6rem 0.2rem; border-bottom: 1px solid var(--rule); }
ul.rows > li.row-problem { border-left: 3px solid var(--accent); padding-left: 0.6rem; }
.row-main { min-width: 0; display: flex; flex-wrap: wrap; align-items: center; gap: 0.3rem 0.45rem; }
.row-name { font-weight: 600; text-decoration: none; }
.row-meta { flex-basis: 100%; color: var(--muted); font-size: 0.85rem; overflow-wrap: anywhere; }
.row-meta .n { font-variant-numeric: tabular-nums; }
.row-err { flex-basis: 100%; color: var(--muted); font-size: 0.85rem; overflow: hidden;
  text-overflow: ellipsis; white-space: nowrap; }
.row-acts { display: flex; gap: 0.4rem; align-items: center; white-space: nowrap; }
.row-acts form { display: contents; }
.row-acts button, .row-acts a.btn { font-size: 0.85rem; padding: 0.3rem 0.6rem; }
.row-acts a.btn { display: inline-block; background: var(--code-bg); font: inherit; font-size: 0.85rem; font-weight: 600;
  color: var(--fg); text-decoration: none; border: 1px solid var(--rule); border-radius: 6px; line-height: 1.2; }
.tl-badge.m-failing, .tl-badge.ci-fail { border-color: var(--accent); color: var(--accent); }
.tl-badge.m-lagging { color: var(--muted); }
details.rows-fold > summary { cursor: pointer; color: var(--muted); padding: 0.5rem 0.2rem; }
@media (max-width: 40rem) {
  ul.rows > li.row { grid-template-columns: minmax(0, 1fr); }
  .row-acts { justify-content: flex-start; }
  .fleet-bulk { width: 100%; }
  .fleet-bulk form { flex: 1; display: contents; }
  .fleet-bulk button { flex: 1; }
  /* The page must never scroll sideways; a wide table scrolls inside
     its own box. */
  main { overflow-x: clip; }
}
/* A labelled control is a column: label over input. Side-by-side put
   the trailing unit on its own line and made the row unreadable. */
form.addform { display: flex; flex-wrap: wrap; gap: 0.6rem; align-items: end;
  margin-top: 1rem; padding-top: 1rem; border-top: 1px solid var(--rule); }
form.addform label { display: flex; flex-direction: column; gap: 0.2rem;
  font-size: 0.85rem; color: var(--muted); min-width: 0; }
form.addform label.grow { flex: 1 1 16rem; }
form.addform input { color: var(--fg); }
form.rowform { margin: 0.75rem 0 0; }
th { border-bottom: 1px solid var(--rule); }
/* Links carry the accent rather than inheriting the body colour: with
   inherit the only cue was the underline, and a page of prose and a page
   of links looked identical at a glance. */
a { color: var(--accent); }
/* A focus ring says "here you are", not "look at this". The accent made
   every tab stop shout in the brand colour; --muted is neutral and
   still clears WCAG 1.4.11's 3:1 against both grounds (8.2:1 dark,
   5.5:1 light) — where --rule, the obvious "lighter" choice, is 1.9:1
   and would not legally be an indicator at all. */
a:focus-visible, button:focus-visible, input:focus-visible, select:focus-visible,
textarea:focus-visible { outline: 2px solid var(--muted); outline-offset: 1px; }
.topbar .site { font-weight: bold; text-decoration: none; display: inline-flex; align-items: center; }
/* The wordmark: QUARRY set in Iosevka Fixed Semibold, traced to
   outlines so no reader downloads a font for six letters. The Q's tail
   descends below the baseline by design — the viewBox keeps it. The
   phone keeps only the round mark. */
/* The box is CAP HEIGHT only — the Q's tail overflows below it, as in
   the source design, so the mark centres on the letters and the tail
   costs no layout space. */
/* Cap height equals the ring's outer diameter: the mark is 1.75rem
   over a 24-unit box whose ring spans 17.2 units (r 7.2 + half the
   2.8 stroke each side), so 1.75 x 17.2/24. */
.topbar .site .wordmark { height: 1.254rem; width: auto; display: block;
  margin-left: 0.45rem; overflow: visible; align-self: center; }
@media (max-width: 34rem) { .topbar .site .wordmark { display: none; } }
/* Sized in CSS as well as in the attributes: the attributes reserve the
   space before the image arrives (no reflow), the CSS keeps it right if
   the asset is ever replaced at another resolution. */
.topbar .site .mark { width: 1.75rem; height: 1.75rem; display: block; }
/* The repository is the subject of every page under it, so it reads as
   the heading and "quarry" recedes to the crumb it is. Without this the
   two sit at equal weight and the forge name — identical on every page —
   competes with the one word that changes. */
.repobar .repo { font-weight: bold; font-size: 1.15rem; text-decoration: none;
  min-width: 3ch; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* The posture badge: a chip beside the name, GitHub's "forked from"
   shape. failing paints its border, nothing else — the notice below
   the bar carries the words. */
.repobar .posture { display: inline-flex; align-items: center; gap: 0.3rem; flex: none;
  font-size: 0.8rem; color: var(--muted); text-decoration: none; border: 1px solid var(--rule);
  border-radius: 999px; padding: 0.1rem 0.55rem; white-space: nowrap; }
.repobar .posture:hover { color: var(--fg); border-color: var(--muted); }
.repobar .posture-failing { border-color: var(--accent); color: var(--fg); }
.repobar .posture-warn { font-size: 0.85rem; color: var(--muted); padding-top: 0; padding-bottom: 0.4rem; }
/* Narrow: the chip keeps its icon and drops its words — the bar's one
   line belongs to the nav, and the title attribute still says it all. */
@media (max-width: 48rem) { .repobar .posture .words { display: none; }
  .repobar .posture { padding: 0.2rem 0.4rem; } }
/* Explore names the posture in a word, the same chip family as
   "private": a glyph alone read as decoration. */
.fleet .r-name .tl-badge.posture-badge { margin-left: 0.35rem; color: var(--muted); }
/* Search sits with the chrome now rather than under it. It takes the
   leftover width so it is the element that shrinks when the header is
   tight, which is right: a repository's name must stay readable and a
   search box is usable at any width. */
.topbar .find { min-width: 0; margin: 0; }
.topbar .find input { width: 100%; }
/* The avatar is initials, not an image: quarry has no avatar store and
   inventing one to fetch a gravatar would send every reader's identity
   to a third party. */
/* A tooltip for controls that are genuinely icon-only, after Basecoat:
   a ::after carrying content: attr(data-tip), positioned against the
   trigger, no script at all.

   Two deliberate departures from Basecoat. It shows on :focus-visible
   as well as :hover — Basecoat explicitly hides its tooltip for
   keyboard users, which makes an icon-only control unnameable without a
   mouse. And it is anchored where the browser can do it, so an
   overflow:hidden ancestor cannot clip it; the absolute fallback is
   what Basecoat does everywhere.

   What this still cannot do is touch: there is no hover on a phone.
   popover=hint with interestfor handles hover, focus AND long-press
   declaratively, but Safari does not implement it, so it cannot be the
   mechanism. That is why visible labels remain the default everywhere
   there is room, and this is reserved for controls whose meaning is
   also carried by aria-label. */
[data-tip] { position: relative; }
[data-tip]::after {
  content: attr(data-tip);
  position: absolute; z-index: 60; bottom: calc(100% + 0.35rem); left: 50%;
  translate: -50% 0.25rem;
  padding: 0.15rem 0.45rem; border: 1px solid var(--rule); border-radius: 5px;
  background: var(--bg); color: var(--fg);
  font-size: 0.75rem; font-weight: normal; white-space: nowrap;
  opacity: 0; visibility: hidden; pointer-events: none;
  transition: opacity 100ms ease, translate 100ms ease, visibility 100ms;
}
[data-tip]:hover::after {
  opacity: 1; visibility: visible; translate: -50% 0;
}
@media (prefers-reduced-motion: reduce) { [data-tip]::after { transition: none; } }
/* No anchor positioning here, on evidence: the implicit-anchor form
   resolved a column off inside table layout (Chrome, fleet headers),
   and a NAMED anchor on a class of trigger resolves every tip to the
   last trigger on the page. Absolute against the trigger is the only
   arrangement that cannot point at the wrong thing. Its cost is
   clipping under overflow ancestors, which each placement below pays
   deliberately instead of accidentally. */

/* A column header names itself when the table is wide enough to say it,
   and falls back to the icon alone when it is not. The label is real
   text, so it is readable by touch, by a screen reader and by anyone
   who does not know the glyph. */
.colhead { display: inline-flex; align-items: center; gap: 0.35rem; justify-content: flex-end; }
/* Narrow: visually hidden, NOT display:none — the label is the header's
   accessible name, and none would silence it for a screen reader. The
   tooltip carries it for sighted pointer users instead. Wide: the label
   is visible, so the tooltip would repeat it and stays off. */
.collabel { position: absolute; width: 1px; height: 1px; overflow: hidden;
  clip-path: inset(50%); white-space: nowrap;
  font-weight: normal; color: var(--muted); font-size: 0.8rem; }
.colhead[data-tip]::after { bottom: auto; top: calc(100% + 0.35rem);
  left: auto; right: 0; translate: 0 -0.25rem; }
.colhead[data-tip]:hover::after { translate: 0 0; }
@media (min-width: 56rem) {
  .collabel { position: static; width: auto; height: auto; overflow: visible;
    clip-path: none; }
  .colhead[data-tip]::after { display: none; }
}
.avatar { flex: none; width: 2.25rem; height: 2.25rem; padding: 0;
  border-radius: 999px; background: var(--bg); border: 1px solid var(--rule);
  font-size: 0.75rem; font-weight: 700; cursor: pointer; display: grid; place-items: center; }
.avatar:hover { border-color: var(--fg); }
/* A BASE size for the mark. Every other .idn rule is scoped to a
   parent, so an identicon used anywhere new inherited no size at all
   and an SVG with no size fills its container — the wiki history page
   rendered one person's mark at the width of the screen. The helper is
   meant to be usable wherever a person is named; that is only true if
   it is safe by default. Scoped rules below are more specific and still
   win. */
.idn { width: 14px; height: 14px; vertical-align: -2px; flex: none; }
.avatar .idn { width: 78%; height: 78%; border-radius: 0; }
button.avatar[popovertarget="acct"] { anchor-name: --avatar; justify-self: end; }
.menu {
  /* One inset declaration, not a shorthand plus overrides: the
     shorthand resets the sides the longhands set, which is how this
     first landed pinned to the top of the viewport. */
  position: fixed; inset: 3.25rem 1rem auto auto; margin: 0;
  min-width: 11rem; padding: 0.4rem; border: 1px solid var(--rule); border-radius: 8px;
  background: var(--bg); color: var(--fg);
  /* display is deliberately NOT set here. The UA stylesheet closes a
     popover with [popover]:not(:popover-open) { display: none }, and an
     author rule beats it — declaring display:flex on the base left the
     menu laid out and hit-testable at opacity 0, an invisible 185x111
     region swallowing clicks on every page whether or not it had ever
     been opened. It is set only in the open state below. */
  flex-direction: column; gap: 0.1rem;
}
/* Anchored to the avatar where the browser can do it, so the menu keeps
   its relationship to the button at any viewport; the fixed corner above
   is the fallback and lands in the same place at these sizes. */
@supports (anchor-name: --a) {
  .menu { position-anchor: --avatar; inset: auto; top: anchor(bottom); right: anchor(right);
    margin-top: 0.4rem; }
}
/* The menu grows out of the button rather than appearing. allow-discrete
   is what lets display participate, so the transition survives the
   popover being display:none between states. */
.menu {
  opacity: 0; transform: translateY(-0.25rem) scale(0.97); transform-origin: top right;
  transition: opacity 120ms ease, transform 120ms ease, overlay 120ms allow-discrete,
              display 120ms allow-discrete;
}
.menu:popover-open { display: flex; opacity: 1; transform: none; }
@starting-style {
  .menu:popover-open { opacity: 0; transform: translateY(-0.25rem) scale(0.97); }
}
@media (prefers-reduced-motion: reduce) { .menu { transition: none; } }
.menu a, .menu button {
  /* border-box, or "width: 100%" means 100% PLUS the padding and every
     row hangs over the menu's right edge — which reads as a clipped,
     scrolling box even when the list is one item long. */
  display: flex; align-items: center; gap: 0.4rem; width: 100%; box-sizing: border-box;
  /* A button's UA font is smaller than the page's; in a menu every
     row must read the same, whatever element it is. */
  font: inherit;
  padding: 0.35rem 0.5rem; border: 0; border-radius: 5px; background: none;
  color: var(--fg); text-decoration: none; text-align: left; font-weight: normal;
}
.menu a:hover, .menu button:hover { background: var(--surface); }
.menu form { margin: 0; }
.menu-who { padding: 0.35rem 0.5rem 0.5rem; color: var(--muted); font-size: 0.85rem;
  border-bottom: 1px solid var(--rule); margin-bottom: 0.2rem; }
/* Without the Popover API the menu renders as a plain inline row rather
   than vanishing: losing the popover is a cosmetic loss, losing the way
   to sign out is not. */
@supports not selector(:popover-open) {
  .avatar { display: none; }
  .menu { position: static; display: flex; flex-direction: row; align-items: center;
    margin-left: auto; border: 0; padding: 0; min-width: 0; gap: 0.5rem; }
  .menu a, .menu button { width: auto; padding: 0.15rem 0.4rem; }
  .menu-who { border: 0; margin: 0; padding: 0; }
}
form.theme button { padding: 0.3rem 0.45rem; line-height: 0; background: none;
  border-color: transparent; color: var(--muted); }
form.theme button:hover { border-color: var(--rule); color: var(--fg); }
form.theme .ic { opacity: 1; width: 1.05em; height: 1.05em; }
/* Scope pills reuse the nav's shape: the reader is choosing among the
   same sections, so they should not look like a different control. */
nav.scopes { display: flex; flex-wrap: wrap; gap: 0.3rem; margin: 0.6rem 0 1rem; }
nav.scopes a { display: inline-block; padding: 0.15rem 0.6rem; border-radius: 999px;
  border: 1px solid var(--rule); text-decoration: none; font-size: 0.9rem; }
nav.scopes a.here { background: var(--surface); font-weight: 600; }
ul.hits { list-style: none; margin: 0; padding: 0; }
ul.hits li { padding: 0.5rem 0; border-bottom: 1px solid var(--code-bg); }
.snip { color: var(--muted); font-size: 0.9rem; overflow-wrap: anywhere; }
/* Fleet-wide results lead with the repository: the same wiki title
   exists in several stores, so a hit without its repo is ambiguous. */
.hit-repo { color: var(--muted); font-size: 0.85rem; }
.hit-repo::after { content: " /"; }
nav.scopes.facets a .n { color: var(--muted); font-size: 0.8rem; }
form.find.wide { max-width: none; display: flex; gap: 0.4rem; margin-bottom: 0.4rem; }
form.find.wide input { flex: 1 1 auto; min-width: 0; }
/* Chrome links are navigation, not references: colouring the whole nav
   with the accent would make the accent mean nothing. */
.topbar .site, .repobar .repo, nav a, .crumbs a, table.tree a { color: var(--fg); }
header form { margin-left: auto; }
.tw { overflow-x: auto; }
/* Timeline card/detail metrics adapted from fossil src/default.css
   (BSD-2-Clause; see third_party/PROVENANCE.md). The graph tiles
   seamlessly: a fixed 36px head band (node + curves) and a stretching
   tail fill each row edge-to-edge at identical pixel x positions, and
   date rows carry the active rails through. */
table.tl td { border: 0; padding: 0; vertical-align: top; }
table.tl td.tl-graph { position: relative; }
svg.tl-head { position: absolute; top: 0; left: 0; display: block; }
svg.tl-tail { position: absolute; top: 36px; left: 0; height: calc(100% - 36px); display: block; }
tr.tl-date svg.tl-tail, tr.tl-flat svg.tl-tail { top: 0; height: 100%; }
.tl-card-flat { padding: 0.45em 0.75em; font-size: 0.95em; }
/* A technote is the one row on this page somebody WROTE to be read
   here, and the one whose position in time is authored rather than
   observed — the E card is a moment its author chose. Every other flat
   row is a record that something happened. They were pixel-identical
   apart from one word of badge text, so the distinction the reader
   needs was carried by four characters.
   The rule and the warmer ground say "editorial"; the excerpt does the
   heavier lifting, because a difference in SHAPE reads faster than a
   difference in colour and survives greyscale and a phone. */
/* The forum's post edge is this colour at 30% saturation over 3px.
   One pixel of the same value is a grey hairline — the width that
   carried it is gone, so the saturation has to do the work instead.
   55% is the identicon's own range (its two steps are 62% and 60%),
   which is the point: the rule and the mark beside it are one person. */
.tl-card-note { border-left: 1px solid hsl(var(--uh, 0), 55%, 50%, 0.9);
  border-top-left-radius: 0; border-bottom-left-radius: 0;
  padding: 0.55em 0.75em; }
.tl-card-note .tl-note-t { font-weight: 550; }
.tl-note-x { margin: 0.3em 0 0; color: color-mix(in srgb, var(--fg) 72%, var(--muted));
  font-size: 0.93em; max-width: 62ch; }

/* ---- notes: the feed, the note, its history ---- */
.tn-head { display: flex; align-items: baseline; justify-content: space-between;
  gap: 1rem; max-width: var(--measure); }
.tn-head h1 { margin: 0; }
.tn-new { white-space: nowrap; font-size: 0.9rem; }
.tn-lede { color: var(--muted); font-size: 0.9rem; max-width: var(--measure);
  margin: 0.4rem 0 1.4rem; padding-bottom: 0.9rem; border-bottom: 1px solid var(--rule); }
.tn-h { margin: 0 0 0.3rem; }
/* A numbered list without the numbers: ordered because a news feed IS
   a sequence, unnumbered because the dates already say where in it. */
.tn-feed { list-style: none; padding: 0; margin: 0;
  display: flex; flex-direction: column; gap: 1.5rem; }
.tn-item { max-width: var(--measure); }
.tn-title { font-size: 1.06rem; font-weight: 560; text-decoration: none; }
.tn-title:hover { text-decoration: underline; }
.tn-x { margin: 0.3rem 0 0; color: color-mix(in srgb, var(--fg) 74%, var(--muted)); }
.tn-m { margin: 0.35rem 0 0; font-size: 0.82rem; color: var(--muted); }
.tn-m a { text-decoration: none; }
.tn-m a:hover { text-decoration: underline; }
.tn-empty { color: var(--muted); max-width: var(--measure); }
.about-note-x { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical;
  overflow: hidden; }
.tn-hist { list-style: none; padding: 0; margin: 0;
  display: flex; flex-direction: column; gap: 0.55rem; }
.tn-hrow { display: flex; flex-wrap: wrap; align-items: baseline; gap: 0.5rem;
  max-width: var(--measure); }
.tn-hrow a { text-decoration: none; }
.tn-hm { font-size: 0.82rem; color: var(--muted); }
/* The one history fact worth colour: an edit that changed the TITLE is
   why a superseded row and its correction can read as two notes. */
.tn-retitle { color: color-mix(in srgb, var(--accent) 70%, var(--muted)); }
.tn-form { max-width: var(--measure); }
.tn-form label { display: block; font-weight: 550; }
.tn-form input, .tn-form textarea { width: 100%; box-sizing: border-box; margin-top: 0.25rem; }
.tn-form input[type="datetime-local"] { width: auto; min-width: 15rem; }
.tn-hint { display: block; margin-top: 0.3rem; font-size: 0.8rem; color: var(--muted); }
.tn-acts { display: flex; align-items: center; gap: 1rem; }
/* ---- operations ---- */
/* The phase banner. Its colour is the state, so an operator glancing at
   a wall display reads it without reading it: amber while stores are
   still coming up, accent while work moves, quiet at rest. */
.ops-phase { background: var(--surface); border-radius: 0.75rem;
  padding: 0.9rem 1rem; margin: 0 0 1.2rem; border-left: 3px solid var(--rule); }
.ops-phase.ph-starting, .ops-phase.ph-indexing { border-left-color: var(--accent); }
.ops-phase.ph-syncing { border-left-color: var(--add); }
.ops-phase-h { display: flex; flex-wrap: wrap; align-items: baseline; gap: 0.6rem; }
.ops-phase-n { font-size: 1.1rem; font-weight: 600; text-transform: uppercase;
  letter-spacing: 0.06em; }
.ops-phase-c { color: var(--muted); font-size: 0.85rem; }
.ops-phase-l { margin: 0.5rem 0 0; font-size: 0.82rem; color: var(--muted); }
/* One track, two segments: ready and stalled are both done waiting, and
   a bar that counted a stalled store as pending would never fill. */
.ops-bar { display: flex; height: 6px; border-radius: 3px; overflow: hidden;
  background: color-mix(in srgb, var(--fg) 12%, transparent); margin-top: 0.6rem; }
.ops-bar-ok { background: var(--accent); }
.ops-bar-bad { background: var(--del); }
@media (prefers-reduced-motion: no-preference) {
  .ops-bar-ok, .ops-bar-bad { transition: width 0.4s ease; }
}
.ops-cards { display: flex; flex-wrap: wrap; gap: 1rem; margin: 0 0 1.6rem; }
.ops-card { flex: 1 1 12rem; background: var(--surface); border-radius: 0.75rem;
  padding: 0.9rem 1rem; display: flex; flex-direction: column; gap: 0.15rem; }
.ops-n { font-size: 1.9rem; font-weight: 600; font-variant-numeric: tabular-nums; line-height: 1; }
.ops-l { font-size: 0.85rem; }
.ops-sub { font-size: 0.78rem; color: var(--muted); }
.ops-sub a { text-decoration: none; }
table.ops-t { width: 100%; border-collapse: collapse; font-size: 0.88rem; }
table.ops-t th { text-align: left; font-weight: 550; color: var(--muted);
  font-size: 0.78rem; text-transform: uppercase; letter-spacing: 0.05em;
  padding: 0 0.6rem 0.35rem 0; border-bottom: 1px solid var(--rule); }
table.ops-t td { padding: 0.3rem 0.6rem 0.3rem 0; border-bottom: 1px solid var(--rule); }
/* Digits line up in columns, which is the whole reason these are tables. */
table.ops-t th.n, table.ops-t td.n { text-align: right; font-variant-numeric: tabular-nums;
  white-space: nowrap; }
table.ops-t code { font-size: 0.95em; }
table.ops-t a { text-decoration: none; }
table.ops-t a:hover { text-decoration: underline; }
.ops-route-p { margin: -0.6rem 0 1.4rem; color: var(--muted); }
/* One request, then what it asked the store for. Indented under it
   because the calls belong to the request, not beside it. */
.ops-reqs { list-style: none; padding: 0; margin: 0;
  display: flex; flex-direction: column; gap: 0.9rem; }
.ops-req { background: var(--surface); border-radius: 0.6rem; padding: 0.6rem 0.8rem; }
.ops-req-h { display: flex; flex-wrap: wrap; align-items: baseline; gap: 0.6rem; }
.ops-req-t { font-weight: 600; font-variant-numeric: tabular-nums; }
.ops-req-r { text-decoration: none; font-weight: 550; }
.ops-req-m { color: var(--muted); font-size: 0.82rem; }
/* Pushed to the end of the row: when a request happened matters less
   than what it cost, and a column of times would draw the eye first. */
.ops-req-w { margin-left: auto; color: var(--muted); font-size: 0.8rem; }
.ops-calls { margin: 0.5rem 0 0; padding-left: 1.4rem; color: var(--muted);
  font-size: 0.85rem; display: flex; flex-direction: column; gap: 0.15rem; }
.ops-calls .n { font-variant-numeric: tabular-nums; }
.hit-meta { font-size: 0.8rem; color: var(--muted); margin: 0.15rem 0 0; }
.hit-meta code { font-size: 0.95em; color: var(--accent); }
.hit-branch { color: color-mix(in srgb, var(--fg) 70%, var(--muted)); }
.role-badge { margin-left: 0.4rem; color: var(--accent); border-color: var(--accent); }
.w-notes { display: flex; align-items: baseline; gap: 0.6rem; margin: 0 0 1rem; }
.w-notes a { text-decoration: none; font-weight: 550; }
.w-notes .tn-hint { display: inline; margin: 0; }
.tl-meta-inline { color: var(--muted); font-size: 85%; }
table.tl td.tl-time { white-space: nowrap; width: 3.4rem; padding: 13px 0.5rem 0 0; text-align: right; }
table.tl td.tl-time a { color: var(--muted); text-decoration: none; }
table.tl td.tl-time a:hover { text-decoration: underline; }
table.tl td.tl-slot { width: 100%; padding: 0 0 5px 0.6rem; }
table.tl td.tl-datecell { padding: 6px 0 6px 0.6rem; }
.tl-card { background: var(--surface); border-radius: 1em; padding: 0.75em; }
.tl-title { font-weight: 550; }
.tl-p { margin: 0.35em 0 0; color: color-mix(in srgb, var(--fg) 78%, var(--muted)); }
/* The landing line is provenance, not prose: quieter than the check-in
   comment it sits under, and the link carries the weight. */
.tl-landed { font-size: 0.92em; color: var(--muted); }
/* The route beside an actual path: present for the drilldown link, and
   quiet enough that the path is what a reader scans. */
.ops-route-l { display: block; font-size: 0.82em; color: var(--muted); }
/* A strata: the rungs under a base row, and the map on a record. */
.strata summary { cursor: pointer; color: var(--muted); font-size: 0.92em; margin-top: 0.3em; }
.strata-rungs { list-style: none; margin: 0.4em 0 0; padding: 0 0 0 0.2em; border-left: 2px solid var(--rule); }
.strata-rungs li { padding: 0.2em 0 0.2em 0.6em; }
.strata-rungs li.here { background: var(--surface); border-radius: 4px; }
.strata-map { margin: 0.6em 0 0.2em; }
.l-steps { font-size: 0.9em; margin: 0.4em 0; padding: 0.5em 0.7em; background: var(--code-bg); border-radius: 4px; }
.l-steps em { color: var(--muted); font-style: normal; }
.tl-meta { color: var(--muted); font-size: 80%; text-align: right; opacity: 0.85; margin-top: 0.5em; }
.tl-meta a { text-decoration: none; }
.tl-meta a:hover { text-decoration: underline; }
@media (max-width: 640px) {
  /* main carries the page's horizontal padding now, not body. This was
     "body { padding: 0.5rem }" — a shorthand, which silently reset the
     bottom reserve the fixed footer depends on and let content run
     underneath it on exactly the screens where that hurts most. */
  main { padding-left: 0.5rem; padding-right: 0.5rem; }
  .bar { padding-left: 0.5rem; padding-right: 0.5rem; }
  table.tl td.tl-time { width: 2.6rem; font-size: 0.8rem; padding-top: 15px; }
  .tl-card { padding: 0.75em 0.55em; border-radius: 0.6em; }
  .tl-meta { font-size: 72%; }
  /* Phone widths: the card's widest line is the metadata run, and its
     max-content is what pushed the table past the viewport (auto table
     layout prefers it, and .tw then scrolls sideways, hiding the
     right-aligned meta). Stacking the items drops that preference to
     the longest single item, so the table fits with the cards still
     wide. */
  .tl-metaitem { display: block; }
  .tl-card { overflow-wrap: anywhere; }
}
/* File listing. The old one spent ~52px of height and three columns on
   one short filename; fossil fits roughly 60 entries in the space that
   showed 25. Density here comes from tight rows and dropping the
   repeated per-row "history" link, not from shrinking the type. */
table.tree { table-layout: auto; }
/* GitHub's middle column: the last check-in to touch each entry, muted,
   one line, eating the slack between name and age. Its collapse is
   GitHub's too — the message yields on a phone, the age stays. The
   size column belongs to the no-data layout; GitHub's listing never
   had one, and the message is worth more. */
table.tree.hc { width: 100%; }
table.tree.hc td.t-name { white-space: nowrap; max-width: 22rem;
  overflow: hidden; text-overflow: ellipsis; padding-right: 1.25rem; }
td.t-change { color: var(--muted); max-width: 0; width: 100%;
  overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
  padding-right: 1rem; }
td.t-change a { color: var(--muted); }
td.t-change a:hover { color: var(--accent); }
td.t-age { color: var(--muted); text-align: right; white-space: nowrap; }
@media (max-width: 44rem) {
  td.t-change { display: none; }
}
table.tree td { padding: 0.15rem 0; border: 0; line-height: 1.45; }
table.tree tr:hover { background: var(--surface); }
/* Thirty underlined names in a column is a wall of rules, and the
   underline carries no information here — every name in the listing is
   a link, so marking them all marks nothing. Hover restores it. */
table.tree a, .tree-bar .crumbs a { text-decoration: none; }
table.tree a:hover, .tree-bar .crumbs a:hover { text-decoration: underline; }
/* The icon and the name are one label, so they get a gap rather than
   sitting flush: without it the glyph reads as the first character of
   the filename. */
td.t-name { white-space: nowrap; }
td.t-name .ic { margin-right: 0.45rem; }
/* Sizes are only comparable when their digits line up, which means
   right-aligned and tabular figures. The column takes only what it
   needs so the name column is not pushed across the viewport. */
td.t-size { text-align: right; white-space: nowrap; width: 1%;
  padding-left: 1.5rem; color: var(--muted); font-variant-numeric: tabular-nums; }
/* Icons are an SVG sprite (see iconSprite), referenced by <use>. They
   were CSS masks with inline data: URIs, which Chrome accepts and iOS
   Safari does not: the raw <, > and quotes make the URI invalid, the
   mask silently fails, and every icon renders as a solid block. A
   sprite has no encoding to get wrong. */
.sprite { display: none; }
.ic { width: 1em; height: 1em; vertical-align: -0.125em; fill: currentColor;
  opacity: 0.55; flex: none; }
/* Flags replace ls(1)'s trailing punctuation. "compile*" reads as part
   of the filename; a labelled chip does not. */
.flag { font-size: 0.7rem; color: var(--muted); border: 1px solid var(--rule);
  border-radius: 3px; padding: 0 0.25rem; vertical-align: 0.05em; }
/* A strip of repository facts, the way forgejo leads a repo page. Each
   is a link to the surface that explains it. */
.repo-stats { display: flex; flex-wrap: wrap; gap: 0.25rem 1.25rem; margin: 0 0 0.75rem;
  padding: 0.5rem 0.75rem; background: var(--surface); border: 1px solid var(--rule);
  border-radius: 8px; font-size: 0.9rem; }
.repo-stats a { display: inline-flex; align-items: center; gap: 0.4rem;
  color: var(--fg); text-decoration: none; }
.repo-stats a:hover { text-decoration: underline; }
.refbtn, .dlbtn { display: inline-flex; align-items: center; gap: 0.4rem; cursor: pointer; }
.refname { max-width: 12rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.caret { color: var(--muted); font-size: 0.7em; }
/* Hug the content; only long ref lists scroll, and their scrolling does
   not chain to the page behind them. */
.menu.refs, .menu.dlmenu { position: fixed; inset: auto; max-height: 60vh; overflow-y: auto;
  overscroll-behavior: contain; scrollbar-width: thin; min-width: 13rem; }
.menu.refs a.here, .menu.dlmenu a.here { background: var(--surface); font-weight: 600; }
@supports (anchor-name: --a) {
  .refbtn { anchor-name: --refbtn; }
  .menu.refs { position-anchor: --refbtn; top: anchor(bottom); left: anchor(left); margin-top: 0.3rem; }
  .dlbtn { anchor-name: --dlbtn; }
  .menu.dlmenu { position-anchor: --dlbtn; top: anchor(bottom); right: anchor(right); margin-top: 0.3rem; }
}
/* basecoat's input-group, same as the search field: ONE bordered shell
   owns the border and the radius; the segments inside are borderless
   with hairline separators. Per-segment borders put a radius at every
   seam, and the corners never quite meet. The tool choice is still a
   URL (?clone=), so it survives a reload and can be linked to. */
.clonebox { display: inline-flex; align-items: stretch; min-width: 0;
  border: 1px solid var(--rule); border-radius: 6px; background: var(--bg);
  overflow: hidden; }
.clonebox:focus-within { outline: 2px solid var(--muted); outline-offset: 1px; }
.clonepick { display: inline-flex; align-items: center; font-size: 0.8rem;
  border-right: 1px solid var(--rule); background: var(--surface); }
.clonepick a { padding: 0.2rem 0.55rem; text-decoration: none; color: var(--muted);
  align-self: stretch; display: inline-flex; align-items: center; }
.clonepick a.here { background: var(--bg); color: var(--fg); font-weight: 600; }
.cloneurl { font-family: ui-monospace, monospace; font-size: 0.8rem; min-width: 0; width: 22rem;
  border: 0; border-radius: 0; background: none; }
.cloneurl:focus-visible { outline: none; }
.copybtn { border: 0; border-left: 1px solid var(--rule); border-radius: 0;
  background: none; padding: 0 0.5rem; cursor: pointer; }
/* Tree chrome: one row carrying branch, crumbs and clone. */
.tree-bar { display: flex; gap: 0.75rem; align-items: center; flex-wrap: nowrap;
  margin-bottom: 0.6rem; min-width: 0; }
.tree-bar .crumbs { font-weight: 600; min-width: 3ch; overflow: hidden;
  text-overflow: ellipsis; white-space: nowrap; }
.tree-bar .tree-acts { margin-left: auto; display: flex; gap: 0.75rem;
  align-items: center; font-size: 0.85rem;
  /* The clone input is the compressible member of this row: without
     min-width the actions block refuses to shrink and spills into the
     About column. */
  min-width: 0; flex: 0 1 auto; }
.tree-bar .tree-acts .clonebox { min-width: 0; flex: 0 1 auto; }
.tree-bar .tree-acts .clonepick, .tree-bar .tree-acts .dlbtn { flex: none; }

.tree-bar .dl { white-space: nowrap; }
/* A select is as wide as its widest option, so one long branch name set
   the control's width for every repository — 288px, most of a phone
   row, to show "trunk". The cap truncates the outlier instead; the full
   name is still in the open list, which is where it is read. */
.tree-bar select { max-width: 11rem; }
@media (max-width: 40rem) {
  /* The clone command is the first thing worth losing on a phone — it
     is long and not what a reader came for — and the zit/fossil picker
     goes with it: a tool choice for a command that is not on screen.
     What remains (ref, path, download) holds ONE line. */
  .tree-bar .clonebox, .tree-bar .clonepick { display: none; }
  .tree-bar { gap: 0.5rem; }
}
/* Form controls inherit the browser's palette, not the page's: a white
   textarea on a dark page, and iOS Safari's blue pill for every button.
   They also default to content-box, so the width:100% on our textareas
   overflowed by exactly the padding and border. Both are the browser
   being reasonable in isolation and wrong here, so they are set once for
   every form rather than per-page. */
input, textarea, select, button {
  font: inherit; color: var(--fg); background: var(--bg);
  border: 1px solid var(--rule); border-radius: 6px;
  padding: 0.35rem 0.55rem; box-sizing: border-box; max-width: 100%;
}
textarea { display: block; width: 100%; resize: vertical; line-height: 1.5; }
/* The UA draws its select caret hard against the border and ignores
   padding. Owning the indicator (a currentColor-matched chevron) is
   how every design system solves it: consistent shape, real breathing
   room, both themes. */
select { appearance: none; -webkit-appearance: none; padding-right: 1.7rem;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'%3E%3Cpath d='M1 1l4 4 4-4' fill='none' stroke='%23888' stroke-width='1.6' stroke-linecap='round'/%3E%3C/svg%3E");
  background-repeat: no-repeat; background-position: right 0.6rem center; }
button, input[type=submit] {
  -webkit-appearance: none; appearance: none;
  background: var(--code-bg); cursor: pointer; font-weight: 600;
}
button:hover, input[type=submit]:hover { border-color: var(--fg); }
::placeholder { color: var(--muted); opacity: 1; }
/* WebKit draws its own clear button inside a search field, in the OS
   accent colour, and nothing but its size is styleable — a blue X in a
   gruvbox page. Basecoat leaves it alone and inherits the same problem.
   It is removed here and replaced, where there is something to clear,
   by a link that resets the filter: the same colour as everything else
   and, being a link, it works with scripting off. */
input[type=search]::-webkit-search-cancel-button,
input[type=search]::-webkit-search-decoration { -webkit-appearance: none; appearance: none; }
/* basecoat's input-group: one bordered shell, borderless controls
   inside it. An add-on then sits WITHIN the field instead of floating
   beside it, which is what the loose clear link looked like. */
/* Forum: GitHub/Codeberg's comment-thread shape. Each post is a card —
   a muted header strip (author, time, hash, controls) over a padded
   body — so authorship and actions live in chrome, not in the prose. */
.f-actions { display: flex; align-items: center; gap: 0.6rem; margin: 0.75rem 0 1rem; flex-wrap: wrap; }
.f-actions form { margin: 0; }
.f-post { border: 1px solid var(--rule); border-radius: 8px; margin: 1rem 0;
  /* The author's hue as a WHISPER on the left edge — same 1px weight
     as every other border, only the color applied. */
  border-left-color: hsl(var(--uh, 0), 30%, 50%, 0.55); }
.f-post-h .idn { width: 16px; height: 16px; }
.f-spectrum { display: block; width: 100%; height: 6px; margin: 0.1rem 0 0.9rem; border-radius: 3px; }
.f-spectrum a rect:hover { fill-opacity: 1; }
/* A mention reads like a BYLINE, not a highlighted link: the mark, then
   the name in the page's own colour. The accent is reserved for hover,
   because a name that is orange wherever it appears turns every
   conversation into a field of links and stops meaning "this is
   clickable" anywhere. */
a.uref { font-weight: 600; color: var(--fg); text-decoration: none; }

/* References and their preview (RFC 0011 §14). The link is styled as a
   link because it IS one — the popover is an accelerator, not the way
   the reference is read. */
a.ref { text-decoration: underline dotted; text-underline-offset: 0.15em; }
#refpop { border: 1px solid var(--rule); border-radius: 6px; padding: 0.5rem 0.7rem;
  max-width: 32rem; background: var(--bg); color: var(--fg); box-shadow: 0 2px 8px rgba(0,0,0,0.15); }
#refpop:not(:popover-open) { display: none; }
/* The card belongs AT the reference that opened it, not centred in the
   viewport where the UA would put it. Anchor positioning is the real
   answer — it survives scroll and reflow — and the opener's measured
   left/top is the inline fallback where it is unknown. inset: auto
   undoes the UA's inset: 0, which would otherwise stretch the card
   across the screen the moment left is set. */
#refpop { position: fixed; inset: auto; margin: 0; }
@supports (anchor-name: --a) {
  #refpop { position-anchor: --qrefpop; top: anchor(bottom); left: anchor(left);
    margin-top: 0.3rem; position-try-fallbacks: flip-block, flip-inline; }
}
.refcard-sum { color: var(--muted); }
.refcard[data-expired] .refcard-sum { font-style: italic; }
a.chatquote { display: block; border-left: 3px solid var(--rule); padding-left: 0.5rem;
  color: var(--muted); text-decoration: none; font-size: 0.9em; }
a.chatreplies { color: var(--muted); font-size: 0.85em; }
a.uref:hover { color: var(--accent); text-decoration: underline; }
.f-parent, .f-replyto { color: inherit; }
.f-replyto { font-weight: 600; }
/* Praise sits in the stats strip because that is where a reader already
   looks for what a repository amounts to. The pressed state rides on
   aria-pressed as well as colour — "is this praised" must not be a claim
   made only in orange, which a colour-blind reader cannot hear. */
.praise-form { display: inline-flex; margin: 0; }
.praise-btn { display: inline-flex; align-items: center; gap: 0.35rem;
  padding: 0.1rem 0.55rem; font-size: 0.85rem; font-weight: 600; }
.praise-btn .ic { width: 0.9em; height: 0.9em; }
.praise-btn.on { border-color: var(--accent); color: var(--accent); }
.praise-n { font-weight: 400; opacity: 0.85; }
/* The listing. Rows stack on a phone for the same reason the webhook
   rows do: a fixed-width control here would drag the page wide again. */
.ev-list { list-style: none; margin: 0.6rem 0; padding: 0; }
.ev-list li { display: flex; flex-wrap: wrap; align-items: baseline;
  gap: 0.35rem 0.8rem; padding: 0.45rem 0; border-top: 1px solid var(--rule); }
.ev-kind { font-size: 0.85em; background: var(--code-bg); border-radius: 4px;
  padding: 0.05rem 0.4rem; flex: 0 0 auto; }
.ev-sum { flex: 1 1 16rem; min-width: 0; overflow-wrap: anywhere; }
.ev-meta { color: var(--muted); font-size: 0.85em; }
.p-h { font-size: 1.05rem; margin: 0 0 0.4rem; }
.praised-list { list-style: none; margin: 0.5rem 0; padding: 0; }
.praised-list li { display: flex; flex-wrap: wrap; align-items: baseline;
  gap: 0.4rem 0.9rem; padding: 0.6rem 0; border-top: 1px solid var(--rule); }
.praised-list .p-name { font-weight: 600; }
.praised-list .p-desc { color: var(--muted); font-size: 0.9em;
  flex: 1 1 14rem; min-width: 0; }
.praised-empty { color: var(--muted); }
/* Webhooks. A table here forced the page wider than a phone: three
   columns, one of them an input beside three buttons, and a table's
   intrinsic width wins over max-width on anything inside it — so every
   field on the page, including the ones above this section, ran off the
   right edge. Rows that stack are the fix, not a narrower table. */
.hook-list { list-style: none; margin: 0.5rem 0 1rem; padding: 0; }
.hook-list li { padding: 0.6rem 0; border-top: 1px solid var(--rule); }
.hook-head { display: flex; flex-wrap: wrap; align-items: baseline;
  gap: 0.4rem 0.6rem; margin: 0; }
/* A URL has no spaces, so it needs explicit permission to break or it
   is itself a minimum width the page must grow to. */
.hook-url { overflow-wrap: anywhere; min-width: 0; }
.hook-state { font-size: 0.85em; color: var(--muted); }
.hook-state.off { font-style: italic; }
.hook-sub { font-size: 0.85em; color: var(--muted); margin: 0.1rem 0 0.45rem; }
.hook-form { display: flex; flex-wrap: wrap; align-items: center;
  gap: 0.4rem; margin: 0; }
/* Grow to fill, shrink to nothing: min-width 0 is what lets a flex item
   actually get smaller than its content, which is the other half of why
   the row used to overflow. */
.hook-form input[name="events"] { flex: 1 1 11rem; min-width: 0; width: auto; }
.hook-acts { display: flex; flex-wrap: wrap; gap: 0.4rem; }
.hook-lbl { flex: 0 0 auto; }
.hook-add p { margin: 0.5rem 0; }
.hook-add input[type="url"] { width: 100%; }
.hook-nouns { display: flex; flex-wrap: wrap; gap: 0.3rem; margin: 0.4rem 0 0.9rem; }
.hook-nouns code { background: var(--code-bg); border-radius: 4px;
  padding: 0.05rem 0.35rem; font-size: 0.9em; }
/* A table sizes to its content, and an <input size=28> in a cell cannot
   shrink — so this table's min-content width exceeded a phone and made
   the WHOLE page wider than the viewport. Everything then ran off the
   right edge, which reads as fields having no padding. The table scrolls
   inside its own box instead; the page does not. */
.tablewrap { overflow-x: auto; max-width: 100%; }
.caps-table { border-collapse: collapse; margin: 0.5rem 0; }
.caps-table td { padding: 0.2rem 0.6rem 0.2rem 0; vertical-align: middle; }
.caps-table input { font-family: var(--mono, ui-monospace), monospace; }
/* The People section and the per-person editor (RFC 0008). A row is a
   name, chips, and one sentence: the chips are the role and the ways a
   person differs from it, so an ordinary row is one chip long. */
.roster { list-style: none; margin: 0.5rem 0; padding: 0; }
.roster li { padding: 0.45rem 0; border-top: 1px solid var(--rule); }
.roster-head { display: flex; flex-wrap: wrap; align-items: center; gap: 0.4rem; }
.roster-can { margin: 0.15rem 0 0; color: var(--muted); font-size: 0.92rem; }
.chip.role { color: var(--fg); border-color: var(--fg); }
.chip.plus { color: var(--ok, #2a7); }
.chip.minus { color: var(--warn, #b60); }
.chip.owns { font-style: italic; }
.roster-add { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem 0.8rem; margin-top: 0.6rem; }
.person-form fieldset { border: 1px solid var(--rule); margin: 0.6rem 0; padding: 0.4rem 0.8rem; }
.person-form legend { font-weight: 600; padding: 0 0.3rem; }
.person-form label { display: block; padding: 0.15rem 0; }
.person-form .roles label small { color: var(--muted); }
.person-form .abilities { display: grid; grid-template-columns: repeat(auto-fill, minmax(18rem, 1fr)); gap: 0 1rem; }
.person-form label.adv { color: var(--muted); }
.person-form .raw { margin: 0.6rem 0; }
.status.err { color: var(--warn, #b60); }
.ci-override { margin-top: 0.4rem; }
/* The run page's log panes (RFC 0009 §logs). */
/* A red check on the decision card: the row is the summary, the failed
   step's tail is the body, open by default — red is exactly when the
   reader needs the why without leaving the decision. */
/* The CI list: every row answers what happened. The chip and the title
   both open the run; a red row says which step and quotes the line. */
.ci-filter { display: flex; gap: 0.5rem; align-items: center; flex-wrap: wrap; margin: 0 0 0.9rem; }
.ci-health { display: flex; gap: 0.5rem; align-items: baseline; flex-wrap: wrap; border: 1px solid var(--rule); border-radius: 8px; padding: 0.5rem 0.9rem; margin: 0 0 0.6rem; }
.ci-rows { border: 1px solid var(--rule); border-radius: 8px; }
.ci-row { display: flex; gap: 0.8rem; align-items: flex-start; padding: 0.6rem 0.9rem; border-bottom: 1px solid var(--rule); }
.ci-row:last-child { border-bottom: none; }
.ci-chip { text-decoration: none; padding-top: 0.1rem; }
.ci-main { flex: 1 1 auto; min-width: 0; display: flex; flex-direction: column; gap: 0.15rem; }
.ci-title { color: var(--ink, inherit); font-weight: 600; text-decoration: none; overflow-wrap: anywhere; }
.ci-title:hover { text-decoration: underline; }
.ci-why { font-size: 0.88rem; overflow-wrap: anywhere; }
.ci-why code { font-size: 0.85em; }
.ci-meta { color: var(--muted); font-size: 0.82rem; }
.ci-side { display: flex; gap: 0.7rem; align-items: baseline; white-space: nowrap; }
.ci-dur { font-variant-numeric: tabular-nums; }
.ci-rerun { font-size: 0.78rem; padding: 0.1rem 0.5rem; }
.ci-pipes { margin-top: 0.7rem; }
/* On a phone the row's three columns do not fit: duration, age and
   Re-run are nowrap and take about 200px, leaving the title 150 and
   forcing it to break mid-word — "gofmt cmd/quarr / y/main.go". The
   side drops to its own line instead, which gives the title the full
   width and lets the badge stay beside the words it qualifies. */
@media (max-width: 34rem) {
  .ci-row { flex-wrap: wrap; gap: 0.5rem; }
  .ci-main { flex: 1 1 100%; }
  .ci-side { width: 100%; justify-content: flex-end; }
  /* Break only where a word genuinely cannot fit: overflow-wrap
     anywhere splits ordinary prose mid-syllable, which is what made
     these unreadable at this width. */
  .ci-title, .ci-why { overflow-wrap: break-word; }
}
.ci-editor textarea { width: 100%; font: 0.85rem/1.55 ui-monospace, monospace; background: none; color: inherit; border: 1px solid var(--rule); border-radius: 8px; padding: 0.7rem 0.9rem; resize: vertical; }

details.l-check summary { list-style: none; cursor: pointer; display: flex; align-items: baseline; gap: 0.45rem; flex-wrap: wrap; }
details.l-check summary::-webkit-details-marker { display: none; }
details.l-check .runlog { margin: 0.45rem 0 0.15rem; max-height: 22rem; overflow-y: auto; }

.runstep { border: 1px solid var(--rule); border-radius: 8px; margin: 0.5rem 0; }
.runlog { line-height: 1.45; }
.runlog .ll { display: block; }
.runlog .ll-err { color: var(--del); }
.runlog .ll-mark { color: var(--muted); font-style: italic; }
.ll-n { display: inline-block; min-width: 3ch; margin-right: 1ch; color: var(--muted); text-align: right; text-decoration: none; user-select: none; }
.ll:target { background: var(--mark); }
/* RFC 0009: the decision card. Status rows lead — icon, headline,
   muted subline — the verbs close the card; nothing about the decision
   lives anywhere else on the page. */
.l-decide { border: 1px solid var(--rule); border-radius: 10px; margin: 0.8rem 0; }
.l-decide .d-row { display: block; padding: 0.65rem 1rem; border-bottom: 1px solid var(--rule); }
.l-decide .d-row summary { list-style: none; cursor: pointer; display: flex; align-items: baseline; gap: 0.6rem; }
.l-decide .d-row summary::-webkit-details-marker { display: none; }
.l-decide div.d-row { display: flex; align-items: baseline; gap: 0.6rem; }
.d-ic { flex: none; width: 16px; height: 16px; transform: translateY(2px); }
.d-ic.pass { color: var(--add); fill: var(--add); }
.d-ic.fail { color: var(--del); fill: var(--del); }
.d-ic.wait { color: var(--muted); fill: var(--muted); }
.d-line { min-width: 0; }
.d-sub { color: var(--muted); font-size: 0.92rem; }
.d-meta { color: var(--muted); font-size: 0.85rem; margin-left: auto; white-space: nowrap; }
.d-meta a { color: var(--muted); }
.d-body { padding: 0.5rem 0 0 1.6rem; }
.d-body .l-check { margin: 0.35rem 0; }
.l-check { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem; }
.d-act { display: flex; flex-wrap: wrap; align-items: center; gap: 0.6rem; row-gap: 0.5rem; padding: 0.65rem 1rem; }
/* A refused verb must not look pressable: the card's disabled buttons
   go ghost — dashed, muted, no fill — the same honesty the reason
   sentence beside them speaks. */
.d-act button:disabled { background: none; color: var(--muted); border: 1px dashed var(--rule); cursor: not-allowed; }
.l-decide > :last-child { border-bottom: none; }
.ci-override summary { color: var(--muted); cursor: pointer; }
.vis-form label { display: block; padding: 0.15rem 0; }
.f-post-f { display: flex; justify-content: flex-end; padding: 0 0.8rem 0.65rem; }
.f-replybtn { font-size: 0.85rem; padding: 0.25rem 0.7rem; }
.f-reply-note { padding: 0.45rem 0.8rem; border-bottom: 1px solid var(--rule);
  background: var(--surface); border-radius: 8px 8px 0 0; font-size: 0.85rem; color: var(--muted); }
.f-post-h { display: flex; align-items: center; gap: 0.5rem; flex-wrap: wrap;
  padding: 0.4rem 0.8rem; background: var(--surface);
  border-bottom: 1px solid var(--rule); border-radius: 8px 8px 0 0;
  font-size: 0.85rem; color: var(--muted); }
.f-post-h strong { color: var(--fg); }
.f-post-h .f-spacer { margin-left: auto; }
.f-post-b { padding: 0.9rem 1rem 0.1rem; }
.f-post-b > :first-child { margin-top: 0; }
/* The vote pill: one bordered capsule, arrow · score · arrow. The two
   forms inside are the no-script mechanism; the pill is just clothes. */
.vote-pill { display: inline-flex; align-items: center; border: 1px solid var(--rule);
  border-radius: 999px; background: var(--bg); line-height: 1.2; }
.vote-pill form { margin: 0; display: inline-flex; }
.vote-pill button { border: 0; border-radius: 999px; background: none;
  padding: 0.1rem 0.45rem; font-weight: normal; font-size: 0.85rem; }
.vote-pill button:hover { background: var(--code-bg); border-color: transparent; }
.vote-pill .vscore { padding: 0 0.1rem; font-weight: 600; color: var(--fg); font-variant-numeric: tabular-nums; }
.vote-cast { color: var(--accent); }
/* Moderator actions fold behind a no-script kebab: details/summary. */
.f-kebab { position: relative; display: inline-block; }
.f-kebab > summary { list-style: none; cursor: pointer; padding: 0 0.45rem;
  border-radius: 5px; color: var(--muted); font-weight: 600; }
.f-kebab > summary::-webkit-details-marker { display: none; }
.f-kebab > summary:hover { background: var(--code-bg); color: var(--fg); }
.f-kebab-pop { position: absolute; right: 0; top: 1.6rem; z-index: 5;
  display: flex; align-items: center; gap: 0.4rem; padding: 0.5rem;
  background: var(--bg); border: 1px solid var(--rule); border-radius: 6px;
  box-shadow: 0 4px 14px rgba(0,0,0,0.25); white-space: nowrap; }
.f-kebab-pop form { margin: 0; display: flex; align-items: center; gap: 0.4rem; }
.f-kebab-pop input { font-size: 0.85rem; }
.f-kebab-pop button { font-size: 0.85rem; }
/* The reply composer: textarea in a card, actions in a footer strip —
   the comment box every forge reader already knows. */
.f-reply { border: 1px solid var(--rule); border-radius: 8px; margin-top: 1.25rem; overflow: clip; }
.f-reply:focus-within { border-color: var(--accent); }
.f-reply textarea { border: 0; border-radius: 8px 8px 0 0; }
.f-reply textarea:focus-visible { outline: none; }
/* The decision row is ONE line. It grew from three verbs to five as
   landings learned to update and to land a whole strata, and the old
   rule let flex shrink the buttons: every label folded to three lines
   and the leftmost still ran off the side of a phone. flex:none and
   nowrap keep each button one line at its own width; where five cannot
   fit, the LABELS shorten rather than the row breaking. */
/* A confirmation is an EVENT, so it has a lifetime. It holds long
   enough to be read, then fades and COLLAPSES — collapsing as well as
   fading, so the page does not keep a paragraph of empty space where a
   sentence used to be.
   
   Done in CSS, not script: this page must behave the same without
   JavaScript, and an animation is the one way to give an element a
   lifetime that costs nothing when the script is absent. role="status"
   announces it on insert, before any of this runs, so a screen reader
   has already heard it.
   
   Reduced motion keeps it: someone who has asked for less movement is
   asking for less MOVEMENT, not for the message to be taken away. */
/* The confirmation lives ON the control that did the saving. Both
   labels sit in the same grid cell, so the button is sized by the wider
   of them and NOTHING moves when they swap — the whole reason to put it
   here rather than in the page's flow.

   The revert is CSS too, on the same four-second beat as the old flash:
   without script the label must still find its way back to "Save", and
   an animation is what gives it a lifetime for free. */
.btn-swap { display: inline-grid; align-items: center; justify-items: center; }
.btn-swap > span { grid-area: 1 / 1; }
/* Green, from the palette's own token — the same --add that marks a
   passing run and an open glyph, so "it worked" reads the same colour
   everywhere rather than this button inventing one. */
.sw-b { opacity: 0; color: var(--add); }
.did-save { border-color: var(--add); }
.did-save .sw-a { opacity: 0; animation: sw-back-a 300ms ease 4s forwards; }
.did-save .sw-b { opacity: 1; animation: sw-back-b 300ms ease 4s forwards; }
@keyframes sw-back-a { to { opacity: 1; } }
@keyframes sw-back-b { to { opacity: 0; } }
/* Reduced motion keeps the word and drops the movement, as the flash
   does: the button simply stays "Saved" until the page next renders. */
@media (prefers-reduced-motion: reduce) {
  .did-save .sw-a, .did-save .sw-b { animation: none; }
}
.flash-once { overflow: hidden; animation: flash-out 400ms ease 4s forwards; }
@keyframes flash-out {
  to { opacity: 0; max-height: 0; margin-top: 0; margin-bottom: 0;
       padding-top: 0; padding-bottom: 0; }
}
@media (prefers-reduced-motion: reduce) { .flash-once { animation: none; } }
/* Wraps: the decision row grows a refusal sentence and an override
   disclosure (RFC 0009), and clipping a button is never the answer. */
.f-reply-foot { display: flex; flex-wrap: wrap; row-gap: 0.5rem; justify-content: flex-end;
  gap: 0.5rem;
  padding: 0.45rem 0.5rem; border-top: 1px solid var(--rule);
  background: var(--surface); border-radius: 0 0 8px 8px; }
/* One line per button, always: a label that folds makes a control three
   times the height of its neighbours, which reads as a different kind
   of thing rather than as the same button with more words. */
.f-reply-foot > * { flex: none; white-space: nowrap; }
/* Below the width where five verbs fit, the words give way — not the
   line. The short form keeps the same verb, so nothing has to be
   relearned on a phone. Reject keeps its word: there is no X in the
   sprite, and an unlabelled destructive control is worse than a
   cramped one. */
.b-abbr, .b-icon { display: none; }
@media (max-width: 30rem) {
  .f-reply-foot { gap: 0.35rem; padding-left: 0.35rem; padding-right: 0.35rem; }
  .f-reply-foot > * { font-size: 0.8rem; padding-left: 0.5rem; padding-right: 0.5rem; }
  .b-long { display: none; }
  .b-abbr { display: inline; }
}
/* A second step for the narrowest phones still sold. Measured at 320:
   five abbreviated buttons want 364px against 302 of room, and Comment
   is the widest word left. It has a sprite icon and is the one action
   here that destroys nothing, so it is the one that loses its label. */
@media (max-width: 22rem) {
  .f-reply-foot > * { font-size: 0.75rem; padding-left: 0.4rem; padding-right: 0.4rem; }
  .b-word { display: none; }
  .b-icon { display: inline-block; }
}
.btn-primary { background: var(--accent); color: var(--bg); border-color: var(--accent); }
.btn-primary:hover { border-color: var(--accent); filter: brightness(1.1); }
/* The markdown composer: GitHub's Write | Preview tabs over a raw
   textarea. The tab bar ships hidden and JS unhides it — without
   script the composer is simply a textarea, which is the whole
   fallback story. Preview renders through the PRODUCTION pipeline. */
.f-composer .f-tabs { display: flex; gap: 0.25rem; padding: 0.45rem 0.6rem 0;
  background: var(--surface); border-bottom: 1px solid var(--rule);
  border-radius: 8px 8px 0 0; }
.f-tab { border: 1px solid transparent; background: none; font-size: 0.85rem;
  padding: 0.3rem 0.75rem; border-radius: 6px 6px 0 0; color: var(--muted); font-weight: 600; }
.f-tab:hover { color: var(--fg); border-color: transparent; }
.f-tab.here { background: var(--bg); border-color: var(--rule); border-bottom-color: var(--bg);
  color: var(--fg); position: relative; top: 1px; }
.f-composer textarea { border: 0; border-radius: 0; }
.f-preview { padding: 0.9rem 1rem; min-height: 9rem; }
.f-composer [hidden] { display: none; }
.f-preview > :first-child { margin-top: 0; }
/* Live split: raw markdown left, the render growing beside it as you
   type — the pane is fed by the production renderer, debounced. JS
   unhides it; without script the composer is a full-width textarea. */
.f-split { display: grid; grid-template-columns: 1fr; }
.f-split:has(.f-live:not([hidden])) { grid-template-columns: 1fr 1fr; }
.f-live { border-left: 1px solid var(--rule); padding: 0.9rem 1rem; overflow-y: auto;
  font-size: 0.95em; }
.f-live-pane > :first-child { margin-top: 0; }
.f-live-pane:empty::before { content: "rendered preview appears as you type"; color: var(--muted); font-size: 0.85rem; }
@media (max-width: 52rem) {
  .f-split:has(.f-live:not([hidden])) { grid-template-columns: 1fr; }
  .f-live { border-left: 0; border-top: 1px solid var(--rule); }
}
/* The poll widget as previewed (ballot-less) and the poll BUILDER —
   structured inputs in the live pane that write the fenced poll block
   back into the raw source. The markdown stays the source of truth. */
.f-pollprev, .f-poll-builder:not(:empty) { border: 1px solid var(--rule); border-radius: 6px;
  padding: 0.6rem 0.8rem; max-width: 30rem; margin: 0.5rem 0; }
.f-pollprev-o { margin: 0.35rem 0; }
.f-pollbar { height: 6px; background: var(--rule); border-radius: 3px; }
.f-poll-builder label { display: block; font-size: 0.8rem; color: var(--muted); margin-top: 0.4rem; }
.f-poll-builder input { width: 100%; margin-top: 0.15rem; }
.f-poll-builder .pb-row { display: flex; gap: 0.3rem; align-items: center; }
.f-poll-builder .pb-row button { padding: 0.2rem 0.5rem; font-size: 0.85rem; }
.f-poll-builder .pb-add { margin-top: 0.4rem; font-size: 0.85rem; }
.f-poll-builder h4 { margin: 0; font-size: 0.9rem; }
/* The slash menu (composer.js): a popover of block snippets. */
.slash-menu { position: absolute; z-index: 6; background: var(--bg);
  border: 1px solid var(--rule); border-radius: 6px; padding: 0.25rem;
  box-shadow: 0 4px 14px rgba(0,0,0,0.25); min-width: 11rem; }
.slash-menu button { display: block; width: 100%; text-align: left; border: 0;
  background: none; padding: 0.3rem 0.5rem; border-radius: 5px; font-weight: normal; font-size: 0.9rem; }
.slash-menu button:hover, .slash-menu button.sel { background: var(--surface); }
.slash-menu small { color: var(--muted); margin-left: 0.4rem; }
/* A described check-in reference: the comment excerpt beside the hash. */
.cref { color: var(--muted); font-size: 0.9em; }
/* The forum list: rows with anatomy — title, opener excerpt, author
   mark, and on the right the participant stack, count, and the
   activity sparkline. Threads YOU have read mute; anything with
   something new in it carries full ink. */
/* The sort links and "mark all read" share a line: one is where you
   are, the other is a sweep of the whole page's state. */
.ft-bar { display: flex; align-items: baseline; justify-content: space-between;
  gap: 1rem; margin: 1rem 0; }
/* A button that is honestly a button — it POSTs and changes state — but
   reads at the weight of the quiet text beside it. */
button.linkish { background: none; border: 0; padding: 0; cursor: pointer;
  color: var(--muted); font: inherit; font-size: 0.8rem; }
button.linkish:hover { color: var(--fg); text-decoration: underline; }
.ft-list { margin: 0.5rem 0 1rem; }
.ft-row { display: flex; align-items: center; gap: 1rem; padding: 0.55rem 0.2rem;
  border-top: 1px solid var(--rule); }
.ft-row:first-child { border-top: 0; }
/* Read rows fade UNIFORMLY. Muting only the title's link color read as
   two kinds of link — meaning must never ride on link color. The fade
   is gentle because read rows are the MAJORITY on a forum you keep up
   with: at 0.62 a page you had merely kept current with looked
   disabled. */
.ft-row.dim { opacity: 0.78; }
.ft-row.dim:hover { opacity: 1; }
.ft-main { min-width: 0; flex: 1; }
.ft-t { font-weight: 600; }
/* The title is already the obvious target — it is the biggest, boldest
   thing on the row and the whole row leads to it — so at rest it wears
   the page's ink and lets the read/unread fade be the only signal it
   carries. The link color arrives on hover, WHERE HOVER EXISTS: a
   touch device would otherwise be left with the tap-emulated hover
   stuck on the last title tapped. :active pays the affordance back to
   touch, which never gets the hover state at all. */
.ft-t a { color: inherit; text-decoration: none;
  -webkit-tap-highlight-color: transparent; }
@media (hover: hover) {
  .ft-t a:hover { color: var(--accent); text-decoration: underline; }
}
.ft-t a:active { color: var(--accent); text-decoration: underline; }
.ft-score { font-size: 0.8rem; color: var(--accent); margin-left: 0.3rem; }
.ft-x { margin: 0.15rem 0 0; color: var(--muted); font-size: 0.9rem;
  overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* A sentence, not a row. As a flex container every bare text run
   between the elements — " · started ", " · last reply " — became its
   own anonymous flex item, and with the default nowrap a narrow screen
   shrank each item until its text wrapped INSIDE it. The result was the
   words stacked in columns rather than the line wrapping once. Normal
   flow wraps it the way prose wraps. */
.ft-meta { margin: 0.25rem 0 0; color: var(--muted); font-size: 0.8rem; }
/* The pieces that must not be split mid-way: a name and its mark are
   one thing, and a date is one thing. Wrapping happens BETWEEN them. */
.ft-meta .who, .ft-meta time { white-space: nowrap; }
.ft-meta .idn { width: 14px; height: 14px; }
.ft-side { flex: none; display: flex; align-items: center; gap: 0.75rem; color: var(--muted); }
.ft-stack { display: inline-flex; }
.ft-stack .idn { width: 18px; height: 18px; border-radius: 5px;
  outline: 2px solid var(--bg); margin-left: -5px; }
.ft-stack .idn:first-child { margin-left: 0; }
.ft-count { font-size: 0.85rem; font-variant-numeric: tabular-nums; min-width: 1.4rem; text-align: right; }
.ft-spark { color: var(--accent); }
@media (max-width: 40rem) { .ft-side { display: none; } }
/* Bar actions are rounded SQUARES; the account stays a circle — a
   button is a thing you do, an avatar is who you are. Icons render at
   full size in the page's ink, not the avatar's small caption size. */
.bar-btn { flex: none; width: 2rem; height: 2rem; padding: 0;
  border-radius: 6px; background: none; border: 1px solid var(--rule);
  color: var(--muted); cursor: pointer; display: inline-flex;
  align-items: center; justify-content: center; }
/* GitHub's header grammar: rest is quiet (muted ink, hairline border),
   hover is a FILL, and keyboard focus gets a real ring — the hover
   affordance and the focus affordance are different signals. */
.bar-btn:hover { background: var(--code-bg); border-color: var(--rule); color: var(--fg); }
.bar-btn:focus-visible, .avatar:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.bar-btn .ic { width: 1rem; height: 1rem; vertical-align: 0; }
a.inboxbtn { position: relative; }
/* The unread badge: a count, not a mystery dot. It informs and holds
   still — no pulse, no animation. */
#inbox-dot { display: none; }
#inbox-dot.on { display: block; position: absolute; top: -0.35rem; right: -0.35rem;
  min-width: 1rem; height: 1rem; padding: 0 0.2rem; box-sizing: border-box;
  border-radius: 999px; background: var(--accent); color: var(--bg);
  font-size: 0.65rem; font-weight: 700; line-height: 1rem; text-align: center; }
/* Toasts (RFC 0011 §5). A stack in the corner, above everything, that
   dismisses ITSELF: the animation is the timer, so no script holds a
   handle on a page that may be left open for a day. The keyframes hold
   the toast still for its whole readable life and only then fade, and
   visibility: hidden at the end takes it out of the tab order as well
   as out of sight. Pointer events stay off the container so an empty
   corner never eats a click on the page beneath it. */
#toasts { position: fixed; right: 1rem; bottom: 1rem; z-index: 50;
  display: flex; flex-direction: column; gap: 0.5rem;
  max-width: min(24rem, calc(100vw - 2rem)); pointer-events: none; }
#toasts .toast { pointer-events: auto; background: var(--bg);
  border: 1px solid var(--rule); border-left: 3px solid var(--accent);
  border-radius: 6px; padding: 0.5rem 0.7rem; box-shadow: 0 2px 10px rgb(0 0 0 / 0.18);
  animation: toast-life 9s forwards; }
#toasts .toast a { font-weight: 600; }
#toasts .toast small { display: block; color: var(--muted); }
#toasts .attn-reason { font-weight: 600; }
/* The banner carrier for a desktop notification when banners are off:
   it exists to hold one expression and must never be seen. */
#toasts .attn-notify { display: none; }
/* The inbox's own list of what was addressed to this account. A plain
   list (Principle 3): the reason, when, and the words underneath. */
.attn-rows { list-style: none; margin: 0.4rem 0; padding: 0; }
.attn-row { padding: 0.4rem 0; border-bottom: 1px solid var(--rule); }
.attn-row:last-child { border-bottom: 0; }
.attn-row.unread .attn-reason { font-weight: 600; }
.attn-summary { color: var(--muted); }
.attn-head { font-size: 0.95rem; margin: 1rem 0 0.2rem; }
@keyframes toast-life { 0%, 88% { opacity: 1; } 100% { opacity: 0; visibility: hidden; } }
/* Reduced motion still needs the dismissal — it is the toast's whole
   lifecycle, not decoration — so the fade becomes a cut. */
@media (prefers-reduced-motion: reduce) {
  #toasts .toast { animation: toast-cut 9s forwards; }
  @keyframes toast-cut { 0%, 99% { opacity: 1; } 100% { opacity: 0; visibility: hidden; } }
}
/* A link dressed as a button, matching the button rule above — for
   "new thread"-style actions that are navigations, not submissions. */
a.btn { display: inline-block; background: var(--code-bg); color: var(--fg);
  border: 1px solid var(--rule); border-radius: 6px; padding: 0.35rem 0.55rem;
  font-weight: 600; text-decoration: none; }
a.btn:hover { border-color: var(--fg); }
/* a.btn is element+class and outranks .btn-primary, so every primary
   ANCHOR button in the forge quietly rendered as a plain one — the New
   ticket call to action included. Matched here rather than by reordering,
   which the next rule appended below would silently undo again. */
a.btn.btn-primary { background: var(--accent); color: var(--bg);
  border-color: var(--accent); }
a.btn.btn-primary:hover { border-color: var(--accent); filter: brightness(1.1); }
.fleet-count { margin: 0 0 0.5rem; }
.input-group { display: inline-flex; align-items: center; min-width: 0;
  border: 1px solid var(--rule); border-radius: 6px; background: var(--bg); }
.input-group:focus-within { outline: 2px solid var(--muted); outline-offset: 1px; }
.input-group > input { flex: 1 1 auto; min-width: 0; border: 0; background: none;
  border-radius: 6px; }
.input-group > input:focus-visible { outline: none; }
.clearq { flex: none; color: var(--muted); text-decoration: none; font-size: 1.05rem;
  line-height: 1; padding: 0 0.5rem; }
.clearq:hover { color: var(--fg); }
/* select keeps its native disclosure arrow — replacing it costs a
   hand-drawn caret that has to be redrawn for both themes. */
.readme-head { margin-top: 1.5rem; padding-bottom: 0.3rem;
  border-bottom: 1px solid var(--rule); font-size: 1rem; }
/* Each entry is one unit — a pill with its count inside — rather than a
   word and a loose number. Loose numbers made every repository's nav a
   different shape and, with a wide count, a different number of lines.
   "here" is a filled pill rather than a colour so it survives both
   themes and does not depend on hue perception; "empty" is dimmed but
   still a link. */
/* The nav is the ONLY thing in the bar allowed to shrink, and it
   shrinks by scrolling, never by pushing: the … button sits outside it
   and is always whole. This is the structural guarantee behind every
   width — a surprising repo name or count can at worst make the tabs
   swipeable, exactly GitHub's mobile behavior. */
.repobar nav { display: flex; flex-wrap: nowrap; gap: 0.9rem; margin-left: auto;
  min-width: 0; flex: 0 1 auto; overflow-x: auto; scrollbar-width: none; }
.repobar nav::-webkit-scrollbar { display: none; }
.navmore-btn { flex: none; }
nav a { display: inline-flex; align-items: baseline; gap: 0.3rem;
  padding: 0.15rem 0.55rem; border-radius: 999px; text-decoration: none;
  border: 1px solid transparent; }
nav a:hover { border-color: var(--rule); }
nav a.here { font-weight: 600; background: var(--surface); border-color: var(--rule); }
nav a.empty { color: var(--muted); }
/* The repobar and explore navs are underline TABS, not pills: the bar
   is a row of places, and GitHub taught everyone what that looks like.
   The underline element carries a view-transition-name, so on browsers
   with cross-document view transitions (Chrome 126+, Safari 18.2+) the
   highlight glides from the old tab to the new one across the page
   load; everywhere else navigation is simply instant. */
.repobar nav a, nav.tabs a { border-radius: 0; border: 0; padding: 0.45rem 0.1rem;
  border-bottom: 2px solid transparent; background: none; color: var(--muted);
  position: relative; }
.repobar nav a:hover, nav.tabs a:hover { border-color: transparent; color: var(--fg); }
.repobar nav a.here, nav.tabs a.here { background: none; border: 0; font-weight: 600;
  color: var(--fg); border-bottom: 2px solid transparent; }
.ink { position: absolute; left: 0; right: 0; bottom: 0; height: 2px;
  background: var(--accent); border-radius: 1px; }
.repobar nav a.here .ink { view-transition-name: repo-tab; }
nav.tabs a.here .ink { view-transition-name: explore-tab; }
nav.doc-tabs a.here .ink { view-transition-name: doc-tab; }
@view-transition { navigation: auto; }
@media (prefers-reduced-motion: reduce) { @view-transition { navigation: none; } }
/* The bars are ISOLATED from the root crossfade: identical on both
   sides of a navigation, so their groups render static instead of
   flashing with the page — the fixed chrome fading in and out was most
   of what read as "weird". Everything else is kept brisk: at 0.4s a
   crossfade is an effect, at 0.15s it is a page load. */
.topbar { view-transition-name: topbar; }
.repobar { view-transition-name: repobar; }
footer { view-transition-name: sitefooter; }
::view-transition-group(*) { animation-duration: 0.15s; }
/* Only the chrome animates — the orange underline slides, the bars hold
   still. The root snapshot does NOT cross-fade: two translucent copies
   of a dark page over a dark backdrop dip in brightness mid-fade, which
   reads as a flash on every slow navigation. Content just swaps. */
::view-transition-old(root), ::view-transition-new(root) { animation: none; }
/* The collapse, GRADUATED: each tier folds at its own width and the …
   menu reveals exactly the tier the bar just hid — a landscape phone
   keeps six tabs and folds two; a portrait phone keeps three. All-at-
   once hiding read as wrong precisely there. Measured collapse needs
   script; tiers are what owning the layout costs in pure CSS. */
/* Fixed square, self-centered: sized by its own box rather than by the
   bar's baseline alignment, which squashed it once it left the nav. */
.navmore-btn { display: none; align-items: center; justify-content: center;
  width: 1.9rem; height: 1.9rem; padding: 0; align-self: center;
  border: 1px solid var(--rule); border-radius: 6px;
  background: none; color: var(--muted); cursor: pointer;
  anchor-name: --navmore; }
.navmore-btn .ic { width: 1rem; height: 1rem; }
.menu.navmore .m1, .menu.navmore .m2, .menu.navmore .m3 { display: none; }
@media (max-width: 62rem) {
  .repobar nav a.aux1:not(.here) { display: none; }
  .navmore-btn { display: inline-flex; }
  .menu.navmore .m1 { display: block; }
  /* An active folded tab stays out of the drawer — selected, visible —
     and wiki (the last tier standing) yields its place for it. */
  .repobar nav:has(a.aux1.here, a.aux2.here) a.aux3:not(.here) { display: none; }
  .repobar nav:has(a.aux3.here) a.aux2:not(.here) { display: none; }
}
@media (max-width: 52rem) {
  .repobar nav a.aux2:not(.here) { display: none; }
  .menu.navmore .m2 { display: block; }
}
@media (max-width: 44rem) {
  .repobar nav a.aux3:not(.here) { display: none; }
  .menu.navmore .m3 { display: block; }
  /* A surfaced drawer tab needs the room a core tab was using: tickets
     yields. The row must NEVER exceed the viewport — an overflowing
     bar drags the whole page sideways — and the clip below is the hard
     guarantee behind these yields. */
  .repobar nav:has(a.aux1.here, a.aux2.here, a.aux3.here) a.yield:not(.here) { display: none; }
}
/* The drawer never lists the tab that is currently OUT of it. */
.menu.navmore span:has(a.here) { display: none !important; }
.menu.navmore a { display: flex; border-radius: 6px; padding: 0.3rem 0.6rem; }
.menu.navmore a.here { background: var(--surface); border: 0; font-weight: 600; }
@supports (anchor-name: --a) {
  .menu.navmore { position-anchor: --navmore; inset: auto; top: anchor(bottom);
    right: anchor(right); margin-top: 0.3rem; }
}
nav .n { color: var(--muted); font-size: 0.75rem; font-variant-numeric: tabular-nums;
  background: var(--code-bg); border-radius: 999px; padding: 0 0.35rem; }
nav a.here .n { background: var(--bg); }
.repo-sub { color: var(--muted); font-size: 0.9rem; margin: -0.6rem 0 1rem; }
.newrepo { margin: 0 0 0.8rem; }
.about { margin: -0.3rem 0 0.8rem; color: var(--fg); }
/* Red and green are the same two tokens the diff uses. They were
   literals with the dark pair behind an unguarded media query, so an
   explicit light choice on a dark-mode device drew the dark red on the
   light ground — the same defect the highlight had. */
.danger-head { color: var(--del); }
.danger { border: 1px solid var(--del); border-radius: 4px; padding: 0.2rem 0.9rem; }
.danger form + form { border-top: 1px solid var(--rule); margin-top: 0.6rem; }
/* The listing's numeric and date columns take only what they need, so
   the description and tip get the width instead of "Check-ins" wrapping
   into two lines beside a mostly-empty row. */
table.fleet th, table.fleet td { vertical-align: top; }
/* The name column takes the slack; the numeric ones take only what
   they need and never wrap. Right-aligned tabular figures line up down
   the page by construction — which a per-row grid could not do. */
table.fleet td.r-name { width: 100%; }
table.fleet th.n, table.fleet td.n { text-align: right; white-space: nowrap;
  width: 1%; padding-left: 0.9rem; font-variant-numeric: tabular-nums;
  color: var(--muted); }
table.fleet td.n.last { color: var(--fg); }
table.fleet th.n { padding-bottom: 0.2rem; }
/* The pair reads as one entry: no rule between a name and its
   description, the rule goes under the description instead. */
table.fleet tr.r-top td { padding-top: 0.5rem; border-top: 1px solid var(--code-bg); }
table.fleet tr.r-desc td { padding: 0 0 0.15rem; color: var(--muted);
  font-size: 0.9rem; border: 0; }
table.fleet tr.r-desc + tr.r-top td { border-top: 1px solid var(--code-bg); }
@media (max-width: 30rem) {
  /* A phone has room for the name and three numbers, not four. Mirror
     freshness is the most specialised of them and the first to go — the
     repository page still reports it. Tighter gutters, and a long name
     may wrap rather than push the table into a sideways scroll. */
  table.fleet th.n, table.fleet td.n { padding-left: 0.5rem; }
  table.fleet td.r-name { white-space: normal; overflow-wrap: anywhere; }
  table.fleet th.n:nth-child(4), table.fleet td.n:nth-child(4) { display: none; }
}
.ci-pass { border-color: var(--add); color: var(--add); }
.ci-fail { border-color: var(--del); color: var(--del); }
/* Ticket fields are label/value pairs, so a dl says what they are and
   escapes the global table rules that banded every label with a border.
   The label column sizes to its own widest label instead of a fixed
   10rem: fossil ticket schemas are arbitrary, so the widest label is
   whatever this repository's tracker defines. Values may be 40-char
   hashes, which must wrap rather than push the page sideways. */
dl.tkt-head {
  display: grid; grid-template-columns: minmax(0, max-content) minmax(0, 1fr);
  gap: 0.3rem 1rem; margin: 0.8rem 0;
}
dl.tkt-head dt { color: var(--muted); font-size: 0.9rem; }
dl.tkt-head dd { margin: 0; min-width: 0; overflow-wrap: anywhere; }
.tkt-id { overflow-wrap: anywhere; }
.tkt-body { margin: 0.5rem 0 1rem; }
.tkt-comment { border-top: 1px solid var(--rule); padding: 0.6rem 0; }
.tkt-comment:first-of-type { border-top: 0; }
/* The ticket editor: body and timeline left, metadata right; one
   column on a phone with the metadata after the body. */
.tkt-layout { display: grid; grid-template-columns: minmax(0, 1fr) 17rem; gap: 0 2.5rem; align-items: start; }
.tkt-side { font-size: 0.9rem; }
.tkt-fields { display: grid; gap: 0.65rem; margin: 0 0 1rem; }
.tkt-fields label { display: grid; gap: 0.2rem; }
.tkt-fields select, .tkt-fields input { width: 100%; box-sizing: border-box; font: inherit; }
.tkt-k { color: var(--muted); font-size: 0.8rem; text-transform: capitalize; }
.tkt-v { padding: 0.2rem 0; }
.tkt-meta { color: var(--muted); font-size: 0.82rem; border-top: 1px solid var(--rule); padding-top: 0.6rem; }
.tkt-event { border-top: 1px solid var(--rule); padding: 0.4rem 0; color: var(--muted); font-size: 0.9rem; }
.tkt-event b { color: var(--fg); font-weight: 600; }
.tkt-remark .f-reply-foot { align-items: center; }
.tkt-edit { margin: 0 0 1rem; }
.tkt-edit > summary { color: var(--muted); font-size: 0.85rem; cursor: pointer; width: max-content; }
.tkt-edit[open] > summary { margin-bottom: 0.5rem; }
.tkt-retitle { margin-top: -0.5rem; }
.tkt-retitle form { display: flex; gap: 0.5rem; }
.tkt-retitle input { flex: 1; font: inherit; }
.tkt-close { display: inline-flex; align-items: center; gap: 0.35rem; color: var(--muted); font-size: 0.85rem; }
.tkt-close select { font: inherit; }
@media (max-width: 52rem) {
  .tkt-layout { grid-template-columns: minmax(0, 1fr); }
  .tkt-side { border-top: 1px solid var(--rule); padding-top: 0.75rem; margin-top: 1rem; }
}
.tl-badge { border: 1px solid var(--rule); border-radius: 3px; padding: 0 0.25rem; font-size: 0.72rem; }
.tl-pill { display: inline-block; border: 1px solid var(--rule); border-radius: 6px;
  padding: 0.05rem 0.5rem; font-weight: bold; margin: 0.55rem 0 0.25rem; }
/* Filter controls wrap as WHOLE units: a label never separates from
   its select, a branch chip never breaks mid-name. The chip is
   GitHub's dismissible filter token — the name truncates before the ×
   detaches. */
/* GRID, not flex: one line is structural. fit-content is GitHub's
   branch-selector rule in one function — sized to its label, capped
   (12rem), and clamped to the space the other two leave, so the row
   cannot overflow whatever the branch is called and a short name gets
   a short control. */
.tl-controls { color: var(--muted); font-size: 0.9rem; display: grid;
  grid-template-columns: fit-content(12rem) max-content max-content;
  gap: 0.5rem; align-items: center; margin-bottom: 0.4rem; max-width: 100%; }
.tl-controls select { min-width: 0; max-width: 100%; }
/* The fleet bar's first grid cell is a FORM holding field and sort;
   left as a block it stacks them. Flex puts them on the one line the
   grid promised, with the New repository link beside them. */
.fleet-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem 0.75rem; }
.fleet-bar > form { display: flex; align-items: center; gap: 0.5rem; min-width: 0; }
.tl-chip { display: inline-flex; align-items: center; gap: 0.35rem; min-width: 0;
  max-width: 100%; border: 1px solid var(--rule); border-radius: 999px;
  padding: 0.1rem 0.6rem; background: var(--surface); white-space: nowrap; }
.tl-chip b { overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
  max-width: min(14rem, 55vw); }
.tl-chip a { text-decoration: none; }
.repobar nav a.cog { display: inline-flex; align-self: center; padding: 0.45rem 0.1rem; }
/* Group labels are help text, shown where there is room for help. */
.tl-help { color: var(--muted); font-size: 0.8rem; }
@media (max-width: 40rem) { .tl-help { display: none; } }
pre { overflow-x: auto; background: var(--code-bg); padding: 0.5rem; border-radius: 4px; }
/* A plaintext DOCUMENT (a license, an old-school README) is prose that
   happens to be monospace — it reads straight off the page, not out of
   a code box. Fenced code inside markdown keeps the box. */
pre.plaindoc { background: none; padding: 0; border-radius: 0; }
pre.diff .add { color: var(--add); } pre.diff .del { color: var(--del); }
pre.diff .hunk { color: var(--muted); } pre.diff .head { font-weight: bold; }
/* Content can contain tokens no viewport fits — a hash, a URL, a wiki
   page literally named "checkin/2cbbabdf5ef624d809fbb40d2d312a29".
   Unbroken they push the whole page sideways, so a phone scrolls to
   read anything. break-word rather than anywhere: it breaks only when a
   word genuinely does not fit, leaving ordinary prose alone. <pre>
   keeps its own horizontal scroll, which is correct for code. */
main { overflow-wrap: break-word; }
/* A date is one token to a reader: breaking "2020-12-19T13:20:19" across
   two lines makes it unreadable and is what content-driven wrapping does
   to it by default. */
time { white-space: nowrap; }

/* A ticket list is read title-first. A table gave the 10-character id
   its own column and left the title the narrowest one on a phone; this
   gives the title the full width and demotes id/status/date to a meta
   line under it. Same shape at every width — no breakpoint to diverge. */
/* Columns that scroll independently: a board's whole value is seeing
   the states side by side, so the page must not grow to the tallest
   column and make the reader scroll past one to reach another. On a
   phone the columns stack, because four 80px columns are not a board. */
/* The board never widens the page. Open columns share the row with a
   16rem floor and wrap past it — a second row beats a sideways scroll
   that hides the columns that matter. Empty columns fold to strips
   (GitHub's collapsed column), which is what keeps a seven-status
   vocabulary on one row in the common case. */
/* The board is a canvas, not prose: it is the one view that leaves the
   reading column and takes the window. The controls above it keep the
   column so they line up with every other page. A column has ONE width
   (GitHub's 350px, here 22rem) so a card is the same object wherever
   it sits; the board is what varies — columns fold, and past the
   window they wrap. The controls leave the column with it, so the
   board's left edge and its filters line up (GitHub does the same). */
main.board-page { max-width: none; }
.board { display: flex; flex-wrap: wrap; gap: 0.8rem; align-items: stretch; padding-bottom: 0.4rem; }
.board-col { flex: 0 0 22rem; min-width: 0; border: 1px solid var(--rule); border-radius: 8px;
  background: var(--surface); padding: 0.6rem; }
.board-col.folded { flex: 0 0 auto; padding: 0.5rem 0.35rem; display: flex; align-items: flex-start;
  justify-content: center; }
.board-col.folded h3 { margin: 0; writing-mode: vertical-rl; transform: rotate(180deg);
  display: flex; align-items: center; gap: 0.4rem; }
.board-col.folded .unfold { text-decoration: none; color: inherit; display: inline-flex;
  align-items: center; gap: 0.4rem; }
/* Rotated, a pill becomes an oval: the strip names the column in
   plain text, the pill's colour kept, its box dropped. */
.board-col.folded .t-status { border: 0; background: none; padding: 0; border-radius: 0;
  font-weight: 600; letter-spacing: 0.02em; }
.board-col.folded .unfold:hover .t-status { text-decoration: underline; }
/* The chevron is the one control a column has: fold on an open one,
   open on a strip. Same glyph family, same spot, both directions. */
.board-col h3 .fold { margin-left: auto; color: var(--muted); text-decoration: none; padding: 0 0.3rem;
  border-radius: 4px; font-size: 1.1rem; line-height: 1; }
.board-col h3 .fold:hover { color: var(--fg); background: var(--bg); }
.board-col.folded .chev { color: var(--muted); font-size: 1.1rem; }
/* Sticky: in a 38-card column the header is the answer to "which
   column am I in" once the top has scrolled away. */
.board-col h3 { position: sticky; top: 0; z-index: 1; background: var(--surface);
  margin: 0 0 0.5rem; padding: 0.1rem 0; font-size: 0.9rem; display: flex; align-items: center;
  gap: 0.4rem; }
.board-col h3 .n { color: var(--muted); font-size: 0.8rem; font-variant-numeric: tabular-nums; }
/* A lane is a horizontal cut across the same columns. The heading is
   sticky because the whole point of a lane is knowing which one you are
   reading while you scroll down a long one. */
.lane-h { position: sticky; top: 0; z-index: 1; margin: 1.2rem 0 0.4rem;
  font-size: 0.85rem; text-transform: uppercase; letter-spacing: 0.06em;
  color: var(--muted); background: var(--bg); padding: 0.3rem 0;
  display: flex; align-items: center; gap: 0.4rem; }
.lane-h .lane-name { color: var(--fg); }
.fieldrow { display: grid; gap: 0.6rem 1rem; margin: 0 0 1rem;
  grid-template-columns: repeat(auto-fit, minmax(11rem, 1fr)); }
.fieldrow label { font-size: 0.9rem; }
.fieldrow input { width: 100%; box-sizing: border-box; }
.board-axes { display: flex; gap: 1rem; align-items: center; flex-wrap: wrap;
  margin: 0 0 0.8rem; font-size: 0.85rem; color: var(--muted); }
.board-trunc { color: var(--muted); font-size: 0.8rem; }
.board-axes select { font-size: 0.85rem; padding: 0.15rem 0.3rem; }
/* Drag: the grip and the cursor say a card moves; the card dims while
   it is in the air; the column under the pointer lights up, which is
   the answer to "where will this land". */
.board .card[draggable="true"] { cursor: grab; }
.board .card.held { opacity: 0.5; cursor: grabbing; }
.board .card .grip { float: right; color: var(--muted); font-size: 1rem; line-height: 1; margin-left: 0.4rem;
  user-select: none; }
.board-col.over { outline: 2px dashed var(--accent); outline-offset: -2px; }
/* The last move, with its undo, sits above the columns. */
.board-moved { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem;
  border: 1px solid var(--rule); border-left: 3px solid var(--accent); border-radius: 6px;
  padding: 0.4rem 0.6rem; margin: 0 0 0.8rem; font-size: 0.9rem; }
.board-moved form { display: contents; }
.board-moved button { font-size: 0.8rem; padding: 0.15rem 0.5rem; }
/* The Move menu: one button, a popover of the other columns. */
.board .card .t-meta { display: flex; align-items: center; gap: 0.35rem; flex-wrap: wrap; }
.board .card .t-id { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.8rem; color: var(--muted); }
.board .card .mv-btn { margin-left: auto; font-size: 0.75rem; padding: 0.15rem 0.5rem; font-weight: 600; }
.board .card .mv-btn .caret { font-size: 0.7em; }
@supports (anchor-name: --a) {
  .menu.mv { top: anchor(bottom); right: anchor(right); margin-top: 0.3rem; min-width: 9rem; }
}
/* Triage badges. Same weight as the metadata line — they are for
   scanning a column, not for shouting. */
.t-badges { display: flex; flex-wrap: wrap; gap: 0.25rem; margin-top: 0.35rem; }
/* The landing page's About block and document tabs. The aside reads
   as a sidebar where there is room and as a header card where there is
   not; the tab strip is the scopes idiom, already legible everywhere. */
/* minmax(0, 1fr), never a bare 1fr. A 1fr track carries min-width:auto,
   so it cannot shrink below its content's min-content width — and the
   feed contains a segmented control that must not wrap. The track grew
   to fit it, the document went wider than the phone, and every heading
   and the pager ran off the right edge. Capping the chips at 100% did
   nothing, because 100% was by then the width of the overgrown track:
   the floor has to be removed at the track, not patched at the child. */
.dash { display: grid; gap: 1.6rem; grid-template-columns: minmax(0, 1fr); }
.dash-side, .dash-feed { min-width: 0; }
@media (min-width: 64rem) {
  /* Two columns, not three: "your recent work" was the feed filtered to
     one author, and a whole column to express one predicate is a column
     that is empty for most accounts. */
  .dash { grid-template-columns: 20rem minmax(0, 1fr); align-items: start; }
}
/* The band that leads the page. It renders only when something is
   actually waiting, so the landing page never opens with an empty
   promise. */
.dash-band { margin-bottom: 1.8rem; }
.aw-row { display: grid; grid-template-columns: auto minmax(0, 1fr);
  gap: 0.55rem; align-items: start; }
.aw-row .t-glyph { margin-top: 0.2rem; }
.dash-more { margin: 0.7rem 0 0; font-size: 0.9rem; }
.dash-act { margin: 1rem 0 0; }
.dash-find { margin: 0 0 0.4rem; }
.dash-find input { width: 100%; }
/* The open-work count beside a repository: a link, because the number
   is only useful if it takes you to what it counts. */
a.dash-open { float: right; font-size: 0.78rem; color: var(--muted);
  text-decoration: none; border: 1px solid var(--rule);
  border-radius: 999px; padding: 0 0.45rem; }
a.dash-open:hover { color: var(--accent); border-color: var(--accent); }
h2.t-view { font-size: 1rem; margin: 0; font-weight: 600; }
/* The wiki's structure panel: two short lists, side by side when there
   is room, under the page list where the reader has finished scanning. */
.w-struct { display: grid; gap: 1.6rem; margin-top: 2rem;
  padding-top: 1.2rem; border-top: 1px solid var(--rule); }
@media (min-width: 48rem) { .w-struct { grid-template-columns: 1fr 1fr; } }
.w-struct h2 { font-size: 0.85rem; margin: 0 0 0.5rem; color: var(--muted);
  text-transform: uppercase; letter-spacing: 0.05em; }
ul.w-links { list-style: none; margin: 0; padding: 0; }
/* The count sits BESIDE its label, not flung to the far edge. With
   space-between it ended 496px from the name it belonged to, in a 595px
   row, which reads as two unrelated columns. */
ul.w-links > li { padding: 0.3rem 0; display: flex; gap: 0.5rem;
  align-items: baseline; flex-wrap: wrap; }
ul.w-links a { text-decoration: none; }
ul.w-links a:hover { text-decoration: underline; }
.w-n { font-size: 0.78rem; color: var(--muted); }
.w-struct h2 a { color: inherit; text-decoration: none; }
.w-struct h2 a:hover { color: var(--accent); }
.w-struct-links { display: inline-flex; align-items: center; gap: 0.8rem;
  margin-left: auto; font-size: 0.85rem; }
.w-struct-links a { text-decoration: none; color: var(--muted); }
.w-struct-links a:hover { color: var(--accent); text-decoration: underline; }
.w-lead { color: var(--muted); font-size: 0.9rem; max-width: 62ch;
  margin: 0.2rem 0 1.1rem; }
ul.w-links-full > li { padding: 0.45rem 0; border-bottom: 1px solid var(--rule);
  display: block; }
.w-link-t { font-weight: 600; }
/* Who reached for the name. A wanted page without its askers is a to-do
   item with no brief. */
.w-from { display: block; font-size: 0.82rem; color: var(--muted);
  margin-top: 0.15rem; }
/* Saving a report: a name box under the rail, quiet enough that it does
   not compete with the views themselves. */
.t-rail-save { display: flex; gap: 0.3rem; margin-top: 1.2rem; }
.t-rail-save input { min-width: 0; flex: 1; font-size: 0.85rem; }
.t-rail-save button { font-size: 0.85rem; }
.t-rail-sec li { display: flex; align-items: center; }
.t-rail-sec li > a { flex: 1; min-width: 0; }
.t-rail-x button { background: none; border: 0; color: var(--muted);
  cursor: pointer; padding: 0 0.25rem; line-height: 1; }
.t-rail-x button:hover { color: var(--del); }
.dash-depth { margin: 0.5rem 0 0; font-size: 0.85rem; color: var(--muted);
  text-align: center; }
/* A landing: the record, then what it would change, then the talking.
   Branch names are code because they are identifiers people retype. */
.l-meta { margin: -0.4rem 0 1rem; color: var(--muted); display: flex; gap: 0.5rem;
  align-items: center; flex-wrap: wrap; }
code.l-branch { background: var(--surface); border: 1px solid var(--rule);
  border-radius: 5px; padding: 0 0.35rem; }
.l-desc { margin: 0.6rem 0 1.4rem; }
.l-desc > :first-child { margin-top: 0; }
.l-cis { margin-bottom: 1.4rem; }
/* A blocked proposal states the obstacle and whose move it is. Loud
   enough to stop a reader reaching for a control that cannot work. */
.l-block { border: 1px solid var(--del); border-radius: 8px;
  padding: 0.8rem 1rem; margin: 0 0 1.4rem; }
.l-block strong { color: var(--del); }
/* Not a failure, just a record that has been overtaken: stated in the
   page's own voice rather than in the red of something broken. */
.l-note { border: 1px solid var(--rule); border-radius: 8px;
  padding: 0.8rem 1rem; margin: 0 0 1.4rem; background: var(--surface); }
.l-note p { margin: 0.3rem 0 0; color: var(--muted); }
.l-paths { margin: 0.4rem 0; }
ol.l-events { list-style: none; margin: 0 0 1.4rem; padding: 0;
  border-left: 2px solid var(--rule); }
.l-ev { padding: 0.35rem 0 0.35rem 0.9rem; color: var(--muted); }
.l-ev strong { color: var(--fg); }
.l-ev-accepted { border-left: 2px solid var(--accent); margin-left: -2px; }
.l-commits h2, .l-diff h2, .l-talk h2 { font-size: 1rem; color: var(--muted);
  text-transform: uppercase; letter-spacing: 0.05em; margin: 1.6rem 0 0.6rem; }
.l-why { margin: 1.2rem 0 0.4rem; color: var(--muted); }
/* Collapsed by default: the summary is a control, so it reads as one. */
.l-changes > summary { cursor: pointer; list-style: none; display: flex;
  align-items: baseline; gap: 0.5rem; padding: 0.5rem 0; }
.l-changes > summary::-webkit-details-marker { display: none; }
.l-changes > summary::before { content: "\25b8"; color: var(--muted);
  transition: transform 0.12s; }
.l-changes[open] > summary::before { content: "\25be"; }
.l-sum { font-size: 1rem; color: var(--muted); text-transform: uppercase;
  letter-spacing: 0.05em; }
.l-n { color: var(--muted); font-size: 0.9rem; }
/* A disabled decision reads as disabled, not as a dimmer accent: the
   accent drains out, the outline goes dashed, and the reason beside it
   is what carries the colour. Half-opacity orange on a dark ground
   looked like a button that was merely tired. */
.f-reply-foot button[disabled] { opacity: 0.6; cursor: not-allowed; background: transparent; color: var(--muted); border: 1px dashed var(--muted); }
/* The filter strip SCROLLS; it does not widen the page. nav.seg-box
   sets flex-wrap: nowrap and beats .dash-chips's wrap on specificity,
   so on a phone the four chips could neither wrap nor shrink and forced
   the document wider than the viewport — which is why the pager looked
   broken and every heading ran off the right edge. Nothing was wrong
   with the pager: it was being measured against a page 40px too wide.
   A segmented control must not wrap (its rounded ends would repeat mid
   row), so the strip is given its own scroll instead. */
.dash-chips { margin-bottom: 0.6rem; max-width: 100%; overflow-x: auto;
  overscroll-behavior-x: contain; }
.dash-chips .n { color: var(--muted); }
.dash-chips .here .n { color: inherit; }
.dash h2 { font-size: 1rem; margin: 0 0 0.6rem; color: var(--muted);
  text-transform: uppercase; letter-spacing: 0.05em; }
.dash .tl-badge { margin-right: 0.35rem; }
/* The dashboard styles its own lists. It used to borrow ul.tickets,
   so when the tracker became a bordered card the dashboard grew three
   boxes it never asked for — a shared class is a shared fate. */
ul.dash-list { list-style: none; margin: 0.2rem 0 0; padding: 0; }
ul.dash-list > li { padding: 0.5rem 0; border-top: 1px solid var(--rule); }
ul.dash-list > li:first-child { border-top: 0; }
/* Weight is a signal, and a page where every line is bold has spent it.
   A repository NAME is a label and keeps some — it is what you scan the
   sidebar for. A feed entry is a sentence; it gets none, and stays
   findable by being the link on its row. */
a.dash-title { font-weight: 500; color: var(--fg); text-decoration: none; }
.dash-feed a.dash-title { font-weight: 400; }
/* Two lines, then stop. One landing comment ran to fifteen lines on a
   phone and WAS the viewport — a feed entry is a pointer to the thing,
   and the thing is one tap away. Clamping is CSS-only, so with styles
   off the full text is still there rather than cut by the server. */
.dash-feed a.dash-title { display: -webkit-box; -webkit-line-clamp: 2;
  -webkit-box-orient: vertical; overflow: hidden; }
a.dash-title:hover { color: var(--accent); text-decoration: underline; }
.dash-meta { margin-top: 0.15rem; font-size: 0.85rem; color: var(--muted); }
.dash-meta a { color: inherit; }
.dash-meta a:hover { color: var(--accent); }
/* GitHub's latest-commit bar: one line, the message eats the slack and
   truncates; the hash/date/count block never wraps. On a phone the
   message yields entirely and the bar keeps author + date, exactly the
   collapse GitHub makes. */
.tip-bar { display: flex; align-items: center; gap: 0.6rem; min-width: 0;
  border: 1px solid var(--rule); border-radius: 8px; background: var(--surface);
  padding: 0.45rem 0.75rem; margin: 0 0 0.6rem; font-size: 0.9rem; }
.tip-user { font-weight: 600; flex: none; }
.tip-msg { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
  color: var(--muted); text-decoration: none; }
.tip-msg:hover { color: var(--accent); text-decoration: underline; }
.tip-right { flex: none; margin-left: auto; color: var(--muted); display: inline-flex;
  align-items: center; gap: 0.35rem; white-space: nowrap; }
.tip-right a { color: var(--muted); text-decoration: none; display: inline-flex;
  align-items: center; gap: 0.3rem; }
.tip-right a:hover { color: var(--accent); }
@media (max-width: 44rem) {
  .tip-bar .tip-msg, .tip-bar .tip-hash { display: none; }
}
/* On a phone the stats strip stops being a card and becomes GitHub's
   wrapping row of inline facts, closing the About flow above the
   branch bar. */
@media (max-width: 44rem) {
  .repo-stats { border: 0; background: none; padding: 0.2rem 0 0.6rem;
    border-bottom: 1px solid var(--rule); border-radius: 0; }
}
/* GitHub's About sidebar, borne on Gitea's literal frame: a real grid,
   not a float — a float squeezes the bars sharing its rows until their
   contents collide. Column 1 holds every bar, table and document;
   column 2 is the sidebar, spanning all rows. One column where there
   is no room, and the aside is FIRST in source order, so the phone
   reads description → facts → branch bar → files, exactly as GitHub
   and Forgejo order it. */
.repo-home { display: grid; grid-template-columns: minmax(0, 1fr); }
.repo-home > * { grid-column: 1; min-width: 0; }
.about-card { margin: 0.4rem 0 0.6rem; font-size: 0.9rem; }
@media (min-width: 64rem) {
  .repo-home.has-about { grid-template-columns: minmax(0, 1fr) 17rem; gap: 0 2.5rem; }
  .repo-home.has-about > .about-card { grid-column: 2; grid-row: 1 / span 40; margin: 0.4rem 0 0; }
}
.about-h { font-size: 1rem; margin: 0 0 0.5rem; }
.about-h a { color: var(--fg); text-decoration: none; }
.about-h a:hover { text-decoration: underline; }
.about-desc { margin: 0 0 0.6rem; color: var(--fg); }
.topics { display: flex; flex-wrap: wrap; gap: 0.35rem; margin: 0.65rem 0 0.75rem; }
a.b-pill { color: inherit; text-decoration: none; }
a.b-pill:hover { border-color: var(--fg); color: var(--fg); }
.about-row { display: flex; align-items: center; gap: 0.5rem; margin: 0;
  padding: 0.22rem 0; color: var(--muted); text-decoration: none; min-width: 0; }
.about-row .ic { flex: none; }
/* A wrapping title starts level with its icon rather than centred
   against the whole block, and its later lines stay in the text
   column. Notes and Announcement carry real titles; the icon rows
   above them are all one line, where this is indistinguishable. */
.about-row:has(strong) { align-items: baseline; }
.about-row strong { min-width: 0; }
.about-row span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
a.about-row:hover { color: var(--accent); }
a.about-row:hover span { text-decoration: underline; }
.about-link { color: var(--accent); font-weight: 600; }
.about-div { border-top: 1px solid var(--rule); margin: 0.9rem 0; }
.about-tag a { color: var(--fg); text-decoration: none; }
.about-tag a:hover { text-decoration: underline; }
.latest-pill { border: 1px solid var(--add); color: var(--add); border-radius: 999px;
  padding: 0 0.5rem; font-size: 0.75rem; line-height: 1.5; }
.about-sub { margin: 0 0 0.2rem 1.5rem; font-size: 0.85rem; color: var(--muted); }
.about-sub a { color: var(--accent); text-decoration: none; }
.about-sub a:hover { text-decoration: underline; }
.doc-tabs { display: flex; flex-wrap: wrap; gap: 0.2rem 1rem; margin: 1.4rem 0 0;
  border-bottom: 1px solid var(--rule); font-size: 0.95rem; }
nav.doc-tabs a { padding: 0.3rem 0.1rem; border: 0; border-bottom: 2px solid transparent;
  border-radius: 0; background: none; color: var(--muted); text-decoration: none; }
nav.doc-tabs a.here { color: var(--fg); background: none; border: 0;
  border-bottom: 2px solid transparent; font-weight: 600; }
nav.doc-tabs a { position: relative; }
.doc-panel { margin-top: 1rem; }
/* The structured diff: gutters own the numbers and the +/- marker so
   selection copies clean code; the mark class is the intra-line "what
   actually changed" emphasis; syntax classes come from the chroma
   stylesheet already on the page (.dtab carries .chroma). */
.dtab { border-collapse: collapse; width: 100%; font: 0.85rem/1.45 ui-monospace, monospace; }
.dtab td { padding: 0 0.5rem 0 0; vertical-align: top; }
.dnum { user-select: none; text-align: right; color: var(--muted); min-width: 3ch;
  font-variant-numeric: tabular-nums; padding-left: 0.4rem; }
.dmark { user-select: none; width: 1ch; color: var(--muted); }
tr.d-addition .dmark::before { content: "+"; }
tr.d-deletion .dmark::before { content: "-"; }
tr.d-addition, .dcell.d-addition { background: var(--add-row); }
tr.d-deletion, .dcell.d-deletion { background: var(--del-row); }
.dcode { white-space: pre-wrap; overflow-wrap: anywhere; width: 100%; }
tr.d-addition .dm, .dcell.d-addition .dm { background: var(--add-mark); border-radius: 2px; }
tr.d-deletion .dm, .dcell.d-deletion .dm { background: var(--del-mark); border-radius: 2px; }
/* Side-by-side: two half-width code cells; a side with no counterpart
   is a hatched void, fossil's idiom for "nothing here". */
.dtab.split .dcell { white-space: pre-wrap; overflow-wrap: anywhere; width: 50%;
  padding-right: 0.5rem; border-left: 1px solid var(--rule); padding-left: 0.4rem; }
.dcell.d-void { background: repeating-linear-gradient(45deg, transparent, transparent 4px,
  var(--surface) 4px, var(--surface) 8px); }
.hunkhead { color: var(--muted); font: 0.8rem/1.4 ui-monospace, monospace;
  padding: 0.35rem 0.5rem; border-top: 1px solid var(--rule); background: var(--surface); }
.filediff { margin: 1.2rem 0; border: 1px solid var(--rule); border-radius: 8px; overflow: hidden; }
/* Side-by-side halves the room each line gets, so the split view earns
   what GitHub gives it: the diff breaks out of the page column and
   takes the viewport, 2rem margins aside. 50% - 50vw walks from the
   centred column's edge to the viewport's. Only once the viewport is
   actually wider than the column — below that the breakout is a no-op
   that still moves pixels. */
@media (min-width: 80rem) {
  .filediff.wide { margin-left: calc(50% - 50vw + 2rem);
    margin-right: calc(50% - 50vw + 2rem); }
}
.filediff-head { margin: 0; padding: 0.5rem 0.75rem; font-size: 0.95rem;
  background: var(--surface); }
.diffcount { font-weight: 600; margin: 1rem 0 0.3rem; }
.diffmore { color: var(--muted); font-size: 0.9rem; margin: 1rem 0; text-align: center; min-height: 1.5rem; }
/* Segmented toggle (GitHub's "Unified | Split"): one bordered group,
   buttons joined, the current one filled. Overrides nav a's pill. */
nav.toggle { display: inline-flex; margin: 0.6rem 0 0.8rem; border: 1px solid var(--rule);
  border-radius: 6px; overflow: hidden; font-size: 0.9rem; }
nav.toggle a { border: 0; border-radius: 0; padding: 0.3rem 0.8rem; color: var(--fg);
  line-height: 1.25; }
nav.toggle a + a { border-left: 1px solid var(--rule); }
nav.toggle a:hover { background: var(--surface); }
nav.toggle a.here { background: var(--surface); font-weight: 600; }
/* The pager, shared by the people list and windowed diffs. GitHub's
   pagination shape: bordered buttons either side of a position
   readout; a disabled end keeps its place, muted, so nothing shifts
   between pages. nav a's pill rule is overridden per button. */
nav.pager { display: flex; align-items: center; justify-content: center; gap: 0.4rem;
  margin: 0.8rem 0 1rem; font-size: 0.9rem; flex-wrap: wrap; }
nav.pager a.pager-btn, nav.pager span.pager-btn { display: inline-block; padding: 0.3rem 0.8rem; border-radius: 6px;
  border: 1px solid var(--rule); text-decoration: none; color: var(--fg); line-height: 1.25;
  white-space: nowrap; }
nav.pager a.pager-btn:hover { background: var(--surface); border-color: var(--muted); }
nav.pager .pager-btn[aria-disabled="true"] { color: var(--muted); border-color: transparent;
  pointer-events: none; }
nav.pager .pager-where { color: var(--muted); padding: 0 0.6rem; font-variant-numeric: tabular-nums; }
nav.pager .pager-where b { color: var(--fg); font-weight: 600; }
/* The message leads the page but is not a headline (no forge makes it
   one — its length is untrusted). wrap-anywhere: a 2000-character
   unbroken line is real data, not a layout veto. */
/* The header names the page (GitHub's "Commit abc123"); the message
   sits below it as content in a quiet box, subject bolded — unless the
   first line is too long to be a subject, in which case it is a
   paragraph and renders like one. wrap-anywhere throughout: a
   2000-character unbroken line is real data, not a layout veto. */
.ci-h { font-size: 1.4rem; font-weight: 600; margin: 0 0 0.2rem;
  display: flex; align-items: center; flex-wrap: wrap; gap: 0.4rem; }
/* The full hash: its own line, wrapping anywhere, because 64 unbroken
   characters have no break opportunity of their own and would push a
   narrow page sideways. */
.ci-fullhash { margin: 0 0 0.75rem; font-size: 0.78rem; color: var(--muted);
  overflow-wrap: anywhere; }
/* Both of these sit inside 1.4rem display type, so their icons are
   sized in REM rather than em — at 1em the glyph would inherit the
   heading and render half again too large. */
.ci-copy { background: none; border: 0; color: var(--muted); cursor: pointer;
  padding: 0.15rem; line-height: 1; display: inline-flex; align-items: center; }
.ci-copy .ic { width: 0.95rem; height: 0.95rem; vertical-align: 0; }
.ci-copy:hover { color: var(--accent); }
/* A 28x22 button is a fine SIGHT and a poor TARGET: a thumb wants
   44px. The hit area is grown with a pseudo-element rather than with
   padding, so the button keeps its size next to the hash and only the
   reachable part changes — and only where the pointer is coarse. */
@media (pointer: coarse) {
  .ci-copy { position: relative; }
  .ci-copy::after { content: ""; position: absolute; top: 50%; left: 50%;
    width: 44px; height: 44px; transform: translate(-50%, -50%); }
}
.ci-copy.done { color: var(--add); }
.ci-tags { display: inline-flex; gap: 0.35rem; flex-wrap: wrap; }
.ci-tag { display: inline-flex; align-items: center; gap: 0.25rem;
  font-size: 0.72rem; font-weight: 500; line-height: 1.3;
  border: 1px solid var(--rule); border-radius: 999px; padding: 0.1rem 0.5rem;
  color: var(--muted); background: var(--surface); white-space: nowrap; }
.ci-tag .ic { width: 0.85rem; height: 0.85rem; vertical-align: 0; }
a.ci-tag { text-decoration: none; }
a.ci-tag:hover { color: var(--accent); border-color: var(--accent); }
/* Tag history. A log read forwards, so the STANDING rows must read as
   current and the overruled ones as past without a legend doing all the
   work: struck text and reduced contrast say "superseded" on sight. */
.ct-back { margin: 0 0 0.9rem; font-size: 0.9rem; }
.ct-h { font-size: 1.05rem; margin: 1.4rem 0 0.5rem; }
.ct-flag { font-size: 0.72rem; text-transform: uppercase; letter-spacing: 0.06em;
  border: 1px solid var(--del); color: var(--del); border-radius: 999px;
  padding: 0.05rem 0.5rem; font-weight: 600; }
.ct-was { margin: 0.5rem 0 0; font-size: 0.85rem; color: var(--muted); }
.ct-waslabel { text-transform: uppercase; letter-spacing: 0.07em; font-size: 0.7rem;
  font-weight: 600; margin-right: 0.35rem; }
table.ct { width: 100%; border-collapse: collapse; font-size: 0.85rem; }
table.ct th { text-align: left; font-weight: 600; color: var(--muted);
  font-size: 0.72rem; text-transform: uppercase; letter-spacing: 0.06em;
  padding: 0.3rem 0.7rem 0.4rem 0; border-bottom: 1px solid var(--rule); white-space: nowrap; }
table.ct td { padding: 0.4rem 0.7rem 0.4rem 0; border-bottom: 1px solid var(--rule);
  vertical-align: top; }
.ct-when { white-space: nowrap; color: var(--muted); font-variant-numeric: tabular-nums;
  font-size: 0.8rem; }
.ct-src, .ct-sign { white-space: nowrap; }
.ct-val { overflow-wrap: anywhere; }
.ct-none { color: var(--muted); font-style: italic; }
.ct-gone { color: var(--muted); }
.ct-gone .ct-val, .ct-gone .ct-name code { text-decoration: line-through; }
.sg { display: inline-block; min-width: 1.1rem; text-align: center; font-weight: 700;
  font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
.sg-add { color: var(--add); }
.sg-del { color: var(--del); }
.sg-prop { color: var(--accent); }
table.mf { width: 100%; border-collapse: collapse; font-size: 0.88rem; }
table.mf td { padding: 0.45rem 0.8rem 0.45rem 0; border-bottom: 1px solid var(--rule);
  vertical-align: baseline; }
.mf-l { width: 1.6rem; }
.mf-l code { font-weight: 700; color: var(--accent); }
.mf-t { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.82rem;
  overflow-wrap: anywhere; }
.mf-n { color: var(--muted); font-size: 0.82rem; white-space: normal; min-width: 12rem; }
@media (max-width: 40rem) {
  table.mf, table.mf tbody, table.mf tr, table.mf td { display: block; width: auto; }
  table.mf tr { border-bottom: 1px solid var(--rule); padding: 0.5rem 0; }
  table.mf td { border: 0; padding: 0.05rem 0; }
  .mf-l { display: inline-block; margin-right: 0.4rem; }
  .mf-t { display: inline; }
}
.mf-files { margin: 1.2rem 0 0; display: flex; flex-wrap: wrap; gap: 0.5rem;
  align-items: baseline; }
.mf-why { color: var(--muted); font-size: 0.85rem; }
.mf-note { color: var(--muted); font-size: 0.83rem; margin: 1rem 0 0; max-width: 62ch; }
.dv-mode { margin: 0 0 0.5rem; font-size: 0.95rem; }
.ct-legend { font-size: 0.82rem; color: var(--muted); margin: 0.8rem 0 0; max-width: 62ch; }
/* A person, as one target: the mark and the name move together, and
   the whole thing takes the page's link colour on hover — the same
   affordance the hash and the branch beside it already have. */
/* A byline inside a row that is ITSELF a link stays plain — the docs
   list and the wiki home card are whole-card anchors, and an anchor
   inside an anchor is invalid: the parser closes the outer one at the
   inner, which tore those rows in half. The row already goes
   somewhere; a second target inside it was never the right idea.

   INLINE, not inline-flex. A flex box is atomic: it cannot flow with
   the text around it, so as a byline it stopped wrapping mid-phrase and
   jumped to a line of its own — which is what it did to the docs list,
   where every row grew a second line. The mark is aligned by the
   baseline rule .idn already carries. */
a.who { color: inherit; text-decoration: none; border: 0; padding: 0;
  white-space: nowrap; }
a.who:hover { color: var(--accent); }
a.who:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.tl-filter { margin: 0 0 0.6rem; font-size: 0.9rem; color: var(--muted);
  display: flex; align-items: center; gap: 0.45rem; flex-wrap: wrap; }
/* Patch is an ACTION, not a third view, so it stands outside the
   segmented toggle and borrows the pager button's shape. */
.ci-patch { display: inline-flex; align-items: center; gap: 0.3rem;
  margin: 0.6rem 0 0.8rem 0.5rem; padding: 0.3rem 0.7rem; font-size: 0.9rem;
  line-height: 1.25; border: 1px solid var(--rule); border-radius: 6px;
  color: var(--fg); text-decoration: none; vertical-align: top; }
.ci-patch .ic { width: 0.95rem; height: 0.95rem; vertical-align: 0; }
.ci-patch:hover { background: var(--surface); border-color: var(--muted); }
/* Counts read as a pair, so they hold their column: tabular numerals
   stop a list of files jittering line to line. */
.ci-stat { font-size: 0.8rem; font-weight: 400; font-variant-numeric: tabular-nums;
  white-space: nowrap; }
.ci-add { color: var(--add); }
.ci-del { color: var(--del); }
.ci-box { margin: 0 0 0.9rem; }
.ci-sub { font-weight: 600; margin: 0; overflow-wrap: anywhere; }
.ci-sub.long { font-weight: 400; }
.ci-msg { white-space: pre-wrap; overflow-wrap: anywhere;
  margin: 0.6rem 0 0; color: var(--muted); }
/* The changed-files list wears the files page's clothes: icon + name
   as one label, no underline until hover, the change kind sitting
   where the listing puts its sizes. */
.difffiles { list-style: none; padding: 0; margin: 0 0 0.8rem; }
.difffiles li { display: flex; align-items: center; gap: 0.5rem;
  padding: 0.15rem 0.2rem; line-height: 1.45; }
.difffiles li:hover { background: var(--surface); }
.difffiles a { text-decoration: none; display: inline-flex; align-items: center;
  gap: 0.45rem; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
.difffiles a:hover { text-decoration: underline; }
.difffiles .tl-badge { margin-left: auto; }
.b-pill { font-size: 0.7rem; padding: 0.05rem 0.35rem; border-radius: 999px;
  border: 1px solid var(--rule); color: var(--muted); white-space: nowrap; }
.b-pill.b-pri { border-color: var(--accent); color: var(--accent); }
.t-badges span { font-size: 0.7rem; padding: 0.05rem 0.35rem; border-radius: 999px;
  border: 1px solid var(--rule); color: var(--muted); white-space: nowrap; }
.t-badges .b-pri { border-color: var(--accent); color: var(--accent); }
.board .card { background: var(--bg); border: 1px solid var(--rule); border-radius: 6px;
  padding: 0.5rem; margin-bottom: 0.5rem; }
.board .card .t-title { display: block; font-weight: 600; overflow-wrap: anywhere; }
.board .card .t-meta { margin-top: 0.2rem; }
/* The move control is deliberately always present, never revealed by
   script: it is how a touch or keyboard reader moves a card, and any
   drag layer is an addition on top of it. */
/* On a phone the open columns stack full-width and the folded ones
   become a row of chips above them. The earlier design kept a swiped
   row here; a page that scrolls sideways was judged worse than a board
   that reads as stacked lists, which it is on any phone-sized screen. */
@media (max-width: 40rem) {
  .board { gap: 0.5rem; }
  .board-col { flex: 1 1 100%; }
  .board-col.folded { flex: 0 0 auto; order: -1; padding: 0.3rem 0.5rem; }
  .board-col.folded h3 { writing-mode: horizontal-tb; transform: none; }
}
/* ---- wiki ---------------------------------------------------------
   Rails beside the page on wide screens, page alone on narrow ones.
   Dropped rather than stacked on a phone: a dozen sibling links and a
   contents above the text push the text itself below the fold, and
   both rails lead only where the page already leads. */
/* Two widths, not one. Running text caps at the measure because that
   is what reading wants; a code block, a table or a diagram gets the
   whole column, because wrapping those to prose width is what makes
   people scroll sideways. The column then sizes to the CONTENT rather
   than eating the viewport — at 1800px the article ended 391px short of
   the contents rail, which is not breathing room, it is a hole. */
.w-doc { --measure: 62ch; --column: 78ch;
  display: grid; grid-template-columns: minmax(0, 1fr); gap: 1.5rem; }
/* The track list follows the rails that are actually THERE. A doc page
   has no sibling rail and a short page has no contents, and a grid that
   reserves a column for a rail nobody rendered puts the document itself
   in the 11.5rem gutter. */
@media (min-width: 64rem) {
  /* Left-aligned, not centred. Centring indented the block away from
     the page title, which sits outside the grid — on a doc page the
     heading started at 392px and its own first paragraph at 495px,
     which reads as two columns that missed each other. The leftover
     goes to the page edge, where every other page in the forge puts it.

     The contents track is reserved WHETHER OR NOT a page has contents.
     Sizing it to what each page happens to hold made the prose jump
     sideways every time a reader clicked from a page with headings to
     one without — the text should sit where it sat, and an empty track
     costs nothing but the space it was always going to occupy. The
     left rail still follows :has, because a doc page has no siblings
     to list and reserving a gutter for nothing is a different mistake. */
  .w-doc { grid-template-columns: minmax(0, var(--column)) 12.5rem; }
  .w-doc:has(.w-rail) {
    grid-template-columns: 11.5rem minmax(0, var(--column)) 12.5rem; }
  /* A page with NEITHER rail centres instead. The rule above is left-
     aligned for one specific reason — the layout's h1 sits outside the
     grid, so centring the block left the heading and its own first
     paragraph starting a hundred pixels apart. A notes page draws its
     heading INSIDE the column (OwnH1), so nothing is left behind to
     miss, and the reserved-but-empty contents track that keeps prose
     from jumping sideways between doc pages has nothing to hold still
     for. Without this the column strands itself against the left edge
     under a wide empty margin, which is not how the rest of the forge
     lays a page out. */
  .w-doc.w-solo { grid-template-columns: minmax(0, var(--column));
    justify-content: center; }
}
.w-rail, .w-toc { display: none; }
@media (min-width: 64rem) { .w-rail, .w-toc { display: block; } }
.w-railhead { font-size: 0.7rem; text-transform: uppercase;
  letter-spacing: 0.07em; color: var(--muted); font-weight: 600;
  margin: 0 0 0.4rem; }
.w-rail ul, .w-toc ul { list-style: none; margin: 0; padding: 0; }
.w-rail a { display: block; padding: 0.2rem 0.45rem; border-radius: 6px;
  text-decoration: none; color: var(--fg); font-size: 0.85rem;
  overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.w-rail a:hover { background: var(--surface); }
.w-rail a.here { background: var(--surface); font-weight: 600; }
/* No ring on these two. A box drawn around a wrapped three-line entry
   reads as a defect, and the rails are dense enough that colour alone
   carries the state. Focus still SHOWS — it borrows the accent the
   current entry uses — because a keyboard reader who cannot see where
   they are is worse off than one looking at an ugly outline. */
.w-rail a:focus-visible, .w-toc a:focus-visible { outline: none; }
.w-rail a:focus-visible { background: var(--surface); color: var(--accent); }
.w-toc a:focus-visible { color: var(--accent); border-left-color: var(--accent); }
.w-railall { color: var(--muted) !important; }
.w-crumb { font-size: 0.82rem; color: var(--muted); margin: 0 0 0.5rem; }
.w-crumb a { text-decoration: none; }
.w-by { font-size: 0.82rem; color: var(--muted); margin: 0 0 1.1rem;
  padding-bottom: 0.6rem; border-bottom: 1px solid var(--rule); }
/* THE measure. Running text at the full content width came out around
   152 characters a line, roughly twice the comfortable maximum, which
   is the single thing most wrong with reading a long page here. */
.w-main article > * { max-width: var(--measure); }
/* The exceptions: content whose lines are authored, not flowed. */
.w-main article > pre,
.w-main article > table,
.w-main article > .tw,
.w-main article > figure,
.w-main article > svg,
.w-main article > .pikchr { max-width: none; }
.w-main article h1:first-child { margin-top: 0; }
.w-toc { position: sticky; top: 0.6rem; align-self: start; }
.w-toc ul { border-left: 2px solid var(--rule); }
/* These rails are nav elements, and the global nav-link rule gives
   every link a 1px box with a radius that the .here rule then COLOURS
   IN. Setting only border-left left the other three sides to show up on
   the current entry as a box drawn around a wrapped label. Reset the
   box, then draw the one edge this component actually wants. */
.w-toc a { display: block; padding: 0.17rem 0.6rem; margin-left: -2px;
  border: 0; border-left: 2px solid transparent; border-radius: 0;
  background: none; text-decoration: none;
  color: var(--muted); font-size: 0.82rem; line-height: 1.35; }
.w-toc a:hover { color: var(--fg); }
.w-toc a.sub { padding-left: 1.3rem; font-size: 0.78rem; }
.w-toc a.here { color: var(--accent); border-left-color: var(--accent);
  background: none; font-weight: 600; }
/* The index. */
.w-home { display: flex; flex-wrap: wrap; align-items: baseline;
  gap: 0.3rem 0.8rem; border: 1px solid var(--rule); border-radius: 10px;
  padding: 0.7rem 0.9rem; margin: 0.2rem 0 1rem; background: var(--surface);
  text-decoration: none; color: var(--fg); }
.w-home:hover { border-color: var(--accent); }
.w-home-t { font-weight: 700; font-size: 1.02rem; }
.w-home-m { color: var(--muted); font-size: 0.82rem; margin-left: auto; }
.w-controls { display: flex; flex-wrap: wrap; align-items: center;
  gap: 0.5rem; margin: 0 0 0.9rem; }
.w-find { display: flex; align-items: center; gap: 0.4rem;
  border: 1px solid var(--rule); border-radius: 8px; background: var(--surface);
  padding: 0.1rem 0.15rem 0.1rem 0.55rem; flex: 1 1 16rem; max-width: 22rem; }
.w-find label { color: var(--muted); font-size: 0.85rem; }
.w-find input { flex: 1 1 auto; min-width: 0; border: 0; background: none;
  color: var(--fg); font: inherit; font-size: 0.9rem; padding: 0.32rem 0; }
.w-find input::placeholder { color: var(--muted); }
.w-find:focus-within { border-color: var(--accent); }
.w-pages { list-style: none; margin: 0; padding: 0; }
@media (min-width: 52rem) { .w-pages { columns: 2; column-gap: 2.2rem; } }
.w-pages li { break-inside: avoid; border-bottom: 1px solid var(--rule); }
.w-pages a { display: grid; grid-template-columns: 1fr auto auto;
  align-items: baseline; gap: 0.7rem; padding: 0.42rem 0.35rem;
  text-decoration: none; color: var(--fg); font-size: 0.92rem; }
.w-pages a:hover { background: var(--surface); }
.w-pages a:hover .w-t { color: var(--accent); }
.w-t { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.w-when { color: var(--muted); font-size: 0.78rem; white-space: nowrap; }
.w-revs { color: var(--muted); font-size: 0.72rem; background: var(--surface);
  border-radius: 999px; padding: 0 0.4rem; min-width: 2.1rem;
  text-align: center; font-variant-numeric: tabular-nums; }
.w-count { margin: 0.9rem 0 0; font-size: 0.82rem; color: var(--muted); }
/* The source marker is deliberately the quietest thing in the row: a
   reader needs it only when they want to EDIT, and until then it is
   noise between them and the title. */
.w-kind { font-size: 0.62rem; text-transform: uppercase; letter-spacing: 0.06em;
  color: var(--muted); border: 1px solid var(--rule); border-radius: 999px;
  padding: 0 0.35rem; white-space: nowrap; opacity: 0.75; }
.w-assoc { margin: 0.9rem 0 0; font-size: 0.82rem; color: var(--muted); }
/* The About sits on the surface tint rather than in a bordered card:
   it is context for what follows, not a peer of it. */
/* The context panel. A rail of hashes down the left with the message
   beside it, and the check-in you are on lifted out of the run — the
   one row that must be findable without reading. */
.ci-ctx { margin: 1.2rem 0; }
.ci-ctx h2 { font-size: 0.72rem; text-transform: uppercase;
  letter-spacing: 0.07em; color: var(--muted); font-weight: 600;
  margin: 0 0 0.5rem; }
.ci-ctx ol { list-style: none; margin: 0; padding: 0; }
.ci-ctx li { display: grid; grid-template-columns: 14px auto auto minmax(0, 1fr);
  align-items: center; gap: 0.6rem; padding: 0; }
.ci-ctx li.here { background: var(--surface); }
.ci-node { width: 14px; height: 34px; display: block; overflow: visible; }
.ci-ctx-h { text-decoration: none; }
.ci-ctx li.here .ci-ctx-h { font-weight: 600; }
.ci-ctx-m { color: var(--muted); font-size: 0.78rem; white-space: nowrap; }
.ci-ctx-c { min-width: 0; overflow: hidden; text-overflow: ellipsis;
  white-space: nowrap; font-size: 0.88rem; }
/* On a phone the row stacks: hash, then the message, then who and when.
   The drawn rail goes with it — an SVG node cannot stretch to a stacked
   row without distorting its circle, so the rule becomes a border on
   the list, which is the same line by other means. */
@media (max-width: 44rem) {
  .ci-ctx ol { border-left: 2px solid var(--rule); }
  .ci-node { display: none; }
  .ci-ctx li { grid-template-columns: minmax(0, 1fr); gap: 0.1rem;
    padding: 0.45rem 0.7rem; border-left: 2px solid transparent;
    margin-left: -2px; }
  .ci-ctx li.here { border-left-color: var(--accent); }
  .ci-ctx-c { white-space: normal; }
}
.a-note { background: var(--surface); border-radius: 10px;
  padding: 0.85rem 1rem 0.5rem; margin: 1.1rem 0; }
/* Closed, it is a one-line control rather than a banner with nothing
   in it: the padding that frames prose looks like a mistake around a
   summary on its own. */
.a-note:has(.a-note-d:not([open])) { padding: 0.45rem 1rem; }
.a-note-b > :first-child { margin-top: 0; }
.a-note-b > :last-child { margin-bottom: 0; }
/* Prose keeps a readable measure; BLOCK content takes the panel. The
   note is as wide as the page, so capping the whole body at 68ch left a
   terminal transcript clipped mid-word inside a box with room to spare
   — the width was there and nothing was allowed to use it. This is the
   same split the doc pages already make between an article and the
   figures inside it. */
.a-note-b > * { max-width: 68ch; }
.a-note-b > pre, .a-note-b > table, .a-note-b > .tw, .a-note-b > figure,
.a-note-b > svg, .a-note-b > .pikchr, .a-note-b > blockquote { max-width: none; }
/* A note carries arbitrary prose, including a command line longer than
   a phone. Its own scroll container, so the PAGE never moves sideways —
   the same treatment rendered tables already get. */
.a-note-b pre { overflow-x: auto; }
.a-note-b code { overflow-wrap: anywhere; }
.a-note-d > summary { cursor: pointer; font-size: 0.78rem; color: var(--muted);
  text-transform: uppercase; letter-spacing: 0.06em; font-weight: 600;
  list-style: none; }
.a-note-d > summary::-webkit-details-marker { display: none; }
.a-note-d > summary::before { content: "\25b8"; display: inline-block;
  margin-right: 0.4rem; transition: transform 0.12s; }
.a-note-d[open] > summary::before { transform: rotate(90deg); }
.a-note-d > summary:hover { color: var(--fg); }
.a-note-d[open] > summary { margin-bottom: 0.6rem; }
@media (prefers-reduced-motion: reduce) {
  .a-note-d > summary::before { transition: none; }
}
.a-note-f { margin: 0.6rem 0 0; font-size: 0.78rem; color: var(--muted); }
.a-note-f a { color: var(--muted); text-decoration: none; }
.a-note-f a:hover { color: var(--accent); text-decoration: underline; }

/* The tracker header is ONE line: which lives are listed on the left,
   how they are drawn and the one action on the right. Stacked, the four
   controls read as four unrelated decisions; in a row they read as the
   axes of a single view, which is what they are. */
.t-head { display: flex; flex-wrap: wrap; align-items: center;
  gap: 0.4rem 1rem; margin: 0.2rem 0 0.8rem; }
.t-tools { display: flex; flex-wrap: wrap; align-items: center;
  gap: 0.5rem; margin-left: auto; }
/* The filter bar is ONE line. The segmented control is the page's
   navigation and cannot shrink; the action beside it can, so below the
   width where both fit it keeps its icon and drops its words. Letting
   the row wrap instead pushed the action onto a line of its own, which
   reads as a second toolbar. */
.act-icon { display: inline-flex; align-items: center; gap: 0.35rem; }
.act-icon .ic { flex: none; }
@media (max-width: 30rem) {
  /* The row wraps, but the state filter is always FIRST and whole:
     it is how a reader says what they are looking at. Where a page
     carries more tool groups than fit beside it (the tracker has three
     and a button), those move to the next line instead. A page whose
     tools do fit — the landings list, one icon — still keeps one line. */
  .t-head { flex-wrap: wrap; gap: 0.4rem 0.5rem; }
  .t-head > nav.seg-box:first-child { flex: none; }
  .act-icon .act-label { display: none; }
  .act-icon { padding-left: 0.55rem; padding-right: 0.55rem; }
  /* nowrap alone would push the action off the side rather than fit
     it: the control is a hair too wide at 390px once the icon is
     beside it. The choices give up the padding, not the words —
     shortening them would cost the reader more than the whitespace. */
  .t-head nav.seg-box a { padding-left: 0.45rem; padding-right: 0.45rem; }
}
/* A segmented control, not a row of loose pills: the choices along one
   axis share a box and butt against each other, so the group reads as
   "pick one of these three" before a single word is read. Loose pills
   read as three unrelated links, which is what they were. */
/* The dividers are GAPS, not borders. A border-right per item is the
   single-row idiom and it breaks the moment the strip wraps: the item
   ending a row keeps a divider that lands against the container edge,
   the last item overall has none, and nothing rules between the rows.
   Measured at 390px this strip is three rows, so wrapping is the normal
   case, not the exception.
   
   Letting the container's colour show through a 1px gap draws every
   divider the layout actually needs — vertical between neighbours,
   horizontal between rows — with no rule knowing where a row ends. */
/* A segmented control is ONE control, so it never breaks mid-way: with
   wrap, a squeezed bar dropped its last choice onto a line of its own
   ("99 All" below "30 Open | 69 Closed"), which reads as a stray button
   rather than as part of the set. It keeps its line; the tools BESIDE
   it are what give way. */
nav.seg-box { display: inline-flex; flex-wrap: nowrap; align-items: stretch;
  gap: 1px; background: var(--rule);
  border: 1px solid var(--rule); border-radius: 8px; overflow: hidden; }
nav.seg-box a { border: 0; border-radius: 0; margin: 0;
  padding: 0.35rem 0.7rem; background: var(--bg); }
nav.seg-box a:hover { background: var(--surface); }
nav.seg-box a.here { background: var(--surface); font-weight: 600; }
/* The report row: six native selects that read as one control strip.
   A set axis is outlined in accent so "why am I only seeing four
   tickets" is answerable by looking rather than by reading the URL. */
.t-filters { display: flex; flex-wrap: wrap; align-items: center;
  gap: 0.4rem; margin: 0 0 0.6rem; }
/* The query box, sized so a real report fits without scrolling inside
   it: "is:closed subsystem:web crash" is the shape people type. */
.t-search { display: flex; align-items: center; gap: 0.25rem;
  border: 1px solid var(--rule); border-radius: 8px;
  background: var(--surface); padding: 0.1rem 0.15rem 0.1rem 0.5rem;
  margin: 0 0 0.5rem; max-width: 34rem; }
.t-search-label { color: var(--muted); font-size: 0.85rem; }
.t-search input { flex: 1 1 auto; min-width: 0; border: 0; background: none;
  color: var(--fg); font: inherit; font-size: 0.9rem; padding: 0.3rem 0; }
.t-search input::placeholder { color: var(--muted); }
.t-search:focus-within { border-color: var(--accent); }
.t-filter { display: inline-flex; align-items: center; gap: 0.3rem;
  border: 1px solid var(--rule); border-radius: 8px;
  padding: 0.15rem 0.45rem; background: var(--surface);
  font-size: 0.85rem; color: var(--muted); }
.t-filter > span { text-transform: lowercase; }
.t-filter select { border: 0; background: none; color: var(--fg);
  font: inherit; font-size: 0.85rem; padding: 0.1rem 0; max-width: 11rem; }
.t-filter.on { border-color: var(--accent); color: var(--accent); }
.t-filter.on select { color: var(--accent); font-weight: 600; }
.t-clear { font-size: 0.85rem; }
/* The dense scan. Rows are for COMPARING here, not reading, so the
   type scale drops and the columns stay narrow enough that an eye can
   run down one without tracking sideways. */
table.t-table { width: 100%; border-collapse: collapse; font-size: 0.9rem; }
table.t-table th { text-align: left; font-weight: 600; white-space: nowrap;
  border-bottom: 1px solid var(--rule); }
table.t-table th a { text-decoration: none; color: var(--muted);
  display: inline-block; padding: 0.4rem 0.5rem; }
table.t-table th a:hover { color: var(--fg); }
table.t-table td { padding: 0.4rem 0.5rem; border-bottom: 1px solid var(--code-bg);
  white-space: nowrap; }
table.t-table tr:hover td { background: var(--surface); }
table.t-table .ord { color: var(--accent); }
table.t-table td.c-title { white-space: normal; min-width: 18rem; }
table.t-table td.c-title a { color: var(--fg); text-decoration: none; font-weight: 600; }
table.t-table td.c-title a:hover { color: var(--accent); text-decoration: underline; }
/* The id is a link because fossil readers reach for it, but the title
   beside it already goes to the same place: underlining both draws two
   lines per row and neither means anything the other does not. */
table.t-table td.c-id a { text-decoration: none; color: var(--muted); }
table.t-table td.c-id a:hover { color: var(--accent); text-decoration: underline; }
table.t-table td.c-id { white-space: nowrap; }
/* Rail beside listing on wide screens, listing alone on narrow ones.
   The rail is dropped rather than stacked on a phone: stacked, a dozen
   browse links push the tickets themselves below the fold, and the
   dropdowns above already reach every value it offers. */
.t-body { display: grid; grid-template-columns: minmax(0, 1fr); gap: 1.2rem; }
@media (min-width: 64rem) {
  .t-body { grid-template-columns: 12rem minmax(0, 1fr); }
}
.t-rail { display: none; }
@media (min-width: 64rem) { .t-rail { display: block; } }
.t-rail-sec + .t-rail-sec { margin-top: 1.1rem; }
.t-rail h2 { font-size: 0.72rem; text-transform: uppercase;
  letter-spacing: 0.06em; color: var(--muted); margin: 0 0 0.35rem;
  font-weight: 600; }
.t-rail ul { list-style: none; margin: 0; padding: 0; }
.t-rail a { display: flex; align-items: baseline; gap: 0.4rem;
  padding: 0.22rem 0.45rem; border: 0; border-radius: 6px;
  text-decoration: none; color: var(--fg); font-size: 0.88rem; }
.t-rail a:hover { background: var(--surface); border-color: transparent; }
.t-rail a.here { background: var(--surface); border-color: transparent;
  font-weight: 600; }
.t-rail .t-rail-name { flex: 1 1 auto; min-width: 0;
  overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.t-rail .n { color: var(--muted); font-size: 0.8rem; }
/* The numbered pager. Page numbers sit close together as one run so the
   eye reads them as a scale; the two step controls stand apart from it,
   and the position line sits apart again because it is a statement
   rather than a control. */
.t-pager { display: flex; align-items: center; justify-content: center;
  flex-wrap: wrap; gap: 0.25rem; margin: 0.9rem 0 0.2rem; font-size: 0.88rem; }
.t-pager a { text-decoration: none; padding: 0.3rem 0.6rem;
  border: 1px solid transparent; border-radius: 6px; color: var(--fg); }
.t-pager a:hover { background: var(--surface); border-color: var(--rule); }
.t-pager > span { color: var(--muted); padding: 0.3rem 0.5rem; }
.t-page-step { margin: 0 0.5rem; }
a.t-page-step { border-color: var(--rule); }
/* One shape for a page number, selected or not, and one way of
   centring it.

   The pager is a nav, and a global "nav a { display: inline-flex }"
   therefore applies to every page link. text-align does nothing to a
   flex container's items, so the digit sat at the flex start — hard
   left — while the CURRENT page, a span, stayed display:block and
   centred properly. Measured live: the anchors had 10.6px to the left
   of the glyph and 33.9px to the right.
   
   The boxes differed too — 0.5rem of padding and no border on the span
   against 0.6rem plus a 1px border on the anchors, 48px versus 53.2px
   for the same digit — so the highlight also changed size as the
   pointer moved. Both are settled here, for both elements. */
.t-page-n { min-width: 2rem; text-align: center;
  font-variant-numeric: tabular-nums; }
.t-pager .t-page-n { display: flex; align-items: center; justify-content: center;
  padding: 0.3rem 0.6rem; border: 1px solid transparent; }
/* Where you are is a statement, not a link — it goes nowhere, so it is
   not shaped like something that would. */
.t-page-n.here { background: var(--accent); color: var(--bg);
  border-radius: 6px; font-weight: 600; }
.t-page-gap { padding: 0.3rem 0.2rem; }
.t-pager .t-pager-at { font-variant-numeric: tabular-nums;
  margin-left: 0.75rem; }
/* Narrow: the count drops to its own line and the controls keep theirs.
   The row already wraps, but justify-content centres each wrapped line
   independently, so whatever spilled — usually "older" — landed centred
   under the numbers beside the count, reading as if it belonged to them.
   The count is a statement ABOUT the list, not a control in it, so it is
   the part that leaves. */
@media (max-width: 34rem) {
  .t-pager .t-pager-at { flex-basis: 100%; margin-left: 0; text-align: center; }
  /* And the controls are trimmed to fit one row rather than spilling a
     lone "older" onto its own. Measured at 390px: the row wanted 398px
     of a 358px container, and most of that was the number cells — 2rem
     of min-width plus padding on each. */
  .t-page-step { margin: 0 0.15rem; }
  .t-pager a { padding: 0.3rem 0.35rem; }
  /* Same selector as the rule above, or it loses on specificity and the
     numbers keep their wide padding while everything else shrinks. */
  .t-pager .t-page-n { padding: 0.3rem 0.35rem; min-width: 1.5rem; }
}
/* A row is a GRID — glyph gutter, the ticket, conversation count pinned
   right — not a paragraph. Inline spans with no box are just more
   words, which is how the type and subsystem chips ran into the title
   and into each other ("Code_Defectci"). */
/* The listing is one CARD with hairlines inside it, the shape every
   forge converged on: a bordered block says "this is the list" and its
   last row is visibly the last, where a stack of underlined paragraphs
   trails off into the footer. */
ul.tickets { list-style: none; margin: 0.2rem 0 0; padding: 0;
  border: 1px solid var(--rule); border-radius: 10px; overflow: hidden; }
li.t-row { display: grid; grid-template-columns: auto minmax(0, 1fr) auto;
  align-items: baseline; column-gap: 0.6rem;
  padding: 0.7rem 0.9rem; border-bottom: 1px solid var(--rule); }
li.t-row:last-child { border-bottom: 0; }
li.t-row:hover { background: var(--surface); }
/* An SVG's baseline is its BOTTOM edge, so a round glyph baseline-aligned
   against text floats above the title's optical centre (measured: 2.4px
   at the 16/24 body scale). Nudged, not re-aligned, so a title that wraps
   still keeps its glyph on the first line. */
.t-glyph { width: 1.05em; height: 1.05em; position: relative; top: 0.15em; }
/* State by hue, spending only tokens both themes already contrast-check:
   a fifth colour for one glyph would owe light and dark a new pair. */
.g-open { color: var(--add); }
.g-review { color: var(--accent); }
.g-done { color: var(--muted); }
.t-main { min-width: 0; display: flex; flex-wrap: wrap;
  align-items: baseline; gap: 0.3rem 0.4rem; }
a.t-title { font-weight: 600; color: var(--fg); text-decoration: none; }
a.t-title:hover { color: var(--accent); text-decoration: underline; }
.t-sub { flex-basis: 100%; font-size: 0.85rem; color: var(--muted); }
/* A chip earns its box only when it DISTINGUISHES the row (see
   ticketRows): type and subsystem read as labels, severity and priority
   speak only when they are shouting. */
.chip { font-size: 0.72rem; line-height: 1.6; padding: 0 0.5rem;
  border-radius: 999px; border: 1px solid var(--rule);
  background: var(--surface); color: var(--muted); white-space: nowrap;
  /* Centred on the flex line rather than sat on the title's baseline: a
     chip's box is taller than its text, so baseline alignment hangs it
     low. align-self needs no magic number to say "middle of the line". */
  align-self: center; }
.c-type { color: var(--fg); }
/* The tracker a row came from, on the cross-repository listing only.
   Quieter than a chip and a link in its own right: it is provenance
   first, and a way to narrow to that tracker second. */
a.t-repo { font-size: 0.72rem; color: var(--muted); text-decoration: none;
  align-self: center; white-space: nowrap; }
a.t-repo:hover { color: var(--accent); text-decoration: underline; }
.c-hot { color: var(--del); border-color: var(--del); font-weight: 600; }
/* The row's trailing cell: the conversation count and the state mark
   read as one group at the end of the row, and stay ONE grid child so
   neither can displace the other onto a line of its own. */
.t-tail { display: flex; align-items: baseline; gap: 0.5rem; }
/* Referenced-by rows read like the tracker's own list: a state glyph
   in the gutter, the name as the click target, the branch pair after. */
.tkt-refs { list-style: none; padding: 0; margin: 0 0 1.2rem; }
.tkt-refs li { display: flex; align-items: baseline; gap: 0.45rem;
  padding: 0.35rem 0; border-bottom: 1px solid var(--rule); }
.tkt-refs li:last-child { border-bottom: 0; }
.tkt-refs .ic { flex: none; }
/* A verdict a reader can follow. The badge kept its own colours; the
   link only makes it clickable, because "fail" with nowhere to go is
   the state this page was in. */
a.ci-link { text-decoration: none; border: 0; }
a.ci-link:hover .tl-badge { border-color: var(--fg); }
/* The exceptions surface. Rows are collapsed to their signature line
   and open onto the trace, because the list is for scanning and the
   trace is for one row at a time. */
.exc summary { cursor: pointer; }
.exc-sig { color: var(--muted); font-size: 0.85em; }
.exc-repo { font-size: 0.85em; }
.exc-body { padding: 0.6rem 0.8rem; border-top: 1px solid var(--rule); }
.exc-msg { margin: 0 0 0.5rem; overflow-wrap: anywhere; }
.exc-trace { max-height: 26rem; overflow: auto; font-size: 0.78rem;
  background: var(--code-bg); padding: 0.6rem 0.8rem; border-radius: 6px;
  white-space: pre; }
.t-conv { display: inline-flex; align-items: center; gap: 0.2rem;
  font-size: 0.85rem; color: var(--muted); text-decoration: none; }
.t-conv:hover { color: var(--fg); }
.t-none { color: var(--muted); }
/* Open vs resolved by weight, not hue: the palette is four variables and
   a fifth for one badge would owe both themes a contrast check. */
.t-status { font-size: 0.7rem; padding: 0.05rem 0.5rem; border-radius: 999px;
  border: 1px solid var(--rule); }
.st-open { color: var(--fg); border-color: var(--fg); font-weight: 600; }
.st-done { color: var(--muted); }
main pre { overflow-wrap: normal; }
/* A quotation had NO rule at all, so it rendered as prose the browser
   happened to indent — indistinguishable from a paragraph someone had
   tabbed. Fossil marks a quote with a rule down its side and a quieter
   voice; the bar carries the author's hue where there is one, so quoting
   a person in a thread looks like that person. */
main blockquote { margin: 0.9rem 0; padding: 0.2rem 0 0.2rem 1rem;
  border-left: 3px solid hsl(var(--uh, 0), 30%, 50%, 0.55);
  color: var(--muted); }
main blockquote > :first-child { margin-top: 0; }
main blockquote > :last-child { margin-bottom: 0; }
main blockquote blockquote { margin-left: 0.2rem; }
/* An @mention carries the same mark as the person's byline, so someone
   named in prose is recognisably the same person named anywhere else. */
a.uref .idn { width: 1em; height: 1em; vertical-align: -0.15em;
  margin-right: 0.15em; }
/* Templates wrap their tables in .tw, which scrolls. Tables that arrive
   from RENDERED CONTENT — the API doc, a wiki page, a ticket body —
   have no wrapper to put them in, and a wide one pushed the whole page
   sideways (the /docs rules column overflowed a phone by 208px). Making
   such a table its own scroll container needs no wrapper and covers
   every source of them, including markup quarry did not generate. */
main :not(.tw) > table { display: block; overflow-x: auto; max-width: 100%; }
.tw > table { display: table; }
/* The highlight is a palette token like everything else. It was a pair
   of literals with the dark one behind an UNGUARDED media query, so a
   reader who chose light on a dark-mode device got the dark highlight
   under light text: a dark block with dark text on it. Tokens follow
   the three-state rule for free, which is the point of having them. */
mark { background: var(--mark); color: var(--fg); }
</style>
<style>` + highlight.CSS() + `</style>
<script type="module" src="/assets/datastar.js" defer></script>
{{if .Composer}}<script src="/assets/composer.js" defer></script>{{end}}
{{if .WikiTOC}}<script src="/assets/wiki.js" defer></script>{{end}}
</head>
{{- /* The reference preview is armed HERE, once, and reaches every
       reference on the page by delegation (RFC 0011 §14). Arming each
       anchor instead put three copies of the same 380-character
       expression on every one of them, which a busy chat log pays for
       two hundred times over. data-ref-repo is the page's own
       repository, the context the fragment route reads a token
       against. */ -}}
<body{{if .Repo}} data-ref-repo="{{.Repo}}"{{end}}` + refDelegation + `>
<svg class="sprite" aria-hidden="true"><symbol id="i-commit" viewBox="0 0 16 16"><path d="M11.93 8.5a4.002 4.002 0 0 1-7.86 0H.75a.75.75 0 0 1 0-1.5h3.32a4.002 4.002 0 0 1 7.86 0h3.32a.75.75 0 0 1 0 1.5Zm-1.43-.75a2.5 2.5 0 1 0-5 0 2.5 2.5 0 0 0 5 0Z"/></symbol><symbol id="i-people" viewBox="0 0 16 16"><path d="M2 5.5a3.5 3.5 0 1 1 5.898 2.549 5.508 5.508 0 0 1 3.034 4.084.75.75 0 1 1-1.482.235 4 4 0 0 0-7.9 0 .75.75 0 0 1-1.482-.236A5.507 5.507 0 0 1 3.102 8.05 3.493 3.493 0 0 1 2 5.5ZM11 4a3.001 3.001 0 0 1 2.22 5.018 5.01 5.01 0 0 1 2.56 3.012.749.749 0 0 1-.885.954.752.752 0 0 1-.549-.514 3.507 3.507 0 0 0-2.522-2.372.75.75 0 0 1-.574-.73v-.352a.75.75 0 0 1 .416-.672A1.5 1.5 0 0 0 11 5.5.75.75 0 0 1 11 4Zm-5.5-.5a2 2 0 1 0-.001 3.999A2 2 0 0 0 5.5 3.5Z"/></symbol><symbol id="i-sync" viewBox="0 0 16 16"><path d="M1.705 8.005a.75.75 0 0 1 .834.656 5.5 5.5 0 0 0 9.592 2.97l-1.204-1.204a.25.25 0 0 1 .177-.427h3.646a.25.25 0 0 1 .25.25v3.646a.25.25 0 0 1-.427.177l-1.38-1.38A7.002 7.002 0 0 1 1.05 8.84a.75.75 0 0 1 .656-.834ZM8 2.5a5.487 5.487 0 0 0-4.131 1.869l1.204 1.204A.25.25 0 0 1 4.896 6H1.25A.25.25 0 0 1 1 5.75V2.104a.25.25 0 0 1 .427-.177l1.38 1.38A7.002 7.002 0 0 1 14.95 7.16a.75.75 0 0 1-1.49.178A5.5 5.5 0 0 0 8 2.5Z"/></symbol><symbol id="i-clock" viewBox="0 0 16 16"><path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Zm7-3.25v2.992l2.028.812a.75.75 0 0 1-.557 1.392l-2.5-1A.751.751 0 0 1 7 8.25v-3.5a.75.75 0 0 1 1.5 0Z"/></symbol><symbol id="i-dir" viewBox="0 0 16 16"><path d="M1.75 1A1.75 1.75 0 0 0 0 2.75v10.5C0 14.216.784 15 1.75 15h12.5A1.75 1.75 0 0 0 16 13.25v-8.5A1.75 1.75 0 0 0 14.25 3H7.5a.25.25 0 0 1-.2-.1l-.9-1.2C6.07 1.26 5.55 1 5 1H1.75Z"/></symbol><symbol id="i-file" viewBox="0 0 16 16"><path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"/></symbol><symbol id="i-branch" viewBox="0 0 16 16"><path d="M9.5 3.25a2.25 2.25 0 1 1 3 2.122V6A2.5 2.5 0 0 1 10 8.5H6a1 1 0 0 0-1 1v1.128a2.251 2.251 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.5 0v1.878A2.493 2.493 0 0 1 6 7h4a1 1 0 0 0 1-1v-.628A2.25 2.25 0 0 1 9.5 3.25Zm-6 0a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Zm8.25-.75a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5ZM4.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z"/></symbol><symbol id="i-tag" viewBox="0 0 16 16"><path d="M1 7.775V2.75C1 1.784 1.784 1 2.75 1h5.025c.464 0 .91.184 1.238.513l6.25 6.25a1.75 1.75 0 0 1 0 2.474l-5.026 5.026a1.75 1.75 0 0 1-2.474 0l-6.25-6.25A1.752 1.752 0 0 1 1 7.775Zm1.5 0c0 .066.026.13.073.177l6.25 6.25a.25.25 0 0 0 .354 0l5.025-5.025a.25.25 0 0 0 0-.354l-6.25-6.25a.25.25 0 0 0-.177-.073H2.75a.25.25 0 0 0-.25.25ZM6 5a1 1 0 1 1 0 2 1 1 0 0 1 0-2Z"/></symbol><symbol id="i-link" viewBox="0 0 16 16"><path d="m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z"/></symbol><symbol id="i-book" viewBox="0 0 16 16"><path d="M0 1.75A.75.75 0 0 1 .75 1h4.253c1.227 0 2.317.59 3 1.501A3.743 3.743 0 0 1 11.006 1h4.245a.75.75 0 0 1 .75.75v10.5a.75.75 0 0 1-.75.75h-4.507a2.25 2.25 0 0 0-1.591.659l-.622.621a.75.75 0 0 1-1.06 0l-.622-.621A2.25 2.25 0 0 0 5.258 13H.75a.75.75 0 0 1-.75-.75Zm7.251 10.324.004-5.073-.002-2.253A2.25 2.25 0 0 0 5.003 2.5H1.5v9h3.757a3.75 3.75 0 0 1 1.994.574ZM8.755 4.75l-.004 7.322a3.752 3.752 0 0 1 1.992-.572H14.5v-9h-3.495a2.25 2.25 0 0 0-2.25 2.25Z"/></symbol><symbol id="i-law" viewBox="0 0 16 16"><path d="M8.75.75V2h.985c.304 0 .603.08.867.231l1.29.736c.038.022.08.033.124.033h2.234a.75.75 0 0 1 0 1.5h-.427l2.111 4.692a.75.75 0 0 1-.154.838l-.53-.53.529.531-.001.002-.002.002-.006.006-.006.005-.01.01-.045.04c-.21.176-.441.327-.686.45C14.556 10.78 13.88 11 13 11a4.498 4.498 0 0 1-2.023-.454 3.544 3.544 0 0 1-.686-.45l-.045-.04-.016-.015-.006-.006-.004-.004v-.001a.75.75 0 0 1-.154-.838L12.178 4.5h-.162c-.305 0-.604-.079-.868-.231l-1.29-.736a.245.245 0 0 0-.124-.033H8.75V13h2.5a.75.75 0 0 1 0 1.5h-6.5a.75.75 0 0 1 0-1.5h2.5V3.5h-.984a.245.245 0 0 0-.124.033l-1.289.737c-.265.15-.564.23-.869.23h-.162l2.112 4.692a.75.75 0 0 1-.154.838l-.53-.53.529.531-.001.002-.002.002-.006.006-.016.015-.045.04c-.21.176-.441.327-.686.45C4.556 10.78 3.88 11 3 11a4.498 4.498 0 0 1-2.023-.454 3.544 3.544 0 0 1-.686-.45l-.045-.04-.016-.015-.006-.006-.004-.004v-.001a.75.75 0 0 1-.154-.838L2.178 4.5H1.75a.75.75 0 0 1 0-1.5h2.234a.249.249 0 0 0 .125-.033l1.288-.737c.265-.15.564-.23.869-.23h.984V.75a.75.75 0 0 1 1.5 0Zm2.945 8.477c.285.135.718.273 1.305.273s1.02-.138 1.305-.273L13 6.327Zm-10 0c.285.135.718.273 1.305.273s1.02-.138 1.305-.273L3 6.327Z"/></symbol><symbol id="i-shield" viewBox="0 0 16 16"><path d="M7.467.133a1.748 1.748 0 0 1 1.066 0l5.25 1.68A1.75 1.75 0 0 1 15 3.48V7c0 1.566-.32 3.182-1.303 4.682-.983 1.498-2.585 2.813-5.032 3.855a1.697 1.697 0 0 1-1.33 0c-2.447-1.042-4.049-2.357-5.032-3.855C1.32 10.182 1 8.566 1 7V3.48a1.75 1.75 0 0 1 1.217-1.667Zm.61 1.429a.25.25 0 0 0-.153 0l-5.25 1.68a.25.25 0 0 0-.174.238V7c0 1.358.275 2.666 1.057 3.86.784 1.194 2.121 2.34 4.366 3.297a.196.196 0 0 0 .154 0c2.245-.956 3.582-2.104 4.366-3.298C13.225 9.666 13.5 8.36 13.5 7V3.48a.251.251 0 0 0-.174-.237l-5.25-1.68ZM8.75 4.75v3a.75.75 0 0 1-1.5 0v-3a.75.75 0 0 1 1.5 0ZM9 10.5a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"/></symbol><symbol id="i-x" viewBox="0 0 16 16"><path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"/></symbol><symbol id="i-check" viewBox="0 0 16 16"><path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L1.72 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 11.44l6.72-6.72a.75.75 0 0 1 1.06 0Z"/></symbol><symbol id="i-praise" viewBox="0 0 16 16"><path d="M5.2 14.2c-1.5 0-2.7-1.2-2.7-2.7V7.1a.9.9 0 0 1 1.8 0v2.1a.4.4 0 0 0 .8 0V3.3a.9.9 0 0 1 1.8 0v4.4a.4.4 0 0 0 .8 0V2.2a.9.9 0 0 1 1.8 0v5.5a.4.4 0 0 0 .8 0V3.6a.9.9 0 0 1 1.8 0v7.9c0 1.5-1.2 2.7-2.7 2.7Z"/></symbol><symbol id="i-download" viewBox="0 0 16 16"><path d="M2.75 14A1.75 1.75 0 0 1 1 12.25v-2.5a.75.75 0 0 1 1.5 0v2.5c0 .138.112.25.25.25h10.5a.25.25 0 0 0 .25-.25v-2.5a.75.75 0 0 1 1.5 0v2.5A1.75 1.75 0 0 1 13.25 14Z"/><path d="M7.25 7.689V2a.75.75 0 0 1 1.5 0v5.689l1.97-1.969a.749.749 0 1 1 1.06 1.06l-3.25 3.25a.749.749 0 0 1-1.06 0L4.22 6.78a.749.749 0 1 1 1.06-1.06Z"/></symbol><symbol id="i-copy" viewBox="0 0 16 16"><path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25Z"/><path d="M5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25Zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Z"/></symbol><symbol id="i-gear" viewBox="0 0 16 16"><path d="M8 0a8.2 8.2 0 0 1 .701.031C9.444.095 9.99.645 10.16 1.29l.288 1.107c.018.066.079.158.212.224.231.114.454.243.668.386.123.082.233.09.299.071l1.103-.303c.644-.176 1.392.021 1.82.63.27.385.506.792.704 1.218.315.675.111 1.422-.364 1.891l-.814.806c-.049.048-.098.147-.088.294a6.214 6.214 0 0 1 0 .772c-.01.147.039.246.088.294l.814.806c.475.469.679 1.216.364 1.891a7.977 7.977 0 0 1-.704 1.217c-.428.61-1.176.807-1.82.63l-1.102-.302c-.067-.019-.177-.011-.3.071a5.909 5.909 0 0 1-.668.386c-.133.066-.194.158-.211.224l-.29 1.106c-.168.646-.715 1.196-1.458 1.26a8.006 8.006 0 0 1-1.402 0c-.743-.064-1.289-.614-1.458-1.26l-.289-1.106c-.018-.066-.079-.158-.212-.224a5.738 5.738 0 0 1-.668-.386c-.123-.082-.233-.09-.299-.071l-1.103.303c-.644.176-1.392-.021-1.82-.63a8.12 8.12 0 0 1-.704-1.218c-.315-.675-.111-1.422.363-1.891l.815-.806c.05-.048.098-.147.088-.294a6.214 6.214 0 0 1 0-.772c.01-.147-.038-.246-.088-.294l-.815-.806C.635 6.045.431 5.298.746 4.623a7.92 7.92 0 0 1 .704-1.217c.428-.61 1.176-.807 1.82-.63l1.102.302c.067.019.177.011.3-.071.214-.143.437-.272.668-.386.133-.066.194-.158.211-.224l.29-1.106C6.009.645 6.556.095 7.299.03 7.53.01 7.764 0 8 0Zm-.571 1.525c-.036.003-.108.036-.137.146l-.289 1.105c-.147.561-.549.967-.998 1.189-.173.086-.34.183-.5.29-.417.278-.97.423-1.529.27l-1.103-.303c-.109-.03-.175.016-.195.045-.22.312-.412.644-.573.99-.014.031-.021.11.059.19l.815.806c.411.406.562.957.53 1.456a4.709 4.709 0 0 0 0 .582c.032.499-.119 1.05-.53 1.456l-.815.806c-.081.08-.073.159-.059.19.162.346.353.677.573.989.02.03.085.076.195.046l1.102-.303c.56-.153 1.113-.008 1.53.27.161.107.328.204.501.29.447.222.85.629.997 1.189l.289 1.105c.029.109.101.143.137.146a6.6 6.6 0 0 0 1.142 0c.036-.003.108-.036.137-.146l.289-1.105c.147-.561.549-.967.998-1.189.173-.086.34-.183.5-.29.417-.278.97-.423 1.529-.27l1.103.303c.109.029.175-.016.195-.045.22-.313.411-.644.573-.99.014-.031.021-.11-.059-.19l-.815-.806c-.411-.406-.562-.957-.53-1.456a4.709 4.709 0 0 0 0-.582c-.032-.499.119-1.05.53-1.456l.815-.806c.081-.08.073-.159.059-.19a6.464 6.464 0 0 0-.573-.989c-.02-.03-.085-.076-.195-.046l-1.102.303c-.56.153-1.113.008-1.53-.27a4.44 4.44 0 0 0-.501-.29c-.447-.222-.85-.629-.997-1.189l-.289-1.105c-.029-.11-.101-.143-.137-.146a6.6 6.6 0 0 0-1.142 0ZM11 8a3 3 0 1 1-6 0 3 3 0 0 1 6 0ZM9.5 8a1.5 1.5 0 1 0-3.001.001A1.5 1.5 0 0 0 9.5 8Z"/></symbol><symbol id="i-more" viewBox="0 0 16 16"><path d="M8 9.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3ZM1.5 9.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3ZM14.5 9.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"/></symbol><symbol id="i-person" viewBox="0 0 16 16"><path d="M10.561 8.073a6.005 6.005 0 0 1 3.432 5.142.75.75 0 1 1-1.498.07 4.5 4.5 0 0 0-8.99 0 .75.75 0 0 1-1.498-.07 6.004 6.004 0 0 1 3.431-5.142 3.999 3.999 0 1 1 5.123 0ZM10.5 5a2.5 2.5 0 1 0-5 0 2.5 2.5 0 0 0 5 0Z"/></symbol><symbol id="i-sun" viewBox="0 0 16 16"><path d="M8 12a4 4 0 1 1 0-8 4 4 0 0 1 0 8Zm0-1.5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5Zm5.657-8.157a.75.75 0 0 1 0 1.061l-1.061 1.06a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734l1.06-1.06a.75.75 0 0 1 1.06 0Zm-9.193 9.193a.75.75 0 0 1 0 1.06l-1.06 1.061a.75.75 0 1 1-1.061-1.06l1.06-1.061a.75.75 0 0 1 1.061 0ZM8 0a.75.75 0 0 1 .75.75v1.5a.75.75 0 0 1-1.5 0V.75A.75.75 0 0 1 8 0ZM3 8a.75.75 0 0 1-.75.75H.75a.75.75 0 0 1 0-1.5h1.5A.75.75 0 0 1 3 8Zm13 0a.75.75 0 0 1-.75.75h-1.5a.75.75 0 0 1 0-1.5h1.5A.75.75 0 0 1 16 8ZM8 13a.75.75 0 0 1 .75.75v1.5a.75.75 0 0 1-1.5 0v-1.5A.75.75 0 0 1 8 13ZM2.343 2.343a.75.75 0 0 1 1.061 0l1.06 1.061a.751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018l-1.06-1.06a.75.75 0 0 1 0-1.06Zm9.193 9.193a.75.75 0 0 1 1.06 0l1.061 1.06a.75.75 0 0 1-1.06 1.061l-1.061-1.06a.75.75 0 0 1 0-1.061Z"/></symbol><symbol id="i-moon" viewBox="0 0 16 16"><path d="M9.598 1.591a.749.749 0 0 1 .785-.175 7.001 7.001 0 1 1-8.967 8.967.75.75 0 0 1 .961-.96 5.5 5.5 0 0 0 7.046-7.046.75.75 0 0 1 .175-.786Zm1.616 1.945a7 7 0 0 1-7.678 7.678 5.499 5.499 0 1 0 7.678-7.678Z"/></symbol><symbol id="i-auto" viewBox="0 0 16 16"><path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Z"/><path d="M8 2.5v11a5.5 5.5 0 0 0 0-11Z"/></symbol><symbol id="i-plus" viewBox="0 0 16 16"><path d="M7.75 2a.75.75 0 0 1 .75.75V7h4.25a.75.75 0 0 1 0 1.5H8.5v4.25a.75.75 0 0 1-1.5 0V8.5H2.75a.75.75 0 0 1 0-1.5H7V2.75A.75.75 0 0 1 7.75 2Z"/></symbol><symbol id="i-tkt-open" viewBox="0 0 16 16"><path d="M8 9.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"/><path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Z"/></symbol><symbol id="i-tkt-done" viewBox="0 0 16 16"><path d="M11.28 6.78a.75.75 0 0 0-1.06-1.06L7.25 8.69 5.78 7.22a.75.75 0 0 0-1.06 1.06l2 2a.75.75 0 0 0 1.06 0Z"/><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0Zm-1.5 0a6.5 6.5 0 1 0-13 0 6.5 6.5 0 0 0 13 0Z"/></symbol><symbol id="i-comment" viewBox="0 0 16 16"><path d="M1 2.75C1 1.784 1.784 1 2.75 1h10.5c.966 0 1.75.784 1.75 1.75v7.5A1.75 1.75 0 0 1 13.25 12H9.06l-2.573 2.573A1.458 1.458 0 0 1 4 13.543V12H2.75A1.75 1.75 0 0 1 1 10.25Zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h2a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 .53-.22h4.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Z"/></symbol><symbol id="i-inbox" viewBox="0 0 16 16"><path d="M2.8 2.06A1.75 1.75 0 0 1 4.41 1h7.18c.7 0 1.333.417 1.61 1.06l2.74 6.395c.04.093.06.194.06.295v4.5A1.75 1.75 0 0 1 14.25 15H1.75A1.75 1.75 0 0 1 0 13.25v-4.5c0-.101.02-.202.06-.295Zm1.61.44a.25.25 0 0 0-.23.152L1.887 8H4.75a.75.75 0 0 1 .6.3L6.625 10h2.75l1.275-1.7a.75.75 0 0 1 .6-.3h2.863L11.82 2.652a.25.25 0 0 0-.23-.152Zm10.09 7h-2.875l-1.275 1.7a.75.75 0 0 1-.6.3h-3.5a.75.75 0 0 1-.6-.3L4.375 9.5H1.5v3.75c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25Z"/></symbol></svg>
{{- /* Two bars, as forgejo does it: a full-width strip carrying the
       things that are the same everywhere — forge name, search, account
       — and, under it, the repository's own name and nav at content
       width. Before this the forge name, the repo name and the account
       links shared one line, so the row's shape changed with the length
       of whatever repository you were looking at. */ -}}
<header class="topbar"><div class="bar">
{{- /* The mark replaces the wordmark, but the LINK keeps its name: alt
       carries "quarry" so a screen reader, a text browser and a page
       with images off all still read the same word the wordmark said.
       An image with an empty alt here would leave the link unnamed. */ -}}
{{- /* The mark, drawn in the timeline's own language: a node (the bowl)
       with a rail leaving it (the tail), and the check-in dot at its
       centre. Inline SVG in currentColor, so one shape serves both
       themes and every size with no image asset and no theme swap. */ -}}
<a class="site" href="/" aria-label="quarry">
<svg class="mark" viewBox="0 0 24 24" role="img" aria-label="quarry">
<circle cx="11" cy="12" r="7.2" fill="none" stroke="currentColor" stroke-width="2.8"/>
<circle cx="11" cy="12" r="2.2" fill="currentColor"/>
<path d="M17.1 18.1 L19.2 20.2" stroke="currentColor" stroke-width="2.8" stroke-linecap="round"/>
</svg><svg class="wordmark" viewBox="0 -735 3000 735" aria-hidden="true"><path fill="currentColor" d="M394 187Q370 187 345.5 182.5Q321 178 299.0 167.5Q277 157 259.0 139.5Q241 122 229.5 100.0Q218 78 213.0 54.0Q208 30 208 5Q184 2 162.0 -7.0Q140 -16 121.5 -31.0Q103 -46 89.0 -65.5Q75 -85 66.5 -107.0Q58 -129 55.0 -152.5Q52 -176 52 -200V-535Q52 -562 56.5 -589.0Q61 -616 72.5 -641.0Q84 -666 102.5 -686.5Q121 -707 145.0 -720.0Q169 -733 196.0 -738.0Q223 -743 250 -743Q277 -743 304.0 -738.0Q331 -733 355.0 -720.0Q379 -707 397.5 -686.5Q416 -666 427.5 -641.0Q439 -616 443.5 -589.0Q448 -562 448 -535V-200Q448 -178 445.5 -155.5Q443 -133 435.5 -112.0Q428 -91 416.0 -72.0Q404 -53 387.0 -38.0Q370 -23 350.0 -13.0Q330 -3 308 2Q308 21 312.5 39.0Q317 57 329.0 71.0Q341 85 358.5 92.0Q376 99 394 99H420V187ZM250 -80Q272 -80 292.5 -89.5Q313 -99 325.5 -116.5Q338 -134 343.0 -156.0Q348 -178 348 -200V-535Q348 -557 343.0 -579.0Q338 -601 325.5 -618.5Q313 -636 292.5 -645.5Q272 -655 250 -655Q228 -655 207.5 -645.5Q187 -636 174.5 -618.5Q162 -601 157.0 -579.0Q152 -557 152 -535V-200Q152 -178 157.0 -156.0Q162 -134 174.5 -116.5Q187 -99 207.5 -89.5Q228 -80 250 -80Z M750 8Q723 8 696.5 2.5Q670 -3 647.0 -16.5Q624 -30 606.5 -50.5Q589 -71 578.5 -95.5Q568 -120 564.0 -146.5Q560 -173 560 -200V-735H660V-200Q660 -186 661.5 -172.0Q663 -158 667.5 -144.5Q672 -131 679.5 -118.5Q687 -106 697.5 -97.0Q708 -88 722.0 -84.0Q736 -80 750 -80Q764 -80 778.0 -84.0Q792 -88 802.5 -97.0Q813 -106 820.5 -118.5Q828 -131 832.5 -144.5Q837 -158 838.5 -172.0Q840 -186 840 -200V-735H940V-200Q940 -173 936.0 -146.5Q932 -120 921.5 -95.5Q911 -71 893.5 -50.5Q876 -30 853.0 -16.5Q830 -3 803.5 2.5Q777 8 750 8Z M1039 0 1053 -70 1192 -735H1308L1461 0H1359L1326 -172H1174L1141 0ZM1310 -260 1267 -490Q1263 -513 1258.5 -536.0Q1254 -559 1250 -582Q1246 -559 1241.5 -536.0Q1237 -513 1233 -490L1190 -260Z M1856 0 1720 -292H1660V0H1560V-735H1755Q1783 -735 1810.5 -729.0Q1838 -723 1861.5 -708.0Q1885 -693 1902.5 -671.0Q1920 -649 1930.0 -623.0Q1940 -597 1944.0 -569.0Q1948 -541 1948 -514Q1948 -481 1942.5 -448.0Q1937 -415 1921.5 -386.0Q1906 -357 1880.5 -334.5Q1855 -312 1824 -302L1964 0ZM1660 -380H1755Q1771 -380 1785.5 -385.0Q1800 -390 1811.0 -400.5Q1822 -411 1829.5 -425.0Q1837 -439 1841.0 -453.5Q1845 -468 1846.5 -483.0Q1848 -498 1848 -514Q1848 -529 1846.5 -544.0Q1845 -559 1841.0 -574.0Q1837 -589 1829.5 -602.5Q1822 -616 1811.0 -626.5Q1800 -637 1785.5 -642.0Q1771 -647 1755 -647H1660Z M2356 0 2220 -292H2160V0H2060V-735H2255Q2283 -735 2310.5 -729.0Q2338 -723 2361.5 -708.0Q2385 -693 2402.5 -671.0Q2420 -649 2430.0 -623.0Q2440 -597 2444.0 -569.0Q2448 -541 2448 -514Q2448 -481 2442.5 -448.0Q2437 -415 2421.5 -386.0Q2406 -357 2380.5 -334.5Q2355 -312 2324 -302L2464 0ZM2160 -380H2255Q2271 -380 2285.5 -385.0Q2300 -390 2311.0 -400.5Q2322 -411 2329.5 -425.0Q2337 -439 2341.0 -453.5Q2345 -468 2346.5 -483.0Q2348 -498 2348 -514Q2348 -529 2346.5 -544.0Q2345 -559 2341.0 -574.0Q2337 -589 2329.5 -602.5Q2322 -616 2311.0 -626.5Q2300 -637 2285.5 -642.0Q2271 -647 2255 -647H2160Z M2700 0V-302L2537 -735H2644L2750 -429L2856 -735H2963L2800 -302V0Z"/></svg></a>
{{if .Repo}}
<form class="find" action="/r/{{.Repo}}/search" method="get">
{{- /* The box searches what the reader is looking at. On the tickets
       page "search tickets" is almost always what is meant. The scope is
       a hidden field rather than a mode, so the URL says what was
       searched and the results page can widen it. */ -}}
{{if .SearchKind}}<input type="hidden" name="kind" value="{{.SearchKind}}">{{end}}
<input type="search" name="q" value="{{.Query}}" placeholder="search {{.SearchScope}}" aria-label="search {{.SearchScope}}" data-on-keydown__window="evt.key == '/' &amp;&amp; !/INPUT|TEXTAREA|SELECT/.test(document.activeElement.tagName) &amp;&amp; (evt.preventDefault(), el.focus())" title="press / to search"></form>
{{else if .SearchAction}}
<form class="find" action="{{.SearchAction}}" method="get">
<input type="search" name="q" value="{{.Query}}" placeholder="filter {{.SearchScope}}" aria-label="filter {{.SearchScope}}" data-on-keydown__window="evt.key == '/' &amp;&amp; !/INPUT|TEXTAREA|SELECT/.test(document.activeElement.tagName) &amp;&amp; (evt.preventDefault(), el.focus())" title="press / to search"></form>
{{else}}
<form class="find" action="/search" method="get">
<input type="search" name="q" value="{{.Query}}" placeholder="search all repositories" aria-label="search all repositories" data-on-keydown__window="evt.key == '/' &amp;&amp; !/INPUT|TEXTAREA|SELECT/.test(document.activeElement.tagName) &amp;&amp; (evt.preventDefault(), el.focus())" title="press / to search"></form>
{{end}}
{{- /* The account menu is a popover, which needs no script: the button
       opens it, Escape and an outside click close it, and the browser
       handles focus. Everything that was loose in the header lives in
       it, so the bar keeps one shape whoever is signed in. */ -}}
<div class="bar-acts">
{{if .SignedIn}}<button class="bar-btn" popovertarget="create" title="create" aria-label="create menu"><svg class="ic" aria-hidden="true"><use href="#i-plus"/></svg></button>
<div id="create" popover class="menu">
{{if .Repo}}<div class="menu-who">in {{.Repo}}</div>
<a href="/r/{{.Repo}}/forum-new">new thread</a>
<a href="/r/{{.Repo}}/ticket/new">new ticket</a>
<a href="/r/{{.Repo}}/wiki">new wiki page</a>
<a href="/r/{{.Repo}}/technote-new">new note</a>
{{end}}{{if .IsAdmin}}<a href="/new">new repository&hellip;</a>{{end}}
</div>{{end}}
{{- /* The dot is filled by the attention stream where one is open,
       and by a single lazy fetch where it is not: two ways to learn one
       number, never both at once. The one-shot's data-init sits on the
       anchor, which is safe only because it fires once — a live patch
       of #inbox-dot inside it would delete a live attribute. */ -}}
{{if and .SignedIn .HasInbox}}<a class="bar-btn inboxbtn" href="/inbox" title="inbox" aria-label="inbox"{{if not .AttnAttr}} data-init="@get('/inbox.unread')"{{end}}><svg class="ic" aria-hidden="true"><use href="#i-inbox"/></svg><span id="inbox-dot"></span></a>{{end}}
<button class="avatar" popovertarget="acct" title="{{if .SignedIn}}{{.SignedIn}}{{else}}account{{end}}" aria-label="account menu">{{if .SignedIn}}{{identicon .SignedIn}}{{else}}<svg class="ic" aria-hidden="true"><use href="#i-person"/></svg>{{end}}</button>
<div id="acct" popover class="menu">
{{if .SignedIn}}<div class="menu-who">{{.SignedIn}}</div>
{{- /* A person's work is not in one repository. Gitea puts the
       cross-repository queues in its top nav and is right to: without a
       door, the only way to this page is a ticket already waiting. */ -}}
<a href="/tickets">your tickets</a>{{end}}
{{if .IsAdmin}}<a href="/fleet">fleet</a>{{end}}
{{if .HasInbox}}<a href="/inbox">inbox</a>{{end}}
{{if .SignedIn}}<a href="/me/notifications">notifications</a>{{end}}
<form class="theme" action="/theme" method="post">
<input type="hidden" name="to" value="{{.NextTheme}}">
<button type="submit" aria-label="colour theme: {{.ThemeName}}, switch to {{.NextTheme}}">
<svg class="ic" aria-hidden="true"><use href="#i-{{.ThemeIcon}}"/></svg> theme: {{.ThemeName}}</button></form>
{{if .SignedIn}}<form action="/logout" method="post"><button type="submit">sign out</button></form>
{{else if .CanSignIn}}<a href="/login">sign in</a>{{end}}
</div>
</div>
</div></header>
{{if .Repo}}<div class="repobar"><div class="bar">
<a class="repo" href="/r/{{.Repo}}">{{.Repo}}</a>
{{- /* Where the repository stands. A mirror says so and names its
       upstream, because "can I contribute here?" is the question a
       reader has before any other; a detached store keeps the link as
       provenance the way a fork says where it came from. */ -}}
{{if .Posture.Mirror.Tracking}}<a class="posture posture-{{.Posture.Mirror.State}}" href="{{.Posture.Mirror.URL}}" title="tracks {{.Posture.Mirror.URL}}{{if .Posture.Mirror.LastOK}}; synced {{ago .Posture.Mirror.LastOK}}{{end}}"><svg class="ic" aria-hidden="true"><use href="#i-sync"/></svg><span class="words">mirror of {{.Posture.Host}}{{if .Posture.Mirror.AcceptWrites}} <small>· accepts writes</small>{{end}}</span></a>
{{else if .Posture.DetachedFrom}}<a class="posture" href="{{.Posture.DetachedFrom}}" title="detached from {{.Posture.DetachedFrom}}; quarry is the source of truth"><svg class="ic" aria-hidden="true"><use href="#i-branch"/></svg><span class="words">forked from {{.Posture.Host}}</span></a>{{end}}
<nav>
{{- /* Counts tell a reader where a repository's content actually IS.
       Across the corpus that varies wildly — pikchr is 1,260 forum posts
       and one ticket, tk is 5,809 tickets and one post — and without
       them every store looks alike. An empty section stays LINKED but is
       dimmed: hiding it would make the nav's shape change per repo,
       which is worse than an honest dead end. */ -}}
{{$s := .Section}}{{$c := .HasCounts}}
{{navlink .Repo "tree" "Files" $s false false}}
{{navlink .Repo "timeline" "Timeline" $s $c .Counts.Checkins}}
{{navlink .Repo "ticket" "Tickets" $s $c .Counts.Tickets 9}}
{{- /* No count on docs. It draws from two stores and the tree half
       costs a subprocess to size, which is not a price every page in
       the forge should pay for a badge. A number that disagreed with
       the page under it — 83 against 205 — is worse than none. A
       non-integer count is navlink's way of saying "no badge": zero
       would render a dimmed 0, which claims the tab is empty. */ -}}
{{navlink .Repo "docs" "Docs" $s $c "" 3}}
{{navlink .Repo "landing" "Landings" $s $c .Counts.OpenLandings 2}}
{{navlink .Repo "forum" "Forum" $s $c .Counts.ForumThreads 2}}
{{- /* No notes tab. fossil's built-in menu has none, and libfossil —
       which uses technotes as a milestone feed and overrode the menu
       to add TODOs and FIXMEs — still did not add one. Notes are
       reached from the About panel, the timeline's kind filter, and
       the docs page, which is where somebody looking for a project's
       news actually goes. The bar already overflows into "more" on a
       phone; this is the tab that was losing that competition. */ -}}
{{navlink .Repo "ci" "CI" $s false false 1}}
{{navlink .Repo "chat" "Chat" $s .HasChatUnread .ChatUnread 1}}
{{if .IsAdmin}}<a class="cog aux1{{if eq $s "settings"}} here{{end}}" href="/r/{{.Repo}}/settings" data-tip="settings" aria-label="repository settings"><svg class="ic" aria-hidden="true"><use href="#i-gear"/></svg>{{if eq $s "settings"}}<span class="ink" aria-hidden="true"></span>{{end}}</a>{{end}}
</nav>
<button type="button" class="navmore-btn" popovertarget="navmore" aria-label="more sections"><svg class="ic" aria-hidden="true"><use href="#i-more"/></svg></button>
{{- /* GitHub's collapse: at narrow widths the aux sections fold into
       this menu so the bar owns its one line instead of wrapping. The
       links are duplicated, not moved — the popover lives OUTSIDE the
       nav so the view-transition name on the visible tab stays unique,
       and a hidden duplicate is inert. */ -}}
<div id="navmore" class="menu navmore" popover>
<span class="m3">{{navlink .Repo "docs" "Docs" $s $c ""}}</span>
<span class="m2">{{navlink .Repo "landing" "Landings" $s $c .Counts.OpenLandings}}</span>
<span class="m2">{{navlink .Repo "forum" "Forum" $s $c .Counts.ForumThreads}}</span>
<span class="m1">{{navlink .Repo "ci" "CI" $s false false}}</span>
<span class="m1">{{navlink .Repo "chat" "Chat" $s .HasChatUnread .ChatUnread}}</span>
{{if .IsAdmin}}<span class="m1"><a href="/r/{{.Repo}}/settings"{{if eq $s "settings"}} class="here"{{end}}><svg class="ic" aria-hidden="true"><use href="#i-gear"/></svg> settings</a></span>{{end}}
</div>
</div>
{{- /* Staleness as a state, not a timestamp. Lagging stays quiet — a
       quiet upstream is normal. Failing is said once, in words a reader
       who has never heard of a mirror can use. */ -}}
{{if eq .Posture.Mirror.State "failing"}}<div class="bar posture-warn">upstream {{.Posture.Host}} unreachable ({{.Posture.Mirror.Failures}} {{plural .Posture.Mirror.Failures "attempt" "attempts"}}){{if .Posture.Mirror.LastOK}}; showing content as of {{ago .Posture.Mirror.LastOK}}{{else}}; nothing has been pulled yet{{end}}</div>{{end}}
</div>{{end}}
<main{{if .BoardView}} class="board-page"{{end}}>
{{if .Counts.IndexBehind}}<p class="status stale-note"><strong>Index rebuilding.</strong>
History-derived data on this page — timeline, counts, last-change columns — may end before
the repository's real tip. File listings come straight from the store and are current.</p>{{end}}
{{if .OwnH1}}{{else if .HideH1}}<h1 class="sr-only">{{.Title}}</h1>{{else}}<h1>{{.Title}}</h1>{{end}}
{{block "content" .}}{{end}}
</main>
{{- /* One popover for every reference on the page (RFC 0011 §14). A
       per-link popover would be a per-link element, and a busy chat
       log has hundreds. The native popover owns Escape and
       outside-click dismissal, and traps no focus. */ -}}
<div id="refpop" popover></div>
{{- /* The attention region (RFC 0011 §5). The stream's data-init sits
       on the WRAPPER, never on #toasts itself: a patch morphs its
       target to match the fragment, so an attribute on the target is
       deleted by the first patch — taking Datastar's own connection
       with it. Empty and inert without the stream, which is what every
       page a signed-out reader sees gets. */ -}}
<div class="toasts-wrap"{{with .AttnAttr}} {{.}}{{end}}><div id="toasts"></div></div>
<footer><div class="bar">
{{- /* Three parts in priority order, because the bar is one line and
       something has to go first on a narrow screen. The render time is
       the reason this footer earns its space, so it is the part that
       never shrinks; the forge name and the version collapse ahead of
       it. Truncating the whole half dropped the timing first, which is
       exactly backwards. */ -}}
<span class="foot-l"><span class="f-brand">powered by <a href="https://github.com/danmestas/zeit">zeit</a> · </span><span class="f-ver">quarry {{.Version}}{{if .Elapsed}} · {{end}}</span>{{if .Elapsed}}<span class="f-time" data-volatile>rendered in {{.Elapsed}}{{if .Breakdown}}<span class="f-ops"> ({{.Breakdown}})</span>{{end}}</span>{{end}}</span>
<span class="foot-r"><a href="/licenses">licenses</a> <a href="/privacy">privacy</a> <a href="/docs">API</a></span>
</div></footer>
</body>
</html>
{{define "ticket-head"}}
{{- /* The tracker's header, in the order every forge that works puts
       it: which lives are listed (with their counts — "open" without a
       number answers half the question), then how they are drawn, then
       the one action the page exists to start.

       State and view are independent axes: filtering to closed and
       switching to the board must not undo each other, so every link
       here is built by ticketNav from the current state. */ -}}
<div class="t-head">
{{- /* The waiting-on-you view forces its own state, so offering the
       three state links would be three controls that cannot work. */ -}}
{{if .Nav.Awaiting}}<h2 class="t-view">{{count .Nav.Open}} waiting on you</h2>{{else}}<nav class="t-states seg-box">
<a href="{{.Nav.URL "state" "open"}}"{{if .Nav.Is "state" "open"}} class="here"{{end}}><svg class="ic g-open" aria-hidden="true"><use href="#i-tkt-open"/></svg>{{count .Nav.Open}} Open</a>
<a href="{{.Nav.URL "state" "closed"}}"{{if .Nav.Is "state" "closed"}} class="here"{{end}}><svg class="ic g-done" aria-hidden="true"><use href="#i-tkt-done"/></svg>{{count .Nav.Closed}} Closed</a>
<a href="{{.Nav.URL "state" "all"}}"{{if .Nav.Is "state" "all"}} class="here"{{end}}>{{count (add .Nav.Open .Nav.Closed)}} All</a>
</nav>{{end}}
<div class="t-tools">
<nav class="seg-box">
<a href="{{.Nav.URL "view" ""}}"{{if .Nav.Is "view" ""}} class="here"{{end}}>list</a>
<a href="{{.Nav.URL "view" "table"}}"{{if .Nav.Is "view" "table"}} class="here"{{end}}>table</a>
{{- /* No board across repositories: its lanes are one tracker's
       vocabulary, and K trackers do not share one. */ -}}
{{if not .Across}}<a href="{{.Nav.URL "view" "board"}}"{{if .Nav.Is "view" "board"}} class="here"{{end}}>board</a>{{end}}
</nav>
{{- /* Priority order is a LIST affordance: the table sorts by whichever
       column its reader clicked, and the board is grouped, not ordered.
       Showing this control on those two would offer a choice neither
       view can honour. */ -}}
{{if .Nav.Is "view" ""}}<nav class="seg-box">
<a href="{{.Nav.URL "sort" ""}}"{{if not (.Nav.Is "sort" "recent")}} class="here"{{end}}>priority</a>
<a href="{{.Nav.URL "sort" "recent"}}"{{if .Nav.Is "sort" "recent"}} class="here"{{end}}>recent</a>
</nav>{{end}}

{{- /* Filing needs one tracker to file into, so the cross-repository
       listing offers no New: pick a repository first. */ -}}
{{if not .Across}}{{if .Posture.ReadOnly}}<a class="btn" href="{{.Posture.Upstream "tktnew"}}">New ticket on {{.Posture.Host}} &rarr;</a>{{else}}<a class="btn btn-primary" href="/r/{{.Repo}}/ticket/new">New ticket</a>{{end}}{{end}}
</div>
</div>
{{end}}
{{define "ticket-filters"}}
{{- /* The report, as native selects in one GET form. Every dropdown is
       a URL parameter and the URL is the whole report, so a narrowed
       listing is shareable, bookmarkable and scriptable (append .json)
       without a query language, saved-search storage, or a line of
       state on the server.

       onchange submits because a filter you must then click Apply to is
       a filter most readers never apply; the form still submits on
       Enter with no script at all, and the hidden fields restate the
       axes a GET form would otherwise wipe. */ -}}
{{- /* The box and the dropdowns are the same report in two spellings.
       They are separate FORMS on purpose: each submits only its own
       spelling, the server turns whichever arrives into the canonical
       parameters, and neither can contradict the other. */ -}}
<form class="t-search" method="get" action="{{.Nav.Path}}">
{{- /* Labelled, because the topbar has a search box too and the two do
       different things: that one searches ticket TEXT across the repo
       and lands on a results page, this one narrows the listing in
       front of you. Two unlabelled boxes a hundred pixels apart is a
       guess the reader should not have to make. */ -}}
<span class="t-search-label">filter</span>
{{range .Nav.ViewFields}}<input type="hidden" name="{{.Name}}" value="{{.Value}}">{{end}}
<input type="search" name="q" value="{{.Nav.Query}}" spellcheck="false"
  placeholder="is:closed subsystem:web crash" aria-label="filter this tracker">
</form>
{{if .Filters}}<form class="t-filters" method="get" action="{{.Nav.Path}}">
{{range .Nav.Hidden}}<input type="hidden" name="{{.Name}}" value="{{.Value}}">{{end}}
{{range $c := .Filters}}<label class="t-filter{{if $c.Selected}} on{{end}}"><span>{{$c.Key}}</span>
<select name="{{$c.Key}}" onchange="this.form.submit()">
<option value="">any</option>
{{range $c.Options}}<option value="{{.}}"{{if eq . $c.Selected}} selected{{end}}>{{.}}</option>{{end}}
</select></label>{{end}}
<noscript><button type="submit">apply</button></noscript>
{{if .Nav.Filtered}}<a class="t-clear" href="{{.Nav.Clear}}">clear filters</a>{{end}}
</form>{{end}}
{{end}}
{{define "ci-context"}}
{{- /* Fossil's Context panel: this check-in among its neighbours in
       time. A commit read alone says what changed; read among the
       commits either side it says what was going on, which is the
       question somebody bisecting a regression is actually asking.
       Two indexed walks, no store read — it costs nothing this page
       was not already paying. */ -}}
{{if .Context}}<section class="ci-ctx">
<h2>Context</h2>
<ol>{{range .Context}}
<li{{if .Here}} class="here"{{end}}>{{.Node}}
<a class="ci-ctx-h" href="/r/{{$.Repo}}/checkin/{{.Hash}}"><code>{{printf "%.10s" .Hash}}</code></a>
<span class="ci-ctx-m">{{ago .Date}} · {{who $.Repo .User}}{{if .Branch}} · {{.Branch}}{{end}}</span>
<span class="ci-ctx-c">{{.Lead}}</span></li>
{{end}}</ol>
</section>{{end}}
{{end}}
{{define "artifact-note"}}
{{- /* An About: the wiki page somebody wrote ABOUT this artifact.
       Fossil's convention — branch/NAME and checkin/HASH — and the
       reason those pages are kept out of the documentation index is
       that this is where they belong. Above the artifact, because a
       note explaining a branch is read before the commits, not after
       scrolling past two hundred of them. */ -}}
{{if .Note}}<section class="a-note">
{{- /* Folded when it is long. Fossil's own auto-toc branch note runs
       three screens, which puts the timeline the reader actually came
       for entirely below the fold — an About that buries its subject
       has stopped being context. details/summary because it costs no
       script and remembers nothing it should not. */ -}}
{{- /* Open by default. It was folded past ~1200 bytes because fossil's
       own auto-toc note runs three screens and pushed a timeline below
       the fold — but a note somebody wrote about this artifact is the
       context you came for, and hiding it to protect the page below is
       the wrong trade. The summary stays, so it can still be collapsed. */ -}}
<details class="a-note-d" open>
<summary>About this {{.NoteKind}}</summary>
<div class="a-note-b">{{.Note}}</div>
<p class="a-note-f"><a href="/r/{{.Repo}}/wiki/{{pathesc .NoteName}}">{{.NoteName}}</a></p>
</details>
</section>{{end}}
{{end}}
{{define "ticket-pager"}}{{template "pager" .Pager}}{{end}}

{{- /* The numbered pager. Both ends are always drawn, dead ones as
       plain text, so the control keeps its shape and nothing shifts
       under the pointer between pages. The numbers are what a one-way
       "older" link never gave: where you are, how much is behind you,
       and a way to the end without walking there. */ -}}
{{- /* The fleet family's one navigation. Stores and mirrors are panels
       of /fleet and morph in place — the href is the no-script path and
       syncurl corrects the address bar, so a tab stays linkable and a
       reload lands where you were. Operations and exceptions are pages
       with more to say than a panel holds, so they navigate. Rendered
       on all four surfaces: a family that changes its nav between
       members is four pages, not one place. */ -}}
{{define "fleet-nav"}}
{{- /* The morph is only offered by the page that can perform it. syncurl
       emits data-on:click__prevent, so on /fleet/ops and /fleet/exceptions
       — which have no #fleet-panel to patch — those two entries swallowed
       the click and went nowhere: from Operations you could not get back
       to Stores or Mirrors at all. Away from /fleet they are ordinary
       links, which is what they always were without script. */ -}}
{{$morph := or (eq .FleetTab "stores") (eq .FleetTab "mirrors")}}
<nav class="seg-box" aria-label="fleet">
<a href="/fleet"{{if eq .FleetTab "stores"}} class="here"{{end}}{{if $morph}} {{syncurl "/fleet/tab.frag?tab=stores"}}{{end}}>Stores</a>
<a href="/fleet?tab=mirrors"{{if eq .FleetTab "mirrors"}} class="here"{{end}}{{if $morph}} {{syncurl "/fleet/tab.frag?tab=mirrors"}}{{end}}>Mirrors</a>
<a href="/fleet/ops"{{if eq .FleetTab "ops"}} class="here"{{end}}>Operations</a>
<a href="/fleet/exceptions"{{if eq .FleetTab "errors"}} class="here"{{end}}>Exceptions{{if .ErrorTotal}} <span class="n">{{.ErrorTotal}}</span>{{end}}</a>
</nav>{{end}}

{{define "pager"}}
{{if .}}{{with .}}<nav class="t-pager" aria-label="pages">
{{if .Prev}}<a class="t-page-step" href="{{.Prev}}" rel="prev">&larr; newer</a>{{else}}<span class="t-page-step">&larr; newer</span>{{end}}
{{range .Steps}}{{if .Gap}}<span class="t-page-gap">&hellip;</span>{{else if .Here}}<span class="t-page-n here" aria-current="page">{{.Page}}</span>{{else}}<a class="t-page-n" href="{{.URL}}">{{.Page}}</a>{{end}}{{end}}
{{if .Next}}<a class="t-page-step" href="{{.Next}}" rel="next">older &rarr;</a>{{else}}<span class="t-page-step">older &rarr;</span>{{end}}
<span class="t-pager-at">{{.From}}&ndash;{{.To}} of {{thousands .Total}}</span>
</nav>{{end}}{{end}}
{{end}}
{{define "ticket-rail"}}
{{- /* Ways in. Every entry is an ordinary report URL, so the rail
       promises nothing the address bar cannot say and needs no storage
       of its own. Clicking the browse entry you are already on removes
       that axis, because a filter you cannot see how to leave is a
       trap. Hidden on narrow screens: the dropdowns above the listing
       reach every one of these values, so the rail is an affordance,
       never the only way through. */ -}}
{{if or .Rail .CanSaveView}}<nav class="t-rail" aria-label="ticket views">
{{range .Rail}}<div class="t-rail-sec"><h2>{{.Title}}</h2>
<ul>{{range .Links}}<li><a href="{{.URL}}"{{if .Here}} class="here"{{end}}>
<span class="t-rail-name">{{.Label}}</span>
{{if not .Bare}}<span class="n" title="{{.Count}} open">{{.Count}}</span>{{end}}</a>
{{- /* A saved view can be dropped from where it lives. The listing it
       named is unaffected — only the shortcut goes. */ -}}
{{if .Saved}}<form class="t-rail-x" method="post" action="/views/delete">
<input type="hidden" name="repo" value="{{$.SaveTarget}}">
<input type="hidden" name="name" value="{{.Label}}">
<button type="submit" title="forget this view" aria-label="forget the view {{.Label}}">&times;</button>
</form>{{end}}</li>{{end}}</ul>
</div>{{end}}
{{- /* Naming a report is the whole feature: the URL already IS the
       report, so this stores a name for it and nothing else. Offered
       only to a reader the forge can attribute it to, and only once a
       report exists to name — the unfiltered listing needs no shortcut
       to itself. */ -}}
{{if and .CanSaveView .Nav.Filtered}}<form class="t-rail-save" method="post" action="/views">
<input type="hidden" name="repo" value="{{.SaveTarget}}">
<input type="hidden" name="query" value="{{.Nav.QueryString}}">
<input name="name" placeholder="name this view" maxlength="48" required aria-label="name this view">
<button type="submit">save</button>
</form>{{end}}
</nav>{{end}}
{{end}}
{{define "explore-tabs"}}
{{- /* Two tabs, not four. Repositories and people are surfaces quarry
       actually has; organisations are v2 (0001 §8 puts org/ACLs there)
       and code search indexes nothing today, and a tab that opens onto
       an empty page teaches a reader the forge is broken rather than
       that the feature is unbuilt. */ -}}
<nav class="tabs">
<a href="/?view=explore"{{if not .Explore}} class="here"{{end}}><svg class="ic" aria-hidden="true"><use href="#i-dir"/></svg> Repositories {{count .FleetTotal}}{{if not .Explore}}<span class="ink" aria-hidden="true"></span>{{end}}</a>
<a href="/people"{{if eq .Explore "people"}} class="here"{{end}}><svg class="ic" aria-hidden="true"><use href="#i-people"/></svg> People {{count .PeopleTotal}}{{if eq .Explore "people"}}<span class="ink" aria-hidden="true"></span>{{end}}</a>
</nav>
{{end}}
`

var fleetPage = template.Must(template.Must(base.Clone()).Parse(fleetSource))

const fleetSource = `{{define "fleet-controls"}}
<div class="tl-controls fleet-bar">
{{- /* Live where the one allowed script runs, a plain GET form where
       it does not. The debounced @get uses Datastar's form content
       type, so it sends exactly the q= and sort= this form would submit
       on Enter — one request shape, one server path, and the listing
       follows the keystrokes without a click.

       The shell is basecoat's input-group: the border lives on the
       wrapper and the controls inside are bare, so the clear button
       reads as part of the field rather than as something beside it. */ -}}
<form method="get" action="/"
  {{- /* Live-at-load WITHOUT the stale-filter trap. The stream
       (/fleet.rev) carries only an invalidation signal — "the fleet is
       at revision N" — so it cannot repaint anything and cannot go
       stale. The effect fires on every revision bump and re-requests
       the listing as a ONE-SHOT (/fleet.frag) with the form content
       type, which serializes THIS form — so the refresh always carries
       whatever the filter says at that moment. The && guard keeps the
       effect's initial run (rev still 0) from re-fetching the page the
       server just rendered. */ -}}
{{if $.Live}} data-signals="{fleetRev: 0}" data-init="@get('/fleet.rev')" data-effect="$fleetRev && @get('/fleet.frag', {contentType: 'form'})"{{end}}>
<span class="input-group">
<input type="search" name="q" value="{{.Query}}" placeholder="filter" aria-label="filter repositories"
{{if $.Live}}data-on:input__debounce.300ms="@get('/fleet.frag', {contentType: 'form'})"{{end}}>
{{if .Query}}<a class="clearq" href="/?view=explore{{if .Sort}}&amp;sort={{.Sort}}{{end}}" aria-label="clear the filter">&times;</a>{{end}}
</span>
<select name="kind" aria-label="kind" data-on:change="@get('/fleet.frag', {contentType: 'form'})" onchange="this.form.submit()">
<option value=""{{if eq .Kind ""}} selected{{end}}>all</option>
<option value="mirror"{{if eq .Kind "mirror"}} selected{{end}}>mirrors</option>
<option value="native"{{if eq .Kind "native"}} selected{{end}}>native</option>
</select>
<select name="sort" aria-label="sort" data-on:change="@get('/fleet.frag', {contentType: 'form'})" onchange="this.form.submit()">
<option value="name"{{if eq .Sort "name"}} selected{{end}}>name</option>
<option value="active"{{if eq .Sort "active"}} selected{{end}}>recently active</option>
<option value="size"{{if eq .Sort "size"}} selected{{end}}>size</option>
</select> <noscript><button type="submit">go</button></noscript></form>
{{if .IsAdmin}}<span class="tree-acts"><a href="/new">New repository</a></span>{{end}}
</div>
{{end}}
{{define "fleet-body"}}
{{- /* The count belongs with the listing, not with the controls: it
       DESCRIBES the rows, so it has to be repainted with them or it
       goes stale the moment the filter changes.

       Filtered, the useful denominator is the fleet rather than the
       match count — "1 of 1" is true and says nothing. Unfiltered there
       is nothing to compare against, so it is just the total. */ -}}
<p class="tl-meta-inline fleet-count">{{if or .Query .Kind}}{{len .Fleet}} of {{.Served}} repositories{{else if .FleetTotal}}{{.FleetTotal}} repositories{{end}}</p>

{{if .Fleet}}{{- /* Below the width where a header carries its own words the
       icons stand alone: the sr-only label names each for a screen
       reader and the tooltip for a pointer. A legend used to restate
       all four in a row above the header — which read as a duplicate
       of the header itself and said nothing the tooltips do not. Touch
       readers at narrow widths are the honest gap; the numbers' shapes
       (counts, durations) carry most of the meaning there. */ -}}
<div class="tw"><table class="fleet">
{{- /* Real columns, not a grid inside one cell. CSS grid aligns within
       ONE grid; a per-row grid gives every row its own column widths, so
       nothing lines up down the page — which was the whole point. */ -}}
{{- /* An icon with only a title tells a touch reader nothing: there is
       no hover, so the label is unreachable. Each header carries a
       VISIBLE label wherever the table has room for one, and the legend
       above names them where it does not. */ -}}
<thead><tr><th scope="col">Repository</th>
{{tipcol "commit" "check-ins"}}{{tipcol "people" "contributors"}}
{{tipcol "sync" "last mirrored"}}{{tipcol "clock" "last activity"}}</tr></thead>
<tbody>{{range .Fleet}}
{{- /* Two rows per repository: the name and its numbers, then the
       description spanning the whole width beneath. Keeping the
       description in the first column made that column as wide as the
       longest sentence, which pushed the numeric columns off a phone
       screen entirely. Spanning lets it wrap against the full page and
       leaves the name column only as wide as a name. */ -}}
{{- /* A repository's name opens the repository itself, which is its
       files. The timeline is one of its sections, reachable from the
       nav; landing there made every arrival start with what changed
       rather than with what the project IS. */ -}}
<tr class="r-top"><td class="r-name"><a href="/r/{{.Name}}">{{.Name}}</a>{{if .Mirror.Tracking}} <span class="tl-badge posture-badge" title="mirror of {{.Mirror.URL}}{{if eq .Mirror.State "failing"}} — failing{{end}}">mirror</span>{{else if .DetachedFrom}} <span class="tl-badge posture-badge" title="forked from {{.DetachedFrom}}">fork</span>{{end}}{{if .Private}} <span class="tl-badge">private</span>{{end}}</td>
{{- /* Compact, as the nav already does: tcl's 25,557 set this column's
       width for every row, and nobody reads a check-in count to five
       significant figures. The exact figure stays in the title. */ -}}
<td class="n">{{if .Indexing}}<small class="tl-meta-inline">…</small>{{else}}{{count .Checkins}}{{end}}</td>
<td class="n">{{if .Contributors}}{{count .Contributors}}{{end}}</td>
<td class="n">{{if .MirroredAt}}{{agoShort .MirroredAt}}{{end}}</td>
<td class="n last">{{if .LastActive}}{{agoShort .LastActive}}{{end}}</td></tr>
{{if .Description}}<tr class="r-desc"><td colspan="5">{{.Description}}</td></tr>{{end}}
{{end}}</tbody>
</table>
</div>{{else}}<p>{{if .Query}}No repository matches “{{.Query}}”.{{else}}No repositories are being served yet.{{if .IsAdmin}} <a href="/new">Create one</a>.{{end}}{{end}}</p>{{end}}
{{end}}
{{- /* The controls sit OUTSIDE #fleet on purpose. Everything inside is
       replaced on every repaint, so a filter box in there would be torn
       out from under the reader mid-keystroke and would re-run its own
       data-init on each morph. Out here the input is a stable element:
       it owns the stream, and typing re-opens it rather than racing a
       second one. */ -}}
{{define "content"}}{{template "explore-tabs" .}}{{template "fleet-controls" .}}
<div><div id="fleet">{{template "fleet-body" .}}</div></div>{{end}}`

var licensesPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
<h2>quarry</h2>
<p>quarry — the forge software serving this site — is BSD 2-Clause.</p>
<pre class="licence">{{.QuarryLicence}}</pre>

<h2>The repositories served here</h2>
<p>Each repository quarry serves carries its own licence, chosen by the
people who wrote it. quarry makes no claim over any of it: a store is
hosted content, not part of this software. Look in the repository itself
— conventionally a <code>LICENSE</code>, <code>LICENCE</code> or
<code>COPYING</code> file at the root of its tree — for the terms that
actually apply to that project.</p>

<h2>Third-party components</h2>
<p>quarry links the modules below. They are listed because their licences
require reproducing them, not because quarry claims anything about them.
The list is generated from the build graph, so it cannot quietly fall
behind what this binary contains.</p>
<details><summary>{{len .Notices}} modules</summary>
{{range .Notices}}
<h3 id="{{.Module}}">{{.Module}}</h3>
<p class="tl-meta-inline">{{.Version}} · {{.License}}</p>
<pre class="licence">{{.Text}}</pre>
{{end}}
</details>
{{end}}`))

var privacyPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
<p>This page describes what this quarry instance stores. It describes the
software's behaviour, not a legal commitment by whoever runs it.</p>

<h2>What is public by construction</h2>
<p>A repository quarry serves is a set of artifacts, and every artifact
records who wrote it and when. Names, e-mail addresses and dates inside
check-ins, wiki edits, tickets, forum posts and technotes are part of the
repository's content: quarry displays them, indexes them for search, and
serves them over the sync protocol. It cannot remove them without
rewriting history, which it will not do. If a repository is public, so is
everything in it.</p>

<h2>What quarry itself keeps</h2>
<ul>
<li><strong>Accounts</strong> — a login name, a password hash (argon2id;
the password itself is never stored), whether the account is a site
admin, and its creation date. Per-repository grants are stored alongside.</li>
<li><strong>Sessions</strong> — a random token in a cookie, with an
expiry. Signing out deletes it.</li>
<li><strong>Sync credentials</strong> — a shared secret per repository
user, as the sync protocol defines it. Never a plaintext password.</li>
<li><strong>Your colour theme</strong> — a cookie holding
"light" or "dark", set only if you choose one. Choosing "system" removes
it. It is not used to identify you.</li>
</ul>

<h2>What quarry does not do</h2>
<ul>
<li>No third-party analytics, advertising, or trackers. The pages load
nothing from another host — there is no external stylesheet, font, image
or script anywhere in this interface.</li>
<li>No avatar fetching. The circle in the corner is your initials drawn
locally, not an image requested from a third party using your address.</li>
<li>No access log of readers is kept by quarry itself. The server it runs
behind may keep its own; that is outside this software.</li>
</ul>

<h2>Deletion</h2>
<p>Deleting an account removes it, its sessions and its grants. It does
not remove artifacts that account authored, because those are repository
content and belong to the history rather than to the forge.</p>
{{end}}`))

// The forge's view of its own behaviour. /fleet answers "are my
// repositories healthy"; this answers "is the forge healthy", which is
// a different question with different numbers.
//
// Site-admin only, and unlike every other page in quarry it assumes
// script: an internal dashboard that cannot update while an operator
// watches a fleet index is worth much less than one that can, and no
// consumer depends on it rendering without Datastar. The op behind it
// is registered and versioned like any other, so the guarantee that
// matters — a documented API — is unchanged.
//
// Slowest first, problems first: the same grammar /fleet already uses.
// exceptionsPage is the fleet's error surface: every distinct failure
// the server has seen since it started, across every store, with the
// trace for the ones that panicked. Deduplicated by message — a hot
// loop is one row with a count, never a flood — and ordered by what is
// still happening rather than by what happened first.
var exceptionsPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
<div class="t-head">
<h1>Exceptions</h1>
{{template "fleet-nav" .}}
</div>
<form method="get" action="/fleet/exceptions" class="fleet-bar">
<input name="q" value="{{.Query}}" placeholder="signature, surface, repository or path" size="40" aria-label="filter exceptions">
<button type="submit">Filter</button>
{{if .Query}}<a href="/fleet/exceptions">clear</a>{{end}}
</form>
{{if .ServerErrors}}
<p class="tl-meta-inline">{{len .ServerErrors}} distinct {{plural (len .ServerErrors) "signature" "signatures"}}{{if .ErrorTotal}} · {{.ErrorTotal}} total {{plural .ErrorTotal "occurrence" "occurrences"}}{{end}} since this server started.</p>
{{range .ServerErrors}}
<details class="d-row exc">
<summary>
<span class="d-line">
<code class="exc-sig">{{.Sig}}</code>
<span class="tl-badge">{{.Surface}}</span>
{{if .Repo}}<a class="exc-repo" href="/r/{{pathesc .Repo}}">{{.Repo}}</a>{{end}}
<strong>{{clip 96 .Message}}</strong>
</span>
<span class="d-sub">{{if .Repeated}}{{.Count}}&times;{{else}}once{{end}} · last {{ago .Last}} · first {{ago .First}}</span>
</summary>
<div class="exc-body">
<p class="exc-msg">{{.Message}}</p>
<p class="tl-meta-inline">first seen at <code>{{.Path}}</code></p>
{{if .Trace}}<pre class="exc-trace">{{.Trace}}</pre>
{{else}}<p class="t-none">No stack: this surfaced as an error return, not a panic. The path above is where it was first reported.</p>{{end}}
{{- /* Filing is offered where the trace is, not on a summary elsewhere:
       the report worth opening is the one that can carry the stack. */ -}}
{{if $.TrackerRepo}}<p><a class="tn-new" href="/r/{{pathesc $.TrackerRepo}}/ticket/new?title={{.Message}}&amp;type=Code_Defect&amp;subsystem={{.Surface}}&amp;comment={{printf "Journalled server error (%s).\n\n    surface: %s\n    path:    %s\n    count:   %d\n    last:    %s" .Sig .Surface .Path .Count .Last}}">file ticket</a></p>{{end}}
</div>
</details>
{{end}}
{{else}}<p class="t-none">{{if .Query}}Nothing matches.{{else}}Nothing has failed since this server started.{{end}}</p>{{end}}
{{end}}`))

var opsPage = template.Must(template.Must(base.Clone()).Parse(opsPageSource))

const opsPageSource = `{{define "ops-body"}}<div id="opsbody">
{{- /* The phase leads, because during startup it is the only thing on
       this page that is true yet: the panels below are steady-state
       numbers and read as an empty forge while one is coming up. The
       bar is stores READY, not bytes — a forge is not up because it
       answered the port, it is up when its stores are readable. */ -}}
<div class="ops-phase ph-{{.Ops.Phase.Name}}">
<div class="ops-phase-h">
<span class="ops-phase-n">{{.Ops.Phase.Name}}</span>
<span class="ops-phase-c">{{.Ops.Phase.Ready}} of {{.Ops.Phase.Repos}} stores ready{{if .Ops.Phase.Artifacts}} · {{count .Ops.Phase.Artifacts}} artifacts this session{{end}}{{if .Ops.Phase.SlowestRoundSeconds}} · slowest round {{printf "%.1f" .Ops.Phase.SlowestRoundSeconds}}s{{end}}</span>
</div>
{{- /* Ready and stalled are both DONE waiting, and a bar that counted a
       stalled store as pending would never fill. They are drawn as two
       segments so the difference stays visible. */ -}}
<div class="ops-bar" role="img" aria-label="{{.Ops.Phase.Ready}} of {{.Ops.Phase.Repos}} stores ready">
<span class="ops-bar-ok" style="width:{{pctOf .Ops.Phase.Ready .Ops.Phase.Repos}}%"></span>
<span class="ops-bar-bad" style="width:{{pctOf (len .Ops.Phase.Stalled) .Ops.Phase.Repos}}%"></span>
</div>
{{if .Ops.Phase.Working}}<p class="ops-phase-l">rebuilding: {{range $i, $n := .Ops.Phase.Working}}{{if $i}}, {{end}}<code>{{$n}}</code>{{end}}</p>{{end}}
{{if .Ops.Phase.Stalled}}<p class="ops-phase-l ci-fail-text">stopped retrying: {{range $i, $n := .Ops.Phase.Stalled}}{{if $i}}, {{end}}<code>{{$n}}</code>{{end}} — these wait for a person, not for time</p>{{end}}
</div>
<div class="ops-cards">
<div class="ops-card"><span class="ops-n{{if gt .Ops.LiveSubprocess 8}} ci-fail-text{{end}}">{{.Ops.LiveSubprocess}}</span>
<span class="ops-l">store subprocesses now</span>
<span class="ops-sub">peak {{.Ops.PeakSubprocess}} since start</span></div>
<div class="ops-card"><span class="ops-n">{{len .Ops.Paths}}</span>
<span class="ops-l">routes seen</span>
<span class="ops-sub">{{.Ops.Window}} in the window</span></div>
<div class="ops-card"><span class="ops-n{{if .Ops.ErrorTotal}} ci-fail-text{{end}}">{{.Ops.ErrorTotal}}</span>
<span class="ops-l">server errors</span>
<span class="ops-sub"><a href="/fleet">fleet health &rarr;</a> · <a href="/fleet/exceptions">exceptions &rarr;</a></span></div>
</div>

{{- /* The panels above are fed by in-memory rings, which fill whether
       or not the durable store is working — so a forge that failed to
       open it looks healthy right up until someone asks it for history
       and finds none. Say which it is. */ -}}
{{if not .Ops.Store.Configured}}
<p class="tn-lede">History is off. The panels above are this process's
live window; nothing is being kept, so nothing can be compared across a
restart. Start with <code>--analytics &lt;dir&gt;</code> to keep it.</p>
{{else if .Ops.Store.Err}}
<p class="tn-lede ci-fail-text">History is NOT being recorded:
{{.Ops.Store.Err}}. The panels above still work — they read this
process's memory — but nothing is reaching
<code>{{.Ops.Store.Path}}</code>.</p>
{{else}}
<p class="tn-lede">History is recorded to <code>{{.Ops.Store.Path}}</code>{{with .Ops.Store.Kept}},
kept for {{.}}{{end}}.</p>
{{end}}

<h2>Slowest routes</h2>
<p class="tn-lede">By p95, not by average: a mean hides the tail, and the tail is
what is worth finding. A route is the PATTERN — one line, not one per hash.
Red is over the {{.Ops.BudgetMs}}ms budget, which is also what notifies.</p>
{{- /* A fleet serving two dozen repositories has a routes panel long
       enough that finding one is a scroll, and "is the wiki slow"
       should not be answered by reading. The controls submit normally
       without script; the live refresh serializes this same form. */ -}}
<form class="tl-controls" action="/fleet/ops" method="get">
<input type="search" name="find" value="{{.Ops.Find}}" placeholder="filter routes" aria-label="filter routes">
<select name="sort" aria-label="sort by" onchange="this.form.submit()">
<option value="p95"{{if eq .Ops.Sort "p95"}} selected{{end}}>slowest p95</option>
<option value="p50"{{if eq .Ops.Sort "p50"}} selected{{end}}>slowest p50</option>
<option value="max"{{if eq .Ops.Sort "max"}} selected{{end}}>worst single</option>
<option value="n"{{if eq .Ops.Sort "n"}} selected{{end}}>busiest</option>
<option value="path"{{if eq .Ops.Sort "path"}} selected{{end}}>route name</option>
</select>
<noscript><button type="submit">Apply</button></noscript>
</form>
{{if .Ops.Paths}}<div class="tw"><table class="ops-t"><thead>
<tr><th>route</th><th class="n">n</th><th class="n">p50</th><th class="n">p95</th><th class="n">max</th></tr>
</thead><tbody>
{{range .Ops.Paths}}<tr><td><a href="/fleet/ops/route?path={{.Path}}"><code>{{.Path}}</code></a></td><td class="n">{{.Count}}</td>
<td class="n">{{.P50Ms}}ms</td><td class="n{{if gt .P95Ms $.Ops.BudgetMs}} ci-fail-text{{end}}">{{.P95Ms}}ms</td>
<td class="n">{{.MaxMs}}ms</td></tr>{{end}}
</tbody></table></div>{{else}}<p class="tn-empty">Nothing served yet.</p>{{end}}

<h2>Store subprocesses</h2>
<p class="tn-lede">Every call to the store is a process. What matters is how many
run at once — one slow listing is a note, the same listing thirteen times over
is an incident.</p>
{{if .Ops.Verbs}}<div class="tw"><table class="ops-t"><thead>
<tr><th>verb</th><th class="n">calls</th><th class="n">total</th><th class="n">slowest</th></tr>
</thead><tbody>
{{range .Ops.Verbs}}<tr><td><code>zit {{.Verb}}</code></td><td class="n">{{.Count}}</td>
<td class="n">{{.TotalMs}}ms</td><td class="n{{if gt .MaxMs 1000}} ci-fail-text{{end}}">{{.MaxMs}}ms</td></tr>{{end}}
</tbody></table></div>{{else}}<p class="tn-empty">No store calls in the window.</p>{{end}}

<h2>Recent renders</h2>
<p class="tn-lede"><a href="/fleet/ops/history">deeper history &rarr;</a> — these are
the last few hundred renders in THIS process's memory, which is the right answer to
"what is happening now" and the wrong one to "when did this start".</p>
<p class="tn-lede">ops time contains zit time. <em>rest</em> is what is left after
ops — template execution and the server's own overhead. The ops column minus zit
is index and OLTP queries plus registry work: SQL is not timed separately, because
the driver offers no connector to wrap, so it is legible only by subtraction.</p>
{{if .Ops.Renders}}<div class="tw"><table class="ops-t"><thead>
<tr><th>when</th><th>request</th><th class="n">total</th><th class="n">ops</th><th class="n">of which zit</th><th class="n">rest</th><th class="n">status</th></tr>
</thead><tbody>
{{- /* The path actually requested, not the pattern: a dozen rows all
       reading GET /r/{repo}/timeline cannot say which repository was
       slow, which is the first thing anybody asks. The route stays
       beside it, as the link to its drilldown. */ -}}
{{range .Ops.Renders}}<tr><td class="tl-meta-inline">{{clock .At}}</td>
<td><code>{{if .URL}}{{.URL}}{{else}}{{.Path}}{{end}}</code>
{{if .URL}}<a class="ops-route-l" href="/fleet/ops/route?path={{.Path}}" title="all renders of this route">{{.Path}}</a>{{end}}</td>
<td class="n{{if gt .ElapsedMs $.Ops.BudgetMs}} ci-fail-text{{end}}">{{.ElapsedMs}}ms</td>
<td class="n">{{.OpsMs}}ms</td><td class="n">{{.ZitMs}}ms</td>
<td class="n">{{rest .ElapsedMs .OpsMs}}ms</td>
<td class="n">{{.Status}}</td></tr>{{end}}
</tbody></table></div>{{else}}<p class="tn-empty">Nothing served yet.</p>{{end}}
</div>{{end}}

{{define "content"}}
<div class="t-head"><h1>Operations</h1>
{{template "fleet-nav" .}}</div>
<p class="tn-lede">What this forge is doing right now — while it starts up and
indexes, while it syncs, and at rest. A snapshot and a recent window; history
lives in the analytics store.</p>
<div data-init="@get('/fleet/ops.frag')" data-on-interval__duration.3s="@get('/fleet/ops.frag')">
{{template "ops-body" .}}
</div>
{{end}}`

// One route, opened up. The panel finds a slow route; this says why.
//
// Two things the roll-up cannot show. Which REPOSITORY — a route
// pattern folds pikchr and tcl into one line, and repository size is
// the dominant cost on this fleet. And which CALLS — the render list
// and the subprocess list were independent tables until requests were
// tagged, so a slow page and the store work behind it could not be
// connected even when one caused the other.
type opsHistoryView struct {
	Rows []struct {
		At        string `json:"at"`
		Path      string `json:"path"`
		URL       string `json:"url"`
		Repo      string `json:"repo"`
		ElapsedMs int64  `json:"elapsedMs"`
		OpsMs     int64  `json:"opsMs"`
		ZitMs     int64  `json:"zitMs"`
		Status    int    `json:"status"`
	} `json:"rows"`
	Find  string `json:"find"`
	Repo  string `json:"repo"`
	Sort  string `json:"sort"`
	Days  int    `json:"days"`
	Store struct {
		Configured bool   `json:"configured"`
		Path       string `json:"path"`
		Err        string `json:"err"`
		Kept       string `json:"kept"`
	} `json:"store"`
}

// DayChoices are the windows the control offers, capped at the op's own
// maximum so a reader cannot pick one the API will refuse.
func (opsHistoryView) DayChoices() []int { return []int{1, 7, 14, 30, 90} }

var opsHistoryPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
<div class="tn-head"><h1>History</h1>
<span class="tn-acts"><a class="tn-new" href="/fleet/ops">&larr; operations</a></span></div>
<p class="tn-lede">Renders read back from the durable store, which survives a
restart. The panels on the operations page are one process's memory and answer
"what is happening now"; this answers "when did it start".</p>

<form class="tl-controls" action="/fleet/ops/history" method="get">
<input type="search" name="find" value="{{.OpsHistory.Find}}" placeholder="filter route or path" aria-label="filter">
<select name="sort" aria-label="sort by" onchange="this.form.submit()">
<option value="recent"{{if ne .OpsHistory.Sort "slowest"}} selected{{end}}>most recent</option>
<option value="slowest"{{if eq .OpsHistory.Sort "slowest"}} selected{{end}}>slowest first</option>
</select>
<select name="days" aria-label="window" onchange="this.form.submit()">
{{range .OpsHistory.DayChoices}}<option value="{{.}}"{{if eq . $.OpsHistory.Days}} selected{{end}}>{{.}} days</option>{{end}}
</select>
<noscript><button type="submit">Apply</button></noscript>
</form>

{{if not .OpsHistory.Store.Configured}}
<p class="tn-empty">History is off, so there is nothing to read back. Start with
<code>--analytics &lt;dir&gt;</code> to keep it.</p>
{{else if .OpsHistory.Store.Err}}
<p class="tn-empty ci-fail-text">The analytics store is not readable:
{{.OpsHistory.Store.Err}}</p>
{{else if .OpsHistory.Rows}}
<div class="tw"><table class="ops-t"><thead>
<tr><th>when</th><th>request</th><th class="n">total</th><th class="n">ops</th><th class="n">of which zit</th><th class="n">rest</th><th class="n">status</th></tr>
</thead><tbody>
{{range .OpsHistory.Rows}}<tr><td class="tl-meta-inline">{{.At}}</td>
<td><code>{{if .URL}}{{.URL}}{{else}}{{.Path}}{{end}}</code>
<a class="ops-route-l" href="/fleet/ops/route?path={{.Path}}">{{.Path}}</a></td>
<td class="n{{if gt .ElapsedMs $.Ops.BudgetMs}} ci-fail-text{{end}}">{{.ElapsedMs}}ms</td>
<td class="n">{{.OpsMs}}ms</td><td class="n">{{.ZitMs}}ms</td>
<td class="n">{{rest .ElapsedMs .OpsMs}}ms</td>
<td class="n">{{.Status}}</td></tr>{{end}}
</tbody></table></div>
<p class="tn-lede">{{len .OpsHistory.Rows}} renders{{with .OpsHistory.Find}} matching
<code>{{.}}</code>{{end}} in the last {{.OpsHistory.Days}} days{{with .OpsHistory.Store.Kept}},
which is kept for {{.}}{{end}}.</p>
{{else}}
<p class="tn-empty">No renders{{with .OpsHistory.Find}} matching <code>{{.}}</code>{{end}}
in the last {{.OpsHistory.Days}} days.</p>
{{end}}
{{end}}`))

var opsRoutePage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
<div class="tn-head"><h1>Route</h1>
<span class="tn-acts"><a class="tn-new" href="/fleet/ops">&larr; operations</a></span></div>
<p class="ops-route-p"><code>{{.OpsRoute.Path}}</code></p>

{{if .OpsRoute.ByRepo}}<h2>By repository</h2>
<p class="tn-lede">The variable the route pattern hides. A page costs what its
store costs, and these differ by orders of magnitude.</p>
<div class="tw"><table class="ops-t"><thead>
<tr><th>repository</th><th class="n">n</th><th class="n">p50</th><th class="n">max</th></tr>
</thead><tbody>
{{range .OpsRoute.ByRepo}}<tr><td>{{if .Repo}}<a href="/r/{{pathesc .Repo}}">{{.Repo}}</a>{{else}}<span class="tl-meta-inline">(none)</span>{{end}}</td>
<td class="n">{{.Count}}</td><td class="n">{{.P50Ms}}ms</td>
<td class="n{{if gt .MaxMs $.Ops.BudgetMs}} ci-fail-text{{end}}">{{.MaxMs}}ms</td></tr>{{end}}
</tbody></table></div>{{end}}

{{- /* The panels above are one process's memory. The question after a
       deploy is not "how fast is this now" but "is this worse than it
       was", and until history was read back nothing on this page could
       answer it. */ -}}
{{if .OpsRoute.Trend}}<h2>Across days</h2>
<p class="tn-lede">From the durable store, not from memory: this survives a
restart. p95 by nearest rank, the same way the snapshot above computes it, so
the two agree about the same window.</p>
<div class="tw"><table class="ops-t"><thead>
<tr><th>day</th><th class="n">n</th><th class="n">p50</th><th class="n">p95</th><th class="n">max</th></tr>
</thead><tbody>
{{range .OpsRoute.Trend}}<tr><td class="tl-meta-inline">{{.Day}}</td>
<td class="n">{{.N}}</td><td class="n">{{.P50Ms}}ms</td>
<td class="n{{if gt .P95Ms $.Ops.BudgetMs}} ci-fail-text{{end}}">{{.P95Ms}}ms</td>
<td class="n{{if gt .MaxMs $.Ops.BudgetMs}} ci-fail-text{{end}}">{{.MaxMs}}ms</td></tr>{{end}}
</tbody></table></div>
{{else if .Ops.Store.Configured}}
<p class="tn-empty">No history for this route in the last {{.OpsRoute.TrendDays}} days.</p>
{{else}}
<p class="tn-empty">History is off, so there is nothing to compare against.
The panels below are this process's live window only.</p>
{{end}}

<h2>Recent requests</h2>
<p class="tn-lede">Each one with the store calls it made, in the order it made
them. A request with no calls listed spent its time somewhere else — which is
itself the answer when the store is not to blame.</p>
{{if .OpsRoute.Renders}}<ul class="ops-reqs">{{range .OpsRoute.Renders}}
<li class="ops-req">
<div class="ops-req-h">
<span class="ops-req-t{{if gt .ElapsedMs $.Ops.BudgetMs}} ci-fail-text{{end}}">{{.ElapsedMs}}ms</span>
{{with .Repo}}<a class="ops-req-r" href="/r/{{pathesc .}}">{{.}}</a>{{end}}
<span class="ops-req-m">ops {{.OpsMs}}ms · zit {{.ZitMs}}ms · rest {{rest .ElapsedMs .OpsMs}}ms{{if .Calls}} · {{len .Calls}} store {{plural (len .Calls) "call" "calls"}} totalling {{.CallMs}}ms{{end}} · {{.Status}}</span>
<span class="ops-req-w">{{clock .At}}</span>
</div>
{{if .Calls}}<ol class="ops-calls">{{range .Calls}}
<li><code>zit {{.Verb}}</code>{{with .Repo}} <span class="tl-meta-inline">{{.}}</span>{{end}} <span class="n">{{.DurationMs}}ms</span></li>
{{end}}</ol>{{end}}
</li>
{{end}}</ul>
{{else}}<p class="tn-empty">Nothing recent for this route. The window holds the
last few hundred renders; anything older is in the analytics store.</p>{{end}}
{{end}}`))

var peoplePage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
{{template "explore-tabs" .}}
<div class="tl-controls">
<form method="get" action="/people"><input type="search" name="q" value="{{.Query}}" placeholder="filter" aria-label="filter people">
<noscript><button type="submit">go</button></noscript></form>
</div>
{{if .People}}<ul class="people">{{range .People}}
<li><span class="avatar" aria-hidden="true">{{identicon .User}}</span>
<div class="p-main"><a href="/people/{{pathesc .User}}">{{.User}}</a>
<div class="p-meta">{{count .Events}} contribution{{if ne .Events 1}}s{{end}} in {{len .Repos}} repositor{{if eq (len .Repos) 1}}y{{else}}ies{{end}} · last {{ago .Last}}</div></div></li>
{{end}}</ul>
<nav class="pager" aria-label="people pages">
{{if .PrevPage}}<a class="pager-btn" href="/people?page={{.PrevPage}}{{if .Query}}&amp;q={{.Query}}{{end}}">&lsaquo; Newer</a>{{else}}<span class="pager-btn" aria-disabled="true">&lsaquo; Newer</span>{{end}}
<span class="pager-where"><b>{{len .People}}</b> of {{thousands .PeopleTotal}}</span>
{{if .NextPage}}<a class="pager-btn" href="/people?page={{.NextPage}}{{if .Query}}&amp;q={{.Query}}{{end}}">Older &rsaquo;</a>{{else}}<span class="pager-btn" aria-disabled="true">Older &rsaquo;</span>{{end}}
</nav>
{{else}}<p>{{if .Query}}Nobody matches “{{.Query}}”.{{else}}No contributions have been indexed yet.{{end}}</p>{{end}}
{{end}}`))

// The repository's own people. The fleet page answers "who works on
// this forge"; a reader who clicked "151 contributors" inside fossil is
// asking "who works on fossil", and used to be thrown out to a list of
// 481 names across 25 repositories with the repo chrome gone.
//
// Same op, repo bound — people.list has taken a repo parameter all
// along; nothing in the UI reached it. The per-person line differs on
// purpose: the fleet counts repositories, and inside one repository
// that number is always 1, so the span of their work here is the fact
// worth carrying instead.
var repoPeoplePage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
<div class="w-doc w-solo"><div class="w-main">
<div class="tn-head">
<h1>People</h1>
<span class="tn-acts">{{if .CanAdmin}}<a class="tn-new" href="/r/{{.Repo}}/settings#access">manage access &rarr;</a>{{end}}
<a class="tn-new" href="/people">everyone on this forge &rarr;</a></span>
</div>
<p class="tn-lede">Everybody who has an artifact in {{.Repo}} — check-ins, tickets,
wiki edits, forum posts and notes are all contributions.
{{if .CanAdmin}} A name here is what an author&rsquo;s client wrote on the artifact, not an
account on this forge; the badge marks the few who are both.{{end}}</p>
<div class="tl-controls">
<form method="get" action="/r/{{.Repo}}/people"><input type="search" name="q" value="{{.Query}}" placeholder="filter" aria-label="filter people">
<noscript><button type="submit">go</button></noscript></form>
</div>
{{if .People}}<ul class="people">{{range .People}}
<li><span class="avatar" aria-hidden="true">{{identicon .User}}</span>
<div class="p-main"><a href="/r/{{$.Repo}}/timeline?user={{.User}}&amp;y=all">{{.User}}</a>{{with .Role}} <span class="tl-badge role-badge">{{.}}</span>{{end}}
<div class="p-meta">{{count .Events}} contribution{{if ne .Events 1}}s{{end}} ·
{{if eq (agoShort .First) (agoShort .Last)}}{{ago .Last}}{{else}}{{ago .First}} &ndash; {{ago .Last}}{{end}} ·
<a href="/people/{{pathesc .User}}">across the forge</a></div></div></li>
{{end}}</ul>
<nav class="pager" aria-label="people pages">
{{if .PrevPage}}<a class="pager-btn" href="/r/{{.Repo}}/people?page={{.PrevPage}}{{if .Query}}&amp;q={{.Query}}{{end}}">&lsaquo; Newer</a>{{else}}<span class="pager-btn" aria-disabled="true">&lsaquo; Newer</span>{{end}}
<span class="pager-where"><b>{{len .People}}</b> of {{thousands .PeopleTotal}}</span>
{{if .NextPage}}<a class="pager-btn" href="/r/{{.Repo}}/people?page={{.NextPage}}{{if .Query}}&amp;q={{.Query}}{{end}}">Older &rsaquo;</a>{{else}}<span class="pager-btn" aria-disabled="true">Older &rsaquo;</span>{{end}}
</nav>
{{else}}<p>{{if .Query}}Nobody in {{.Repo}} matches &ldquo;{{.Query}}&rdquo;.{{else}}No contributions have been indexed yet.{{end}}</p>{{end}}
</div></div>
{{end}}`))

var personPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
<div class="person-head">
<span class="avatar" aria-hidden="true">{{identicon .Title}}</span>
<div><h1>{{.Title}}</h1>
<p class="p-meta">{{count .Person.Events}} contribution{{if ne .Person.Events 1}}s{{end}} ·
first {{ago .Person.First}} · last {{ago .Person.Last}}</p></div>
</div>
<h2>Repositories</h2>
<ul class="hits">{{range .Person.Repos}}
<li><a href="/r/{{.}}">{{.}}</a></li>
{{end}}</ul>
{{end}}`))

// wikiStructLimit bounds each structure list. Fossil's own wiki has
// over two hundred pages nothing links to; the panel exists to start a
// reader on the work, not to be the work.
const wikiStructLimit = 12

// landingDetail is one record as its page renders it: the record itself,
// the discussion, and what the viewer may do about it.
type landingDetail struct {
	landingRow
	// Events are the state transitions, lifted OUT of the discussion.
	// zit records them as replies because a reply is an artifact fossil
	// understands; a reader wants them as what they are — "dan accepted
	// this" belongs on the record's timeline, not in the conversation.
	Events []landingEvent
	// Description is the opener's body — the proposal itself, not a
	// comment on it.
	Description template.HTML
	// Comments is what is left: the remarks people actually wrote.
	Comments []forumPostRow
	// MergeCI is the verdict on the check-in this record PRODUCED, and
	// MergeCIRun the run behind it. Set only once settled.
	MergeCI    string `json:"mergeCi"`
	MergeCIRun string `json:"mergeCiRun"`
	// ReplyTo aims the composer at one remark, exactly as the forum's
	// ?reply-to does; empty means the reply answers the record itself.
	ReplyTo     string
	ReplyToUser string
	// Stack is the chain this record is part of, bottom-up, for the map
	// above the fold (RFC 0006). Empty for a standalone landing.
	Stack stackView
	// Position is this rung's, counted from 1 at the base.
	Position int
	// Checks is the branch tip's runs; Required and Unmet are RFC
	// 0009's answer for the target branch. MayOverride offers the
	// accept-anyway control.
	Checks      []ciRunRow
	Required    []string
	Unmet       []string
	MayOverride bool
	// AutoBy names who armed auto-land; empty means nobody has.
	AutoBy   string
	Premerge bool
	Behind   int
	// MayLand is CanAccept minus RFC 0007: the target is protected and
	// this viewer is not an owner. Protected and Owners let the
	// disabled control say why.
	MayLand   bool
	Protected bool
	Owners    []string
	// CanAccept and CanSpeak gate the controls. Accepting writes a
	// merge check-in and takes `i`; speaking is a forum capability.
	CanAccept, CanSpeak bool
	// Diff is the branch against its target, computed at view time
	// because the record points at a MOVING branch (zit#127): a diff
	// cached against a frozen range would describe a proposal that no
	// longer exists.
	Diff  *diffDetail
	Stale string // why the diff is absent, when it is
	// Mergeable is the tri-state a forge needs and a checkout does not:
	// "clean", "conflict", or "" for not-yet-knowable. zit#131 phase 1
	// adds the read-only probe that answers it; until then the honest
	// answer is that we do not know, which must NOT read as "clean".
	//
	// A conflicted landing disables accept and names the paths rather
	// than offering a control that would fail — the GitHub shape, and
	// the reason the probe is phase 1: keeping conflicts off the server
	// entirely is worth more than accepting them there.
	Mergeable string
	Conflicts []string
	// Merge is the check-in this landing produced. A settled record
	// pointed at nothing that showed what it actually did: settled_by
	// names the reply that decided the state, not the commit.
	Merge struct {
		Checkin string `json:"checkin"`
		Date    string `json:"date"`
		User    string `json:"user"`
		Comment string `json:"comment"`
	}
	// FullDiff is where the whole change lives. The record shows a
	// window; a reader who wants every line follows this.
	FullDiff string
	// Commits is the branch's own check-ins — a proposal is a set of
	// changes with reasons attached, and the diff alone throws the
	// reasons away. Every forge shows this beside the diff.
	Commits []landingCommit
}

// landingCommit is one check-in on the proposed branch.
type landingCommit struct {
	Hash    string
	Short   string
	User    string
	Date    string
	Comment string
}

// stackView is the record page's map of its strata.
type stackView struct {
	Top      string `json:"top"`
	CI       string `json:"ci"`
	Base     string `json:"base"`
	Broken   string `json:"broken"`
	Segments []struct {
		ID       string `json:"id"`
		Title    string `json:"title"`
		Branch   string `json:"branch"`
		Target   string `json:"target"`
		State    string `json:"state"`
		Position int    `json:"position"`
		Landable bool   `json:"landable"`
		CI       string `json:"ci"`
	} `json:"segments"`
}

// Verdict renders the strata's verdict — the top rung's — as the badge
// the timeline already uses.
func (s stackView) Verdict() template.HTML { return ciBadge(s.CI) }

// RequiredHas says whether either name a run carries is required here.
func (l landingDetail) RequiredHas(names ...string) bool {
	for _, r := range l.Required {
		for _, n := range names {
			if n != "" && r == n {
				return true
			}
		}
	}
	return false
}

// checksSummary is the roll-up line the decision card leads with
// (RFC 0009): one sentence, the way GitHub's merge box reads, computed
// from the same rows the expansion shows.
type checksSummary struct {
	// Merge marks a verdict about the check-in the record PRODUCED
	// rather than about its branch tip, so the panel can say which
	// question it is answering.
	Merge    bool
	State    string // pass | fail | wait
	Headline string
	Subline  string
	Open     bool // expand the rows when something needs attention
}

func (l landingDetail) ChecksSummary() checksSummary {
	var pass, fail, run int
	var failing []string
	name := func(c ciRunRow) string {
		if c.Pipeline != "" && c.Pipeline != "external" {
			return c.Pipeline
		}
		return c.Workflow
	}
	for _, c := range l.Checks {
		switch {
		case c.Status == "completed" || c.Status == "succeeded" || c.Status == "success":
			pass++
		case c.Status == "failed" || c.Status == "error" || c.Status == "cancelled" || c.Status == "canceled":
			fail++
			failing = append(failing, name(c))
		default:
			run++
		}
	}
	waiting := l.MissingChecks()
	plural := func(n int, word string) string {
		if n == 1 {
			return "1 " + word
		}
		return fmt.Sprintf("%d %ss", n, word)
	}
	// A settled record reports the MERGE. The checks above are the
	// branch tip's — the right answer to decide on, the wrong one to
	// act on afterwards, because the tip describes a proposal while the
	// merge describes what the target now is. Reporting only the tip is
	// what let this panel say "all checks have passed" beside a
	// timeline saying the check-in it produced failed.
	if l.MergeCI != "" {
		switch l.MergeCI {
		case "ci-fail":
			return checksSummary{State: "fail", Open: true, Merge: true,
				Headline: "The merge this produced is failing",
				Subline:  "the branch passed before it landed"}
		case "ci-pass":
			return checksSummary{State: "pass", Merge: true,
				Headline: "The merge this produced passed"}
		}
	}
	switch {
	case fail > 0:
		return checksSummary{State: "fail", Open: true,
			Headline: plural(fail, "failing check"),
			Subline:  strings.Join(failing, ", ")}
	case len(waiting) > 0 || len(l.Unmet) > 0:
		names := waiting
		if len(names) == 0 {
			names = l.Unmet
		}
		return checksSummary{State: "wait", Open: true,
			Headline: "Waiting for " + plural(len(names), "required check"),
			Subline:  strings.Join(names, ", ")}
	case run > 0:
		return checksSummary{State: "wait", Open: true,
			Headline: plural(run, "check") + " in flight",
			Subline:  plural(pass, "check") + " passed so far"}
	default:
		return checksSummary{State: "pass",
			Headline: "All checks have passed",
			Subline:  plural(pass, "successful check")}
	}
}

// OrderedChecks sorts the panel for attention: failed first, then
// running, then passed — the reader's question is "what is wrong",
// answered before the reassurance (RFC 0009, the Buildkite spine).
func (l landingDetail) OrderedChecks() []ciRunRow {
	rank := func(status string) int {
		switch status {
		case "completed", "succeeded", "success":
			return 2
		case "failed", "error", "cancelled", "canceled":
			return 0
		}
		return 1
	}
	out := make([]ciRunRow, len(l.Checks))
	copy(out, l.Checks)
	sort.SliceStable(out, func(i, j int) bool { return rank(out[i].Status) < rank(out[j].Status) })
	return out
}

// MissingChecks names the required checks with no run at all — drawn
// as waiting, because absence must read as blocking, not as fine.
func (l landingDetail) MissingChecks() []string {
	var out []string
	for _, r := range l.Required {
		found := false
		for _, c := range l.Checks {
			if c.Workflow == r || c.Pipeline == r {
				found = true
			}
		}
		if !found {
			out = append(out, r)
		}
	}
	return out
}

// OwnersText names the owners for a title or a sentence.
func (l landingDetail) OwnersText() string { return strings.Join(l.Owners, ", ") }

// AcceptState says what the accept control should be: "go" to offer it,
// "conflict" or "landed" to show it disabled with a reason, "" to render
// nothing. One function so the button and the reason cannot disagree.
func (l landingDetail) AcceptState() string {
	if !l.CanAccept || l.State != "open" {
		return ""
	}
	// Protection first: a conflict on a branch this viewer may not
	// land is still, to them, a branch they may not land.
	if l.Protected && !l.MayLand {
		return "protected"
	}
	switch l.Mergeable {
	case "stacked":
		// Above the bottom of a strata: zit#144 refuses the accept,
		// so the control is not offered (RFC 0006).
		return "stacked"
	case "conflict":
		return "conflict"
	case "up-to-date":
		// The branch is ALREADY on the target — merged by hand, or by
		// another landing. Accepting settles the record with nothing to
		// merge — zit answers "merges up-to-date" — and the fold reads
		// it as accepted by ancestry; but there is still nothing here to
		// LAND, so the control says so. (Earlier zit refused this case:
		// "already contained in
		// 'trunk'; nothing to land") and is right to: there is no merge
		// to make. Offering accept anyway produced exactly the error
		// this state exists to prevent.
		return "landed"
	}
	// RFC 0009: the machine's verdict gates last — a conflict or a
	// protection is a harder fact than a red check.
	if len(l.Unmet) > 0 {
		return "checks"
	}
	return "go"
}

// landingEvent is one state transition on the record's timeline.
type landingEvent struct {
	// Merge is the check-in an update wrote, for the event's link.
	Merge string
	State string
	// Detail names what the event acted on — the new target for a
	// retarget. Empty for the state transitions, which act on the
	// record itself and have nothing to name.
	Detail string
	User   string
	Date   string
	HTML   template.HTML // the transition's own remark, when it carried one
}

// landingRow is one record in the listing.
type landingRow struct {
	ID      string `json:"id"`
	Branch  string `json:"branch"`
	Target  string `json:"target"`
	Title   string `json:"title"`
	Author  string `json:"author"`
	Opened  string `json:"opened"`
	Updated string `json:"updated"`
	State   string `json:"state"`
	// Replies is the thread's remark count, state transitions excluded —
	// the same reading the ticket list gives a conversation.
	Replies int `json:"replies"`
	// SupersededBy names the landing this one defers to, when two were
	// opened on one branch. Empty is the ordinary case.
	SupersededBy string `json:"superseded_by"`
	// ClaimedBy is a reply that asserted acceptance while nothing was
	// merged (RFC 0007): the record is open and says a claim was made.
	ClaimedBy string `json:"claimed_by"`
	// CI is the branch tip's recorded verdict, empty when no run has
	// written one.
	CI string `json:"ci"`
	// RFC 0006's reading: the base's id, this rung counted from 1 at
	// the base, the stack's height, and why the chain cannot be walked.
	Stack    string `json:"stack"`
	Position int    `json:"position"`
	Depth    int    `json:"depth"`
	Broken   string `json:"broken"`
}

// landingGroup is one row of the open queue: a landing, and the rungs
// stacked on it when it is the base of a strata. A stack is ONE row
// because the list is a queue and a queue that shows five rows for one
// decision counts wrong; the count chip counts decisions.
type landingGroup struct {
	landingRow
	Segments []landingRow // bottom-up, base first; nil for a standalone
}

// TooTall reports a strata past what the page draws (index.MaxDrawnRungs).
func (g landingGroup) TooTall() bool { return len(g.Segments) > index.MaxDrawnRungs }

// TooTall reports a map past what the page draws.
func (s stackView) TooTall() bool { return len(s.Segments) > index.MaxDrawnRungs }

// StackVerdict is the top rung's verdict: its tip contains every rung
// below, so a run there speaks for the stack.
func (g landingGroup) StackVerdict() template.HTML {
	if n := len(g.Segments); n > 0 {
		return ciBadge(g.Segments[n-1].CI)
	}
	return ""
}

// groupLandings folds an open listing into rows, one per decision.
// Rungs above a base fold under it in position order; a rung whose
// base is not in the listing (rejected, or landed and not yet
// retargeted) heads its own row and says why it is not landable.
func groupLandings(rows []landingRow) []landingGroup {
	byID := map[string]int{}
	var out []landingGroup
	for _, r := range rows {
		if r.Stack == "" || r.Position == 1 {
			byID[r.ID] = len(out)
			out = append(out, landingGroup{landingRow: r})
		}
	}
	for _, r := range rows {
		if r.Stack == "" || r.Position == 1 {
			continue
		}
		i, ok := byID[r.Stack]
		if !ok {
			out = append(out, landingGroup{landingRow: r})
			continue
		}
		out[i].Segments = append(out[i].Segments, r)
	}
	for i := range out {
		if out[i].Segments == nil {
			continue
		}
		segs := append([]landingRow{out[i].landingRow}, out[i].Segments...)
		for a := 1; a < len(segs); a++ {
			for b := a; b > 0 && segs[b].Position < segs[b-1].Position; b-- {
				segs[b], segs[b-1] = segs[b-1], segs[b]
			}
		}
		out[i].Segments = segs
	}
	return out
}

// Verdict renders the branch tip's CI result, reusing the timeline's
// badge: a reader already knows what pass and fail look like here, and
// a second vocabulary for the same idea would be one to learn.
func (l landingRow) Verdict() template.HTML { return ciBadge(l.CI) }

// Glyph and Icon name the row's state mark, reusing the tracker's sprite:
// the same three-way open/settled/done reading a reader already knows from
// the ticket list rather than a second vocabulary for the same idea.
func (l landingRow) Glyph() string {
	if l.State == "open" {
		return "open"
	}
	return "done"
}

func (l landingRow) Icon() string {
	switch l.State {
	case "accepted":
		return "i-tkt-done"
	case "rejected":
		return "i-tkt-done"
	}
	return "i-tkt-open"
}

// wikiWant is a page name the wiki reaches for and has not got.
type wikiWant struct {
	Title string
	Links int
	// From is the pages asking for it, so a reader can go and see what
	// reached for the name before writing it.
	From []string
}

// wikiStructPage is one of the two structure lists shown in full. The
// panel on the docs index is a PREVIEW — it was capped at twelve with
// "and 66 more" in plain text, which is a dead end wearing a summary's
// clothes.
var wikiStructPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
<p class="w-crumb"><a href="/r/{{.Repo}}/docs">docs</a> / <span>{{if eq .StructKind "wanted"}}wanted pages{{else}}nothing links here{{end}}</span></p>
{{if eq .StructKind "wanted"}}
<p class="w-lead">Names a page links to with <code>[[double brackets]]</code> that nobody has written yet. Writing one makes every link to it work at once.</p>
{{if .WikiWanted}}<ul class="w-links w-links-full">{{range .WikiWanted}}
<li><a class="w-link-t" href="/r/{{$.Repo}}/wiki-new?name={{pathesc .Title}}">{{.Title}}</a>
<span class="w-from">wanted by {{range $i, $p := .From}}{{if $i}}, {{end}}<a href="/r/{{$.Repo}}/wiki/{{pathesc $p}}">{{$p}}</a>{{end}}</span></li>
{{end}}</ul>{{else}}<p class="t-none">Every link in this wiki goes somewhere.</p>{{end}}
{{else}}
<p class="w-lead">Live pages that no other page links to. Reachable only by knowing the name — which usually means nobody finds them.</p>
{{if .WikiOrphans}}<ul class="w-links w-links-full">{{range .WikiOrphans}}
<li><a class="w-link-t" href="/r/{{$.Repo}}/wiki/{{pathesc .}}">{{.}}</a></li>
{{end}}</ul>{{else}}<p class="t-none">Every page here is linked from somewhere.</p>{{end}}
{{end}}
{{template "ticket-pager" .}}
{{end}}`))

var landingListPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
{{- /* What is awaiting decision. The shape is the tracker's, because it
       answers the same question about different work: state segments with
       counts, then a row per record with the title first. A landing is a
       branch proposed for a target, so the row leads with that pair — it
       is the one fact a reader needs before opening anything. */ -}}
<div class="t-head">
<nav class="t-states seg-box">
<a href="/r/{{.Repo}}/landing"{{if not .Nav.State}} class="here"{{end}}><svg class="ic g-open" aria-hidden="true"><use href="#i-tkt-open"/></svg>{{count .LandingOpen}} Open</a>
<a href="/r/{{.Repo}}/landing?state=accepted"{{if eq .Nav.State "accepted"}} class="here"{{end}}>Accepted</a>
<a href="/r/{{.Repo}}/landing?state=rejected"{{if eq .Nav.State "rejected"}} class="here"{{end}}>Rejected</a>
<a href="/r/{{.Repo}}/landing?state=all"{{if eq .Nav.State "all"}} class="here"{{end}}>All</a>
</nav>
{{- /* Proposing needs somewhere to propose INTO, so a mirror offers
       the upstream instead of a control that cannot write here. */ -}}
<div class="t-tools">
{{if .Posture.ReadOnly}}<a class="btn" href="{{.Posture.Upstream "forum"}}">Propose on {{.Posture.Host}} &rarr;</a>
{{else if .CanWrite}}<a class="btn btn-primary act-icon" href="/r/{{.Repo}}/landing-new" title="New landing" aria-label="New landing"><svg class="ic" aria-hidden="true"><use href="#i-plus"/></svg><span class="act-label">New landing</span></a>{{end}}
</div>
</div>
{{- /* RFC 0006: a strata is one row, the base's, with a strata mark
       and the rungs folded under it in a details element — no script,
       and the count above counts decisions. A settled view is flat. */ -}}
{{if .LandingGroups}}<ul class="tickets">{{range .LandingGroups}}
<li class="t-row{{if .Segments}} t-strata{{end}}">
<svg class="ic t-glyph g-{{.Glyph}}" aria-hidden="true"><use href="#{{.Icon}}"/></svg>
<div class="t-main">
<a class="t-title" href="/r/{{$.Repo}}/landing/{{printf "%.12s" .ID}}">{{clip 72 (unmark (firstline .Title))}}</a>
{{if .Segments}}<div class="t-sub"><span class="t-status st-open">strata</span> · {{len .Segments}} segments ·
<code class="l-branch">{{.Branch}}</code> &rarr; <code class="l-branch">{{.Target}}</code>{{if .Broken}} · <span class="ci-fail-text">{{.Broken}}</span>{{else}} landable{{end}}{{with .StackVerdict}} · stack {{.}}{{end}}</div>
{{if .TooTall}}<p class="tl-meta-inline">too tall to fold here — open the base and walk it from the map</p>{{else}}<details class="strata"><summary>the segments, bottom-up</summary>
<ol class="strata-rungs">{{range .Segments}}<li>
<span class="t-status{{if eq .Position 1}}{{if not .Broken}} st-done{{end}}{{end}}" title="rung {{.Position}} of {{.Depth}}">{{.Position}}/{{.Depth}}</span>
<a href="/r/{{$.Repo}}/landing/{{printf "%.12s" .ID}}">{{firstline .Title}}</a>
<code class="l-branch">{{.Branch}}</code> &rarr; <code class="l-branch">{{.Target}}</code>
{{with .Verdict}}{{.}}{{end}}</li>{{end}}</ol></details>{{end}}
{{else}}<div class="t-sub"><code class="l-branch">{{.Branch}}</code> &rarr; <code class="l-branch">{{.Target}}</code>
 · opened {{ago .Opened}}{{if .Author}} by {{who $.Repo .Author}}{{end}}{{if ne .Updated .Opened}} · updated {{ago .Updated}}{{end}}{{if .Broken}} · <span class="ci-fail-text">{{.Broken}}</span>{{end}}</div>{{end}}
</div>
<div class="t-tail">
{{if .Replies}}<a class="t-conv" href="/r/{{$.Repo}}/landing/{{printf "%.12s" .ID}}#discussion" title="{{.Replies}} repl{{if eq .Replies 1}}y{{else}}ies{{end}}"><svg class="ic" aria-hidden="true"><use href="#i-comment"/></svg>{{.Replies}}</a>{{end}}
{{with .Verdict}}{{.}} {{end}}{{if .SupersededBy}}<span class="t-status st-open">superseded</span>{{end}}
</div>
</li>
{{end}}</ul>
{{else if .Landings}}<ul class="tickets">{{range .Landings}}
<li class="t-row">
<svg class="ic t-glyph g-{{.Glyph}}" aria-hidden="true"><use href="#{{.Icon}}"/></svg>
<div class="t-main">
<a class="t-title" href="/r/{{$.Repo}}/landing/{{printf "%.12s" .ID}}">{{clip 72 (unmark (firstline .Title))}}</a>
<div class="t-sub"><code class="l-branch">{{.Branch}}</code> &rarr; <code class="l-branch">{{.Target}}</code>
 · opened {{ago .Opened}}{{if .Author}} by {{who $.Repo .Author}}{{end}}{{if ne .Updated .Opened}} · updated {{ago .Updated}}{{end}}</div>
</div>
{{- /* One grid cell, not several: t-row is a three-column grid, and a
       fourth child wraps to an implicit row under the glyph instead of
       sitting at the end of this one. */ -}}
<div class="t-tail">
{{if .Replies}}<a class="t-conv" href="/r/{{$.Repo}}/landing/{{printf "%.12s" .ID}}#discussion" title="{{.Replies}} repl{{if eq .Replies 1}}y{{else}}ies{{end}}"><svg class="ic" aria-hidden="true"><use href="#i-comment"/></svg>{{.Replies}}</a>{{end}}
{{with .Verdict}}{{.}} {{end}}{{if .SupersededBy}}<span class="t-status st-open">superseded</span>
{{else if ne .State "open"}}<span class="t-status st-{{if eq .State "accepted"}}done{{else}}open{{end}}">{{.State}}</span>{{end}}
</div>
</li>
{{end}}</ul>
{{else}}<p class="t-none">{{if .Nav.State}}Nothing {{.Nav.State}}.{{else}}No branch is awaiting a decision.{{end}}</p>{{end}}
{{end}}`))

// landingSource is the record page, a constant so a test can read what
// it says without a store to render it against.
const landingSource = `{{- /* The decision controls, out of the composer: accept, land and
       update take the check-in capability and reject the forum one, so
       a reviewer who may land but may not post still gets a control —
       and a form to press it in. */ -}}
{{define "landing-decide"}}{{- /* zit#152: bring the target into the branch on the store. Offered
       only when the probe says the merge is clean — when it says
       conflict the verb refuses and the steps stay, and a control that
       would fail is not offered. Writes to the PROPOSED branch, so it
       follows the check-in capability, not ownership of the target. */ -}}
{{if and (eq $.Landing.Mergeable "clean") (gt $.Landing.Behind 0) $.Landing.CanAccept (eq $.Landing.State "open")}}<button type="submit" class="btn" formaction="/r/{{$.Repo}}/landing/{{printf "%.12s" $.Landing.ID}}/update" title="merge {{$.Landing.Target}} into {{$.Landing.Branch}} on the store, so the record and its CI see the combined state"><span class="b-long">Update from {{$.Landing.Target}}</span><span class="b-abbr">Update</span></button>{{end}}
{{if eq $.Landing.AcceptState "go"}}<button type="submit" class="btn-primary" formaction="/r/{{$.Repo}}/landing/{{printf "%.12s" $.Landing.ID}}/accept"><span class="b-long">Accept and land</span><span class="b-abbr">Accept</span></button>
{{if gt (len $.Landing.Stack.Segments) 1}}<button type="submit" class="btn" formaction="/r/{{$.Repo}}/landing/{{printf "%.12s" $.Landing.Stack.Top}}/land" title="accept every rung of the strata, bottom-up"><span class="b-long">Land strata ({{len $.Landing.Stack.Segments}})</span><span class="b-abbr">Land &times;{{len $.Landing.Stack.Segments}}</span></button>{{end}}
{{else if eq $.Landing.AcceptState "conflict"}}<button type="button" class="btn-primary" disabled title="resolve the conflict first"><span class="b-long">Accept and land</span><span class="b-abbr">Accept</span></button>
{{else if eq $.Landing.AcceptState "landed"}}<button type="button" class="btn-primary" disabled title="already on the target — there is nothing left to merge"><span class="b-long">Accept and land</span><span class="b-abbr">Accept</span></button>
{{- /* A control that would fail is not offered (docs/landings.md);
       one that names why is better than none. Forge policy, said as
       forge policy: not a capability, and not fossil's. */ -}}
{{else if eq $.Landing.AcceptState "stacked"}}<button type="button" class="btn-primary" disabled title="stacked: the segment below must land first"><span class="b-long">Accept and land</span><span class="b-abbr">Accept</span></button>
{{- /* RFC 0006, the one thing every other stack implementation had and
       strata did not: land the rungs below and this one in sequence.
       Each is an ordinary accept; the first that will not merge stops
       the walk, and what landed stays landed. */ -}}
<button type="submit" class="btn" formaction="/r/{{$.Repo}}/landing/{{printf "%.12s" $.Landing.ID}}/land" title="accept every rung below, then this one">Land up to here ({{$.Landing.Position}} rungs)</button>
<span class="tl-meta-inline">stacked — the segment below lands first</span>
{{else if eq $.Landing.AcceptState "checks"}}<button type="button" class="btn-primary" disabled title="required checks are not green"><span class="b-long">Accept</span></button>
<span class="tl-meta-inline">required checks not green: {{range $i, $c := $.Landing.Unmet}}{{if $i}}, {{end}}<code>{{$c}}</code>{{end}}</span>
{{- /* RFC 0009: override is the owner's, said out loud — the reason is
       recorded on the record before the merge is written. The control
       exists only for who may use it; everyone else reads why the
       accept is closed. */ -}}
{{if $.Landing.MayOverride}}<details class="ci-override"><summary>Accept anyway</summary>
<p><input name="override" size="40" maxlength="300" placeholder="why this lands red" required aria-label="override reason">
<button type="submit" class="btn-warn" formaction="/r/{{$.Repo}}/landing/{{printf "%.12s" $.Landing.ID}}/accept">Accept over red checks</button></p>
</details>{{end}}
{{- /* RFC 0009 §verdicts, the follow-through: the decision made now,
       executed when the machine agrees. The deferred accept is the
       ordinary one, as the arming account, so every gate re-applies
       when it fires. */ -}}
{{if $.Landing.AutoBy}}<span class="tl-meta-inline">auto-land armed by {{$.Landing.AutoBy}} — accepts itself when the checks go green</span>
<button type="submit" class="btn" formaction="/r/{{$.Repo}}/landing/{{printf "%.12s" $.Landing.ID}}/auto" name="on" value="false">Cancel auto-land</button>
{{else}}<button type="submit" class="btn" formaction="/r/{{$.Repo}}/landing/{{printf "%.12s" $.Landing.ID}}/auto" name="on" value="true" title="accept and land automatically once every required check is green"><span class="b-long">Land when green</span><span class="b-abbr">Auto</span></button>{{end}}
{{else if eq $.Landing.AcceptState "protected"}}<button type="button" class="btn-primary" disabled title="{{$.Landing.Target}} is protected; owners: {{$.Landing.OwnersText}}"><span class="b-long">Accept and land</span><span class="b-abbr">Accept</span></button>
<span class="tl-meta-inline"><code>{{$.Landing.Target}}</code> is protected on this forge; owners: {{$.Landing.OwnersText}}</span>{{end}}
{{end}}
{{define "content"}}
{{with .Landing}}
{{- /* The record. Branch → target leads, because that pair IS the
       proposal; then who and when, then the decision controls. */ -}}
{{- /* No h1 here: base draws the page's visible heading for a detail
       page, and the convention is that a detail page keeps it because
       its title says something the tab does not. A second h1 would
       announce the record twice to a screen reader. */ -}}
<div class="l-head">
<p class="l-meta"><span class="t-status st-{{if eq .State "open"}}open{{else}}done{{end}}">{{.State}}</span>
<code class="l-branch">{{.Branch}}</code> &rarr; <code class="l-branch">{{.Target}}</code>
{{with .Verdict}} {{.}}{{end}}
· opened {{ago .Opened}}{{if .Author}} by {{who $.Repo .Author}}{{end}}</p>
{{- /* RFC 0007: the merge is the fact and the reply is the claim. A
       reply said "accepted" and nothing was merged, so the record is
       open and says so rather than repeating the claim as a state. */ -}}
{{with $.Landed}}<p class="l-meta"><strong>{{.}}</strong> rung{{if ne . "1"}}s{{end}} landed{{with $.Stopped}}; stopped at <a href="/r/{{$.Repo}}/landing/{{.}}">{{.}}</a> — it would not merge, and what landed stays landed{{end}}.</p>{{end}}
{{if .ClaimedBy}}<p class="l-meta">acceptance was claimed in the discussion, but nothing has been merged to <code>{{.Target}}</code> — the record stays open</p>{{end}}
{{- /* RFC 0006: the stack map. Every rung bottom-up, this one marked,
       the landable one named; a rejected base drawn as a broken rung,
       not only said. */ -}}
{{if .Stack.Segments}}<div class="strata-map">
<p class="l-meta"><span class="t-status st-open">strata</span> · {{len .Stack.Segments}} segments{{if .Stack.Broken}} · <span class="ci-fail-text">{{.Stack.Broken}}</span>{{end}}{{with .Stack.Verdict}} · stack {{.}}{{end}}</p>
{{if .Stack.TooTall}}<p class="tl-meta-inline">too tall to draw: {{len .Stack.Segments}} rungs. This is rung {{.Position}}; the base is <a href="/r/{{$.Repo}}/landing/{{printf "%.12s" .Stack.Base}}">here</a>.</p>{{else}}<ol class="strata-rungs">{{range .Stack.Segments}}<li{{if eq .ID $.Landing.ID}} class="here" aria-current="true"{{end}}>
<span class="t-status{{if .Landable}} st-done{{end}}">{{.Position}}/{{len $.Landing.Stack.Segments}}</span>
{{if eq .ID $.Landing.ID}}<strong>{{firstline .Title}}</strong>{{else}}<a href="/r/{{$.Repo}}/landing/{{printf "%.12s" .ID}}">{{firstline .Title}}</a>{{end}}
<code class="l-branch">{{.Branch}}</code> &rarr; <code class="l-branch">{{.Target}}</code>{{if .Landable}} · landable{{end}}{{if ne .State "open"}} · {{.State}}{{end}}</li>{{end}}</ol>{{end}}
</div>{{end}}
</div>
{{chatrefs $.ChatRefs $.Repo}}

{{- /* A conflicted proposal cannot be landed from here, and saying so is
       the whole point: the alternative is a button that fails. The fix is
       the author's to make, so the page names it. */ -}}
{{- /* A settled record's most useful outbound link: what it actually
       did. Only ever present on an accepted landing, so it doubles as
       the difference between "decided" and "landed". */ -}}
{{- /* Two landings on one branch: both records stay, because a record
       somebody argued in is not noise, but only one is current and the
       other has to say where the conversation went. */ -}}
{{if .SupersededBy}}<div class="l-note">
<strong>Superseded.</strong>
<p>A newer landing was opened for <code>{{.Branch}}</code>. This record and its
discussion are kept; the decision belongs to
<a href="/r/{{$.Repo}}/landing/{{printf "%.16s" .SupersededBy}}">the current one</a>.</p>
</div>{{end}}

{{if .Merge.Checkin}}<p class="l-meta">landed as
<a href="/r/{{$.Repo}}/checkin/{{printf "%.16s" .Merge.Checkin}}"><code>{{printf "%.12s" .Merge.Checkin}}</code></a>
· {{ago .Merge.Date}}{{with .Merge.User}} by {{who $.Repo .}}{{end}}</p>{{end}}

{{- /* RFC 0009: the decision card. Where a decision gets made, in one
       place: the checks roll-up (open when something needs attention,
       folded when green), the mergeability, the protection when it
       bites, and the verbs — the merge-box shape every reviewer already
       reads, in this forge's voice. */ -}}
{{if ne .State "settled"}}<div class="l-decide">
{{if or .Checks .Required .MergeCI}}<details class="d-row" id="l-checks"{{if .ChecksSummary.Open}} open{{end}}>
<summary><svg class="ic d-ic {{.ChecksSummary.State}}" aria-hidden="true"><use href="#i-{{if eq .ChecksSummary.State "pass"}}check{{else if eq .ChecksSummary.State "fail"}}x{{else}}clock{{end}}"/></svg>
<span class="d-line"><strong>{{.ChecksSummary.Headline}}</strong> <span class="d-sub">{{.ChecksSummary.Subline}}{{if and .ChecksSummary.Merge .MergeCIRun}} · <a href="/r/{{$.Repo}}/ci/run/{{.MergeCIRun}}">the run</a>{{end}}</span></span></summary>
<div class="d-body">
{{if .Premerge}}<p class="d-sub">premerge: these checks test the MERGED tree — the pair of tips — and a moved target expires them.</p>{{end}}
{{range .MissingChecks}}<p class="l-check"><span class="tl-badge">waiting</span> <code>{{.}}</code> <span class="chip">required</span> <span class="d-meta">no run yet</span></p>
{{end}}{{range .OrderedChecks}}{{if or .Tail .TailNote}}<details class="l-check l-checkfail" open>
<summary><span class="tl-badge ci-fail">{{ciState .Status}}</span>
<code>{{if and .Pipeline (ne .Pipeline "external")}}{{.Pipeline}}{{else}}{{.Workflow}}{{end}}</code>
{{if $.Landing.RequiredHas .Workflow .Pipeline}}<span class="chip">required</span>{{end}}
{{with .TailStep}}<span class="d-sub">step <strong>{{.}}</strong> failed</span>{{end}}
<span class="d-meta"><a href="/r/{{$.Repo}}/ci/run/{{printf "%.12s" .RunID}}">full run &rarr;</a> · {{ago .Started}}</span></summary>
{{if .Tail}}<pre class="runlog">{{range .Tail}}<span class="ll{{if eq .Stream "err"}} ll-err{{end}}{{if eq .Stream "marker"}} ll-mark{{end}}">{{.Data}}</span>{{end}}</pre>{{else}}<p class="d-sub">{{.TailNote}}</p>{{end}}
</details>
{{else}}<p class="l-check"><span class="tl-badge{{if eq (ciState .Status) "pass"}} ci-pass{{else if eq (ciState .Status) "fail"}} ci-fail{{end}}">{{ciState .Status}}</span>
<code>{{if and .Pipeline (ne .Pipeline "external")}}{{.Pipeline}}{{else}}{{.Workflow}}{{end}}</code>{{if eq .Pipeline "external"}} <span class="chip">external</span>{{end}}
{{if $.Landing.RequiredHas .Workflow .Pipeline}}<span class="chip">required</span>{{end}}
<span class="d-meta"><a href="{{if .URL}}{{.URL}}{{else}}/r/{{$.Repo}}/ci/run/{{printf "%.12s" .RunID}}{{end}}">{{if .URL}}details{{else}}logs · run {{printf "%.8s" .RunID}}{{end}}</a> · {{ago .Started}}</span></p>
{{end}}{{end}}{{if .CanAccept}}<form method="post" action="/r/{{$.Repo}}/ci/trigger" class="l-check"><button type="submit" class="btn">Re-run</button>
<input type="hidden" name="back" value="/r/{{$.Repo}}/landing/{{printf "%.12s" .ID}}"></form>{{end}}
</div></details>{{end}}
{{if eq .Mergeable "clean"}}<div class="d-row"><svg class="ic d-ic pass" aria-hidden="true"><use href="#i-check"/></svg>
<span class="d-line"><strong>No conflicts with {{.Target}}</strong> <span class="d-sub">accepting writes the merge check-in</span></span></div>
{{if gt .Behind 0}}<div class="d-row"><svg class="ic d-ic wait" aria-hidden="true"><use href="#i-sync"/></svg>
<span class="d-line"><strong>{{.Target}} has moved</strong> <span class="d-sub">{{.Behind}} check-in{{if ne .Behind 1}}s{{end}} this branch has not seen — it merges cleanly, and updating tests against what you would land on</span></span></div>{{end}}
{{else if eq .Mergeable "conflict"}}<details class="d-row" open>
<summary><svg class="ic d-ic fail" aria-hidden="true"><use href="#i-x"/></svg>
<span class="d-line"><strong>This branch conflicts with {{.Target}}</strong> <span class="d-sub">{{len .Conflicts}} file{{if ne (len .Conflicts) 1}}s{{end}}; the fix is the author's to make</span></span></summary>
<div class="d-body">
{{if .Conflicts}}<ul class="l-paths">{{range .Conflicts}}<li><code>{{.}}</code></li>{{end}}</ul>{{end}}
<p>Merge {{.Target}} into <code>{{.Branch}}</code>, resolve, and push. The record follows the branch, so it will update itself.</p>
<pre class="l-steps">zit update {{.Branch}}
zit merge {{.Target}}
<em># resolve, then</em>
zit commit -m "merge {{.Target}} into {{.Branch}}"
zit push</pre>
{{if .Stack.Segments}}<p class="d-sub">Rungs stacked on <code>{{.Branch}}</code> follow: each targets this branch, so once it carries {{.Target}} they do too. Nothing above needs touching.</p>{{end}}
</div></details>
{{else if eq .Mergeable "up-to-date"}}<div class="d-row"><svg class="ic d-ic pass" aria-hidden="true"><use href="#i-check"/></svg>
<span class="d-line"><strong>{{.Branch}} is already on {{.Target}}</strong> <span class="d-sub">it landed by another route; Reject settles the record without pretending a merge happened here</span></span></div>
{{else if eq .Mergeable "stacked"}}<div class="d-row"><svg class="ic d-ic wait" aria-hidden="true"><use href="#i-clock"/></svg>
<span class="d-line"><strong>Stacked</strong> <span class="d-sub">the segment below lands first (RFC 0006)</span></span></div>
{{else if eq .State "open"}}<div class="d-row"><svg class="ic d-ic wait" aria-hidden="true"><use href="#i-clock"/></svg>
<span class="d-line"><strong>Mergeability unknown</strong> <span class="d-sub">the store could not be asked, and unknown must not read as clean</span></span></div>{{end}}
{{if and .Protected (not .MayLand)}}<div class="d-row"><svg class="ic d-ic fail" aria-hidden="true"><use href="#i-shield"/></svg>
<span class="d-line"><strong><code>{{.Target}}</code> is protected on this forge</strong> <span class="d-sub">owners: {{.OwnersText}}</span></span></div>{{end}}
{{if and .CanAccept (eq .State "open")}}<form method="post" action="/r/{{$.Repo}}/landing/{{printf "%.12s" .ID}}/accept" class="d-act">
{{template "landing-decide" $}}
</form>{{end}}
</div>{{end}}

{{if .Events}}<ol class="l-events">{{range .Events}}
<li class="l-ev l-ev-{{.State}}"><strong>{{.User}}</strong> {{if eq .State "updated"}}brought the target in{{with .Merge}} as <a href="/r/{{$.Repo}}/checkin/{{printf "%.16s" .}}"><code>{{printf "%.12s" .}}</code></a>{{end}}{{else}}{{.State}} this{{with .Detail}} to <code class="l-branch">{{.}}</code>{{end}}{{end}} · {{ago .Date}}
{{if .HTML}}<div class="l-ev-body">{{.HTML}}</div>{{end}}</li>
{{end}}</ol>{{end}}

{{if .Description}}<div class="l-desc">{{.Description}}</div>{{end}}

{{if .Commits}}<section class="l-commits">
<h2>{{len .Commits}} check-in{{if ne (len .Commits) 1}}s{{end}} on {{.Branch}}</h2>
<ul class="tickets l-cis">{{range .Commits}}
<li class="t-row">
<svg class="ic t-glyph" aria-hidden="true"><use href="#i-commit"/></svg>
<div class="t-main"><a class="t-title" href="/r/{{$.Repo}}/checkin/{{.Hash}}">{{firstline .Comment}}</a>
<div class="t-sub"><code>{{.Short}}</code> · {{who $.Repo .User}} · {{ago .Date}}</div></div>
</li>
{{end}}</ul>
</section>{{end}}

{{- /* The diff is COLLAPSED. This page is where a decision gets made,
       and six hundred lines of it between the proposal and the controls
       means scrolling past the change to reach the button. GitHub puts
       the same content behind a tab for the same reason; a details
       element is that, without a second page. */ -}}
<section class="l-diff">
{{if .Stale}}<h2>Changes</h2><p class="t-none">{{.Stale}}</p>
{{else if .Diff}}<details class="l-changes">
<summary><span class="l-sum">Changes</span>{{with .Diff.Files}} <span class="l-n">{{len .}} file{{if ne (len .) 1}}s{{end}}</span>{{end}}</summary>
{{template "diff-body" $}}
{{if .FullDiff}}<p class="l-more"><a href="{{.FullDiff}}">every line of this change &rarr;</a></p>{{end}}
</details>
{{else}}<h2>Changes</h2><p class="t-none">Nothing to show.</p>{{end}}
</section>

<section class="l-talk" id="discussion">
<h2>Discussion</h2>
{{- /* The forum's own post: a headed card with the author's hue on its
       left edge. f-post-h and f-post-b are where the padding lives, so
       naming the wrapper alone gets a border round unpadded text. */ -}}
{{spectrum .Comments}}
{{if .Comments}}{{range .Comments}}
<article class="f-post{{if .Hidden}} hidden{{end}}" id="p-{{printf "%.12s" .Hash}}" style="--uh: {{userhue .User}}{{if .IndentPx}}; margin-left: {{.IndentPx}}px{{end}}">
<div class="f-post-h"><strong>{{who $.Repo .User}}</strong> {{ago .Date}}{{if .ParentUser}} · replying to <a class="f-parent" href="#p-{{printf "%.12s" .Parent}}">{{.ParentUser}}</a>{{end}}<span class="f-spacer"></span><code>{{printf "%.12s" .Hash}}</code></div>
<div class="f-post-b">{{if .Hidden}}<p class="t-none">withheld: {{.HiddenReason}}</p>{{else}}{{.HTML}}{{end}}</div>
{{if $.Landing.CanSpeak}}<div class="f-post-f"><a class="btn f-replybtn" href="?reply-to={{printf "%.12s" .Hash}}#composer">Reply</a></div>{{end}}
</article>
{{end}}{{else}}<p class="t-none">No remarks yet.</p>{{end}}

{{if $.Landing.CanSpeak}}
{{- /* f-reply is the frame the composer is built for: the textarea has
       no border of its own, so without this wrapper the tabs and the
       text float unframed and the split runs past the page. Same
       container the ticket page and the forum use. */ -}}
<form class="f-reply" id="composer" method="post" action="/r/{{$.Repo}}/landing/{{printf "%.12s" .ID}}/comment">
{{if $.Landing.ReplyTo}}<div class="f-reply-note">Replying to <strong>{{$.Landing.ReplyToUser}}</strong> · <code>{{$.Landing.ReplyTo}}</code> — <a href="?#composer">answer the record instead</a><input type="hidden" name="to" value="{{$.Landing.ReplyTo}}"></div>{{end}}
{{template "composer" (landingctx $.Repo 6 "Leave a remark (Markdown — type / for blocks)")}}
<div class="f-reply-foot">
<button type="submit" title="Comment" aria-label="Comment"><svg class="ic b-icon" aria-hidden="true"><use href="#i-comment"/></svg><span class="b-word">Comment</span></button>
{{- /* Reject writes no check-in, so it rides the same capability as
       speaking. Accept merges, and takes the check-in capability —
       which is why the two controls are not siblings. */ -}}
{{if eq $.Landing.State "open"}}<button type="submit" class="btn-warn" formaction="/r/{{$.Repo}}/landing/{{printf "%.12s" .ID}}/reject">Reject</button>{{end}}
</div>
</form>
{{else if $.Landing.CanAccept}}<p class="t-none">You may land this record above. Remarks and rejection need the forum capability.</p>
{{else if $.SignedIn}}<p class="t-none">You may read this record. Taking part needs the forum capability.</p>
{{else}}<p class="t-none">Sign in to take part.</p>{{end}}
</section>
{{end}}
{{end}}`

var landingPage = template.Must(template.Must(base.Clone()).Parse(diffBodySource + composerSource + landingSource))

var landingNewPage = template.Must(template.Must(base.Clone()).Parse(composerSource + `{{define "content"}}
{{- /* Proposing a branch. The branch is already in the store — nothing
       is transported here — so the form asks only which branch, where it
       should land, and why. A select rather than a text field: a landing
       names a branch that EXISTS, and typing one that does not is a
       mistake the form can simply refuse to allow. */ -}}
<form method="post" action="/r/{{.Repo}}/landing-new">
<div class="fieldrow">
<label>Branch<br><select name="branch" required>
{{range .Branches}}{{if ne .Name $.RefName}}<option value="{{.Name}}"{{if eq .Name $.Query}} selected{{end}}>{{.Name}}</option>{{end}}{{end}}
</select></label>
<label>Lands on<br><select name="target" required>
{{range .Branches}}<option value="{{.Name}}"{{if eq .Name $.RefName}} selected{{end}}>{{.Name}}</option>{{end}}
</select></label>
</div>
<p class="l-why">Why this should land</p>
<div class="f-reply">
{{template "composer" (landingctx .Repo 10 "What this changes, and why it is ready (Markdown)")}}
<div class="f-reply-foot"><a href="/r/{{.Repo}}/landing">cancel</a>
<button type="submit" class="btn-primary">Open landing</button></div>
</div>
</form>
{{end}}`))

var wikiListPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
{{- /* A front door, not a directory listing. Eighty-three pages as one
       alphabetical bullet list ran 2,265 pixels down a column using
       two-fifths of the width, with fossil's own test fixtures filed
       between real documentation and no way to narrow it. */ -}}
{{if .WikiHome}}<a class="w-home" href="/r/{{.Repo}}/wiki/{{pathesc .WikiHome.Title}}">
<span class="w-home-t">{{.WikiHome.Title}}</span>
<span class="w-home-m">edited {{ago .WikiHome.Date}} by {{identicon .WikiHome.User}} {{.WikiHome.User}}</span></a>{{end}}
{{with .DocEntry}}<a class="w-home" href="{{.URL}}">
<span class="w-home-t">{{.Title}}</span>
<span class="w-home-m">{{if .Date}}changed {{ago .Date}}{{if .User}} by {{identicon .User}} {{.User}}{{end}}{{end}}</span></a>{{end}}
{{- /* fossil reaches technotes from its wiki landing, and so does
       this. Notes are documentation with a date on them; a reader who
       has come looking for the project's writing should find them
       here rather than only through a timeline filter. */ -}}
{{if .Counts.Technotes}}<p class="w-notes"><a href="/r/{{.Repo}}/technote">Notes <span class="w-n">{{count .Counts.Technotes}}</span></a>
<span class="tn-hint">dated notes — milestones, releases, decisions</span></p>{{end}}
{{- /* A filter box and a sort toggle over four documents are two
       controls that cannot change what you see. They appear when the
       list is long enough to need finding, or a filter is already on. */ -}}
{{if or (gt (len .DocRows) 8) .Query}}<form class="w-controls" method="get" action="/r/{{.Repo}}/docs">
{{if .Sort}}<input type="hidden" name="sort" value="{{.Sort}}">{{end}}
{{if .ShowAssociated}}<input type="hidden" name="associated" value="1">{{end}}
<span class="w-find"><label for="wq">filter</label>
<input id="wq" type="search" name="q" value="{{.Query}}" placeholder="name of a page" autocomplete="off" spellcheck="false"></span>
<nav class="seg-box">
<a href="/r/{{.Repo}}/docs?sort=&amp;q={{.Query}}{{if .ShowAssociated}}&amp;associated=1{{end}}"{{if not .Sort}} class="here"{{end}}>name</a>
<a href="/r/{{.Repo}}/docs?sort=recent&amp;q={{.Query}}{{if .ShowAssociated}}&amp;associated=1{{end}}"{{if .Sort}} class="here"{{end}}>recently changed</a>
</nav>
{{- /* The structure lists, up here where they can be FOUND. The panel
       at the foot of the page is a preview of the same two lists, and
       on a wiki of any size it sits a hundred rows down — which is a
       place to put something a reader already knows about, not a place
       to discover it. */ -}}
{{if or .WikiWanted .WikiOrphans}}<span class="w-struct-links">
{{if .WikiWanted}}<a href="/r/{{.Repo}}/docs/wanted">wanted <span class="w-n">{{count (add (len .WikiWanted) .MoreWanted)}}</span></a>{{end}}
{{if .WikiOrphans}}<a href="/r/{{.Repo}}/docs/orphans">unlinked <span class="w-n">{{count (add (len .WikiOrphans) .MoreOrphans)}}</span></a>{{end}}
</span>{{end}}
</form>{{end}}
{{if .DocRows}}<ul class="w-pages">{{range .DocRows}}
<li><a href="{{.URL}}">
<span class="w-t">{{.Title}}</span>
<span class="w-when">{{if .Date}}{{ago .Date}}{{end}}{{if .User}} · {{identicon .User}} {{.User}}{{end}}</span>
{{- /* The store is named, quietly: it is not what the document IS, but
       it is where you go to change it — the browser, or a check-in. */ -}}
<span class="w-kind w-{{.Kind}}" title="{{if eq .Kind "wiki"}}wiki page — edited in the browser{{else}}in the tree — edited by check-in{{end}}">{{if eq .Kind "wiki"}}wiki{{else}}tree{{end}}</span></a></li>
{{end}}</ul>
{{if .Associated}}<p class="w-assoc">{{if .ShowAssociated}}Showing {{count .Associated}} notes attached to branches and check-ins.
<a href="/r/{{.Repo}}/docs{{if .Query}}?q={{.Query}}{{end}}">Hide them</a>.{{else}}{{count .Associated}} wiki pages are notes on a branch or check-in, shown on those pages.
<a href="/r/{{.Repo}}/docs?associated=1{{if .Query}}&amp;q={{.Query}}{{end}}">Show them anyway</a>.{{end}}</p>{{end}}
<p class="w-count">{{if .Query}}{{count .Shown}} of {{count .Served}} match “{{.Query}}”{{else}}{{count .Shown}} documents{{end}}</p>
{{template "ticket-pager" .}}
{{else}}<p class="t-none">{{if .Query}}Nothing matches “{{.Query}}”. <a href="/r/{{.Repo}}/docs">Show all</a>.{{else}}No documents yet.{{end}}</p>{{end}}
{{if .Posture.ReadOnly}}<p><a href="{{.Posture.Upstream "wikinew"}}">new page on {{.Posture.Host}} &rarr;</a></p>{{else}}<form method="get" action="/r/{{.Repo}}/wiki-new"><input name="name" placeholder="new page name" required> <button type="submit">Create</button></form>{{end}}

{{- /* What a page listing cannot tell you. A wiki goes bad in two
       directions — pages nothing reaches, and links that promise a page
       nobody wrote — and neither shows up in an alphabetical list.
       MediaWiki keeps both as special pages; here they are derived from
       the live text, so they cost nothing and cannot go stale. Shown
       only when the wiki is big enough for either to be a question, and
       never while a filter is narrowing the list they describe. */ -}}
{{if and (not .Query) (or .WikiOrphans .WikiWanted)}}<div class="w-struct">
{{if .WikiWanted}}<section>
<h2><a href="/r/{{.Repo}}/docs/wanted">Wanted pages</a>{{if .MoreWanted}} <span class="w-n">{{count (add (len .WikiWanted) .MoreWanted)}}</span>{{end}}</h2>
<ul class="w-links">{{range .WikiWanted}}
<li><a href="/r/{{$.Repo}}/wiki-new?name={{pathesc .Title}}">{{.Title}}</a>
<span class="w-n" title="{{.Links}} page{{if ne .Links 1}}s{{end}} ask{{if eq .Links 1}}s{{end}} for it">{{.Links}}</span></li>
{{end}}</ul>
{{if .MoreWanted}}<p class="w-n"><a href="/r/{{.Repo}}/docs/wanted">and {{count .MoreWanted}} more &rarr;</a></p>{{end}}
</section>{{end}}
{{if .WikiOrphans}}<section>
<h2><a href="/r/{{.Repo}}/docs/orphans">Nothing links here</a>{{if .MoreOrphans}} <span class="w-n">{{count (add (len .WikiOrphans) .MoreOrphans)}}</span>{{end}}</h2>
<ul class="w-links">{{range .WikiOrphans}}
<li><a href="/r/{{$.Repo}}/wiki/{{pathesc .}}">{{.}}</a></li>
{{end}}</ul>
{{if .MoreOrphans}}<p class="w-n"><a href="/r/{{.Repo}}/docs/orphans">and {{count .MoreOrphans}} more &rarr;</a></p>{{end}}
</section>{{end}}
</div>{{end}}
{{end}}`))

var forumQueuePage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
<p><a href="/r/{{.Repo}}/forum">← forum</a> · <a href="/r/{{.Repo}}/forum/modlog">moderation log</a></p>
<form method="post" action="/r/{{.Repo}}/forum/queue"><button name="toggle" value="{{if .ModOn}}off{{else}}on{{end}}">turn moderation {{if .ModOn}}off{{else}}on{{end}}</button>
<small>{{if .ModOn}}new posts from accounts without a role are held here{{else}}everything posts directly{{end}}</small></form>
{{if .Queue}}{{range .Queue}}<article style="border-top:1px solid var(--rule); padding-top:0.5rem; margin-top:0.5rem">
<p><small>#{{.ID}} · {{.Kind}} by {{identicon .Author}} <strong>{{.Author}}</strong> · {{ago .At}}{{if .AIAction}} · hook: <strong>{{.AIAction}}</strong> ({{printf "%.2f" .AIScore}}){{if .AIReason}} — {{.AIReason}}{{end}}{{end}}</small></p>
{{if .Title}}<p><strong>{{.Title}}</strong></p>{{end}}
<pre style="white-space:pre-wrap">{{.Body}}</pre>
<form method="post" action="/r/{{$.Repo}}/forum/queue">
<input type="hidden" name="id" value="{{.ID}}">
<button name="action" value="approve" class="btn-primary">Approve</button>
<input name="reason" placeholder="reason (required to reject)">
<button name="action" value="reject">Reject</button>
</form>
</article>{{end}}{{else}}<p>The queue is empty.</p>{{end}}
{{end}}`))

var forumModlogPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
<p><a href="/r/{{.Repo}}/forum">← forum</a></p>
<p><small>Every moderation action — human and automated — is recorded here permanently. There is no way to edit or remove an entry.</small></p>
{{if .ModLog}}<ul>{{range .ModLog}}
<li><small>{{ago .At}}</small> <strong>{{.Actor}}</strong> {{.Action}} <code>{{.Target}}</code>{{if .Reason}} — {{.Reason}}{{end}}</li>
{{end}}</ul>{{else}}<p>No moderation actions.</p>{{end}}
{{end}}`))

var forumListPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
{{if .Flash}}<p class="status">{{.Flash}}</p>{{end}}
{{range .ForumPinned}}<p class="f-pinned" style="border:1px solid var(--rule); border-radius:6px; padding:0.4rem 0.6rem"><span class="b-pill">announcement</span> <a href="/r/{{$.Repo}}/forum/{{printf "%.16s" .Root}}"><strong>{{if .Title}}{{.Title}}{{else}}(untitled){{end}}</strong></a> <small>{{.Posts}} post{{if ne .Posts 1}}s{{end}} · last {{ago .Updated}}</small></p>
{{end}}<div class="ft-bar"><small>{{if eq .Sort "hot"}}<a href="/r/{{.Repo}}/forum">recent</a> · <strong>hot</strong>{{else}}<strong>recent</strong> · <a href="/r/{{.Repo}}/forum?sort=hot">hot</a>{{end}}</small>{{if .SignedIn}}<form method="post" action="/r/{{.Repo}}/forum/read"><button class="linkish" type="submit">mark all read</button></form>{{end}}</div>
{{if .Forum}}<div class="ft-list">{{range .Forum}}
<div class="ft-row{{if .Read}} dim{{end}}">
<div class="ft-main">
<div class="ft-t">{{if .HasPoll}}<span class="b-pill">poll</span> {{end}}<a href="/r/{{$.Repo}}/forum/{{printf "%.16s" .Root}}">{{if .Title}}{{.Title}}{{else}}(untitled thread){{end}}</a>{{if .Score}} <span class="ft-score" title="net votes" data-score="{{.Score}}">▲ {{.Score}}</span>{{end}}</div>
{{if .Excerpt}}<p class="ft-x">{{.Excerpt}}</p>{{end}}
<p class="ft-meta"><strong>{{who $.Repo .User}}</strong> · started {{ago .Created}} · last reply {{ago .Updated}}</p>
</div>
<div class="ft-side">
<span class="ft-stack" title="{{len .Participants}} participant{{if ne (len .Participants) 1}}s{{end}}">{{range .Participants}}{{identicon .}}{{end}}</span>
<span class="ft-count" title="{{.Posts}} post{{if ne .Posts 1}}s{{end}}">{{.Posts}}</span>
{{spark .Spark}}
</div>
</div>
{{end}}</div>{{else}}<p>No forum threads.</p>{{end}}
{{if eq .Sort "hot"}}<p class="hot-formula"><small>ranked by (score + ½·replies) ÷ (age_hours + 2)<sup>1.8</sup>; threads quiet for 30 days follow in recency order</small></p>{{end}}
<div class="f-actions">{{if .Posture.ReadOnly}}<a class="btn" href="{{.Posture.Upstream "forumnew"}}">New thread on {{.Posture.Host}} &rarr;</a>{{else}}<a class="btn" href="/r/{{.Repo}}/forum-new">New thread</a>{{if .CanWrite}}<a class="btn" href="/r/{{.Repo}}/announce-new">New announcement</a><a href="/r/{{.Repo}}/forum/queue">queue</a>{{end}}{{end}}<small><a href="/r/{{.Repo}}/forum/modlog">moderation log</a></small></div>
{{end}}`))

var forumAnnouncePage = template.Must(template.Must(base.Clone()).Parse(composerSource + `{{define "content"}}
<p><small>Announcements pin above the forum and surface on the repository home. Anyone can reply; only maintainers start one.</small></p>
<form method="post" action="/r/{{.Repo}}/announce-new">
<p><label>Title<br><input name="title" required></label></p>
<div class="f-reply">{{template "composer" (composerctx .Repo 14 "Markdown — type / for blocks")}}
<div class="f-reply-foot"><a href="/r/{{.Repo}}/forum">cancel</a> <button type="submit" class="btn-primary">Announce</button></div></div>
</form>
{{end}}`))

// voteWidgetSource is the pair of arrows and the score. The FORMS are
// the mechanism (no-JS: POST + redirect, back where you were); datastar
// layers @post over submit, and the vote handler answers a datastar
// request with an SSE patch of exactly this span — no page flash. One
// form per arrow so the direction rides a hidden input: fetch-built
// form data never carries the clicked button.
var voteWidgetSource = `{{define "vote-widget"}}<span class="vote-pill" id="vote-{{printf "%.12s" .Hash}}" data-score="{{.Score}}"><form method="post" action="/r/{{.Repo}}/forum/{{.Root}}/vote" data-on-submit="@post('/r/{{.Repo}}/forum/{{.Root}}/vote', {contentType: 'form'})"><input type="hidden" name="post" value="{{.Hash}}"><input type="hidden" name="dir" value="{{if eq .YourVote 1}}none{{else}}up{{end}}"><button title="{{if eq .YourVote 1}}retract upvote{{else}}upvote{{end}}"{{if eq .YourVote 1}} class="vote-cast"{{end}}>▲</button></form><span class="vscore">{{.Score}}</span><form method="post" action="/r/{{.Repo}}/forum/{{.Root}}/vote" data-on-submit="@post('/r/{{.Repo}}/forum/{{.Root}}/vote', {contentType: 'form'})"><input type="hidden" name="post" value="{{.Hash}}"><input type="hidden" name="dir" value="{{if eq .YourVote -1}}none{{else}}down{{end}}"><button title="{{if eq .YourVote -1}}retract downvote{{else}}downvote{{end}}"{{if eq .YourVote -1}} class="vote-cast"{{end}}>▼</button></form></span>{{end}}`

// voteCtx feeds vote-widget: one post's vote state on one thread page.
type voteCtx struct {
	Repo, Root, Hash string
	Score, YourVote  int
}

// composerSource is the markdown composer: Write | Preview tabs over a
// raw textarea (raw text is never more than one click away — it IS the
// Write tab). Without JS the tab bar stays hidden and the composer is a
// plain textarea. Preview posts the draft to markup-preview, which runs
// the PRODUCTION render pipeline and patches the pane — the preview
// cannot drift from what a reader will see.
var composerSource = `{{define "composer"}}<div class="f-composer" data-live="/r/{{.Repo}}/markup-preview?plain=1">
<div class="f-tabs" hidden>
<button type="button" class="f-tab here" data-tab="write">Write</button>
<button type="button" class="f-tab" data-tab="preview">Preview</button>
</div>
<div class="f-split">
<textarea name="{{.FieldName}}" rows="{{.Rows}}" placeholder="{{.Placeholder}}"{{if not .Optional}} required{{end}} data-slash>{{.Value}}</textarea>
<div class="f-live" hidden>
<div class="f-poll-builder"></div>
<div class="f-live-pane"></div>
</div>
</div>
<div class="f-preview" hidden></div>
</div>{{end}}`

// composerCtx feeds the composer define.
type composerCtx struct {
	Repo, Placeholder, Value string
	Rows                     int
	Name                     string // form field; "" means body
	Optional                 bool   // the text may be empty (a status change alone)
	Autofocus                bool   // land the page IN the box (an aimed reply)
}

// FieldName is the textarea's name; the forum's reply is "body", a
// ticket's remark is "comment".
func (c composerCtx) FieldName() string {
	if c.Name == "" {
		return "body"
	}
	return c.Name
}

var forumThreadPage = template.Must(template.Must(base.Clone()).Parse(voteWidgetSource + composerSource + `{{define "content"}}
<div class="f-actions"><a href="/r/{{.Repo}}/forum">← forum</a>{{if .CanWrite}}
<form method="post" action="/r/{{.Repo}}/forum/{{.ForumRoot}}/subscribe" style="margin-left:auto">
{{if eq .YourSub "sub"}}<button name="state" value="unsub" title="stop notifications for this thread">Unsubscribe</button>{{else}}<button name="state" value="sub" title="notify me about replies in this thread">Subscribe</button>{{end}}
</form>{{end}}</div>
{{if .Flash}}<p class="status">{{.Flash}}</p>{{end}}
{{spectrum .ForumPosts}}
{{chatrefs .ChatRefs .Repo}}
{{$op := ""}}{{if .ForumPosts}}{{$op = (index .ForumPosts 0).User}}{{end}}
{{range .ForumPosts}}<article class="f-post" id="p-{{printf "%.12s" .Hash}}" style="--uh: {{userhue .User}}{{if .IndentPx}}; margin-left: {{.IndentPx}}px{{end}}">
<div class="f-post-h"><strong>{{who $.Repo .User}}</strong>{{if and $op (eq .User $op)}} <span class="b-pill" title="started this thread">opener</span>{{end}} {{ago .Date}}{{if .Parent}} · replying to <a class="f-parent" href="#p-{{printf "%.12s" .Parent}}">{{if .ParentUser}}{{.ParentUser}}{{else}}{{printf "%.12s" .Parent}}{{end}}</a>{{end}}<span class="f-spacer"></span><code>{{printf "%.12s" .Hash}}</code>
{{- if $.CanWrite}} {{template "vote-widget" (votectx $.Repo $.ForumRoot .Hash .Score .YourVote)}}{{else if .Score}} <span class="vote-pill" data-score="{{.Score}}"><span class="vscore" style="padding:0.1rem 0.5rem">▲ {{.Score}}</span></span>{{end}}
{{- if $.CanMod}} <details class="f-kebab"><summary aria-label="moderate">···</summary><div class="f-kebab-pop">
<form method="post" action="/r/{{$.Repo}}/forum/{{$.ForumRoot}}/hide">
<input type="hidden" name="post" value="{{.Hash}}">
{{if .Hidden}}<button name="action" value="unhide">Unhide</button>{{else}}<input name="reason" placeholder="reason (public)" required> <button name="action" value="hide">Hide</button>{{end}}
</form></div></details>{{end}}</div>
<div class="f-post-b">
{{if .Hidden}}<details class="f-hidden"><summary><small>hidden by a moderator — {{.HiddenReason}}</small></summary>{{.HTML}}</details>{{else}}{{.HTML}}{{end}}
{{$p := .}}{{if .Poll.Present}}{{with .Poll}}<div style="border:1px solid var(--rule); border-radius:6px; padding:0.6rem 0.8rem; max-width:30rem; margin:0.5rem 0">
<p style="margin:0 0 0.4rem"><strong>{{.Question}}</strong> <small>{{.Total}} {{plural .Total "ballot" "ballots"}}{{if .Closed}} · closed{{else if .Closes}} · closes {{.Closes}}{{end}}</small></p>
{{range $i, $o := .Options}}<div style="margin:0.35rem 0">
<div><small>{{if and $.CanWrite (not $p.Poll.Closed)}}<form method="post" action="/r/{{$.Repo}}/forum/{{$.ForumRoot}}/poll" style="display:inline"><input type="hidden" name="post" value="{{$p.Hash}}"><button name="choice" value="{{$i}}" title="{{if eq $p.Poll.YourChoice $i}}your ballot{{else}}vote {{$o}}{{end}}" style="background:none;border:none;cursor:pointer;padding:0 0.15rem{{if eq $p.Poll.YourChoice $i}};color:var(--accent){{end}}">{{if eq $p.Poll.YourChoice $i}}◉{{else}}○{{end}}</button></form>{{end}}{{$o}} · {{index $p.Poll.Counts $i}}</small></div>
<div style="height:6px; background:var(--rule); border-radius:3px"><div style="height:6px; width:{{index $p.Poll.Percents $i}}%; background:var(--accent); border-radius:3px"></div></div>
</div>{{end}}
</div>{{end}}{{end}}
</div>
{{if $.Posture.ReadOnly}}<div class="f-post-f"><a class="btn f-replybtn" href="{{$.Posture.Upstream (printf "forumpost/%s" .Hash)}}">Reply on {{$.Posture.Host}} &#8599;</a></div>
{{- else if $.CanWrite}}<div class="f-post-f"><a class="btn f-replybtn" href="?reply-to={{printf "%.12s" .Hash}}#composer">Reply</a></div>{{end}}
</article>{{end}}
{{if .Posture.ReadOnly}}<p style="margin-top:1rem"><a href="{{.Posture.Upstream "forum"}}">reply on {{.Posture.Host}} &rarr;</a></p>{{else}}<form class="f-reply" id="composer" method="post" action="/r/{{.Repo}}/forum/{{.ForumRoot}}/reply">
{{if .ReplyTo}}<div class="f-reply-note">Replying to <strong>{{.ReplyToUser}}</strong> · <code>{{.ReplyTo}}</code> — <a href="?#composer">answer the thread instead</a><input type="hidden" name="to" value="{{.ReplyTo}}"></div>{{end}}
{{template "composer" (composerfocus .Repo 6 "Write a reply (Markdown — type / for blocks)" (ne .ReplyTo ""))}}
<div class="f-reply-foot"><button type="submit" class="btn-primary">Post reply</button></div>
</form>{{end}}
{{end}}`))

var forumNewPage = template.Must(template.Must(base.Clone()).Parse(composerSource + `{{define "content"}}
<form method="post" action="/r/{{.Repo}}/forum-new">
<p><label>Title<br><input name="title" required></label></p>
<div class="f-reply">{{template "composer" (composerctx .Repo 14 "Markdown — type / for blocks")}}
<div class="f-reply-foot"><a href="/r/{{.Repo}}/forum">cancel</a> <button type="submit" class="btn-primary">Open thread</button></div></div>
</form>
{{end}}`))

// The filing time is a FIELD, not a side effect. It is the whole
// difference between a note and a forum post — a note is filed at a
// moment its author chose, and may be back-dated to when the thing it
// describes happened — and it was previously unreachable: a new note
// got "now" and an edit silently re-filed the note at the moment it
// was edited, moving it in the timeline. fossil's own technote editor
// has had this field all along.
var technoteEditPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
<div class="w-doc w-solo"><div class="w-main">
<p class="w-crumb"><a href="/r/{{.Repo}}/technote">notes</a> /
{{if .Technote.Event}}<a href="/r/{{.Repo}}/technote/{{printf "%.16s" .Technote.Event}}">{{if .Technote.Comment}}{{plain .Technote.Comment}}{{else}}{{.Technote.Date}}{{end}}</a> / <span>edit</span>{{else}}<span>new</span>{{end}}</p>
<h1 class="tn-h">{{if .Technote.Event}}Edit note{{else}}New note{{end}}</h1>
<form class="tn-form" method="post" action="{{if .Technote.Event}}/r/{{.Repo}}/technote/{{printf "%.16s" .Technote.Event}}/edit{{else}}/r/{{.Repo}}/technote-new{{end}}">
<p><label>Title<br><input name="comment" maxlength="200" required value="{{.Technote.Comment}}"></label>
<small class="tn-hint">What the timeline and the note listing call it.{{if .Technote.Event}} Changing it retitles the note; earlier versions keep the wording they were saved with.{{end}}</small></p>
<p><label>Filed under<br><input type="datetime-local" name="time" value="{{dtlocal .Technote.Date}}"></label>
<small class="tn-hint">Where the note sits in the timeline. {{if .Technote.Event}}Left as it is, the note stays where it was filed.{{else}}Leave it empty to file the note now, or back-date it to when the thing it describes happened.{{end}}</small></p>
<p><label>Note<br><textarea name="body" rows="18" placeholder="Markdown" required>{{.EditSource}}</textarea></label></p>
<p class="tn-acts"><button type="submit" class="btn-primary">Save</button>
<a href="{{if .Technote.Event}}/r/{{.Repo}}/technote/{{printf "%.16s" .Technote.Event}}{{else}}/r/{{.Repo}}/technote{{end}}">cancel</a></p>
</form>
</div></div>
{{end}}`))

// A project's news, not a list of links. Every technote in libfossil is
// a milestone announcement — "SHA3 artifact hash support", "merge algo
// ported in" — and a bare <ul> of titles reads as an index of documents
// nobody has a reason to open. An opening line is what turns it back
// into something you read. fossil reaches this page from the timeline
// and from the wiki landing; it is not a tab there and is not one here.
var technoteListPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
<div class="w-doc w-solo"><div class="w-main">
<div class="tn-head">
<h1>Notes</h1>
{{if .Posture.ReadOnly}}<a class="tn-new" href="{{.Posture.Upstream "technoteedit"}}">write one on {{.Posture.Host}} &rarr;</a>{{else}}<a class="tn-new" href="/r/{{.Repo}}/technote-new"><svg class="ic" aria-hidden="true"><use href="#i-plus"/></svg> new note</a>{{end}}
</div>
<p class="tn-lede">Dated notes written into the repository — milestones, release
notes, decisions. Each is filed at a moment its author chose, and appears in the
<a href="/r/{{.Repo}}/timeline?y=e">timeline</a> there.</p>
{{if .Technotes}}<ol class="tn-feed">{{range .Technotes}}
<li class="tn-item">
<a class="tn-title" href="/r/{{$.Repo}}/technote/{{printf "%.16s" .Event}}">{{if .Comment}}{{plain .Comment}}{{else}}Note of {{.Date}}{{end}}</a>
{{with .Excerpt}}<p class="tn-x">{{.}}</p>{{end}}
<p class="tn-m"><time>{{ago .Date}}</time> · {{who $.Repo .User}}{{if gt .Revisions 1}} · <a href="/r/{{$.Repo}}/technote/{{printf "%.16s" .Event}}/history">{{.Revisions}} versions</a>{{end}}</p>
</li>
{{end}}</ol>
{{else}}<p class="tn-empty">No notes yet. A note is a dated document — a milestone,
a release announcement, a decision worth finding again — filed at whatever moment
it belongs to rather than attached to a check-in.</p>{{end}}
</div></div>
{{end}}`))

// The wiki page's reading furniture, because it is the same job: a
// document somebody wrote to be read. It previously rendered the body
// and nothing else — you clicked a title and landed on an untitled page
// — so the title, the byline and the door to the history lead now, the
// way they do on a wiki page.
var technotePage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
<div class="w-doc w-solo"><div class="w-main">
<p class="w-crumb"><a href="/r/{{.Repo}}/technote">notes</a> / <span>{{if .Technote.Comment}}{{plain .Technote.Comment}}{{else}}{{.Technote.Date}}{{end}}</span></p>
{{if .Technote.Historical}}<p class="status"><em>Historical version <code>{{printf "%.12s" .Technote.Hash}}</code>, written {{ago .Technote.Edited}} —
<a href="/r/{{.Repo}}/technote/{{printf "%.16s" .Technote.Event}}">view current</a></em></p>{{end}}
{{if .Technote.Comment}}<h1 class="tn-h">{{plain .Technote.Comment}}</h1>{{end}}
{{- /* Filed, not written: the E card is a moment the AUTHOR chose, and
       an edit can move it. Where the two disagree the page says both,
       because "filed 2013 · last edited 2021" is a fact about the note
       that one date cannot express. */ -}}
<p class="w-by">filed {{ago .Technote.Date}} by {{who .Repo .Technote.User}}
{{- if and (gt .Technote.Revisions 1) (ne .Technote.Edited .Technote.Date)}} · last edited {{ago .Technote.Edited}}{{end}} ·
{{if .Posture.ReadOnly}}<a href="{{.Posture.Upstream "technoteedit"}}?name={{.Technote.Event}}">edit on {{.Posture.Host}} &rarr;</a>{{else}}<a href="/r/{{.Repo}}/technote/{{printf "%.16s" .Technote.Event}}/edit">edit</a>{{end}}
{{- if gt .Technote.Revisions 1}} · <a href="/r/{{.Repo}}/technote/{{printf "%.16s" .Technote.Event}}/history">history ({{.Technote.Revisions}})</a>{{end}}</p>
<article>{{.WikiHTML}}</article>
</div></div>
{{end}}`))

// Wiki history's shape with one column more. A technote carries two
// times that routinely disagree — when a version was WRITTEN and the
// moment it is FILED under — and an edit may change the title, so the
// history is where "this used to say something else" is answerable.
// Each is shown only where it differs, so an ordinary note with three
// quiet edits stays a plain list.
var technoteHistoryPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
<div class="w-doc w-solo"><div class="w-main">
<p class="w-crumb"><a href="/r/{{.Repo}}/technote">notes</a> /
<a href="/r/{{.Repo}}/technote/{{printf "%.16s" .Technote.Event}}">{{if .Technote.Comment}}{{plain .Technote.Comment}}{{else}}{{.Technote.Date}}{{end}}</a> / <span>history</span></p>
<h1 class="tn-h">History</h1>
<p class="tn-lede">{{len .TechRevs}} {{plural (len .TechRevs) "version" "versions"}} of this note. Every one stays readable.</p>
<ol class="tn-hist">{{$top := true}}{{$newer := ""}}{{range .TechRevs}}
<li class="tn-hrow">
<a href="/r/{{$.Repo}}/technote/{{printf "%.16s" $.Technote.Event}}{{if not $top}}?rev={{printf "%.12s" .Hash}}{{end}}"><code>{{printf "%.12s" .Hash}}</code></a>
{{if $top}}<span class="tl-badge">current</span>{{end}}
<span class="tn-hm">written {{ago .Edited}}{{with clock .Edited}} at {{.}}{{end}} by {{who $.Repo .User}}</span>
{{- if ne .Date $.Technote.Date}}<span class="tn-hm">filed under {{.Date}}</span>{{end}}
{{- if and (ne $newer "") (ne .Comment $newer)}}<span class="tn-hm tn-retitle">titled &ldquo;{{plain .Comment}}&rdquo;</span>{{end}}
{{$newer = .Comment}}{{$top = false}}</li>{{end}}
</ol>
</div></div>
{{end}}`))

// chat-log is the shared list body: the page's initial render and the
// SSE-appended tail both end up as <li> rows produced by chatMsgHTML,
// so a message looks identical whichever path drew it.
var chatLogSource = `{{define "chat-log"}}<ol id="chatlog" class="chatlog">
{{$read := .ChatReadSeq}}{{$viewer := .ChatViewer}}{{$shown := false}}{{$day := ""}}
{{- /* A day boundary gets its own separator: a log read the next
       morning has to say WHICH morning, and "3 hours ago" stops
       answering that as soon as it stops being today. */ -}}
{{range .ChatMsgs}}{{$d := chatday .At}}{{if and (ne $d "") (ne $d $day)}}<li class="chat-date"><span>{{$d}}</span></li>{{$day = $d}}{{end}}
{{if and $viewer (not $shown) (gt .Seq $read)}}<li class="chat-divider" data-seq="{{$read}}"><span>new</span></li>{{$shown = true}}{{end}}
<li>{{chatMsgHTML . $.Repo $.ChatViewer $.ChatViewerAll}}</li>
{{end}}</ol>{{end}}`

// chatStyleSource is the chat rules, spelled once: the permalink page
// draws the same rows through the same renderer, so it needs the same
// rules or a message looks like two different things depending on which
// page you reached it from.
var chatStyleSource = `{{define "chat-style"}}<style>.chatwrap{position:relative}
.chatlog{max-height:60vh;overflow-y:auto;border:1px solid var(--rule);border-radius:var(--r-2);
  padding:var(--sp-2) var(--sp-3);margin:0 0 var(--sp-2);list-style:none}
.chatlog>li{margin:0}
{{- /* The forum's own vocabulary at chat density, but at a chat
       product's proportions: a 44px gutter holding a 32px mark (an
       identicon is square art, so it takes a radius, never a circle),
       the author's hue as a 2px rail down the whole group, and the
       run's rows separated by 2px against 14px between groups. The
       rail is drawn with PADDING inside a group rather than margin, so
       it runs unbroken from the first row of a run to the last. */ -}}
.chatmsg{position:relative;display:grid;grid-template-columns:44px 1fr;
  align-items:start;margin:0;padding:2px var(--sp-2);
  border-left:2px solid hsl(var(--uh, 0), 45%, 50%, 0.6);
  border-radius:0 var(--r-row) var(--r-row) 0;
  transition:background var(--t-fast)}
{{- /* A robot line is the channel talking about the repository, not
       a person with a column: no author hue, a muted rail, muted text,
       and a small mark where a name would be. */ -}}
.chatmsg[data-kind="robot"]{border-left-color:var(--rule);color:var(--muted)}
.chatmsg[data-kind="robot"] .chat-head b{font-weight:600;color:var(--muted)}
.chat-robot{display:inline-block;border:1px solid var(--rule);border-radius:var(--r-1);
  padding:0 5px;margin-right:var(--sp-1);font-size:0.65rem;font-weight:600;
  letter-spacing:0.06em;text-transform:uppercase;color:var(--muted);vertical-align:1px}
.chatlog>li:not(:first-child)>.chatmsg:not([data-grouped]){margin-top:14px}
{{- /* One step toward the rule, not a new colour: the row lifts off
       the page without introducing a surface the palette never
       declared. The flat wash is the fallback where color-mix is not
       understood. */ -}}
.chatmsg:hover,.chatmsg:focus-within{background:var(--surface)}
.chatmsg:hover,.chatmsg:focus-within{background:color-mix(in srgb, var(--rule) 35%, transparent)}
.chat-gut{grid-column:1;grid-row:1 / -1;display:flex;align-items:flex-start;padding-top:2px}
.chatmsg>*:not(.chat-gut){grid-column:2;min-width:0}
.chat-gut .idn{width:32px;height:32px;border-radius:var(--r-2);vertical-align:0}
{{- /* A continuation row has no header, so the gutter carries the one
       thing it would otherwise never say: the absolute time, on hover,
       where the mark would have been. */ -}}
.chat-clock{font-size:0.72rem;color:var(--muted);font-variant-numeric:tabular-nums;
  opacity:0;transition:opacity var(--t-fast)}
.chatmsg:hover .chat-clock,.chatmsg:focus-within .chat-clock{opacity:1}
.chat-head{display:block;line-height:1.4}
.chat-head b{font-size:0.95rem;font-weight:700;color:var(--fg)}
.chat-when{font-size:0.78rem;font-weight:400;opacity:0.55}
.chatbody{display:block;font-size:0.95rem;line-height:1.5}
.chatbody>p{margin:0.2rem 0}
.chatbody>p:first-child{margin-top:0}
.chatbody>p:last-child{margin-bottom:0}
{{- /* The quote is a card, not a blockquote: mark, name, number, one
       line, all on one row, and the whole card is the permalink. A
       reply-to quote and an inline #seq quote are the same card. */ -}}
.chat-quote{display:flex;align-items:center;gap:var(--sp-1);overflow:hidden;
  border-left:2px solid var(--rule);padding:4px 10px;margin:var(--sp-1) 0;
  background:var(--surface);background:color-mix(in srgb, var(--rule) 12%, transparent);
  border-radius:0 var(--r-row) var(--r-row) 0;font-size:0.85rem;
  color:var(--muted);text-decoration:none;white-space:nowrap}
.chat-quote .idn{width:16px;height:16px;border-radius:var(--r-1);flex:none;vertical-align:0}
.chat-quote b{color:var(--fg);font-weight:600}
.chat-quote:hover{background:color-mix(in srgb, var(--rule) 22%, transparent)}
.chatreply{font-size:0.85rem;color:var(--muted)}
{{- /* On touch the toolbar is simply there, under the row and to the
       right — "point at it" is not an instruction a touch screen can
       follow. Where there IS a pointer it becomes a floating box at
       the row's top-right, appearing on hover or focus. */ -}}
.chat-toolbar{display:flex;gap:var(--sp-2);align-items:center;justify-content:flex-end;
  margin-top:var(--sp-1);font-size:0.78rem;color:var(--muted)}
.chat-act{color:var(--muted);text-decoration:none;background:none;border:0;padding:0;
  font:inherit;font-size:0.78rem;cursor:pointer}
.chat-act:hover,.chat-act:focus{color:var(--accent);text-decoration:underline}
.chatdelete{display:inline}
.chatedit{display:inline;position:relative}
.chatedit>summary{list-style:none}
.chatedit>summary::-webkit-details-marker{display:none}
.chatedit form{display:flex;gap:var(--sp-1);margin:var(--sp-1) 0}
.chatedit textarea{flex:1;font:inherit;resize:vertical}
@media (hover: hover) and (pointer: fine){
  .chat-toolbar{position:absolute;top:-10px;right:var(--sp-2);margin:0;z-index:1;
    background:var(--bg);border:1px solid var(--rule);border-radius:var(--r-row);
    box-shadow:var(--shadow-1);padding:2px var(--sp-2);
    opacity:0;pointer-events:none;transition:opacity var(--t-fast)}
  .chatmsg:hover .chat-toolbar,.chatmsg:focus-within .chat-toolbar,
  .chatmsg:has(.chatedit[open]) .chat-toolbar{opacity:1;pointer-events:auto}
  {{- /* The edit disclosure opens UNDER the floating box rather than
         inside it: a textarea cannot live in a 24px strip. */ -}}
  .chatedit[open]>form{position:absolute;right:0;top:1.8em;z-index:2;
    width:min(420px, 60vw);background:var(--bg);border:1px solid var(--rule);
    border-radius:var(--r-2);box-shadow:var(--shadow-1);padding:var(--sp-2)}
}
@media (prefers-reduced-motion: reduce){
  .chatmsg,.chat-toolbar,.chat-clock{transition:none}
}
{{- /* Code, mentions and references, at chat weight. The mention chip
       is scoped to chat: the forum keeps its byline treatment. */ -}}
.chatmsg code{background:var(--code-bg);border-radius:var(--r-1);padding:1px 5px}
.chatmsg pre{background:var(--code-bg);border:1px solid var(--rule);
  border-radius:var(--r-2);padding:10px 12px;overflow-x:auto}
.chatmsg pre code{background:none;padding:0}
.chatmsg .at{background:var(--code-bg);
  background:color-mix(in srgb, var(--accent) 18%, transparent);
  color:var(--accent);border-radius:var(--r-1);padding:0 4px;font-weight:600;
  text-decoration:none}
.chatmsg a.ref{opacity:0.6}
.chatmsg a.ref:hover,.chatmsg a.ref:focus{opacity:1}
{{- /* Two pills on a rule: the unread line in the accent, the day
       separator neutral. Same shape, so they read as the same kind of
       thing — a mark in the log, not a message. */ -}}
.chat-divider,.chat-date{display:flex;align-items:center;gap:var(--sp-2);
  margin:var(--sp-4) 0;list-style:none}
.chat-divider::before,.chat-divider::after{content:"";flex:1;height:1px;background:var(--accent)}
.chat-date::before,.chat-date::after{content:"";flex:1;height:1px;background:var(--rule)}
.chat-divider>span,.chat-date>span{border-radius:var(--r-4);padding:2px 10px;
  font-size:0.7rem;font-weight:600;letter-spacing:0.05em;text-transform:uppercase;
  white-space:nowrap}
.chat-divider>span{background:var(--accent);color:var(--bg)}
.chat-date>span{background:var(--rule);color:var(--fg)}
{{- /* Jump-to-latest is drawn only when the server KNOWS the reader is
       not at the latest — an older page. Without script that is the
       only honest answer, so with script off the pill is simply
       absent rather than wrong. */ -}}
.chat-jump{position:absolute;left:50%;transform:translateX(-50%);bottom:var(--sp-4);
  background:var(--accent);color:var(--bg);border-radius:var(--r-4);
  padding:var(--sp-1) var(--sp-3);font-size:0.78rem;font-weight:600;
  text-decoration:none;box-shadow:var(--shadow-1)}
{{- /* The composer: one rounded field with a toolbar strip inside its
       own border — the note on the left, the key hint and Send on the
       right, mark-read as a text link between them. The strip is not a
       second control bar under a box; it is part of the box. */ -}}
.composer{display:block;margin:0 0 var(--sp-2);background:var(--bg);
  border:1px solid var(--rule);border-radius:var(--r-3)}
.composer:focus-within{outline:2px solid var(--accent);outline-offset:-1px}
.composer-in{display:block;width:100%;box-sizing:border-box;border:0;background:none;
  color:var(--fg);font:inherit;padding:0.55em 1em;resize:none;outline:none;
  field-sizing:content;min-height:2.7em;max-height:9.5em;overflow-y:auto}
.composer-bar{display:flex;align-items:center;gap:var(--sp-2);flex-wrap:wrap;
  border-top:1px solid var(--rule);padding:var(--sp-1) var(--sp-2) var(--sp-1) 1em}
.composer-note{flex:1 0 15rem;min-width:0;font-size:0.72rem;color:var(--muted)}
.composer-hint{font-size:0.72rem;color:var(--muted);white-space:nowrap}
.composer-send{background:var(--accent);color:var(--bg);border:0;border-radius:var(--r-2);
  padding:var(--sp-1) var(--sp-3);font:inherit;font-size:0.85rem;font-weight:600;
  cursor:pointer}
.composer-send:disabled{opacity:0.45;cursor:default}
{{- /* Two words, one line: on a narrow viewport the note beside it
       wraps, never the control. */ -}}
.chat-mark{background:none;border:0;padding:0;font:inherit;font-size:0.72rem;
  color:var(--muted);cursor:pointer;text-decoration:underline;white-space:nowrap}
.mentions{list-style:none;margin:0 0 var(--sp-1);padding:0 1em;display:flex;
  gap:var(--sp-1);flex-wrap:wrap}
.mentions[hidden]{display:none}</style>{{end}}`

var chatPage = template.Must(template.Must(base.Clone()).Parse(chatStyleSource + chatLogSource + `{{define "content"}}
{{template "chat-style" .}}
{{if .ChatNext}}<p><a href="/r/{{.Repo}}/chat?before={{.ChatNext}}">load older messages</a></p>{{end}}
<div class="chatwrap"{{if .Live}} {{.LiveAttr}}{{end}}>{{template "chat-log" .}}
{{- if .ChatBefore}}<a class="chat-jump" href="/r/{{.Repo}}/chat">jump to latest &darr;</a>{{end}}</div>
{{if .ChatViewer}}
{{- /* One field, one strip inside its border. Enter-to-send is an
       ENHANCEMENT: with no script the key makes a newline and the Send
       button is the way, which is why Send is a real submit and starts
       enabled. */ -}}
<form class="composer" method="post" action="/r/{{.Repo}}/chat"
  data-signals="{chatText:'',chatSending:false}" data-indicator="chatSending"
  data-on:submit__prevent="@post(evt.target.action, {contentType: 'form'})">
<textarea class="composer-in" name="text" data-bind="chatText" rows="1"
  placeholder="Message #{{.Repo}}" maxlength="4096" required autocomplete="off"
  data-on:keydown="evt.key === 'Enter' &amp;&amp; !evt.shiftKey &amp;&amp; (evt.preventDefault(), evt.target.form.requestSubmit())"
  data-on:input__debounce.200ms="@get('/r/{{.Repo}}/mention.frag', {contentType: 'form'})"></textarea>
{{- /* The completion list is additive: it starts empty and stays empty
       without script, and the textarea is a textarea either way. */ -}}
<ul id="mentions" class="mentions" hidden></ul>
<div class="composer-bar">
<small class="composer-note">Messages persist for 7 days; durable forum-thread archival lands with zit forum verbs.</small>
{{- /* "Mark read" is housekeeping, not an action the page is about: a
       text link in the strip, never a button competing with Send. It
       submits its OWN form through the form attribute, because a form
       cannot be nested inside another one. */ -}}
<button type="submit" class="chat-mark" form="chat-read">mark read</button>
<span class="composer-hint">&crarr; send &middot; &#8679;&crarr; newline</span>
<button type="submit" class="composer-send" data-attr:disabled="$chatSending || !$chatText">Send</button>
</div>
</form>
<form id="chat-read" method="post" action="/r/{{.Repo}}/chat/read"></form>
{{else}}<p><small class="tl-meta-inline">Sign in to post.</small></p>
<p><small class="tl-meta-inline">Messages persist for 7 days; durable forum-thread archival lands with zit forum verbs.</small></p>{{end}}
{{end}}`))

// chatPermalinkPage renders one folded message (chat.get) plus its
// direct replies — the page a reference in durable text links to
// (RFC 0011 §14, wired by Phase 1b; this page exists now so that link
// resolves). Its "aged out" state is the honest answer to a seq the
// window has already dropped.
var chatPermalinkPage = template.Must(template.Must(base.Clone()).Parse(chatStyleSource + `{{define "content"}}
{{template "chat-style" .}}
{{if .ChatExpired}}<p data-hook="chat-expired">This message has aged out of the chat window.</p>
{{else}}
<div class="chatlog">{{chatMsgHTML .ChatOne $.Repo $.ChatViewer $.ChatViewerAll}}
{{range .ChatReplies}}{{chatMsgHTML . $.Repo $.ChatViewer $.ChatViewerAll}}{{end}}</div>
<p><a href="/r/{{.Repo}}/chat">back to chat</a></p>
{{end}}
{{end}}`))

var docsPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
<article>{{.WikiHTML}}</article>
{{end}}`))

var wikiEditPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
<form method="post" action="/r/{{.Repo}}/wiki/{{pathesc .Wiki.Title}}/edit">
<p><textarea name="body" rows="20" placeholder="Markdown">{{.EditSource}}</textarea></p>
<p><button type="submit">Save</button> <a href="/r/{{.Repo}}/wiki/{{pathesc .Wiki.Title}}">cancel</a></p>
</form>
{{end}}`))

// ticketVocab renders the repository's vocabulary as datalists —
// shared by the new and edit forms, which are separate template trees;
// a define in one is invisible to the other.
const ticketVocab = `{{define "ticket-vocab"}}
{{- /* The repository's own words (ticket.config), offered as
       SUGGESTIONS: a datalist completes, a select would refuse a word
       the tracker already uses. */ -}}
{{range $field, $words := .Vocab}}{{if $words}}<datalist id="v-{{$field}}">{{range $words}}<option value="{{.}}">{{end}}</datalist>
{{end}}{{end}}{{end}}`

// The triage fields are `input list=` rather than `select`: the
// vocabulary below is fossil's DEFAULT, and a tracker may use any words
// it likes. A select would refuse a word the tracker already writes,
// which would leave quarry unable to edit trackers it can read.
var ticketNewPage = template.Must(template.Must(base.Clone()).Parse(ticketVocab + `{{define "content"}}
<form method="post" action="/r/{{.Repo}}/ticket/new">
<p><label>Title<br><input name="title" required value="{{.Prefill.Title}}"></label></p>
<div class="fieldrow">
<label>Status<br><input name="status" value="Open" list="v-status"></label>
<label>Type<br><input name="type" list="v-type" value="{{.Prefill.Type}}"></label>
<label>Severity<br><input name="severity" list="v-severity" value="{{.Prefill.Severity}}"></label>
<label>Priority<br><input name="priority" list="v-priority" value="{{.Prefill.Priority}}"></label>
<label>Subsystem<br><input name="subsystem" value="{{.Prefill.Subsystem}}"></label>
<label>Found in<br><input name="foundin" value="{{.Prefill.FoundIn}}" placeholder="version"></label>
</div>
<p><label>Comment<br><textarea name="comment" rows="8">{{.Prefill.Comment}}</textarea></label></p>
<p><button type="submit">Open ticket</button></p>
</form>
{{template "ticket-vocab" .}}
{{end}}
`))

var ticketEditPage = template.Must(template.Must(base.Clone()).Parse(ticketVocab + `{{define "content"}}
<form method="post" action="/r/{{.Repo}}/ticket/{{printf "%.10s" .Ticket.ID}}/edit">
<p><label>Title<br><input name="title" value="{{.Ticket.Field "title"}}"></label></p>
<div class="fieldrow">
<label>Status<br><input name="status" value="{{.Ticket.Field "status"}}" list="v-status"></label>
<label>Resolution<br><input name="resolution" value="{{.Ticket.Field "resolution"}}" list="v-resolution"></label>
<label>Type<br><input name="type" value="{{.Ticket.Field "type"}}" list="v-type"></label>
<label>Severity<br><input name="severity" value="{{.Ticket.Field "severity"}}" list="v-severity"></label>
<label>Priority<br><input name="priority" value="{{.Ticket.Field "priority"}}" list="v-priority"></label>
<label>Subsystem<br><input name="subsystem" value="{{.Ticket.Field "subsystem"}}"></label>
<label>Found in<br><input name="foundin" value="{{.Ticket.Field "foundin"}}" placeholder="version"></label>
</div>
<p><label>Comment<br><textarea name="comment" rows="6" placeholder="add a comment"></textarea></label></p>
{{template "ticket-vocab" .}}
<p><button type="submit">Save change</button> <a href="/r/{{.Repo}}/ticket/{{printf "%.10s" .Ticket.ID}}">cancel</a></p>
</form>
{{end}}`))

// commentText flattens fossil-wiki link syntax for places that want
// the comment as TEXT — the h1, the <title>. "[target|label]" reads as
// its label, "[target]" as its target; fossil renders these as links
// where there is room for markup, but a heading full of pipe syntax
// reads as a rendering bug.
var fossilCommentLink = regexp.MustCompile(`\[([^\]|]*)\|([^\]]*)\]|\[([^\]]*)\]`)

func commentText(s string) string {
	return fossilCommentLink.ReplaceAllStringFunc(s, func(m string) string {
		sub := fossilCommentLink.FindStringSubmatch(m)
		if sub[2] != "" {
			return sub[2]
		}
		return sub[3]
	})
}

var hexTarget = regexp.MustCompile(`^[0-9a-f]{6,64}$`)

// commentHTML renders a comment the way fossil renders it: escaped
// text with the bracket syntax turned into real links. A hex target
// goes to /info, which resolves it to a check-in, ticket, wiki edit,
// technote or forum post at click time — the renderer cannot know the
// kind, and fossil's own comments reference tickets as often as
// check-ins. An http(s) target leaves the site; anything else stays
// literal text, brackets and all. (A "[0]" is a footnote, not a page.)
// looksLikeFossilRoute reports whether a comment link target was aimed
// at a fossil page rather than being ordinary bracketed prose. Only
// these degrade to their label; anything else stays as written, because
// "[see below]" in a commit message is not a broken link.
func looksLikeFossilRoute(target string) bool {
	return strings.HasPrefix(target, "/") ||
		strings.HasPrefix(target, "forum:") ||
		strings.HasPrefix(target, "wiki:")
}

// routeLabel names a fossil route for a reader when the comment gave no
// label of its own. Without it the LINK TEXT is the raw path — markup
// leaking into prose, which is the one thing this renderer must never
// do. Only the hash-bearing forum forms need it in practice; anything
// else keeps the target as written.
func routeLabel(target string) string {
	t := strings.TrimPrefix(target, "forum:")
	for _, r := range []struct{ verb, name string }{
		{"/forumpost/", "forum post "},
		{"/forumthread/", "forum post "},
		{"/tktview/", "ticket "},
		// An artifact citation reads as the hash itself — the same way
		// a bare [hash] renders, because it is the same reference.
		{"/info/", ""},
		{"/artifact/", ""},
		{"/whatis/", ""},
	} {
		if rest := strings.TrimPrefix(t, r.verb); rest != t && rest != "" {
			return r.name + rest
		}
	}
	if t == "/timeline" {
		return "timeline"
	}
	if name := strings.TrimPrefix(target, "wiki:"); name != target && name != "" {
		return name
	}
	return target
}

func commentHTML(repo, s string) template.HTML {
	var b strings.Builder
	last := 0
	for _, m := range fossilCommentLink.FindAllStringSubmatchIndex(s, -1) {
		b.WriteString(template.HTMLEscapeString(s[last:m[0]]))
		last = m[1]
		target, label := "", ""
		if m[2] >= 0 {
			target, label = s[m[2]:m[3]], s[m[4]:m[5]]
		} else {
			target = s[m[6]:m[7]]
			label = routeLabel(target)
		}
		href := ""
		switch {
		case hexTarget.MatchString(strings.ToLower(target)):
			href = "/r/" + url.PathEscape(repo) + "/info/" + url.PathEscape(target)
		case strings.HasPrefix(target, "http://") || strings.HasPrefix(target, "https://"):
			href = target
		case strings.HasPrefix(target, "/"):
			// fossil's own site-relative links, through the SAME table
			// the wiki renderer uses. Empty when quarry has no
			// equivalent, and the label is shown as text — the rule
			// fossil-wiki already follows for these.
			href = api.FossilRoute(repo, target)
		case strings.HasPrefix(target, "forum:"):
			// [forum:/forumthread/<hash>|label]
			href = api.FossilRoute(repo, strings.TrimPrefix(target, "forum:"))
		case strings.HasPrefix(target, "wiki:"):
			href = "/r/" + url.PathEscape(repo) + "/wiki/" +
				url.PathEscape(strings.TrimPrefix(target, "wiki:"))
		}
		if href == "" && label != "" && looksLikeFossilRoute(target) {
			// A fossil route quarry has no equivalent for: show the
			// human label, not the wiki source. Same rule the wiki
			// renderer follows — the reader loses a link, never gains
			// visible markup. This is why fossil's [/md_rules|Markdown]
			// read as "[/md_rules#ftnts|Markdown]" in a comment.
			b.WriteString(template.HTMLEscapeString(label))
			continue
		}
		if href == "" || label == "" {
			b.WriteString(template.HTMLEscapeString(s[m[0]:m[1]]))
			continue
		}
		b.WriteString(`<a href="` + template.HTMLEscapeString(href) + `">` +
			template.HTMLEscapeString(label) + `</a>`)
	}
	b.WriteString(template.HTMLEscapeString(s[last:]))
	return template.HTML(b.String())
}

var checkinPage = template.Must(template.Must(base.Clone()).Parse(diffBodySource + `{{define "content"}}
{{- /* GitHub's shape: the page is NAMED by its hash and the message
       is CONTENT — a quiet box at body size, subject bolded, the rest
       verbatim with its line breaks, bracket links live as fossil
       renders them. No forge headlines the message, because none can
       trust its length: fossil comments have no subject-line
       convention and 2% of first lines in real repositories run past
       200 characters. The full manifest lives in the tree browser —
       this page answers "what changed". */ -}}
<div class="ci-h">check-in <code>{{printf "%.12s" .Checkin.Hash}}</code>
{{- /* The full hash is what a reader COPIES — into a bug report, a
       cherry-pick, a message. Hiding all 64 characters in a title
       attribute made it hoverable and nothing else: unreachable on a
       phone, unreachable from the keyboard. It gets its own line
       because 64 characters set inline would push the tags off a
       narrow screen.

       The copy is written three ways on purpose. navigator.clipboard
       is UNDEFINED on an insecure origin, and quarry is served over
       plain HTTP on a LAN more often than not — a button that silently
       does nothing there is worse than no button. So the hash is
       selected first (which execCommand can act on, and which is the
       native copy gesture on a phone), execCommand tried, and the
       Clipboard API used when it exists. If all of it fails the text
       is still selected, ready to copy by hand. */ -}}
<button type="button" class="ci-copy"
  title="copy the full hash" aria-label="copy the full hash"
  onclick="var c=this.parentNode.nextElementSibling.firstChild,b=this,u=b.firstChild.firstChild,s=getSelection(),r=document.createRange();r.selectNodeContents(c);s.removeAllRanges();s.addRange(r);var d=function(){b.classList.add('done');u.setAttribute('href','#i-check');b.setAttribute('aria-label','full hash copied');clearTimeout(b._t);b._t=setTimeout(function(){b.classList.remove('done');u.setAttribute('href','#i-copy');b.setAttribute('aria-label','copy the full hash')},5000)},k=false;try{k=document.execCommand('copy')}catch(e){}if(navigator.clipboard){navigator.clipboard.writeText(c.textContent).then(d,function(){if(k)d()})}else if(k){d()}"><svg class="ic" aria-hidden="true"><use href="#i-copy"/></svg></button>
{{- if .Checkin.Tags}}
<span class="ci-tags" aria-label="tags">{{range .Checkin.Tags}}<a class="ci-tag" href="/r/{{$.Repo}}/timeline?tag={{.}}"><svg class="ic" aria-hidden="true"><use href="#i-tag"/></svg>{{.}}</a>{{end}}</span>
{{- end}}
</div>
<p class="ci-fullhash"><code>{{.Checkin.Hash}}</code></p>
<div class="ci-box">
<p class="ci-sub{{if .CheckinLongLead}} long{{end}}">{{.CheckinLead}}</p>
{{if .CheckinBody}}<div class="ci-msg">{{.CheckinBody}}</div>{{end}}
{{- /* A comment tag lets an author correct a check-in message after
       the fact, and the correction is what fossil shows. Showing it
       silently would be the wrong kind of quiet: someone who followed a
       link written against the old wording must be able to see that it
       changed. */ -}}
{{if .Checkin.CommentOrig}}<p class="ct-was"><span class="ct-waslabel">corrected</span> from &ldquo;{{.Checkin.CommentOrig}}&rdquo; &middot; <a href="/r/{{.Repo}}/checkin/{{.Checkin.Hash}}/tags">history</a></p>{{end}}
</div>
<div class="repo-stats">
<span>{{if .CIBadge}}{{if .Checkin.CIRun}}<a class="ci-link" href="/r/{{.Repo}}/ci/run/{{.Checkin.CIRun}}" title="the run behind this verdict">{{.CIBadge}}</a>{{else}}{{.CIBadge}}{{end}} {{end}}{{ago .Checkin.Date}} by {{who .Repo .Checkin.User}}</span>
<a href="/r/{{.Repo}}/timeline?branch={{.Checkin.Branch}}"><svg class="ic" aria-hidden="true"><use href="#i-branch"/></svg> {{.Checkin.Branch}}</a>
{{range $i, $p := .Checkin.Parents}}<a href="/r/{{$.Repo}}/checkin/{{$p}}" title="{{$p}}">{{if $i}}merged from{{else}}parent{{end}}</a>{{end}}
<a href="/r/{{.Repo}}/tree/{{.Checkin.Hash}}/"><svg class="ic" aria-hidden="true"><use href="#i-dir"/></svg> browse files</a>
<a href="/r/{{.Repo}}/checkin/{{.Checkin.Hash}}/tags"><svg class="ic" aria-hidden="true"><use href="#i-tag"/></svg> tag history</a>
{{if .BranchDiff}}<a href="/r/{{.Repo}}/checkin/{{.Checkin.Hash}}/diff?branch=1"><svg class="ic" aria-hidden="true"><use href="#i-branch"/></svg> branch diff</a>{{end}}
<a href="/r/{{.Repo}}/checkin/{{.Checkin.Hash}}/manifest"><svg class="ic" aria-hidden="true"><use href="#i-file"/></svg> manifest</a>
{{if .Checkin.Hidden}}<span class="ct-flag">hidden</span>{{end}}
{{if .Checkin.Closed}}<span class="ct-flag">closed</span>{{end}}
</div>
{{- /* After the comment and the metadata, before what changed —
       fossil's own order (Overview, About, Context). Above the title it
       was a wide empty bar floating over the page name, which reads as
       a defect rather than a section. */ -}}
{{template "artifact-note" .}}
{{template "ci-context" .}}
{{chatrefs .ChatRefs .Repo}}
{{if .Checkin.DiscussedIn}}<p><small>discussed in {{range $i, $t := .Checkin.DiscussedIn}}{{if $i}} · {{end}}<a href="/r/{{$.Repo}}/forum/{{printf "%.16s" $t.Root}}">{{if $t.Title}}{{$t.Title}}{{else}}(untitled thread){{end}}</a>{{end}}</small></p>{{end}}
{{template "diff-body" .}}
{{end}}`))

var checkinTagsPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
{{- /* The provenance of a check-in, not its labels. Fossil records
       every tag artifact that ever touched an object — a branch
       renamed, a comment corrected, hidden and closed set and unset --
       and reading them in order is how you find out what happened to a
       check-in after it was made. Oldest first, because this is a
       history and a history is read forwards. */ -}}
<p class="ct-back"><a href="/r/{{.Repo}}/checkin/{{.CheckinTags.Hash}}">&larr; check-in <code>{{printf "%.12s" .CheckinTags.Hash}}</code></a></p>
<div class="ci-box">
<p class="ci-sub">{{.CheckinTags.Comment}}</p>
{{if .CheckinTags.CommentOrig}}
{{- /* The correction is what fossil shows and what quarry now shows.
       The superseded text is kept because a reader who followed a link
       written against the OLD wording needs to see that it changed,
       not silently get different words. */ -}}
<p class="ct-was"><span class="ct-waslabel">originally</span> {{.CheckinTags.CommentOrig}}</p>{{end}}
</div>
<div class="repo-stats">
<span>{{ago .CheckinTags.Date}} by {{who .Repo .CheckinTags.User}}</span>
<a href="/r/{{.Repo}}/timeline?branch={{.CheckinTags.Branch}}"><svg class="ic" aria-hidden="true"><use href="#i-branch"/></svg> {{.CheckinTags.Branch}}</a>
{{if .CheckinTags.Hidden}}<span class="ct-flag">hidden</span>{{end}}
{{if .CheckinTags.Closed}}<span class="ct-flag">closed</span>{{end}}
</div>
{{if .CheckinTags.Events}}
<h2 class="ct-h">{{count (len .CheckinTags.Events)}} tag {{plural (len .CheckinTags.Events) "artifact" "artifacts"}}</h2>
<div class="tw"><table class="ct">
<thead><tr><th>when</th><th>tag</th><th><span class="sr-only">effect</span></th><th>value</th><th>from</th></tr></thead>
<tbody>{{range .CheckinTags.Events}}
<tr{{if not .Standing}} class="ct-gone"{{end}}>
<td class="ct-when">{{.Date}}</td>
<td class="ct-name"><code>{{.Name}}</code></td>
<td class="ct-sign"><span class="sg sg-{{signClass .Sign}}" title="{{signWord .Sign}}">{{.Sign}}</span></td>
<td class="ct-val">{{if .Value}}{{.Value}}{{else}}<span class="ct-none">{{signWord .Sign}}</span>{{end}}</td>
<td class="ct-src"><a href="/r/{{$.Repo}}/checkin/{{.Src}}"><code>{{printf "%.10s" .Src}}</code></a></td>
</tr>{{end}}</tbody>
</table></div>
<p class="ct-legend">A row in force is shown plain; a row a later artifact overruled is struck through. Fossil tags are a log, so the newest row for each name is the one that counts.</p>
{{else}}<p>No tag artifact has ever touched this check-in.</p>{{end}}
{{end}}`))

var manifestPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
{{- /* The canonical record of a check-in. Almost all of a manifest is
       its file list -- 980 cards of 988 on a real fossil release -- and
       the tree browser renders that same set with paths you can click.
       So the file list is COUNTED here and linked, and the cards that
       carry everything else get the page. That is the whole difference
       between this and fossil's raw /artifact: same facts, without the
       wall. */ -}}
<p class="ct-back"><a href="/r/{{.Repo}}/checkin/{{.Manifest.Hash}}">&larr; check-in <code>{{printf "%.12s" .Manifest.Hash}}</code></a></p>
<table class="mf">
<tbody>{{range .Manifest.Cards}}
<tr>
<td class="mf-l"><code>{{.Letter}}</code></td>
<td class="mf-t">{{.Text}}</td>
<td class="mf-n">{{.Note}}</td>
</tr>{{end}}</tbody>
</table>
<p class="mf-files"><a href="/r/{{.Repo}}/tree/{{.Manifest.Hash}}/"><svg class="ic" aria-hidden="true"><use href="#i-dir"/></svg> {{count .Manifest.Files}} <code>F</code> {{plural .Manifest.Files "card" "cards"}}</a>
<span class="mf-why">the file list &mdash; nearly all of this artifact&rsquo;s {{thousands .Manifest.Size}} bytes. Browse it in the tree, where the paths are links.</span></p>
<p class="mf-note">Card text is shown exactly as the artifact stores it, escapes and all, because that is what the <code>R</code> and <code>Z</code> checksums are taken over. Decoding it for display would make this no longer the record.</p>
{{end}}`))

var ticketBoardPage = template.Must(template.Must(base.Clone()).Parse(boardSource))

const boardSource = `{{define "content"}}
{{template "ticket-head" .}}
{{template "ticket-filters" .}}
{{- /* The board is a grid of server-grouped columns crossed by
       swimlanes. Everything works with no script at all: a card is moved
       with the select beneath it, which submits like any form.

       That select is the MECHANISM, not a fallback. Dragging is layered
       over it for pointer users and picking-up is layered over it for
       everyone else; hiding the select once script loads would leave a
       board that keyboard and assistive-technology readers cannot
       operate. All three do the same POST. */ -}}
<form class="board-axes" method="get" action="{{.Nav.Path}}">
<input type="hidden" name="view" value="board">
{{range .Nav.Hidden}}{{if ne .Name "view"}}<input type="hidden" name="{{.Name}}" value="{{.Value}}">{{end}}{{end}}
<label>columns <select name="group" onchange="this.form.submit()">
{{range .AxisFields}}<option value="{{.Key}}"{{if eq .Key $.GroupBy}} selected{{end}}>{{.Label}}</option>{{end}}
</select></label>
<label>lanes <select name="lane" onchange="this.form.submit()">
<option value="none"{{if eq .LaneBy ""}} selected{{end}}>none</option>
{{range .AxisFields}}{{if ne .Key $.GroupBy}}<option value="{{.Key}}"{{if eq .Key $.LaneBy}} selected{{end}}>{{.Label}}</option>{{end}}{{end}}
</select></label>
<noscript><button type="submit">apply</button></noscript>
{{if .Truncated}}<span class="board-trunc">showing the {{count .Shown}} most recently updated</span>{{end}}
</form>
<div id="board" data-signals="{held: '', over: ''}">{{template "board-body" .}}</div>
{{end}}

{{define "board-body"}}
{{if .Board}}
{{- /* Feedback for the last move, with its undo: the one thing a reader
       needs after a drop is to know it landed, and a way back. A live
       region so it is announced; a form so it works without script. */ -}}
{{with .Moved}}<div class="board-moved" role="status">Moved <strong>{{.Title}}</strong>{{if .From}} from {{.From}}{{end}} to <strong>{{.To}}</strong>
<form method="post" action="/r/{{$.Repo}}/ticket/{{.ID}}/move?to={{if .From}}{{.From}}{{else}}{{unsetLane}}{{end}}&amp;field={{.Field}}&amp;group={{$.GroupBy}}&amp;lane={{if $.LaneBy}}{{$.LaneBy}}{{else}}none{{end}}{{if $.Nav.State}}&amp;state={{$.Nav.State}}{{end}}" data-on:submit__prevent="@post(evt.target.action)"><button type="submit">undo</button></form></div>{{end}}
{{range .Board}}
{{if $.LaneBy}}<h2 class="lane-h"><span class="lane-name">{{.Label}}</span> <span class="n">{{count .Count}}</span></h2>{{end}}
<div class="board">{{range .Columns}}
{{- /* The column is the drop target. While a card is over it the
       column says so (data-class:over), which is the signifier a drag
       needs: where this will land. */ -}}
<section class="board-col{{if not .Expanded}} folded{{end}}"
  data-class:over="$over === '{{.Status}}'"
  data-on:dragover__prevent="$over = '{{.Status}}'"
  data-on:dragleave="$over === '{{.Status}}' &amp;&amp; ($over = '')"
  data-on:drop__prevent="$over = ''; $held &amp;&amp; (@post('/r/{{$.Repo}}/ticket/' + $held + '/move?to={{.Status}}&amp;field={{$.GroupBy}}&amp;group={{$.GroupBy}}&amp;lane={{if $.LaneBy}}{{$.LaneBy}}{{else}}none{{end}}{{if $.Nav.State}}&amp;state={{$.Nav.State}}{{end}}'), $held = '')">
{{- /* A folded column is GitHub's collapsed column: the name and its
       count on a narrow strip, still a drop target. The name links to
       the same view with this column opened. */ -}}
{{if not .Expanded}}<h3><a class="unfold" href="{{.ToggleURL}}" title="open the {{.Status}} column"><span class="t-status {{statusClass .Status}}">{{.Status}}</span> <span class="n">{{len .Tickets}}</span> <span class="chev" aria-hidden="true">&rsaquo;</span></a></h3>
{{else}}<h3><span class="t-status {{statusClass .Status}}">{{.Status}}</span> <span class="n">{{count (len .Tickets)}}</span> <a class="fold" href="{{.ToggleURL}}" aria-label="fold the {{.Status}} column" title="fold"><span class="chev" aria-hidden="true">&lsaquo;</span></a></h3>{{end}}
{{range .Tickets}}
{{- /* Two ways to move a card, one per kind of input: drag it (the
       grip says so, the cursor says so), or open its Move menu — a
       native popover of forms, so it works by keyboard, by touch, and
       with scripting off. Nothing is a mode. */ -}}
<article class="card" data-ticket="{{.ID}}"{{if $.CanWrite}} draggable="true"
  data-on:dragstart="$held = '{{printf "%.10s" .ID}}'"
  data-on:dragend="$held = ''; $over = ''"
  data-class:held="$held === '{{printf "%.10s" .ID}}'"{{end}}>
{{if $.CanWrite}}<span class="grip" aria-hidden="true" title="drag to move">&#x2807;</span>{{end}}
<a class="t-title" href="/r/{{$.Repo}}/ticket/{{.ID}}">{{.Title}}</a>
<div class="t-badges">
{{- /* A lane already names its field for every card in it; repeating
       the badge on each card is noise. */ -}}
{{if and .Priority (ne $.LaneBy "priority")}}<span class="b-pri" title="priority">{{.Priority}}</span>{{end}}
{{if and .Severity (ne $.LaneBy "severity")}}<span class="b-sev" title="severity">{{.Severity}}</span>{{end}}
{{if and .Type (ne $.LaneBy "type")}}<span class="b-type" title="type">{{.Type}}</span>{{end}}
{{if and .Subsystem (ne $.LaneBy "subsystem")}}<span class="b-sub" title="subsystem">{{.Subsystem}}</span>{{end}}
</div>
<div class="t-meta"><span class="t-id" title="{{.ID}}">#{{printf "%.8s" .ID}}</span> · {{ago .Updated}}{{if $.CanWrite}}
{{$id := printf "%.10s" .ID}}{{$here := .}}<button type="button" class="mv-btn" popovertarget="mv-{{$id}}" style="anchor-name: --mv-{{$id}}" aria-label="move {{.Title}}">Move <span class="caret" aria-hidden="true">&#9662;</span></button>
<div id="mv-{{$id}}" popover class="menu mv" style="position-anchor: --mv-{{$id}}">
{{range $.ColumnLabels}}{{if ne . (fieldOf $here $.GroupBy)}}<form method="post" action="/r/{{$.Repo}}/ticket/{{$id}}/move?to={{.}}&amp;field={{$.GroupBy}}&amp;group={{$.GroupBy}}&amp;lane={{if $.LaneBy}}{{$.LaneBy}}{{else}}none{{end}}{{if $.Nav.State}}&amp;state={{$.Nav.State}}{{end}}" data-on:submit__prevent="@post(evt.target.action)"><button type="submit">{{.}}</button></form>{{end}}{{end}}
</div>{{end}}</div>
</article>
{{end}}
</section>
{{end}}</div>
{{end}}
{{else}}<p>{{if .Nav.Is "state" "open"}}No open tickets. <a href="{{.Nav.URL "state" "all"}}">See all {{count (add .Nav.Open .Nav.Closed)}}</a>.{{else}}No tickets.{{end}}</p>{{end}}
{{end}}`

var ticketListPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
{{template "ticket-head" .}}
{{template "ticket-filters" .}}
{{if .Truncated}}<p class="board-trunc">priority order covers the {{count .Shown}} most recently updated; the rest are on the recent pages</p>{{end}}
{{- /* The row, in GitHub's anatomy over fossil's schema: a state glyph
       in the gutter, the title as the whole click target, labels for
       the fields that distinguish this ticket from its neighbours, and
       a byline saying who opened it and when it last moved. What the
       old row printed instead — Open, Medium, Important on every line —
       was three chips of pure noise. */ -}}
<div class="t-body">
{{template "ticket-rail" .}}
<div class="t-listing">
{{if .Rows}}<ul class="tickets">{{range .Rows}}
<li class="t-row">
<svg class="ic t-glyph g-{{.State}}" aria-hidden="true"><use href="#{{.Glyph}}"/></svg>
<div class="t-main">
<a class="t-title" href="{{.Href}}">{{.Title}}</a>{{if $.Across}}<a class="t-repo" href="{{$.Nav.Facet "repo" .Repo}}">{{.Repo}}</a>{{end}}
{{range .Chips}}<span class="chip {{.Class}}" title="{{.Title}}">{{.Text}}</span>{{end}}
<div class="t-sub"><code>#{{printf "%.8s" .ID}}</code>{{if eq .State "review"}} · {{.Status}}{{end}} · opened {{ago .Created}}{{if .Author}} by {{who $.Repo .Author}}{{end}}{{if ne .Updated .Created}} · updated {{ago .Updated}}{{end}}</div>
</div>
{{if .Refs}}<a class="t-conv" href="{{.Href}}#tkt-refs" title="{{.Refs}} landing{{if ne .Refs 1}}s{{end}} reference{{if eq .Refs 1}}s{{end}} this ticket"><svg class="ic" aria-hidden="true"><use href="#i-branch"/></svg>{{.Refs}}</a>{{end}}
{{if .Comments}}<a class="t-conv" href="{{.Href}}#tkt-timeline" title="{{.Comments}} comment{{if ne .Comments 1}}s{{end}}"><svg class="ic" aria-hidden="true"><use href="#i-comment"/></svg>{{.Comments}}</a>{{end}}
</li>
{{end}}</ul>{{else}}<p class="t-none">{{if .Nav.Is "state" "closed"}}Nothing finished yet.{{else if .Nav.Is "state" "all"}}This tracker has no tickets.{{else}}No open tickets. <a href="{{.Nav.URL "state" "all"}}">See all {{count (add .Nav.Open .Nav.Closed)}}</a>.{{end}}</p>{{end}}
{{template "ticket-pager" .}}
</div></div>
{{end}}`))

var ticketTablePage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
{{template "ticket-head" .}}
{{template "ticket-filters" .}}
{{- /* Fossil parity, done properly: the dense tabular scan its report
       pages are loved for, with the column headers as sort links and
       the state glyph kept so a row's standing survives the change of
       shape. .tw scrolls it rather than pushing the page sideways. */ -}}
{{if .Truncated}}<p class="board-trunc">a sorted table covers the {{count .Shown}} most recently updated; narrow the report to see further</p>{{end}}
<div class="t-body">
{{template "ticket-rail" .}}
<div class="t-listing">
{{if .Rows}}<div class="tw"><table class="t-table">
<thead><tr>
{{range $.Columns}}<th><a href="{{$.Nav.OrderURL .Key}}">{{.Label}}{{with $.Nav.OrderMark .Key}} <span class="ord">{{.}}</span>{{end}}</a></th>{{end}}
</tr></thead>
<tbody>
{{range .Rows}}<tr>
<td class="c-id"><svg class="ic t-glyph g-{{.State}}" aria-hidden="true"><use href="#{{.Glyph}}"/></svg> <a href="{{.Href}}"><code>{{printf "%.8s" .ID}}</code></a></td>
<td class="c-title"><a href="{{.Href}}">{{.Title}}</a>{{if $.Across}} <a class="t-repo" href="{{$.Nav.Facet "repo" .Repo}}">{{.Repo}}</a>{{end}}</td>
<td>{{.Status}}</td>
<td>{{.Type}}</td>
<td>{{.Subsystem}}</td>
<td>{{.Author}}</td>
<td>{{ago .Updated}}</td>
</tr>
{{end}}</tbody></table></div>{{else}}<p class="t-none">{{if .Nav.Is "state" "closed"}}Nothing finished yet.{{else if .Nav.Is "state" "all"}}This tracker has no tickets.{{else}}No open tickets. <a href="{{.Nav.URL "state" "all"}}">See all {{count (add .Nav.Open .Nav.Closed)}}</a>.{{end}}</p>{{end}}
{{template "ticket-pager" .}}
</div></div>
{{end}}`))

var inboxPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
{{- /* A triage queue, not a settings screen with a list under it: the
       filters and "mark all read" on one bar, one row per item at a
       tap-sized height, and the preferences folded away at the bottom
       where somebody goes once. Every control is an ordinary form, so
       the page is complete with no script at all (0001 Principle 3). */ -}}
<style>.inbox-bar{display:flex;gap:var(--sp-4);align-items:baseline;font-size:0.85rem;
  border-bottom:1px solid var(--rule);padding-bottom:var(--sp-1);margin-bottom:var(--sp-1);
  flex-wrap:wrap}
.inbox-f{color:var(--muted);font-weight:400;text-decoration:none;padding-bottom:var(--sp-1)}
.inbox-f:hover{color:var(--accent)}
.inbox-f.on{color:var(--fg);font-weight:600;box-shadow:inset 0 -2px 0 var(--accent)}
.inbox-n{color:var(--muted);font-weight:400}
.inbox-spacer{flex:1}
.inbox-allread{background:none;border:1px solid var(--rule);border-radius:var(--r-1);
  padding:2px var(--sp-2);font:inherit;font-size:0.8rem;color:var(--muted);cursor:pointer}
.inbox-allread:hover:enabled{color:var(--accent);border-color:var(--accent)}
.inbox-allread:disabled{opacity:0.45;cursor:default}
.attn-rows{list-style:none;margin:0;padding:0}
{{- /* 56px of row, so a thumb has something to hit and the eye has a
       rhythm to follow: the dot, two lines, the time, the actions. */ -}}
.attn-row{display:grid;grid-template-columns:var(--sp-3) 1fr auto auto;
  gap:var(--sp-2);align-items:center;min-height:56px;
  padding:var(--sp-2) var(--sp-2);border-bottom:1px solid var(--rule);
  border-radius:var(--r-row);transition:background var(--t-fast)}
.attn-row:last-child{border-bottom:0}
.attn-row:hover{background:var(--surface)}
.attn-row:hover{background:color-mix(in srgb, var(--rule) 35%, transparent)}
.attn-dot{width:8px;height:8px;border-radius:var(--r-4);background:var(--accent)}
.attn-reason{font-size:0.95rem;font-weight:400;color:var(--fg);text-decoration:none}
.attn-row[data-unread="1"] .attn-reason{font-weight:600}
a.attn-reason:hover{color:var(--accent);text-decoration:underline}
.attn-why{font-size:0.82rem;color:var(--muted);margin-top:2px}
.attn-repo{background:var(--rule);color:var(--fg);border-radius:var(--r-1);padding:0 var(--sp-1)}
.attn-when{font-variant-numeric:tabular-nums;font-size:0.82rem;color:var(--muted);
  text-align:right;white-space:nowrap}
.attn-acts{display:flex;gap:var(--sp-2);align-items:center;font-size:0.78rem;white-space:nowrap}
.attn-acts form{display:inline}
{{- /* Done is the action this page exists for, so it is the only
       filled thing on the row; Unfollow is a text link beside it, not
       a second button of equal weight. */ -}}
.attn-done{background:var(--accent);color:var(--bg);border:0;border-radius:var(--r-row);
  padding:2px var(--sp-2);font:inherit;font-size:0.78rem;font-weight:600;cursor:pointer}
.attn-unfollow{background:none;border:0;padding:0;font:inherit;font-size:0.78rem;
  color:var(--muted);text-decoration:underline;cursor:pointer}
.attn-unfollow:hover{color:var(--accent)}
{{- /* Quiet until the row is reached — the chat log's own rule, so a
       long list reads as a list and not as a wall of buttons. Where
       there is no hover there is no "point at it", so they stay. */ -}}
@media (hover: hover) and (pointer: fine){
  .attn-acts{opacity:0;pointer-events:none;transition:opacity var(--t-fast)}
  .attn-row:hover .attn-acts,.attn-row:focus-within .attn-acts{opacity:1;pointer-events:auto}
}
@media (prefers-reduced-motion: reduce){.attn-acts,.attn-row{transition:none}}
.attn-none{color:var(--muted)}
.inbox-older{margin-top:var(--sp-3);font-size:0.85rem}
.inbox-settings{margin-top:var(--sp-6);border-top:1px solid var(--rule);
  padding-top:var(--sp-3);font-size:0.9rem}
.inbox-settings>summary{cursor:pointer;color:var(--muted);font-size:0.9rem}
.inbox-settings .inbox-pref{margin:var(--sp-3) 0}
.inbox-settings .inbox-pref small{display:block;color:var(--muted);margin-top:var(--sp-1)}</style>
<p id="inbox-error" class="attn-none"{{if .Error}} data-error="1"{{end}}>
{{- if .Error}}<strong>{{.Error}}</strong>{{end}}</p>
<div class="inbox-bar">
{{range .AttnTabs}}<a class="inbox-f{{if .On}} on{{end}}" data-filter="{{.Key}}"
  href="/inbox?f={{.Key}}">{{.Label}}{{if .Count}} <span class="inbox-n">{{.Count}}</span>{{end}}</a>
{{end}}<span class="inbox-spacer"></span>
<form method="post" action="/inbox/mark"><input type="hidden" name="all" value="1">
<input type="hidden" name="as" value="read"><input type="hidden" name="f" value="{{.AttnFilter}}">
<button type="submit" class="inbox-allread"
  {{if not .AttnUnread}}disabled{{end}}>Mark all read</button></form>
</div>
{{if .AttnRecent}}<ul class="attn-rows">{{range .AttnRecent}}
<li class="attn-row{{if .Unread}} unread{{end}}" id="{{.ElemID}}" data-id="{{.ID}}"
  data-seq="{{.Seq}}" data-reason-kind="{{.Kind}}" data-source="{{if .Notify}}notify{{else}}local{{end}}"
  data-unread="{{if .Unread}}1{{else}}0{{end}}">
{{if .Unread}}<span class="attn-dot" aria-hidden="true"></span>{{else}}<span></span>{{end}}
<div>{{if .Link}}<a class="attn-reason" href="{{.Link}}">{{.Reason}}</a>
{{- else}}<span class="attn-reason">{{.Reason}}</span>{{end}}
<div class="attn-why">{{if .Repo}}<span class="attn-repo">{{.Repo}}</span> · {{end}}
{{- if .Summary}}<span class="attn-summary">{{.Summary}}</span>{{end}}</div></div>
{{if .At}}<time class="attn-when">{{ago .At}}</time>{{else}}<span></span>{{end}}
<div class="attn-acts">
{{- if .ID}}<form method="post" action="/inbox/mark"
  data-on:submit__prevent="@post('/inbox/mark', {contentType: 'form'})">
<input type="hidden" name="id" value="{{.ID}}">
{{- /* A notify message can be archived; one of quarry's own attention
       events has no per-item archive, so its control marks it read and
       says that word. Two labels because they are two actions. */ -}}
<input type="hidden" name="as" value="{{if .Notify}}done{{else}}read{{end}}">
<input type="hidden" name="f" value="{{$.AttnFilter}}">
<input type="hidden" name="before" value="{{$.AttnBefore}}">
<button type="submit" class="attn-done">{{if .Notify}}Done{{else}}Mark read{{end}}</button></form>{{end}}
{{- if .Root}}<form method="post" action="/r/{{.Repo}}/forum/{{.Root}}/subscribe">
<input type="hidden" name="state" value="off"><input type="hidden" name="back" value="inbox">
<button type="submit" class="attn-unfollow">Unfollow</button></form>{{end}}
</div></li>
{{end}}</ul>{{else}}<p class="attn-none">{{.AttnEmpty}}</p>{{end}}
{{if .AttnNext}}<p class="inbox-older"><a class="inbox-older-link"
  href="/inbox?f={{.AttnFilter}}&amp;before={{.AttnNext}}">Older</a></p>{{end}}
{{if .HasPrefs}}
{{- /* Settings live at the bottom, folded: a person sets them once and
       triages every day. They are SET on the preferences page — one
       matrix, one place — and summarised here so the fold still answers
       "how am I told?" without becoming a second form that can
       disagree with the first. */ -}}
<details class="inbox-settings"><summary>Notification settings</summary>
<p class="inbox-pref" data-pref="toasts">In-page banners: <strong>{{if .AttnToasts}}on{{else}}off{{end}}</strong></p>
<p class="inbox-pref" data-pref="notify_desktop">Desktop notifications: <strong>{{if .NotifyDesktop}}on{{else}}off{{end}}</strong></p>
<p class="inbox-pref"><a href="/me/notifications">Notification preferences</a> — which channels
carry which kind of message, push on this device, and the repositories you have muted.</p>
</details>{{end}}
{{end}}`))

var loginPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
{{if .Error}}<p><strong>{{.Error}}</strong></p>{{end}}
<form method="post" action="/login">
<input type="hidden" name="next" value="{{.LoginNext}}">
<p><label>Account<br><input name="user" autocomplete="username" required autofocus></label></p>
<p><label>Password<br><input name="password" type="password" autocomplete="current-password" required></label></p>
<p><button type="submit">Sign in</button></p>
</form>
{{end}}`))

var historyPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
<p><a href="/r/{{.Repo}}/file/{{.TreeVersion}}/{{.HistoryPath}}"><code>{{.HistoryPath}}</code></a></p>
{{if .History}}<div class="tw"><table>
<thead><tr><th scope="col">Check-in</th><th scope="col">When</th><th scope="col">Who</th><th scope="col">Comment</th></tr></thead>
<tbody>{{range .History}}
<tr><td><a href="/r/{{$.Repo}}/checkin/{{printf "%.16s" .Hash}}"><code>{{printf "%.12s" .Hash}}</code></a></td>
<td class="tl-meta-inline">{{ago .Date}}</td><td>{{identicon .User}} {{.User}}</td><td>{{.Comment}}</td></tr>
{{end}}</tbody>
</table></div>
{{else}}<p>No recorded changes to this file — it has existed in one state for its whole life here.</p>{{end}}
{{end}}`))

var ciPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
{{- /* The controls stay OUTSIDE the live region: a patch redraws the
       runs, never the reader's half-filled filter form. */ -}}
<form method="get" class="ci-filter" action="/r/{{.Repo}}/ci">
<select name="state" aria-label="status">
<option value="">any status</option>
{{range $s := ciStates}}<option value="{{$s}}"{{if eq $.CIState $s}} selected{{end}}>{{$s}}</option>{{end}}
</select>
<select name="branch" aria-label="branch">
<option value="">any branch</option>
{{range .CIBranches}}<option{{if eq $.CIBranch .}} selected{{end}}>{{.}}</option>{{end}}
</select>
{{if gt (len .CIPipelines) 1}}<select name="pipeline" aria-label="pipeline">
<option value="">any pipeline</option>
{{range .CIPipelines}}<option{{if eq $.CIPipeline .}} selected{{end}}>{{.}}</option>{{end}}
</select>{{end}}
<button type="submit" class="btn">Filter</button>
</form>
<div{{if .Live}} {{.LiveAttr}}{{end}}><div id="ci">{{template "ci-body" .}}</div></div>
{{end}}
{{define "ci-body"}}
{{range .CIBypasses}}<div class="ci-health">
<svg class="ic d-ic fail" aria-hidden="true"><use href="#i-shield"/></svg>
<span><strong><code>{{.Branch}}</code> moved past its gate</strong> at <a href="/r/{{$.Repo}}/checkin/{{printf "%.16s" .Checkin}}"><code>{{printf "%.12s" .Checkin}}</code></a> — no forge accept behind it</span>
<span class="d-meta">{{ago .Seen}}</span>
</div>
{{end}}{{range .CIHealth}}{{if .Pipeline}}<div class="ci-health">
{{if eq .TipState "fail"}}<svg class="ic d-ic fail" aria-hidden="true"><use href="#i-x"/></svg>
<span><strong><code>{{.Pipeline}}</code> is red on trunk</strong> at <a href="/r/{{$.Repo}}/checkin/{{printf "%.16s" .TipCheckin}}"><code>{{printf "%.12s" .TipCheckin}}</code></a>{{with .TipFailStep}} — step <strong>{{.}}</strong>{{end}}</span>
{{else if eq .TipState "pass"}}<svg class="ic d-ic pass" aria-hidden="true"><use href="#i-check"/></svg>
<span><code>{{.Pipeline}}</code> is green on trunk</span>
{{else}}<svg class="ic d-ic wait" aria-hidden="true"><use href="#i-clock"/></svg>
<span><code>{{.Pipeline}}</code> <span class="d-meta">{{if eq .TipState "running"}}running on trunk{{else}}no recent trunk run{{end}}</span></span>{{end}}
{{if .N}}<span class="d-meta">{{.PassPct}}% pass over {{.N}}{{with .Median}} · median {{.}}{{end}}</span>{{end}}
</div>{{end}}{{end}}
{{if .CIRuns}}<div class="ci-rows">{{range .CIRuns}}
<div class="ci-row">
<a class="ci-chip" href="/r/{{$.Repo}}/ci/run/{{printf "%.12s" .RunID}}"><span class="tl-badge{{if eq (ciState .Status) "pass"}} ci-pass{{else if eq (ciState .Status) "fail"}} ci-fail{{end}}">{{ciState .Status}}</span></a>
<div class="ci-main">
<a class="ci-title" href="/r/{{$.Repo}}/ci/run/{{printf "%.12s" .RunID}}">{{if .Comment}}{{firstline .Comment}}{{else}}run {{printf "%.12s" .RunID}}{{end}}</a>
{{if .FailStep}}<span class="ci-why">step <strong>{{.FailStep}}</strong> failed{{with .FailLine}} · <code>{{.}}</code>{{end}}</span>{{end}}
<span class="ci-meta"><a href="/r/{{$.Repo}}/checkin/{{printf "%.16s" .Checkin}}"><code>{{printf "%.12s" .Checkin}}</code></a>{{with .Branch}} · <code>{{.}}</code>{{end}}{{with .User}} · {{.}}{{end}} · {{.Pipeline}}{{if .Pair}} · <span class="chip">premerge</span>{{end}}</span>
</div>
<div class="ci-side">{{with .Duration}}<span class="ci-dur">{{.}}</span>{{end}}<span class="d-meta" title="{{.Started}}">{{ago .Started}}</span>
{{if and $.CanTrigger (ne (ciState .Status) "running")}}<form method="post" action="/r/{{$.Repo}}/ci/trigger"><input type="hidden" name="checkin" value="{{.Checkin}}"><input type="hidden" name="back" value="/r/{{$.Repo}}/ci"><button type="submit" class="btn ci-rerun">Re-run</button></form>{{end}}
</div>
</div>{{end}}</div>
{{else if or .CIState .CIBranch .CIPipeline}}<p>No runs match the filter.</p>
{{else}}<p>No CI runs. A pipeline is <code>ci/*.json</code> in the repository, in dagnats' workflow format; it runs on the check-ins made after it lands.</p>{{end}}
{{if .CanTrigger}}<p class="ci-meta ci-pipes">pipelines: {{range .CIPipelines}}{{if ne . "external"}}<a href="/r/{{$.Repo}}/ci/pipeline?path={{pathesc .}}"><code>{{.}}</code></a> · {{end}}{{end}}<a href="/r/{{$.Repo}}/ci/pipeline?new=1">new pipeline</a></p>{{end}}
{{end}}`))

var ciEditPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
<p class="d-sub">A pipeline is tracked content. Saving writes a check-in on a fresh
branch and opens a landing — it lands like any change, gated by the very checks it
defines. Nothing here can write to the target branch.</p>
{{if .CIEditDiags}}<div class="ci-health"><svg class="ic d-ic fail" aria-hidden="true"><use href="#i-x"/></svg>
<span><strong>It does not compile.</strong></span></div>
<ul class="l-paths">{{range .CIEditDiags}}<li>{{.}}</li>{{end}}</ul>
{{else if .CIEditOK}}<div class="ci-health"><svg class="ic d-ic pass" aria-hidden="true"><use href="#i-check"/></svg>
<span><strong>It compiles.</strong> <span class="d-meta">the engine (or the JSON shape check) found nothing to say</span></span></div>{{end}}
<form method="post" action="/r/{{.Repo}}/ci/pipeline" class="ci-editor">
<p><label>path <input name="path" value="{{.CIEditPath}}" size="32" maxlength="120" placeholder="ci/checks.json"{{if not .CIEditNew}} readonly{{end}}></label></p>
<textarea name="content" rows="18" spellcheck="false" aria-label="pipeline definition">{{.CIEditContent}}</textarea>
<p><label>why <input name="message" value="{{.CIEditMessage}}" size="48" maxlength="500" placeholder="ci: what this change does"></label></p>
<p><button type="submit" name="action" value="validate" class="btn">Validate</button>
<button type="submit" name="action" value="save" class="btn-primary">Save to a branch and open a landing</button>
<a class="tn-new" href="/r/{{.Repo}}/ci">back to runs</a></p>
</form>
{{end}}`))

// The run page (RFC 0009 §logs): what happened, step by step, with
// the output underneath — failed steps open, green ones folded, and a
// repro line so the failing task can be run locally with no forge in
// the loop. An engine that cannot serve logs yet says so in words.
const runStepsSource = `{{define "run-steps"}}{{with .CIRunView}}{{range .Steps}}<details class="d-row runstep"{{if .Open}} open{{end}}>
<summary><svg class="ic d-ic {{.State}}" aria-hidden="true"><use href="#i-{{if eq .State "pass"}}check{{else if eq .State "fail"}}x{{else if eq .State "cancelled"}}x{{else if eq .State "notrun"}}x{{else}}clock{{end}}"/></svg>
<span class="d-line"><strong>{{.ID}}</strong> <span class="d-sub">{{.Status}}{{if .Duration}} · {{.Duration}}{{end}}{{if gt .Attempts 1}} · attempt {{.Attempts}}{{end}}{{with .Error}} · {{.}}{{end}}</span></span></summary>
<div class="d-body">
{{if .Chunks}}<pre class="runlog">{{range .Chunks}}<span class="ll{{if eq .Stream "err"}} ll-err{{end}}{{if eq .Stream "marker"}} ll-mark{{end}}" id="s-{{$.CIRunView.Anchor}}-{{.Seq}}"><a class="ll-n" href="#s-{{$.CIRunView.Anchor}}-{{.Seq}}">{{.Seq}}</a>{{.Data}}</span>{{end}}</pre>{{else if .LogNote}}<p class="d-sub">{{.LogNote}}</p>{{else}}<p class="d-sub">no output recorded</p>{{end}}
</div></details>
{{end}}{{end}}{{end}}`

var ciRunPage = template.Must(template.Must(template.Must(base.Clone()).Parse(runStepsSource)).Parse(`{{define "content"}}
{{with .CIRunView}}
<h1><code>{{.Row.Pipeline}}</code> <span class="tl-badge{{if eq (ciState .Row.Status) "pass"}} ci-pass{{else if eq (ciState .Row.Status) "fail"}} ci-fail{{end}}">{{ciState .Row.Status}}</span></h1>
<p class="l-meta">run <code>{{printf "%.12s" .Row.RunID}}</code> · {{.Row.Workflow}}
· on <a href="/r/{{$.Repo}}/checkin/{{printf "%.16s" .Row.Checkin}}"><code>{{printf "%.12s" .Row.Checkin}}</code></a>
· started {{ago .Row.Started}}{{if .Duration}} · took {{.Duration}}{{end}}
{{if .Row.Pair}} · <span class="chip">premerge</span>{{end}}</p>
{{if .EngineGone}}<p class="d-sub">{{.EngineGone}}</p>{{end}}
{{- /* Baseline is this page, reloaded by the reader; Datastar layers a
       3s follow while the run is live and never adds a control
       (RFC 0001 Principle 3). */ -}}
{{if .Running}}<div data-init="@get('{{$.RunFragPath}}')" data-on-interval__duration.3s="@get('{{$.RunFragPath}}')">{{end}}
<div id="run-body">
{{template "run-steps" $}}
</div>
{{if .Running}}</div>{{end}}
{{if .Repro}}<h2>Reproduce</h2>
<p class="d-sub">The failing task, locally — no forge in the loop:</p>
<pre class="l-steps">{{.Repro}}</pre>{{end}}
<p><a class="tn-new" href="/r/{{$.Repo}}/ci">all runs &rarr;</a></p>
{{end}}{{end}}`))

const docPanelSource = `{{define "doc-panel"}}
{{- /* Switching tabs is a MORPH, not a navigation: a reload threw away
       the reader's scroll position mid-README. The href stays as the
       no-script path — a plain load of the same view — and syncurl
       fetches the one-shot fragment while correcting the address bar to
       that same href. Without the correction the tab you are reading is
       unlinkable and a reload silently drops you back on README, even
       though /r/REPO?doc=LICENSE has always been a real route. */ -}}
{{with .About}}<nav class="doc-tabs">
{{$sel := .DocPath}}{{range .Docs}}<a href="/r/{{$.Repo}}?doc={{pathesc .Path}}"{{if eq .Path $sel}} class="here"{{end}} {{syncurl (printf "/r/%s/doc.frag?doc=%s" $.Repo (pathesc .Path))}}>{{.Label}}{{if eq .Path $sel}}<span class="ink" aria-hidden="true"></span>{{end}}</a>{{end}}
</nav>
<div class="tkt-body readme doc-panel">{{$.DocHTML}}</div>{{end}}
{{end}}`

var dashboardPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
{{with .Dash}}
{{- /* The landing page answers three questions in the order a person
       actually has them: what needs me, where do I go, what changed.
       GitHub and Codeberg both lead with the feed — the least
       actionable of the three — and leave "what needs me" to a
       different page entirely. */ -}}
{{if .Awaiting}}<section class="dash-band">
<h2>Waiting on you</h2>
<ul class="dash-list awaiting">{{range .Awaiting}}
<li class="aw-row">
<svg class="ic t-glyph g-{{.State}}" aria-hidden="true"><use href="#{{.Glyph}}"/></svg>
<div class="aw-main"><a class="dash-title" href="{{.Href}}">{{.Title}}</a>
<div class="dash-meta"><a href="/r/{{pathesc .Repo}}/ticket">{{.Repo}}</a> · <code>#{{printf "%.8s" .ID}}</code>{{if .LastUser}} · {{.LastUser}} answered{{end}} {{ago .Updated}}</div></div>
</li>
{{end}}</ul>
<p class="dash-more"><a href="/tickets?awaiting=1">every ticket waiting on you &rarr;</a> · <a href="/tickets">all your trackers</a></p>
</section>{{end}}

<div class="dash">
<aside class="dash-side">
<h2>Your repositories</h2>
{{- /* GitHub's most-clicked control on this page is the repository
       filter box, and it needs no script to work: a GET form is a
       filter. */ -}}
{{if gt (len .Repos) 6}}<form class="dash-find" method="get" action="/">
{{if .Kind}}<input type="hidden" name="kind" value="{{.Kind}}">{{end}}
<input type="search" name="find" value="{{.Find}}" placeholder="find a repository" aria-label="find a repository">
</form>{{end}}
{{if .Repos}}<ul class="dash-list">{{range .Repos}}
<li><a class="dash-title" href="/r/{{pathesc .Name}}">{{.Name}}</a>
{{if .Open}}<a class="dash-open" href="/r/{{pathesc .Name}}/ticket" title="open tickets">{{count .Open}}</a>{{end}}
<div class="dash-meta">{{if .Description}}{{.Description}} · {{end}}{{if .LastActivity}}active {{ago .LastActivity}}{{end}}</div></li>
{{end}}</ul>{{else if .Find}}<p>No repository of yours is called that.</p>{{else}}<p>No repositories granted to this account yet.</p>{{end}}
<p class="dash-more"><a href="/?view=explore">explore all {{if $.FleetTotal}}{{$.FleetTotal}} {{end}}repositories &rarr;</a></p>
{{- /* Only what this reader can actually start. */ -}}
{{if .CanCreate}}<p class="dash-act"><a class="btn" href="/new">New repository</a></p>{{end}}
</aside>

<section class="dash-feed">
<h2>Activity</h2>
{{- /* Every artifact in quarry is one typed event stream, so this feed
       can be filtered honestly — a chip's number counts exactly the
       rows clicking it shows. Neither reference forge can do that,
       because their feeds are not one type system. */ -}}
{{if .Kinds}}<nav class="dash-chips seg-box" aria-label="activity kinds">
<a href="{{.FeedURL ""}}"{{if not .Kind}} class="here"{{end}}>everything</a>
{{range .Kinds}}<a href="{{$.Dash.FeedURL .Kind}}"{{if eq $.Dash.Kind .Kind}} class="here"{{end}}>{{kindLabel .Kind}} <span class="n">{{count .Count}}</span></a>{{end}}
</nav>{{end}}
{{if .Feed}}<ul class="dash-list">{{range .Feed}}
<li>{{template "dash-event" .}}</li>
{{end}}</ul>
{{template "pager" .Pager}}
{{- /* The feed is a window on recent activity, not an archive. Saying
       how far it reaches AND how much there is keeps the pager honest:
       a control that numbered every page would be promising a walk it
       cannot take. The archive is each repository's own timeline. */ -}}
{{if gt .Total .Depth}}<p class="dash-depth">the {{thousands .Depth}} most recent of {{thousands .Total}} — a repository's timeline holds the rest</p>{{end}}
{{else}}<p>Nothing yet — activity in your repositories lands here.</p>{{end}}
</section>
</div>
{{end}}
{{end}}

{{define "dash-event"}}
{{- /* ci and tickets and wiki link straight to their object; technote
       and forum link to their section — their refs are not stable page
       paths yet. */ -}}
<span class="tl-badge">{{if eq .Kind "ci"}}check-in{{else if eq .Kind "t"}}ticket{{else if eq .Kind "w"}}wiki{{else if eq .Kind "e"}}technote{{else if eq .Kind "f"}}forum{{else}}{{.Kind}}{{end}}</span>
<a class="dash-title" href="/r/{{pathesc .Repo}}{{if eq .Kind "ci"}}/checkin/{{printf "%.16s" .Hash}}{{else if eq .Kind "t"}}/ticket/{{printf "%.10s" .Ref}}{{else if eq .Kind "w"}}/wiki/{{pathesc .Ref}}{{else if eq .Kind "e"}}/technote{{else if eq .Kind "f"}}/forum{{else}}{{end}}">
{{- if .Comment}}{{firstline .Comment}}{{else}}{{.Ref}}{{end}}</a>
<div class="dash-meta"><a href="/r/{{pathesc .Repo}}">{{.Repo}}</a> · {{.User}} · {{ago .Date}}</div>
{{end}}`))

// splitRow is one side-by-side row: a deletion paired with the
// addition that replaced it, a context line on both sides, or one side
// alone. Pairing is the same run-alignment the word-diff uses, so the
// marks land opposite each other.
type splitRow struct {
	Left, Right *diff.Line
}

func splitRows(h diff.Hunk) []splitRow {
	var out []splitRow
	i := 0
	for i < len(h.Lines) {
		l := h.Lines[i]
		switch l.Kind {
		case "context":
			out = append(out, splitRow{&h.Lines[i], &h.Lines[i]})
			i++
		case "deletion":
			ds := i
			for i < len(h.Lines) && h.Lines[i].Kind == "deletion" {
				i++
			}
			as := i
			for i < len(h.Lines) && h.Lines[i].Kind == "addition" {
				i++
			}
			dn, an := as-ds, i-as
			for k := 0; k < max(dn, an); k++ {
				var row splitRow
				if k < dn {
					row.Left = &h.Lines[ds+k]
				}
				if k < an {
					row.Right = &h.Lines[as+k]
				}
				out = append(out, row)
			}
		default: // addition run with no deletions before it
			out = append(out, splitRow{nil, &h.Lines[i]})
			i++
		}
	}
	return out
}

var branchesPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
{{- /* fossil's /brlist split: the open branches are the living work
       and lead; the closed ones are history and follow, marked. */ -}}
{{if .Branches}}<div class="tw"><table>
<thead><tr><th scope="col">Branch</th><th scope="col">Updated</th><th scope="col">Tip</th></tr></thead>
<tbody>{{range .Branches}}{{if not .Closed}}
<tr><td><a href="/r/{{$.Repo}}/tree/{{pathesc .Tip}}/">{{.Name}}</a></td>
<td class="tl-meta-inline">{{ago .Date}}</td>
<td><a href="/r/{{$.Repo}}/checkin/{{printf "%.16s" .Tip}}"><code>{{printf "%.12s" .Tip}}</code></a></td></tr>
{{end}}{{end}}</tbody></table></div>
{{if .ClosedCount}}<h3>Closed <span class="tl-badge">{{count .ClosedCount}}</span></h3>
<div class="tw"><table>
<tbody>{{range .Branches}}{{if .Closed}}
<tr><td><a href="/r/{{$.Repo}}/tree/{{pathesc .Tip}}/">{{.Name}}</a> <span class="tl-badge">closed</span></td>
<td class="tl-meta-inline">{{ago .Date}}</td>
<td><a href="/r/{{$.Repo}}/checkin/{{printf "%.16s" .Tip}}"><code>{{printf "%.12s" .Tip}}</code></a></td></tr>
{{end}}{{end}}</tbody></table></div>{{end}}
{{else}}<p>No branches yet.</p>{{end}}
{{end}}`))

var tagsPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
{{if .Tags}}<div class="tw"><table>
<thead><tr><th scope="col">Tag</th><th scope="col">When</th><th scope="col">Check-in</th></tr></thead>
<tbody>{{range .Tags}}
<tr><td><svg class="ic" aria-hidden="true"><use href="#i-tag"/></svg> {{.Name}}</td>
<td class="tl-meta-inline">{{if .Date}}{{ago .Date}}{{end}}</td>
<td><a href="/r/{{$.Repo}}/checkin/{{printf "%.16s" .Tip}}"><code>{{printf "%.12s" .Tip}}</code></a></td></tr>
{{end}}</tbody></table></div>
{{else}}<p>No tags yet. A release tag names a check-in: <code>zit tag &lt;name&gt; &lt;check-in&gt;</code>.</p>{{end}}
{{end}}`))

var treePage = template.Must(template.Must(base.Clone()).Parse(docPanelSource + `{{define "content"}}
{{- /* One line of chrome, not four. The branch picker, the crumb trail
       and the clone affordances all belong to "which tree am I looking
       at", so they share a row and the listing starts near the top. */ -}}
<div class="repo-home{{if .About}} has-about{{end}}">
{{if .About}}{{with .About}}
{{- /* The document tabs: README | Contributing | License | Security by
       root-level convention, or the .quarry/repo.json docs list when
       the project curates. Tab choice is URL state (?doc=), so it is
       linkable, back-button-correct and needs no script. The aside
       precedes the file table in source order for the same reason it
       does on GitHub and Forgejo: floated, it rides the right edge
       from the top of the listing; stacked on a phone, "what is this"
       comes before the files. */ -}}
<aside class="about-card">
<h2 class="about-h">About</h2>
{{if .Description}}<p class="about-desc">{{.Description}}</p>{{end}}
{{if .Homepage}}<a class="about-row about-link" href="{{.Homepage}}" rel="nofollow"><svg class="ic" aria-hidden="true"><use href="#i-link"/></svg> <span>{{.Homepage}}</span></a>{{end}}
{{if .Topics}}<p class="topics">{{range .Topics}}<a class="b-pill" href="/?q={{.}}" title="repositories tagged {{.}}">{{.}}</a>{{end}}</p>{{end}}
{{range .Docs}}<a class="about-row" href="?doc={{pathesc .Path}}#docs"><svg class="ic" aria-hidden="true"><use href="#{{docIcon .Label}}"/></svg> <span>{{docRowLabel .Label $.About.LicenseName}}</span></a>
{{end -}}
{{if .Contributors}}<a class="about-row" href="/r/{{$.Repo}}/people"><svg class="ic" aria-hidden="true"><use href="#i-people"/></svg> <span><strong>{{count .Contributors}}</strong> {{plural .Contributors "contributor" "contributors"}}</span></a>{{end}}
{{- /* Where a project's news belongs, and ABOVE the tags: what a
       project has been doing is a better first answer to "what is
       this" than which versions it has cut. It also carries the weight
       of being a main door — notes have no tab, since fossil's own
       default menu has none and libfossil, which uses them as a
       milestone feed, did not add one either — and a door reads
       poorly third in a sidebar. */ -}}
{{if .NoteEvent}}<div class="about-div"></div>
<h2 class="about-h"><a href="/r/{{$.Repo}}/technote">Notes</a>{{if gt .NoteCount 1}} <span class="tl-badge">{{.NoteCount}}</span>{{end}}</h2>
<p class="about-row"><svg class="ic" aria-hidden="true"><use href="#i-clock"/></svg> <a href="/r/{{$.Repo}}/technote/{{printf "%.16s" .NoteEvent}}"><strong>{{if .NoteTitle}}{{plain .NoteTitle}}{{else}}(untitled){{end}}</strong></a></p>
{{with .NoteExcerpt}}<p class="about-sub about-note-x">{{.}}</p>{{end}}
<p class="about-sub">{{ago .NoteDate}}{{with .NoteUser}} · {{who $.Repo .}}{{end}}</p>
{{end}}
{{if .LatestTag}}<div class="about-div"></div>
<h2 class="about-h"><a href="/r/{{$.Repo}}/tag">Tags</a> <span class="tl-badge">{{count .TagCount}}</span></h2>
<p class="about-row about-tag"><svg class="ic" aria-hidden="true"><use href="#i-tag"/></svg> <a href="/r/{{$.Repo}}/checkin/{{.LatestTagTip}}" title="{{.LatestTagTip}}"><strong>{{.LatestTag}}</strong></a> <span class="latest-pill">Latest</span></p>
<p class="about-sub">{{ago .LatestTagDate}}</p>
{{if gt .TagCount 1}}<p class="about-sub"><a href="/r/{{$.Repo}}/tag">+ {{count (sub .TagCount 1)}} tags</a></p>{{end}}
{{end}}
{{if .AnnounceRoot}}<div class="about-div"></div>
<h2 class="about-h"><a href="/r/{{$.Repo}}/forum">Announcement</a></h2>
<p class="about-row"><svg class="ic" aria-hidden="true"><use href="#i-comment"/></svg> <a href="/r/{{$.Repo}}/forum/{{printf "%.16s" .AnnounceRoot}}"><strong>{{if .AnnounceTitle}}{{.AnnounceTitle}}{{else}}(untitled){{end}}</strong></a></p>
<p class="about-sub">{{ago .AnnounceDate}}</p>
{{end}}
</aside>
{{end}}{{end}}
{{- /* Forgejo's shape: a strip of repository facts, then a row with the
       ref switcher on the left and clone/download on the right. The
       facts were previously nowhere and the switcher was a bare select
       whose width was set by its longest branch name. */ -}}
<div class="repo-stats">
<a href="/r/{{.Repo}}/timeline"><svg class="ic" aria-hidden="true"><use href="#i-commit"/></svg> {{count .Counts.Checkins}} {{plural .Counts.Checkins "check-in" "check-ins"}}</a>
<a href="/r/{{.Repo}}/branch"><svg class="ic" aria-hidden="true"><use href="#i-branch"/></svg> {{count .BranchTotal}} {{plural .BranchTotal "branch" "branches"}}</a>
{{if .Counts.Tags}}<a href="/r/{{.Repo}}/tag"><svg class="ic" aria-hidden="true"><use href="#i-tag"/></svg> {{count .Counts.Tags}} {{plural .Counts.Tags "tag" "tags"}}</a>{{end}}
{{- /* Zero is not rendered. "0 clones" is a true statement that reads
       as a judgement, and a repository nobody has cloned yet is the
       normal state of a new one. */ -}}
{{if .CanPraise}}<form class="praise-form" method="post" action="/r/{{.Repo}}/praise">
<input type="hidden" name="on" value="{{if .Praised}}0{{else}}1{{end}}">
<input type="hidden" name="back" value="/r/{{.Repo}}">
<button type="submit" class="praise-btn{{if .Praised}} on{{end}}"
  aria-pressed="{{if .Praised}}true{{else}}false{{end}}"
  title="{{if .Praised}}withdraw praise{{else}}praise this repository{{end}}"
><svg class="ic" aria-hidden="true"><use href="#i-praise"/></svg>
{{if .Praised}}praised{{else}}praise{{end}}{{if .PraiseCount}} <span class="praise-n">{{.PraiseCount}}</span>{{end}}</button>
</form>{{end}}
{{if .CloneCount}}<span title="clones served since counting began"><svg class="ic" aria-hidden="true"><use href="#i-download"/></svg> {{count .CloneCount}} {{plural .CloneCount "clone" "clones"}}</span>{{end}}
<a href="/r/{{.Repo}}/people"><svg class="ic" aria-hidden="true"><use href="#i-people"/></svg> {{count .Counts.Contributors}} {{plural .Counts.Contributors "contributor" "contributors"}}</a>
</div>
<div class="tree-bar">
{{if .Branches}}
{{- /* A popover, not a select: a select is as wide as its widest option
       and cannot show branches and tags as separate lists. This shows
       both, and stays one button wide whatever the names are. */ -}}
<div class="refpick">
<button type="button" class="refbtn" popovertarget="refs" aria-label="switch branch or tag">
<svg class="ic" aria-hidden="true"><use href="#i-branch"/></svg> <span class="refname">{{.RefName}}</span> <span class="caret" aria-hidden="true">▾</span></button>
<div id="refs" popover class="menu refs">
<div class="menu-who">branches{{if .MoreBranches}} · {{.MoreBranches}} older not shown{{end}}</div>
{{range .Branches}}<a href="/r/{{$.Repo}}/tree/{{.Tip}}"{{if eq .Tip $.TreeVersion}} class="here"{{end}}>{{.Label}}</a>{{end}}
{{if .Tags}}<div class="menu-who">tags</div>
{{range .Tags}}<a href="/r/{{$.Repo}}/tree/{{.Tip}}"{{if eq .Tip $.TreeVersion}} class="here"{{end}}>{{.Name}}</a>{{end}}{{end}}
</div>
</div>{{end}}
<span class="crumbs"><a href="/r/{{.Repo}}/tree">{{.Repo}}</a>{{range .Crumbs}} / <a href="/r/{{$.Repo}}/tree/{{$.TreeVersion}}/{{.Path}}">{{.Name}}</a>{{end}}</span>
<span class="tree-acts">
{{- /* The clone URL is selectable text with a copy button beside it, and
       the archives sit behind one "download" rather than two loose
       links, which is what stopped this row fitting a phone. */ -}}
{{- /* zit and fossil share the sync protocol, so a store that never
       emitted a sub-manifest can be cloned by either. Offering the
       choice saves a reader who already has fossil from installing
       anything; it is withheld where it would not work, because a
       command that fails is worse than one never offered. */ -}}
<span class="clonebox">{{if .FossilClone}}<span class="clonepick">
<a href="?clone=zit" class="{{if ne .CloneTool "fossil"}}here{{end}}">zit</a>
<a href="?clone=fossil" class="{{if eq .CloneTool "fossil"}}here{{end}}">fossil</a>
</span>{{end}}<input class="cloneurl" type="text" readonly value="{{.CloneTool}} clone {{.CloneURL}} {{.Repo}}" aria-label="clone command" onfocus="this.select()">
<button type="button" class="copybtn" data-tip="select the clone command" aria-label="select the clone command" onclick="this.previousElementSibling.select()"><svg class="ic" aria-hidden="true"><use href="#i-copy"/></svg></button></span>
<button type="button" class="dlbtn" popovertarget="dl">download <span class="caret" aria-hidden="true">▾</span></button>
<div id="dl" popover class="menu dlmenu">
<a href="/r/{{.Repo}}/archive/{{.TreeVersion}}">tar.gz</a>
<a href="/r/{{.Repo}}/archive/{{.TreeVersion}}?format=zip">zip</a>
</div>
</span>
</div>
{{- /* The description belongs where the repository is, not only in the
       listing: a reader arriving from a link otherwise sees nav and a
       file tree and no statement of what the project is. */ -}}
{{if and (or .RepoDescription .RepoPrivate) (not .About)}}<p class="about">{{if .RepoPrivate}}<span class="tl-badge">private</span> {{end}}{{.RepoDescription}}</p>{{end}}
{{if .Tip}}
{{- /* GitHub's latest-commit bar: who last touched this tree, what they
       said, and the door to the full history — the file table's header
       row in spirit. Root listing only until the index carries
       per-path change data. */ -}}
<div class="tip-bar">
<span class="tip-user">{{.Tip.User}}</span>
<a class="tip-msg" href="/r/{{.Repo}}/checkin/{{.Tip.Hash}}">{{commentFirst .Tip.Comment}}</a>
<span class="tip-right"><span class="tip-hash"><code>{{printf "%.10s" .Tip.Hash}}</code> ·</span> {{ago .Tip.Date}} · <a href="/r/{{.Repo}}/timeline{{if .RefName}}?branch={{.RefName}}{{end}}"><svg class="ic" aria-hidden="true"><use href="#i-clock"/></svg> {{count .Counts.Checkins}} {{plural .Counts.Checkins "check-in" "check-ins"}}</a></span>
</div>
{{end}}
{{- /* No History column: it was one identical link per row, thirty of
       them, and the file page already links its own history. GitHub and
       Forgejo both spend that space on the last change instead, which is
       what goes here once the index carries per-file data. */ -}}
<div class="tw"><table class="tree{{if .TreeChanges}} hc{{end}}">
<tbody>{{range .Tree}}
<tr>
<td class="t-name">{{if .Dir}}<svg class="ic" aria-hidden="true"><use href="#i-dir"/></svg><a href="/r/{{$.Repo}}/tree/{{$.TreeVersion}}/{{.Path}}">{{.Name}}</a>
{{- else}}<svg class="ic" aria-hidden="true"><use href="#i-file"/></svg><a href="/r/{{$.Repo}}/file/{{$.TreeVersion}}/{{.Path}}">{{.Name}}</a>
{{- if .Exec}} <span class="flag" title="executable">exe</span>{{end}}
{{- if .Link}} <span class="flag" title="symbolic link">link</span>{{end}}
{{- if .Binary}} <span class="flag" title="binary">bin</span>{{end}}{{end}}</td>
{{if $.TreeChanges}}<td class="t-change">{{if .LastHash}}<a href="/r/{{$.Repo}}/checkin/{{.LastHash}}">{{commentFirst .LastComment}}</a>{{end}}</td>
<td class="t-age">{{if .LastDate}}{{ago .LastDate}}{{end}}</td>
{{else}}<td class="t-size">{{if .Dir}}{{.Files}} files{{else}}{{.Human}}{{end}}</td>{{end}}
</tr>
{{end}}</tbody>
</table></div>
{{if .Readme}}<h3 class="readme-head">{{.ReadmeIn}}</h3>
<div class="tkt-body readme">{{.Readme}}</div>{{end}}
{{if .About}}{{with .About}}{{if .Docs}}<div id="docs">{{template "doc-panel" $}}</div>{{end}}{{end}}{{end}}
</div>
{{end}}`))

var ticketPage = template.Must(template.Must(base.Clone()).Parse(composerSource + ticketSource))

// The ticket page is the editor. Fossil keeps a separate tktedit page
// with every field as a select; GitHub has no edit page at all — the
// issue page carries its metadata in a sidebar, its composer at the
// foot of the timeline, and each field change in the timeline as an
// event. This is the GitHub shape over fossil's schema: a sidebar form
// of selects (one Update button without script, save-on-change with
// it), a remark composer whose second button closes or reopens, and
// the artifact's own J cards rendered as "status Open → Review" lines.
const ticketSource = `{{- /* One select per triage field. The form is the no-script
       path: change several, press Update. With script each select
       posts the form on change and the Update button hides — the
       sidebar and timeline come back as a patch. */ -}}
{{define "tkt-side"}}{{if and .CanWrite (not .Posture.ReadOnly)}}<form method="post" action="/r/{{.Repo}}/ticket/{{printf "%.10s" .Ticket.ID}}/edit" class="tkt-fields" data-on:submit__prevent="@post('/r/{{.Repo}}/ticket/{{printf "%.10s" .Ticket.ID}}/edit', {contentType: 'form'})">
{{range .TicketFields}}{{$cur := .Value}}{{if or .Options (ne .Name "resolution")}}<label><span class="tkt-k">{{.Name}}</span>
{{if and (eq .Name "resolution") (not $.Ticket.Closed)}}<span class="tkt-v">{{if .Value}}{{.Value}}{{else}}—{{end}}</span>{{else if .Options}}<select name="{{.Name}}" data-on:change="@post('/r/{{$.Repo}}/ticket/{{printf "%.10s" $.Ticket.ID}}/edit', {contentType: 'form'})">{{if not .Value}}<option value="" selected>—</option>{{end}}{{range .Options}}<option{{if eq . $cur}} selected{{end}}>{{.}}</option>{{end}}</select>{{else}}<input name="{{.Name}}" value="{{.Value}}" data-on:change="@post('/r/{{$.Repo}}/ticket/{{printf "%.10s" $.Ticket.ID}}/edit', {contentType: 'form'})">{{end}}</label>
{{end}}{{end}}<button type="submit" data-attr:hidden="true">Update</button>
</form>{{else}}<dl class="tkt-head">{{range .Ticket.Header}}
<dt>{{.Name}}</dt><dd>{{.Value}}</dd>{{end}}</dl>{{end}}
<dl class="tkt-head tkt-meta">{{range .Ticket.Extra}}
<dt>{{.Name}}</dt><dd>{{.Value}}</dd>{{end}}
<dt>created</dt><dd>{{ago .Ticket.Created}}</dd>
<dt>last change</dt><dd>{{ago .Ticket.Updated}}</dd>
<dt>ticket</dt><dd><code class="tkt-id">{{printf "%.20s" .Ticket.ID}}</code></dd>
</dl>
{{if .Posture.ReadOnly}}<p><a href="{{.Posture.Upstream "tktedit"}}?name={{.Ticket.ID}}">edit on {{.Posture.Host}} &rarr;</a></p>{{end}}{{end}}
{{- /* Remarks and field moves, oldest first, one block per artifact. */ -}}
{{define "tkt-timeline"}}{{range .Timeline}}<div class="{{if .HTML}}tkt-comment{{else}}tkt-event{{end}}">
<div class="tl-meta-inline">{{identicon .Login}} {{.Login}}{{if .DifferentUsername}} (claiming to be {{.Username}}){{end}}{{with .Summary}} {{.}}{{end}} · {{ago .Date}}</div>
{{.HTML}}
</div>
{{end}}{{end}}
{{define "content"}}
{{template "artifact-note" .}}
{{- /* Title and description edit where they are read: a details
       fold holding the form, so it works without script and the page
       never leaves. The layout already drew the title as its h1; the
       fold's summary is the pencil beside it. */ -}}
{{if and .CanWrite (not .Posture.ReadOnly)}}<details class="tkt-edit tkt-retitle"><summary aria-label="edit title">&#9998; title</summary>
<form method="post" action="/r/{{.Repo}}/ticket/{{printf "%.10s" .Ticket.ID}}/edit"><input name="title" value="{{.Ticket.Title}}" maxlength="200" required aria-label="title"> <button type="submit">Save</button></form></details>{{end}}
<div class="tkt-layout">
<div class="tkt-main">
{{if .DescriptionHTML}}<div class="tkt-body">{{.DescriptionHTML}}</div>{{end}}
{{if and .CanWrite (not .Posture.ReadOnly)}}<details class="tkt-edit"><summary>&#9998; {{if .DescriptionHTML}}edit description{{else}}add a description{{end}}</summary>
<form class="f-reply" method="post" action="/r/{{.Repo}}/ticket/{{printf "%.10s" .Ticket.ID}}/edit">
{{template "composer" (descctx .Repo 12 .Ticket.Description)}}
<div class="f-reply-foot"><button type="submit" class="btn-primary">Save description</button></div></form></details>{{end}}
{{if .Attachments}}<h3>Attachments</h3>
<ul>{{range .Attachments}}
<li><a href="/r/{{$.Repo}}/attachment/{{.Src}}">{{.Name}}</a> <small class="tl-meta-inline">{{ago .Date}} by {{who $.Repo .User}}</small></li>
{{end}}</ul>{{end}}
{{- /* What proposed to fix this. The references were always indexed —
       every hex ref a post writes becomes an anchor — but only the
       check-in page ever asked. A landing says how it went, because
       "something landed for this" is the whole answer a reader wants
       and a bare link makes them go and find out. */ -}}
{{if .Mentions}}<h3 id="tkt-refs">Referenced by</h3>
<ul class="tkt-refs">{{range .Mentions}}
<li><svg class="ic t-glyph g-{{if eq .State "accepted"}}done{{else}}open{{end}}" aria-hidden="true"><use href="#{{.Glyph}}"/></svg>
<a href="{{.Href $.Repo}}">{{if .Title}}{{clip 72 (unmark .Title)}}{{else}}(untitled){{end}}</a>
{{if eq .Kind "landing"}}<span class="tl-badge">{{if .State}}{{.State}}{{else}}open{{end}}</span>
{{if .Branch}}<code class="l-branch">{{.Branch}}</code>{{if .Target}} &rarr; <code class="l-branch">{{.Target}}</code>{{end}}{{end}}
{{else}}<span class="tl-badge">thread</span>{{end}}</li>
{{end}}</ul>{{end}}
{{chatrefs .ChatRefs .Repo}}
<div id="tkt-timeline">{{template "tkt-timeline" .}}</div>
{{- /* The composer: Comment, or the same remark with a status move.
       Closing asks for the resolution right there — the only moment
       it is required, and the only place it is offered while open. */ -}}
{{if and .CanWrite (not .Posture.ReadOnly)}}<form class="f-reply tkt-remark" method="post" action="/r/{{.Repo}}/ticket/{{printf "%.10s" .Ticket.ID}}/edit">
{{template "composer" (remarkctx .Repo 6 "Leave a comment (Markdown — type / for blocks)")}}
<div class="f-reply-foot">{{if .Ticket.Closed}}<button type="submit" name="status" value="Open">Reopen</button>{{else}}<label class="tkt-close">with <select name="resolution">{{range .TicketFields}}{{if eq .Name "resolution"}}{{range .Options}}<option{{if eq . "Fixed"}} selected{{end}}>{{.}}</option>{{end}}{{end}}{{end}}</select></label><button type="submit" name="status" value="Closed">Comment &amp; close</button>{{end}} <button type="submit" class="btn-primary">Comment</button></div>
</form>{{end}}
</div>
<aside class="tkt-side" id="tkt-side">{{template "tkt-side" .}}</aside>
</div>
{{end}}`

var filePage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
<p><small>at <a href="/r/{{.Repo}}/checkin/{{.File.Hash}}"><code>{{printf "%.12s" .File.Hash}}</code></a> — {{.File.Size}} bytes{{if .DocPath}} ·
<a href="/r/{{.Repo}}/doc/{{.File.Hash}}/{{.File.Path}}">rendered</a>{{end}}</small></p>
{{if .File.Binary}}<p>Binary file.</p>{{else if .FileHTML}}{{.FileHTML}}{{else}}<pre>{{.File.Content}}</pre>{{end}}
{{end}}`))

// fleetAdminPage is the operator's view of the fleet. The ordering is
// deliberate: failures first and loud, because the whole reason this
// page exists is that with eleven stores a wedged one is invisible —
// the fleet listing shows counts, and a store that has failed its round
// every two seconds for an hour has exactly the counts it had when it
// broke.
var fleetAdminPage = template.Must(template.Must(base.Clone()).Parse(fleetAdminSource))

const fleetAdminSource = `{{- /* One row per store, ingest and mirror together, because they are
       one store: the old page had two tables keyed by the same name and
       the reader scrolled twice to learn one thing. Problems lead; when
       there are any, the healthy rows fold behind a disclosure so a
       phone shows the one row that matters and a count. Counts that
       are zero do not render — a column of zeros says nothing — and
       the ones that are not are chips the eye can find. The row is a
       grid on a wide screen and a stack on a narrow one; same markup. */ -}}
{{define "fleet-row"}}<li class="row{{if .Problem}} row-problem{{end}}">
<div class="row-main">
<a class="row-name" href="/r/{{.Name}}">{{.Name}}</a>
{{$st := .IngestState}}{{if ne $st "ok"}}<span class="tl-badge{{if or (eq $st "failing") (eq $st "stalled") (eq $st "gaps")}} ci-fail{{end}}" title="{{if .Health.Stalled}}ingest has stopped retrying; next attempt {{.Health.RetryAt}}{{else if .Health.LastErr}}{{.Health.LastErr}}{{else if .Health.Gaps}}{{.Health.Gaps}} artifacts missing from the index{{end}}">{{if eq $st "gaps"}}{{.Health.Gaps}} gaps{{else}}{{$st}}{{end}}</span>{{end}}
{{with .Mirror}}{{if .Enabled}}<span class="tl-badge m-{{.State}}" title="mirror of {{.URL}}">{{if eq .State "failing"}}failing ×{{.Failures}}{{else}}{{.State}}{{end}}</span>{{if .AcceptWrites}}<span class="tl-badge" title="local writes accepted">writes</span>{{end}}{{else}}<span class="tl-badge" title="forked from {{.DetachedFrom}}">fork</span>{{end}}{{end}}
{{if .Health.Fallbacks}}<span class="tl-badge" title="artifacts parsed by the fallback parser">{{.Health.Fallbacks}} fallbacks</span>{{end}}
<div class="row-meta">
{{with .Mirror}}{{if .Enabled}}<a href="{{.URL}}" title="{{.URL}}">{{hostOf .URL}}</a> · every {{dur .Every}} · pulled {{if .LastAt}}{{ago .LastAt}}{{else}}never{{end}} · {{else}}<a href="{{.DetachedFrom}}">{{hostOf .DetachedFrom}}</a> · {{end}}{{end}}{{thousands .Checkins}} check-ins · indexed {{if .Health.LastOK}}{{ago .Health.LastOK}} <span class="n">({{printf "%.2f" .Health.RoundSeconds}}s)</span>{{else}}never{{end}} · <code>{{printf "%.10s" .Code}}</code>
</div>
{{if .Health.LastErr}}<div class="row-err" title="{{.Health.LastErr}}">ingest: {{.Health.LastErr}}</div>{{end}}
{{with .Mirror}}{{if and .Enabled .LastErr}}<div class="row-err" title="{{.LastErr}}">pull: {{.LastErr}}</div>{{end}}{{end}}
{{- with .Mirror}}{{if .Bridged}}{{with .ChatBridge}}<div class="row-meta" data-hook="chatbridge" data-state="{{.State}}">chat bridge: {{.State}} &middot; <a href="{{.URL}}">{{hostOf .URL}}</a> as <code>{{.User}}</code>{{if .At}} &middot; last message {{ago .At}}{{end}}</div>
{{if .LastErr}}<div class="row-err" title="{{.LastErr}}">chat bridge: {{.LastErr}}</div>{{end}}{{end}}{{end}}{{end}}
</div>
<div class="row-acts">
<form method="post" action="/fleet/sync"><input type="hidden" name="repo" value="{{.Name}}"><button type="submit">sync</button></form>
{{with .Mirror}}{{if .Enabled}}<form method="post" action="/fleet/mirror/run"><input type="hidden" name="repo" value="{{.Repo}}"><button type="submit">pull</button></form>
{{- /* A native popover, like the account menu: the browser owns
       light-dismiss, Esc and the top layer, and the items share the
       .menu rules so they size the same. Anchored to its own button;
       the anchor name is the row's index, since store names can hold
       characters a CSS ident cannot. */ -}}
<button type="button" class="kebab-btn" popovertarget="km{{$.Idx}}" style="anchor-name: --km{{$.Idx}}" aria-label="more actions for {{.Repo}}">&#8943;</button>
<div id="km{{$.Idx}}" popover class="menu km" style="position-anchor: --km{{$.Idx}}">
<a href="/fleet?edit={{.Repo}}#mirror-form">edit mirror</a>
<form method="post" action="/fleet/mirror/writes"><input type="hidden" name="repo" value="{{.Repo}}"><input type="hidden" name="accept" value="{{if .AcceptWrites}}false{{else}}true{{end}}"><button type="submit">{{if .AcceptWrites}}refuse local writes{{else}}allow local writes{{end}}</button></form>
<a href="/fleet?detach={{.Repo}}">detach&hellip;</a>
</div>
{{else}}<a class="btn" href="/fleet?reattach={{.Repo}}">re-attach&hellip;</a>{{end}}{{end}}
</div>
</li>{{end}}
{{define "content"}}
{{- /* The layout already renders the page title as its h1; a second
       heading saying the same word twice is what "fleet Fleet" was. */ -}}
{{if .SyncResults}}<div class="status"><p><strong>Sync run.</strong></p>
<ul>{{range .SyncResults}}<li><code>{{.Repo}}</code> — {{if .Err}}<strong>failed:</strong> {{.Err}}{{else}}{{.Artifacts}} artifacts{{end}}</li>{{end}}</ul></div>{{end}}
{{- /* One nav for the whole fleet family. /fleet used to answer three
       questions in one scroll — stores, then mirrors, then errors — so
       it answered whichever one you were not asking first. Two of those
       are panels of THIS page and morph in place; the other two are
       pages that already existed with more to say than a panel could
       hold, so they are navigations. An earlier cut made "Exceptions" a
       tab showing a summary table beside a richer page of the same
       name, which is the failure this shape exists to avoid: one label,
       one destination, and the best version of it. */ -}}
<div class="t-head">
<h1>Fleet</h1>
{{template "fleet-nav" .}}
</div>
<div id="fleet-panel">{{template "fleet-panel" .}}</div>
{{end}}

{{define "fleet-panel"}}
{{if eq .FleetTab "mirrors"}}
{{template "fleet-mirrors" .}}

{{else}}
<div class="fleet-head">
<p class="fleet-sum">{{len .FleetRows}} {{plural (len .FleetRows) "store" "stores"}}{{with .MirrorCounts}} · {{index . "all"}} {{plural (index . "all") "mirror" "mirrors"}}{{end}}{{if $.FleetProblems}} · <strong class="ci-fail-text">{{$.FleetProblems}} {{plural $.FleetProblems "problem" "problems"}}</strong>{{else}} · all healthy{{end}}{{if .ErrorTotal}} · <span class="tl-badge ci-fail">{{.ErrorTotal}} server {{plural .ErrorTotal "error" "errors"}}</span>{{end}}
{{- /* The door. /fleet answers "are my repositories healthy"; /fleet/ops
       answers "is the forge healthy", and the question continues here.
       It was reachable only by typing the URL — a page with no inbound
       link is a page that does not exist, which is the second time
       that has shipped. */ -}}
 · <a href="/fleet/ops">operations &rarr;</a></p>
<div class="fleet-bulk"><form method="post" action="/fleet/sync"><button type="submit">Sync all</button></form>
{{if .Mirrors}}<form method="post" action="/fleet/mirror/run"><button type="submit">Pull all</button></form>{{end}}</div>
</div>
{{if .MirrorResults}}<div class="status"><p><strong>Pull run.</strong></p>
<ul>{{range .MirrorResults}}<li><code>{{.Repo}}</code> — {{if .Err}}<strong>failed:</strong> {{.Err}}{{else if .Changed}}new artifacts{{else}}already up to date{{end}}</li>{{end}}</ul></div>{{end}}
{{if .FleetRows}}
{{if .FleetProblems}}<ul class="rows">{{range .FleetRows}}{{if .Problem}}{{template "fleet-row" .}}{{end}}{{end}}</ul>
{{$healthy := 0}}{{range .FleetRows}}{{if not .Problem}}{{$healthy = 1}}{{end}}{{end}}
{{if $healthy}}<details class="rows-fold"><summary>{{len .FleetRows}} stores in all — show the healthy ones</summary>
<ul class="rows">{{range .FleetRows}}{{if not .Problem}}{{template "fleet-row" .}}{{end}}{{end}}</ul></details>{{end}}
{{else}}<ul class="rows">{{range .FleetRows}}{{template "fleet-row" .}}{{end}}</ul>{{end}}
{{else}}<p>Nothing matches.</p>{{end}}
{{end}}
{{end}}

{{define "fleet-mirrors"}}
<h3 id="mirror-form-head">Add or update a mirror</h3>
{{- /* Each control keeps its label above it rather than beside it: at
       "every 3600 seconds" the trailing word wrapped onto its own line
       and the row read as three broken sentences. */ -}}
{{- /* One form adds and edits: the store name is the key, so saving
       a name that exists updates that row. Said on the button, because
       "Add" alone hid that a repair was possible. */ -}}
<form method="post" action="/fleet/mirror" class="addform" id="mirror-form">
<label>store<input name="repo" required{{with .MirrorEdit}} value="{{.Repo}}"{{end}}></label>
<label class="grow">upstream<input name="url" type="url" placeholder="https://fossil-scm.org/home" required{{with .MirrorEdit}} value="{{if .Enabled}}{{.URL}}{{else}}{{.DetachedFrom}}{{end}}"{{end}}></label>
<label>every (seconds)<input name="every" type="number" value="{{with .MirrorEdit}}{{if .Every}}{{.Every}}{{else}}3600{{end}}{{else}}3600{{end}}" min="60"></label>
<button type="submit">{{if .MirrorEdit}}Save mirror{{else}}Add or update mirror{{end}}</button></form>

<h3 id="chatbridge-form-head">Bridge a chat channel to Fossil</h3>
{{- /* RFC 0011 §9. Opt-in, per store, and honest about its edges in
       the note rather than in a doc nobody opens: fossil chat has no
       edits, no mentions, and one chat per server. The password is
       write-only — it is stored and never rendered back, so the field
       is always empty even for a bridge that is already running. */ -}}
<form method="post" action="/fleet/mirror/chatbridge" class="addform" id="chatbridge-form">
<label>store<input name="repo" required{{with .MirrorEdit}} value="{{.Repo}}"{{end}}></label>
<label class="grow">fossil server<input name="url" type="url" placeholder="https://fossil-scm.org/home" required{{with .MirrorEdit}}{{if .Bridged}} value="{{.ChatBridge.URL}}"{{end}}{{end}}></label>
<label>login<input name="user" required{{with .MirrorEdit}}{{if .Bridged}} value="{{.ChatBridge.User}}"{{end}}{{end}}></label>
<label>password<input name="password" type="password" autocomplete="new-password" required></label>
<button type="submit">Save bridge</button></form>
<p class="fleet-note"><small>The login needs fossil&rsquo;s <code>C</code> capability, and the
upstream needs <code>http_authentication_ok</code> set or it refuses HTTP Basic.
Bridged messages arrive as <code>fossil:&lt;user&gt;</code>; quarry&rsquo;s go out prefixed with
the author&rsquo;s name. Fossil messages cannot be edited from quarry, and two Fossil
servers are two chats.</small></p>
{{if .Mirrors}}{{range .Mirrors}}{{if .Bridged}}{{with .ChatBridge}}<form method="post" action="/fleet/mirror/chatbridge" class="confirm" data-hook="chatbridge-detach">
<input type="hidden" name="repo" value="{{.Repo}}"><input type="hidden" name="detach" value="1">
<button type="submit">detach the {{.Repo}} chat bridge</button></form>
{{end}}{{end}}{{end}}{{end}}
{{end}}`

// newRepoPage is the forge's "create a repository" form. Deliberately
// the same three questions every forge asks — name, description, where
// it comes from — and NOT a filesystem path: the server places it.
// mirrorDetachPage is the acknowledgement before a posture change that
// cannot be undone by a click: detaching makes the store a fork. The
// checkbox is required, which is what an acknowledgement is.
var mirrorDetachPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
{{with .MirrorEdit}}
<p class="tl-meta-inline"><a href="/fleet">&larr; fleet</a></p>
<p><strong>{{.Repo}}</strong> tracks <a href="{{.URL}}">{{.URL}}</a>. Detaching makes it a <strong>fork</strong>:</p>
<ul>
<li>quarry becomes the source of truth; scheduled pulls stop.</li>
<li>pushes, tickets, wiki and forum writes are accepted here from now on.</li>
<li>the upstream is kept as provenance — the repository will say "forked from {{hostOf .URL}}".</li>
<li>re-attaching later merges whatever the upstream did in the meantime on top of local history.</li>
</ul>
<form method="post" action="/fleet/mirror/detach" class="confirm">
<input type="hidden" name="repo" value="{{.Repo}}">
<p><label><input type="checkbox" name="ack" value="fork" required> I understand {{.Repo}} becomes a fork of {{hostOf .URL}}</label></p>
<p><button type="submit">Detach {{.Repo}}</button> <a href="/fleet">cancel</a></p>
</form>
{{end}}{{end}}`))

// mirrorReattachPage: one click to resume tracking, with the one thing
// that can go wrong said first. Drift is not measured yet (see the
// divergence ticket); the warning is the honest placeholder.
var mirrorReattachPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
{{with .MirrorEdit}}
<p class="tl-meta-inline"><a href="/fleet">&larr; fleet</a></p>
<p><strong>{{.Repo}}</strong> is a fork of <a href="{{.DetachedFrom}}">{{.DetachedFrom}}</a>. Re-attaching resumes tracking it:</p>
<ul>
<li>scheduled pulls resume every {{dur .Every}}; the next pull merges the upstream's history on top of whatever was committed here since the detach.</li>
<li>local writes return to <strong>refused</strong>; allow them again on the fleet page if this is meant to stay a fork that follows upstream.</li>
<li>if local history has diverged from the upstream, both lines stay in the store as separate branches — nothing is lost, but the timeline will show both.</li>
</ul>
<form method="post" action="/fleet/mirror" class="confirm">
<input type="hidden" name="repo" value="{{.Repo}}">
<input type="hidden" name="url" value="{{.DetachedFrom}}">
<input type="hidden" name="every" value="{{if .Every}}{{.Every}}{{else}}3600{{end}}">
<p><button type="submit">Re-attach {{.Repo}} to {{hostOf .DetachedFrom}}</button> <a href="/fleet">cancel</a></p>
</form>
{{end}}{{end}}`))

var newRepoPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
{{if .Error}}<p class="status"><strong>{{.Error}}</strong></p>{{end}}
<form method="post" action="/new" class="newrepo-form">
<p><label>Name<br><input name="name" required autofocus pattern="[A-Za-z0-9][A-Za-z0-9._-]*"
  title="letters, digits, dot, dash, underscore"></label></p>
<p><label>Description <small class="tl-meta-inline">optional</small><br>
  <input name="description" size="52" maxlength="300"></label></p>
<p><label><input type="checkbox" name="private" value="true"> Private
  <small class="tl-meta-inline">— only accounts with a role on it can see that it exists</small></label></p>
<fieldset><legend>Contents</legend>
<p><label><input type="radio" name="kind" value="create" checked> Start empty</label></p>
<p class="seed"><label><input type="checkbox" name="readme" value="true" checked> Add a README</label>
<label><input type="checkbox" name="ignore" value="true"> Add a .zitignore</label>
<label>License
  <select name="license"><option value="">none</option><option value="mit">MIT</option><option value="bsd-2">BSD 2-Clause</option></select></label></p>
{{- /* The posture is chosen here, once, on purpose. A clone used to
       record a mirror silently; now the form says what each choice
       means for who owns the history afterwards. */ -}}
<p><label><input type="radio" name="kind" value="own"> Import and own</label>
  <small class="tl-meta-inline">— clone once; quarry becomes the source of truth</small></p>
<p><label><input type="radio" name="kind" value="clone"> Mirror</label>
  <small class="tl-meta-inline">— clone and keep tracking the upstream; writes are refused here</small></p>
<p><input name="from" size="52" placeholder="https://fossil-scm.org/home" aria-label="repository URL">
  <label>pull every <input name="every" type="number" value="3600" min="60" size="6" aria-label="pull interval in seconds"> seconds</label></p>
</fieldset>
<p><button type="submit">Create repository</button></p>
</form>
{{end}}`))

// quickStartPage is what an empty repository shows instead of an empty
// timeline: a repository with no check-ins is not broken, it is waiting,
// and the reader's next move is to push to it.
var quickStartPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
{{if or .RepoDescription .RepoPrivate}}<p class="about">{{if .RepoPrivate}}<span class="tl-badge">private</span> {{end}}{{.RepoDescription}}</p>{{end}}
<p>This repository is empty.</p>
<h3>Push an existing repository</h3>
<pre>zit remote {{.CloneURL}}
zit push</pre>
<h3>Start from scratch</h3>
<pre>zit clone {{.CloneURL}} {{.Repo}}
cd {{.Repo}}
echo "# {{.Repo}}" &gt; README.md
zit add README.md
zit commit -m "first check-in"
zit push</pre>
{{end}}`))

// settingsPage is the repository's own admin screen. Description and
// visibility for now; the destructive actions belong here too when they
// exist, kept visually apart from the settings that are reversible.
// settingsSource is the settings page, a constant so a test can read
// what it says without a session and a fleet to render it.
const settingsSource = `{{define "repo-settings"}}
{{- /* The save's own word, beside the control that did the saving —
       not at the top of a page the reader has scrolled away from. */ -}}
{{- /* Announced, not drawn: the visible confirmation is on the button
       itself, which cannot be read by a screen reader as a change. */ -}}
{{if eq .SavedPanel "about"}}<p class="sr-only" role="status">Saved.</p>{{end}}
{{if .PanelError}}<p class="status err" role="alert"><strong>{{.PanelError}}</strong></p>{{end}}
<form method="post" action="/r/{{.Repo}}/settings" data-on:submit__prevent="@post(evt.target.action, {contentType: 'form'})">
<p><label>Description<br>
  <input name="description" size="52" maxlength="300" value="{{.RepoDescription}}"></label></p>
<p><label>Homepage <small class="tl-meta-inline">— shown on the About panel; http(s) only</small><br>
  <input name="homepage" type="url" size="52" maxlength="300" placeholder="https://" value="{{.RepoHomepage}}"></label></p>
<p><label>Topics <small class="tl-meta-inline">— space-separated, at most 20</small><br>
  <input name="topics" size="52" maxlength="600" value="{{.RepoTopics}}"></label></p>
<p><button type="submit" class="btn-swap{{if eq .SavedPanel "about"}} did-save{{end}}"><span class="sw-a">Save</span><span class="sw-b">Saved &check;</span></button></p>
</form>
{{end}}
{{define "content"}}

{{if .Error}}<p class="status"><strong>{{.Error}}</strong></p>{{end}}
{{- /* RFC 0008 §IA: the first question is who can see this. The three
       presets are the two category strings; Custom is whatever else
       the strings say, decoded, with the letters one section down. */ -}}
{{with .Visibility}}<h3 id="visibility">Who can see this</h3>
{{if .Refused}}<p class="status"><strong>{{.Refused}}</strong></p>{{end}}
<form method="post" action="/r/{{$.Repo}}/settings/visibility" class="vis-form">
{{range .Options}}<label><input type="radio" name="visibility" value="{{.Name}}"{{if eq .Name $.Visibility.Current}} checked{{end}}> <strong>{{.Name}}</strong> <small class="tl-meta-inline">{{.Blurb}}</small></label>
{{end}}{{if eq .Current "Custom"}}<label><input type="radio" name="visibility" value="Custom" checked> <strong>Custom</strong>
<small class="tl-meta-inline">visitors can {{range $i, $s := .NobodyCan}}{{if $i}}, {{end}}{{$s}}{{else}}do nothing{{end}}; anyone signed in can {{range $i, $s := .AnonCan}}{{if $i}}, {{end}}{{$s}}{{else}}do nothing{{end}} — <a href="#access">the strings</a></small></label>
{{end}}<p><button type="submit" class="btn-swap{{if eq $.SavedPanel "visibility"}} did-save{{end}}"><span class="sw-a">Save visibility</span><span class="sw-b">Saved &check;</span></button>
{{if $.IsAdmin}}<small class="tl-meta-inline">New repositories start as <strong>{{.Fleet}}</strong> · <a href="/fleet/settings">change</a></small>{{end}}</p>
</form>{{end}}
{{- /* RFC 0008. People first, in sentences: a role, the chips where a
       person differs from it, and what they can do here. The letters
       themselves live one section down, for the categories, and on
       the person's own page under a disclosure. */ -}}
{{if .Roster}}<h3 id="people">People</h3>
<p class="tl-meta-inline">Who can do what here. A role is a named set of abilities;
a chip after it is where someone differs. Anyone signed in also holds what the
categories below grant.</p>
{{if .Roster.Rows}}<ul class="roster">{{range .Roster.Rows}}<li>
<div class="roster-head">{{identicon .Name}} <a href="/r/{{$.Repo}}/people/{{pathesc .Name}}"><strong>{{.Name}}</strong></a>
<span class="chip role">{{.Role}}</span>{{range .Plus}}<span class="chip plus">+ {{.}}</span>{{end}}{{range .Minus}}<span class="chip minus">&minus; {{.}}</span>{{end}}{{range .Owns}}<span class="chip owns">owns {{.}}</span>{{end}}</div>
<p class="roster-can">{{.Sentence}}</p></li>{{end}}</ul>{{else}}<p class="tl-meta-inline">No one holds a role here yet.</p>{{end}}
<form method="post" action="/r/{{.Repo}}/people" class="roster-add">
<label>Add <input name="name" size="14" maxlength="64" placeholder="login" required aria-label="login"></label> as
{{range .Roster.Presets}}<label><input type="radio" name="role" value="{{.Name}}"{{if eq .Name "Developer"}} checked{{end}}> {{.Name}}</label>{{end}}
<button type="submit">Add</button></form>{{end}}
{{- /* RFC 0007. Forge policy, said as forge policy: not a capability,
       not fossil's, and it leaves no trace in the repository. The cost
       is stated where the rule is set, because both things it changes
       are surprising to someone who knows fossil. */ -}}
{{if .Protect}}<h3 id="protected">Protected branches</h3>
<p class="tl-meta-inline">A check-in joins a protected branch only by an owner's hand —
whether that hand is an accept on a landing, a <code>zit landing accept</code> on a
clone followed by a push, or a stock fossil client pushing a merge. A branch is a
name or a glob (<code>release-*</code>); owners are account logins. Every matching
rule applies. Blank the owners to remove a rule.</p>
<p class="tl-meta-inline">This is policy of this forge, stored outside the repository:
a clone is byte-identical to an unprotected one, and the same repository hosted
elsewhere has no protection. On this forge <code>i</code> means less than it means in
fossil, and a stock client can be refused a push its capability string says it may
make.</p>
<form method="post" action="/r/{{.Repo}}/settings/protect">
<div class="tablewrap"><table class="caps-table"><tbody>
{{range $i, $r := .Protect.Rules}}<tr>
<td><input name="branch-{{$i}}" size="18" maxlength="64" value="{{$r.Branch}}" aria-label="branch"></td>
<td><input name="owners-{{$i}}" size="28" maxlength="600" value="{{$r.Owners}}" aria-label="owners of {{$r.Branch}}"></td>
<td><input name="checks-{{$i}}" size="24" maxlength="600" value="{{$r.Checks}}" placeholder="required checks" aria-label="required checks on {{$r.Branch}}"></td>
<td><label class="tl-meta-inline"><input type="checkbox" name="premerge-{{$i}}" value="1"{{if $r.Premerge}} checked{{end}}> premerge</label></td>
</tr>{{end}}
<tr>
<td><input name="branch-{{.Protect.Blank}}" size="18" maxlength="64" placeholder="branch or glob" aria-label="new branch"></td>
<td><input name="owners-{{.Protect.Blank}}" size="28" maxlength="600" placeholder="owner logins, space-separated" aria-label="owners of the new branch"></td>
<td><input name="checks-{{.Protect.Blank}}" size="24" maxlength="600" placeholder="required checks" aria-label="required checks on the new branch"></td>
<td><label class="tl-meta-inline"><input type="checkbox" name="premerge-{{.Protect.Blank}}" value="1"> premerge</label></td>
</tr>
</tbody></table></div>
<p><button type="submit" class="btn-swap{{if eq $.SavedPanel "protect"}} did-save{{end}}"><span class="sw-a">Save protected branches</span><span class="sw-b">Saved &check;</span></button></p>
</form>{{end}}
<h3 id="about">Repository</h3>
{{- /* One block, drawn by the page and re-drawn by the save. The panel
       is the patch target, so a Datastar save replaces exactly what it
       changed and the reader keeps their place on a long page; without
       the script the attribute below is inert and the form posts and
       redirects as it always has (0001 Principle 3). */ -}}
<div id="repo-settings">{{template "repo-settings" .}}</div>
<h3 id="integrations">Integrations</h3>
{{if .HasRobot}}<h3 id="robot">Activity robot</h3>
{{- /* The timeline talking in the channel (RFC 0011 §10). Same pattern
       syntax as a webhook, because it is the same question asked of the
       same vocabulary; empty turns it off. */ -}}
<p class="tl-meta-inline">One compact line in this repository's chat channel per matching
event: <code>*</code>, a noun, or an exact kind like <code>landing.accepted</code>.
Leave it empty to turn the robot off. Robot lines never count as unread.</p>
<form class="hook-form" method="post" action="/r/{{.Repo}}/settings/robot">
<label for="robot-events" class="hook-lbl">events</label>
<input id="robot-events" name="events" maxlength="300" value="{{.ChatRobot}}"
  placeholder="checkin landing" list="robot-nouns" aria-label="activity robot events">
<datalist id="robot-nouns"><option value="*">{{range .RobotNouns}}<option value="{{.}}">{{end}}</datalist>
<button type="submit">Save</button>
</form>{{end}}
{{if .HasHooks}}<h3 id="webhooks">Webhooks</h3>
<p class="tl-meta-inline">Signed JSON, POSTed for the events you pick:
<code>*</code>, a noun, or an exact kind like <code>landing.accepted</code>.</p>
<p class="hook-nouns">{{range .EventNouns}}<code>{{.}}</code>{{end}}</p>
{{- /* The question "did my hook fire" is asked standing here, so the
       answer is linked from here rather than given a tab of its own. */ -}}
<p class="tl-meta-inline"><a href="/r/{{.Repo}}/events">See what this repository has raised &rarr;</a></p>
{{if .NewHookSecret}}<p class="status"><strong>Signing secret, shown once:</strong>
<code>{{.NewHookSecret}}</code><br>
<small>Verify <code>X-Quarry-Signature</code> as
<code>sha256=HMAC-SHA256(secret, body)</code>. It cannot be read back.</small></p>{{end}}
<ul class="hook-list">
{{range .Hooks}}<li>
<p class="hook-head"><code class="hook-url">{{.URL}}</code>
  <span class="hook-state{{if not .Active}} off{{end}}">{{if .Active}}active{{else}}paused{{end}}</span></p>
<p class="hook-sub">added {{.Created}}</p>
<form class="hook-form" method="post" action="/r/{{$.Repo}}/settings/hooks">
  <input type="hidden" name="id" value="{{.ID}}">
  <input name="events" maxlength="300" value="{{.Events}}" aria-label="events for {{.URL}}">
  <span class="hook-acts">
  <button type="submit" name="do" value="events">Save</button>
  <button type="submit" name="do" value="{{if .Active}}pause{{else}}resume{{end}}"
    >{{if .Active}}Pause{{else}}Resume{{end}}</button>
  <button type="submit" name="do" value="delete">Delete</button>
  </span>
</form>
</li>{{end}}
</ul>
<form class="hook-add" method="post" action="/r/{{.Repo}}/settings/hooks">
<p><label for="hook-url">Add an endpoint</label>
  <input id="hook-url" name="url" type="url" maxlength="300" placeholder="https://" required></p>
<p class="hook-form"><label for="hook-events" class="hook-lbl">events</label>
  <input id="hook-events" name="events" maxlength="300" placeholder="*" list="hook-nouns">
  <button type="submit" name="do" value="add">Add</button></p>
<datalist id="hook-nouns"><option value="*">{{range .EventNouns}}<option value="{{.}}">{{end}}</datalist>
</form>{{end}}
{{if .Workers}}<h4 id="runners">Runners</h4>
<p class="tl-meta-inline">Workers connected to the CI engine and what they can run.
Workers attach with tokens minted — and revoked — at the engine (dagnats#627).</p>
<div class="tablewrap"><table class="caps-table"><tbody>
{{range .Workers}}<tr><td><code>{{.WorkerID}}</code></td>
<td>{{range $i, $t := .TaskTypes}}{{if $i}}, {{end}}<code>{{$t}}</code>{{end}}</td>
<td class="tl-meta-inline">{{.Transport}}{{with .Hostname}} · {{.}}{{end}}{{with .Version}} · {{.}}{{end}}</td></tr>
{{end}}</tbody></table></div>{{end}}
{{if or .WorkerTokens .WorkerTokensErr .NewWorkerToken}}<h4 id="worker-tokens">Worker tokens</h4>
<p class="tl-meta-inline">Credentials a worker attaches with (dagnats#627), scoped to task-type
prefixes. These are the engine's, fleet-wide — not this repository's. Revoking is immediate.</p>
{{with .WorkerTokensErr}}<p class="tl-meta-inline">{{.}}</p>{{end}}
{{if .NewWorkerToken}}<p class="status"><strong>Worker token, shown once:</strong>
<code>{{.NewWorkerToken}}</code></p>{{end}}
{{if .WorkerTokens}}<ul class="hook-list">{{range .WorkerTokens}}<li>
<form method="post" action="/r/{{$.Repo}}/settings/worker-tokens" class="hook-form">
<code>{{printf "%.12s" .ID}}</code> {{if .Label}}<strong>{{.Label}}</strong>{{end}}
<span class="tl-meta-inline">{{range $i, $p := .TaskTypePrefixes}}{{if $i}}, {{end}}<code>{{$p}}</code>{{end}} · minted {{ago .CreatedAt}}{{if .RevokedAt}} · revoked{{end}}</span>
{{if not .RevokedAt}}<button type="submit" name="revoke" value="{{.ID}}">Revoke</button>{{end}}
</form></li>{{end}}</ul>{{end}}
{{if not .WorkerTokensErr}}<form method="post" action="/r/{{.Repo}}/settings/worker-tokens" class="hook-add">
<p><label>Mint a worker token <input name="label" maxlength="100" placeholder="who runs this worker"></label>
<label>task-type prefixes <input name="prefixes" maxlength="200" placeholder="e2e- build."></label>
<button type="submit">Mint</button></p>
</form>{{end}}{{end}}
{{if .CITagsMode}}<h4 id="ci-tags">CI verdict tags</h4>
<p class="tl-meta-inline">Write <code>ci-pass</code>/<code>ci-fail</code> tag artifacts onto
check-ins, so CI history clones with the repository (RFC 0009). Tags already written stay
either way; turning this on resumes from the next run, with no backfill.</p>
<form method="post" action="/r/{{.Repo}}/settings/ci-tags">
<p><select name="mode" aria-label="verdict tags">
<option value=""{{if eq .CITagsMode "default"}} selected{{end}}>fleet default</option>
<option value="on"{{if eq .CITagsMode "on"}} selected{{end}}>on</option>
<option value="off"{{if eq .CITagsMode "off"}} selected{{end}}>off</option>
</select> <button type="submit">Save</button></p>
</form>{{end}}
{{if .CITokens}}<h4 id="ci-reporters">CI reporters</h4>
<p class="tl-meta-inline">Tokens for CI quarry does not run (RFC 0009): a reporter token
may post check states onto check-ins — <code>POST /api/v1/r/{{.Repo}}/checks</code> —
and nothing else. Revoking is immediate.</p>
{{if .NewReporterToken}}<p class="status"><strong>Reporter token, shown once:</strong>
<code>{{.NewReporterToken}}</code></p>{{end}}
<ul class="hook-list">{{range .CITokens.Tokens}}<li>
<form method="post" action="/r/{{$.Repo}}/settings/ci-tokens" class="hook-form">
<code>{{printf "%.12s" .Hash}}</code> {{if .Label}}<strong>{{.Label}}</strong>{{end}}
<span class="tl-meta-inline">minted {{.Created}}</span>
<button type="submit" name="revoke" value="{{.Hash}}">Revoke</button>
</form></li>{{end}}</ul>
<form method="post" action="/r/{{.Repo}}/settings/ci-tokens" class="hook-add">
<p><label>Mint a reporter token <input name="label" maxlength="100" placeholder="who is reporting"></label>
<button type="submit">Mint</button></p>
</form>{{end}}
<h3>Clone</h3>
<pre>zit clone {{.CloneURL}} {{.Repo}}</pre>
{{if .Caps}}<h3 id="access">Advanced (fossil)</h3>
<details class="adv-fossil"><summary>Capability letters and category strings</summary>
<p class="tl-meta-inline">The presets and roles above compile to these fossil capability
letters (RFC 0004); this is the same access said in fossil's own alphabet. Every account
signed in holds what a category grants: <strong>nobody</strong> every visitor,
<strong>anonymous</strong> any signed-in account, <strong>reader</strong> holders of
<code>u</code>, <strong>developer</strong> holders of <code>v</code>. Blanking nobody and
anonymous takes the repository private — the <a href="#visibility">visibility</a> presets
do this for you.</p>
<form method="post" action="/r/{{.Repo}}/settings/caps">
<div class="tablewrap"><table class="caps-table"><tbody>
{{range .Caps.Categories}}<tr>
<td><code>{{.Name}}</code></td>
<td><input name="cat-{{.Name}}" size="28" maxlength="64" value="{{.Caps}}"
     aria-label="{{.Name}} capabilities"></td>
<td class="tl-meta-inline">{{.Note}}{{if .Decoded}} — can {{.Decoded}}{{else}} — grants nothing{{end}}</td>
</tr>{{end}}
</tbody></table></div>
<p><button type="submit" class="btn-swap{{if eq $.SavedPanel "caps"}} did-save{{end}}"><span class="sw-a">Save categories</span><span class="sw-b">Saved &check;</span></button></p>
</form>
{{with $.Fossil}}<h4 id="fossil-settings">Fossil settings</h4>
{{if .Supported}}<p class="tl-meta-inline">The settings this store applies. A value can also
come from a tracked <code>.fossil-settings/&lt;name&gt;</code> file, which wins and clones with
the repository; those settings are marked <em>versionable</em>.</p>
<form method="post" action="/r/{{$.Repo}}/settings/fossil">
<div class="tablewrap"><table class="caps-table"><tbody>
{{range .Rows}}<tr>
<td><code>{{.Name}}</code>{{if .Versionable}} <small class="tl-meta-inline">versionable</small>{{end}}</td>
<td><input name="set-{{.Name}}" size="28" maxlength="256" value="{{.Value}}" aria-label="{{.Name}}"></td>
</tr>{{end}}
</tbody></table></div>
<p><button type="submit" class="btn-swap{{if eq $.SavedPanel "fossil"}} did-save{{end}}"><span class="sw-a">Save settings</span><span class="sw-b">Saved &check;</span></button></p>
</form>
{{else}}<p class="status">{{.Note}}</p>{{end}}
<h4 id="fossil-config">Configuration areas</h4>
<p class="tl-meta-inline">Import a fossil configuration export (<code>user</code>, <code>shun</code>, …)
&mdash; the file <code>fossil configuration export AREA</code> writes.</p>
{{if $.Fossil.Supported}}<form method="post" action="/r/{{$.Repo}}/settings/config" enctype="multipart/form-data">
<p><input type="file" name="file" required aria-label="configuration file">
<label><input type="checkbox" name="merge" value="1"> merge instead of replace</label></p>
<p><button type="submit">Import</button></p>
</form>{{else}}<p class="status">{{$.Fossil.Note}}</p>{{end}}
{{end}}</details>{{end}}
{{- /* Kept apart, and last. Both actions here are one click from
       something the settings above are not: irreversible. */ -}}
<h3 class="danger-head">Danger zone</h3>
<div class="danger">
<form method="post" action="/r/{{.Repo}}/settings/remove">
<p><strong>Stop serving this repository.</strong> The store on disk and its
index are left alone; registering it again brings it back.</p>
<p><button type="submit">Stop serving</button></p>
</form>
{{if .Deletable}}<form method="post" action="/r/{{.Repo}}/settings/delete">
<p><strong>Delete this repository.</strong> Its store, its index, its grants,
its sync users, its mirror and its webhooks are destroyed. There is no undo.</p>
<p><label>Type <code>{{.Repo}}</code> to confirm<br>
  <input name="confirm" required autocomplete="off"></label></p>
<p><button type="submit">Delete forever</button></p>
</form>{{else}}<p class="tl-meta-inline">This repository's store was not created by quarry,
so it cannot be deleted here — stop serving it and remove the directory yourself.</p>{{end}}
</div>
{{end}}`

var settingsPage = template.Must(template.Must(base.Clone()).Parse(settingsSource))

// Taking a repository private is a wizard, not a switch (RFC 0008
// bulletproofing): the people who reach it only through the
// categories are named, and each can be given a role before the
// strings blank.
var takePrivatePage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
<h1>Take {{.Repo}} private</h1>
{{with .TakePrivate}}
<p>Private means only the people with a role here can see that it exists. These accounts
reach it today through the categories alone and would lose it:</p>
<form method="post" action="/r/{{$.Repo}}/settings/private">
<ul class="roster">{{range .Names}}<li><div class="roster-head">{{identicon .}} <strong>{{.}}</strong>
<select name="role-{{.}}" aria-label="role for {{.}}"><option value="">loses access</option>{{range $.TakePrivate.Presets}}<option value="{{.Name}}">{{.Name}}</option>{{end}}</select></div></li>
{{end}}</ul>
<p><button type="submit" name="confirm" value="1" class="danger">Take private</button>
<a class="tn-new" href="/r/{{$.Repo}}/settings#visibility">keep it as it is &rarr;</a></p>
</form>
{{end}}{{end}}`))

// The fleet default (RFC 0008 §IA): what a new repository starts as.
var fleetSettingsPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
<h1>Fleet settings</h1>
{{if .Saved}}<p class="status">Saved.</p>{{end}}
{{with .Visibility}}<h3 id="visibility">New repositories start as</h3>
<form method="post" action="/fleet/settings" class="vis-form">
{{range .Options}}<label><input type="radio" name="visibility" value="{{.Name}}"{{if eq .Name $.Visibility.Current}} checked{{end}}> <strong>{{.Name}}</strong> <small class="tl-meta-inline">{{.Blurb}}</small></label>
{{end}}<p class="tl-meta-inline">A repository with strings of its own keeps them; this is what one without any gets.</p>
<p><button type="submit" class="btn-swap{{if eq .SavedPanel "fleet"}} did-save{{end}}"><span class="sw-a">Save</span><span class="sw-b">Saved &check;</span></button></p>
</form>{{end}}{{end}}`))

// The per-person editor (RFC 0008): fossil's /setup_uedit in
// sentences. Forms only; script, when it comes, adds the same things
// live and never makes a control possible.
// person-live is the region the compiler owns: the preview sentence,
// the role radios, the ability boxes, the string. The baseline form
// posts and reloads it server-computed; Datastar re-requests the frag
// on every change and morphs this region in place, so the string and
// the checkboxes are two views of one signal and the sentence updates
// as you click. Script never adds a control (RFC 0001, RFC 0008).
const personLiveSource = `{{define "person-live"}}
<div id="person-live"{{if .Live}} data-signals="{}"{{end}}>
<input type="hidden" name="was-role" value="{{if .Exact}}{{.Role}}{{else}}Custom{{end}}">
<input type="hidden" name="was-raw" value="{{.Caps}}">
<input type="hidden" name="was-ab" value="{{.CheckedLetters}}">
{{if .Refused}}<p class="status err">Not saved: {{.Refused}}</p>{{end}}
{{if .Changed}}<p class="status">Saved. {{.Changed}}.</p>{{end}}
{{if .Warn}}<p class="status">{{.Warn}}.</p>{{end}}
<p class="roster-can" id="person-preview"><strong>{{.Preview}}</strong></p>
{{if .Owns}}<p>{{range .Owns}}<span class="chip owns">owns {{.}}</span> {{end}}</p>{{end}}
<fieldset class="roles"><legend>Role</legend>
{{$e := .}}{{range .Presets}}<label><input type="radio" name="role" value="{{.Name}}"{{if and $e.Exact (eq .Name $e.Role)}} checked{{end}}{{$e.On}}> <strong>{{.Name}}</strong> <small>{{.Blurb}}</small></label>
{{end}}<label><input type="radio" name="role" value="Custom"{{if not .Exact}} checked{{end}}{{.On}}> <strong>Custom</strong> <small>{{if .Caps}}nearest {{.Role}}{{range .Plus}}, plus {{.}}{{end}}{{range .Minus}}, minus {{.}}{{end}}{{else}}no role here; the categories still apply{{end}}</small></label>
</fieldset>
<p class="tl-meta-inline">Picking another role replaces the abilities below with that role's.
Ticking or clearing an ability keeps the role and records the difference.</p>
<div class="abilities">{{range .Groups}}<fieldset><legend>{{.Name}}</legend>
{{range .Abilities}}<label{{if .Advanced}} class="adv"{{end}}><input type="checkbox" name="ab" value="{{.Letters}}"{{if .Checked}} checked{{end}}{{$e.On}}> {{.Sentence}}{{if .Category}} <small class="tl-meta-inline">(granted to everyone signed in)</small>{{end}}</label>
{{end}}</fieldset>{{end}}</div>
<details class="raw"{{if .Caps}} open{{end}}><summary>The string</summary>
<p><input id="person-raw" name="raw" size="28" maxlength="64" value="{{.Caps}}" aria-label="capability string"{{.OnRaw}}>
<small class="tl-meta-inline">effective <code>{{.Effective}}</code></small></p>
<p class="tl-meta-inline">Fossil letters (RFC 0004). An edit here wins over the controls above.</p></details>
</div>{{end}}`

var personEditPage = template.Must(template.Must(template.Must(base.Clone()).Parse(personLiveSource)).Parse(`{{define "content"}}
{{with .Editor}}
<h1>{{identicon .Name}} {{.Name}} <small class="tl-meta-inline">on {{.Repo}}</small></h1>
<form method="post" action="/r/{{.Repo}}/people/{{pathesc .Name}}" class="person-form">
{{template "person-live" .}}
<p><button type="submit">Save</button>
{{if .Caps}}<button type="submit" name="revoke" value="1" class="danger">Remove from this repository</button>{{end}}
<a class="tn-new" href="/r/{{.Repo}}/settings#people">back to settings &rarr;</a></p>
</form>
{{end}}{{end}}`))

// praisedPage is where praise is revisited and reversed. It exists apart
// from /people/{user} because that page lists CONTRIBUTORS, derived from
// the DAG, and a praiser need never have authored anything — an account
// that has only ever read would have no page there at all.
var praisedPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
{{- /* h2, not h1: base already emits the page's h1 as the screen-reader
       title when HideH1 is set, and two h1s is two answers to "what is
       this page". */ -}}
<h2 class="p-h">{{if .PraiseIsMine}}Repositories you praise{{else}}Praised by {{.PraiseOwner}}{{end}}</h2>
{{if .PraisedRepos}}
<ul class="praised-list">
{{range .PraisedRepos}}<li>
<a class="p-name" href="/r/{{.Repo}}">{{.Repo}}</a>
<span class="p-desc">{{.Description}}</span>
{{if $.CanPraise}}<form class="praise-form" method="post" action="/r/{{.Repo}}/praise">
  <input type="hidden" name="on" value="{{if .Praised}}0{{else}}1{{end}}">
  <input type="hidden" name="back" value="/praised{{if not $.PraiseIsMine}}?user={{$.PraiseOwner}}{{end}}">
  <button type="submit" class="praise-btn{{if .Praised}} on{{end}}"
    aria-pressed="{{if .Praised}}true{{else}}false{{end}}"
    >{{if .Praised}}praised{{else}}praise{{end}}</button>
</form>{{end}}
</li>{{end}}
</ul>
{{else}}<p class="praised-empty">{{if .PraiseIsMine}}You have not praised anything yet.
Praise sits beside the clone count on a repository's page.{{else}}Nothing you can see.{{end}}</p>{{end}}
{{end}}`))

// eventsPage answers "did my hooks fire". It shows what the repository
// RAISED, which is a different question from whether any delivery
// arrived — that one needs delivery records, which this deliberately is
// not pretending to be.
var eventsPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
<h2 class="p-h">Events</h2>
<p class="tl-meta-inline">What this repository has raised, newest first. Webhook
subscriptions select from these by name; a workflow subscribes to the same
subjects. Kept for {{.EventWindow}} — this is a live tail, not history.</p>
{{if .Events}}
<ul class="ev-list">
{{range .Events}}<li>
<code class="ev-kind">{{.Kind}}</code>
<span class="ev-sum">{{.Summary}}</span>
<span class="ev-meta">{{if .Actor}}{{.Actor}} · {{end}}{{agoTime .At}}</span>
</li>{{end}}
</ul>
{{else}}<p class="praised-empty">Nothing raised in the last {{.EventWindow}}.</p>{{end}}
{{end}}`))

var notFoundPage = template.Must(template.Must(base.Clone()).Parse(
	`{{define "content"}}
{{- /* A 404 keeps its footing: inside a known repository the repobar
       stays (set by fail), so the reader is one click from every
       surface that DOES exist rather than dumped back at the door.
       The path is echoed so a typo is findable by eye. */ -}}
<p class="status"><strong>404</strong> — nothing lives at <code>{{.MissPath}}</code>.</p>
{{if .Repo}}<p>The repository exists; this page within it does not. The tabs above are all real.</p>
{{else}}<p>Start from the <a href="/">repository list</a>.</p>{{end}}
{{end}}`))

var busyPage = template.Must(template.Must(base.Clone()).Parse(
	`{{define "content"}}<p>The server is at capacity for this kind of request. Nothing is wrong —
	this is the limit doing its job — and the same request should succeed shortly.</p>{{end}}`))

var errorPage = template.Must(template.Must(base.Clone()).Parse(
	`{{define "content"}}<p>Something went wrong serving this page. The details are in the server log.</p>{{end}}`))

var forbiddenPage = template.Must(template.Must(base.Clone()).Parse(
	`{{define "content"}}<p>{{.Error}}</p>{{end}}`))

// hitMetaSource is the line that tells two results apart, defined once
// and used by both search pages. "use after free" on tk returned three
// rows identical on screen — same repository, same title, same snippet
// — because the same fix landed on three branches and the row carried
// nothing that differed; the reader had to open all three.
//
// A doc or a file is already identified by its path, so those rows
// render nothing here rather than a date nobody asked for.
const hitMetaSource = `{{define "hit-meta"}}{{if or .Short .Date .Status}}<div class="hit-meta">
{{- with .Short}}<code>{{.}}</code>{{end}}
{{- with .Status}} <span class="tl-badge">{{.}}</span>{{end}}
{{- with .Date}} {{ago .}}{{end}}
{{- with .User}} · {{identicon .}} {{.}}{{end}}
{{- with .Branch}} · <span class="hit-branch">{{.}}</span>{{end}}
</div>{{end}}{{end}}`

var globalSearchPage = template.Must(template.Must(base.Clone()).Parse(hitMetaSource + `{{define "content"}}
{{- /* No second box: the header carries one on every page including
       this one, and two inputs for the same query invite a reader to
       wonder which is authoritative. */ -}}
{{if .Query}}<nav class="scopes">{{range scopes}}
<a href="/search?q={{$.Query}}{{if .Kind}}&amp;kind={{.Kind}}{{end}}"{{if eq .Kind $.SearchKind}} class="here"{{end}}>{{.Label}}</a>
{{end}}</nav>
<p class="tl-meta-inline">{{len .Results}} result{{if ne (len .Results) 1}}s{{end}} across {{.Searched}} repositor{{if eq .Searched 1}}y{{else}}ies{{end}}</p>
{{- /* One repository can fill a page of results honestly — fossil really
       does have the most to say about memory leaks. The facet is how a
       reader gets to the others without retyping the query. */ -}}
{{if .ByRepo}}<nav class="scopes facets">
<a href="/search?q={{.Query}}{{if .SearchKind}}&amp;kind={{.SearchKind}}{{end}}"{{if not .RepoFilter}} class="here"{{end}}>all repositories</a>
{{range .ByRepo}}<a href="/search?q={{$.Query}}{{if $.SearchKind}}&amp;kind={{$.SearchKind}}{{end}}&amp;repo={{.Repo}}"{{if eq .Repo $.RepoFilter}} class="here"{{end}}>{{.Repo}} <span class="n">{{.Count}}</span></a>
{{end}}</nav>{{end}}{{end}}
{{- /* The fleet listing needs the distinguishing line at least as
       badly as the per-repo one: it is where the three identical tk
       rows were found. The per-repo page carries the same block —
       whichever of these two templates gains a field and the other
       does not is a difference nobody sees until they compare. */ -}}
{{if .Results}}<ul class="hits">{{range .Results}}
<li><a class="hit-repo" href="/r/{{.Repo}}">{{.Repo}}</a>
<a href="{{.URL}}">{{.Label}}</a> <small class="tl-meta-inline">{{.Kind}}</small>
{{template "hit-meta" .}}
<div class="snip">{{.Snippet}}</div></li>
{{end}}</ul>{{else if .Query}}<p>Nothing in {{.SearchScope}} matches “{{.Query}}”.</p>{{end}}
{{end}}`))

var searchPage = template.Must(template.Must(base.Clone()).Parse(hitMetaSource + `{{define "content"}}
{{- /* The scope the header chose is shown and changeable here. A reader
       who searched from the tickets page and found nothing needs to widen
       without retyping, which is one click rather than a new query. */ -}}
{{if .Query}}<nav class="scopes">{{range scopes}}
<a href="/r/{{$.Repo}}/search?q={{$.Query}}{{if .Kind}}&amp;kind={{.Kind}}{{end}}"{{if eq .Kind $.SearchKind}} class="here"{{end}}>{{.Label}}</a>
{{end}}</nav>{{end}}
{{if .Results}}<ul class="hits">{{range .Results}}
<li><a href="{{.URL}}">{{.Label}}</a> <small class="tl-meta-inline">{{.Kind}}</small>
{{template "hit-meta" .}}
<div class="snip">{{.Snippet}}</div></li>
{{end}}</ul>{{else if .Query}}<p>Nothing in {{.SearchScope}} matches “{{.Query}}”.</p>{{end}}
{{end}}`))

// diffBodySource is the structured diff shared by the check-in page
// (fossil's /info shape: metadata, then the change inline) and the
// standalone /diff deep link. One template, two doors.
const diffBodySource = `{{define "dtoks"}}{{range .Tokens}}{{if or .Class .Mark}}<span class="{{if .Class}}{{.Class}}{{end}}{{if and .Class .Mark}} {{end}}{{if .Mark}}dm{{end}}">{{.Text}}</span>{{else}}{{.Text}}{{end}}{{end}}{{end}}
{{define "diff-body"}}<div id="diffbody">
{{if .Diff.Note}}<p><em>{{.Diff.Note}}</em></p>{{end}}
{{if .Diff.Structured}}
{{if .Diff.Offset}}<p class="diffcount">{{if .Diff.File}}<code>{{.Diff.File}}</code>{{else}}{{len .Diff.Structured}} {{plural (len .Diff.Structured) "file" "files"}} changed{{end}}{{with diffstat .Diff.Structured}} {{.}}{{end}} <small>— continued</small></p>
{{else}}<p class="diffcount">{{len .Diff.Structured}} {{plural (len .Diff.Structured) "file" "files"}} changed{{with diffstat .Diff.Structured}} {{.}}{{end}}{{if .Diff.OmittedLines}} <small hidden data-attr:hidden="false">— a large change; the rest loads as you scroll</small>{{end}}</p>
<ul class="difffiles">{{range .Diff.Structured}}
<li><a href="#f-{{pathesc .Path}}"><svg class="ic" aria-hidden="true"><use href="#i-file"/></svg> {{.Path}}</a><span class="tl-badge">{{.Change}}</span></li>{{end}}</ul>
{{end}}
{{- /* Two links, enhanced in place. Without script they are links and
       the page reloads; with it, syncurl swaps the body and corrects
       the address bar. The reasoning for that handler lives once, on
       syncURLAttr. */ -}}
<nav class="toggle" aria-label="diff view">
<a href="{{.Diff.ToggleHref false}}"{{if not .DiffSplit}} class="here" aria-current="true"{{end}}
  {{syncurl (.Diff.ToggleFrag false)}}>unified</a>
<a href="{{.Diff.ToggleHref true}}"{{if .DiffSplit}} class="here" aria-current="true"{{end}}
  {{syncurl (.Diff.ToggleFrag true)}}>side-by-side</a>
</nav>
{{if .Diff.To}}<a class="ci-patch" href="/r/{{.Repo}}/checkin/{{.Diff.To}}/patch{{if .Diff.Branch}}?branch=1{{end}}"><svg class="ic" aria-hidden="true"><use href="#i-download"/></svg> patch</a>{{end}}
{{if .Diff.Offset}}{{template "diff-pager" .}}{{else if .Diff.OmittedLines}}<noscript>{{template "diff-pager" .}}</noscript>{{end}}
{{template "diff-more" .}}
{{else if .Diff.Files}}<ul class="difffiles">{{range .Diff.Files}}
<li><a href="/r/{{$.Repo}}/checkin/{{$.Diff.To}}/diff?file={{.Name}}"><svg class="ic" aria-hidden="true"><use href="#i-file"/></svg> {{.Name}}</a><span class="tl-badge">{{.Status}}</span></li>{{end}}</ul>{{end}}
</div>
{{end}}
{{- /* One window of file sections, then the sentinel that fetches the
       next window when it scrolls into view. The sentinel is ALSO a
       link: with scripting off the same URL renders the next window as
       a page, so the whole diff stays reachable either way. The
       fragment response replaces #diff-more with this very template,
       which is how the chain continues. */ -}}
{{define "diff-more"}}{{range .Diff.Structured}}{{if .Hunks}}
<section class="filediff{{if $.DiffSplit}} wide{{end}}"{{if .Before}}{{else}} id="f-{{pathesc .Path}}"{{end}}>
<h3 class="filediff-head"><span class="tl-badge">{{.Change}}</span> <code>{{.Path}}</code>{{if .PrevPath}} <small>(was {{.PrevPath}})</small>{{end}}{{if .Before}} <small>(continued)</small>{{end}}{{with filestat .}} {{.}}{{end}}</h3>
{{range .Hunks}}
<div class="hunkhead"><span class="hunkfold">&#8943;</span>{{if .Header}} {{.Header}}{{end}}</div>
{{if $.DiffSplit}}
<div class="tw"><table class="dtab chroma split"><tbody>
{{range splitrows .}}<tr>
{{if .Left}}<td class="dnum">{{.Left.OldNum}}</td><td class="dcell d-{{.Left.Kind}}">{{template "dtoks" .Left}}</td>
{{else}}<td class="dnum"></td><td class="dcell d-void"></td>{{end}}
{{if .Right}}<td class="dnum">{{.Right.NewNum}}</td><td class="dcell d-{{.Right.Kind}}">{{template "dtoks" .Right}}</td>
{{else}}<td class="dnum"></td><td class="dcell d-void"></td>{{end}}
</tr>
{{end}}</tbody></table></div>
{{else}}
<div class="tw"><table class="dtab chroma"><tbody>
{{range .Lines}}<tr class="d-{{.Kind}}">
<td class="dnum">{{if .OldNum}}{{.OldNum}}{{end}}</td>
<td class="dnum">{{if .NewNum}}{{.NewNum}}{{end}}</td>
<td class="dmark"></td>
<td class="dcode">{{template "dtoks" .}}</td>
</tr>
{{end}}</tbody></table></div>
{{end}}
{{end}}
</section>
{{end}}{{end}}
{{with .Diff.More true}}<div id="diff-more" class="diffmore" data-on-intersect__once="@get('{{.}}')"><noscript>{{template "diff-pager" $}}</noscript><span aria-hidden="true" hidden data-attr:hidden="false">&#8943;</span></div>{{else}}{{if .Diff.Offset}}<noscript>{{template "diff-pager" .}}</noscript>{{end}}{{end}}
{{end}}
{{- /* The pager: where this window sits in the whole diff, and the
       way to the one before, the one after, and the start. The paged
       reading (no script) lives on it; with script it only appears on
       a window reached by link, as a bearing. Disabled ends stay in
       the row so the buttons never shift. */ -}}
{{define "diff-pager"}}<nav class="pager" aria-label="diff pages">
<a class="pager-btn" href="{{.Diff.Start}}"{{if not .Diff.Offset}} aria-disabled="true"{{end}}>&laquo; Start</a>
{{with .Diff.Back}}<a class="pager-btn" href="{{.}}">&lsaquo; Previous</a>{{else}}<span class="pager-btn" aria-disabled="true">&lsaquo; Previous</span>{{end}}
<span class="pager-where">Lines <b>{{thousands (add .Diff.Offset 1)}}&ndash;{{thousands .Diff.NextOffset}}</b> of {{thousands .Diff.TotalLines}}</span>
{{with .Diff.More false}}<a class="pager-btn" href="{{.}}">Next &rsaquo;</a>{{else}}<span class="pager-btn" aria-disabled="true">Next &rsaquo;</span>{{end}}
{{with .Diff.Last}}<a class="pager-btn" href="{{.}}">Last &raquo;</a>{{else}}<span class="pager-btn" aria-disabled="true">Last &raquo;</span>{{end}}
</nav>{{end}}`

var diffPage = template.Must(template.Must(base.Clone()).Parse(diffBodySource + `{{define "content"}}
{{if .DiffBranch}}<p class="dv-mode">the whole of branch <a href="/r/{{.Repo}}/timeline?branch={{.DiffBranch}}"><b>{{.DiffBranch}}</b></a>, from where it forked to its tip</p>{{end}}
<p><small>{{if .Diff.From}}<a href="/r/{{.Repo}}/checkin/{{.Diff.From}}"><code>{{printf "%.12s" .Diff.From}}</code></a> →{{else}}root check-in →{{end}}
<a href="/r/{{.Repo}}/checkin/{{.Diff.To}}"><code>{{printf "%.12s" .Diff.To}}</code></a></small></p>
{{template "diff-body" .}}
{{end}}`))

var wikiPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
{{- /* Three columns: the pages beside this one, the page, and where you
       are inside it. A wiki page used to be an island — no siblings, no
       contents, no way back but the browser button — and fossil's own
       Cookbook answered that by hand-writing an index at the top, which
       is the reader's need stated in the only place they could state
       it. Both rails are hidden on narrow screens; every link in them
       exists elsewhere on the page or one level up. */ -}}
<div class="w-doc">
{{if .WikiPages}}<aside class="w-rail">
<p class="w-railhead">pages</p>
<ul>{{range .WikiPages}}<li><a href="/r/{{$.Repo}}/wiki/{{pathesc .Title}}"{{if eq .Title $.Wiki.Title}} class="here"{{end}}>{{.Title}}</a></li>{{end}}
{{if .Truncated}}<li><a class="w-railall" href="/r/{{.Repo}}/docs">all documents &rarr;</a></li>{{end}}</ul>
</aside>{{end}}
<div class="w-main">
<p class="w-crumb"><a href="/r/{{.Repo}}/docs">docs</a> / <span>{{.Wiki.Title}}</span></p>
{{if .WikiRev}}<p class="status"><em>Historical revision <code>{{printf "%.12s" .Wiki.Hash}}</code> ({{.Wiki.Date}}) —
<a href="/r/{{.Repo}}/wiki/{{pathesc .Wiki.Title}}">view latest</a></em></p>{{end}}
{{- /* Fossil deletes a page by writing an empty edit. The tombstone
       says so rather than presenting a blank page as content, and the
       history stays one click away — the record survives deletion. */ -}}
{{if .Wiki.Deleted}}<p class="status"><em>This page was deleted {{ago .Wiki.Date}} by {{.Wiki.User}}.
Its <a href="/r/{{.Repo}}/wiki/{{pathesc .Wiki.Title}}/history">history</a> remains readable.</em></p>
{{else}}
{{- /* The byline leads rather than trails: on a 26,000-pixel page a
       footer saying how stale the text is arrives twenty-six screens
       after the reader needed it. */ -}}
<p class="w-by">edited {{ago .Wiki.Date}} by {{who .Repo .Wiki.User}} ·
{{if .Posture.ReadOnly}}<a href="{{.Posture.Upstream "wikiedit"}}?name={{.Wiki.Title}}">edit on {{.Posture.Host}} &rarr;</a>{{else}}<a href="/r/{{.Repo}}/wiki/{{pathesc .Wiki.Title}}/edit">edit</a>{{end}} ·
<a href="/r/{{.Repo}}/wiki/{{pathesc .Wiki.Title}}/history">history</a></p>
<article>{{.WikiHTML}}</article>{{end}}
</div>
{{if .WikiTOC}}<nav class="w-toc" aria-label="On this page">
<p class="w-railhead">on this page</p>
<ul>{{range .WikiTOC}}<li><a href="#{{.ID}}"{{if .Sub}} class="sub"{{end}}>{{.Text}}</a></li>{{end}}</ul>
</nav>{{end}}
</div>
{{end}}`))

var docPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
{{- /* A repository's own documentation lives in its TREE — fossil keeps
       every page of www/ there, not as wiki artifacts — so without this
       route the docs of every fossil repository quarry serves could only
       be read as source. Same reading furniture as a wiki page, because
       it is the same job: a long document someone has to get through. */ -}}
<div class="w-doc">
<div class="w-main">
<p class="w-crumb"><a href="/r/{{.Repo}}/docs">docs</a> / <span>{{.Doc.Path}}</span></p>
<p class="w-by">at <a href="/r/{{.Repo}}/checkin/{{.Doc.Hash}}"><code>{{printf "%.12s" .Doc.Hash}}</code></a> ·
{{.Doc.Size}} bytes ·
<a href="/r/{{.Repo}}/file/{{.Doc.Hash}}/{{.Doc.Path}}">source</a></p>
<article>{{.WikiHTML}}</article>
</div>
{{if .WikiTOC}}<nav class="w-toc" aria-label="On this page">
<p class="w-railhead">on this page</p>
<ul>{{range .WikiTOC}}<li><a href="#{{.ID}}"{{if .Sub}} class="sub"{{end}}>{{.Text}}</a></li>{{end}}</ul>
</nav>{{end}}
</div>
{{end}}`))

var wikiHistoryPage = template.Must(template.Must(base.Clone()).Parse(`{{define "content"}}
<p><a href="/r/{{.Repo}}/wiki/{{pathesc .Wiki.Title}}">← {{.Wiki.Title}}</a></p>
<ul>{{$top := true}}{{range .WikiRevs}}
<li>{{ago .Date}} <a href="/r/{{$.Repo}}/wiki/{{pathesc $.Wiki.Title}}{{if not $top}}?rev={{printf "%.12s" .Hash}}{{end}}"><code>{{printf "%.12s" .Hash}}</code></a>
by {{who $.Repo .User}}{{if $top}} <small>(current)</small>{{end}}{{$top = false}}</li>{{end}}
</ul>
{{end}}`))

var timelinePage = template.Must(template.Must(base.Clone()).Parse(timelineSource))

const timelineSource = `{{define "content"}}
{{template "artifact-note" .}}
{{- /* Three selects, one row, whatever the content: a select shows
       its choice, truncates its own text natively, and submits on
       change (the button exists only where script does not). Pills
       spent three phone rows saying the same thing. */ -}}
{{- /* The live signal lives on the CONTROLS, not on the listing: the
       effect re-requests the fragment with the form content type, which
       serializes THIS form — so a refresh always carries whatever the
       filter says at that moment rather than whatever it said when a
       stream was opened. The && guard keeps the effect's initial run
       (rev still 0) from re-fetching the page the server just drew. */ -}}
<form class="tl-controls" action="/r/{{.Repo}}/timeline" method="get"
{{- if .Live}} data-signals="{tlRev: 0}" data-init="@get('/r/{{.Repo}}/timeline.rev')" data-effect="$tlRev &amp;&amp; @get('/r/{{.Repo}}/timeline.frag', {contentType: 'form'})"{{end}}>
{{if .Tag}}<input type="hidden" name="tag" value="{{.Tag}}">{{end}}
{{if .User}}<input type="hidden" name="user" value="{{.User}}">{{end}}
<select name="branch" aria-label="branch" onchange="this.form.submit()">
<option value="">all branches</option>
{{range .Branches}}<option value="{{.Name}}"{{if eq .Name $.Branch}} selected{{end}}>{{.Name}}</option>{{end}}
</select>
<select name="y" aria-label="show" onchange="this.form.submit()">
<option value="ci"{{if eq .Y "ci"}} selected{{end}}>check-ins</option>
<option value="all"{{if eq .Y "all"}} selected{{end}}>everything</option>
<option value="w"{{if eq .Y "w"}} selected{{end}}>wiki</option>
<option value="t"{{if eq .Y "t"}} selected{{end}}>tickets</option>
<option value="e"{{if eq .Y "e"}} selected{{end}}>notes</option>
<option value="f"{{if eq .Y "f"}} selected{{end}}>forum</option>
<option value="l"{{if eq .Y "l"}} selected{{end}}>landings</option>
</select>
<select name="n" aria-label="how many" onchange="this.form.submit()">
{{range .LimitChoices}}<option{{if eq . $.Limit}} selected{{end}}>{{.}}</option>{{end}}
</select>
<noscript><button type="submit">Apply</button></noscript>
</form>
{{if .User}}<p class="tl-filter">everything by {{who .Repo .User}} <a href="/r/{{.Repo}}/timeline{{with .Y}}?y={{.}}{{end}}">clear</a></p>{{end}}
{{if .Tag}}<p class="tl-filter">tagged <span class="ci-tag"><svg class="ic" aria-hidden="true"><use href="#i-tag"/></svg>{{.Tag}}</span> <a href="/r/{{.Repo}}/timeline{{with .Y}}?y={{.}}{{end}}">clear</a></p>{{end}}
{{- /* Notes have no tab, so this filter is where a reader browsing them
       actually stands — and it used to be a dead end: the one page in
       the forge that lists nothing BUT notes offered no way to the page
       that reads them as a feed. The other two doors are the About
       panel and the docs page, neither of which is where somebody who
       just filtered a timeline is looking. */ -}}
{{if eq .Y "e"}}<p class="tl-filter">notes, in the order they are filed ·
<a href="/r/{{.Repo}}/technote">read them as a feed &rarr;</a></p>{{end}}
<div id="tl">{{template "tl-body" .}}</div>
{{end}}
{{define "tl-body"}}
{{if .Days}}<div class="tw"><table class="tl">
<tbody>{{range .Days}}
<tr class="tl-date"><td></td><td class="tl-graph" style="min-width:{{.Width}}px">{{.Carry}}</td><td class="tl-datecell"><span class="tl-pill">{{with weekday .Date}}{{.}} · {{end}}{{.Date}}</span></td></tr>
{{range .Rows}}<tr{{if ne .Kind "ci"}} class="tl-flat"{{end}}>
<td class="tl-time"><a href="{{.URL}}">{{.Time}}</a></td>
<td class="tl-graph" style="min-width:{{.Width}}px">{{.Head}}{{.Tail}}</td>
<td class="tl-slot"><div class="tl-card{{if ne .Kind "ci"}} tl-card-flat{{end}}{{if eq .Kind "e"}} tl-card-note{{end}}"{{if eq .Kind "e"}} style="--uh: {{userhue .User}}"{{else}}{{with .Tint}} style="{{.}}"{{end}}{{end}}>
{{if eq .Kind "ci"}}<span class="tl-title">{{.Lead}}</span>
{{range .Paras}}<p class="tl-p">{{.}}</p>{{end}}
{{- /* A merge that settled a landing says so, and says who decided.
       That is the difference between a merge somebody made by hand and
       one a decision record produced — and it is the link from the
       history back to the argument that put it there. */ -}}
{{if .Landing}}<p class="tl-p tl-landed">landed <a href="/r/{{$.Repo}}/landing/{{printf "%.16s" .Landing}}">{{clip 72 .LandingTitle}}</a>{{with .LandingApprover}}, approved by <b>{{who $.Repo .}}</b>{{end}}</p>{{end}}
<div class="tl-meta">{{.CI}}{{if .CI}} {{end}}{{if .IsMerge}}<span class="tl-badge">Merge</span> {{end}}{{if .IsLeaf}}<span class="tl-badge">Leaf</span> {{end}}<span class="tl-metaitem">check-in: <a href="{{.URL}}"><b>{{.Short}}</b></a></span>
<span class="tl-metaitem">user: <b>{{who $.Repo .User}}</b></span>
<span class="tl-metaitem">branch: <a href="/r/{{$.Repo}}/timeline?branch={{.Branch}}"><b>{{.Branch}}</b></a></span></div>
{{- /* A note shows that it HAS a body. The other flat kinds are
       records that something happened and their title says all there
       is to say; this one is a document, and one line of its prose is
       what separates it from them at a glance. */ -}}
{{else if eq .Kind "e"}}<span class="tl-badge">note</span> <a class="tl-note-t" href="{{.URL}}">{{.Title}}</a>
{{with .Excerpt}}<p class="tl-note-x">{{.}}</p>{{end}}
<span class="tl-meta-inline">by <b>{{who $.Repo .User}}</b></span>
{{else}}<span class="tl-badge">{{if eq .Kind "w"}}wiki{{else if eq .Kind "f"}}forum{{else if eq .Kind "l"}}landing{{else if eq .Kind "lc"}}landing comment{{else}}ticket{{end}}</span> <a href="{{.URL}}">{{.Title}}</a>
<span class="tl-meta-inline">by <b>{{who $.Repo .User}}</b></span>{{end}}
</div></td>
</tr>
{{end}}{{end}}</tbody>
</table></div>
{{if .Next}}<p><a href="/r/{{.Repo}}/timeline?before={{.Next}}{{if .Branch}}&branch={{.Branch}}{{end}}{{if .Tag}}&tag={{.Tag}}{{end}}{{if .User}}&user={{.User}}{{end}}{{with .Y}}&y={{.}}{{end}}&n={{.Limit}}">older →</a></p>{{end}}
{{else}}<p>No check-ins.</p>{{end}}
{{end}}`

type pageData struct {
	Title        string
	Version      string
	Origin       string // scheme://host we were reached by; for absolute URLs
	Path         string // the request path, for og:url
	Repo         string // repo context; empty on fleet-level pages
	Branch       string // active timeline branch filter
	Tag          string // active timeline tag filter
	User         string // active timeline user filter
	CheckinTags  checkinTagsDetail
	Manifest     manifestDetail
	BranchDiff   bool   // this check-in sits on a branch that forked from somewhere
	DiffBranch   string // set when the diff being shown is a whole branch
	Limit        int
	LimitChoices []int
	Y            string
	Live         bool
	// LiveAttr carries the data-init that opens the SSE stream. It MUST
	// sit on a wrapper OUTSIDE the element the stream patches: a patch
	// morphs the target to match the fragment, and the fragment has no
	// data-init, so an attribute on the target is deleted by the first
	// patch — taking Datastar's own connection with it. The failure is
	// quiet and easy to miss, because the first patch still applies.
	LiveAttr   template.HTMLAttr
	Fleet      []repoInfo
	FleetTotal int
	// Served is the fleet size before a filter, so a filtered listing
	// can say how many of the whole it matched — "1 of 1" is true and
	// tells a reader nothing.
	Served int
	// Notices is the third-party licence inventory; QuarryLicence is
	// this software's own.
	Notices       []legal.Notice
	QuarryLicence string
	// Explore names the aggregate tab in view; People and PeopleTotal
	// back the people one.
	Explore   string
	Person    personRow
	BoardView bool
	// Nav builds every link in the tracker header; Rows are the list's
	// decorated summaries.
	Nav     ticketNav
	Rows    []ticketRow
	Filters []ticketFilterControl
	// Landings is the awaiting-decision listing; LandingOpen is the
	// whole record set's open count, which the state segments show
	// regardless of which filter is on.
	Landings []landingRow
	// Landed and Stopped carry a strata walk's result back to the page.
	Landed, Stopped string
	// LandingGroups is the open queue folded one row per decision.
	LandingGroups []landingGroup
	LandingOpen   int
	Landing       *landingDetail
	// Across marks the cross-repository listing, where a row must say
	// which tracker it came from and the page addresses /tickets.
	Across bool
	// CanSaveView says an identified reader is looking, so the page may
	// offer to name this report. SaveTarget is the listing it would be
	// saved against — a repository, or empty for the cross-repository
	// listing.
	CanSaveView bool
	SaveTarget  string
	Columns     []ticketColumn
	Rail        []railSection
	Pager       *pager
	// CanWrite decides whether the board draws its move control. It is
	// write CAPABILITY, not session state — see mayWrite.
	CanWrite bool
	Board    []boardLane
	// The board's two axes and the choices offered for them, so the
	// controls can be rendered without the template knowing the
	// vocabulary.
	GroupBy    string
	LaneBy     string
	AxisFields []struct{ Key, Label string }
	// The column set, so the per-card move select offers every column
	// the board draws rather than only the ones already occupied — the
	// bug that made the board useless: one column meant the only move
	// available was to where the ticket already was.
	ColumnLabels []string
	// The board reads a bounded page of the tracker. Saying so is the
	// difference between "these are the tickets" and "these are some".
	Shown      int
	Truncated  bool
	ByPriority bool
	// MissPath is the URL a 404 echoes back, so a typo is findable.
	MissPath string
	// TrackerRepo names the forge's own tracker for /fleet's file-ticket
	// buttons; empty draws none.
	TrackerRepo string
	// DiffSplit selects the side-by-side diff view (?view=split).
	DiffSplit bool
	// CheckinLead is the comment's first line, linkified; CheckinBody
	// is the rest of the comment, linkified, line breaks preserved.
	// CheckinLongLead marks a first line too long to be a subject line —
	// it wears near-body styling instead of the bold lead.
	CheckinLead     template.HTML
	CheckinBody     template.HTML
	CheckinLongLead bool
	// Prefill seeds the new-ticket form from query parameters, so a
	// surface that knows about a problem (the fleet's error journal)
	// can deep-link a half-written ticket. Values pass through
	// template escaping like any other text.
	Prefill ticketPrefill
	// Dash is the signed-in landing page's aggregate (me.feed).
	Dash *dashData
	// FleetTab is which of the fleet page's three panels is showing:
	// stores, mirrors or errors. One page answering three questions in
	// one scroll answered whichever one you were not asking first.
	FleetTab string
	// ServerErrors is /fleet's error journal panel.
	ServerErrors []errlogRow
	ErrorTotal   int
	// About is the repo landing page's sidebar aggregate (repo.about);
	// nil everywhere else. DocHTML is the selected tab, op-rendered and
	// sanitizer-gated like WikiHTML.
	About   *aboutData
	DocHTML template.HTML
	// Vocab is the repository's ticket vocabulary (ticket.config), for
	// form datalists and anything else that offers the words back.
	Vocab       map[string][]string
	Page        int
	NextPage    int
	PrevPage    int
	People      []personRow
	PeopleTotal int
	// Searched is how many repositories a fleet-wide search consulted;
	// ByRepo is the per-repository facet and RepoFilter the one the
	// reader has narrowed to.
	Searched   int
	ByRepo     []repoFacet
	RepoFilter string
	Sort       string
	Entries    []timelineEntry
	Days       []tlDay
	Next       string
	WikiPages  []wikiTitle
	// The two things a page listing cannot say: what nothing links to,
	// and what is linked to but was never written.
	WikiOrphans []string
	WikiWanted  []wikiWant
	// StructKind names the full-list page in view: "wanted" or
	// "orphans". Empty on the docs index, where both are previews.
	StructKind string
	// What the two lists above left out, so a bound is never silent.
	MoreOrphans, MoreWanted int
	DocRows                 []docRow
	WikiHome                *wikiTitle
	DocEntry                *docRow
	// Note is the wiki page attached to whatever artifact this page
	// shows, and NoteName is its title so a reader can go and edit it.
	Note     template.HTML
	NoteName string
	// NoteKind names the artifact for the fold's summary.
	NoteKind string
	// Context is the check-in among its neighbours in time.
	Context  []ciContext
	WikiDocs []docEntry
	// Associated counts the artifact notes left out of the listing;
	// ShowAssociated says the reader asked for them anyway.
	Associated     int
	ShowAssociated bool
	DocVersion     string
	Doc            docDetail
	// DocPath is set when this file also has a rendered form.
	DocPath     bool
	WikiTOC     []wikiHeading
	Wiki        wikiDetail
	WikiRev     string        // non-empty when viewing a historical revision
	WikiRevs    []wikiRev     // the history page's edit list
	TechRevs    []technoteRev // a technote's edit list
	EditSource  string        // wiki edit form's prefilled markdown
	Checkin     checkinDetail
	Ticket      ticketDetail
	Attachments []attachmentRow
	// Mentions are the landings and threads that named this ticket —
	// what proposed to fix it, and how each went.
	Mentions []mentionRow
	// ChatRefs is the WINDOW-BOUNDED count of chat messages that named
	// this artifact. Kept apart from Mentions on purpose: those are
	// durable index facts and this expires with the channel.
	ChatRefs chatRefsRow
	// DescriptionHTML and TicketComments are pre-rendered by the op; the
	// sanitizer already ran, which is why they are template.HTML here.
	DescriptionHTML template.HTML
	TicketComments  []ticketComment
	Timeline        []ticketEvent // comments and field changes, oldest first
	TicketFields    []ticketControl
	History         []fileChange
	HistoryPath     string
	CIRuns          []ciRunRow
	CIBadge         template.HTML
	Tree            []treeRow
	TreeVersion     string
	Crumbs          []crumb
	Branches        []branchRow
	ClosedCount     int
	MoreBranches    int
	// BranchTotal and TagTotal back the repository stats strip; Tags
	// and RefName back the ref switcher.
	BranchTotal int
	// CloneCount is how many times the repository has been cloned. Shown
	// to anyone who may READ the repository rather than to admins only:
	// a public repository's popularity is public information, and one
	// nobody may read never renders this at all because the page itself
	// is already gated.
	CloneCount int
	// PraiseCount is how many accounts praise this repository, Praised
	// whether the VIEWER is one of them. Both are needed: the control
	// has to say what pressing it will DO, not only what the number is.
	PraiseCount int
	Praised     bool
	// CanPraise gates the control on there being an account behind it.
	// A forge with no accounts configured draws no button rather than
	// one that refuses — a control must not render unless what it
	// invokes can exist here.
	CanPraise bool
	// PraisedRepos backs the listing where praise is revisited and
	// reversed; PraiseOwner is whose list it is.
	PraisedRepos []praisedRow
	PraiseOwner  string
	PraiseIsMine bool
	// Events is the repository's recent raised events, and EventWindow
	// says how far back the log can see. The window is stated because
	// the stream is a live tail, not history — a log that let a reader
	// assume otherwise would be lying by omission.
	Events      []LoggedEvent
	EventWindow string
	TagTotal    int
	Tags        []tagRow
	RefName     string
	// FossilClone offers the fossil clone command alongside zit;
	// CloneTool is the one currently shown.
	FossilClone bool
	CloneTool   string
	CloneURL    string
	Readme      template.HTML
	ReadmeIn    string
	Forum       []forumThreadRow
	ForumPinned []forumThreadRow
	ForumRoot   string // reply-form target on the thread page
	Flash       string // one-render notice ("post held for moderation")
	OGDesc      string // og:description for link unfurls
	Composer    bool   // page carries a markdown composer: load its script
	YourSub     string // the viewer's thread-subscription standing
	ReplyTo     string // specific post the composer answers (hash prefix)
	ReplyToUser string
	CanMod      bool // moderation controls follow Admin
	// CanAdmin is "may administer THIS repository" — the inline admin
	// controls. IsAdmin above is site-wide and answers a different
	// question.
	CanAdmin   bool
	ModOn      bool
	Queue      []stagedRow
	ModLog     []modRow
	ForumPosts []forumPostRow
	LoginNext  string // post-login redirect target (Next is the page cursor)
	SignedIn   string // the signed-in account, for the header
	HasInbox   bool   // an inbox is configured, so link to it
	// AttnAttr opens the attention stream (RFC 0011 §5) on this page:
	// the data-signals and data-init the toasts wrapper carries, empty
	// when the page does not open one. AttnTitleAttr is the same
	// decision reflected in the document title, which is why they are
	// set and cleared together.
	//
	// Empty is the ordinary case on a fleet page: plain HTTP/1.1 allows
	// six connections per origin and a repository page already spends
	// one or two, so the stream is opened on repository pages only
	// unless --attention-everywhere says the deployment multiplexes.
	AttnAttr      template.HTMLAttr
	AttnTitleAttr template.HTMLAttr
	// AttnUnread is the count the inbox page's "mark all seen" control
	// acts on; NotifyDesktop is that account's desktop-notification
	// preference (RFC 0011 §5: the permission prompt is only ever
	// raised from this control, never on page load).
	AttnUnread    int
	NotifyDesktop bool
	// AttnToasts is that account's in-page banner preference. Off by
	// default: the stream's own job is the badge and the title count,
	// and a banner that arrives uninvited over what somebody is reading
	// is the part of "live" people turn off first.
	AttnToasts bool
	// AttnRecent is the local attention window as the inbox lists it
	// (RFC 0011 §5), newest first. It is rendered whether or not notify
	// is configured — HasNotify says which, so the page can label the
	// two lists when it shows both.
	AttnRecent []attnRow
	HasNotify  bool
	// AttnTabs is the filter bar, AttnFilter the tab it is showing,
	// and AttnEmpty the one sentence a filter with nothing in it says.
	// Filtering is the SERVER's: the tabs are links, so the page works
	// with no script and a filtered view is a URL somebody can send.
	AttnTabs   []attnFilter
	AttnFilter string
	AttnEmpty  string
	// AttnNext is `inbox.list`'s composite cursor for the page after
	// this one, "" at the end of the list. It is carried as it arrived:
	// it addresses notify's half and quarry's half at once. AttnBefore
	// is the cursor THIS page was fetched with, so a control on it
	// comes back to the page it was clicked on rather than to the top.
	AttnNext   string
	AttnBefore string
	// ChatRobot is the repository's activity-robot event patterns
	// (RFC 0011 §10), empty when the robot is off. HasRobot says the op
	// is registered at all — a forge with no chat plane has no robot,
	// and the panel is not drawn rather than drawn and inert.
	ChatRobot string
	HasRobot  bool
	// HasPrefs says a preference store is attached, so the switch is
	// drawn. Without one it is not drawn at all rather than drawn and
	// inert — a control that does nothing is worse than none.
	HasPrefs bool
	// NotifyPrefs is the whole state of /me/notifications (RFC 0011
	// §6): the family x channel matrix, the two forge-local switches,
	// the muted repositories and the push control. nil on every other
	// page.
	NotifyPrefs *prefsView
	CanSignIn   bool   // sessions are configured, so offer the link
	IsAdmin     bool   // site admin, so show the fleet link
	Error       string // form-level failure, shown above the fields
	Technotes   []technoteRow
	Technote    technoteDetail
	ChatMsgs    []ChatMessage
	// ChatReadSeq is chat_read.seq for the signed-in viewer — the
	// divider sits at the first message whose Seq exceeds it. ChatNext
	// pages the "load older" link; ChatBefore is the cursor the CURRENT
	// page was fetched with (0 on the latest page, so "jump to latest"
	// can tell whether it has anywhere to go). ChatViewer is who may
	// edit/delete their own lines.
	ChatReadSeq   uint64
	ChatNext      uint64
	ChatBefore    uint64
	ChatViewer    string
	ChatViewerAll bool // holds capability "a": may delete anyone's message
	// One folded message plus its replies, for the permalink page.
	ChatOne        ChatMessage
	ChatReplies    []ChatMessage
	ChatExpired    bool
	ChatEditWindow bool // true when ChatOne is still inside its edit window
	// HasChatUnread/ChatUnread feed the repo nav's Chat badge.
	HasChatUnread bool
	ChatUnread    int
	File          fileDetail
	Diff          diffDetail
	Query         string
	Results       []searchHit
	// WikiHTML and FileHTML are op-rendered, sanitizer-gated markup —
	// the trusted HTML injection points (0002 §2: the sanitizer is the
	// gate).
	WikiHTML template.HTML
	FileHTML template.HTML
	// FleetHealth is the admin surface's per-store ingest state, and
	// Unhealthy the count an operator scans for. SyncResults is non-nil
	// only just after a manual round.
	FleetHealth []fleetHealthRow
	Unhealthy   int
	// FleetRows is the joined, problems-first listing; FleetProblems
	// how many lead it. MirrorCounts summarises the mirrors by state.
	FleetRows     []fleetRow
	FleetProblems int
	MirrorCounts  map[string]int
	SyncResults   []fleetSyncRow
	// Mirrors is the configured upstream tracking; MirrorResults is
	// non-nil only just after a manual pull.
	Mirrors       []mirrorRow
	MirrorResults []mirrorRunRow
	// MirrorEdit prefills the add form with one row, for editing in
	// place; set from ?edit=<repo> on the fleet page.
	MirrorEdit *mirrorRow
	Ops        opsView
	OpsRoute   opsRouteView
	OpsHistory opsHistoryView
	// Posture is the repo's mirror standing, set for every repo page.
	Posture posture
	// Kind is the explore listing's posture filter: "", mirror, native.
	Kind string
	// Moved is the board's last move, for the status line and its undo.
	Moved *boardMove
	// SearchAction, when set on a fleet-level page, points the header
	// box at that page as a filter instead of at global search.
	SearchAction string
	// Section is the nav entry the current page belongs to, so the nav
	// can say where the reader is. Counts is the per-section census;
	// HasCounts distinguishes "no content" from "counts unavailable",
	// which otherwise both render as zero.
	Section string
	// SearchKind and SearchScope are derived from Section by
	// searchContext, so no handler has to remember to set them.
	SearchKind  string
	SearchScope string
	// Theme is the reader's explicit colour choice, empty when they
	// have made none and the system decides. NextTheme is what the
	// switcher will move to; ThemeIcon and ThemeName describe the
	// current state.
	Theme     string
	NextTheme string
	ThemeIcon string
	ThemeName string
	Counts    navCounts
	HasCounts bool
	// RepoDescription and RepoPrivate are this repository's settings,
	// for the settings form and the About panel.
	RepoDescription string
	RepoHomepage    string
	RepoTopics      string
	// PanelError is the description form's OWN refusal, shown beside
	// that form. Distinct from Error, which belongs to the page: a
	// fragment patch replaces only the panel, so a message meant for
	// it must travel with it.
	PanelError string
	// SavedPanel names the panel that just saved. A page carries six
	// Save buttons, and a bare boolean would light all of them for one
	// save — telling the reader that everything was written when one
	// thing was.
	SavedPanel       string
	Caps             *capsPanel
	Protect          *protectPanel
	Roster           *rosterPanel
	Editor           *personEditor
	Visibility       *visibilityPanel
	TakePrivate      *takePrivatePanel
	Fossil           *fossilPanel
	CIRunView        *ciRunView
	RunFragPath      string
	Workers          []ci.Worker
	CITokens         *ciTokenPanel
	NewReporterToken string
	// Worker tokens (dagnats#627): the engine's own credential set,
	// engine-wide rather than per-repository. Err carries the engine's
	// refusal in its own words; NewWorkerToken shows a bearer once.
	WorkerTokens    []ci.WorkerToken
	WorkerTokensErr string
	NewWorkerToken  string
	// The CI list's controls and health strip (RFC 0009).
	CIHealth    []ciHealthRow
	CIBranches  []string
	CIPipelines []string
	CIState     string
	CIBranch    string
	CIPipeline  string
	CanTrigger  bool
	CIBypasses  []ciBypassRow
	// The pipeline editor (RFC 0009): tracked content, edited on the
	// web, landing like any change.
	CIEditPath    string
	CIEditContent string
	CIEditMessage string
	CIEditDiags   []string
	CIEditOK      bool
	CIEditNew     bool
	CITagsMode    string // "default" | "on" | "off"; "" hides the block
	Tip           *timelineEntry
	// TreeChanges: the listing has last-change data, so the table shows
	// GitHub's message + age columns instead of sizes.
	TreeChanges bool
	RepoPrivate bool
	Saved       bool
	// Deletable is whether quarry created this repository's store and
	// may therefore destroy it.
	Deletable bool
	// HasHooks says a webhook store is attached. Distinct from a
	// non-empty Hooks: a repository with no subscriptions must still
	// show the form that creates the first one, where a forge with no
	// OLTP must not show a section nothing can save.
	HasHooks bool
	Hooks    []HookSub
	// NewHookSecret is shown once, immediately after creating a
	// subscription, and never again.
	NewHookSecret string
	// EventNouns is the vocabulary's nouns, so the field that takes
	// patterns can say what patterns exist instead of expecting the
	// reader to know.
	EventNouns []string
	// RobotNouns is EventNouns as the ACTIVITY ROBOT should offer it:
	// `ci` is dropped on a forge with no engine, because a pattern
	// that can never match is a robot an owner turns on and then
	// believes is broken. The webhook surface keeps the full list —
	// an endpoint may be subscribed before the engine arrives.
	RobotNouns []string
	// Elapsed is how long this request took to render, reported the way
	// fossil reports it ("This page was generated in about 0.003s").
	// Publishing it is what made the timeline regression measurable
	// against fossil at all, so it stays on the page rather than in a
	// header only a developer would look at.
	Elapsed string
	// Breakdown says which layer the time went to ("zit 147ms, sql 3ms").
	// One number tells a reader the page is slow; it does not say whether
	// to look at the store, the index, or the template.
	Breakdown string
	// OwnH1 says the CONTENT renders the page's h1, so the layout emits
	// none at all. HideH1's sr-only fallback exists to keep a page that
	// shows no title accessibly named; on a page that draws its own,
	// that fallback is the same words twice — read out twice by a
	// screen reader, which is the double headline in its other form.
	OwnH1 bool
	// HideH1 lets a page that already names itself suppress the layout's
	// heading. The file listing does: its crumb trail starts with the
	// repository, so an h1 above it repeats the same word and costs a
	// heading's worth of vertical space to say nothing.
	HideH1 bool
}

// navCounts mirrors the repo.counts op.
type navCounts struct {
	IndexBehind  bool `json:"indexBehind"`
	Checkins     int  `json:"checkins"`
	WikiPages    int  `json:"wikiPages"`
	Tickets      int  `json:"tickets"`
	ForumThreads int  `json:"forumThreads"`
	OpenLandings int  `json:"openLandings"`
	Technotes    int  `json:"technotes"`
	Contributors int  `json:"contributors"`
	Tags         int  `json:"tags"`
}

// sectionOf names the nav entry a path belongs to. It reads the segment
// after /r/{repo}/, so every page under a section — a ticket, a wiki
// revision, a file's history — marks its section, not just the section's
// index page.
func sectionOf(path string) string {
	rest, ok := strings.CutPrefix(path, "/r/")
	if !ok {
		return ""
	}
	_, rest, ok = strings.Cut(rest, "/")
	if !ok || rest == "" {
		return "tree" // the repository home is the file tree
	}
	seg, _, _ := strings.Cut(rest, "/")
	switch seg {
	// Pages that live under a section without sharing its path segment.
	case "file", "history", "archive", "tree":
		return "tree"
	case "checkin", "diff", "timeline":
		return "timeline"
	default:
		return seg
	}
}

// mirrorRow mirrors the mirror.list op's row.
type mirrorRow struct {
	Repo         string `json:"repo"`
	URL          string `json:"url"`
	Every        int    `json:"every"`
	Enabled      bool   `json:"enabled"`
	LastAt       string `json:"lastAt"`
	LastOK       string `json:"lastOk"`
	LastErr      string `json:"lastErr"`
	Failures     int    `json:"failures"`
	AcceptWrites bool   `json:"acceptWrites"`
	DetachedFrom string `json:"detachedFrom"`
	State        string `json:"state"`
	// Bridged says this store has RFC 0011 §9's connector, and
	// ChatBridge is it. The flag rather than a nil pointer, because a
	// zero row would render as a bridge to an empty URL.
	Bridged    bool          `json:"bridged"`
	ChatBridge chatBridgeRow `json:"chatBridge"`
}

// chatBridgeRow mirrors the mirror.list op's bridge object. There is
// deliberately no password field: a struct that can hold one ends up
// rendered eventually.
type chatBridgeRow struct {
	Repo      string `json:"repo"`
	URL       string `json:"url"`
	User      string `json:"user"`
	LastMsgID int64  `json:"lastMsgId"`
	At        string `json:"at"`
	LastErr   string `json:"lastErr"`
}

// State is the one word the status line needs: a bridge that has
// heard nothing and failed at nothing is still connecting.
func (b chatBridgeRow) State() string {
	switch {
	case b.LastErr != "":
		return "failing"
	case b.At != "":
		return "connected"
	default:
		return "connecting"
	}
}

// posture is what every repo page knows about where the repository
// stands: tracking an upstream (and how freshly), detached from one,
// or native. It comes from repo.get, so the page and the API agree.
type posture struct {
	Mirror struct {
		Tracking     bool   `json:"tracking"`
		URL          string `json:"url"`
		State        string `json:"state"`
		LastOK       string `json:"lastOk"`
		LastAt       string `json:"lastAt"`
		Failures     int    `json:"failures"`
		AcceptWrites bool   `json:"acceptWrites"`
	} `json:"mirror"`
	DetachedFrom string `json:"detachedFrom"`
}

// ReadOnly: the store refuses local writes, so the page offers the
// upstream's write surfaces instead of its own.
func (p posture) ReadOnly() bool { return p.Mirror.Tracking && !p.Mirror.AcceptWrites }

// Host is the upstream's host, which is how a badge names it.
func (p posture) Host() string {
	u := p.Mirror.URL
	if u == "" {
		u = p.DetachedFrom
	}
	if parsed, err := url.Parse(u); err == nil && parsed.Host != "" {
		return parsed.Host
	}
	return u
}

// Upstream joins a Fossil page path onto the upstream URL: the write
// surfaces over there have predictable names.
func (p posture) Upstream(path string) string {
	return strings.TrimSuffix(p.Mirror.URL, "/") + "/" + strings.TrimPrefix(path, "/")
}

type mirrorRunRow struct {
	Repo    string `json:"repo"`
	Changed bool   `json:"changed"`
	Err     string `json:"err"`
}

// fleetHealthRow mirrors the fleet.status op's row. Durations arrive as
// seconds and are formatted for reading here rather than in the op: the
// JSON surface stays machine-shaped, the page stays human-shaped.
type fleetHealthRow struct {
	Name     string `json:"name"`
	Code     string `json:"code"`
	Checkins int    `json:"checkins"`
	Indexing bool   `json:"indexing"`
	Health   struct {
		LastOK       string  `json:"lastOk"`
		RoundSeconds float64 `json:"roundSeconds"`
		LastCount    int     `json:"lastCount"`
		Total        int     `json:"total"`
		Fallbacks    int     `json:"fallbacks"`
		LastErr      string  `json:"lastErr"`
		LastErrAt    string  `json:"lastErrAt"`
		Failures     int     `json:"failures"`
		Gaps         int     `json:"gaps"`
		Stalled      bool    `json:"stalled"`
		RetryAt      string  `json:"retryAt"`
	} `json:"health"`
}

// fleetRow is one store as the fleet page shows it: ingest health and
// mirror posture on one line, because they are one store. Problem is
// what sorts it to the top and keeps it out of the collapsed group.
type fleetRow struct {
	fleetHealthRow
	Mirror  *mirrorRow
	Problem bool
	Idx     int // position in the listing; names the row's popover and its anchor
}

// IngestState is the one-word verdict for the index side.
func (f fleetRow) IngestState() string {
	switch {
	case f.Health.Stalled:
		return "stalled"
	case f.Health.Failures > 0 || f.Health.LastErr != "":
		return "failing"
	case f.Indexing:
		return "indexing"
	case f.Health.Gaps > 0:
		return "gaps"
	}
	return "ok"
}

// fleetRows joins the two lists by name, marks problems, and orders
// the problems first. The healthy majority reads as a single block.
func fleetRows(health []fleetHealthRow, mirrors []mirrorRow) (rows []fleetRow, problems int) {
	byName := map[string]*mirrorRow{}
	for i := range mirrors {
		byName[mirrors[i].Repo] = &mirrors[i]
	}
	for _, h := range health {
		row := fleetRow{fleetHealthRow: h, Mirror: byName[h.Name]}
		st := row.IngestState()
		row.Problem = st == "stalled" || st == "failing" || st == "gaps" ||
			(row.Mirror != nil && row.Mirror.State == "failing")
		if row.Problem {
			problems++
		}
		rows = append(rows, row)
	}
	sort.SliceStable(rows, func(i, j int) bool { return rows[i].Problem && !rows[j].Problem })
	for i := range rows {
		rows[i].Idx = i
	}
	return rows, problems
}

// errlogRow mirrors errlog.Entry through the op boundary.
type errlogRow struct {
	Message string `json:"message"`
	Surface string `json:"surface"`
	Path    string `json:"path"`
	Count   int    `json:"count"`
	First   string `json:"first"`
	Last    string `json:"last"`
	Repo    string `json:"repo"`
	Trace   string `json:"trace"`
}

// Sig is the signature a reader can quote — the message is the identity
// here, and a fingerprint gives them something short to name it by.
func (e errlogRow) Sig() string {
	sum := sha256.Sum256([]byte(e.Message))
	return hex.EncodeToString(sum[:])[:8]
}

// Repeated marks a signature seen more than once: the panel leads with
// what is still happening, not with what happened once at boot.
func (e errlogRow) Repeated() bool { return e.Count > 1 }

type fleetSyncRow struct {
	Repo      string `json:"repo"`
	Artifacts int    `json:"artifacts"`
	Err       string `json:"err"`
}

type repoInfo struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Private     bool   `json:"private"`
	Mirror      struct {
		Tracking bool   `json:"tracking"`
		URL      string `json:"url"`
		State    string `json:"state"`
	} `json:"mirror"`
	DetachedFrom string `json:"detachedFrom"`
	Homepage     string `json:"homepage"`
	Topics       string `json:"topics"`
	LastActive   string `json:"lastActive"`
	Deletable    bool   `json:"deletable"`
	Contributors int    `json:"contributors"`
	MirroredAt   string `json:"mirroredAt"`
	Checkins     int    `json:"checkins"`
	TipDate      string `json:"tipDate"`
	TipComment   string `json:"tipComment"`
	Indexing     bool   `json:"indexing"`
}

type timelineEntry struct {
	Kind    string   `json:"kind"`
	Ref     string   `json:"ref"`
	Hash    string   `json:"hash"`
	Date    string   `json:"date"`
	User    string   `json:"user"`
	Comment string   `json:"comment"`
	Branch  string   `json:"branch"`
	IsLeaf  bool     `json:"isLeaf"`
	IsMerge bool     `json:"isMerge"`
	Parents []string `json:"parents"`
	CI      string   `json:"ci"`
	Excerpt string   `json:"excerpt"`
	// The landing a merge settled, when it settled one.
	Landing         string `json:"landing"`
	LandingTitle    string `json:"landingTitle"`
	LandingApprover string `json:"landingApprover"`
}

type wikiTitle struct {
	Title     string `json:"title"`
	Date      string `json:"date"`
	User      string `json:"user"`
	Revisions int    `json:"revisions"`
}

// docEntry is one document in the tree, for the index.
type docEntry struct {
	Path string `json:"path"`
	Size int64  `json:"size"`
	Date string `json:"date"`
	User string `json:"user"`
}

// docRow is one entry of the documentation index, WHICHEVER store it
// came from. A reader looking for how something works does not care
// whether the answer is a wiki artifact or a file in the tree, and on
// fossil's own repository the distinction actively misleads: the wiki
// holds 41 real pages last touched in 2018, while the 113 documents in
// www/ are current. One list, one shape, the source named quietly for
// anyone who needs to know where to edit.
type docRow struct {
	Title string
	URL   string
	Date  string
	User  string
	// Kind is "wiki" or "tree" — how it is stored, and therefore how it
	// is edited: in the browser, or by check-in.
	Kind string
	// Revisions is set for wiki pages.
	Revisions int
}

// entryDoc matches a project's front door. Fossil has no per-document
// importance metadata — its one explicit signal, the index-page setting,
// lives in server config that zit does not carry — so the honest
// substitutes are CONVENTION and recency. This is the convention half:
// a documentation directory's own index is the page its authors wrote
// to be read first, and www/index.wiki is exactly that on fossil.
//
// Anchored to the top level of a documentation directory on purpose:
// www/server/debian/index.md is a leaf, not a front door.
var entryDoc = regexp.MustCompile(`^(?:www|doc|docs)/index\.(?:wiki|md|markdown|html?|txt)$`)

// repoReadme is the fallback front door for a project that keeps no
// documentation directory at all.
var repoReadme = regexp.MustCompile(`^README\.(?:wiki|md|markdown|html?|txt)$`)

// associatedNote fetches the wiki page attached to an artifact, if one
// has been written. Fossil's wikitheory.wiki: "Stand-alone wiki pages
// with special names branch/BRANCHNAME or checkin/HASH are associated
// with the corresponding branch or check-in", and it shows them in an
// About section on those screens rather than in the wiki index. That is
// the other half of hiding them from the documentation index: they are
// not junk, they are just filed somewhere else.
//
// Best-effort by design. A note is an extra, and the overwhelming
// majority of artifacts have none — none of them should pay an error.
func associatedNote(r *ops.Registry, req *http.Request, repo, name string) (wikiDetail, bool) {
	out, err := invoke(req.Context(), r, "wiki.get",
		url.Values{"repo": {repo}, "name": {name}})
	if err != nil {
		return wikiDetail{}, false
	}
	var wd wikiDetail
	remarshal(out, &wd)
	// A deleted page is an empty edit, not content: fossil keeps the
	// tombstone so history survives, and a tombstone is not an About.
	if wd.Deleted || strings.TrimSpace(wd.HTML) == "" {
		return wikiDetail{}, false
	}
	return wd, true
}

// noteFor turns a fetched note into the fields the About block needs.
func noteFor(wd wikiDetail) (html template.HTML, name, kind string) {
	kind, _, _ = strings.Cut(wd.Title, "/")
	switch kind {
	case "checkin":
		kind = "check-in"
	case "":
		kind = "page"
	}
	return template.HTML(wd.HTML), wd.Title, kind
}

// associatedWiki are the page-name prefixes fossil treats as ASSOCIATED
// wiki: notes attached to another artifact rather than documents in
// their own right (see fossil's wikitheory.wiki). A branch/ page belongs
// at the top of that branch's timeline and a checkin/ page in that
// check-in's About section — not in an index of a project's
// documentation, which is why fossil's own /wcontent hides them behind
// a "Show associated wikis" checkbox.
//
// This is not a tidying preference. On fossil's own repository 49 of 83
// wiki pages are these, so an index that lists them is 59% notes about
// something else.
var associatedWiki = []string{"branch/", "checkin/", "tag/", "ticket/"}

func isAssociatedWiki(title string) bool {
	for _, p := range associatedWiki {
		if strings.HasPrefix(title, p) {
			return true
		}
	}
	return false
}

// docDetail is a file from the tree rendered as documentation.
type docDetail struct {
	Hash        string        `json:"hash"`
	Path        string        `json:"path"`
	Size        int           `json:"size"`
	Mimetype    string        `json:"mimetype"`
	HTML        string        `json:"html"`
	Outline     []wikiHeading `json:"outline"`
	ContentType string        `json:"contentType"`
	Content     string        `json:"content"`
}

// wikiHeading is one entry of a page's contents.
type wikiHeading struct {
	Level int    `json:"level"`
	ID    string `json:"id"`
	Text  string `json:"text"`
	// Sub is true for anything below the page's shallowest heading, so
	// the contents can indent one level without pretending to model a
	// tree the document may not actually have.
	Sub bool `json:"-"`
}

// aboutData mirrors repo.about's aggregate for the landing page.
type aboutData struct {
	Description string   `json:"description"`
	Homepage    string   `json:"homepage"`
	Topics      []string `json:"topics"`
	Docs        []struct {
		Path  string `json:"path"`
		Label string `json:"label"`
	} `json:"docs"`
	DocPath       string `json:"docPath"`
	DocLabel      string `json:"docLabel"`
	DocHTML       string `json:"docHtml"`
	LatestTag     string `json:"latestTag"`
	LatestTagTip  string `json:"latestTagTip"`
	LatestTagDate string `json:"latestTagDate"`
	TagCount      int    `json:"tagCount"`
	Contributors  int    `json:"contributors"`
	LicenseName   string `json:"licenseName"`
	AnnounceRoot  string `json:"announceRoot"`
	AnnounceTitle string `json:"announceTitle"`
	AnnounceDate  string `json:"announceDate"`
	NoteEvent     string `json:"noteEvent"`
	NoteTitle     string `json:"noteTitle"`
	NoteDate      string `json:"noteDate"`
	NoteUser      string `json:"noteUser"`
	NoteExcerpt   string `json:"noteExcerpt"`
	NoteCount     int    `json:"noteCount"`
}

// dashData mirrors me.feed for the signed-in landing page.
type dashData struct {
	User  string `json:"user"`
	Repos []struct {
		Name         string `json:"name"`
		Description  string `json:"description"`
		LastActivity string `json:"lastActivity"`
		Open         int    `json:"open"`
	} `json:"repos"`
	Kinds []struct {
		Kind  string `json:"kind"`
		Count int    `json:"count"`
	} `json:"kinds"`
	// Total is everything the caller's repositories hold; Depth is how
	// far back this feed pages. They are different questions, and the
	// page says both rather than letting one stand for the other.
	Total int         `json:"total"`
	Depth int         `json:"depth"`
	Feed  []dashEvent `json:"feed"`
	Mine  []dashEvent `json:"mine"`

	// Awaiting is the band at the top: the caller's open tickets that
	// somebody else has answered and left with them. It is the one
	// thing on this page that is about the reader rather than about
	// what happened, so it leads — and when there is nothing waiting it
	// does not render at all rather than sitting there empty.
	Awaiting []ticketRow
	// Kind is the feed's chosen chip, Find the repository filter box.
	Kind, Find string
	// Offset is the page, and Pager the numbered control built from it.
	Offset int
	Pager  *pager
	// CanCreate says the reader may start a repository, so the page can
	// offer it. A control that cannot work does not render.
	CanCreate bool
}

// kindLabel names a feed chip. The timeline's letters are storage, not
// something to show a reader.
//
// Each label names EVENTS, because that is what the chip counts and
// pages: one ticket with nine comments is nine rows here, not one. A
// chip reading "tickets 93,649" against a corpus of 17,000 tickets was
// not wrong about its number — it was wrong about its noun.
func kindLabel(k string) string {
	switch k {
	case "ci":
		return "check-ins"
	case "t":
		return "ticket changes"
	case "w":
		return "wiki edits"
	case "f":
		return "forum posts"
	case "l":
		return "landings"
	case "e":
		return "technote edits"
	}
	return k
}

// dashFeedSize is the feed's page, and must match me.feed's own — the
// pager's arithmetic is only right if both agree what a page is.
//
// Ten, not twenty-five. The dashboard is a glance at what moved, not an
// archive: at twenty-five the phone asked for six screens of scrolling
// before it reached the pager, and a landing page you have to scroll
// past is a landing page nobody reads to the end of. The archive is
// each repository's own timeline, which the depth line below says.
const dashFeedSize = 10

// PageURL is the dashboard at one page, keeping whatever the reader has
// narrowed to. Changing the page must not silently drop the chip or the
// repository filter, which is why every pager link comes from here.
func (d dashData) PageURL(offset int) string {
	q := url.Values{}
	if d.Kind != "" {
		q.Set("kind", d.Kind)
	}
	if d.Find != "" {
		q.Set("find", d.Find)
	}
	if offset > 0 {
		q.Set("offset", strconv.Itoa(offset))
	}
	if len(q) == 0 {
		return "/"
	}
	return "/?" + q.Encode()
}

// FeedURL is the dashboard at one kind chip, with the repository filter
// kept: changing what you look at must not silently drop what you
// narrowed to.
func (d dashData) FeedURL(kind string) string {
	q := url.Values{}
	if kind != "" {
		q.Set("kind", kind)
	}
	if d.Find != "" {
		q.Set("find", d.Find)
	}
	if len(q) == 0 {
		return "/"
	}
	return "/?" + q.Encode()
}

type dashEvent struct {
	Repo    string `json:"repo"`
	Kind    string `json:"kind"`
	Ref     string `json:"ref"`
	Hash    string `json:"hash"`
	Date    string `json:"date"`
	User    string `json:"user"`
	Comment string `json:"comment"`
}

type ticketPrefill struct {
	Title, Comment, Type, Severity, Priority, Subsystem string
	FoundIn                                             string
}

type wikiDetail struct {
	Hash    string        `json:"hash"`
	Title   string        `json:"title"`
	Date    string        `json:"date"`
	User    string        `json:"user"`
	HTML    string        `json:"html"`
	Outline []wikiHeading `json:"outline"`
	Deleted bool          `json:"deleted"`
}

// docsPageSize is the documentation index's page. Larger than the
// tracker's because these are one-line rows in two columns, so a page
// is fifty rows down each side rather than fifty down one.
//
// Wiki pages alone would not need paging — human authorship bounds them
// at a couple of hundred — but the tree half does not: a repository can
// carry any number of documents, and the previous bound of 400 was a
// dead end rather than a page, with everything past it reachable only
// by guessing a filter.
const docsPageSize = 100

// wikiTOCLimit bounds the contents rail. Fossil's Cookbook has 51
// headings and yields 17 entries once depth is capped; a rail longer
// than this has stopped being a glance at the page's shape.
const wikiTOCLimit = 40

// wikiRailLimit caps the sibling rail. Past a dozen it stops being a
// glance and starts being the index, which is one click away anyway.
const wikiRailLimit = 12

// wikiHome is the page a tracker opens on when it has one, the way
// every forge with a wiki does. Fossil has no such convention, so this
// is additive: with no Home page /wiki is the index it always was.
const wikiHome = "Home"

// wikiContents decides whether a page earns a contents rail and shapes
// it. Two headings do not need navigating and a page of h4s is still a
// page, so depth is relative to the SHALLOWEST heading present rather
// than to h1 — a document that opens at h2 reads the same as one that
// opens at h1, and neither should be indented for it.
func wikiContents(hs []wikiHeading) []wikiHeading {
	if len(hs) < 3 {
		return nil
	}
	top := hs[0].Level
	for _, h := range hs {
		if h.Level < top {
			top = h.Level
		}
	}
	pick := func(depth int) []wikiHeading {
		out := make([]wikiHeading, 0, len(hs))
		for _, h := range hs {
			// Below the second level the rail becomes a wall; fossil's
			// Cookbook alone would contribute 51 entries unbounded.
			if h.Level > top+depth {
				continue
			}
			h.Sub = h.Level > top
			out = append(out, h)
		}
		return out
	}
	out := pick(1)
	if len(out) > wikiTOCLimit {
		// Shallower before shorter: dropping the subsections keeps the
		// contents a true map of the page, where truncating it mid-way
		// would claim the document ends where the rail does.
		out = pick(0)
	}
	if len(out) > wikiTOCLimit {
		out = out[:wikiTOCLimit]
	}
	if len(out) < 3 {
		return nil
	}
	return out
}

type wikiRev struct {
	Hash string `json:"hash"`
	Date string `json:"date"`
	User string `json:"user"`
}

type forumThreadRow struct {
	Root         string   `json:"root"`
	Title        string   `json:"title"`
	Posts        int      `json:"posts"`
	Created      string   `json:"created"`
	Updated      string   `json:"updated"`
	User         string   `json:"user"`
	Score        int      `json:"score"`
	Excerpt      string   `json:"excerpt"`
	HasPoll      bool     `json:"hasPoll"`
	Participants []string `json:"participants"`
	Spark        []int    `json:"spark"`
	Read         bool     `json:"read"`
}

type forumPostRow struct {
	Hash         string `json:"hash"`
	Parent       string `json:"parent"`
	Date         string `json:"date"`
	User         string `json:"user"`
	Score        int    `json:"score"`
	YourVote     int    `json:"yourVote"`
	Hidden       bool   `json:"hidden"`
	HiddenReason string `json:"hiddenReason"`
	ParentUser   string // author of the post this one answers (web-side join)
	IndentPx     int    // DAG depth as indentation (capped)
	HTML         template.HTML
	Poll         struct {
		Present    bool     `json:"present"`
		Question   string   `json:"question"`
		Options    []string `json:"options"`
		Counts     []int    `json:"counts"`
		Percents   []int    `json:"percents"`
		Total      int      `json:"total"`
		YourChoice int      `json:"yourChoice"`
		Closed     bool     `json:"closed"`
		Closes     string   `json:"closes"`
	} `json:"poll"`
}

// threadShape joins each post to the author it answers and orders the
// thread as the DAG it is: depth-first, siblings in date order, each
// level indented — capped so deep chains stay readable. Posts whose
// parent is not in the slice hang off the root rather than vanishing.
//
// Shared because a landing IS a forum thread: the two pages must agree
// on what "replying to" and "one level in" look like, and a second copy
// of this walk is how they would stop agreeing.
func threadShape(posts []forumPostRow) []forumPostRow {
	if len(posts) == 0 {
		return posts
	}
	authors := make(map[string]string, len(posts))
	for _, p := range posts {
		authors[p.Hash] = p.User
	}
	for i := range posts {
		if p := posts[i].Parent; p != "" {
			posts[i].ParentUser = authors[p]
		}
	}
	byHash := map[string]int{}
	children := map[string][]int{}
	for i, p := range posts {
		byHash[p.Hash] = i
	}
	var orphans []int
	for i, p := range posts {
		if i == 0 {
			continue
		}
		if _, ok := byHash[p.Parent]; ok && p.Parent != "" {
			children[p.Parent] = append(children[p.Parent], i)
		} else {
			orphans = append(orphans, i)
		}
	}
	ordered := make([]forumPostRow, 0, len(posts))
	var walk func(idx, depth int)
	walk = func(idx, depth int) {
		row := posts[idx]
		if depth > 4 {
			depth = 4
		}
		row.IndentPx = depth * 26
		ordered = append(ordered, row)
		for _, c := range children[posts[idx].Hash] {
			walk(c, depth+1)
		}
	}
	walk(0, 0)
	for _, o := range orphans {
		walk(o, 1)
	}
	if len(ordered) != len(posts) {
		return posts
	}
	return ordered
}

// identicon draws a deterministic identity mark from a login name: a
// 5x5 horizontally-mirrored pixel grid, hued by the name's hash — the
// same idea as GitHub's identicons. Inline SVG, so it costs no request
// and no script; the same name renders the same mark everywhere.
// userHue is one login's hue, shared by the identicon, the hued name,
// the post edge and the spectrum ribbon — one color IS one person,
// everywhere.
func userHue(name string) int { return idn.Hue(name) }

// spectrumSVG is a thread's fingerprint: one band per post, in the
// author's hue, in posting order. A two-person volley reads striped; a
// question with one long answer reads as a field with an interruption.
// spectrumShades assigns each voice in a thread a lightness step, so that
// two people whose hues happen to land near each other do not paint one
// indistinguishable block.
//
// The hue is NEVER moved. It is the identity: one hue per person across
// every surface, and a face that changes colour by context is not a face.
// Lightness is free, and the identicon already draws itself in two steps of
// one hue, so stepping a colliding voice is borrowing a value the palette
// owns rather than inventing one.
//
// Near-collisions are not bad luck to be engineered away. Ten names in this
// corpus put their closest pair 3 degrees apart; that is the birthday bound,
// and no hash fixes it. So this resolves what is ACTUALLY IN THE THREAD, the
// way the timeline resolves branch colours on a page — the difference being
// that a branch may take a new colour and a person may not.
//
// Assigned per VOICE, not per segment: someone who posts three times is the
// same tone all three times, or the bar would say two people where there is
// one.
func spectrumShades(posts []forumPostRow) map[string]int {
	// The identicon's own two steps, then one more for a third voice in
	// the same arc. Past three the bar has bigger problems than tone.
	ladder := []int{40, 56, 30}
	var order []string
	seen := map[string]bool{}
	for _, p := range posts {
		if !seen[p.User] {
			seen[p.User] = true
			order = append(order, p.User)
		}
	}
	out := make(map[string]int, len(order))
	for _, u := range order {
		h := userHue(u)
		step := 0
		// Take the first step no near neighbour has already claimed.
		for step < len(ladder)-1 {
			clash := false
			for _, other := range order {
				if other == u {
					break // only voices already assigned
				}
				if hueNear(h, userHue(other)) && out[other] == ladder[step] {
					clash = true
					break
				}
			}
			if !clash {
				break
			}
			step++
		}
		out[u] = ladder[step]
	}
	return out
}

// hueNear reports whether two hues are close enough to read as one colour
// in a six-pixel band. Measured on the circle, so 359 and 2 are neighbours.
func hueNear(a, b int) bool {
	d := a - b
	if d < 0 {
		d = -d
	}
	if d > 180 {
		d = 360 - d
	}
	return d < 25
}

func spectrumSVG(posts []forumPostRow) template.HTML {
	if len(posts) < 2 {
		return ""
	}
	// One voice makes a solid bar that says nothing and reads as an
	// error stripe; the ribbon draws only when there is a conversation
	// to fingerprint.
	voices := map[string]bool{}
	for _, p := range posts {
		voices[p.User] = true
	}
	if len(voices) < 2 {
		return ""
	}
	shade := spectrumShades(posts)
	var b strings.Builder
	n := len(posts)
	// One continuous bar, constant height: contiguous segments, no
	// gaps — presence comes from height and the muted edge recipe, and
	// only the rounded OUTER corners say "designed element".
	fmt.Fprintf(&b, `<svg class="f-spectrum" viewBox="0 0 100 6" preserveAspectRatio="none" aria-hidden="true">`)
	seg := 100 / float64(n)
	for i, p := range posts {
		// The author's identicon hue, at the lightness this thread
		// assigned them (same hsl recipe — the mark and the bar must
		// never disagree about WHOSE colour it is), and each segment is
		// a link: click a color, land on that post.
		fmt.Fprintf(&b, `<a href="#p-%.12s"><rect x="%.2f" y="0" width="%.2f" height="6" fill="hsl(%d, 62%%, %d%%)" fill-opacity="0.75"><title>%s</title></rect></a>`,
			p.Hash, float64(i)*seg, seg+0.05, userHue(p.User), shade[p.User], template.HTMLEscapeString(p.User))
	}
	b.WriteString(`</svg>`)
	return template.HTML(b.String())
}

func identicon(name string) template.HTML { return template.HTML(idn.Mark(name)) }

// chatMsgHTML renders one chat message row — the single renderer the
// page's initial listing and the SSE append/replace patches both call
// (RFC 0012 Phase 1: "one renderer, two translators"). viewer is the
// signed-in account (own-message edit/delete), canDeleteAny holds when
// the viewer has capability "a" (may delete anyone's message).
//
// Consecutive messages by one author in one minute share a header:
// m.Grouped says this is one of the later ones, and it is then drawn as
// a body alone. Every control is still a plain form or link, and the
// edit disclosure is a <details> — it opens with no script at all
// (Principle 3).
func chatMsgHTML(m ChatMessage, repo, viewer string, canDeleteAny bool) template.HTML {
	var b strings.Builder
	// A div, not a p: the row carries a <details> and a <form>, and
	// both of those END a paragraph in the HTML parser — the closing
	// tags would then be stray and the body span the live patches
	// target would not be where the markup says it is.
	fmt.Fprintf(&b, `<div class="chatmsg" id="chatmsg-%d" data-seq="%d" data-kind="%s"`,
		m.Seq, m.Seq, template.HTMLEscapeString(m.Kind))
	// The author's hue as a whisper on the left edge — the forum post's
	// own rule, at chat density, so "who said this" reads the same on
	// both surfaces. A robot line takes no hue: it is the channel
	// talking about the repository, not a person with a column.
	if m.Kind == "msg" && m.User != "" {
		fmt.Fprintf(&b, ` style="--uh: %d"`, userHue(m.User))
	}
	if m.Grouped {
		b.WriteString(` data-grouped`)
	}
	if m.Deleted {
		b.WriteString(` data-deleted`)
	}
	if m.Edited {
		b.WriteString(` data-edited`)
	}
	b.WriteString(">")
	// Every row reserves the same gutter, so the column reads as one
	// column: a group header fills it with the author's mark, a
	// continuation row with the absolute clock, which is the one thing
	// a headerless row cannot otherwise say.
	if !m.Grouped {
		b.WriteString(`<span class="chat-gut">` + string(identicon(m.User)) + `</span>`)
		// One header per run: the name and the time. The permalink is
		// not here — it belongs with the row's other actions, which are
		// quiet until the row is pointed at.
		// A robot line takes a mark instead of borrowing a person's:
		// the identicon column already says "somebody", and the one
		// thing this row has to say is that nobody did.
		mark := ""
		if m.Kind == "robot" {
			mark = `<span class="chat-robot" data-hook="robot-mark">robot</span>`
		}
		fmt.Fprintf(&b, `<span class="chat-head">%s<b>%s</b> <small class="chat-when">%s</small></span>`,
			mark, template.HTMLEscapeString(m.User), string(ago(m.At)))
	} else {
		b.WriteString(`<span class="chat-gut">`)
		if hm := clock(m.At); hm != "" {
			fmt.Fprintf(&b, `<span class="chat-clock">%s</span>`, hm)
		}
		b.WriteString(`</span>`)
	}
	if m.Ref != 0 && m.Kind == "msg" {
		// The quote when the referenced message is in hand, the bare
		// link when it is not: a reply whose original fell out of the
		// page still says what it answers.
		if q := chatQuoteHTML(m, repo); q != "" {
			b.WriteString(string(q))
		} else {
			fmt.Fprintf(&b, `<a class="chatreply" href="/r/%s/chat/%d">in reply to #%d</a>`,
				url.PathEscape(repo), m.Ref, m.Ref)
		}
	}
	// An inline #seq is a reference like any other, and answers the
	// same question a reply's quote does: what is being pointed at.
	for _, q := range m.RefQuotes {
		b.WriteString(string(chatQuoteBlock(q.Seq, q.User, q.Line, repo)))
	}
	b.WriteString(string(chatBodyHTML(m, repo, viewer, canDeleteAny)))
	b.WriteString("</div>")
	return template.HTML(b.String())
}

// chatMinute is a timestamp to the minute — the grain a run of messages
// is grouped by. Empty for anything that is not an RFC3339 stamp, which
// groups nothing rather than grouping everything.
func chatMinute(at string) string {
	if len(at) < 16 || at[4] != '-' || at[10] != 'T' {
		return ""
	}
	return at[:16]
}

// chatGroupRuns marks each row that continues the run above it. A reply
// always starts a new run so its quote sits under a header, and so does
// the first unread row, because the "new" divider is drawn above it and
// a header must not end up on the wrong side of the line.
func chatGroupRuns(msgs []ChatMessage, readSeq uint64) {
	for i := range msgs {
		if i == 0 {
			continue
		}
		msgs[i].Grouped = chatGrouped(msgs[i-1], msgs[i]) &&
			!(readSeq > 0 && msgs[i].Seq > readSeq && msgs[i-1].Seq <= readSeq)
	}
}

// chatGrouped reports whether m continues prev's run.
func chatGrouped(prev, m ChatMessage) bool {
	if m.Kind != "msg" || prev.Kind != "msg" || m.User == "" || m.User != prev.User {
		return false
	}
	if m.Ref != 0 {
		return false // a reply carries a quote, which needs a header over it
	}
	minute := chatMinute(m.At)
	return minute != "" && minute == chatMinute(prev.At)
}

// chatRefQuoteMax caps how many inline references one message quotes.
// A quote is a reminder of what is being pointed at; a message that
// names five things would otherwise be mostly other people's words.
const chatRefQuoteMax = 2

// chatRefQuotes fills each row's inline-reference quotes from the rows
// the SAME listing carries — no lookup at all, for chatQuote's reason:
// a page never shows a quote whose original it cannot also show. A seq
// the window has dropped, or that lives further up the log, keeps its
// link in prose and gets no block.
func chatRefQuotes(msgs []ChatMessage) {
	bySeq := make(map[uint64]ChatMessage, len(msgs))
	for _, m := range msgs {
		if m.Kind == "msg" && !m.Deleted {
			bySeq[m.Seq] = m
		}
	}
	for i := range msgs {
		msgs[i].RefQuotes = chatQuotesFor(msgs[i], bySeq)
	}
}

// chatQuotesFor is one row's inline quotes, from the canonical
// reference tokens the op already parsed out of its text (RFC 0011
// §14) — never a second scan of the prose, which is how a link and its
// quote drift apart.
func chatQuotesFor(m ChatMessage, bySeq map[uint64]ChatMessage) []ChatQuote {
	if m.Kind != "msg" || m.Deleted || len(m.Refs) == 0 {
		return nil
	}
	// The row's own number and the message it formally answers are
	// already accounted for: one draws itself, the other draws the
	// reply quote just above.
	seen := map[uint64]bool{m.Seq: true, m.Ref: true}
	var out []ChatQuote
	for _, tok := range m.Refs {
		seq, ok := chatRefSeq(tok)
		if !ok || seen[seq] {
			continue
		}
		seen[seq] = true
		src, ok := bySeq[seq]
		if !ok {
			continue
		}
		out = append(out, ChatQuote{Seq: seq, User: src.User, Line: firstLine(src.Text)})
		if len(out) == chatRefQuoteMax {
			break
		}
	}
	return out
}

// chatRefSeq reads a chat reference's sequence out of a canonical
// token — "#12" or "repo:#12" (markup.RefToken.Canonical). Anything
// else is a reference to something that is not a chat message.
func chatRefSeq(tok string) (uint64, bool) {
	if i := strings.IndexByte(tok, ':'); i >= 0 {
		tok = tok[i+1:]
	}
	if !strings.HasPrefix(tok, "#") {
		return 0, false
	}
	seq, err := strconv.ParseUint(tok[1:], 10, 64)
	if err != nil || seq == 0 {
		return 0, false
	}
	return seq, true
}

// chatBodyHTML renders everything about a message that an edit or a
// delete can change — the text, the "(edited)" mark, and the row's own
// actions — inside its own addressable element.
//
// It is separate from the header for one reason: a live edit or delete
// arrives as a TOMBSTONE, whose author and timestamp are the tombstone's
// (a moderator's, five minutes later), not the row's. Replacing the
// whole row from a tombstone repaints the message under the wrong name.
// Replacing only #chatbody-<seq> cannot: the header the page already
// rendered — identicon, author, time — stays exactly as it was, because
// nothing in a tombstone has any business changing it.
//
// The actions live in here rather than beside it for the same reason in
// reverse: a delete must take the edit and delete controls away with
// the text, and one patch has to do both.
func chatBodyHTML(m ChatMessage, repo, viewer string, canDeleteAny bool) template.HTML {
	var b strings.Builder
	fmt.Fprintf(&b, `<div class="chatbody" id="chatbody-%d"`, m.Seq)
	if m.Deleted {
		b.WriteString(` data-deleted`)
	}
	if m.Edited {
		b.WriteString(` data-edited`)
	}
	b.WriteString(">")
	switch {
	case m.Deleted:
		b.WriteString(`<i>message deleted</i>`)
	case m.HTML != "":
		// Links AND hooks are markup's (RFC 0011 §14): the anchors
		// arrive armed, so chat previews exactly like every other
		// surface rather than through a chat-only second pass.
		b.WriteString(string(m.HTML))
	default:
		// A ChatLive implementation that has no markup pipeline to hand
		// (main.go's chatAdapter, over raw chat.Tail) still shows the
		// message, plainly escaped, rather than an empty row.
		b.WriteString(template.HTMLEscapeString(m.Text))
	}
	if m.Edited {
		b.WriteString(` <small class="tl-meta-inline">(edited)</small>`)
	}
	b.WriteString(string(chatActionsHTML(m, repo, viewer, canDeleteAny)))
	b.WriteString("</div>")
	return template.HTML(b.String())
}

// chatActionsHTML is the row's action row: reply, its own number, the
// replies it has, and — on your own messages — edit and delete. Small,
// muted, and (where the browser has a pointer) shown only while the row
// is pointed at or focused, which is the CSS's job.
//
// The edit control is a <details>: it opens with no script, which is
// why it is not a signal toggle. Delete is a form; the confirmation is
// an attribute that a browser without Datastar simply ignores, so the
// control still works there — it just does not ask twice.
func chatActionsHTML(m ChatMessage, repo, viewer string, canDeleteAny bool) template.HTML {
	var b strings.Builder
	link := "/r/" + url.PathEscape(repo) + "/chat/" + strconv.FormatUint(m.Seq, 10)
	// A div for the same parsing reason the row itself is one: it holds
	// a <details> and a <form>, which are flow content.
	b.WriteString(`<div class="chat-toolbar">`)
	own := viewer != "" && viewer == m.User
	if !m.Deleted && m.Kind == "msg" && viewer != "" {
		fmt.Fprintf(&b, `<a class="chat-act chatreplyto" href="%s">reply</a>`, link)
	}
	fmt.Fprintf(&b, `<a class="chat-act chatpermalink" href="%s">#%d</a>`, link, m.Seq)
	if m.Replies > 0 {
		fmt.Fprintf(&b, `<a class="chat-act chatreplies" data-replies="%d" href="%s">%d %s</a>`,
			m.Replies, link, m.Replies,
			map[bool]string{true: "reply", false: "replies"}[m.Replies == 1])
	}
	if !m.Deleted && m.Kind == "msg" && viewer != "" && (own || canDeleteAny) {
		if own {
			fmt.Fprintf(&b, `<details class="chatedit"><summary class="chat-act">edit</summary>`+
				`<form method="post" action="/r/%s/chat/%d/edit">`+
				`<textarea name="text" rows="2" required maxlength="4096">%s</textarea>`+
				`<button type="submit">save</button></form></details>`,
				url.PathEscape(repo), m.Seq, template.HTMLEscapeString(m.Text))
		}
		fmt.Fprintf(&b, `<form method="post" action="/r/%s/chat/%d/delete" class="chatdelete"`+
			` data-on:submit="!confirm('Delete this message?') &amp;&amp; evt.preventDefault()">`+
			`<button type="submit" class="chat-act">delete</button></form>`,
			url.PathEscape(repo), m.Seq)
	}
	b.WriteString(`</div>`)
	return template.HTML(b.String())
}

// sparkSVG draws a thread's activity levels (0-4) as a tiny bar-run —
// conversation SHAPE at a glance: a flare-and-die support question and
// a slow-burn RFC stop looking alike.
func sparkSVG(levels []int) template.HTML {
	if len(levels) == 0 {
		return ""
	}
	var b strings.Builder
	w := len(levels) * 3
	fmt.Fprintf(&b, `<svg class="ft-spark" viewBox="0 0 %d 10" width="%d" height="10" aria-hidden="true">`, w, w)
	for i, l := range levels {
		h := l * 2
		if h == 0 {
			h = 1
		}
		fmt.Fprintf(&b, `<rect x="%d" y="%d" width="2" height="%d" rx="0.5" fill="currentColor" fill-opacity="%s"/>`,
			i*3, 10-h, h, map[bool]string{true: "0.9", false: "0.25"}[l > 0])
	}
	b.WriteString(`</svg>`)
	return template.HTML(b.String())
}

// capsPanelFor builds the settings editor's model. Returns nil when
// the forge has no caps administration plane — the section then simply
// does not render.
// protectPanel is the settings page's view of RFC 0007: the rules as
// stored, plus one blank row so a new rule has somewhere to go.
type protectPanel struct {
	Rules []protectRule
	// Blank is the index of the empty row, for the form's field names.
	Blank int
}

type protectRule struct {
	Branch   string
	Owners   string // space-separated, as typed
	Checks   string // required check names, space-separated (RFC 0009)
	Premerge bool   // test the merged tree, not the tip
}

// protectPanelFor is nil when the forge has no policy store — the
// section is not drawn rather than drawn empty — and never nil when it
// does, because an empty list IS the ordinary state and the page has
// to offer the first row.
func protectPanelFor(p Protect, repo string) *protectPanel {
	if p == nil {
		return nil
	}
	rules, err := p.Protections(repo)
	if err != nil {
		return nil
	}
	out := &protectPanel{}
	byBranch := map[string]int{}
	for _, r := range rules {
		byBranch[r.Branch] = len(out.Rules)
		out.Rules = append(out.Rules, protectRule{Branch: r.Branch, Owners: strings.Join(r.Owners, " ")})
	}
	// RFC 0009: required checks share the table — same branches, their
	// own storage, so owners and checks blank independently.
	if ck, ok := p.(ChecksRules); ok {
		if crs, err := ck.CheckRules(repo); err == nil {
			for _, cr := range crs {
				if i, seen := byBranch[cr.Branch]; seen {
					out.Rules[i].Checks = strings.Join(cr.Checks, " ")
					out.Rules[i].Premerge = cr.Mode == "premerge"
				} else {
					out.Rules = append(out.Rules, protectRule{Branch: cr.Branch,
						Checks: strings.Join(cr.Checks, " "), Premerge: cr.Mode == "premerge"})
				}
			}
		}
	}
	out.Blank = len(out.Rules)
	return out
}

// ChecksRules is the settings page's read seam for RFC 0009 rules.
type ChecksRules interface {
	CheckRules(repo string) ([]oltp.CheckRule, error)
}

// CITagsAdmin is the verdict-tags setting's seam (RFC 0009).
type CITagsAdmin interface {
	CITagsMode(repo string) string
	SetCITagsMode(repo, mode string) error
}

// ciTagsModeOf reads the setting for the page; "" when the plane
// cannot answer, which hides the block.
func ciTagsModeOf(caps Caps, repo string) string {
	adm, ok := caps.(CITagsAdmin)
	if !ok {
		return ""
	}
	if m := adm.CITagsMode(repo); m != "" {
		return m
	}
	return "default"
}

// ChecksAdmin writes them.
type ChecksAdmin interface {
	SetCheckRule(repo, branch string, checks []string, mode string) error
}

func capsPanelFor(caps Caps, repo string) *capsPanel {
	admin, ok := caps.(CapsAdmin)
	if !ok || admin == nil {
		return nil
	}
	notes := map[string]string{
		"nobody":    "every visitor, no session",
		"anonymous": "any signed-in account",
		"reader":    "holders of u",
		"developer": "holders of v",
	}
	p := &capsPanel{}
	for _, cat := range []string{"nobody", "anonymous", "reader", "developer"} {
		cs := admin.CategoryCaps(repo, cat)
		p.Categories = append(p.Categories, capRow{
			Name: cat, Caps: cs, Note: notes[cat], Decoded: strings.Join(oltp.Decode(cs), ", "),
		})
	}
	holders, err := admin.CapHolders(repo)
	if err != nil {
		return p
	}
	for _, h := range holders {
		row := capRow{Name: h.Account, Caps: h.Caps}
		if c := caps.CapsOf(h.Account, repo); c != nil {
			row.Effective = fmt.Sprint(c)
		}
		p.Accounts = append(p.Accounts, row)
	}
	return p
}

// capsPanel drives the settings page's capability editor: the four
// fossil categories and every account holding explicit caps here.
type capsPanel struct {
	Categories []capRow
	Accounts   []capRow
}

type capRow struct {
	Name      string
	Caps      string
	Note      string
	Effective string
	Decoded   string // what the string grants, in words (RFC 0008)
}

// rosterPanel is the People section (RFC 0008): one row per person
// holding a role here, read as a role plus the ways they differ from
// it, with the sentence of what they can do.
type rosterPanel struct {
	Rows    []rosterRow
	Presets []oltp.Preset
}

type rosterRow struct {
	Name     string
	Role     string
	Exact    bool
	Plus     []string
	Minus    []string
	Owns     []string // protected branches this person owns (RFC 0007)
	Sentence string
	Caps     string
}

// personEditor is the per-person page: the same reading as a roster
// row, plus every ability as a checkbox and the string itself.
type personEditor struct {
	Name, Repo     string
	Caps           string // stored
	Effective      string
	Role           string
	Exact          bool
	Plus, Minus    []string
	Sentence       string
	Owns           []string
	Groups         []abilityGroup
	Presets        []oltp.Preset
	CheckedLetters string // what the checkboxes said when rendered
	Changed, Warn  string
	Refused        string
	Preview        string            // sentence for the candidate's effective set
	Live           bool              // Datastar is enhancing this render
	On             template.HTMLAttr // data-on for the role/ability controls
	OnRaw          template.HTMLAttr // data-on for the string input
}

type abilityGroup struct {
	Name      string
	Abilities []abilityBox
}

type abilityBox struct {
	Sentence string
	Letters  string
	Checked  bool // held by the stored string
	Category bool // not stored, but the categories grant it anyway
	Advanced bool
}

// visibilityPanel is Settings' first question (RFC 0008 §IA): who can
// see this. Three presets and Custom, which shows the strings decoded.
type visibilityPanel struct {
	Current   string
	Options   []oltp.Visibility
	Nobody    string
	Anonymous string
	NobodyCan []string
	AnonCan   []string
	Fleet     string // what a new repository starts as
	Refused   string
}

func visibilityFor(caps Caps, repo string) *visibilityPanel {
	admin, ok := caps.(CapsAdmin)
	if !ok || admin == nil {
		return nil
	}
	n, a := admin.CategoryCaps(repo, "nobody"), admin.CategoryCaps(repo, "anonymous")
	return &visibilityPanel{Current: oltp.VisibilityOf(n, a), Options: oltp.Visibilities,
		Nobody: n, Anonymous: a, NobodyCan: oltp.Decode(n), AnonCan: oltp.Decode(oltp.Closure(n + a)),
		Fleet: oltp.VisibilityOf(admin.CategoryCaps("", "nobody"), admin.CategoryCaps("", "anonymous"))}
}

// workersOf lists the engine's connected workers; nil engine, none.
func workersOf(e EngineViews) []ci.Worker {
	if e == nil {
		return nil
	}
	ws, err := e.Workers()
	if err != nil {
		return nil
	}
	return ws
}

// ciTokenPanel lists a repository's reporter tokens (RFC 0009).
type ciTokenPanel struct {
	Tokens []struct {
		Hash    string `json:"hash"`
		Label   string `json:"label"`
		Created string `json:"created"`
	} `json:"tokens"`
}

func ciTokenPanelFor(r *ops.Registry, req *http.Request, repo string) *ciTokenPanel {
	out, err := invoke(req.Context(), r, "ci.token.list", url.Values{"repo": {repo}})
	if err != nil {
		return nil
	}
	var p ciTokenPanel
	remarshal(out, &p)
	return &p
}

// fossilPanel is rung 8's Advanced surface: the store's fossil
// settings, editable, versionable ones flagged — or, while zit refuses
// -R on a bare store (zit#153), the note that says so. Read through
// the settings.list op so the web layer never touches the store.
type fossilPanel struct {
	Supported bool
	Note      string
	Rows      []fossilRow
}

type fossilRow struct {
	Name        string
	Value       string
	Versionable bool
}

func fossilPanelFor(r *ops.Registry, req *http.Request, repo string) *fossilPanel {
	out, err := invoke(req.Context(), r, "settings.list", url.Values{"repo": {repo}})
	if err != nil {
		return nil
	}
	var v struct {
		Supported bool   `json:"supported"`
		Note      string `json:"note"`
		Settings  []struct {
			Name        string `json:"name"`
			Value       string `json:"value"`
			Versionable bool   `json:"versionable"`
		} `json:"settings"`
	}
	remarshal(out, &v)
	p := &fossilPanel{Supported: v.Supported, Note: v.Note}
	for _, st := range v.Settings {
		p.Rows = append(p.Rows, fossilRow{Name: st.Name, Value: st.Value, Versionable: st.Versionable})
	}
	return p
}

// takePrivatePanel lists who loses access and offers each a role —
// fossil's own warning, built in.
type takePrivatePanel struct {
	Names   []string
	Presets []oltp.Preset
}

// whoLosesAccess is the take-private list: the plane's own answer when
// it has one, else every account holding no string here.
func whoLosesAccess(caps Caps, repo string) []string {
	if r, ok := caps.(Reach); ok {
		names, _ := r.ReachOnlyByCategory(repo)
		return names
	}
	admin, ok := caps.(CapsAdmin)
	if !ok {
		return nil
	}
	holders, _ := admin.CapHolders(repo)
	var out []string
	for _, h := range holders {
		if h.Caps == "" && !caps.CapsOf(h.Account, repo).HasAny("s") {
			out = append(out, h.Account)
		}
	}
	return out
}

func sentencesOf(as []oltp.Ability) []string {
	var out []string
	for _, a := range as {
		out = append(out, a.Sentence)
	}
	return out
}

// ownedBy lists the protected branches whose owners include name.
func ownedBy(p *protectPanel, name string) []string {
	if p == nil {
		return nil
	}
	var out []string
	for _, r := range p.Rules {
		for _, o := range strings.Fields(r.Owners) {
			if o == name {
				out = append(out, r.Branch)
			}
		}
	}
	return out
}

func rosterFor(caps Caps, prot *protectPanel, repo string) *rosterPanel {
	admin, ok := caps.(CapsAdmin)
	if !ok || admin == nil {
		return nil
	}
	p := &rosterPanel{Presets: oltp.Presets}
	holders, err := admin.CapHolders(repo)
	if err != nil {
		return p
	}
	for _, h := range holders {
		eff := ""
		if c := caps.CapsOf(h.Account, repo); c != nil {
			eff = fmt.Sprint(c)
		}
		site := strings.ContainsRune(eff, 's')
		if h.Caps == "" && !site {
			continue
		}
		rd := oltp.Infer(h.Caps)
		row := rosterRow{Name: h.Account, Role: rd.Role, Exact: rd.Exact, Caps: h.Caps,
			Plus: sentencesOf(rd.Plus), Minus: sentencesOf(rd.Minus),
			Owns: ownedBy(prot, h.Account), Sentence: oltp.Explain(h.Account, oltp.CapSet(eff))}
		if site && h.Caps == "" {
			row.Role, row.Exact = "Site admin", true
		}
		p.Rows = append(p.Rows, row)
	}
	return p
}

// editorFor builds the per-person page for the account's stored string;
// false when no such account.
func editorFor(caps Caps, prot *protectPanel, repo, name string) (*personEditor, bool) {
	stored, found := storedCaps(caps, repo, name)
	if !found {
		return nil, false
	}
	return buildEditor(caps, prot, repo, name, stored), true
}

// storedCaps reads one account's stored string, reporting whether the
// account exists on this repository at all.
func storedCaps(caps Caps, repo, name string) (string, bool) {
	admin, ok := caps.(CapsAdmin)
	if !ok || admin == nil {
		return "", false
	}
	holders, err := admin.CapHolders(repo)
	if err != nil {
		return "", false
	}
	for _, h := range holders {
		if h.Account == name {
			return h.Caps, true
		}
	}
	return "", false
}

// buildEditor renders the editor as if caps were the account's string:
// the same function the live frag calls with a candidate, so the page
// and the preview never disagree about what a string means.
func buildEditor(caps Caps, prot *protectPanel, repo, name, capsStr string) *personEditor {
	eff := ""
	if w, ok := caps.(CapsWhatIf); ok {
		eff = fmt.Sprint(w.EffectiveWith(name, repo, capsStr))
	} else if c := caps.CapsOf(name, repo); c != nil {
		eff = fmt.Sprint(c)
	}
	rd := oltp.Infer(capsStr)
	ed := &personEditor{Name: name, Repo: repo, Caps: capsStr, Effective: eff,
		Role: rd.Role, Exact: rd.Exact && capsStr != "", Plus: sentencesOf(rd.Plus), Minus: sentencesOf(rd.Minus),
		Sentence: oltp.Explain(name, oltp.CapSet(eff)), Owns: ownedBy(prot, name), Presets: oltp.Presets}
	ed.Preview = ed.Sentence
	held, effSet := oltp.Closure(capsStr), oltp.CapSet(eff)
	var checked strings.Builder
	byGroup := map[string]int{}
	for _, a := range oltp.Abilities {
		box := abilityBox{Sentence: a.Sentence, Letters: a.Letters, Advanced: a.Advanced}
		box.Checked = holdsAll(held, a.Letters)
		if box.Checked {
			checked.WriteString(a.Letters)
		} else {
			box.Category = holdsAll(string(effSet), a.Letters)
		}
		i, seen := byGroup[a.Group]
		if !seen {
			byGroup[a.Group] = len(ed.Groups)
			ed.Groups = append(ed.Groups, abilityGroup{Name: a.Group})
			i = len(ed.Groups) - 1
		}
		ed.Groups[i].Abilities = append(ed.Groups[i].Abilities, box)
	}
	ed.CheckedLetters = checked.String()
	return ed
}

// setVisibility writes a preset's two strings through the plane, so
// the same seam that saves a typed string saves a chosen one.
func setVisibility(admin CapsAdmin, repo, name string) error {
	for _, v := range oltp.Visibilities {
		if v.Name == name {
			if err := admin.SetCategoryCaps(repo, "nobody", v.Nobody); err != nil {
				return err
			}
			return admin.SetCategoryCaps(repo, "anonymous", v.Anonymous)
		}
	}
	return fmt.Errorf("no visibility called %q", name)
}

// liveEditor arms an editor for Datastar: every control re-requests
// the preview frag, debounced, and the frag morphs #person-live. The
// baseline needs none of it — these attributes are inert without the
// script (RFC 0001).
func liveEditor(ed *personEditor, caps Caps, repo, name string) {
	if _, ok := caps.(CapsWhatIf); !ok {
		return // no dry-run path: leave the page as pure forms
	}
	ed.Live = true
	get := "@get('/r/" + repo + "/people/" + url.PathEscape(name) + "/preview.frag', {contentType: 'form'})"
	ed.On = template.HTMLAttr(` data-on:change="` + get + `"`)
	ed.OnRaw = template.HTMLAttr(` data-on:input__debounce.400ms="` + get + `"`)
}

func holdsAll(set, letters string) bool {
	for _, r := range letters {
		if !strings.ContainsRune(set, r) {
			return false
		}
	}
	return true
}

// nextCaps reads the editor form as the string to store. The string
// input wins when edited; else a changed role radio replaces
// everything with the preset; else the checkboxes are the string —
// unchanged boxes keep the stored string byte for byte, so a save
// that changes nothing writes nothing new.
func nextCaps(f url.Values, old string) string {
	if f.Get("revoke") != "" {
		return ""
	}
	raw := strings.Join(strings.Fields(f.Get("raw")), "")
	if raw != strings.Join(strings.Fields(f.Get("was-raw")), "") {
		return raw
	}
	if role := f.Get("role"); role != f.Get("was-role") && role != "Custom" {
		for _, p := range oltp.Presets {
			if p.Name == role {
				return p.Caps
			}
		}
	}
	union := oltp.Minimal(strings.Join(f["ab"], ""))
	if oltp.Closure(union) == oltp.Closure(f.Get("was-ab")) {
		return old
	}
	return union
}

// stagedRow is one held submission in the moderation queue.
type stagedRow struct {
	ID       int64   `json:"id"`
	Kind     string  `json:"kind"`
	Title    string  `json:"title"`
	Body     string  `json:"body"`
	Author   string  `json:"author"`
	At       string  `json:"at"`
	AIAction string  `json:"aiAction"`
	AIScore  float64 `json:"aiScore"`
	AIReason string  `json:"aiReason"`
}

// modRow is one public moderation-log line.
type modRow struct {
	At     string `json:"at"`
	Actor  string `json:"actor"`
	Action string `json:"action"`
	Target string `json:"target"`
	Reason string `json:"reason"`
}

// attachmentRow is one live attachment on a ticket. Fossil keeps the
// content as its own artifact, which the download route serves by hash.
// CIBadge renders a check-in's verdict for a listing. Empty for a
// check-in with no verdict: a repository without CI, or a check-in made
// before its pipeline landed, should show nothing at all rather than a
// neutral badge that reads as a result.
func ciBadge(verdict string) template.HTML {
	switch verdict {
	case "ci-pass":
		return template.HTML(`<span class="tl-badge ci-pass" title="CI passed">pass</span>`)
	case "ci-fail":
		return template.HTML(`<span class="tl-badge ci-fail" title="CI failed">fail</span>`)
	}
	return ""
}

// fileChange is one check-in that touched a file.
type fileChange struct {
	Hash    string `json:"hash"`
	Date    string `json:"date"`
	User    string `json:"user"`
	Comment string `json:"comment"`
}

// ciRunRow is one CI run for the display.
type ciRunRow struct {
	URL       string `json:"url"`
	Pair      string `json:"pair"`
	RunID     string `json:"runId"`
	Checkin   string `json:"checkin"`
	Workflow  string `json:"workflow"`
	Pipeline  string `json:"pipeline"`
	Status    string `json:"status"`
	Started   string `json:"started"`
	Completed string `json:"completed"`
	Branch    string `json:"branch"`
	Comment   string `json:"comment"`
	User      string `json:"user"`
	// Duration, FailStep and FailLine are computed for the list view:
	// how long it took, and — for a red row — which step broke and the
	// first line that says so, read from the drained record.
	Duration string `json:"-"`
	FailStep string `json:"-"`
	FailLine string `json:"-"`
	// The tail rides only on the landing's decision card, and only on a
	// red row: the failed step's last chunks, so the reader learns WHY
	// without leaving the decision. Filled web-side, never over JSON.
	TailStep string        `json:"-"`
	Tail     []ci.LogChunk `json:"-"`
	TailNote string        `json:"-"`
}

// ciRunView is the run page's data: the forge's row, the engine's
// detail, and the logs — each degrading in words when absent.
type ciRunView struct {
	Running    bool
	Row        ciRunRow
	Duration   string
	EngineGone string
	Steps      []ciStepView
	Repro      string
	Anchor     string
}

type ciStepView struct {
	ID       string
	Status   string
	State    string // pass | fail | wait
	Duration string
	Attempts int
	Error    string
	Open     bool
	Chunks   []ci.LogChunk
	LogNote  string
}

// buildRunView assembles the page; every absence is a sentence. The
// forge's drained record answers first — it outlives the engine's hot
// lane — and the engine fills in for runs still warm.
func buildRunView(engine EngineViews, logs LogStore, repo, cloneURL string, row ciRunRow) *ciRunView {
	a := row.RunID
	if len(a) > 8 {
		a = a[:8]
	}
	v := &ciRunView{Row: row, Anchor: a, Running: ciStateOf(row.Status) == "running"}
	if engine == nil {
		v.EngineGone = "No CI engine is configured; this is the forge's record of the run."
		return v
	}
	run, err := engine.RunDetail(row.RunID)
	if err != nil {
		// The drained record outlives the engine's memory of the run —
		// that is what retention is FOR. Steps rebuild from the chunks;
		// the row's own status colours the last one.
		if logs != nil {
			if all, ok := logs.DrainedLogs(repo, row.RunID); ok {
				bySteps := map[string][]ci.LogChunk{}
				var order []string
				for _, c := range all {
					if _, seen := bySteps[c.Step]; !seen {
						order = append(order, c.Step)
					}
					bySteps[c.Step] = append(bySteps[c.Step], c)
				}
				failRow := ciStateOf(row.Status) == "fail"
				sawFail := false
				for _, id := range order {
					sv := ciStepView{ID: id, Status: "completed", State: "pass", Chunks: bySteps[id]}
					for _, c := range bySteps[id] {
						if c.Stream == "marker" && c.Data == "failed" {
							sv.State, sv.Open, sv.Status = "fail", true, "failed"
							sawFail = true
						}
					}
					v.Steps = append(v.Steps, sv)
				}
				// A failed row with no marker: the last step carries it.
				if failRow && !sawFail && len(v.Steps) > 0 {
					last := &v.Steps[len(v.Steps)-1]
					last.State, last.Open, last.Status = "fail", true, "failed"
				}
				if failRow && cloneURL != "" {
					v.Repro = "zit clone " + cloneURL + " work && cd work\nzit open " + row.Checkin + "\n# run the failing task against this tree"
				}
				return v
			}
		}
		v.EngineGone = "The engine could not be asked about this run: " + err.Error()
		return v
	}
	if run.CreatedAt != "" && run.CompletedAt != "" {
		v.Duration = durationBetween(run.CreatedAt, run.CompletedAt)
	}
	ids := make([]string, 0, len(run.Steps))
	for id := range run.Steps {
		ids = append(ids, id)
	}
	sort.Slice(ids, func(i, j int) bool {
		x, y := run.Steps[ids[i]], run.Steps[ids[j]]
		// A step that never dispatched has no place in the story's
		// middle: executed steps first, in dispatch order.
		if (x.StartedAt == "") != (y.StartedAt == "") {
			return x.StartedAt != ""
		}
		if x.StartedAt != y.StartedAt {
			return x.StartedAt < y.StartedAt
		}
		return ids[i] < ids[j]
	})
	var drained map[string][]ci.LogChunk
	if logs != nil {
		if all, ok := logs.DrainedLogs(repo, row.RunID); ok {
			drained = map[string][]ci.LogChunk{}
			for _, c := range all {
				drained[c.Step] = append(drained[c.Step], c)
			}
		}
	}
	anyFail := false
	noLogs := false
	for _, id := range ids {
		st := run.Steps[id]
		sv := ciStepView{ID: id, Status: st.Status, Attempts: st.Attempts, Error: st.Error}
		switch {
		case st.Status == "completed" || st.Status == "succeeded" || st.Status == "success":
			sv.State = "pass"
		case st.Status == "failed" || st.Status == "error":
			sv.State, sv.Open, anyFail = "fail", true, true
		case st.Status == "cancelled" || st.Status == "canceled":
			sv.State = "cancelled" // stopped, not broken: nothing to reproduce
		default:
			sv.State, sv.Open = "wait", true
			if !v.Running {
				// The run is over and this step never dispatched —
				// an earlier step's failure ended the workflow.
				sv.State, sv.Open, sv.Status = "notrun", false, "not run"
				sv.LogNote = "Not dispatched — the run ended first."
			}
		}
		if st.StartedAt != "" && st.CompletedAt != "" {
			sv.Duration = durationBetween(st.StartedAt, st.CompletedAt)
		}
		if sv.State == "notrun" {
			// Never dispatched: there are no logs to ask anyone for,
			// and the note already says why.
			v.Steps = append(v.Steps, sv)
			continue
		}
		// One "no logs yet" answers for every step: an engine that
		// predates the lane is not asked N more times per render.
		if drained != nil {
			sv.Chunks = drained[id]
			if len(sv.Chunks) == 0 {
				sv.LogNote = "no output recorded"
			}
			v.Steps = append(v.Steps, sv)
			continue
		}
		if noLogs {
			sv.LogNote = "The engine does not serve logs yet (dagnats#624); status only."
		} else {
			chunks, lerr := engine.StepLogs(row.RunID, id, 0, sv.State == "fail")
			switch {
			case errors.Is(lerr, ci.ErrNoLogs):
				noLogs = true
				sv.LogNote = "The engine does not serve logs yet (dagnats#624); status only."
			case lerr != nil:
				sv.LogNote = "Logs could not be read: " + lerr.Error()
			default:
				sv.Chunks = chunks
			}
		}
		v.Steps = append(v.Steps, sv)
	}
	if anyFail {
		clone, _ := run.Input["cloneUrl"].(string)
		checkin, _ := run.Input["checkin"].(string)
		if clone != "" && checkin != "" {
			v.Repro = "zit clone " + clone + " work && cd work\nzit open " + checkin + "\n# run the failing task against this tree"
		}
	}
	return v
}

// failTailMax bounds the log excerpt a red check inlines on the
// decision card. Enough to read the failure; the run page has it all.
const failTailMax = 40

// failTail finds a failed run's failing step and its last chunks —
// drained record first (it outlives the engine's hot lane), engine
// second — for the landing's checks panel. Absences come back as a
// note in words, never as a silently bare row.
func failTail(eng EngineViews, logs LogStore, repo, runID string) (step string, tail []ci.LogChunk, note string) {
	if logs != nil {
		if all, ok := logs.DrainedLogs(repo, runID); ok {
			for _, c := range all {
				if c.Stream == "marker" && c.Data == "failed" {
					step = c.Step
				}
			}
			if step != "" {
				for _, c := range all {
					if c.Step == step {
						tail = append(tail, c)
					}
				}
				return step, capTail(tail), ""
			}
		}
	}
	if eng == nil {
		return "", nil, ""
	}
	run, err := eng.RunDetail(runID)
	if err != nil {
		return "", nil, "The engine could not be asked why: " + err.Error()
	}
	for id, st := range run.Steps {
		if st.Status == "failed" || st.Status == "error" {
			step = id
		}
	}
	if step == "" {
		return "", nil, ""
	}
	chunks, err := eng.StepLogs(runID, step, 0, true)
	switch {
	case errors.Is(err, ci.ErrNoLogs):
		return step, nil, "The engine does not serve logs yet (dagnats#624); the run page has the step's status."
	case err != nil:
		return step, nil, "Logs could not be read: " + err.Error()
	}
	return step, capTail(chunks), ""
}

// capTail keeps the last failTailMax chunks.
func capTail(chunks []ci.LogChunk) []ci.LogChunk {
	if len(chunks) > failTailMax {
		return chunks[len(chunks)-failTailMax:]
	}
	return chunks
}

// ciBypassRow is one tripwire finding on the CI page.
type ciBypassRow struct {
	Branch  string `json:"branch"`
	Checkin string `json:"checkin"`
	Seen    string `json:"seen"`
}

// ciHealthRow is one pipeline's line in the health strip: the tip's
// state on the main branch, and small honest numbers over recent runs.
type ciHealthRow struct {
	Pipeline    string
	TipState    string // pass | fail | running | cancelled | ""
	TipCheckin  string
	TipFailStep string
	PassPct     int // over terminal runs in the window
	Median      string
	N           int
}

// failSummary reads a red run's drained record for the step that broke
// and the first line that says so. No drained record is simply no
// summary — the run page still answers.
func failSummary(logs LogStore, repo, runID string) (step, line string) {
	if logs == nil {
		return "", ""
	}
	all, ok := logs.DrainedLogs(repo, runID)
	if !ok {
		return "", ""
	}
	for _, c := range all {
		if c.Stream == "marker" && c.Data == "failed" {
			step = c.Step
		}
	}
	if step == "" {
		return "", ""
	}
	for _, c := range all {
		if c.Step != step {
			continue
		}
		for _, l := range strings.Split(c.Data, "\n") {
			t := strings.TrimSpace(l)
			if strings.HasPrefix(t, "--- FAIL") || strings.HasPrefix(t, "FAIL") ||
				strings.Contains(t, "error") || strings.Contains(t, "Error") {
				return step, t
			}
		}
	}
	for _, c := range all {
		if c.Step == step && c.Stream == "err" {
			if t := strings.TrimSpace(strings.SplitN(c.Data, "\n", 2)[0]); t != "" {
				return step, t
			}
		}
	}
	return step, ""
}

// ciListMaxSummaries bounds drained-record reads per render.
const ciListMaxSummaries = 30

// buildCIList enriches ci.list's rows for the page and computes the
// health strip: filters from the query, durations, red-row summaries,
// facets for the filter controls.
func buildCIList(reg *ops.Registry, logs LogStore, repo string, q url.Values) pageData {
	out, err := invoke(context.Background(), reg, "ci.list", url.Values{"repo": {repo}, "limit": {"200"}})
	data := pageData{Title: "ci", Repo: repo,
		CIState: q.Get("state"), CIBranch: q.Get("branch"), CIPipeline: q.Get("pipeline")}
	if err != nil {
		return data
	}
	var cl struct {
		Runs     []ciRunRow    `json:"runs"`
		Bypasses []ciBypassRow `json:"bypasses"`
	}
	remarshal(out, &cl)
	data.CIBypasses = cl.Bypasses

	// Facets and health come from the WHOLE window; filters narrow only
	// what is listed, or a filtered view would also rewrite the truth.
	branches, pipelines := map[string]bool{}, map[string]bool{}
	byPipe := map[string][]ciRunRow{}
	for i := range cl.Runs {
		r := &cl.Runs[i]
		r.Duration = durationBetween(r.Started, r.Completed)
		branches[r.Branch] = true
		pipelines[r.Pipeline] = true
		byPipe[r.Pipeline] = append(byPipe[r.Pipeline], *r)
	}
	summaries := 0
	for i := range cl.Runs {
		r := &cl.Runs[i]
		if ciStateOf(r.Status) == "fail" && summaries < ciListMaxSummaries {
			r.FailStep, r.FailLine = failSummary(logs, repo, r.RunID)
			summaries++
		}
	}
	for _, b := range sortedKeys(branches) {
		data.CIBranches = append(data.CIBranches, b)
	}
	for _, p := range sortedKeys(pipelines) {
		data.CIPipelines = append(data.CIPipelines, p)
	}
	for _, p := range data.CIPipelines {
		rows := byPipe[p]
		h := ciHealthRow{Pipeline: p}
		for _, r := range rows { // newest first
			if r.Branch == "trunk" && r.Pair == "" {
				h.TipState, h.TipCheckin = ciStateOf(r.Status), r.Checkin
				if h.TipState == "fail" {
					h.TipFailStep, _ = failSummary(logs, repo, r.RunID)
				}
				break
			}
		}
		var pass, term int
		var secs []float64
		for _, r := range rows {
			if term >= 20 {
				break
			}
			switch ciStateOf(r.Status) {
			case "pass":
				pass++
				term++
			case "fail", "cancelled":
				term++
			default:
				continue
			}
			if a, e1 := time.Parse(time.RFC3339, r.Started); e1 == nil {
				if b, e2 := time.Parse(time.RFC3339, r.Completed); e2 == nil && b.After(a) {
					secs = append(secs, b.Sub(a).Seconds())
				}
			}
		}
		if term > 0 {
			h.PassPct, h.N = pass*100/term, term
		}
		if len(secs) > 0 {
			sort.Float64s(secs)
			h.Median = (time.Duration(secs[len(secs)/2]) * time.Second).String()
		}
		data.CIHealth = append(data.CIHealth, h)
	}
	for _, r := range cl.Runs {
		if data.CIState != "" && ciStateOf(r.Status) != data.CIState {
			continue
		}
		if data.CIBranch != "" && r.Branch != data.CIBranch {
			continue
		}
		if data.CIPipeline != "" && r.Pipeline != data.CIPipeline {
			continue
		}
		data.CIRuns = append(data.CIRuns, r)
	}
	return data
}

// sortedKeys is the deterministic order every facet list needs.
func sortedKeys(m map[string]bool) []string {
	out := make([]string, 0, len(m))
	for k := range m {
		if k != "" {
			out = append(out, k)
		}
	}
	sort.Strings(out)
	return out
}

// ciStateOf folds a status to pass|fail|running, as the chips read it.
func ciStateOf(status string) string {
	switch status {
	case "completed", "succeeded", "success":
		return "pass"
	case "failed", "error":
		return "fail"
	case "cancelled", "canceled":
		return "cancelled"
	}
	return "running"
}

// durationBetween renders the human span between two RFC3339 stamps.
func durationBetween(a, b string) string {
	ta, err1 := time.Parse(time.RFC3339, a)
	tb, err2 := time.Parse(time.RFC3339, b)
	if err1 != nil || err2 != nil || tb.Before(ta) {
		return ""
	}
	d := tb.Sub(ta).Round(time.Second)
	if d <= 0 {
		return "" // equal stamps say nothing, not "0s"
	}
	return d.String()
}

// treeRow is one entry of a directory listing.
type treeRow struct {
	Name        string `json:"name"`
	Path        string `json:"path"`
	Dir         bool   `json:"dir"`
	Blob        string `json:"blob"`
	Files       int    `json:"files"`
	Size        int64  `json:"size"`
	Exec        bool   `json:"exec"`
	Link        bool   `json:"link"`
	Binary      bool   `json:"binary"`
	LastHash    string `json:"lastHash"`
	LastDate    string `json:"lastDate"`
	LastComment string `json:"lastComment"`
}

// Human renders a size the way a file listing should: bytes are noise
// past a few thousand, and the reader wants magnitude.
func (t treeRow) Human() string {
	const unit = 1024
	if t.Size < unit {
		return fmt.Sprintf("%d B", t.Size)
	}
	div, exp := int64(unit), 0
	for n := t.Size / unit; n >= unit; n /= unit {
		div *= unit
		exp++
	}
	return fmt.Sprintf("%.1f %cB", float64(t.Size)/float64(div), "KMGT"[exp])
}

// openBranches drops closed branches from a selector — a hundred
// finished work branches bury the four live ones — but never the one
// the reader is currently on: a closed branch is still browsable, and
// a selector that cannot show its own state is lying.
func openBranches(rows []branchRow, current string) []branchRow {
	out := rows[:0:0]
	for _, b := range rows {
		if !b.Closed || b.Name == current || b.Tip == current {
			out = append(out, b)
		}
	}
	return out
}

// labelBranches fills each row's selector label. zit allows two
// branches to share a name, so a name is not always enough to tell the
// options apart — but it almost always is, and appending a hash to every
// one made the control as wide as its widest hash for no gain. The hash
// appears only on the names that actually repeat.
func labelBranches(rows []branchRow) {
	seen := map[string]int{}
	for _, b := range rows {
		seen[b.Name]++
	}
	for i, b := range rows {
		rows[i].Label = b.Name
		if seen[b.Name] > 1 {
			rows[i].Label = b.Name + " · " + b.Tip[:min(10, len(b.Tip))]
		}
	}
}

// localRef is the Referer reduced to a path on this origin, or "/". A
// Referer is attacker-controllable, so only its path and query survive;
// anything naming another host, or a protocol-relative "//evil" that a
// browser would read as one, becomes the home page.
func localRef(req *http.Request) string {
	ref := req.Referer()
	if ref == "" {
		return "/"
	}
	u, err := url.Parse(ref)
	if err != nil || u.Path == "" || !strings.HasPrefix(u.Path, "/") ||
		strings.HasPrefix(u.Path, "//") {
		return "/"
	}
	out := u.Path
	if u.RawQuery != "" {
		out += "?" + u.RawQuery
	}
	return out
}

// themeCookie holds an explicit colour choice. Absent means "follow the
// system", which is the default and stores nothing — a reader who never
// touches the control is never given a cookie.
const themeCookie = "theme"

// themeCycle is the order the switcher moves through. Three states, not
// two: with only light and dark, a reader who wanted "follow my phone"
// back would have no way to ask for it.
var themeCycle = []string{"", "light", "dark"}

// themeState describes one point in the cycle for the template.
func themeState(theme string) (next, icon, name string) {
	i := slices.Index(themeCycle, theme)
	if i < 0 {
		i = 0
	}
	next = themeCycle[(i+1)%len(themeCycle)]
	switch theme {
	case "light":
		return next, "sun", "light"
	case "dark":
		return next, "moon", "dark"
	}
	return next, "auto", "system"
}

// searchScopeName is searchContext's inverse: the word for a kind, used
// where the kind is already known and the section is not.
func searchScopeName(kind string) (string, string) {
	for _, section := range []string{"timeline", "wiki", "ticket", "forum", "technote"} {
		if k, scope := searchContext(section); k == kind && kind != "" {
			return k, scope
		}
	}
	return "", "everything"
}

// searchScopes are the choices offered on the results page, in the
// order the nav uses so the two surfaces agree.
var searchScopes = []struct{ Kind, Label string }{
	{"", "everything"}, {"checkin", "check-ins"}, {"doc", "docs"}, {"file", "files"},
	{"wiki", "wiki"}, {"ticket", "tickets"}, {"forum", "forum"}, {"technote", "technotes"},
}

// searchContext maps a nav section to the search kind it means and the
// word for it. A section with nothing indexed — files, ci, chat — falls
// through to searching everything rather than to an empty scope that
// would silently find nothing.
func searchContext(section string) (kind, scope string) {
	switch section {
	case "docs":
		return "doc", "docs"
	case "tree":
		return "file", "files"
	case "timeline":
		return "checkin", "check-ins"
	case "wiki":
		return "wiki", "wiki"
	case "ticket":
		return "ticket", "tickets"
	case "forum":
		return "forum", "forum"
	case "technote":
		return "technote", "notes"
	}
	return "", "everything"
}

// matchesRepo is the fleet page's filter: a case-insensitive substring
// of the store name or, for a mirror, its upstream.
func matchesRepo(q string, fields ...string) bool {
	if q == "" {
		return true
	}
	q = strings.ToLower(q)
	for _, f := range fields {
		if strings.Contains(strings.ToLower(f), q) {
			return true
		}
	}
	return false
}

// tagRow is one release tag for the ref switcher.
type tagRow struct {
	Name string `json:"name"`
	Tip  string `json:"tip"`
	Date string `json:"date"`
}

// branchRow is one branch for the selector. Tip is carried because zit
// allows two branches to share a name, so the name alone cannot select.
type branchRow struct {
	Name   string `json:"name"`
	Tip    string `json:"tip"`
	Date   string `json:"date"`
	Closed bool   `json:"closed"`
	// Label is what the selector shows. Usually just the name: the hash
	// was in every option, which made the control as wide as its widest
	// hash on every repository and told a reader nothing they chose by.
	// It comes back only for a name two branches share, which is the
	// one case where the name alone does not identify the choice.
	Label string `json:"-"`
}

// crumb is one path segment of the breadcrumb trail.
type crumb struct {
	Name string
	Path string
}

type attachmentRow struct {
	Name string `json:"name"`
	Src  string `json:"src"` // content artifact — the download target
	Date string `json:"date"`
	User string `json:"user"`
}

type technoteRow struct {
	Event     string `json:"event"`
	Date      string `json:"date"`
	User      string `json:"user"`
	Comment   string `json:"comment"`
	Excerpt   string `json:"excerpt"`
	Revisions int    `json:"revisions"`
}

type technoteDetail struct {
	Event      string `json:"event"`
	Hash       string `json:"hash"`
	Date       string `json:"date"`
	Edited     string `json:"edited"`
	User       string `json:"user"`
	Comment    string `json:"comment"`
	Revisions  int    `json:"revisions"`
	Historical bool   `json:"historical"`
}

// technoteRev is one row of a note's edit history.
type technoteRev struct {
	Hash    string `json:"hash"`
	Date    string `json:"date"`
	Edited  string `json:"edited"`
	User    string `json:"user"`
	Comment string `json:"comment"`
}

type ticketSummary struct {
	ID         string `json:"id"`
	Title      string `json:"title"`
	Status     string `json:"status"`
	Updated    string `json:"updated"`
	Created    string `json:"created,omitempty"`
	Type       string `json:"type,omitempty"`
	Severity   string `json:"severity,omitempty"`
	Priority   string `json:"priority,omitempty"`
	Subsystem  string `json:"subsystem,omitempty"`
	Resolution string `json:"resolution,omitempty"`
	Author     string `json:"author,omitempty"`
	LastUser   string `json:"lastUser,omitempty"`
	Comments   int    `json:"comments"`
	Refs       int    `json:"refs"` // landings that named this ticket
}

// ticketNav is the tracker header's URL state: which lives are listed,
// which view draws them, how they are ordered, and the board's axes.
// One place builds every link on the page, so switching state keeps the
// view and switching view keeps the state — the axes stay independent,
// which is the whole reason they are separate controls.
type ticketNav struct {
	Repo string
	// Base is the listing this nav addresses, empty for one repository's
	// tracker. The cross-repository listing is the same report machinery
	// pointed at a different path, so every link, facet and page control
	// asks the nav for the path rather than spelling one.
	Base string
	// Awaiting marks the "waiting on you" view. It is carried by every
	// link this nav builds, so switching sort or view stays inside the
	// view the reader chose rather than dumping them in the full list.
	Awaiting bool
	State    string // "" or open | closed | all
	View     string // "" (list) | board
	Sort     string // "" (priority) | recent
	Open     int
	Closed   int
	Group    string
	Lane     string
	// Order names the table view's column order; see index.TicketOrders.
	Order string
	// Title is the query box's free words, matched against titles.
	Title string
	// Offset is the page. Only PageURL sets it: changing ANY other axis
	// returns to the first page, because "filtered to three results,
	// showing rows 101-150" is an empty screen with no cause on it.
	Offset int
	// Report is the filter axes, rebuilt into every link this nav makes.
	// Narrowing to a subsystem and then clicking Closed must show that
	// subsystem's closed tickets, not the whole tracker's: an axis the
	// header silently drops is an axis the reader cannot trust.
	Report url.Values
}

// Filtered reports whether any report axis is set, for the clear link.
func (n ticketNav) Filtered() bool { return len(n.Report) > 0 || n.Title != "" }

// Clear is this view with every report axis dropped and the state, view
// and sort kept: "show me everything again", not "start over".
func (n ticketNav) Clear() string {
	n.Report, n.Title = nil, ""
	return n.URL("", "")
}

// Hidden is what the DROPDOWN form must restate: a GET form replaces
// the whole query string, so anything not carried here is discarded on
// the first dropdown change. The six report axes are deliberately
// absent — that form has a select for each of them already, and
// restating one would submit it twice.
func (n ticketNav) Hidden() []ticketField {
	var out []ticketField
	add := func(k, v string) {
		if v != "" {
			out = append(out, ticketField{Name: k, Value: v})
		}
	}
	if n.State != "open" {
		add("state", n.State)
	}
	add("view", n.View)
	if n.View == "" {
		add("sort", n.Sort)
	}
	if n.View == "table" {
		add("order", n.Order)
	}
	add("title", n.Title)
	return out
}

// ViewFields is the presentation axes alone, for the query box's form.
// That box's own text spells the state, the report and the free words,
// so restating any of them here would send each one twice.
func (n ticketNav) ViewFields() []ticketField {
	var out []ticketField
	for _, f := range n.Hidden() {
		switch f.Name {
		case "view", "sort", "order":
			out = append(out, f)
		}
	}
	return out
}

// Query is this listing spelled as a reader would type it.
func (n ticketNav) Query() string {
	return ticketQueryString(n.State, n.Report, n.Title)
}

// with returns this nav with one axis replaced.
func (n ticketNav) with(axis, value string) ticketNav {
	n.Offset = 0
	switch axis {
	case "state":
		n.State = value
	case "view":
		n.View = value
	case "sort":
		n.Sort = value
	case "order":
		n.Order = value
	}
	return n
}

// params is the query this nav describes, and the ONE place that knows
// which axes a view carries: a board has group and lane, a table has a
// column order, a list has a sort. Building the page's links and its
// .json link from the same function is what keeps the two honest —
// the machine-readable URL is the human one with the view removed.
func (n ticketNav) params() url.Values {
	q := url.Values{}
	if n.Awaiting {
		q.Set("awaiting", "1")
	}
	if n.State != "" && n.State != "open" {
		q.Set("state", n.State)
	}
	if n.View != "" {
		q.Set("view", n.View)
	}
	switch n.View {
	case "board":
		if n.Group != "" {
			q.Set("group", n.Group)
		}
		if n.Lane != "" {
			q.Set("lane", n.Lane)
		}
	case "table":
		if n.Order != "" {
			q.Set("order", n.Order)
		}
	default:
		if n.Sort != "" {
			q.Set("sort", n.Sort)
		}
	}
	for k, vs := range n.Report {
		q[k] = vs
	}
	if n.Title != "" {
		q.Set("title", n.Title)
	}
	if n.Offset > 0 {
		q.Set("offset", strconv.Itoa(n.Offset))
	}
	return q
}

// QueryString is this listing spelled as URL parameters — what a saved
// view stores, so that restoring one is the same page and not an
// approximation of it.
func (n ticketNav) QueryString() string { return n.params().Encode() }

// Facet is this listing narrowed to one value of a report axis — how a
// row's own chip becomes a way to see the rest of its kind.
func (n ticketNav) Facet(axis, value string) string {
	n.Report = cloneValues(n.Report)
	n.Report.Set(axis, value)
	n.Offset = 0
	return n.URL("", "")
}

// Path is where this listing lives — the one place that knows whether
// a control belongs to one tracker or to the cross-repository listing,
// so no form can post itself at a repository that is not there.
func (n ticketNav) Path() string { return n.path() }

func (n ticketNav) path() string {
	if n.Base != "" {
		return n.Base
	}
	return "/r/" + n.Repo + "/ticket"
}

// PageURL is this exact listing at another offset — the only way an
// offset is ever set, so no other control can strand a reader on a page
// that no longer exists.
func (n ticketNav) PageURL(offset int) string {
	if offset < 0 {
		offset = 0
	}
	n.Offset = offset
	q := n.params()
	if len(q) == 0 {
		return n.path()
	}
	return n.path() + "?" + q.Encode()
}

// URL renders this nav with one axis replaced. An axis at its default
// contributes no parameter, so the plain tracker URL stays plain.
func (n ticketNav) URL(axis, value string) string {
	q := n.with(axis, value).params()
	if len(q) == 0 {
		return n.path()
	}
	return n.path() + "?" + q.Encode()
}

// ticketReverse pairs the orders that have an opposite, so clicking the
// column you are already sorted by turns it around — the one thing a
// table header owes a reader. Columns with no pair simply stay put
// rather than pretending to toggle.
var ticketReverse = map[string]string{"updated": "oldest", "oldest": "updated"}

// OrderURL is one column header's link.
func (n ticketNav) OrderURL(key string) string {
	if n.Order == key || (n.Order == "" && key == "updated") {
		if rev, ok := ticketReverse[key]; ok {
			return n.URL("order", rev)
		}
	}
	return n.URL("order", key)
}

// OrderMark is the arrow on the column currently sorted by, if any.
func (n ticketNav) OrderMark(key string) string {
	cur := n.Order
	if cur == "" {
		cur = "updated"
	}
	switch {
	case cur == key:
		return "\u25be" // sorted descending / natural
	case ticketReverse[cur] == key:
		return "\u25b4"
	}
	return ""
}

// Is reports whether an axis currently holds a value, for the "here"
// class. The empty state and "open" are the same state.
func (n ticketNav) Is(axis, value string) bool {
	switch axis {
	case "state":
		cur := n.State
		if cur == "" {
			cur = "open"
		}
		return cur == value
	case "view":
		return n.View == value
	case "sort":
		return n.Sort == value
	}
	return false
}

// ticketChip is one value worth showing on a list row. A chip every row
// carries is not information: the old list printed status, priority and
// severity on all 71 rows, and 68 of them read "Open Medium Important".
// Only fields that DISTINGUISH a ticket earn one, which is why severity
// and priority appear solely in the urgent half of their vocabulary.
type ticketChip struct {
	Text  string
	Class string
	Title string
}

// ticketRow is a list row: the summary plus the two things the template
// should not compute — which glyph names its state, and which of its
// fields are worth a chip.
type ticketRow struct {
	ticketSummary
	// Repo is the tracker this row came from. Every row carries it, so
	// one template serves a repository's tracker and the cross-repository
	// listing without a link that guesses which page it is on.
	Repo  string
	State string // open | review | done
	Chips []ticketChip
}

// Href is the ticket this row stands for.
func (r ticketRow) Href() string { return "/r/" + r.Repo + "/ticket/" + r.ID }

// Glyph names the sprite symbol for this row's state. Fossil paints the
// whole row by status and needs a colour key above the table to explain
// itself; a glyph in the first column says the same thing in the place
// the eye already is, and reads without colour.
func (r ticketRow) Glyph() string {
	switch r.State {
	case "done":
		return "i-tkt-done"
	case "review":
		return "i-auto" // the half-filled disc: started, not finished
	}
	return "i-tkt-open"
}

// urgent reports whether value sits in the leading half of its
// vocabulary — the half that means "look at this". A word the
// vocabulary does not list counts as urgent: an unknown value is
// exactly the kind of thing a reader should see.
func urgent(vocab []string, value string) bool {
	if value == "" {
		return false
	}
	for i, w := range vocab {
		if strings.EqualFold(w, value) {
			return i < len(vocab)/2
		}
	}
	return true
}

// ticketFacet is one value of a browse field with its open count.
type ticketFacet struct {
	Value string `json:"value"`
	Open  int    `json:"open"`
}

// ticketPageSize is how many rows a paged view shows. Smaller than the
// board's bounded fetch: a page you scroll for a minute is not a page.
const ticketPageSize = 50

// pager is the position line under a listing: where the reader
// is, how much there is, and the two ways out. Both ends are rendered
// even when dead, so the control does not move under the cursor
// between pages.
type pager struct {
	From, To, Total int
	Prev, Next      string
	// Steps is the numbered row: which page a reader is on and the ones
	// they can jump to. GitHub's issues pager, and for the reason it
	// uses one — "older" alone never says how much is behind you, and
	// cannot take you to the end.
	Steps []pageStep
}

// pageStep is one entry in a numbered pager: a page to jump to, or the
// gap where pages were left out.
type pageStep struct {
	Page int
	URL  string
	Here bool
	Gap  bool
}

// pageWindow is which page numbers a pager shows. The ends are always
// reachable and the current page always has its neighbours, so a reader
// can step or jump without the control changing shape under them.
// Everything between is a gap.
//
// Page numbers are 1-based, and a run of pages is never replaced by a
// gap that is no shorter than the run it hides — an ellipsis standing
// in for a single page is furniture that costs a click.
func pageWindow(cur, last int) []int {
	if last < 1 {
		return nil
	}
	const edge, near = 1, 2 // pages pinned at each end; pages either side of here
	// The widest the elided form ever gets: both ends, both gaps, and
	// the run around here. A list no longer than that is cheaper shown
	// whole than hidden behind ellipses that save nothing.
	if last <= edge*2+near*2+1+2 {
		var out []int
		for i := 1; i <= last; i++ {
			out = append(out, i)
		}
		return out
	}
	keep := map[int]bool{}
	for i := 1; i <= edge && i <= last; i++ {
		keep[i] = true
		keep[last-i+1] = true
	}
	for i := cur - near; i <= cur+near; i++ {
		if i >= 1 && i <= last {
			keep[i] = true
		}
	}
	var out []int
	for i := 1; i <= last; i++ {
		if keep[i] {
			out = append(out, i)
			continue
		}
		// A gap must hide MORE than one page, or it has saved nothing
		// and taken away a destination.
		run := i
		for run <= last && !keep[run] {
			run++
		}
		if run-i == 1 {
			out = append(out, i)
			continue
		}
		out = append(out, 0) // the gap
		i = run - 1
	}
	return out
}

// pagerFor builds the pager for a listing that is ordered by SQL and so
// can be offset into. Nil when everything fits on one page — a pager
// under nine rows is furniture.
func pagerFor(nav ticketNav, shown, total int) *pager {
	if shown == 0 || (nav.Offset == 0 && shown >= total) {
		return nil
	}
	p := &pager{From: nav.Offset + 1, To: nav.Offset + shown, Total: total}
	if nav.Offset > 0 {
		p.Prev = nav.PageURL(nav.Offset - ticketPageSize)
	}
	if p.To < total {
		p.Next = nav.PageURL(nav.Offset + ticketPageSize)
	}
	p.Steps = pageSteps(nav.Offset, ticketPageSize, total, nav.PageURL)
	return p
}

// pageSteps turns an offset into the numbered row, asking the caller
// for each page's URL. Both listings that page keep their own idea of
// what a URL looks like; only the arithmetic is shared.
func pageSteps(offset, size, total int, at func(offset int) string) []pageStep {
	if size <= 0 || total <= 0 {
		return nil
	}
	last := (total + size - 1) / size
	cur := offset/size + 1
	var out []pageStep
	for _, p := range pageWindow(cur, last) {
		if p == 0 {
			out = append(out, pageStep{Gap: true})
			continue
		}
		out = append(out, pageStep{Page: p, URL: at((p - 1) * size), Here: p == cur})
	}
	return out
}

// railLink is one entry in the left rail.
type railLink struct {
	Label string
	URL   string
	Count int
	Here  bool
	// Saved marks an entry the reader named themselves, which is the
	// only kind that can be forgotten.
	Saved bool
	// Bare suppresses the count for entries that are a way IN rather
	// than a bucket — "recently updated" has no number of its own.
	Bare bool
}

// railSection is a titled group of rail entries.
type railSection struct {
	Title string
	Links []railLink
}

// railLimit caps a browse group. A rail is a way in, not an inventory:
// past a dozen entries a reader scans past it, and the dropdown beside
// the listing already offers every value there is.
const railLimit = 8

// ticketRail builds the left rail: the standing ways into a tracker,
// then the two fields worth browsing by. Every entry is an ordinary
// report URL — the rail invents no query the address bar cannot say,
// which is why it needs no storage and stays honest about what a click
// will do.
func ticketRail(nav ticketNav, subs, authors, repos []ticketFacet, me string, saved []savedView) []railSection {
	var out []railSection
	ways := railSection{Title: "views"}
	add := func(sec *railSection, label, url string, count int, here, bare bool) {
		sec.Links = append(sec.Links, railLink{Label: label, URL: url,
			Count: count, Here: here, Bare: bare})
	}
	// The waiting-on-you view names its own author and state, so the
	// state links would offer choices it cannot honour. The way out is
	// the whole listing, not a state.
	if nav.Awaiting {
		add(&ways, "waiting on you", nav.URL("", ""), nav.Open, true, false)
		out := nav
		out.Awaiting = false
		add(&ways, "all your tickets", out.URL("", ""), 0, false, true)
		return []railSection{ways}
	}
	add(&ways, "open", nav.URL("state", "open"), nav.Open, nav.Is("state", "open"), false)
	add(&ways, "everything", nav.URL("state", "all"), nav.Open+nav.Closed, nav.Is("state", "all"), false)
	add(&ways, "recently updated", nav.URL("sort", "recent"), 0, nav.Is("sort", "recent"), true)
	if me != "" {
		n := nav
		n.Report = cloneValues(nav.Report)
		n.Report.Set("author", me)
		add(&ways, "opened by me", n.URL("", ""), 0, nav.Report.Get("author") == me, true)
	}
	out = append(out, ways)

	browse := func(title, axis string, fs []ticketFacet) {
		if len(fs) == 0 {
			return
		}
		sec := railSection{Title: title}
		for i, f := range fs {
			if i >= railLimit {
				break
			}
			n := nav
			n.Report = cloneValues(nav.Report)
			here := nav.Report.Get(axis) == f.Value
			if here {
				n.Report.Del(axis) // a second click is how you get back out
			} else {
				n.Report.Set(axis, f.Value)
			}
			add(&sec, f.Value, n.URL("", ""), f.Open, here, false)
		}
		out = append(out, sec)
	}
	// Repository leads when there is one: on a cross-repository listing
	// "where is this work" is answered by tracker before subsystem.
	browse("repositories", "repo", repos)
	browse("subsystems", "subsystem", subs)
	browse("people", "author", authors)
	// A saved view is a NAME for a URL this page could already produce,
	// so it is an ordinary rail entry and nothing here needs to know it
	// came from storage. It sits last because the standing ways in and
	// the browse axes are what a stranger to this tracker needs first.
	if len(saved) > 0 {
		sec := railSection{Title: "saved"}
		here := nav.params().Encode()
		for _, v := range saved {
			url := nav.path()
			if v.Query != "" {
				url += "?" + v.Query
			}
			sec.Links = append(sec.Links, railLink{Label: v.Name, URL: url,
				Here: v.Query == here, Bare: true, Saved: true})
		}
		out = append(out, sec)
	}
	return out
}

// landingDiffLines bounds the change summary on a landing. The full diff has
// its own page, which pages properly; a decision surface that ships a
// megabyte of it helps nobody and stalls the browser it was drawn for.
const landingDiffLines = "600"

// landingRoot reports whether a forum thread root is a landing record, and
// its id. Asked of the same op the landing pages use, so the forum and the
// landing surface cannot disagree about which threads are records.
func landingRoot(r *ops.Registry, req *http.Request, repo, root string) (string, bool) {
	out, err := invoke(req.Context(), r, "landing.get",
		url.Values{"repo": {repo}, "id": {root}})
	if err != nil {
		return "", false
	}
	var lg struct {
		Landing struct {
			ID string `json:"id"`
		} `json:"landing"`
	}
	remarshal(out, &lg)
	return lg.Landing.ID, lg.Landing.ID != ""
}

// branchTip resolves a branch name to the check-in it points at. A landing
// names branches, and both of them MOVE — that is the whole reason the diff
// is computed per view rather than frozen at open — so the resolution has to
// happen now, at the moment the page is drawn.
func branchTip(r *ops.Registry, req *http.Request, repo, branch string) string {
	if branch == "" {
		return ""
	}
	out, err := invoke(req.Context(), r, "timeline.list", url.Values{
		"repo": {repo}, "branch": {branch}, "kind": {"ci"}, "limit": {"1"}})
	if err != nil {
		return ""
	}
	var tl struct {
		Entries []struct {
			Hash string `json:"hash"`
		} `json:"entries"`
	}
	remarshal(out, &tl)
	if len(tl.Entries) == 0 {
		return ""
	}
	return tl.Entries[0].Hash
}

// landingCap is the capability each decision needs. accept MERGES — it
// writes a check-in — so it takes `i`; the other two only speak in the
// record's thread. Written once so the gate and the op cannot disagree.
func landingCap(verb string) string {
	// accept writes a merge onto the target; update writes one onto the
	// proposed branch. Both are check-ins.
	if verb == "accept" || verb == "update" {
		return "i"
	}
	return "3"
}

// listingPath is the tracker listing a saved view belongs to. It is
// built HERE from the repository name rather than taken from the form,
// so a hand-made post cannot turn a redirect into a door out of the
// forge; a repository name that is not one simply lands on the
// cross-repository listing.
func listingPath(repo, query string) string {
	path := "/tickets"
	if repo != "" && !strings.ContainsAny(repo, "/:?#") {
		path = "/r/" + url.PathEscape(repo) + "/ticket"
	}
	if q, err := url.ParseQuery(strings.TrimPrefix(query, "?")); err == nil && len(q) > 0 {
		path += "?" + q.Encode()
	}
	return path
}

// savedViewsFor reads the caller's named reports for one listing. Any
// failure — no OLTP, no account, a broken store — is simply no saved
// views: they are a convenience over URLs the page can already build,
// so losing them must never cost the reader the listing itself.
func savedViewsFor(r *ops.Registry, req *http.Request, user, repo string) []savedView {
	if user == "" {
		return nil
	}
	out, err := invoke(ops.WithUser(req.Context(), user), r, "view.list", url.Values{"repo": {repo}})
	if err != nil {
		return nil
	}
	var vl struct {
		Views []savedView `json:"views"`
	}
	remarshal(out, &vl)
	return vl.Views
}

// savedView is one named report in the rail.
type savedView struct {
	Name  string `json:"name"`
	Query string `json:"query"`
}

// cloneValues copies a report so a rail entry can vary one axis without
// every other entry inheriting the change.
func cloneValues(v url.Values) url.Values {
	out := url.Values{}
	for k, vs := range v {
		out[k] = append([]string(nil), vs...)
	}
	return out
}

// ticketColumn is one table column: the order key it sorts by (a key of
// index.TicketOrders, never raw SQL) and what the header calls it.
type ticketColumn struct{ Key, Label string }

// ticketColumns is fossil's report table, which is the shape people who
// live in trackers actually scan: identity, then the triage fields as
// aligned columns you can run an eye down, then when it last moved.
// The list view is for reading titles; this is for comparing rows.
var ticketColumns = []ticketColumn{
	{"id", "#"}, {"title", "title"}, {"status", "status"},
	{"type", "type"}, {"subsystem", "subsystem"},
	{"author", "opened by"}, {"updated", "updated"},
}

// ticketFilterControl is one report axis as a dropdown: the field, the
// words it offers, and which one is chosen.
type ticketFilterControl struct {
	Key, Selected string
	Options       []string
}

// ticketFilters builds the report controls. The configured fields offer
// the project's own vocabulary in the project's own order (that is what
// .quarry/tickets.json is for); subsystem and author offer what the
// tracker actually holds, because no config can predict either. An axis
// with nothing to choose from is left out rather than rendered as an
// empty dropdown that answers nothing.
func ticketFilters(vocab map[string][]string, subs, authors []ticketFacet, q url.Values) []ticketFilterControl {
	return ticketFiltersAcross(vocab, subs, authors, nil, q)
}

// ticketFiltersAcross is the same controls with the repository axis,
// which only the cross-repository listing offers.
func ticketFiltersAcross(vocab map[string][]string, subs, authors, repos []ticketFacet, q url.Values) []ticketFilterControl {
	values := func(fs []ticketFacet) []string {
		var out []string
		for _, f := range fs {
			out = append(out, f.Value)
		}
		return out
	}
	src := map[string][]string{
		"type": vocab["type"], "status": vocab["status"],
		"severity": vocab["severity"], "priority": vocab["priority"],
		"subsystem": values(subs), "author": values(authors),
		"repo": values(repos),
	}
	var out []ticketFilterControl
	for _, k := range ticketAxesAcross {
		if len(src[k]) == 0 {
			continue
		}
		out = append(out, ticketFilterControl{
			Key: k, Options: src[k], Selected: q.Get(k)})
	}
	return out
}

// ticketRows decorates summaries for the list. Fossil's own report
// pages colour a row by status and print every column; GitHub shows a
// state glyph, the title, and labels. This is the second shape over
// fossil's schema: type and subsystem read as labels, and the triage
// fields speak only when they are shouting.
// dominantShare is the fraction of a listing one value must cover before
// its chip is muted; dominantFloor is the smallest listing where a
// majority means anything rather than being an accident of three rows.
const (
	dominantShare = 0.7
	dominantFloor = 5
)

// dominant names the value of one field that says NOTHING on this page,
// because nearly every listed ticket shares it. A chip earns its box by
// distinguishing a ticket from its neighbours, so its neighbours are
// what decide: the old list printed status, priority and severity on all
// 71 rows and 68 of them read "Open Medium Important", and filtering to
// closed brought the identical noise back spelled "Fixed" on 34 of 34.
// Empty is never dominant — an unset field is already no chip.
func dominant(ts []ticketSummary, of func(ticketSummary) string) string {
	if len(ts) < dominantFloor {
		return ""
	}
	n := map[string]int{}
	for _, t := range ts {
		if v := of(t); v != "" {
			n[v]++
		}
	}
	for v, c := range n {
		if float64(c) >= dominantShare*float64(len(ts)) {
			return v
		}
	}
	return ""
}

func ticketRows(repo string, ts []ticketSummary, vocab map[string][]string) []ticketRow {
	// Keyed by the field name add() is called with, so a chip and its
	// muted value cannot drift apart.
	mute := map[string]string{
		"type":       dominant(ts, func(t ticketSummary) string { return t.Type }),
		"subsystem":  dominant(ts, func(t ticketSummary) string { return t.Subsystem }),
		"severity":   dominant(ts, func(t ticketSummary) string { return t.Severity }),
		"priority":   dominant(ts, func(t ticketSummary) string { return t.Priority }),
		"resolution": dominant(ts, func(t ticketSummary) string { return t.Resolution }),
	}
	rows := make([]ticketRow, 0, len(ts))
	for _, t := range ts {
		r := ticketRow{ticketSummary: t, Repo: repo, State: "open"}
		switch strings.ToLower(strings.TrimSpace(t.Status)) {
		case "review", "testing", "tested", "pending":
			r.State = "review"
		default:
			if statusClass(t.Status) == "st-done" {
				r.State = "done"
			}
		}
		add := func(text, class, title string) {
			if text != "" && text != mute[title] {
				r.Chips = append(r.Chips, ticketChip{Text: text, Class: class, Title: title})
			}
		}
		add(t.Type, "c-type", "type")
		add(t.Subsystem, "c-sub", "subsystem")
		if urgent(vocab["severity"], t.Severity) {
			add(t.Severity, "c-hot", "severity")
		}
		if urgent(vocab["priority"], t.Priority) {
			add(t.Priority, "c-hot", "priority")
		}
		if r.State == "done" {
			add(t.Resolution, "c-done", "resolution")
		}
		rows = append(rows, r)
	}
	return rows
}

type ticketField struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

// mentionRow is one landing or thread that referenced this ticket.
type mentionRow struct {
	Root   string `json:"root"`
	Title  string `json:"title"`
	Kind   string `json:"kind"`
	State  string `json:"state"`
	Branch string `json:"branch"`
	Target string `json:"target"`
}

// Href sends a landing to its record and a thread to the forum: they
// share an index and a hash, not a page.
func (m mentionRow) Href(repo string) string {
	kind := "forum"
	if m.Kind == "landing" {
		kind = "landing"
	}
	root := m.Root
	if len(root) > 16 {
		root = root[:16]
	}
	return "/r/" + repo + "/" + kind + "/" + root
}

// Glyph reuses the tracker's own marks, so a landed proposal reads the
// same here as it does in a listing.
func (m mentionRow) Glyph() string {
	switch m.State {
	case "accepted":
		return "i-tkt-done"
	case "rejected":
		return "i-tkt-done"
	}
	return "i-tkt-open"
}

type ticketDetail struct {
	ID          string         `json:"id"`
	Created     string         `json:"created"`
	Updated     string         `json:"updated"`
	Description string         `json:"description"`
	Fields      []ticketField  `json:"fields"`
	Changes     []ticketChange `json:"changes"`
	// ShowPrivate is the viewer's capability e, resolved by the handler
	// and carried on the ticket rather than reached for in a template.
	// It has no json tag on purpose: remarshal must never be able to set
	// it from op output, so the only way it becomes true is a handler
	// asking who is looking.
	ShowPrivate bool `json:"-"`
}

// ticketChange is one recorded change to a ticket.
type ticketChange struct {
	Date   string        `json:"date"`
	User   string        `json:"user"`
	Fields []ticketField `json:"fields"`
}

// ticketComment is one rendered discussion entry.
type ticketComment struct {
	Date     string        `json:"date"`
	Login    string        `json:"login"`
	Username string        `json:"username"`
	HTML     template.HTML `json:"html"`
}

// DifferentUsername reports whether the typed name disagrees with the
// authenticated one. Fossil surfaces that ("claiming to be …") because
// on an open tracker the two need not match, and hiding the difference
// would attribute words to the wrong person.
func (c ticketComment) DifferentUsername() bool {
	return c.Username != "" && c.Username != c.Login
}

// Title is the ticket's headline, promoted out of the field table the
// way fossil's view does — a ticket is known by its title, not its hash.
func (t ticketDetail) Title() string { return t.Field("title") }

// Header is the ordered subset fossil shows above the description. The
// order is fossil's own (status/type, severity/priority,
// subsystem/resolution), and unset fields are dropped rather than
// rendered as blank rows.
func (t ticketDetail) Header() []ticketField {
	order := []string{"status", "type", "severity", "priority",
		"subsystem", "resolution", "assignee", "foundin", "submitter", "closer"}
	var out []ticketField
	for _, name := range order {
		if v := t.Field(name); v != "" {
			out = append(out, ticketField{Name: name, Value: v})
		}
	}
	return out
}

// privateFields are the ticket fields fossil does NOT show publicly.
// Its own new-ticket template labels private_contact "Not publicly
// visible" and gates it behind capability "e" (view private email
// addresses) with enable_output [hascap e]. quarry rendered it to
// everyone: across this corpus that is 2,650 values, of which some in
// fossil's own tracker are real e-mail addresses. Reproducing a
// tracker's content faithfully must not mean publishing what the
// tracker deliberately withheld.
//
// quarry now HAS that capability (RFC 0004), so these are gated rather
// than dropped: withheld by default, rendered to a viewer who holds e.
// The default is deny and there is no ungated-forge exemption — see
// maySeePrivate. A capability nobody can exercise is not a capability,
// and a tracker's own maintainers are exactly who the field is for.
var privateFields = map[string]bool{"private_contact": true, "contact": true}

// Extra is everything else a repository's ticket schema carries — trackers
// define their own columns, so a fixed list would hide them.
func (t ticketDetail) Extra() []ticketField {
	known := map[string]bool{"title": true, "status": true, "type": true,
		"severity": true, "priority": true, "subsystem": true, "resolution": true,
		"assignee": true, "foundin": true, "submitter": true, "closer": true}
	var out []ticketField
	for _, f := range t.Fields {
		if !known[f.Name] && (t.ShowPrivate || !privateFields[f.Name]) && f.Value != "" {
			out = append(out, f)
		}
	}
	return out
}

// Field folds the current value of one named field (for form prefill).
func (t ticketDetail) Field(name string) string {
	for _, f := range t.Fields {
		if f.Name == name {
			return f.Value
		}
	}
	return ""
}

// Closed reports whether the ticket is in a terminal status. Fossil's
// default vocabulary closes on "Closed" and "Fixed"; a tracker with
// other words still gets a Comment & close button that writes Closed.
func (t ticketDetail) Closed() bool {
	switch strings.ToLower(t.Field("status")) {
	case "closed", "fixed":
		return true
	}
	return false
}

// ticketEvent is one entry of the ticket's timeline: a remark, a set of
// field changes, or both — fossil lets one artifact carry both, and a
// "closed with comment" is exactly that.
type ticketEvent struct {
	Date        string
	Login       string
	Username    string
	HTML        template.HTML
	Deltas      []fieldDelta
	Redescribed bool // the change rewrote the description
}

// fieldDelta is one field's move, for the "status Open → Review" line.
type fieldDelta struct {
	Name, From, To string
}

func (e ticketEvent) DifferentUsername() bool {
	return e.Username != "" && e.Username != e.Login
}

// Summary is the event's verb phrase: "edited the description, retitled
// <b>Short</b> and changed status <b>Open → Review</b>". Empty for a
// plain remark.
func (e ticketEvent) Summary() template.HTML {
	esc := template.HTMLEscapeString
	var parts, moves []string
	if e.Redescribed {
		parts = append(parts, "edited the description")
	}
	for _, d := range e.Deltas {
		if d.Name == "title" {
			parts = append(parts, "retitled <b>"+esc(d.To)+"</b>")
			continue
		}
		m := esc(d.Name) + " <b>"
		if d.From != "" {
			m += esc(d.From) + " → "
		}
		if d.To != "" {
			m += esc(d.To)
		} else {
			m += "—"
		}
		moves = append(moves, m+"</b>")
	}
	if len(moves) > 0 {
		parts = append(parts, "changed "+strings.Join(moves, ", "))
	}
	switch len(parts) {
	case 0:
		return ""
	case 1:
		return template.HTML(parts[0])
	}
	return template.HTML(strings.Join(parts[:len(parts)-1], ", ") + " and " + parts[len(parts)-1])
}

// timelineNoise is what a change artifact carries that is not a field
// the reader edits: the remark itself and the two mimetype columns.
var timelineNoise = map[string]bool{"icomment": true, "mimetype": true,
	"comment": true, "cmimetype": true}

// ticketTimeline merges the rendered remarks with the field changes the
// artifacts record, oldest first. The first change is the ticket's
// birth — its fields are the description, not a move — so it only
// contributes its remark. Later changes walk forward from that state
// so each event knows where a field came from. A remark and the field
// changes written in the same artifact share a date, which is how they
// fold into one event.
func ticketTimeline(t ticketDetail, comments []ticketComment) []ticketEvent {
	byDate := map[string]*ticketEvent{}
	var out []*ticketEvent
	at := func(date, login string) *ticketEvent {
		if e := byDate[date]; e != nil {
			return e
		}
		e := &ticketEvent{Date: date, Login: login}
		byDate[date] = e
		out = append(out, e)
		return e
	}
	state := map[string]string{}
	for i, c := range t.Changes {
		if i == 0 {
			for _, f := range c.Fields {
				state[f.Name] = f.Value
			}
			continue
		}
		var deltas []fieldDelta
		redescribed := false
		for _, f := range c.Fields {
			if f.Name == "comment" {
				redescribed = true
			}
			if timelineNoise[f.Name] || (privateFields[f.Name] && !t.ShowPrivate) {
				continue
			}
			if state[f.Name] == f.Value {
				continue
			}
			deltas = append(deltas, fieldDelta{Name: f.Name, From: state[f.Name], To: f.Value})
			state[f.Name] = f.Value
		}
		if len(deltas) > 0 || redescribed {
			e := at(c.Date, c.User)
			e.Deltas = append(e.Deltas, deltas...)
			e.Redescribed = e.Redescribed || redescribed
		}
	}
	for _, c := range comments {
		e := at(c.Date, c.Login)
		e.Username, e.HTML = c.Username, c.HTML
		if e.Login == "" {
			e.Login = c.Login
		}
	}
	sort.SliceStable(out, func(i, j int) bool { return out[i].Date < out[j].Date })
	res := make([]ticketEvent, len(out))
	for i, e := range out {
		res[i] = *e
	}
	return res
}

// ticketControl is one editable field in the sidebar: the words the
// tracker uses for it, with the current value kept even when the
// vocabulary does not list it — a select that refused a word the
// tracker already writes would make the ticket uneditable.
type ticketControl struct {
	Name    string
	Value   string
	Options []string // empty: free text
}

// ticketControls builds the sidebar from fossil's triage fields in the
// order its view shows them, taking each field's words from the
// repository's vocabulary.
func ticketControls(t ticketDetail, vocab map[string][]string) []ticketControl {
	var out []ticketControl
	// Fossil's default schema, all ten columns of it less the two this
	// forge does not author: title has its own control at the top of the
	// page, and private_contact is withheld on purpose.
	for _, name := range []string{"status", "type", "severity", "priority",
		"subsystem", "foundin", "resolution"} {
		c := ticketControl{Name: name, Value: t.Field(name)}
		if words := vocab[name]; len(words) > 0 {
			c.Options = append([]string(nil), words...)
			if c.Value != "" && !slices.Contains(c.Options, c.Value) {
				c.Options = append([]string{c.Value}, c.Options...)
			}
		}
		out = append(out, c)
	}
	return out
}

type checkinDetail struct {
	Hash    string   `json:"hash"`
	CI      string   `json:"ci"`
	CIRun   string   `json:"ciRun"`
	Branch  string   `json:"branch"`
	Date    string   `json:"date"`
	User    string   `json:"user"`
	Comment string   `json:"comment"`
	Parents []string `json:"parents"`
	Files   []struct {
		Blob string `json:"blob"`
		Name string `json:"name"`
	} `json:"files"`
	Tags        []string         `json:"tags"`
	CommentOrig string           `json:"commentOrig"`
	Hidden      bool             `json:"hidden"`
	Closed      bool             `json:"closed"`
	Fork        string           `json:"fork"`
	DiscussedIn []forumThreadRow `json:"discussedIn"`
	Context     []ciContext      `json:"context"`
}

type tagEventRow struct {
	Date     string `json:"date"`
	Src      string `json:"src"`
	Name     string `json:"name"`
	Sign     string `json:"sign"`
	Value    string `json:"value"`
	Standing bool   `json:"standing"`
}

type manifestCardRow struct {
	Letter string `json:"letter"`
	Text   string `json:"text"`
	Note   string `json:"note"`
}

type manifestDetail struct {
	Hash  string            `json:"hash"`
	Size  int               `json:"size"`
	Cards []manifestCardRow `json:"cards"`
	Files int               `json:"files"`
}

type checkinTagsDetail struct {
	Hash        string        `json:"hash"`
	Date        string        `json:"date"`
	User        string        `json:"user"`
	Comment     string        `json:"comment"`
	CommentOrig string        `json:"commentOrig"`
	Branch      string        `json:"branch"`
	Hidden      bool          `json:"hidden"`
	Closed      bool          `json:"closed"`
	Events      []tagEventRow `json:"events"`
}

type fileDetail struct {
	Hash       string `json:"hash"`
	Path       string `json:"path"`
	Size       int    `json:"size"`
	Binary     bool   `json:"binary"`
	Content    string `json:"content"`
	HTML       string `json:"html"`
	Renderable bool   `json:"renderable"`
}

// contextRail fills in each context row's rendered comment and its
// graph mark. The rail is ONE line — the panel shows a slice of time,
// not a branch graph, and drawing lanes for three neighbours would
// promise a topology the panel is not actually showing.
func contextRail(repo, here string, rows []ciContext) []ciContext {
	// The timeline's palette, so a branch keeps one colour across the
	// forge rather than being blue on one page and green on another.
	var entries []timelineEntry
	for _, c := range rows {
		entries = append(entries, timelineEntry{Branch: c.Branch})
	}
	pal := newPalette("trunk", entries)
	for i := range rows {
		c := &rows[i]
		c.Here = c.Hash == here
		first, _, _ := strings.Cut(strings.TrimSpace(c.Comment), "\n")
		c.Lead = commentHTML(repo, first)

		stroke := pal.stroke(c.Branch)
		var b strings.Builder
		b.WriteString(`<svg class="ci-node" viewBox="0 0 14 34" aria-hidden="true">`)
		// The rail runs the full height except at the ends, so the run
		// reads as one line rather than three floating dots.
		y1, y2 := 0, 34
		if i == 0 {
			y1 = 17
		}
		if i == len(rows)-1 {
			y2 = 17
		}
		fmt.Fprintf(&b, `<line x1="7" y1="%d" x2="7" y2="%d" stroke="%s" stroke-width="2"/>`,
			y1, y2, stroke)
		if c.Here {
			fmt.Fprintf(&b, `<circle cx="7" cy="17" r="5" fill="%s"/>`, stroke)
		} else {
			fmt.Fprintf(&b, `<circle cx="7" cy="17" r="4" fill="var(--bg)" stroke="%s" stroke-width="2"/>`, stroke)
		}
		b.WriteString(`</svg>`)
		c.Node = template.HTML(b.String())
	}
	return rows
}

// ciContext is one neighbouring check-in in the context panel.
type ciContext struct {
	Hash    string `json:"hash"`
	Date    string `json:"date"`
	User    string `json:"user"`
	Comment string `json:"comment"`
	Branch  string `json:"branch"`
	// Here marks the check-in the page is about.
	Here bool `json:"-"`
	// Lead is the comment's first line, rendered — the same treatment
	// the timeline gives it, so bracket links live here too.
	Lead template.HTML `json:"-"`
	// Node is the graph mark for this row: a rail segment and a dot,
	// coloured by branch through the SAME palette the timeline uses, so
	// a branch is one colour wherever a reader meets it.
	Node template.HTML `json:"-"`
}

type diffDetail struct {
	From  string `json:"from"`
	To    string `json:"to"`
	Note  string `json:"note"`
	Files []struct {
		Status string `json:"status"`
		Name   string `json:"name"`
	} `json:"files"`
	Structured   []diff.FileDiff `json:"structured"`
	OmittedLines int             `json:"omittedLines"`
	NextOffset   int             `json:"nextOffset"`
	TotalLines   int             `json:"totalLines"`
	LastOffset   int             `json:"lastOffset"`
	// Page-side: the file the view is narrowed to, the offset this
	// window began at, and the view mode — what the next-chunk URL
	// has to repeat.
	Repo string `json:"-"`
	File string `json:"-"`
	// Branch marks this as a whole-branch diff, which every URL the
	// page emits must repeat or the next window silently becomes the
	// parent diff.
	Branch bool `json:"-"`
	Offset int  `json:"offset"` // snapped by the op to the hunk it starts on
	Prev   int  `json:"-"`      // offset of the window before this one; -1 when unknown
	Split  bool `json:"-"`
}

// Back is the URL of the window this one continued from, for the
// paged (no-script) reading: the continue link carries its own offset
// as prev, so one step back is always known. "" on the first window.
func (d diffDetail) Back() string {
	if d.Offset == 0 || d.Prev < 0 {
		return ""
	}
	return "?" + d.query(d.Prev, -1).Encode()
}

// Last is the URL of the final window, "" when this is it.
func (d diffDetail) Last() string {
	if d.LastOffset <= d.Offset {
		return ""
	}
	return "?" + d.query(d.LastOffset, -1).Encode()
}

// Start is the URL of the first window, same view.
func (d diffDetail) Start() string {
	return "?" + d.query(0, -1).Encode()
}

func (d diffDetail) query(after, prev int) url.Values {
	v := url.Values{}
	if after > 0 {
		v.Set("after", strconv.Itoa(after))
	}
	if prev >= 0 {
		v.Set("prev", strconv.Itoa(prev))
	}
	if d.File != "" {
		v.Set("file", d.File)
	}
	if d.Split {
		v.Set("view", "split")
	}
	if d.Branch {
		// Every paging URL runs through here, which is why the mode is
		// repeated here and nowhere else: Back, Last, Start and More
		// all inherit it, and none of them can forget.
		v.Set("branch", "1")
	}
	return v
}

// ToggleHref is the ordinary link to the other view, and ToggleFrag is
// the same switch made in place. Both keep the file, the branch mode
// and the WINDOW: switching to side-by-side three pages into a long
// diff should change how those lines look, not which lines they are.
//
// The href is what the page ships; the fragment is layered over it
// where script runs. Neither is a fallback for the other — the link
// works on its own, and the enhancement reuses its target.
func (d diffDetail) ToggleHref(split bool) string {
	return "?" + d.toggleQuery(split).Encode()
}

func (d diffDetail) ToggleFrag(split bool) string {
	v := d.toggleQuery(split)
	v.Set("whole", "1")
	return "/r/" + d.Repo + "/checkin/" + d.To + "/diff.frag?" + v.Encode()
}

func (d diffDetail) toggleQuery(split bool) url.Values {
	v := d.query(d.Offset, -1)
	v.Del("view")
	if split {
		v.Set("view", "split")
	}
	return v
}

// More is the URL of the window after this one, or "" at the end.
func (d diffDetail) More(frag bool) string {
	if d.OmittedLines == 0 {
		return ""
	}
	v := d.query(d.NextOffset, d.Offset)
	if frag {
		v.Del("prev")
		// Absolute: the check-in page and its /diff deep link share
		// this template, and a relative URL would resolve differently
		// from each.
		return "/r/" + d.Repo + "/checkin/" + d.To + "/diff.frag?" + v.Encode()
	}
	return "?" + v.Encode()
}

// Paged reports whether the diff spans more than this window, which
// is when the pager is worth drawing.
func (d diffDetail) Paged() bool { return d.Offset > 0 || d.OmittedLines > 0 }

// Continued reports whether this window opens mid-file.
func (d diffDetail) Continued() bool {
	return len(d.Structured) > 0 && d.Structured[0].Before > 0 && len(d.Structured[0].Hunks) > 0
}

// diffWindow loads one window of a check-in's diff as the page shows
// it: ?file= narrows, ?after= continues, ?view=split widens.
func diffWindow(r *ops.Registry, req *http.Request, repo, hash string) (diffDetail, error) {
	q := req.URL.Query()
	after, _ := strconv.Atoi(q.Get("after"))
	vals := url.Values{
		"repo": {repo}, "hash": {hash}, "file": {q.Get("file")},
		// from= makes this the diff against an explicit base rather
		// than the parent — how a landing links to the whole of its
		// change. Absent, every existing caller keeps parent semantics.
		"from":   {q.Get("from")},
		"offset": {strconv.Itoa(max(after, 0))}, "maxLines": {diffBudget}}
	// The branch mode must survive paging: a window two pages into a
	// branch diff that quietly reverted to the parent diff would show
	// different content under the same heading. Set only when asked
	// for — the field is a boolean, and "" is not one.
	if b := q.Get("branch"); b != "" {
		vals.Set("branch", b)
	}
	out, err := invoke(req.Context(), r, "checkin.diff", vals)
	if err != nil {
		return diffDetail{}, err
	}
	var dd diffDetail
	remarshal(out, &dd)
	dd.Repo, dd.File, dd.Split = repo, q.Get("file"), q.Get("view") == "split"
	dd.Branch = q.Get("branch") != "" && q.Get("branch") != "0"
	dd.Prev = -1
	if p, err := strconv.Atoi(q.Get("prev")); err == nil && p >= 0 && p < dd.Offset {
		dd.Prev = p
	}
	return dd, nil
}

// diffBudget is the most diff lines a page renders. Past it, files
// show a count and a link to their own diff. ~3,000 keeps the whole
// page — diff, highlight, render — inside the response budget, and is
// already far more than anyone reads in one scroll.
const diffBudget = "3000"

// personRow is one contributor on the people tab.
type personRow struct {
	User   string   `json:"user"`
	Events int      `json:"events"`
	First  string   `json:"first"`
	Last   string   `json:"last"`
	Repos  []string `json:"repos"`
	// Role is this contributor's grant on the repository being viewed,
	// filled for an admin only and empty for almost everybody: a
	// contributor is a NAME ON AN ARTIFACT — whatever U card the
	// author's client wrote — and an account is a login on this forge.
	// On a mirror the two populations barely intersect, which is the
	// fact an admin is here to see.
	Role string `json:"-"`
}

// repoFacet is one repository's share of a fleet-wide result set.
// opsRouteView is one route opened up.
type opsRouteView struct {
	Path    string `json:"path"`
	Renders []struct {
		At        string `json:"at"`
		Repo      string `json:"repo"`
		ElapsedMs int64  `json:"elapsedMs"`
		OpsMs     int64  `json:"opsMs"`
		ZitMs     int64  `json:"zitMs"`
		Status    int    `json:"status"`
		CallMs    int64  `json:"callMs"`
		Calls     []struct {
			Verb       string `json:"verb"`
			Repo       string `json:"repo"`
			DurationMs int64  `json:"durationMs"`
		} `json:"calls"`
	} `json:"renders"`
	Trend []struct {
		Day   string `json:"day"`
		N     int    `json:"n"`
		P50Ms int64  `json:"p50Ms"`
		P95Ms int64  `json:"p95Ms"`
		MaxMs int64  `json:"maxMs"`
	} `json:"trend"`
	TrendDays int `json:"trendDays"`
	ByRepo    []struct {
		Repo  string `json:"repo"`
		Count int    `json:"count"`
		P50Ms int64  `json:"p50Ms"`
		MaxMs int64  `json:"maxMs"`
	} `json:"byRepo"`
}

// opsView is the operations page's model, decoded straight from the op.
// opsRenderView is one row of the recent-renders table. Named, unlike
// its neighbours, because a test has to be able to build one.
type opsRenderView struct {
	At        string `json:"at"`
	Path      string `json:"path"`
	URL       string `json:"url"`
	Repo      string `json:"repo"`
	ElapsedMs int64  `json:"elapsedMs"`
	OpsMs     int64  `json:"opsMs"`
	ZitMs     int64  `json:"zitMs"`
	Status    int    `json:"status"`
}

type opsView struct {
	Phase struct {
		Name                string   `json:"name"`
		Repos               int      `json:"repos"`
		Ready               int      `json:"ready"`
		Working             []string `json:"working"`
		Stalled             []string `json:"stalled"`
		Artifacts           int      `json:"artifacts"`
		SlowestRoundSeconds float64  `json:"slowestRoundSeconds"`
	} `json:"phase"`
	Paths []struct {
		Path  string `json:"path"`
		Count int    `json:"count"`
		P50Ms int64  `json:"p50Ms"`
		P95Ms int64  `json:"p95Ms"`
		MaxMs int64  `json:"maxMs"`
	} `json:"paths"`
	Renders []opsRenderView `json:"renders"`
	Verbs   []struct {
		Verb    string `json:"verb"`
		Count   int    `json:"count"`
		TotalMs int64  `json:"totalMs"`
		MaxMs   int64  `json:"maxMs"`
	} `json:"verbs"`
	LiveSubprocess int   `json:"liveSubprocess"`
	PeakSubprocess int   `json:"peakSubprocess"`
	ErrorTotal     int   `json:"errorTotal"`
	BudgetMs       int64 `json:"budgetMs"`
	Store          struct {
		Configured bool   `json:"configured"`
		Path       string `json:"path"`
		Err        string `json:"err"`
		Kept       string `json:"kept"`
	} `json:"store"`
	Find string `json:"find"`
	Sort string `json:"sort"`
	// Window is how many renders the ring is holding, said in words so
	// the page cannot imply it covers all of history.
	Window string `json:"-"`
}

type repoFacet struct {
	Repo  string
	Count int
}

type searchHit struct {
	// Repo is set only for fleet-wide results, where a hit is
	// meaningless without saying which repository it came from.
	Repo    string
	Kind    string
	Label   string
	URL     string
	Snippet template.HTML
	// What tells two results apart. Three tk check-ins for "use after
	// free" rendered identically — same repository, same title, same
	// snippet — because the same fix landed on three branches, and the
	// row carried nothing that differed. Empty fields render as
	// nothing.
	Short  string
	Date   string
	User   string
	Branch string
	Status string
}

// searchMeta is the distinguishing half of a result, as the op sends it.
type searchMeta struct {
	Kind    string `json:"kind"`
	Ref     string `json:"ref"`
	Label   string `json:"label"`
	Snippet string `json:"snippet"`
	Date    string `json:"date"`
	User    string `json:"user"`
	Branch  string `json:"branch"`
	Status  string `json:"status"`
	Hash    string `json:"hash"`
}

// hitOf turns one search result into its page link. The label is the
// human-readable name the op provides (ticket title, wiki name,
// check-in comment) with the ref as fallback; the snippet's ⟦…⟧ match
// markers become <mark> AFTER escaping, so content stays inert.
func hitOf(repo, kind, ref, label, snippet string) searchHit {
	return hitOfMeta(repo, searchMeta{Kind: kind, Ref: ref, Label: label, Snippet: snippet})
}

func hitOfMeta(repo string, m searchMeta) searchHit {
	kind, ref, label, snippet := m.Kind, m.Ref, m.Label, m.Snippet
	h := searchHit{Kind: kind, Label: label,
		Date: m.Date, User: m.User, Branch: m.Branch, Status: m.Status}
	if m.Hash != "" {
		h.Short = m.Hash[:min(12, len(m.Hash))]
	}
	prefix := "/r/" + repo
	switch kind {
	case "checkin":
		h.URL = prefix + "/checkin/" + ref
		if h.Label == "" {
			h.Label = ref[:min(12, len(ref))]
		}
	case "wiki":
		h.URL = prefix + "/wiki/" + url.PathEscape(ref)
		if h.Label == "" {
			h.Label = ref
		}
	case "ticket":
		h.URL = prefix + "/ticket/" + ref
		if h.Label == "" {
			h.Label = ref[:min(10, len(ref))]
		}
	// Forum and technote hits used to fall through this switch with no
	// URL at all, so the index found them, the facet chips offered
	// them, the page rendered them — and the title was <a href="">,
	// which a browser resolves to the CURRENT page. Clicking a forum
	// result reloaded the search.
	//
	// Their refs are not artifact hashes: searchDoc files a forum post
	// under its thread ROOT and a technote under its EVENT id, because
	// that is the thing a reader wants to land on. Both routes take the
	// 16-character prefix every other link in the forge uses.
	case "forum":
		h.URL = prefix + "/forum/" + ref[:min(16, len(ref))]
		if h.Label == "" {
			h.Label = "(untitled thread)"
		}
	case "technote":
		h.URL = prefix + "/technote/" + ref[:min(16, len(ref))]
		if h.Label == "" {
			h.Label = "(untitled note)"
		}
	// Tree kinds. Their ref is "<version>/<path>", because a link has
	// to name the check-in the row was indexed at — resolving a branch
	// name at click time would be a second source of truth about which
	// tree this row describes, and the two would disagree the moment
	// somebody committed between the index pass and the click.
	//
	// A document renders; a source file is shown as source. Same tree,
	// same pass, two destinations, because that is what a reader
	// clicking each of them wants.
	case "doc", "file":
		h.URL = prefix + "/" + kind + "/" + ref
		if h.Label == "" {
			// The path, without the version the ref carries for the
			// link. A label naming the check-in would say the same
			// hash on every row.
			if _, path, ok := strings.Cut(ref, "/"); ok {
				h.Label = path
			} else {
				h.Label = ref
			}
		}
	}
	esc := template.HTMLEscapeString(snippet)
	esc = strings.ReplaceAll(esc, "⟦", "<mark>")
	esc = strings.ReplaceAll(esc, "⟧", "</mark>")
	h.Snippet = template.HTML(esc)
	return h
}

// Handler mounts every HTML page over the registry. n may be nil (no
// live updates; pages are unchanged otherwise).
// Verify checks one repo credential pair against a required capability;
// nil leaves writes open (single-user local serving, author "anonymous").
type Verify func(repo, user, password string, need ops.Auth) api.Decision

// Sessions is the browser half of the gate: a cookie a person can drop.
// HTTP Basic keeps working alongside it — that is what the API and every
// script uses — but a browser needs a way to log OUT, which Basic does
// not give it. A nil Sessions disables the login page and leaves Basic
// as the only path.
type Sessions interface {
	// Login issues a token for correct credentials.
	Login(user, password string) (token string, expires time.Time, ok bool)
	// Resolve names the account a token belongs to.
	Resolve(token string) (user string, ok bool)
	// Logout drops one token.
	Logout(token string)
	// Allow authorizes an ALREADY-authenticated user, so a cookie is
	// checked against the same roles a password would be.
	Allow(user, repo string, need ops.Auth) bool
}

// CapSet is an expanded fossil capability set (RFC 0004). The web layer
// holds it structurally, never importing storage types.
type CapSet interface{ HasAny(letters string) bool }

// CapsAdmin is the settings editor's seam: read every account's caps
// on a repo, read and write the four category strings. Optional — a
// Caps plane that does not implement it simply has no editor.
type CapsAdmin interface {
	CapHolders(repo string) ([]CapHolder, error)
	CategoryCaps(repo, category string) string
	SetCaps(account, repo, caps string) error
	SetCategoryCaps(repo, category, caps string) error
}

// CapsGuard is the editor's refusal seam (RFC 0008): asked before every
// save with the actor, it answers a warning to show, or a Refusal the
// page shows instead of saving. Optional — without it every save goes.
type CapsGuard interface {
	GuardCaps(actor, account, repo, caps string) (warning string, err error)
}

// Reach is the take-private wizard's seam: who reaches a repository
// through the categories alone, and so loses it when they blank.
type Reach interface {
	ReachOnlyByCategory(repo string) ([]string, error)
}

// LogStore is the forge's own drained-log record (RFC 0009 §logs):
// what the poller stored beside the verdict when the run finished.
type LogStore interface {
	DrainedLogs(repo, runID string) ([]ci.LogChunk, bool)
}

// EngineViews is the CI engine as the run page needs it (RFC 0009
// §logs): a run's detail, a step's log chunks, the worker directory.
// nil renders the pages honest about the absence.
type EngineViews interface {
	RunDetail(runID string) (ci.Run, error)
	StepLogs(runID, step string, afterSeq int, fromFailure bool) ([]ci.LogChunk, error)
	Workers() ([]ci.Worker, error)
	// Worker tokens (dagnats#627): the engine's admin-gated mint,
	// list, revoke. Errors are worded for the settings page.
	WorkerTokens() ([]ci.WorkerToken, error)
	MintWorkerToken(label string, prefixes []string) (ci.WorkerToken, error)
	RevokeWorkerToken(id string) error
}

// CapsWhatIf answers what a not-yet-stored string would grant, so the
// live editor previews without a write (RFC 0008). Optional.
type CapsWhatIf interface {
	EffectiveWith(account, repo, own string) CapSet
}

// CapHolder is one account's stored caps on a repository.
type CapHolder struct {
	Account string
	Caps    string
}

// Caps resolves effective capabilities for a viewer on a repository.
// A Sessions implementation that also satisfies this interface enables
// capability gating; without it the role floor is the whole story.
type Caps interface {
	CapsOf(account, repo string) CapSet
}

// capsOf resolves the viewer's caps when the session plane provides
// them. The second return reports whether caps are available at all —
// callers fall back to role gating when they are not, so an
// unconfigured forge behaves exactly as before.
// syncURLAttr builds the click handler for a control that swaps part of
// the page instead of navigating: correct the address bar to the link's
// OWN href, then fetch the fragment. The href is the real, cold-loadable
// route, so the URL on screen keeps describing what is on screen — a
// view toggle that leaves a stale URL behind breaks sharing and reload,
// which is most of what a URL is for.
//
// The address-bar update CANNOT be allowed to fail the click. On a page
// opened with credentials in the URL, replaceState to a credential-free
// one is a cross-origin write and throws — and it throws BEFORE @get
// runs, leaving a control that neither swaps nor navigates, because
// __prevent already cancelled the link. Cosmetics must never stand in
// front of the actual work, hence the catch.
//
// replaceState, not pushState: these are view toggles, so the back
// button should leave the page rather than walk every view the reader
// tried on the way here.
//
// frag is app-built and its quotes are already percent-encoded, but it
// lands inside a JS string inside an HTML attribute with escaping
// switched off, so the three characters that could break out are
// neutralized here rather than trusted at every call site.
func syncURLAttr(frag string) template.HTMLAttr {
	safe := strings.NewReplacer(`\`, "%5C", `'`, "%27", `"`, "%22").Replace(frag)
	return template.HTMLAttr(`data-on:click__prevent="` +
		`try{history.replaceState(null,'',evt.currentTarget.getAttribute('href'))}catch(e){} ` +
		`@get('` + safe + `')"`)
}

func capsOf(caps Caps, sess Sessions, verify Verify, repo string, req *http.Request) (CapSet, bool) {
	c := caps
	if c == nil {
		sc, ok := sess.(Caps)
		if !ok || sc == nil {
			return nil, false
		}
		c = sc
	}
	return c.CapsOf(viewer(verify, sess, repo, req), repo), true
}

// mayCap answers "does this viewer hold any of these letters here?".
// Without a caps plane it falls back to the role floor the caller
// names, so every call site states both truths (RFC 0004 §5).
func mayCap(caps Caps, verify Verify, sess Sessions, repo string, letters string, floor ops.Auth, req *http.Request) bool {
	if verify == nil {
		return true
	}
	if c, ok := capsOf(caps, sess, verify, repo, req); ok {
		return c.HasAny(letters)
	}
	return mayAt(verify, sess, repo, floor, req)
}

// maySeePrivate answers whether this viewer holds fossil's capability e
// — view private e-mail addresses — for this repository.
//
// Deliberately NOT mayCap. Every other gate treats "no auth model
// configured" as "allow", because an ungated forge has no strangers.
// That rule is wrong here and only here: an ungated forge is usually a
// PUBLIC one, and applying it would publish the 2,650 contact values in
// this corpus — some of them real addresses in fossil's own tracker —
// to the open internet. So this one defaults to deny and needs a caps
// plane to say yes. The cost of being wrong is asymmetric, so the
// default follows the cheaper mistake.
func maySeePrivate(caps Caps, verify Verify, sess Sessions, repo string, req *http.Request) bool {
	if verify == nil {
		return false
	}
	c, ok := capsOf(caps, sess, verify, repo, req)
	return ok && c.HasAny("e")
}

// InboxMessage is one notification as the inbox page shows it. quarry
// does not model notifications — notify owns them (0001 §5) — so this is
// only what the page renders.
type InboxMessage struct {
	Subject   string
	Content   string
	CreatedAt string
	Read      bool
}

// Inbox reads a subscriber's notifications from the notify companion.
// nil disables the inbox page, which is the default: notifications are
// off unless --notify is configured.
type Inbox interface {
	Messages(ctx context.Context, subscriber string) ([]InboxMessage, error)
}

// WithInbox attaches the notify-backed inbox.
func WithInbox(in Inbox) Option {
	return func(o *handlerOpts) { o.inbox = in }
}

// sessionCookie is the browser's session key. Host-only, path-wide,
// unreadable to scripts, and not sent on cross-site requests — the last
// of which is what keeps a POST form from being submitted by another
// origin on the reader's behalf.
const sessionCookie = "quarry_session"

func setSession(w http.ResponseWriter, req *http.Request, token string, expires time.Time) {
	http.SetCookie(w, &http.Cookie{
		Name: sessionCookie, Value: token, Path: "/",
		Expires:  expires,
		HttpOnly: true,
		SameSite: http.SameSiteLaxMode,
		Secure:   req.TLS != nil,
	})
}

func clearSession(w http.ResponseWriter, req *http.Request) {
	http.SetCookie(w, &http.Cookie{
		Name: sessionCookie, Value: "", Path: "/", MaxAge: -1,
		HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: req.TLS != nil,
	})
}

// flashCookie carries a word across a redirect and is spent on arrival.
// A query parameter cannot do this job: ?saved=1 stays in the address
// bar, so a reload — or a bookmark — announces a save that happened
// once, hours ago. A confirmation is an EVENT, and an event that a
// refresh can replay is not one.
const flashCookie = "q_flash"

func setFlash(w http.ResponseWriter, req *http.Request, msg string) {
	http.SetCookie(w, &http.Cookie{
		Name: flashCookie, Value: msg, Path: "/", MaxAge: 30,
		HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: req.TLS != nil,
	})
}

// takeFlash reads the flash and spends it in the same breath, so the
// next render of the same URL is silent.
func takeFlash(w http.ResponseWriter, req *http.Request) string {
	c, err := req.Cookie(flashCookie)
	if err != nil || c.Value == "" {
		return ""
	}
	http.SetCookie(w, &http.Cookie{
		Name: flashCookie, Value: "", Path: "/", MaxAge: -1,
		HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: req.TLS != nil,
	})
	return c.Value
}

func cookieToken(req *http.Request) string {
	if c, err := req.Cookie(sessionCookie); err == nil {
		return c.Value
	}
	return ""
}

// gate runs the write-page auth check at Token: HTTP Basic against
// verify, the authenticated user carried to the op via context. Almost
// every gated HTML page is a write page and wants exactly this.
func gate(verify Verify, sess Sessions, repo string, w http.ResponseWriter, req *http.Request) (*http.Request, bool) {
	return gateAt(verify, sess, repo, ops.Token, w, req)
}

// gateAt is gate at an explicit capability. The fleet admin pages are
// the reason it exists: they are not scoped to one repository and they
// expose operational detail, so Token is not the right bar for them.
// mayWrite answers whether this caller could write to the repository,
// WITHOUT challenging or refusing. gate answers the same question but
// as a decision that writes a response, which a page cannot use to
// decide whether to draw a control.
//
// It exists because the board's move control must follow write
// CAPABILITY, not session state: a caller authenticating with Basic
// auth can write and is not "signed in", and gating the control on
// SignedIn hid the only mechanism a no-script reader has for moving a
// card. Getting this wrong in the other direction is worse — a control
// shown to somebody who cannot use it — so it mirrors gateAt's decision
// rather than approximating it.
func mayWrite(verify Verify, sess Sessions, repo string, req *http.Request) bool {
	return mayAt(verify, sess, repo, ops.Token, req)
}

// mayAt is mayWrite at an explicit capability — the announcement
// control follows Admin the way the board's move control follows Token.
func mayAt(verify Verify, sess Sessions, repo string, level ops.Auth, req *http.Request) bool {
	if verify == nil {
		return true
	}
	if sess != nil {
		if user, ok := sess.Resolve(cookieToken(req)); ok {
			return sess.Allow(user, repo, level)
		}
	}
	user, pass, _ := req.BasicAuth()
	return verify(repo, user, pass, level) == api.Allowed
}

// viewer resolves who is LOOKING at a page, without ever challenging:
// session identity first, then Basic credentials — mayWrite's order.
// "" is anonymous. It personalizes reads (the lit arrow on a vote the
// viewer already cast); it grants nothing.
func viewer(verify Verify, sess Sessions, repo string, req *http.Request) string {
	if sess != nil {
		if user, ok := sess.Resolve(cookieToken(req)); ok {
			return user
		}
	}
	if user, pass, ok := req.BasicAuth(); ok && verify != nil &&
		verify(repo, user, pass, ops.Token) == api.Allowed {
		return user
	}
	return ""
}

// gateCap is gate() refined by capability (RFC 0004): the Auth floor
// authenticates, then the letters decide. A caller holding a session
// but not the letters gets forbid() — "better credentials are not what
// is missing" — never a challenge. Without a caps plane it is exactly
// gateAt(floor), so a forge with no accounts behaves as before.
func gateCap(caps Caps, verify Verify, sess Sessions, repo, letters string, floor ops.Auth, w http.ResponseWriter, req *http.Request) (*http.Request, bool) {
	req, ok := gateAt(verify, sess, repo, floor, w, req)
	if !ok {
		return nil, false
	}
	// No verifier means no auth model at all — gateAt waves everyone
	// through, and capabilities cannot be about a caller nobody
	// identifies. An ungated forge stays ungated.
	if verify == nil {
		return req, true
	}
	c, have := capsOf(caps, sess, verify, repo, req)
	if !have || c.HasAny(letters) {
		return req, true
	}
	forbid(w, viewer(verify, sess, repo, req), repo, floor)
	return nil, false
}

func gateAt(verify Verify, sess Sessions, repo string, level ops.Auth, w http.ResponseWriter, req *http.Request) (*http.Request, bool) {
	if verify == nil {
		return req, true
	}
	if sess != nil {
		if user, ok := sess.Resolve(cookieToken(req)); ok {
			if !sess.Allow(user, repo, level) {
				// Signed in, but without the capability on THIS
				// repository. A challenge would be a lie — better
				// credentials are not what is missing.
				forbid(w, user, repo, level)
				return nil, false
			}
			return req.WithContext(ops.WithUser(req.Context(), user)), true
		}
	}
	user, pass, _ := req.BasicAuth()
	switch verify(repo, user, pass, level) {
	case api.Allowed:
	case api.Insufficient:
		// Authenticated and short of the capability: a challenge would
		// invite the reader to type the same password again.
		forbid(w, user, repo, level)
		return nil, false
	default:
		if sess != nil && user == "" {
			// A browser with no credential gets the login page, not a
			// Basic prompt it cannot log out of.
			http.Redirect(w, req, "/login?next="+url.QueryEscape(req.URL.Path), http.StatusSeeOther)
			return nil, false
		}
		w.Header().Set("WWW-Authenticate", `Basic realm="quarry"`)
		w.WriteHeader(http.StatusUnauthorized)
		w.Write([]byte("authentication required"))
		return nil, false
	}
	return req.WithContext(ops.WithUser(req.Context(), user)), true
}

// forbid states what the signed-in user actually lacks. The fleet pages
// are not scoped to a repository, so a message naming one would be
// nonsense ("no write access to ”"); the level and the empty repo pick
// the honest wording.
// isEmptyRepo reports whether a registered repository simply has no
// check-ins yet, as opposed to not existing.
func isEmptyRepo(r *ops.Registry, req *http.Request, repo string) bool {
	out, err := invoke(req.Context(), r, "repo.counts", url.Values{"repo": {repo}})
	if err != nil {
		return false // unknown repository: a real not-found
	}
	var c struct {
		Checkins int `json:"checkins"`
	}
	remarshal(out, &c)
	return c.Checkins == 0
}

// deletable reports whether quarry created this repository's store, so
// the settings page can offer deletion only where it would work rather
// than offering it and failing.
// mirrorGate refuses a write PAGE on a read-only mirror the way the
// ops refuse the write itself: the page would only collect input the
// op is going to reject. The refusal names the upstream.
func mirrorGate(r *ops.Registry, w http.ResponseWriter, req *http.Request, repo string) bool {
	info, err := invoke(req.Context(), r, "repo.get", url.Values{"repo": {repo}})
	if err != nil {
		return true // an unknown repo fails later, with its own message
	}
	var p posture
	remarshal(info, &p)
	if !p.ReadOnly() {
		return true
	}
	fail(r, w, req, fmt.Errorf("%w: %s mirrors %s and does not accept local writes", ops.ErrForbidden, repo, p.Mirror.URL))
	return false
}

func deletable(r *ops.Registry, req *http.Request, repo string) bool {
	out, err := invoke(req.Context(), r, "repo.list", nil)
	if err != nil {
		return false
	}
	var rl struct {
		Repos []repoInfo `json:"repos"`
	}
	remarshal(out, &rl)
	for _, x := range rl.Repos {
		if x.Name == repo {
			return x.Deletable
		}
	}
	return false
}

// fleetHealth renders the admin page, optionally above the results of a
// sync or a pull the operator just ran.
func fleetHealth(r *ops.Registry, w http.ResponseWriter, req *http.Request,
	sync []fleetSyncRow, pulls []mirrorRunRow, tracker string) {
	out, err := invoke(req.Context(), r, "fleet.status", nil)
	if err != nil {
		fail(r, w, req, err)
		return
	}
	var fs struct {
		Repos      []fleetHealthRow `json:"repos"`
		Unhealthy  int              `json:"unhealthy"`
		Errors     []errlogRow      `json:"errors"`
		ErrorTotal int              `json:"errorTotal"`
	}
	remarshal(out, &fs)
	// Which panel. Default is stores: "are my repositories healthy" is
	// the question /fleet exists to answer.
	tab := req.URL.Query().Get("tab")
	if tab != "mirrors" {
		tab = "stores"
	}
	// The header box filters THIS page: on the fleet page "search"
	// means "find the store", and both tables narrow to the match.
	q := req.URL.Query().Get("q")
	if q != "" {
		kept := fs.Repos[:0]
		for _, row := range fs.Repos {
			if matchesRepo(q, row.Name) {
				kept = append(kept, row)
			}
		}
		fs.Repos = kept
	}
	data := pageData{
		Title: "Fleet", OwnH1: true, FleetHealth: fs.Repos, Unhealthy: fs.Unhealthy,
		SyncResults: sync, MirrorResults: pulls,
		ServerErrors: fs.Errors, ErrorTotal: fs.ErrorTotal, FleetTab: tab,
		TrackerRepo: tracker, Query: q, SearchScope: "fleet", SearchAction: "/fleet",
	}
	// mirror.list is absent when no mirror store is configured, which is
	// a forge that mirrors nothing rather than an error — the section
	// simply renders its empty state.
	if mo, err := invoke(req.Context(), r, "mirror.list", nil); err == nil {
		var ml struct {
			Mirrors []mirrorRow `json:"mirrors"`
		}
		remarshal(mo, &ml)
		data.MirrorCounts = map[string]int{}
		for _, m := range ml.Mirrors {
			if m.Enabled {
				data.MirrorCounts[m.State]++
				data.MirrorCounts["all"]++
			}
			if matchesRepo(q, m.Repo, m.URL, m.DetachedFrom) {
				data.Mirrors = append(data.Mirrors, m)
			}
		}
		if edit := req.URL.Query().Get("edit"); edit != "" {
			for i := range ml.Mirrors {
				if ml.Mirrors[i].Repo == edit {
					data.MirrorEdit = &ml.Mirrors[i]
				}
			}
		}
		// The confirmation pages for the two posture changes.
		if name := req.URL.Query().Get("detach"); name != "" {
			for i := range ml.Mirrors {
				if ml.Mirrors[i].Repo == name && ml.Mirrors[i].Enabled {
					data.MirrorEdit = &ml.Mirrors[i]
					data.Title = "detach " + name
					render(r, w, req, mirrorDetachPage, data)
					return
				}
			}
		}
		if name := req.URL.Query().Get("reattach"); name != "" {
			for i := range ml.Mirrors {
				if ml.Mirrors[i].Repo == name && !ml.Mirrors[i].Enabled {
					data.MirrorEdit = &ml.Mirrors[i]
					data.Title = "re-attach " + name
					render(r, w, req, mirrorReattachPage, data)
					return
				}
			}
		}
	}
	data.FleetRows, data.FleetProblems = fleetRows(data.FleetHealth, data.Mirrors)
	if req.URL.Path == "/fleet/tab.frag" {
		var buf bytes.Buffer
		buf.WriteString(`<div id="fleet-panel">`)
		if err := fleetAdminPage.ExecuteTemplate(&buf, "fleet-panel", data); err != nil {
			fail(r, w, req, err)
			return
		}
		buf.WriteString(`</div>`)
		w.Header().Set("Content-Type", "text/event-stream")
		fmt.Fprint(w, "event: datastar-patch-elements\n")
		for _, line := range strings.Split(buf.String(), "\n") {
			fmt.Fprintf(w, "data: elements %s\n", line)
		}
		fmt.Fprint(w, "\n")
		return
	}
	render(r, w, req, fleetAdminPage, data)
}

func forbid(w http.ResponseWriter, user, repo string, level ops.Auth) {
	w.WriteHeader(http.StatusForbidden)
	switch {
	case level >= ops.Admin && repo == "":
		fmt.Fprintf(w, "%s is not a site admin", user)
	case level >= ops.Admin:
		fmt.Fprintf(w, "%s has no admin access to %s", user, repo)
	default:
		fmt.Fprintf(w, "%s has no write access to %s", user, repo)
	}
}

// WithSessions attaches the cookie plane to a handler built by Handler.
// Kept separate from Handler's signature so a caller that only needs the
// Basic gate — every test, and single-user local serving — is unchanged.
// WithCaps supplies the capability resolver (RFC 0004) independently of
// the sessions plane: capability enforcement and cookie login are
// separate concerns, and an API-only forge wants the first without the
// second.
func WithCaps(c Caps) func(*handlerOpts) {
	return func(o *handlerOpts) { o.caps = c }
}

// WithEngine attaches the CI engine's read side (RFC 0009 §logs).
func WithEngine(e EngineViews) func(*handlerOpts) {
	return func(o *handlerOpts) { o.engine = e }
}

// WithCILogs attaches the forge's drained-log record.
func WithCILogs(l LogStore) func(*handlerOpts) {
	return func(o *handlerOpts) { o.cilogs = l }
}

// Protect is the branch-protection policy (RFC 0007), read and written
// by the settings page under `a`.
type Protect interface {
	Protections(repo string) ([]oltp.Protection, error)
	SetProtection(repo, branch string, owners []string) error
}

func WithProtect(p Protect) func(*handlerOpts) {
	return func(o *handlerOpts) { o.protect = p }
}

func WithSessions(s Sessions) func(*handlerOpts) {
	return func(o *handlerOpts) { o.sessions = s }
}

type handlerOpts struct {
	engine   EngineViews
	cilogs   LogStore
	caps     Caps
	protect  Protect
	sessions Sessions
	inbox    Inbox
	prefs    Prefs
	// attnEverywhere opens the attention stream on every page rather
	// than repository pages alone — see WithAttentionEverywhere.
	attnEverywhere bool
	hooks          Hooks
	tallies        Tallies
	praise         Praise
	evlog          EventLog
	// tracker names the repository whose ticket tracker is the forge's
	// own — where the fleet's "file ticket" buttons lead. Empty means
	// no such repo is designated and the buttons are not drawn.
	tracker string
}

// Hooks is the repository's webhook subscriptions — Principle 6's
// outbound surface, managed by the repository's own admin.
//
// An interface here rather than the oltp type for the same reason every
// other plane is: the web layer names what a settings screen needs, and
// the composition root owns where it is stored. nil means the section
// is not drawn at all, which is how a forge with no OLTP simply has no
// webhook settings.
type Hooks interface {
	Webhooks(repo string) ([]HookSub, error)
	AddWebhook(repo, url, events string) (HookSub, error)
	SetWebhookEvents(id int64, events string) error
	SetWebhookActive(id int64, active bool) error
	DeleteWebhook(id int64) error
}

// HookSub is one subscription as the settings screen shows it. Secret is
// populated only by AddWebhook — a signing key a listing can read back
// is a key that leaks through screenshots and shoulders.
type HookSub struct {
	ID      int64
	URL     string
	Events  string
	Active  bool
	Created string
	Secret  string
}

// hookList reads a repository's subscriptions for display. A store that
// errors renders an empty section rather than a broken page: the rest of
// the settings screen is still true and still usable.
func hookList(h Hooks, repo string) []HookSub {
	if h == nil {
		return nil
	}
	subs, err := h.Webhooks(repo)
	if err != nil {
		log.Printf("web: webhooks for %s: %v", repo, err)
		return nil
	}
	return subs
}

// oneTimeSecret carries a freshly minted signing key from the POST that
// created it to the one render that shows it. It exists only in the
// redirect; nothing stores it readable.
func oneTimeSecret(req *http.Request) string {
	return req.URL.Query().Get("s")
}

// EventLog reads what a repository has raised. A VIEW of the event
// stream, not a second copy of it — so it cannot disagree with what the
// forge actually published, and it costs no storage.
type EventLog interface {
	Recent(repo string, limit int) ([]LoggedEvent, error)
}

// LoggedEvent is one raised event as the log shows it.
type LoggedEvent struct {
	Kind    string
	Actor   string
	Summary string
	At      time.Time
}

// WithEventLog attaches the event log.
func WithEventLog(l EventLog) Option {
	return func(o *handlerOpts) { o.evlog = l }
}

// Praise is the forge's approval signal. Per ACCOUNT, not per
// contributor — someone who has never authored an artifact can still say
// a repository is worth attention, which is why the listing cannot hang
// off the contributor pages.
type Praise interface {
	Praised(repo, account string) bool
	PraiseCount(repo string) int
	PraisedBy(account string) ([]string, error)
}

// praisedRow is one entry in a praise listing: the repository, plus what
// a reader needs to decide whether to keep praising it.
type praisedRow struct {
	Repo        string
	Description string
	Praised     bool // whether the VIEWER praises it, which is not the owner's answer
}

// WithPraise attaches the praise store.
func WithPraise(p Praise) Option {
	return func(o *handlerOpts) { o.praise = p }
}

// Tallies reads the forge's counters (RFC 0005 operational events). A
// clone leaves no trace in the DAG — it reads, it writes nothing — so
// without a tally it is activity the forge cannot see at all.
type Tallies interface {
	Total(repo, name string) (int64, error)
}

// tallyOf reads one counter for display. A counter plane that errors
// renders no number rather than a wrong one or a broken page: the rest
// of the repository page is still true.
func tallyOf(t Tallies, repo, name string) int {
	if t == nil {
		return 0
	}
	n, err := t.Total(repo, name)
	if err != nil {
		log.Printf("web: tally %s/%s: %v", repo, name, err)
		return 0
	}
	return int(n)
}

// WithTallies attaches the counter plane.
func WithTallies(t Tallies) Option {
	return func(o *handlerOpts) { o.tallies = t }
}

// forkPointOf asks where a check-in's branch grew from. checkin.get
// already computes it, so this needs no new op and no subprocess.
func forkPointOf(r *ops.Registry, req *http.Request, repo, hash string) string {
	if hash == "" {
		return ""
	}
	out, err := invoke(req.Context(), r, "checkin.get",
		url.Values{"repo": {repo}, "hash": {hash}, "files": {"0"}})
	if err != nil {
		return ""
	}
	var got struct {
		Fork string `json:"fork"`
	}
	remarshal(out, &got)
	return got.Fork
}

// shortHash is the length quarry shows a hash at elsewhere.
func shortHash(h string) string {
	if len(h) > 12 {
		return h[:12]
	}
	return h
}

// WithHooks attaches the webhook store.
func WithHooks(h Hooks) Option {
	return func(o *handlerOpts) { o.hooks = h }
}

// WithTracker designates the forge's own issue tracker.
func WithTracker(repo string) Option {
	return func(o *handlerOpts) { o.tracker = repo }
}

// Option configures the handler beyond its required planes.
type Option func(*handlerOpts)

func Handler(r *ops.Registry, n Notifier, live ChatLive, v ...Verify) http.Handler {
	return HandlerWith(r, n, live, nil, v...)
}

// HandlerWith is Handler plus options; Handler is the common case.
// recovered wraps the whole handler tree: a panic becomes a recorded
// journal entry and a clean 500 instead of a dropped connection and a
// stack trace nobody sees.
func recovered(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		defer func() {
			if p := recover(); p != nil {
				err := fmt.Errorf("panic: %v", p)
				stack := string(debug.Stack())
				log.Printf("web: %s: %v\n%s", req.URL.Path, err, stack)
				// The stack goes to the JOURNAL, not only to stdout: a
				// trace nobody can reach from the panel is a trace
				// nobody reads, which is the whole reason this funnel
				// exists.
				errlog.Default.ReportIn("panic", req.URL.Path, req.PathValue("repo"), stack, err)
				// Headers may already be gone; best effort.
				http.Error(w, "internal error", http.StatusInternalServerError)
			}
		}()
		next.ServeHTTP(w, req)
	})
}

func HandlerWith(r *ops.Registry, n Notifier, live ChatLive, opts []Option, v ...Verify) http.Handler {
	var verify Verify
	if len(v) > 0 {
		verify = v[0]
	}
	o := &handlerOpts{}
	for _, fn := range opts {
		fn(o)
	}
	sessions := o.sessions
	capsPlane := o.caps
	protectPlane := o.protect
	inbox := o.inbox
	hooks := o.hooks
	tallies := o.tallies
	praise := o.praise
	evlog := o.evlog
	mux := http.NewServeMux()
	if sessions != nil {
		mux.HandleFunc("GET /login", func(w http.ResponseWriter, req *http.Request) {
			render(r, w, req, loginPage, pageData{
				Title: "sign in", LoginNext: safeNext(req.URL.Query().Get("next")),
			})
		})
		mux.HandleFunc("POST /login", func(w http.ResponseWriter, req *http.Request) {
			user, password := req.FormValue("user"), req.FormValue("password")
			next := safeNext(req.FormValue("next"))
			token, expires, ok := sessions.Login(user, password)
			if !ok {
				// One message for a bad name and a bad password: naming
				// which was wrong tells an attacker which accounts exist.
				w.WriteHeader(http.StatusUnauthorized)
				render(r, w, req, loginPage, pageData{
					Title: "sign in", LoginNext: next,
					Error: "That account and password do not match.",
				})
				return
			}
			setSession(w, req, token, expires)
			http.Redirect(w, req, next, http.StatusSeeOther)
		})
		mux.HandleFunc("POST /logout", func(w http.ResponseWriter, req *http.Request) {
			sessions.Logout(cookieToken(req))
			clearSession(w, req)
			http.Redirect(w, req, "/", http.StatusSeeOther)
		})
	}
	mux.HandleFunc("GET /people", func(w http.ResponseWriter, req *http.Request) {
		q := req.URL.Query().Get("q")
		// A page, not the fleet: at any real size this list is longer
		// than anyone scrolls, and rendering all of it helps nobody.
		const perPage = 50
		page, _ := strconv.Atoi(req.URL.Query().Get("page"))
		if page < 1 {
			page = 1
		}
		vals := url.Values{
			"limit":  {strconv.Itoa(perPage)},
			"offset": {strconv.Itoa((page - 1) * perPage)},
		}
		if q != "" {
			vals.Set("q", q)
		}
		out, err := invoke(req.Context(), r, "people.list", vals)
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var pl struct {
			People []personRow `json:"people"`
			Total  int         `json:"total"`
		}
		remarshal(out, &pl)
		data := pageData{Title: "people", HideH1: true, Explore: "people",
			Query: q, People: pl.People, PeopleTotal: pl.Total, Page: page}
		if page*perPage < pl.Total {
			data.NextPage = page + 1
		}
		if page > 1 {
			data.PrevPage = page - 1
		}
		// The other tab's count comes from its own op, so the pair of
		// numbers on the tabs always describes the same moment.
		if fo, err := invoke(req.Context(), r, "repo.list", nil); err == nil {
			var fl struct {
				Total int `json:"total"`
			}
			remarshal(fo, &fl)
			data.FleetTotal = fl.Total
		}
		render(r, w, req, peoplePage, data)
	})
	// One repository's people. Same op and same paging as the fleet
	// listing; the repo binding is the only difference, and rendering
	// inside the repo keeps a reader where they clicked from.
	mux.HandleFunc("GET /r/{repo}/people", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		q := req.URL.Query().Get("q")
		const perPage = 50
		page, _ := strconv.Atoi(req.URL.Query().Get("page"))
		if page < 1 {
			page = 1
		}
		vals := url.Values{
			"repo":   {repo},
			"limit":  {strconv.Itoa(perPage)},
			"offset": {strconv.Itoa((page - 1) * perPage)},
		}
		if q != "" {
			vals.Set("q", q)
		}
		out, err := invoke(req.Context(), r, "people.list", vals)
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var pl struct {
			People []personRow `json:"people"`
			Total  int         `json:"total"`
		}
		remarshal(out, &pl)
		data := pageData{Title: "people", OwnH1: true, Repo: repo,
			Query: q, People: pl.People, PeopleTotal: pl.Total, Page: page,
			CanAdmin: mayAt(verify, sessions, repo, ops.Admin, req)}
		// Which of these names is also an account with a grant HERE.
		// account.list is forge-wide and site-admin only, so a repo
		// admin gets the door without the badges rather than an error:
		// the badges are an extra, and the page is the same page.
		if data.CanAdmin {
			if ao, aerr := invoke(req.Context(), r, "account.list", nil); aerr == nil {
				var al struct {
					Accounts []struct {
						Name   string `json:"name"`
						Admin  bool   `json:"admin"`
						Grants []struct {
							Repo string `json:"repo"`
							Role string `json:"role"`
						} `json:"grants"`
					} `json:"accounts"`
				}
				remarshal(ao, &al)
				role := map[string]string{}
				for _, a := range al.Accounts {
					if a.Admin {
						role[a.Name] = "site admin"
					}
					for _, g := range a.Grants {
						if g.Repo == repo {
							role[a.Name] = g.Role
						}
					}
				}
				for i, p := range data.People {
					data.People[i].Role = role[p.User]
				}
			}
		}
		if page*perPage < pl.Total {
			data.NextPage = page + 1
		}
		if page > 1 {
			data.PrevPage = page - 1
		}
		render(r, w, req, repoPeoplePage, data)
	})
	mux.HandleFunc("GET /people/{user}", func(w http.ResponseWriter, req *http.Request) {
		want := req.PathValue("user")
		out, err := invoke(req.Context(), r, "people.list",
			url.Values{"q": {want}, "limit": {"500"}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var pl struct {
			People []personRow `json:"people"`
		}
		remarshal(out, &pl)
		// q is a substring filter, so an exact match must be picked out
		// of it: "dan" must not open "dan.mestas".
		for _, p := range pl.People {
			if p.User == want {
				render(r, w, req, personPage, pageData{Title: p.User, HideH1: true, Person: p})
				return
			}
		}
		fail(r, w, req, fmt.Errorf("no contributor %q: %w", want, ops.ErrNotFound))
	})
	mux.HandleFunc("GET /licenses", func(w http.ResponseWriter, req *http.Request) {
		notices, err := legal.Notices()
		if err != nil {
			fail(r, w, req, err)
			return
		}
		render(r, w, req, licensesPage, pageData{Title: "licenses",
			Notices: notices, QuarryLicence: legal.Quarry})
	})
	mux.HandleFunc("GET /privacy", func(w http.ResponseWriter, req *http.Request) {
		render(r, w, req, privacyPage, pageData{Title: "privacy"})
	})
	mux.HandleFunc("POST /theme", func(w http.ResponseWriter, req *http.Request) {
		to := req.FormValue("to")
		if !slices.Contains(themeCycle, to) {
			http.Error(w, "unknown theme", http.StatusBadRequest)
			return
		}
		c := &http.Cookie{Name: themeCookie, Value: to, Path: "/",
			HttpOnly: true, SameSite: http.SameSiteLaxMode, MaxAge: 400 * 24 * 60 * 60}
		if to == "" {
			// "Follow the system" is the absence of a choice, so it
			// removes the cookie rather than storing a third value.
			c.MaxAge, c.Expires = -1, time.Unix(0, 0)
		}
		http.SetCookie(w, c)
		// Back to the page the reader was on. Only a same-site path is
		// honoured: an open redirect here would let any page bounce a
		// reader off this origin through a control they expect to be
		// inert.
		http.Redirect(w, req, localRef(req), http.StatusSeeOther)
	})
	// The inbox page exists wherever sessions do, not only where notify
	// does: RFC 0011 §5's whole point is that a forge with no notify
	// still tells people what was addressed to them, and this is where
	// they clear it and set how they are told.
	if sessions != nil {
		mux.HandleFunc("GET /inbox", func(w http.ResponseWriter, req *http.Request) {
			user, ok := sessions.Resolve(cookieToken(req))
			if !ok {
				http.Redirect(w, req, "/login?next=%2Finbox", http.StatusSeeOther)
				return
			}
			data := pageData{Title: "inbox"}
			ctx := ops.WithUser(req.Context(), user)
			// One list, one op. `inbox.list` merges notify's messages
			// with quarry's own attention events and hands back the
			// cursor that addresses both — a page that merged them
			// itself would be a second implementation of the order,
			// the ids and the read state (RFC 0011 §6).
			data.AttnBefore = req.URL.Query().Get("before")
			rows, next, err := inboxRowsOf(ctx, r, data.AttnBefore, inboxPageRows)
			if err != nil {
				// An outage is not an empty inbox; an empty list and a
				// failure are different answers.
				log.Printf("web: inbox for %s: %v", user, err)
				data.Error = "Notifications are unavailable right now."
			}
			data.AttnNext = next
			// A mark that failed redirected back here saying so; the
			// row it was clicked on is still in the list, unmarked.
			if req.URL.Query().Get("err") == "mark" && data.Error == "" {
				data.Error = inboxMarkError
			}
			// The count and the switch are the page's own state, so it
			// is right on load with no stream and no script (Principle 3).
			if n, err := attentionUnread(ctx, r); err == nil {
				data.AttnUnread = n
			}
			data.HasNotify = inbox != nil
			data.AttnFilter = inboxFilter(req.URL.Query().Get("f"))
			data.AttnTabs = attnFilters(rows, data.AttnFilter)
			data.AttnRecent = slices.DeleteFunc(rows, func(row attnRow) bool {
				return !attnMatches(data.AttnFilter, row)
			})
			data.AttnEmpty = inboxEmptyLine(data.AttnFilter)
			data.HasPrefs = o.prefs != nil
			data.NotifyDesktop = o.prefs != nil && o.prefs.Pref(user, notifyDesktopPref) == "on"
			data.AttnToasts = o.prefs != nil && o.prefs.Pref(user, toastsPref) == "on"
			render(r, w, req, inboxPage, data)
		})
		// "Mark all read" clears the whole inbox; a row's own control
		// clears that row. One op either way (`inbox.mark`), so both
		// halves of the list — notify's messages and quarry's attention
		// events — are cleared by the same control, and the badge the
		// count is measured from moves with them.
		//
		// The two halves clear DIFFERENTLY, and the page says so rather
		// than pretending otherwise: a notify message can be archived
		// (`done` — off the list), while a local attention event has no
		// per-item archive, so its control marks it read and the row
		// stays, read. The live patch removes a row only where a reload
		// would also stop showing it.
		mux.HandleFunc("POST /inbox/mark", func(w http.ResponseWriter, req *http.Request) {
			user, ok := sessions.Resolve(cookieToken(req))
			if !ok {
				http.Redirect(w, req, "/login?next=%2Finbox", http.StatusSeeOther)
				return
			}
			filter := inboxFilter(req.FormValue("f"))
			as := req.FormValue("as")
			if as != "done" && as != "read" {
				as = "read"
			}
			form := url.Values{"as": {as}}
			all := req.FormValue("all") != ""
			if all {
				form.Set("all", "true")
			}
			var ids []string
			for _, id := range req.Form["id"] {
				// The id is echoed back into a CSS selector below, so
				// it is checked here rather than trusted: it is a
				// notify message id or "local:<seq>", and anything
				// else is not a row this page drew.
				if inboxMarkableID(id) {
					form.Add("ids", id)
					ids = append(ids, id)
				}
			}
			back := "/inbox?f=" + url.QueryEscape(filter)
			if before := req.FormValue("before"); before != "" {
				back += "&before=" + url.QueryEscape(before)
			}
			if _, err := invoke(ops.WithUser(req.Context(), user), r,
				"inbox.mark", form); err != nil {
				// A mark that did not land must not look like one that
				// did: nothing is taken off the page, and the page says
				// what happened.
				log.Printf("web: inbox.mark for %s: %v", user, err)
				if req.Header.Get("datastar-request") != "true" {
					http.Redirect(w, req, back+"&err=mark", http.StatusSeeOther)
					return
				}
				markOneShot(w)
				w.Header().Set("Content-Type", "text/event-stream")
				fmt.Fprint(w, "event: datastar-patch-elements\n")
				fmt.Fprintf(w, "data: elements %s\n\n", inboxErrorHTML(inboxMarkError))
				return
			}
			// A datastar submit takes the row off the page where it
			// stands; a plain form submit gets the redirect it always
			// did, back to the filter and page it was sent from
			// (Principle 3).
			if all || req.Header.Get("datastar-request") != "true" {
				http.Redirect(w, req, back, http.StatusSeeOther)
				return
			}
			markOneShot(w)
			w.Header().Set("Content-Type", "text/event-stream")
			for _, id := range ids {
				// Removed only where a reload agrees: an archived
				// notify row is gone from the list, and a row marked
				// read is gone from the unread tab. Anywhere else the
				// row stays and the next load redraws it read.
				if as != "done" && filter != "unread" {
					continue
				}
				fmt.Fprint(w, "event: datastar-patch-elements\n")
				fmt.Fprint(w, "data: mode remove\n")
				fmt.Fprintf(w, "data: selector #%s\n\n", attnRow{ID: id}.ElemID())
			}
		})
		// The preferences page and the push routes (RFC 0011 §6). They
		// live wherever sessions do, for the inbox's reason: a forge
		// with no notify still owns the forge-local switches and the
		// mutes, and the push control says honestly that it cannot work.
		registerPrefs(mux, r, sessions)
		// The attention stream as Datastar patches (RFC 0011 §5). The
		// base layout opens it on repository pages, or everywhere when
		// the deployment says it multiplexes.
		mux.HandleFunc("GET /me.sse", func(w http.ResponseWriter, req *http.Request) {
			user, ok := sessions.Resolve(cookieToken(req))
			if !ok {
				// The stream is opened by the layout only for a
				// signed-in reader, so an anonymous request here is a
				// mistake or a probe — and an empty 200 tells it it
				// succeeded. It costs nothing to say otherwise.
				http.Error(w, "the attention stream needs a signed-in account",
					http.StatusUnauthorized)
				return
			}
			serveAttention(r, o.prefs, user, w, req)
		})
	}
	if inbox != nil && sessions != nil {
		mux.HandleFunc("GET /inbox.unread", func(w http.ResponseWriter, req *http.Request) {
			// The bar's dot on a page with no stream open: fired lazily
			// after render, so no page ever waits on notify to draw.
			// Anonymous or outage answers "no dot" — a decoration must
			// never 500 a page.
			w.Header().Set("Content-Type", "text/event-stream")
			user, ok := sessions.Resolve(cookieToken(req))
			if !ok {
				return
			}
			msgs, err := inbox.Messages(req.Context(), user)
			if err != nil {
				return
			}
			unread := 0
			for _, m := range msgs {
				if !m.Read {
					unread++
				}
			}
			if unread == 0 {
				return
			}
			fmt.Fprint(w, "event: datastar-patch-elements\n")
			fmt.Fprintf(w, "data: elements %s\n\n", inboxDotHTML(unread))
		})
	}
	// The mark. Immutable per build and small, so it is cached hard —
	// a favicon refetched on every page load is the most pointless
	// request a site can make.
	icon := func(ctype string, body []byte) http.HandlerFunc {
		return func(w http.ResponseWriter, _ *http.Request) {
			w.Header().Set("Content-Type", ctype)
			w.Header().Set("Cache-Control", "public, max-age=604800")
			w.Write(body)
		}
	}
	mux.HandleFunc("GET /favicon.ico", icon("image/x-icon", faviconICO))
	mux.HandleFunc("GET /apple-touch-icon.png", icon("image/png", appleTouchIcon))
	mux.HandleFunc("GET /assets/quarry.png", icon("image/png", markPNG))
	mux.HandleFunc("GET /assets/composer.js", func(w http.ResponseWriter, _ *http.Request) {
		w.Header().Set("Content-Type", "text/javascript; charset=utf-8")
		w.Header().Set("Cache-Control", "public, max-age=86400")
		w.Write(composerJS)
	})
	mux.HandleFunc("GET /assets/wiki.js", func(w http.ResponseWriter, _ *http.Request) {
		w.Header().Set("Content-Type", "text/javascript; charset=utf-8")
		w.Header().Set("Cache-Control", "public, max-age=86400")
		w.Write(wikiJS)
	})
	mux.HandleFunc("GET /assets/datastar.js", func(w http.ResponseWriter, _ *http.Request) {
		w.Header().Set("Content-Type", "text/javascript; charset=utf-8")
		w.Header().Set("Cache-Control", "public, max-age=86400")
		w.Write(datastarJS)
	})
	// The cross-repository tracker: the same report machinery as one
	// repository's, asked of every tracker the reader can reach. A
	// person's work does not live in one repository, so this is the page
	// that answers "what is on me" — the repository becomes one more
	// browse axis rather than the address.
	// Saving and forgetting a view. Both are ordinary form posts that
	// return the reader to the listing they were on: naming a report is
	// not a place you go, it is something you do where you already are.
	// Where the listing lives comes from the form, but only ever as one
	// of the two paths this forge serves — a redirect target taken from
	// a request is an open redirect unless it is checked.
	mux.HandleFunc("POST /views", func(w http.ResponseWriter, req *http.Request) {
		id, ok := req.Context().Value(ctxIdentity{}).(identity)
		if !ok || id.user == "" {
			http.Error(w, "sign in to save a view", http.StatusUnauthorized)
			return
		}
		if err := req.ParseForm(); err != nil {
			http.Error(w, "bad form", http.StatusBadRequest)
			return
		}
		repo := req.FormValue("repo")
		_, err := invoke(ops.WithUser(req.Context(), id.user), r, "view.save", url.Values{
			"repo": {repo}, "name": {req.FormValue("name")},
			"query": {req.FormValue("query")}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		http.Redirect(w, req, listingPath(repo, req.FormValue("query")), http.StatusSeeOther)
	})
	mux.HandleFunc("POST /views/delete", func(w http.ResponseWriter, req *http.Request) {
		id, ok := req.Context().Value(ctxIdentity{}).(identity)
		if !ok || id.user == "" {
			http.Error(w, "sign in to forget a view", http.StatusUnauthorized)
			return
		}
		if err := req.ParseForm(); err != nil {
			http.Error(w, "bad form", http.StatusBadRequest)
			return
		}
		repo := req.FormValue("repo")
		if _, err := invoke(ops.WithUser(req.Context(), id.user), r, "view.delete", url.Values{
			"repo": {repo}, "name": {req.FormValue("name")}}); err != nil {
			fail(r, w, req, err)
			return
		}
		http.Redirect(w, req, listingPath(repo, ""), http.StatusSeeOther)
	})
	mux.HandleFunc("GET /tickets", func(w http.ResponseWriter, req *http.Request) {
		id, ok := req.Context().Value(ctxIdentity{}).(identity)
		if !ok || id.user == "" {
			// Nothing here exists without an identity to scope it to.
			http.Redirect(w, req, "/login?next=/tickets", http.StatusSeeOther)
			return
		}
		q := req.URL.Query()
		// The query box is input sugar here too, and canonicalises to
		// this page's URL rather than a repository's.
		if q.Has("q") {
			v := ticketParseQuery(q.Get("q"))
			for _, k := range []string{"view", "sort", "order", "repo"} {
				if x := q.Get(k); x != "" {
					v.Set(k, x)
				}
			}
			dest := "/tickets"
			if len(v) > 0 {
				dest += "?" + v.Encode()
			}
			http.Redirect(w, req, dest, http.StatusSeeOther)
			return
		}
		// Awaiting is a view, not an axis: it names its own author and
		// state, so it cannot be combined with a report that would
		// contradict it.
		awaiting := q.Get("awaiting") == "1"
		state := ticketState(q)
		report := ticketReportAcross(q)
		if awaiting {
			state, report = "", url.Values{}
		}
		title := strings.TrimSpace(q.Get("title"))
		view := q.Get("view")
		if view != "table" {
			// No board: its lanes are one tracker's vocabulary, and K
			// trackers do not share one.
			view = ""
		}
		order := q.Get("order")
		if _, ok := index.TicketOrders[order]; !ok {
			order = ""
		}
		sortBy := ""
		if q.Get("sort") == "recent" {
			sortBy = "recent"
		}
		byPriority := view != "table" && sortBy != "recent"
		vals := url.Values{"limit": {strconv.Itoa(acrossLimit)}}
		if awaiting {
			vals.Set("awaiting", "1")
		}
		if state != "" {
			vals.Set("state", state)
		}
		if view == "table" && order != "" {
			vals.Set("order", order)
		}
		if title != "" {
			vals.Set("title", title)
		}
		for k, vs := range report {
			vals[k] = vs
		}
		out, err := invoke(ops.WithUser(req.Context(), id.user), r, "ticket.across", vals)
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var tl struct {
			Tickets []struct {
				ticketSummary
				Repo string `json:"repo"`
			} `json:"tickets"`
			Open       int           `json:"open"`
			Closed     int           `json:"closed"`
			Repos      []ticketFacet `json:"repos"`
			Subsystems []ticketFacet `json:"subsystems"`
			Authors    []ticketFacet `json:"authors"`
			Truncated  bool          `json:"truncated"`
		}
		remarshal(out, &tl)
		// One vocabulary cannot describe K trackers, so the chips and the
		// triage order here use the defaults rather than any one
		// repository's words — the alternative is showing repository A's
		// idea of "urgent" against repository B's rows.
		vocab := ticketVocabFor(r, req, "")
		var rows []ticketRow
		for _, t := range tl.Tickets {
			rows = append(rows, ticketRows(t.Repo, []ticketSummary{t.ticketSummary}, vocab)...)
		}
		if byPriority {
			byTriageRows(rows, vocab)
		}
		nav := ticketNav{Base: "/tickets", State: state, Sort: sortBy, View: view,
			Order: order, Title: title, Open: tl.Open, Closed: tl.Closed,
			Report: report}
		nav.Awaiting = awaiting
		data := pageData{Title: "tickets", HideH1: true, Across: true,
			Rows: rows, ByPriority: byPriority, Nav: nav,
			Filters: ticketFiltersAcross(vocab, tl.Subsystems, tl.Authors, tl.Repos, q),
			Columns: ticketColumns,
			Shown:   len(rows), Truncated: tl.Truncated}
		data.Rail = ticketRail(data.Nav, tl.Subsystems, tl.Authors, tl.Repos, id.user,
			savedViewsFor(r, req, id.user, ""))
		data.CanSaveView, data.SaveTarget = id.user != "", ""
		if view == "table" {
			render(r, w, req, ticketTablePage, data)
			return
		}
		render(r, w, req, ticketListPage, data)
	})
	mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, req *http.Request) {
		// A signed-in reader's landing page is their dashboard —
		// GitHub's rule. The fleet stays one query param away
		// (?view=explore) and IS the page for everyone anonymous. A
		// filter or sort in the URL means the reader is exploring, so
		// those stay on the fleet too.
		if id, ok := req.Context().Value(ctxIdentity{}).(identity); ok && id.user != "" &&
			req.URL.Query().Get("view") != "explore" && req.URL.Query().Get("q") == "" &&
			req.URL.Query().Get("sort") == "" {
			q := req.URL.Query()
			kind, find := q.Get("kind"), strings.TrimSpace(q.Get("find"))
			ctx := ops.WithUser(req.Context(), id.user)
			offset := 0
			if n, aerr := strconv.Atoi(q.Get("offset")); aerr == nil && n > 0 {
				offset = n
			}
			mf, err := invoke(ctx, r, "me.feed", url.Values{
				"kind": {kind}, "find": {find}, "offset": {strconv.Itoa(offset)}})
			if err == nil {
				var out dashData
				remarshal(mf, &out)
				out.Kind, out.Find, out.Offset = kind, find, offset
				out.CanCreate = id.isAdmin
				// The pager measures what it can reach, never the corpus:
				// numbering ten thousand pages a reader cannot walk is
				// a control that lies about where it goes.
				if len(out.Feed) > 0 && (offset > 0 || len(out.Feed) < out.Depth) {
					p := &pager{From: offset + 1, To: offset + len(out.Feed), Total: out.Depth,
						Steps: pageSteps(offset, dashFeedSize, out.Depth, out.PageURL)}
					if offset > 0 {
						p.Prev = out.PageURL(offset - dashFeedSize)
					}
					if p.To < out.Depth {
						p.Next = out.PageURL(offset + dashFeedSize)
					}
					out.Pager = p
				}
				// The band that leads the page: the caller's open
				// tickets somebody else has answered and left with
				// them. A dashboard is a glance, so it shows the few
				// and links to the rest.
				if aw, aerr := invoke(ctx, r, "ticket.across",
					url.Values{"awaiting": {"1"}, "limit": {"6"}}); aerr == nil {
					var tl struct {
						Tickets []struct {
							ticketSummary
							Repo string `json:"repo"`
						} `json:"tickets"`
					}
					remarshal(aw, &tl)
					for _, t := range tl.Tickets {
						out.Awaiting = append(out.Awaiting,
							ticketRows(t.Repo, []ticketSummary{t.ticketSummary}, nil)...)
					}
				}
				data := pageData{Title: "home", HideH1: true, Dash: &out}
				// The explore link names the fleet's size, so "where are
				// the rest of the repositories" answers itself.
				if ro, rerr := invoke(req.Context(), r, "repo.list", url.Values{"limit": {"1"}}); rerr == nil {
					var rl struct {
						Total int `json:"total"`
					}
					remarshal(ro, &rl)
					data.FleetTotal = rl.Total
				}
				render(r, w, req, dashboardPage, data)
				return
			}
			// No grants, no accounts plane, any failure: the fleet is
			// the honest fallback, never an error page for "/".
			log.Printf("web: dashboard for %s: %v", id.user, err)
		}
		q, sortBy, kind := req.URL.Query().Get("q"), req.URL.Query().Get("sort"), req.URL.Query().Get("kind")
		if sortBy == "" {
			sortBy = "name"
		}
		out, err := invoke(req.Context(), r, "repo.list",
			url.Values{"q": {q}, "sort": {sortBy}, "kind": {kind}, "limit": {"100"}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var fl struct {
			Repos  []repoInfo `json:"repos"`
			Total  int        `json:"total"`
			Served int        `json:"served"`
		}
		remarshal(out, &fl)
		// The forge names itself in the top bar on every page, so the
		// aggregate page repeating it as a heading says nothing. The
		// heading stays in the document for structure and screen
		// readers; it is the visible duplicate that goes.
		peopleTotal := 0
		if po, err := invoke(req.Context(), r, "people.list", url.Values{"limit": {"1"}}); err == nil {
			var pl struct {
				Total int `json:"total"`
			}
			remarshal(po, &pl)
			peopleTotal = pl.Total
		}
		data := pageData{Title: "repositories", HideH1: true, PeopleTotal: peopleTotal,
			Fleet: fl.Repos, FleetTotal: fl.Total, Served: fl.Served,
			Query: q, Sort: sortBy, Kind: kind}
		if n != nil {
			data.Live = true
		}
		render(r, w, req, fleetPage, data)
	})
	settingsFor := func(req *http.Request, repo string) (info repoInfo) {
		out, err := invoke(req.Context(), r, "repo.get", url.Values{"repo": {repo}})
		if err != nil {
			return repoInfo{}
		}
		remarshal(out, &info)
		return info
	}
	// settingsData builds the WHOLE settings page. One builder, because
	// the page has a dozen panels and the description form used to
	// render it from seven fields of its own: after Save, every panel
	// below the form vanished and a stray h1 appeared, since the two
	// sites had quietly drifted apart. A second copy of this list is
	// the bug, so there is only one.
	settingsData := func(req *http.Request, repo string) pageData {
		info := settingsFor(req, repo)
		return pageData{
			Title: "settings", HideH1: true, Repo: repo,
			RepoDescription: info.Description, RepoPrivate: info.Private,
			RepoHomepage: info.Homepage, RepoTopics: info.Topics,
			Caps:             capsPanelFor(capsPlane, repo),
			Protect:          protectPanelFor(protectPlane, repo),
			Roster:           rosterFor(capsPlane, protectPanelFor(protectPlane, repo), repo),
			Visibility:       visibilityFor(capsPlane, repo),
			Fossil:           fossilPanelFor(r, req, repo),
			CITokens:         ciTokenPanelFor(r, req, repo),
			Workers:          workersOf(o.engine),
			NewReporterToken: req.URL.Query().Get("rt"),
			NewWorkerToken:   req.URL.Query().Get("wt"),
			CITagsMode:       ciTagsModeOf(capsPlane, repo),
			CloneURL:         cloneURL(req, repo), Deletable: deletable(r, req, repo),
			HasHooks: hooks != nil, Hooks: hookList(hooks, repo),
			HasRobot: robotRegistered(r), ChatRobot: robotPatternsOf(r, req, repo),
			EventNouns:    evt.Nouns(),
			RobotNouns:    robotNouns(o.engine != nil),
			NewHookSecret: oneTimeSecret(req),
			// A refused pattern comes back on the query string, because
			// the POST redirects: saying nothing would leave the owner
			// looking at an unchanged field with no idea why.
			Error: req.URL.Query().Get("e"),
		}
	}
	workerTokensInto := func(data *pageData) {
		if o.engine == nil {
			return
		}
		ts, err := o.engine.WorkerTokens()
		if err != nil {
			// The client's errors are prefixed for logs; a settings
			// page speaks prose.
			data.WorkerTokensErr = strings.TrimPrefix(err.Error(), "ci: ")
			return
		}
		data.WorkerTokens = ts
	}
	mux.HandleFunc("GET /r/{repo}/settings", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateAt(verify, sessions, repo, ops.Admin, w, req)
		if !ok {
			return
		}
		data := settingsData(req, repo)
		workerTokensInto(&data)
		data.SavedPanel = takeFlash(w, req)
		data.Saved = data.SavedPanel != ""
		render(r, w, req, settingsPage, data)
	})
	// One POST for every webhook action, discriminated by the button.
	// Five endpoints for add/save/pause/resume/delete would be five
	// places to forget the capability gate; one is one.
	// The event log. Gated on reading the repository and nothing more:
	// these are the events that repository raised, so anyone who may see
	// the repository may see what happened in it.
	mux.HandleFunc("GET /r/{repo}/events", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		// No session gate. Every other repository page — timeline,
		// forum, landings — leaves visibility entirely to the ops layer,
		// and a gateAt here made this the one page a public repository
		// would not show an anonymous reader.
		//
		// It is safe to be as public as the timeline because of what is
		// on it. The derived events restate artifacts the timeline
		// already shows, so they leak nothing new. The operational ones
		// carry no identity at all — Counted is func(repo, clone bool),
		// with no user and no address anywhere in the path — so a clone
		// event says how many, never who.
		if _, err := invoke(req.Context(), r, "repo.get", url.Values{"repo": {repo}}); err != nil {
			fail(r, w, req, err)
			return
		}
		if evlog == nil {
			http.NotFound(w, req)
			return
		}
		events, err := evlog.Recent(repo, 100)
		if err != nil {
			log.Printf("web: events for %s: %v", repo, err)
		}
		render(r, w, req, eventsPage, pageData{
			Title: "events", HideH1: true, Repo: repo,
			Events: events, EventWindow: "24 hours",
		})
	})
	// Praise: one POST, and it carries the DESIRED state rather than
	// toggling. A double-submit or a retried request then lands where
	// the reader pressed instead of on the opposite of it.
	mux.HandleFunc("POST /r/{repo}/praise", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		back := safeNext(req.FormValue("back"))
		if back == "" {
			back = "/r/" + repo
		}
		// Praise is attributable, so the op runs AS the signed-in
		// account. Anonymous is refused by the op rather than here, so
		// there is one place that rule lives.
		user := ""
		if sessions != nil {
			user, _ = sessions.Resolve(cookieToken(req))
		}
		_, err := invoke(ops.WithUser(req.Context(), user), r, "praise.set", url.Values{
			"repo": {repo}, "on": {req.FormValue("on")},
		})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		http.Redirect(w, req, back, http.StatusSeeOther)
	})
	// The listing. Defaults to the signed-in account; ?user= views
	// somebody else's, filtered to what the VIEWER may read.
	mux.HandleFunc("GET /praised", func(w http.ResponseWriter, req *http.Request) {
		me := ""
		if sessions != nil {
			me, _ = sessions.Resolve(cookieToken(req))
		}
		who := req.URL.Query().Get("user")
		mine := who == "" || who == me
		if who == "" {
			who = me
		}
		if who == "" {
			http.Redirect(w, req, "/login?next=%2Fpraised", http.StatusSeeOther)
			return
		}
		out, err := invoke(req.Context(), r, "praise.list", url.Values{"user": {who}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var pl struct {
			Repos []string `json:"repos"`
		}
		remarshal(out, &pl)
		rows := make([]praisedRow, 0, len(pl.Repos))
		for _, name := range pl.Repos {
			row := praisedRow{Repo: name}
			if praise != nil && me != "" {
				row.Praised = praise.Praised(name, me)
			}
			rows = append(rows, row)
		}
		render(r, w, req, praisedPage, pageData{
			Title: "praised", HideH1: true,
			PraisedRepos: rows, PraiseOwner: who, PraiseIsMine: mine,
			CanPraise: me != "",
		})
	})
	mux.HandleFunc("POST /r/{repo}/settings/hooks", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "a", ops.Admin, w, req)
		if !ok {
			return
		}
		if hooks == nil {
			http.NotFound(w, req)
			return
		}
		q := url.Values{}
		id, _ := strconv.ParseInt(req.FormValue("id"), 10, 64)
		events := strings.TrimSpace(req.FormValue("events"))
		var err error
		switch req.FormValue("do") {
		case "add":
			if err = evt.CheckPatterns(events); err == nil {
				var sub HookSub
				// The secret rides back on the URL because it is shown
				// exactly once and there is nowhere else to put it: it
				// is never stored readable, so a redirect that dropped
				// it would lose it for good.
				if sub, err = hooks.AddWebhook(repo, strings.TrimSpace(req.FormValue("url")), events); err == nil {
					q.Set("s", sub.Secret)
				}
			}
		case "events":
			if err = evt.CheckPatterns(events); err == nil {
				err = hooks.SetWebhookEvents(id, events)
			}
		case "pause":
			err = hooks.SetWebhookActive(id, false)
		case "resume":
			err = hooks.SetWebhookActive(id, true)
		case "delete":
			err = hooks.DeleteWebhook(id)
		}
		if err != nil {
			q.Set("e", err.Error())
		}
		back := "/r/" + repo + "/settings"
		if len(q) > 0 {
			back += "?" + q.Encode()
		}
		http.Redirect(w, req, back+"#webhooks", http.StatusSeeOther)
	})
	mux.HandleFunc("POST /r/{repo}/settings/robot", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "a", ops.Admin, w, req)
		if !ok {
			return
		}
		q := url.Values{}
		// The op owns the rule: it refuses a pattern no event can match,
		// the same refusal the API and the CLI give, and the message
		// comes back on the query string because the POST redirects.
		if _, err := invoke(req.Context(), r, "chat.robot", url.Values{
			"repo": {repo}, "events": {strings.TrimSpace(req.FormValue("events"))},
		}); err != nil {
			q.Set("e", strings.TrimSuffix(err.Error(), ": invalid request"))
		}
		back := "/r/" + repo + "/settings"
		if len(q) > 0 {
			back += "?" + q.Encode()
		}
		http.Redirect(w, req, back+"#robot", http.StatusSeeOther)
	})
	mux.HandleFunc("POST /r/{repo}/settings/protect", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "a", ops.Admin, w, req)
		if !ok {
			return
		}
		if protectPlane == nil {
			setFlash(w, req, "protect")
			http.Redirect(w, req, "/r/"+repo+"/settings", http.StatusSeeOther)
			return
		}
		if err := req.ParseForm(); err != nil {
			fail(r, w, req, err)
			return
		}
		// Rows arrive as branch-N / owners-N pairs. A row whose branch
		// was renamed is a delete of the old rule and a write of the
		// new one, so the stored set is rebuilt from the form: every
		// existing rule the form no longer names is cleared first.
		current, err := protectPlane.Protections(repo)
		if err != nil {
			fail(r, w, req, err)
			return
		}
		named := map[string]bool{}
		for i := 0; ; i++ {
			b, ok := req.Form["branch-"+strconv.Itoa(i)]
			if !ok {
				break
			}
			branch := strings.TrimSpace(strings.Join(b, ""))
			if branch == "" {
				continue
			}
			named[branch] = true
			owners := strings.Fields(strings.Join(req.Form["owners-"+strconv.Itoa(i)], " "))
			if err := protectPlane.SetProtection(repo, branch, owners); err != nil {
				fail(r, w, req, err)
				return
			}
			if ck, isCk := protectPlane.(ChecksAdmin); isCk {
				checks := strings.Fields(strings.Join(req.Form["checks-"+strconv.Itoa(i)], " "))
				mode := ""
				if req.FormValue("premerge-"+strconv.Itoa(i)) == "1" {
					mode = "premerge"
				}
				if err := ck.SetCheckRule(repo, branch, checks, mode); err != nil {
					fail(r, w, req, err)
					return
				}
			}
		}
		for _, c := range current {
			if !named[c.Branch] {
				if err := protectPlane.SetProtection(repo, c.Branch, nil); err != nil {
					fail(r, w, req, err)
					return
				}
			}
		}
		if ck, isCk := protectPlane.(ChecksAdmin); isCk {
			if cr, isR := protectPlane.(ChecksRules); isR {
				if crs, err := cr.CheckRules(repo); err == nil {
					for _, c := range crs {
						if !named[c.Branch] {
							if err := ck.SetCheckRule(repo, c.Branch, nil, ""); err != nil {
								fail(r, w, req, err)
								return
							}
						}
					}
				}
			}
		}
		setFlash(w, req, "protect")
		http.Redirect(w, req, "/r/"+repo+"/settings#protected", http.StatusSeeOther)
	})
	mux.HandleFunc("POST /r/{repo}/settings/caps", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "a", ops.Admin, w, req)
		if !ok {
			return
		}
		admin, isAdmin := capsPlane.(CapsAdmin)
		if !isAdmin {
			setFlash(w, req, "caps")
			http.Redirect(w, req, "/r/"+repo+"/settings", http.StatusSeeOther)
			return
		}
		if err := req.ParseForm(); err != nil {
			fail(r, w, req, err)
			return
		}
		warn := ""
		for key, vals := range req.Form {
			if len(vals) == 0 {
				continue
			}
			// Whitespace is not a capability; a stray space would
			// silently become a letter nobody can read.
			v := strings.Join(strings.Fields(vals[0]), "")
			switch {
			case strings.HasPrefix(key, "cat-"):
				if err := admin.SetCategoryCaps(repo, strings.TrimPrefix(key, "cat-"), v); err != nil {
					fail(r, w, req, err)
					return
				}
			case strings.HasPrefix(key, "acct-"):
				// Audit follow-up (ticket ed5bdd89c39a): the Advanced
				// form no longer renders acct- inputs, but the handler
				// still honors them — so it honors the guard too, or a
				// stale page could make the save the editor refuses.
				name := strings.TrimPrefix(key, "acct-")
				if g, isGuard := capsPlane.(CapsGuard); isGuard {
					w2, err := g.GuardCaps(viewer(verify, sessions, repo, req), name, repo, v)
					if oltp.IsRefusal(err) {
						http.Redirect(w, req, "/r/"+repo+"/settings?e="+url.QueryEscape(err.Error())+"#access", http.StatusSeeOther)
						return
					}
					if err != nil {
						fail(r, w, req, err)
						return
					}
					if w2 != "" && warn == "" {
						warn = w2
					}
				}
				if err := admin.SetCaps(name, repo, v); err != nil {
					fail(r, w, req, err)
					return
				}
			}
		}
		setFlash(w, req, "caps")
		dest := "/r/" + repo + "/settings"
		if warn != "" {
			dest += "&e=" + url.QueryEscape(warn)
		}
		http.Redirect(w, req, dest+"#access", http.StatusSeeOther)
	})
	// RFC 0008 rung 8: the fossil settings editor and configuration
	// import, both through ops so the web layer never runs the store.
	mux.HandleFunc("POST /r/{repo}/settings/fossil", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "a", ops.Admin, w, req)
		if !ok {
			return
		}
		if err := req.ParseForm(); err != nil {
			fail(r, w, req, err)
			return
		}
		before := fossilPanelFor(r, req, repo)
		byName := map[string]string{}
		if before != nil {
			for _, row := range before.Rows {
				byName[row.Name] = row.Value
			}
		}
		for key, vals := range req.Form {
			name, ok := strings.CutPrefix(key, "set-")
			if !ok || len(vals) == 0 {
				continue
			}
			if old, seen := byName[name]; seen && old == vals[0] {
				continue // unchanged: do not spend a store write
			}
			if _, err := invoke(req.Context(), r, "settings.set",
				url.Values{"repo": {repo}, "name": {name}, "value": {vals[0]}}); err != nil {
				fail(r, w, req, err)
				return
			}
		}
		setFlash(w, req, "fossil")
		http.Redirect(w, req, "/r/"+repo+"/settings#fossil-settings", http.StatusSeeOther)
	})
	mux.HandleFunc("POST /r/{repo}/settings/config", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "a", ops.Admin, w, req)
		if !ok {
			return
		}
		f, _, err := req.FormFile("file")
		if err != nil {
			http.Redirect(w, req, "/r/"+repo+"/settings?e=choose+a+file#fossil-config", http.StatusSeeOther)
			return
		}
		defer f.Close()
		body, err := io.ReadAll(io.LimitReader(f, 8<<20))
		if err != nil {
			fail(r, w, req, err)
			return
		}
		form := url.Values{"repo": {repo}, "file": {string(body)}}
		if req.FormValue("merge") == "1" {
			form.Set("merge", "true")
		}
		if _, err := invoke(req.Context(), r, "config.import", form); err != nil {
			fail(r, w, req, err)
			return
		}
		setFlash(w, req, "fossil")
		http.Redirect(w, req, "/r/"+repo+"/settings#fossil-config", http.StatusSeeOther)
	})
	// RFC 0008 §Visibility: a preset writes the two category strings;
	// Private goes through the wizard when anyone would lose access.
	mux.HandleFunc("POST /r/{repo}/settings/visibility", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "a", ops.Admin, w, req)
		if !ok {
			return
		}
		admin, isAdmin := capsPlane.(CapsAdmin)
		if !isAdmin {
			setFlash(w, req, "visibility")
			http.Redirect(w, req, "/r/"+repo+"/settings", http.StatusSeeOther)
			return
		}
		want := req.FormValue("visibility")
		if want == "Custom" {
			http.Redirect(w, req, "/r/"+repo+"/settings#access", http.StatusSeeOther)
			return
		}
		if want == "Private" && len(whoLosesAccess(capsPlane, repo)) > 0 {
			http.Redirect(w, req, "/r/"+repo+"/settings/private", http.StatusSeeOther)
			return
		}
		if err := setVisibility(admin, repo, want); err != nil {
			http.Redirect(w, req, "/r/"+repo+"/settings?e="+url.QueryEscape(err.Error())+"#visibility", http.StatusSeeOther)
			return
		}
		setFlash(w, req, "visibility")
		http.Redirect(w, req, "/r/"+repo+"/settings#visibility", http.StatusSeeOther)
	})
	mux.HandleFunc("GET /r/{repo}/settings/private", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "a", ops.Admin, w, req)
		if !ok {
			return
		}
		render(r, w, req, takePrivatePage, pageData{Title: "take private", OwnH1: true, Repo: repo,
			TakePrivate: &takePrivatePanel{Names: whoLosesAccess(capsPlane, repo), Presets: oltp.Presets}})
	})
	mux.HandleFunc("POST /r/{repo}/settings/private", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "a", ops.Admin, w, req)
		if !ok {
			return
		}
		admin, isAdmin := capsPlane.(CapsAdmin)
		if !isAdmin || req.FormValue("confirm") != "1" {
			http.Redirect(w, req, "/r/"+repo+"/settings#visibility", http.StatusSeeOther)
			return
		}
		// Roles first, then the blanking: the order in which nobody is
		// ever locked out between the two.
		for _, name := range whoLosesAccess(capsPlane, repo) {
			for _, p := range oltp.Presets {
				if p.Name == req.FormValue("role-"+name) {
					if err := admin.SetCaps(name, repo, p.Caps); err != nil {
						fail(r, w, req, err)
						return
					}
				}
			}
		}
		if err := setVisibility(admin, repo, "Private"); err != nil {
			fail(r, w, req, err)
			return
		}
		setFlash(w, req, "visibility")
		http.Redirect(w, req, "/r/"+repo+"/settings#visibility", http.StatusSeeOther)
	})
	mux.HandleFunc("GET /fleet/settings", func(w http.ResponseWriter, req *http.Request) {
		req, ok := gateAt(verify, sessions, "", ops.Admin, w, req)
		if !ok {
			return
		}
		v := visibilityFor(capsPlane, "")
		if v == nil {
			http.NotFound(w, req)
			return
		}
		saved := takeFlash(w, req)
		render(r, w, req, fleetSettingsPage, pageData{Title: "fleet settings", OwnH1: true,
			Visibility: v, Saved: saved != "", SavedPanel: saved})
	})
	mux.HandleFunc("POST /fleet/settings", func(w http.ResponseWriter, req *http.Request) {
		req, ok := gateAt(verify, sessions, "", ops.Admin, w, req)
		if !ok {
			return
		}
		admin, isAdmin := capsPlane.(CapsAdmin)
		if !isAdmin {
			http.NotFound(w, req)
			return
		}
		if err := setVisibility(admin, "", req.FormValue("visibility")); err != nil {
			fail(r, w, req, err)
			return
		}
		setFlash(w, req, "fleet")
		http.Redirect(w, req, "/fleet/settings", http.StatusSeeOther)
	})
	// RFC 0009 §triggers: the re-run button — ci.trigger at the tip.
	mux.HandleFunc("POST /r/{repo}/ci/trigger", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "i", ops.Token, w, req)
		if !ok {
			return
		}
		if _, err := invoke(req.Context(), r, "ci.trigger", url.Values{"repo": {repo},
			"checkin": {req.FormValue("checkin")}}); err != nil {
			fail(r, w, req, err)
			return
		}
		back := req.FormValue("back")
		if back == "" || !strings.HasPrefix(back, "/r/") {
			back = "/r/" + repo + "/ci"
		}
		http.Redirect(w, req, back, http.StatusSeeOther)
	})
	// RFC 0009 §verdict-tags: the repository's choice, its own or the
	// fleet's default.
	mux.HandleFunc("POST /r/{repo}/settings/ci-tags", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "a", ops.Admin, w, req)
		if !ok {
			return
		}
		if adm, isAdm := capsPlane.(CITagsAdmin); isAdm {
			if err := adm.SetCITagsMode(repo, req.FormValue("mode")); err != nil {
				fail(r, w, req, err)
				return
			}
		}
		http.Redirect(w, req, "/r/"+repo+"/settings?saved=1#ci-tags", http.StatusSeeOther)
	})
	// RFC 0009 §external-ci: reporter tokens, minted and revoked from
	// the settings page; the token itself rides the redirect once.
	mux.HandleFunc("POST /r/{repo}/settings/ci-tokens", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "a", ops.Admin, w, req)
		if !ok {
			return
		}
		if hash := req.FormValue("revoke"); hash != "" {
			if _, err := invoke(req.Context(), r, "ci.token.revoke",
				url.Values{"repo": {repo}, "hash": {hash}}); err != nil {
				fail(r, w, req, err)
				return
			}
			http.Redirect(w, req, "/r/"+repo+"/settings?saved=1#ci-reporters", http.StatusSeeOther)
			return
		}
		out, err := invoke(req.Context(), r, "ci.token.new",
			url.Values{"repo": {repo}, "label": {req.FormValue("label")}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var tk struct {
			Token string `json:"token"`
		}
		remarshal(out, &tk)
		http.Redirect(w, req, "/r/"+repo+"/settings?rt="+url.QueryEscape(tk.Token)+"#ci-reporters", http.StatusSeeOther)
	})
	mux.HandleFunc("POST /r/{repo}/settings/worker-tokens", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "a", ops.Admin, w, req)
		if !ok {
			return
		}
		if o.engine == nil {
			http.NotFound(w, req)
			return
		}
		if id := req.FormValue("revoke"); id != "" {
			if err := o.engine.RevokeWorkerToken(id); err != nil {
				fail(r, w, req, err)
				return
			}
			http.Redirect(w, req, "/r/"+repo+"/settings?saved=1#runners", http.StatusSeeOther)
			return
		}
		tok, err := o.engine.MintWorkerToken(req.FormValue("label"), strings.Fields(req.FormValue("prefixes")))
		if err != nil {
			fail(r, w, req, err)
			return
		}
		http.Redirect(w, req, "/r/"+repo+"/settings?wt="+url.QueryEscape(tok.Token)+"#runners", http.StatusSeeOther)
	})
	// RFC 0008: the People section's editor, on its own URL.
	personData := func(req *http.Request, repo, name string) (*personEditor, bool) {
		return editorFor(capsPlane, protectPanelFor(protectPlane, repo), repo, name)
	}
	mux.HandleFunc("GET /r/{repo}/people/{name}", func(w http.ResponseWriter, req *http.Request) {
		repo, name := req.PathValue("repo"), req.PathValue("name")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "a", ops.Admin, w, req)
		if !ok {
			return
		}
		ed, found := personData(req, repo, name)
		if !found {
			http.NotFound(w, req)
			return
		}
		q := req.URL.Query()
		ed.Changed, ed.Warn = q.Get("changed"), q.Get("warn")
		liveEditor(ed, capsPlane, repo, name)
		render(r, w, req, personEditPage, pageData{Title: name, OwnH1: true, Repo: repo, Editor: ed})
	})
	// The live preview: recompute from the form, guard as a dry run,
	// and morph #person-live so the sentence, the checkboxes and the
	// string stay one signal. No write happens here.
	mux.HandleFunc("GET /r/{repo}/people/{name}/preview.frag", func(w http.ResponseWriter, req *http.Request) {
		repo, name := req.PathValue("repo"), req.PathValue("name")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "a", ops.Admin, w, req)
		if !ok {
			return
		}
		stored, found := storedCaps(capsPlane, repo, name)
		if !found {
			http.NotFound(w, req)
			return
		}
		if err := req.ParseForm(); err != nil {
			fail(r, w, req, err)
			return
		}
		candidate := nextCaps(req.Form, stored)
		ed := buildEditor(capsPlane, protectPanelFor(protectPlane, repo), repo, name, candidate)
		ed.Changed = oltp.Change(stored, candidate)
		if g, ok := capsPlane.(CapsGuard); ok {
			warn, err := g.GuardCaps(viewer(verify, sessions, repo, req), name, repo, candidate)
			if oltp.IsRefusal(err) {
				ed.Refused, ed.Preview = err.Error(), ed.Sentence
			} else if warn != "" {
				ed.Warn = warn
			}
		}
		liveEditor(ed, capsPlane, repo, name)
		var buf bytes.Buffer
		if err := personEditPage.ExecuteTemplate(&buf, "person-live", ed); err != nil {
			fail(r, w, req, err)
			return
		}
		w.Header().Set("Content-Type", "text/event-stream")
		fmt.Fprint(w, "event: datastar-patch-elements\n")
		for _, line := range strings.Split(buf.String(), "\n") {
			fmt.Fprintf(w, "data: elements %s\n", line)
		}
		fmt.Fprint(w, "\n")
	})
	// saveCaps is the one path a person's string changes by: guard,
	// write, say what changed. A refusal re-renders the editor with the
	// reason where the save button was.
	saveCaps := func(w http.ResponseWriter, req *http.Request, repo, name, old, next string) {
		admin := capsPlane.(CapsAdmin)
		var warn string
		if g, ok := capsPlane.(CapsGuard); ok {
			var err error
			warn, err = g.GuardCaps(viewer(verify, sessions, repo, req), name, repo, next)
			if oltp.IsRefusal(err) {
				ed, _ := personData(req, repo, name)
				ed.Refused = err.Error()
				renderStatus(r, w, req, personEditPage, pageData{Title: name, OwnH1: true, Repo: repo, Editor: ed}, http.StatusUnprocessableEntity)
				return
			}
			if err != nil {
				fail(r, w, req, err)
				return
			}
		}
		if err := admin.SetCaps(name, repo, next); err != nil {
			fail(r, w, req, err)
			return
		}
		q := url.Values{}
		if ch := oltp.Change(old, next); ch != "" {
			q.Set("changed", ch)
		} else {
			q.Set("changed", "nothing changed")
		}
		if warn != "" {
			q.Set("warn", warn)
		}
		http.Redirect(w, req, "/r/"+repo+"/people/"+url.PathEscape(name)+"?"+q.Encode(), http.StatusSeeOther)
	}
	mux.HandleFunc("POST /r/{repo}/people/{name}", func(w http.ResponseWriter, req *http.Request) {
		repo, name := req.PathValue("repo"), req.PathValue("name")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "a", ops.Admin, w, req)
		if !ok {
			return
		}
		ed, found := personData(req, repo, name)
		if !found {
			http.NotFound(w, req)
			return
		}
		if err := req.ParseForm(); err != nil {
			fail(r, w, req, err)
			return
		}
		saveCaps(w, req, repo, name, ed.Caps, nextCaps(req.Form, ed.Caps))
	})
	mux.HandleFunc("POST /r/{repo}/people", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "a", ops.Admin, w, req)
		if !ok {
			return
		}
		if err := req.ParseForm(); err != nil {
			fail(r, w, req, err)
			return
		}
		name := strings.TrimSpace(req.Form.Get("name"))
		ed, found := personData(req, repo, name)
		if !found {
			http.Redirect(w, req, "/r/"+repo+"/settings?e="+url.QueryEscape("no account named "+name)+"#people", http.StatusSeeOther)
			return
		}
		caps := ""
		for _, p := range oltp.Presets {
			if p.Name == req.Form.Get("role") {
				caps = p.Caps
			}
		}
		if caps == "" {
			http.Redirect(w, req, "/r/"+repo+"/settings?e=pick+a+role#people", http.StatusSeeOther)
			return
		}
		saveCaps(w, req, repo, name, ed.Caps, caps)
	})
	mux.HandleFunc("POST /r/{repo}/settings/remove", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateAt(verify, sessions, repo, ops.Admin, w, req)
		if !ok {
			return
		}
		if _, err := invoke(req.Context(), r, "repo.remove", url.Values{"name": {repo}}); err != nil {
			fail(r, w, req, err)
			return
		}
		http.Redirect(w, req, "/", http.StatusSeeOther)
	})
	mux.HandleFunc("POST /r/{repo}/settings/delete", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateAt(verify, sessions, repo, ops.Admin, w, req)
		if !ok {
			return
		}
		_, err := invoke(req.Context(), r, "repo.delete",
			url.Values{"name": {repo}, "confirm": {req.FormValue("confirm")}})
		if err != nil {
			info := settingsFor(req, repo)
			renderStatus(r, w, req, settingsPage, pageData{
				Title: repo, Repo: repo, RepoDescription: info.Description, RepoPrivate: info.Private,
				RepoHomepage: info.Homepage, RepoTopics: info.Topics,
				CloneURL: cloneURL(req, repo), Deletable: deletable(r, req, repo),
				Error: err.Error(),
			}, http.StatusBadRequest)
			return
		}
		http.Redirect(w, req, "/", http.StatusSeeOther)
	})
	mux.HandleFunc("POST /r/{repo}/settings", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateAt(verify, sessions, repo, ops.Admin, w, req)
		if !ok {
			return
		}
		form := url.Values{"name": {repo}, "description": {req.FormValue("description")},
			"homepage": {req.FormValue("homepage")}, "topics": {req.FormValue("topics")}}
		// Visibility has its own section now (RFC 0008); repo.update
		// applies fields whole, so the description form restates it.
		if v := visibilityFor(capsPlane, repo); v != nil && v.Current == "Private" || req.FormValue("private") == "true" {
			form.Set("private", "true")
		}
		// The refusal keeps what the reader TYPED, over the whole page,
		// so the panels below the form survive it too.
		updateErr := ""
		if _, err := invoke(req.Context(), r, "repo.update", form); err != nil {
			updateErr = err.Error()
		}
		data := settingsData(req, repo)
		if updateErr != "" {
			data.RepoDescription = req.FormValue("description")
			data.RepoHomepage = req.FormValue("homepage")
			data.RepoTopics = req.FormValue("topics")
			data.RepoPrivate = req.FormValue("private") == "true"
			data.PanelError = updateErr
		} else {
			data.Saved, data.SavedPanel = true, "about"
		}
		// Without the script the form posted itself and expects a page:
		// refuse in place, or redirect so the saved state lives in ONE
		// place — the GET — and a reload does not re-submit.
		if req.Header.Get("Datastar-Request") == "" {
			if updateErr != "" {
				data.Error, data.PanelError = updateErr, ""
				renderStatus(r, w, req, settingsPage, data, http.StatusBadRequest)
				return
			}
			setFlash(w, req, "about")
			http.Redirect(w, req, "/r/"+url.PathEscape(repo)+"/settings", http.StatusSeeOther)
			return
		}
		// With it, the panel answers for itself: the reader keeps their
		// scroll on a long page, and the URL is left alone — ?saved=1
		// exists to carry a word across a navigation, and there is no
		// navigation here. Putting it in the address bar would make a
		// later reload announce a save that already happened.
		var buf bytes.Buffer
		if err := settingsPage.ExecuteTemplate(&buf, "repo-settings", data); err != nil {
			http.Error(w, "settings render failed", http.StatusInternalServerError)
			return
		}
		w.Header().Set("Content-Type", "text/event-stream")
		fmt.Fprint(w, "event: datastar-patch-elements\n")
		fmt.Fprint(w, "data: selector #repo-settings\n")
		fmt.Fprint(w, "data: mode inner\n")
		for _, line := range strings.Split(buf.String(), "\n") {
			fmt.Fprintf(w, "data: elements %s\n", line)
		}
		fmt.Fprint(w, "\n")
	})
	mux.HandleFunc("GET /new", func(w http.ResponseWriter, req *http.Request) {
		req, ok := gateAt(verify, sessions, "", ops.Admin, w, req)
		if !ok {
			return
		}
		render(r, w, req, newRepoPage, pageData{Title: "new repository"})
	})
	mux.HandleFunc("POST /new", func(w http.ResponseWriter, req *http.Request) {
		req, ok := gateAt(verify, sessions, "", ops.Admin, w, req)
		if !ok {
			return
		}
		form := url.Values{
			"name":        {req.FormValue("name")},
			"description": {req.FormValue("description")},
		}
		if req.FormValue("private") == "true" {
			form.Set("private", "true")
		}
		switch req.FormValue("kind") {
		case "clone":
			form.Set("clone", req.FormValue("from"))
			if every := req.FormValue("every"); every != "" {
				form.Set("mirrorEvery", every)
			}
		case "own":
			form.Set("clone", req.FormValue("from"))
			form.Set("noMirror", "true")
		default:
			form.Set("create", "true")
			// Seeding applies to a new repository only; a clone arrives
			// with its own history and the op refuses the combination.
			if req.FormValue("readme") == "true" {
				form.Set("readme", "true")
			}
			if req.FormValue("ignore") == "true" {
				form.Set("ignore", "true")
			}
			form.Set("license", req.FormValue("license"))
		}
		out, err := invoke(req.Context(), r, "repo.add", form)
		if err != nil {
			// A rejected form comes BACK as a form with the reason on it,
			// not as an error page: the reader has a correction to make,
			// and an error page throws their input away.
			renderStatus(r, w, req, newRepoPage,
				pageData{Title: "new repository", Error: err.Error()}, http.StatusBadRequest)
			return
		}
		var added struct {
			Name string `json:"name"`
		}
		remarshal(out, &added)
		http.Redirect(w, req, "/r/"+added.Name, http.StatusSeeOther)
	})
	// The fleet admin pages are gated at Admin with an EMPTY repo: they
	// are not scoped to a store, and a site admin is the only role for
	// which "every store's health" is a meaningful question.
	mux.HandleFunc("GET /fleet", func(w http.ResponseWriter, req *http.Request) {
		req, ok := gateAt(verify, sessions, "", ops.Admin, w, req)
		if !ok {
			return
		}
		fleetHealth(r, w, req, nil, nil, o.tracker)
	})
	// The tab morph. Same handler, same assembly — the panel is rendered
	// from exactly the data the page would have used, so the pushed view
	// and the reloaded view cannot disagree. The href beside each tab is
	// the no-script path to the identical view.
	mux.HandleFunc("GET /fleet/tab.frag", func(w http.ResponseWriter, req *http.Request) {
		req, ok := gateAt(verify, sessions, "", ops.Admin, w, req)
		if !ok {
			return
		}
		fleetHealth(r, w, req, nil, nil, o.tracker)
	})
	// Exceptions: the whole journal, across every store, with the trace.
	// /fleet shows the same rows as a summary beside the store table;
	// this is the page you open when one of them is the thing you are
	// actually chasing.
	mux.HandleFunc("GET /fleet/exceptions", func(w http.ResponseWriter, req *http.Request) {
		req, ok := gateAt(verify, sessions, "", ops.Admin, w, req)
		if !ok {
			return
		}
		out, err := invoke(req.Context(), r, "fleet.status", nil)
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var fs struct {
			Errors     []errlogRow `json:"errors"`
			ErrorTotal int         `json:"errorTotal"`
		}
		remarshal(out, &fs)
		rows := fs.Errors
		// Narrowing is by SIGNATURE, surface or repository — the three
		// things a reader has when they arrive from an alert.
		if q := strings.TrimSpace(req.URL.Query().Get("q")); q != "" {
			var keep []errlogRow
			for _, e := range rows {
				if strings.Contains(strings.ToLower(e.Message+" "+e.Surface+" "+e.Repo+" "+e.Path), strings.ToLower(q)) ||
					strings.HasPrefix(e.Sig(), q) {
					keep = append(keep, e)
				}
			}
			rows = keep
		}
		render(r, w, req, exceptionsPage, pageData{Title: "exceptions", OwnH1: true,
			FleetTab: "errors", ServerErrors: rows, ErrorTotal: fs.ErrorTotal,
			TrackerRepo: o.tracker, Query: req.URL.Query().Get("q")})
	})
	mux.HandleFunc("GET /fleet/ops", func(w http.ResponseWriter, req *http.Request) {
		req, ok := gateAt(verify, sessions, "", ops.Admin, w, req)
		if !ok {
			return
		}
		v, err := opsSnapshot(r, req)
		if err != nil {
			fail(r, w, req, err)
			return
		}
		render(r, w, req, opsPage, pageData{Title: "operations", OwnH1: true,
			FleetTab: "ops", ErrorTotal: v.ErrorTotal, Ops: v})
	})
	// The live half. Datastar patches the body every few seconds; there
	// is deliberately no no-script path, because an internal dashboard
	// that cannot move while an operator watches a fleet index is worth
	// much less than one that can.
	mux.HandleFunc("GET /fleet/ops/route", func(w http.ResponseWriter, req *http.Request) {
		req, ok := gateAt(verify, sessions, "", ops.Admin, w, req)
		if !ok {
			return
		}
		out, err := invoke(req.Context(), r, "ops.route",
			present(req.URL.Query(), "path", "days"))
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var v opsRouteView
		remarshal(out, &v)
		// The budget travels with the page so the drilldown colours
		// against the same number the panel does.
		snap, _ := opsSnapshot(r, req)
		render(r, w, req, opsRoutePage, pageData{
			Title: "route", OwnH1: true, OpsRoute: v, Ops: snap})
	})
	mux.HandleFunc("GET /fleet/ops/history", func(w http.ResponseWriter, req *http.Request) {
		req, ok := gateAt(verify, sessions, "", ops.Admin, w, req)
		if !ok {
			return
		}
		q := req.URL.Query()
		out, err := invoke(req.Context(), r, "ops.history",
			present(q, "find", "repo", "sort", "days"))
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var v opsHistoryView
		remarshal(out, &v)
		snap, _ := opsSnapshot(r, req)
		render(r, w, req, opsHistoryPage, pageData{
			Title: "history", OwnH1: true, OpsHistory: v, Ops: snap})
	})
	mux.HandleFunc("GET /fleet/ops.frag", func(w http.ResponseWriter, req *http.Request) {
		req, ok := gateAt(verify, sessions, "", ops.Admin, w, req)
		if !ok {
			return
		}
		v, err := opsSnapshot(r, req)
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var buf bytes.Buffer
		if err := opsPage.ExecuteTemplate(&buf, "ops-body", pageData{Ops: v}); err != nil {
			fail(r, w, req, err)
			return
		}
		w.Header().Set("Content-Type", "text/event-stream")
		fmt.Fprint(w, "event: datastar-patch-elements\n")
		for _, line := range strings.Split(buf.String(), "\n") {
			fmt.Fprintf(w, "data: elements %s\n", line)
		}
		fmt.Fprint(w, "\n")
	})
	mux.HandleFunc("POST /fleet/sync", func(w http.ResponseWriter, req *http.Request) {
		req, ok := gateAt(verify, sessions, "", ops.Admin, w, req)
		if !ok {
			return
		}
		out, err := invoke(req.Context(), r, "fleet.sync",
			url.Values{"repo": {req.FormValue("repo")}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var fs struct {
			Results []fleetSyncRow `json:"results"`
		}
		remarshal(out, &fs)
		// Rendered in place rather than redirected: the results ARE the
		// answer to pressing the button, and a redirect would drop them.
		fleetHealth(r, w, req, fs.Results, nil, o.tracker)
	})
	mux.HandleFunc("POST /fleet/mirror", func(w http.ResponseWriter, req *http.Request) {
		req, ok := gateAt(verify, sessions, "", ops.Admin, w, req)
		if !ok {
			return
		}
		if _, err := invoke(req.Context(), r, "mirror.set", url.Values{
			"repo": {req.FormValue("repo")}, "url": {req.FormValue("url")},
			"every": {req.FormValue("every")},
		}); err != nil {
			fail(r, w, req, err)
			return
		}
		http.Redirect(w, req, "/fleet", http.StatusSeeOther)
	})
	mux.HandleFunc("POST /fleet/mirror/chatbridge", func(w http.ResponseWriter, req *http.Request) {
		req, ok := gateAt(verify, sessions, "", ops.Admin, w, req)
		if !ok {
			return
		}
		form := url.Values{"repo": {req.FormValue("repo")}}
		if req.FormValue("detach") != "" {
			form.Set("detach", "true")
		} else {
			form.Set("url", req.FormValue("url"))
			form.Set("user", req.FormValue("user"))
			form.Set("password", req.FormValue("password"))
		}
		if _, err := invoke(req.Context(), r, "mirror.chatbridge", form); err != nil {
			fail(r, w, req, err)
			return
		}
		http.Redirect(w, req, "/fleet", http.StatusSeeOther)
	})
	mux.HandleFunc("POST /fleet/mirror/detach", func(w http.ResponseWriter, req *http.Request) {
		req, ok := gateAt(verify, sessions, "", ops.Admin, w, req)
		if !ok {
			return
		}
		// No acknowledgement, no detach: the button on the table row
		// leads to the confirmation page, never straight here.
		if req.FormValue("ack") != "fork" {
			http.Redirect(w, req, "/fleet?detach="+url.QueryEscape(req.FormValue("repo")), http.StatusSeeOther)
			return
		}
		if _, err := invoke(req.Context(), r, "mirror.detach",
			url.Values{"repo": {req.FormValue("repo")}}); err != nil {
			fail(r, w, req, err)
			return
		}
		http.Redirect(w, req, "/fleet", http.StatusSeeOther)
	})
	mux.HandleFunc("POST /fleet/mirror/writes", func(w http.ResponseWriter, req *http.Request) {
		req, ok := gateAt(verify, sessions, "", ops.Admin, w, req)
		if !ok {
			return
		}
		if _, err := invoke(req.Context(), r, "mirror.writes", url.Values{
			"repo": {req.FormValue("repo")}, "accept": {req.FormValue("accept")}}); err != nil {
			fail(r, w, req, err)
			return
		}
		http.Redirect(w, req, "/fleet", http.StatusSeeOther)
	})
	mux.HandleFunc("POST /fleet/mirror/run", func(w http.ResponseWriter, req *http.Request) {
		req, ok := gateAt(verify, sessions, "", ops.Admin, w, req)
		if !ok {
			return
		}
		out, err := invoke(req.Context(), r, "mirror.run",
			url.Values{"repo": {req.FormValue("repo")}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var mr struct {
			Results []mirrorRunRow `json:"results"`
		}
		remarshal(out, &mr)
		fleetHealth(r, w, req, nil, mr.Results, o.tracker)
	})
	mux.HandleFunc("GET /docs", func(w http.ResponseWriter, req *http.Request) {
		out, err := invoke(req.Context(), r, "meta.docs", nil)
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var d struct {
			HTML string `json:"html"`
		}
		remarshal(out, &d)
		render(r, w, req, docsPage, pageData{
			Title: "API", WikiHTML: template.HTML(d.HTML),
		})
	})
	mux.HandleFunc("GET /fleet.rev", func(w http.ResponseWriter, req *http.Request) {
		if n == nil {
			http.Error(w, "no live plane", http.StatusNotFound)
			return
		}
		fleetRevStream(r, n, w, req)
	})
	mux.HandleFunc("GET /fleet.frag", func(w http.ResponseWriter, req *http.Request) {
		fleetFrag(r, w, req)
	})
	// Everything unmatched gets the themed 404, never Go's bare
	// plain-text default.
	mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		fail(r, w, req, ops.ErrNotFound)
	})
	// The repository's front door. A forge lands on code — fossil's own
	// default is the timeline, and departing from it is deliberate: a
	// repository with no file view has no front door at all, and every
	// GitHub habit misses.
	treeHandler := func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		version, path := req.PathValue("version"), req.PathValue("path")
		if v := req.URL.Query().Get("v"); v != "" {
			// The branch selector posts here; redirect so the chosen
			// version lives in the path and the page is linkable.
			http.Redirect(w, req, "/r/"+repo+"/tree/"+url.PathEscape(v)+"/", http.StatusSeeOther)
			return
		}
		// An empty version stays empty: the op substitutes the
		// repository's DEFAULT branch, which is not always literally
		// "trunk", and reports the name it used in Ref.
		out, err := invoke(req.Context(), r, "tree.list", url.Values{
			"repo": {repo}, "version": {version}, "path": {path},
		})
		if err != nil {
			// A repository with no check-ins has an unborn trunk, so the
			// listing legitimately finds nothing — and answering 404
			// tells its owner the repository does not exist, moments
			// after they created it. Distinguish the two by asking the
			// index whether this repository is merely empty.
			if isEmptyRepo(r, req, repo) {
				info := settingsFor(req, repo)
				render(r, w, req, quickStartPage, pageData{
					Title: repo, Repo: repo, CloneURL: cloneURL(req, repo),
					RepoDescription: info.Description, RepoPrivate: info.Private,
				})
				return
			}
			fail(r, w, req, err)
			return
		}
		var tl struct {
			Version  string    `json:"version"`
			Ref      string    `json:"ref"`
			Path     string    `json:"path"`
			Entries  []treeRow `json:"entries"`
			Readme   string    `json:"readme"`
			ReadmeIn string    `json:"readmeIn"`
		}
		remarshal(out, &tl)
		if version == "" && tl.Ref != "" {
			version = tl.Ref
		}

		data := pageData{
			Title: repo, Repo: repo, Tree: tl.Entries, TreeVersion: version,
			Readme: template.HTML(tl.Readme), ReadmeIn: tl.ReadmeIn,
			CloneURL: cloneURL(req, repo),
		}
		for _, e := range tl.Entries {
			if e.LastHash != "" {
				data.TreeChanges = true
				break
			}
		}
		if tl.Path != "" {
			var acc string
			for _, seg := range strings.Split(tl.Path, "/") {
				acc = strings.TrimPrefix(acc+"/"+seg, "/")
				data.Crumbs = append(data.Crumbs, crumb{Name: seg, Path: acc})
			}
		}
		if tl.Path == "" {
			// GitHub's bar names the branch's tip; a hash version has no
			// branch timeline, and the empty answer simply hides the bar.
			if to, terr := invoke(req.Context(), r, "timeline.list", url.Values{
				"repo": {repo}, "limit": {"1"}, "y": {"ci"}, "branch": {version}}); terr == nil {
				var tt struct {
					Entries []timelineEntry `json:"entries"`
				}
				remarshal(to, &tt)
				// Only when the index's newest IS the tree being shown:
				// while an index rebuild lags the store, the timeline's
				// "newest" is years behind the listing zit just served,
				// and a bar contradicting the files below it is worse
				// than no bar.
				if len(tt.Entries) == 1 && tt.Entries[0].Hash == tl.Version {
					data.Tip = &tt.Entries[0]
				}
			}
		}
		if bo, err := invoke(req.Context(), r, "branch.list", url.Values{"repo": {repo}}); err == nil {
			var bl struct {
				Branches []branchRow `json:"branches"`
			}
			remarshal(bo, &bl)
			// The strip's count keeps ALL branches — the number a reader
			// compares with the branch page — while the selector below
			// lists only the open ones.
			data.BranchTotal = len(bl.Branches)
			data.CloneCount = tallyOf(tallies, repo, "clone")
			if praise != nil {
				data.PraiseCount = praise.PraiseCount(repo)
				if sessions != nil {
					if who, ok := sessions.Resolve(cookieToken(req)); ok && who != "" {
						data.CanPraise = true
						data.Praised = praise.Praised(repo, who)
					}
				}
			}
			bl.Branches = openBranches(bl.Branches, version)
			// tcl has 1,855 branches and sqlite 1,747. Rendering every
			// one is both an unusable control and 90% of the page's
			// weight — 239KB of <option>. Show the recently active ones,
			// which branch.list already returns first.
			const shown = 25
			data.Branches = bl.Branches
			if len(bl.Branches) > shown {
				data.Branches = bl.Branches[:shown]
				data.MoreBranches = len(bl.Branches) - shown
				// The branch being VIEWED must appear even when it is
				// not recently active, or the selector silently shows
				// the wrong thing for anyone browsing older work.
				found := false
				for _, b := range data.Branches {
					if b.Tip == version {
						found = true
						break
					}
				}
				if !found {
					for _, b := range bl.Branches {
						if b.Tip == version {
							data.Branches = append([]branchRow{b}, data.Branches...)
							break
						}
					}
				}
			}
			labelBranches(data.Branches)
			// The button says which ref is in view. Falling back to the
			// short hash rather than to "trunk" keeps it honest when a
			// reader is on a detached check-in.
			data.RefName = version[:min(12, len(version))]
			for _, b := range data.Branches {
				if b.Tip == version {
					data.RefName = b.Name
					break
				}
			}
		}
		if to, err := invoke(req.Context(), r, "tag.list",
			url.Values{"repo": {repo}, "limit": {"25"}}); err == nil {
			var tl struct {
				Tags  []tagRow `json:"tags"`
				Count int      `json:"count"`
			}
			remarshal(to, &tl)
			data.Tags = tl.Tags
			data.TagTotal = tl.Count
			for _, t := range tl.Tags {
				if t.Tip == version {
					data.RefName = t.Name
					break
				}
			}
		}
		// An empty repository is not a broken one — it is waiting for a
		// first push. Showing a bare file table says nothing about what
		// to do next, which is the only thing its reader wants to know.
		sinfo := settingsFor(req, repo)
		data.RepoDescription, data.RepoPrivate = sinfo.Description, sinfo.Private
		if len(data.Tree) == 0 && len(data.Crumbs) == 0 {
			render(r, w, req, quickStartPage, pageData{
				Title: repo, Repo: repo, CloneURL: cloneURL(req, repo),
				RepoDescription: data.RepoDescription, RepoPrivate: data.RepoPrivate,
			})
			return
		}
		// The clone tool is a URL parameter so the choice survives a
		// reload and can be linked to. fossil is offered only where the
		// store can actually be cloned by it.
		data.CloneTool = "zit"
		if info, err := invoke(req.Context(), r, "repo.get", url.Values{"repo": {repo}}); err == nil {
			var ri struct {
				FossilClone bool `json:"fossilClone"`
			}
			remarshal(info, &ri)
			data.FossilClone = ri.FossilClone
			if ri.FossilClone && req.URL.Query().Get("clone") == "fossil" {
				data.CloneTool = "fossil"
			}
		}
		// The repository ROOT carries the About sidebar whatever ref is
		// showing — switching branches must not make the repo forget
		// what it is. The document TABS are default-ref only, though:
		// repo.about renders default-branch docs, and presenting them
		// under a branch's listing would show the wrong branch's README
		// as if it were this one's. On a branch root the aside sheds its
		// doc rows and the branch's own README renders below, plainly.
		if tl.Path == "" {
			atDefault := req.PathValue("version") == ""
			vals := url.Values{"repo": {repo}}
			if d := req.URL.Query().Get("doc"); d != "" && atDefault {
				vals.Set("doc", d)
			}
			if ao, err := invoke(req.Context(), r, "repo.about", vals); err == nil {
				var about aboutData
				remarshal(ao, &about)
				data.About = &about
				if atDefault {
					data.DocHTML = template.HTML(about.DocHTML)
					// The tab panel replaces the plain README block:
					// README is the first tab, and rendering it twice
					// says nothing.
					data.Readme, data.ReadmeIn = "", ""
				} else {
					about.Docs, about.DocPath, about.DocLabel, about.DocHTML = nil, "", "", ""
				}
			} else if !errors.Is(err, ops.ErrNotFound) {
				log.Printf("web: about %s: %v", repo, err)
			} else if atDefault {
				// ?doc= named a tab that does not exist.
				fail(r, w, req, err)
				return
			}
		}
		// The crumb trail is this page's heading.
		data.HideH1 = true
		render(r, w, req, treePage, data)
	}
	mux.HandleFunc("GET /r/{repo}/doc.frag", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		vals := url.Values{"repo": {repo}}
		if d := req.URL.Query().Get("doc"); d != "" {
			vals.Set("doc", d)
		}
		ao, err := invoke(req.Context(), r, "repo.about", vals)
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var about aboutData
		remarshal(ao, &about)
		data := pageData{Repo: repo, About: &about, DocHTML: template.HTML(about.DocHTML)}
		var buf bytes.Buffer
		buf.WriteString(`<div id="docs">`)
		if err := treePage.ExecuteTemplate(&buf, "doc-panel", data); err != nil {
			http.Error(w, "panel render failed", http.StatusInternalServerError)
			return
		}
		buf.WriteString(`</div>`)
		w.Header().Set("Content-Type", "text/event-stream")
		fmt.Fprint(w, "event: datastar-patch-elements\n")
		for _, line := range strings.Split(buf.String(), "\n") {
			fmt.Fprintf(w, "data: elements %s\n", line)
		}
		fmt.Fprint(w, "\n")
	})
	mux.HandleFunc("GET /r/{repo}/branch", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		out, err := invoke(req.Context(), r, "branch.list", url.Values{"repo": {repo}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var bl struct {
			Branches []branchRow `json:"branches"`
		}
		remarshal(out, &bl)
		closed := 0
		for _, b := range bl.Branches {
			if b.Closed {
				closed++
			}
		}
		render(r, w, req, branchesPage, pageData{Title: "branches", Repo: repo,
			Branches: bl.Branches, ClosedCount: closed})
	})
	mux.HandleFunc("GET /r/{repo}/tag", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		out, err := invoke(req.Context(), r, "tag.list",
			url.Values{"repo": {repo}, "limit": {"200"}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var tl struct {
			Tags []tagRow `json:"tags"`
		}
		remarshal(out, &tl)
		render(r, w, req, tagsPage, pageData{Title: "tags", Repo: repo, Tags: tl.Tags})
	})
	mux.HandleFunc("GET /r/{repo}", treeHandler)
	mux.HandleFunc("GET /r/{repo}/tree", treeHandler)
	mux.HandleFunc("GET /r/{repo}/tree/{version}/{path...}", treeHandler)
	mux.HandleFunc("GET /r/{repo}/history/{version}/{path...}", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		version, path := req.PathValue("version"), req.PathValue("path")
		out, err := invoke(req.Context(), r, "file.history", url.Values{
			"repo": {repo}, "version": {version}, "path": {path},
		})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var fh struct {
			Changes []fileChange `json:"changes"`
		}
		remarshal(out, &fh)
		render(r, w, req, historyPage, pageData{
			Title: path, Repo: repo, TreeVersion: version,
			HistoryPath: path, History: fh.Changes,
		})
	})
	mux.HandleFunc("GET /r/{repo}/ci", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		data := buildCIList(r, o.cilogs, repo, req.URL.Query())
		data.CanTrigger = mayCap(capsPlane, verify, sessions, repo, "i", ops.Token, req)
		if n != nil {
			// A run's status changes while nobody is clicking, so the
			// page follows it. data-init sits on a WRAPPER, outside the
			// element the stream patches — a patch morphs its target to
			// match the fragment, and the fragment has no data-init.
			data.Live = true
			// The stream carries the reader's own filters, so a patch
			// draws the same list a reload would.
			sse := "/r/" + repo + "/ci.sse"
			if q := req.URL.RawQuery; q != "" {
				sse += "?" + q
			}
			data.LiveAttr = template.HTMLAttr(`data-init="@get('` + template.JSEscapeString(sse) + `')"`)
		}
		render(r, w, req, ciPage, data)
	})
	mux.HandleFunc("GET /r/{repo}/ci.sse", func(w http.ResponseWriter, req *http.Request) {
		if n == nil {
			http.NotFound(w, req)
			return
		}
		repo := req.PathValue("repo")
		liveCI(r, o.cilogs, repo, w, req)
	})
	// The pipeline editor (RFC 0009): tracked content, edited here,
	// landing like any change. Gated on the check-in letter — the same
	// hand that could commit the file any other way.
	ciEditorData := func(req *http.Request, repo string) pageData {
		q := req.URL.Query()
		data := pageData{Title: "edit pipeline", Repo: repo,
			CIEditPath: q.Get("path"), CIEditNew: q.Get("new") == "1" || q.Get("path") == ""}
		if data.CIEditNew && data.CIEditPath == "" {
			if q.Get("template") == "yml" {
				data.CIEditPath = "ci/checks.yml"
				data.CIEditContent = "checks:\n  test: { call: \"test\" }\n"
			} else {
				data.CIEditPath = "ci/checks.json"
				data.CIEditContent = "{\n  \"name\": \"checks\",\n  \"version\": \"1.0\",\n  \"steps\": [\n    { \"id\": \"test\", \"task\": \"my-test-task\" }\n  ]\n}\n"
			}
			return data
		}
		out, err := invoke(req.Context(), r, "file.get", url.Values{
			"repo": {repo}, "hash": {"trunk"}, "path": {data.CIEditPath}})
		if err == nil {
			var fg struct {
				Content string `json:"content"`
			}
			remarshal(out, &fg)
			data.CIEditContent = fg.Content
		}
		return data
	}
	mux.HandleFunc("GET /r/{repo}/ci/pipeline", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "i", ops.Token, w, req)
		if !ok {
			return
		}
		render(r, w, req, ciEditPage, ciEditorData(req, repo))
	})
	mux.HandleFunc("POST /r/{repo}/ci/pipeline", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "i", ops.Token, w, req)
		if !ok {
			return
		}
		if err := req.ParseForm(); err != nil {
			http.Error(w, "bad form", http.StatusBadRequest)
			return
		}
		form := url.Values{"repo": {repo}, "path": {req.FormValue("path")},
			"content": {req.FormValue("content")}, "message": {req.FormValue("message")}}
		validateOnly := req.FormValue("action") != "save"
		if validateOnly {
			form.Set("validate", "true")
		}
		// The commit is authored: the op needs to know whose hand.
		out, err := invoke(ops.WithUser(req.Context(), viewer(verify, sessions, repo, req)), r, "ci.pipeline.save", form)
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var res struct {
			Diagnostics []string `json:"diagnostics"`
			Landing     string   `json:"landing"`
			Branch      string   `json:"branch"`
		}
		remarshal(out, &res)
		if len(res.Diagnostics) > 0 || validateOnly {
			data := pageData{Title: "edit pipeline", Repo: repo,
				CIEditPath: req.FormValue("path"), CIEditContent: req.FormValue("content"),
				CIEditMessage: req.FormValue("message"), CIEditNew: true,
				CIEditDiags: res.Diagnostics, CIEditOK: len(res.Diagnostics) == 0}
			render(r, w, req, ciEditPage, data)
			return
		}
		if res.Landing != "" {
			http.Redirect(w, req, "/r/"+repo+"/landing/"+res.Landing[:min(12, len(res.Landing))], http.StatusSeeOther)
			return
		}
		http.Redirect(w, req, "/r/"+repo+"/landing", http.StatusSeeOther)
	})
	// RFC 0009 §logs: one run, step by step, output underneath.
	mux.HandleFunc("GET /r/{repo}/ci/run/{id}", func(w http.ResponseWriter, req *http.Request) {
		repo, id := req.PathValue("repo"), req.PathValue("id")
		out, err := invoke(req.Context(), r, "ci.list", url.Values{"repo": {repo}, "limit": {"200"}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var cl struct {
			Runs []ciRunRow `json:"runs"`
		}
		remarshal(out, &cl)
		var row *ciRunRow
		for i := range cl.Runs {
			if strings.HasPrefix(cl.Runs[i].RunID, id) {
				row = &cl.Runs[i]
				break
			}
		}
		if row == nil {
			http.NotFound(w, req)
			return
		}
		render(r, w, req, ciRunPage, pageData{Title: "run " + id, OwnH1: true, Repo: repo,
			CIRunView:   buildRunView(o.engine, o.cilogs, repo, cloneURL(req, repo), *row),
			RunFragPath: "/r/" + repo + "/ci/run-frag/" + id})
	})
	// The live follow: recompute the step region and morph it in place.
	mux.HandleFunc("GET /r/{repo}/ci/run-frag/{id}", func(w http.ResponseWriter, req *http.Request) {
		repo, id := req.PathValue("repo"), req.PathValue("id")
		out, err := invoke(req.Context(), r, "ci.list", url.Values{"repo": {repo}, "limit": {"200"}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var cl struct {
			Runs []ciRunRow `json:"runs"`
		}
		remarshal(out, &cl)
		var row *ciRunRow
		for i := range cl.Runs {
			if strings.HasPrefix(cl.Runs[i].RunID, id) {
				row = &cl.Runs[i]
				break
			}
		}
		if row == nil {
			http.NotFound(w, req)
			return
		}
		var buf bytes.Buffer
		if err := ciRunPage.ExecuteTemplate(&buf, "run-steps", pageData{Repo: repo,
			CIRunView: buildRunView(o.engine, o.cilogs, repo, cloneURL(req, repo), *row)}); err != nil {
			fail(r, w, req, err)
			return
		}
		w.Header().Set("Content-Type", "text/event-stream")
		fmt.Fprint(w, "event: datastar-patch-elements\n")
		fmt.Fprintf(w, "data: elements <div id=\"run-body\">\n")
		for _, line := range strings.Split(buf.String(), "\n") {
			fmt.Fprintf(w, "data: elements %s\n", line)
		}
		fmt.Fprint(w, "data: elements </div>\n\n")
	})
	mux.HandleFunc("GET /r/{repo}/timeline", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		vals, limit := timelineQuery(req.URL.Query(), repo)
		out, err := invoke(req.Context(), r, "timeline.list", vals)
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var tl struct {
			Entries       []timelineEntry `json:"entries"`
			Next          string          `json:"next"`
			IndexBehind   bool            `json:"indexBehind"`
			DefaultBranch string          `json:"defaultBranch"`
		}
		remarshal(out, &tl)
		data := pageData{
			Title: "timeline", Repo: repo, Days: buildTimeline(repo, tl.DefaultBranch, tl.Entries), Next: tl.Next,
			Branch: req.URL.Query().Get("branch"), Tag: req.URL.Query().Get("tag"),
			User: req.URL.Query().Get("user"), Y: vals.Get("y"),
			Limit: limit, LimitChoices: []int{20, 50, 100, 200},
		}
		// Only when the timeline is narrowed TO that branch: a note
		// about one branch above a timeline of all of them is a caption
		// on the wrong picture.
		if data.Branch != "" {
			if note, ok := associatedNote(r, req, repo, "branch/"+data.Branch); ok {
				data.Note, data.NoteName, data.NoteKind = noteFor(note)
			}
		}
		// A tag has an associated wiki page the same way a branch does
		// — fossil links tag/<name> from the check-in page, and this is
		// where a reader who followed the tag ends up.
		if data.Tag != "" && data.Note == "" {
			if note, ok := associatedNote(r, req, repo, "tag/"+data.Tag); ok {
				data.Note, data.NoteName, data.NoteKind = noteFor(note)
			}
		}
		if bo, err := invoke(req.Context(), r, "branch.list", url.Values{"repo": {repo}}); err == nil {
			var bl struct {
				Branches []branchRow `json:"branches"`
			}
			remarshal(bo, &bl)
			bl.Branches = openBranches(bl.Branches, data.Branch)
			const shown = 25
			data.Branches = bl.Branches
			if len(bl.Branches) > shown {
				data.Branches = bl.Branches[:shown]
				found := false
				for _, b := range data.Branches {
					if b.Name == data.Branch {
						found = true
						break
					}
				}
				if !found && data.Branch != "" {
					for _, b := range bl.Branches {
						if b.Name == data.Branch {
							data.Branches = append([]branchRow{b}, data.Branches...)
							break
						}
					}
				}
			}
		}
		// Live updates enhance the first page only; history pages are
		// static by nature. Without the notifier (or JS) the page is
		// simply itself — Principle 3's refresh-fallback.
		// The filter no longer travels with the stream: the signal
		// carries a revision and the client re-sends its own controls.
		// That is the whole difference — nothing here can capture a
		// filter and hold it.
		if n != nil && req.URL.Query().Get("before") == "" {
			data.Live = true
		}
		render(r, w, req, timelinePage, data)
	})
	mux.HandleFunc("GET /r/{repo}/timeline.rev", func(w http.ResponseWriter, req *http.Request) {
		if n == nil {
			http.NotFound(w, req)
			return
		}
		timelineRevStream(n, w, req)
	})
	mux.HandleFunc("GET /r/{repo}/timeline.frag", func(w http.ResponseWriter, req *http.Request) {
		timelineFrag(r, w, req)
	})
	// The documentation index. One list from two stores: wiki artifacts
	// and documents in the tree. Which store a page lives in decides how
	// it is EDITED, not what it is, and a reader hunting for how
	// something works should not have to know the difference — on
	// fossil's own repository the wiki's 41 real pages were last touched
	// in 2018 while the 113 documents under www/ are current, so a UI
	// that shows only the wiki shows the stale half.
	mux.HandleFunc("GET /r/{repo}/wiki", func(w http.ResponseWriter, req *http.Request) {
		q := req.URL.Query()
		dest := "/r/" + url.PathEscape(req.PathValue("repo")) + "/docs"
		if len(q) > 0 {
			dest += "?" + q.Encode()
		}
		http.Redirect(w, req, dest, http.StatusMovedPermanently)
	})
	mux.HandleFunc("GET /r/{repo}/docs/{kind}", func(w http.ResponseWriter, req *http.Request) {
		repo, kind := req.PathValue("repo"), req.PathValue("kind")
		if kind != "wanted" && kind != "orphans" {
			http.Redirect(w, req, "/r/"+url.PathEscape(repo)+"/docs", http.StatusSeeOther)
			return
		}
		out, err := invoke(req.Context(), r, "wiki.list", url.Values{"repo": {repo}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var wl struct {
			Orphans []string `json:"orphans"`
			Wanted  []struct {
				Title string   `json:"title"`
				Links int      `json:"links"`
				From  []string `json:"from"`
			} `json:"wanted"`
		}
		remarshal(out, &wl)
		data := pageData{Repo: repo, StructKind: kind}
		total := 0
		offset := 0
		if n, err := strconv.Atoi(req.URL.Query().Get("offset")); err == nil && n > 0 {
			offset = n
		}
		link := func(off int) string {
			u := "/r/" + url.PathEscape(repo) + "/docs/" + kind
			if off > 0 {
				u += "?offset=" + strconv.Itoa(off)
			}
			return u
		}
		if kind == "wanted" {
			data.Title = "wanted pages"
			total = len(wl.Wanted)
			if offset >= total {
				offset = 0
			}
			for _, w := range wl.Wanted[offset:min(offset+docsPageSize, total)] {
				data.WikiWanted = append(data.WikiWanted,
					wikiWant{Title: w.Title, Links: w.Links, From: w.From})
			}
		} else {
			data.Title = "nothing links here"
			total = len(wl.Orphans)
			if offset >= total {
				offset = 0
			}
			data.WikiOrphans = wl.Orphans[offset:min(offset+docsPageSize, total)]
		}
		shown := len(data.WikiOrphans) + len(data.WikiWanted)
		if total > docsPageSize {
			pg := &pager{From: offset + 1, To: offset + shown, Total: total}
			if offset > 0 {
				pg.Prev = link(max(0, offset-docsPageSize))
			}
			if pg.To < total {
				pg.Next = link(offset + docsPageSize)
			}
			data.Pager = pg
		}
		render(r, w, req, wikiStructPage, data)
	})
	mux.HandleFunc("GET /r/{repo}/docs", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		q := strings.TrimSpace(req.URL.Query().Get("q"))
		sort := ""
		if req.URL.Query().Get("sort") == "recent" {
			sort = "recent"
		}
		showAssociated := req.URL.Query().Get("associated") == "1"
		associated := 0
		var rows []docRow
		var home *wikiTitle
		var entry *docRow

		if out, err := invoke(req.Context(), r, "wiki.list", url.Values{"repo": {repo}}); err == nil {
			var wl struct {
				Pages []wikiTitle `json:"pages"`
			}
			remarshal(out, &wl)
			pages := wl.Pages[:0:0]
			for _, p := range wl.Pages {
				if p.Title == wikiHome {
					h := p
					home = &h
					continue
				}
				pages = append(pages, p)
			}
			for _, p := range pages {
				if isAssociatedWiki(p.Title) {
					associated++
					if !showAssociated {
						continue
					}
				}
				rows = append(rows, docRow{Title: p.Title, Kind: "wiki",
					URL:  "/r/" + url.PathEscape(repo) + "/wiki/" + url.PathEscape(p.Title),
					Date: p.Date, User: p.User, Revisions: p.Revisions})
			}
		}
		if out, err := invoke(req.Context(), r, "doc.list", url.Values{"repo": {repo}}); err == nil {
			var dl struct {
				Version string     `json:"version"`
				Docs    []docEntry `json:"docs"`
			}
			remarshal(out, &dl)
			for _, e := range dl.Docs {
				row := docRow{Title: e.Path, Kind: "tree", Date: e.Date, User: e.User,
					URL: "/r/" + url.PathEscape(repo) + "/doc/" + url.PathEscape(dl.Version) + "/" + e.Path}
				// The front door leads, and leaves the list: a page
				// somebody wrote to be read first is the one entry a
				// reader is least likely to go hunting for alphabetically.
				switch {
				case entryDoc.MatchString(e.Path):
					entry = &row
				case repoReadme.MatchString(e.Path) && entry == nil:
					entry = &row
				default:
					rows = append(rows, row)
				}
			}
			if entry != nil {
				// Whichever won, the other stays in the list.
				kept := rows[:0:0]
				for _, row := range rows {
					if row.URL != entry.URL {
						kept = append(kept, row)
					}
				}
				rows = kept
			}
		}

		served := len(rows)
		if q != "" {
			match := rows[:0:0]
			for _, row := range rows {
				if strings.Contains(strings.ToLower(row.Title), strings.ToLower(q)) {
					match = append(match, row)
				}
			}
			rows = match
		}
		if sort == "recent" {
			slices.SortStableFunc(rows, func(a, b docRow) int { return strings.Compare(b.Date, a.Date) })
		} else {
			slices.SortStableFunc(rows, func(a, b docRow) int {
				return strings.Compare(strings.ToLower(a.Title), strings.ToLower(b.Title))
			})
		}
		shown := len(rows)
		offset := 0
		if n, err := strconv.Atoi(req.URL.Query().Get("offset")); err == nil && n > 0 {
			offset = n
		}
		if offset >= shown {
			offset = 0 // a stale link lands on the first page, not an empty one
		}
		// One place builds every link on this page, so a filter, a sort,
		// a page and the associated-wiki choice cannot lose each other.
		link := func(off int) string {
			v := url.Values{}
			if q != "" {
				v.Set("q", q)
			}
			if sort != "" {
				v.Set("sort", sort)
			}
			if showAssociated {
				v.Set("associated", "1")
			}
			if off > 0 {
				v.Set("offset", strconv.Itoa(off))
			}
			u := "/r/" + url.PathEscape(repo) + "/docs"
			if len(v) > 0 {
				u += "?" + v.Encode()
			}
			return u
		}
		rows = rows[offset:min(offset+docsPageSize, shown)]
		var pg *pager
		if shown > docsPageSize {
			pg = &pager{From: offset + 1, To: offset + len(rows), Total: shown}
			if offset > 0 {
				pg.Prev = link(max(0, offset-docsPageSize))
			}
			if pg.To < shown {
				pg.Next = link(offset + docsPageSize)
			}
		}
		// The tab above already says Docs, and the README card below is
		// the page's real first line — so the h1 said the same word a
		// third time. Suppressed the way the landings and tickets
		// listings do it: sr-only, so the page stays named for a screen
		// reader without spending a heading on the repetition.
		data := pageData{Title: "docs", HideH1: true, Repo: repo,
			DocRows: rows, WikiHome: home, DocEntry: entry, Query: q, Sort: sort,
			Shown: shown, Served: served, Pager: pg,
			Associated: associated, ShowAssociated: showAssociated}
		// The structure panel describes the WIKI, which is one of the
		// two stores this page merges. Both lists are bounded: fossil's
		// own wiki has 78 pages nothing links to, and a panel that long
		// stops being a panel. What is left out is counted, never
		// silently dropped.
		if st, serr := invoke(req.Context(), r, "wiki.list", url.Values{"repo": {repo}}); serr == nil {
			var wl struct {
				Orphans []string `json:"orphans"`
				Wanted  []struct {
					Title string   `json:"title"`
					Links int      `json:"links"`
					From  []string `json:"from"`
				} `json:"wanted"`
			}
			remarshal(st, &wl)
			for _, o := range wl.Orphans {
				if len(data.WikiOrphans) < wikiStructLimit {
					data.WikiOrphans = append(data.WikiOrphans, o)
				}
			}
			data.MoreOrphans = len(wl.Orphans) - len(data.WikiOrphans)
			for _, w := range wl.Wanted {
				if len(data.WikiWanted) < wikiStructLimit {
					data.WikiWanted = append(data.WikiWanted,
						wikiWant{Title: w.Title, Links: w.Links, From: w.From})
				}
			}
			data.MoreWanted = len(wl.Wanted) - len(data.WikiWanted)
		}
		render(r, w, req, wikiListPage, data)
	})
	mux.HandleFunc("GET /r/{repo}/chat", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		q := req.URL.Query()
		form := url.Values{"repo": {repo}}
		var before uint64
		if b := q.Get("before"); b != "" {
			form.Set("before", b)
			before, _ = strconv.ParseUint(b, 10, 64)
		}
		// The reader's identity rides into chat.history so the answer
		// can carry THEIR read mark. It comes back from the history op
		// (which reads chat_read directly) rather than from chat.unread,
		// because chat.unread omits a repository with nothing unread:
		// sourcing the mark there cannot tell "read to the tip" from
		// "never read a word", and draws the divider above everything.
		ctx := req.Context()
		who := viewer(verify, sessions, repo, req)
		if who != "" {
			ctx = ops.WithUser(ctx, who)
		}
		out, err := invoke(ctx, r, "chat.history", form)
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var ch struct {
			Messages []ChatMessage `json:"messages"`
			Next     uint64        `json:"next"`
			Read     uint64        `json:"read"`
		}
		remarshal(out, &ch)
		data := pageData{Title: "chat", Repo: repo, ChatMsgs: ch.Messages,
			ChatNext: ch.Next, ChatBefore: before}
		data.ChatViewer = who
		// One header per run of an author's messages, computed here
		// because a template cannot see the row above the one it is
		// drawing. The read mark breaks a run: the "new" divider goes
		// between them, and a header must not land on its far side.
		chatGroupRuns(data.ChatMsgs, ch.Read)
		// The quotes an inline #seq earns, sourced from this same
		// listing: server-rendered, so they are there with script off.
		chatRefQuotes(data.ChatMsgs)
		if data.ChatViewer != "" {
			data.ChatReadSeq = ch.Read
			if c, ok := capsOf(capsPlane, sessions, verify, repo, req); ok {
				data.ChatViewerAll = c.HasAny("a")
			}
		}
		if live != nil {
			data.Live = true
			data.LiveAttr = template.HTMLAttr(`data-init="@get('/r/` + repo + `/chat.sse')"`)
		}
		render(r, w, req, chatPage, data)
	})
	mux.HandleFunc("POST /r/{repo}/chat", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "C", ops.Token, w, req)
		if !ok {
			return
		}
		form := url.Values{"repo": {repo}, "text": {req.FormValue("text")}}
		if ref := req.FormValue("ref"); ref != "" {
			form.Set("ref", ref)
		}
		if _, err := invoke(req.Context(), r, "chat.post", form); err != nil {
			fail(r, w, req, err)
			return
		}
		http.Redirect(w, req, "/r/"+repo+"/chat", http.StatusSeeOther)
	})
	mux.HandleFunc("POST /r/{repo}/chat/{seq}/edit", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "C", ops.Token, w, req)
		if !ok {
			return
		}
		if _, err := invoke(req.Context(), r, "chat.edit", url.Values{
			"repo": {repo}, "seq": {req.PathValue("seq")}, "text": {req.FormValue("text")},
		}); err != nil {
			fail(r, w, req, err)
			return
		}
		http.Redirect(w, req, "/r/"+repo+"/chat", http.StatusSeeOther)
	})
	mux.HandleFunc("POST /r/{repo}/chat/{seq}/delete", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "C", ops.Token, w, req)
		if !ok {
			return
		}
		if _, err := invoke(req.Context(), r, "chat.delete", url.Values{
			"repo": {repo}, "seq": {req.PathValue("seq")},
		}); err != nil {
			fail(r, w, req, err)
			return
		}
		http.Redirect(w, req, "/r/"+repo+"/chat", http.StatusSeeOther)
	})
	mux.HandleFunc("POST /r/{repo}/chat/read", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "C", ops.Token, w, req)
		if !ok {
			return
		}
		if _, err := invoke(req.Context(), r, "chat.read", url.Values{"repo": {repo}}); err != nil {
			fail(r, w, req, err)
			return
		}
		http.Redirect(w, req, "/r/"+repo+"/chat", http.StatusSeeOther)
	})
	mux.HandleFunc("GET /r/{repo}/chat/{seq}", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		out, err := invoke(req.Context(), r, "chat.get",
			url.Values{"repo": {repo}, "seq": {req.PathValue("seq")}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var g struct {
			Message ChatMessage   `json:"message"`
			Replies []ChatMessage `json:"replies"`
			Expired bool          `json:"expired"`
		}
		remarshal(out, &g)
		// The folded message and its replies are one listing for the
		// purpose of quoting: a reply that names its neighbour can be
		// quoted from what this page already carries.
		fold := append([]ChatMessage{g.Message}, g.Replies...)
		chatRefQuotes(fold)
		data := pageData{Title: fmt.Sprintf("chat #%s", req.PathValue("seq")), Repo: repo,
			ChatOne: fold[0], ChatReplies: fold[1:], ChatExpired: g.Expired}
		data.ChatViewer = viewer(verify, sessions, repo, req)
		if data.ChatViewer != "" {
			if c, ok := capsOf(capsPlane, sessions, verify, repo, req); ok {
				data.ChatViewerAll = c.HasAny("a")
			}
		}
		render(r, w, req, chatPermalinkPage, data)
	})
	// The preview fragment: ref.resolve, drawn (RFC 0011 §14). It
	// patches the ONE shared #refpop, so hovering a hundred references
	// costs one element and one request each, not a hundred elements.
	mux.HandleFunc("GET /r/{repo}/ref.frag", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		ref := req.URL.Query().Get("ref")
		out, err := invoke(req.Context(), r, "ref.resolve",
			url.Values{"repo": {repo}, "ref": {ref}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var card refCard
		remarshal(out, &card)
		body := refPopHTML(refCardHTML(card))
		// A reference's card changes only when its target does, and a
		// hovered reference is re-hovered constantly. The ETag is the
		// card itself, so a repeat hover is a 304 rather than a redraw.
		etag := `"ref-` + strconv.FormatUint(uint64(crc32.ChecksumIEEE([]byte(body))), 16) + `"`
		w.Header().Set("ETag", etag)
		w.Header().Set("Cache-Control", "no-cache")
		if req.Header.Get("If-None-Match") == etag {
			w.WriteHeader(http.StatusNotModified)
			return
		}
		patchElements(w, body)
	})
	// @ completion in the composer: additive, and the composer works
	// without it (Principle 3 — the textarea is a textarea).
	mux.HandleFunc("GET /r/{repo}/mention.frag", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		text := req.FormValue("chatText")
		q, ok := trailingMention(text)
		if !ok {
			patchElements(w, `<ul id="mentions" class="mentions" hidden></ul>`)
			return
		}
		out, err := invoke(req.Context(), r, "people.mention",
			url.Values{"repo": {repo}, "q": {q}})
		if err != nil {
			// A completion nobody may run is not an error worth a page:
			// the list stays empty and the textarea stays a textarea.
			patchElements(w, `<ul id="mentions" class="mentions" hidden></ul>`)
			return
		}
		var ml struct {
			Handles []struct {
				Handle string `json:"handle"`
				Caps   string `json:"caps"`
			} `json:"handles"`
		}
		remarshal(out, &ml)
		var b strings.Builder
		b.WriteString(`<ul id="mentions" class="mentions" data-count="`)
		b.WriteString(strconv.Itoa(len(ml.Handles)))
		b.WriteString(`">`)
		for _, h := range ml.Handles {
			fmt.Fprintf(&b, `<li data-handle="%s"><button type="button" data-caps="%s">%s</button></li>`,
				template.HTMLEscapeString(h.Handle), template.HTMLEscapeString(h.Caps),
				template.HTMLEscapeString(h.Handle))
		}
		b.WriteString(`</ul>`)
		patchElements(w, b.String())
	})
	mux.HandleFunc("GET /r/{repo}/chat.sse", func(w http.ResponseWriter, req *http.Request) {
		if live == nil {
			http.NotFound(w, req)
			return
		}
		repo := req.PathValue("repo")
		// The stream carries the same messages the page does, so it
		// passes the same gate: capability "C" first, then visibility.
		// chat.history is the visibility check — it resolves the repo
		// through repoFor/CanRead, so an invisible repository answers
		// 404 here exactly as it does on the page, instead of quietly
		// opening a private channel to anyone who guessed the name.
		req, ok := gateCap(capsPlane, verify, sessions, repo, "C", ops.Anonymous, w, req)
		if !ok {
			return
		}
		if _, err := invoke(req.Context(), r, "chat.history",
			url.Values{"repo": {repo}, "limit": {"1"}}); err != nil {
			fail(r, w, req, err)
			return
		}
		v := viewer(verify, sessions, repo, req)
		canDeleteAny := false
		if v != "" {
			if c, ok := capsOf(capsPlane, sessions, verify, repo, req); ok {
				canDeleteAny = c.HasAny("a")
			}
		}
		// The page's rows were rendered by the api's markup pipeline;
		// live rows reach the same renderer through markup.preview, so
		// there is one renderer rather than two that drift.
		render := func(text string) string {
			out, err := invoke(req.Context(), r, "markup.preview",
				url.Values{"repo": {repo}, "body": {text}})
			if err != nil {
				return ""
			}
			var mp struct {
				HTML string `json:"html"`
			}
			remarshal(out, &mp)
			return mp.HTML
		}
		liveChatAs(live, repo, v, canDeleteAny, render, w, req)
	})
	mux.HandleFunc("GET /r/{repo}/forum", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		sort := req.URL.Query().Get("sort")
		// The viewer's identity rides into forum.list so the page can
		// mute what THEY have already read. Anonymous stays anonymous:
		// no identity, no read-state, every row at full ink.
		ctx := req.Context()
		reader := viewer(verify, sessions, repo, req)
		if reader != "" {
			ctx = ops.WithUser(ctx, reader)
		}
		out, err := invoke(ctx, r, "forum.list", url.Values{"repo": {repo}, "sort": {sort}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var fl struct {
			Threads       []forumThreadRow `json:"threads"`
			Announcements []forumThreadRow `json:"announcements"`
		}
		remarshal(out, &fl)
		flash := ""
		if req.URL.Query().Get("staged") != "" {
			flash = "Your post is held for moderation and will appear once a moderator approves it."
		}
		render(r, w, req, forumListPage, pageData{Title: "forum", Repo: repo,
			Forum: fl.Threads, ForumPinned: fl.Announcements, Sort: sort, Flash: flash,
			// On THIS page CanWrite carries the announce capability: the
			// "new announcement" control follows Admin.
			CanWrite: mayCap(capsPlane, verify, sessions, repo, "5", ops.Admin, req)})
	})
	mux.HandleFunc("POST /r/{repo}/forum/read", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "3", ops.Token, w, req)
		if !ok {
			return
		}
		// No root: the whole forum, up to now. Failing to remember is
		// not worth a failure page, but it IS worth not lying about —
		// the redirect lands on a list that still shows the truth.
		if _, err := invoke(req.Context(), r, "forum.read", url.Values{"repo": {repo}}); err != nil {
			fail(r, w, req, err)
			return
		}
		http.Redirect(w, req, "/r/"+repo+"/forum", http.StatusSeeOther)
	})
	mux.HandleFunc("GET /r/{repo}/forum/queue", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateAt(verify, sessions, repo, ops.Admin, w, req)
		if !ok {
			return
		}
		out, err := invoke(req.Context(), r, "forum.queue", url.Values{"repo": {repo}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var q struct {
			Entries []stagedRow `json:"entries"`
			Enabled bool        `json:"enabled"`
		}
		remarshal(out, &q)
		render(r, w, req, forumQueuePage, pageData{Title: "moderation queue", Repo: repo,
			Queue: q.Entries, ModOn: q.Enabled})
	})
	mux.HandleFunc("POST /r/{repo}/forum/queue", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateAt(verify, sessions, repo, ops.Admin, w, req)
		if !ok {
			return
		}
		var err error
		if t := req.FormValue("toggle"); t != "" {
			_, err = invoke(req.Context(), r, "forum.moderation",
				url.Values{"repo": {repo}, "enabled": {t}})
		} else {
			_, err = invoke(req.Context(), r, "forum.moderate", url.Values{
				"repo": {repo}, "id": {req.FormValue("id")},
				"action": {req.FormValue("action")}, "reason": {req.FormValue("reason")},
			})
		}
		if err != nil {
			fail(r, w, req, err)
			return
		}
		http.Redirect(w, req, "/r/"+repo+"/forum/queue", http.StatusSeeOther)
	})
	mux.HandleFunc("GET /r/{repo}/forum/modlog", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		out, err := invoke(req.Context(), r, "forum.modlog", url.Values{"repo": {repo}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var ml struct {
			Entries []modRow `json:"entries"`
		}
		remarshal(out, &ml)
		render(r, w, req, forumModlogPage, pageData{Title: "moderation log", Repo: repo, ModLog: ml.Entries})
	})
	mux.HandleFunc("POST /r/{repo}/markup-preview", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gate(verify, sessions, repo, w, req)
		if !ok {
			return
		}
		out, err := invoke(req.Context(), r, "markup.preview", url.Values{
			"repo": {repo}, "body": {req.FormValue("body")},
		})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var mp struct {
			HTML string `json:"html"`
		}
		remarshal(out, &mp)
		// A bare sanitized fragment: composer.js owns both the live pane
		// and the Preview tab and sets innerHTML itself.
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		io.WriteString(w, mp.HTML)
	})
	mux.HandleFunc("POST /r/{repo}/forum/{root}/subscribe", func(w http.ResponseWriter, req *http.Request) {
		repo, root := req.PathValue("repo"), req.PathValue("root")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "3", ops.Token, w, req)
		if !ok {
			return
		}
		if _, err := invoke(req.Context(), r, "forum.subscribe", url.Values{
			"repo": {repo}, "root": {root}, "state": {req.FormValue("state")},
		}); err != nil {
			fail(r, w, req, err)
			return
		}
		// Unfollowing from the inbox goes back to the inbox: a triage
		// pass must not be interrupted by the thread being left.
		if req.FormValue("back") == "inbox" {
			http.Redirect(w, req, "/inbox", http.StatusSeeOther)
			return
		}
		http.Redirect(w, req, "/r/"+repo+"/forum/"+root, http.StatusSeeOther)
	})
	mux.HandleFunc("POST /r/{repo}/forum/{root}/hide", func(w http.ResponseWriter, req *http.Request) {
		repo, root := req.PathValue("repo"), req.PathValue("root")
		req, ok := gateAt(verify, sessions, repo, ops.Admin, w, req)
		if !ok {
			return
		}
		if _, err := invoke(req.Context(), r, "forum.hide", url.Values{
			"repo": {repo}, "post": {req.FormValue("post")},
			"action": {req.FormValue("action")}, "reason": {req.FormValue("reason")},
		}); err != nil {
			fail(r, w, req, err)
			return
		}
		http.Redirect(w, req, "/r/"+repo+"/forum/"+root, http.StatusSeeOther)
	})
	mux.HandleFunc("GET /r/{repo}/announce-new", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		if _, ok := gateAt(verify, sessions, repo, ops.Admin, w, req); !ok {
			return
		}
		render(r, w, req, forumAnnouncePage, pageData{Title: "new announcement", Repo: repo, Composer: true})
	})
	mux.HandleFunc("POST /r/{repo}/announce-new", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateAt(verify, sessions, repo, ops.Admin, w, req)
		if !ok {
			return
		}
		out, err := invoke(req.Context(), r, "forum.announce", url.Values{
			"repo": {repo}, "title": {req.FormValue("title")}, "body": {req.FormValue("body")},
		})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var fp struct {
			Hash string `json:"hash"`
		}
		remarshal(out, &fp)
		http.Redirect(w, req, "/r/"+repo+"/forum/"+fp.Hash[:min(16, len(fp.Hash))], http.StatusSeeOther)
	})
	mux.HandleFunc("GET /r/{repo}/forum-new", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		if !mirrorGate(r, w, req, repo) {
			return
		}
		if _, ok := gate(verify, sessions, repo, w, req); !ok {
			return
		}
		render(r, w, req, forumNewPage, pageData{Title: "new thread", Repo: repo, Composer: true})
	})
	mux.HandleFunc("POST /r/{repo}/forum-new", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "3", ops.Token, w, req)
		if !ok {
			return
		}
		out, err := invoke(req.Context(), r, "forum.post", url.Values{
			"repo": {repo}, "title": {req.FormValue("title")}, "body": {req.FormValue("body")},
		})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var fp struct {
			Hash   string `json:"hash"`
			Staged bool   `json:"staged"`
		}
		remarshal(out, &fp)
		if fp.Staged {
			http.Redirect(w, req, "/r/"+repo+"/forum?staged=1", http.StatusSeeOther)
			return
		}
		http.Redirect(w, req, "/r/"+repo+"/forum/"+fp.Hash[:min(16, len(fp.Hash))], http.StatusSeeOther)
	})
	mux.HandleFunc("POST /r/{repo}/forum/{root}/reply", func(w http.ResponseWriter, req *http.Request) {
		repo, root := req.PathValue("repo"), req.PathValue("root")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "3", ops.Token, w, req)
		if !ok {
			return
		}
		out, err := invoke(req.Context(), r, "forum.reply", url.Values{
			"repo": {repo}, "root": {root}, "body": {req.FormValue("body")},
			"to": {req.FormValue("to")},
		})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var fr struct {
			Staged bool `json:"staged"`
		}
		remarshal(out, &fr)
		if fr.Staged {
			http.Redirect(w, req, "/r/"+repo+"/forum/"+root+"?staged=1", http.StatusSeeOther)
			return
		}
		http.Redirect(w, req, "/r/"+repo+"/forum/"+root, http.StatusSeeOther)
	})
	mux.HandleFunc("GET /r/{repo}/technote-new", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		if !mirrorGate(r, w, req, repo) {
			return
		}
		if _, ok := gate(verify, sessions, repo, w, req); !ok {
			return
		}
		render(r, w, req, technoteEditPage, pageData{Title: "new note", OwnH1: true, Repo: repo})
	})
	mux.HandleFunc("POST /r/{repo}/technote-new", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "k", ops.Token, w, req)
		if !ok {
			return
		}
		args := url.Values{"repo": {repo}, "body": {req.FormValue("body")},
			"comment": {req.FormValue("comment")}}
		// Empty means "now" on a new note; sending the key empty fails
		// validation, so only set it when the author chose a moment.
		if when := req.FormValue("time"); when != "" {
			args.Set("time", when)
		}
		out, err := invoke(req.Context(), r, "technote.add", args)
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var ta struct {
			Event string `json:"event"`
		}
		remarshal(out, &ta)
		http.Redirect(w, req, "/r/"+repo+"/technote/"+ta.Event[:min(16, len(ta.Event))], http.StatusSeeOther)
	})
	mux.HandleFunc("GET /r/{repo}/technote/{event}/edit", func(w http.ResponseWriter, req *http.Request) {
		repo, event := req.PathValue("repo"), req.PathValue("event")
		if !mirrorGate(r, w, req, repo) {
			return
		}
		if _, ok := gate(verify, sessions, repo, w, req); !ok {
			return
		}
		out, err := invoke(req.Context(), r, "technote.get",
			url.Values{"repo": {repo}, "event": {event}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var tg struct {
			Event   string `json:"event"`
			Date    string `json:"date"`
			Body    string `json:"body"`
			Comment string `json:"comment"`
		}
		remarshal(out, &tg)
		render(r, w, req, technoteEditPage, pageData{
			Title: "edit note", OwnH1: true, Repo: repo,
			Technote:   technoteDetail{Event: tg.Event, Comment: tg.Comment, Date: tg.Date},
			EditSource: tg.Body,
		})
	})
	mux.HandleFunc("POST /r/{repo}/technote/{event}/edit", func(w http.ResponseWriter, req *http.Request) {
		repo, event := req.PathValue("repo"), req.PathValue("event")
		req, ok := gate(verify, sessions, repo, w, req)
		if !ok {
			return
		}
		args := url.Values{"repo": {repo}, "body": {req.FormValue("body")},
			"event": {event}, "comment": {req.FormValue("comment")}}
		if when := req.FormValue("time"); when != "" {
			args.Set("time", when)
		}
		if _, err := invoke(req.Context(), r, "technote.add", args); err != nil {
			fail(r, w, req, err)
			return
		}
		http.Redirect(w, req, "/r/"+repo+"/technote/"+event, http.StatusSeeOther)
	})
	mux.HandleFunc("GET /r/{repo}/forum/{root}", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		// A landing record is a forum thread and is deliberately not
		// forum CONTENT, so it does not render here. An existing link
		// still resolves though — it goes to the surface that owns the
		// record, where the marker is a header and not a first line of
		// prose. Refusing outright would break links for no gain.
		if id, ok := landingRoot(r, req, repo, req.PathValue("root")); ok {
			http.Redirect(w, req, "/r/"+repo+"/landing/"+id, http.StatusSeeOther)
			return
		}
		// The viewer's identity rides into forum.get so the page can
		// light the arrow they already cast (YourVote).
		ctx := req.Context()
		reader := viewer(verify, sessions, repo, req)
		if reader != "" {
			ctx = ops.WithUser(ctx, reader)
		}
		out, err := invoke(ctx, r, "forum.get",
			url.Values{"repo": {repo}, "root": {req.PathValue("root")}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		// A person opening this page really is reading the thread, so
		// the mark happens HERE and not inside forum.get — which stays a
		// pure query for crawlers, feeds and API clients. Failing to
		// remember must never cost the reader their page, so the error
		// goes nowhere.
		if reader != "" {
			_, _ = invoke(ctx, r, "forum.read",
				url.Values{"repo": {repo}, "root": {req.PathValue("root")}})
		}
		var fg struct {
			Title   string         `json:"title"`
			Excerpt string         `json:"excerpt"`
			Posts   []forumPostRow `json:"posts"`
			YourSub string         `json:"yourSub"`
		}
		remarshal(out, &fg)
		title := fg.Title
		if title == "" {
			title = "thread"
		}
		flash := ""
		if req.URL.Query().Get("staged") != "" {
			flash = "Your reply is held for moderation and will appear once a moderator approves it."
		}
		// The reply DAG, joined for display: each post learns who wrote
		// the post it answers, and ?reply-to aims the composer at a
		// specific post (validated against the thread; a stray value is
		// ignored rather than smuggled into the form).
		fg.Posts = threadShape(fg.Posts)
		replyTo, replyToUser := "", ""
		if rt := req.URL.Query().Get("reply-to"); rt != "" {
			for _, p := range fg.Posts {
				if strings.HasPrefix(p.Hash, rt) {
					replyTo, replyToUser = p.Hash[:min(12, len(p.Hash))], p.User
					break
				}
			}
		}
		render(r, w, req, forumThreadPage, pageData{
			Title: title, Repo: repo, ForumPosts: fg.Posts, YourSub: fg.YourSub,
			OGDesc:  fg.Excerpt,
			ReplyTo: replyTo, ReplyToUser: replyToUser,
			ForumRoot: req.PathValue("root"), Flash: flash, Composer: true,
			// Same rule as the board's move control: the arrows follow
			// write CAPABILITY, not session state.
			CanWrite: mayCap(capsPlane, verify, sessions, repo, "3", ops.Token, req),
			CanMod:   mayCap(capsPlane, verify, sessions, repo, "5", ops.Admin, req),
			ChatRefs: chatRefsOf(out),
		})
	})
	mux.HandleFunc("POST /r/{repo}/forum/{root}/vote", func(w http.ResponseWriter, req *http.Request) {
		repo, root := req.PathValue("repo"), req.PathValue("root")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "3", ops.Token, w, req)
		if !ok {
			return
		}
		out, err := invoke(req.Context(), r, "forum.vote", url.Values{
			"repo": {repo}, "post": {req.FormValue("post")}, "dir": {req.FormValue("dir")},
		})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		// A datastar submit gets the widget patched in place — the
		// score and arrows update with no page flash. A plain form
		// submit gets the redirect it always did (Principle 3).
		if req.Header.Get("datastar-request") != "true" {
			http.Redirect(w, req, "/r/"+repo+"/forum/"+root, http.StatusSeeOther)
			return
		}
		var fv struct {
			Post  string `json:"post"`
			Score int    `json:"score"`
		}
		remarshal(out, &fv)
		yourVote := map[string]int{"up": 1, "down": -1}[req.FormValue("dir")]
		var buf bytes.Buffer
		if err := forumThreadPage.ExecuteTemplate(&buf, "vote-widget",
			voteCtx{Repo: repo, Root: root, Hash: fv.Post, Score: fv.Score, YourVote: yourVote}); err != nil {
			http.Error(w, "widget render failed", http.StatusInternalServerError)
			return
		}
		w.Header().Set("Content-Type", "text/event-stream")
		fmt.Fprint(w, "event: datastar-patch-elements\n")
		for _, line := range strings.Split(buf.String(), "\n") {
			fmt.Fprintf(w, "data: elements %s\n", line)
		}
		fmt.Fprint(w, "\n")
	})
	mux.HandleFunc("POST /r/{repo}/forum/{root}/poll", func(w http.ResponseWriter, req *http.Request) {
		repo, root := req.PathValue("repo"), req.PathValue("root")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "3", ops.Token, w, req)
		if !ok {
			return
		}
		if _, err := invoke(req.Context(), r, "forum.poll", url.Values{
			"repo": {repo}, "post": {req.FormValue("post")}, "choice": {req.FormValue("choice")},
		}); err != nil {
			fail(r, w, req, err)
			return
		}
		http.Redirect(w, req, "/r/"+repo+"/forum/"+root, http.StatusSeeOther)
	})
	mux.HandleFunc("GET /r/{repo}/technote", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		out, err := invoke(req.Context(), r, "technote.list", url.Values{"repo": {repo}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var tl struct {
			Notes []technoteRow `json:"notes"`
		}
		remarshal(out, &tl)
		render(r, w, req, technoteListPage, pageData{Title: "notes", OwnH1: true, Repo: repo, Technotes: tl.Notes})
	})
	mux.HandleFunc("GET /r/{repo}/technote/{event}", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		args := url.Values{"repo": {repo}, "event": {req.PathValue("event")}}
		// Only when asked for. An empty rev is "latest", and sending
		// the key with an empty value fails validation.
		if rev := req.URL.Query().Get("rev"); rev != "" {
			args.Set("rev", rev)
		}
		out, err := invoke(req.Context(), r, "technote.get", args)
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var tg technoteDetail
		var html string
		var body struct {
			HTML string `json:"html"`
		}
		remarshal(out, &tg)
		remarshal(out, &body)
		html = body.HTML
		title := plainTitle(tg.Comment)
		if title == "" {
			title = "note " + tg.Date
		}
		render(r, w, req, technotePage, pageData{
			Title: title, OwnH1: true, Repo: repo, Technote: tg,
			WikiHTML: template.HTML(html),
		})
	})
	mux.HandleFunc("GET /r/{repo}/technote/{event}/history", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		out, err := invoke(req.Context(), r, "technote.history",
			url.Values{"repo": {repo}, "event": {req.PathValue("event")}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var th struct {
			Event   string        `json:"event"`
			Comment string        `json:"comment"`
			Edits   []technoteRev `json:"edits"`
		}
		remarshal(out, &th)
		// The note's own filing date comes from the CURRENT version, so
		// the history can say which older versions were filed elsewhere.
		filed := ""
		if len(th.Edits) > 0 {
			filed = th.Edits[0].Date
		}
		render(r, w, req, technoteHistoryPage, pageData{
			Title: "history", OwnH1: true, Repo: repo,
			Technote: technoteDetail{Event: th.Event, Comment: th.Comment, Date: filed},
			TechRevs: th.Edits,
		})
	})
	// Landings: what is awaiting a decision. A landing is a branch
	// proposed for a target, not a request to transfer commits — the
	// branch is already here — so the page reads as a decision queue.
	// Proposing a branch. Both handlers gate on the forum capability:
	// opening a landing mints a thread, and nothing here merges.
	mux.HandleFunc("GET /r/{repo}/landing-new", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		if !mirrorGate(r, w, req, repo) {
			return
		}
		if _, ok := gateCap(capsPlane, verify, sessions, repo, "3", ops.Token, w, req); !ok {
			return
		}
		var bl struct {
			Branches []branchRow `json:"branches"`
		}
		if out, err := invoke(req.Context(), r, "branch.list",
			url.Values{"repo": {repo}, "limit": {"200"}}); err == nil {
			remarshal(out, &bl)
		}
		// The target defaults to the repository's own default branch,
		// which the timeline op already reports — one source, so the
		// form cannot disagree with the graph about what trunk is.
		var tl struct {
			DefaultBranch string `json:"defaultBranch"`
		}
		if out, err := invoke(req.Context(), r, "timeline.list",
			url.Values{"repo": {repo}, "limit": {"1"}}); err == nil {
			remarshal(out, &tl)
		}
		def := tl.DefaultBranch
		render(r, w, req, landingNewPage, pageData{Title: "new landing", Repo: repo,
			Branches: bl.Branches, RefName: def, Query: req.URL.Query().Get("branch"),
			Composer: true})
	})
	mux.HandleFunc("POST /r/{repo}/landing-new", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		if !mirrorGate(r, w, req, repo) {
			return
		}
		req, ok := gateCap(capsPlane, verify, sessions, repo, "3", ops.Token, w, req)
		if !ok {
			return
		}
		if err := req.ParseForm(); err != nil {
			http.Error(w, "bad form", http.StatusBadRequest)
			return
		}
		out, err := invoke(req.Context(), r, "landing.open", url.Values{
			"repo": {repo}, "branch": {req.FormValue("branch")},
			"target": {req.FormValue("target")}, "message": {req.FormValue("message")}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var opened struct {
			ID string `json:"id"`
		}
		remarshal(out, &opened)
		http.Redirect(w, req, "/r/"+repo+"/landing/"+opened.ID, http.StatusSeeOther)
	})
	mux.HandleFunc("GET /r/{repo}/landing", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		state := req.URL.Query().Get("state")
		ask := state
		switch state {
		case "accepted", "rejected":
		case "all":
			ask = ""
		default:
			state, ask = "", "open"
		}
		out, err := invoke(req.Context(), r, "landing.list",
			url.Values{"repo": {repo}, "state": {ask}, "limit": {"200"}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var ll struct {
			Landings []landingRow `json:"landings"`
			Open     int          `json:"open"`
		}
		remarshal(out, &ll)
		// No h1: the tab already says "landings", and the page's own
		// first line is the state chips — the same reading the tickets
		// list gives across the fleet.
		// The open queue groups a strata under its base; the settled
		// views stay flat, because a settled segment has left its chain.
		var groups []landingGroup
		if ask == "open" {
			groups = groupLandings(ll.Landings)
		}
		render(r, w, req, landingListPage, pageData{Title: "landings", HideH1: true, Repo: repo,
			Landings: ll.Landings, LandingGroups: groups, LandingOpen: ll.Open,
			// Proposing mints a forum thread, so the control follows the
			// capability that writes one — not the one that merges.
			CanWrite: mayCap(capsPlane, verify, sessions, repo, "3", ops.Token, req),
			Nav:      ticketNav{Repo: repo, State: state}})
	})
	mux.HandleFunc("GET /r/{repo}/landing/{id}", func(w http.ResponseWriter, req *http.Request) {
		repo, id := req.PathValue("repo"), req.PathValue("id")
		// The viewer travels with the read: MayLand is a question about
		// THIS person, and an op asked with no user answers for nobody,
		// who owns nothing.
		out, err := invoke(ops.WithUser(req.Context(), viewer(verify, sessions, repo, req)), r, "landing.get",
			url.Values{"repo": {repo}, "id": {id}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var lg struct {
			Landing landingRow `json:"landing"`
			Posts   []struct {
				Hash         string `json:"hash"`
				Parent       string `json:"parent"`
				Date         string `json:"date"`
				User         string `json:"user"`
				HTML         string `json:"html"`
				Hidden       bool   `json:"hidden"`
				HiddenReason string `json:"hiddenReason"`
				Transition   string `json:"transition"`
				Retarget     string `json:"retarget"`
				TitleIsBody  bool   `json:"titleIsBody"`
				Updated      string `json:"updated"`
				Root         bool   `json:"root"`
			} `json:"posts"`
			CanAccept   bool       `json:"canAccept"`
			MayLand     bool       `json:"mayLand"`
			Protected   bool       `json:"protected"`
			Owners      []string   `json:"owners"`
			Checks      []ciRunRow `json:"checks"`
			Required    []string   `json:"required"`
			Unmet       []string   `json:"unmet"`
			MayOverride bool       `json:"mayOverride"`
			AutoBy      string     `json:"autoBy"`
			Premerge    bool       `json:"premerge"`
			Behind      int        `json:"behind"`
			Stack       stackView  `json:"stack"`
			Mergeable   string     `json:"mergeable"`
			Conflicts   []string   `json:"conflicts"`
			Commits     []struct {
				Hash    string `json:"hash"`
				Date    string `json:"date"`
				User    string `json:"user"`
				Comment string `json:"comment"`
			} `json:"commits"`
			Merge struct {
				Checkin string `json:"checkin"`
				Date    string `json:"date"`
				User    string `json:"user"`
				Comment string `json:"comment"`
			} `json:"merge"`
			MergeCI    string `json:"mergeCi"`
			MergeCIRun string `json:"mergeCiRun"`
		}
		remarshal(out, &lg)
		det := &landingDetail{landingRow: lg.Landing, CanAccept: lg.CanAccept,
			CanSpeak: mayCap(capsPlane, verify, sessions, repo, "3", ops.Token, req)}
		det.Mergeable, det.Conflicts, det.Merge = lg.Mergeable, lg.Conflicts, lg.Merge
		det.MergeCI, det.MergeCIRun = lg.MergeCI, lg.MergeCIRun
		det.MayLand, det.Protected, det.Owners = lg.MayLand, lg.Protected, lg.Owners
		det.Checks, det.Required, det.Unmet, det.MayOverride = lg.Checks, lg.Required, lg.Unmet, lg.MayOverride
		det.Premerge, det.Behind = lg.Premerge, lg.Behind
		det.AutoBy = lg.AutoBy
		// RFC 0009: red is where the decision needs the WHY, so the
		// failed step's log rides on the card instead of asking the
		// reader to navigate away to learn what broke.
		for i := range det.Checks {
			c := &det.Checks[i]
			if ciStateOf(c.Status) != "fail" || c.RunID == "" || c.Pipeline == "external" {
				continue
			}
			c.TailStep, c.Tail, c.TailNote = failTail(o.engine, o.cilogs, repo, c.RunID)
		}
		det.Stack = lg.Stack
		for _, sgm := range lg.Stack.Segments {
			if sgm.ID == lg.Landing.ID {
				det.Position = sgm.Position
			}
		}
		// zit records a transition as a reply because a reply is an
		// artifact fossil understands. A reader wants it as an EVENT,
		// so the two are separated here rather than rendered alike.
		//
		// Threading is shaped over the WHOLE thread — opener and
		// transitions included — and only then filtered down to the
		// remarks. Shaping the remainder alone would re-root the walk
		// on whichever remark came first and flatten every depth below
		// it, so a reply to the opener would read as a reply to nobody.
		all := make([]forumPostRow, 0, len(lg.Posts))
		for _, p := range lg.Posts {
			all = append(all, forumPostRow{Hash: p.Hash, Parent: p.Parent,
				Date: p.Date, User: p.User, HTML: template.HTML(p.HTML),
				Hidden: p.Hidden, HiddenReason: p.HiddenReason})
		}
		all = threadShape(all)
		titleIsBody := false
		kind := make(map[string]string, len(lg.Posts))
		for _, p := range lg.Posts {
			switch {
			case p.Transition != "":
				kind[p.Hash] = "event"
				det.Events = append(det.Events, landingEvent{State: p.Transition,
					User: p.User, Date: p.Date})
			case p.Retarget != "":
				// Machine text. Left in the discussion it renders the
				// marker itself as somebody's remark.
				kind[p.Hash] = "event"
				det.Events = append(det.Events, landingEvent{State: "retargeted",
					Detail: p.Retarget, User: p.User, Date: p.Date})
			case p.Updated != "":
				kind[p.Hash] = "event"
				det.Events = append(det.Events, landingEvent{State: "updated",
					Merge: p.Updated, User: p.User, Date: p.Date, HTML: template.HTML(p.HTML)})
			case p.Root:
				kind[p.Hash] = "root"
				det.Description = template.HTML(p.HTML)
				titleIsBody = p.TitleIsBody
			}
		}
		for _, row := range all {
			if kind[row.Hash] != "" {
				continue // the opener IS the description; transitions are events
			}
			// A remark answering the opener sits at the left margin, and
			// says nothing about who it answers: the opener is not drawn
			// in this list, so the indent would have nothing to sit under
			// and the attribution would link at a post that is not on the
			// page. Answering the record IS the default, so silence is
			// the honest rendering of it.
			if kind[row.Parent] == "root" {
				row.Parent, row.ParentUser = "", ""
			}
			if row.IndentPx > 0 {
				row.IndentPx -= 26
			}
			det.Comments = append(det.Comments, row)
		}
		// ?reply-to aims the composer at one remark, validated against
		// the record's own thread — a stray value is ignored rather than
		// smuggled into the form.
		if rt := req.URL.Query().Get("reply-to"); rt != "" {
			for _, c := range det.Comments {
				if strings.HasPrefix(c.Hash, rt) {
					det.ReplyTo = c.Hash[:min(12, len(c.Hash))]
					det.ReplyToUser = c.User
					break
				}
			}
		}
		// The diff is computed NOW, branch against target: the record
		// follows a MOVING branch, so a range frozen at open would
		// describe a proposal that no longer exists.
		// A heading is ONE line, and one line is not the same as one
		// SHORT line: zit puts the whole -m message in the record's
		// title card, and a message written without a subject line
		// arrives as a single 400-character "line" that firstLine
		// happily returns whole. Rendered at h1 size that fills a phone
		// screen before the record says anything about itself.
		//
		// Clipped at the same 72 the timeline already uses for this
		// exact string, so the two agree on what a landing is called.
		// Nothing is lost: the opener's full text renders immediately
		// below as the description.
		// A record only HAS a headline when its author wrote one: a
		// subject line, a blank line, then the body. Written without
		// that, the whole message is the title, and clipping it to 72
		// invents a headline the author never wrote — then ends it in an
		// ellipsis that says something is hidden, when the same words
		// are in full directly below. So the visible heading goes; the
		// chips and the message carry the record, and the sr-only h1
		// keeps the page named.
		data := pageData{Title: unmarkTitle(firstLine(lg.Landing.Title)), Repo: repo,
			Landing: det, Composer: true, HideH1: titleIsBody,
			Landed: req.URL.Query().Get("landed"), Stopped: req.URL.Query().Get("stopped")}
		// Which base depends on whether the record is still a question.
		//
		// While a landing is OPEN the useful diff is against the
		// target's current tip: "what would merging this change now".
		// Once it is SETTLED that question has a degenerate answer —
		// the branch is already contained in the target, so the diff is
		// empty — and the only meaningful reading left is historical:
		// "what did this branch do", which is the fork point.
		//
		// Diffing a settled record against the moving tip is why an
		// accepted landing showed an empty Changes section: not an
		// error, just the right answer to a question nobody was asking.
		tip := branchTip(r, req, repo, lg.Landing.Branch)
		base := branchTip(r, req, repo, lg.Landing.Target)
		if lg.Landing.State != "open" {
			if fork := forkPointOf(r, req, repo, tip); fork != "" {
				base = fork
			}
		}
		// The branch's own check-ins. A proposal is a set of changes
		// with REASONS attached; a diff keeps the changes and throws the
		// reasons away, which is why every forge shows both.
		// In ancestry order, from the op — NOT through the timeline,
		// which sorts by date and falls back to hash for the
		// same-second ties this branch produces routinely.
		for _, e := range lg.Commits {
			det.Commits = append(det.Commits, landingCommit{Hash: e.Hash,
				Short: e.Hash[:min(12, len(e.Hash))], User: e.User,
				Date: e.Date, Comment: e.Comment})
		}
		// The changes are a SUMMARY here, not the whole diff. A branch
		// worth landing is often large — this record's own diff is 20
		// files and 900KB rendered, enough to stall a browser — and the
		// landing page's job is the decision, not the reading. The full
		// diff has a page already; this one links to it.
		if dd, derr := invoke(req.Context(), r, "checkin.diff", url.Values{
			"repo": {repo}, "hash": {tip}, "from": {base},
			"maxLines": {landingDiffLines}}); derr == nil && tip != "" && base != "" {
			remarshal(dd, &data.Diff)
			data.Diff.Repo = repo
			// A successful call that found nothing is not the same as a
			// failed one, and it must not render as an empty dropdown
			// either — that reads as "no changes" when the truth is
			// "these two check-ins hold the same tree".
			if len(data.Diff.Files) == 0 {
				det.Stale = "No difference between " + shortHash(base) +
					" and " + shortHash(tip) + ": the two hold the same tree."
			} else {
				det.Diff = &data.Diff
				det.FullDiff = "/r/" + repo + "/checkin/" + tip + "/diff?from=" + base
			}
		} else {
			// A branch that no longer resolves is the common cause: it
			// was renamed or removed after the record was opened. Say
			// which, rather than rendering an empty Changes section that
			// reads as "no changes".
			det.Stale = "No diff: " + lg.Landing.Branch + " does not resolve against " + lg.Landing.Target + " right now."
		}
		data.ChatRefs = chatRefsOf(out)
		render(r, w, req, landingPage, data)
	})
	// The three decisions, as ordinary form posts. Each is capability
	// gated at the op; the page only decides which controls to draw, so
	// a hand-made post is refused by the same rule the button obeys.
	// Land a strata up to a rung: one accept per rung, bottom-up, in
	// the op; the page comes back to the rung asked for, whose map now
	// shows what landed and where it stopped.
	mux.HandleFunc("POST /r/{repo}/landing/{id}/land", func(w http.ResponseWriter, req *http.Request) {
		repo, id := req.PathValue("repo"), req.PathValue("id")
		if !mirrorGate(r, w, req, repo) {
			return
		}
		req, ok := gateCap(capsPlane, verify, sessions, repo, landingCap("accept"), ops.Token, w, req)
		if !ok {
			return
		}
		if err := req.ParseForm(); err != nil {
			http.Error(w, "bad form", http.StatusBadRequest)
			return
		}
		out, err := invoke(req.Context(), r, "landing.land", url.Values{"repo": {repo}, "id": {id},
			"message": {req.FormValue("message")}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var res struct {
			Landed  []string `json:"landed"`
			Stopped string   `json:"stopped"`
		}
		remarshal(out, &res)
		q := "?landed=" + strconv.Itoa(len(res.Landed))
		if res.Stopped != "" {
			q += "&stopped=" + url.QueryEscape(res.Stopped[:min(12, len(res.Stopped))])
		}
		http.Redirect(w, req, "/r/"+repo+"/landing/"+id+q, http.StatusSeeOther)
	})
	for _, verb := range []string{"comment", "reject", "accept", "update"} {
		mux.HandleFunc("POST /r/{repo}/landing/{id}/"+verb, func(w http.ResponseWriter, req *http.Request) {
			repo, id := req.PathValue("repo"), req.PathValue("id")
			if !mirrorGate(r, w, req, repo) {
				return
			}
			req, ok := gateCap(capsPlane, verify, sessions, repo, landingCap(verb), ops.Token, w, req)
			if !ok {
				return
			}
			if err := req.ParseForm(); err != nil {
				http.Error(w, "bad form", http.StatusBadRequest)
				return
			}
			form := url.Values{"repo": {repo}, "id": {id},
				"message": {req.FormValue("message")}}
			// Only a remark carries a target; a transition settles the
			// whole record and has nothing to answer.
			if to := req.FormValue("to"); to != "" && verb == "comment" {
				form.Set("to", to)
			}
			// RFC 0009: the stated reason for accepting over a red
			// required check travels with the accept, nothing else.
			if o := strings.TrimSpace(req.FormValue("override")); o != "" && verb == "accept" {
				form.Set("override", o)
			}
			_, err := invoke(req.Context(), r, "landing."+verb, form)
			if err != nil {
				fail(r, w, req, err)
				return
			}
			http.Redirect(w, req, "/r/"+repo+"/landing/"+id, http.StatusSeeOther)
		})
	}
	mux.HandleFunc("POST /r/{repo}/landing/{id}/auto", func(w http.ResponseWriter, req *http.Request) {
		repo, id := req.PathValue("repo"), req.PathValue("id")
		if !mirrorGate(r, w, req, repo) {
			return
		}
		req, ok := gateCap(capsPlane, verify, sessions, repo, landingCap("accept"), ops.Token, w, req)
		if !ok {
			return
		}
		if err := req.ParseForm(); err != nil {
			http.Error(w, "bad form", http.StatusBadRequest)
			return
		}
		if _, err := invoke(req.Context(), r, "landing.auto", url.Values{"repo": {repo}, "id": {id},
			"on": {req.FormValue("on")}}); err != nil {
			fail(r, w, req, err)
			return
		}
		http.Redirect(w, req, "/r/"+repo+"/landing/"+id, http.StatusSeeOther)
	})
	mux.HandleFunc("GET /r/{repo}/ticket", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		q := req.URL.Query()
		// The query box is INPUT SUGAR: parse it into the parameters
		// that are the report and send the reader to that URL, so what
		// they end up sharing is the canonical form and there is only
		// ever one spelling of a listing in the address bar. A present
		// but empty box means "clear", which is why this tests for the
		// key rather than for a value.
		if q.Has("q") {
			v := ticketParseQuery(q.Get("q"))
			for _, k := range []string{"view", "sort", "order", "group", "lane"} {
				if x := q.Get(k); x != "" {
					v.Set(k, x)
				}
			}
			dest := "/r/" + repo + "/ticket"
			if len(v) > 0 {
				dest += "?" + v.Encode()
			}
			http.Redirect(w, req, dest, http.StatusSeeOther)
			return
		}
		state := ticketState(q)
		report := ticketReport(q)
		title := strings.TrimSpace(q.Get("title"))
		view := q.Get("view")
		if view != "table" && view != "board" {
			view = "" // the list, and the one URL that means it
		}
		order := q.Get("order")
		if _, ok := index.TicketOrders[order]; !ok {
			order = "" // a stale link degrades to the default, not a 500
		}
		sort := ""
		if q.Get("sort") == "recent" {
			sort = "recent"
		}
		// The table is ordered by SQL, so the vocabulary-aware triage
		// sort is the list's alone; asking for both would be two
		// orderings fighting over one slice.
		byPriority := view != "table" && sort != "recent"
		// Only a listing SQL put in order can be offset into. Triage
		// order is computed in Go over the rows already fetched, so
		// page two of it would be "the best of the next fifty by date"
		// — a different question wearing the same label.
		paged := !byPriority && view != "board"
		offset := 0
		if paged {
			if n, err := strconv.Atoi(q.Get("offset")); err == nil && n > 0 {
				offset = n
			}
		}
		vals := url.Values{"repo": {repo}, "before": {q.Get("before")}}
		if state != "" {
			vals.Set("state", state)
		}
		if view == "table" && order != "" {
			vals.Set("order", order)
		}
		if title != "" {
			vals.Set("title", title)
		}
		if paged {
			vals.Del("before")
			vals.Set("limit", strconv.Itoa(ticketPageSize))
			if offset > 0 {
				vals.Set("offset", strconv.Itoa(offset))
			}
		}
		for k, vs := range report {
			vals[k] = vs
		}
		if byPriority {
			// Neither priority order nor a sorted column can ride the
			// updated-cursor pagination, since that cursor encodes the
			// DEFAULT order's position. Both take one op-limit page and
			// say when that is not everything — the board's honesty.
			vals.Del("before")
			vals.Set("limit", strconv.Itoa(boardLimit))
		}
		out, err := invoke(req.Context(), r, "ticket.list", vals)
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var tl struct {
			Tickets    []ticketSummary `json:"tickets"`
			Next       string          `json:"next"`
			Open       int             `json:"open"`
			Closed     int             `json:"closed"`
			Subsystems []ticketFacet   `json:"subsystems"`
			Authors    []ticketFacet   `json:"authors"`
		}
		remarshal(out, &tl)
		vocab := ticketVocabFor(r, req, repo)
		if byPriority {
			byTriage(tl.Tickets, vocab)
			tl.Next = ""
		}
		data := pageData{Title: "tickets", Repo: repo, Rows: ticketRows(repo, tl.Tickets, vocab),
			Next: tl.Next, ByPriority: byPriority,
			Nav: ticketNav{Repo: repo, State: state, Sort: sort, View: view,
				Order: order, Title: title, Open: tl.Open, Closed: tl.Closed,
				Report: report, Offset: offset},
			Filters: ticketFilters(vocab, tl.Subsystems, tl.Authors, q),
			Columns: ticketColumns,
			Shown:   len(tl.Tickets), Truncated: byPriority && len(tl.Tickets) >= boardLimit}
		// The rail needs the counts the op just returned, so it is built
		// from the completed nav rather than the request.
		me := ""
		if sessions != nil {
			if u, ok := sessions.Resolve(cookieToken(req)); ok {
				me = u
			}
		}
		data.Rail = ticketRail(data.Nav, tl.Subsystems, tl.Authors, nil, me,
			savedViewsFor(r, req, me, repo))
		data.CanSaveView, data.SaveTarget = me != "", repo
		if paged {
			// The counts already came back through this report's
			// filter, so the total is the state the reader chose.
			total := tl.Open + tl.Closed
			switch state {
			case "closed":
				total = tl.Closed
			case "all":
			default:
				total = tl.Open
			}
			data.Pager = pagerFor(data.Nav, len(tl.Tickets), total)
			data.Next, data.Truncated = "", false
		}
		if view == "table" {
			render(r, w, req, ticketTablePage, data)
			return
		}
		if view == "board" {
			bd, err := boardData(r, req, ticketNav{Repo: repo, State: state,
				Title: title, Report: report, View: "board",
				Group: q.Get("group"), Lane: q.Get("lane")})
			if id := q.Get("moved"); id != "" && err == nil {
				mv := &boardMove{ID: id, Field: bd.GroupBy, From: q.Get("from"), To: q.Get("to")}
				for _, lane := range bd.Board {
					for _, col := range lane.Columns {
						for _, t := range col.Tickets {
							if strings.HasPrefix(t.ID, id) {
								mv.Title = t.Title
							}
						}
					}
				}
				bd.Moved = mv
			}
			if err != nil {
				fail(r, w, req, err)
				return
			}
			bd.CanWrite = mayWrite(verify, sessions, repo, req)
			render(r, w, req, ticketBoardPage, bd)
			return
		}
		render(r, w, req, ticketListPage, data)
	})
	mux.HandleFunc("GET /r/{repo}/ticket/{id}", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		out, err := invoke(req.Context(), r, "ticket.get",
			url.Values{"repo": {repo}, "id": {req.PathValue("id")}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var td struct {
			Ticket          ticketDetail    `json:"ticket"`
			Attachments     []attachmentRow `json:"attachments"`
			DescriptionHTML string          `json:"descriptionHtml"`
			Comments        []ticketComment `json:"comments"`
			Mentions        []mentionRow    `json:"mentions"`
		}
		remarshal(out, &td)
		ticketNote, hasTicketNote := associatedNote(r, req, repo, "ticket/"+td.Ticket.ID)
		// A ticket is known by its title, not its hash; fall back to the
		// id only when the tracker recorded no title.
		title := td.Ticket.Title()
		if title == "" {
			title = "ticket " + td.Ticket.ID[:10]
		}
		vocab := ticketVocabFor(r, req, repo)
		td.Ticket.ShowPrivate = maySeePrivate(capsPlane, verify, sessions, repo, req)
		var note template.HTML
		var noteName, noteKind string
		if hasTicketNote {
			note, noteName, noteKind = noteFor(ticketNote)
		}
		render(r, w, req, ticketPage, pageData{
			Title: title, Repo: repo, Ticket: td.Ticket,
			Note:            note,
			NoteName:        noteName,
			NoteKind:        noteKind,
			Attachments:     td.Attachments,
			Mentions:        td.Mentions,
			ChatRefs:        chatRefsOf(out),
			DescriptionHTML: template.HTML(td.DescriptionHTML),
			TicketComments:  td.Comments,
			Timeline:        ticketTimeline(td.Ticket, td.Comments),
			TicketFields:    ticketControls(td.Ticket, vocab),
			Vocab:           vocab,
			CanWrite:        mayWrite(verify, sessions, repo, req),
			Composer:        true,
		})
	})
	mux.HandleFunc("GET /search", func(w http.ResponseWriter, req *http.Request) {
		q := req.URL.Query().Get("q")
		kind := req.URL.Query().Get("kind")
		if kind != "" && !slices.Contains(index.SearchKinds, kind) {
			fail(r, w, req, fmt.Errorf("no such search scope %q: %w", kind, ops.ErrNotFound))
			return
		}
		_, scope := searchScopeName(kind)
		only := req.URL.Query().Get("repo")
		data := pageData{Title: "search", Query: q, SearchKind: kind, SearchScope: scope,
			RepoFilter: only}
		if q != "" {
			vals := url.Values{"q": {q}}
			if kind != "" {
				vals.Set("kind", kind)
			}
			if only != "" {
				vals.Set("repo", only)
			}
			out, err := invoke(req.Context(), r, "search.all", vals)
			if err != nil {
				fail(r, w, req, err)
				return
			}
			var sr struct {
				Results []struct {
					Repo string `json:"repo"`
					searchMeta
				} `json:"results"`
				Searched int `json:"searched"`
				ByRepo   []struct {
					Repo  string `json:"repo"`
					Count int    `json:"count"`
				} `json:"by_repo"`
			}
			remarshal(out, &sr)
			data.Searched = sr.Searched
			for _, b := range sr.ByRepo {
				data.ByRepo = append(data.ByRepo, repoFacet{Repo: b.Repo, Count: b.Count})
			}
			for _, res := range sr.Results {
				h := hitOfMeta(res.Repo, res.searchMeta)
				h.Repo = res.Repo
				data.Results = append(data.Results, h)
			}
		}
		render(r, w, req, globalSearchPage, data)
	})
	mux.HandleFunc("GET /r/{repo}/search", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		q := req.URL.Query().Get("q")
		kind := req.URL.Query().Get("kind")
		if kind != "" && !slices.Contains(index.SearchKinds, kind) {
			// An unknown scope is a bad URL, not an empty result: saying
			// "no results" would blame the query for a typo in the link.
			fail(r, w, req, fmt.Errorf("no such search scope %q: %w", kind, ops.ErrNotFound))
			return
		}
		_, scope := searchScopeName(kind)
		data := pageData{Title: "search", Repo: repo, Query: q,
			SearchKind: kind, SearchScope: scope}
		if q != "" {
			vals := req.URL.Query()
			vals.Set("repo", repo)
			out, err := invoke(req.Context(), r, "search.query", vals)
			if err != nil {
				fail(r, w, req, err)
				return
			}
			var sr struct {
				Results []struct {
					searchMeta
				} `json:"results"`
			}
			remarshal(out, &sr)
			for _, res := range sr.Results {
				data.Results = append(data.Results, hitOfMeta(repo, res.searchMeta))
			}
		}
		render(r, w, req, searchPage, data)
	})
	mux.HandleFunc("GET /r/{repo}/checkin/{hash}/diff", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		dd, err := diffWindow(r, req, repo, req.PathValue("hash"))
		if err != nil {
			fail(r, w, req, err)
			return
		}
		title := "diff " + dd.To[:12]
		if dd.File != "" {
			title = dd.File + " — " + title
		}
		data := pageData{Title: title, Repo: repo, Diff: dd, DiffSplit: dd.Split}
		if dd.Branch {
			if out, oerr := invoke(req.Context(), r, "checkin.get", url.Values{
				"repo": {repo}, "hash": {dd.To}, "files": {"0"}}); oerr == nil {
				var cd checkinDetail
				remarshal(out, &cd)
				data.DiffBranch = cd.Branch
				data.Title = "branch diff " + cd.Branch
			}
		}
		render(r, w, req, diffPage, data)
	})
	// The next window of a diff, for the sentinel at the end of the
	// last one: the same sections the page renders, replacing the
	// sentinel, followed by a fresh sentinel (or none, at the end).
	// The change as a patch. Fossil offers the same thing from its
	// check-in page, and it is what a reader wanting to apply the
	// change actually needs — the tarball beside it is the WHOLE tree,
	// megabytes for a four-line edit. Costs nothing new: the unified
	// text is the diff op's own output, asked for here and nowhere
	// else, which is why it is opt-in.
	mux.HandleFunc("GET /r/{repo}/checkin/{hash}/manifest", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		out, err := invoke(req.Context(), r, "checkin.manifest",
			url.Values{"repo": {repo}, "hash": {req.PathValue("hash")}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var md manifestDetail
		remarshal(out, &md)
		render(r, w, req, manifestPage, pageData{
			Title: "manifest · " + md.Hash[:12], Repo: repo, Manifest: md})
	})
	mux.HandleFunc("GET /r/{repo}/checkin/{hash}/tags", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		out, err := invoke(req.Context(), r, "checkin.tags",
			url.Values{"repo": {repo}, "hash": {req.PathValue("hash")}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var ct checkinTagsDetail
		remarshal(out, &ct)
		render(r, w, req, checkinTagsPage, pageData{
			Title: "tags · " + ct.Hash[:12], Repo: repo, CheckinTags: ct})
	})
	mux.HandleFunc("GET /r/{repo}/checkin/{hash}/patch", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		pv := url.Values{
			"repo": {repo}, "hash": {req.PathValue("hash")}, "unified": {"1"},
			// The patch is the whole change or it is not a patch: no
			// window, and no per-file narrowing.
			"maxLines": {"0"}}
		if b := req.URL.Query().Get("branch"); b != "" {
			pv.Set("branch", b)
		}
		out, err := invoke(req.Context(), r, "checkin.diff", pv)
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var dd struct {
			To      string `json:"to"`
			Unified string `json:"unified"`
		}
		remarshal(out, &dd)
		name := dd.To
		if len(name) > 12 {
			name = name[:12]
		}
		w.Header().Set("Content-Type", "text/x-patch; charset=utf-8")
		w.Header().Set("Content-Disposition", `attachment; filename="`+name+`.patch"`)
		w.Header().Set("X-Content-Type-Options", "nosniff")
		io.WriteString(w, dd.Unified)
	})
	mux.HandleFunc("GET /r/{repo}/checkin/{hash}/diff.frag", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		dd, err := diffWindow(r, req, repo, req.PathValue("hash"))
		if err != nil {
			fail(r, w, req, err)
			return
		}
		// whole=1 swaps the ENTIRE diff body, which is how the
		// unified/side-by-side toggle works without a reload: the two
		// views differ in every row, not in what follows the window.
		// Without it this returns the next window only, appended to
		// what is already on screen.
		tmpl, target := "diff-more", "#diff-more"
		if req.URL.Query().Get("whole") != "" {
			tmpl, target = "diff-body", "#diffbody"
		}
		var buf strings.Builder
		if err := diffPage.ExecuteTemplate(&buf, tmpl, pageData{Repo: repo, Diff: dd, DiffSplit: dd.Split}); err != nil {
			http.Error(w, "diff render failed", http.StatusInternalServerError)
			return
		}
		w.Header().Set("Content-Type", "text/event-stream")
		w.Header().Set("Cache-Control", "no-store")
		fmt.Fprintf(w, "event: datastar-patch-elements\ndata: mode replace\ndata: selector %s\n", target)
		for _, line := range strings.Split(buf.String(), "\n") {
			fmt.Fprintf(w, "data: elements %s\n", line)
		}
		fmt.Fprint(w, "\n")
	})
	// Archive download. Same posture as an attachment: a download, never
	// an inline render, with the stored content type discarded — a
	// tarball is bytes a reader saves, not a document a browser should
	// try to interpret.
	mux.HandleFunc("GET /r/{repo}/archive/{version}", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		format := req.URL.Query().Get("format")
		out, err := invoke(req.Context(), r, "archive.get", url.Values{
			"repo": {repo}, "version": {req.PathValue("version")}, "format": {format},
		})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var ad struct {
			Name    string `json:"name"`
			Version string `json:"version"`
			Content string `json:"content"`
		}
		remarshal(out, &ad)
		raw, err := base64.StdEncoding.DecodeString(ad.Content)
		if err != nil {
			fail(r, w, req, err)
			return
		}
		ctype := "application/gzip"
		if strings.HasSuffix(ad.Name, ".zip") {
			ctype = "application/zip"
		}
		// The archive is a pure function of a resolved check-in and zit
		// guarantees the bytes are reproducible, so this entity can
		// never change and the ETag is the check-in itself. A reader who
		// already has it gets a 304 and downloads nothing — which is
		// worth more than any server-side cache, because the bytes never
		// leave the machine at all.
		etag := `"` + ad.Version + "-" + format + `"`
		w.Header().Set("ETag", etag)
		w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
		if match := req.Header.Get("If-None-Match"); match == etag {
			w.WriteHeader(http.StatusNotModified)
			return
		}
		w.Header().Set("Content-Type", ctype)
		w.Header().Set("X-Content-Type-Options", "nosniff")
		w.Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+url.PathEscape(ad.Name))
		w.Header().Set("Content-Length", strconv.Itoa(len(raw)))
		w.Write(raw)
	})
	// Attachment download. This is the only route that hands a reader
	// bytes somebody else uploaded, so it is deliberately hostile to its
	// own payload: always a download, never an inline render; the stored
	// content type is discarded in favour of octet-stream; nosniff stops
	// the browser guessing its way back to HTML; and the CSP denies
	// everything in case a viewer renders it anyway.
	mux.HandleFunc("GET /r/{repo}/attachment/{hash}", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		out, err := invoke(req.Context(), r, "attachment.get", url.Values{
			"repo": {repo}, "hash": {req.PathValue("hash")},
		})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var ad struct {
			Name    string `json:"name"`
			Content string `json:"content"`
		}
		remarshal(out, &ad)
		raw, err := base64.StdEncoding.DecodeString(ad.Content)
		if err != nil {
			fail(r, w, req, err)
			return
		}
		w.Header().Set("Content-Type", "application/octet-stream")
		w.Header().Set("X-Content-Type-Options", "nosniff")
		w.Header().Set("Content-Security-Policy", "default-src 'none'; sandbox")
		w.Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+url.PathEscape(ad.Name))
		w.Header().Set("Content-Length", strconv.Itoa(len(raw)))
		w.Write(raw)
	})
	mux.HandleFunc("GET /r/{repo}/doc/{hash}/{path...}", func(w http.ResponseWriter, req *http.Request) {
		repo, path := req.PathValue("repo"), req.PathValue("path")
		out, err := invoke(req.Context(), r, "doc.get", url.Values{
			"repo": {repo}, "hash": {req.PathValue("hash")}, "path": {path},
		})
		if err != nil {
			// Not a document is not an error a reader needs explaining:
			// the file exists, it simply has no rendered form, and the
			// source view is what they wanted.
			if errors.Is(err, ops.ErrNotFound) {
				// A directory with no index belongs in the TREE view; a
				// file with no rendered form belongs in the source view.
				// Sending a directory to /file/ was a 404 with a real
				// page behind it, which is the worst kind.
				where := "/file/"
				if strings.HasSuffix(path, "/") {
					where = "/tree/"
					path = strings.TrimSuffix(path, "/")
				}
				http.Redirect(w, req, "/r/"+url.PathEscape(repo)+where+
					url.PathEscape(req.PathValue("hash"))+"/"+path, http.StatusSeeOther)
				return
			}
			fail(r, w, req, err)
			return
		}
		var dd docDetail
		remarshal(out, &dd)
		if dd.ContentType != "" {
			// An image referenced from a document. Served under the doc
			// route because that is the URL the markup points at, and
			// nosniff so a mislabelled file cannot be talked into
			// becoming something executable.
			raw, derr := base64.StdEncoding.DecodeString(dd.Content)
			if derr != nil {
				fail(r, w, req, derr)
				return
			}
			w.Header().Set("Content-Type", dd.ContentType)
			w.Header().Set("X-Content-Type-Options", "nosniff")
			w.Header().Set("Cache-Control", "public, max-age=86400")
			w.Header().Set("Content-Length", strconv.Itoa(len(raw)))
			w.Write(raw)
			return
		}
		render(r, w, req, docPage, pageData{
			Title: dd.Path, Repo: repo, Doc: dd,
			WikiHTML: template.HTML(dd.HTML),
			WikiTOC:  wikiContents(dd.Outline),
		})
	})
	mux.HandleFunc("GET /r/{repo}/file/{hash}/{path...}", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		out, err := invoke(req.Context(), r, "file.get", url.Values{
			"repo": {repo},
			"hash": {req.PathValue("hash")},
			"path": {req.PathValue("path")},
		})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var fd fileDetail
		remarshal(out, &fd)
		render(r, w, req, filePage, pageData{
			Title: fd.Path, Repo: repo, File: fd, FileHTML: template.HTML(fd.HTML),
			// The two views are the same file; each says so.
			DocPath: fd.Renderable,
		})
	})
	// The /info dispatch, as fossil has it: a bare artifact prefix
	// resolves to whatever kind of page owns it. Comment bracket links
	// land here, because "[4bd630]" in a real comment is as often a
	// ticket as a check-in.
	mux.HandleFunc("GET /r/{repo}/info/{prefix}", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		out, err := invoke(req.Context(), r, "artifact.resolve",
			url.Values{"repo": {repo}, "prefix": {req.PathValue("prefix")}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var res struct{ Kind, Ref string }
		remarshal(out, &res)
		page := ""
		switch res.Kind {
		case "ci":
			page = "/checkin/" + url.PathEscape(res.Ref)
		case "t":
			page = "/ticket/" + url.PathEscape(res.Ref)
		case "w":
			page = "/wiki/" + url.PathEscape(res.Ref)
		case "e":
			page = "/technote/" + url.PathEscape(res.Ref)
		case "f":
			page = "/forum/" + url.PathEscape(res.Ref)
		default:
			fail(r, w, req, ops.ErrNotFound)
			return
		}
		http.Redirect(w, req, "/r/"+url.PathEscape(repo)+page, http.StatusFound)
	})
	mux.HandleFunc("GET /r/{repo}/checkin/{hash}", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		out, err := invoke(req.Context(), r, "checkin.get",
			url.Values{"repo": {repo}, "hash": {req.PathValue("hash")}, "files": {"0"}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var cd checkinDetail
		remarshal(out, &cd)
		// The message IS the page's name — fossil's /info leads with the
		// comment, and a reader recognises "fix shift key firing twice"
		// where they will never recognise twelve hex digits.
		first, body, _ := strings.Cut(strings.TrimSpace(cd.Comment), "\n")
		title := commentText(first)
		if title == "" {
			title = "check-in " + cd.Hash[:12]
		}
		data := pageData{Title: title, HideH1: true, Repo: repo, Checkin: cd,
			CheckinLead: commentHTML(repo, first),
			CheckinBody: commentHTML(repo, strings.TrimSpace(body)),
			// 100 characters covers 90% of first lines in the ingested
			// corpus; past it this is a paragraph, and a paragraph in
			// bold display type is a wall.
			CheckinLongLead: len([]rune(title)) > 100,
			CIBadge:         ciBadge(cd.CI),
			DiffSplit:       req.URL.Query().Get("view") == "split"}
		data.ChatRefs = chatRefsOf(out)
		if dd, derr := diffWindow(r, req, repo, req.PathValue("hash")); derr == nil {
			data.Diff, data.DiffSplit = dd, dd.Split
		}
		data.BranchDiff = cd.Fork != ""
		data.Context = contextRail(repo, cd.Hash, cd.Context)
		if note, ok := associatedNote(r, req, repo, "checkin/"+cd.Hash); ok {
			data.Note, data.NoteName, data.NoteKind = noteFor(note)
		}
		render(r, w, req, checkinPage, data)
	})
	mux.HandleFunc("GET /r/{repo}/wiki/{name}", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		rev := req.URL.Query().Get("rev")
		out, err := invoke(req.Context(), r, "wiki.get",
			url.Values{"repo": {repo}, "name": {req.PathValue("name")}, "rev": {rev}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var wd wikiDetail
		remarshal(out, &wd)
		data := pageData{
			Title: wd.Title, Repo: repo, Wiki: wd, WikiRev: rev,
			WikiHTML: template.HTML(wd.HTML),
			WikiTOC:  wikiContents(wd.Outline),
		}
		// The sibling rail. A second op call per page view, the same
		// shape as the ticket page reading its vocabulary: a failure
		// here costs the rail, never the page a reader asked for.
		if list, lerr := invoke(req.Context(), r, "wiki.list",
			url.Values{"repo": {repo}}); lerr == nil {
			var wl struct {
				Pages []wikiTitle `json:"pages"`
			}
			remarshal(list, &wl)
			data.Served = len(wl.Pages)
			if len(wl.Pages) > wikiRailLimit {
				// Keep the page being read in the rail whatever the cut
				// would otherwise do, so the rail always says where you
				// are — that is most of what it is for.
				kept := wl.Pages[:wikiRailLimit]
				here := false
				for _, p := range kept {
					if p.Title == wd.Title {
						here = true
					}
				}
				if !here {
					for _, p := range wl.Pages {
						if p.Title == wd.Title {
							kept = append(kept[:wikiRailLimit-1:wikiRailLimit-1], p)
							break
						}
					}
				}
				wl.Pages, data.Truncated = kept, true
			}
			data.WikiPages = wl.Pages
		}
		render(r, w, req, wikiPage, data)
	})
	mux.HandleFunc("GET /r/{repo}/wiki/{name}/edit", func(w http.ResponseWriter, req *http.Request) {
		repo, name := req.PathValue("repo"), req.PathValue("name")
		if !mirrorGate(r, w, req, repo) {
			return
		}
		if _, ok := gate(verify, sessions, repo, w, req); !ok {
			return
		}
		source := ""
		if out, err := invoke(req.Context(), r, "wiki.get",
			url.Values{"repo": {repo}, "name": {name}}); err == nil {
			var wd struct {
				Source string `json:"source"`
			}
			remarshal(out, &wd)
			source = wd.Source
		}
		render(r, w, req, wikiEditPage, pageData{
			Title: "edit " + name, Repo: repo,
			Wiki: wikiDetail{Title: name}, EditSource: source,
		})
	})
	mux.HandleFunc("POST /r/{repo}/wiki/{name}/edit", func(w http.ResponseWriter, req *http.Request) {
		repo, name := req.PathValue("repo"), req.PathValue("name")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "kf", ops.Token, w, req)
		if !ok {
			return
		}
		if _, err := invoke(req.Context(), r, "wiki.save", url.Values{
			"repo": {repo}, "name": {name},
			"body": {req.FormValue("body")},
		}); err != nil {
			fail(r, w, req, err)
			return
		}
		http.Redirect(w, req, "/r/"+repo+"/wiki/"+url.PathEscape(name), http.StatusSeeOther)
	})
	mux.HandleFunc("GET /r/{repo}/wiki-new", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		if !mirrorGate(r, w, req, repo) {
			return
		}
		name := req.URL.Query().Get("name")
		if name == "" {
			http.Redirect(w, req, "/r/"+repo+"/wiki", http.StatusSeeOther)
			return
		}
		http.Redirect(w, req, "/r/"+repo+"/wiki/"+url.PathEscape(name)+"/edit", http.StatusSeeOther)
	})
	mux.HandleFunc("GET /r/{repo}/ticket/new", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		if !mirrorGate(r, w, req, repo) {
			return
		}
		if _, ok := gate(verify, sessions, repo, w, req); !ok {
			return
		}
		q := req.URL.Query()
		render(r, w, req, ticketNewPage, pageData{Title: "new ticket", Repo: repo,
			Vocab: ticketVocabFor(r, req, repo),
			Prefill: ticketPrefill{Title: q.Get("title"), Comment: q.Get("comment"),
				Type: q.Get("type"), Severity: q.Get("severity"),
				Priority: q.Get("priority"), Subsystem: q.Get("subsystem"),
				FoundIn: q.Get("foundin")}})
	})
	mux.HandleFunc("POST /r/{repo}/ticket/new", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "n", ops.Token, w, req)
		if !ok {
			return
		}
		// Every field the form offers, not three of them. The form has
		// always rendered type, severity, priority and subsystem and
		// this handler dropped them on the floor: a control that
		// accepts what you type and discards it is worse than one that
		// is not there, because the reader believes they filed it.
		vals := url.Values{"repo": {repo}}
		for _, f := range []string{"title", "status", "comment",
			"type", "severity", "priority", "subsystem", "foundin"} {
			if v := strings.TrimSpace(req.FormValue(f)); v != "" {
				vals.Set(f, v)
			}
		}
		out, err := invoke(req.Context(), r, "ticket.new", vals)
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var tn struct {
			ID string `json:"id"`
		}
		remarshal(out, &tn)
		http.Redirect(w, req, "/r/"+repo+"/ticket/"+tn.ID, http.StatusSeeOther)
	})
	mux.HandleFunc("GET /r/{repo}/ticket/{id}/edit", func(w http.ResponseWriter, req *http.Request) {
		repo, id := req.PathValue("repo"), req.PathValue("id")
		if !mirrorGate(r, w, req, repo) {
			return
		}
		if _, ok := gate(verify, sessions, repo, w, req); !ok {
			return
		}
		out, err := invoke(req.Context(), r, "ticket.get",
			url.Values{"repo": {repo}, "id": {id}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var tg struct {
			Ticket ticketDetail `json:"ticket"`
		}
		remarshal(out, &tg)
		render(r, w, req, ticketEditPage, pageData{
			Title: "edit ticket", Repo: repo, Ticket: tg.Ticket,
			Vocab: ticketVocabFor(r, req, repo),
		})
	})
	mux.HandleFunc("POST /r/{repo}/ticket/{id}/edit", func(w http.ResponseWriter, req *http.Request) {
		repo, id := req.PathValue("repo"), req.PathValue("id")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "cw", ops.Token, w, req)
		if !ok {
			return
		}
		// Only what moved is written. The sidebar posts every field on
		// each change; sending them all would record a J card per field
		// per save, and the timeline would read "changed status Open →
		// Open, priority High → High" after every click.
		out, err := invoke(req.Context(), r, "ticket.get", url.Values{"repo": {repo}, "id": {id}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var tg struct {
			Ticket ticketDetail `json:"ticket"`
		}
		remarshal(out, &tg)
		vals := url.Values{"repo": {repo}, "id": {id}}
		if c := strings.TrimSpace(req.FormValue("comment")); c != "" {
			vals.Set("comment", c)
		}
		for _, f := range []string{"title", "status", "resolution", "type", "severity", "priority", "subsystem", "foundin"} {
			if _, sent := req.Form[f]; !sent {
				continue
			}
			if v := req.FormValue(f); v != "" && v != tg.Ticket.Field(f) {
				vals.Set(f, v)
			}
		}
		if v := req.FormValue("description"); v != "" && v != tg.Ticket.Description {
			vals.Set("description", v)
		}
		if len(vals) > 2 {
			if _, err := invoke(req.Context(), r, "ticket.set", vals); err != nil {
				fail(r, w, req, err)
				return
			}
		}
		if req.Header.Get("Datastar-Request") == "" {
			http.Redirect(w, req, "/r/"+repo+"/ticket/"+id, http.StatusSeeOther)
			return
		}
		// Script saved a select: patch the sidebar and the timeline.
		out, err = invoke(req.Context(), r, "ticket.get", url.Values{"repo": {repo}, "id": {id}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var td struct {
			Ticket   ticketDetail    `json:"ticket"`
			Comments []ticketComment `json:"comments"`
		}
		remarshal(out, &td)
		td.Ticket.ShowPrivate = maySeePrivate(capsPlane, verify, sessions, repo, req)
		vocab := ticketVocabFor(r, req, repo)
		data := pageData{Repo: repo, Ticket: td.Ticket, CanWrite: true,
			Timeline: ticketTimeline(td.Ticket, td.Comments), TicketFields: ticketControls(td.Ticket, vocab), Vocab: vocab}
		w.Header().Set("Content-Type", "text/event-stream")
		for _, part := range []struct{ sel, tpl string }{{"#tkt-timeline", "tkt-timeline"}, {"#tkt-side", "tkt-side"}} {
			var buf bytes.Buffer
			if err := ticketPage.ExecuteTemplate(&buf, part.tpl, data); err != nil {
				http.Error(w, "ticket render failed", http.StatusInternalServerError)
				return
			}
			fmt.Fprint(w, "event: datastar-patch-elements\n")
			fmt.Fprintf(w, "data: selector %s\n", part.sel)
			fmt.Fprint(w, "data: mode inner\n")
			for _, line := range strings.Split(buf.String(), "\n") {
				fmt.Fprintf(w, "data: elements %s\n", line)
			}
			fmt.Fprint(w, "\n")
		}
	})
	// POST .../move is the board's write: one field, one value, and a
	// repainted board in reply. The per-card select posts to /edit and
	// gets a redirect; this exists because a fetch cannot follow one.
	//
	// The field is checked against the board's own axes. Without that
	// check the query string would choose which ticket column to write,
	// which is a different feature than "move a card".
	mux.HandleFunc("POST /r/{repo}/ticket/{id}/move", func(w http.ResponseWriter, req *http.Request) {
		repo, id := req.PathValue("repo"), req.PathValue("id")
		req, ok := gateCap(capsPlane, verify, sessions, repo, "w", ops.Token, w, req)
		if !ok {
			return
		}
		q := req.URL.Query()
		field, to := q.Get("field"), q.Get("to")
		if !boardAxis(field) {
			http.Error(w, "not a board field", http.StatusBadRequest)
			return
		}
		// The blank lane is a rendering of absence, not a value to write.
		if to == unsetLane {
			to = ""
		}
		// Where it came from, for the status line and its undo.
		move := boardMove{ID: id, Field: field, To: to}
		if tg, err := invoke(req.Context(), r, "ticket.get", url.Values{"repo": {repo}, "id": {id}}); err == nil {
			var cur struct {
				Ticket struct {
					Fields []struct {
						Name, Value string
					} `json:"fields"`
				} `json:"ticket"`
			}
			remarshal(tg, &cur)
			for _, f := range cur.Ticket.Fields {
				switch {
				case strings.EqualFold(f.Name, field):
					move.From = f.Value
				case strings.EqualFold(f.Name, "title"):
					move.Title = f.Value
				}
			}
		}
		if _, err := invoke(req.Context(), r, "ticket.set", url.Values{
			"repo": {repo}, "id": {id}, field: {to},
		}); err != nil {
			fail(r, w, req, err)
			return
		}
		// A plain form post (the Move menu with scripting off, or undo)
		// lands back on the board; Datastar gets the fragment.
		if req.Header.Get("Datastar-Request") == "" {
			back := url.Values{"view": {"board"}, "group": {q.Get("group")}, "lane": {q.Get("lane")},
				"moved": {id}, "to": {to}, "from": {move.From}}
			if s := ticketState(q); s != "" {
				back.Set("state", s)
			}
			for k, vs := range ticketReport(q) {
				back[k] = vs
			}
			if t := strings.TrimSpace(q.Get("title")); t != "" {
				back.Set("title", t)
			}
			http.Redirect(w, req, "/r/"+repo+"/ticket?"+back.Encode(), http.StatusSeeOther)
			return
		}
		data, err := boardData(r, req, ticketNav{Repo: repo, State: ticketState(q),
			Title: strings.TrimSpace(q.Get("title")), Report: ticketReport(q),
			View: "board", Group: q.Get("group"), Lane: q.Get("lane")})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		data.CanWrite = true
		data.Moved = &move
		var buf bytes.Buffer
		if err := ticketBoardPage.ExecuteTemplate(&buf, "board-body", data); err != nil {
			http.Error(w, "board render failed", http.StatusInternalServerError)
			return
		}
		w.Header().Set("Content-Type", "text/event-stream")
		fmt.Fprint(w, "event: datastar-patch-elements\n")
		fmt.Fprint(w, "data: selector #board\n")
		fmt.Fprint(w, "data: mode inner\n")
		for _, line := range strings.Split(buf.String(), "\n") {
			fmt.Fprintf(w, "data: elements %s\n", line)
		}
		fmt.Fprint(w, "\n")
	})
	mux.HandleFunc("GET /r/{repo}/wiki/{name}/history", func(w http.ResponseWriter, req *http.Request) {
		repo := req.PathValue("repo")
		name := req.PathValue("name")
		out, err := invoke(req.Context(), r, "wiki.history",
			url.Values{"repo": {repo}, "name": {name}})
		if err != nil {
			fail(r, w, req, err)
			return
		}
		var wh struct {
			Title string    `json:"title"`
			Edits []wikiRev `json:"edits"`
		}
		remarshal(out, &wh)
		render(r, w, req, wikiHistoryPage, pageData{
			Title: wh.Title + " history", Repo: repo,
			Wiki: wikiDetail{Title: wh.Title}, WikiRevs: wh.Edits,
		})
	})
	// Identity is resolved ONCE per request and carried in the context,
	// so every page header can show who is signed in without each route
	// knowing about the session plane.
	return recovered(withTimer(mux, withIdentity(sessions, inbox != nil || sessions != nil, o.attnEverywhere,
		func(repo string, req *http.Request) ops.Caps {
			c, ok := capsOf(capsPlane, sessions, verify, repo, req)
			if !ok {
				return nil
			}
			return c
		}, mux)))
}

// liveChat streams chat messages as Datastar patches into #chatlog,
// resumable by Last-Event-ID (RFC 0011 §2): an ordinary "msg" (or
// "robot") appends a new row via chatMsgHTML — the same renderer the
// page's initial listing used, so a live-arrived message looks
// identical to one that was already there — while an edit or delete
// REPLACES the row it targets in place, folding the tombstone into the
// view exactly as History already does server-side for the initial
// page. Every event carries `id: <seq>`, so a client that reconnects
// resends its own cursor and nothing is missed (Datastar's fetch.ts
// resends last-event-id on retry). Without JS the page still shows the
// on-load window and posts via the plain form (Principle 3).
func liveChatAs(live ChatLive, repo, viewer string, canDeleteAny bool, render func(string) string, w http.ResponseWriter, req *http.Request) {
	fl, ok := w.(http.Flusher)
	if !ok {
		http.Error(w, "streaming unsupported", http.StatusInternalServerError)
		return
	}
	var from uint64
	if leid := req.Header.Get("Last-Event-ID"); leid != "" {
		from, _ = strconv.ParseUint(leid, 10, 64)
	}
	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-store")
	w.WriteHeader(http.StatusOK)
	fmt.Fprint(w, ": live\n\n")
	fl.Flush()

	msgs, cancel := live.Tail(repo, from)
	defer cancel()
	// The last row this connection appended, for grouping the next one,
	// and the rows it has seen, for quoting an inline reference to one.
	// Bounded: a connection left open for a day must not hold the day.
	var last ChatMessage
	recent := map[uint64]ChatMessage{}
	var order []uint64
	heartbeat := time.NewTicker(20 * time.Second)
	defer heartbeat.Stop()
	for {
		select {
		case <-req.Context().Done():
			return
		case <-heartbeat.C:
			fmt.Fprint(w, ": ping\n\n")
			fl.Flush()
		case m, open := <-msgs:
			if !open {
				return
			}
			if m.Kind == "gap" {
				// The resume point is older than the window, so the
				// replay that follows is the whole channel, not a
				// continuation of what this page already shows.
				// Appending it would leave the reader with two copies
				// of every row, so the list is replaced with an empty
				// one and the replay re-renders it: a full re-render,
				// expressed as one outer patch plus the appends that
				// were coming anyway. No id: line — a gap is not a
				// resume point.
				fmt.Fprint(w, "event: datastar-patch-elements\n")
				fmt.Fprint(w, "data: mode outer\n")
				fmt.Fprint(w, "data: selector #chatlog\n")
				fmt.Fprint(w, `data: elements <ol id="chatlog" class="chatlog"></ol>`+"\n\n")
				fl.Flush()
				last = ChatMessage{}
				recent, order = map[uint64]ChatMessage{}, nil
				continue
			}
			// One renderer for both paths: a ChatLive that carries no
			// markup pipeline (main.go's adapter, over raw chat.Tail)
			// gets its markdown rendered here through the same op the
			// page's own rows went through, so a live line and a
			// reloaded one are the same HTML.
			if m.HTML == "" && m.Text != "" && render != nil {
				m.HTML = template.HTML(render(m.Text))
			}
			// The same grouping the page did, continued across the
			// stream: this connection knows what it appended last, so a
			// run that arrives live reads like one that was reloaded.
			// The first live row after a page load always gets a
			// header — the stream did not draw what is above it.
			if m.Kind == "msg" {
				m.Grouped = chatGrouped(last, m)
			}
			// Every APPENDED row is what the next one is grouped
			// against — a robot line between two of an author's
			// messages breaks the run on this path exactly as it does
			// on the page's, or a live header goes missing.
			if m.Kind != "edit" && m.Kind != "del" {
				last = m
				if m.Kind == "msg" && !m.Deleted {
					if _, dup := recent[m.Seq]; !dup {
						recent[m.Seq] = m
						order = append(order, m.Seq)
						if len(order) > chatLiveQuoteWindow {
							delete(recent, order[0])
							order = order[1:]
						}
					}
				}
				m.RefQuotes = chatQuotesFor(m, recent)
			}
			fmt.Fprintf(w, "id: %d\n", m.Seq)
			fmt.Fprint(w, "event: datastar-patch-elements\n")
			var el template.HTML
			if m.Kind == "edit" || m.Kind == "del" {
				// Replace the ORIGINAL row's body alone. The header —
				// identicon, author, time, permalink — belongs to the
				// message, not to the tombstone that arrived about it,
				// and a tombstone's author is routinely someone else
				// (a moderator deleting another account's message).
				fmt.Fprint(w, "data: mode replace\n")
				fmt.Fprintf(w, "data: selector #chatbody-%d\n", m.Ref)
				replaced := m
				replaced.Seq, replaced.Kind = m.Ref, "msg"
				if m.Kind == "edit" {
					// An edit is own-message-only (chat.edit refuses
					// otherwise), so the tombstone's author IS the
					// row's for the purpose of drawing controls.
					replaced.Text, replaced.HTML, replaced.Edited = m.Text, m.HTML, true
				} else {
					replaced.Text, replaced.HTML, replaced.Deleted = "", "", true
				}
				el = chatBodyHTML(replaced, repo, viewer, canDeleteAny)
			} else {
				fmt.Fprint(w, "data: mode append\n")
				fmt.Fprint(w, "data: selector #chatlog\n")
				el = template.HTML("<li>" + string(chatMsgHTML(m, repo, viewer, canDeleteAny)) + "</li>")
			}
			fmt.Fprintf(w, "data: elements %s\n\n", el)
			fl.Flush()
		}
	}
}

// chatLiveQuoteWindow is how many of a connection's own rows stay
// available to quote an inline reference from. A quote is only ever
// drawn from a message the reader can also see, and beyond a screenful
// or two of scrollback that stops being true anyway.
const chatLiveQuoteWindow = 200

// timelineRevStream is the timeline's live signal. Like the fleet's, it
// says THAT the repository changed and never what it looks like.
//
// The old stream carried rendered rows, so it also carried the filter
// it was opened with. That is not a bug that gets fixed once: a stream
// holds a connection, the filter it captured ages, and every later tick
// repaints the reader's page with a view they left. It shipped, was
// fixed, and came back the moment a default moved — because the shape
// makes it possible.
//
// A revision number cannot be stale by construction. The client
// re-requests the listing itself and sends its own filter with it, so
// what it gets back is always what it asked for.
func timelineRevStream(n Notifier, w http.ResponseWriter, req *http.Request) {
	fl, ok := w.(http.Flusher)
	if !ok {
		http.Error(w, "streaming unsupported", http.StatusInternalServerError)
		return
	}
	repo := req.PathValue("repo")
	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-store")
	fmt.Fprint(w, ": live\n\n")
	fl.Flush()

	ticks, cancel := n.Watch(repo)
	defer cancel()
	heartbeat := time.NewTicker(20 * time.Second)
	defer heartbeat.Stop()
	rev := 0
	for {
		select {
		case <-req.Context().Done():
			return
		case <-heartbeat.C:
			fmt.Fprint(w, ": ping\n\n")
			fl.Flush()
		case _, open := <-ticks:
			if !open {
				return
			}
			rev++
			fmt.Fprint(w, "event: datastar-patch-signals\n")
			fmt.Fprintf(w, "data: signals {tlRev: %d}\n\n", rev)
			fl.Flush()
		}
	}
}

// timelineFrag renders #tl ONCE, with whatever filter the request
// carries, and closes. Datastar's form content type serializes the
// controls onto the GET, so the scripted refresh and the no-script
// submit send the same parameters — and a one-shot response holds no
// connection that could go stale.
func timelineFrag(r *ops.Registry, w http.ResponseWriter, req *http.Request) {
	frag, err := timelineFragment(r, req.PathValue("repo"), req.URL.Query())
	if err != nil {
		http.Error(w, "timeline render failed", http.StatusInternalServerError)
		return
	}
	markOneShot(w)
	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-store")
	fmt.Fprint(w, "event: datastar-patch-elements\n")
	for _, line := range strings.Split(frag, "\n") {
		fmt.Fprintf(w, "data: elements %s\n", line)
	}
	fmt.Fprint(w, "\n")
}

// fleetRevStream is the landing page's live signal: it says THAT the
// fleet changed, never WHAT it looks like. The old stream carried
// rendered rows, so it also carried the filter it was opened with —
// opened at load that filter was empty, and a few seconds after the
// reader typed, the background repaint replaced their filtered rows
// with everything (and Datastar's retry resurrected the stale stream
// after any attempt to cancel it). A revision number cannot be stale
// by construction: the client re-requests the listing itself, sending
// whatever its form says NOW.
func fleetRevStream(r *ops.Registry, n Notifier, w http.ResponseWriter, req *http.Request) {
	fl, ok := w.(http.Flusher)
	if !ok {
		http.Error(w, "streaming unsupported", http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-store")
	fmt.Fprint(w, ": live\n\n")
	fl.Flush()

	ticks, cancel := n.Watch("*")
	defer cancel()
	// The indexing badge clears AFTER a store's last event, so ticks
	// alone would leave it stuck until the next unrelated change. The
	// poll watches a cheap fingerprint — which repositories are still
	// indexing — and bumps only when it changes; an idle fleet costs
	// one op invoke per poll and sends nothing.
	poll := time.NewTicker(2 * time.Second)
	defer poll.Stop()
	heartbeat := time.NewTicker(20 * time.Second)
	defer heartbeat.Stop()

	rev := 0
	bump := func() {
		rev++
		fmt.Fprint(w, "event: datastar-patch-signals\n")
		fmt.Fprintf(w, "data: signals {fleetRev: %d}\n\n", rev)
		fl.Flush()
	}
	fingerprint := func() string {
		out, err := invoke(req.Context(), r, "repo.list", url.Values{})
		if err != nil {
			return ""
		}
		var fl2 struct {
			Repos []struct {
				Name     string `json:"name"`
				Indexing bool   `json:"indexing"`
			} `json:"repos"`
		}
		remarshal(out, &fl2)
		var b strings.Builder
		for _, rp := range fl2.Repos {
			if rp.Indexing {
				b.WriteString(rp.Name)
				b.WriteByte(' ')
			}
		}
		return b.String()
	}
	lastFP := fingerprint()
	for {
		select {
		case <-req.Context().Done():
			return
		case <-heartbeat.C:
			fmt.Fprint(w, ": ping\n\n")
			fl.Flush()
		case <-poll.C:
			if fp := fingerprint(); fp != lastFP {
				lastFP = fp
				bump()
			}
		case _, open := <-ticks:
			if !open {
				return
			}
			bump()
		}
	}
}

// fleetFrag renders the #fleet region ONCE, with whatever filter the
// request carries, and closes. Datastar's form content type serializes
// the surrounding form onto the GET, so the scripted refresh and the
// no-script submit send the same parameters — and a one-shot response
// holds no connection that could go stale.
func fleetFrag(r *ops.Registry, w http.ResponseWriter, req *http.Request) {
	view := url.Values{}
	for _, k := range []string{"q", "sort", "kind"} {
		if v := req.URL.Query().Get(k); v != "" {
			view.Set(k, v)
		}
	}
	admin := false
	if id, ok := req.Context().Value(ctxIdentity{}).(identity); ok {
		admin = id.isAdmin
	}
	frag, err := fleetFragment(r, view, admin)
	if err != nil {
		http.Error(w, "fleet render failed", http.StatusInternalServerError)
		return
	}
	markOneShot(w)
	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-store")
	fmt.Fprint(w, "event: datastar-patch-elements\n")
	for _, line := range strings.Split(frag, "\n") {
		fmt.Fprintf(w, "data: elements %s\n", line)
	}
	fmt.Fprint(w, "\n")
}

func streamPatches(n Notifier, repo string, w http.ResponseWriter, req *http.Request, fragment func() (string, error)) {
	fl, ok := w.(http.Flusher)
	if !ok {
		http.Error(w, "streaming unsupported", http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-store")
	fmt.Fprint(w, ": live\n\n")
	fl.Flush()

	ticks, cancel := n.Watch(repo)
	defer cancel()
	heartbeat := time.NewTicker(20 * time.Second)
	defer heartbeat.Stop()
	for {
		select {
		case <-req.Context().Done():
			return
		case <-heartbeat.C:
			fmt.Fprint(w, ": ping\n\n")
			fl.Flush()
		case _, open := <-ticks:
			if !open {
				return
			}
			// Debounce: a burst of artifacts is one repaint.
			time.Sleep(200 * time.Millisecond)
			select {
			case <-ticks:
			default:
			}
			frag, err := fragment()
			if err != nil {
				log.Printf("web: live %s: %v", repo, err)
				continue
			}
			// Datastar v1 element patch: morphs the fragment in place.
			fmt.Fprint(w, "event: datastar-patch-elements\n")
			for _, line := range strings.Split(frag, "\n") {
				fmt.Fprintf(w, "data: elements %s\n", line)
			}
			fmt.Fprint(w, "\n")
			fl.Flush()
		}
	}
}

// fleetFragment renders the #fleet body through repo.list — shared by
// the page render and the live patches.
// fleetFragment re-renders the morphed region. It must be given
// EVERYTHING the full page gave the same template: the first repaint
// arrives immediately on connect and replaces the server-rendered
// listing, so any field the fragment omits appears on load and then
// vanishes a moment later. That is what dropped "23 of 23" and the
// New repository link, and previously the filter and sort.
//
// admin is per-connection rather than global: the fragment decides
// whether to draw an admin-only control, so it has to be the identity
// of the reader this stream belongs to.
func fleetFragment(r *ops.Registry, view url.Values, admin bool) (string, error) {
	out, err := invoke(context.Background(), r, "repo.list", view)
	if err != nil {
		return "", err
	}
	var fl struct {
		Repos  []repoInfo `json:"repos"`
		Total  int        `json:"total"`
		Served int        `json:"served"`
	}
	remarshal(out, &fl)
	var buf bytes.Buffer
	buf.WriteString(`<div id="fleet">`)
	if err := fleetPage.ExecuteTemplate(&buf, "fleet-body", pageData{Fleet: fl.Repos,
		FleetTotal: fl.Total, Served: fl.Served, IsAdmin: admin,
		Query: view.Get("q"), Sort: view.Get("sort"), Kind: view.Get("kind")}); err != nil {
		return "", err
	}
	buf.WriteString(`</div>`)
	return buf.String(), nil
}

// timelineFragment renders the #tl body for the given query — shared by
// the page render and the live patches, so both always agree.
// timelineQuery resolves a raw timeline query into the values the
// timeline.list op wants, and the page size to show alongside them.
//
// Check-ins are the default view: a code timeline is what a reader
// comes for, and a busy wiki or tracker was drowning it. "everything"
// is one pill away and explicit in the URL (y=all). The Max control
// uses fossil's n= name where the op's field is limit.
//
// Both the page and the live stream resolve through here. When only
// the page knew the default, a reader sitting on the default timeline
// had an empty query string — so the stream it opened asked for no
// filter at all, and the first tick after a landing replaced their
// check-ins with everything.
func timelineQuery(q url.Values, repo string) (url.Values, int) {
	vals := url.Values{}
	for k, v := range q {
		vals[k] = v
	}
	vals.Set("repo", repo)
	if vals.Get("y") == "" {
		vals.Set("y", "ci")
	}
	limit := 50
	if n := vals.Get("n"); n != "" {
		vals.Set("limit", n)
		if v, err := strconv.Atoi(n); err == nil && v > 0 && v <= 200 {
			limit = v
		}
	}
	return vals, limit
}

func timelineFragment(r *ops.Registry, repo string, q url.Values) (string, error) {
	vals, limit := timelineQuery(q, repo)
	out, err := invoke(context.Background(), r, "timeline.list", vals)
	if err != nil {
		return "", err
	}
	var tl struct {
		Entries       []timelineEntry `json:"entries"`
		Next          string          `json:"next"`
		DefaultBranch string          `json:"defaultBranch"`
	}
	remarshal(out, &tl)
	data := pageData{
		Repo: repo, Days: buildTimeline(repo, tl.DefaultBranch, tl.Entries), Next: tl.Next,
		Branch: vals.Get("branch"), Y: vals.Get("y"), Limit: limit,
	}
	var buf bytes.Buffer
	buf.WriteString(`<div id="tl">`)
	if err := timelinePage.ExecuteTemplate(&buf, "tl-body", data); err != nil {
		return "", err
	}
	buf.WriteString(`</div>`)
	return buf.String(), nil
}

// render executes a page template with the version footer served by the
// meta.version op — every page reports it (0001 Principle 1).
func render(r *ops.Registry, w http.ResponseWriter, req *http.Request,
	page *template.Template, data pageData) {
	renderStatus(r, w, req, page, data, http.StatusOK)
}

func renderStatus(r *ops.Registry, w http.ResponseWriter, req *http.Request,
	page *template.Template, data pageData, status int) {
	if id, ok := req.Context().Value(ctxIdentity{}).(identity); ok {
		data.SignedIn, data.CanSignIn, data.HasInbox = id.user, id.canSignIn, id.hasInbox
		data.IsAdmin = id.isAdmin
		if id.user != "" && (id.attnEverywhere || data.Repo != "") {
			data.AttnAttr = attentionAttr
			data.AttnTitleAttr = attentionTitleAttr(data.Title)
		}
	}
	out, err := invoke(req.Context(), r, "meta.version", nil)
	if err != nil {
		http.Error(w, "version op failed", http.StatusInternalServerError)
		return
	}
	var v struct {
		Version string `json:"version"`
	}
	remarshal(out, &v)
	data.Version = v.Version
	if c, err := req.Cookie(themeCookie); err == nil && (c.Value == "light" || c.Value == "dark") {
		data.Theme = c.Value
	}
	data.NextTheme, data.ThemeIcon, data.ThemeName = themeState(data.Theme)
	// A card scraper fetches the image from another machine, so og:image
	// cannot be the site-relative path the favicon links use.
	data.Origin, data.Path = origin(req), req.URL.Path
	if start, ok := req.Context().Value(ctxStart{}).(time.Time); ok {
		data.Elapsed = timing.Format(time.Since(start))
	}
	// Read the breakdown LAST: the ops this page invoked have all run by
	// now, so the accumulator is complete.
	data.Breakdown = timing.From(req.Context()).Breakdown()
	// The nav belongs to the layout, not to any one handler, so its
	// counts and its current-section marker are filled in here rather
	// than in each of the thirty-odd places that render a repo page.
	// A counts failure is NOT fatal: the nav degrades to bare labels,
	// which is what it showed before counts existed.
	if data.Repo != "" {
		data.Section = sectionOf(req.URL.Path)
		// The repobar's active tab already names these pages; an h1
		// repeating the word underneath it is chrome saying the same
		// thing twice. The h1 goes sr-only (HideH1's mechanism), so the
		// page keeps its accessible name. Detail pages — a ticket's
		// title, a wiki page's name — keep their visible h1: those say
		// something the tab does not.
		if !data.HideH1 {
			switch data.Title {
			case map[string]string{
				"tree": "files", "timeline": "timeline", "ticket": "tickets",
				"wiki": "wiki", "forum": "forum", "technote": "technotes",
				"ci": "ci", "chat": "chat",
			}[data.Section]:
				data.HideH1 = data.Title != ""
			}
		}
		// Derived in the one place every page passes through, so a new page
		// gets a correctly scoped search box without knowing it exists. A
		// handler that already set a scope keeps it: the results page holds
		// the scope the reader is actually searching in, which is not the
		// one its own section would imply.
		if data.SearchScope == "" {
			data.SearchKind, data.SearchScope = searchContext(data.Section)
		}
		if co, err := invoke(req.Context(), r, "repo.counts",
			url.Values{"repo": {data.Repo}}); err == nil {
			remarshal(co, &data.Counts)
			data.HasCounts = true
		} else {
			log.Printf("web: counts for %s: %v", data.Repo, err)
		}
		if info, err := invoke(req.Context(), r, "repo.get", url.Values{"repo": {data.Repo}}); err == nil {
			remarshal(info, &data.Posture)
		}
		// The Chat nav badge (RFC 0011 §3). chat.unread answers every
		// readable repository at once — the shape Phase 2's inbox
		// rollup needs — so this reads one repo out of that rather than
		// adding a second, narrower op. Accepted for Phase 1: an O(repos)
		// query on every signed-in page view, the same trade-off already
		// made for mention resolution (register.go's mentionKnown).
		if data.SignedIn != "" {
			if u, err := invoke(ops.WithUser(req.Context(), data.SignedIn), r, "chat.unread", nil); err == nil {
				var uo chatUnreadView
				remarshal(u, &uo)
				if cr, ok := uo.Repos[data.Repo]; ok {
					data.ChatUnread, data.HasChatUnread = cr.Unread, true
				}
			}
		}
	}
	// Render to a buffer first: a template error mid-stream would
	// otherwise emit a silently truncated page (a bug class this exact
	// code once shipped) — buffered, it becomes a loud, logged 500.
	var buf bytes.Buffer
	if err := page.Execute(&buf, data); err != nil {
		log.Printf("web: template %s: %v", req.URL.Path, err)
		http.Error(w, "template error", http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	// A page had NO cache directive and no validator at all — not an
	// ETag, not a Last-Modified — which does not mean "do not cache", it
	// means the browser may pick a freshness lifetime for itself.
	// Safari does, and it served a timeline rendered before a deploy
	// while the server was answering with a different one: the reader
	// sees stale state and has no way to know.
	//
	// no-cache, not no-store: the copy may be kept and reused after
	// revalidation, which is what makes the back button instant. Only
	// reuse WITHOUT asking is wrong here, because every one of these
	// pages is a view of state that moves.
	w.Header().Set("Cache-Control", "no-cache")
	w.WriteHeader(status)
	w.Write(buf.Bytes())
}

// fail renders the themed error page for an op failure: not-found gets
// the 404 page, everything else logs and gets the 500 page — never
// Go's bare plain-text defaults (every page keeps theme, nav, version).
// fail renders an op error, mapping the op layer's error kinds the way
// the API router already does. Only ErrNotFound was mapped, so every
// other kind rendered as 500 — and a 500 tells a client the request
// failed, not that it should try again. Two paths depended on the
// distinction and lost it: a single-writer lease refusal (0001 §3),
// which is explicitly retryable, and a shed from a saturated work lane,
// which is retryable by construction.
func fail(r *ops.Registry, w http.ResponseWriter, req *http.Request, err error) {
	switch {
	case errors.Is(err, ops.ErrNotFound):
		data := pageData{Title: "not found", MissPath: req.URL.Path}
		// Keep the repo chrome when the repository itself is real — the
		// existence check is one op, paid only on the error path. When
		// the repo is what is missing (or private: indistinguishable by
		// design), the page falls back to the fleet-level frame.
		if repo := req.PathValue("repo"); repo != "" {
			if _, cerr := invoke(req.Context(), r, "repo.counts",
				url.Values{"repo": {repo}}); cerr == nil {
				data.Repo = repo
			}
		}
		renderStatus(r, w, req, notFoundPage, data, http.StatusNotFound)
	case errors.Is(err, ops.ErrInvalid):
		renderStatus(r, w, req, errorPage, pageData{Title: "bad request"}, http.StatusBadRequest)
	case errors.Is(err, ops.ErrForbidden):
		// The message is the content here: it says where the write
		// belongs, which is the one thing the reader needs next.
		renderStatus(r, w, req, forbiddenPage, pageData{Title: "not accepted here", Error: err.Error()}, http.StatusForbidden)
	case errors.Is(err, ops.ErrUnavailable):
		// Retry-After makes the refusal actionable rather than merely
		// polite: a client that backs off is what keeps a shed from
		// becoming a retry storm.
		w.Header().Set("Retry-After", "5")
		renderStatus(r, w, req, busyPage, pageData{Title: "busy"}, http.StatusServiceUnavailable)
	default:
		log.Printf("web: %s: %v", req.URL.Path, err)
		errlog.Default.ReportIn("web", req.URL.Path, req.PathValue("repo"), "", err)
		renderStatus(r, w, req, errorPage, pageData{Title: "error"}, http.StatusInternalServerError)
	}
}

// invoke runs an op through its descriptor with form-shaped input — the
// same decode path the API router uses, so HTML pages and API calls hit
// identical op semantics. Results come back as opaque values; pages pick
// the fields they render via remarshal.
func invoke(ctx context.Context, r *ops.Registry, name string, form url.Values) (any, error) {
	// The registry is the one seam every page's data crosses, so timing
	// it here covers index queries, OLTP reads and store calls in a
	// single place. It CONTAINS the zit total rather than excluding it;
	// the footer says so rather than adding the two.
	defer timing.Record(ctx, timing.Ops, time.Now())
	d, ok := r.Lookup(name)
	if !ok {
		return nil, fmt.Errorf("web: unknown op %q", name)
	}
	inPtr := d.NewIn()
	if err := ops.DecodeValues(form, inPtr); err != nil {
		return nil, err
	}
	in := reflect.ValueOf(inPtr).Elem().Interface()
	if err := ops.Validate(in); err != nil {
		return nil, err
	}
	return r.Invoke(ctx, name, in)
}

// remarshal projects an op result onto the fields a page renders — the
// JSON round-trip keeps web coupled to op output *shapes* (the API
// contract) rather than to concrete Go types in other packages.
func remarshal(from any, to any) {
	b, err := json.Marshal(from)
	if err == nil {
		json.Unmarshal(b, to)
	}
}

// opsSnapshot reads the operations op and words the window. One helper
// for the page and its live fragment, so the two cannot describe the
// forge differently.
func opsSnapshot(r *ops.Registry, req *http.Request) (opsView, error) {
	out, err := invoke(req.Context(), r, "ops.status",
		present(req.URL.Query(), "find", "sort"))
	if err != nil {
		return opsView{}, err
	}
	var v opsView
	remarshal(out, &v)
	v.Find, v.Sort = req.URL.Query().Get("find"), req.URL.Query().Get("sort")
	if v.Sort == "" {
		v.Sort = "p95"
	}
	v.Window = fmt.Sprintf("%d recent renders", len(v.Renders))
	return v, nil
}

// present copies the named query parameters, keeping only those the
// caller actually sent.
//
// An absent parameter and an empty one are different things to the
// validator: a numeric field with a "default" tag takes it when the key
// is missing and REFUSES when the key is present and empty. Forwarding
// req.URL.Query().Get() unconditionally turns every absent optional
// parameter into a 400 — which is how the ops drilldown started
// answering 500 to its own links the moment it gained a days control.
func present(q url.Values, keys ...string) url.Values {
	out := url.Values{}
	for _, k := range keys {
		if v := q.Get(k); v != "" {
			out.Set(k, v)
		}
	}
	return out
}

// repoOfPath is the repository a URL is about, or empty.
//
// Read from the path rather than from PathValue, for the same reason
// the route pattern is asked of the mux: path values are set on the
// request the mux passes DOWN, a copy this middleware never sees. Every
// render recorded before this carried an empty repo — 61 of 61 rows in
// the analytics store — which made the numbers unattributable on a
// fleet where repository size is the dominant cost.
func repoOfPath(p string) string {
	rest, ok := strings.CutPrefix(p, "/r/")
	if !ok {
		return ""
	}
	name, _, _ := strings.Cut(rest, "/")
	// The escaping the router would have undone. A name that will not
	// unescape is reported raw rather than dropped: a strange row is
	// evidence, a missing one is silence.
	if un, err := url.PathUnescape(name); err == nil {
		return un
	}
	return name
}

type ctxStart struct{}

// withTimer stamps request start so the layout can report render time,
// and files the finished request with the recorder. Outermost of the
// middlewares, so the number covers everything the server does for the
// request, not just the part after auth.
//
// The recorder runs AFTER the handler, which is the only place the
// template's own cost is known: the footer's breakdown is assembled
// before the template executes, so the page can never report the time
// it spent rendering itself. The ops surface can.
func withTimer(mux *http.ServeMux, next http.Handler) http.Handler {
	return withTimerFor(obs.Default, mux, next)
}

// withTimerFor is withTimer against a named recorder, so a test can
// assert what was filed rather than inspect the process-wide default.
func withTimerFor(rec *obs.Recorder, mux *http.ServeMux, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		ctx, t := timing.With(req.Context())
		// Tagged here, at the outermost middleware, so every store call
		// made anywhere under this request can name it.
		ctx, rid := obs.WithRequest(ctx)
		start := time.Now()
		sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
		next.ServeHTTP(sw, req.WithContext(context.WithValue(ctx, ctxStart{}, start)))
		if rec == nil {
			return
		}
		// The ROUTE, not the URL: /r/fossil/checkin/<hash> and its
		// twenty thousand siblings are one line on the page, not
		// twenty thousand.
		//
		// Asked of the mux rather than read off req.Pattern, which is
		// set on the request the mux passes DOWN — a copy this
		// middleware never sees, being outside it. Reading it here
		// filed every request in the forge under "/", which the ops
		// page reported as one route with an n of 26 the first time it
		// was looked at. Handler() resolves without dispatching.
		pattern := ""
		if mux != nil {
			_, pattern = mux.Handler(req)
		}
		if pattern == "" {
			// No route matched: a 404 sweep, worth seeing as one.
			pattern = "(unmatched)"
		}
		// A LIVE STREAM is not a slow page. chat, the timeline and the
		// ops panel all hold a connection open for as long as the
		// reader keeps the tab, so its "duration" is that tab's
		// lifetime: the fleet recorded timeline.sse at a p95 of 435
		// SECONDS, which headed the slowest-routes panel and buried the
		// findings under it.
		//
		// Worse, every stream crosses the render budget by design, so
		// the first-crossing alert fired on connections that are
		// working perfectly — the muted-channel failure that rule
		// exists to prevent, defeated by a category error in the same
		// feature.
		//
		// Detected from the response rather than the path: a handler
		// that streams says so in its Content-Type, and a name-based
		// rule (".sse") would miss the next streaming route somebody
		// adds under a different name.
		if isStream(sw.Header().Get("Content-Type")) && !sw.oneShot {
			return
		}
		// Static assets are file serving, not renders. The browser also
		// asks for sourcemaps nobody ships, so /assets/datastar.js.map
		// fell through to the catch-all and filed a 404 against route
		// "/" — several rows per page view, every one of them noise in
		// a panel whose whole job is to make the signal findable.
		//
		// By path here, unlike the stream rule: an asset IS a path
		// prefix by construction (the routes are literally
		// "GET /assets/..."), so there is no response to read it from
		// and nothing for a later route to accidentally slip past.
		if strings.HasPrefix(req.URL.Path, "/assets/") {
			return
		}
		rec.RecordRender(obs.Render{
			ID: rid, At: start, Path: pattern, URL: req.URL.Path,
			Repo:    repoOfPath(req.URL.Path),
			Elapsed: time.Since(start), Status: sw.status,
			Ops: t.Category(timing.Ops), Zit: t.Category(timing.Zit),
		})
	})
}

// isStream reports whether a response is a live stream rather than a
// page. Prefix-matched because the header may carry a charset.
func isStream(contentType string) bool {
	return strings.HasPrefix(contentType, "text/event-stream")
}

// statusWriter remembers the status so a render can be filed by
// outcome. A page that is slow because it is erroring is a different
// finding from one that is slow while working.
type statusWriter struct {
	http.ResponseWriter
	status  int
	written bool
	// oneShot marks a response that uses the event-stream content type
	// and yet completes immediately: a Datastar fragment is delivered
	// as SSE but is a RENDER, and its duration is work rather than a
	// tab left open.
	//
	// Still derived from the response and not the path — the handler
	// declares its own shape, which a ".frag" name rule would only
	// approximate until somebody named one differently.
	oneShot bool
}

func (w *statusWriter) markOneShot() { w.oneShot = true }

// markOneShot tells the timer that this event-stream response is a
// fragment, not a stream. Without it the refresh path is invisible to
// the panel: the fragment is what a live timeline actually spends its
// time in, and it would have been the one route nothing measured.
func markOneShot(w http.ResponseWriter) {
	if m, ok := w.(interface{ markOneShot() }); ok {
		m.markOneShot()
	}
}

func (w *statusWriter) WriteHeader(code int) {
	if !w.written {
		w.status, w.written = code, true
	}
	w.ResponseWriter.WriteHeader(code)
}

func (w *statusWriter) Write(b []byte) (int, error) {
	w.written = true
	return w.ResponseWriter.Write(b)
}

// Flush and Unwrap keep the SSE streams working: chat and the live
// panels write through this wrapper, and a wrapper that swallows Flush
// turns a stream into a page that never arrives.
func (w *statusWriter) Flush() {
	if f, ok := w.ResponseWriter.(http.Flusher); ok {
		f.Flush()
	}
}

func (w *statusWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }

type ctxIdentity struct{}

type identity struct {
	user      string
	canSignIn bool
	hasInbox  bool
	// attnEverywhere records --attention-everywhere: the deployment
	// multiplexes (h2 in front), so the attention stream may be opened
	// on every page rather than repository pages alone.
	attnEverywhere bool
	// isAdmin drives the fleet link in the header. It is a DISPLAY
	// decision only — /fleet gates itself, so a wrong answer here hides
	// or shows a link, never grants access.
	isAdmin bool
}

func withIdentity(sessions Sessions, hasInbox, attnEverywhere bool, caps func(repo string, req *http.Request) ops.Caps, next http.Handler) http.Handler {
	if sessions == nil {
		return next
	}
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		id := identity{canSignIn: true, hasInbox: hasInbox, attnEverywhere: attnEverywhere}
		if user, ok := sessions.Resolve(cookieToken(req)); ok {
			id.user = user
			// Empty repo at Admin is the site-admin question — the same
			// one /fleet asks.
			id.isAdmin = sessions.Allow(user, "", ops.Admin)
		}
		ctx := context.WithValue(req.Context(), ctxIdentity{}, id)
		// The viewer's capabilities for the repository this request is
		// about, resolved ONCE here so the ninety-odd invoke() calls
		// downstream cannot each get it subtly wrong — and so it can
		// never arrive as a request parameter, which is the one way a
		// "show me the private ones" flag must not be settable.
		if caps != nil {
			if c := caps(repoFromPath(req.URL.Path), req); c != nil {
				ctx = ops.WithCaps(ctx, c)
			}
		}
		next.ServeHTTP(w, req.WithContext(ctx))
	})
}

// repoFromPath names the repository a web request is about, for the
// middleware that runs BEFORE the mux has parsed path values. Every
// repository surface lives under /r/<name>/; anything else is a
// fleet-wide page, whose capabilities are the site-wide ones.
func repoFromPath(path string) string {
	rest, ok := strings.CutPrefix(path, "/r/")
	if !ok {
		return ""
	}
	name, _, _ := strings.Cut(rest, "/")
	if unescaped, err := url.PathUnescape(name); err == nil {
		return unescaped
	}
	return name
}

// safeNext keeps the post-login redirect on this site. An attacker who
// can choose ?next= can otherwise land a freshly-signed-in reader on
// their own page, which is how a login form becomes an open redirect.
// Only a rooted, single-slash path is allowed; anything else goes home.
func safeNext(next string) string {
	if next == "" || !strings.HasPrefix(next, "/") || strings.HasPrefix(next, "//") {
		return "/"
	}
	if strings.Contains(next, "\n") || strings.Contains(next, "\r") {
		return "/"
	}
	return next
}

// cloneURL is the address a reader clones from: quarry's own sync
// fronting for this repository (0001 §7), on whatever host they reached
// us by — a hardcoded base would be wrong for every deployment but one.
func cloneURL(req *http.Request, repo string) string {
	return origin(req) + "/r/" + repo
}

// origin is the scheme://host a reader reached us by. Everything that
// must be absolute — a clone address, an og:image a scraper fetches from
// another machine — is built from this, because a hardcoded base would
// be wrong for every deployment but one.
func origin(req *http.Request) string {
	scheme := "http"
	if req.TLS != nil {
		scheme = "https"
	}
	if p := req.Header.Get("X-Forwarded-Proto"); p != "" {
		scheme = p
	}
	return scheme + "://" + req.Host
}

// ciFragment renders the CI table for a repo — shared by the page and
// the stream, so a patch cannot drift from what a reload would draw.
func ciFragment(r *ops.Registry, logs LogStore, repo string, q url.Values) (string, error) {
	data := buildCIList(r, logs, repo, q)
	var buf bytes.Buffer
	if err := ciPage.ExecuteTemplate(&buf, "ci-body", data); err != nil {
		return "", err
	}
	return `<div id="ci">` + buf.String() + `</div>`, nil
}

// liveCI streams the CI table. Unlike the timeline, a CI page changes
// without any artifact arriving — a run finishes inside dagnats — so
// this polls rather than waiting on the event plane, and sends only
// when the rendered fragment actually differs.
func liveCI(r *ops.Registry, logs LogStore, repo string, w http.ResponseWriter, req *http.Request) {
	fl, ok := w.(http.Flusher)
	if !ok {
		http.Error(w, "streaming unsupported", http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-store")
	fmt.Fprint(w, ": live\n\n")
	fl.Flush()

	poll := time.NewTicker(3 * time.Second)
	defer poll.Stop()
	heartbeat := time.NewTicker(20 * time.Second)
	defer heartbeat.Stop()
	last := ""
	for {
		select {
		case <-req.Context().Done():
			return
		case <-heartbeat.C:
			fmt.Fprint(w, ": ping\n\n")
			fl.Flush()
		case <-poll.C:
			frag, err := ciFragment(r, logs, repo, req.URL.Query())
			if err != nil || frag == last {
				continue
			}
			last = frag
			fmt.Fprint(w, "event: datastar-patch-elements\n")
			for _, line := range strings.Split(frag, "\n") {
				fmt.Fprintf(w, "data: elements %s\n", line)
			}
			fmt.Fprint(w, "\n")
			fl.Flush()
		}
	}
}

// robotNouns is the vocabulary the activity robot offers. RFC 0011
// §10's robot announces what actually happens in a repository, so a
// forge with no CI engine does not offer `ci`: those events are never
// raised there, and a pattern that cannot match is indistinguishable
// — from the owner's chair — from a robot that is broken.
//
// The `ci` BRANCH in chat.RobotLine stays either way: an engine
// arriving later must announce without a code change.
func robotNouns(hasCI bool) []string {
	all := evt.Nouns()
	if hasCI {
		return all
	}
	out := make([]string, 0, len(all))
	for _, n := range all {
		if n == "ci" {
			continue
		}
		out = append(out, n)
	}
	return out
}