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
fix(handoff): close detached-launch races and carry more store paths (#1014)
Justin D'Souza89e3468c8bc7
diff --git a/CLAUDE.md b/CLAUDE.mdindex fa290c2e..47a805ad 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -70,7 +70,7 @@ Supported runtime surfaces today:- A local-only dashboard served by `beacon endpoint dashboard`, bound to loopback by default and backed by the runtime JSONL log.- Token usage and runtime-reported cost capture across spans, logs, and metric datapoints, normalized into `gen_ai.usage`, with attribution rollups served by the dashboard token view (`/api/tokens`) and the `beacon token-usage` report command for local and CI logs. Every report row carries three costs (`cli/beacon/internal/tokens/cost.go`): `cost_usd` (runtime-reported, unchanged), `estimated_cost_usd` (list price of every priced token, from `internal/pricing`, computed after dedup and cumulative resolution) and `effective_cost_usd` with `cost_source` (per endpoint/harness/session scope, reported cost wins wholesale when the scope has any; otherwise the estimate; session-less events per event), plus `unpriced_events`/`unpriced_tokens` and a report-level `pricing` block (catalog provenance, per-model key, match, base rates, bands applied, fallbacks, unpriced models). Long-context bands apply only to events `requestScoped` classifies as one model request; it defaults to aggregate, so a new capture path is priced at base rates until it is added there with a test. Lens data (`LensDataV1`) carries no estimate.- 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, over `https://` only (plain http just for loopback, no redirect off https), size-capped, and verified first when `--sha256` is given. A small frozen baseline is embedded so `scan` works before any rules are installed, and it stays active alongside the store: a store rule replaces a baseline rule only by id (`rulestore.LoadActiveSkipping`), so installing one rule never silently switches the baseline off; only `--rules <dir>` runs a directory alone.-- 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. By default the runtime runs in the calling terminal; `--launch auto|new-terminal|tmux` (`internal/handoff/detached.go`) instead writes a one-time `launch-<id>.json` specification (0600, expires after five minutes) beside the briefs, opens a terminal surface (cmux or Terminal.app, Windows Terminal or PowerShell, a Linux terminal emulator, or a detached tmux session) running the hidden `beacon handoff _launch --spec`, and waits up to 15 s for it to confirm the runtime started, removing the specification on a timeout so a late terminal starts nothing. Content is never put on the terminal's command line, and only the store-locating path variables in `carriedEnvNames`, never credentials, are carried into the specification. 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.+- 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. By default the runtime runs in the calling terminal; `--launch auto|new-terminal|tmux` (`internal/handoff/detached.go`) instead writes a one-time `launch-<id>.json` specification (0600, expires after five minutes) beside the briefs, opens a terminal surface (cmux or Terminal.app, Windows Terminal or PowerShell, a Linux terminal emulator, or a detached tmux session) running the hidden `beacon handoff _launch --spec`, and waits up to 15 s for it to confirm the runtime started, removing the specification on a timeout so a late terminal starts nothing (the trampoline claims it by an atomic rename, so a timeout after the claim reports that the runtime may still start rather than cancelled, and the status is renamed into place so the caller never reads it half-written). Content is never put on the terminal's command line, and only the store-locating path variables in `carriedEnvNames`, never credentials, are carried into the specification. 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.- Session sharing via `beacon share` and `beacon share refresh` (`cli/beacon/cmd/share.go`; docs in `docs/cli/share.mdx`, with the workflow guides in `docs/sharing/` kept in sync). It publishes one session the person names (or the most recent in a directory) to beacon.sh as a shared trace that is a `beacon.trace.v1` trace, the projection the dashboard uses: `BuildShareBundle` (sanitize, scrub, then `TraceEventFromEvent`/`TraceBuilder`), the wire types (`ShareTraceV1` summary body, `ShareEventsBatchV1` of `TraceEventV1`s, `ShareTraceStateV1` with `last_event_id`), `ShareExternalID` (`<harness>:<session-id>`, or a sha256 form), `ShareRelation` and `ShareEventsAfter` live in `pkg/asymptoteobserve/share.go`, and the client in `cli/beacon/internal/account/share.go` (`PUT /v1/traces/{external_id}`, `POST .../events/batch` capped at `ShareMaxEventsPerBatch`, `GET`). The chat view is derived on beacon.sh with `TraceMessages` (`pkg/asymptoteobserve/tracemessages.go`), which pairs a tool invocation and its completion by `tool_call_id` and writes a call reported twice once; messages are never uploaded. Sessions resolve through the handoff registry (store first, then the runtime log). Every event goes through `SanitizeEvent` and session-directory/home paths are rewritten in every projected field before projection, and the shared summary drops the working directory and repository path and names the project by `project.name`. `--print` shows the exact `{external_id, trace, events}` payload with no network, `public` needs confirmation (refused without a terminal unless `--yes`), a re-share upserts by stable event id, and a refresh sends only `ShareEventsAfter` the server's `last_event_id` (re-sending it and any tool call still open). After an upload it writes one `session.shared` event (`event.fidelity=inferred`, no collection method) carrying `shared_url`, `visibility`, `shared_at`/`last_refreshed_at` in raw, which the trace list reads as the sharing state; the projection skips that event. It never runs from hooks or in the background, except the opted-in pre-push sharing below. From a Metadata-only endpoint the share payload goes through `asymptoteobserve.StripToMetadata` (the same fields the Vector metadata transform removes, applied after event ids are derived) and drops the derived title. With no selector (or `--current`) it shares the session it runs inside: `BEACON_SESSION_ID`/`BEACON_HARNESS` (the Claude Code SessionStart hook appends both as `export` lines to `$CLAUDE_ENV_FILE`, plain identifiers only; a child runtime inherits them, so without `--harness` they are refused, naming both sessions, when the named session ran outside this directory and its parents or another runtime worked here more recently: `shareEnvContradiction`), then the active-session record (only when the entry was seen at least as recently as the directory's newest session, since OTLP-only and poll runtimes never write it), then the directory's most recent session. The record is `pkg/asymptoteobserve/activesession` (`~/.beacon/endpoint/active-sessions.json`, 0600 under 0700, atomic and locked, at most 256 entries, 14-day prune, an unchanged entry rewritten at most once a minute), written by the hook logger after every endpoint event with a session id, working directory and harness; it holds identifiers and paths only, never content, and hooks write it silently and never touch the network for it. Hook tests point `BEACON_ACTIVE_SESSIONS_FILE` at a temp file in `TestMain`. Auto-share (`beacon share auto enable|disable|status`, `cli/beacon/cmd/share_auto.go`, settings in `pkg/asymptoteobserve/shareauto`) is server-side publishing: when it applies to a session's working directory, the hook logger writes ONE local `session.share_requested` event per session (`event.fidelity=inferred`, `share.visibility`; deduplicated under the active-session record's lock) and Beacon Cloud forwarding ships it; beacon.sh builds and refreshes the trace with the same `BuildShareBundle` projection and `ShareExternalID`. Hooks never upload. The user file `~/.beacon/endpoint/share.json` (0600, CLI-written) holds the user-wide switch, three-state (unset, on, or off as a kill switch over every project; `auto.state`, with `auto.enabled` kept in step so older files read) and per-project choices by path, which a user-wide enable or disable never rewrites; a project marker `<repo>/.beacon/share.json` may disable on its own (and an off marker wins over the user's entry for the same directory; the closest directory with an entry or marker decides) but enables only when the user's file trusts that project, with the user's visibility, so a cloned repository can never publish someone's sessions. `ForHook` costs one failed read when nothing is enabled. Hook tests point `BEACON_SHARE_SETTINGS_FILE` at a temp file. The share projection and `handoff.LogSessions` recency skip `session.share_requested`.- 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. A note line may carry the session's share URL as its first trailing field (`beacon:<harness>/<id> <url>`; an identifier, not content): `gitlink.ValidShareURL` admits only https URLs on beacon.sh or the configured Beacon host (`AllowShareHost`, fed by `gitAllowShareHosts`), on write and on read, and `MergeNote`/`ParseNote` prefer the line with the URL over the bare one. Post-commit and `link` take URLs only from local `session.shared` events (`localShareURLs`). `setup --share-sessions [--share-visibility]` (implies `--share-notes`; stored as `beacon.shareSessions`/`beacon.shareVisibility` in local git config; public needs confirmation or `--yes`) makes the pre-push hook, which now receives git's stdin, share sessions linked to pushed commits that have no URL (at most 100 commits/10 sessions, silent without credentials, never failing the push; the budget is enforced by the clock: the share phase runs in a goroutine delivering URLs to a collector, the hook takes what it holds after the 6 s upload budget and abandons the rest, then writes notes and pushes the notes ref with what remains of the hook's 10 s, never less than 1 s and 3 s, so only the main path ever writes notes) through `shareUpload` (`cmd/share_upload.go`: `alignShareSource` + `ShareEventsAfter`), then write the URLs into the notes before pushing them. `beacon share --follow [--interval]` (`cmd/share_follow.go`) polls the session locally, uploads through `shareUpload` only when the fingerprint of the projected trace events changed (the events only: the trace body carries its build time), stops at `session.ended` or Ctrl+C (`shareFollowWait`/`shareFollowSignals` are the test seams), and records `session.shared` after each upload, later ones as refreshes that keep the share date; `docs/cli/share.mdx` carries the API-key CI walkthrough with GitHub Actions and GitLab CI examples. Local views show sharing read-only: the trace summary (`traceFold`, which wraps `asymptoteobserve.TraceBuilder` with the local-only `traceStaleness`, and the history through `traceAggregateState`, derivation version 12) and the dashboard's `SessionRecord.Sharing` mark a shared session `stale` when an event `asymptoteobserve.ShareProjects` accepts (the one definition of what a share publishes) and that is not the share's own (`shareActivity`) is newer than what its last `session.shared` record covered (`shared_through`), and carry `asymptoteobserve.ShareRefreshCommand` for the reader to copy; the session list/page, `beacon traces` TUI and plain list display them, and nothing in them shares.- 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 an unattended install; the onboarding wizard runs it only after the person chose Beacon Cloud and left "Beacon Cloud MCP" selected (that screen is the confirmation), and otherwise the install only suggests it. It is 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.diff --git a/cli/beacon/internal/handoff/detached.go b/cli/beacon/internal/handoff/detached.goindex b454d255..bf7c6899 100644--- a/cli/beacon/internal/handoff/detached.go+++ b/cli/beacon/internal/handoff/detached.go@@ -24,6 +24,9 @@ const (LaunchModeTmux = "tmux"launchSpecVersion = 1+ // launchSpecLifetime is how long a launch specification stays valid. A caller waits seconds for+ // its status, so a status file older than this has no caller left to read it.+ launchSpecLifetime = 5 * time.Minute)// DetachedOptions controls how LaunchDetached opens the terminal surface. The exported hooks keep@@ -63,18 +66,28 @@ type launchSpec struct {CarriedEnv map[string]string `json:"carried_env,omitempty"`}-// carriedEnvNames are the variables that locate a runtime's configuration and session store. They-// hold paths, never credentials, so they may be written to the launch specification.+// carriedEnvNames are the variables that locate the configuration and session store of a runtime+// handoff launches. They hold paths or profile names, never credentials, so they may be written+// to the launch specification.var carriedEnvNames = []string{"CLAUDE_CONFIG_DIR",+ "CLINE_DIR","CODEX_HOME","COPILOT_HOME","CURSOR_CONFIG_DIR",- "DSH_HOME","GEMINI_CLI_HOME",+ "HERMES_DATA_DIR_SUFFIX","HERMES_HOME","KIRO_HOME",+ "OH_PERSISTENCE_DIR",+ "OMP_PROFILE",+ "OPENCLAW_STATE_DIR",+ "OPENCODE_DB","PI_CODING_AGENT_DIR",+ "PI_CONFIG_DIR",+ "PI_PROFILE",+ "PRIME_AGENT_CODING_AGENT_DIR",+ "QWEN_HOME","XDG_CONFIG_HOME","XDG_DATA_HOME","XDG_STATE_HOME",@@ -141,7 +154,7 @@ func LaunchDetached(plan Plan, opts DetachedOptions) (DetachedResult, error) {Version: launchSpecVersion,Plan: plan,StatusPath: files.statusPath,- ExpiresAt: opts.Now().Add(5 * time.Minute).UTC(),+ ExpiresAt: opts.Now().Add(launchSpecLifetime).UTC(),CarriedEnv: carriedEnv(opts.Getenv),}if command.needsScript {@@ -169,9 +182,15 @@ func LaunchDetached(plan Plan, opts DetachedOptions) (DetachedResult, error) {}status, err := waitLaunchStatus(files.statusPath, opts)if err != nil {- // Remove the specification so a terminal that opens late finds nothing to run: the caller- // is told the launch failed and may retry, which must not start the runtime twice.- cleanup()+ // Withdraw the specification so a terminal that opens late finds nothing to run: the caller+ // is told the launch failed and may retry, which must not start the runtime twice. When the+ // terminal claimed it first, the runtime may be starting.+ cancelled := cancelLaunchSpec(files.specPath)+ _ = os.Remove(files.statusPath)+ _ = os.Remove(files.scriptPath)+ if !cancelled {+ return DetachedResult{}, fmt.Errorf("%s opened and took the launch but the target runtime did not confirm startup: %w; it may still start there, so check %s before retrying", command.name, err, command.name)+ }return DetachedResult{}, fmt.Errorf("%s opened but the target runtime did not confirm startup: %w; the launch was cancelled", command.name, err)}_ = os.Remove(files.statusPath)@@ -232,6 +251,7 @@ func newDetachedFiles(dir string) (detachedFiles, error) {if err := os.Chmod(dir, 0o700); err != nil {return detachedFiles{}, fmt.Errorf("restrict handoff directory: %w", err)}+ pruneStaleLaunchStatus(dir, time.Now())var random [12]byteif _, err := rand.Read(random[:]); err != nil {return detachedFiles{}, fmt.Errorf("generate handoff launch id: %w", err)@@ -246,6 +266,24 @@ func newDetachedFiles(dir string) (detachedFiles, error) {}, nil}+// pruneStaleLaunchStatus removes status files no caller is waiting for: a terminal that confirms+// after its caller gave up writes one that nobody reads.+func pruneStaleLaunchStatus(dir string, now time.Time) {+ entries, err := os.ReadDir(dir)+ if err != nil {+ return+ }+ for _, entry := range entries {+ name := entry.Name()+ if !strings.HasPrefix(name, "launch-") || !strings.HasSuffix(name, ".status.json") {+ continue+ }+ if info, err := entry.Info(); err == nil && now.Sub(info.ModTime()) > launchSpecLifetime {+ _ = os.Remove(filepath.Join(dir, name))+ }+ }+}+func writeLaunchSpec(path string, spec launchSpec) error {data, err := json.Marshal(spec)if err != nil {@@ -550,11 +588,15 @@ func waitLaunchStatus(path string, opts DetachedOptions) (launchStatus, error) {// RunLaunchSpec consumes a one-time launch specification and runs its target in the new terminal.func RunLaunchSpec(path string, stdin io.Reader, stdout, stderr io.Writer) (int, error) {- spec, err := readLaunchSpec(path)+ claimed, err := claimLaunchSpec(path)+ if err != nil {+ return -1, err+ }+ spec, err := readLaunchSpecAt(claimed, path)+ _ = os.Remove(claimed)if err != nil {return -1, err}- _ = os.Remove(path)for _, cleanup := range spec.CleanupPaths {_ = os.Remove(cleanup)}@@ -580,8 +622,48 @@ func RunLaunchSpec(path string, stdin io.Reader, stdout, stderr io.Writer) (int,return code, err}-func readLaunchSpec(path string) (launchSpec, error) {+// claimLaunchSpec renames the specification out of the path the caller would withdraw it from to+// cancel it, so either the caller cancels and the terminal finds nothing, or the terminal claims it+// and the caller's cancel fails.+func claimLaunchSpec(path string) (string, error) {if !filepath.IsAbs(path) {+ return "", errors.New("handoff launch spec path must be absolute")+ }+ claimed := path + ".claimed"+ if err := os.Rename(path, claimed); err != nil {+ if os.IsNotExist(err) {+ return "", errors.New("handoff launch spec is gone: the launch was cancelled or has already run")+ }+ return "", fmt.Errorf("claim handoff launch spec: %w", err)+ }+ return claimed, nil+}++// cancelLaunchSpec withdraws a specification no terminal has claimed and reports whether it did.+// Exactly one of it and claimLaunchSpec wins because both rename the published file. A plain+// remove is not enough: on macOS, an unlink racing the claim can succeed although the claim did.+func cancelLaunchSpec(path string) bool {+ withdrawn := path + ".cancelled"+ err := os.Rename(path, withdrawn)+ if os.IsNotExist(err) {+ return false+ }+ if err != nil {+ _ = os.Remove(path)+ return true+ }+ _ = os.Remove(withdrawn)+ return true+}++func readLaunchSpec(path string) (launchSpec, error) {+ return readLaunchSpecAt(path, path)+}++// readLaunchSpecAt reads the specification stored at path, which was published as published; the+// paths it names must stay in the published file's directory.+func readLaunchSpecAt(path, published string) (launchSpec, error) {+ if !filepath.IsAbs(path) || !filepath.IsAbs(published) {return launchSpec{}, errors.New("handoff launch spec path must be absolute")}info, err := os.Lstat(path)@@ -608,7 +690,7 @@ func readLaunchSpec(path string) (launchSpec, error) {if !filepath.IsAbs(spec.Plan.Executable) || !filepath.IsAbs(spec.Plan.Dir) || !filepath.IsAbs(spec.StatusPath) {return launchSpec{}, errors.New("handoff launch spec paths must be absolute")}- specDir := filepath.Clean(filepath.Dir(path))+ specDir := filepath.Clean(filepath.Dir(published))if filepath.Clean(filepath.Dir(spec.StatusPath)) != specDir {return launchSpec{}, errors.New("handoff launch status must stay in the spec directory")}@@ -626,8 +708,20 @@ func writeLaunchStatus(path string, status launchStatus) error {return err}data = append(data, '\n')- if err := os.WriteFile(path, data, 0o600); err != nil {+ // Written beside the status and renamed into place, so the waiting caller never reads a+ // partly written file.+ temp := path + ".tmp"+ if err := os.WriteFile(temp, data, 0o600); err != nil {+ _ = os.Remove(temp)+ return fmt.Errorf("write handoff launch status: %w", err)+ }+ if err := os.Chmod(temp, 0o600); err != nil {+ _ = os.Remove(temp)+ return fmt.Errorf("write handoff launch status: %w", err)+ }+ if err := os.Rename(temp, path); err != nil {+ _ = os.Remove(temp)return fmt.Errorf("write handoff launch status: %w", err)}- return os.Chmod(path, 0o600)+ return nil}diff --git a/cli/beacon/internal/handoff/detached_test.go b/cli/beacon/internal/handoff/detached_test.goindex 3ee282d5..8535f743 100644--- a/cli/beacon/internal/handoff/detached_test.go+++ b/cli/beacon/internal/handoff/detached_test.go@@ -268,39 +268,6 @@ func TestLaunchDetachedReportsAnUnconfirmedTerminal(t *testing.T) {}}-func TestLaunchDetachedCarriesStoreLocatingEnvironment(t *testing.T) {- dir := t.TempDir()- env := map[string]string{"CODEX_HOME": "/home/me/.codex-work", "ANTHROPIC_API_KEY": "secret"}- var carried map[string]string- _, err := LaunchDetached(Plan{Executable: "/bin/codex", Dir: dir}, DetachedOptions{- Mode: LaunchModeTmux,- BeaconExecutable: "/opt/beacon/bin/beacon",- SpecDir: dir,- GOOS: "linux",- Getenv: func(name string) string { return env[name] },- LookPath: func(string) (string, error) { return "/usr/bin/tmux", nil },- Start: func(*exec.Cmd) error {- specs, _ := filepath.Glob(filepath.Join(dir, "launch-*[0-9a-f].json"))- if len(specs) != 1 {- return fmt.Errorf("specs = %v", specs)- }- spec, err := readLaunchSpec(specs[0])- if err != nil {- return err- }- carried = spec.CarriedEnv- return writeLaunchStatus(spec.StatusPath, launchStatus{State: "started"})- },- Sleep: func(time.Duration) {},- })- if err != nil {- t.Fatalf("LaunchDetached: %v", err)- }- if !reflect.DeepEqual(carried, map[string]string{"CODEX_HOME": "/home/me/.codex-work"}) {- t.Fatalf("carried env = %v", carried)- }-}-func TestWindowsTerminalEscapesSemicolons(t *testing.T) {files := detachedFiles{id: "0123456789abcdef01234567", specPath: `C:\Users\a;b\handoffs\launch.json`}command, err := terminalLauncher(Plan{Dir: `C:\work;x`}, files, normalizeDetachedOptions(detachedTestOptions("windows", "wt.exe")))@@ -351,7 +318,7 @@ func TestRunLaunchSpecStartsTheExactPlanAndConsumesPrivateFiles(t *testing.T) {if stdout.String() != "argument with spaces|safe|/carried/codex" {t.Fatalf("stdout = %q", stdout.String())}- for _, path := range []string{specPath, cleanupPath} {+ for _, path := range []string{specPath, specPath + ".claimed", statusPath + ".tmp", cleanupPath} {if _, err := os.Stat(path); !os.IsNotExist(err) {t.Fatalf("%s was not consumed: %v", path, err)}@@ -476,3 +443,85 @@ func TestLaunchDetachedReportsLauncherStartFailure(t *testing.T) {t.Fatalf("err = %v", err)}}++func TestLaunchDetachedReportsALaunchTheTerminalAlreadyTook(t *testing.T) {+ dir := t.TempDir()+ now := time.Now()+ _, err := LaunchDetached(Plan{Executable: "/bin/codex", Dir: dir}, DetachedOptions{+ Mode: LaunchModeTmux,+ BeaconExecutable: "/opt/beacon/bin/beacon",+ SpecDir: dir,+ GOOS: "linux",+ LookPath: func(string) (string, error) { return "/usr/bin/tmux", nil },+ // The terminal claims the specification but never confirms startup.+ Start: func(*exec.Cmd) error {+ specs, _ := filepath.Glob(filepath.Join(dir, "launch-*[0-9a-f].json"))+ if len(specs) != 1 {+ return fmt.Errorf("specs = %v", specs)+ }+ _, err := claimLaunchSpec(specs[0])+ return err+ },+ Now: func() time.Time {+ now = now.Add(time.Second)+ return now+ },+ Sleep: func(time.Duration) {},+ StartupTimeout: 2 * time.Second,+ })+ if err == nil || !strings.Contains(err.Error(), "may still start") || strings.Contains(err.Error(), "cancelled") {+ t.Fatalf("err = %v", err)+ }+}++// The caller cancels while a terminal may be opening the specification. Whenever the cancel+// succeeds, the caller reports the launch cancelled, so the terminal must not go on to start the+// runtime. The runtime here does not exist: a trampoline that tries to start it records an error+// status, which is how an attempted start shows.+func TestRunLaunchSpecStartsNothingAfterACancel(t *testing.T) {+ dir := t.TempDir()+ for i := range 500 {+ specPath := filepath.Join(dir, fmt.Sprintf("launch-%d.json", i))+ statusPath := filepath.Join(dir, fmt.Sprintf("launch-%d.status.json", i))+ spec := launchSpec{+ Version: launchSpecVersion,+ Plan: Plan{Executable: filepath.Join(dir, "missing-runtime"), Dir: dir},+ StatusPath: statusPath,+ ExpiresAt: time.Now().Add(time.Minute),+ }+ if err := writeLaunchSpec(specPath, spec); err != nil {+ t.Fatal(err)+ }+ cancelled := make(chan bool)+ go func() { cancelled <- cancelLaunchSpec(specPath) }()+ _, _ = RunLaunchSpec(specPath, nil, &strings.Builder{}, &strings.Builder{})+ _, statErr := os.Stat(statusPath)+ if <-cancelled && statErr == nil {+ t.Fatalf("attempt %d: the caller cancelled but the terminal still tried to start the runtime", i)+ }+ }+}++func TestNewDetachedFilesPrunesOnlyStaleStatus(t *testing.T) {+ dir := t.TempDir()+ stale := filepath.Join(dir, "launch-stale.status.json")+ live := filepath.Join(dir, "launch-live.status.json")+ for _, path := range []string{stale, live} {+ if err := os.WriteFile(path, []byte(`{"state":"started"}`), 0o600); err != nil {+ t.Fatal(err)+ }+ }+ old := time.Now().Add(-launchSpecLifetime - time.Minute)+ if err := os.Chtimes(stale, old, old); err != nil {+ t.Fatal(err)+ }+ if _, err := newDetachedFiles(dir); err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(stale); !os.IsNotExist(err) {+ t.Fatalf("stale status kept: %v", err)+ }+ if _, err := os.Stat(live); err != nil {+ t.Fatalf("live status removed: %v", err)+ }+}diff --git a/docs/cli/handoff.mdx b/docs/cli/handoff.mdxindex bae7e870..76919b0b 100644--- a/docs/cli/handoff.mdx+++ b/docs/cli/handoff.mdx@@ -222,13 +222,17 @@ specification, starts the exact approval-safe argument vector, and confirms starprocess. Prompt or brief content is never interpolated into a terminal-launch shell command.If the runtime does not confirm startup within 15 seconds, Beacon removes the specification andreports the launch as cancelled, so a terminal that opens late starts nothing and a retry cannot-start the runtime twice.+start the runtime twice. The trampoline claims the specification by renaming it before it reads+it, so only one side wins: if the terminal had already claimed it, Beacon says the runtime may+still start there instead of reporting it cancelled. Check that terminal before retrying.A new terminal starts from its own environment rather than the calling process's. Beacon carriesthe variables that locate a runtime's configuration and sessions (`CLAUDE_CONFIG_DIR`,-`CODEX_HOME`, `COPILOT_HOME`, `CURSOR_CONFIG_DIR`, `DSH_HOME`, `GEMINI_CLI_HOME`, `HERMES_HOME`,-`KIRO_HOME`, `PI_CODING_AGENT_DIR` and `XDG_CONFIG_HOME`/`XDG_DATA_HOME`/`XDG_STATE_HOME`) into-the specification. It never writes other variables there, so credentials such as API keys must be+`CLINE_DIR`, `CODEX_HOME`, `COPILOT_HOME`, `CURSOR_CONFIG_DIR`, `GEMINI_CLI_HOME`,+`HERMES_DATA_DIR_SUFFIX`, `HERMES_HOME`, `KIRO_HOME`, `OH_PERSISTENCE_DIR`, `OMP_PROFILE`,+`OPENCLAW_STATE_DIR`, `OPENCODE_DB`, `PI_CODING_AGENT_DIR`, `PI_CONFIG_DIR`, `PI_PROFILE`,+`PRIME_AGENT_CODING_AGENT_DIR`, `QWEN_HOME` and `XDG_CONFIG_HOME`/`XDG_DATA_HOME`/`XDG_STATE_HOME`)+into the specification. It never writes other variables there, so credentials such as API keys must beavailable in the new terminal's own environment, for example from your shell profile.The runtime starts in the session's recorded directory. If that directory no longer exists, Beacon