The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
onboarding: set up the MCP server and Beacon skills by default (opt-out)
Claudea6407ec41f5c
diff --git a/CLAUDE.md b/CLAUDE.mdindex 20cbcfeb..9ccd7352 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -13,7 +13,7 @@ Beacon Endpoint Agent is a local-only endpoint telemetry agent for AI runtimes.- `browser-extension`: optional MV3 collector (Chrome, plus a beta Firefox build target) that relays Claude.ai and ChatGPT chat telemetry into the local pipeline as OTLP.- `pkg/asymptoteobserve`: shared Go library — event schema, harness-name normalization, provenance markers, token usage, and the threat-rules engine. Imported by the CLI, the hook adapter, and the collector exporter, so a change here reaches all three.- `plugins`: TypeScript sources for the managed runtime plugins/extensions (`opencode-beacon`, `cline-beacon`, `pi-beacon`, `omp-beacon`, `openclaw-beacon`, `prime-beacon`, `omo-beacon`), each mirrored into an embedded copy under `cli/beacon/internal/endpoint/hooks/assets/`.-- `agent-skills`: publishable Agent Skills plugin for the traces-to-memory workflow (`beacon-memory-recall`, `beacon-memory-distill`, `beacon-memory-promote`) and for authoring dashboard lenses (`beacon-lens-create`) with manifests for Claude Code, Agent Plugins (Codex, Copilot, VS Code, Kiro, Devin), Cursor, Kimi Code, and Gemini CLI. At the repo root, `.claude-plugin/marketplace.json` is read by most harnesses, `.cursor-plugin/marketplace.json` by Cursor, and `package.json` (`pi.skills` only) makes the repo a Pi/Prime Agent package; keep that root `package.json` free of dependencies and scripts. `cli/beacon/cmd/agent_skills_test.go` checks every `beacon` command and flag the skills name against the real command tree, so rename a command and update the skills together.+- `agent-skills`: publishable Agent Skills plugin for the traces-to-memory workflow (`beacon-memory-recall`, `beacon-memory-distill`, `beacon-memory-promote`) and for authoring dashboard lenses (`beacon-lens-create`) with manifests for Claude Code, Agent Plugins (Codex, Copilot, VS Code, Kiro, Devin), Cursor, Kimi Code, and Gemini CLI. At the repo root, `.claude-plugin/marketplace.json` is read by most harnesses, `.cursor-plugin/marketplace.json` by Cursor, and `package.json` (`pi.skills` only) makes the repo a Pi/Prime Agent package; keep that root `package.json` free of dependencies and scripts. `cli/beacon/cmd/agent_skills_test.go` checks every `beacon` command and flag the skills name against the real command tree, so rename a command and update the skills together. The binary carries a copy of `agent-skills/skills` in `cli/beacon/internal/agentskills/skills` for onboarding and `beacon skills install`; a test keeps it identical, so copy it across whenever a skill changes.- `rules` and `spec/threat-rules`: the open rule corpus and the Threat Rules format it conforms to. Every rule's `taxonomy.beacon_category` is its directory name, and the six embedded baseline rules in `pkg/asymptoteobserve/rulestore/baseline` are byte-identical copies of their corpus rules; conformance tests enforce both.- `spec/lenses`: the Lenses format — single-file HTML views of one trace that the local dashboard runs in a sandboxed, network-less frame and feeds once through `window.beacon.getTrace()`. The contract types (`LensManifestV1`, `LensDataV1`) live in `pkg/asymptoteobserve/lens.go`, and `lens_test.go` pins the spec's examples and manifest schema to them. The dashboard builds the data in `BuildLensData` (`/api/lens-data`), lists lenses at `/api/lenses`, and serves each lens at `/lenses/frame/<id>` under the spec's CSP with `lenses/prelude.js` (which defines `window.beacon`) injected ahead of it; that route is the only one that may be framed. Built-in lenses are `cli/beacon/internal/endpoint/dashboard/lenses/*.lens.html`, and `activity` is byte-identical to the spec example (a test enforces it). The session page (`static/session.html`, `initLensTabs` in `app.js`) shows lenses as tabs fed by `/api/lens-data?session=`, which projects exactly the events that page lists; it is the host half of the protocol and closes a lens that errors, stalls, or navigates its own frame. Installed lenses live in the lens store (`cli/beacon/internal/endpoint/lensstore`, `<BaseDir>/lenses/<id>.lens.html`, 0600 under 0700), written only by `beacon lenses add|remove` (`cli/beacon/cmd/lenses.go`); the dashboard rescans it per request and never writes it, and a store lens can never shadow a built-in. `asymptoteobserve.CheckLensFile` is the one file check every installer, server and linter uses. User docs are `docs/concepts/lenses.mdx` and `docs/cli/lenses.mdx`; keep them in sync with the commands and built-in lenses. The authoring loop is `beacon lenses spec` (the spec carried in the binary as `dashboard/lenses/SPEC.md`, kept byte-identical to `spec/lenses/SPEC.md` by a test), `beacon lenses data` (the exact `LensDataV1` for a session), `beacon lenses lint` (`lensstore.Lint`; built-ins must lint clean) and `beacon lenses preview` (the dashboard with `Options.LensFiles`, re-read per reload).- `beacon-sandbox`: harness that runs a real Claude Code session in a disposable sandbox and checks what Beacon captured. See `beacon-sandbox/AGENTS.md`.@@ -28,7 +28,7 @@ Do not recreate or depend on removed `asymptote` mirror trees. Keep new work foc- Preserve the local-only default. The public Beacon build must not require a hosted account, remote policy fetch, hosted dashboard, or external network dependency during normal hook execution, and hooks themselves never touch the network.- `beacon login` is the account-identity channel for interactive users and is required by the interactive `beacon endpoint install` wizard. It uses browser PKCE against beacon.sh and stores the scoped CLI token only in `~/.beacon/auth/session.json` (0600 under a 0700 directory). Signing in alone never starts forwarding. User-mode `beacon endpoint connect` may send that token once to `POST /api/cli/enroll/account` to authorize minting a separate device ingest key, and `beacon mcp token create` may send it to `POST /api/cli/mcp/tokens` (scope `mcp:token:create`, listed on the sign-in page) to mint a personal MCP token that is printed once to stdout and never written to a file; never copy the account token into endpoint config, Vector, hook environments, logs, or command output. System/root/package/MDM/CI/piped-stdin/dry-run installs stay noninteractive and account-free.- Beacon Cloud forwarding (`cli/beacon/internal/endpoint/asymptote`, `beacon endpoint connect`, `beacon endpoint asymptote`) is Vector-shaped: Beacon writes local JSONL, Vector ships runtime lines only from the connection point forward and reads inventory from the beginning to establish the endpoint's current baseline, and the `bcn_device_*` key stays only in `<BaseDir>/asymptote/vector-secrets.json` via Vector's secret backend. The onboarding wizard preselects Beacon Cloud, and confirming it connects this endpoint in the same command once the local install has succeeded; an endpoint that is already enrolled is never re-enrolled, because enrollment rotates the device key. Standard mode ships locally sanitized retained content; metadata-only uses local Vector transforms to remove prompts, responses, reasoning, tool arguments/results, command output, raw fields, diffs, inventory content, and MCP definitions before buffering/upload. Keep the ingest URL `https://`, the wire contract aligned with `beacon-ingest` (`/v1/ingest/{runtime,inventory}` and `/v1/ingest/health`), and do not add another endpoint network channel. The cloud-sandbox shuttle is the bounded exception: only with `BEACON_ORIGIN=cloud`, it can upload new runtime lines to GCS, S3, or the same Beacon ingest contract because no Vector/service manager/browser/persistent disk exists there.-- `beacon endpoint install` has a full-screen onboarding wizard on interactive user TTYs. It signs in, preselects Beacon Cloud, requires an explicit choice to opt out to Local, and asks Managed users to choose Standard or Metadata-only privacy. Signing in alone still moves no telemetry. Confirming Beacon Cloud does: the confirm screen states that it installs Beacon and starts forwarding, and names what the selected privacy mode sends, so that screen is the consent point. The managed destination is recorded only after enrollment succeeds, so a failed enrollment leaves a working local install, prints `beacon endpoint connect` as the retry, and re-offers the question on the next install. The onboarding record is written only after `lifecycle.Install` returns, because a profile written first left a failed install looking onboarded and silently skipped the wizard on the retry. Explicit `install --connect` is unchanged. The wizard is skipped for system/root/CI/piped-stdin/dry-run or `BEACON_ONBOARDING=0`; those unattended paths must never gain an account or browser dependency. Legacy `BEACON_ONBOARDING_EMAIL`/`USAGE` submissions remain only for fleet compatibility. Implementation lives in `cli/beacon/internal/onboarding` and `cli/beacon/cmd/endpoint_onboarding.go`; keep `docs/cli/endpoint-onboarding.mdx` in sync.+- `beacon endpoint install` has a full-screen onboarding wizard on interactive user TTYs. It signs in, preselects Beacon Cloud, requires an explicit choice to opt out to Local, and asks Managed users to choose Standard or Metadata-only privacy. Signing in alone still moves no telemetry. Confirming Beacon Cloud does: the confirm screen states that it installs Beacon and starts forwarding, and names what the selected privacy mode sends, so that screen is the consent point. The managed destination is recorded only after enrollment succeeds, so a failed enrollment leaves a working local install, prints `beacon endpoint connect` as the retry, and re-offers the question on the next install. The onboarding record is written only after `lifecycle.Install` returns, because a profile written first left a failed install looking onboarded and silently skipped the wizard on the retry. Explicit `install --connect` is unchanged. The wizard is skipped for system/root/CI/piped-stdin/dry-run or `BEACON_ONBOARDING=0`; those unattended paths must never gain an account or browser dependency. Legacy `BEACON_ONBOARDING_EMAIL`/`USAGE` submissions remain only for fleet compatibility. After the destination, the wizard offers two agent tools for either destination, both preselected (opt-out, space toggles): the local `beacon` stdio MCP server registered in detected harnesses (`mcpconnect.InstallLocal`, `beacon mcp install|uninstall`, manifest `~/.beacon/mcp/local.json`; it adds the entry only where the name `beacon` is free and never replaces one) and the Beacon Agent Skills installed user-wide into `~/.agents/skills` and, when Claude Code is set up, `~/.claude/skills` (`cli/beacon/internal/agentskills`, `beacon skills install|uninstall`; a `.beacon-managed` marker decides what Beacon may replace or remove). Both run after `lifecycle.Install` returns, warn rather than fail, and never touch the network; install and repair refresh only skill copies Beacon already wrote. The answers are recorded as `onboarding.mcp_server`/`agent_skills`. Implementation lives in `cli/beacon/internal/onboarding`, `cli/beacon/cmd/endpoint_onboarding.go` and `cli/beacon/cmd/agent_tools.go`; keep `docs/cli/endpoint-onboarding.mdx`, `docs/cli/mcp-install.mdx` and `docs/cli/skills.mdx` in sync.- Do not add dependency vulnerability scanning, OSV/GHSA lookups, package remediation, or other vulnerability-enforcement flows to the public hook path.- Do not add broad runtime enforcement unless explicitly requested. Current control behavior is limited to hook-native approvals/denials exposed by supported agent runtimes.- Keep destination support shaped like the existing local JSONL and customer-managed forwarding paths. Beacon may render supported packs or token-based endpoint forwarders, but should not add hosted SIEM dependencies or store third-party service credentials beyond the explicit supported configs. Elastic remains a file-tailing pack over local JSONL.@@ -68,7 +68,7 @@ Supported runtime surfaces today:- Local threat detection via `beacon scan`, which runs the open Threat Rules format (`spec/threat-rules`; CEL match conditions over the endpoint event schema, with embedded conformance fixtures) over the runtime JSONL. The engine (`pkg/asymptoteobserve/threatrules`) ships in the binary; the rule corpus is external data loaded from a local store (`~/.beacon/endpoint/rules`) managed by `beacon rules`, so the corpus can grow without enlarging the binary. `scan` is read-only and offline; only the explicit, user-initiated `beacon rules pull <url>` reaches the network. A small frozen baseline is embedded so `scan` works before any rules are installed.- Session handoff via `beacon handoff list|export|resume` (`cli/beacon/internal/handoff`, `cli/beacon/cmd/handoff*.go`; docs in `docs/cli/handoff.mdx` and `docs/concepts/session-handoff.mdx`). Every runtime is one entry in the registry in `cli/beacon/internal/handoff/runtimes.go`: its session source, the names it answers to, and the commands that reopen it or start it from a brief; `TestRegistryIsConsistent` checks the entries. Handoff reads the session stores of Claude Code, Codex CLI, OpenCode, Cline, Pi, Prime Agent, Factory Droid, GitHub Copilot CLI, Hermes Agent, DeepSeek Harness, fx, Grok Build, OpenClaw Gateway and Cursor read-only and never touches the network. Oh My Pi, Gemini CLI, Qwen Code, Kiro, Antigravity CLI, Devin CLI, Muse Code, OpenHands and goose have no store Beacon reads: their sessions come from the runtime log, and they take a brief as the target of `--agent`. `resume` reopens a session natively with its runtime's own command when it can, and otherwise writes a brief to `~/.beacon/endpoint/handoffs` (0700/0600) and starts a new session pointed at it. DeepSeek Harness cannot be started, and Hermes Agent and fx only reopen their own sessions, so their sessions continue in another runtime. fx, Grok Build and Cursor find a session by the directory they run in, so they are reopened natively only in the session's own directory. The brief is passed by absolute path, never inlined on a command line. Every launch keeps the runtime's approvals on: Beacon never passes a flag that turns them off, names the approval mode that asks where a CLI takes one (Cline always gets `--auto-approve false`, because Cline defaults to approving every tool call), and removes or overrides environment switches that would approve everything (`COPILOT_ALLOW_ALL`, `COPILOT_PLAN_THEN_AUTOPILOT`, `HERMES_YOLO_MODE`, `GOOSE_MODE`); `--print` shows them under `env`. Briefs run every event through `SanitizeEvent`, and quoted content goes in fences longer than any backtick run it contains, with inline fields reduced to one line, so quoted content cannot forge brief structure. A new session's first prompt ends with the `[beacon-handoff from=<harness> session=<id>]` marker (`pkg/asymptoteobserve/handoff.go`). The hook and plugin prompt paths and the session-store mappers record a `session.handoff` event with `handoff.{source_harness,source_session_id}` when they see it; that is an observed claim, not a verified identity.- Commit-to-session links via `beacon git setup|status|remove|link|notes` (`cli/beacon/internal/gitlink`, `cli/beacon/cmd/git*.go`; docs in `docs/cli/git.mdx`). A link is a `beacon:<harness>/<session-id>` line in a git note under `refs/notes/beacon`; it carries identifiers only, never content, because notes can be pushed. Which sessions to link is inferred from the local runtime log: a session is linked when, between the parent commit and the commit (at least two hours, at most 24), it wrote a file the commit changes (for a merge, only files that differ from every parent, so a clean merge or pull links nothing). Evidence is file write events, write-type `file.operation`s, plainly readable shell targets, and `apply_patch` envelopes; reads never count. Note updates are a compare-and-swap on the notes ref through a private `refs/notes/beacon-tx/` working ref, and every existing note line, a teammate's or a person's, is kept verbatim. `setup` installs post-commit (links HEAD in the foreground with a 3 s budget, silent, never fails the commit, skips rebase/cherry-pick/revert) and post-rewrite (normalizes the note git concatenates on amend) as standalone `beacon-<hook>` scripts called from a marked block inserted after the shebang of the repository's own hook; only shell hooks are edited, `core.hooksPath` is refused without `--hooks-path`, and `notes.rewriteRef` carries links through amend and rebase. `BEACON_GIT_HOOKS=0` disables the hooks for one command. Every link a run adds is also written to the runtime log as one `session.commit_linked` event in the linked session's timeline (`event.fidelity=inferred`, no collection method), with commit id, branch and credential-stripped remote in the OTel-shaped `vcs` block and overlap counts in `vcs.attribution`; the event deliberately carries no file, command or tool fields so it can never become attribution evidence. Sharing is opt-in (`setup --share-notes`, off by default): a non-destructive fetch refspec `+refs/notes/beacon:refs/notes/beacon-remotes/<remote>` so git's own fetch brings teammates' links into a read-only tracking ref that `beacon git notes` unions with the local one (never force-fetch into `refs/notes/beacon`: it would destroy unpushed links), and a pre-push hook that fetches, merges with `cat_sort_uniq` through the same CAS, and pushes only the notes ref with `--no-verify`, within a 10 s budget and never failing the push. That pre-push hook is the only Beacon git hook that touches the network, and only during a push the person started; `beacon git notes push|fetch` do the same by hand.-- Beacon Cloud MCP registration via `beacon mcp connect|disconnect|status` (`cli/beacon/internal/mcpconnect`, `cli/beacon/cmd/mcp_connect.go`; docs in `docs/cli/mcp-connect.mdx`). It registers the Beacon Cloud MCP server as `beacon-managed`, a different name from the local stdio server `beacon`, in the user-level config of Claude Code, Codex CLI, Cursor, VS Code, Gemini CLI and OpenCode. It prints manual steps for runtimes without confirmed MCP OAuth support. OAuth is the default and writes only the URL; `--token-env` writes a reference to an environment variable in each harness's own syntax, never a value. `connect` never reads or copies the account token and never writes a token; minting one is the separate, explicit `beacon mcp token create`. It is explicit and interactive: never run by `endpoint install` or onboarding (the install only suggests it after the wizard's Managed choice), refused as root, and refused in CI or without a terminal unless `--yes` is given. Its one network request is the RFC 9728 resource-metadata check of the URL, which `--dry-run` skips. Configs are edited like the Kimi Code writer: never re-serialized, spliced as text, parsed back and compared before an atomic replace, backed up first. What was written is recorded in `~/.beacon/mcp/connections.json`, and `disconnect` removes only entries recorded there that still point at the recorded URL. `cmd/mcp_connect_e2e_test.go` runs the real harness CLIs when they are installed; re-run it when a harness changes its MCP config format.+- Beacon Cloud MCP registration via `beacon mcp connect|disconnect|status` (`cli/beacon/internal/mcpconnect`, `cli/beacon/cmd/mcp_connect.go`; docs in `docs/cli/mcp-connect.mdx`). It registers the Beacon Cloud MCP server as `beacon-managed`, a different name from the local stdio server `beacon`, in the user-level config of Claude Code, Codex CLI, Cursor, VS Code, Gemini CLI and OpenCode. It prints manual steps for runtimes without confirmed MCP OAuth support. OAuth is the default and writes only the URL; `--token-env` writes a reference to an environment variable in each harness's own syntax, never a value. `connect` never reads or copies the account token and never writes a token; minting one is the separate, explicit `beacon mcp token create`. It is explicit and interactive: never run by `endpoint install` or onboarding (the install only suggests it after the wizard's Managed choice; what onboarding registers is the separate local `beacon` server), refused as root, and refused in CI or without a terminal unless `--yes` is given. Its one network request is the RFC 9728 resource-metadata check of the URL, which `--dry-run` skips. Configs are edited like the Kimi Code writer: never re-serialized, spliced as text, parsed back and compared before an atomic replace, backed up first. What was written is recorded in `~/.beacon/mcp/connections.json`, and `disconnect` removes only entries recorded there that still point at the recorded URL. `cmd/mcp_connect_e2e_test.go` runs the real harness CLIs when they are installed; re-run it when a harness changes its MCP config format.- An optional, off-by-default policy seam in the hook path (`cli/beacon-hooks/internal/policy`) governed by the stable contract in `pkg/asymptoteobserve/policycontract`. When `BEACON_POLICY_PROVIDER` names an executable, the `pre-tool` and `permission-request` hooks send it a JSON request describing the imminent tool call and honor an allow/deny response, returning the runtime's native deny shape and `policy.enforcement=enforce` telemetry on a deny. The seam is inert when unset and fail-open on any error (timeout, non-zero exit, malformed output), so the open build ships no enforcement of its own; all audit/enforce decision logic lives in the external provider. `rules/agent-control/agent-permission-bypass-spawn.rule.yaml` is the open detect twin that flags the same pattern in `beacon scan`.Current non-goals unless explicitly requested:diff --git a/README.md b/README.mdindex 516cbc4f..202d57cd 100644--- a/README.md+++ b/README.md@@ -154,6 +154,12 @@ Or inspect the raw event stream:> Local to keep everything on this machine, and disconnect any time with> `beacon endpoint disconnect`.+Whichever destination you choose, the wizard also sets up two agent tools unless you+turn them off: the local `beacon` MCP server (`beacon mcp serve`) in every detected+harness, and the [Beacon Skills](https://docs.beacon.sh/concepts/beacon-skills) in+`~/.agents/skills` and `~/.claude/skills`. Both read local data only. Redo or undo+them with `beacon mcp install|uninstall` and `beacon skills install|uninstall`.+If this endpoint forwards to Beacon Cloud, your agents can search that history over MCP:```bashdiff --git a/cli/beacon/cmd/agent_tools.go b/cli/beacon/cmd/agent_tools.gonew file mode 100644index 00000000..20e7963b--- /dev/null+++ b/cli/beacon/cmd/agent_tools.go@@ -0,0 +1,269 @@+package cmd++import (+ "fmt"+ "io"++ "github.com/spf13/cobra"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/agentskills"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/mcpconnect"+)++// Agent tools are what onboarding sets up for the person's agents, whichever destination they+// chose: the local Beacon MCP server registered in each detected harness, and the Beacon Agent+// Skills installed user-wide. Both are selected by default in the wizard and turned off there;+// `beacon mcp install|uninstall` and `beacon skills install|uninstall` redo or undo them later.+// Neither touches the network.++// Seams for tests.+var (+ agentToolsHome = mcpHome+ agentToolsExecutable = beaconExecutable+)++var mcpInstallCmd = &cobra.Command{+ Use: "install",+ Short: "Register the local Beacon MCP server in detected harnesses",+ SilenceUsage: true,+ RunE: func(cmd *cobra.Command, args []string) error {+ return installLocalMCP(cmd.OutOrStdout(), cmd)+ },+}++var mcpUninstallCmd = &cobra.Command{+ Use: "uninstall",+ Short: "Remove the local Beacon MCP server entries Beacon registered",+ SilenceUsage: true,+ RunE: runMCPUninstall,+}++var skillsCmd = &cobra.Command{+ Use: "skills",+ Short: "Install the Beacon Agent Skills for every project",+ Long: `Install the Beacon Agent Skills for every project on this machine.++The skills go to ~/.agents/skills, which Codex CLI, Gemini CLI, OpenCode, Pi and other runtimes+read, and to ~/.claude/skills when Claude Code is set up. A skill directory of the same name that+Beacon did not write is left alone.`,+}++var skillsInstallCmd = &cobra.Command{+ Use: "install",+ Short: "Install or update the Beacon Agent Skills",+ SilenceUsage: true,+ RunE: func(cmd *cobra.Command, args []string) error {+ return installAgentSkills(cmd.OutOrStdout())+ },+}++var skillsUninstallCmd = &cobra.Command{+ Use: "uninstall",+ Short: "Remove the Beacon Agent Skills Beacon installed",+ SilenceUsage: true,+ RunE: runSkillsUninstall,+}++func init() {+ mcpCmd.AddCommand(mcpInstallCmd, mcpUninstallCmd)+ mcpInstallCmd.Flags().StringSliceVar(&mcpConnectOpts.harnesses, "harness", nil, "Harness to configure (repeatable; default: every detected harness)")+ rootCmd.AddCommand(skillsCmd)+ skillsCmd.AddCommand(skillsInstallCmd, skillsUninstallCmd)+ mcpInstallCmd.PreRunE = refuseRoot("beacon mcp install")+ mcpUninstallCmd.PreRunE = refuseRoot("beacon mcp uninstall")+ skillsInstallCmd.PreRunE = refuseRoot("beacon skills install")+ skillsUninstallCmd.PreRunE = refuseRoot("beacon skills uninstall")+}++func localMCPOptions(home string) mcpconnect.LocalOptions {+ return mcpconnect.LocalOptions{Home: home, Command: agentToolsExecutable(), LookPath: mcpLookPath, Run: mcpRunCLI}+}++// installAgentTools carries out the agent tools the wizard kept selected. It runs after the local+// install has succeeded, and a failure is a warning: the endpoint works without them.+func installAgentTools(cmd *cobra.Command, decided onboardingOutcome) {+ if !decided.InstallMCP && !decided.InstallSkills {+ return+ }+ out := cmd.OutOrStdout()+ if decided.InstallMCP {+ if err := installLocalMCP(out, cmd); err != nil {+ fmt.Fprintf(cmd.ErrOrStderr(), "beacon: the Beacon MCP server was not registered (%v). Run `beacon mcp install` to try again.\n", err)+ }+ }+ if decided.InstallSkills {+ if err := installAgentSkills(out); err != nil {+ fmt.Fprintf(cmd.ErrOrStderr(), "beacon: the Beacon agent skills were not installed (%v). Run `beacon skills install` to try again.\n", err)+ }+ }+}++func installLocalMCP(out io.Writer, cmd *cobra.Command) error {+ home, err := agentToolsHome()+ if err != nil {+ return err+ }+ targets, _, err := resolveMCPTargets(mcpConnectOpts.harnesses)+ if err != nil {+ return err+ }+ var local []mcpconnect.Target+ for _, t := range targets {+ if t.LocalSupported() {+ local = append(local, t)+ }+ }+ if len(local) == 0 {+ fmt.Fprintln(out, "Beacon MCP server: no harness Beacon can register it in was detected.")+ return nil+ }+ items, err := mcpconnect.InstallLocal(commandContext(cmd), localMCPOptions(home), local)+ if err != nil {+ return err+ }+ var failed int+ for _, it := range items {+ where := displayPath(home, it.Path)+ switch {+ case it.Err != nil:+ failed+++ fmt.Fprintf(out, "Beacon MCP server: %s not registered: %v\n", it.Target.DisplayName, it.Err)+ case it.Action == mcpconnect.ActionAdd:+ fmt.Fprintf(out, "Beacon MCP server: registered for %s (%s)\n", it.Target.DisplayName, where)+ case it.Action == mcpconnect.ActionPresent:+ fmt.Fprintf(out, "Beacon MCP server: %s already has a %q entry; left as is\n", it.Target.DisplayName, mcpconnect.LocalServerName)+ default:+ fmt.Fprintf(out, "Beacon MCP server: %s skipped: %s\n", it.Target.DisplayName, it.Detail)+ }+ }+ if failed > 0 {+ return fmt.Errorf("%d harness(es) could not be configured", failed)+ }+ return nil+}++func runMCPUninstall(cmd *cobra.Command, args []string) error {+ out := cmd.OutOrStdout()+ home, err := agentToolsHome()+ if err != nil {+ return err+ }+ items, err := mcpconnect.UninstallLocal(commandContext(cmd), localMCPOptions(home))+ if err != nil {+ return err+ }+ if len(items) == 0 {+ fmt.Fprintln(out, "No local Beacon MCP server entries written by Beacon.")+ return nil+ }+ var failed int+ for _, it := range items {+ where := displayPath(home, it.Path)+ switch {+ case it.Err != nil:+ failed+++ fmt.Fprintf(out, "%s: %v\n", it.Target.DisplayName, it.Err)+ case it.Action == mcpconnect.ActionRemove:+ fmt.Fprintf(out, "Removed from %s (%s)\n", it.Target.DisplayName, where)+ default:+ fmt.Fprintf(out, "%s: %s\n", it.Target.DisplayName, it.Detail)+ }+ }+ if failed > 0 {+ return fmt.Errorf("%d entr(ies) could not be removed", failed)+ }+ return nil+}++func installAgentSkills(out io.Writer) error {+ home, err := agentToolsHome()+ if err != nil {+ return err+ }+ return reportSkills(out, home, agentskills.Install(agentskills.Roots(home)), "installed in")+}++func runSkillsUninstall(cmd *cobra.Command, args []string) error {+ out := cmd.OutOrStdout()+ home, err := agentToolsHome()+ if err != nil {+ return err+ }+ results := agentskills.Uninstall(agentskills.Roots(home))+ if len(results) == 0 {+ fmt.Fprintln(out, "No Beacon agent skills installed by Beacon.")+ return nil+ }+ return reportSkills(out, home, results, "removed from")+}++// refreshAgentSkills updates skills Beacon already installed to this binary's copies, so an+// upgrade never leaves an agent following instructions for commands that changed. It installs+// nothing new and stays quiet unless something failed.+func refreshAgentSkills(errOut io.Writer) {+ if !endpointUserMode() || onboardingIsRoot() {+ return+ }+ home, err := agentToolsHome()+ if err != nil {+ return+ }+ for _, r := range agentskills.Refresh(agentskills.Roots(home)) {+ if r.Err != nil {+ fmt.Fprintf(errOut, "beacon: could not update the %s skill in %s: %v\n", r.Skill, displayPath(home, r.Root), r.Err)+ }+ }+}++func reportSkills(out io.Writer, home string, results []agentskills.Result, verb string) error {+ type rootSummary struct{ written, current, skipped []string }+ byRoot := map[string]*rootSummary{}+ var roots []string+ var failed int+ for _, r := range results {+ s, ok := byRoot[r.Root]+ if !ok {+ s = &rootSummary{}+ byRoot[r.Root] = s+ roots = append(roots, r.Root)+ }+ switch {+ case r.Err != nil:+ failed+++ fmt.Fprintf(out, "Beacon agent skills: %s in %s: %v\n", r.Skill, displayPath(home, r.Root), r.Err)+ case r.Action == agentskills.ActionAdd, r.Action == agentskills.ActionUpdate, r.Action == agentskills.ActionRemove:+ s.written = append(s.written, r.Skill)+ case r.Action == agentskills.ActionPresent:+ s.current = append(s.current, r.Skill)+ case r.Action == agentskills.ActionSkip:+ s.skipped = append(s.skipped, r.Skill)+ }+ }+ for _, root := range roots {+ s := byRoot[root]+ where := displayPath(home, root)+ if len(s.written) > 0 {+ fmt.Fprintf(out, "Beacon agent skills: %d %s %s\n", len(s.written), verb, where)+ }+ if len(s.current) > 0 {+ fmt.Fprintf(out, "Beacon agent skills: %d already current in %s\n", len(s.current), where)+ }+ for _, name := range s.skipped {+ fmt.Fprintf(out, "Beacon agent skills: %s in %s was not written by Beacon; left as is\n", name, where)+ }+ }+ if failed > 0 {+ return fmt.Errorf("%d skill(s) could not be written", failed)+ }+ return nil+}++// refuseRoot keeps root from writing into its own home on behalf of a person.+func refuseRoot(command string) func(*cobra.Command, []string) error {+ return func(*cobra.Command, []string) error {+ if mcpIsRoot() {+ return fmt.Errorf("%s configures one person's agents; run it as that user, not as root", command)+ }+ return nil+ }+}diff --git a/cli/beacon/cmd/agent_tools_test.go b/cli/beacon/cmd/agent_tools_test.gonew file mode 100644index 00000000..3d79153c--- /dev/null+++ b/cli/beacon/cmd/agent_tools_test.go@@ -0,0 +1,196 @@+package cmd++import (+ "bytes"+ "context"+ "errors"+ "io"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/spf13/cobra"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/agentskills"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/harness"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/onboarding"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"+)++func TestOnboardingOffersAgentToolsWhicheverDestination(t *testing.T) {+ for _, tc := range []struct {+ destination string+ mcp, skills bool+ wantMCPAnswer string+ wantSkills string+ }{+ {onboarding.DestinationLocal, true, true, onboarding.AgentToolInstalled, onboarding.AgentToolInstalled},+ {onboarding.DestinationAsymptote, true, false, onboarding.AgentToolInstalled, onboarding.AgentToolDeclined},+ {onboarding.DestinationLocal, false, false, onboarding.AgentToolDeclined, onboarding.AgentToolDeclined},+ } {+ h := newOnboardingHarness(t)+ var offered bool+ onboardingRunWizard = func(_ io.Reader, _ io.Writer, opts onboarding.WizardOptions) (onboarding.WizardResult, error) {+ offered = opts.OfferAgentTools+ return onboarding.WizardResult{+ Completed: true,+ Destination: tc.destination,+ PrivacyMode: "standard",+ InstallMCP: tc.mcp,+ InstallSkills: tc.skills,+ }, nil+ }+ outcome, err := maybeRunOnboarding(h.cmd)+ if err != nil {+ t.Fatal(err)+ }+ if !offered {+ t.Fatalf("%s: the wizard was not offered the agent tools", tc.destination)+ }+ if outcome.InstallMCP != tc.mcp || outcome.InstallSkills != tc.skills {+ t.Fatalf("%s: outcome = %+v", tc.destination, outcome)+ }+ if err := outcome.Persist(); err != nil {+ t.Fatal(err)+ }+ got := h.saved[len(h.saved)-1].Onboarding+ if got.MCPServer != tc.wantMCPAnswer || got.AgentSkills != tc.wantSkills {+ t.Fatalf("%s: recorded mcp=%q skills=%q", tc.destination, got.MCPServer, got.AgentSkills)+ }+ }+}++type agentToolsFixture struct {+ home string+ cmd *cobra.Command+ out *bytes.Buffer+ err *bytes.Buffer+}++func newAgentToolsFixture(t *testing.T) agentToolsFixture {+ t.Helper()+ home := t.TempDir()+ testenv.SetHome(t, home)+ t.Setenv("XDG_CONFIG_HOME", "")+ t.Setenv("CLAUDE_CONFIG_DIR", "")+ t.Setenv("CODEX_HOME", "")+ if err := os.Mkdir(filepath.Join(home, ".claude"), 0o700); err != nil {+ t.Fatal(err)+ }+ prevHome, prevExe := agentToolsHome, agentToolsExecutable+ prevDiscover, prevLook, prevRun := mcpDiscover, mcpLookPath, mcpRunCLI+ prevHarnesses := mcpConnectOpts.harnesses+ agentToolsHome = func() (string, error) { return home, nil }+ agentToolsExecutable = func() string { return "/opt/beacon/bin/beacon" }+ mcpDiscover = func() []harness.Harness {+ return []harness.Harness{+ {Name: "cursor", DisplayName: "Cursor", Detected: true},+ {Name: "gemini_cli", DisplayName: "Gemini CLI", Detected: true},+ {Name: "codex_cli", DisplayName: "Codex CLI", Detected: false},+ }+ }+ mcpLookPath = func(string) (string, error) { return "", errors.New("not on PATH") }+ mcpRunCLI = func(context.Context, string, ...string) ([]byte, error) {+ return nil, errors.New("no harness CLI may run here")+ }+ mcpConnectOpts.harnesses = nil+ t.Cleanup(func() {+ agentToolsHome, agentToolsExecutable = prevHome, prevExe+ mcpDiscover, mcpLookPath, mcpRunCLI = prevDiscover, prevLook, prevRun+ mcpConnectOpts.harnesses = prevHarnesses+ })+ f := agentToolsFixture{home: home, cmd: &cobra.Command{}, out: &bytes.Buffer{}, err: &bytes.Buffer{}}+ f.cmd.SetOut(f.out)+ f.cmd.SetErr(f.err)+ f.cmd.SetContext(context.Background())+ return f+}++func TestInstallAgentToolsRegistersMCPAndInstallsSkills(t *testing.T) {+ f := newAgentToolsFixture(t)+ installAgentTools(f.cmd, onboardingOutcome{InstallMCP: true, InstallSkills: true})+ if f.err.Len() != 0 {+ t.Fatalf("stderr: %s", f.err)+ }+ for _, rel := range []string{".cursor/mcp.json", ".gemini/settings.json"} {+ data, err := os.ReadFile(filepath.Join(f.home, rel))+ if err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(string(data), `"beacon"`) || !strings.Contains(string(data), "/opt/beacon/bin/beacon") {+ t.Fatalf("%s:\n%s", rel, data)+ }+ }+ // A harness that was not detected is not configured.+ if _, err := os.Stat(filepath.Join(f.home, ".codex", "config.toml")); !os.IsNotExist(err) {+ t.Fatalf("codex config written for an undetected harness (err=%v)", err)+ }+ for _, root := range []string{".agents/skills", ".claude/skills"} {+ for _, name := range agentskills.Names() {+ if _, err := os.Stat(filepath.Join(f.home, root, name, "SKILL.md")); err != nil {+ t.Fatalf("%s/%s not installed: %v", root, name, err)+ }+ }+ }+ out := f.out.String()+ for _, want := range []string{"registered for Cursor", "registered for Gemini CLI", "installed in ~/.agents/skills", "installed in ~/.claude/skills"} {+ if !strings.Contains(out, want) {+ t.Fatalf("output missing %q:\n%s", want, out)+ }+ }++ // Both are undone by their uninstall commands.+ if err := runMCPUninstall(f.cmd, nil); err != nil {+ t.Fatal(err)+ }+ if err := runSkillsUninstall(f.cmd, nil); err != nil {+ t.Fatal(err)+ }+ for _, rel := range []string{".cursor/mcp.json", ".gemini/settings.json", ".agents/skills/beacon-memory-recall", ".claude/skills/beacon-memory-recall"} {+ if _, err := os.Stat(filepath.Join(f.home, rel)); !os.IsNotExist(err) {+ t.Fatalf("%s still present after uninstall (err=%v)", rel, err)+ }+ }+}++func TestDeclinedAgentToolsWriteNothing(t *testing.T) {+ f := newAgentToolsFixture(t)+ installAgentTools(f.cmd, onboardingOutcome{})+ for _, rel := range []string{".cursor", ".gemini", ".agents", ".claude/skills"} {+ if _, err := os.Stat(filepath.Join(f.home, rel)); !os.IsNotExist(err) {+ t.Fatalf("%s written although the agent tools were turned off (err=%v)", rel, err)+ }+ }+ if f.out.Len() != 0 || f.err.Len() != 0 {+ t.Fatalf("output: %q %q", f.out, f.err)+ }+}++func TestRefreshAgentSkillsOnlyUpdatesInstalledCopies(t *testing.T) {+ f := newAgentToolsFixture(t)+ prevOpts := endpointOpts+ prevRoot := onboardingIsRoot+ endpointOpts.userMode, endpointOpts.systemMode = true, false+ onboardingIsRoot = func() bool { return false }+ t.Cleanup(func() { endpointOpts, onboardingIsRoot = prevOpts, prevRoot })++ refreshAgentSkills(f.err)+ if _, err := os.Stat(filepath.Join(f.home, ".agents")); !os.IsNotExist(err) {+ t.Fatalf("refresh installed skills nobody asked for (err=%v)", err)+ }+ if err := installAgentSkills(f.out); err != nil {+ t.Fatal(err)+ }+ stale := filepath.Join(f.home, ".agents", "skills", "beacon-memory-recall", "SKILL.md")+ if err := os.WriteFile(stale, []byte("old"), 0o644); err != nil {+ t.Fatal(err)+ }+ refreshAgentSkills(f.err)+ if data, _ := os.ReadFile(stale); string(data) == "old" {+ t.Fatal("refresh left a stale skill")+ }+ if f.err.Len() != 0 {+ t.Fatalf("stderr: %s", f.err)+ }+}diff --git a/cli/beacon/cmd/endpoint_install.go b/cli/beacon/cmd/endpoint_install.goindex 16629edb..e4025ffd 100644--- a/cli/beacon/cmd/endpoint_install.go+++ b/cli/beacon/cmd/endpoint_install.go@@ -179,6 +179,8 @@ func runEndpointInstall(cmd *cobra.Command, args []string) error {}printLingerGap(cmd.ErrOrStderr(), result)installHookTargetsFromEndpointInstall(cmd.ErrOrStderr(), selection.Hooks)+ refreshAgentSkills(cmd.ErrOrStderr())+ installAgentTools(cmd, onboarded)if connectAfterInstall {// The install is complete and stands on its own; a failed connect is reported// with the retry command rather than turning a working install into an error.@@ -330,6 +332,7 @@ func runEndpointRepair(cmd *cobra.Command, args []string) error {fmt.Printf("Endpoint repaired. Manifest: %s\n", result.ManifestPath)printLingerGap(cmd.ErrOrStderr(), result)installHookTargetsFromEndpointInstall(cmd.ErrOrStderr(), selection.Hooks)+ refreshAgentSkills(cmd.ErrOrStderr())return nil}diff --git a/cli/beacon/cmd/endpoint_onboarding.go b/cli/beacon/cmd/endpoint_onboarding.goindex 8ad9f403..ca079006 100644--- a/cli/beacon/cmd/endpoint_onboarding.go+++ b/cli/beacon/cmd/endpoint_onboarding.go@@ -104,6 +104,11 @@ type onboardingOutcome struct {// machine marked onboarded, so the retry took the already-completed branch, said// nothing, and never offered the destination again.Persist func() error+ // InstallMCP and InstallSkills are the agent tools the person kept selected. They are+ // offered whichever destination was chosen, and installed after lifecycle.Install+ // returns, like everything else the wizard decided.+ InstallMCP bool+ InstallSkills bool}// maybeRunOnboarding runs the one-time account and destination wizard when this@@ -163,6 +168,7 @@ func runAccountOnboarding(cmd *cobra.Command, profile *onboarding.Profile, destiDestinationOnly: destinationOnly,PresetDestination: preset,PresetPrivacyMode: profile.Onboarding.PrivacyMode,+ OfferAgentTools: true,NoBrowser: endpointOpts.noBrowser,NoDisplay: onboardingDisplayCheck(),Now: onboardingClock,@@ -256,7 +262,13 @@ func runAccountOnboarding(cmd *cobra.Command, profile *onboarding.Profile, destirecordedDestination = ""}- decided := onboardingOutcome{Connect: connectAfterInstall}+ decided := onboardingOutcome{+ Connect: connectAfterInstall,+ InstallMCP: result.InstallMCP,+ InstallSkills: result.InstallSkills,+ }+ mcpAnswer := onboarding.AgentToolAnswer(result.InstallMCP)+ skillsAnswer := onboarding.AgentToolAnswer(result.InstallSkills)email := status.User.Email// A run that never signed in is recorded as skipped, not authenticated.outcome := onboarding.OutcomeAuthenticated@@ -272,11 +284,15 @@ func runAccountOnboarding(cmd *cobra.Command, profile *onboarding.Profile, destiBeaconVersion: version.GetVersion(),Destination: recordedDestination,PrivacyMode: privacyMode,+ MCPServer: mcpAnswer,+ AgentSkills: skillsAnswer,}profile.Pending = nil} else {profile.Onboarding.Destination = recordedDestinationprofile.Onboarding.PrivacyMode = privacyMode+ profile.Onboarding.MCPServer = mcpAnswer+ profile.Onboarding.AgentSkills = skillsAnswer}if _, err := onboarding.EnsureInstallID(profile); err != nil {return fmt.Errorf("create onboarding install id: %w", err)@@ -538,6 +554,8 @@ type endpointOnboardingStatus struct {BeaconVersion string `json:"beacon_version,omitempty"`Destination string `json:"destination,omitempty"`PrivacyMode string `json:"privacy_mode,omitempty"`+ MCPServer string `json:"mcp_server,omitempty"`+ AgentSkills string `json:"agent_skills,omitempty"`Pending bool `json:"pending_submission"`SkipReason string `json:"skip_reason,omitempty"`ProfilePath string `json:"profile_path"`@@ -578,6 +596,8 @@ func runEndpointOnboarding(cmd *cobra.Command, args []string) error {BeaconVersion: profile.Onboarding.BeaconVersion,Destination: profile.Onboarding.Destination,PrivacyMode: profile.Onboarding.PrivacyMode,+ MCPServer: profile.Onboarding.MCPServer,+ AgentSkills: profile.Onboarding.AgentSkills,Pending: profile.Pending != nil,SkipReason: reason,ProfilePath: onboarding.Path(),@@ -608,6 +628,12 @@ func runEndpointOnboarding(cmd *cobra.Command, args []string) error {if status.PrivacyMode != "" {fmt.Fprintf(out, "Managed privacy: %s\n", managedprivacy.Label(status.PrivacyMode))}+ if status.MCPServer != "" {+ fmt.Fprintf(out, "Beacon MCP server: %s\n", status.MCPServer)+ }+ if status.AgentSkills != "" {+ fmt.Fprintf(out, "Beacon agent skills: %s\n", status.AgentSkills)+ }fmt.Fprintf(out, "Install ID: %s\n", status.InstallID)fmt.Fprintf(out, "Profile: %s\n", status.ProfilePath)if status.Outcome != onboarding.OutcomeAuthenticated {diff --git a/cli/beacon/cmd/mcp.go b/cli/beacon/cmd/mcp.goindex a3cc7206..8983b3af 100644--- a/cli/beacon/cmd/mcp.go+++ b/cli/beacon/cmd/mcp.go@@ -34,7 +34,7 @@ var mcpCmd = &cobra.Command{Long: `Expose Beacon activity through MCP.serve and doctor run and check the local "beacon" server, which reads this machine's runtime-log. connect, disconnect and status manage the "beacon-managed" entry that points your harnesses+log; install and uninstall register it in your harnesses or remove it. connect, disconnect and status manage the "beacon-managed" entry that points your harnessesat Beacon Cloud MCP, which searches the session history this endpoint forwards.`,}diff --git a/cli/beacon/internal/agentskills/agentskills.go b/cli/beacon/internal/agentskills/agentskills.gonew file mode 100644index 00000000..3a5906b2--- /dev/null+++ b/cli/beacon/internal/agentskills/agentskills.go@@ -0,0 +1,267 @@+// Package agentskills installs the Beacon Agent Skills (agent-skills/skills in the repository) into+// the user-level skill directories agent runtimes read, so every project on the machine sees them.+//+// The embedded copy under skills/ is kept byte-identical to agent-skills/skills by a test, the+// same arrangement the dashboard uses for the Lenses spec.+//+// A skill directory Beacon wrote carries a marker file next to SKILL.md. Beacon replaces or removes+// only directories that carry it, so a skill a person wrote or installed under the same name is+// never touched.+package agentskills++import (+ "embed"+ "errors"+ "fmt"+ "io/fs"+ "os"+ "path"+ "path/filepath"+ "sort"+ "strings"+)++//go:embed skills+var embedded embed.FS++// MarkerFile is the file in a skill directory that says Beacon wrote it.+const MarkerFile = ".beacon-managed"++const markerContent = "beacon-managed-agent-skill:v1\n"++// Action is what happened to one skill in one directory.+type Action string++const (+ ActionAdd Action = "add" // the skill was written+ ActionUpdate Action = "update" // Beacon's earlier copy was replaced+ ActionPresent Action = "present" // Beacon's copy is already current+ ActionSkip Action = "skip" // a skill by that name exists that Beacon did not write+ ActionRemove Action = "remove" // uninstall removed Beacon's copy+)++// Result is one skill in one root.+type Result struct {+ Skill string+ Root string+ Path string+ Action Action+ Err error+}++// Names lists the embedded skills.+func Names() []string {+ entries, _ := fs.ReadDir(embedded, "skills")+ var out []string+ for _, e := range entries {+ if e.IsDir() {+ out = append(out, e.Name())+ }+ }+ sort.Strings(out)+ return out+}++// Roots are the user-level skill directories Beacon installs into: ~/.agents/skills, the+// cross-runtime location (Codex CLI, Gemini CLI, OpenCode, Pi and others read it), and Claude+// Code's own ~/.claude/skills when Claude Code is set up on this machine. Claude Code does not+// read ~/.agents/skills.+func Roots(home string) []string {+ roots := []string{filepath.Join(home, ".agents", "skills")}+ claudeDir := strings.TrimSpace(os.Getenv("CLAUDE_CONFIG_DIR"))+ if claudeDir == "" {+ claudeDir = filepath.Join(home, ".claude")+ }+ if info, err := os.Stat(claudeDir); err == nil && info.IsDir() {+ roots = append(roots, filepath.Join(claudeDir, "skills"))+ }+ return roots+}++// Install writes every embedded skill into every root. Each skill is independent: one that fails+// is reported on its result and the rest still run.+func Install(roots []string) []Result {+ return apply(roots, false)+}++// Refresh brings the copies Beacon already wrote up to date with this binary, and writes nothing+// new. Install and repair run it, so an upgraded Beacon never leaves skills naming commands it no+// longer has.+func Refresh(roots []string) []Result {+ return apply(roots, true)+}++func apply(roots []string, onlyManaged bool) []Result {+ var out []Result+ for _, root := range roots {+ for _, name := range Names() {+ dir := filepath.Join(root, name)+ res := Result{Skill: name, Root: root, Path: dir}+ managed, exists, err := inspect(dir)+ switch {+ case err != nil:+ res.Action, res.Err = ActionSkip, err+ case exists && !managed:+ res.Action = ActionSkip+ case !exists && onlyManaged:+ continue+ case exists && current(dir, name):+ res.Action = ActionPresent+ default:+ res.Action = ActionAdd+ if exists {+ res.Action = ActionUpdate+ }+ res.Err = write(dir, name)+ }+ out = append(out, res)+ }+ }+ return out+}++// Uninstall removes the copies Beacon wrote, and nothing else.+func Uninstall(roots []string) []Result {+ var out []Result+ for _, root := range roots {+ for _, name := range Names() {+ dir := filepath.Join(root, name)+ managed, exists, err := inspect(dir)+ if err != nil {+ out = append(out, Result{Skill: name, Root: root, Path: dir, Action: ActionSkip, Err: err})+ continue+ }+ if !exists || !managed {+ continue+ }+ res := Result{Skill: name, Root: root, Path: dir, Action: ActionRemove}+ res.Err = os.RemoveAll(dir)+ out = append(out, res)+ }+ }+ return out+}++func inspect(dir string) (managed, exists bool, err error) {+ info, err := os.Lstat(dir)+ if errors.Is(err, os.ErrNotExist) {+ return false, false, nil+ }+ if err != nil {+ return false, false, err+ }+ if !info.IsDir() {+ // A symlink or a file: something the person set up. Never followed or replaced.+ return false, true, nil+ }+ data, err := os.ReadFile(filepath.Join(dir, MarkerFile))+ if errors.Is(err, os.ErrNotExist) {+ return false, true, nil+ }+ if err != nil {+ return false, true, err+ }+ return string(data) == markerContent, true, nil+}++// files lists one embedded skill's files, as slash paths relative to the skill directory.+func files(name string) ([]string, error) {+ var out []string+ base := path.Join("skills", name)+ err := fs.WalkDir(embedded, base, func(p string, d fs.DirEntry, err error) error {+ if err != nil {+ return err+ }+ if !d.IsDir() {+ out = append(out, strings.TrimPrefix(p, base+"/"))+ }+ return nil+ })+ return out, err+}++// current reports whether dir holds exactly the embedded skill and the marker.+func current(dir, name string) bool {+ want, err := files(name)+ if err != nil {+ return false+ }+ count := 0+ err = filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error {+ if err != nil {+ return err+ }+ if !d.IsDir() {+ count+++ }+ return nil+ })+ if err != nil || count != len(want)+1 {+ return false+ }+ for _, rel := range want {+ have, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(rel)))+ if err != nil {+ return false+ }+ data, _ := embedded.ReadFile(path.Join("skills", name, rel))+ if string(have) != string(data) {+ return false+ }+ }+ return true+}++// write builds the skill in a temporary sibling directory and swaps it into place, so a runtime+// never reads half a skill and a failure leaves the previous copy intact.+func write(dir, name string) error {+ parent := filepath.Dir(dir)+ if err := os.MkdirAll(parent, 0o755); err != nil {+ return err+ }+ tmp, err := os.MkdirTemp(parent, "."+name+".beacon-*")+ if err != nil {+ return err+ }+ defer os.RemoveAll(tmp)+ if err := os.Chmod(tmp, 0o755); err != nil {+ return err+ }+ rels, err := files(name)+ if err != nil {+ return err+ }+ for _, rel := range rels {+ data, err := embedded.ReadFile(path.Join("skills", name, rel))+ if err != nil {+ return err+ }+ target := filepath.Join(tmp, filepath.FromSlash(rel))+ if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {+ return err+ }+ if err := os.WriteFile(target, data, 0o644); err != nil {+ return err+ }+ }+ if err := os.WriteFile(filepath.Join(tmp, MarkerFile), []byte(markerContent), 0o644); err != nil {+ return err+ }+ var old string+ if _, err := os.Lstat(dir); err == nil {+ old = tmp + ".old"+ if err := os.Rename(dir, old); err != nil {+ return fmt.Errorf("could not replace %s: %w", dir, err)+ }+ }+ if err := os.Rename(tmp, dir); err != nil {+ if old != "" {+ _ = os.Rename(old, dir)+ }+ return err+ }+ if old != "" {+ return os.RemoveAll(old)+ }+ return nil+}diff --git a/cli/beacon/internal/agentskills/agentskills_test.go b/cli/beacon/internal/agentskills/agentskills_test.gonew file mode 100644index 00000000..5f9ad946--- /dev/null+++ b/cli/beacon/internal/agentskills/agentskills_test.go@@ -0,0 +1,164 @@+package agentskills++import (+ "io/fs"+ "os"+ "path"+ "path/filepath"+ "strings"+ "testing"+)++const publishedSkills = "../../../../agent-skills/skills"++func normalize(data []byte) string {+ return strings.ReplaceAll(string(data), "\r\n", "\n")+}++// The embedded copy is what onboarding installs; the published copy is what marketplaces ship.+// They must be the same skills. Edit agent-skills/skills and copy it here.+func TestEmbeddedSkillsMatchPublishedSkills(t *testing.T) {+ published := map[string]string{}+ err := filepath.WalkDir(publishedSkills, func(p string, d fs.DirEntry, err error) error {+ if err != nil || d.IsDir() {+ return err+ }+ rel, _ := filepath.Rel(publishedSkills, p)+ data, err := os.ReadFile(p)+ published[filepath.ToSlash(rel)] = normalize(data)+ return err+ })+ if err != nil {+ t.Fatal(err)+ }+ embeddedFiles := map[string]string{}+ err = fs.WalkDir(embedded, "skills", func(p string, d fs.DirEntry, err error) error {+ if err != nil || d.IsDir() {+ return err+ }+ data, err := embedded.ReadFile(p)+ embeddedFiles[strings.TrimPrefix(p, "skills/")] = normalize(data)+ return err+ })+ if err != nil {+ t.Fatal(err)+ }+ if len(published) == 0 {+ t.Fatal("no published skills found")+ }+ for rel, want := range published {+ if got, ok := embeddedFiles[rel]; !ok {+ t.Errorf("%s is published but not embedded: copy agent-skills/skills into cli/beacon/internal/agentskills/skills", rel)+ } else if got != want {+ t.Errorf("%s differs from the published copy: copy agent-skills/skills into cli/beacon/internal/agentskills/skills", rel)+ }+ }+ for rel := range embeddedFiles {+ if _, ok := published[rel]; !ok {+ t.Errorf("%s is embedded but no longer published: remove it", rel)+ }+ }+}++func TestInstallRefreshUninstall(t *testing.T) {+ root := filepath.Join(t.TempDir(), "skills")+ results := Install([]string{root})+ if len(results) != len(Names()) {+ t.Fatalf("results = %d, want %d", len(results), len(Names()))+ }+ for _, r := range results {+ if r.Err != nil || r.Action != ActionAdd {+ t.Fatalf("%s: action=%s err=%v", r.Skill, r.Action, r.Err)+ }+ data, err := os.ReadFile(filepath.Join(r.Path, "SKILL.md"))+ if err != nil {+ t.Fatal(err)+ }+ want, _ := embedded.ReadFile(path.Join("skills", r.Skill, "SKILL.md"))+ if string(data) != string(want) {+ t.Fatalf("%s: SKILL.md differs from the embedded copy", r.Skill)+ }+ }+ if _, err := os.Stat(filepath.Join(root, "beacon-memory-distill", "references", "lesson-quality.md")); err != nil {+ t.Fatalf("nested reference not installed: %v", err)+ }++ for _, r := range Install([]string{root}) {+ if r.Action != ActionPresent {+ t.Fatalf("%s: second install action = %s", r.Skill, r.Action)+ }+ }++ // A stale copy Beacon wrote is brought up to date by Refresh.+ stale := filepath.Join(root, "beacon-memory-recall", "SKILL.md")+ if err := os.WriteFile(stale, []byte("old"), 0o644); err != nil {+ t.Fatal(err)+ }+ refreshed := Refresh([]string{root})+ updated := 0+ for _, r := range refreshed {+ if r.Action == ActionUpdate {+ updated+++ }+ }+ if updated != 1 {+ t.Fatalf("refresh updated %d skills, want 1: %+v", updated, refreshed)+ }+ if data, _ := os.ReadFile(stale); string(data) == "old" {+ t.Fatal("refresh left the stale copy")+ }++ for _, r := range Uninstall([]string{root}) {+ if r.Err != nil || r.Action != ActionRemove {+ t.Fatalf("%s: action=%s err=%v", r.Skill, r.Action, r.Err)+ }+ }+ entries, _ := os.ReadDir(root)+ if len(entries) != 0 {+ t.Fatalf("uninstall left %d entries", len(entries))+ }+}++func TestNeverTouchesASkillBeaconDidNotWrite(t *testing.T) {+ root := filepath.Join(t.TempDir(), "skills")+ mine := filepath.Join(root, "beacon-memory-recall")+ if err := os.MkdirAll(mine, 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(mine, "SKILL.md"), []byte("mine"), 0o644); err != nil {+ t.Fatal(err)+ }+ for _, r := range Install([]string{root}) {+ if r.Skill == "beacon-memory-recall" && r.Action != ActionSkip {+ t.Fatalf("action = %s, want skip", r.Action)+ }+ }+ Uninstall([]string{root})+ if data, _ := os.ReadFile(filepath.Join(mine, "SKILL.md")); string(data) != "mine" {+ t.Fatal("a skill Beacon did not write was changed")+ }+}++func TestRefreshWritesNothingNew(t *testing.T) {+ root := filepath.Join(t.TempDir(), "skills")+ if results := Refresh([]string{root}); len(results) != 0 {+ t.Fatalf("refresh on an empty root = %+v", results)+ }+ if _, err := os.Stat(root); !os.IsNotExist(err) {+ t.Fatalf("refresh created %s", root)+ }+}++func TestRootsAddClaudeOnlyWhenClaudeIsSetUp(t *testing.T) {+ home := t.TempDir()+ t.Setenv("CLAUDE_CONFIG_DIR", "")+ if roots := Roots(home); len(roots) != 1 || roots[0] != filepath.Join(home, ".agents", "skills") {+ t.Fatalf("roots = %v", roots)+ }+ if err := os.Mkdir(filepath.Join(home, ".claude"), 0o700); err != nil {+ t.Fatal(err)+ }+ if roots := Roots(home); len(roots) != 2 || roots[1] != filepath.Join(home, ".claude", "skills") {+ t.Fatalf("roots = %v", roots)+ }+}diff --git a/cli/beacon/internal/agentskills/skills/beacon-lens-create/SKILL.md b/cli/beacon/internal/agentskills/skills/beacon-lens-create/SKILL.mdnew file mode 100644index 00000000..66a880a8--- /dev/null+++ b/cli/beacon/internal/agentskills/skills/beacon-lens-create/SKILL.md@@ -0,0 +1,222 @@+---+name: beacon-lens-create+description: Create, revise, debug or validate a Beacon lens, a single HTML file that renders one agent trace as a purpose-built view (a per-file review, a cost breakdown, a timeline of risky commands, a map of tool use) in a sandboxed tab of the local Beacon dashboard, fed once through window.beacon.getTrace(). Use when the user asks to "make a lens", "build a view of my traces", "visualize this session", wants a custom tab next to the full session in the Beacon dashboard, or when a lens fails to load, renders wrong, or needs checking before install.+license: MIT+compatibility: Requires the Beacon CLI (beacon) on PATH with endpoint capture installed, so there are traces to render. Reads only local state and makes no network calls.+metadata:+ author: asymptote-labs+ homepage: https://docs.beacon.sh/concepts/lenses+ version: "0.1.0"+---++# Beacon lens create++A **lens** is one self-contained HTML file that renders one agent trace: the prompts, agent+messages, tool calls, commands, file edits, approvals, token usage and threat-rule findings+Beacon recorded for a session. The local dashboard (`beacon endpoint dashboard`) shows lenses as+tabs on a session's page, next to **Full session**, and runs each one in a locked-down frame.++You write the file, check it against the user's real sessions, and install it. Nothing is+published anywhere: lenses live on this machine.++## Step 1: check that Beacon is available++```bash+beacon version+```++If `beacon` is not found, tell the user that lenses need the Beacon CLI, point them to+https://docs.beacon.sh/get-started/overview, and stop. Do not install it yourself.++## Step 2: decide what the lens shows++Start from the user's description. If it is missing, or leaves a choice open that changes what+the numbers mean (what counts as a "turn", a "failure", a "risky" command, which cost total), ask+one focused question before building. Define each unit from this request, not from another lens,+and label anything derived or estimated as such.++## Step 3: read the spec and the real data++```bash+beacon lenses spec # the format, the data, the sandbox, the style tokens+beacon lenses spec --example # a complete working lens to start from+beacon lenses list # lens ids already in use+beacon lenses data # exactly what getTrace() returns for the latest session+beacon lenses data --session <session-id>+```++Read the whole spec before writing anything. Then look at real data rather than guessing its+shape from the spec: note which event `type`s the user's sessions carry, whether `file.diff`,+`command.output` or `usage` is present, and whether `findings` exists. Design for those, and for+sessions that lack them. The output contains whatever content the log retained (prompts, command+output, diffs), so read it locally and do not paste large amounts back to the user.++## Step 4: write the file++One HTML file. No build step, bundler or `package.json`. Write it in the user's project or a+scratch directory, never directly in the lens store.++### Hard limits++The dashboard enforces these; a lens that breaks them fails to install or fails to run.++- **One file, at most 16 MiB**, with every script, style, image and font inline (`data:` URIs for+ images and fonts). Inlining a library is allowed but counts against the size and costs parse+ time on every open; prefer a few lines of your own.+- **A manifest**, in exactly one element whose opening tag is spelled exactly+ `<script type="application/beacon-lens+json">`, holding `id`, `title`, `version` and+ `"api": "beacon.lens.v1"` (optionally `description`, `icon`, `author`; unknown keys are an+ error). The `id` is lowercase letters, digits and hyphens, and cannot be a built-in lens's id.+- **No network and nothing loaded by URL.** The frame's Content Security Policy blocks `fetch`,+ XHR, WebSockets, `EventSource`, `sendBeacon`, remote scripts, stylesheets, fonts and images,+ `@import`, workers, nested frames, `eval` and `new Function`.+- **No dashboard access.** The frame is `sandbox="allow-scripts"` with an opaque origin: no+ cookies, `localStorage`, `sessionStorage` or IndexedDB, no access to the parent page, no popups+ or forms. Keep state in memory.+- **Never navigate the frame.** The dashboard closes a lens that loads a second document.++### The data++The host defines `window.beacon` before your scripts run. Its one call is the whole data API:++```js+const data = await window.beacon.getTrace();+```++It resolves once with everything you get and never refreshes. Calling it again returns the same+promise. It rejects with an `Error` if the trace does not arrive within 10 seconds; show that+message instead of a blank tab.++The result is `LensDataV1`; `beacon lenses spec` has the full shape. The parts you will use most:++- `trace.summary`: title, `started_at`/`ended_at`, `event_count`, `harness.name`, `session`,+ `repository`, `model`, `token_usage`.+- `trace.events[]`, in order, each with `id`, `number`, `timestamp`, `type`, `action` and+ optional `title`, `summary`, `fidelity`, `content`, `tool`, `command`, `file`, `mcp`,+ `approval`, `model`, `usage`, `tool_call_id`. `type` is one of `user_message`,+ `agent_message`, `agent_reasoning`, `tool_call`, `tool_result`, `command`, `file`, `mcp`,+ `approval`, `token_usage`, `session`, `error`, `other`, and the list can grow.+- `findings`: threat-rule matches, each pointing at its evidence by `event_ids`.+- `token_usage` and `token_coverage`: the trace's counted usage, and whether this runtime reports+ usage at all.+- `truncated`: the trace was cut to fit the size cap.++Things that are easy to get wrong:++- **Retained text is an object, not a string.** Prompts, messages, `command.output` and+ `file.diff` arrive as `{text?, included, retention, redacted?, truncated?, hash?, bytes?}`.+ When `included` is false the text was not kept or was redacted; show the `hash` and `bytes`+ instead of an empty box, and say why.+- **Missing is not empty.** An absent `findings` means the trace was not scanned; an empty+ `findings.items` means it was scanned and nothing matched. Say which. The same goes for+ `token_usage`.+- **Do not sum `usage` across events for a total.** Some runtimes report the same tokens on two+ channels or as cumulative counters. `token_usage.totals` is the deduplicated count; if you+ also show per-event figures, say they can add up to more. `cost_usd` is only ever what the+ runtime reported; Beacon never estimates cost, and neither should a lens.+- **`fidelity: "inferred"`** marks an action Beacon derived rather than observed (for example an+ approval built from a pre-tool notification). Show the difference when it matters.+- **Pair calls with results on `tool_call_id`**, not on adjacency, and order by `number` or+ `timestamp`, not array position.+- **Be honest about truncation.** When `truncated` is true, or `trace.events.length` is less than+ `trace.summary.event_count`, say "over the first N of M events" instead of presenting a partial+ total as the whole trace. A finding's evidence may point at an event that is not in the bundle.++### Rules for the code++- **Only these fields are guaranteed:** `api_version`, `trace.schema_version`, `trace.id`,+ `trace.summary.id`, `trace.events` (possibly empty), each event's `id`, `number`, `timestamp`,+ `type` and `action`, and `truncated`. Everything else can be missing. Show a placeholder, never+ `undefined` or `NaN`, and never throw on a missing field.+- **Skip what you do not recognise**: new event types, enum values and fields appear without a+ version bump.+- **Treat every string as untrusted.** Trace content is whatever the agent and its tools produced,+ often HTML, code and markup. Build nodes with `textContent` or `document.createTextNode`; never+ `innerHTML`, `outerHTML`, `insertAdjacentHTML` or `document.write`, and never use trace content+ as a URL.+- **Render immediately**: a loading line first, then the content when `getTrace()` resolves, an+ error line if it rejects, and an empty state for a trace with nothing to show. Keep the states+ mutually exclusive; if you use the `hidden` attribute, add `[hidden] { display: none !important; }`+ so your own `display` rules cannot reveal two states at once.+- **Expect thousands of events.** Build the DOM once; summarise, collapse or paginate long lists+ instead of rendering every row.+- No settings and no persistence; there is nowhere to save anything.++### Look like the dashboard++The lens renders inside a session page, under the page's own heading and tab bar, so it should+read as that tab's content rather than an embedded widget.++- **No page chrome.** Do not open with a title, `<h1>` or eyebrow text; the tab label is the+ heading. Add an `<h2>` only where a later section needs one. Leave `html` and `body`+ transparent, with no background, no outer padding or margin (`body { margin: 0 }`), and no+ outer border.+- **Full width.** Do not cap the content with a centred `max-width`.+- **Let it grow.** The dashboard sizes the frame to your document's height as it changes. Never+ size the root to `100vh` or `height: 100%`, and do not build an inner scrolling container.+- **Use the dashboard's tokens, each with a fallback** so the file also renders on its own:+ `--beacon-text`, `--beacon-muted`, `--beacon-line` (hairlines), `--beacon-panel-soft`+ (recessed fills), `--beacon-accent` and `--beacon-accent-soft` (links, selection, focus, one+ emphasis), `--beacon-danger`, `--beacon-warn`, `--beacon-ok` (only where they mean something),+ `--beacon-font-sans` and `--beacon-font-mono`. Take colours from these tokens rather than+ inventing a palette, so the lens follows the dashboard if its theme changes.+- **Type.** Body 13–14px. Monospace at about 13px for commands, paths, tool names, hashes, IDs+ and number columns. Two weights only, 400 and 500; headings are 400 and get their hierarchy+ from size. Use as few sizes, colours and spacing values as you can.+- **Dense and flat.** Compact tables and tight rows over padded cards; one hairline between rows+ rather than a box around each; no shadows or gradients; a light fill on hover. Right-align+ numbers and format them with `Intl.NumberFormat`; format times as short dates or relative times.+- **Motion.** Almost none: under 150 ms, and off under `prefers-reduced-motion: reduce`.+- Check it at a narrow and a wide width; the frame is as wide as the session page.++## Step 5: lint until clean++```bash+beacon lenses lint --strict path/to/my-lens.lens.html+```++Errors (size, a missing or invalid manifest) stop the lens from running. Warnings name the line+where the lens does something the sandbox blocks or the spec forbids: HTML parsing of content,+network calls, resources loaded by URL, browser storage, navigation, viewport-height layouts, or+never calling `getTrace()`. Fix both.++## Step 6: preview it against real sessions++```bash+beacon lenses preview path/to/my-lens.lens.html --session <session-id>+```++This serves the dashboard with the lens added and prints the session page to open (`--open`+opens a browser). It runs until interrupted, so start it in the background if your harness+blocks on long-running commands. The file is read again on every page load: edit, reload,+repeat. Nothing is installed.++Ask the user to look at it, and check at least one session that lacks the data the lens is about+(no diffs, no usage, no findings) to see the empty state. If the dashboard shows "The … lens+could not be shown" and falls back to the full session, the notice gives the reason:++- **it raised an error**: an exception before the lens settled, usually a missing field. Guard it.+- **it did not render within 10 seconds**: the lens never called `getTrace()`, or blocked the+ main thread on a large trace.+- **it navigated away from itself**: something set `location`, submitted a form or followed a+ link inside the frame.++## Step 7: install it++Only after the user has seen it in preview and is happy with it:++```bash+beacon lenses add path/to/my-lens.lens.html+```++It now appears in the **+** menu on every session page. To change it later, edit the source+file, bump `version` in its manifest, and run `beacon lenses add` again; an equal or lower+version is refused unless the user asks for `--force`. `beacon lenses remove <id>` uninstalls it.++## Rules++- Never weaken the sandbox or ask the user to. A lens that needs the network is the wrong design;+ everything it can have is in `getTrace()`.+- Never put trace content into the lens file. The file holds only code; it renders data at view+ time.+- Never install a lens the user has not seen in preview, and never use a built-in lens's id.diff --git a/cli/beacon/internal/agentskills/skills/beacon-memory-distill/SKILL.md b/cli/beacon/internal/agentskills/skills/beacon-memory-distill/SKILL.mdnew file mode 100644index 00000000..004447d9--- /dev/null+++ b/cli/beacon/internal/agentskills/skills/beacon-memory-distill/SKILL.md@@ -0,0 +1,246 @@+---+name: beacon-memory-distill+description: Turn recorded agent sessions (Beacon traces from Claude Code, Cursor, Codex, OpenCode, and other harnesses) into reviewed, reusable project memory. Scores selected traces, reads the source trace behind each high-signal candidate, drafts a grounded lesson, and approves it only after the user confirms. Use when the user asks to "learn from", "remember", "save the lesson from", or "turn into memory" a recent session, fix, or debugging effort, or asks to review Beacon memory candidates.+license: MIT+compatibility: Requires the Beacon CLI (beacon) on PATH with endpoint capture installed. Scoring calls the configured Jev evaluator over the network (hosted TypeSafe by default) and needs TYPESAFE_API_KEY or BEACON_JEV_API_KEY; every other step is local.+metadata:+ author: asymptote-labs+ homepage: https://docs.beacon.sh/concepts/cross-harness-memory+ version: "0.1.0"+---++# Beacon memory distill: traces to memory++Beacon captures what agents do in every supported harness. This skill runs the review+loop that turns a few of those sessions into **approved project memory** that any later+agent can recall, whichever harness it runs in:++1. Pick traces.+2. Score them with the evaluator (the one networked step, and only with consent), or,+ where evaluation is not allowed, skip scoring and read the traces yourself.+3. For each candidate, read the source trace and draft the lesson.+4. The user confirms, edits, or rejects each draft.+5. Approve with the reviewed text.++The evaluator returns probabilities only. It says a trace looks reusable; it does not say+what the lesson is. **You write the lesson, from the trace, and the user approves it.**+Never approve a candidate with its placeholder body ("no lesson text was extracted").++Commands that start from a trace (`evaluations run`, `candidates create`) file the+memory under the repository the trace recorded, wherever you run them. Run every other+command from inside the repository the memory is for, or pass `--project <path>`.++## Step 1: preflight++```bash+beacon version+beacon endpoint traces status --json+```++- If `beacon` is missing, stop and point the user to+ https://docs.beacon.sh/get-started/overview. Do not install it yourself.+- If `status` reports `"enabled": false`, there is no local history, and only the last day or+ two of sessions are still in the runtime log. Suggest creating the history, which keeps+ sessions for 90 days and stays on this machine, and run it only if the user agrees:+ `beacon endpoint traces reindex`.++## Step 2: pick traces++Use what the user named: a session, a date, a harness, or a topic. Otherwise list recent+traces and propose a short set (up to 10) that look like finished work with a correction,+a fix, or a non-obvious procedure.++```bash+beacon endpoint traces list --json --limit 20+beacon endpoint traces list --json --limit 20 -q "<topic terms>"+beacon endpoint traces search "<error text or file>" --json --limit 10+```++Prefer traces from this repository. Skip trivial sessions (a single question, an+abandoned attempt) since they cost evaluator calls and yield nothing.++Reading the list:++- Only `session:` IDs are sessions. IDs starting `event:` are single events with no+ session, almost always OTLP metric samples such as `claude_code.active_time.total`.+ They arrive every few seconds and sort to the top, so a short list can be all noise;+ raise `--limit` or use `--page` until you have sessions, and never select them.+ `evaluations run` skips them on its own when it selects by `--limit`, but never pass+ one to `--trace`.+- A session whose `updated_at` is within the last few minutes is still being written.+ Leave it for next time: a lesson drafted from half a session is usually wrong about+ how it ended.+- A session's `repository` is where its memory will be filed. It is null for many+ sessions, because not every event carries one, and then Beacon falls back to the+ current directory. Evaluate or create a candidate for such a session only with an+ explicit `--project <path>` you can justify from the paths in its commands.++## Step 3: dry run, then ask++The dry run is local. It shows the traces selected and the estimated cost:++```bash+beacon memory evaluations run --dry-run --trace <trace-id>+beacon memory evaluations run --dry-run --limit 10 --harness <name> --since <rfc3339>+```++Before the real run, tell the user plainly and **wait for an explicit yes**:++- Each selected trace is sent, as a bounded and redacted projection, to the evaluator at+ `BEACON_JEV_ENDPOINT` if that is set, otherwise to the hosted TypeSafe endpoint.+- It costs about the estimate the dry run printed.+- Nothing is approved or written into memory by this step.++Check for a key without printing it:++```bash+test -n "${TYPESAFE_API_KEY:-}${BEACON_JEV_API_KEY:-}" && echo "evaluator key present" || echo "no evaluator key"+```++With no key, stop and tell the user to export `TYPESAFE_API_KEY` (or point+`BEACON_JEV_ENDPOINT` at their organization's compatible evaluator). Never ask them to+paste a key into the chat, and never pass `--jev-api-key` on the command line. If the user+or their organization does not allow external evaluation, or has no key and does not want+one, skip Steps 3 and 4 and go to [Without an evaluator](#without-an-evaluator).++## Step 4: score++Repeat the exact selection the user approved, without `--dry-run`:++```bash+beacon memory evaluations run --trace <trace-id> --json+beacon memory evaluations run --limit 10 --harness <name> --since <rfc3339> --json+```++A trace becomes a candidate only when `task_success` is at least 0.50 and the mean score+is at least 0.60. Report how many were scored and how many became candidates. The text+output names why each trace was not promoted; do not try to overturn that.++## Step 5: draft a lesson for each candidate++```bash+beacon memory candidates list --state candidate --json+beacon memory candidates show <candidate-id> --json+```++For each candidate, read its evidence trace. Filter to the event types that carry+substance and write the JSON to a file before reading it:++```bash+beacon endpoint traces show <trace-id> --json --event-type user_message,tool_call,command,tool_result,approval,error --limit 150 > trace-1.json+beacon endpoint traces show <trace-id> --json --event-type user_message,tool_call,command,tool_result,approval,error --offset 151 --limit 150 > trace-2.json+beacon endpoint traces show <trace-id> --json --around-event <n> --before 5 --after 5+```++How to read what comes back:++- `--event-type` filters the coarse `type` field (`user_message`, `tool_call`,+ `command`, `tool_result`, `approval`, `error`, `session`, `token_usage`, `metric`).+ Action names such as `prompt.submitted` match nothing.+- Filter every read. Hooks and OTLP both record, so an unfiltered session is mostly+ `token_usage` and `session` events, and an unfiltered `traces show` on a large log can+ take minutes and exceed a tool timeout. Filtered reads return in seconds.+ `range.total_events` counts the filtered events, so it tells you how much is left.+- The log usually holds no assistant text and no tool output. For Claude Code, a+ session's substance is its `user_message` events (the only ones with a `content`+ object), its `tool_call` and `command` events (tool name and command line), and+ whether a `tool_result` was a failure. The strongest evidence for a lesson is a+ failed command followed by a different command that succeeded.+- A `user_message` with `content.included` false, or only a hash, means Beacon kept+ metadata only. You cannot draft from a hash; say the trace was unreadable.+- `--around-event` centres on the unfiltered event number. Combined with `--event-type`+ it can return no events at all, so read a small unfiltered window around the number+ and skip the `token_usage` and `session` rows yourself.++Work out, from the events themselves:++- What the task was (the first prompt).+- What went wrong or was non-obvious: a failed command, a correction from the user, a+ retry, a wrong assumption that got reversed.+- What finally worked, with the specific command, file, flag, or order of steps.+- How the agent confirmed it worked (a passing test, a clean build).++Then check whether it is already known:++```bash+beacon memory list --json -q "<two or three distinctive terms>"+```++Draft each lesson in the shape given in [references/lesson-quality.md](references/lesson-quality.md):+title, kind, applicability, body, tags, and the event numbers it rests on. Read that file+before writing your first draft.++Recommend **reject** when the trace has no transferable lesson (it was routine, too+specific to one moment, or the fix was later reverted), and **supersede** when an+existing memory already says the same thing.++## Step 6: review with the user++Show every draft at once, each with its recommendation (approve, reject, or supersede),+the candidate ID, and the trace events that support it. Ask the user to confirm or edit+each one. Do not approve, reject, or supersede anything they have not confirmed. Silence+is not approval.++## Step 7: record the decisions++Approve with the reviewed text. Pass the body on stdin so quoting stays safe:++```bash+beacon memory candidates approve <candidate-id> \+ --title "<title>" \+ --kind <workflow|correction|debugging_pattern|gotcha|convention> \+ --applicability "<when this applies>" \+ --tag <tag> --tag <tag> \+ --reason "Reviewed with the user; lesson drafted from trace events <n>-<m>" \+ --body-file - --json <<'LESSON'+<body>+LESSON+```++```bash+beacon memory candidates reject <candidate-id> --reason "<why it is not reusable>"+beacon memory candidates supersede <candidate-id> --replacement <memory-id> --reason "<which memory already covers it>"+```++Confirm what was stored with `beacon memory show <memory-id>`, then summarize: approved,+rejected, superseded, and the new memory IDs. Mention that any agent in any harness can+now recall these with the `beacon-memory-recall` skill or the Beacon MCP tools, and that a+memory worth loading automatically can be installed as a skill with+`beacon-memory-promote`.++## Without an evaluator++When scoring is not allowed, there is no evaluator to prefilter, so pick fewer traces+(three at most) and only ones the user named or that clearly hold finished work. For+each one, read it and draft the lesson exactly as in Step 5, then review the drafts with+the user as in Step 6. Only after the user confirms a draft, write it as a candidate:++```bash+beacon memory candidates create --trace <trace-id> \+ --title "<title>" \+ --kind <workflow|correction|debugging_pattern|gotcha|convention> \+ --applicability "<when this applies>" \+ --tag <tag> --tag <tag> \+ --body-file - --json <<'LESSON'+<body>+LESSON+```++The trace's events become the candidate's evidence, and it has no+`source_evaluation_id`. It still waits for approval, so approve it with its candidate ID+and a `--reason` as in Step 7; the text it was created with carries through, so the+title, kind, and body flags can be left off. A trace the evaluator scored and did not+promote is not a reason to write one by hand: that path is for when there is no+evaluator, not for overturning it.++## Boundaries++- The evaluation run is the only networked step. Run it only after the dry run and the+ user's explicit yes, and only on the selection they approved. `candidates create` is+ local.+- Memory is shared with every future agent in this project. Never put secrets, tokens,+ credentials, internal hostnames, customer data, or personal information into a title,+ body, tag, or reason, even when the trace contains them. Describe them instead ("the+ staging API key from 1Password").+- Quote trace content sparingly and only to support a draft.+- Never edit `memory.db` or the runtime log directly. Use the CLI.diff --git a/cli/beacon/internal/agentskills/skills/beacon-memory-distill/references/lesson-quality.md b/cli/beacon/internal/agentskills/skills/beacon-memory-distill/references/lesson-quality.mdnew file mode 100644index 00000000..a49af13e--- /dev/null+++ b/cli/beacon/internal/agentskills/skills/beacon-memory-distill/references/lesson-quality.md@@ -0,0 +1,58 @@+# Writing a Beacon memory lesson++A memory is read by a future agent that has never seen the original session, often in a+different harness, at the start of an unrelated task. Write for that reader.++## Shape++| Field | Rule |+|-------|------|+| `--title` | Imperative, specific, under 80 characters. It is the search hit and the skill description, so name the tool, file, or error. |+| `--kind` | One of the five kinds below. |+| `--applicability` | Starts with "when", "before", or "after". Names the trigger a future agent would recognise, such as a file path, a command, or an error string. |+| body | 3–10 lines. First, what to do. Then why, in one sentence, from the trace. Then how to confirm it worked. Use exact commands and paths in backticks. |+| `--tag` | 2–4 lowercase tags: the subsystem, the tool, the harness only if it matters. |+| `--reason` | Who reviewed it and which trace events support it. |++## Kinds++- `workflow`: a procedure with a required order. "Build the hooks binary before+ `go test ./...` in cli/beacon."+- `correction`: the user corrected the agent, and the correction generalises. "Use+ `testenv.SetHome`, not `t.Setenv(\"HOME\")`: Windows ignores HOME."+- `debugging_pattern`: a symptom that points to a cause that is not obvious. "`pattern+ hooks.bin: no matching files` means the embedded hooks binary was never built."+- `gotcha`: a trap with no error message, or a misleading one. "Vector 0.57+ stops+ expanding `${VAR}` in the generated packs."+- `convention`: a project rule the trace shows, not a personal preference. "Every new+ collection path sets `harness.collection_method`."++## Good++```text+Title: Build the embedded hooks binary before running cli/beacon tests+Kind: workflow+Applicability: when running go test in cli/beacon on a fresh checkout+Tags: build, testing, cli++Run `make build-hooks-current` in cli/beacon before `go test ./...`.+The package embeds hooks.bin, and on a fresh checkout the build fails with+"pattern hooks.bin: no matching files found" (trace events 14-19).+Confirm with `go build ./...`, which should exit 0 before you run the tests.+```++## Not a memory++- A summary of what happened ("The agent fixed the flaky test"). Say what to do next time.+- A one-off fact ("PR 612 was merged on Tuesday").+- Anything true only on one machine, branch, or day.+- Speculation the trace does not show. If you cannot point to the events, do not write it.+- A restatement of the repository's own docs. Memory is for what the docs do not say.++## Before you present a draft++- Every claim traces to an event number you read.+- No secret, token, credential, hostname, customer name, or personal detail appears+ anywhere in the fields.+- It would still help an agent that has never seen this session.+- It does not duplicate an existing memory (check with `beacon memory list -q`).diff --git a/cli/beacon/internal/agentskills/skills/beacon-memory-promote/SKILL.md b/cli/beacon/internal/agentskills/skills/beacon-memory-promote/SKILL.mdnew file mode 100644index 00000000..1a13f7cd--- /dev/null+++ b/cli/beacon/internal/agentskills/skills/beacon-memory-promote/SKILL.md@@ -0,0 +1,94 @@+---+name: beacon-memory-promote+description: Install approved Beacon project memory as an Agent Skill in the repository (.agents/skills/<slug>/SKILL.md), so every skill-capable harness loads the lesson automatically without a memory lookup. Use when the user asks to "make this a skill", "promote", "install", or "share" an approved Beacon memory, or wants the team's agents to always follow a learned workflow or convention.+license: MIT+compatibility: Requires the Beacon CLI (beacon) on PATH. Local only. Writes files inside the current project.+metadata:+ author: asymptote-labs+ homepage: https://docs.beacon.sh/cli/memory+ version: "0.1.0"+---++# Beacon memory promote: memory to skill++Approved memory is recalled on demand. A **skill** is loaded by the harness itself+whenever its description matches the task, and when it is committed to the repository it+reaches every teammate and every harness that reads `.agents/skills` (Codex, Cursor,+Gemini CLI, GitHub Copilot, OpenCode, Amp, goose, and others; Claude Code reads+`.claude/skills`).++Promote only what earns that. Each installed skill adds to what every agent considers on+every task.++## What to promote++Good candidates:++- `workflow` and `convention` memories that apply to many tasks in this repository.+- A `debugging_pattern` for a failure that keeps recurring.++Leave in memory, where recall finds them when needed:++- One-off gotchas tied to a single file or incident.+- Anything that duplicates the repository's CLAUDE.md, AGENTS.md, or contributing docs.+ Suggest editing those docs instead.++## Step 1: choose the memory++```bash+beacon memory list --limit 25+beacon memory show <memory-id> --json+```++The skill commands take the **candidate** ID, which is the `candidate_id` field of the+memory.++## Step 2: preview++```bash+beacon memory skills preview <candidate-id>+```++Check the preview with the user:++- The `description` is the title plus the memory's applicability. It decides when a+ harness loads the skill, so it must name the trigger (a command, path, or error). If it+ is vague, the fix is a better memory: draft a sharper title and applicability, approve a+ replacement through the `beacon-memory-distill` workflow, and supersede the old one.+- The body must hold no secrets, hostnames, or personal details. It is about to become a+ file that is likely to be committed.++## Step 3: install, after the user confirms++```bash+beacon memory skills install <candidate-id>+```++This writes `.agents/skills/<slug>/SKILL.md` in the project (or the `--project` path). It+refuses to overwrite an existing file; pass `--force` only when the user wants to replace+the generated skill, and never over a file a person has edited by hand without asking.++For Claude Code, which reads `.claude/skills` rather than `.agents/skills`, offer to+link the skill there:++```bash+mkdir -p .claude/skills && ln -s ../../.agents/skills/<slug> .claude/skills/<slug>+```++## Step 4: hand off++Show the path and remind the user that:++- The file carries Beacon provenance under `metadata` (`beacon_memory_id`,+ `beacon_candidate_id`), so a reviewer can trace it back to the approved memory and the+ source session.+- It becomes team-wide only when they commit it. Do not commit or push unless they ask.+- If the memory is later superseded, the installed skill is not updated automatically.+ Re-run preview and install with `--force` from the replacement candidate.++## Boundaries++- Never install without the user seeing the preview and confirming.+- Never approve or edit memory here. Use `beacon-memory-distill`.+- Do not write to user-level skill directories (such as `~/.agents/skills`). Beacon memory+ is scoped to a project.diff --git a/cli/beacon/internal/agentskills/skills/beacon-memory-recall/SKILL.md b/cli/beacon/internal/agentskills/skills/beacon-memory-recall/SKILL.mdnew file mode 100644index 00000000..4518156d--- /dev/null+++ b/cli/beacon/internal/agentskills/skills/beacon-memory-recall/SKILL.md@@ -0,0 +1,107 @@+---+name: beacon-memory-recall+description: Retrieve reviewed project memory that Beacon distilled from earlier agent sessions in any harness (Claude Code, Cursor, Codex, OpenCode, and others) before starting work. Use at the start of a non-trivial task in a repository, when the user asks "have we seen this before", "what did we learn last time", or "how did we fix this in Cursor/Codex", or when a build, test, or deploy step fails in a way that may have a known fix.+license: MIT+compatibility: Requires the Beacon CLI (beacon) on PATH with endpoint capture installed. Reads only local state and makes no network calls.+metadata:+ author: asymptote-labs+ homepage: https://docs.beacon.sh/concepts/cross-harness-memory+ version: "0.1.0"+---++# Beacon memory recall++Beacon records what agents do across every supported harness into a local log. Through+the `beacon-memory-distill` workflow, a person reviews selected sessions and approves the+reusable lessons into **project memory**. This skill reads that memory back, so you start+the task knowing what earlier agents, in this harness or any other, already learned about+this repository.++Approved memory has been reviewed by a person. Raw traces have not. Keep the two apart in+everything you say.++## When to recall++- Before planning a non-trivial change in a repository you have not worked in during this+ session.+- When a command fails in a way that could have a known fix (flaky tests, packaging,+ environment setup, release steps).+- When the user asks what was learned, tried, or decided before.++Skip it for trivial edits, and recall at most once per task unless the task changes+direction.++## Step 1: check that Beacon is available++```bash+beacon version+```++If `beacon` is not found, tell the user that project memory is unavailable because the+Beacon CLI is not installed, point them to https://docs.beacon.sh/get-started/overview, and+continue the task without memory. Do not install it yourself.++## Step 2: retrieve memory++Prefer the Beacon MCP tools when this session has them. They are named `search_memory`,+`get_memory`, and `get_memory_context`, usually under a server called `beacon`.++1. Call `get_memory_context` with `task` set to two or three distinctive keywords from+ the current task (a tool name, file, error string). Terms are ANDed, so a full+ sentence will over-constrain the search and return nothing. Drop terms if the first+ attempt is empty.+2. Call `get_memory` with an `id` from that result when you need the full body and its+ evidence.++Without the MCP tools, use the CLI from inside the repository:++```bash+# Up to five memories matching the task's key terms (every term must match)+beacon memory list --json --limit 5 -q "<two or three distinctive terms>"++# Everything approved for this project, newest first+beacon memory list --limit 25++# One memory in full, with its source traces+beacon memory show <memory-id>+```++Search terms are ANDed, so start with two or three distinctive words (a tool, a file, an+error string) and drop terms if nothing matches. `--kind` narrows to `workflow`,+`correction`, `debugging_pattern`, `gotcha`, or `convention`.++Memory is scoped to the project resolved from the current directory. Run from inside the+repository, or pass `--project <path>`.++## Step 3: use what you found++- Apply a memory only when its applicability matches the current situation. Memories are+ lessons from specific sessions, not project policy. If one conflicts with the user's+ instructions or the repository's own docs (CLAUDE.md, AGENTS.md, README), follow the+ user and the docs, and mention the conflict.+- When a memory changes what you do, say so in one line and cite its ID, for example:+ "Using Beacon memory `memory_4f2c…`: package smoke needs build-pkg.sh first."+- If nothing relevant comes back, carry on. Do not report an empty result unless the user+ asked.++## Raw history, only when asked++When the user explicitly asks what happened in an earlier session ("what did Cursor do+yesterday on the release script?"), you can search raw traces:++```bash+beacon endpoint traces search "<terms>" --json --limit 10+beacon endpoint traces show <trace-id> --json --limit 200+```++Present that as unreviewed history, never as approved memory. Traces can contain prompts,+command output, and file contents: quote only what the user needs, and never repeat+anything that looks like a credential. If the history holds a lesson worth keeping,+suggest the `beacon-memory-distill` workflow so a person can review it.++## Boundaries++- Read-only. Never approve, reject, or edit memory from this skill.+- Never run `beacon memory evaluations run` here. That step sends trace data to an+ evaluator over the network and belongs to `beacon-memory-distill`, where the user+ consents to it.diff --git a/cli/beacon/internal/mcpconnect/engine.go b/cli/beacon/internal/mcpconnect/engine.goindex 92774a14..b72a3ef4 100644--- a/cli/beacon/internal/mcpconnect/engine.go+++ b/cli/beacon/internal/mcpconnect/engine.go@@ -111,6 +111,11 @@ type state struct {}func inspect(t Target, path string) (state, error) {+ return inspectNamed(t, path, ServerName)+}++// inspectNamed reads what a config holds under one server name.+func inspectNamed(t Target, path, name string) (state, error) {var st statecf, err := readConfig(path)if err != nil {@@ -129,7 +134,7 @@ func inspect(t Target, path string) (state, error) {return st, fmt.Errorf("%s: %q is not a table", path, t.container[0])}}- st.entry, st.exists = tomlTableEntry(parsed, t.container[0], ServerName)+ st.entry, st.exists = tomlTableEntry(parsed, t.container[0], name)default:parsed, err := decodeJSONC(cf.text)if err != nil {@@ -141,12 +146,12 @@ func inspect(t Target, path string) (state, error) {if err != nil {return st, fmt.Errorf("%s: %v", path, err)}- if len(chain) == len(t.container)+1 && chain[len(chain)-1].memberCount(ServerName) > 1 {- return st, fmt.Errorf("%s: %q appears more than once", path, ServerName)+ if len(chain) == len(t.container)+1 && chain[len(chain)-1].memberCount(name) > 1 {+ return st, fmt.Errorf("%s: %q appears more than once", path, name)}}container := dig(parsed, t.container)- if raw, ok := container[ServerName]; ok {+ if raw, ok := container[name]; ok {st.exists = truest.entry, _ = raw.(map[string]any)if st.entry == nil {diff --git a/cli/beacon/internal/mcpconnect/local.go b/cli/beacon/internal/mcpconnect/local.gonew file mode 100644index 00000000..f630a5ee--- /dev/null+++ b/cli/beacon/internal/mcpconnect/local.go@@ -0,0 +1,284 @@+package mcpconnect++import (+ "context"+ "errors"+ "fmt"+ "path/filepath"+ "reflect"+ "strings"+ "time"+)++// The local stdio server, `beacon mcp serve`, reads this machine's runtime log. Onboarding+// registers it in every detected harness unless the person opts out, so an agent can search its+// own history whichever destination was chosen. It is a different entry from Beacon Cloud MCP+// (ServerName) and has its own manifest, so `beacon mcp connect` and `disconnect` never touch it+// and removing it never touches theirs.+//+// The policy is narrower than connect's: Beacon adds the entry where the name is free and never+// replaces one that is already there, whoever wrote it. Nothing here touches the network.++// LocalServerName is the name the local stdio server is registered under.+const LocalServerName = "beacon"++// LocalManifestPath is the file under the home directory that records the local entries Beacon+// wrote.+const LocalManifestPath = ".beacon/mcp/local.json"++// LocalOptions configures registering the local server.+type LocalOptions struct {+ Home string+ // Command is the beacon executable the harness runs, as an absolute path: harnesses started+ // from a desktop launcher do not see a shell's PATH.+ Command string++ LookPath func(string) (string, error)+ Run func(ctx context.Context, name string, args ...string) ([]byte, error)+}++func (o LocalOptions) connectOptions() Options {+ return Options{Home: o.Home, LookPath: o.LookPath, Run: o.Run}+}++var timeNow = time.Now++func localArgs() []any {+ return []any{"mcp", "serve"}+}++// LocalSupported reports whether Beacon can register the local server in t.+func (t Target) LocalSupported() bool {+ return t.Automatic && t.localEntry != nil+}++// InstallLocal registers the local server in each target that supports it. Each target is+// independent: a failure is reported on its item and the rest still run.+func InstallLocal(ctx context.Context, opts LocalOptions, targets []Target) ([]Item, error) {+ if strings.TrimSpace(opts.Command) == "" {+ return nil, errors.New("the beacon executable path is required")+ }+ manifestFile := filepath.Join(opts.Home, LocalManifestPath)+ m, err := loadManifestAt(manifestFile)+ if err != nil {+ return nil, err+ }+ copts := opts.connectOptions()+ var items []Item+ for _, t := range targets {+ if !t.LocalSupported() {+ continue+ }+ it := Item{Target: t, Method: "file"}+ path, err := t.path(opts.Home)+ if err != nil {+ it.Action, it.Detail = ActionSkip, err.Error()+ items = append(items, it)+ continue+ }+ it.Path = path+ st, err := inspectNamed(t, path, LocalServerName)+ if err != nil {+ it.Action, it.Detail = ActionSkip, err.Error()+ items = append(items, it)+ continue+ }+ if st.exists {+ it.Action, it.Detail = ActionPresent, "an entry named "+LocalServerName+" is already configured; left as is"+ items = append(items, it)+ continue+ }+ it.Action = ActionAdd+ if t.cli != "" {+ if cliPath, err := copts.lookPath(t.cli); err == nil {+ it.cliPath, it.Method = cliPath, t.cli+" CLI"+ }+ }+ rec, err := addLocal(ctx, opts, it, st)+ if err != nil {+ it.Err = err+ items = append(items, it)+ continue+ }+ m.put(rec)+ if err := m.saveAt(manifestFile); err != nil {+ it.Err = fmt.Errorf("the entry was written, but the record of it could not be saved (%w); `beacon mcp uninstall` will not remove it", err)+ }+ items = append(items, it)+ }+ return items, nil+}++func addLocal(ctx context.Context, opts LocalOptions, it Item, st state) (Record, error) {+ t := it.Target+ entry := t.localEntry(opts.Command)+ rec := Record{Harness: t.Name, Path: it.Path, ServerName: LocalServerName, Command: opts.Command, Method: "file"}+ if it.cliPath != "" {+ rec.Method = t.cli + "-cli"+ backup, err := st.file.backup(timeNow())+ if err != nil {+ return Record{}, fmt.Errorf("could not back up %s: %w", it.Path, err)+ }+ rec.Backup = backup+ args := []string{"mcp", "add", "--scope", "user", LocalServerName, "--", opts.Command}+ for _, a := range localArgs() {+ args = append(args, fmt.Sprint(a))+ }+ if out, err := opts.connectOptions().run(ctx, it.cliPath, args...); err != nil {+ return Record{}, fmt.Errorf("`%s mcp add` failed: %v: %s", t.cli, err, strings.TrimSpace(string(out)))+ }+ after, err := inspectNamed(t, it.Path, LocalServerName)+ if err != nil {+ return Record{}, err+ }+ if !after.exists || !sameLocalCommand(t, after.entry, opts.Command) {+ return Record{}, fmt.Errorf("`%s mcp add` ran, but %s does not hold the expected %s entry", t.cli, it.Path, LocalServerName)+ }+ return rec, nil+ }++ cf := st.file+ var updated string+ if t.format == formatTOML {+ eol := tomlLineEnding(cf.text)+ updated = appendTOMLBlock(cf.text, tomlBlock(t.container[0], LocalServerName, entry, eol), eol)+ } else {+ updated = cf.text+ if strings.TrimSpace(updated) == "" && len(t.skeleton) > 0 {+ updated = renderJSONDocument(t.skeleton, detectJSONStyle(cf.text))+ }+ var err error+ if updated, rec.CreatedParents, err = insertJSONMember(updated, t.container, LocalServerName, entry); err != nil {+ return Record{}, fmt.Errorf("could not edit %s: %w", it.Path, err)+ }+ }+ b, a, err := parseBoth(t, cf.text, updated)+ if err != nil {+ return Record{}, fmt.Errorf("%s: %w; the file was left unchanged", it.Path, err)+ }+ if strings.TrimSpace(cf.text) == "" {+ for _, f := range t.skeleton {+ b[f.Key] = normalizeJSON(f.Value)+ }+ }+ setPath(b, t.container, LocalServerName, normalizeJSON(entry))+ if !reflect.DeepEqual(normalizeValue(b), normalizeValue(a)) {+ return Record{}, fmt.Errorf("%s: Beacon's edit would have changed more than its own %s entry; the file was left unchanged", it.Path, LocalServerName)+ }+ backup, err := cf.backup(timeNow())+ if err != nil {+ return Record{}, fmt.Errorf("could not back up %s: %w", it.Path, err)+ }+ rec.Backup, rec.CreatedFile = backup, !cf.exists+ if err := cf.write(updated); err != nil {+ return Record{}, fmt.Errorf("could not write %s: %w", it.Path, err)+ }+ rec.AfterSHA256 = digest(updated)+ return rec, nil+}++// sameLocalCommand reports whether an entry runs command with the local server's arguments,+// whatever else the harness added to it (Claude Code writes an empty "env").+func sameLocalCommand(t Target, entry map[string]any, command string) bool {+ want, _ := normalizeJSON(t.localEntry(command)).(map[string]any)+ for _, key := range []string{"command", "args"} {+ if !reflect.DeepEqual(normalizeValue(entry[key]), normalizeValue(want[key])) {+ return false+ }+ }+ return true+}++// UninstallLocal removes the local entries Beacon recorded, and only while each still runs the+// command Beacon wrote: an entry someone has since changed is theirs.+func UninstallLocal(ctx context.Context, opts LocalOptions) ([]Item, error) {+ manifestFile := filepath.Join(opts.Home, LocalManifestPath)+ m, err := loadManifestAt(manifestFile)+ if err != nil {+ return nil, err+ }+ copts := opts.connectOptions()+ var items []Item+ for _, rec := range append([]Record(nil), m.Records...) {+ t, ok := Lookup(rec.Harness)+ if !ok || !t.LocalSupported() {+ continue+ }+ it := Item{Target: t, Path: rec.Path, Method: rec.Method}+ it.Action, it.Detail, it.Err = removeLocal(ctx, copts, t, rec)+ if it.Err == nil {+ m.drop(rec.Harness, rec.Path)+ if err := m.saveAt(manifestFile); err != nil {+ it.Err = err+ }+ }+ items = append(items, it)+ }+ return items, nil+}++func removeLocal(ctx context.Context, opts Options, t Target, rec Record) (Action, string, error) {+ st, err := inspectNamed(t, rec.Path, LocalServerName)+ if err != nil {+ return ActionSkip, "", err+ }+ if !st.exists {+ return ActionAbsent, "the entry is already gone", nil+ }+ if !sameLocalCommand(t, st.entry, rec.Command) {+ return ActionAbsent, "the " + LocalServerName + " entry was changed after Beacon wrote it; left alone", nil+ }+ if rec.Method == t.cli+"-cli" && t.cli != "" {+ if cliPath, err := opts.lookPath(t.cli); err == nil {+ if out, err := opts.run(ctx, cliPath, "mcp", "remove", LocalServerName, "--scope", "user"); err != nil {+ return ActionSkip, "", fmt.Errorf("`%s mcp remove` failed: %v: %s", t.cli, err, strings.TrimSpace(string(out)))+ }+ after, err := inspectNamed(t, rec.Path, LocalServerName)+ if err != nil {+ return ActionSkip, "", err+ }+ if after.exists {+ return ActionSkip, "", fmt.Errorf("`%s mcp remove` ran, but %s still holds %s", t.cli, rec.Path, LocalServerName)+ }+ return ActionRemove, "removed with `" + t.cli + " mcp remove`", nil+ }+ }+ cf := st.file+ var updated string+ if t.format == formatTOML {+ stripped, found := stripTOMLTable(cf.text, t.container[0], LocalServerName)+ if !found {+ return ActionSkip, "", errors.New("the " + LocalServerName + " entry is not a [" + t.container[0] + "." + LocalServerName + "] table; remove it by hand")+ }+ updated = endTOMLWithNewline(stripped, tomlLineEnding(cf.text))+ } else {+ if updated, err = removeJSONMember(cf.text, t.container, LocalServerName, rec.CreatedParents); err != nil {+ return ActionSkip, "", fmt.Errorf("could not edit %s: %w", rec.Path, err)+ }+ }+ b, a, err := parseBoth(t, cf.text, updated)+ if err != nil {+ return ActionSkip, "", err+ }+ deletePath(b, t.container, LocalServerName, rec.CreatedParents)+ if t.format == formatTOML {+ dropEmptyTable(b, t.container[0])+ dropEmptyTable(a, t.container[0])+ }+ if !reflect.DeepEqual(normalizeValue(b), normalizeValue(a)) {+ return ActionSkip, "", fmt.Errorf("%s: Beacon's edit would have changed more than its own %s entry; the file was left unchanged", rec.Path, LocalServerName)+ }+ if rec.CreatedFile && onlySkeleton(t, updated) {+ if err := cf.remove(); err != nil {+ return ActionSkip, "", err+ }+ return ActionRemove, "removed the file Beacon created", nil+ }+ if _, err := cf.backup(timeNow()); err != nil {+ return ActionSkip, "", fmt.Errorf("could not back up %s: %w", rec.Path, err)+ }+ if err := cf.write(updated); err != nil {+ return ActionSkip, "", err+ }+ return ActionRemove, "removed Beacon's entry", nil+}diff --git a/cli/beacon/internal/mcpconnect/local_test.go b/cli/beacon/internal/mcpconnect/local_test.gonew file mode 100644index 00000000..3e6516fd--- /dev/null+++ b/cli/beacon/internal/mcpconnect/local_test.go@@ -0,0 +1,222 @@+package mcpconnect++import (+ "context"+ "errors"+ "os"+ "path/filepath"+ "strings"+ "testing"+)++const testBeacon = "/opt/beacon/bin/beacon"++func localFileOptions(home string) LocalOptions {+ return LocalOptions{+ Home: home, Command: testBeacon,+ LookPath: func(string) (string, error) { return "", errors.New("not on PATH") },+ Run: func(context.Context, string, ...string) ([]byte, error) {+ return nil, errors.New("no CLI may run in file-writer tests")+ },+ }+}++func localTargets() []Target {+ var out []Target+ for _, t := range Targets() {+ if t.LocalSupported() {+ out = append(out, t)+ }+ }+ return out+}++func TestLocalSupportedOnEveryAutomaticTarget(t *testing.T) {+ for _, target := range Targets() {+ if target.Automatic != target.LocalSupported() {+ t.Errorf("%s: automatic=%t local=%t", target.Name, target.Automatic, target.LocalSupported())+ }+ }+}++func TestInstallLocalCreatesEachConfigAndUninstallRemovesIt(t *testing.T) {+ home := isolate(t)+ opts := localFileOptions(home)+ items, err := InstallLocal(context.Background(), opts, localTargets())+ if err != nil {+ t.Fatal(err)+ }+ if len(items) != len(localTargets()) {+ t.Fatalf("items = %d, want %d", len(items), len(localTargets()))+ }+ for _, it := range items {+ if it.Err != nil || it.Action != ActionAdd {+ t.Fatalf("%s: action=%s err=%v", it.Target.Name, it.Action, it.Err)+ }+ st, err := inspectNamed(it.Target, it.Path, LocalServerName)+ if err != nil {+ t.Fatal(err)+ }+ if !st.exists || !sameLocalCommand(it.Target, st.entry, testBeacon) {+ t.Fatalf("%s: entry = %#v", it.Target.Name, st.entry)+ }+ // Beacon Cloud MCP's entry is a different name and stays unconfigured.+ if cloud, _ := inspect(it.Target, it.Path); cloud.exists {+ t.Fatalf("%s: local install wrote %s", it.Target.Name, ServerName)+ }+ }+ codex, err := os.ReadFile(filepath.Join(home, ".codex", "config.toml"))+ if err != nil {+ t.Fatal(err)+ }+ if want := "[mcp_servers.beacon]\ncommand = \"/opt/beacon/bin/beacon\"\nargs = [\"mcp\", \"serve\"]\n"; string(codex) != want {+ t.Fatalf("codex config:\n%s\nwant:\n%s", codex, want)+ }++ // A second run finds every entry in place and writes nothing.+ again, err := InstallLocal(context.Background(), opts, localTargets())+ if err != nil {+ t.Fatal(err)+ }+ for _, it := range again {+ if it.Action != ActionPresent {+ t.Fatalf("%s: second run action = %s", it.Target.Name, it.Action)+ }+ }++ removed, err := UninstallLocal(context.Background(), opts)+ if err != nil {+ t.Fatal(err)+ }+ if len(removed) != len(localTargets()) {+ t.Fatalf("removed %d items, want %d", len(removed), len(localTargets()))+ }+ for _, it := range removed {+ if it.Err != nil || it.Action != ActionRemove {+ t.Fatalf("%s: action=%s err=%v", it.Target.Name, it.Action, it.Err)+ }+ if _, err := os.Stat(it.Path); !errors.Is(err, os.ErrNotExist) {+ t.Fatalf("%s: %s should be gone, Beacon created it (err=%v)", it.Target.Name, it.Path, err)+ }+ }+ if _, err := os.Stat(filepath.Join(home, LocalManifestPath)); !errors.Is(err, os.ErrNotExist) {+ t.Fatalf("empty local manifest should be removed (err=%v)", err)+ }+}++func TestInstallLocalKeepsExistingContentAndEntries(t *testing.T) {+ home := isolate(t)+ cursor := mustTarget(t, "cursor")+ path := targetPath(t, cursor, home)+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {+ t.Fatal(err)+ }+ existing := `{+ // my servers+ "mcpServers": {+ "other": {"command": "other"}+ }+}+`+ if err := os.WriteFile(path, []byte(existing), 0o600); err != nil {+ t.Fatal(err)+ }+ items, err := InstallLocal(context.Background(), localFileOptions(home), []Target{cursor})+ if err != nil || len(items) != 1 || items[0].Err != nil {+ t.Fatalf("items=%+v err=%v", items, err)+ }+ data, _ := os.ReadFile(path)+ if !strings.Contains(string(data), "// my servers") || !strings.Contains(string(data), `"other": {"command": "other"}`) {+ t.Fatalf("existing content not preserved:\n%s", data)+ }+ if _, err := UninstallLocal(context.Background(), localFileOptions(home)); err != nil {+ t.Fatal(err)+ }+ after, _ := os.ReadFile(path)+ if string(after) != existing {+ t.Fatalf("uninstall did not restore the original content:\n%s", after)+ }+}++func TestInstallLocalNeverReplacesAnEntryNamedBeacon(t *testing.T) {+ home := isolate(t)+ gemini := mustTarget(t, "gemini_cli")+ path := targetPath(t, gemini, home)+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {+ t.Fatal(err)+ }+ existing := `{"mcpServers": {"beacon": {"command": "/somewhere/else/beacon", "args": ["mcp", "serve"]}}}`+ if err := os.WriteFile(path, []byte(existing), 0o600); err != nil {+ t.Fatal(err)+ }+ items, err := InstallLocal(context.Background(), localFileOptions(home), []Target{gemini})+ if err != nil {+ t.Fatal(err)+ }+ if items[0].Action != ActionPresent {+ t.Fatalf("action = %s, want present", items[0].Action)+ }+ if data, _ := os.ReadFile(path); string(data) != existing {+ t.Fatalf("existing entry was changed:\n%s", data)+ }+ // Nothing was recorded, so uninstall leaves it alone too.+ removed, err := UninstallLocal(context.Background(), localFileOptions(home))+ if err != nil || len(removed) != 0 {+ t.Fatalf("removed=%+v err=%v", removed, err)+ }+}++func TestUninstallLocalLeavesAnEntryChangedAfterInstall(t *testing.T) {+ home := isolate(t)+ gemini := mustTarget(t, "gemini_cli")+ if _, err := InstallLocal(context.Background(), localFileOptions(home), []Target{gemini}); err != nil {+ t.Fatal(err)+ }+ path := targetPath(t, gemini, home)+ changed := `{"mcpServers": {"beacon": {"command": "/mine/beacon", "args": ["mcp", "serve"]}}}`+ if err := os.WriteFile(path, []byte(changed), 0o600); err != nil {+ t.Fatal(err)+ }+ removed, err := UninstallLocal(context.Background(), localFileOptions(home))+ if err != nil || len(removed) != 1 || removed[0].Action != ActionAbsent {+ t.Fatalf("removed=%+v err=%v", removed, err)+ }+ if data, _ := os.ReadFile(path); string(data) != changed {+ t.Fatalf("changed entry was touched:\n%s", data)+ }+}++func TestInstallLocalUsesClaudeCLIWhenPresent(t *testing.T) {+ home := isolate(t)+ claude := mustTarget(t, "claude_code")+ path := targetPath(t, claude, home)+ var calls [][]string+ opts := localFileOptions(home)+ opts.LookPath = func(name string) (string, error) { return "/usr/bin/" + name, nil }+ opts.Run = func(_ context.Context, name string, args ...string) ([]byte, error) {+ calls = append(calls, append([]string{name}, args...))+ switch args[1] {+ case "add":+ // What `claude mcp add --scope user beacon -- <cmd> mcp serve` writes.+ return nil, os.WriteFile(path, []byte(`{"mcpServers":{"beacon":{"type":"stdio","command":"`+testBeacon+`","args":["mcp","serve"],"env":{}}}}`), 0o600)+ case "remove":+ return nil, os.WriteFile(path, []byte(`{"mcpServers":{}}`), 0o600)+ }+ return nil, errors.New("unexpected")+ }+ items, err := InstallLocal(context.Background(), opts, []Target{claude})+ if err != nil || items[0].Err != nil || items[0].Method != "claude CLI" {+ t.Fatalf("items=%+v err=%v", items, err)+ }+ want := "/usr/bin/claude mcp add --scope user beacon -- " + testBeacon + " mcp serve"+ if got := strings.Join(calls[0], " "); got != want {+ t.Fatalf("call = %q, want %q", got, want)+ }+ removed, err := UninstallLocal(context.Background(), opts)+ if err != nil || len(removed) != 1 || removed[0].Action != ActionRemove || removed[0].Err != nil {+ t.Fatalf("removed=%+v err=%v", removed, err)+ }+ if got := strings.Join(calls[1], " "); got != "/usr/bin/claude mcp remove beacon --scope user" {+ t.Fatalf("remove call = %q", got)+ }+}diff --git a/cli/beacon/internal/mcpconnect/manifest.go b/cli/beacon/internal/mcpconnect/manifest.goindex 1d00a9f4..ca605af7 100644--- a/cli/beacon/internal/mcpconnect/manifest.go+++ b/cli/beacon/internal/mcpconnect/manifest.go@@ -26,13 +26,15 @@ const manifestSchemaVersion = 1// Record is one entry Beacon wrote into one harness config.type Record struct {- Harness string `json:"harness"`- Path string `json:"path"`- ServerName string `json:"server_name"`- URL string `json:"url"`- Auth AuthMode `json:"auth"`- TokenEnv string `json:"token_env,omitempty"`- Method string `json:"method"`+ Harness string `json:"harness"`+ Path string `json:"path"`+ ServerName string `json:"server_name"`+ URL string `json:"url"`+ // Command is the executable a local stdio entry runs; empty for Beacon Cloud entries.+ Command string `json:"command,omitempty"`+ Auth AuthMode `json:"auth"`+ TokenEnv string `json:"token_env,omitempty"`+ Method string `json:"method"`// CreatedFile is set when the config did not exist before connect, so disconnect can remove a// file that holds nothing else.CreatedFile bool `json:"created_file,omitempty"`@@ -58,7 +60,11 @@ func manifestPath(home string) string {}func loadManifest(home string) (*manifest, error) {- data, err := os.ReadFile(manifestPath(home))+ return loadManifestAt(manifestPath(home))+}++func loadManifestAt(path string) (*manifest, error) {+ data, err := os.ReadFile(path)if errors.Is(err, os.ErrNotExist) {return &manifest{SchemaVersion: manifestSchemaVersion}, nil}@@ -67,10 +73,10 @@ func loadManifest(home string) (*manifest, error) {}var m manifestif err := json.Unmarshal(data, &m); err != nil {- return nil, fmt.Errorf("%s is not valid JSON: %w", manifestPath(home), err)+ return nil, fmt.Errorf("%s is not valid JSON: %w", path, err)}if m.SchemaVersion != manifestSchemaVersion {- return nil, fmt.Errorf("%s has schema version %d; this Beacon understands %d", manifestPath(home), m.SchemaVersion, manifestSchemaVersion)+ return nil, fmt.Errorf("%s has schema version %d; this Beacon understands %d", path, m.SchemaVersion, manifestSchemaVersion)}return &m, nil}@@ -125,7 +131,10 @@ func (m *manifest) drop(harness, path string) {// save writes the manifest 0600 in a 0700 directory, like the rest of ~/.beacon. An empty// manifest is removed rather than left behind.func (m *manifest) save(home string) error {- path := manifestPath(home)+ return m.saveAt(manifestPath(home))+}++func (m *manifest) saveAt(path string) error {if len(m.Records) == 0 {err := os.Remove(path)if errors.Is(err, os.ErrNotExist) {diff --git a/cli/beacon/internal/mcpconnect/targets.go b/cli/beacon/internal/mcpconnect/targets.goindex d4bbda5c..751f9bff 100644--- a/cli/beacon/internal/mcpconnect/targets.go+++ b/cli/beacon/internal/mcpconnect/targets.go@@ -61,6 +61,8 @@ type Target struct {path func(home string) (string, error)container []string // path to the object holding servers, e.g. ["mcpServers"]entry func(url, tokenEnv string) ordered+ // localEntry is the entry for the local stdio server `beacon mcp serve`, run by command.+ localEntry func(command string) ordered// skeleton is the content of a config Beacon creates, besides the server entry.skeleton ordered// cli names a CLI whose own `mcp add`/`mcp remove` Beacon prefers when it is on PATH.@@ -89,6 +91,9 @@ func Targets() []Target {}return e},+ localEntry: func(command string) ordered {+ return ordered{{"type", "stdio"}, {"command", command}, {"args", localArgs()}}+ },oauthNext: "In Claude Code, run /mcp, choose " + ServerName + ", and sign in.",tokenNext: "Set %s in the environment Claude Code starts from.",},@@ -102,6 +107,9 @@ func Targets() []Target {}return e},+ localEntry: func(command string) ordered {+ return ordered{{"command", command}, {"args", localArgs()}}+ },oauthNext: "Run `codex mcp login " + ServerName + "`.",tokenNext: "Set %s in the environment Codex starts from.",},@@ -115,6 +123,9 @@ func Targets() []Target {}return e},+ localEntry: func(command string) ordered {+ return ordered{{"command", command}, {"args", localArgs()}}+ },oauthNext: "In Cursor Settings → MCP, find " + ServerName + " (marked \"Needs login\") and sign in.",tokenNext: "Set %s in the environment Cursor starts from.",},@@ -129,6 +140,9 @@ func Targets() []Target {}return e},+ localEntry: func(command string) ordered {+ return ordered{{"type", "stdio"}, {"command", command}, {"args", localArgs()}}+ },oauthNext: "In VS Code, run \"MCP: List Servers\", start " + ServerName + ", and sign in.",tokenNext: "VS Code asks for the token the first time " + ServerName + " starts and keeps it in its secret storage; it does not read %s.",},@@ -142,6 +156,9 @@ func Targets() []Target {}return e},+ localEntry: func(command string) ordered {+ return ordered{{"command", command}, {"args", localArgs()}}+ },oauthNext: "In Gemini CLI, run /mcp auth " + ServerName + ". Gemini CLI loads MCP servers only in trusted folders.",tokenNext: "Set %s in the environment Gemini CLI starts from. Gemini CLI loads MCP servers only in trusted folders.",},@@ -156,6 +173,9 @@ func Targets() []Target {}return e},+ localEntry: func(command string) ordered {+ return ordered{{"type", "local"}, {"command", append([]any{command}, localArgs()...)}, {"enabled", true}}+ },oauthNext: "Run `opencode mcp auth " + ServerName + "`.",tokenNext: "Set %s in the environment OpenCode starts from.",},diff --git a/cli/beacon/internal/mcpconnect/tomledit.go b/cli/beacon/internal/mcpconnect/tomledit.goindex fd996dde..e9b5b5c1 100644--- a/cli/beacon/internal/mcpconnect/tomledit.go+++ b/cli/beacon/internal/mcpconnect/tomledit.go@@ -45,11 +45,23 @@ func tomlBlock(table string, name string, fields []field, eol string) string {var b strings.Builderb.WriteString("[" + table + "." + tomlKey(name) + "]" + eol)for _, f := range fields {- b.WriteString(f.Key + " = " + tomlString(fmt.Sprint(f.Value)) + eol)+ b.WriteString(f.Key + " = " + tomlValue(f.Value) + eol)}return b.String()}+// tomlValue renders a string, or an array of strings, the way `codex mcp add` writes them.+func tomlValue(value any) string {+ if list, ok := value.([]any); ok {+ parts := make([]string, len(list))+ for i, v := range list {+ parts[i] = tomlString(fmt.Sprint(v))+ }+ return "[" + strings.Join(parts, ", ") + "]"+ }+ return tomlString(fmt.Sprint(value))+}+var bareTOMLKey = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)func tomlKey(name string) string {diff --git a/cli/beacon/internal/onboarding/profile.go b/cli/beacon/internal/onboarding/profile.goindex 4568f6ed..46815a25 100644--- a/cli/beacon/internal/onboarding/profile.go+++ b/cli/beacon/internal/onboarding/profile.go@@ -78,6 +78,24 @@ type Onboarding struct {Destination string `json:"destination,omitempty"`// PrivacyMode applies only to Beacon Cloud forwarding.PrivacyMode string `json:"privacy_mode,omitempty"`+ // MCPServer and AgentSkills record the agent tools answer: "installed" when the person+ // kept the tool selected, "declined" when they turned it off, empty when never asked.+ MCPServer string `json:"mcp_server,omitempty"`+ AgentSkills string `json:"agent_skills,omitempty"`+}++// Answers to the agent tools question.+const (+ AgentToolInstalled = "installed"+ AgentToolDeclined = "declined"+)++// AgentToolAnswer is how a kept or turned-off agent tool is recorded.+func AgentToolAnswer(kept bool) string {+ if kept {+ return AgentToolInstalled+ }+ return AgentToolDeclined}// Answers to the telemetry destination question.diff --git a/cli/beacon/internal/onboarding/wizard.go b/cli/beacon/internal/onboarding/wizard.goindex 79e20b88..ead1f5b3 100644--- a/cli/beacon/internal/onboarding/wizard.go+++ b/cli/beacon/internal/onboarding/wizard.go@@ -60,6 +60,9 @@ type WizardOptions struct {DestinationOnly boolPresetDestination stringPresetPrivacyMode string+ // OfferAgentTools adds the agent tools screen before confirm, whichever destination is+ // chosen. Both tools start selected: turning one off is the person's choice to make.+ OfferAgentTools bool// SignIn signs in in place. When nil the wizard keeps its original contract:// it exits with NeedLogin and the caller signs in and runs it again.@@ -89,6 +92,11 @@ type WizardResult struct {// a sign-in failure. Destination is then always local: managed forwarding has// nothing to authorize it.WithoutAccount bool++ // InstallMCP and InstallSkills are the agent tools the person kept selected. Both are+ // false when the screen was not offered.+ InstallMCP bool+ InstallSkills bool}type wizardScreen int@@ -101,9 +109,17 @@ const (destinationScreenmanagedDisclosureScreenprivacyScreen+ agentToolsScreenconfirmScreen)+// Rows of the agent tools screen.+const (+ agentToolMCP = iota+ agentToolSkills+ agentToolCount+)+type wizardModel struct {options WizardOptionsresult WizardResult@@ -189,7 +205,12 @@ var (func newWizardModel(options WizardOptions) wizardModel {screen := welcomeScreen- result := WizardResult{Destination: options.PresetDestination, PrivacyMode: options.PresetPrivacyMode}+ result := WizardResult{+ Destination: options.PresetDestination,+ PrivacyMode: options.PresetPrivacyMode,+ InstallMCP: options.OfferAgentTools,+ InstallSkills: options.OfferAgentTools,+ }needSignIn := falseif options.DestinationOnly {switch {@@ -198,7 +219,7 @@ func newWizardModel(options WizardOptions) wizardModel {case options.PresetDestination == DestinationAsymptote:screen = managedDisclosureScreencase options.PresetDestination != "":- screen = confirmScreen+ screen = beforeConfirm(options)default:screen = destinationScreen}@@ -292,6 +313,10 @@ func (m wizardModel) Update(message tea.Msg) (tea.Model, tea.Cmd) {if n := m.choiceCount(); m.isPicker() && n > 0 {m.selected = (m.selected + 1) % n}+ case " ", "space", "x":+ if m.screen == agentToolsScreen {+ m.toggleAgentTool()+ }case "enter":return m.advance()}@@ -300,7 +325,16 @@ func (m wizardModel) Update(message tea.Msg) (tea.Model, tea.Cmd) {}func (m wizardModel) isPicker() bool {- return m.screen == destinationScreen || m.screen == privacyScreen || m.screen == signInFailedScreen+ return m.screen == destinationScreen || m.screen == privacyScreen || m.screen == signInFailedScreen || m.screen == agentToolsScreen+}++func (m *wizardModel) toggleAgentTool() {+ switch m.selected {+ case agentToolMCP:+ m.result.InstallMCP = !m.result.InstallMCP+ case agentToolSkills:+ m.result.InstallSkills = !m.result.InstallSkills+ }}func (m *wizardModel) stopSignIn() {@@ -380,12 +414,26 @@ func (m wizardModel) afterSignIn() wizardScreen {case m.options.PresetDestination == DestinationAsymptote:return managedDisclosureScreencase m.options.PresetDestination != "":- return confirmScreen+ return beforeConfirm(m.options)default:return destinationScreen}}+// beforeConfirm is the screen that precedes confirm: the agent tools when they are offered.+func beforeConfirm(options WizardOptions) wizardScreen {+ if options.OfferAgentTools {+ return agentToolsScreen+ }+ return confirmScreen+}++// toConfirm moves to the screen before confirm, with the cursor on its first row.+func (m *wizardModel) toConfirm() {+ m.selected = 0+ m.screen = beforeConfirm(m.options)+}+func (m wizardModel) advance() (tea.Model, tea.Cmd) {switch m.screen {case welcomeScreen:@@ -395,7 +443,7 @@ func (m wizardModel) advance() (tea.Model, tea.Cmd) {case m.options.PresetDestination == DestinationAsymptote:m.screen = managedDisclosureScreencase m.options.PresetDestination != "":- m.screen = confirmScreen+ m.toConfirm()default:m.screen = destinationScreen}@@ -417,13 +465,15 @@ func (m wizardModel) advance() (tea.Model, tea.Cmd) {if m.result.Destination == DestinationAsymptote {m.screen = managedDisclosureScreen} else {- m.screen = confirmScreen+ m.toConfirm()}case managedDisclosureScreen:m.selected = privacyIndex(m.result.PrivacyMode)m.screen = privacyScreencase privacyScreen:m.result.PrivacyMode = managedprivacy.Modes[m.selected]+ m.toConfirm()+ case agentToolsScreen:m.screen = confirmScreencase confirmScreen:m.result.Completed = true@@ -445,6 +495,8 @@ func (m wizardModel) choiceCount() int {return len(managedprivacy.Modes)case signInFailedScreen:return len(m.recoveryChoices())+ case agentToolsScreen:+ return agentToolCountdefault:return len(m.destinations())}@@ -517,7 +569,7 @@ func (m wizardModel) recover() (tea.Model, tea.Cmd) {// would show an account on the confirm screen next to "not signed in".m.options.Email = ""m.options.SignedIn = false- m.screen = confirmScreen+ m.toConfirm()return m, nildefault:return m, tea.Quit@@ -623,6 +675,23 @@ func (m wizardModel) View() string {rows = append(rows, line, choiceDetail(detail, contentWidth))}body = strings.Join(rows, "\n")+ case agentToolsScreen:+ title = "Set up your agents"+ body = "Give your agents their own history. Both run on this machine and send nothing anywhere.\n\n"+ var rows []string+ for index := 0; index < agentToolCount; index++ {+ label, detail := agentToolCopy(index)+ box := "[ ] "+ if m.agentToolOn(index) {+ box = "[x] "+ }+ line := " " + box + label+ if index == m.selected {+ line = wizardChoice.Render(" ❯ " + box + label)+ }+ rows = append(rows, line, choiceDetail(detail, contentWidth))+ }+ body += strings.Join(rows, "\n")case confirmScreen:title = "Ready to set up Beacon"label, _ := destinationCopy(m.result.Destination)@@ -639,7 +708,9 @@ func (m wizardModel) View() string {if m.result.WithoutAccount {body += " You are not signed in; connect later with `beacon endpoint connect`."}-+ }+ if m.options.OfferAgentTools {+ body += "\n\nAgent tools: " + m.agentToolsSummary()}}@@ -655,6 +726,41 @@ func (m wizardModel) View() string {return lipgloss.NewStyle().Padding(1, 3).Render(card)}+func (m wizardModel) agentToolOn(index int) bool {+ switch index {+ case agentToolMCP:+ return m.result.InstallMCP+ case agentToolSkills:+ return m.result.InstallSkills+ }+ return false+}++func (m wizardModel) agentToolsSummary() string {+ var on []string+ if m.result.InstallMCP {+ on = append(on, "Beacon MCP server")+ }+ if m.result.InstallSkills {+ on = append(on, "Beacon agent skills")+ }+ if len(on) == 0 {+ return "none"+ }+ return strings.Join(on, ", ")+}++func agentToolCopy(index int) (string, string) {+ if index == agentToolMCP {+ return "Beacon MCP server",+ "Registers `beacon mcp serve` with Claude Code, Codex, Cursor, VS Code, Gemini CLI and " ++ "OpenCode, so agents can search this machine's sessions."+ }+ return "Beacon agent skills",+ "Installs the Beacon skills for every project (~/.agents/skills, and ~/.claude/skills for " ++ "Claude Code): recall lessons from past sessions, distill new ones, and build lenses."+}+func destinationCopy(destination string) (string, string) {switch destination {case DestinationAsymptote:@@ -751,6 +857,8 @@ func (m wizardModel) wizardHint(screen wizardScreen) string {return "↑/↓ choose · enter continue · esc cancel"case privacyScreen:return "↑/↓ choose · enter continue · esc cancel"+ case agentToolsScreen:+ return "↑/↓ move · space turn on/off · enter continue · esc cancel"case signInScreen:if m.options.NoBrowser {return "enter show the sign-in URL · esc cancel"diff --git a/cli/beacon/internal/onboarding/wizard_test.go b/cli/beacon/internal/onboarding/wizard_test.goindex 163e5867..53b0f31d 100644--- a/cli/beacon/internal/onboarding/wizard_test.go+++ b/cli/beacon/internal/onboarding/wizard_test.go@@ -661,3 +661,98 @@ func TestSignInScreenHonorsNoBrowser(t *testing.T) {}}}++func TestAgentToolsAreOfferedForEitherDestinationAndStartSelected(t *testing.T) {+ for _, destination := range []string{DestinationLocal, DestinationAsymptote} {+ model := newWizardModel(WizardOptions{+ SignedIn: true,+ Email: "[email protected]",+ OfferManaged: true,+ OfferAgentTools: true,+ })+ model.width, model.height = 100, 40+ model, _ = advanceWizard(t, model, "enter")+ if destination == DestinationLocal {+ model, _ = advanceWizard(t, model, "j")+ }+ model, _ = advanceWizard(t, model, "enter")+ if destination == DestinationAsymptote {+ model, _ = advanceWizard(t, model, "enter") // disclosure+ model, _ = advanceWizard(t, model, "enter") // privacy+ }+ if model.screen != agentToolsScreen {+ t.Fatalf("%s: screen = %v, want agent tools", destination, model.screen)+ }+ if !model.result.InstallMCP || !model.result.InstallSkills {+ t.Fatalf("%s: agent tools should start selected: %#v", destination, model.result)+ }+ view := model.View()+ for _, want := range []string{"[x] Beacon MCP server", "[x] Beacon agent skills", "space"} {+ if !strings.Contains(view, want) {+ t.Fatalf("%s: agent tools screen missing %q:\n%s", destination, want, view)+ }+ }+ model, _ = advanceWizard(t, model, "enter")+ if model.screen != confirmScreen {+ t.Fatalf("%s: screen = %v, want confirm", destination, model.screen)+ }+ if view := model.View(); !strings.Contains(view, "Agent tools: Beacon MCP server, Beacon agent skills") {+ t.Fatalf("%s: confirm screen should list the agent tools:\n%s", destination, view)+ }+ model, _ = advanceWizard(t, model, "enter")+ if !model.result.Completed || model.result.Destination != destination {+ t.Fatalf("%s: result = %#v", destination, model.result)+ }+ }+}++func TestAgentToolsCanBeTurnedOff(t *testing.T) {+ model := newWizardModel(WizardOptions{+ SignedIn: true,+ OfferManaged: true,+ OfferAgentTools: true,+ DestinationOnly: true,+ PresetDestination: DestinationLocal,+ })+ model.width, model.height = 100, 40+ if model.screen != agentToolsScreen {+ t.Fatalf("screen = %v, want agent tools", model.screen)+ }+ model, _ = advanceWizard(t, model, " ")+ if model.result.InstallMCP || !model.result.InstallSkills {+ t.Fatalf("space should turn off the MCP server only: %#v", model.result)+ }+ if view := model.View(); !strings.Contains(view, "[ ] Beacon MCP server") {+ t.Fatalf("turned-off tool should render unchecked:\n%s", view)+ }+ model, _ = advanceWizard(t, model, "j")+ model, _ = advanceWizard(t, model, " ")+ model, _ = advanceWizard(t, model, "enter")+ if view := model.View(); !strings.Contains(view, "Agent tools: none") {+ t.Fatalf("confirm should say no agent tools:\n%s", view)+ }+ model, _ = advanceWizard(t, model, "enter")+ if !model.result.Completed || model.result.InstallMCP || model.result.InstallSkills {+ t.Fatalf("result = %#v", model.result)+ }+}++func TestFinishingWithoutAnAccountStillOffersAgentTools(t *testing.T) {+ model := newWizardModel(WizardOptions{OfferManaged: true, OfferAgentTools: true, NoDisplay: errors.New("no display")})+ model.width, model.height = 100, 40+ model, _ = advanceWizard(t, model, "enter")+ if model.screen != signInFailedScreen {+ t.Fatalf("screen = %v, want recovery", model.screen)+ }+ model, _ = advanceWizard(t, model, "enter") // finish without an account+ if model.screen != agentToolsScreen || !model.result.InstallMCP || !model.result.InstallSkills {+ t.Fatalf("screen = %v result = %#v", model.screen, model.result)+ }+}++func TestAgentToolsScreenIsSkippedWhenNotOffered(t *testing.T) {+ model := newWizardModel(WizardOptions{SignedIn: true, OfferManaged: true, DestinationOnly: true, PresetDestination: DestinationLocal})+ if model.screen != confirmScreen || model.result.InstallMCP || model.result.InstallSkills {+ t.Fatalf("screen = %v result = %#v", model.screen, model.result)+ }+}diff --git a/docs/cli/endpoint-onboarding.mdx b/docs/cli/endpoint-onboarding.mdxindex 2af11cd6..a68c97e7 100644--- a/docs/cli/endpoint-onboarding.mdx+++ b/docs/cli/endpoint-onboarding.mdx@@ -26,7 +26,9 @@ The first interactive `beacon endpoint install` opens a full-screen terminal wizusage coming soon. Local is a dashboard for this machine's telemetry,kept for as long as the logs are on disk, with nothing leaving the machine.3. For Beacon Cloud, choose **Standard** or **Metadata only** forwarding.-4. Review the destination and privacy mode, then confirm installation.+4. Choose the agent tools to set up. Both are selected; press <kbd>space</kbd> to turn+ one off.+5. Review the destination, privacy mode and agent tools, then confirm installation.Move between choices with the arrow keys, continue with <kbd>enter</kbd>, and cancelwith <kbd>esc</kbd>.@@ -90,6 +92,35 @@ treating the machine as settled. Verify forwarding with `beacon endpoint status--json`. The onboarding record itself is written only after the install succeeds, soa failed install leaves nothing behind and asks again next time.+## Agent tools++Whichever destination you choose, the wizard then offers two agent tools. Both are+selected by default, so setting them up is opt-out:++- **Beacon MCP server** registers the local server, [`beacon mcp serve`](/cli/mcp-serve),+ as `beacon` in the user-level config of every detected harness Beacon can write:+ Claude Code, Codex CLI, Cursor, VS Code, Gemini CLI and OpenCode. Agents can then+ search this machine's sessions and approved memory. See+ [`beacon mcp install`](/cli/mcp-install).+- **Beacon agent skills** installs the [Beacon Skills](/concepts/beacon-skills) for+ every project: into `~/.agents/skills`, and into `~/.claude/skills` when Claude Code+ is set up. See [`beacon skills`](/cli/skills).++Both read local data only and send nothing anywhere. They are set up after the local+install succeeds, alongside the runtime hooks; a failure is a warning that names the+command to retry, never a failed install. An existing `beacon` MCP entry, or a skill+directory of the same name that Beacon did not write, is left as it is.++Turning a tool off writes nothing for it. The answer is recorded in the onboarding+record as `onboarding.mcp_server` and `onboarding.agent_skills` (`installed` or+`declined`). Set up or remove either one later with `beacon mcp install|uninstall` and+`beacon skills install|uninstall`. Beacon Cloud MCP stays a separate, explicit step:+[`beacon mcp connect`](/cli/mcp-connect).++Every later `beacon endpoint install` and `beacon endpoint repair` updates the skill+copies Beacon installed to match the new binary. It never installs skills that were+turned off or removed.+The explicit `beacon endpoint install --connect` flag is unchanged: it presets Beacon Cloudand skips the destination question.diff --git a/docs/cli/mcp-install.mdx b/docs/cli/mcp-install.mdxnew file mode 100644index 00000000..cecd1957--- /dev/null+++ b/docs/cli/mcp-install.mdx@@ -0,0 +1,61 @@+---+title: "beacon mcp install"+description: "Register the local Beacon MCP server in your harnesses, or remove it"+---++## Command overview++`beacon mcp install` registers the local Beacon MCP server, [`beacon mcp serve`](/cli/mcp-serve),+in the user-level config of every detected harness Beacon can write. `beacon mcp uninstall`+removes the entries it wrote.++```bash title="Command syntax"+beacon mcp install [--harness NAME]...+beacon mcp uninstall+```++The interactive [`beacon endpoint install`](/cli/endpoint-onboarding#agent-tools) runs+`beacon mcp install` for you unless you turn the Beacon MCP server off in the wizard.++The entry is named `beacon` and runs the `beacon` executable by its absolute path with+`mcp serve`, because harnesses started from a desktop launcher do not see your shell's+`PATH`. The server reads this machine's runtime log, so it works whether telemetry stays+local or is also forwarded to Beacon Cloud. Nothing here touches the network.++| Harness | Config |+|---------|--------|+| Claude Code | `~/.claude.json`, through `claude mcp add --scope user` when the `claude` CLI is on `PATH` |+| Codex CLI | `~/.codex/config.toml` (or `$CODEX_HOME/config.toml`) |+| Cursor | `~/.cursor/mcp.json` |+| VS Code | the user profile's `mcp.json` |+| Gemini CLI | `~/.gemini/settings.json` |+| OpenCode | `~/.config/opencode/opencode.json` or `opencode.jsonc` |++Beacon adds the entry only where the name `beacon` is free. An existing `beacon` entry,+whoever wrote it, is left as it is. Configs are edited the way+[`beacon mcp connect`](/cli/mcp-connect) edits them: never re-serialized, backed up first,+and parsed back to prove nothing else changed. What was written is recorded in+`~/.beacon/mcp/local.json`.++`beacon mcp uninstall` removes only the entries recorded there, and only while each one+still runs the command Beacon wrote. An entry you have since changed is yours and stays.++This is a different entry from Beacon Cloud MCP (`beacon-managed`), which+`beacon mcp connect` manages. Neither command touches the other's entry.++## Flags++| Flag | Description |+|------|-------------|+| `--harness NAME` | Harness to configure (repeatable). Defaults to every detected harness |++## Related++<Columns cols={2}>+ <Card title="beacon mcp serve" icon="server" href="/cli/mcp-serve">+ The local server the entry runs.+ </Card>+ <Card title="beacon skills" icon="book" href="/cli/skills">+ Install the Beacon Skills for every project.+ </Card>+</Columns>diff --git a/docs/cli/skills.mdx b/docs/cli/skills.mdxnew file mode 100644index 00000000..0513e24e--- /dev/null+++ b/docs/cli/skills.mdx@@ -0,0 +1,49 @@+---+title: "beacon skills"+description: "Install the Beacon Skills for every project, or remove them"+---++## Command overview++`beacon skills install` installs the [Beacon Skills](/concepts/beacon-skills) into the+user-level skill directories agent runtimes read, so every project on this machine sees+them. `beacon skills uninstall` removes the copies Beacon installed.++```bash title="Command syntax"+beacon skills install+beacon skills uninstall+```++The interactive [`beacon endpoint install`](/cli/endpoint-onboarding#agent-tools) runs+`beacon skills install` for you unless you turn the Beacon agent skills off in the wizard.++The skills are carried in the `beacon` binary, so installing them needs no network. They go to:++| Directory | Read by |+|-----------|---------|+| `~/.agents/skills` | Codex CLI, Gemini CLI, OpenCode, Pi and other runtimes that read the shared location |+| `~/.claude/skills` (or `$CLAUDE_CONFIG_DIR/skills`) | Claude Code. Written only when Claude Code is set up on this machine |++Each skill directory Beacon writes carries a `.beacon-managed` marker. Beacon replaces or+removes only directories that carry it, so a skill of the same name that you wrote or+installed another way is left alone.++Running `beacon skills install` again updates Beacon's copies. Every+`beacon endpoint install` and `beacon endpoint repair` also brings them up to date with+the installed binary, so an upgrade never leaves an agent following instructions for+commands that changed. Neither ever installs skills you removed.++If you also installed the Beacon plugin from a marketplace, a harness may list the skills+twice: once from the plugin and once from the user-level directory. Remove one copy with+`beacon skills uninstall` or by uninstalling the plugin.++## Related++<Columns cols={2}>+ <Card title="Beacon Skills" icon="book" href="/concepts/beacon-skills">+ What each skill does and how to use it.+ </Card>+ <Card title="beacon mcp install" icon="server" href="/cli/mcp-install">+ Register the local Beacon MCP server.+ </Card>+</Columns>diff --git a/docs/concepts/beacon-skills.mdx b/docs/concepts/beacon-skills.mdxindex d3f04b8e..921c1304 100644--- a/docs/concepts/beacon-skills.mdx+++ b/docs/concepts/beacon-skills.mdx@@ -37,7 +37,16 @@ that accept MCP servers from plugins. When the server is available, recall uses## Install-Beacon Skills install from the `asymptote-labs/agent-beacon` repository. Most harnesses+The interactive [`beacon endpoint install`](/cli/endpoint-onboarding#agent-tools)+installs the skills for every project, and registers the local MCP server, unless you+turn them off in the wizard. To do the same at any other time:++```bash+beacon skills install # ~/.agents/skills, and ~/.claude/skills when Claude Code is set up+beacon mcp install # registers `beacon mcp serve` in detected harnesses+```++Beacon Skills also install from the `asymptote-labs/agent-beacon` repository. Most harnessesread its plugin marketplace directly:| Runtime | Install |diff --git a/docs/docs.json b/docs/docs.jsonindex ee335d06..0de9d331 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -334,10 +334,12 @@"pages": ["cli/mcp-serve","cli/mcp-doctor",+ "cli/mcp-install","cli/mcp-connect"]},"cli/memory",+ "cli/skills",{"group": "beacon rules","root": "cli/rules",