diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000..3d7f8fa
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,12 @@
+.git
+.gitignore
+.gocache
+.gobuild
+.pi
+bin/
+*.md
+*.db
+*.db-shm
+*.db-wal
+environment.d
+deploy
diff --git a/.gitignore b/.gitignore
index 23c0a75..6ff6957 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,9 +3,13 @@
.env.*
*.local
*.keystore
+environment.d/*.env
+environment.d/*.bak*
# Go
bin/
+.gocache/
+.gobuild/
*.exe
*.test
*.out
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..4671f20
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,30 @@
+# syntax=docker/dockerfile:1
+
+# ---- build stage ----------------------------------------------------------
+# Compass / NHS — its own image, built from source.
+FROM golang:1.25-alpine AS build
+WORKDIR /src
+RUN apk add --no-cache git
+COPY go.mod go.sum ./
+RUN go mod download
+COPY . .
+ARG VERSION=dev
+RUN CGO_ENABLED=0 GOOS=linux go build \
+ -trimpath \
+ -ldflags "-s -w -X main.version=${VERSION}" \
+ -o /out/school ./cmd/school
+
+# ---- runtime stage --------------------------------------------------------
+FROM alpine:3.21
+RUN apk add --no-cache ca-certificates tzdata wget \
+ && addgroup -g 10002 -S school \
+ && adduser -S -D -H -u 10002 -G school school \
+ && mkdir -p /data && chown school:school /data
+
+USER school
+WORKDIR /app
+COPY --from=build /out/school /app/school
+
+EXPOSE 8792
+VOLUME ["/data"]
+ENTRYPOINT ["/app/school"]
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..f242650
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,66 @@
+IMAGE ?= compass-teams-nhs/school:0.1.0-phase1
+BUILD_VERSION ?= 0.1.0-phase1
+
+# Bounded docker helper for the Go toolchain. The container runs as the current
+# user, so the repository and the module cache stay owned by you.
+GO_IMAGE ?= golang:1.25-alpine
+GO_RUN = timeout 600 docker run --rm --network host --user "$$(id -u):$$(id -g)" \
+ -e HOME=/src/.gocache -e GOMODCACHE=/src/.gocache/mod -e GOCACHE=/src/.gocache/build \
+ -v "$$PWD":/src -w /src $(GO_IMAGE)
+
+.PHONY: help test vet build up down restart logs ps deps fmt hash-password gen-secret verify-phase1
+
+help:
+ @echo "make test run go test ./... in golang:1.25-alpine"
+ @echo "make vet run go vet ./... in golang:1.25-alpine"
+ @echo "make build build the container image ($(IMAGE))"
+ @echo "make up docker compose up -d --build"
+ @echo "make down docker compose down"
+ @echo "make logs follow container logs"
+ @echo "make ps docker compose ps"
+ @echo "make deps go mod tidy + download (writes go.mod/go.sum)"
+ @echo "make hash-password generate a bcrypt hash (PASSWORD=...)"
+ @echo "make gen-secret print a fresh session secret"
+ @echo "make verify-phase1 prove /health, the login and the Caddy route"
+
+test:
+ $(GO_RUN) go test ./...
+
+vet:
+ $(GO_RUN) go vet ./...
+
+deps:
+ $(GO_RUN) sh -c 'go mod tidy'
+
+fmt:
+ $(GO_RUN) sh -c 'go fmt ./...'
+
+build:
+ docker build --build-arg VERSION=$(BUILD_VERSION) -t $(IMAGE) .
+
+up:
+ docker compose up -d --build
+
+down:
+ docker compose down
+
+restart:
+ docker compose restart school
+
+logs:
+ docker compose logs -f school
+
+ps:
+ docker compose ps
+
+hash-password:
+ @test -n "$(PASSWORD)" || (echo "usage: make hash-password PASSWORD=secret"; exit 2)
+ docker run --rm --entrypoint /app/school $(IMAGE) hash-password '$(PASSWORD)'
+
+gen-secret:
+ docker run --rm --entrypoint /app/school $(IMAGE) gen-secret
+
+# Phase 1 definition of done: /health 200, login page + session login, and the
+# Caddy route on .35.
+verify-phase1:
+ deploy/verify-phase1.sh
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..0e91f02
--- /dev/null
+++ b/README.md
@@ -0,0 +1,80 @@
+# Compass / NHS
+
+A school service for Harry and Finn: **Compass** for the daily schedule and
+notices, **Teams** for homework and assignments. It stores what is due per child,
+puts overdue work first, and tells the family before work is late.
+
+> Build spec: [`AGENTS.md`](AGENTS.md). This repository is at **Phase 1** (the
+> skeleton). See §11 of the spec for the phase order.
+
+## Status — Phase 1
+
+Built and deployed on `.13`:
+
+- Go service, SQLite schema for `children`, `items`, `scans`, `notifications`,
+ `session` (`internal/store/migrations/001_init.sql`).
+- The service's **own session login** — a signed cookie, not SSO.
+- Server-rendered **HTMX** shell using the Family Home Lab design tokens
+ (`internal/web/static/tokens.css`), phone-friendly with dark mode.
+- `GET /health`.
+- Its own container and port **8792**, behind Caddy at
+ `school.lab.audasmedia.com.au`.
+
+Not built yet (later phases): the Compass login and fetch, parsing, both
+children's data, the dashboard data, the calendar write, notifications, and the
+Hub API. It does **not** scan the school in this phase.
+
+### Fail loudly (FR-12)
+
+A missing or failed scan is shown as an explicit warning or error, never as an
+empty day. The dashboard reads the `scans` table and shows one of:
+
+- **NO SCAN HAS RUN YET** — amber banner.
+- **SCAN FAILED** — red banner with the failure on record.
+- **Last scan completed** — green banner.
+
+## Layout
+
+```
+cmd/school/ service entry point
+internal/config/ environment configuration
+internal/store/ SQLite: schema, migrations, queries
+internal/auth/ session login (signed cookies, CSRF)
+internal/web/ HTTP handlers, templates, static assets
+deploy/ Caddy snippet, deployment notes, verify script
+environment.d/ env example (the real file is gitignored)
+```
+
+## Run
+
+```bash
+cp environment.d/school-service.env.example environment.d/school-service.env
+chmod 600 environment.d/school-service.env # then fill in the secrets
+docker compose up -d --build
+```
+
+Generate secrets with the built image:
+
+```bash
+docker run --rm --entrypoint /app/school compass-teams-nhs/school:0.1.0-phase1 gen-secret
+docker run --rm --entrypoint /app/school compass-teams-nhs/school:0.1.0-phase1 hash-password 'the-password'
+```
+
+Note: Docker Compose interpolates `$VAR` inside `env_file`. A bcrypt hash
+contains `$`, so escape each one as `$$` in the env file.
+
+## Verify
+
+```bash
+make verify-phase1
+```
+
+It checks the container is healthy, `GET /health` returns 200, the login page
+renders and a session login succeeds, and Caddy serves the public URL.
+
+## Rules
+
+- **Read-only against the school.** Never post, message, or submit anything.
+- A failed scan must be loud — never report an empty day as "nothing due".
+- School credentials and harness session state are secrets; never commit them.
+- This project has its own folder, container, and port.
diff --git a/cmd/school/main.go b/cmd/school/main.go
new file mode 100644
index 0000000..348f16b
--- /dev/null
+++ b/cmd/school/main.go
@@ -0,0 +1,167 @@
+// Command school is the Compass / NHS service (school.lab.audasmedia.com.au).
+//
+// Phase 1 skeleton: Go service, SQLite schema (AGENTS.md §7), the service's own
+// session login, HTMX server-rendered shell, and GET /health. It does not scan
+// the school; the Compass login and fetch are Phase 2.
+package main
+
+import (
+ "context"
+ "crypto/rand"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "net/http"
+ "os"
+ "os/signal"
+ "syscall"
+ "time"
+
+ "golang.org/x/crypto/bcrypt"
+
+ "gitea.lab.audasmedia.com.au/sam/compass_teams_nhs/internal/auth"
+ "gitea.lab.audasmedia.com.au/sam/compass_teams_nhs/internal/config"
+ "gitea.lab.audasmedia.com.au/sam/compass_teams_nhs/internal/store"
+ "gitea.lab.audasmedia.com.au/sam/compass_teams_nhs/internal/web"
+)
+
+// version is injected with -ldflags at build time.
+var version = "dev"
+
+// seedChildren is the fixed set from AGENTS.md: Harry and Finn.
+var seedChildren = []string{"Harry", "Finn"}
+
+func main() {
+ if len(os.Args) > 1 {
+ switch os.Args[1] {
+ case "hash-password":
+ hashPassword(os.Args[2:])
+ return
+ case "gen-secret":
+ genSecret()
+ return
+ case "version":
+ fmt.Println(version)
+ return
+ }
+ }
+ if err := run(); err != nil {
+ fmt.Fprintln(os.Stderr, "school:", err)
+ os.Exit(1)
+ }
+}
+
+func run() error {
+ started := time.Now()
+
+ cfg, err := config.Load()
+ if err != nil {
+ return err
+ }
+ cfg.Version = version
+
+ log := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: cfg.LogLevel}))
+ slog.SetDefault(log)
+
+ st, err := store.Open(cfg.DBPath)
+ if err != nil {
+ return err
+ }
+ defer st.Close()
+
+ if err := st.Migrate(context.Background()); err != nil {
+ return err
+ }
+ if err := st.SeedChildren(context.Background(), seedChildren...); err != nil {
+ return err
+ }
+
+ am, err := auth.New(cfg.SessionSecret, cfg.SessionTTL, cfg.CookieSecure,
+ cfg.AdminUsername, cfg.AdminPasswordHash, cfg.AdminPassword)
+ if err != nil {
+ return err
+ }
+ if !am.Hashed() {
+ log.Warn("admin password is plaintext; set SCHOOL_ADMIN_PASSWORD_HASH to use bcrypt")
+ }
+
+ srv, err := web.New(cfg, st, am, log)
+ if err != nil {
+ return err
+ }
+
+ httpServer := &http.Server{
+ Addr: cfg.Addr,
+ Handler: srv.Handler(),
+ ReadHeaderTimeout: 10 * time.Second,
+ ReadTimeout: 30 * time.Second,
+ WriteTimeout: 30 * time.Second,
+ IdleTimeout: 60 * time.Second,
+ }
+
+ errCh := make(chan error, 1)
+ go func() {
+ log.Info("school service listening",
+ "addr", cfg.Addr, "db", cfg.DBPath, "env", cfg.AppEnv, "version", version)
+ if err := httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
+ errCh <- err
+ }
+ }()
+
+ stop := make(chan os.Signal, 1)
+ signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
+
+ select {
+ case err := <-errCh:
+ return err
+ case sig := <-stop:
+ log.Info("shutting down", "signal", sig.String())
+ }
+
+ ctxShutdown, cancelShutdown := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancelShutdown()
+ if err := httpServer.Shutdown(ctxShutdown); err != nil {
+ return fmt.Errorf("shutdown: %w", err)
+ }
+ log.Info("stopped", "uptime", time.Since(started).Round(time.Second).String())
+ return nil
+}
+
+// hashPassword prints a bcrypt hash for the password given as an argument or
+// read from stdin. It never prints the password itself.
+func hashPassword(args []string) {
+ var password string
+ if len(args) > 0 {
+ password = args[0]
+ } else {
+ b, err := io.ReadAll(os.Stdin)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "school:", err)
+ os.Exit(1)
+ }
+ password = string(b)
+ }
+ if password == "" {
+ fmt.Fprintln(os.Stderr, "school: empty password")
+ os.Exit(2)
+ }
+ hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "school:", err)
+ os.Exit(1)
+ }
+ fmt.Println(string(hash))
+}
+
+// genSecret prints a fresh 32-byte hex secret. Use it to set
+// SCHOOL_SESSION_SECRET without pasting a secret into a shell history file by
+// hand. It never reads or stores anything.
+func genSecret() {
+ b := make([]byte, 32)
+ if _, err := rand.Read(b); err != nil {
+ fmt.Fprintln(os.Stderr, "school:", err)
+ os.Exit(1)
+ }
+ fmt.Printf("%x\n", b)
+}
diff --git a/deploy/DEPLOYMENT.md b/deploy/DEPLOYMENT.md
new file mode 100644
index 0000000..bd2e39a
--- /dev/null
+++ b/deploy/DEPLOYMENT.md
@@ -0,0 +1,58 @@
+# Deployment — Compass / NHS (school.lab.audasmedia.com.au)
+
+Own image, own container, own port **8792**, host `.13` (nixos-desktop). Caddy
+on `.35` (sam-ubuntu1) terminates TLS and proxies to `192.168.20.13:8792`.
+
+## Ports
+
+| Port | Service |
+|---|---|
+| 8792 | Compass / NHS (this project) |
+
+## Host (.13)
+
+1. Project folder: `/home/sam/paseo/projects/compass_teams_nhs`.
+2. Data: the named volume `compass-teams-nhs_compass-teams-nhs-data` at `/data`
+ (SQLite `school.db`).
+3. Create the environment file from the example:
+
+ ```bash
+ cd /home/sam/paseo/projects/compass_teams_nhs
+ cp environment.d/school-service.env.example environment.d/school-service.env
+ chmod 600 environment.d/school-service.env
+ # fill SCHOOL_SESSION_SECRET, SCHOOL_ADMIN_PASSWORD_HASH
+ ```
+
+4. Build and start:
+
+ ```bash
+ docker compose up -d --build
+ docker compose ps # compass-teams-nhs Up (healthy) 0.0.0.0:8792->8792/tcp
+ ```
+
+5. Verify:
+
+ ```bash
+ make verify-phase1
+ ```
+
+## Caddy (.35)
+
+1. SSH: `ssh sam@192.168.20.35`.
+2. Append `deploy/caddy/Caddyfile.snippet` to `/Docker/Containers/caddy/Caddyfile`.
+3. Validate and reload (never restart):
+
+ ```bash
+ docker exec caddy caddy validate --config /etc/caddy/Caddyfile
+ docker exec caddy caddy reload --config /etc/caddy/Caddyfile
+ ```
+
+4. Test: `curl -sS -o /dev/null -w '%{http_code}\n' https://school.lab.audasmedia.com.au/health`
+
+## Notes
+
+- `.13` has every default Docker address pool subnetted out. This single-container
+ service therefore uses `network_mode: bridge` and publishes 8792; it does not
+ create a project network.
+- The env file is gitignored. School credentials and harness session state are
+ secrets (AGENTS.md §10 rule 3); they never enter git.
diff --git a/deploy/caddy/Caddyfile.snippet b/deploy/caddy/Caddyfile.snippet
new file mode 100644
index 0000000..75b2cf7
--- /dev/null
+++ b/deploy/caddy/Caddyfile.snippet
@@ -0,0 +1,12 @@
+# Caddyfile addition for the Compass / NHS service.
+# Apply on .35 (sam-ubuntu1, 192.168.20.35) — append to /Docker/Containers/caddy/Caddyfile
+# and reload: docker exec caddy caddy reload --config /etc/caddy/Caddyfile
+#
+# The public zone lab.audasmedia.com.au already resolves to 144.6.86.11 -> router
+# -> .35. No Pi-hole local record is required.
+
+# Compass / NHS (AUD-103) — school.lab.audasmedia.com.au -> .13:8792
+# No basic-auth: the service has its own session login (AGENTS.md §9, §10).
+school.lab.audasmedia.com.au {
+ reverse_proxy 192.168.20.13:8792
+}
diff --git a/deploy/verify-phase1.sh b/deploy/verify-phase1.sh
new file mode 100755
index 0000000..d57355b
--- /dev/null
+++ b/deploy/verify-phase1.sh
@@ -0,0 +1,93 @@
+#!/usr/bin/env bash
+# Phase 1 definition of done (AUD-103).
+#
+# - the container is up and healthy
+# - GET /health returns 200 with status ok
+# - the login page renders and a session login succeeds
+# - the Caddy route on .35 serves school.lab.audasmedia.com.au
+#
+# Run on .13 from the project folder. It reads the admin password from
+# environment.d/school-service.env, never prints it, and never touches the
+# school's systems.
+set -u
+
+BASE="${SCHOOL_VERIFY_BASE:-http://127.0.0.1:8792}"
+PUBLIC="${SCHOOL_VERIFY_PUBLIC:-https://school.lab.audasmedia.com.au}"
+ENV_FILE="${SCHOOL_ENV_FILE:-environment.d/school-service.env}"
+TMP="$(mktemp -d)"
+trap 'rm -rf "$TMP"' EXIT
+
+fail=0
+pass() { printf 'PASS %s\n' "$1"; }
+bad() { printf 'FAIL %s\n' "$1"; fail=1; }
+
+echo "== container =="
+timeout 60 docker compose ps || true
+
+echo
+echo "== GET /health =="
+code="$(curl -sS -o "$TMP/health.json" -w '%{http_code}' "$BASE/health" || echo 000)"
+body="$(cat "$TMP/health.json" 2>/dev/null)"
+printf 'HTTP %s\n%s\n' "$code" "$body"
+if [ "$code" = "200" ] && printf '%s' "$body" | grep -q '"status":"ok"'; then
+ pass "/health 200 and status ok"
+else
+ bad "/health did not return 200 status ok"
+fi
+
+echo
+echo "== login page =="
+curl -sS -c "$TMP/cookies" -o "$TMP/login.html" -w 'HTTP %{http_code}\n' "$BASE/login"
+if grep -q 'name="csrf"' "$TMP/login.html"; then
+ pass "login page renders with a csrf token"
+else
+ bad "login page did not render a csrf token"
+fi
+
+echo
+echo "== session login =="
+# Extract the plaintext password or use the hash-only path. With a hash-only
+# env file the operator must supply SCHOOL_VERIFY_PASSWORD.
+pw="${SCHOOL_VERIFY_PASSWORD:-}"
+if [ -z "$pw" ] && [ -f "$ENV_FILE" ]; then
+ pw="$(sed -n 's/^SCHOOL_ADMIN_PASSWORD=//p' "$ENV_FILE" | head -1)"
+fi
+csrf="$(grep -o 'name="csrf" value="[^"]*"' "$TMP/login.html" | head -1 | sed 's/.*value="//; s/"//')"
+if [ -z "$pw" ]; then
+ echo "SKIP no SCHOOL_VERIFY_PASSWORD and no plaintext password in $ENV_FILE"
+elif [ -z "$csrf" ]; then
+ bad "no csrf token to submit"
+else
+ code="$(curl -sS -b "$TMP/cookies" -c "$TMP/cookies" -o /dev/null -w '%{http_code}' \
+ -d "csrf=$csrf" -d "username=sam" -d "password=$pw" "$BASE/login")"
+ if [ "$code" = "303" ]; then
+ dash="$(curl -sS -b "$TMP/cookies" -o "$TMP/dash.html" -w '%{http_code}' "$BASE/")"
+ if [ "$dash" = "200" ] && grep -q 'What is due' "$TMP/dash.html"; then
+ pass "session login succeeds and the dashboard renders"
+ else
+ bad "dashboard did not render after login (HTTP $dash)"
+ fi
+ else
+ bad "login POST returned $code, expected 303"
+ fi
+fi
+
+echo
+echo "== Caddy route (.35) =="
+code="$(curl -sS -o "$TMP/pub.json" -D "$TMP/pub.headers" -w '%{http_code}' --max-time 25 "$PUBLIC/health" || echo 000)"
+printf 'HTTP %s\n' "$code"
+grep -i '^server:' "$TMP/pub.headers" 2>/dev/null || true
+grep -i '^content-type:' "$TMP/pub.headers" 2>/dev/null || true
+if [ "$code" = "200" ] && grep -qi '^server: Caddy' "$TMP/pub.headers"; then
+ pass "Caddy serves $PUBLIC/health"
+else
+ bad "Caddy route did not answer 200 (HTTP $code)"
+fi
+
+echo
+if [ "$fail" = "0" ]; then
+ echo "RESULT: Phase 1 verified"
+else
+ echo "RESULT: Phase 1 verification FAILED"
+fi
+exit "$fail"
diff --git a/docker-compose.yml b/docker-compose.yml
new file mode 100644
index 0000000..878ce42
--- /dev/null
+++ b/docker-compose.yml
@@ -0,0 +1,40 @@
+# Compass / NHS — its own image, own container, own port (8792).
+# Deploy on .13: cd /home/sam/paseo/projects/compass_teams_nhs && docker compose up -d --build
+#
+# Secrets live in environment.d/school-service.env (gitignored), never here.
+
+name: compass-teams-nhs
+
+services:
+ school:
+ build:
+ context: .
+ args:
+ VERSION: "0.1.0-phase1"
+ image: compass-teams-nhs/school:0.1.0-phase1
+ container_name: compass-teams-nhs
+ restart: unless-stopped
+ env_file:
+ - environment.d/school-service.env
+ ports:
+ - "8792:8792"
+ volumes:
+ - compass-teams-nhs-data:/data
+ healthcheck:
+ test: ["CMD", "wget", "-qO-", "http://127.0.0.1:8792/health"]
+ interval: 30s
+ timeout: 5s
+ retries: 3
+ start_period: 10s
+ logging:
+ driver: json-file
+ options:
+ max-size: "10m"
+ max-file: "3"
+ # .13 has every default Docker address pool subnetted out (many projects),
+ # so this single-container service uses the host's default bridge and does
+ # not create a project network. The port is published above.
+ network_mode: bridge
+
+volumes:
+ compass-teams-nhs-data:
diff --git a/environment.d/school-service.env.example b/environment.d/school-service.env.example
new file mode 100644
index 0000000..f12abaa
--- /dev/null
+++ b/environment.d/school-service.env.example
@@ -0,0 +1,30 @@
+# Compass / NHS — service environment (EXAMPLE).
+#
+# Copy to environment.d/school-service.env and fill the secrets in. The real
+# file is gitignored; never commit it. Generate values with:
+# docker run --rm --entrypoint /app/school compass-teams-nhs/school:0.1.0-phase1 gen-secret
+# docker run --rm --entrypoint /app/school compass-teams-nhs/school:0.1.0-phase1 hash-password 'the-password'
+
+# Listen address inside the container. The host maps 8792 -> 8792.
+SCHOOL_ADDR=:8792
+
+# SQLite database in the named volume.
+SCHOOL_DB_PATH=/data/school.db
+
+# Signs the session cookie. Required, >= 16 characters. Secret.
+SCHOOL_SESSION_SECRET=change-me-32-bytes-of-random
+
+# The single dashboard login (Sam). Prefer the bcrypt hash over the plaintext.
+SCHOOL_ADMIN_USERNAME=sam
+SCHOOL_ADMIN_PASSWORD_HASH=
+SCHOOL_ADMIN_PASSWORD=
+
+# Keep true behind HTTPS (Caddy terminates TLS).
+SCHOOL_COOKIE_SECURE=true
+SCHOOL_SESSION_TTL=12h
+
+# Family timezone for due dates and briefs.
+SCHOOL_TIMEZONE=Australia/Sydney
+
+SCHOOL_LOG_LEVEL=info
+SCHOOL_APP_ENV=production
diff --git a/go.mod b/go.mod
new file mode 100644
index 0000000..b8e42a4
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,20 @@
+module gitea.lab.audasmedia.com.au/sam/compass_teams_nhs
+
+go 1.25
+
+require (
+ golang.org/x/crypto v0.42.0
+ modernc.org/sqlite v1.34.5
+)
+
+require (
+ github.com/dustin/go-humanize v1.0.1 // indirect
+ github.com/google/uuid v1.6.0 // indirect
+ github.com/mattn/go-isatty v0.0.20 // indirect
+ github.com/ncruces/go-strftime v0.1.9 // indirect
+ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
+ golang.org/x/sys v0.36.0 // indirect
+ modernc.org/libc v1.55.3 // indirect
+ modernc.org/mathutil v1.6.0 // indirect
+ modernc.org/memory v1.8.0 // indirect
+)
diff --git a/go.sum b/go.sum
new file mode 100644
index 0000000..339a9ba
--- /dev/null
+++ b/go.sum
@@ -0,0 +1,45 @@
+github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
+github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
+github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=
+github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw=
+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
+github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
+github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
+golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI=
+golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8=
+golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic=
+golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
+golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k=
+golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
+golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw=
+golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc=
+modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ=
+modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ=
+modernc.org/ccgo/v4 v4.19.2 h1:lwQZgvboKD0jBwdaeVCTouxhxAyN6iawF3STraAal8Y=
+modernc.org/ccgo/v4 v4.19.2/go.mod h1:ysS3mxiMV38XGRTTcgo0DQTeTmAO4oCmJl1nX9VFI3s=
+modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE=
+modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ=
+modernc.org/gc/v2 v2.4.1 h1:9cNzOqPyMJBvrUipmynX0ZohMhcxPtMccYgGOJdOiBw=
+modernc.org/gc/v2 v2.4.1/go.mod h1:wzN5dK1AzVGoH6XOzc3YZ+ey/jPgYHLuVckd62P0GYU=
+modernc.org/libc v1.55.3 h1:AzcW1mhlPNrRtjS5sS+eW2ISCgSOLLNyFzRh/V3Qj/U=
+modernc.org/libc v1.55.3/go.mod h1:qFXepLhz+JjFThQ4kzwzOjA/y/artDeg+pcYnY+Q83w=
+modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4=
+modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo=
+modernc.org/memory v1.8.0 h1:IqGTL6eFMaDZZhEWwcREgeMXYwmW83LYW8cROZYkg+E=
+modernc.org/memory v1.8.0/go.mod h1:XPZ936zp5OMKGWPqbD3JShgd/ZoQ7899TUuQqxY+peU=
+modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4=
+modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0=
+modernc.org/sortutil v1.2.0 h1:jQiD3PfS2REGJNzNCMMaLSp/wdMNieTbKX920Cqdgqc=
+modernc.org/sortutil v1.2.0/go.mod h1:TKU2s7kJMf1AE84OoiGppNHJwvB753OYfNl2WRb++Ss=
+modernc.org/sqlite v1.34.5 h1:Bb6SR13/fjp15jt70CL4f18JIN7p7dnMExd+UFnF15g=
+modernc.org/sqlite v1.34.5/go.mod h1:YLuNmX9NKs8wRNK2ko1LW1NGYcc9FkBO69JOt1AR9JE=
+modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA=
+modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0=
+modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
+modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
diff --git a/internal/auth/auth.go b/internal/auth/auth.go
new file mode 100644
index 0000000..75d88f4
--- /dev/null
+++ b/internal/auth/auth.go
@@ -0,0 +1,207 @@
+// Package auth implements the service's own session login (AGENTS.md §9 Auth:
+// a separate session login, not SSO). Sessions are stateless, signed cookies.
+// A random CSRF cookie uses the double-submit pattern for forms.
+package auth
+
+import (
+ "crypto/hmac"
+ "crypto/rand"
+ "crypto/sha256"
+ "crypto/subtle"
+ "encoding/base64"
+ "errors"
+ "fmt"
+ "net/http"
+ "strconv"
+ "strings"
+ "time"
+
+ "golang.org/x/crypto/bcrypt"
+)
+
+const (
+ sessionCookie = "school_session"
+ csrfCookie = "school_csrf"
+)
+
+// Manager issues and validates sessions.
+type Manager struct {
+ // Secret signs every cookie. Required.
+ Secret []byte
+ // TTL is the session lifetime.
+ TTL time.Duration
+ // Secure sets the Secure cookie attribute. Keep true behind HTTPS.
+ Secure bool
+ // Username is the single allowed login name.
+ Username string
+ // passwordHash is a bcrypt hash, or nil when only a plaintext password is set.
+ passwordHash []byte
+ // plaintext is the fallback password, or empty when a hash is set.
+ plaintext string
+}
+
+// New builds a Manager. Exactly one of bcryptHash or plaintext must be set.
+func New(secret []byte, ttl time.Duration, secure bool, username, bcryptHash, plaintext string) (*Manager, error) {
+ if len(secret) < 16 {
+ return nil, errors.New("session secret too short")
+ }
+ m := &Manager{Secret: secret, TTL: ttl, Secure: secure, Username: username}
+ switch {
+ case bcryptHash != "":
+ if _, err := bcrypt.Cost([]byte(bcryptHash)); err != nil {
+ return nil, fmt.Errorf("SCHOOL_ADMIN_PASSWORD_HASH is not a valid bcrypt hash: %w", err)
+ }
+ m.passwordHash = []byte(bcryptHash)
+ case plaintext != "":
+ m.plaintext = plaintext
+ default:
+ return nil, errors.New("no admin password configured")
+ }
+ return m, nil
+}
+
+// Hashed reports whether the manager verifies against a bcrypt hash.
+func (m *Manager) Hashed() bool { return m.passwordHash != nil }
+
+// CheckCredentials validates a username and password in constant time where
+// possible. It never reveals which part was wrong.
+func (m *Manager) CheckCredentials(username, password string) bool {
+ userOK := subtle.ConstantTimeCompare([]byte(username), []byte(m.Username)) == 1
+ passOK := false
+ if m.passwordHash != nil {
+ passOK = bcrypt.CompareHashAndPassword(m.passwordHash, []byte(password)) == nil
+ } else {
+ passOK = subtle.ConstantTimeCompare([]byte(password), []byte(m.plaintext)) == 1
+ }
+ return userOK && passOK
+}
+
+// Issue writes a signed session cookie and the matching CSRF cookie.
+func (m *Manager) Issue(w http.ResponseWriter) {
+ csrf := randomToken()
+ expires := time.Now().Add(m.TTL).Unix()
+ payload := strings.Join([]string{m.Username, csrf, strconv.FormatInt(expires, 10)}, "\n")
+
+ http.SetCookie(w, &http.Cookie{
+ Name: sessionCookie,
+ Value: m.sign(payload),
+ Path: "/",
+ HttpOnly: true,
+ Secure: m.Secure,
+ SameSite: http.SameSiteLaxMode,
+ Expires: time.Unix(expires, 0),
+ MaxAge: int(m.TTL.Seconds()),
+ })
+ http.SetCookie(w, &http.Cookie{
+ Name: csrfCookie,
+ Value: csrf,
+ Path: "/",
+ HttpOnly: true,
+ Secure: m.Secure,
+ SameSite: http.SameSiteLaxMode,
+ Expires: time.Unix(expires, 0),
+ MaxAge: int(m.TTL.Seconds()),
+ })
+}
+
+// Clear removes the session and CSRF cookies.
+func (m *Manager) Clear(w http.ResponseWriter) {
+ for _, name := range []string{sessionCookie, csrfCookie} {
+ http.SetCookie(w, &http.Cookie{
+ Name: name,
+ Value: "",
+ Path: "/",
+ HttpOnly: true,
+ Secure: m.Secure,
+ SameSite: http.SameSiteLaxMode,
+ MaxAge: -1,
+ Expires: time.Unix(0, 0),
+ })
+ }
+}
+
+// Authenticated reports whether the request carries a valid, unexpired session.
+func (m *Manager) Authenticated(r *http.Request) bool {
+ c, err := r.Cookie(sessionCookie)
+ if err != nil {
+ return false
+ }
+ payload, ok := m.verify(c.Value)
+ if !ok {
+ return false
+ }
+ parts := strings.Split(payload, "\n")
+ if len(parts) != 3 || parts[0] != m.Username {
+ return false
+ }
+ expires, err := strconv.ParseInt(parts[2], 10, 64)
+ if err != nil || time.Now().Unix() > expires {
+ return false
+ }
+ return true
+}
+
+// EnsureCSRF returns the CSRF token for a form, setting the cookie if absent.
+func (m *Manager) EnsureCSRF(w http.ResponseWriter, r *http.Request) string {
+ if c, err := r.Cookie(csrfCookie); err == nil && c.Value != "" {
+ return c.Value
+ }
+ token := randomToken()
+ http.SetCookie(w, &http.Cookie{
+ Name: csrfCookie,
+ Value: token,
+ Path: "/",
+ HttpOnly: true,
+ Secure: m.Secure,
+ SameSite: http.SameSiteLaxMode,
+ MaxAge: int(m.TTL.Seconds()),
+ })
+ return token
+}
+
+// CheckCSRF compares the submitted form token with the CSRF cookie.
+func (m *Manager) CheckCSRF(r *http.Request) bool {
+ c, err := r.Cookie(csrfCookie)
+ if err != nil || c.Value == "" {
+ return false
+ }
+ form := r.PostFormValue("csrf")
+ return subtle.ConstantTimeCompare([]byte(form), []byte(c.Value)) == 1
+}
+
+func (m *Manager) sign(payload string) string {
+ mac := hmac.New(sha256.New, m.Secret)
+ mac.Write([]byte(payload))
+ sig := mac.Sum(nil)
+ return base64.RawURLEncoding.EncodeToString([]byte(payload)) + "." +
+ base64.RawURLEncoding.EncodeToString(sig)
+}
+
+func (m *Manager) verify(token string) (string, bool) {
+ encoded, sigEncoded, ok := strings.Cut(token, ".")
+ if !ok {
+ return "", false
+ }
+ payload, err := base64.RawURLEncoding.DecodeString(encoded)
+ if err != nil {
+ return "", false
+ }
+ gotSig, err := base64.RawURLEncoding.DecodeString(sigEncoded)
+ if err != nil {
+ return "", false
+ }
+ mac := hmac.New(sha256.New, m.Secret)
+ mac.Write(payload)
+ if !hmac.Equal(gotSig, mac.Sum(nil)) {
+ return "", false
+ }
+ return string(payload), true
+}
+
+func randomToken() string {
+ b := make([]byte, 32)
+ if _, err := rand.Read(b); err != nil {
+ panic("auth: random source failed: " + err.Error())
+ }
+ return base64.RawURLEncoding.EncodeToString(b)
+}
diff --git a/internal/config/config.go b/internal/config/config.go
new file mode 100644
index 0000000..f39b6d3
--- /dev/null
+++ b/internal/config/config.go
@@ -0,0 +1,129 @@
+// Package config loads the Compass/NHS service configuration from the process
+// environment. Every secret comes from the environment (environment.d); nothing
+// is compiled into the binary and nothing secret is read from a committed file.
+package config
+
+import (
+ "errors"
+ "fmt"
+ "log/slog"
+ "os"
+ "strconv"
+ "strings"
+ "time"
+ // Embed the IANA time zone database so SCHOOL_TIMEZONE resolves even in a
+ // container without tzdata.
+ _ "time/tzdata"
+)
+
+// Config is the fully resolved runtime configuration.
+type Config struct {
+ // Addr is the listen address, for example ":8792".
+ Addr string
+ // DBPath is the SQLite database file, for example "/data/school.db".
+ DBPath string
+ // SessionSecret signs the session cookie. Required, >= 16 bytes.
+ SessionSecret []byte
+ // AdminUsername is the single dashboard login name (Sam).
+ AdminUsername string
+ // AdminPassword is the plaintext password. Optional if AdminPasswordHash is set.
+ AdminPassword string
+ // AdminPasswordHash is a bcrypt hash. Optional if AdminPassword is set.
+ AdminPasswordHash string
+ // CookieSecure sets the Secure attribute on cookies. Keep true behind HTTPS.
+ CookieSecure bool
+ // SessionTTL is how long a session cookie stays valid.
+ SessionTTL time.Duration
+ // LogLevel is the slog level.
+ LogLevel slog.Level
+ // AppEnv is a label such as "production" or "development".
+ AppEnv string
+ // Version is injected at build time.
+ Version string
+ // Location is the family timezone. Due dates and briefs are wall-clock, so
+ // this must be the family's zone, not the container default of UTC.
+ Location *time.Location
+}
+
+// DefaultTimezone is the family timezone used when SCHOOL_TIMEZONE is unset.
+const DefaultTimezone = "Australia/Sydney"
+
+// Load reads and validates the configuration.
+func Load() (*Config, error) {
+ cfg := &Config{
+ Addr: env("SCHOOL_ADDR", ":8792"),
+ DBPath: env("SCHOOL_DB_PATH", "/data/school.db"),
+ AdminUsername: env("SCHOOL_ADMIN_USERNAME", "sam"),
+ AdminPassword: os.Getenv("SCHOOL_ADMIN_PASSWORD"),
+ AdminPasswordHash: os.Getenv("SCHOOL_ADMIN_PASSWORD_HASH"),
+ CookieSecure: envBool("SCHOOL_COOKIE_SECURE", true),
+ AppEnv: env("SCHOOL_APP_ENV", "production"),
+ }
+
+ secret := os.Getenv("SCHOOL_SESSION_SECRET")
+ if len(secret) < 16 {
+ return nil, errors.New("SCHOOL_SESSION_SECRET must be set and at least 16 characters")
+ }
+ cfg.SessionSecret = []byte(secret)
+
+ if cfg.AdminPassword == "" && cfg.AdminPasswordHash == "" {
+ return nil, errors.New("set SCHOOL_ADMIN_PASSWORD or SCHOOL_ADMIN_PASSWORD_HASH")
+ }
+ if cfg.AdminUsername == "" {
+ return nil, errors.New("SCHOOL_ADMIN_USERNAME must not be empty")
+ }
+
+ ttl, err := time.ParseDuration(env("SCHOOL_SESSION_TTL", "12h"))
+ if err != nil {
+ return nil, fmt.Errorf("SCHOOL_SESSION_TTL: %w", err)
+ }
+ cfg.SessionTTL = ttl
+
+ lvl, err := parseLevel(env("SCHOOL_LOG_LEVEL", "info"))
+ if err != nil {
+ return nil, err
+ }
+ cfg.LogLevel = lvl
+
+ loc, err := time.LoadLocation(env("SCHOOL_TIMEZONE", DefaultTimezone))
+ if err != nil {
+ return nil, fmt.Errorf("SCHOOL_TIMEZONE: %w", err)
+ }
+ cfg.Location = loc
+
+ return cfg, nil
+}
+
+func env(key, fallback string) string {
+ if v := strings.TrimSpace(os.Getenv(key)); v != "" {
+ return v
+ }
+ return fallback
+}
+
+func envBool(key string, fallback bool) bool {
+ v := strings.TrimSpace(os.Getenv(key))
+ if v == "" {
+ return fallback
+ }
+ b, err := strconv.ParseBool(v)
+ if err != nil {
+ return fallback
+ }
+ return b
+}
+
+func parseLevel(s string) (slog.Level, error) {
+ switch strings.ToLower(strings.TrimSpace(s)) {
+ case "debug":
+ return slog.LevelDebug, nil
+ case "info", "":
+ return slog.LevelInfo, nil
+ case "warn", "warning":
+ return slog.LevelWarn, nil
+ case "error":
+ return slog.LevelError, nil
+ default:
+ return 0, fmt.Errorf("SCHOOL_LOG_LEVEL: unknown level %q", s)
+ }
+}
diff --git a/internal/store/migrations/001_init.sql b/internal/store/migrations/001_init.sql
new file mode 100644
index 0000000..968b25f
--- /dev/null
+++ b/internal/store/migrations/001_init.sql
@@ -0,0 +1,67 @@
+-- Migration 001 — Phase 1 foundation (AGENTS.md §7).
+--
+-- Every item is stored with its child, source page, type, subject, due date and
+-- link (FR-5). Scans are append-only and record success or an explicit error,
+-- so a failed scan can never be mistaken for "nothing due" (FR-12).
+
+CREATE TABLE IF NOT EXISTS children (
+ id INTEGER PRIMARY KEY,
+ name TEXT NOT NULL UNIQUE,
+ year TEXT,
+ compass_id TEXT,
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
+);
+
+-- One row per message, task or calendar event read from Compass or Teams.
+CREATE TABLE IF NOT EXISTS items (
+ id INTEGER PRIMARY KEY,
+ child_id INTEGER NOT NULL REFERENCES children(id),
+ source TEXT NOT NULL DEFAULT 'compass' CHECK (source IN ('compass', 'teams')),
+ type TEXT NOT NULL CHECK (type IN ('message', 'task', 'event')),
+ subject TEXT,
+ teacher TEXT,
+ title TEXT NOT NULL,
+ body TEXT,
+ due_at TEXT,
+ url TEXT,
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
+);
+
+CREATE INDEX IF NOT EXISTS idx_items_child ON items(child_id);
+CREATE INDEX IF NOT EXISTS idx_items_due ON items(child_id, due_at);
+CREATE INDEX IF NOT EXISTS idx_items_type ON items(child_id, type);
+
+-- Append-only scan log (FR-13). ok = 0 with a message is a loud failure.
+CREATE TABLE IF NOT EXISTS scans (
+ id INTEGER PRIMARY KEY,
+ child_id INTEGER REFERENCES children(id),
+ started_at TEXT NOT NULL DEFAULT (datetime('now')),
+ finished_at TEXT,
+ pages_fetched INTEGER NOT NULL DEFAULT 0,
+ items_found INTEGER NOT NULL DEFAULT 0,
+ ok INTEGER NOT NULL DEFAULT 0,
+ error TEXT
+);
+
+CREATE INDEX IF NOT EXISTS idx_scans_started ON scans(started_at);
+
+-- One row per delivered brief (FR-9, FR-14).
+CREATE TABLE IF NOT EXISTS notifications (
+ id INTEGER PRIMARY KEY,
+ recipient TEXT NOT NULL,
+ summary TEXT NOT NULL,
+ sent_at TEXT,
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
+);
+
+CREATE INDEX IF NOT EXISTS idx_notifications_sent ON notifications(sent_at);
+
+-- Harness session state per child. SECRET: session cookies and tokens live
+-- here, in the database volume only. Never exported, never logged (AGENTS.md
+-- §10 rule 3).
+CREATE TABLE IF NOT EXISTS session (
+ child_id INTEGER PRIMARY KEY REFERENCES children(id),
+ state TEXT NOT NULL,
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
+);
diff --git a/internal/store/store.go b/internal/store/store.go
new file mode 100644
index 0000000..a52b630
--- /dev/null
+++ b/internal/store/store.go
@@ -0,0 +1,271 @@
+// Package store owns the SQLite database (AGENTS.md §7). It is the single
+// source of truth for stored items, scans, notifications and session state.
+package store
+
+import (
+ "context"
+ "database/sql"
+ "embed"
+ "fmt"
+ "io/fs"
+ "sort"
+ "time"
+
+ _ "modernc.org/sqlite" // pure-Go SQLite driver (no cgo)
+)
+
+//go:embed migrations/*.sql
+var migrationFS embed.FS
+
+// Store wraps the database handle.
+type Store struct {
+ db *sql.DB
+}
+
+// Open opens (creating if needed) the SQLite database at path.
+func Open(path string) (*Store, error) {
+ dsn := fmt.Sprintf(
+ "file:%s?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_pragma=foreign_keys(1)&_pragma=synchronous(NORMAL)",
+ path,
+ )
+ db, err := sql.Open("sqlite", dsn)
+ if err != nil {
+ return nil, fmt.Errorf("open sqlite: %w", err)
+ }
+ // modernc/sqlite serialises writes; one connection avoids lock churn.
+ db.SetMaxOpenConns(1)
+ db.SetMaxIdleConns(1)
+ return &Store{db: db}, nil
+}
+
+// DB exposes the handle for read-only queries.
+func (s *Store) DB() *sql.DB { return s.db }
+
+// Ping verifies the database is reachable.
+func (s *Store) Ping(ctx context.Context) error {
+ return s.db.PingContext(ctx)
+}
+
+// Close closes the database.
+func (s *Store) Close() error { return s.db.Close() }
+
+// Migrate applies every embedded migration that has not run yet. It tracks the
+// applied version with PRAGMA user_version, so reruns are safe.
+func (s *Store) Migrate(ctx context.Context) error {
+ files, err := migrationFiles()
+ if err != nil {
+ return err
+ }
+
+ var version int
+ if err := s.db.QueryRowContext(ctx, "PRAGMA user_version").Scan(&version); err != nil {
+ return fmt.Errorf("read user_version: %w", err)
+ }
+
+ for i := version; i < len(files); i++ {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return fmt.Errorf("begin migration %d: %w", i+1, err)
+ }
+ if _, err := tx.ExecContext(ctx, files[i].sql); err != nil {
+ _ = tx.Rollback()
+ return fmt.Errorf("migration %s: %w", files[i].name, err)
+ }
+ if _, err := tx.ExecContext(ctx, fmt.Sprintf("PRAGMA user_version = %d", i+1)); err != nil {
+ _ = tx.Rollback()
+ return fmt.Errorf("set user_version %d: %w", i+1, err)
+ }
+ if err := tx.Commit(); err != nil {
+ return fmt.Errorf("commit migration %s: %w", files[i].name, err)
+ }
+ }
+ return nil
+}
+
+type migration struct {
+ name string
+ sql string
+}
+
+func migrationFiles() ([]migration, error) {
+ entries, err := fs.ReadDir(migrationFS, "migrations")
+ if err != nil {
+ return nil, fmt.Errorf("read migrations: %w", err)
+ }
+ names := make([]string, 0, len(entries))
+ for _, e := range entries {
+ if !e.IsDir() {
+ names = append(names, e.Name())
+ }
+ }
+ sort.Strings(names) // 001_, 002_, ... apply in order
+
+ out := make([]migration, 0, len(names))
+ for _, n := range names {
+ b, err := fs.ReadFile(migrationFS, "migrations/"+n)
+ if err != nil {
+ return nil, fmt.Errorf("read migration %s: %w", n, err)
+ }
+ out = append(out, migration{name: n, sql: string(b)})
+ }
+ return out, nil
+}
+
+// Child is one school child (AGENTS.md §7).
+type Child struct {
+ ID int64
+ Name string
+ Year string
+ CompassID string
+ CreatedAt time.Time
+}
+
+// SeedChildren inserts the given names if they are not present yet. It is
+// idempotent, so it is safe to call on every start. It never deletes a child.
+func (s *Store) SeedChildren(ctx context.Context, names ...string) error {
+ for _, name := range names {
+ if _, err := s.db.ExecContext(ctx,
+ `INSERT INTO children (name) VALUES (?) ON CONFLICT(name) DO NOTHING`, name); err != nil {
+ return fmt.Errorf("seed child %q: %w", name, err)
+ }
+ }
+ return nil
+}
+
+// ListChildren returns every child, oldest first.
+func (s *Store) ListChildren(ctx context.Context) ([]Child, error) {
+ rows, err := s.db.QueryContext(ctx,
+ `SELECT id, name, COALESCE(year, ''), COALESCE(compass_id, ''), created_at
+ FROM children ORDER BY id`)
+ if err != nil {
+ return nil, fmt.Errorf("list children: %w", err)
+ }
+ defer rows.Close()
+
+ var out []Child
+ for rows.Next() {
+ var c Child
+ var created string
+ if err := rows.Scan(&c.ID, &c.Name, &c.Year, &c.CompassID, &created); err != nil {
+ return nil, fmt.Errorf("scan child: %w", err)
+ }
+ c.CreatedAt = parseTime(created)
+ out = append(out, c)
+ }
+ return out, rows.Err()
+}
+
+// Scan is one row of the append-only scan log (FR-13).
+type Scan struct {
+ ID int64 `json:"id"`
+ ChildID *int64 `json:"child_id,omitempty"`
+ ChildName string `json:"child,omitempty"`
+ StartedAt time.Time `json:"started_at"`
+ FinishedAt *time.Time `json:"finished_at,omitempty"`
+ PagesFetched int `json:"pages_fetched"`
+ ItemsFound int `json:"items_found"`
+ OK bool `json:"ok"`
+ Error string `json:"error,omitempty"`
+}
+
+// ScanStatus summarises scan health for the dashboard. It exists so that a
+// failed scan is shown as an explicit failure and never as an empty day
+// (FR-12).
+type ScanStatus struct {
+ // EverRun is false until the first scan is recorded.
+ EverRun bool `json:"ever_run"`
+ // Total is the number of scan rows.
+ Total int `json:"total"`
+ // Failed is the number of rows with ok = 0.
+ Failed int `json:"failed"`
+ // Last is the most recent scan, when one exists.
+ Last *Scan `json:"last,omitempty"`
+}
+
+// LastScan returns the most recent scan row, or nil when none exists.
+func (s *Store) LastScan(ctx context.Context) (*Scan, error) {
+ row := s.db.QueryRowContext(ctx,
+ `SELECT sc.id, sc.child_id, COALESCE(ch.name, ''), sc.started_at,
+ sc.finished_at, sc.pages_fetched, sc.items_found, sc.ok, COALESCE(sc.error, '')
+ FROM scans sc LEFT JOIN children ch ON ch.id = sc.child_id
+ ORDER BY sc.started_at DESC, sc.id DESC LIMIT 1`)
+ sc, err := scanRow(row)
+ if err == sql.ErrNoRows {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ return &sc, nil
+}
+
+// ScanSummary builds the scan health status shown on the dashboard.
+func (s *Store) ScanSummary(ctx context.Context) (ScanStatus, error) {
+ var st ScanStatus
+ if err := s.db.QueryRowContext(ctx,
+ `SELECT COUNT(*), COALESCE(SUM(CASE WHEN ok = 0 THEN 1 ELSE 0 END), 0) FROM scans`).
+ Scan(&st.Total, &st.Failed); err != nil {
+ return st, fmt.Errorf("scan summary: %w", err)
+ }
+ st.EverRun = st.Total > 0
+ last, err := s.LastScan(ctx)
+ if err != nil {
+ return st, err
+ }
+ st.Last = last
+ return st, nil
+}
+
+type rowScanner interface {
+ Scan(dest ...any) error
+}
+
+func scanRow(r rowScanner) (Scan, error) {
+ var sc Scan
+ var childID sql.NullInt64
+ var started string
+ var finished sql.NullString
+ var ok int
+ if err := r.Scan(&sc.ID, &childID, &sc.ChildName, &started, &finished,
+ &sc.PagesFetched, &sc.ItemsFound, &ok, &sc.Error); err != nil {
+ return sc, err
+ }
+ if childID.Valid {
+ sc.ChildID = &childID.Int64
+ }
+ sc.StartedAt = parseTime(started)
+ if finished.Valid {
+ t := parseTime(finished.String)
+ sc.FinishedAt = &t
+ }
+ sc.OK = ok == 1
+ return sc, nil
+}
+
+// parseTime accepts SQLite's default datetime format and RFC3339.
+func parseTime(s string) time.Time {
+ for _, layout := range []string{"2006-01-02 15:04:05", time.RFC3339} {
+ if t, err := time.ParseInLocation(layout, s, time.UTC); err == nil {
+ return t
+ }
+ }
+ return time.Time{}
+}
+
+// RecordScan appends one scan row. It exists so later phases and the tests can
+// prove the fail-loudly path. A non-empty errMsg records a failure even when
+// nothing was fetched.
+func (s *Store) RecordScan(ctx context.Context, childID *int64, pages, items int, ok bool, errMsg string) (int64, error) {
+ okInt := 0
+ if ok {
+ okInt = 1
+ }
+ res, err := s.db.ExecContext(ctx,
+ `INSERT INTO scans (child_id, finished_at, pages_fetched, items_found, ok, error)
+ VALUES (?, datetime('now'), ?, ?, ?, NULLIF(?, ''))`,
+ childID, pages, items, okInt, errMsg)
+ if err != nil {
+ return 0, fmt.Errorf("record scan: %w", err)
+ }
+ return res.LastInsertId()
+}
diff --git a/internal/web/server.go b/internal/web/server.go
new file mode 100644
index 0000000..8d9e831
--- /dev/null
+++ b/internal/web/server.go
@@ -0,0 +1,324 @@
+// Package web is the HTTP surface of the Compass/NHS service: /health, the
+// service's own session login, and the server-rendered HTMX dashboard
+// (AGENTS.md §5, §9).
+package web
+
+import (
+ "context"
+ "embed"
+ "encoding/json"
+ "fmt"
+ "html/template"
+ "io/fs"
+ "log/slog"
+ "net/http"
+ "strings"
+ "time"
+
+ "gitea.lab.audasmedia.com.au/sam/compass_teams_nhs/internal/auth"
+ "gitea.lab.audasmedia.com.au/sam/compass_teams_nhs/internal/config"
+ "gitea.lab.audasmedia.com.au/sam/compass_teams_nhs/internal/store"
+)
+
+//go:embed templates/*.html templates/partials/*.html
+var templateFS embed.FS
+
+//go:embed static
+var staticFS embed.FS
+
+// Server holds the dependencies for the HTTP handlers.
+type Server struct {
+ cfg *config.Config
+ store *store.Store
+ auth *auth.Manager
+ tmpl *template.Template
+ log *slog.Logger
+}
+
+// New builds a Server and parses the embedded templates.
+func New(cfg *config.Config, st *store.Store, am *auth.Manager, log *slog.Logger) (*Server, error) {
+ funcs := template.FuncMap{
+ "year": func() int { return time.Now().Year() },
+ "clock": func() string { return time.Now().Format("15:04:05 MST") },
+ }
+ tmpl, err := template.New("").Funcs(funcs).ParseFS(templateFS,
+ "templates/*.html", "templates/partials/*.html")
+ if err != nil {
+ return nil, fmt.Errorf("parse templates: %w", err)
+ }
+ return &Server{cfg: cfg, store: st, auth: am, tmpl: tmpl, log: log}, nil
+}
+
+// Handler returns the fully wrapped HTTP handler.
+func (s *Server) Handler() http.Handler {
+ mux := http.NewServeMux()
+
+ mux.HandleFunc("GET /health", s.handleHealth)
+ mux.HandleFunc("GET /login", s.handleLoginPage)
+ mux.HandleFunc("POST /login", s.handleLoginSubmit)
+ mux.HandleFunc("POST /logout", s.handleLogout)
+ mux.HandleFunc("GET /{$}", s.requireAuth(s.handleDashboard))
+ mux.HandleFunc("GET /partials/scan-status", s.requireAuth(s.handleScanStatusPartial))
+
+ staticSub, err := fs.Sub(staticFS, "static")
+ if err != nil {
+ panic("web: embedded static dir missing: " + err.Error())
+ }
+ mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.FS(staticSub))))
+
+ return s.recoverer(s.securityHeaders(s.requestLogger(mux)))
+}
+
+// ---------- middleware ----------
+
+type statusRecorder struct {
+ http.ResponseWriter
+ status int
+}
+
+func (r *statusRecorder) WriteHeader(code int) {
+ r.status = code
+ r.ResponseWriter.WriteHeader(code)
+}
+
+func (s *Server) requestLogger(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ start := time.Now()
+ rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
+ next.ServeHTTP(rec, r)
+ s.log.Info("http",
+ "method", r.Method,
+ "path", r.URL.Path,
+ "status", rec.status,
+ "remote", r.RemoteAddr,
+ "duration", time.Since(start).String(),
+ )
+ })
+}
+
+func (s *Server) securityHeaders(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ h := w.Header()
+ h.Set("X-Content-Type-Options", "nosniff")
+ h.Set("X-Frame-Options", "DENY")
+ h.Set("Referrer-Policy", "same-origin")
+ h.Set("Content-Security-Policy",
+ "default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; form-action 'self'; frame-ancestors 'none'")
+ next.ServeHTTP(w, r)
+ })
+}
+
+func (s *Server) recoverer(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ defer func() {
+ if rec := recover(); rec != nil {
+ s.log.Error("panic", "err", rec, "path", r.URL.Path)
+ http.Error(w, "internal server error", http.StatusInternalServerError)
+ }
+ }()
+ next.ServeHTTP(w, r)
+ })
+}
+
+func (s *Server) requireAuth(next http.HandlerFunc) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ if !s.auth.Authenticated(r) {
+ http.Redirect(w, r, "/login", http.StatusSeeOther)
+ return
+ }
+ next(w, r)
+ }
+}
+
+// ---------- handlers ----------
+
+type healthResponse struct {
+ Status string `json:"status"`
+ Service string `json:"service"`
+ Version string `json:"version"`
+ Database string `json:"database"`
+ Scans store.ScanStatus `json:"scans"`
+ Time string `json:"time"`
+}
+
+func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
+ resp := healthResponse{
+ Status: "ok",
+ Service: "compass-teams-nhs",
+ Version: s.cfg.Version,
+ Database: "ok",
+ Time: time.Now().UTC().Format(time.RFC3339),
+ }
+ code := http.StatusOK
+ if err := s.store.Ping(r.Context()); err != nil {
+ resp.Status = "error"
+ resp.Database = "error"
+ code = http.StatusServiceUnavailable
+ }
+ if st, err := s.store.ScanSummary(r.Context()); err == nil {
+ resp.Scans = st
+ }
+
+ w.Header().Set("Content-Type", "application/json; charset=utf-8")
+ w.WriteHeader(code)
+ _ = json.NewEncoder(w).Encode(resp)
+}
+
+type loginData struct {
+ CSRF string
+ Error string
+ Username string
+}
+
+func (s *Server) handleLoginPage(w http.ResponseWriter, r *http.Request) {
+ if s.auth.Authenticated(r) {
+ http.Redirect(w, r, "/", http.StatusSeeOther)
+ return
+ }
+ s.render(w, r, "login.html", loginData{CSRF: s.auth.EnsureCSRF(w, r)})
+}
+
+func (s *Server) handleLoginSubmit(w http.ResponseWriter, r *http.Request) {
+ if err := r.ParseForm(); err != nil {
+ http.Error(w, "bad request", http.StatusBadRequest)
+ return
+ }
+ username := strings.TrimSpace(r.PostFormValue("username"))
+
+ if !s.auth.CheckCSRF(r) {
+ s.log.Warn("login rejected: bad csrf token", "remote", r.RemoteAddr)
+ s.render(w, r, "login.html", loginData{
+ CSRF: s.auth.EnsureCSRF(w, r),
+ Error: "Session expired. Please try again.",
+ Username: username,
+ })
+ return
+ }
+
+ if !s.auth.CheckCredentials(username, r.PostFormValue("password")) {
+ s.log.Warn("login failed", "user", username, "remote", r.RemoteAddr)
+ w.WriteHeader(http.StatusUnauthorized)
+ s.render(w, r, "login.html", loginData{
+ CSRF: s.auth.EnsureCSRF(w, r),
+ Error: "Incorrect username or password.",
+ Username: username,
+ })
+ return
+ }
+
+ s.auth.Issue(w)
+ s.log.Info("login success", "user", username, "remote", r.RemoteAddr)
+ http.Redirect(w, r, "/", http.StatusSeeOther)
+}
+
+func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
+ if err := r.ParseForm(); err != nil {
+ http.Error(w, "bad request", http.StatusBadRequest)
+ return
+ }
+ s.auth.Clear(w)
+ http.Redirect(w, r, "/login", http.StatusSeeOther)
+}
+
+// scanStatusView is the fail-loudly view of scan health (FR-12). It is shared
+// by the dashboard and the HTMX partial.
+type scanStatusView struct {
+ store.ScanStatus
+ // Level is "none", "error", "ok" or "warn". The template never renders an
+ // empty day as "nothing due".
+ Level string
+ Message string
+ LastAt string
+}
+
+func (s *Server) scanStatus(ctx context.Context) scanStatusView {
+ st, err := s.store.ScanSummary(ctx)
+ if err != nil {
+ s.log.Error("scan summary", "err", err)
+ return scanStatusView{Level: "error", Message: "Could not read the scan log: " + err.Error()}
+ }
+ v := scanStatusView{ScanStatus: st}
+ if !st.EverRun {
+ v.Level = "warn"
+ v.Message = "NO SCAN HAS RUN YET — do not read this as “nothing due”."
+ return v
+ }
+ if st.Last != nil && !st.Last.OK {
+ v.Level = "error"
+ v.Message = "SCAN FAILED — the last scan did not complete, so due work is UNKNOWN."
+ v.LastAt = st.Last.StartedAt.Format("Mon 02 Jan 2006 15:04")
+ return v
+ }
+ v.Level = "ok"
+ v.Message = "Last scan completed."
+ if st.Last != nil {
+ v.LastAt = st.Last.StartedAt.Format("Mon 02 Jan 2006 15:04")
+ }
+ return v
+}
+
+type childView struct {
+ store.Child
+}
+
+type dashboardData struct {
+ Title string
+ Username string
+ CSRF string
+ Version string
+ AppEnv string
+ Children []childView
+ Scan scanStatusView
+ ServerUp string
+ ErrMsg string
+}
+
+var serverStarted = time.Now()
+
+func (s *Server) handleDashboard(w http.ResponseWriter, r *http.Request) {
+ ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
+ defer cancel()
+
+ children, err := s.store.ListChildren(ctx)
+ if err != nil {
+ s.log.Error("list children", "err", err)
+ }
+ views := make([]childView, 0, len(children))
+ for _, c := range children {
+ views = append(views, childView{Child: c})
+ }
+
+ s.render(w, r, "dashboard.html", dashboardData{
+ Title: "Dashboard",
+ Username: s.cfg.AdminUsername,
+ CSRF: s.auth.EnsureCSRF(w, r),
+ Version: s.cfg.Version,
+ AppEnv: s.cfg.AppEnv,
+ Children: views,
+ Scan: s.scanStatus(ctx),
+ ServerUp: time.Since(serverStarted).Round(time.Second).String(),
+ ErrMsg: strings.TrimSpace(r.URL.Query().Get("err")),
+ })
+}
+
+func (s *Server) handleScanStatusPartial(w http.ResponseWriter, r *http.Request) {
+ ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
+ defer cancel()
+ s.renderFragment(w, r, "scan-status.html", s.scanStatus(ctx))
+}
+
+func (s *Server) render(w http.ResponseWriter, _ *http.Request, name string, data any) {
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ if err := s.tmpl.ExecuteTemplate(w, name, data); err != nil {
+ s.log.Error("render", "template", name, "err", err)
+ http.Error(w, "template error", http.StatusInternalServerError)
+ }
+}
+
+func (s *Server) renderFragment(w http.ResponseWriter, _ *http.Request, name string, data any) {
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ if err := s.tmpl.ExecuteTemplate(w, name, data); err != nil {
+ s.log.Error("render fragment", "template", name, "err", err)
+ http.Error(w, "template error", http.StatusInternalServerError)
+ }
+}
diff --git a/internal/web/static/app.css b/internal/web/static/app.css
new file mode 100644
index 0000000..11f74fd
--- /dev/null
+++ b/internal/web/static/app.css
@@ -0,0 +1,328 @@
+/* Compass / Teams — Phase 1 UI
+ Built on the Family Home Lab design tokens (tokens.css).
+ Rules: canvas-soft app background, white cards, hairlines, one action blue,
+ pill CTAs, 8px grid, touch targets >= 44px, dark mode from the tokens. */
+
+*, *::before, *::after { box-sizing: border-box; }
+
+html { font-size: 16px; }
+
+body {
+ margin: 0;
+ background: var(--canvas-soft);
+ color: var(--ink-secondary);
+ font: var(--type-body-md);
+ -webkit-font-smoothing: antialiased;
+ min-height: 100dvh;
+}
+
+h1, h2, h3 { margin: 0; color: var(--ink); }
+a { color: var(--primary); text-decoration: none; }
+a:hover { text-decoration: underline; }
+
+/* ---------- Login ---------- */
+
+.login-page {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: var(--space-lg);
+ padding: var(--space-lg);
+ background:
+ radial-gradient(1200px 600px at 15% 0%, #2b3d93 0%, transparent 60%),
+ var(--secondary);
+}
+
+.login-band {
+ width: 100%;
+ max-width: 960px;
+ display: grid;
+ grid-template-columns: 1.1fr 0.9fr;
+ gap: var(--space-xxl);
+ align-items: center;
+ padding: var(--space-xxl) 0;
+}
+
+.login-eyebrow {
+ margin: 0 0 var(--space-sm);
+ font: var(--type-eyebrow);
+ text-transform: uppercase;
+ letter-spacing: 0.14em;
+ color: rgba(255, 255, 255, 0.72);
+}
+
+.login-headline {
+ margin: 0;
+ font: var(--type-display-1);
+ letter-spacing: -1.5px;
+ color: #ffffff;
+}
+
+.login-sub {
+ margin: var(--space-md) 0 0;
+ font: var(--type-body-md);
+ color: rgba(255, 255, 255, 0.78);
+}
+
+.auth-card {
+ background: var(--surface);
+ border-radius: var(--rounded-lg);
+ box-shadow: var(--shadow-level-2);
+ padding: var(--space-xl);
+}
+
+.auth-card__title {
+ font: var(--type-heading-2);
+ margin-bottom: var(--space-lg);
+}
+
+.auth-form { display: grid; gap: var(--space-md); }
+
+.auth-error {
+ margin: 0 0 var(--space-md);
+ padding: var(--space-sm) var(--space-md);
+ border: 1px solid var(--sticker-red);
+ border-left-width: 3px;
+ border-radius: var(--rounded-sm);
+ color: var(--sticker-red);
+ background: color-mix(in srgb, var(--sticker-red) 8%, var(--surface));
+ font: var(--type-body-sm);
+}
+
+.field { display: grid; gap: var(--space-xs); }
+.field__label {
+ font: var(--type-eyebrow);
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ color: var(--ink-muted);
+}
+
+.text-input {
+ width: 100%;
+ min-height: 44px;
+ padding: 10px 12px;
+ font: var(--type-body-md);
+ color: var(--ink);
+ background: var(--surface);
+ border: 1px solid #dddddd;
+ border-radius: var(--rounded-xs);
+}
+[data-theme="dark"] .text-input { border-color: var(--hairline); }
+.text-input:focus {
+ outline: none;
+ border-color: var(--primary);
+ box-shadow: var(--shadow-level-1), 0 0 0 3px color-mix(in srgb, var(--primary) 25%, transparent);
+}
+
+.login-foot {
+ font: var(--type-caption);
+ color: rgba(255, 255, 255, 0.55);
+}
+
+/* ---------- Buttons ---------- */
+
+.button-primary,
+.button-utility {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ min-height: 44px;
+ padding: 10px 20px;
+ font: var(--type-button);
+ cursor: pointer;
+ transition: background 120ms ease, transform 80ms ease, box-shadow 120ms ease;
+}
+.button-primary {
+ border: 0;
+ border-radius: var(--rounded-full);
+ background: var(--primary);
+ color: var(--on-primary);
+}
+.button-primary:active { background: var(--primary-active); transform: scale(0.97); }
+.button-primary:focus-visible {
+ outline: 3px solid color-mix(in srgb, var(--primary) 35%, transparent);
+ outline-offset: 2px;
+}
+
+.button-utility {
+ border: 1px solid var(--hairline);
+ border-radius: var(--rounded-md);
+ background: var(--surface);
+ color: var(--ink);
+ padding: 8px 14px;
+}
+.button-utility:hover { box-shadow: var(--shadow-level-1); }
+
+/* ---------- App shell ---------- */
+
+.app { display: flex; flex-direction: column; min-height: 100dvh; }
+
+.nav-bar {
+ position: sticky;
+ top: 0;
+ z-index: 10;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-md);
+ padding: var(--space-sm) var(--space-lg);
+ background: var(--surface);
+ border-bottom: 1px solid var(--hairline);
+}
+.nav-bar__brand {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-xs);
+ color: var(--ink);
+ font: var(--type-title);
+}
+.nav-bar__brand:hover { text-decoration: none; }
+.nav-bar__mark {
+ width: 12px; height: 12px; border-radius: var(--rounded-full);
+ background: var(--primary);
+ box-shadow: 0 0 0 4px color-mix(in srgb, var(--primary) 18%, transparent);
+}
+.nav-bar__right { display: flex; align-items: center; gap: var(--space-md); }
+.nav-bar__user { font: var(--type-body-sm); color: var(--ink-muted); }
+.nav-bar__logout { margin: 0; }
+
+.container {
+ width: 100%;
+ max-width: var(--container-max);
+ margin: 0 auto;
+ padding: var(--space-xxl) var(--space-lg);
+ display: grid;
+ gap: var(--space-xxl);
+ flex: 1;
+}
+
+.page-head { display: grid; gap: var(--space-xs); }
+.heading-1 { font: var(--type-heading-1); letter-spacing: -0.8px; }
+.heading-2 { font: var(--type-heading-2); }
+.page-head__sub { margin: 0; color: var(--ink-muted); max-width: 62ch; }
+
+.section { display: grid; gap: var(--space-md); }
+.section__head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-sm);
+}
+
+.category-pill {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-xxs);
+ padding: 4px 10px;
+ border-radius: var(--rounded-full);
+ background: var(--surface-2);
+ color: var(--ink-muted);
+ font: var(--type-eyebrow);
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+}
+.dot { width: 7px; height: 7px; border-radius: var(--rounded-full); background: var(--ink-faint); }
+.dot--faint { background: var(--ink-faint); }
+
+/* ---------- Flash ---------- */
+
+.flash {
+ margin: 0;
+ padding: var(--space-sm) var(--space-md);
+ border-radius: var(--rounded-md);
+ border: 1px solid var(--hairline);
+ font: var(--type-body-sm);
+}
+.flash--error {
+ border-color: var(--sticker-red);
+ border-left-width: 3px;
+ color: var(--sticker-red);
+ background: color-mix(in srgb, var(--sticker-red) 8%, var(--surface));
+}
+
+/* ---------- Scan status (FR-12: fail loudly) ---------- */
+
+.scan {
+ display: grid;
+ gap: var(--space-xs);
+ padding: var(--space-md) var(--space-lg);
+ border-radius: var(--rounded-lg);
+ border: 1px solid var(--hairline);
+ border-left-width: 4px;
+ background: var(--surface);
+ box-shadow: var(--shadow-level-1);
+}
+.scan__head { display: flex; align-items: center; justify-content: space-between; gap: var(--space-sm); }
+.scan__pill { background: var(--surface-2); color: var(--ink-muted); }
+.scan__message { margin: 0; font: var(--type-body-md); color: var(--ink-secondary); }
+.scan__meta { margin: 0; font: var(--type-caption); color: var(--ink-muted); }
+
+.scan--ok { border-left-color: var(--sticker-green); }
+.scan--ok .scan__pill { background: color-mix(in srgb, var(--sticker-green) 16%, var(--surface)); color: #0f7a28; }
+.scan--warn { border-left-color: var(--sticker-orange); background: color-mix(in srgb, var(--sticker-orange) 5%, var(--surface)); }
+.scan--warn .scan__pill { background: color-mix(in srgb, var(--sticker-orange) 16%, var(--surface)); color: var(--sticker-orange-deep); }
+.scan--error { border-left-color: var(--sticker-red); background: color-mix(in srgb, var(--sticker-red) 6%, var(--surface)); }
+.scan--error .scan__pill { background: color-mix(in srgb, var(--sticker-red) 16%, var(--surface)); color: var(--sticker-red); }
+.scan--error .scan__message { color: var(--sticker-red); font-weight: 600; }
+
+/* ---------- Children ---------- */
+
+.child-list {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
+ gap: var(--space-md);
+}
+.child-card {
+ display: grid;
+ gap: var(--space-xxs);
+ padding: var(--space-md) var(--space-lg);
+ background: var(--surface);
+ border: 1px solid var(--hairline);
+ border-radius: var(--rounded-lg);
+ box-shadow: var(--shadow-level-1);
+}
+.child-card__name { margin: 0; font: var(--type-title); color: var(--ink); }
+.child-card__meta { margin: 0; font: var(--type-caption); color: var(--ink-muted); }
+.child-card__body { margin: var(--space-xs) 0 0; font: var(--type-body-sm); color: var(--ink-muted); }
+
+.empty-state {
+ display: grid;
+ gap: var(--space-xs);
+ padding: var(--space-xl);
+ text-align: center;
+ background: var(--surface);
+ border: 1px dashed var(--hairline);
+ border-radius: var(--rounded-lg);
+}
+.empty-state__title { margin: 0; font: var(--type-title); color: var(--ink); }
+.empty-state__body { margin: 0; font: var(--type-body-sm); color: var(--ink-muted); }
+
+/* ---------- Footer ---------- */
+
+.app-foot {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: var(--space-xs);
+ padding: var(--space-md) var(--space-lg);
+ border-top: 1px solid var(--hairline);
+ background: var(--surface);
+ font: var(--type-caption);
+ color: var(--ink-muted);
+}
+.app-foot__sep { color: var(--ink-faint); }
+
+/* ---------- Responsive ---------- */
+
+@media (max-width: 760px) {
+ .login-band { grid-template-columns: 1fr; gap: var(--space-xl); text-align: left; }
+ .login-headline { font: var(--type-heading-1); letter-spacing: -0.8px; }
+ .container { padding: var(--space-lg) var(--space-md); gap: var(--space-xl); }
+ .nav-bar { padding: var(--space-sm) var(--space-md); }
+ .nav-bar__user { display: none; }
+ .section__head { flex-wrap: wrap; }
+}
diff --git a/internal/web/static/fonts/inter-400.woff2 b/internal/web/static/fonts/inter-400.woff2
new file mode 100644
index 0000000..33002f1
Binary files /dev/null and b/internal/web/static/fonts/inter-400.woff2 differ
diff --git a/internal/web/static/fonts/inter-500.woff2 b/internal/web/static/fonts/inter-500.woff2
new file mode 100644
index 0000000..03aaea1
Binary files /dev/null and b/internal/web/static/fonts/inter-500.woff2 differ
diff --git a/internal/web/static/fonts/inter-600.woff2 b/internal/web/static/fonts/inter-600.woff2
new file mode 100644
index 0000000..fb50a02
Binary files /dev/null and b/internal/web/static/fonts/inter-600.woff2 differ
diff --git a/internal/web/static/fonts/inter-700.woff2 b/internal/web/static/fonts/inter-700.woff2
new file mode 100644
index 0000000..12b51d7
Binary files /dev/null and b/internal/web/static/fonts/inter-700.woff2 differ
diff --git a/internal/web/static/htmx.min.js b/internal/web/static/htmx.min.js
new file mode 100644
index 0000000..59937d7
--- /dev/null
+++ b/internal/web/static/htmx.min.js
@@ -0,0 +1 @@
+var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=cn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true},parseInterval:null,_:null,version:"2.0.4"};Q.onLoad=j;Q.process=kt;Q.on=ye;Q.off=be;Q.trigger=he;Q.ajax=Rn;Q.find=u;Q.findAll=x;Q.closest=g;Q.remove=z;Q.addClass=K;Q.removeClass=G;Q.toggleClass=W;Q.takeClass=Z;Q.swap=$e;Q.defineExtension=Fn;Q.removeExtension=Bn;Q.logAll=V;Q.logNone=_;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:le,canAccessLocalStorage:B,findThisElement:Se,filterValues:hn,swap:$e,hasAttribute:s,getAttributeValue:te,getClosestAttributeValue:re,getClosestMatch:o,getExpressionVars:En,getHeaders:fn,getInputValues:cn,getInternalData:ie,getSwapSpecification:gn,getTriggerSpecs:st,getTarget:Ee,makeFragment:P,mergeObjects:ce,makeSettleInfo:xn,oobSwap:He,querySelectorExt:ae,settleImmediately:Kt,shouldCancel:ht,triggerEvent:he,triggerErrorEvent:fe,withExtensions:Ft};const r=["get","post","put","delete","patch"];const H=r.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function te(e,t){return ee(e,t)||ee(e,"data-"+t)}function c(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function ne(){return document}function m(e,t){return e.getRootNode?e.getRootNode({composed:t}):ne()}function o(e,t){while(e&&!t(e)){e=c(e)}return e||null}function i(e,t,n){const r=te(t,n);const o=te(t,"hx-disinherit");var i=te(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function re(t,n){let r=null;o(t,function(e){return!!(r=i(t,ue(e),n))});if(r!=="unset"){return r}}function h(e,t){const n=e instanceof Element&&(e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector);return!!n&&n.call(e,t)}function T(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function q(e){const t=new DOMParser;return t.parseFromString(e,"text/html")}function L(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function A(e){const t=ne().createElement("script");se(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function N(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function I(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(N(e)){const t=A(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){O(e)}finally{e.remove()}}})}function P(e){const t=e.replace(/
]*)?>[\s\S]*?<\/head>/i,"");const n=T(t);let r;if(n==="html"){r=new DocumentFragment;const i=q(e);L(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=q(t);L(r,i.body);r.title=i.title}else{const i=q(''+t+"");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){I(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function oe(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function k(e){return typeof e==="function"}function D(e){return t(e,"Object")}function ie(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function M(t){const n=[];if(t){for(let e=0;e=0}function le(e){return e.getRootNode({composed:true})===document}function F(e){return e.trim().split(/\s+/)}function ce(e,t){for(const n in t){if(t.hasOwnProperty(n)){e[n]=t[n]}}return e}function S(e){try{return JSON.parse(e)}catch(e){O(e);return null}}function B(){const e="htmx:localStorageTest";try{localStorage.setItem(e,e);localStorage.removeItem(e);return true}catch(e){return false}}function U(t){try{const e=new URL(t);if(e){t=e.pathname+e.search}if(!/^\/$/.test(t)){t=t.replace(/\/+$/,"")}return t}catch(e){return t}}function e(e){return vn(ne().body,function(){return eval(e)})}function j(t){const e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function V(){Q.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function _(){Q.logger=null}function u(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return u(ne(),e)}}function x(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return x(ne(),e)}}function E(){return window}function z(e,t){e=y(e);if(t){E().setTimeout(function(){z(e);e=null},t)}else{c(e).removeChild(e)}}function ue(e){return e instanceof Element?e:null}function $(e){return e instanceof HTMLElement?e:null}function J(e){return typeof e==="string"?e:null}function f(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function K(e,t,n){e=ue(y(e));if(!e){return}if(n){E().setTimeout(function(){K(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function G(e,t,n){let r=ue(y(e));if(!r){return}if(n){E().setTimeout(function(){G(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function W(e,t){e=y(e);e.classList.toggle(t)}function Z(e,t){e=y(e);se(e.parentElement.children,function(e){G(e,t)});K(ue(e),t)}function g(e,t){e=ue(y(e));if(e&&e.closest){return e.closest(t)}else{do{if(e==null||h(e,t)){return e}}while(e=e&&ue(c(e)));return null}}function l(e,t){return e.substring(0,t.length)===t}function Y(e,t){return e.substring(e.length-t.length)===t}function ge(e){const t=e.trim();if(l(t,"<")&&Y(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function p(t,r,n){if(r.indexOf("global ")===0){return p(t,r.slice(7),true)}t=y(t);const o=[];{let t=0;let n=0;for(let e=0;e"){t--}}if(n0){const r=ge(o.shift());let e;if(r.indexOf("closest ")===0){e=g(ue(t),ge(r.substr(8)))}else if(r.indexOf("find ")===0){e=u(f(t),ge(r.substr(5)))}else if(r==="next"||r==="nextElementSibling"){e=ue(t).nextElementSibling}else if(r.indexOf("next ")===0){e=pe(t,ge(r.substr(5)),!!n)}else if(r==="previous"||r==="previousElementSibling"){e=ue(t).previousElementSibling}else if(r.indexOf("previous ")===0){e=me(t,ge(r.substr(9)),!!n)}else if(r==="document"){e=document}else if(r==="window"){e=window}else if(r==="body"){e=document.body}else if(r==="root"){e=m(t,!!n)}else if(r==="host"){e=t.getRootNode().host}else{s.push(r)}if(e){i.push(e)}}if(s.length>0){const e=s.join(",");const c=f(m(t,!!n));i.push(...M(c.querySelectorAll(e)))}return i}var pe=function(t,e,n){const r=f(m(t,n)).querySelectorAll(e);for(let e=0;e=0;e--){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_FOLLOWING){return o}}};function ae(e,t){if(typeof e!=="string"){return p(e,t)[0]}else{return p(ne().body,e)[0]}}function y(e,t){if(typeof e==="string"){return u(f(t)||document,e)}else{return e}}function xe(e,t,n,r){if(k(t)){return{target:ne().body,event:J(e),listener:t,options:n}}else{return{target:y(e),event:J(t),listener:n,options:r}}}function ye(t,n,r,o){Vn(function(){const e=xe(t,n,r,o);e.target.addEventListener(e.event,e.listener,e.options)});const e=k(n);return e?n:r}function be(t,n,r){Vn(function(){const e=xe(t,n,r);e.target.removeEventListener(e.event,e.listener)});return k(n)?n:r}const ve=ne().createElement("output");function we(e,t){const n=re(e,t);if(n){if(n==="this"){return[Se(e,t)]}else{const r=p(e,n);if(r.length===0){O('The selector "'+n+'" on '+t+" returned no matches!");return[ve]}else{return r}}}}function Se(e,t){return ue(o(e,function(e){return te(ue(e),t)!=null}))}function Ee(e){const t=re(e,"hx-target");if(t){if(t==="this"){return Se(e,"hx-target")}else{return ae(e,t)}}else{const n=ie(e);if(n.boosted){return ne().body}else{return e}}}function Ce(t){const n=Q.config.attributesToSettle;for(let e=0;e0){s=e.substring(0,e.indexOf(":"));n=e.substring(e.indexOf(":")+1)}else{s=e}o.removeAttribute("hx-swap-oob");o.removeAttribute("data-hx-swap-oob");const r=p(t,n,false);if(r){se(r,function(e){let t;const n=o.cloneNode(true);t=ne().createDocumentFragment();t.appendChild(n);if(!Re(s,e)){t=f(n)}const r={shouldSwap:true,target:e,fragment:t};if(!he(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){qe(t);_e(s,e,e,t,i);Te()}se(i.elts,function(e){he(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);fe(ne().body,"htmx:oobErrorNoTarget",{content:o})}return e}function Te(){const e=u("#--htmx-preserve-pantry--");if(e){for(const t of[...e.children]){const n=u("#"+t.id);n.parentNode.moveBefore(t,n);n.remove()}e.remove()}}function qe(e){se(x(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=te(e,"id");const n=ne().getElementById(t);if(n!=null){if(e.moveBefore){let e=u("#--htmx-preserve-pantry--");if(e==null){ne().body.insertAdjacentHTML("afterend","");e=u("#--htmx-preserve-pantry--")}e.moveBefore(n,null)}else{e.parentNode.replaceChild(n,e)}}})}function Le(l,e,c){se(e.querySelectorAll("[id]"),function(t){const n=ee(t,"id");if(n&&n.length>0){const r=n.replace("'","\\'");const o=t.tagName.replace(":","\\:");const e=f(l);const i=e&&e.querySelector(o+"[id='"+r+"']");if(i&&i!==e){const s=t.cloneNode();Oe(t,i);c.tasks.push(function(){Oe(t,s)})}}})}function Ae(e){return function(){G(e,Q.config.addedClass);kt(ue(e));Ne(f(e));he(e,"htmx:load")}}function Ne(e){const t="[autofocus]";const n=$(h(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function a(e,t,n,r){Le(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;K(ue(o),Q.config.addedClass);e.insertBefore(o,t);if(o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE){r.tasks.push(Ae(o))}}}function Ie(e,t){let n=0;while(n0}function $e(e,t,r,o){if(!o){o={}}e=y(e);const i=o.contextElement?m(o.contextElement,false):ne();const n=document.activeElement;let s={};try{s={elt:n,start:n?n.selectionStart:null,end:n?n.selectionEnd:null}}catch(e){}const l=xn(e);if(r.swapStyle==="textContent"){e.textContent=t}else{let n=P(t);l.title=n.title;if(o.selectOOB){const u=o.selectOOB.split(",");for(let t=0;t0){E().setTimeout(c,r.settleDelay)}else{c()}}function Je(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=S(r);for(const i in o){if(o.hasOwnProperty(i)){let e=o[i];if(D(e)){n=e.target!==undefined?e.target:n}else{e={value:e}}he(n,i,e)}}}else{const s=r.split(",");for(let e=0;e0){const s=o[0];if(s==="]"){e--;if(e===0){if(n===null){t=t+"true"}o.shift();t+=")})";try{const l=vn(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){fe(ne().body,"htmx:syntax:error",{error:e,source:t});return null}}}else if(s==="["){e++}if(tt(s,n,i)){t+="(("+i+"."+s+") ? ("+i+"."+s+") : (window."+s+"))"}else{t=t+s}n=o.shift()}}}function C(e,t){let n="";while(e.length>0&&!t.test(e[0])){n+=e.shift()}return n}function rt(e){let t;if(e.length>0&&Ye.test(e[0])){e.shift();t=C(e,Qe).trim();e.shift()}else{t=C(e,v)}return t}const ot="input, textarea, select";function it(e,t,n){const r=[];const o=et(t);do{C(o,w);const l=o.length;const c=C(o,/[,\[\s]/);if(c!==""){if(c==="every"){const u={trigger:"every"};C(o,w);u.pollInterval=d(C(o,/[,\[\s]/));C(o,w);var i=nt(e,o,"event");if(i){u.eventFilter=i}r.push(u)}else{const a={trigger:c};var i=nt(e,o,"event");if(i){a.eventFilter=i}C(o,w);while(o.length>0&&o[0]!==","){const f=o.shift();if(f==="changed"){a.changed=true}else if(f==="once"){a.once=true}else if(f==="consume"){a.consume=true}else if(f==="delay"&&o[0]===":"){o.shift();a.delay=d(C(o,v))}else if(f==="from"&&o[0]===":"){o.shift();if(Ye.test(o[0])){var s=rt(o)}else{var s=C(o,v);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const h=rt(o);if(h.length>0){s+=" "+h}}}a.from=s}else if(f==="target"&&o[0]===":"){o.shift();a.target=rt(o)}else if(f==="throttle"&&o[0]===":"){o.shift();a.throttle=d(C(o,v))}else if(f==="queue"&&o[0]===":"){o.shift();a.queue=C(o,v)}else if(f==="root"&&o[0]===":"){o.shift();a[f]=rt(o)}else if(f==="threshold"&&o[0]===":"){o.shift();a[f]=C(o,v)}else{fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}r.push(a)}}if(o.length===l){fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function st(e){const t=te(e,"hx-trigger");let n=[];if(t){const r=Q.config.triggerSpecsCache;n=r&&r[t]||it(e,t,r)}if(n.length>0){return n}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,ot)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function lt(e){ie(e).cancelled=true}function ct(e,t,n){const r=ie(e);r.timeout=E().setTimeout(function(){if(le(e)&&r.cancelled!==true){if(!gt(n,e,Mt("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ct(e,t,n)}},n.pollInterval)}function ut(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function at(e){return g(e,Q.config.disableSelector)}function ft(t,n,e){if(t instanceof HTMLAnchorElement&&ut(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"&&String(ee(t,"method")).toLowerCase()!=="dialog"){n.boosted=true;let r,o;if(t.tagName==="A"){r="get";o=ee(t,"href")}else{const i=ee(t,"method");r=i?i.toLowerCase():"get";o=ee(t,"action");if(o==null||o===""){o=ne().location.href}if(r==="get"&&o.includes("?")){o=o.replace(/\?[^#]+/,"")}}e.forEach(function(e){pt(t,function(e,t){const n=ue(e);if(at(n)){b(n);return}de(r,o,n,t)},n,e,true)})}}function ht(e,t){const n=ue(t);if(!n){return false}if(e.type==="submit"||e.type==="click"){if(n.tagName==="FORM"){return true}if(h(n,'input[type="submit"], button')&&(h(n,"[form]")||g(n,"form")!==null)){return true}if(n instanceof HTMLAnchorElement&&n.href&&(n.getAttribute("href")==="#"||n.getAttribute("href").indexOf("#")!==0)){return true}}return false}function dt(e,t){return ie(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function gt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;fe(ne().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function pt(l,c,e,u,a){const f=ie(l);let t;if(u.from){t=p(l,u.from)}else{t=[l]}if(u.changed){if(!("lastValue"in f)){f.lastValue=new WeakMap}t.forEach(function(e){if(!f.lastValue.has(u)){f.lastValue.set(u,new WeakMap)}f.lastValue.get(u).set(e,e.value)})}se(t,function(i){const s=function(e){if(!le(l)){i.removeEventListener(u.trigger,s);return}if(dt(l,e)){return}if(a||ht(e,l)){e.preventDefault()}if(gt(u,l,e)){return}const t=ie(e);t.triggerSpec=u;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(l)<0){t.handledFor.push(l);if(u.consume){e.stopPropagation()}if(u.target&&e.target){if(!h(ue(e.target),u.target)){return}}if(u.once){if(f.triggeredOnce){return}else{f.triggeredOnce=true}}if(u.changed){const n=event.target;const r=n.value;const o=f.lastValue.get(u);if(o.has(n)&&o.get(n)===r){return}o.set(n,r)}if(f.delayed){clearTimeout(f.delayed)}if(f.throttle){return}if(u.throttle>0){if(!f.throttle){he(l,"htmx:trigger");c(l,e);f.throttle=E().setTimeout(function(){f.throttle=null},u.throttle)}}else if(u.delay>0){f.delayed=E().setTimeout(function(){he(l,"htmx:trigger");c(l,e)},u.delay)}else{he(l,"htmx:trigger");c(l,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:u.trigger,listener:s,on:i});i.addEventListener(u.trigger,s)})}let mt=false;let xt=null;function yt(){if(!xt){xt=function(){mt=true};window.addEventListener("scroll",xt);window.addEventListener("resize",xt);setInterval(function(){if(mt){mt=false;se(ne().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){bt(e)})}},200)}}function bt(e){if(!s(e,"data-hx-revealed")&&X(e)){e.setAttribute("data-hx-revealed","true");const t=ie(e);if(t.initHash){he(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){he(e,"revealed")},{once:true})}}}function vt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;he(e,"htmx:trigger");t(e)}};if(r>0){E().setTimeout(o,r)}else{o()}}function wt(t,n,e){let i=false;se(r,function(r){if(s(t,"hx-"+r)){const o=te(t,"hx-"+r);i=true;n.path=o;n.verb=r;e.forEach(function(e){St(t,e,n,function(e,t){const n=ue(e);if(g(n,Q.config.disableSelector)){b(n);return}de(r,o,n,t)})})}});return i}function St(r,e,t,n){if(e.trigger==="revealed"){yt();pt(r,n,t,e);bt(ue(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=ae(r,e.root)}if(e.threshold){o.threshold=parseFloat(e.threshold)}const i=new IntersectionObserver(function(t){for(let e=0;e0){t.polling=true;ct(ue(r),n,e)}else{pt(r,n,t,e)}}function Et(e){const t=ue(e);if(!t){return false}const n=t.attributes;for(let e=0;e", "+e).join(""));return o}else{return[]}}function Tt(e){const t=g(ue(e.target),"button, input[type='submit']");const n=Lt(e);if(n){n.lastButtonClicked=t}}function qt(e){const t=Lt(e);if(t){t.lastButtonClicked=null}}function Lt(e){const t=g(ue(e.target),"button, input[type='submit']");if(!t){return}const n=y("#"+ee(t,"form"),t.getRootNode())||g(t,"form");if(!n){return}return ie(n)}function At(e){e.addEventListener("click",Tt);e.addEventListener("focusin",Tt);e.addEventListener("focusout",qt)}function Nt(t,e,n){const r=ie(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){vn(t,function(){if(at(t)){return}if(!o){o=new Function("event",n)}o.call(t,e)})};t.addEventListener(e,i);r.onHandlers.push({event:e,listener:i})}function It(t){ke(t);for(let e=0;eQ.config.historyCacheSize){i.shift()}while(i.length>0){try{localStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(ne().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Vt(t){if(!B()){return null}t=U(t);const n=S(localStorage.getItem("htmx-history-cache"))||[];for(let e=0;e=200&&this.status<400){he(ne().body,"htmx:historyCacheMissLoad",i);const e=P(this.response);const t=e.querySelector("[hx-history-elt],[data-hx-history-elt]")||e;const n=Ut();const r=xn(n);kn(e.title);qe(e);Ve(n,t,r);Te();Kt(r.tasks);Bt=o;he(ne().body,"htmx:historyRestore",{path:o,cacheMiss:true,serverResponse:this.response})}else{fe(ne().body,"htmx:historyCacheMissLoadError",i)}};e.send()}function Wt(e){zt();e=e||location.pathname+location.search;const t=Vt(e);if(t){const n=P(t.content);const r=Ut();const o=xn(r);kn(t.title);qe(n);Ve(r,n,o);Te();Kt(o.tasks);E().setTimeout(function(){window.scrollTo(0,t.scroll)},0);Bt=e;he(ne().body,"htmx:historyRestore",{path:e,item:t})}else{if(Q.config.refreshOnHistoryMiss){window.location.reload(true)}else{Gt(e)}}}function Zt(e){let t=we(e,"hx-indicator");if(t==null){t=[e]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.classList.add.call(e.classList,Q.config.requestClass)});return t}function Yt(e){let t=we(e,"hx-disabled-elt");if(t==null){t=[]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","");e.setAttribute("data-disabled-by-htmx","")});return t}function Qt(e,t){se(e.concat(t),function(e){const t=ie(e);t.requestCount=(t.requestCount||1)-1});se(e,function(e){const t=ie(e);if(t.requestCount===0){e.classList.remove.call(e.classList,Q.config.requestClass)}});se(t,function(e){const t=ie(e);if(t.requestCount===0){e.removeAttribute("disabled");e.removeAttribute("data-disabled-by-htmx")}})}function en(t,n){for(let e=0;en.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);se(e,e=>r.append(t,e))}}function on(t,n,r,o,i){if(o==null||en(t,o)){return}else{t.push(o)}if(tn(o)){const s=ee(o,"name");let e=o.value;if(o instanceof HTMLSelectElement&&o.multiple){e=M(o.querySelectorAll("option:checked")).map(function(e){return e.value})}if(o instanceof HTMLInputElement&&o.files){e=M(o.files)}nn(s,e,n);if(i){sn(o,r)}}if(o instanceof HTMLFormElement){se(o.elements,function(e){if(t.indexOf(e)>=0){rn(e.name,e.value,n)}else{t.push(e)}if(i){sn(e,r)}});new FormData(o).forEach(function(e,t){if(e instanceof File&&e.name===""){return}nn(t,e,n)})}}function sn(e,t){const n=e;if(n.willValidate){he(n,"htmx:validation:validate");if(!n.checkValidity()){t.push({elt:n,message:n.validationMessage,validity:n.validity});he(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})}}}function ln(n,e){for(const t of e.keys()){n.delete(t)}e.forEach(function(e,t){n.append(t,e)});return n}function cn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=ie(e);if(s.lastButtonClicked&&!le(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||te(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){on(n,o,i,g(e,"form"),l)}on(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&ee(e,"type")==="submit"){const u=s.lastButtonClicked||e;const a=ee(u,"name");nn(a,u.value,o)}const c=we(e,"hx-include");se(c,function(e){on(n,r,i,ue(e),l);if(!h(e,"form")){se(f(e).querySelectorAll(ot),function(e){on(n,r,i,e,l)})}});ln(r,o);return{errors:i,formData:r,values:An(r)}}function un(e,t,n){if(e!==""){e+="&"}if(String(n)==="[object Object]"){n=JSON.stringify(n)}const r=encodeURIComponent(n);e+=encodeURIComponent(t)+"="+r;return e}function an(e){e=qn(e);let n="";e.forEach(function(e,t){n=un(n,t,e)});return n}function fn(e,t,n){const r={"HX-Request":"true","HX-Trigger":ee(e,"id"),"HX-Trigger-Name":ee(e,"name"),"HX-Target":te(t,"id"),"HX-Current-URL":ne().location.href};bn(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(ie(e).boosted){r["HX-Boosted"]="true"}return r}function hn(n,e){const t=re(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){se(t.slice(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;se(t.split(","),function(t){t=t.trim();if(n.has(t)){n.getAll(t).forEach(function(e){r.append(t,e)})}});return r}}else{return n}}function dn(e){return!!ee(e,"href")&&ee(e,"href").indexOf("#")>=0}function gn(e,t){const n=t||re(e,"hx-swap");const r={swapStyle:ie(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&ie(e).boosted&&!dn(e)){r.show="top"}if(n){const s=F(n);if(s.length>0){for(let e=0;e0?o.join(":"):null;r.scroll=u;r.scrollTarget=i}else if(l.indexOf("show:")===0){const a=l.slice(5);var o=a.split(":");const f=o.pop();var i=o.length>0?o.join(":"):null;r.show=f;r.showTarget=i}else if(l.indexOf("focus-scroll:")===0){const h=l.slice("focus-scroll:".length);r.focusScroll=h=="true"}else if(e==0){r.swapStyle=l}else{O("Unknown modifier in hx-swap: "+l)}}}}return r}function pn(e){return re(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function mn(t,n,r){let o=null;Ft(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(pn(n)){return ln(new FormData,qn(r))}else{return an(r)}}}function xn(e){return{tasks:[],elts:[e]}}function yn(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=ue(ae(n,t.scrollTarget))}if(t.scroll==="top"&&(n||o)){o=o||n;o.scrollTop=0}if(t.scroll==="bottom"&&(r||o)){o=o||r;o.scrollTop=o.scrollHeight}}if(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=ue(ae(n,e))}if(t.show==="top"&&(n||o)){o=o||n;o.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(r||o)){o=o||r;o.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function bn(r,e,o,i){if(i==null){i={}}if(r==null){return i}const s=te(r,e);if(s){let e=s.trim();let t=o;if(e==="unset"){return null}if(e.indexOf("javascript:")===0){e=e.slice(11);t=true}else if(e.indexOf("js:")===0){e=e.slice(3);t=true}if(e.indexOf("{")!==0){e="{"+e+"}"}let n;if(t){n=vn(r,function(){return Function("return ("+e+")")()},{})}else{n=S(e)}for(const l in n){if(n.hasOwnProperty(l)){if(i[l]==null){i[l]=n[l]}}}}return bn(ue(c(r)),e,o,i)}function vn(e,t,n){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return n}}function wn(e,t){return bn(e,"hx-vars",true,t)}function Sn(e,t){return bn(e,"hx-vals",false,t)}function En(e){return ce(wn(e),Sn(e))}function Cn(t,n,r){if(r!==null){try{t.setRequestHeader(n,r)}catch(e){t.setRequestHeader(n,encodeURIComponent(r));t.setRequestHeader(n+"-URI-AutoEncoded","true")}}}function On(t){if(t.responseURL&&typeof URL!=="undefined"){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(ne().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function R(e,t){return t.test(e.getAllResponseHeaders())}function Rn(t,n,r){t=t.toLowerCase();if(r){if(r instanceof Element||typeof r==="string"){return de(t,n,null,null,{targetOverride:y(r)||ve,returnPromise:true})}else{let e=y(r.target);if(r.target&&!e||r.source&&!e&&!y(r.source)){e=ve}return de(t,n,y(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:e,swapOverride:r.swap,select:r.select,returnPromise:true})}}else{return de(t,n,null,null,{returnPromise:true})}}function Hn(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function Tn(e,t,n){let r;let o;if(typeof URL==="function"){o=new URL(t,document.location.href);const i=document.location.origin;r=i===o.origin}else{o=t;r=l(t,document.location.origin)}if(Q.config.selfRequestsOnly){if(!r){return false}}return he(e,"htmx:validateUrl",ce({url:o,sameHost:r},n))}function qn(e){if(e instanceof FormData)return e;const t=new FormData;for(const n in e){if(e.hasOwnProperty(n)){if(e[n]&&typeof e[n].forEach==="function"){e[n].forEach(function(e){t.append(n,e)})}else if(typeof e[n]==="object"&&!(e[n]instanceof Blob)){t.append(n,JSON.stringify(e[n]))}else{t.append(n,e[n])}}}return t}function Ln(r,o,e){return new Proxy(e,{get:function(t,e){if(typeof e==="number")return t[e];if(e==="length")return t.length;if(e==="push"){return function(e){t.push(e);r.append(o,e)}}if(typeof t[e]==="function"){return function(){t[e].apply(t,arguments);r.delete(o);t.forEach(function(e){r.append(o,e)})}}if(t[e]&&t[e].length===1){return t[e][0]}else{return t[e]}},set:function(e,t,n){e[t]=n;r.delete(o);e.forEach(function(e){r.append(o,e)});return true}})}function An(o){return new Proxy(o,{get:function(e,t){if(typeof t==="symbol"){const r=Reflect.get(e,t);if(typeof r==="function"){return function(){return r.apply(o,arguments)}}else{return r}}if(t==="toJSON"){return()=>Object.fromEntries(o)}if(t in e){if(typeof e[t]==="function"){return function(){return o[t].apply(o,arguments)}}else{return e[t]}}const n=o.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Ln(e,t,n)}},set:function(t,n,e){if(typeof n!=="string"){return false}t.delete(n);if(e&&typeof e.forEach==="function"){e.forEach(function(e){t.append(n,e)})}else if(typeof e==="object"&&!(e instanceof Blob)){t.append(n,JSON.stringify(e))}else{t.append(n,e)}return true},deleteProperty:function(e,t){if(typeof t==="string"){e.delete(t)}return true},ownKeys:function(e){return Reflect.ownKeys(Object.fromEntries(e))},getOwnPropertyDescriptor:function(e,t){return Reflect.getOwnPropertyDescriptor(Object.fromEntries(e),t)}})}function de(t,n,r,o,i,D){let s=null;let l=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var e=new Promise(function(e,t){s=e;l=t})}if(r==null){r=ne().body}const M=i.handler||Dn;const X=i.select||null;if(!le(r)){oe(s);return e}const c=i.targetOverride||ue(Ee(r));if(c==null||c==ve){fe(r,"htmx:targetError",{target:te(r,"hx-target")});oe(l);return e}let u=ie(r);const a=u.lastButtonClicked;if(a){const L=ee(a,"formaction");if(L!=null){n=L}const A=ee(a,"formmethod");if(A!=null){if(A.toLowerCase()!=="dialog"){t=A}}}const f=re(r,"hx-confirm");if(D===undefined){const K=function(e){return de(t,n,r,o,i,!!e)};const G={target:c,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:f};if(he(r,"htmx:confirm",G)===false){oe(s);return e}}let h=r;let d=re(r,"hx-sync");let g=null;let F=false;if(d){const N=d.split(":");const I=N[0].trim();if(I==="this"){h=Se(r,"hx-sync")}else{h=ue(ae(r,I))}d=(N[1]||"drop").trim();u=ie(h);if(d==="drop"&&u.xhr&&u.abortable!==true){oe(s);return e}else if(d==="abort"){if(u.xhr){oe(s);return e}else{F=true}}else if(d==="replace"){he(h,"htmx:abort")}else if(d.indexOf("queue")===0){const W=d.split(" ");g=(W[1]||"last").trim()}}if(u.xhr){if(u.abortable){he(h,"htmx:abort")}else{if(g==null){if(o){const P=ie(o);if(P&&P.triggerSpec&&P.triggerSpec.queue){g=P.triggerSpec.queue}}if(g==null){g="last"}}if(u.queuedRequests==null){u.queuedRequests=[]}if(g==="first"&&u.queuedRequests.length===0){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="all"){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="last"){u.queuedRequests=[];u.queuedRequests.push(function(){de(t,n,r,o,i)})}oe(s);return e}}const p=new XMLHttpRequest;u.xhr=p;u.abortable=F;const m=function(){u.xhr=null;u.abortable=false;if(u.queuedRequests!=null&&u.queuedRequests.length>0){const e=u.queuedRequests.shift();e()}};const B=re(r,"hx-prompt");if(B){var x=prompt(B);if(x===null||!he(r,"htmx:prompt",{prompt:x,target:c})){oe(s);m();return e}}if(f&&!D){if(!confirm(f)){oe(s);m();return e}}let y=fn(r,c,x);if(t!=="get"&&!pn(r)){y["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){y=ce(y,i.headers)}const U=cn(r,t);let b=U.errors;const j=U.formData;if(i.values){ln(j,qn(i.values))}const V=qn(En(r));const v=ln(j,V);let w=hn(v,r);if(Q.config.getCacheBusterParam&&t==="get"){w.set("org.htmx.cache-buster",ee(c,"id")||"true")}if(n==null||n===""){n=ne().location.href}const S=bn(r,"hx-request");const _=ie(r).boosted;let E=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:_,useUrlParams:E,formData:w,parameters:An(w),unfilteredFormData:v,unfilteredParameters:An(v),headers:y,target:c,verb:t,errors:b,withCredentials:i.credentials||S.credentials||Q.config.withCredentials,timeout:i.timeout||S.timeout||Q.config.timeout,path:n,triggeringEvent:o};if(!he(r,"htmx:configRequest",C)){oe(s);m();return e}n=C.path;t=C.verb;y=C.headers;w=qn(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){he(r,"htmx:validation:halted",C);oe(s);m();return e}const z=n.split("#");const $=z[0];const O=z[1];let R=n;if(E){R=$;const Z=!w.keys().next().done;if(Z){if(R.indexOf("?")<0){R+="?"}else{R+="&"}R+=an(w);if(O){R+="#"+O}}}if(!Tn(r,R,C)){fe(r,"htmx:invalidPath",C);oe(l);return e}p.open(t.toUpperCase(),R,true);p.overrideMimeType("text/html");p.withCredentials=C.withCredentials;p.timeout=C.timeout;if(S.noHeaders){}else{for(const k in y){if(y.hasOwnProperty(k)){const Y=y[k];Cn(p,k,Y)}}}const H={xhr:p,target:c,requestConfig:C,etc:i,boosted:_,select:X,pathInfo:{requestPath:n,finalRequestPath:R,responsePath:null,anchor:O}};p.onload=function(){try{const t=Hn(r);H.pathInfo.responsePath=On(p);M(r,H);if(H.keepIndicators!==true){Qt(T,q)}he(r,"htmx:afterRequest",H);he(r,"htmx:afterOnLoad",H);if(!le(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(le(n)){e=n}}if(e){he(e,"htmx:afterRequest",H);he(e,"htmx:afterOnLoad",H)}}oe(s);m()}catch(e){fe(r,"htmx:onLoadError",ce({error:e},H));throw e}};p.onerror=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendError",H);oe(l);m()};p.onabort=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendAbort",H);oe(l);m()};p.ontimeout=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:timeout",H);oe(l);m()};if(!he(r,"htmx:beforeRequest",H)){oe(s);m();return e}var T=Zt(r);var q=Yt(r);se(["loadstart","loadend","progress","abort"],function(t){se([p,p.upload],function(e){e.addEventListener(t,function(e){he(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});he(r,"htmx:beforeSend",H);const J=E?null:mn(p,r,w);p.send(J);return e}function Nn(e,t){const n=t.xhr;let r=null;let o=null;if(R(n,/HX-Push:/i)){r=n.getResponseHeader("HX-Push");o="push"}else if(R(n,/HX-Push-Url:/i)){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(R(n,/HX-Replace-Url:/i)){r=n.getResponseHeader("HX-Replace-Url");o="replace"}if(r){if(r==="false"){return{}}else{return{type:o,path:r}}}const i=t.pathInfo.finalRequestPath;const s=t.pathInfo.responsePath;const l=re(e,"hx-push-url");const c=re(e,"hx-replace-url");const u=ie(e).boosted;let a=null;let f=null;if(l){a="push";f=l}else if(c){a="replace";f=c}else if(u){a="push";f=s||i}if(f){if(f==="false"){return{}}if(f==="true"){f=s||i}if(t.pathInfo.anchor&&f.indexOf("#")===-1){f=f+"#"+t.pathInfo.anchor}return{type:a,path:f}}else{return{}}}function In(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function Pn(e){for(var t=0;t0){E().setTimeout(e,x.swapDelay)}else{e()}}if(f){fe(o,"htmx:responseError",ce({error:"Response Status Error Code "+s.status+" from "+i.pathInfo.requestPath},i))}}const Mn={};function Xn(){return{init:function(e){return null},getSelectors:function(){return null},onEvent:function(e,t){return true},transformResponse:function(e,t,n){return e},isInlineSwap:function(e){return false},handleSwap:function(e,t,n,r){return false},encodeParameters:function(e,t,n){return null}}}function Fn(e,t){if(t.init){t.init(n)}Mn[e]=ce(Xn(),t)}function Bn(e){delete Mn[e]}function Un(e,n,r){if(n==undefined){n=[]}if(e==undefined){return n}if(r==undefined){r=[]}const t=te(e,"hx-ext");if(t){se(t.split(","),function(e){e=e.replace(/ /g,"");if(e.slice(0,7)=="ignore:"){r.push(e.slice(7));return}if(r.indexOf(e)<0){const t=Mn[e];if(t&&n.indexOf(t)<0){n.push(t)}}})}return Un(ue(c(e)),n,r)}var jn=false;ne().addEventListener("DOMContentLoaded",function(){jn=true});function Vn(e){if(jn||ne().readyState==="complete"){e()}else{ne().addEventListener("DOMContentLoaded",e)}}function _n(){if(Q.config.includeIndicatorStyles!==false){const e=Q.config.inlineStyleNonce?` nonce="${Q.config.inlineStyleNonce}"`:"";ne().head.insertAdjacentHTML("beforeend","")}}function zn(){const e=ne().querySelector('meta[name="htmx-config"]');if(e){return S(e.content)}else{return null}}function $n(){const e=zn();if(e){Q.config=ce(Q.config,e)}}Vn(function(){$n();_n();let e=ne().body;kt(e);const t=ne().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.target;const n=ie(t);if(n&&n.xhr){n.xhr.abort()}});const n=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){Wt();se(t,function(e){he(e,"htmx:restored",{document:ne(),triggerEvent:he})})}else{if(n){n(e)}}};E().setTimeout(function(){he(e,"htmx:load",{});e=null},0)});return Q}();
\ No newline at end of file
diff --git a/internal/web/static/theme.js b/internal/web/static/theme.js
new file mode 100644
index 0000000..93efc6f
--- /dev/null
+++ b/internal/web/static/theme.js
@@ -0,0 +1,55 @@
+// Theme controller. The design tokens ship both palettes; nothing switches
+// between them unless this runs. It follows the OS preference by default and
+// remembers an explicit choice. Loaded with defer from /static/, so it is
+// allowed by the page's `script-src 'self'` policy (no inline script).
+(function () {
+ "use strict";
+ var KEY = "webrestrict.theme";
+ var root = document.documentElement;
+ var media = window.matchMedia("(prefers-color-scheme: dark)");
+ var stored = null;
+ try {
+ stored = window.localStorage.getItem(KEY);
+ } catch (e) {
+ stored = null;
+ }
+
+ function apply() {
+ var theme = stored || (media.matches ? "dark" : "light");
+ root.setAttribute("data-theme", theme);
+ var buttons = document.querySelectorAll("[data-theme-toggle]");
+ for (var i = 0; i < buttons.length; i++) {
+ buttons[i].textContent = theme === "dark" ? "Light" : "Dark";
+ buttons[i].setAttribute(
+ "aria-label",
+ "Switch to " + (theme === "dark" ? "light" : "dark") + " theme"
+ );
+ }
+ }
+
+ document.addEventListener("click", function (event) {
+ var target = event.target && event.target.closest
+ ? event.target.closest("[data-theme-toggle]")
+ : null;
+ if (!target) {
+ return;
+ }
+ stored = root.getAttribute("data-theme") === "dark" ? "light" : "dark";
+ try {
+ window.localStorage.setItem(KEY, stored);
+ } catch (e) {
+ /* private mode: the choice just does not persist */
+ }
+ apply();
+ });
+
+ if (media.addEventListener) {
+ media.addEventListener("change", function () {
+ if (!stored) {
+ apply();
+ }
+ });
+ }
+
+ apply();
+})();
diff --git a/internal/web/static/tokens.css b/internal/web/static/tokens.css
new file mode 100644
index 0000000..1516a04
--- /dev/null
+++ b/internal/web/static/tokens.css
@@ -0,0 +1,110 @@
+/* ============================================================
+ Family Home Lab — Design Tokens
+ Source: DESIGN.md (Notion design language)
+ Only structural/semantic tokens here. All values map 1:1.
+ ============================================================ */
+
+/* Inter (@fontsource) — self-hosted substitute for NotionInter */
+@font-face { font-family: "Inter"; font-style: normal; font-weight: 400; font-display: swap; src: url("/static/fonts/inter-400.woff2") format("woff2"); }
+@font-face { font-family: "Inter"; font-style: normal; font-weight: 500; font-display: swap; src: url("/static/fonts/inter-500.woff2") format("woff2"); }
+@font-face { font-family: "Inter"; font-style: normal; font-weight: 600; font-display: swap; src: url("/static/fonts/inter-600.woff2") format("woff2"); }
+@font-face { font-family: "Inter"; font-style: normal; font-weight: 700; font-display: swap; src: url("/static/fonts/inter-700.woff2") format("woff2"); }
+
+:root {
+ /* --- Surface --- */
+ --canvas-soft: #f6f5f4;
+ --surface: #ffffff;
+ --surface-2: #f2f2f1;
+ --hairline: #e6e6e6;
+
+ /* --- Text --- */
+ --ink: #000000;
+ --ink-secondary: #31302e;
+ --ink-muted: #615d59;
+ --ink-faint: #a39e98;
+
+ /* --- Structural accents --- */
+ --primary: #0075de; /* the ONLY action colour */
+ --primary-active: #005bab;
+ --on-primary: #ffffff;
+ --secondary: #213183; /* deep indigo — login band + greeting only */
+
+ /* --- Sticker palette (decorative only) --- */
+ --sticker-sky: #62aef0; /* chat */
+ --sticker-purple: #d6b6f6; /* image */
+ --sticker-pink: #ff64c8; /* video */
+ --sticker-orange: #dd5b00; /* audio */
+ --sticker-teal: #2a9d99; /* docs */
+ --sticker-green: #1aae39; /* status: online/saved */
+ --sticker-red: #d33a2b; /* status: failed / error (ON_OFF.md decision) */
+ --sticker-purple-deep: #391c57; /* illustration only */
+ --sticker-orange-deep: #793400; /* illustration only */
+
+ /* --- Typography (Inter, self-hosted via @font-face) --- */
+ --font-family: "Inter", -apple-system, system-ui, "Segoe UI",
+ Helvetica, Arial, sans-serif;
+
+ /* Font-family is baked into each token below: the CSS `font` shorthand
+ resets font-family to the UA default (serif) unless a family is written,
+ and it cannot carry letter-spacing — so weights/sizes ship inline and the
+ family is appended per token. */
+ --type-display-1: 700 48px/1.05 var(--font-family);
+ --type-heading-1: 700 32px/1.1 var(--font-family);
+ --type-heading-2: 700 22px/1.27 var(--font-family);
+ --type-title: 600 17px/1.4 var(--font-family);
+ --type-body-md: 400 15px/1.5 var(--font-family);
+ --type-body-sm: 400 14px/1.4 var(--font-family);
+ --type-button: 500 15px/1.4 var(--font-family);
+ --type-caption: 400 13px/1.43 var(--font-family);
+ --type-eyebrow: 600 12px/1.33 var(--font-family);
+
+ /* --- Layout (base unit 8px) --- */
+ --space-xxs: 4px;
+ --space-xs: 8px;
+ --space-sm: 12px;
+ --space-md: 16px;
+ --space-lg: 24px;
+ --space-xl: 28px;
+ --space-xxl: 32px;
+
+ --container-max: 1200px;
+
+ /* --- Elevation --- */
+ --shadow-level-1: rgba(0, 0, 0, 0.01) 0 0.175px 1px,
+ rgba(0, 0, 0, 0.02) 0 0.8px 3px,
+ rgba(0, 0, 0, 0.027) 0 2px 8px,
+ rgba(0, 0, 0, 0.04) 0 4px 18px;
+ --shadow-level-2: rgba(0, 0, 0, 0.0122) 0 0.175px 1px,
+ rgba(0, 0, 0, 0.024) 0 0.8px 3px,
+ rgba(0, 0, 0, 0.032) 0 2px 8px,
+ rgba(0, 0, 0, 0.047) 0 4px 18px,
+ rgba(0, 0, 0, 0.05) 0 23px 52px;
+
+ /* --- Shapes --- */
+ --rounded-xs: 4px;
+ --rounded-sm: 5px;
+ --rounded-md: 8px;
+ --rounded-lg: 12px;
+ --rounded-full: 9999px;
+}
+
+/* Dark mode — flip the semantic tokens only (components use var(--…)). */
+[data-theme="dark"] {
+ --canvas-soft: #141518;
+ --surface: #1c1e22;
+ --surface-2: #24262c;
+ --hairline: #33363d;
+ --ink: #f5f6f7;
+ --ink-secondary: #dcdee2;
+ --ink-muted: #a9adb6;
+ --ink-faint: #727680;
+ --primary: #3d8be0;
+ --primary-active: #5d9ff0;
+ --on-primary: #ffffff;
+ --secondary: #10142a;
+ --shadow-level-1: rgba(0, 0, 0, 0.45) 0 1px 3px;
+ --shadow-level-2: rgba(0, 0, 0, 0.55) 0 5px 22px;
+}
+
+/* Numerals: enable OpenType lnum */
+html { font-feature-settings: "lnum" 1; }
\ No newline at end of file
diff --git a/internal/web/templates/dashboard.html b/internal/web/templates/dashboard.html
new file mode 100644
index 0000000..55781aa
--- /dev/null
+++ b/internal/web/templates/dashboard.html
@@ -0,0 +1,78 @@
+{{define "dashboard.html"}}
+
+
+
+
+
+ {{.Title}} — Compass / Teams
+
+
+
+
+
+
+
+
+
+
+ What is due
+ Overdue work first. Compass for the schedule, Teams for homework.
+ This is Phase 1: the skeleton is live, the school scan is not connected yet.
+
+
+ {{if .ErrMsg}}{{.ErrMsg}}
{{end}}
+
+
+ {{template "scan-status.html" .Scan}}
+
+
+
+
+
Children
+ {{len .Children}} on file
+
+ {{if .Children}}
+
+ {{else}}
+
+
No children on file
+
Harry and Finn are seeded on first start. If this is empty,
+ the database was not seeded.
+
+ {{end}}
+
+
+
+
+
+{{end}}
diff --git a/internal/web/templates/login.html b/internal/web/templates/login.html
new file mode 100644
index 0000000..0bde9fc
--- /dev/null
+++ b/internal/web/templates/login.html
@@ -0,0 +1,41 @@
+{{define "login.html"}}
+
+
+
+
+
+ Sign in — Compass / Teams
+
+
+
+
+
+
+
+
Compass / Teams
+
Good to see you,
Sam.
+
Sign in to see what Harry and Finn have due.
+
+
+
+ Sign in
+ {{if .Error}}{{.Error}}
{{end}}
+
+
+
+
+
+{{end}}
diff --git a/internal/web/templates/partials/scan-status.html b/internal/web/templates/partials/scan-status.html
new file mode 100644
index 0000000..a39c6eb
--- /dev/null
+++ b/internal/web/templates/partials/scan-status.html
@@ -0,0 +1,19 @@
+{{define "scan-status.html"}}
+{{/* Fail-loudly scan banner (FR-12). A missing or failed scan is never shown as
+ "nothing due". */}}
+
+
+
Scan status
+
+ {{if eq .Level "ok"}}healthy
+ {{else if eq .Level "error"}}failed
+ {{else if eq .Level "warn"}}never run
+ {{else}}unknown{{end}}
+
+
+ {{.Message}}
+ {{if .LastAt}}Last scan: {{.LastAt}}
+ {{if .Last}}· {{.Last.PagesFetched}} pages · {{.Last.ItemsFound}} items{{end}}
{{end}}
+ {{if gt .Failed 0}}{{.Failed}} failed scan(s) on record.
{{end}}
+
+{{end}}