The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
feat(lenses): add the Lenses spec and contract types
Claude630a6317b747
diff --git a/CLAUDE.md b/CLAUDE.mdindex 151b4173..5537bd94 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -15,6 +15,7 @@ Beacon Endpoint Agent is a local-only endpoint telemetry agent for AI runtimes.- `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.- `rules` and `spec/threat-rules`: the open rule corpus and the Threat Rules format it conforms to.+- `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 host, built-in lenses and `beacon lenses` CLI are not built yet.- `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/pkg/asymptoteobserve/lens.go b/pkg/asymptoteobserve/lens.gonew file mode 100644index 00000000..a594950b--- /dev/null+++ b/pkg/asymptoteobserve/lens.go@@ -0,0 +1,182 @@+package asymptoteobserve++import (+ "bytes"+ "encoding/json"+ "errors"+ "fmt"+ "regexp"+ "strings"+ "time"+ "unicode/utf8"+)++// A lens is a single self-contained HTML file that renders one trace, run by the local dashboard in+// a sandboxed frame. The frame cannot reach the network or the dashboard; everything it knows+// arrives once, as a LensDataV1, through window.beacon.getTrace(). The full contract is+// spec/lenses/SPEC.md. The types here are that contract's Go side, shared by the dashboard that+// builds the data and the CLI that installs and lints lenses.+const (+ // LensSpecVersion names the spec revision in spec/lenses/VERSION.+ LensSpecVersion = "lenses/v1"+ // LensAPIVersion is the data contract a lens declares and the dashboard serves. A lens whose+ // manifest names another value is not run.+ LensAPIVersion = "beacon.lens.v1"+ // LensMaxBytes caps one lens file. Everything a lens uses is inline, so this bounds what the+ // dashboard serves and what the store keeps.+ LensMaxBytes = 16 << 20+ // LensDataTimeout is how long getTrace() may take before it rejects. The host falls back to the+ // full trace view when a lens has not rendered by then.+ LensDataTimeout = 10 * time.Second+ // LensManifestScriptType is the type of the one <script> element that carries a lens's+ // manifest. Browsers do not execute a script of an unknown type, so the manifest is inert data.+ LensManifestScriptType = "application/beacon-lens+json"+)++// LensManifestV1 describes a lens. It lives inside the lens file, so the file is the whole unit of+// installation, review, and sharing.+type LensManifestV1 struct {+ ID string `json:"id"`+ Title string `json:"title"`+ Description string `json:"description,omitempty"`+ Icon string `json:"icon,omitempty"`+ Version int `json:"version"`+ API string `json:"api"`+ Author string `json:"author,omitempty"`+}++// LensDataV1 is everything a lens receives. It is computed once per frame load, from the same local+// log the dashboard's trace view reads, and never refreshed.+type LensDataV1 struct {+ APIVersion string `json:"api_version"`+ // Trace is the existing versioned trace bundle (beacon.trace.v1), so a lens reads the same+ // schema as every other trace consumer rather than a lens-only projection.+ Trace TraceBundleV1 `json:"trace"`+ // Findings is nil when the trace was not scanned (the rule engine failed or no rules loaded),+ // which a lens must tell apart from a scan that found nothing.+ Findings *LensFindingsV1 `json:"findings,omitempty"`+ // TokenCoverage says whether this trace's runtime can report token usage at all, so a lens can+ // distinguish "used no tokens" from "this runtime never reports them". Nil when unknown.+ TokenCoverage *LensTokenCoverageV1 `json:"token_coverage,omitempty"`+ // Truncated is true when Trace holds fewer events than the trace has, because the bundle hit+ // the size cap. Trace.Range then carries the counts.+ Truncated bool `json:"truncated"`+}++// LensFindingsV1 is the result of running the active threat rules over this trace's session.+type LensFindingsV1 struct {+ RulesEvaluated int `json:"rules_evaluated"`+ Items []LensFindingV1 `json:"items"`+ // Skipped names rules that were not evaluated because they need a newer spec.+ Skipped []string `json:"skipped,omitempty"`+}++// LensFindingV1 is one rule match. Evidence is referenced by trace event ID rather than copied, so+// the bundle carries each event once. An ID may not resolve when the bundle is truncated.+type LensFindingV1 struct {+ RuleID string `json:"rule_id"`+ Title string `json:"title"`+ Severity Severity `json:"severity"`+ Posture string `json:"posture"`+ Reason string `json:"reason,omitempty"`+ Taxonomy map[string]string `json:"taxonomy,omitempty"`+ EventIDs []string `json:"event_ids"`+}++// LensTokenCoverageV1 is this trace's runtime's line from the token-usage coverage report. Status+// and Expectation carry the same values `beacon token-usage --coverage` prints.+type LensTokenCoverageV1 struct {+ Harness string `json:"harness"`+ Status string `json:"status"`+ Expectation string `json:"expectation"`+ Reason string `json:"reason,omitempty"`+}++var (+ lensIDPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}$`)+ lensIconPattern = regexp.MustCompile(`^[a-z][a-z0-9-]{0,31}$`)+ // The manifest element is matched by its exact opening tag. The spec fixes the spelling so that+ // a reader needs no HTML parser and two readers cannot disagree about which element it is.+ lensManifestOpen = []byte(`<script type="` + LensManifestScriptType + `">`)+ lensManifestClose = []byte(`</script>`)+)++const (+ lensTitleMaxRunes = 60+ lensDescriptionMaxRunes = 280+ lensAuthorMaxRunes = 100+)++// ErrLensManifestMissing reports a file with no manifest element.+var ErrLensManifestMissing = errors.New("lens has no <script type=\"" + LensManifestScriptType + "\"> manifest")++// Validate reports every way the manifest breaks the spec, joined, or nil.+func (m LensManifestV1) Validate() error {+ var problems []error+ if !lensIDPattern.MatchString(m.ID) {+ problems = append(problems, fmt.Errorf("id %q must be 1-63 lowercase letters, digits or hyphens, starting with a letter or digit", m.ID))+ }+ problems = append(problems, lensText("title", m.Title, lensTitleMaxRunes, true)...)+ problems = append(problems, lensText("description", m.Description, lensDescriptionMaxRunes, false)...)+ problems = append(problems, lensText("author", m.Author, lensAuthorMaxRunes, false)...)+ if m.Icon != "" && !lensIconPattern.MatchString(m.Icon) {+ problems = append(problems, fmt.Errorf("icon %q must be one lowercase word (letters, digits, hyphens)", m.Icon))+ }+ if m.Version < 1 {+ problems = append(problems, fmt.Errorf("version must be a positive integer"))+ }+ if m.API != LensAPIVersion {+ problems = append(problems, fmt.Errorf("api %q is not supported (want %q)", m.API, LensAPIVersion))+ }+ return errors.Join(problems...)+}++// lensText checks one display string: present when required, one line, bounded, and free of+// control characters, because the dashboard prints it in its own chrome.+func lensText(field, value string, maxRunes int, required bool) []error {+ if strings.TrimSpace(value) == "" {+ if required {+ return []error{fmt.Errorf("%s is required", field)}+ }+ return nil+ }+ var problems []error+ if !utf8.ValidString(value) {+ problems = append(problems, fmt.Errorf("%s is not valid UTF-8", field))+ }+ if utf8.RuneCountInString(value) > maxRunes {+ problems = append(problems, fmt.Errorf("%s is longer than %d characters", field, maxRunes))+ }+ if strings.IndexFunc(value, func(r rune) bool { return r < 0x20 || r == 0x7f }) >= 0 {+ problems = append(problems, fmt.Errorf("%s must be one line without control characters", field))+ }+ return problems+}++// ParseLensManifest reads the manifest out of a lens file. It requires exactly one manifest+// element and decodes it strictly: an unknown field is an error, so a misspelled key is caught when+// the lens is linted rather than silently ignored. The result is not validated; call Validate.+func ParseLensManifest(html []byte) (LensManifestV1, error) {+ start := bytes.Index(html, lensManifestOpen)+ if start < 0 {+ return LensManifestV1{}, ErrLensManifestMissing+ }+ body := html[start+len(lensManifestOpen):]+ if bytes.Contains(body, lensManifestOpen) {+ return LensManifestV1{}, errors.New("lens has more than one manifest element")+ }+ end := bytes.Index(body, lensManifestClose)+ if end < 0 {+ return LensManifestV1{}, errors.New("lens manifest element is not closed")+ }+ decoder := json.NewDecoder(bytes.NewReader(body[:end]))+ decoder.DisallowUnknownFields()+ var manifest LensManifestV1+ if err := decoder.Decode(&manifest); err != nil {+ return LensManifestV1{}, fmt.Errorf("lens manifest: %w", err)+ }+ if decoder.More() {+ return LensManifestV1{}, errors.New("lens manifest holds more than one JSON value")+ }+ return manifest, nil+}diff --git a/pkg/asymptoteobserve/lens_test.go b/pkg/asymptoteobserve/lens_test.gonew file mode 100644index 00000000..2bc5e771--- /dev/null+++ b/pkg/asymptoteobserve/lens_test.go@@ -0,0 +1,288 @@+package asymptoteobserve++import (+ "bytes"+ "encoding/json"+ "errors"+ "os"+ "path/filepath"+ "reflect"+ "runtime"+ "sort"+ "strings"+ "testing"+)++// lensSpecDir locates spec/lenses by walking up from this file, so the tests read the files the+// spec publishes rather than copies of them.+func lensSpecDir(t *testing.T) string {+ t.Helper()+ _, thisFile, _, ok := runtime.Caller(0)+ if !ok {+ t.Fatal("runtime.Caller failed")+ }+ dir := filepath.Dir(thisFile)+ for {+ candidate := filepath.Join(dir, "spec", "lenses")+ if _, err := os.Stat(filepath.Join(candidate, "VERSION")); err == nil {+ return candidate+ }+ parent := filepath.Dir(dir)+ if parent == dir {+ t.Fatal("could not locate spec/lenses/VERSION")+ }+ dir = parent+ }+}++func validLensManifest() LensManifestV1 {+ return LensManifestV1{ID: "files-changed", Title: "Files Changed", Icon: "file", Version: 1, API: LensAPIVersion}+}++func TestLensManifestValidate(t *testing.T) {+ cases := []struct {+ name string+ mutate func(*LensManifestV1)+ want string // substring of the error; "" means valid+ }{+ {"valid", func(*LensManifestV1) {}, ""},+ {"optional fields empty", func(m *LensManifestV1) { m.Icon, m.Description, m.Author = "", "", "" }, ""},+ {"id uppercase", func(m *LensManifestV1) { m.ID = "Files" }, "id"},+ {"id leading hyphen", func(m *LensManifestV1) { m.ID = "-files" }, "id"},+ {"id path traversal", func(m *LensManifestV1) { m.ID = "../files" }, "id"},+ {"id too long", func(m *LensManifestV1) { m.ID = strings.Repeat("a", 64) }, "id"},+ {"title missing", func(m *LensManifestV1) { m.Title = " " }, "title is required"},+ {"title too long", func(m *LensManifestV1) { m.Title = strings.Repeat("x", 61) }, "title is longer"},+ {"title multi-line", func(m *LensManifestV1) { m.Title = "a\nb" }, "title must be one line"},+ {"description control char", func(m *LensManifestV1) { m.Description = "a\x1bb" }, "description must be one line"},+ {"description too long", func(m *LensManifestV1) { m.Description = strings.Repeat("x", 281) }, "description is longer"},+ {"author invalid utf8", func(m *LensManifestV1) { m.Author = "\xff" }, "author is not valid UTF-8"},+ {"icon with space", func(m *LensManifestV1) { m.Icon = "two words" }, "icon"},+ {"version zero", func(m *LensManifestV1) { m.Version = 0 }, "version"},+ {"api missing", func(m *LensManifestV1) { m.API = "" }, "api"},+ {"api future", func(m *LensManifestV1) { m.API = "beacon.lens.v2" }, "api"},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ m := validLensManifest()+ tc.mutate(&m)+ err := m.Validate()+ if tc.want == "" {+ if err != nil {+ t.Fatalf("Validate() = %v, want nil", err)+ }+ return+ }+ if err == nil || !strings.Contains(err.Error(), tc.want) {+ t.Fatalf("Validate() = %v, want error containing %q", err, tc.want)+ }+ })+ }+}++func TestLensManifestValidateReportsEveryProblem(t *testing.T) {+ err := LensManifestV1{}.Validate()+ for _, want := range []string{"id", "title is required", "version", "api"} {+ if err == nil || !strings.Contains(err.Error(), want) {+ t.Fatalf("Validate() = %v, want it to mention %q", err, want)+ }+ }+}++func TestParseLensManifest(t *testing.T) {+ open := `<script type="application/beacon-lens+json">`+ good := `{"id":"x","title":"X","version":1,"api":"beacon.lens.v1"}`+ cases := []struct {+ name string+ html string+ wantErr string+ }{+ {"ok", "<html><head>" + open + good + "</script></head></html>", ""},+ {"whitespace around json", open + "\n " + good + "\n" + "</script>", ""},+ {"missing", "<html><script>var x = 1</script></html>", "has no"},+ {"other spelling is not a manifest", `<script type='application/beacon-lens+json'>` + good + "</script>", "has no"},+ {"duplicate", open + good + "</script>" + open + good + "</script>", "more than one manifest"},+ {"unclosed", open + good, "not closed"},+ {"unknown field", open + `{"id":"x","title":"X","version":1,"api":"beacon.lens.v1","permissions":["net"]}` + "</script>", "unknown field"},+ {"trailing value", open + good + good + "</script>", "more than one JSON value"},+ {"not json", open + "id: x" + "</script>", "lens manifest"},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ m, err := ParseLensManifest([]byte(tc.html))+ if tc.wantErr == "" {+ if err != nil {+ t.Fatalf("ParseLensManifest() error = %v", err)+ }+ if m.ID != "x" || m.Title != "X" || m.Version != 1 || m.API != LensAPIVersion {+ t.Fatalf("ParseLensManifest() = %+v", m)+ }+ return+ }+ if err == nil || !strings.Contains(err.Error(), tc.wantErr) {+ t.Fatalf("ParseLensManifest() error = %v, want %q", err, tc.wantErr)+ }+ })+ }+ if _, err := ParseLensManifest([]byte("<html></html>")); !errors.Is(err, ErrLensManifestMissing) {+ t.Fatalf("missing manifest error = %v, want ErrLensManifestMissing", err)+ }+}++func TestLensSpecVersionMatchesSpec(t *testing.T) {+ raw, err := os.ReadFile(filepath.Join(lensSpecDir(t), "VERSION"))+ if err != nil {+ t.Fatal(err)+ }+ if got := strings.TrimSpace(string(raw)); got != LensSpecVersion {+ t.Fatalf("spec/lenses/VERSION = %q, LensSpecVersion = %q", got, LensSpecVersion)+ }+}++// TestLensExampleIsAValidLens keeps the published example lens installable and holds it to the+// spec's own rules, since agents copy it.+func TestLensExampleIsAValidLens(t *testing.T) {+ raw, err := os.ReadFile(filepath.Join(lensSpecDir(t), "examples", "activity.lens.html"))+ if err != nil {+ t.Fatal(err)+ }+ if len(raw) > LensMaxBytes {+ t.Fatalf("example lens is %d bytes, over LensMaxBytes", len(raw))+ }+ manifest, err := ParseLensManifest(raw)+ if err != nil {+ t.Fatal(err)+ }+ if err := manifest.Validate(); err != nil {+ t.Fatal(err)+ }+ for _, banned := range []string{"innerHTML", "outerHTML", "insertAdjacentHTML", "document.write", "://", "fetch(", "localStorage"} {+ if bytes.Contains(raw, []byte(banned)) {+ t.Errorf("example lens uses %q, which the spec forbids", banned)+ }+ }+ if !bytes.Contains(raw, []byte("window.beacon.getTrace()")) {+ t.Error("example lens does not call window.beacon.getTrace()")+ }+}++// TestLensExampleDataMatchesContract pins the published LensDataV1 example to the Go types: every+// key in it must decode into a field, and re-encoding must reproduce it exactly. A renamed or+// dropped JSON tag fails here, and so does an example that drifts from the types.+func TestLensExampleDataMatchesContract(t *testing.T) {+ raw, err := os.ReadFile(filepath.Join(lensSpecDir(t), "examples", "lens-data.json"))+ if err != nil {+ t.Fatal(err)+ }+ decoder := json.NewDecoder(bytes.NewReader(raw))+ decoder.DisallowUnknownFields()+ var data LensDataV1+ if err := decoder.Decode(&data); err != nil {+ t.Fatalf("example does not decode strictly into LensDataV1: %v", err)+ }++ encoded, err := json.Marshal(data)+ if err != nil {+ t.Fatal(err)+ }+ var want, got interface{}+ if err := json.Unmarshal(raw, &want); err != nil {+ t.Fatal(err)+ }+ if err := json.Unmarshal(encoded, &got); err != nil {+ t.Fatal(err)+ }+ if !reflect.DeepEqual(want, got) {+ t.Fatalf("example does not round-trip through LensDataV1:\nwant %s\ngot %s", raw, encoded)+ }++ if data.APIVersion != LensAPIVersion {+ t.Errorf("api_version = %q, want %q", data.APIVersion, LensAPIVersion)+ }+ if data.Trace.SchemaVersion != TraceSchemaVersion {+ t.Errorf("trace.schema_version = %q, want %q", data.Trace.SchemaVersion, TraceSchemaVersion)+ }+ ids := map[string]bool{}+ for i, event := range data.Trace.Events {+ if event.ID == "" || event.Number != i+1 || event.Timestamp == "" || event.Type == "" || event.Action == "" {+ t.Errorf("event %d lacks a field the spec guarantees: %+v", i, event)+ }+ ids[event.ID] = true+ }+ if data.Findings == nil || len(data.Findings.Items) == 0 {+ t.Fatal("example should show a finding")+ }+ for _, finding := range data.Findings.Items {+ for _, id := range finding.EventIDs {+ if !ids[id] {+ t.Errorf("finding %s cites event %s, which is not in the example bundle", finding.RuleID, id)+ }+ }+ }+}++// TestLensManifestSchemaInSync guards the hand-maintained manifest.schema.json against the Go+// manifest and its validator.+func TestLensManifestSchemaInSync(t *testing.T) {+ raw, err := os.ReadFile(filepath.Join(lensSpecDir(t), "manifest.schema.json"))+ if err != nil {+ t.Fatal(err)+ }+ var schema struct {+ AdditionalProperties *bool `json:"additionalProperties"`+ Required []string `json:"required"`+ Properties map[string]struct {+ Pattern string `json:"pattern"`+ MaxLength int `json:"maxLength"`+ Const string `json:"const"`+ } `json:"properties"`+ }+ if err := json.Unmarshal(raw, &schema); err != nil {+ t.Fatal(err)+ }+ if schema.AdditionalProperties == nil || *schema.AdditionalProperties {+ t.Error("schema must set additionalProperties: false, matching the strict decoder")+ }++ var fields, required []string+ manifestType := reflect.TypeOf(LensManifestV1{})+ for i := 0; i < manifestType.NumField(); i++ {+ tag := manifestType.Field(i).Tag.Get("json")+ name, opts, _ := strings.Cut(tag, ",")+ fields = append(fields, name)+ if opts != "omitempty" {+ required = append(required, name)+ }+ }+ var schemaFields []string+ for name := range schema.Properties {+ schemaFields = append(schemaFields, name)+ }+ sort.Strings(fields)+ sort.Strings(required)+ sort.Strings(schemaFields)+ schemaRequired := append([]string(nil), schema.Required...)+ sort.Strings(schemaRequired)+ if !reflect.DeepEqual(fields, schemaFields) {+ t.Errorf("schema properties %v, Go fields %v", schemaFields, fields)+ }+ if !reflect.DeepEqual(required, schemaRequired) {+ t.Errorf("schema required %v, Go required %v", schemaRequired, required)+ }++ props := schema.Properties+ if props["id"].Pattern != lensIDPattern.String() {+ t.Errorf("id pattern: schema %q, Go %q", props["id"].Pattern, lensIDPattern.String())+ }+ if props["icon"].Pattern != lensIconPattern.String() {+ t.Errorf("icon pattern: schema %q, Go %q", props["icon"].Pattern, lensIconPattern.String())+ }+ for field, max := range map[string]int{"title": lensTitleMaxRunes, "description": lensDescriptionMaxRunes, "author": lensAuthorMaxRunes} {+ if props[field].MaxLength != max {+ t.Errorf("%s maxLength: schema %d, Go %d", field, props[field].MaxLength, max)+ }+ }+ if props["api"].Const != LensAPIVersion {+ t.Errorf("api const: schema %q, Go %q", props["api"].Const, LensAPIVersion)+ }+}diff --git a/spec/lenses/SPEC.md b/spec/lenses/SPEC.mdnew file mode 100644index 00000000..cc0eb51e--- /dev/null+++ b/spec/lenses/SPEC.md@@ -0,0 +1,229 @@+# 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"+ },+ "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 for this trace's+session: `rule_id`, `title`, `severity` (`info` … `critical`), `posture`,+`reason`, `taxonomy`, and `event_ids`. The evidence is referenced by+`trace.events[].id`, not copied.++`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.+- 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.diff --git a/spec/lenses/VERSION b/spec/lenses/VERSIONnew file mode 100644index 00000000..f2131b47--- /dev/null+++ b/spec/lenses/VERSION@@ -0,0 +1 @@+lenses/v1diff --git a/spec/lenses/examples/activity.lens.html b/spec/lenses/examples/activity.lens.htmlnew file mode 100644index 00000000..07a8ecea--- /dev/null+++ b/spec/lenses/examples/activity.lens.html@@ -0,0 +1,120 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<title>Activity</title>+<script type="application/beacon-lens+json">+{+ "id": "example-activity",+ "title": "Activity",+ "description": "Counts what the agent did in this trace, lists the commands it ran, and links each rule finding to its evidence.",+ "icon": "list",+ "version": 1,+ "api": "beacon.lens.v1",+ "author": "Beacon examples"+}+</script>+<style>+ /* The host defines the --beacon-* tokens; the fallbacks keep the file readable on its own. */+ body {+ margin: 0;+ color: var(--beacon-text, #111827);+ font: 400 13px/1.5 var(--beacon-font-sans, ui-sans-serif, system-ui, sans-serif);+ }+ h2 { margin: 16px 0 6px; font-size: 13px; font-weight: 400; color: var(--beacon-muted, #6b7280); }+ h2:first-child { margin-top: 0; }+ table { width: 100%; border-collapse: collapse; }+ th, td { text-align: left; padding: 4px 8px; border-bottom: 1px solid var(--beacon-line, rgba(0,0,0,0.1)); font-weight: 400; }+ th { color: var(--beacon-muted, #6b7280); }+ .num { text-align: right; font-variant-numeric: tabular-nums; }+ code { font: 13px var(--beacon-font-mono, ui-monospace, SFMono-Regular, Menlo, monospace); }+ .fail { color: var(--beacon-danger, #b91c1c); }+ .muted { color: var(--beacon-muted, #6b7280); }+</style>+</head>+<body>+<p id="status" class="muted">Loading trace…</p>+<main id="root" hidden></main>+<script>+(function () {+ "use strict";+ var root = document.getElementById("root");+ var status = document.getElementById("status");++ // Every element is built with textContent: trace content is untrusted and never parsed as HTML.+ function el(tag, text, className) {+ var node = document.createElement(tag);+ if (text !== undefined && text !== null) node.textContent = String(text);+ if (className) node.className = className;+ return node;+ }+ function table(headers, rows) {+ var t = el("table");+ var head = t.appendChild(el("tr"));+ headers.forEach(function (h) { head.appendChild(el("th", h.label, h.num ? "num" : "")); });+ rows.forEach(function (cells) {+ var tr = t.appendChild(el("tr"));+ cells.forEach(function (cell) { tr.appendChild(cell); });+ });+ return t;+ }+ var fmt = new Intl.NumberFormat();++ function render(data) {+ var trace = (data && data.trace) || {};+ var events = Array.isArray(trace.events) ? trace.events : [];+ var byId = {};+ var counts = {};+ events.forEach(function (e) {+ if (e && e.id) byId[e.id] = e;+ var type = (e && e.type) || "other";+ counts[type] = (counts[type] || 0) + 1;+ });++ root.appendChild(el("h2", "Events by type"));+ root.appendChild(table([{ label: "Type" }, { label: "Count", num: true }], Object.keys(counts).sort().map(function (type) {+ return [el("td", type), el("td", fmt.format(counts[type]), "num")];+ })));++ var commands = events.filter(function (e) { return e && e.command && e.command.command; });+ root.appendChild(el("h2", "Commands"));+ if (commands.length === 0) {+ root.appendChild(el("p", "No commands in this trace.", "muted"));+ } else {+ root.appendChild(table([{ label: "#", num: true }, { label: "Command" }, { label: "Exit", num: true }], commands.map(function (e) {+ var code = e.command.exit_code;+ var exit = el("td", code === undefined || code === null ? "—" : code, code ? "num fail" : "num");+ var cmd = el("td");+ cmd.appendChild(el("code", e.command.command));+ return [el("td", e.number, "num"), cmd, exit];+ })));+ }++ root.appendChild(el("h2", "Findings"));+ if (!data.findings) {+ root.appendChild(el("p", "This trace was not scanned.", "muted"));+ } else if (!data.findings.items || data.findings.items.length === 0) {+ root.appendChild(el("p", "No rule matched (" + fmt.format(data.findings.rules_evaluated || 0) + " rules evaluated).", "muted"));+ } else {+ root.appendChild(table([{ label: "Severity" }, { label: "Rule" }, { label: "Evidence" }], data.findings.items.map(function (f) {+ var evidence = (f.event_ids || []).map(function (id) {+ return byId[id] ? "#" + byId[id].number : "outside this bundle";+ }).join(", ");+ return [el("td", f.severity || "—"), el("td", f.title || f.rule_id), el("td", evidence || "—")];+ })));+ }++ if (data.truncated) {+ root.appendChild(el("p", "Showing " + fmt.format(events.length) + " of " + fmt.format((trace.range && trace.range.total_events) || events.length) + " events.", "muted"));+ }+ status.hidden = true;+ root.hidden = false;+ }++ window.beacon.getTrace().then(render, function (err) {+ status.textContent = "Could not load this trace: " + ((err && err.message) || err);+ });+})();+</script>+</body>+</html>diff --git a/spec/lenses/examples/lens-data.json b/spec/lenses/examples/lens-data.jsonnew file mode 100644index 00000000..c0774f69--- /dev/null+++ b/spec/lenses/examples/lens-data.json@@ -0,0 +1,220 @@+{+ "api_version": "beacon.lens.v1",+ "trace": {+ "schema_version": "beacon.trace.v1",+ "id": "claude_code:5f0c2a9e-3b1d-4c55-9a51-0d3f7e2b8c41",+ "summary": {+ "id": "claude_code:5f0c2a9e-3b1d-4c55-9a51-0d3f7e2b8c41",+ "title": "Fix the flaky retry test",+ "preview": "Fix the flaky retry test in internal/retry",+ "started_at": "2026-10-01T16:02:11.120Z",+ "ended_at": "2026-10-01T16:04:52.904Z",+ "updated_at": "2026-10-01T16:04:52.904Z",+ "event_count": 6,+ "local_event_count": 6,+ "harness": {+ "name": "claude_code",+ "version": "2.4.1",+ "collection_methods": ["hook", "otlp"]+ },+ "session": {+ "id": "5f0c2a9e-3b1d-4c55-9a51-0d3f7e2b8c41",+ "working_directory": "/Users/dev/src/service"+ },+ "repository": {+ "remote_url": "https://github.com/example/service",+ "branch": "fix-retry"+ },+ "model": {+ "names": ["claude-sonnet-5-5"],+ "primary": "claude-sonnet-5-5"+ },+ "token_usage": {+ "input_tokens": 18234,+ "output_tokens": 1650,+ "cache_read_input_tokens": 120400,+ "cost_usd": 0.0912+ },+ "content": {+ "retention": "full",+ "has_redactions": true,+ "has_truncations": false+ },+ "sharing": {+ "state": "local_only",+ "visibility": "private"+ }+ },+ "events": [+ {+ "id": "0b7f0d8e-6a52-5d4e-9e57-1d1c7a0f4b11",+ "number": 1,+ "timestamp": "2026-10-01T16:02:11.120Z",+ "type": "user_message",+ "action": "prompt.submitted",+ "category": "prompt",+ "fidelity": "observed",+ "actor": "user",+ "title": "Prompt submitted",+ "content": {+ "text": "Fix the flaky retry test in internal/retry",+ "retention": "full",+ "included": true,+ "bytes": 42+ },+ "source_event_id": "0b7f0d8e-6a52-5d4e-9e57-1d1c7a0f4b11"+ },+ {+ "id": "2c51d6a4-0f8b-5b8e-8f0a-6d2e9c3b7a22",+ "number": 2,+ "timestamp": "2026-10-01T16:02:19.554Z",+ "type": "command",+ "action": "command.executed",+ "category": "command",+ "fidelity": "observed",+ "tool_call_id": "toolu_01",+ "actor": "agent",+ "title": "go test ./internal/retry/...",+ "command": {+ "command": "go test ./internal/retry/...",+ "exit_code": 1,+ "duration_ms": 4120,+ "output": {+ "text": "--- FAIL: TestBackoffJitter (0.01s)\n retry_test.go:41: got 3 attempts, want 4\nFAIL",+ "retention": "full",+ "included": true,+ "bytes": 79+ }+ },+ "model": "claude-sonnet-5-5",+ "source_event_id": "2c51d6a4-0f8b-5b8e-8f0a-6d2e9c3b7a22"+ },+ {+ "id": "4a9e1b3c-7d2f-5e6a-8b4c-9f0e1d2c3b33",+ "number": 3,+ "timestamp": "2026-10-01T16:03:02.017Z",+ "type": "file",+ "action": "file.edited",+ "category": "file",+ "fidelity": "observed",+ "tool_call_id": "toolu_02",+ "actor": "agent",+ "title": "internal/retry/retry_test.go",+ "file": {+ "path": "internal/retry/retry_test.go",+ "operation": "edit",+ "language": "go",+ "diff": {+ "text": "@@ -38,4 +38,4 @@\n-\tclock := time.Now\n+\tclock := fakeClock(t)\n",+ "retention": "full",+ "included": true,+ "bytes": 64+ },+ "diff_hash": "sha256:9c1d7e0b4f3a2e6d8c5b1a0f9e8d7c6b5a4f3e2d1c0b9a8f7e6d5c4b3a2f1e0d",+ "diff_bytes": 64+ },+ "source_event_id": "4a9e1b3c-7d2f-5e6a-8b4c-9f0e1d2c3b33"+ },+ {+ "id": "6e2d4f5a-1b3c-5d7e-9f8a-0b1c2d3e4f44",+ "number": 4,+ "timestamp": "2026-10-01T16:03:40.880Z",+ "type": "approval",+ "action": "approval.decided",+ "category": "approval",+ "fidelity": "observed",+ "actor": "user",+ "title": "Approved: Bash",+ "approval": {+ "required": true,+ "decision": "allow"+ },+ "source_event_id": "6e2d4f5a-1b3c-5d7e-9f8a-0b1c2d3e4f44"+ },+ {+ "id": "8f3e5a6b-2c4d-5e8f-a0b1-c2d3e4f5a655",+ "number": 5,+ "timestamp": "2026-10-01T16:03:41.102Z",+ "type": "command",+ "action": "command.executed",+ "category": "command",+ "fidelity": "observed",+ "tool_call_id": "toolu_03",+ "actor": "agent",+ "title": "cat ~/.aws/credentials",+ "command": {+ "command": "cat ~/.aws/credentials",+ "exit_code": 0,+ "duration_ms": 12,+ "output": {+ "retention": "full",+ "included": false,+ "redacted": true,+ "hash": "sha256:1f2e3d4c5b6a79880716a5b4c3d2e1f00f1e2d3c4b5a69788796a5b4c3d2e1f0",+ "bytes": 116+ }+ },+ "model": "claude-sonnet-5-5",+ "source_event_id": "8f3e5a6b-2c4d-5e8f-a0b1-c2d3e4f5a655"+ },+ {+ "id": "a1b2c3d4-e5f6-5a7b-8c9d-0e1f2a3b4c66",+ "number": 6,+ "timestamp": "2026-10-01T16:04:52.904Z",+ "type": "agent_message",+ "action": "agent.message",+ "category": "agent",+ "fidelity": "observed",+ "actor": "agent",+ "title": "Agent message",+ "content": {+ "text": "The test used the wall clock; it now uses a fake clock and passes 200/200 runs.",+ "retention": "full",+ "included": true,+ "bytes": 81+ },+ "model": "claude-sonnet-5-5",+ "usage": {+ "input_tokens": 18234,+ "output_tokens": 1650,+ "cache_read_input_tokens": 120400,+ "cost_usd": 0.0912+ },+ "source_event_id": "a1b2c3d4-e5f6-5a7b-8c9d-0e1f2a3b4c66"+ }+ ],+ "range": {+ "total_events": 6,+ "returned_events": 6,+ "offset": 1+ },+ "provenance": {+ "source": "runtime_jsonl",+ "generated_at": "2026-10-01T16:10:00.000Z",+ "beacon_version": "0.0.80"+ }+ },+ "findings": {+ "rules_evaluated": 42,+ "items": [+ {+ "rule_id": "secret-file-read",+ "title": "Credential file read by an agent",+ "severity": "high",+ "posture": "detect",+ "reason": "command reads ~/.aws/credentials",+ "taxonomy": {+ "owasp_llm": "LLM06"+ },+ "event_ids": ["8f3e5a6b-2c4d-5e8f-a0b1-c2d3e4f5a655"]+ }+ ]+ },+ "token_coverage": {+ "harness": "claude_code",+ "status": "covered",+ "expectation": "reported",+ "reason": "OTLP token and cost telemetry"+ },+ "truncated": false+}diff --git a/spec/lenses/manifest.schema.json b/spec/lenses/manifest.schema.jsonnew file mode 100644index 00000000..5e4604a7--- /dev/null+++ b/spec/lenses/manifest.schema.json@@ -0,0 +1,46 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://beacon.dev/spec/lenses/v1/manifest.schema.json",+ "title": "Beacon Lens Manifest",+ "description": "The JSON object inside a lens file's <script type=\"application/beacon-lens+json\"> element (lenses/v1).",+ "type": "object",+ "additionalProperties": false,+ "required": ["id", "title", "version", "api"],+ "properties": {+ "id": {+ "type": "string",+ "pattern": "^[a-z0-9][a-z0-9-]{0,62}$",+ "description": "Stable identity. Unique on the endpoint; built-in lens IDs are reserved."+ },+ "title": {+ "type": "string",+ "minLength": 1,+ "maxLength": 60,+ "description": "Tab label. One line."+ },+ "description": {+ "type": "string",+ "maxLength": 280,+ "description": "One or two sentences shown in the lens picker. One line."+ },+ "icon": {+ "type": "string",+ "pattern": "^[a-z][a-z0-9-]{0,31}$",+ "description": "One generic word naming an icon. The dashboard falls back to a default icon for a word it does not know."+ },+ "version": {+ "type": "integer",+ "minimum": 1,+ "description": "Lens content revision; bump on every change."+ },+ "api": {+ "const": "beacon.lens.v1",+ "description": "The data contract the lens was written against."+ },+ "author": {+ "type": "string",+ "maxLength": 100,+ "description": "Free-text attribution. One line."+ }+ }+}