Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

feat(lenses): `beacon lenses spec|data|lint|preview` and the beacon-lens-create skill

Claude0fc8b4fde658
diff --git a/CLAUDE.md b/CLAUDE.md
index 82ca57c7..8fed9cca 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -13,9 +13,9 @@ Beacon Endpoint Agent is a local-only endpoint telemetry agent for AI runtimes.
- `browser-extension`: optional MV3 collector (Chrome, plus a beta Firefox build target) that relays Claude.ai and ChatGPT chat telemetry into the local pipeline as OTLP.
- `pkg/asymptoteobserve`: shared Go library — event schema, harness-name normalization, provenance markers, token usage, and the threat-rules engine. Imported by the CLI, the hook adapter, and the collector exporter, so a change here reaches all three.
- `plugins`: TypeScript sources for the managed runtime plugins/extensions (`opencode-beacon`, `cline-beacon`, `pi-beacon`, `omp-beacon`, `openclaw-beacon`, `prime-beacon`, `omo-beacon`), each mirrored into an embedded copy under `cli/beacon/internal/endpoint/hooks/assets/`.
-- `agent-skills`: publishable Agent Skills plugin for the traces-to-memory workflow (`beacon-memory-recall`, `beacon-memory-distill`, `beacon-memory-promote`) with manifests for Claude Code, Agent Plugins (Codex, Copilot, VS Code, Kiro, Devin), Cursor, Kimi Code, and Gemini CLI. At the repo root, `.claude-plugin/marketplace.json` is read by most harnesses, `.cursor-plugin/marketplace.json` by Cursor, and `package.json` (`pi.skills` only) makes the repo a Pi/Prime Agent package; keep that root `package.json` free of dependencies and scripts. `cli/beacon/cmd/agent_skills_test.go` checks every `beacon` command and flag the skills name against the real command tree, so rename a command and update the skills together.
+- `agent-skills`: publishable Agent Skills plugin for the traces-to-memory workflow (`beacon-memory-recall`, `beacon-memory-distill`, `beacon-memory-promote`) and for authoring dashboard lenses (`beacon-lens-create`) with manifests for Claude Code, Agent Plugins (Codex, Copilot, VS Code, Kiro, Devin), Cursor, Kimi Code, and Gemini CLI. At the repo root, `.claude-plugin/marketplace.json` is read by most harnesses, `.cursor-plugin/marketplace.json` by Cursor, and `package.json` (`pi.skills` only) makes the repo a Pi/Prime Agent package; keep that root `package.json` free of dependencies and scripts. `cli/beacon/cmd/agent_skills_test.go` checks every `beacon` command and flag the skills name against the real command tree, so rename a command and update the skills together.
- `rules` and `spec/threat-rules`: the open rule corpus and the Threat Rules format it conforms to. Every rule's `taxonomy.beacon_category` is its directory name, and the six embedded baseline rules in `pkg/asymptoteobserve/rulestore/baseline` are byte-identical copies of their corpus rules; conformance tests enforce both.
-- `spec/lenses`: the Lenses format — single-file HTML views of one trace that the local dashboard runs in a sandboxed, network-less frame and feeds once through `window.beacon.getTrace()`. The contract types (`LensManifestV1`, `LensDataV1`) live in `pkg/asymptoteobserve/lens.go`, and `lens_test.go` pins the spec's examples and manifest schema to them. The dashboard builds the data in `BuildLensData` (`/api/lens-data`), lists lenses at `/api/lenses`, and serves each lens at `/lenses/frame/<id>` under the spec's CSP with `lenses/prelude.js` (which defines `window.beacon`) injected ahead of it; that route is the only one that may be framed. Built-in lenses are `cli/beacon/internal/endpoint/dashboard/lenses/*.lens.html`, and `activity` is byte-identical to the spec example (a test enforces it). The session page (`static/session.html`, `initLensTabs` in `app.js`) shows lenses as tabs fed by `/api/lens-data?session=`, which projects exactly the events that page lists; it is the host half of the protocol and closes a lens that errors, stalls, or navigates its own frame. Installed lenses live in the lens store (`cli/beacon/internal/endpoint/lensstore`, `<BaseDir>/lenses/<id>.lens.html`, 0600 under 0700), written only by `beacon lenses add|remove` (`cli/beacon/cmd/lenses.go`); the dashboard rescans it per request and never writes it, and a store lens can never shadow a built-in. `asymptoteobserve.CheckLensFile` is the one file check every installer, server and linter uses.
+- `spec/lenses`: the Lenses format — single-file HTML views of one trace that the local dashboard runs in a sandboxed, network-less frame and feeds once through `window.beacon.getTrace()`. The contract types (`LensManifestV1`, `LensDataV1`) live in `pkg/asymptoteobserve/lens.go`, and `lens_test.go` pins the spec's examples and manifest schema to them. The dashboard builds the data in `BuildLensData` (`/api/lens-data`), lists lenses at `/api/lenses`, and serves each lens at `/lenses/frame/<id>` under the spec's CSP with `lenses/prelude.js` (which defines `window.beacon`) injected ahead of it; that route is the only one that may be framed. Built-in lenses are `cli/beacon/internal/endpoint/dashboard/lenses/*.lens.html`, and `activity` is byte-identical to the spec example (a test enforces it). The session page (`static/session.html`, `initLensTabs` in `app.js`) shows lenses as tabs fed by `/api/lens-data?session=`, which projects exactly the events that page lists; it is the host half of the protocol and closes a lens that errors, stalls, or navigates its own frame. Installed lenses live in the lens store (`cli/beacon/internal/endpoint/lensstore`, `<BaseDir>/lenses/<id>.lens.html`, 0600 under 0700), written only by `beacon lenses add|remove` (`cli/beacon/cmd/lenses.go`); the dashboard rescans it per request and never writes it, and a store lens can never shadow a built-in. `asymptoteobserve.CheckLensFile` is the one file check every installer, server and linter uses. The authoring loop is `beacon lenses spec` (the spec carried in the binary as `dashboard/lenses/SPEC.md`, kept byte-identical to `spec/lenses/SPEC.md` by a test), `beacon lenses data` (the exact `LensDataV1` for a session), `beacon lenses lint` (`lensstore.Lint`; built-ins must lint clean) and `beacon lenses preview` (the dashboard with `Options.LensFiles`, re-read per reload).
- `beacon-sandbox`: harness that runs a real Claude Code session in a disposable sandbox and checks what Beacon captured. See `beacon-sandbox/AGENTS.md`.
- `packaging`: macOS, Linux, and Windows packaging and deployment assets.
- `docs`: the published documentation site (docs.asymptotelabs.ai).
diff --git a/agent-skills/skills/beacon-lens-create/SKILL.md b/agent-skills/skills/beacon-lens-create/SKILL.md
new file mode 100644
index 00000000..bd644a83
--- /dev/null
+++ b/agent-skills/skills/beacon-lens-create/SKILL.md
@@ -0,0 +1,132 @@
+---
+name: beacon-lens-create
+description: Build a Beacon lens, a single HTML file that renders one agent trace as a purpose-built view (a hub-and-spoke tool map, a timeline of risky commands, a per-file review, a cost breakdown) inside the local Beacon dashboard. Reads the lens spec, inspects real trace data, writes the file, lints it, previews it against a real session, and installs it. Use when the user asks to "make a lens", "build a view of my traces", "visualize this session", or wants a custom tab next to the full trace in the Beacon dashboard.
+license: MIT
+compatibility: Requires the Beacon CLI (beacon) on PATH with endpoint capture installed, so there are traces to render. Reads only local state and makes no network calls.
+metadata:
+ author: asymptote-labs
+ homepage: https://docs.beacon.sh/concepts/lenses
+ version: "0.1.0"
+---
+
+# Beacon lens create
+
+A **lens** is one HTML file that renders one trace. The Beacon dashboard shows lenses as
+tabs on a session's page, next to the full event list. Each lens runs in a sandboxed frame
+with no network access and receives the trace once, through `window.beacon.getTrace()`.
+Everything else is plain HTML, CSS and JavaScript in that one file.
+
+Your job is to turn what the user wants to see into a lens that works on their real
+sessions, then install it.
+
+## Step 1: check that Beacon is available
+
+```bash
+beacon version
+```
+
+If `beacon` is not found, tell the user that lenses need the Beacon CLI, point them to
+https://docs.beacon.sh/get-started/overview, and stop. Do not install it yourself.
+
+## Step 2: read the spec
+
+```bash
+beacon lenses spec
+```
+
+Read all of it before writing anything. It defines the manifest, the exact shape of the
+data, the sandbox, the style tokens and the robustness rules. The parts that most often go
+wrong:
+
+- The manifest is a `<script type="application/beacon-lens+json">` element spelled exactly
+ that way, with `id`, `title`, `version` and `api: "beacon.lens.v1"`.
+- Nothing loads by URL: no CDN scripts, fonts, images or stylesheets. Inline everything.
+- Trace content is untrusted. Build every node with `textContent`; never `innerHTML`.
+- Every field except the few the spec guarantees is optional. Render a placeholder when one
+ is missing.
+
+For a complete, working lens to start from:
+
+```bash
+beacon lenses spec --example
+```
+
+## Step 3: look at real data
+
+Do not guess the data shape from the spec alone. Print exactly what a lens would receive
+for a real session:
+
+```bash
+# The most recent session
+beacon lenses data
+
+# A specific session (IDs are on the dashboard's session pages)
+beacon lenses data --session <session-id>
+```
+
+The output includes whatever content the log retained (prompts, command output, diffs), so
+read it locally and do not paste large amounts of it back to the user. Note which fields the
+user's sessions actually carry: event `type` values, whether `file.diff` or `usage` is
+present, whether there are `findings`. Design for those, and handle their absence.
+
+## Step 4: write the lens
+
+Pick a short, lowercase, hyphenated `id` that is not a built-in. `beacon lenses list` shows
+the ones in use. Write the file in the user's project or a scratch directory, not in the
+lens store. Follow the spec's layout rules:
+
+- Render a loading line immediately, then fill it in when `getTrace()` resolves; show the
+ error message if it rejects.
+- Use the `--beacon-*` style tokens with fallbacks, compact tables over cards, 13px text at
+ weight 400, right-aligned numbers.
+- Let the page grow; never size the root to `100vh`. The dashboard sizes the frame.
+- Expect thousands of events. Build the DOM once, and cap or paginate long lists.
+
+## Step 5: lint until clean
+
+```bash
+beacon lenses lint path/to/my-lens.lens.html
+```
+
+Errors stop the lens from running. Warnings name code the sandbox will block or the spec
+forbids, with a line number. Fix both; use `--strict` to make warnings fail the check:
+
+```bash
+beacon lenses lint --strict path/to/my-lens.lens.html
+```
+
+## Step 6: preview it against a real session
+
+```bash
+beacon lenses preview path/to/my-lens.lens.html --session <session-id>
+```
+
+This serves the dashboard with the lens added and prints the session page to open (pass
+`--open` to open a browser). It runs until interrupted, so start it in the background if
+your harness blocks on long-running commands. The file is read again on every page load:
+edit, reload, repeat. Ask the user to look at it, and check at least one session that lacks
+the data the lens is about (no diffs, no usage, no findings) to see the empty state.
+
+If the lens shows "could not be shown" and the dashboard falls back to the full session,
+the lens threw before rendering, never called `getTrace()`, or navigated its own frame. The
+notice says which.
+
+## Step 7: install it
+
+When the user is happy with it:
+
+```bash
+beacon lenses add path/to/my-lens.lens.html
+```
+
+It now appears in the **+** menu on every session page. To change it later, edit the source
+file, bump `version` in its manifest, and run `beacon lenses add` again. `beacon lenses list`
+shows what is installed and `beacon lenses remove <id>` uninstalls it.
+
+## Rules
+
+- Never weaken the sandbox or ask the user to: a lens that needs the network is the wrong
+ design. Everything it needs is in `getTrace()`.
+- Never put trace content into a lens file. The lens renders data at view time; the file
+ holds only code.
+- Never install a lens the user has not seen in preview.
diff --git a/cli/beacon/cmd/lenses_tools.go b/cli/beacon/cmd/lenses_tools.go
new file mode 100644
index 00000000..d2b0fe52
--- /dev/null
+++ b/cli/beacon/cmd/lenses_tools.go
@@ -0,0 +1,250 @@
+package cmd
+
+import (
+ "errors"
+ "fmt"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/spf13/cobra"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/auth"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/dashboard"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lensstore"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+)
+
+// The lens authoring loop: read the spec, look at real data, write the file, lint it, and preview
+// it against a real session in the dashboard before installing it with `beacon lenses add`.
+
+// lensPreviewAddr is one port above the dashboard's default, so a preview can run next to it.
+const lensPreviewAddr = "127.0.0.1:8766"
+
+var lensToolsOpts struct {
+ example bool
+ strict bool
+ json bool
+ session string
+ trace string
+ logPath string
+ addr string
+ open bool
+}
+
+var lensesSpecCmd = &cobra.Command{
+ Use: "spec",
+ Short: "Print the lens specification (or, with --example, a complete example lens)",
+ Long: `Print spec/lenses/SPEC.md: the file format, the data window.beacon.getTrace() returns,
+the sandbox rules and the style tokens. It is carried in the binary, so it works offline.
+With --example, print a complete lens to start from (the built-in activity lens).`,
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ if lensToolsOpts.example {
+ _, err := cmd.OutOrStdout().Write(dashboard.ExampleLens())
+ return err
+ }
+ _, err := fmt.Fprint(cmd.OutOrStdout(), dashboard.LensSpec())
+ return err
+ },
+}
+
+var lensesLintCmd = &cobra.Command{
+ Use: "lint <file>...",
+ Short: "Check lens files against the spec",
+ Long: `Check lens files against spec/lenses/SPEC.md. Errors (an oversized file, a missing or
+invalid manifest) stop a lens from running. Warnings flag code the sandbox will block or the
+spec forbids: HTML parsing of trace content, network requests, resources loaded by URL,
+browser storage, navigation, viewport-height layouts and a lens that never calls getTrace().
+Exits non-zero on errors, or on warnings with --strict.`,
+ Args: cobra.MinimumNArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ out := cmd.OutOrStdout()
+ type fileResult struct {
+ Path string `json:"path"`
+ Findings []lensstore.LintFinding `json:"findings"`
+ }
+ var results []fileResult
+ errorsFound, warningsFound := 0, 0
+ for _, path := range args {
+ html, err := os.ReadFile(path)
+ if err != nil {
+ return err
+ }
+ findings := lensstore.Lint(html)
+ if findings == nil {
+ findings = []lensstore.LintFinding{}
+ }
+ results = append(results, fileResult{Path: path, Findings: findings})
+ for _, f := range findings {
+ if f.Severity == lensstore.LintError {
+ errorsFound++
+ } else {
+ warningsFound++
+ }
+ if lensToolsOpts.json {
+ continue
+ }
+ if f.Line > 0 {
+ fmt.Fprintf(out, "%s:%d: %s: %s\n", path, f.Line, f.Severity, f.Message)
+ } else {
+ fmt.Fprintf(out, "%s: %s: %s\n", path, f.Severity, f.Message)
+ }
+ }
+ }
+ if lensToolsOpts.json {
+ if err := writeIndentedJSON(out, map[string]interface{}{"files": results, "errors": errorsFound, "warnings": warningsFound}); err != nil {
+ return err
+ }
+ } else {
+ fmt.Fprintf(out, "%d error(s), %d warning(s) in %d file(s).\n", errorsFound, warningsFound, len(args))
+ }
+ switch {
+ case errorsFound > 0:
+ return fmt.Errorf("%d lint error(s)", errorsFound)
+ case lensToolsOpts.strict && warningsFound > 0:
+ return fmt.Errorf("%d lint warning(s) with --strict", warningsFound)
+ }
+ return nil
+ },
+}
+
+var lensesDataCmd = &cobra.Command{
+ Use: "data",
+ Short: "Print the data a lens receives for a session or trace",
+ Long: `Print the exact LensDataV1 that window.beacon.getTrace() resolves with, for one session
+(the dashboard's session page) or one trace. With neither flag, the most recent session is
+used. Reads only the local log; the output includes whatever content the log retained.`,
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ logPath := lensesLogPath()
+ opts := dashboard.LensDataOptions{UserMode: lensesUserMode()}
+ var (
+ data dashboard.LensDataV1
+ ok bool
+ err error
+ )
+ switch {
+ case lensToolsOpts.session != "" && lensToolsOpts.trace != "":
+ return errors.New("pass --session or --trace, not both")
+ case lensToolsOpts.trace != "":
+ data, ok, err = dashboard.BuildLensData(logPath, lensToolsOpts.trace, opts)
+ default:
+ session := lensToolsOpts.session
+ if session == "" {
+ if session, err = latestSession(logPath); err != nil {
+ return err
+ }
+ }
+ data, ok, err = dashboard.BuildSessionLensData(logPath, session, opts)
+ }
+ if err != nil {
+ return err
+ }
+ if !ok {
+ return errors.New("no such session or trace in the runtime log")
+ }
+ return writeIndentedJSON(cmd.OutOrStdout(), data)
+ },
+}
+
+var lensesPreviewCmd = &cobra.Command{
+ Use: "preview <file>",
+ Short: "Serve a lens file in the dashboard against a real session, re-read on every reload",
+ Long: `Lint a lens file, then run the dashboard with it added and print the session page that
+shows it. The file is read again on every page load, so edit it and reload. Nothing is
+installed; use 'beacon lenses add' when it is done. Runs until interrupted.`,
+ Args: cobra.ExactArgs(1),
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ out := cmd.OutOrStdout()
+ file, err := filepath.Abs(args[0])
+ if err != nil {
+ return err
+ }
+ html, err := os.ReadFile(file)
+ if err != nil {
+ return err
+ }
+ findings := lensstore.Lint(html)
+ for _, f := range findings {
+ fmt.Fprintf(out, "%s:%d: %s: %s\n", args[0], f.Line, f.Severity, f.Message)
+ }
+ if lensstore.HasLintErrors(findings) {
+ return errors.New("fix the lint errors before previewing")
+ }
+ manifest, _ := asymptoteobserve.ParseLensManifest(html) // lint already proved it valid
+ reserved, err := dashboard.BuiltinLensIDs()
+ if err != nil {
+ return err
+ }
+ if reserved[manifest.ID] {
+ return fmt.Errorf("%q is a built-in lens id; give this lens another id", manifest.ID)
+ }
+ if err := dashboard.ValidateLoopbackAddr(lensToolsOpts.addr); err != nil {
+ return err
+ }
+ logPath := lensesLogPath()
+ session := lensToolsOpts.session
+ if session == "" {
+ session, _ = latestSession(logPath)
+ }
+ page := dashboard.URL(lensToolsOpts.addr)
+ if session != "" {
+ page = strings.TrimRight(page, "/") + "/session.html?" + url.Values{"id": {session}, "lens": {manifest.ID}}.Encode()
+ }
+ fmt.Fprintf(out, "Previewing %s (%s) from %s\n", manifest.Title, manifest.ID, file)
+ if session == "" {
+ fmt.Fprintln(out, "No sessions in the runtime log yet; open a session in the dashboard and add the lens from its + menu.")
+ }
+ fmt.Fprintf(out, "Open: %s\nEdits to the file show on reload. Press Ctrl-C to stop.\n", page)
+ if lensToolsOpts.open {
+ if err := dashboard.OpenBrowser(page); err != nil && !errors.Is(err, auth.ErrNoDisplay) {
+ return err
+ }
+ }
+ return dashboardListenAndServe(dashboard.Options{
+ Addr: lensToolsOpts.addr,
+ LogPath: logPath,
+ UserMode: lensesUserMode(),
+ LensFiles: []string{file},
+ })
+ },
+}
+
+func lensesLogPath() string {
+ return lifecycle.ResolveRuntimeLog(lensesUserMode(), lensToolsOpts.logPath).EffectiveLogPath
+}
+
+// latestSession returns the most recently active session in the log.
+func latestSession(logPath string) (string, error) {
+ sessions, err := dashboard.ReadSessions(logPath, dashboard.EventQuery{Limit: 1})
+ if err != nil {
+ return "", err
+ }
+ if len(sessions.Sessions) == 0 {
+ return "", errors.New("the runtime log has no sessions yet; pass --session or --trace")
+ }
+ return sessions.Sessions[0].ID, nil
+}
+
+func init() {
+ lensesSpecCmd.Flags().BoolVar(&lensToolsOpts.example, "example", false, "Print a complete example lens instead of the spec")
+ lensesLintCmd.Flags().BoolVar(&lensToolsOpts.strict, "strict", false, "Fail on warnings too")
+ lensesLintCmd.Flags().BoolVar(&lensToolsOpts.json, "json", false, "Print JSON")
+ for _, c := range []*cobra.Command{lensesDataCmd, lensesPreviewCmd} {
+ c.Flags().StringVar(&lensToolsOpts.session, "session", "", "Session ID (default: the most recent session)")
+ c.Flags().StringVar(&lensToolsOpts.logPath, "log-path", "", "Runtime JSONL log path")
+ c.Flags().BoolVar(&lensesOpts.userMode, "user", true, "Use per-user endpoint paths")
+ c.Flags().BoolVar(&lensesOpts.systemMode, "system", false, "Use system endpoint paths")
+ }
+ lensesDataCmd.Flags().StringVar(&lensToolsOpts.trace, "trace", "", "Trace ID instead of a session")
+ lensesPreviewCmd.Flags().StringVar(&lensToolsOpts.addr, "addr", lensPreviewAddr, "Loopback address to serve the preview on")
+ lensesPreviewCmd.Flags().BoolVar(&lensToolsOpts.open, "open", false, "Open the preview in a browser")
+ lensesCmd.AddCommand(lensesSpecCmd, lensesLintCmd, lensesDataCmd, lensesPreviewCmd)
+}
diff --git a/cli/beacon/cmd/lenses_tools_test.go b/cli/beacon/cmd/lenses_tools_test.go
new file mode 100644
index 00000000..47989022
--- /dev/null
+++ b/cli/beacon/cmd/lenses_tools_test.go
@@ -0,0 +1,172 @@
+package cmd
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/dashboard"
+)
+
+func useLensToolsDefaults(t *testing.T) {
+ t.Helper()
+ useLensTestHome(t)
+ prev := lensToolsOpts
+ lensToolsOpts.example, lensToolsOpts.strict, lensToolsOpts.json = false, false, false
+ lensToolsOpts.session, lensToolsOpts.trace, lensToolsOpts.logPath = "", "", ""
+ lensToolsOpts.addr, lensToolsOpts.open = lensPreviewAddr, false
+ t.Cleanup(func() { lensToolsOpts = prev })
+}
+
+func writeLensLog(t *testing.T) string {
+ t.Helper()
+ path := filepath.Join(t.TempDir(), "runtime.jsonl")
+ lines := []string{
+ `{"timestamp":"2026-06-11T10:00:00Z","vendor":"beacon","product":"endpoint-agent","schema_version":"1.0","event":{"id":"old-1","kind":"agent_runtime","action":"prompt.submitted","category":"prompt"},"severity":"info","endpoint":{"os":"linux"},"harness":{"name":"claude_code"},"session":{"id":"older"},"prompt":{"text":"first"},"message":"prompt.submitted"}`,
+ `{"timestamp":"2026-06-11T11:00:00Z","vendor":"beacon","product":"endpoint-agent","schema_version":"1.0","event":{"id":"new-1","kind":"agent_runtime","action":"command.executed","category":"command"},"severity":"info","endpoint":{"os":"linux"},"harness":{"name":"claude_code"},"session":{"id":"newer"},"command":{"command":"ls"},"message":"command.executed"}`,
+ }
+ if err := os.WriteFile(path, []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ return path
+}
+
+func TestLensesSpecPrintsTheSpecAndAnExample(t *testing.T) {
+ useLensToolsDefaults(t)
+ cmd, buf := newCmd()
+ if err := lensesSpecCmd.RunE(cmd, nil); err != nil || !strings.HasPrefix(buf.String(), "# Lenses — Specification") {
+ t.Fatalf("spec = %v, %.60q", err, buf.String())
+ }
+ lensToolsOpts.example = true
+ cmd, buf = newCmd()
+ if err := lensesSpecCmd.RunE(cmd, nil); err != nil || !strings.Contains(buf.String(), `<script type="application/beacon-lens+json">`) {
+ t.Fatalf("spec --example = %v", err)
+ }
+}
+
+func TestLensesLint(t *testing.T) {
+ useLensToolsDefaults(t)
+ dir := t.TempDir()
+ clean := writeTestLens(t, dir, "clean", "1")
+ warn := filepath.Join(dir, "warn.html")
+ if err := os.WriteFile(warn, []byte(`<script type="application/beacon-lens+json">{"id":"warn","title":"W","version":1,"api":"beacon.lens.v1"}</script>
+<script>window.beacon.getTrace().then(function (d) { document.body.innerHTML = d.trace.id; });</script>`), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ broken := filepath.Join(dir, "broken.html")
+ if err := os.WriteFile(broken, []byte("<p>nothing</p>"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ cmd, buf := newCmd()
+ if err := lensesLintCmd.RunE(cmd, []string{clean}); err != nil || !strings.Contains(buf.String(), "0 error(s), 0 warning(s) in 1 file(s).") {
+ t.Fatalf("clean = %v, %q", err, buf.String())
+ }
+ cmd, buf = newCmd()
+ if err := lensesLintCmd.RunE(cmd, []string{warn}); err != nil || !strings.Contains(buf.String(), warn+":2: warning:") {
+ t.Fatalf("warning = %v, %q", err, buf.String())
+ }
+ lensToolsOpts.strict = true
+ cmd, _ = newCmd()
+ if err := lensesLintCmd.RunE(cmd, []string{warn}); err == nil {
+ t.Fatal("--strict passed a lens with warnings")
+ }
+ lensToolsOpts.strict = false
+ cmd, _ = newCmd()
+ if err := lensesLintCmd.RunE(cmd, []string{clean, broken}); err == nil || !strings.Contains(err.Error(), "lint error") {
+ t.Fatalf("broken = %v", err)
+ }
+
+ lensToolsOpts.json = true
+ cmd, buf = newCmd()
+ _ = lensesLintCmd.RunE(cmd, []string{warn, clean})
+ var report struct {
+ Files []struct {
+ Path string `json:"path"`
+ Findings []struct {
+ Line int `json:"line"`
+ Severity string `json:"severity"`
+ } `json:"findings"`
+ } `json:"files"`
+ Warnings int `json:"warnings"`
+ }
+ if err := json.Unmarshal(buf.Bytes(), &report); err != nil || len(report.Files) != 2 || report.Warnings == 0 || len(report.Files[1].Findings) != 0 {
+ t.Fatalf("lint --json = %v, %s", err, buf.String())
+ }
+}
+
+func TestLensesDataPrintsWhatALensReceives(t *testing.T) {
+ useLensToolsDefaults(t)
+ lensToolsOpts.logPath = writeLensLog(t)
+
+ cmd, buf := newCmd()
+ if err := lensesDataCmd.RunE(cmd, nil); err != nil {
+ t.Fatal(err)
+ }
+ var data dashboard.LensDataV1
+ if err := json.Unmarshal(buf.Bytes(), &data); err != nil {
+ t.Fatal(err)
+ }
+ if data.APIVersion != "beacon.lens.v1" || data.Trace.ID != "session:claude_code:newer" {
+ t.Fatalf("default data = %s, %s; want the most recent session", data.APIVersion, data.Trace.ID)
+ }
+
+ lensToolsOpts.session = "older"
+ cmd, buf = newCmd()
+ if err := lensesDataCmd.RunE(cmd, nil); err != nil || !strings.Contains(buf.String(), `"id": "session:claude_code:older"`) {
+ t.Fatalf("--session = %v", err)
+ }
+ lensToolsOpts.session = ""
+ lensToolsOpts.trace = "session:claude_code:older"
+ cmd, _ = newCmd()
+ if err := lensesDataCmd.RunE(cmd, nil); err != nil {
+ t.Fatalf("--trace = %v", err)
+ }
+ lensToolsOpts.session = "older"
+ if err := lensesDataCmd.RunE(cmd, nil); err == nil {
+ t.Fatal("--session with --trace was accepted")
+ }
+ lensToolsOpts.session, lensToolsOpts.trace = "nope", ""
+ if err := lensesDataCmd.RunE(cmd, nil); err == nil {
+ t.Fatal("an unknown session was accepted")
+ }
+}
+
+func TestLensesPreviewServesTheFileAgainstARealSession(t *testing.T) {
+ useLensToolsDefaults(t)
+ lensToolsOpts.logPath = writeLensLog(t)
+ var served dashboard.Options
+ prev := dashboardListenAndServe
+ dashboardListenAndServe = func(opts dashboard.Options) error { served = opts; return nil }
+ t.Cleanup(func() { dashboardListenAndServe = prev })
+
+ file := writeTestLens(t, t.TempDir(), "my-lens", "1")
+ cmd, buf := newCmd()
+ if err := lensesPreviewCmd.RunE(cmd, []string{file}); err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(buf.String(), "Open: http://127.0.0.1:8766/session.html?id=newer&lens=my-lens") {
+ t.Fatalf("preview output = %q", buf.String())
+ }
+ if served.Addr != lensPreviewAddr || len(served.LensFiles) != 1 || !filepath.IsAbs(served.LensFiles[0]) || served.LogPath != lensToolsOpts.logPath {
+ t.Fatalf("served = %+v", served)
+ }
+
+ cmd, _ = newCmd()
+ if err := lensesPreviewCmd.RunE(cmd, []string{writeTestLens(t, t.TempDir(), "activity", "1")}); err == nil || !strings.Contains(err.Error(), "built-in") {
+ t.Fatalf("built-in id = %v", err)
+ }
+ broken := filepath.Join(t.TempDir(), "broken.html")
+ if err := os.WriteFile(broken, []byte("<p>no manifest</p>"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := lensesPreviewCmd.RunE(cmd, []string{broken}); err == nil {
+ t.Fatal("a lens with lint errors was previewed")
+ }
+ lensToolsOpts.addr = "0.0.0.0:8766"
+ if err := lensesPreviewCmd.RunE(cmd, []string{file}); err == nil {
+ t.Fatal("a non-loopback preview address was accepted")
+ }
+}
diff --git a/cli/beacon/internal/endpoint/dashboard/lenses.go b/cli/beacon/internal/endpoint/dashboard/lenses.go
index 5c498347..ae6d36d3 100644
--- a/cli/beacon/internal/endpoint/dashboard/lenses.go
+++ b/cli/beacon/internal/endpoint/dashboard/lenses.go
@@ -28,6 +28,21 @@ var lensPreludeJS string
//go:embed lenses/tokens.css
var lensTokensCSS string
+// lensSpec is spec/lenses/SPEC.md, carried in the binary so `beacon lenses spec` works offline. A
+// test keeps the copy identical to the published spec.
+//
+//go:embed lenses/SPEC.md
+var lensSpec string
+
+// LensSpec returns the lens specification.
+func LensSpec() string { return lensSpec }
+
+// ExampleLens returns the spec's example lens, which is also the built-in activity lens.
+func ExampleLens() []byte {
+ html, _ := builtinLensFiles.ReadFile("lenses/activity.lens.html")
+ return html
+}
+
// lensFrameCSP is the policy spec/lenses/SPEC.md promises. The sandbox directive repeats the
// iframe's sandbox attribute, so a lens URL opened on its own -- outside the dashboard's frame --
// still runs in an opaque origin with no network.
diff --git a/cli/beacon/internal/endpoint/dashboard/lenses/SPEC.md b/cli/beacon/internal/endpoint/dashboard/lenses/SPEC.md
new file mode 100644
index 00000000..42f7357d
--- /dev/null
+++ b/cli/beacon/internal/endpoint/dashboard/lenses/SPEC.md
@@ -0,0 +1,249 @@
+# Lenses — Specification (v1)
+
+A lens is a single HTML file that renders one Beacon trace. The local dashboard
+(`beacon endpoint dashboard`) shows lenses as tabs next to the full trace view.
+Each tab reads the same trace and answers a different question: which files
+changed, what the run cost, what the threat rules flagged.
+
+A lens runs in a sandboxed frame with no network and no access to the dashboard.
+It receives the trace through one call, `window.beacon.getTrace()`. Everything
+else is plain HTML, CSS and JavaScript, so any coding agent can write one from
+this document.
+
+- Spec version: `lenses/v1` (see `VERSION` and [Versioning](#versioning)).
+- Data contract: `beacon.lens.v1`, the Go types `LensDataV1` and
+ `LensManifestV1` in `pkg/asymptoteobserve/lens.go`.
+- Manifest schema: `manifest.schema.json` (JSON Schema, draft 2020-12).
+- Examples: `examples/activity.lens.html` (a complete lens) and
+ `examples/lens-data.json` (what `getTrace()` resolves with). A test pins
+ both against the Go types.
+
+## The lens file
+
+A lens is one UTF-8 HTML document of at most **16 MiB**. All CSS, JavaScript,
+images and fonts are inline (`data:` URIs for images and fonts). Nothing is
+loaded from anywhere else.
+
+The file carries its own manifest in exactly one element whose opening tag is
+spelled exactly like this:
+
+```html
+<script type="application/beacon-lens+json">
+{
+ "id": "files-changed",
+ "title": "Files Changed",
+ "description": "Every file the agent touched, with its diffs.",
+ "icon": "file",
+ "version": 1,
+ "api": "beacon.lens.v1"
+}
+</script>
+```
+
+Readers find the manifest by that literal opening tag, without an HTML parser,
+so do not add attributes or change quoting or case. Browsers do not run a
+script of an unknown type, so the manifest is inert. If a string in it
+contains `<`, write it as `<` so the text `</script>` cannot occur early.
+
+| Field | Required | Type | Meaning |
+|---|---|---|---|
+| `id` | yes | `^[a-z0-9][a-z0-9-]{0,62}$` | Stable identity. Unique on the endpoint. Built-in lens IDs are reserved. |
+| `title` | yes | string, 1–60 chars, one line | Tab label. |
+| `description` | no | string, ≤ 280 chars, one line | Shown in the lens picker. |
+| `icon` | no | `^[a-z][a-z0-9-]{0,31}$` | One generic word (`file`, `shield`, `coins`, `list`, …). An unknown word gets the default icon. |
+| `version` | yes | int ≥ 1 | Content revision; bump on every change. |
+| `api` | yes | `"beacon.lens.v1"` | The data contract the lens was written against. A lens naming another value is not run. |
+| `author` | no | string, ≤ 100 chars, one line | Attribution. |
+
+Unknown fields are an error, so a misspelled key fails lint instead of being
+ignored.
+
+## Getting the trace
+
+```js
+const data = await window.beacon.getTrace();
+```
+
+- The host defines `window.beacon` before any lens script runs.
+- `getTrace()` returns a promise. Calling it again returns the same promise;
+ the data is computed once per load and never refreshed.
+- It resolves within **10 seconds** or rejects with an `Error`. If the lens
+ has not loaded the trace by then, the host shows the full trace view.
+- There are no other calls. A lens cannot ask for more events, another trace,
+ or anything from the network.
+
+### `LensDataV1`
+
+```jsonc
+{
+ "api_version": "beacon.lens.v1",
+ "trace": { /* TraceBundleV1: schema_version "beacon.trace.v1" */ },
+ "findings": { // absent: the trace was not scanned
+ "rules_evaluated": 42,
+ "items": [ /* LensFindingV1 */ ],
+ "skipped": ["rule-needing-a-newer-spec"]
+ },
+ "token_coverage": { // absent: unknown
+ "harness": "claude_code",
+ "status": "covered", // covered | silent | inactive | not_instrumented
+ "expectation": "reported", // reported | generic_otlp | none
+ "reason": "OTLP token and cost telemetry"
+ },
+ "token_usage": { // absent: unknown
+ "totals": { "input_tokens": 18234, "output_tokens": 1650, "cost_usd": 0.0912 },
+ "events_with_usage": 1,
+ "by_model": [{ "model": "claude-sonnet-5-5", "usage": { /* same shape */ }, "events": 1 }]
+ },
+ "truncated": false
+}
+```
+
+`trace` is the existing trace bundle, the same projection the dashboard's
+trace view uses. Its main parts:
+
+- `trace.summary`: title, `started_at`/`ended_at`, `event_count`, `harness`
+ (`name`, `version`, `collection_methods`), `session`, `repository`,
+ `model`, `token_usage`, and `content.retention`.
+- `trace.events[]`, in order. Each event has `id`, `number` (1-based
+ position), `timestamp`, `type`, `action`, and optional `category`,
+ `fidelity` (`observed` | `inferred`), `actor`, `title`, `summary`,
+ `content`, `tool`, `command`, `file`, `mcp`, `approval`, `model`, `usage`,
+ `tool_call_id` and `trace` (span IDs).
+- `type` is one of `user_message`, `agent_message`, `agent_reasoning`,
+ `tool_call`, `tool_result`, `command`, `file`, `mcp`, `approval`,
+ `token_usage`, `session`, `error` or `other`. The list may grow (see
+ [Robustness](#robustness)).
+- Retained text arrives as a content object: `{text?, json?, retention,
+ included, redacted?, truncated?, hash?, bytes?}`. When `included` is false
+ the text was not retained or was redacted; `hash` and `bytes` still
+ identify it. Command output and file diffs use the same object
+ (`command.output`, `file.diff`).
+- `trace.spans[]` and `trace.range` (`total_events`, `returned_events`).
+
+`findings.items[]` are the active threat rules' matches over this trace's
+own events: `rule_id`, `title`, `severity` (`info` … `critical`), `posture`,
+`reason`, `taxonomy`, and `event_ids`. The evidence is referenced by
+`trace.events[].id`, not copied. Findings, `token_coverage` and
+`token_usage` are computed from the live runtime log. For a trace whose lines
+have been rotated out of that log (and are kept only in the opt-in trace
+history), they may be missing or partial while `trace` is still complete.
+
+`token_usage` is the trace's usage as `beacon token-usage` counts it, with
+duplicate channels removed and cumulative counters turned into deltas. Each
+event's own `usage` is what that event reported, so summing those can count
+the same tokens twice; use `token_usage.totals` for the total, and say so if
+you show both. `cost_usd` is only ever what the runtime reported; Beacon never
+estimates cost.
+
+`truncated` is true when the bundle holds fewer events than the trace has,
+because it hit the size cap. A finding's evidence ID may then point at an
+event that is not in the bundle.
+
+The full field list is the Go source in `pkg/asymptoteobserve/trace.go` and
+`lens.go`. `examples/lens-data.json` is a complete instance.
+
+### Content and privacy
+
+A lens sees whatever the local log retained. With `full` retention that
+includes prompts, responses, command output and diffs, after Beacon's local
+redaction. A lens can show that content on screen and nowhere else: the
+sandbox below gives it no way to send it anywhere. Forwarding privacy modes
+(such as metadata-only) govern what leaves the machine. They do not reduce
+what a local lens receives.
+
+## Sandbox
+
+The host enforces these rules; a lens does not opt into them.
+
+- The frame is `<iframe sandbox="allow-scripts">`, without
+ `allow-same-origin`. The lens runs in an opaque origin and cannot read the
+ dashboard, its cookies, its storage or its API. It also cannot navigate the
+ page, open popups or submit forms.
+- A lens must not navigate its own frame. The dashboard's policy refuses any
+ frame navigation off its origin (including `data:` and `blob:` URLs), and
+ the host closes a lens whose frame loads a second document, without giving
+ that document a port.
+- The frame is served with this Content Security Policy:
+
+ ```
+ default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline';
+ img-src data: blob:; font-src data:; media-src data: blob:;
+ connect-src 'none'; form-action 'none'; base-uri 'none'; frame-ancestors 'self'
+ ```
+
+ No `fetch`, XHR, WebSocket, `EventSource`, remote image, remote font,
+ worker, nested frame, `eval` or `new Function`. Load nothing by URL.
+- Trace data reaches the frame only over a private `MessageChannel` port. The
+ one `postMessage` from the host to the window carries that port and
+ nothing else. The lens never uses `window.postMessage` itself;
+ `window.beacon` handles the port.
+- `localStorage`, `sessionStorage`, IndexedDB and cookies are unavailable in
+ an opaque origin. Keep state in memory.
+- If the lens throws before rendering, rejects, or does not render within
+ the timeout, the host falls back to the full trace view. A broken lens
+ cannot break the dashboard.
+
+## Layout and style
+
+- **Height.** The host sizes the frame to the document's height and keeps it
+ updated as the content changes. Do not use `100vh` or `height: 100%` on the
+ root; let the page grow.
+- **Width.** Use the full frame width, with no centred `max-width` and no outer
+ padding on `html` or `body`. Do not put a background on the root; the frame
+ is transparent over the dashboard.
+- **Tokens.** Before the lens's own styles, the host defines these custom
+ properties on `:root`. Use them with a fallback so the file also renders on
+ its own:
+
+ | Token | Value |
+ |---|---|
+ | `--beacon-text` | `#111827` |
+ | `--beacon-muted` | `#6b7280` |
+ | `--beacon-line` | `rgba(0, 0, 0, 0.1)` |
+ | `--beacon-panel-soft` | `#f9fafb` |
+ | `--beacon-accent` | `#036aa2` |
+ | `--beacon-accent-soft` | `#e2f0f8` |
+ | `--beacon-danger` | `#b91c1c` |
+ | `--beacon-warn` | `#92400e` |
+ | `--beacon-ok` | `#047857` |
+ | `--beacon-font-sans` | the dashboard's sans stack |
+ | `--beacon-font-mono` | `ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace` |
+
+- **Type.** 13–14px body at weight 400; monospace at 13px for code, paths and
+ commands. Use as few type sizes and spacing values as you can.
+- **Density.** Prefer compact tables and tight rows over padded cards. Use
+ hairline borders (`--beacon-line`) rather than shadows. Right-align numbers
+ and format them with `Intl.NumberFormat`. Keep animation under 150 ms.
+- **Colour.** Use `--beacon-accent` for links and focus, and `--beacon-danger`,
+ `--beacon-warn` and `--beacon-ok` only where they mean something.
+
+## Robustness
+
+- Render a loading state immediately, then fill it in when `getTrace()`
+ resolves. On rejection, show the error message.
+- Only these are guaranteed present: `api_version`, `trace.schema_version`,
+ `trace.id`, `trace.summary.id`, `trace.events` (possibly empty), each
+ event's `id`, `number`, `timestamp`, `type` and `action`, and `truncated`.
+ Every other field is optional, so show a placeholder when it is missing.
+- Skip event types, finding fields and enum values you do not recognise.
+ Additive changes do not bump the API version.
+- **Treat every string as untrusted.** Trace content is what an agent and the
+ tools it ran produced. Insert it with `textContent` or
+ `document.createTextNode`, never with `innerHTML`, `outerHTML`,
+ `insertAdjacentHTML` or `document.write`, and never as a URL.
+- Expect thousands of events. Build the DOM once, and paginate or virtualise
+ long lists.
+
+## Versioning
+
+- `lenses/v1` is this document; `beacon.lens.v1` is the data contract.
+- Adding an optional field to `LensDataV1`, the trace bundle, or the manifest
+ is backward compatible and keeps both versions.
+- Removing or renaming a field, changing a field's meaning, or loosening the
+ sandbox is a breaking change. It ships as `beacon.lens.v2` alongside `v1`,
+ and the dashboard keeps serving `v1` lenses the `v1` shape.
+
+### Changelog
+
+- `lenses/v1`: initial specification.
+- `lenses/v1` (additive): `token_usage`, the counted usage of the trace.
diff --git a/cli/beacon/internal/endpoint/dashboard/lenses_test.go b/cli/beacon/internal/endpoint/dashboard/lenses_test.go
index 75dd2a9b..a185192e 100644
--- a/cli/beacon/internal/endpoint/dashboard/lenses_test.go
+++ b/cli/beacon/internal/endpoint/dashboard/lenses_test.go
@@ -403,3 +403,30 @@ func TestStoreLensesAreServedFromTheStore(t *testing.T) {
t.Fatalf("removed lens = %d, want 404", rec.Code)
}
}
+
+// Built-in lenses are the examples users and agents copy, so they lint clean.
+func TestBuiltinLensesLintClean(t *testing.T) {
+ names, err := fs.Glob(builtinLensFiles, "lenses/*.lens.html")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, name := range names {
+ html, _ := builtinLensFiles.ReadFile(name)
+ if findings := lensstore.Lint(html); len(findings) != 0 {
+ t.Errorf("%s: %+v", name, findings)
+ }
+ }
+}
+
+func TestEmbeddedLensSpecIsThePublishedSpec(t *testing.T) {
+ published, err := os.ReadFile(filepath.Join(lensSpecDir(t), "SPEC.md"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if LensSpec() != string(published) {
+ t.Fatal("lenses/SPEC.md drifted from spec/lenses/SPEC.md; copy the spec over")
+ }
+ if !bytes.Contains(ExampleLens(), []byte(`"id": "activity"`)) {
+ t.Fatal("ExampleLens is not the activity lens")
+ }
+}
diff --git a/cli/beacon/internal/endpoint/lensstore/lint.go b/cli/beacon/internal/endpoint/lensstore/lint.go
new file mode 100644
index 00000000..6e1d8723
--- /dev/null
+++ b/cli/beacon/internal/endpoint/lensstore/lint.go
@@ -0,0 +1,82 @@
+package lensstore
+
+import (
+ "regexp"
+ "strings"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+)
+
+// Lint severities. An error means the dashboard will not run the lens; a warning means the lens
+// will run but something in it cannot work in the sandbox or breaks a rule in the spec.
+const (
+ LintError = "error"
+ LintWarning = "warning"
+)
+
+// LintFinding is one problem in a lens file. Line is 1-based, or 0 for the file as a whole.
+type LintFinding struct {
+ Line int `json:"line,omitempty"`
+ Severity string `json:"severity"`
+ Message string `json:"message"`
+}
+
+// lintChecks are line-level patterns for things the spec forbids or the sandbox blocks. They are
+// heuristics over the source text, which is what an agent writing a lens needs to hear about
+// before it opens a browser; the sandbox is what actually enforces them.
+var lintChecks = []struct {
+ pattern *regexp.Regexp
+ message string
+}{
+ {regexp.MustCompile(`\.(innerHTML|outerHTML)\s*[+]?=|insertAdjacentHTML\s*\(|document\.write(ln)?\s*\(`),
+ "parses a string as HTML; trace content is untrusted, so build nodes with textContent"},
+ {regexp.MustCompile(`\beval\s*\(|\bnew\s+Function\s*\(|setTimeout\s*\(\s*["'` + "`" + `]`),
+ "evaluates a string as code, which the lens CSP blocks"},
+ {regexp.MustCompile(`\bfetch\s*\(|\bXMLHttpRequest\b|\bnew\s+WebSocket\b|\bnew\s+EventSource\b|\bsendBeacon\s*\(`),
+ "makes a network request, which the lens CSP blocks (connect-src 'none'); everything comes from getTrace()"},
+ {regexp.MustCompile(`\b(src|href|action|poster)\s*=\s*["']?\s*(https?:)?//`),
+ "loads a resource by URL, which the lens CSP blocks; inline it or use a data: URI"},
+ {regexp.MustCompile(`url\(\s*["']?\s*(https?:)?//|@import\b`),
+ "loads a stylesheet resource by URL, which the lens CSP blocks"},
+ {regexp.MustCompile(`\b(localStorage|sessionStorage|indexedDB)\b|document\.cookie`),
+ "uses browser storage, which an opaque-origin lens frame does not have; keep state in memory"},
+ {regexp.MustCompile(`\b(window\.)?(parent|top|opener)\.(postMessage|document|location)\b|\blocation\.(href|assign|replace)\b`),
+ "talks to or navigates a window; the host ignores window messages and closes a lens that navigates"},
+ {regexp.MustCompile(`\b100vh\b|\bheight\s*:\s*100%`),
+ "sizes to the viewport; the frame grows to fit the document, so a viewport-height root never settles"},
+ {regexp.MustCompile(`new\s+Worker\s*\(|new\s+SharedWorker\s*\(|serviceWorker`),
+ "starts a worker, which the lens CSP blocks"},
+}
+
+// Lint checks a lens file against spec/lenses/SPEC.md. The file-level rules (size, manifest) are
+// errors; everything else is a warning tied to the line it appears on.
+func Lint(html []byte) []LintFinding {
+ var findings []LintFinding
+ if _, err := asymptoteobserve.CheckLensFile(html); err != nil {
+ for _, line := range strings.Split(err.Error(), "\n") {
+ findings = append(findings, LintFinding{Severity: LintError, Message: line})
+ }
+ }
+ text := strings.ReplaceAll(string(html), "\r\n", "\n")
+ for i, line := range strings.Split(text, "\n") {
+ for _, check := range lintChecks {
+ if check.pattern.MatchString(line) {
+ findings = append(findings, LintFinding{Line: i + 1, Severity: LintWarning, Message: check.message})
+ }
+ }
+ }
+ if !strings.Contains(text, "window.beacon.getTrace()") && !strings.Contains(text, "beacon.getTrace()") {
+ findings = append(findings, LintFinding{Severity: LintWarning, Message: "never calls window.beacon.getTrace(), so it has no trace to render and the dashboard will give up on it after 10 seconds"})
+ }
+ return findings
+}
+
+// HasLintErrors reports whether any finding is an error.
+func HasLintErrors(findings []LintFinding) bool {
+ for _, f := range findings {
+ if f.Severity == LintError {
+ return true
+ }
+ }
+ return false
+}
diff --git a/cli/beacon/internal/endpoint/lensstore/lint_test.go b/cli/beacon/internal/endpoint/lensstore/lint_test.go
new file mode 100644
index 00000000..3d1deaac
--- /dev/null
+++ b/cli/beacon/internal/endpoint/lensstore/lint_test.go
@@ -0,0 +1,80 @@
+package lensstore
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+const lintManifest = `<script type="application/beacon-lens+json">{"id":"x","title":"X","version":1,"api":"beacon.lens.v1"}</script>`
+
+func TestLintFlagsWhatTheSandboxBlocks(t *testing.T) {
+ cases := map[string]string{
+ `el.innerHTML = data.trace.title`: "textContent",
+ `el.insertAdjacentHTML("beforeend", s)`: "textContent",
+ `eval("1 + 1")`: "evaluates a string",
+ `fetch("/api/status")`: "network request",
+ `new WebSocket("ws://x")`: "network request",
+ `<script src="https://cdn.example/lib.js"></script>`: "by URL",
+ `<img src="//cdn.example/a.png">`: "by URL",
+ `body { background: url(https://x/y.png) }`: "stylesheet resource",
+ `@import "theme.css";`: "stylesheet resource",
+ `localStorage.setItem("k", "v")`: "storage",
+ `window.parent.postMessage({}, "*")`: "navigates a window",
+ `location.href = "/elsewhere"`: "navigates a window",
+ `main { height: 100vh }`: "viewport",
+ `new Worker(url)`: "worker",
+ }
+ for line, want := range cases {
+ html := "<!doctype html>\n" + lintManifest + "\n<script>window.beacon.getTrace()</script>\n" + line + "\n"
+ findings := Lint([]byte(html))
+ var hit *LintFinding
+ for i := range findings {
+ if strings.Contains(findings[i].Message, want) {
+ hit = &findings[i]
+ }
+ }
+ if hit == nil || hit.Line != 4 || hit.Severity != LintWarning {
+ t.Errorf("Lint(%q) = %+v, want a line-4 warning about %q", line, findings, want)
+ }
+ if HasLintErrors(findings) {
+ t.Errorf("Lint(%q) reported an error for a warning-level problem: %+v", line, findings)
+ }
+ }
+}
+
+func TestLintClean(t *testing.T) {
+ html := "<!doctype html>\r\n" + lintManifest + "\r\n<p id=out></p>\r\n<script>\r\nwindow.beacon.getTrace().then(function (d) { out.textContent = d.trace.id; });\r\n</script>\r\n"
+ if findings := Lint([]byte(html)); len(findings) != 0 {
+ t.Fatalf("a clean lens (with CRLF line endings) got %+v", findings)
+ }
+}
+
+func TestLintErrorsAndMissingGetTrace(t *testing.T) {
+ findings := Lint([]byte("<p>no manifest</p>"))
+ if !HasLintErrors(findings) {
+ t.Fatalf("a lens without a manifest has no error: %+v", findings)
+ }
+ found := false
+ for _, f := range findings {
+ if strings.Contains(f.Message, "never calls window.beacon.getTrace()") {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatalf("missing getTrace not reported: %+v", findings)
+ }
+}
+
+// The hostile e2e probe does everything the spec forbids; lint should say so.
+func TestLintCatchesTheHostileProbe(t *testing.T) {
+ html, err := os.ReadFile(filepath.Join("..", "dashboard", "testdata", "lens-e2e", "fixtures", "probe.lens.html"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ findings := Lint(html)
+ if HasLintErrors(findings) || len(findings) < 6 {
+ t.Fatalf("probe lint = %+v, want several warnings and no errors", findings)
+ }
+}