Skip to content

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

feat(spool): a workspace spool every harness's hooks can stage in, drained by Beacon (#1287)

kyle-elliott-asymptotef9851e2978cd
diff --git a/CLAUDE.md b/CLAUDE.md
index f157c62f..542a8761 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -30,6 +30,7 @@ Do not recreate or depend on removed `asymptote` mirror trees. Keep new work foc
- `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, and `beacon share` may send it (scope `traces:write`, also on the sign-in page) to `PUT /v1/traces/{external_id}`, `POST /v1/traces/{external_id}/events/batch` and `GET /v1/traces/{external_id}` on the Beacon API host (`https://api.beacon.sh` for a beacon.sh sign-in, other hosts unchanged, `BEACON_API_URL` overrides) to upload a shared trace the person chose to publish, as a `beacon.trace.v1` summary and its events (`cli/beacon/internal/account/share.go`; a `bcn_api_` API key from `--key` or `BEACON_API_KEY` may stand in for it, precedence `--key`, then a current sign-in carrying the scope, then the environment). These are explicit, user-initiated requests with redirects refused. Hooks, plugins and background jobs never make them, with one exception: the git pre-push hook, only when the person opted in with `beacon git setup --share-sessions` (public needs confirmation), may make the three share requests during a push the person started, within the hook's budget and never failing the push. 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.
- System log access (`beacon endpoint install|repair --system --log-access shared|restricted`; docs in `docs/cli/endpoint-install.mdx#restricted-log-access`). Shared, the CLI default, is the system log as it always was: hooks append to `/var/log/beacon-agent/runtime.jsonl` directly, so it is `0666`. Restricted is opt-in for the CLI and the default for a first package install on every platform (see below; on Linux `packaging/linux/install-endpoint.sh` passes `--log-access restricted` only when neither the system `config.json` nor the runtime log exists, `/proc/1/comm` is systemd and `BEACON_SERVICE` is unset, `auto` or `systemd`; otherwise it passes nothing and the endpoint keeps its mode; `packaging/linux/beacon-settings.sh`, sourced by that script and by the postinstall (which takes only `BEACON_ENDPOINT_HARNESSES`, through `beacon_settings_harnesses` in a subshell, because its user-config step re-runs the CLI as each logged-in user with its environment and must not hand them a Splunk HEC token from the file), reads the `BEACON_*` install settings, never sourcing the file, from a root-owned, not group/other-writable `/etc/default/beacon` or `/etc/sysconfig/beacon` in shell syntax with trailing comments, skipping a malformed value with a warning naming only the key, the last assignment of a key winning within the file, the environment and `install-endpoint.sh`'s positional arguments winning over it; the postinstall prints the `usermod -aG beacon-log` hint for a restricted log; `packaging/linux/test-endpoint-scripts.sh` checks all of it). Restricted makes the root collector the only writer: its `beacon_ingest` extension (`collector-builder/exporter/beaconjsonexporter/beaconingestextension`, appending through the exporter's own `internal/runtimelog`) serves `/var/run/beacon-agent/ingest.sock`, and the hook adapter and the CLI writer, as any account but root writing the system log, hand finished lines to it through `pkg/asymptoteobserve/localingest` (`Deliverer`). The protocol is one batch per connection (`BEACON-INGEST/1`, a header naming the log, one event per line, one JSON reply saying how far it got); the server refuses a batch for any log but its own, identifies the sender only by kernel peer credentials (`SO_PEERCRED`, `LOCAL_PEERCRED`), overwrites the event's `user` with that uid and its resolved name and always derives `event.id` itself (`StampLine` re-encodes, so a sender cannot split or forge lines or reuse another event's id), and bounds connections overall and per uid, batch size, each account's bytes per second, and its own time per connection (shorter than the client's, so it reports how far it got instead of being resent). The client sends only to a socket that root owns in a directory nobody else can write, under ancestors owned by root or by the sending account (a sandbox without a user namespace, such as bubblewrap, assembles its root on a tmpfs that account owns, so a bind-mounted `/var/run/beacon-agent` works there; group-writable ancestors only for gid 0/1, which macOS's `/private/var/run` needs), and only once the connected socket's own peer credentials name root as the server (`checkServer`), so no swap of the path between the check and the dial reaches another listener. Sandboxes with their own user namespace are out of scope. `Deliverer.Write` sends through the socket when it answers and otherwise appends directly as before; only a direct append that cannot reach the log (refused for permission, its directory missing, or a read-only mount: a restricted log whose collector is down, or a sandbox that leaves the log out) spools the line, to the account's private spool for that log (`~/.beacon/endpoint/spool/<log digest>`, 0600 under 0700, only in a home that exists), and the next line that gets through either way drains it. Root writers and per-user logs always write directly. No ordinary account creates the system log's directory, and no writer creates a missing home to hold a log (`asymptoteobserve.RuntimeLogDirCreatable`) or the hook's state directories, so a sandbox whose root filesystem is its own gets a `NOT recorded` explanation on stderr instead of events written into its tmpfs. The mode is `config.json` `log_access`, carried through repair and package upgrades (`BEACON_LOG_ACCESS` in the install scripts). A first install from any package (`.deb`/`.rpm` on systemd hosts, the macOS `.pkg`, the MSI unless `BEACON_SERVICE` names the supervised collector; no system config and no kept log) defaults to restricted in its install script, and adds to `beacon-log` (`--log-readers`, `loggroup.AddMember`: gpasswd/addgroup, dseditgroup, net.exe; add-only, failures reported not fatal; `validAccount` also admits spaces, an apostrophe and non-ASCII letters on Windows, because OOBE names local accounts from what the person typed) exactly `BEACON_LOG_READERS` when set, even empty, else only a person who installed interactively (Linux `SUDO_USER` with a controlling terminal (`/dev/tty`, not stdin, which rpm scriptlets get as a pipe) and not `DEBIAN_FRONTEND=noninteractive`, because Ansible `become` and Packer sudo set `SUDO_USER` too; macOS without `COMMAND_LINE_INSTALL` and with an `Installer` process of the console user whose lsof `txt` executable is Apple's `/System/Library/CoreServices/Installer.app`, never a bare process name; Windows MSI `UILevel` >= 4 via the custom action's `-UiLevel`), never an unattended fleet install. In both shell settings parsers an environment variable set to an empty string counts as unset (except `BEACON_LOG_READERS`, where empty means nobody), and the macOS Fleet wrapper (`packaging/macos/fleet/scripts/install.sh`) passes only arguments it was given, so neither hides the settings file or managed preferences. Fleet tooling sets the `BEACON_*` install settings where it writes settings: `/etc/default/beacon`/`/etc/sysconfig/beacon` (`packaging/linux/beacon-settings.sh`), managed or local preferences for `com.beacon.endpoint` (`packaging/macos/beacon-settings.sh`), `HKLM\SOFTWARE\Policies\Beacon\Endpoint` (`install-endpoint.ps1`); each read only when root/admin-controlled, environment wins; docs in `docs/security/restricted-log-access.mdx#package-installs`. Install creates the `beacon-log` group (`internal/endpoint/loggroup`, getent/groupadd, dscl/dseditgroup) and `writer.RestrictSystemLog` makes the directory `root:beacon-log 02750`, the log and archives `0640` and the lock root-only `0600`, after writing the root-owned `.beacon-log-access` marker beside the log; a shared log is not narrowed in place but copied to fresh root-created files and renamed over, under its lock (bounded wait), because a descriptor opened while it was 0666 survives any chmod. A failed install restores the previous mode in its rollback (`logAccessRestorer`), or, when there was no log before, removes the log, lock and marker it created, because every package script reads a log without a system config as one kept by `--keep-logs`, which would turn the retry of a failed first install into an upgrade; and a shared install removes a dead socket. The marker is what tells every root writer (`asymptoteobserve.RuntimeLogModes`) to keep the restricted modes. The OTLP receivers on loopback are not covered by the socket: any local process can still send OTLP. On Linux, macOS and Windows those events are attributed to the account that owns the sending socket (peer attribution, below), which names the sender but does not stop an account sending what it likes under its own name, so never claim more than that. Doctor's `runtime_log_access` covers the marker, the socket and pending spool. Unix sockets are local IPC, not a network channel, so the hooks-never-touch-the-network rule holds. On Windows the same mode runs over the named pipe `\\.\pipe\beacon-agent-ingest` (`localingest` `transport_windows.go`, go-winio): the collector creates it as the first instance, and when the name is taken (any account may create one) it reports a recoverable error and retries every few seconds rather than failing, so the rest of the collector stays up; it rejects remote clients and its DACL denies NETWORK and withholds `FILE_CREATE_PIPE_INSTANCE` from ordinary accounts, so it is not a network channel either; a client connects at identification level and sends only to a pipe owned by SYSTEM or Administrators; the server counts a connection against its account from the client process's token before reading and stamps the SID it reads by `ImpersonateNamedPipeClient` after the preamble (they must agree), with `Peer.UID` a string (decimal uid on Unix, SID on Windows) and the name from `LookupAccountSid`, bounded. Privileged writers there are SYSTEM and tokens with Administrators enabled (`CheckTokenMembership`; elevation for another group is not enough). The directory gets `sysacl.RestrictedLogDirDACL` (protected: SYSTEM and Administrators full, `beacon-log` local group read, nothing else; the lock SYSTEM and Administrators only) and everything below it is reset, because every account may bypass traverse checking; `writer.RestrictSystemLog` replaces every file directly in the directory (the log family under the lock; files outside it with another hard link are skipped) with a copy created with its final owner and DACL (`sysacl.CreateRestrictedFile`) and a POSIX-semantics rename, fails naming any file held open without sharing delete and then puts a log that was shared back to shared, and writes the marker last (on Windows it decides nothing for root writers, so a failed or killed run is not mistaken for a finished one). The marker counts there when SYSTEM or Administrators own it and no other account can write it. `loggroup` creates the local group with `net.exe` and looks it up qualified with the computer name. Doctor reads the restricted ACL (`writer.CheckRestrictedSystemLogACL`). `packaging/windows/smoke-restricted-log.ps1` runs in `windows-package-smoke` against the installed MSI with a real ordinary account. Hook and writer tests point `logging.EndpointIngest`/`writer.Ingest` at sockets of their own.
- Sandbox roots (Linux): no unprivileged writer puts the log directory (`RuntimeLogDirCreatable`) or the account spool (`DefaultSpoolDir` returns "") on the throwaway root of a sandbox it assembled (`asymptoteobserve.OnSandboxRoot`: `/` a tmpfs owned by this non-root account, and the path's nearest existing directory on that filesystem). Both conditions matter: a persistent account-owned `/` (a rootfs bound at `/`, an Apptainer sandbox) keeps its writes. The home-exists checks alone are not enough, because a launcher that binds a project under the home makes bwrap create the home as an empty mount point on its tmpfs. Hook state and the active-session record may still go there: they are per-session dedupe, and refusing them re-records prompts on every tool call. What the sandbox bind-mounts is another filesystem and is written as usual: a mounted `~/.beacon/endpoint/spool` spools for real, and a workspace is where #1284's workspace spool stages.
+- Workspace spool (`pkg/asymptoteobserve/workspacespool.go`, `cli/beacon/internal/workspacespool`, `beacon endpoint spool drain|status`; docs in `docs/cli/endpoint-spool.mdx`). A hook of any harness that cannot deliver an event by any other route (socket, log, account spool) stages it in `<workspace>/.beacon/spool/<harness>/<session>/` (a `localingest.Spool`), because a sandbox that confines hook writes to the session workspace (DeepSeek Harness #605, container and operator sandboxes #1284) still lets it write there; `.beacon/dsh-spool/<session>` is an earlier layout drains still empty. A `.gitignore` of `*` in `.beacon/spool/` (and `.git/info/exclude`) keeps it out of an agent's `git add -A`, since it holds prompts; it is a precondition of staging (`ensureSpoolGitignore`, checked before every append): created when missing, never overwritten, and when one is already there (a repository can commit its own) staging goes ahead only if it is a regular file that ignores `*` and negates nothing. It never stages a Beacon-only action (drains refuse them, so `requestShareOnce` must see the failure and take its mark back), on a sandbox's own root filesystem (`OnSandboxRoot`), or as root in a workspace another account owns (`rootInAnotherAccountsWorkspace`, which the hook's own drain also honors): a rootful container over the user's checkout would leave root-owned 0700/0600 files the user can neither drain nor delete, and a root drain would rewrite the user's `pending.jsonl` as root's; root that owns the workspace (a rootless container) stages as anyone. The first event a session stages prints one stderr note with a shell-quoted `beacon endpoint spool drain --log-path … --workspace … --harness … --session …` naming the hook's own log and that session alone (not printed for DeepSeek Harness, whose store-backed `dsh sync` finds it). The threat model is untrusted workspace content: a cloned repository and the sandboxed agent itself. So every drain admits a line only through `AdmitStagedLine` (Beacon envelope, that harness and session, hook or plugin collection, not a Beacon-only action: a planted `session.share_requested` would publish a session), the CLI drains also through `Event.Validate` (a refused line is removed, never left to block the spool), an admitted line is written again through the writer's own encoder (hook: `encodeEndpointLine`; CLI: `writer.AppendEvent`), and only sessions Beacon has recorded in the runtime log tail are drained (`KnownSessions`; the default log when no config exists), or those under the operator's `config.json` `workspace_spool_roots` (globs, kept through repair) or a `--workspace` the person names (literal, never a glob; `--harness`/`--session` narrow it). Every component below the workspace must be a real directory and the spool file a regular file no larger than `DefaultSpoolMaxBytes` (`Append` never grows one past it, so a bigger one was written by hand), Lstat-checked (`realSpool`, `spoolPathIsReal`) and opened `O_NOFOLLOW|O_NONBLOCK`, because the agent knows its own session id and could plant that directory as a link to the account spool, which a drain outside the sandbox would then empty. The CLI drains each spool in one `Spool.Drain` pass (one read, one rewrite of the remainder): batches would re-read and rewrite the whole file each time. Deliberately not defended, because they need an unguessable session id or an agent actively racing renames against a drain for a negligible payoff (the agent can already rewrite its own staged events): spool directories other accounts plant in shared directories, and swaps between the Lstat check and use; do not add ownership checks or `os.Root` confinement for them. A config `spool drain` cannot read (root-only when it holds a destination secret) is never guessed around: without `--log-path` the drain refuses and names the flag, and status lists only `--workspace` spools. Three drains: the user-mode sweep (a `Workspace spools` step after the runners, within the budget and retention guard), `beacon endpoint spool drain` (never as root; in system mode through the socket, without the sweep lock), and the session's own next hook that reaches the log (one batch of 256, its own session only). A confined root sweep (`sessionfs.Active`) leaves spools alone. Doctor reports `workspace_spool_pending_drain`, and `dsh_spool_pending_drain` for DeepSeek Harness.
- 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, plus the one bounded exception of the session backfill (below), 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, tool descriptions/definitions, retrieval queries/documents, evaluation explanations, agent descriptions, stop sequences, approval/policy reasons, command output, raw fields, diffs, inventory content, and MCP definitions before buffering/upload. Every text-shaped event field must be classified in `metadata_fields_test.go` (`metadataOnlyRemoved`, each with its own `del()` in `pack/metadata-transforms.toml`, or `metadataOnlyKept`); a new field fails that test until it is, and `BEACON_TEST_VECTOR_BIN` runs the transform on an event with every field set. `vector.toml` is not rendered only at connect: `asymptote.ReconcileForwarder` re-renders it in place for a connected endpoint from the current pack with the enrollment's ingest URL and recorded privacy mode, validates it with the forwarder's own Vector exactly as connect does, atomically replaces it, and, when run from install, repair, the package upgrade or the hidden reconcile the macOS postinstall runs (`ReconcileOptions.Restart`), restarts a running forwarder even when nothing changed (after `vector validate` of the current config with the forwarder's own Vector, and never after a warning, so a refused config or a missing Vector leaves the running forwarder alone), as the Sentinel reconcile does: switching to restricted log access replaces the runtime log with a copy, and Vector, which recognizes a file by its first line, keeps tailing the replaced one until it restarts; an upgrade may also have installed a new Vector. A stopped one is never started and reads the new config when it next starts. The `beacon_runtime` source reads `runtime.jsonl.1` too, as the Sentinel pack does, so lines written to a replaced log before a restart are found again at the next rotation instead of lost. It never enrolls, reads or rewrites the secrets file, makes a network request, or touches `vector-data/` (checkpoints stay, so pack changes must keep source ids and fingerprinting stable), and a rejected config is a warning that keeps the old one; it is a no-op when not connected, after an incomplete connect, without an installed unit, or where `ForwarderManager` is unsupported (supervised mode). `lifecycle.Install` runs it last when services are started (so install, repair and the Linux package upgrade), repair's teardown keeps the forwarder (`UninstallOptions.KeepManagedIngest`) instead of disconnecting it, and the macOS postinstall, which installs with `--no-start`, runs the hidden `beacon endpoint asymptote reconcile --system`. 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.
- Session backfill (`cli/beacon/cmd/endpoint_backfill.go`; docs in `docs/cli/endpoint-install.mdx#session-backfill` and `docs/cli/endpoint-connect.mdx#session-backfill`): after every successful install (user or system mode), every session-store collector runs once with `CollectOptions.Since` (30 days; `sessionwindow.Recent` keeps those sessions, newest first, and never touches the cursors of the rest) and a shared `writer.Budget` (24 MiB, at most 12 MiB per runtime through `Budget.Sub`; a refused append returns `writer.ErrBudgetSpent`, the collector stops with cursors past only what was written, and a manual sync reads the rest). A new session-store collector takes both fields, reads its store only through `internal/sessionfs` (a test parses every collector package to enforce it), and joins `endpointBackfillRunners` and that test's list. Every connect, first or re-connect, user or system, runs the same sweep before enrollment (skipped when install just ran it) and, before the forwarder starts, `asymptote.StageBackfill` copies the window's `harness.collection_method=poll` lines into `cloud-backfill.jsonl` beside the runtime log, which the `beacon_backfill` Vector source (fingerprinted `device_and_inode`, so each atomically restaged copy is a new file) reads from the beginning into the runtime sink through the same privacy transform. Live hook/OTLP/plugin history before the connection point stays local. Re-connects restage, so a resend of already-shipped lines is expected and rests on the deterministic `event.id`; a privacy-mode change clears the checkpoints and the restage renames the new-mode copy over the old one (kept until then so the copy is always a new inode; deleted instead when nothing restages), and `disconnect` removes it. System mode runs the collectors under `withUserHome` for the active console user (`activeConsoleUser`), with cursors under the system base directory, and reports a skip when nobody is logged in; root is reading a home the console user controls, so the sweep runs under `sessionfs.Confine` (an `os.Root` on that home, files owned by the home's owner only, non-blocking opens that refuse FIFOs/devices, SQLite read from a private snapshot under `<SystemBaseDir>/state/backfill-snapshots`, retried until the database size/change counter and WAL header are unchanged across the copy, and refused past `sessionfs.MaxSnapshotBytes` (512 MiB with its WAL) with the runtime's sync command named in the report), and refused paths read as absent and are listed in the report. User-mode sync and backfill stay unconfined. The wizard's confirm screen names the upload (`WizardOptions.BackfillDays`). Dry-run, `--no-backfill` and `BEACON_BACKFILL=0` skip all of it; the cmd tests run with `BEACON_BACKFILL=0` set in `TestMain`.
- `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 shows an agent tools screen; every row is preselected (opt-out, space toggles). Beacon Cloud MCP is offered only with Beacon Cloud and runs the `beacon mcp connect` flow (`connectCloudMCP` with `yes`, OAuth, detected harnesses) only after the endpoint is connected (or already was), via `finishCloudSetup`; a failed enrollment skips it and names the retry. The Beacon Agent Skills are offered for either destination and 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; install and repair refresh only copies Beacon already wrote). Both run after `lifecycle.Install` returns and warn rather than fail. The answers are recorded as `onboarding.cloud_mcp`/`agent_skills`. Implementation lives in `cli/beacon/internal/onboarding`, `cli/beacon/cmd/endpoint_onboarding.go`, `cli/beacon/cmd/endpoint_install.go` and `cli/beacon/cmd/agent_tools.go`; keep `docs/cli/endpoint-onboarding.mdx` and `docs/cli/skills.mdx` in sync.
diff --git a/cli/beacon-hooks/cmd/omp_event_test.go b/cli/beacon-hooks/cmd/omp_event_test.go
index e11312a1..b31decf8 100644
--- a/cli/beacon-hooks/cmd/omp_event_test.go
+++ b/cli/beacon-hooks/cmd/omp_event_test.go
@@ -254,7 +254,8 @@ func TestOmpEventMCPToolRoutesAreWrittenAsListings(t *testing.T) {
}
// The extension decides whether to resend a skill listing from this reply, because the hook exits 0
-// whether or not it wrote anything. Every way an event is dropped must report nothing recorded.
+// whether or not it wrote anything. Every way an event is dropped must report nothing recorded; an
+// event staged in the workspace spool is recorded, since a drain delivers it later.
func TestOmpEventReplyReportsWhatWasRecorded(t *testing.T) {
listing := map[string]interface{}{"type": "context", "sessionId": "sess-1", "skillListing": "- deploy: Deploy applications."}
noLog := func(t *testing.T) {
@@ -269,23 +270,41 @@ func TestOmpEventReplyReportsWhatWasRecorded(t *testing.T) {
}
t.Setenv("BEACON_ENDPOINT_LOG", dir)
}
+ // A workspace under a regular file cannot be created on any platform, so nothing stages.
+ unwritableWorkspace := func(t *testing.T) string {
+ blocker := filepath.Join(t.TempDir(), "not-a-directory")
+ if err := os.WriteFile(blocker, []byte("x"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ return filepath.Join(blocker, "workspace")
+ }
+ writableWorkspace := func(t *testing.T) string { return t.TempDir() }
for _, tc := range []struct {
name string
input map[string]interface{}
setup func(*testing.T)
+ cwd func(*testing.T) string
written float64
}{
- {"written", listing, nil, 1},
- {"log not writable", listing, unwritable, 0},
- {"no endpoint log configured", listing, noLog, 0},
- {"type this build does not map", map[string]interface{}{"type": "message_update", "sessionId": "sess-1"}, nil, 0},
+ {"written", listing, nil, nil, 1},
+ {"log not writable", listing, unwritable, unwritableWorkspace, 0},
+ {"log not writable, staged in the workspace", listing, unwritable, writableWorkspace, 1},
+ {"no endpoint log configured", listing, noLog, nil, 0},
+ {"type this build does not map", map[string]interface{}{"type": "message_update", "sessionId": "sess-1"}, nil, nil, 0},
} {
t.Run(tc.name, func(t *testing.T) {
ompTestLog(t)
if tc.setup != nil {
tc.setup(t)
}
- if out := runHookWithInput(t, runOmpEvent, tc.input); out["recorded"] != tc.written {
+ input := make(map[string]interface{}, len(tc.input)+1)
+ for key, value := range tc.input {
+ input[key] = value
+ }
+ if tc.cwd != nil {
+ input["cwd"] = tc.cwd(t)
+ }
+ if out := runHookWithInput(t, runOmpEvent, input); out["recorded"] != tc.written {
t.Fatalf("reply = %v, want recorded = %v", out, tc.written)
}
})
diff --git a/cli/beacon-hooks/internal/logging/endpoint_write_failure_test.go b/cli/beacon-hooks/internal/logging/endpoint_write_failure_test.go
index 55a5abac..4a85fc1b 100644
--- a/cli/beacon-hooks/internal/logging/endpoint_write_failure_test.go
+++ b/cli/beacon-hooks/internal/logging/endpoint_write_failure_test.go
@@ -11,8 +11,8 @@ import (
// A hook that cannot write the runtime log records nothing, and on DeepSeek Harness that is the
// normal state of a sandboxed session rather than a fault (#605): the harness confines hook
-// commands to the session workspace, so ~/.beacon is unreachable. A session-scoped dsh logger
-// would stage the event in the workspace spool instead (see spool_test.go); these cases run
+// commands to the session workspace, so ~/.beacon is unreachable. A session-scoped logger of any
+// harness would stage the event in the workspace spool instead (see spool_test.go); these cases run
// without a session id, where no spool applies, so the loss is reported -- which is also the
// shape every non-workspace-write sandbox ends up in when the spool write fails too. The hook
// still exits 0 -- a telemetry failure must never become a block -- which makes stderr the only
diff --git a/cli/beacon-hooks/internal/logging/logging.go b/cli/beacon-hooks/internal/logging/logging.go
index e80d69f1..3be33efa 100644
--- a/cli/beacon-hooks/internal/logging/logging.go
+++ b/cli/beacon-hooks/internal/logging/logging.go
@@ -153,22 +153,23 @@ func (l *Logger) EndpointEventWithFidelity(action, category, severity, message,
normalizeEventModel(event)
attachDerivedTrace(event)
if err := writeEndpointJSON(path, event); err != nil {
- // DeepSeek Harness runs hook commands inside the session sandbox, which cannot reach
- // ~/.beacon but CAN write the session workspace in workspace-write mode (#605).
- // Staging the event there keeps capture live; `beacon endpoint dsh sync` drains the
- // spool from outside the sandbox. A staged event is deliberately silent: one process
- // per event would print a note on every event into the runtime's hook stderr stream,
- // so the staged state surfaces through `dsh status`, `dsh sync` and `doctor` instead.
- // When staging fails too -- read-only mode, no workspace, unsafe ids, a full spool --
- // the NOT-recorded explanation below fires unchanged, which is the honest report for
- // an event nothing captured.
- if l.stageInDSHSpool(event) {
+ // A hook inside a sandbox that confines writes to the session workspace cannot reach the
+ // runtime log (DeepSeek Harness first, #605; container and operator sandboxes since, #1284)
+ // but can write the workspace. Staging the event there keeps capture live; a sweep, `beacon
+ // endpoint spool drain`, or this session's next hook that can reach the log drains it. A
+ // staged event is not reported as lost; the first one a session stages prints one note
+ // saying where it waits (stageInWorkspaceSpool). When staging fails too -- read-only mode,
+ // no workspace, unsafe ids, a full spool, a Beacon-only action -- the NOT-recorded
+ // explanation below fires unchanged, which is the honest report for an event nothing
+ // captured.
+ if l.stageInWorkspaceSpool(event, path) {
return nil
}
fmt.Fprintf(os.Stderr, "logging: failed to write endpoint event to %s: %v\n", path, err)
reportEndpointWriteFailure(os.Stderr, l.platform, path, err)
return err
}
+ l.drainOwnWorkspaceSpool(path, event)
recordActiveSession(event)
l.requestShareOnce(event)
return nil
@@ -253,47 +254,194 @@ func recordActiveSession(event map[string]interface{}) {
_ = activesession.Record(activesession.DefaultPath(), name, id, dir, time.Now())
}
-// stageInDSHSpool stages one event a sandboxed DeepSeek Harness hook could not write to the
-// runtime log in the session workspace's spool, and reports whether it did.
+// stageInWorkspaceSpool stages one event this hook could not write to the runtime log at logPath
+// in its session's workspace spool (asymptoteobserve.WorkspaceSpoolDir), and reports whether it
+// did.
//
-// Staging is dsh-only: its sandbox is the reason the log write fails (#605), and staging another
-// runtime's events into a project checkout would be new pollution with no drain path. The session
-// id must be a safe directory name on BOTH the writing and the draining side
-// (ValidDSHSessionIDForSpool is what they share), and the workspace comes from the event's own
-// session.working_directory -- the envelope value the bridge stamped from session.header.cwd, the
-// same directory the sandbox confines writes to -- with the process cwd as the fallback for callers
-// that did not carry the field.
+// Every harness stages, because every harness's spool has a drain: the sweep, `beacon endpoint
+// spool drain`, and the session's own next hook that reaches the log. It began as DeepSeek
+// Harness's alone (#605) and became general once other sandboxes showed the same shape (#1284).
+// The session id and harness name must be safe directory names on BOTH the writing and the
+// draining side (ValidSpoolName is what they share), so a hook without a session id stages
+// nothing. The workspace comes from the event's own session.working_directory -- the directory a
+// sandbox confines writes to -- with the process cwd as the fallback for callers that did not
+// carry the field.
+//
+// An action only Beacon writes (IsBeaconOnlyAction) is never staged: every drain refuses it, as it
+// must refuse one a repository planted, so staging would only turn a write the caller can retry
+// (requestShareOnce takes its mark back) into one silently lost.
//
// The spool is a localingest.Spool, the store a restricted-mode hook already falls back to, not the
// runtime log's writer: it is private to this account wherever the workspace lives, bounded, and
-// waits at most its short lock timeout for a sweep draining it, so a hook never holds the agent up
-// behind `beacon endpoint dsh sync`.
-func (l *Logger) stageInDSHSpool(event map[string]interface{}) bool {
- if l == nil || asymptoteobserve.NormalizeHarnessName(l.platform) != dshHarnessName {
+// waits at most its short lock timeout for a drain under way, so a hook never holds the agent up
+// behind one. A hook running as root never stages in a workspace another account owns
+// (rootInAnotherAccountsWorkspace): that account could never drain the root-owned files.
+func (l *Logger) stageInWorkspaceSpool(event map[string]interface{}, logPath string) bool {
+ if l == nil || l.sessionID == "" {
return false
}
- cwd := ""
- if session, ok := event["session"].(map[string]interface{}); ok {
- cwd, _ = session["working_directory"].(string)
- }
- if strings.TrimSpace(cwd) == "" {
- cwd, _ = os.Getwd()
+ if info, _ := event["event"].(map[string]interface{}); info != nil {
+ if action, _ := info["action"].(string); asymptoteobserve.IsBeaconOnlyAction(action) {
+ return false
+ }
}
- dir, ok := asymptoteobserve.DSHSpoolDir(cwd, l.sessionID)
- if !ok {
+ harness := asymptoteobserve.NormalizeHarnessName(l.platform)
+ workspace := spoolWorkspace(event)
+ dir, ok := asymptoteobserve.WorkspaceSpoolDir(workspace, harness, l.sessionID)
+ // A workspace on the sandbox's own root filesystem (a cwd the sandbox never mounted) would
+ // hold the spool only as long as the sandbox lives.
+ if !ok || rootInAnotherAccountsWorkspace(workspace) || asymptoteobserve.OnSandboxRoot(dir) || !spoolPathIsReal(dir, true) {
return false
}
line, err := encodeEndpointLine(event)
if err != nil {
return false
}
- if dropped, err := (localingest.Spool{Dir: dir}).Append([][]byte{line}); err != nil || dropped > 0 {
+ // <ws>/.beacon/spool, two levels above <harness>/<session>. Nothing is staged unless its
+ // .gitignore keeps the spool out of git (ensureSpoolGitignore).
+ spoolRoot := filepath.Dir(filepath.Dir(dir))
+ if !ensureSpoolGitignore(spoolRoot) {
+ return false
+ }
+ spool := localingest.Spool{Dir: dir}
+ pending, _, err := spool.Pending()
+ first := err != nil || pending == 0
+ if dropped, err := spool.Append([][]byte{line}); err != nil || dropped > 0 {
return false
}
- ensureSpoolGitExclude(filepath.Dir(dir))
+ ensureSpoolGitExclude(spoolRoot)
+ if first {
+ reportStagedSession(os.Stderr, harness, l.sessionID, logPath, dir, workspace)
+ }
return true
}
+// reportStagedSession prints, once for each session's spool (when it starts holding events), where
+// this session's events now wait and what delivers them. Not on every event: a hook runs as one
+// process per event, and every note lands in the runtime's hook stderr stream. Nothing tells the
+// hook whether a drain will find the session -- that needs Beacon to have recorded it outside the
+// sandbox, or the workspace under workspace_spool_roots -- so the note names the drain the person
+// can always run. That command names this session alone and the log this hook writes, shell-quoted
+// to paste as it is: pasted, it vouches for one session, never for every spool a cloned repository
+// planted beside it, and delivers to the log the hook meant, whatever mode the command runs in.
+// DeepSeek Harness is the exception: `beacon endpoint dsh sync` finds its sessions through its own
+// store, so its staging stays silent as it always was.
+func reportStagedSession(w io.Writer, harness, sessionID, logPath, dir, workspace string) {
+ if harness == dshHarnessName {
+ return
+ }
+ fmt.Fprintf(w, "beacon-hooks: cannot write the Beacon runtime log %s here; this session's events are held in %s until Beacon drains them.\n", logPath, dir)
+ fmt.Fprintf(w, "beacon-hooks: they are delivered by this session's next hook that reaches the log, or by running this outside the sandbox: beacon endpoint spool drain --log-path %s --workspace %s --harness %s --session %s\n",
+ shellQuote(logPath), shellQuote(workspace), shellQuote(harness), shellQuote(sessionID))
+}
+
+// shellQuote quotes s for a POSIX shell, so a path with spaces, quotes or `$(...)` pastes as one
+// literal argument.
+func shellQuote(s string) string {
+ return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
+}
+
+// spoolWorkspace is the workspace an event's session runs in: its session.working_directory, or
+// the process cwd when the caller did not carry one.
+func spoolWorkspace(event map[string]interface{}) string {
+ cwd := ""
+ if session, ok := event["session"].(map[string]interface{}); ok {
+ cwd, _ = session["working_directory"].(string)
+ }
+ if strings.TrimSpace(cwd) == "" {
+ cwd, _ = os.Getwd()
+ }
+ return cwd
+}
+
+// spoolPathIsReal reports whether the components WorkspaceSpoolDir adds below the workspace --
+// .beacon, spool, <harness> and <session> -- are real directories and the spool file, if present,
+// a regular file no larger than a spool can grow. allowMissing lets components that do not exist
+// yet pass, for a writer that creates them.
+//
+// The sandboxed agent can write the workspace and knows its own session id, so it can plant the
+// session directory as a link to the account's own spool; the hook's drain, running outside the
+// sandbox, would then remove the lines it refuses from that spool. Spool.Append never lets the
+// file outgrow DefaultSpoolMaxBytes, so a larger one was written by hand and is not read. Lstat
+// checks the components themselves, from the session directory up, so a missing spool costs a
+// drain one stat.
+func spoolPathIsReal(dir string, allowMissing bool) bool {
+ file := localingest.Spool{Dir: dir}.FilePath()
+ for i := 0; i < 4; i, dir = i+1, filepath.Dir(dir) {
+ info, err := os.Lstat(dir)
+ switch {
+ case err == nil:
+ if !info.IsDir() {
+ return false
+ }
+ case allowMissing && os.IsNotExist(err):
+ default:
+ return false
+ }
+ }
+ info, err := os.Lstat(file)
+ return err != nil || (info.Mode().IsRegular() && info.Size() <= localingest.DefaultSpoolMaxBytes)
+}
+
+// ownSpoolDrainBatch bounds how many staged lines one hook delivers, so a long-sandboxed session's
+// backlog never makes a single hook slow; what is left waits for a sweep or a later process.
+const ownSpoolDrainBatch = 256
+
+// drainedOwnSpools remembers the spool directories this process has already drained, so a hook
+// that emits several events drains once rather than once per event.
+var drainedOwnSpools sync.Map
+
+// drainOwnWorkspaceSpool delivers, after this hook reached the runtime log at path, one batch of
+// what earlier hooks of the same session staged when they could not -- a session that leaves its
+// sandbox, or whose log comes back, catches up without waiting for a sweep.
+//
+// Only this hook's own session spool is drained: the hook knows its own session id is genuine, and
+// cannot know that of any other directory under the workspace, which anything able to write the
+// workspace (a cloned repository included) may have planted. Lines are untrusted all the same, so
+// each passes AdmitStagedLine first; a refused one counts as processed, discarded rather than
+// retried forever. A delivery error leaves it and the rest staged for the next drain.
+//
+// Everything here is best-effort and quiet: it never stages, never goes back through
+// EndpointEventWithFidelity, never writes stderr and never fails the hook. It drains only through
+// real directories (spoolPathIsReal), and Spool.Drain skips without waiting when another drainer
+// holds the spool. Each admitted line is decoded and written again through encodeEndpointLine, as
+// every line this hook writes is -- redacted, size-capped and stamped -- never appended byte for
+// byte. Like staging, a hook running as root never drains in a workspace another account owns:
+// the rewrite would leave that account's pending.jsonl root's.
+func (l *Logger) drainOwnWorkspaceSpool(path string, event map[string]interface{}) {
+ if l == nil || l.sessionID == "" {
+ return
+ }
+ harness := asymptoteobserve.NormalizeHarnessName(l.platform)
+ workspace := spoolWorkspace(event)
+ dir, ok := asymptoteobserve.WorkspaceSpoolDir(workspace, harness, l.sessionID)
+ if !ok || rootInAnotherAccountsWorkspace(workspace) {
+ return
+ }
+ if _, done := drainedOwnSpools.LoadOrStore(dir, true); done || !spoolPathIsReal(dir, false) {
+ return
+ }
+ _, _ = localingest.Spool{Dir: dir}.Drain(ownSpoolDrainBatch, func(lines [][]byte) (int, error) {
+ for i, line := range lines {
+ if !asymptoteobserve.AdmitStagedLine(line, harness, l.sessionID) {
+ continue
+ }
+ var staged map[string]interface{}
+ if err := json.Unmarshal(line, &staged); err != nil {
+ continue
+ }
+ encoded, err := encodeEndpointLine(staged)
+ if err != nil {
+ continue
+ }
+ if err := deliverEndpointLine(path, encoded); err != nil {
+ return i, err
+ }
+ }
+ return len(lines), nil
+ })
+}
+
// reportedWriteFailures remembers which runtime log paths this process has already explained a
// write failure for, so the explanation is printed once per path rather than once per event. One
// hook invocation can emit several events -- a post-tool hook records the tool result, the file
diff --git a/cli/beacon-hooks/internal/logging/spool_git.go b/cli/beacon-hooks/internal/logging/spool_git.go
index 261b1dba..c25684fa 100644
--- a/cli/beacon-hooks/internal/logging/spool_git.go
+++ b/cli/beacon-hooks/internal/logging/spool_git.go
@@ -7,20 +7,69 @@ import (
"strings"
)
+// spoolGitignore, in <workspace>/.beacon/spool/, ignores everything there, itself included.
+const spoolGitignore = "# Beacon staged hook events here; never commit them.\n*\n"
+
+// ensureSpoolGitignore makes sure the workspace spool at spoolRoot (<workspace>/.beacon/spool)
+// holds a .gitignore that ignores everything in it, and reports whether it does. Staging depends
+// on it: the spool holds prompts, raw hook payloads and diffs, which an agent's `git add -A` must
+// never pick up, and this file works however git is laid out -- a linked worktree, a .git the
+// sandbox mounts read-only or not at all, a repository root above the mount -- every case
+// ensureSpoolGitExclude cannot reach. Being the deepest ignore file, it overrides any negation
+// higher up.
+//
+// It is created when missing. One already there is kept, never overwritten, but it counts only
+// when it is a regular file that ignores `*` and negates nothing: a cloned repository can commit
+// its own .beacon/spool/.gitignore to switch the protection off, and staging next to it would hand
+// the session's prompts to the next commit.
+func ensureSpoolGitignore(spoolRoot string) bool {
+ if err := os.MkdirAll(spoolRoot, 0o700); err != nil {
+ return false
+ }
+ path := filepath.Join(spoolRoot, ".gitignore")
+ f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
+ if err == nil {
+ _, werr := f.WriteString(spoolGitignore)
+ cerr := f.Close()
+ return werr == nil && cerr == nil
+ }
+ if !os.IsExist(err) {
+ return false
+ }
+ info, err := os.Lstat(path)
+ if err != nil || !info.Mode().IsRegular() || info.Size() > 4096 {
+ return false
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return false
+ }
+ ignoresAll := false
+ for _, line := range strings.Split(string(data), "\n") {
+ switch line = strings.TrimSpace(line); {
+ case strings.HasPrefix(line, "!"):
+ return false
+ case line == "*":
+ ignoresAll = true
+ }
+ }
+ return ignoresAll
+}
+
// ensureSpoolGitExclude hides a freshly created spool directory from `git status` by adding
-// its workspace-relative path to the repository's .git/info/exclude.
+// its workspace-relative path to the repository's .git/info/exclude, alongside the spool's own
+// .gitignore (ensureSpoolGitignore), which also hides the .gitignore itself.
//
// The spool is telemetry that exists only while a sandboxed session is being captured, so an
-// untracked `.beacon/dsh-spool/` showing up in an operator's status output for the duration
-// is exactly the repository pollution the spool design has to avoid. .git/info/exclude (not
-// .gitignore) is the mechanism git reserves for local, unshared ignores, and it is the same
-// one Beacon's cloud setup script already uses for its repo-local files -- add-only, never
-// removed, because an entry naming a path that no longer exists is inert.
+// untracked `.beacon/spool/` showing up in an operator's status output for the duration
+// is exactly the repository pollution the spool design has to avoid. .git/info/exclude is the
+// mechanism git reserves for local, unshared ignores, and it is the same one Beacon's cloud setup
+// script already uses for its repo-local files -- add-only, never removed, because an entry naming
+// a path that no longer exists is inert.
//
-// Everything here is best-effort: a missing or unwritable exclude file means the directory
-// stays visible in git status, which costs a line of noise and no correctness. A linked
-// worktree (.git is a file, not a directory) is skipped rather than resolved -- writing into
-// a worktree's shared git dir from a telemetry hook is a step too far for a hint.
+// Everything here is best-effort: a missing or unwritable exclude file leaves the .gitignore
+// alone to do the job. A linked worktree (.git is a file, not a directory) is skipped rather than
+// resolved -- writing into a worktree's shared git dir from a telemetry hook is a step too far.
func ensureSpoolGitExclude(spoolDir string) {
root := gitRootAbove(spoolDir)
if root == "" {
diff --git a/cli/beacon-hooks/internal/logging/spool_owner_other.go b/cli/beacon-hooks/internal/logging/spool_owner_other.go
new file mode 100644
index 00000000..b2a66cdd
--- /dev/null
+++ b/cli/beacon-hooks/internal/logging/spool_owner_other.go
@@ -0,0 +1,6 @@
+//go:build !unix
+
+package logging
+
+// rootInAnotherAccountsWorkspace is never true off Unix, where no hook runs as uid 0.
+func rootInAnotherAccountsWorkspace(string) bool { return false }
diff --git a/cli/beacon-hooks/internal/logging/spool_owner_unix.go b/cli/beacon-hooks/internal/logging/spool_owner_unix.go
new file mode 100644
index 00000000..ad807c8c
--- /dev/null
+++ b/cli/beacon-hooks/internal/logging/spool_owner_unix.go
@@ -0,0 +1,27 @@
+//go:build unix
+
+package logging
+
+import (
+ "os"
+ "syscall"
+)
+
+// rootInAnotherAccountsWorkspace reports whether this hook runs as root in a workspace another
+// account owns -- typically a rootful container sandbox running the agent as uid 0 over the user's
+// bind-mounted checkout. Root must neither stage nor drain there. Staging would leave root-owned
+// 0700/0600 spool files the workspace's owner can neither drain (spool drain refuses root) nor
+// delete. Draining would rewrite the owner's pending.jsonl as root's, so the owner's own hooks
+// could no longer append to it. Root that owns the workspace -- uid 0 in a rootless container, the
+// user mapped -- stages and drains as any account does.
+func rootInAnotherAccountsWorkspace(workspace string) bool {
+ if os.Geteuid() != 0 {
+ return false
+ }
+ info, err := os.Stat(workspace)
+ if err != nil {
+ return true
+ }
+ st, ok := info.Sys().(*syscall.Stat_t)
+ return !ok || st.Uid != 0
+}
diff --git a/cli/beacon-hooks/internal/logging/spool_test.go b/cli/beacon-hooks/internal/logging/spool_test.go
index afa3d5cc..db36cb3c 100644
--- a/cli/beacon-hooks/internal/logging/spool_test.go
+++ b/cli/beacon-hooks/internal/logging/spool_test.go
@@ -11,17 +11,16 @@ import (
"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/localingest"
)
-// stagedSpoolFile is where a dsh hook stages events for sessionID in workspace.
-func stagedSpoolFile(workspace, sessionID string) string {
- return localingest.Spool{Dir: filepath.Join(workspace, ".beacon", "dsh-spool", sessionID)}.FilePath()
+// stagedSpoolFile is where a hook of harness stages events for sessionID in workspace.
+func stagedSpoolFile(workspace, harness, sessionID string) string {
+ return localingest.Spool{Dir: filepath.Join(workspace, ".beacon", "spool", harness, sessionID)}.FilePath()
}
// When the runtime log is unreachable but the workspace is writable -- the normal
// workspace-write sandbox DeepSeek Harness runs hooks in (#605) -- a dsh hook stages the
-// event in the session workspace instead of losing it. `beacon endpoint dsh sync` drains
-// that spool later; at capture time the event is recorded, so nothing is reported as lost
-// and stderr stays silent (one process per event: a note here would be a note on every
-// event).
+// event in the session workspace instead of losing it, to be drained later; at capture time
+// the event is recorded, so nothing is reported as lost and stderr stays silent (one process
+// per event: a note here would be a note on every event).
func TestDshSandboxedWriteStagesEventInWorkspaceSpool(t *testing.T) {
isolateHookHome(t)
@@ -43,7 +42,7 @@ func TestDshSandboxedWriteStagesEventInWorkspaceSpool(t *testing.T) {
if stderr != "" {
t.Fatalf("a staged event printed to stderr:\n%s", stderr)
}
- spool := stagedSpoolFile(workspace, "sess-stage-1")
+ spool := stagedSpoolFile(workspace, "deepseek_harness", "sess-stage-1")
data, err := os.ReadFile(spool)
if err != nil {
t.Fatalf("staged event not in spool: %v", err)
@@ -79,38 +78,251 @@ func TestDshSandboxedWriteStagesEventInWorkspaceSpool(t *testing.T) {
}
}
-// Only DeepSeek Harness gets a spool. Staging another runtime's events into a project
-// checkout would be new repository pollution with nothing to drain it, so a claude or cursor
-// hook that cannot write the log reports the loss exactly as before.
-func TestNonDshWriteFailureDoesNotStageASpool(t *testing.T) {
+// Staging is not DeepSeek Harness's alone: any harness whose hook is confined to the session
+// workspace (#1284) stages there under its own canonical name, and the hook carries on. The first
+// event a session stages prints one note naming the drain, since nothing tells the hook a sweep
+// will find the session; later ones are silent. Once a later hook of the same session reaches the
+// log, it drains that spool -- but only what AdmitStagedLine admits for this session and harness,
+// since anything that can write the workspace can write the spool.
+func TestOtherHarnessStagesThenDrainsOnItsNextWrite(t *testing.T) {
isolateHookHome(t)
- logPath := unwritableEndpointLog(t)
- t.Setenv("BEACON_ENDPOINT_LOG", logPath)
+ unwritable := unwritableEndpointLog(t)
+ t.Setenv("BEACON_ENDPOINT_LOG", unwritable)
workspace := t.TempDir()
- t.Chdir(workspace)
+ const sessionID = "sess-oc-1"
+ emit := func(message string) error {
+ logger := NewSessionLogger("tool-use", "opencode", sessionID)
+ return logger.EndpointEvent("tool.invoked", "tool", "info", message,
+ map[string]interface{}{
+ "session": map[string]interface{}{"id": sessionID, "working_directory": workspace},
+ })
+ }
var writeErr error
- stderr := captureStderr(t, func() {
- logger := NewSessionLogger("session-start", "cursor", "sess-notdsh")
- writeErr = logger.EndpointEvent("session.started", "session", "info", "Agent started",
- map[string]interface{}{
- "session": map[string]interface{}{"id": "sess-notdsh", "working_directory": workspace},
+ stderr := captureStderr(t, func() { writeErr = emit("staged while sandboxed") })
+ drainCmd := "beacon endpoint spool drain --log-path '" + unwritable + "' --workspace '" + workspace + "' --harness 'opencode' --session '" + sessionID + "'"
+ if writeErr != nil || strings.Contains(stderr, "NOT recorded") || !strings.Contains(stderr, drainCmd) {
+ t.Fatalf("staging = %v, stderr %q; want nil and one note naming this session's drain", writeErr, stderr)
+ }
+ if data, err := os.ReadFile(filepath.Join(workspace, ".beacon", "spool", ".gitignore")); err != nil || !strings.Contains(string(data), "\n*\n") {
+ t.Fatalf("the spool has no .gitignore hiding it from git: %q, %v", data, err)
+ }
+ spool := stagedSpoolFile(workspace, "opencode", sessionID)
+ data, err := os.ReadFile(spool)
+ if err != nil {
+ t.Fatalf("opencode event not staged in its workspace spool: %v", err)
+ }
+ if stderr = captureStderr(t, func() { writeErr = emit("staged again") }); writeErr != nil || stderr != "" {
+ t.Fatalf("second staged event = %v, stderr %q; want a silent nil", writeErr, stderr)
+ }
+
+ // Lines planted next to the genuine one, each differing from it in one field the drain must
+ // check: another session, another harness, and an action only Beacon writes.
+ var planted [][]byte
+ for _, mutate := range []func(map[string]interface{}){
+ func(e map[string]interface{}) { e["session"].(map[string]interface{})["id"] = "sess-other" },
+ func(e map[string]interface{}) { e["harness"].(map[string]interface{})["name"] = "claude_code" },
+ func(e map[string]interface{}) {
+ e["event"].(map[string]interface{})["action"] = "session.share_requested"
+ },
+ } {
+ var event map[string]interface{}
+ if err := json.Unmarshal([]byte(strings.TrimSpace(string(data))), &event); err != nil {
+ t.Fatal(err)
+ }
+ mutate(event)
+ event["message"] = "planted"
+ line, err := json.Marshal(event)
+ if err != nil {
+ t.Fatal(err)
+ }
+ planted = append(planted, line)
+ }
+ // And one the drain admits -- this session, this harness -- written by hand with a secret in
+ // it: the drain writes it the way the hook writes every line, redacted, never byte for byte.
+ const secret = "ghp_wJalrXUtnFEMIK7MDENGbPxRfiCYEXAMPLE1"
+ var admitted map[string]interface{}
+ if err := json.Unmarshal([]byte(strings.TrimSpace(string(data))), &admitted); err != nil {
+ t.Fatal(err)
+ }
+ admitted["message"] = "hand-written " + secret
+ handWritten, err := json.Marshal(admitted)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := (localingest.Spool{Dir: filepath.Dir(spool)}).Append(append(planted, handWritten)); err != nil {
+ t.Fatal(err)
+ }
+
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ t.Setenv("BEACON_ENDPOINT_LOG", logPath)
+ stderr = captureStderr(t, func() { writeErr = emit("written directly") })
+ if writeErr != nil || stderr != "" {
+ t.Fatalf("direct write = %v, stderr %q", writeErr, stderr)
+ }
+ logData, err := os.ReadFile(logPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ log := string(logData)
+ for _, want := range []string{"written directly", "staged while sandboxed", "staged again"} {
+ if strings.Count(log, want) != 1 {
+ t.Errorf("log holds %q %d times, want once:\n%s", want, strings.Count(log, want), log)
+ }
+ }
+ if strings.Contains(log, "planted") {
+ t.Errorf("a planted spool line reached the log:\n%s", log)
+ }
+ if !strings.Contains(log, "hand-written") || strings.Contains(log, secret) {
+ t.Errorf("an admitted spool line was not written through the hook's encoder (redacted):\n%s", log)
+ }
+ if _, err := os.Stat(spool); !os.IsNotExist(err) {
+ t.Errorf("spool still holds lines after the drain (refused ones must be discarded): %v", err)
+ }
+}
+
+// A rootful container sandbox runs the agent as uid 0 over the user's bind-mounted checkout. Staged
+// there, the spool would be root's 0700/0600 files the user could neither drain nor delete, so the
+// event is reported as not recorded instead. Root that owns the workspace (uid 0 in a rootless
+// container owns the mapped one) stages as any account does.
+func TestRootStagesOnlyInAWorkspaceItOwns(t *testing.T) {
+ if runtime.GOOS == "windows" || os.Geteuid() != 0 {
+ t.Skip("needs root")
+ }
+ isolateHookHome(t)
+ t.Setenv("BEACON_ENDPOINT_LOG", unwritableEndpointLog(t))
+ emit := func(session, workspace string) (error, string) {
+ var writeErr error
+ stderr := captureStderr(t, func() {
+ writeErr = NewSessionLogger("tool-use", "opencode", session).EndpointEvent("tool.invoked", "tool", "info", "as root",
+ map[string]interface{}{"session": map[string]interface{}{"id": session, "working_directory": workspace}})
+ })
+ return writeErr, stderr
+ }
+
+ users := t.TempDir()
+ if err := os.Chown(users, 1000, 1000); err != nil {
+ t.Fatal(err)
+ }
+ if writeErr, stderr := emit("sess-root-1", users); writeErr == nil || !strings.Contains(stderr, "NOT recorded") {
+ t.Fatalf("root's unwritten event in another account's workspace = %v, stderr %q; want it reported as not recorded", writeErr, stderr)
+ }
+ if _, err := os.Stat(filepath.Join(users, ".beacon")); !os.IsNotExist(err) {
+ t.Fatalf("root staged in another account's workspace: %v", err)
+ }
+
+ own := t.TempDir()
+ if writeErr, _ := emit("sess-root-2", own); writeErr != nil {
+ t.Fatalf("root did not stage in a workspace it owns: %v", writeErr)
+ }
+ if _, err := os.Stat(stagedSpoolFile(own, "opencode", "sess-root-2")); err != nil {
+ t.Fatalf("root's own workspace holds no spool: %v", err)
+ }
+}
+
+// A cloned repository can commit its own .beacon/spool/.gitignore that does not ignore the spool.
+// Staged next to it, the session's prompts would go into the agent's next `git add -A`, so nothing
+// is staged and the event is reported as not recorded; the repository's file is left as it is.
+func TestNoStagingNextToAGitignoreThatDoesNotHideTheSpool(t *testing.T) {
+ isolateHookHome(t)
+ t.Setenv("BEACON_ENDPOINT_LOG", unwritableEndpointLog(t))
+ for name, content := range map[string]string{"empty": "", "negated": "*\n!*.jsonl\n"} {
+ t.Run(name, func(t *testing.T) {
+ workspace := t.TempDir()
+ gitignore := filepath.Join(workspace, ".beacon", "spool", ".gitignore")
+ if err := os.MkdirAll(filepath.Dir(gitignore), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(gitignore, []byte(content), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ var writeErr error
+ captureStderr(t, func() {
+ writeErr = NewSessionLogger("tool-use", "opencode", "sess-gi").EndpointEvent("tool.invoked", "tool", "info", "next to a planted .gitignore",
+ map[string]interface{}{"session": map[string]interface{}{"id": "sess-gi", "working_directory": workspace}})
})
+ if writeErr == nil {
+ t.Fatal("an event next to a planted .gitignore was reported recorded")
+ }
+ if _, err := os.Stat(stagedSpoolFile(workspace, "opencode", "sess-gi")); !os.IsNotExist(err) {
+ t.Fatalf("an event was staged next to a .gitignore that does not hide it: %v", err)
+ }
+ if data, _ := os.ReadFile(gitignore); string(data) != content {
+ t.Fatalf("the repository's .gitignore was changed: %q", data)
+ }
+ })
+ }
+}
+
+// A share request is an action only Beacon writes, which every drain refuses. Staged, it would be
+// discarded and the session, already marked as requested, never shared; so it is not staged, the
+// write fails, and the caller takes its mark back.
+func TestShareRequestIsNeverStaged(t *testing.T) {
+ isolateHookHome(t)
+ t.Setenv("BEACON_ENDPOINT_LOG", unwritableEndpointLog(t))
+ workspace := t.TempDir()
+ var writeErr error
+ captureStderr(t, func() {
+ writeErr = NewSessionLogger("session-start", "opencode", "sess-share-1").EndpointEventWithFidelity(
+ "session.share_requested", "session", "info", "Auto-share requested for this session", "inferred",
+ map[string]interface{}{"session": map[string]interface{}{"id": "sess-share-1", "working_directory": workspace}})
})
if writeErr == nil {
- t.Fatal("EndpointEvent returned nil; the caller could not tell the event was lost")
- }
- if !strings.Contains(stderr, "this event was NOT recorded") {
- t.Fatalf("stderr lacks the NOT-recorded explanation:\n%s", stderr)
+ t.Fatal("an unwritten share request was reported recorded")
}
if _, err := os.Stat(filepath.Join(workspace, ".beacon")); !os.IsNotExist(err) {
- t.Errorf("a non-dsp hook created a spool directory in the workspace: %v", err)
+ t.Fatalf("a share request was staged: %v", err)
+ }
+}
+
+// A workspace can plant its session directory as a link to another directory the user owns -- the
+// account's own spool, say. Draining through it would discard that spool's lines as refused, and
+// staging through it would write into it, so the hook does neither.
+func TestSpoolDirPlantedAsALinkIsNeitherDrainedNorWritten(t *testing.T) {
+ isolateHookHome(t)
+ workspace := t.TempDir()
+ const sessionID = "sess-link-1"
+ victim := localingest.Spool{Dir: t.TempDir()}
+ if _, err := victim.Append([][]byte{[]byte(`{"belongs":"elsewhere"}`)}); err != nil {
+ t.Fatal(err)
+ }
+ before, err := os.ReadFile(victim.FilePath())
+ if err != nil {
+ t.Fatal(err)
+ }
+ harnessDir := filepath.Join(workspace, ".beacon", "spool", "opencode")
+ if err := os.MkdirAll(harnessDir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(victim.Dir, filepath.Join(harnessDir, sessionID)); err != nil {
+ t.Skipf("cannot create a symlink here: %v", err)
+ }
+ emit := func() error {
+ logger := NewSessionLogger("tool-use", "opencode", sessionID)
+ return logger.EndpointEvent("tool.invoked", "tool", "info", "through a link",
+ map[string]interface{}{
+ "session": map[string]interface{}{"id": sessionID, "working_directory": workspace},
+ })
+ }
+
+ t.Setenv("BEACON_ENDPOINT_LOG", filepath.Join(t.TempDir(), "runtime.jsonl"))
+ if err := emit(); err != nil {
+ t.Fatalf("direct write: %v", err)
+ }
+ t.Setenv("BEACON_ENDPOINT_LOG", unwritableEndpointLog(t))
+ var writeErr error
+ captureStderr(t, func() { writeErr = emit() })
+ if writeErr == nil {
+ t.Error("an event was reported recorded although its only spool path runs through a link")
+ }
+ if after, err := os.ReadFile(victim.FilePath()); err != nil || string(after) != string(before) {
+ t.Fatalf("the linked-to spool changed: %q (%v), want %q", after, err, before)
}
}
// An unsafe session id must not produce a spool file anywhere: writer and drainer agree via
-// ValidDSHSessionIDForSpool that such ids get no spool, so a path-shaped id can neither
-// escape the spool directory nor strand events where no drain will ever look.
+// ValidSpoolName that such ids get no spool, so a path-shaped id can neither escape the spool
+// directory nor strand events where no drain will ever look.
func TestUnsafeSessionIDFallsBackToReportedLoss(t *testing.T) {
isolateHookHome(t)
logPath := unwritableEndpointLog(t)
@@ -207,7 +419,7 @@ func TestFirstSpoolUseExcludesTheDirectoryFromGitStatus(t *testing.T) {
if err != nil {
t.Fatalf("exclude file not written: %v", err)
}
- want := "pkg/app/.beacon/dsh-spool/"
+ want := "pkg/app/.beacon/spool/"
if got := strings.Count(string(data), want); got != 1 {
t.Fatalf("exclude lists %q %d times, want once:\n%s", want, got, data)
}
@@ -231,7 +443,7 @@ func TestSpoolOutsideAGitWorktreeSkipsContainment(t *testing.T) {
}); err != nil {
t.Fatalf("staged write outside a repo: %v", err)
}
- spool := stagedSpoolFile(workspace, "sess-nogit-1")
+ spool := stagedSpoolFile(workspace, "deepseek_harness", "sess-nogit-1")
if _, err := os.Stat(spool); err != nil {
t.Fatalf("spool file missing outside a repo: %v", err)
}
diff --git a/cli/beacon/cmd/endpoint_backfill.go b/cli/beacon/cmd/endpoint_backfill.go
index c695eadd..3142391a 100644
--- a/cli/beacon/cmd/endpoint_backfill.go
+++ b/cli/beacon/cmd/endpoint_backfill.go
@@ -34,6 +34,7 @@ import (
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/primesession"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionsync"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/workspacespool"
"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/filelock"
)
@@ -606,10 +607,49 @@ func sweepEndpointBackfill(logPath string, userMode bool, sweep endpointSweep) e
result.Runtimes = append(result.Runtimes, runtime)
}
}
+ if userMode && !sessionfs.Active() {
+ if runtime, ok := drainWorkspaceSpools(logPath, total); ok {
+ result.Events += runtime.Events
+ result.Limited = result.Limited || runtime.Limited
+ result.Runtimes = append(result.Runtimes, runtime)
+ }
+ }
result.Bytes = total.Used()
return result
}
+// drainWorkspaceSpools moves the events sandboxed hooks staged in session workspaces (#605, #1284)
+// into the runtime log, within the sweep's budget like every runtime. The sessions are the ones
+// Beacon has recorded plus those under the operator's workspace_spool_roots, so a spool planted in
+// a cloned repository for an invented session is never read. Only a user sweep drains: root must
+// not write or remove files in a user's workspace, and the user's own sweep reaches them. ok is
+// false when there is nothing to report.
+func drainWorkspaceSpools(logPath string, total *writer.Budget) (endpointBackfillRuntimeResult, bool) {
+ if logPath == "" {
+ // The sink's writer appends to the default path then; the recorded sessions are there.
+ logPath = writer.DefaultPath(true)
+ }
+ var roots []string
+ if cfg, err := endpointconfig.Load(true); err == nil {
+ roots = cfg.WorkspaceSpoolRoots
+ }
+ sessions, err := workspacespool.Discover(logPath, roots, nil)
+ share := total.Sub(endpointBackfillShareBytes)
+ sink := sessionsync.Sink{Write: true, Log: writer.Options{Path: logPath, UserMode: true, Budget: share}}
+ sink.GuardRetention()
+ var summary workspacespool.Summary
+ err = errors.Join(err, workspacespool.Drain(sessions, sink.Emit, &summary))
+ runtime := endpointBackfillRuntimeResult{Name: "Workspace spools", Sync: "beacon endpoint spool drain", Events: summary.Events}
+ if sessionsync.Stopped(err) || share.Refused() {
+ runtime.Limited = true
+ }
+ runtime.RetentionLimited = errors.Is(err, writer.ErrRetentionWindowFull)
+ if err != nil && !onlyStopped(err) {
+ runtime.Err = err
+ }
+ return runtime, runtime.Events > 0 || runtime.Limited || runtime.Err != nil
+}
+
// onlyStopped reports whether err says nothing but that the sweep stopped early: the budget ran
// out, or writing more would have rotated the sweep's own output out of the log. Either way the
// collector's cursors stop at what was written and the runtime's sync reads the rest.
diff --git a/cli/beacon/cmd/endpoint_backfill_spool_test.go b/cli/beacon/cmd/endpoint_backfill_spool_test.go
new file mode 100644
index 00000000..98dec4d7
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_backfill_spool_test.go
@@ -0,0 +1,69 @@
+package cmd
+
+import (
+ "encoding/json"
+ "path/filepath"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/localingest"
+)
+
+func spoolSweepEvent(t *testing.T, workspace, sessionID, action string) schema.Event {
+ t.Helper()
+ event := schema.NewEvent(schema.NewEventOptions{
+ Action: action,
+ Category: "agent",
+ Severity: schema.SeverityInfo,
+ Harness: schema.HarnessInfo{Name: "opencode", CollectionMethod: asymptoteobserve.CollectionMethodPlugin},
+ Message: action + " " + sessionID,
+ })
+ event.Session = &schema.SessionInfo{ID: sessionID, WorkingDirectory: workspace}
+ return event
+}
+
+func stageSpoolSweepEvent(t *testing.T, workspace, sessionID string) localingest.Spool {
+ t.Helper()
+ dir, ok := asymptoteobserve.WorkspaceSpoolDir(workspace, "opencode", sessionID)
+ if !ok {
+ t.Fatalf("unsafe test session id %q", sessionID)
+ }
+ line, err := json.Marshal(spoolSweepEvent(t, workspace, sessionID, "prompt.submitted"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ spool := localingest.Spool{Dir: dir}
+ if dropped, err := spool.Append([][]byte{line}); err != nil || dropped != 0 {
+ t.Fatalf("stage: dropped %d, err %v", dropped, err)
+ }
+ return spool
+}
+
+// A user sweep drains the spool of a session Beacon has recorded in that workspace, and leaves a
+// spool for a session it never saw -- one a cloned repository could carry -- where it is.
+func TestSweepDrainsWorkspaceSpoolsOfKnownSessionsOnly(t *testing.T) {
+ testenv.SetHome(t, t.TempDir())
+ stubBackfill(t, 1<<20, 1<<19)
+ workspace := t.TempDir()
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ if _, err := writer.AppendEvent(spoolSweepEvent(t, workspace, "s1", "session.started"), writer.Options{Path: logPath, UserMode: true}); err != nil {
+ t.Fatal(err)
+ }
+ known := stageSpoolSweepEvent(t, workspace, "s1")
+ planted := stageSpoolSweepEvent(t, workspace, "invented")
+
+ result := sweepEndpointBackfill(logPath, true, endpointSweep{})
+
+ if result.Events != 1 || len(result.Runtimes) != 1 || result.Runtimes[0].Name != "Workspace spools" || result.Runtimes[0].Events != 1 {
+ t.Fatalf("result = %+v, want one drained event under Workspace spools", result)
+ }
+ if lines, _, err := known.Pending(); err != nil || lines != 0 {
+ t.Fatalf("known session's spool holds %d lines (err %v), want it drained", lines, err)
+ }
+ if lines, _, err := planted.Pending(); err != nil || lines != 1 {
+ t.Fatalf("unknown session's spool holds %d lines (err %v), want it left alone", lines, err)
+ }
+}
diff --git a/cli/beacon/cmd/endpoint_diagnostics.go b/cli/beacon/cmd/endpoint_diagnostics.go
index 2e0bc83b..98022e8a 100644
--- a/cli/beacon/cmd/endpoint_diagnostics.go
+++ b/cli/beacon/cmd/endpoint_diagnostics.go
@@ -194,6 +194,13 @@ func buildDoctorResult(status lifecycle.Status, generatedAt time.Time) doctorRes
if check, ok := gitHookBudgetCheck(status.LogPath, generatedAt); ok {
checks = append(checks, check)
}
+ var spoolRoots []string
+ if cfg, err := endpointconfig.Load(status.RuntimeLog.EffectiveUserMode); err == nil {
+ spoolRoots = cfg.WorkspaceSpoolRoots
+ }
+ if check, ok := doctorWorkspaceSpoolCheck(status.LogPath, spoolRoots); ok {
+ checks = append(checks, check)
+ }
result := doctorResult{
Status: aggregateCheckStatus(checks),
Checks: checks,
diff --git a/cli/beacon/cmd/endpoint_dsh_spool_test.go b/cli/beacon/cmd/endpoint_dsh_spool_test.go
index d7fcceb8..dd48ccce 100644
--- a/cli/beacon/cmd/endpoint_dsh_spool_test.go
+++ b/cli/beacon/cmd/endpoint_dsh_spool_test.go
@@ -52,7 +52,7 @@ func jsonString(s string) string {
// would, and returns the staged byte count.
func plantSpool(t *testing.T, workspace, id string) int {
t.Helper()
- dir, ok := asymptoteobserve.DSHSpoolDir(workspace, id)
+ dir, ok := asymptoteobserve.WorkspaceSpoolDir(workspace, "deepseek_harness", id)
if !ok {
t.Fatalf("unsafe test session id %q", id)
}
@@ -126,7 +126,7 @@ func TestDshHookCapturePendingDrainClearsOnceTheSpoolIsEmpty(t *testing.T) {
// Drain: the events land in the log as hook events and the spool file goes away.
f.event(t, "hook", f.installedAt.Add(2*time.Hour))
- dir, _ := asymptoteobserve.DSHSpoolDir(workspace, "pending-1")
+ dir, _ := asymptoteobserve.WorkspaceSpoolDir(workspace, "deepseek_harness", "pending-1")
if err := os.Remove((localingest.Spool{Dir: dir}).FilePath()); err != nil {
t.Fatal(err)
}
diff --git a/cli/beacon/cmd/endpoint_spool.go b/cli/beacon/cmd/endpoint_spool.go
new file mode 100644
index 00000000..8000cdbf
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_spool.go
@@ -0,0 +1,277 @@
+package cmd
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/dshsession"
+ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/diagnostics"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/workspacespool"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+ "github.com/spf13/cobra"
+)
+
+var endpointSpoolCmd = &cobra.Command{
+ Use: "spool",
+ Short: "Drain hook events staged in workspace spools",
+ Long: `Drain hook events that sandboxed agents staged in their session workspace.
+
+A hook that cannot reach the ingest socket, the runtime log or an account spool
+(for example inside a sandbox that confines writes to the session workspace)
+stages its event under <workspace>/.beacon/spool/<harness>/<session>/. Beacon
+drains those spools into the runtime log for sessions it has already recorded,
+and for every session under the configured workspace_spool_roots.`,
+}
+
+var endpointSpoolDrainCmd = &cobra.Command{
+ Use: "drain",
+ Short: "Append staged hook events to the runtime log",
+ SilenceUsage: true,
+ RunE: runEndpointSpoolDrain,
+}
+
+var endpointSpoolStatusCmd = &cobra.Command{
+ Use: "status",
+ Short: "List workspace spools holding staged hook events",
+ SilenceUsage: true,
+ RunE: runEndpointSpoolStatus,
+}
+
+var endpointSpoolOpts struct {
+ workspaces []string
+ logPath string
+ harness string
+ session string
+}
+
+// endpointSpoolGeteuid is a seam so tests can exercise the root refusal without running as root.
+var endpointSpoolGeteuid = os.Geteuid
+
+func init() {
+ endpointCmd.AddCommand(endpointSpoolCmd)
+ endpointSpoolCmd.AddCommand(endpointSpoolDrainCmd)
+ endpointSpoolCmd.AddCommand(endpointSpoolStatusCmd)
+
+ for _, c := range []*cobra.Command{endpointSpoolDrainCmd, endpointSpoolStatusCmd} {
+ f := c.Flags()
+ f.StringArrayVar(&endpointSpoolOpts.workspaces, "workspace", nil, "Also include every session spool in this workspace, taken literally (repeatable)")
+ f.StringVar(&endpointSpoolOpts.harness, "harness", "", "Only spools of this harness (for example opencode)")
+ f.StringVar(&endpointSpoolOpts.session, "session", "", "Only spools of this session id")
+ f.StringVar(&endpointSpoolOpts.logPath, "log-path", "", "Runtime JSONL log path (default resolved endpoint log)")
+ f.BoolVar(&endpointOpts.jsonOutput, "json", false, "Print the result as JSON")
+ f.BoolVar(&endpointOpts.userMode, "user", true, "Use per-user endpoint paths")
+ f.BoolVar(&endpointOpts.systemMode, "system", false, "Use system endpoint paths")
+ }
+}
+
+// spoolScope is what a spool command looks at: the runtime log whose sessions it knows, the
+// configured roots (globs), and the --workspace paths, which stay literal (a workspace whose name
+// holds `[` or `*` is still that one workspace).
+type spoolScope struct {
+ logPath string
+ roots []string
+ workspaces []string
+ // note says why the configured roots are missing, when the config could not be read.
+ note string
+}
+
+// resolveSpoolScope reads the endpoint config for the log and the roots. A config this account
+// cannot read -- a system config holding a destination secret is root-only, and root may not
+// drain -- is not guessed around: the log it names may be anywhere, and a drain aimed at the
+// default path would deliver to a log no collector reads. Without --log-path the scope then has no
+// log (unreadable is set): status lists only --workspace spools, and drain refuses, naming the
+// flag. A missing config is another matter: the writers then use the default path, and so does
+// the scope.
+func resolveSpoolScope(userMode bool) (spoolScope, error) {
+ var scope spoolScope
+ cfg, err := endpointconfig.Load(userMode)
+ unreadable := false
+ switch {
+ case err == nil, os.IsNotExist(err):
+ case errors.Is(err, os.ErrPermission):
+ unreadable = true
+ default:
+ return scope, err
+ }
+ for _, ws := range endpointSpoolOpts.workspaces {
+ abs, err := filepath.Abs(ws)
+ if err != nil {
+ return scope, fmt.Errorf("workspace %q: %w", ws, err)
+ }
+ scope.workspaces = append(scope.workspaces, abs)
+ }
+ if unreadable && endpointSpoolOpts.logPath == "" {
+ scope.note = fmt.Sprintf("cannot read the endpoint config (%v), which names the runtime log; pass --log-path with that log", err)
+ return scope, nil
+ }
+ if unreadable {
+ scope.note = fmt.Sprintf("cannot read the endpoint config (%v); no configured roots are searched", err)
+ }
+ override := endpointSpoolOpts.logPath
+ if override == "" {
+ override = cfg.LogPath
+ }
+ scope.logPath = lifecycle.ResolveRuntimeLog(userMode, override).EffectiveLogPath
+ if scope.logPath == "" {
+ // No installed log named anywhere: the writers append to the default path, so the
+ // sessions they recorded are there.
+ scope.logPath = writer.DefaultPath(userMode)
+ }
+ scope.roots = cfg.WorkspaceSpoolRoots
+ return scope, nil
+}
+
+// sessions is every session the scope covers, narrowed to --harness and --session. Narrowed, a
+// --workspace vouches for that one session only, never for every spool a cloned repository
+// planted beside it: the command a hook prints for a staged session names all three.
+func (s spoolScope) sessions() ([]workspacespool.Session, error) {
+ all, err := workspacespool.Discover(s.logPath, s.roots, s.workspaces)
+ harness := asymptoteobserve.NormalizeHarnessName(endpointSpoolOpts.harness)
+ var out []workspacespool.Session
+ for _, session := range all {
+ if (endpointSpoolOpts.harness == "" || session.Harness == harness) && (endpointSpoolOpts.session == "" || session.ID == endpointSpoolOpts.session) {
+ out = append(out, session)
+ }
+ }
+ return out, err
+}
+
+func runEndpointSpoolDrain(cmd *cobra.Command, args []string) error {
+ // Root never writes or removes files under a user's workspace: a drain run as root could be
+ // steered by a planted link into touching files the user's account could not.
+ if endpointSpoolGeteuid() == 0 {
+ return errors.New("refusing to drain workspace spools as root; run `beacon endpoint spool drain` as the user who owns the workspace")
+ }
+ userMode := endpointUserMode()
+ scope, err := resolveSpoolScope(userMode)
+ if err != nil {
+ return err
+ }
+ if scope.logPath == "" {
+ return errors.New(scope.note)
+ }
+ logPath := scope.logPath
+ // The user-mode sweep drains these same spools, so wait for it rather than race it. The
+ // system-mode root sweep never drains workspace spools, so there is nothing to wait for.
+ if userMode {
+ release, err := acquireEndpointSweepLock(true, endpointSweepLockWait)
+ if err != nil {
+ return err
+ }
+ defer release()
+ }
+ out := cmd.OutOrStdout()
+ if scope.note != "" && !endpointOpts.jsonOutput {
+ fmt.Fprintf(out, "note: %s\n", scope.note)
+ }
+ sessions, discoverErr := scope.sessions()
+ if discoverErr != nil && !endpointOpts.jsonOutput {
+ // A system log this account cannot read hides only the known sessions; the roots and
+ // --workspace still name spools worth draining.
+ fmt.Fprintf(out, "note: could not list sessions from %s: %v\n", logPath, discoverErr)
+ }
+ emit := func(event schema.Event) error {
+ // No Budget or Guard: an ordinary user in system mode goes through the ingest socket.
+ _, err := writer.AppendEvent(event, writer.Options{Path: logPath, UserMode: userMode})
+ return err
+ }
+ var summary workspacespool.Summary
+ drainErr := workspacespool.Drain(sessions, emit, &summary)
+ if endpointOpts.jsonOutput {
+ if err := json.NewEncoder(out).Encode(summary); err != nil {
+ return err
+ }
+ } else {
+ fmt.Fprintf(out, "workspace spool drain: %d sessions, %d events, %d rejected\n",
+ summary.Sessions, summary.Events, summary.Rejected)
+ if summary.Rejected > 0 {
+ fmt.Fprintln(out, " rejected lines were unreadable, or not a hook event of the session whose spool held them")
+ }
+ }
+ return drainErr
+}
+
+type spoolPendingStatus struct {
+ Workspace string `json:"workspace"`
+ Harness string `json:"harness"`
+ SessionID string `json:"session_id"`
+ Bytes int64 `json:"bytes"`
+}
+
+func pendingSpools(sessions []workspacespool.Session) []spoolPendingStatus {
+ pending := []spoolPendingStatus{}
+ for _, s := range sessions {
+ if n := workspacespool.PendingBytes(s); n > 0 {
+ pending = append(pending, spoolPendingStatus{Workspace: s.Workspace, Harness: s.Harness, SessionID: s.ID, Bytes: n})
+ }
+ }
+ return pending
+}
+
+func runEndpointSpoolStatus(cmd *cobra.Command, args []string) error {
+ scope, err := resolveSpoolScope(endpointUserMode())
+ if err != nil {
+ return err
+ }
+ sessions, discoverErr := scope.sessions()
+ pending := pendingSpools(sessions)
+ out := cmd.OutOrStdout()
+ if endpointOpts.jsonOutput {
+ return json.NewEncoder(out).Encode(struct {
+ Sessions []spoolPendingStatus `json:"sessions"`
+ }{pending})
+ }
+ if scope.note != "" {
+ fmt.Fprintf(out, "note: %s\n", scope.note)
+ }
+ if discoverErr != nil {
+ fmt.Fprintf(out, "note: could not list sessions from %s: %v\n", scope.logPath, discoverErr)
+ }
+ if len(pending) == 0 {
+ fmt.Fprintln(out, "workspace spools: nothing staged")
+ return nil
+ }
+ fmt.Fprintf(out, "workspace spools: %d session(s) with staged events\n", len(pending))
+ for _, p := range pending {
+ fmt.Fprintf(out, " %s %s %s %dB\n", p.Workspace, p.Harness, p.SessionID, p.Bytes)
+ }
+ return nil
+}
+
+// doctorWorkspaceSpoolCheck is a seam so doctor tests can stub the spool scan.
+var doctorWorkspaceSpoolCheck = workspaceSpoolCheck
+
+// workspaceSpoolCheck reports hook events staged in workspace spools. Like
+// dsh_spool_pending_drain, staged events mean capture worked and only the drain is missing.
+// DeepSeek Harness sessions are left to that check, so one spool is never reported twice.
+func workspaceSpoolCheck(logPath string, roots []string) (diagnostics.Check, bool) {
+ found, _ := workspacespool.Discover(logPath, roots, nil)
+ pending := pendingSpools(found)
+ sessions := 0
+ for _, p := range pending {
+ if p.Harness != dshsession.Harness {
+ sessions++
+ }
+ }
+ if sessions == 0 {
+ return diagnostics.Check{}, false
+ }
+ return diagnostics.Check{
+ Name: "workspace_spool",
+ Target: "workspace_spool",
+ Status: diagnostics.StatusWarn,
+ Severity: diagnostics.SeverityLow,
+ Evidence: "workspace_spool_pending_drain",
+ Message: fmt.Sprintf(
+ "%d session(s) have hook events staged in their workspace spool; capture is working, but the events are not in %s yet",
+ sessions, logPath),
+ Action: "run `beacon endpoint spool drain` as the user who owns the workspace",
+ }, true
+}
diff --git a/cli/beacon/cmd/endpoint_spool_test.go b/cli/beacon/cmd/endpoint_spool_test.go
new file mode 100644
index 00000000..dc6abab6
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_spool_test.go
@@ -0,0 +1,220 @@
+package cmd
+
+import (
+ "bytes"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+
+ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/diagnostics"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/localingest"
+ "github.com/spf13/cobra"
+)
+
+// plantWorkspaceSpool stages one hook event for (harness, id) in workspace, the way a sandboxed
+// hook would, and returns the staged byte count.
+func plantWorkspaceSpool(t *testing.T, workspace, harness, id string) int {
+ t.Helper()
+ dir, ok := asymptoteobserve.WorkspaceSpoolDir(workspace, harness, id)
+ if !ok {
+ t.Fatalf("unsafe test spool %q/%q", harness, id)
+ }
+ body := `{"timestamp":"2026-11-13T12:00:00Z","vendor":"beacon","product":"endpoint-agent",` +
+ `"schema_version":"1.0","event":{"kind":"agent_runtime","action":"prompt.submitted"},` +
+ `"severity":"info","endpoint":{"os":"darwin"},"session":{"id":"` + id + `"},` +
+ `"harness":{"name":"` + harness + `","collection_method":"hook"}}`
+ if dropped, err := (localingest.Spool{Dir: dir}).Append([][]byte{[]byte(body)}); err != nil || dropped != 0 {
+ t.Fatalf("plant spool: dropped %d, err %v", dropped, err)
+ }
+ return len(body) + 1
+}
+
+// spoolCommandEnv points every user-mode path at a temp home and returns the runtime log path.
+func spoolCommandEnv(t *testing.T) string {
+ t.Helper()
+ t.Setenv("HOME", t.TempDir())
+ opts, endpointOptsState, euid := endpointSpoolOpts, endpointOpts, endpointSpoolGeteuid
+ t.Cleanup(func() {
+ endpointSpoolOpts, endpointOpts, endpointSpoolGeteuid = opts, endpointOptsState, euid
+ })
+ endpointSpoolGeteuid = func() int { return 1000 }
+ endpointOpts.userMode, endpointOpts.systemMode, endpointOpts.jsonOutput = true, false, false
+ logPath := filepath.Join(t.TempDir(), "events.jsonl")
+ endpointSpoolOpts.logPath = logPath
+ endpointSpoolOpts.workspaces, endpointSpoolOpts.harness, endpointSpoolOpts.session = nil, "", ""
+ return logPath
+}
+
+func runSpoolCmd(t *testing.T, run func(*cobra.Command, []string) error) (string, error) {
+ t.Helper()
+ out := &bytes.Buffer{}
+ cmd := &cobra.Command{}
+ cmd.SetOut(out)
+ cmd.SetErr(out)
+ err := run(cmd, nil)
+ return out.String(), err
+}
+
+// Root never writes or removes files in a user's workspace, so the drain refuses outright and
+// says whose account should run it.
+func TestEndpointSpoolDrainRefusesRoot(t *testing.T) {
+ spoolCommandEnv(t)
+ endpointSpoolGeteuid = func() int { return 0 }
+ _, err := runSpoolCmd(t, runEndpointSpoolDrain)
+ if err == nil || !strings.Contains(err.Error(), "as the user who owns the workspace") {
+ t.Fatalf("drain as root: err = %v, want a refusal naming the workspace owner", err)
+ }
+}
+
+// An explicit --workspace vouches for its spools even when the log has never seen the session.
+func TestEndpointSpoolDrainExplicitWorkspace(t *testing.T) {
+ logPath := spoolCommandEnv(t)
+ workspace := t.TempDir()
+ plantWorkspaceSpool(t, workspace, "gemini_cli", "sess-1")
+ endpointSpoolOpts.workspaces = []string{workspace}
+ endpointOpts.jsonOutput = true
+
+ out, err := runSpoolCmd(t, runEndpointSpoolDrain)
+ if err != nil {
+ t.Fatalf("drain: %v\n%s", err, out)
+ }
+ var summary struct{ Sessions, Events, Rejected int }
+ if err := json.Unmarshal([]byte(out), &summary); err != nil {
+ t.Fatalf("drain JSON: %v\n%s", err, out)
+ }
+ if summary.Sessions != 1 || summary.Events != 1 || summary.Rejected != 0 {
+ t.Fatalf("summary = %+v, want 1 session, 1 event, 0 rejected", summary)
+ }
+ data, err := os.ReadFile(logPath)
+ if err != nil || !strings.Contains(string(data), `"sess-1"`) {
+ t.Fatalf("runtime log does not hold the drained event (err %v):\n%s", err, data)
+ }
+}
+
+// The command a hook prints for a staged session names its workspace, harness and session. Pasted,
+// it vouches for that session alone: a spool a cloned repository planted beside it for an invented
+// session stays unread.
+func TestEndpointSpoolDrainNamedSessionOnly(t *testing.T) {
+ logPath := spoolCommandEnv(t)
+ workspace := t.TempDir()
+ plantWorkspaceSpool(t, workspace, "opencode", "sess-real")
+ plantWorkspaceSpool(t, workspace, "claude_code", "invented")
+ endpointSpoolOpts.workspaces = []string{workspace}
+ endpointSpoolOpts.harness, endpointSpoolOpts.session = "opencode", "sess-real"
+ endpointOpts.jsonOutput = true
+
+ if out, err := runSpoolCmd(t, runEndpointSpoolDrain); err != nil {
+ t.Fatalf("drain: %v\n%s", err, out)
+ }
+ data, _ := os.ReadFile(logPath)
+ if !strings.Contains(string(data), `"sess-real"`) || strings.Contains(string(data), `"invented"`) {
+ t.Fatalf("drain of one named session wrote:\n%s", data)
+ }
+ if !spoolFileHolds(t, workspace, "claude_code", "invented") {
+ t.Fatal("the planted spool beside the named session was drained")
+ }
+}
+
+// spoolFileHolds reports whether a session's workspace spool still holds lines.
+func spoolFileHolds(t *testing.T, workspace, harness, id string) bool {
+ t.Helper()
+ dir, _ := asymptoteobserve.WorkspaceSpoolDir(workspace, harness, id)
+ info, err := os.Stat(localingest.Spool{Dir: dir}.FilePath())
+ return err == nil && info.Size() > 0
+}
+
+// A system config holding a destination secret is root-only, and root may not drain. The ordinary
+// account that may drain cannot learn the log from it, so the drain never guesses one: without
+// --log-path it refuses, naming the flag, and drains nothing; with it, it drains its --workspace.
+func TestEndpointSpoolDrainWithAnUnreadableConfig(t *testing.T) {
+ if runtime.GOOS == "windows" || os.Geteuid() == 0 {
+ t.Skip("needs Unix permissions that bind this account")
+ }
+ logPath := spoolCommandEnv(t)
+ config := endpointconfig.ConfigPath(true)
+ if err := os.MkdirAll(filepath.Dir(config), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(config, []byte(`{"user_mode":true}`), 0o000); err != nil {
+ t.Fatal(err)
+ }
+ workspace := t.TempDir()
+ plantWorkspaceSpool(t, workspace, "gemini_cli", "sess-1")
+ endpointSpoolOpts.workspaces = []string{workspace}
+
+ endpointSpoolOpts.logPath = ""
+ if out, err := runSpoolCmd(t, runEndpointSpoolDrain); err == nil || !strings.Contains(err.Error(), "--log-path") {
+ t.Fatalf("drain with an unreadable config and no --log-path: err %v, want a refusal naming --log-path\n%s", err, out)
+ }
+ if !spoolFileHolds(t, workspace, "gemini_cli", "sess-1") {
+ t.Fatal("a drain with no known log took the staged event out of the spool")
+ }
+
+ endpointSpoolOpts.logPath = logPath
+ out, err := runSpoolCmd(t, runEndpointSpoolDrain)
+ if err != nil || !strings.Contains(out, "cannot read the endpoint config") {
+ t.Fatalf("drain with an unreadable config: %v\n%s", err, out)
+ }
+ if data, _ := os.ReadFile(logPath); !strings.Contains(string(data), `"sess-1"`) {
+ t.Fatalf("the --workspace spool was not drained:\n%s", data)
+ }
+}
+
+func TestEndpointSpoolStatusListsPendingBytes(t *testing.T) {
+ spoolCommandEnv(t)
+ workspace := t.TempDir()
+ staged := plantWorkspaceSpool(t, workspace, "qwen_code", "sess-2")
+ endpointSpoolOpts.workspaces = []string{workspace}
+ endpointOpts.jsonOutput = true
+
+ out, err := runSpoolCmd(t, runEndpointSpoolStatus)
+ if err != nil {
+ t.Fatalf("status: %v\n%s", err, out)
+ }
+ var report struct {
+ Sessions []spoolPendingStatus `json:"sessions"`
+ }
+ if err := json.Unmarshal([]byte(out), &report); err != nil {
+ t.Fatalf("status JSON: %v\n%s", err, out)
+ }
+ if len(report.Sessions) != 1 || report.Sessions[0].SessionID != "sess-2" || report.Sessions[0].Bytes != int64(staged) {
+ t.Fatalf("sessions = %+v, want sess-2 with %d bytes", report.Sessions, staged)
+ }
+
+ endpointOpts.jsonOutput = false
+ out, err = runSpoolCmd(t, runEndpointSpoolStatus)
+ if err != nil || !strings.Contains(out, "sess-2") {
+ t.Fatalf("text status (err %v) does not list sess-2:\n%s", err, out)
+ }
+}
+
+// Staged events are capture working and the drain missing; DeepSeek Harness spools are left
+// to dsh_spool_pending_drain so one spool is never reported twice.
+func TestDoctorWorkspaceSpoolCheck(t *testing.T) {
+ logPath := filepath.Join(t.TempDir(), "events.jsonl")
+ dshOnly := t.TempDir()
+ plantWorkspaceSpool(t, dshOnly, "deepseek_harness", "dsh-1")
+ if check, ok := workspaceSpoolCheck(logPath, []string{dshOnly}); ok {
+ t.Fatalf("dsh-only spool reported by workspace_spool: %+v", check)
+ }
+
+ mixed := t.TempDir()
+ plantWorkspaceSpool(t, mixed, "deepseek_harness", "dsh-2")
+ plantWorkspaceSpool(t, mixed, "gemini_cli", "gem-1")
+ check, ok := workspaceSpoolCheck(logPath, []string{mixed})
+ if !ok {
+ t.Fatal("pending spool not reported")
+ }
+ if check.Name != "workspace_spool" || check.Status != diagnostics.StatusWarn ||
+ check.Severity != diagnostics.SeverityLow || check.Evidence != "workspace_spool_pending_drain" {
+ t.Fatalf("check = %+v", check)
+ }
+ if !strings.HasPrefix(check.Message, "1 session(s)") || !strings.Contains(check.Action, "beacon endpoint spool drain") {
+ t.Errorf("message/action = %q / %q", check.Message, check.Action)
+ }
+}
diff --git a/cli/beacon/internal/dshsession/spool.go b/cli/beacon/internal/dshsession/spool.go
index 5ad3ecd7..e8a5d6a5 100644
--- a/cli/beacon/internal/dshsession/spool.go
+++ b/cli/beacon/internal/dshsession/spool.go
@@ -1,107 +1,50 @@
package dshsession
import (
- "encoding/json"
-
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
- "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs"
- "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
- "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/localingest"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/workspacespool"
)
-// spoolDrainBatch is how many staged lines one Spool.Drain call hands the sweep's sink.
-const spoolDrainBatch = 256
-
-// sessionSpool is the workspace spool a sandboxed hook of ref stages events in (#605), found
-// through the working directory the session store recorded for it.
-func sessionSpool(ref SessionRef) (localingest.Spool, bool) {
+// spoolSession is ref's workspace spool session, found through the working directory the session
+// store recorded for it.
+func spoolSession(ref SessionRef) (workspacespool.Session, bool) {
if ref.Meta == nil {
- return localingest.Spool{}, false
+ return workspacespool.Session{}, false
}
- dir, ok := asymptoteobserve.DSHSpoolDir(ref.Meta.CWD, ref.ID)
- return localingest.Spool{Dir: dir}, ok
+ return workspacespool.Session{Workspace: ref.Meta.CWD, Harness: Harness, ID: ref.ID}, true
}
-// SpoolPendingBytes is how many bytes of hook events ref's workspace spool holds, waiting for a
-// sweep to drain them. Zero when nothing is staged. The size comes from sessionfs.Stat, so a
-// confined reader never follows a user-planted path out of the user's home.
+// SpoolPendingBytes is how many bytes of hook events ref's workspace spools hold, waiting for a
+// sweep to drain them. Zero when nothing is staged.
func SpoolPendingBytes(ref SessionRef) int64 {
- spool, ok := sessionSpool(ref)
+ s, ok := spoolSession(ref)
if !ok {
return 0
}
- info, err := sessionfs.Stat(spool.FilePath())
- if err != nil {
- return 0
- }
- return info.Size()
+ return workspacespool.PendingBytes(s)
}
// drainSessionSpool moves one session's staged hook events out of its workspace spool and into
// the runtime log, counting them in summary.
//
-// Why a spool exists: DeepSeek Harness runs hook commands inside the session sandbox (#605), which
-// cannot write ~/.beacon but can write the session workspace in workspace-write mode. Nothing
-// inside the sandbox can hand those events to the runtime log, so the drain happens here, outside
-// the harness, on the sweep an operator or the watch loop already runs.
+// DeepSeek Harness runs hook commands inside the session sandbox (#605), which cannot write
+// ~/.beacon but can write the session workspace, so its hooks stage there. The session store names
+// the workspace, so the dsh sweep drains its sessions' spools itself, before it maps the store.
//
// Events go through the sweep's own sink, so the budget and retention guard bound them like every
-// mapped event, and a refusal by either stops the sweep with the rest left staged. Delivery is at
-// least once: a sweep killed between appending a batch and removing it from the spool appends it
-// again next time, the same contract localingest.Spool keeps for a restricted-mode hook.
-//
-// A system backfill (sessionfs confinement active) leaves spools alone: the drain writes and
-// removes files under a workspace path the session store names, which root must not do on a
-// user's behalf. The user's own `beacon endpoint dsh sync` drains them.
+// mapped event, and a refusal by either stops the sweep with the rest left staged. A system
+// backfill leaves spools alone (workspacespool.DrainSession); the user's own sync drains them.
func drainSessionSpool(ref SessionRef, opts CollectOptions, summary *Summary) error {
- if !opts.Write || opts.Print || sessionfs.Active() {
+ if !opts.Write || opts.Print {
return nil
}
- spool, ok := sessionSpool(ref)
+ s, ok := spoolSession(ref)
if !ok {
return nil
}
- for {
- n, err := spool.Drain(spoolDrainBatch, func(lines [][]byte) (int, error) {
- for i, line := range lines {
- event, ok := stagedHookEvent(line, ref.ID)
- if !ok {
- summary.SpoolRejected++
- continue
- }
- if err := emitEvent(event, opts); err != nil {
- return i, err
- }
- summary.SpoolEvents++
- }
- return len(lines), nil
- })
- if err != nil || n < spoolDrainBatch {
- return err
- }
- }
-}
-
-// stagedHookEvent decodes one spooled line and admits it only if it is what a sandboxed Beacon
-// hook of this session stages: an event of sessionID, from DeepSeek Harness, collected by a hook,
-// and not an action only Beacon itself writes.
-//
-// The spool sits in a directory the sandboxed agent can write by design, so its contents are
-// untrusted input, held to the same rule as telemetry from outside (IsBeaconOnlyAction). Without
-// these checks anything running in the workspace could append events for any session, or a
-// session.share_requested that Beacon Cloud acts on by publishing the session. A torn line from a
-// killed hook fails to decode and is rejected the same way.
-func stagedHookEvent(line []byte, sessionID string) (schema.Event, bool) {
- var event schema.Event
- if err := json.Unmarshal(line, &event); err != nil {
- return event, false
- }
- switch {
- case event.Session == nil || event.Session.ID != sessionID,
- event.Harness.Name != Harness,
- event.Harness.CollectionMethod != asymptoteobserve.CollectionMethodHook,
- asymptoteobserve.IsBeaconOnlyAction(event.Event.Action):
- return event, false
- }
- return event, true
+ var drained workspacespool.Summary
+ err := workspacespool.DrainSession(s, func(event schema.Event) error { return emitEvent(event, opts) }, &drained)
+ summary.SpoolEvents += drained.Events
+ summary.SpoolRejected += drained.Rejected
+ return err
}
diff --git a/cli/beacon/internal/dshsession/spool_test.go b/cli/beacon/internal/dshsession/spool_test.go
index 20e70dbc..1990f794 100644
--- a/cli/beacon/internal/dshsession/spool_test.go
+++ b/cli/beacon/internal/dshsession/spool_test.go
@@ -50,15 +50,44 @@ func spoolTestLine(t *testing.T, event schema.Event) []byte {
// stage appends lines to sessionID's spool in workspace the way a sandboxed hook does.
func stage(t *testing.T, workspace, sessionID string, lines ...[]byte) {
t.Helper()
- dir, ok := asymptoteobserve.DSHSpoolDir(workspace, sessionID)
+ dir, ok := asymptoteobserve.WorkspaceSpoolDir(workspace, Harness, sessionID)
if !ok {
t.Fatalf("unsafe test session id %q", sessionID)
}
+ stageIn(t, dir, lines...)
+}
+
+func stageIn(t *testing.T, dir string, lines ...[]byte) {
+ t.Helper()
if dropped, err := (localingest.Spool{Dir: dir}).Append(lines); err != nil || dropped != 0 {
t.Fatalf("stage: dropped %d, err %v", dropped, err)
}
}
+// A spool an earlier hook left in .beacon/dsh-spool/<session> is still drained, once.
+func TestDrainSessionSpoolDrainsTheLegacyDSHSpool(t *testing.T) {
+ workspace := t.TempDir()
+ opts := spoolTestOpts(t)
+ ref := spoolTestRef("sess-legacy-1", workspace)
+ legacy, ok := asymptoteobserve.LegacyDSHSpoolDir(workspace, ref.ID)
+ if !ok {
+ t.Fatal("unsafe test session id")
+ }
+ stageIn(t, legacy, spoolTestLine(t, spoolTestEvent(t, ref.ID, "session.started")))
+ stage(t, workspace, ref.ID, spoolTestLine(t, spoolTestEvent(t, ref.ID, "prompt.submitted")))
+
+ var summary Summary
+ if err := drainSessionSpool(ref, opts, &summary); err != nil {
+ t.Fatalf("drain: %v", err)
+ }
+ if summary.SpoolEvents != 2 || summary.SpoolRejected != 0 {
+ t.Fatalf("SpoolEvents/SpoolRejected = %d/%d, want 2/0", summary.SpoolEvents, summary.SpoolRejected)
+ }
+ if pending := SpoolPendingBytes(ref); pending != 0 {
+ t.Errorf("spools still hold %d bytes after the drain", pending)
+ }
+}
+
func spoolTestRef(sessionID, workspace string) SessionRef {
return SessionRef{ID: sessionID, Meta: &SessionMeta{ID: sessionID, CWD: workspace}}
}
@@ -330,19 +359,21 @@ func TestCollectOnceStopsTheDrainWhenTheBudgetIsSpent(t *testing.T) {
}
}
-// An append the writer refuses for any other reason fails the session's drain; what landed before
-// it is counted and the refused event stays staged.
-func TestCollectOnceCountsSpoolEventsAppendedBeforeDrainFailure(t *testing.T) {
+// A staged event the writer would refuse as invalid is rejected and removed, never left at the
+// head of the spool to fail every later drain; the events around it are delivered. (A writer error,
+// such as a spent budget, still stops the drain with the rest staged.)
+func TestCollectOnceRejectsAnInvalidSpoolEventWithoutBlockingTheRest(t *testing.T) {
root := t.TempDir()
workspace := t.TempDir()
writeSession(t, filepath.Join(root, "sessions", "s-partial-drain"), SessionFileJSON,
record("session", map[string]interface{}{"id": "s-partial-drain", "cwd": workspace}),
)
invalid := spoolTestEvent(t, "s-partial-drain", "prompt.submitted")
- invalid.Vendor = ""
+ invalid.Severity = ""
stage(t, workspace, "s-partial-drain",
spoolTestLine(t, spoolTestEvent(t, "s-partial-drain", "session.started")),
spoolTestLine(t, invalid),
+ spoolTestLine(t, spoolTestEvent(t, "s-partial-drain", "session.ended")),
)
opts := CollectOptions{
@@ -353,14 +384,14 @@ func TestCollectOnceCountsSpoolEventsAppendedBeforeDrainFailure(t *testing.T) {
UserMode: true,
}
summary, err := CollectOnce(opts)
- if err == nil {
- t.Fatal("CollectOnce succeeded despite the invalid second spool event")
+ if err != nil {
+ t.Fatalf("CollectOnce: %v", err)
}
- if summary.SpoolEvents != 1 {
- t.Fatalf("SpoolEvents = %d, want 1 event appended before the drain failed", summary.SpoolEvents)
+ if summary.SpoolEvents != 2 || summary.SpoolRejected != 1 {
+ t.Fatalf("SpoolEvents/SpoolRejected = %d/%d, want 2/1", summary.SpoolEvents, summary.SpoolRejected)
}
- if SpoolPendingBytes(spoolTestRef("s-partial-drain", workspace)) == 0 {
- t.Fatal("the refused event was taken out of the spool")
+ if SpoolPendingBytes(spoolTestRef("s-partial-drain", workspace)) != 0 {
+ t.Fatal("the invalid event was left in the spool")
}
}
diff --git a/cli/beacon/internal/endpoint/config/config.go b/cli/beacon/internal/endpoint/config/config.go
index 3f0ff14d..05d1106a 100644
--- a/cli/beacon/internal/endpoint/config/config.go
+++ b/cli/beacon/internal/endpoint/config/config.go
@@ -127,6 +127,11 @@ type Config struct {
// the default) or "disabled". Only the system config's value counts, and it applies to every
// account on the machine; read it through SystemDashboardDisabled.
Dashboard string `json:"dashboard,omitempty"`
+ // WorkspaceSpoolRoots are absolute paths, or globs of them, naming workspace directories whose
+ // staged hook spools (<workspace>/.beacon/spool) a sweep drains even for sessions Beacon has
+ // not recorded: the operator configuring a root vouches for what is staged under it. Load drops
+ // any entry that is not absolute or not a valid glob.
+ WorkspaceSpoolRoots []string `json:"workspace_spool_roots,omitempty"`
}
const (
@@ -626,12 +631,31 @@ func Load(userMode bool) (Config, error) {
}
loadOTLPForwardSecrets(&cfg)
NormalizeDestinations(&cfg)
+ cfg.WorkspaceSpoolRoots = validWorkspaceSpoolRoots(cfg.WorkspaceSpoolRoots)
if err := ValidateDestinations(cfg.Destinations); err != nil {
return Config{}, err
}
return cfg, nil
}
+// validWorkspaceSpoolRoots keeps the roots that are absolute paths or well-formed globs of them.
+// A relative root would resolve against whatever directory a sweep happens to run in, so it names
+// nothing; like an unknown harness, an invalid entry is dropped rather than failing the load.
+func validWorkspaceSpoolRoots(roots []string) []string {
+ var out []string
+ for _, root := range roots {
+ root = strings.TrimSpace(root)
+ if root == "" || !filepath.IsAbs(root) {
+ continue
+ }
+ if _, err := filepath.Match(root, ""); err != nil {
+ continue
+ }
+ out = append(out, root)
+ }
+ return out
+}
+
func Save(cfg Config) (string, error) {
NormalizeDestinations(&cfg)
if err := ValidateDestinations(cfg.Destinations); err != nil {
diff --git a/cli/beacon/internal/endpoint/config/config_test.go b/cli/beacon/internal/endpoint/config/config_test.go
index 586d8099..6b3bb792 100644
--- a/cli/beacon/internal/endpoint/config/config_test.go
+++ b/cli/beacon/internal/endpoint/config/config_test.go
@@ -1,6 +1,7 @@
package config
import (
+ "encoding/json"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"
"os"
"path/filepath"
@@ -237,6 +238,33 @@ func TestLoadIgnoresLegacyContentRetention(t *testing.T) {
}
}
+// Load keeps absolute spool roots and globs of them, and drops the rest without failing.
+func TestLoadKeepsOnlyValidWorkspaceSpoolRoots(t *testing.T) {
+ home := t.TempDir()
+ testenv.SetHome(t, home)
+ path := filepath.Join(home, UserConfigPath)
+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+ t.Fatal(err)
+ }
+ abs := filepath.Join(home, "sandboxes")
+ glob := filepath.Join(abs, "*")
+ roots := []string{abs, glob, "relative/ws", "", filepath.Join(abs, "[")}
+ data, err := json.Marshal(map[string]any{"user_mode": true, "workspace_spool_roots": roots})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, data, 0644); err != nil {
+ t.Fatal(err)
+ }
+ loaded, err := Load(true)
+ if err != nil {
+ t.Fatalf("Load: %v", err)
+ }
+ if got := loaded.WorkspaceSpoolRoots; len(got) != 2 || got[0] != abs || got[1] != glob {
+ t.Fatalf("WorkspaceSpoolRoots = %q, want [%q %q]", got, abs, glob)
+ }
+}
+
func TestLoadRejectsCorruptJSON(t *testing.T) {
home := t.TempDir()
testenv.SetHome(t, home)
diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
index 4a07c51b..5506fbf7 100644
--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
@@ -1323,6 +1323,9 @@ func buildConfig(opts InstallOptions) endpointconfig.Config {
if existing.SessionSync != nil {
cfg.SessionSync = existing.SessionSync
}
+ // Spool roots are an operator's vouching for where hooks may stage; a repair that dropped
+ // them would leave those sessions' events staged for good.
+ cfg.WorkspaceSpoolRoots = existing.WorkspaceSpoolRoots
// The OTLP forward replaces the export a runtime had to another backend before Beacon
// pointed it at the collector. An upgrade or repair that dropped it would silently cut that
// backend off, so it is kept until --no-otlp-forward removes it.
diff --git a/cli/beacon/internal/endpoint/lifecycle/session_sync_test.go b/cli/beacon/internal/endpoint/lifecycle/session_sync_test.go
index 915e83c5..79789b90 100644
--- a/cli/beacon/internal/endpoint/lifecycle/session_sync_test.go
+++ b/cli/beacon/internal/endpoint/lifecycle/session_sync_test.go
@@ -87,6 +87,21 @@ func TestBuildConfigKeepsSessionSyncUntilChanged(t *testing.T) {
}
}
+// A repair or upgrade rewrites config.json from buildConfig; the operator's spool roots survive it.
+func TestBuildConfigKeepsWorkspaceSpoolRoots(t *testing.T) {
+ testenv.SetHome(t, t.TempDir())
+ // Absolute on this platform: Load drops a root that is not, and "/srv" is not on Windows.
+ root := filepath.Join(t.TempDir(), "sandboxes", "*")
+ data, err := json.Marshal(map[string]any{"user_mode": true, "log_path": "/tmp/runtime.jsonl", "workspace_spool_roots": []string{root}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ writeInventoryConfig(t, true, string(data))
+ if cfg := buildConfig(InstallOptions{UserMode: true}); len(cfg.WorkspaceSpoolRoots) != 1 || cfg.WorkspaceSpoolRoots[0] != root {
+ t.Fatalf("buildConfig dropped workspace_spool_roots: %v", cfg.WorkspaceSpoolRoots)
+ }
+}
+
// A user-mode job carries the store-locating variables set at install, including the ones only a
// session-store collector reads.
func TestSessionSyncJobEnvCarriesCollectorVariables(t *testing.T) {
diff --git a/cli/beacon/internal/workspacespool/workspacespool.go b/cli/beacon/internal/workspacespool/workspacespool.go
new file mode 100644
index 00000000..7b2e8215
--- /dev/null
+++ b/cli/beacon/internal/workspacespool/workspacespool.go
@@ -0,0 +1,358 @@
+// Package workspacespool drains the workspace spools hooks stage events in when a sandbox leaves
+// them no other way to deliver one: no ingest socket, no runtime log, no account spool (#605,
+// #1284). A sandbox that confines a hook's writes to the session's working directory still lets it
+// write <workspace>/.beacon/spool/<harness>/<session>/, and Beacon, outside, moves those events
+// into the runtime log later.
+//
+// Everything in a spool is untrusted: the workspace is writable by the agent and by whatever a
+// checked-out repository carries. A line reaches the log only through
+// asymptoteobserve.AdmitStagedLine, and a spool is drained only for a session Beacon has already
+// recorded in that workspace (KnownSessions) or under a root an operator configured
+// (RootSessions), so a planted spool for an invented session is never read.
+package workspacespool
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "io"
+ "math"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionsync"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/localingest"
+)
+
+// legacyDSHHarness is the harness whose hooks once staged in .beacon/dsh-spool/<session>.
+const legacyDSHHarness = "deepseek_harness"
+
+// knownTailBytes bounds how much of the runtime log KnownSessions reads: enough for the sessions
+// of recent days on a busy machine, without reading a whole rotation window on every sweep.
+const knownTailBytes int64 = 8 << 20
+
+// maxKnownSessions caps KnownSessions, so a log stuffed with distinct ids cannot make a sweep
+// stat an unbounded number of workspace paths.
+const maxKnownSessions = 10000
+
+// Session is one harness session in one workspace, whose spool a drain looks in.
+type Session struct{ Workspace, Harness, ID string }
+
+// Summary counts what drains did.
+type Summary struct {
+ Sessions int `json:"sessions"` // sessions whose spool held at least one line
+ Events int `json:"events"` // staged events appended to the runtime log
+ Rejected int `json:"rejected"` // staged lines refused (AdmitStagedLine false, or undecodable into schema.Event)
+}
+
+// Emit appends one admitted event, through the sweep's own sink.
+type Emit func(event schema.Event) error
+
+// spoolDirs is every spool directory s may have staged in: the shared one, and for DeepSeek
+// Harness the directory its hooks used before every harness shared it. A spool whose path below
+// the workspace passes through anything but real directories is left out (realSpool).
+func (s Session) spoolDirs() []string {
+ var out []string
+ if dir, ok := asymptoteobserve.WorkspaceSpoolDir(s.Workspace, s.Harness, s.ID); ok && realSpool(s.Workspace, dir) {
+ out = append(out, dir)
+ }
+ if s.Harness == legacyDSHHarness {
+ if dir, ok := asymptoteobserve.LegacyDSHSpoolDir(s.Workspace, s.ID); ok && realSpool(s.Workspace, dir) {
+ out = append(out, dir)
+ }
+ }
+ return out
+}
+
+// realSpool reports whether every component of dir below workspace (.beacon, spool, harness,
+// session) is a real directory and the spool file, if present, a regular file no larger than a
+// spool can grow. The sandboxed agent can write the workspace and knows its own session id, so it
+// can plant .beacon/spool/<harness>/<its-id> as a link to the account's own spool; a drain through
+// it would remove the lines it refuses from that spool. Spool.Append never lets the file outgrow
+// DefaultSpoolMaxBytes, so a larger one was written by hand and is left unread. The workspace
+// itself may be a link; it comes from Beacon's own log or an operator's root.
+func realSpool(workspace, dir string) bool {
+ rel, err := filepath.Rel(filepath.Clean(workspace), dir)
+ if err != nil || rel == "." || strings.HasPrefix(rel, "..") {
+ return false
+ }
+ path := filepath.Clean(workspace)
+ for _, part := range strings.Split(rel, string(filepath.Separator)) {
+ path = filepath.Join(path, part)
+ info, err := os.Lstat(path)
+ if err != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
+ return false
+ }
+ }
+ info, err := os.Lstat(localingest.Spool{Dir: dir}.FilePath())
+ return errors.Is(err, os.ErrNotExist) || (err == nil && info.Mode().IsRegular() && info.Size() <= localingest.DefaultSpoolMaxBytes)
+}
+
+// DrainSession moves s's staged events through emit, counting them in summary.
+//
+// Each spool is drained in one pass: Spool.Drain reads it once, emit takes the lines in order, and
+// the remainder is rewritten once. A drain in small batches would re-read and rewrite the whole
+// file per batch. The file is at most DefaultSpoolMaxBytes (realSpool), so one read is bounded.
+//
+// Delivery is at least once: a drain killed between emitting and removing the lines emits them
+// again next time, the contract localingest.Spool keeps for every spool. An emit error (a spent
+// budget, a full retention window) stops the drain with the unsent rest left staged. A refused
+// line -- not admitted, undecodable, or not a valid event -- is removed with the rest, since it
+// would be refused on every later drain too and would block the lines behind it.
+//
+// Under sessionfs confinement (a root sweep) it does nothing: the drain writes and removes files
+// under a user's workspace, which root must not do on their behalf. The user's own sweep drains it.
+func DrainSession(s Session, emit Emit, summary *Summary) error {
+ if sessionfs.Active() {
+ return nil
+ }
+ counted := false
+ for _, dir := range s.spoolDirs() {
+ if err := drainSpool(localingest.Spool{Dir: dir}, s, emit, summary, &counted); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func drainSpool(spool localingest.Spool, s Session, emit Emit, summary *Summary, counted *bool) error {
+ _, err := spool.Drain(math.MaxInt, func(lines [][]byte) (int, error) {
+ if !*counted {
+ *counted = true
+ summary.Sessions++
+ }
+ for i, line := range lines {
+ if !asymptoteobserve.AdmitStagedLine(line, s.Harness, s.ID) {
+ summary.Rejected++
+ continue
+ }
+ var event schema.Event
+ if err := json.Unmarshal(line, &event); err != nil || event.Validate() != nil {
+ summary.Rejected++
+ continue
+ }
+ if err := emit(event); err != nil {
+ return i, err
+ }
+ summary.Events++
+ }
+ return len(lines), nil
+ })
+ return err
+}
+
+// Drain drains each session. A stopped sweep (sessionsync.Stopped) ends it, since every later
+// session would be refused the same way; any other error is one session's, and the rest still run.
+func Drain(sessions []Session, emit Emit, summary *Summary) error {
+ var errs []error
+ for _, s := range sessions {
+ if err := DrainSession(s, emit, summary); err != nil {
+ if sessionsync.Stopped(err) {
+ return errors.Join(append(errs, err)...)
+ }
+ errs = append(errs, err)
+ }
+ }
+ return errors.Join(errs...)
+}
+
+// PendingBytes is how many bytes s's spools hold, waiting for a drain. The sizes come from
+// sessionfs.Stat, so a confined reader never follows a user-planted path out of the user's home.
+func PendingBytes(s Session) int64 {
+ var total int64
+ for _, dir := range s.spoolDirs() {
+ if info, err := sessionfs.Stat(localingest.Spool{Dir: dir}.FilePath()); err == nil {
+ total += info.Size()
+ }
+ }
+ return total
+}
+
+// KnownSessions lists the sessions Beacon has recorded in the tail of the runtime log at logPath:
+// the distinct working directory, harness and session id of its lines. Session-store collectors
+// and live hooks both record a session's working directory, so this is how a sweep learns which
+// workspaces to look in, and for which sessions, without trusting anything a workspace holds.
+//
+// Only the last knownTailBytes are read: of the current file, and of its first archive when the
+// current file holds less. A missing log is no sessions.
+func KnownSessions(logPath string) ([]Session, error) {
+ current, size, err := readTail(logPath, knownTailBytes)
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return nil, nil
+ }
+ return nil, err
+ }
+ var archive []byte
+ if size < knownTailBytes {
+ archive, _, err = readTail(logPath+".1", knownTailBytes-size)
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ return nil, err
+ }
+ }
+ seen := map[Session]bool{}
+ var out []Session
+ for _, data := range [][]byte{archive, current} {
+ for len(data) > 0 && len(out) < maxKnownSessions {
+ line := data
+ if i := bytes.IndexByte(data, '\n'); i >= 0 {
+ line, data = data[:i], data[i+1:]
+ } else {
+ data = nil
+ }
+ s, ok := lineSession(line)
+ if ok && !seen[s] {
+ seen[s] = true
+ out = append(out, s)
+ }
+ }
+ }
+ return out, nil
+}
+
+// lineSession decodes only the fields that name a line's session.
+func lineSession(line []byte) (Session, bool) {
+ var event struct {
+ Harness struct {
+ Name string `json:"name"`
+ } `json:"harness"`
+ Session *struct {
+ ID string `json:"id"`
+ WorkingDirectory string `json:"working_directory"`
+ } `json:"session"`
+ }
+ if len(bytes.TrimSpace(line)) == 0 || json.Unmarshal(line, &event) != nil || event.Session == nil {
+ return Session{}, false
+ }
+ ws := event.Session.WorkingDirectory
+ if ws == "" || !filepath.IsAbs(ws) || !asymptoteobserve.ValidSpoolName(event.Harness.Name) || !asymptoteobserve.ValidSpoolName(event.Session.ID) {
+ return Session{}, false
+ }
+ return Session{Workspace: filepath.Clean(ws), Harness: event.Harness.Name, ID: event.Session.ID}, true
+}
+
+// readTail reads at most limit bytes from the end of path, without the partial line a cut through
+// the middle of the file starts with, and returns the file's size.
+func readTail(path string, limit int64) ([]byte, int64, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return nil, 0, err
+ }
+ defer f.Close()
+ info, err := f.Stat()
+ if err != nil {
+ return nil, 0, err
+ }
+ size := info.Size()
+ offset := size - limit
+ if offset < 0 {
+ offset = 0
+ }
+ data, err := io.ReadAll(io.NewSectionReader(f, offset, size-offset))
+ if err != nil {
+ return nil, 0, err
+ }
+ if offset > 0 {
+ if i := bytes.IndexByte(data, '\n'); i >= 0 {
+ data = data[i+1:]
+ } else {
+ data = nil
+ }
+ }
+ return data, size, nil
+}
+
+// RootSessions lists every session spool under the operator's configured roots, each a glob of
+// workspace directories. An operator naming a root vouches for what is staged there, so these
+// sessions need not be known to Beacon; their lines still pass AdmitStagedLine. An invalid glob
+// names nothing.
+func RootSessions(roots []string) []Session {
+ var out []Session
+ for _, root := range roots {
+ matches, err := filepath.Glob(root)
+ if err != nil {
+ continue
+ }
+ for _, ws := range matches {
+ out = append(out, WorkspaceSessions(ws)...)
+ }
+ }
+ return out
+}
+
+// WorkspaceSessions lists every session spool in one workspace, named literally (`beacon endpoint
+// spool drain --workspace`): a path is never a glob here, so one holding `[` or `*` names itself.
+// Whoever names the workspace vouches for it, as for a root. Harness and session directories are
+// taken only as real directories, never through a symlink a workspace could plant to point a
+// drain elsewhere.
+func WorkspaceSessions(ws string) []Session {
+ var out []Session
+ spoolRoot := filepath.Join(ws, asymptoteobserve.WorkspaceSpoolRootRel)
+ for _, harness := range realSubdirs(spoolRoot) {
+ for _, id := range realSubdirs(filepath.Join(spoolRoot, harness)) {
+ out = append(out, Session{Workspace: ws, Harness: harness, ID: id})
+ }
+ }
+ for _, id := range realSubdirs(filepath.Join(ws, asymptoteobserve.LegacyDSHSpoolRootRel)) {
+ out = append(out, Session{Workspace: ws, Harness: legacyDSHHarness, ID: id})
+ }
+ return out
+}
+
+// realSubdirs names dir's subdirectories that are real directories with valid spool names. dir
+// itself must be a real directory too.
+func realSubdirs(dir string) []string {
+ if info, err := os.Lstat(dir); err != nil || !info.IsDir() {
+ return nil
+ }
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ return nil
+ }
+ var out []string
+ for _, entry := range entries {
+ name := entry.Name()
+ if !asymptoteobserve.ValidSpoolName(name) {
+ continue
+ }
+ if info, err := os.Lstat(filepath.Join(dir, name)); err == nil && info.IsDir() {
+ out = append(out, name)
+ }
+ }
+ return out
+}
+
+// Discover is every session a drain covers: those Beacon has recorded, those under the configured
+// roots, and those in the workspaces named literally, deduplicated and sorted. A runtime log that
+// cannot be read is reported alongside the others.
+func Discover(logPath string, roots, workspaces []string) ([]Session, error) {
+ known, err := KnownSessions(logPath)
+ seen := map[Session]bool{}
+ var out []Session
+ all := append(known, RootSessions(roots)...)
+ for _, ws := range workspaces {
+ all = append(all, WorkspaceSessions(ws)...)
+ }
+ for _, s := range all {
+ if !seen[s] {
+ seen[s] = true
+ out = append(out, s)
+ }
+ }
+ sort.Slice(out, func(i, j int) bool {
+ a, b := out[i], out[j]
+ if a.Workspace != b.Workspace {
+ return a.Workspace < b.Workspace
+ }
+ if a.Harness != b.Harness {
+ return a.Harness < b.Harness
+ }
+ return a.ID < b.ID
+ })
+ return out, err
+}
diff --git a/cli/beacon/internal/workspacespool/workspacespool_test.go b/cli/beacon/internal/workspacespool/workspacespool_test.go
new file mode 100644
index 00000000..19f2b22b
--- /dev/null
+++ b/cli/beacon/internal/workspacespool/workspacespool_test.go
@@ -0,0 +1,295 @@
+package workspacespool
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/localingest"
+)
+
+func testEvent(harness, sessionID, workspace, action string) schema.Event {
+ event := schema.NewEvent(schema.NewEventOptions{
+ Action: action,
+ Category: "agent",
+ Severity: schema.SeverityInfo,
+ Harness: schema.HarnessInfo{Name: harness, CollectionMethod: asymptoteobserve.CollectionMethodHook},
+ Message: action,
+ })
+ event.Session = &schema.SessionInfo{ID: sessionID, WorkingDirectory: workspace}
+ return event
+}
+
+func line(t *testing.T, event schema.Event) []byte {
+ t.Helper()
+ data, err := json.Marshal(event)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return data
+}
+
+func stageAt(t *testing.T, dir string, lines ...[]byte) localingest.Spool {
+ t.Helper()
+ spool := localingest.Spool{Dir: dir}
+ if dropped, err := spool.Append(lines); err != nil || dropped != 0 {
+ t.Fatalf("stage: dropped %d, err %v", dropped, err)
+ }
+ return spool
+}
+
+func stage(t *testing.T, s Session, lines ...[]byte) localingest.Spool {
+ t.Helper()
+ dir, ok := asymptoteobserve.WorkspaceSpoolDir(s.Workspace, s.Harness, s.ID)
+ if !ok {
+ t.Fatalf("unsafe test session %+v", s)
+ }
+ return stageAt(t, dir, lines...)
+}
+
+func pending(t *testing.T, spool localingest.Spool) int {
+ t.Helper()
+ lines, _, err := spool.Pending()
+ if err != nil {
+ t.Fatal(err)
+ }
+ return lines
+}
+
+func collect(events *[]schema.Event) Emit {
+ return func(event schema.Event) error {
+ *events = append(*events, event)
+ return nil
+ }
+}
+
+func TestDrainSessionAdmitsOnlyTheSessionsOwnHookEvents(t *testing.T) {
+ ws := t.TempDir()
+ s := Session{Workspace: ws, Harness: "opencode", ID: "s1"}
+ beaconOnly := testEvent("opencode", "s1", ws, "session.share_requested")
+ poll := testEvent("opencode", "s1", ws, "prompt.submitted")
+ poll.Harness.CollectionMethod = schema.CollectionMethodPoll
+ spool := stage(t, s,
+ line(t, testEvent("opencode", "s1", ws, "session.started")),
+ line(t, testEvent("opencode", "other", ws, "prompt.submitted")),
+ line(t, testEvent("codex", "s1", ws, "prompt.submitted")),
+ line(t, beaconOnly),
+ line(t, poll),
+ []byte(`{"torn":`),
+ )
+
+ var events []schema.Event
+ var summary Summary
+ if err := DrainSession(s, collect(&events), &summary); err != nil {
+ t.Fatal(err)
+ }
+ if summary != (Summary{Sessions: 1, Events: 1, Rejected: 5}) || len(events) != 1 || events[0].Event.Action != "session.started" {
+ t.Fatalf("summary %+v events %d, want one admitted and five refused", summary, len(events))
+ }
+ if pending(t, spool) != 0 || PendingBytes(s) != 0 {
+ t.Fatal("drained and refused lines were left staged")
+ }
+}
+
+func TestDrainSessionStopsOnEmitErrorAndKeepsTheRest(t *testing.T) {
+ ws := t.TempDir()
+ s := Session{Workspace: ws, Harness: "opencode", ID: "s1"}
+ spool := stage(t, s,
+ line(t, testEvent("opencode", "s1", ws, "session.started")),
+ line(t, testEvent("opencode", "s1", ws, "prompt.submitted")),
+ )
+ calls := 0
+ emit := func(schema.Event) error {
+ calls++
+ if calls == 2 {
+ return writer.ErrBudgetSpent
+ }
+ return nil
+ }
+ var summary Summary
+ err := Drain([]Session{s, {Workspace: ws, Harness: "opencode", ID: "s2"}}, emit, &summary)
+ if !errors.Is(err, writer.ErrBudgetSpent) || summary.Events != 1 || pending(t, spool) != 1 {
+ t.Fatalf("err %v, summary %+v, pending %d; want the refused event left staged", err, summary, pending(t, spool))
+ }
+}
+
+// A line the gate admits but the log writer would refuse (here, no schema_version) is rejected
+// and removed, not left at the head of the spool for every later drain to stop at.
+func TestDrainSessionRejectsAnInvalidEventWithoutBlockingTheRest(t *testing.T) {
+ ws := t.TempDir()
+ s := Session{Workspace: ws, Harness: "opencode", ID: "s1"}
+ invalid := testEvent("opencode", "s1", ws, "session.started")
+ invalid.SchemaVersion = ""
+ spool := stage(t, s, line(t, invalid), line(t, testEvent("opencode", "s1", ws, "prompt.submitted")))
+ var emitted []string
+ emit := func(e schema.Event) error {
+ if err := e.Validate(); err != nil {
+ return err
+ }
+ emitted = append(emitted, e.Event.Action)
+ return nil
+ }
+ var summary Summary
+ if err := DrainSession(s, emit, &summary); err != nil {
+ t.Fatal(err)
+ }
+ if summary.Rejected != 1 || len(emitted) != 1 || emitted[0] != "prompt.submitted" || pending(t, spool) != 0 {
+ t.Fatalf("summary %+v, emitted %v, pending %d; want the invalid line rejected and the next one drained", summary, emitted, pending(t, spool))
+ }
+}
+
+func TestDrainSessionDrainsTheLegacyDSHSpool(t *testing.T) {
+ ws := t.TempDir()
+ s := Session{Workspace: ws, Harness: legacyDSHHarness, ID: "d1"}
+ dir, _ := asymptoteobserve.LegacyDSHSpoolDir(ws, "d1")
+ legacy := stageAt(t, dir, line(t, testEvent(legacyDSHHarness, "d1", ws, "session.started")))
+ if PendingBytes(s) == 0 {
+ t.Fatal("PendingBytes misses the legacy spool")
+ }
+ var events []schema.Event
+ var summary Summary
+ if err := DrainSession(s, collect(&events), &summary); err != nil || summary.Events != 1 || pending(t, legacy) != 0 {
+ t.Fatalf("err %v summary %+v", err, summary)
+ }
+}
+
+// A link planted for a known session's spool directory, pointing at another spool (the account's
+// own, say), is never read: draining it would remove the lines it refuses from the target.
+func TestDrainSessionSkipsALinkedSpoolDirectory(t *testing.T) {
+ ws := t.TempDir()
+ target := stageAt(t, filepath.Join(t.TempDir(), "account-spool"), []byte(`{"not":"this session"}`))
+ s := Session{Workspace: ws, Harness: "opencode", ID: "s1"}
+ dir, _ := asymptoteobserve.WorkspaceSpoolDir(ws, s.Harness, s.ID)
+ if err := os.MkdirAll(filepath.Dir(dir), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(target.Dir, dir); err != nil {
+ t.Skipf("symlinks unavailable: %v", err)
+ }
+ var events []schema.Event
+ var summary Summary
+ if err := DrainSession(s, collect(&events), &summary); err != nil {
+ t.Fatal(err)
+ }
+ if summary != (Summary{}) || pending(t, target) != 1 || PendingBytes(s) != 0 {
+ t.Fatalf("summary %+v, target holds %d lines; the linked spool was read", summary, pending(t, target))
+ }
+}
+
+// Spool.Append never lets a spool outgrow DefaultSpoolMaxBytes, so a larger pending.jsonl was
+// written by hand -- millions of junk lines, say, that would hold the sweep lock for hours. It is
+// left unread, and not reported as pending.
+func TestDrainSessionSkipsAnOversizeSpool(t *testing.T) {
+ ws := t.TempDir()
+ s := Session{Workspace: ws, Harness: "opencode", ID: "s1"}
+ spool := stage(t, s, line(t, testEvent("opencode", "s1", ws, "session.started")))
+ junk := bytes.Repeat([]byte("x\n"), int(localingest.DefaultSpoolMaxBytes/2)+1)
+ if err := os.WriteFile(spool.FilePath(), junk, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ var events []schema.Event
+ var summary Summary
+ if err := DrainSession(s, collect(&events), &summary); err != nil {
+ t.Fatal(err)
+ }
+ if summary != (Summary{}) || PendingBytes(s) != 0 {
+ t.Fatalf("summary %+v, pending %d; an oversize spool was read", summary, PendingBytes(s))
+ }
+ if info, err := os.Stat(spool.FilePath()); err != nil || info.Size() != int64(len(junk)) {
+ t.Fatalf("the oversize spool changed: %v, %v", info, err)
+ }
+}
+
+func writeLog(t *testing.T, path string, lines ...string) {
+ t.Helper()
+ if err := os.WriteFile(path, []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestKnownSessionsReadsTheLogAndItsArchive(t *testing.T) {
+ ws := t.TempDir()
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ if got, err := KnownSessions(logPath); err != nil || got != nil {
+ t.Fatalf("missing log: %v %v", got, err)
+ }
+ writeLog(t, logPath+".1", string(line(t, testEvent("codex", "a1", ws, "session.started"))))
+ writeLog(t, logPath,
+ string(line(t, testEvent("opencode", "s1", ws, "session.started"))),
+ string(line(t, testEvent("opencode", "s1", ws, "prompt.submitted"))),
+ string(line(t, testEvent("opencode", "rel", "relative/ws", "prompt.submitted"))),
+ string(line(t, testEvent("opencode", "../up", ws, "prompt.submitted"))),
+ "not json",
+ )
+ got, err := KnownSessions(logPath)
+ want := []Session{{Workspace: ws, Harness: "codex", ID: "a1"}, {Workspace: ws, Harness: "opencode", ID: "s1"}}
+ if err != nil || len(got) != 2 || got[0] != want[0] || got[1] != want[1] {
+ t.Fatalf("KnownSessions = %+v, %v; want %+v", got, err, want)
+ }
+}
+
+func TestReadTailSkipsThePartialFirstLine(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "log")
+ writeLog(t, path, "first-line", "second", "third")
+ data, size, err := readTail(path, 10)
+ if err != nil || size != 24 || string(data) != "third\n" {
+ t.Fatalf("readTail = %q %d %v", data, size, err)
+ }
+}
+
+func TestRootSessionsListsRealSpoolDirectoriesOnly(t *testing.T) {
+ root := t.TempDir()
+ ws := filepath.Join(root, "ws1")
+ stage(t, Session{Workspace: ws, Harness: "opencode", ID: "s1"}, []byte("x"))
+ legacyDir, _ := asymptoteobserve.LegacyDSHSpoolDir(ws, "d1")
+ stageAt(t, legacyDir, []byte("x"))
+ elsewhere := t.TempDir()
+ if err := os.MkdirAll(filepath.Join(elsewhere, "s9"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(elsewhere, filepath.Join(ws, asymptoteobserve.WorkspaceSpoolRootRel, "codex")); err != nil {
+ t.Skipf("symlinks unavailable: %v", err)
+ }
+ got := RootSessions([]string{filepath.Join(root, "*"), filepath.Join(root, "[")})
+ want := []Session{{Workspace: ws, Harness: "opencode", ID: "s1"}, {Workspace: ws, Harness: legacyDSHHarness, ID: "d1"}}
+ if len(got) != 2 || got[0] != want[0] || got[1] != want[1] {
+ t.Fatalf("RootSessions = %+v, want %+v", got, want)
+ }
+}
+
+func TestDiscoverMergesAndSorts(t *testing.T) {
+ root := t.TempDir()
+ ws := filepath.Join(root, "ws")
+ stage(t, Session{Workspace: ws, Harness: "opencode", ID: "s1"}, []byte("x"))
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ writeLog(t, logPath,
+ string(line(t, testEvent("opencode", "s1", ws, "session.started"))),
+ string(line(t, testEvent("codex", "c1", ws, "session.started"))),
+ )
+ got, err := Discover(logPath, []string{filepath.Join(root, "*")}, nil)
+ if err != nil || len(got) != 2 || got[0].Harness != "codex" || got[1].Harness != "opencode" {
+ t.Fatalf("Discover = %+v, %v", got, err)
+ }
+}
+
+// A workspace named on the command line is that directory, even when its name reads as a glob:
+// "proj[1]" must not match "proj1", or a drain reports nothing staged and empties another
+// workspace's spool.
+func TestNamedWorkspaceIsLiteral(t *testing.T) {
+ root := t.TempDir()
+ literal := filepath.Join(root, "proj[1]")
+ lookalike := filepath.Join(root, "proj1")
+ stage(t, Session{Workspace: literal, Harness: "opencode", ID: "s1"}, []byte("x"))
+ stage(t, Session{Workspace: lookalike, Harness: "opencode", ID: "s2"}, []byte("x"))
+ got, err := Discover(filepath.Join(t.TempDir(), "runtime.jsonl"), nil, []string{literal})
+ if want := (Session{Workspace: literal, Harness: "opencode", ID: "s1"}); len(got) != 1 || got[0] != want {
+ t.Fatalf("Discover(--workspace %s) = %+v, %v; want only %+v", literal, got, err, want)
+ }
+}
diff --git a/docs/cli/endpoint-doctor.mdx b/docs/cli/endpoint-doctor.mdx
index 88ce0e5b..5b2dd89a 100644
--- a/docs/cli/endpoint-doctor.mdx
+++ b/docs/cli/endpoint-doctor.mdx
@@ -124,6 +124,22 @@ git_hook_budget: warn target=/work/my-repo (2 hook run(s) ran out of time in the
It warns when a run was cut short, because a commit may have been left unlinked; runs that only finished late are reported as ok. The budgets are fixed, so `--fix` lists the check as a manual skip.
+### `workspace_spool`
+
+This check appears only when a [workspace spool](/cli/endpoint-spool) holds hook events: a sandboxed hook could not reach the socket or the runtime log, staged its events in the session workspace, and nothing has drained them yet. Capture is working; only the drain is missing.
+
+```
+workspace_spool: warn target=workspace_spool (2 session(s) have hook events staged in their workspace
+ spool; capture is working, but the events are not in ~/.beacon/endpoint/logs/runtime.jsonl yet)
+ action="run `beacon endpoint spool drain` as the user who owns the workspace"
+```
+
+| Evidence | Status | Meaning |
+|----------|--------|---------|
+| `workspace_spool_pending_drain` | warn (low) | Sessions Beacon has recorded, or sessions under `workspace_spool_roots`, have staged events waiting for a drain |
+
+DeepSeek Harness sessions are left out: [`dsh_spool_pending_drain`](#dsh_hook_capture) already reports them.
+
## Fix mode
`beacon endpoint doctor --fix` plans and applies safe remediations for supported findings. It can create a missing runtime log, and recreate managed collector configuration and the service definition (a launchd plist or a systemd unit) when the endpoint configuration is valid. On a Windows system install it also resets the log directory ACL, from an elevated shell, when interactive users cannot append to the runtime log or when they hold more than append (an older install's Modify grant): the same ACL a fresh install applies, described in [Windows](/platforms/windows#what-the-install-does).
diff --git a/docs/cli/endpoint-dsh.mdx b/docs/cli/endpoint-dsh.mdx
index e39a27be..fca7f1ee 100644
--- a/docs/cli/endpoint-dsh.mdx
+++ b/docs/cli/endpoint-dsh.mdx
@@ -24,8 +24,9 @@ Every event mapped from a session record is marked `harness.collection_method=po
reads committed records after the fact, so this path cannot hold, approve, deny, or delay
a tool call and does not synthesize approval events. Reading is local and offline. A sweep
also drains workspace spools: hook events that a sandboxed DeepSeek session staged in
-`<workspace>/.beacon/dsh-spool/` are appended with the `harness.collection_method=hook`
-label they were captured under, so the two sources stay distinguishable in the log.
+`<workspace>/.beacon/spool/deepseek_harness/` (or the older `<workspace>/.beacon/dsh-spool/`)
+are appended with the `harness.collection_method=hook` label they were captured under, so the
+two sources stay distinguishable in the log. See [`beacon endpoint spool`](/cli/endpoint-spool).
## Commands
@@ -79,9 +80,11 @@ as corruption.
Each sweep also drains workspace spools. When DeepSeek Harness runs hooks
inside its session sandbox, a hook that cannot write the runtime log stages the
-event in `<workspace>/.beacon/dsh-spool/<session>/`, a directory only your
+event in the [workspace spool](/cli/endpoint-spool),
+`<workspace>/.beacon/spool/deepseek_harness/<session>/`, a directory only your
account can read; the sweep appends those events to the runtime log and
-removes them from the spool. The report says how many landed:
+removes them from the spool. Spools an earlier hook left in
+`<workspace>/.beacon/dsh-spool/<session>/` are drained too. The report says how many landed:
```text
dsh sync: 3 sessions, 1 changed, 12 events, 0 errors
diff --git a/docs/cli/endpoint-spool.mdx b/docs/cli/endpoint-spool.mdx
new file mode 100644
index 00000000..ad362d73
--- /dev/null
+++ b/docs/cli/endpoint-spool.mdx
@@ -0,0 +1,161 @@
+---
+title: "beacon endpoint spool"
+description: "Drain hook events that sandboxed agents staged in their session workspace"
+---
+
+## Command overview
+
+Some agents run their hooks in a sandbox that confines writes to the session
+workspace: DeepSeek Harness in `workspace-write`, Gemini CLI and Qwen Code in a
+container sandbox, or an operator's own sandbox that mounts nothing of Beacon's.
+A hook there cannot reach the ingest socket, the runtime log, or the account
+spool. Instead of dropping the event, it stages it in the **workspace spool**:
+
+```text
+<workspace>/.beacon/spool/<harness>/<session>/
+```
+
+Hooks stage only when every other route failed. The spool is readable only by
+your account and capped at 8 MiB per session, and a `.gitignore` inside
+`.beacon/spool/` keeps it out of `git add`, whatever the repository's layout.
+Beacon later drains it into the runtime log with the `harness.collection_method=hook`
+label the event was captured under. Hooks never stage:
+
+- actions only Beacon writes, such as an auto-share request, which are reported
+ as not recorded, as before;
+- as root in a workspace another account owns, such as a rootful container over
+ your checkout: you could neither drain nor delete root's files. Run the
+ container as your own uid, or mount the ingest socket. Root that owns the
+ workspace (a rootless container) stages as usual;
+- in a working directory that exists only on the sandbox's own root
+ filesystem, where the spool would disappear with the sandbox;
+- next to a `.beacon/spool/.gitignore` that does not ignore everything there.
+ A repository can commit its own to switch the protection off; Beacon leaves
+ it alone and stages nothing beside it.
+
+The first event a session stages prints one note to the hook's stderr, naming
+the spool and a drain command for that one session and the log the hook writes:
+
+```text
+beacon endpoint spool drain --log-path '/var/log/beacon-agent/runtime.jsonl' --workspace '/home/dev/src/app' --harness 'opencode' --session 'ses_123'
+```
+
+Later events of the session stage without a note, so the agent's hook output is
+not flooded. A hook cannot tell whether a sweep will find the session, so the
+note always names the command. The command names the session, so running it
+never drains a spool a cloned repository planted beside it, and it names the
+log, so the events go where the hook meant them, whichever mode it runs in.
+DeepSeek Harness stages silently, because
+[`beacon endpoint dsh sync`](/cli/endpoint-dsh) finds its sessions through its
+own session store.
+
+```bash title="Command syntax"
+beacon endpoint spool [command]
+```
+
+## Commands
+
+| Command | Description |
+|---------|-------------|
+| `beacon endpoint spool drain` | Append staged hook events to the runtime log |
+| `beacon endpoint spool status` | List workspace spools holding staged hook events |
+
+## Flags
+
+| Flag | Description |
+|------|-------------|
+| `--workspace <path>` | Also include every session spool in this workspace. Repeatable. The path is taken literally, never as a glob |
+| `--harness <name>` | Only spools of this harness, for example `opencode` |
+| `--session <id>` | Only spools of this session id |
+| `--log-path <path>` | Runtime JSONL log path. Defaults to the resolved endpoint log |
+| `--json` | Print the result as JSON |
+| `--user` | Use per-user endpoint paths. Enabled by default |
+| `--system` | Use system endpoint paths |
+
+## When staged events are drained
+
+Staged events reach the runtime log in one of three ways:
+
+1. **The user-mode sweep.** The scheduled [session sync](/cli/endpoint-install#scheduled-session-sync) and the install backfill drain every spool they find.
+2. **`beacon endpoint spool drain`**, run by hand or from your own scheduler.
+3. **The next hook of the same session that gets through**, for example once the session leaves the sandbox, delivers what that session staged first.
+
+```bash title="Drain spools"
+beacon endpoint spool drain
+beacon endpoint spool drain --workspace ~/src/my-repo
+```
+
+```text
+workspace spool drain: 2 sessions, 14 events, 0 rejected
+```
+
+In system mode, the root sweep never drains workspace spools, so use (2) or (3).
+`drain` refuses to run as root: run it as the account that owns the workspace.
+It appends through the ingest socket like a hook, so an ordinary account does
+not need write access to the system log. If that account cannot read the system
+log, Beacon cannot list the sessions it has recorded; `drain` prints a note and
+still drains configured roots and `--workspace`. If it cannot read the system
+`config.json` (root-only when it holds a destination secret), Beacon does not
+know which log to write: `drain` asks for `--log-path`, and `status` lists only
+`--workspace` spools.
+
+`status` lists each session with staged bytes: workspace, harness, session, and
+size. [`beacon endpoint doctor`](/cli/endpoint-doctor#workspace_spool) reports
+the same state as `workspace_spool_pending_drain`.
+
+## Security model
+
+Anything running in a workspace can write to it, so Beacon treats every staged
+line as untrusted:
+
+- **Lines are checked one by one.** A line is appended only if it is a valid
+ hook or plugin event from Beacon, for the harness and session whose spool
+ holds it. Actions only Beacon writes, such as `session.share_requested`, are
+ refused. Everything else is counted as rejected and removed. Each admitted
+ line is written again through Beacon's own encoder, so it is redacted and
+ size-capped like any other event.
+- **Only known sessions are drained.** Beacon drains a spool only for a session
+ it has already recorded in the runtime log, with that workspace as its working
+ directory. A cloned repository that carries a planted
+ `.beacon/spool/<harness>/<id>/` is never drained.
+- **Configured roots are vouched for by the operator.** Sessions under
+ `workspace_spool_roots` or a `--workspace` are drained even if Beacon has not
+ recorded them, because the operator named those directories. Add `--harness`
+ and `--session` to vouch for one session only.
+- **Links are never followed.** Every directory below the workspace must be a
+ real directory and `pending.jsonl` a regular file, so a sandboxed agent cannot
+ plant its session directory as a link to the account's own spool and have a
+ drain outside the sandbox empty it. A `pending.jsonl` larger than a spool can
+ grow (8 MiB) was written by hand and is left unread, so it cannot tie up a
+ sweep.
+- **Root never drains for a user.** Neither the system-mode sweep nor
+ `beacon endpoint spool drain` drains as root.
+
+Delivery is at least once: a drain killed between appending a batch and removing
+it from the spool appends that batch again.
+
+## Configuring roots
+
+For sandboxes whose sessions Beacon has not recorded yet, such as a container
+sandbox where no hook ever reached the log, list the workspaces in
+`workspace_spool_roots` in the endpoint `config.json`. Each entry is a glob of
+workspace directories:
+
+```json title="config.json"
+{
+ "workspace_spool_roots": [
+ "/home/dev/src/*",
+ "/srv/agents/workspaces/*"
+ ]
+}
+```
+
+Every `<workspace>/.beacon/spool/<harness>/<session>/` under a matching
+directory is drained.
+
+## DeepSeek Harness
+
+DeepSeek Harness hooks stage in `.beacon/spool/deepseek_harness/<session>/`.
+Spools an earlier hook left in `.beacon/dsh-spool/<session>/` are still drained.
+[`beacon endpoint dsh sync`](/cli/endpoint-dsh) drains them too, and doctor
+reports them as `dsh_spool_pending_drain`.
diff --git a/docs/docs.json b/docs/docs.json
index d85abf5e..a341074a 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -352,6 +352,7 @@
"cli/endpoint-dsh",
"cli/endpoint-fx",
"cli/endpoint-harness2",
+ "cli/endpoint-spool",
"cli/endpoint-traces",
"cli/dashboard",
"cli/wazuh",
diff --git a/docs/runtimes/deepseek-harness.mdx b/docs/runtimes/deepseek-harness.mdx
index 29b487be..d066d4ca 100644
--- a/docs/runtimes/deepseek-harness.mdx
+++ b/docs/runtimes/deepseek-harness.mdx
@@ -120,7 +120,7 @@ When this happens, each hook still exits `0`. That is deliberate: on this hook c
What the hook does next depends on the sandbox mode:
-- **`workspace-write`: the event is staged in the workspace.** The hook writes it to a spool in `<workspace>/.beacon/dsh-spool/<session>/` — the one path both sides can reach: the sandbox confines hook writes to the session's working directory, and `beacon endpoint dsh sync` runs outside the harness. The spool is readable only by your account wherever the workspace lives, and is capped at 8 MiB per session; an event that does not fit is reported as not recorded. Staging is silent on stderr (one process per event, so a note here would be a note on every event); the staged state shows up as `spool_bytes` in `beacon endpoint dsh status` instead. On first spool use in a repository, the hook also adds the directory to `.git/info/exclude` — the local, unshared ignore file, never `.gitignore` — so it stays out of `git status`. A linked worktree (where `.git` is a file) is left without the entry.
+- **`workspace-write`: the event is staged in the workspace.** The hook writes it to the [workspace spool](/cli/endpoint-spool) in `<workspace>/.beacon/spool/deepseek_harness/<session>/` — the one path both sides can reach: the sandbox confines hook writes to the session's working directory, and `beacon endpoint dsh sync` runs outside the harness. Spools an earlier hook left in `<workspace>/.beacon/dsh-spool/<session>/` are still drained. The spool is readable only by your account wherever the workspace lives, and is capped at 8 MiB per session; an event that does not fit is reported as not recorded. Staging is silent on stderr (one process per event, so a note here would be a note on every event); the staged state shows up as `spool_bytes` in `beacon endpoint dsh status` instead. On first spool use in a repository, the hook also adds the directory to `.git/info/exclude` — the local, unshared ignore file, never `.gitignore` — so it stays out of `git status`. A linked worktree (where `.git` is a file) is left without the entry.
- **`read-only` (the default): nothing is writable, including the workspace.** The spool write fails too. The hook then prints on stderr that the event was **not recorded**, names the log path and the error, and points at the remedies. The explanation is printed once per hook invocation, not once per event, so it stays readable wherever `dsh` shows or logs hook output.
The poll half is unaffected. `beacon endpoint dsh sync` runs outside the harness and reads DeepSeek's own session store, so sessions the hooks missed can still be backfilled with assistant text, tool calls, commands, file activity, and token usage. What is lost without live capture is immediacy: poll events arrive after the fact, carry `harness.collection_method=poll`, and cannot hold or deny a tool call. Drained spool events are the opposite: they were captured live and keep `harness.collection_method=hook` when the sweep appends them, so they count as live capture everywhere it is measured.
diff --git a/docs/security/restricted-log-access.mdx b/docs/security/restricted-log-access.mdx
index 450a24ec..7d526725 100644
--- a/docs/security/restricted-log-access.mdx
+++ b/docs/security/restricted-log-access.mdx
@@ -55,6 +55,8 @@ To also hold events while the collector restarts, mount the account's spool too:
A hook that can reach neither the socket nor a spool does not record the event. It prints `beacon-hooks: this event was NOT recorded` and the reason to the hook's stderr, and the agent carries on. On Linux, inside a sandbox whose root filesystem is a tmpfs owned by the account (bubblewrap's), a hook never puts the log or the spool on that filesystem; only directories the sandbox mounts take them. That holds even when a project bound under the home makes the home exist inside the sandbox, so events never go to files that disappear with the sandbox.
+Runtimes that build their own sandbox, such as DeepSeek Harness or Gemini CLI and Qwen Code in a container, usually leave only the session workspace writable, and you cannot add mounts. There the hook stages the event in the session workspace instead, and Beacon drains it later; see [`beacon endpoint spool`](/cli/endpoint-spool).
+
## Turn it on
<Note>
diff --git a/pkg/asymptoteobserve/dshspool.go b/pkg/asymptoteobserve/dshspool.go
deleted file mode 100644
index f9486389..00000000
--- a/pkg/asymptoteobserve/dshspool.go
+++ /dev/null
@@ -1,49 +0,0 @@
-package asymptoteobserve
-
-import (
- "path/filepath"
- "strings"
-)
-
-// DSHSpoolRootRel is the workspace-relative directory where sandboxed DeepSeek Harness hooks stage
-// events when the runtime log under ~/.beacon is unreachable from inside the session sandbox
-// (#605). The sandbox confines hook writes to the session's working directory, so this is the one
-// durable location both the hook (inside the sandbox) and `beacon endpoint dsh sync` (outside it)
-// can reach. Each session gets its own directory below it, holding a localingest.Spool.
-var DSHSpoolRootRel = filepath.Join(".beacon", "dsh-spool")
-
-// dshSpoolMaxSessionID bounds the directory name so a hostile or malformed session id cannot
-// produce an unwieldy path. Real ids are UUID-shaped; 128 is far above any of them.
-const dshSpoolMaxSessionID = 128
-
-// ValidDSHSessionIDForSpool reports whether a session id is safe to use as a spool directory name.
-// The id arrives from the runtime's hook payload and from the session store, so the writer and the
-// drainer must agree on exactly which ids get a spool: an id containing a path separator, a leading
-// dot, or anything outside the portable filename alphabet gets no spool at all, on both sides,
-// rather than a sanitized name the other side would never look for.
-func ValidDSHSessionIDForSpool(id string) bool {
- if id == "" || len(id) > dshSpoolMaxSessionID || strings.HasPrefix(id, ".") {
- return false
- }
- for _, r := range id {
- switch {
- case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9':
- case r == '-' || r == '_' || r == '.':
- default:
- return false
- }
- }
- return true
-}
-
-// DSHSpoolDir is the spool directory for one session in one workspace. ok is false when the
-// workspace is empty or the session id is not a safe directory name; the writer then stages
-// nothing and the drainer looks for nothing, which is the agreement ValidDSHSessionIDForSpool
-// exists to keep.
-func DSHSpoolDir(workspace, sessionID string) (dir string, ok bool) {
- workspace = strings.TrimSpace(workspace)
- if workspace == "" || !ValidDSHSessionIDForSpool(sessionID) {
- return "", false
- }
- return filepath.Join(workspace, DSHSpoolRootRel, sessionID), true
-}
diff --git a/pkg/asymptoteobserve/dshspool_test.go b/pkg/asymptoteobserve/dshspool_test.go
deleted file mode 100644
index 4fd28dc0..00000000
--- a/pkg/asymptoteobserve/dshspool_test.go
+++ /dev/null
@@ -1,50 +0,0 @@
-package asymptoteobserve
-
-import (
- "path/filepath"
- "testing"
-)
-
-func TestValidDSHSessionIDForSpool(t *testing.T) {
- cases := []struct {
- id string
- want bool
- }{
- {"60fdb1c1-0000-5000-8000-000000000000", true},
- {"session-abc_123.v2", true},
- {"", false},
- {".", false},
- {"..", false},
- {".hidden", false},
- {"a/b", false},
- {"a\\b", false},
- {"../escape", false},
- {"has space", false},
- {"line\nbreak", false},
- {string(make([]byte, 129)), false},
- }
- for _, tc := range cases {
- if got := ValidDSHSessionIDForSpool(tc.id); got != tc.want {
- t.Errorf("ValidDSHSessionIDForSpool(%q) = %v, want %v", tc.id, got, tc.want)
- }
- }
-}
-
-// The writer and the drainer must derive the same directory from the same inputs, and an unsafe
-// id must yield none on BOTH sides rather than one side's sanitized guess.
-func TestDSHSpoolDirAgreesOnSafeAndUnsafeIDs(t *testing.T) {
- workspace := t.TempDir()
- dir, ok := DSHSpoolDir(workspace, "sess-1")
- if !ok {
- t.Fatal("safe id produced no directory")
- }
- if want := filepath.Join(workspace, ".beacon", "dsh-spool", "sess-1"); dir != want {
- t.Errorf("DSHSpoolDir = %q, want %q", dir, want)
- }
- if _, ok := DSHSpoolDir(workspace, "../evil"); ok {
- t.Error("unsafe id produced a directory")
- }
- if _, ok := DSHSpoolDir(" ", "sess-1"); ok {
- t.Error("empty workspace produced a directory")
- }
-}
diff --git a/pkg/asymptoteobserve/localingest/spool.go b/pkg/asymptoteobserve/localingest/spool.go
index ea402c6a..4c863abe 100644
--- a/pkg/asymptoteobserve/localingest/spool.go
+++ b/pkg/asymptoteobserve/localingest/spool.go
@@ -6,6 +6,7 @@ import (
"context"
"errors"
"fmt"
+ "io"
"os"
"path/filepath"
"time"
@@ -63,7 +64,39 @@ func (s Spool) openNamedLock(name string) (*os.File, error) {
}
// MkdirAll leaves an existing directory's mode alone and is masked by the umask.
_ = os.Chmod(s.Dir, SpoolDirMode)
- return os.OpenFile(filepath.Join(s.Dir, name), os.O_CREATE|os.O_RDWR, SpoolFileMode)
+ return openSpoolFile(filepath.Join(s.Dir, name), os.O_CREATE|os.O_RDWR, SpoolFileMode)
+}
+
+// openSpoolFile opens one of a spool's files, but never through a link at its name, never
+// blocking on a FIFO, and only when it is a regular file. A spool can sit where others write -- a
+// workspace spool is in a directory the sandboxed agent and a checked-out repository can write --
+// so an entry named pending.jsonl is not trusted to be the spool: a planted link would point a
+// drain's reads and an append at another file, and a FIFO would hang the writer.
+func openSpoolFile(path string, flag int, perm os.FileMode) (*os.File, error) {
+ f, err := os.OpenFile(path, flag|openNoFollow|openNonBlock, perm)
+ if err != nil {
+ return nil, err
+ }
+ info, err := f.Stat()
+ if err != nil {
+ _ = f.Close()
+ return nil, err
+ }
+ if !info.Mode().IsRegular() {
+ _ = f.Close()
+ return nil, fmt.Errorf("localingest: %s is not a regular file", path)
+ }
+ return f, nil
+}
+
+// readSpoolFile reads one of a spool's files under openSpoolFile's rules.
+func readSpoolFile(path string) ([]byte, error) {
+ f, err := openSpoolFile(path, os.O_RDONLY, 0)
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+ return io.ReadAll(f)
}
// Append adds lines to the spool and returns how many were dropped because the spool is full or
@@ -73,7 +106,7 @@ func (s Spool) Append(lines [][]byte) (dropped int, err error) {
return 0, nil
}
err = s.withLock(func() (err error) {
- f, err := os.OpenFile(s.FilePath(), os.O_APPEND|os.O_CREATE|os.O_WRONLY, SpoolFileMode)
+ f, err := openSpoolFile(s.FilePath(), os.O_APPEND|os.O_CREATE|os.O_WRONLY, SpoolFileMode)
if err != nil {
return err
}
@@ -128,7 +161,7 @@ func (s Spool) Drain(maxLines int, send func(lines [][]byte) (int, error)) (n in
if maxLines <= 0 {
return 0, nil
}
- if _, err := os.Stat(s.FilePath()); errors.Is(err, os.ErrNotExist) {
+ if _, err := os.Lstat(s.FilePath()); errors.Is(err, os.ErrNotExist) {
return 0, nil
}
drainFile, err := s.openNamedLock(spoolDrainLockName)
@@ -144,7 +177,7 @@ func (s Spool) Drain(maxLines int, send func(lines [][]byte) (int, error)) (n in
var batch [][]byte
if err := s.withLock(func() error {
- data, err := os.ReadFile(s.FilePath())
+ data, err := readSpoolFile(s.FilePath())
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil
@@ -173,7 +206,7 @@ func (s Spool) Drain(maxLines int, send func(lines [][]byte) (int, error)) (n in
return 0, sendErr
}
if err := s.withLock(func() error {
- data, err := os.ReadFile(s.FilePath())
+ data, err := readSpoolFile(s.FilePath())
if err != nil {
return err
}
@@ -210,7 +243,7 @@ func (s Spool) withLock(fn func() error) (err error) {
// Pending reports how many events are spooled and their size.
func (s Spool) Pending() (lines int, size int64, err error) {
- data, err := os.ReadFile(s.FilePath())
+ data, err := readSpoolFile(s.FilePath())
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return 0, 0, nil
diff --git a/pkg/asymptoteobserve/localingest/spool_open_other.go b/pkg/asymptoteobserve/localingest/spool_open_other.go
new file mode 100644
index 00000000..87416742
--- /dev/null
+++ b/pkg/asymptoteobserve/localingest/spool_open_other.go
@@ -0,0 +1,10 @@
+//go:build !unix
+
+package localingest
+
+// openNoFollow and openNonBlock have no open(2) flag here; openSpoolFile's regular-file check still
+// applies.
+const (
+ openNoFollow = 0
+ openNonBlock = 0
+)
diff --git a/pkg/asymptoteobserve/localingest/spool_open_unix.go b/pkg/asymptoteobserve/localingest/spool_open_unix.go
new file mode 100644
index 00000000..8642a4d1
--- /dev/null
+++ b/pkg/asymptoteobserve/localingest/spool_open_unix.go
@@ -0,0 +1,11 @@
+//go:build unix
+
+package localingest
+
+import "syscall"
+
+// openNoFollow and openNonBlock make openSpoolFile refuse a link at the name and not wait on a FIFO.
+const (
+ openNoFollow = syscall.O_NOFOLLOW
+ openNonBlock = syscall.O_NONBLOCK
+)
diff --git a/pkg/asymptoteobserve/localingest/spool_unix_test.go b/pkg/asymptoteobserve/localingest/spool_unix_test.go
new file mode 100644
index 00000000..6d9102bf
--- /dev/null
+++ b/pkg/asymptoteobserve/localingest/spool_unix_test.go
@@ -0,0 +1,56 @@
+//go:build unix
+
+package localingest
+
+import (
+ "os"
+ "path/filepath"
+ "syscall"
+ "testing"
+ "time"
+)
+
+// A workspace spool sits where a checked-out repository can write, so its pending.jsonl is not
+// trusted to be the spool. A planted link must not let an append write, or a drain read and
+// rewrite, the file it points at; a planted FIFO must not hang the hook that opens it.
+func TestSpoolRefusesAPlantedLinkOrFIFOAtItsFile(t *testing.T) {
+ t.Run("link", func(t *testing.T) {
+ s := Spool{Dir: t.TempDir()}
+ target := filepath.Join(t.TempDir(), "elsewhere.jsonl")
+ if err := os.WriteFile(target, []byte("{\"keep\":true}\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(target, s.FilePath()); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.Append([][]byte{[]byte(`{"a":1}`)}); err == nil {
+ t.Fatal("Append wrote through a planted link")
+ }
+ sent := 0
+ if _, err := s.Drain(10, func(lines [][]byte) (int, error) { sent += len(lines); return len(lines), nil }); err == nil || sent != 0 {
+ t.Fatalf("Drain read through a planted link: sent %d, err %v", sent, err)
+ }
+ if data, _ := os.ReadFile(target); string(data) != "{\"keep\":true}\n" {
+ t.Fatalf("the link's target changed: %q", data)
+ }
+ })
+ t.Run("FIFO", func(t *testing.T) {
+ s := Spool{Dir: t.TempDir()}
+ if err := syscall.Mkfifo(s.FilePath(), 0o600); err != nil {
+ t.Skipf("no FIFOs here: %v", err)
+ }
+ done := make(chan error, 1)
+ go func() {
+ _, err := s.Append([][]byte{[]byte(`{"a":1}`)})
+ done <- err
+ }()
+ select {
+ case err := <-done:
+ if err == nil {
+ t.Fatal("Append wrote to a FIFO")
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("Append hung on a planted FIFO")
+ }
+ })
+}
diff --git a/pkg/asymptoteobserve/workspacespool.go b/pkg/asymptoteobserve/workspacespool.go
new file mode 100644
index 00000000..da3c6a71
--- /dev/null
+++ b/pkg/asymptoteobserve/workspacespool.go
@@ -0,0 +1,109 @@
+package asymptoteobserve
+
+import (
+ "encoding/json"
+ "path/filepath"
+ "strings"
+)
+
+// WorkspaceSpoolRootRel is the workspace-relative directory where a hook stages an event it could
+// deliver no other way: not through the collector's socket, not to the runtime log, not to the
+// account's own spool. That is the position of a hook inside a sandbox a runtime builds for its
+// own tools (DeepSeek Harness, #605) or a launcher builds without mounting Beacon in (#1284): the
+// sandbox confines writes to the session's working directory, so the workspace is the one durable
+// place both the hook, inside, and a drain, outside, can reach.
+//
+// Below it, each harness has a directory named by its canonical name, and each session one below
+// that, holding a localingest.Spool: <workspace>/.beacon/spool/<harness>/<session>/.
+// A constant, built with the platform's separator, so package init allocates nothing for it.
+const WorkspaceSpoolRootRel = ".beacon" + string(filepath.Separator) + "spool"
+
+// LegacyDSHSpoolRootRel is where DeepSeek Harness hooks staged events before every harness shared
+// the workspace spool. Nothing writes it any more; drains still empty it, once, for spools an
+// earlier hook left behind.
+const LegacyDSHSpoolRootRel = ".beacon" + string(filepath.Separator) + "dsh-spool"
+
+// spoolNameMax bounds a spool directory name so a hostile or malformed id cannot produce an
+// unwieldy path. Real session ids are UUID-shaped; 128 is far above any of them.
+const spoolNameMax = 128
+
+// ValidSpoolName reports whether a harness name or session id is safe to use as a spool directory
+// name. Both arrive from outside -- a hook payload, a session store, a directory listing -- so the
+// writer and every drainer must agree on exactly which names get a spool: one containing a path
+// separator, a leading dot, or anything outside the portable filename alphabet gets no spool at
+// all, on every side, rather than a sanitized name another side would never look for.
+func ValidSpoolName(name string) bool {
+ if name == "" || len(name) > spoolNameMax || strings.HasPrefix(name, ".") {
+ return false
+ }
+ for _, r := range name {
+ switch {
+ case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9':
+ case r == '-' || r == '_' || r == '.':
+ default:
+ return false
+ }
+ }
+ return true
+}
+
+// WorkspaceSpoolDir is the spool directory for one session of one harness in one workspace. harness
+// is the canonical harness name (NormalizeHarnessName). ok is false when the workspace is empty or
+// either name is unsafe (ValidSpoolName); the writer then stages nothing and a drainer looks for
+// nothing.
+func WorkspaceSpoolDir(workspace, harness, sessionID string) (dir string, ok bool) {
+ workspace = strings.TrimSpace(workspace)
+ if workspace == "" || !ValidSpoolName(harness) || !ValidSpoolName(sessionID) {
+ return "", false
+ }
+ return filepath.Join(workspace, WorkspaceSpoolRootRel, harness, sessionID), true
+}
+
+// LegacyDSHSpoolDir is the spool directory an earlier DeepSeek Harness hook staged one session's
+// events in, under the same agreement as WorkspaceSpoolDir.
+func LegacyDSHSpoolDir(workspace, sessionID string) (dir string, ok bool) {
+ workspace = strings.TrimSpace(workspace)
+ if workspace == "" || !ValidSpoolName(sessionID) {
+ return "", false
+ }
+ return filepath.Join(workspace, LegacyDSHSpoolRootRel, sessionID), true
+}
+
+// AdmitStagedLine reports whether one line from a workspace spool is what a Beacon hook or plugin
+// of harness's session sessionID stages: an endpoint event of that session and harness, captured
+// live, and not an action only Beacon itself writes. Every drain applies it before a line reaches a
+// runtime log.
+//
+// A workspace spool sits where the sandboxed agent, and anything else that can write the
+// workspace, can write by design -- a checked-out repository included -- so its lines are
+// untrusted input, held to the same rule as telemetry from outside (IsBeaconOnlyAction). Without
+// it, a planted spool could append events for any session, or a session.share_requested that
+// Beacon Cloud acts on by publishing a session. A torn line from a killed hook fails to decode and
+// is refused the same way.
+func AdmitStagedLine(line []byte, harness, sessionID string) bool {
+ var event struct {
+ Vendor string `json:"vendor"`
+ Product string `json:"product"`
+ Harness struct {
+ Name string `json:"name"`
+ CollectionMethod string `json:"collection_method"`
+ } `json:"harness"`
+ Session *struct {
+ ID string `json:"id"`
+ } `json:"session"`
+ Event struct {
+ Action string `json:"action"`
+ } `json:"event"`
+ }
+ if err := json.Unmarshal(line, &event); err != nil {
+ return false
+ }
+ method := event.Harness.CollectionMethod
+ return event.Vendor == Vendor &&
+ event.Product == Product &&
+ event.Session != nil && event.Session.ID == sessionID &&
+ event.Harness.Name == harness &&
+ (method == CollectionMethodHook || method == CollectionMethodPlugin) &&
+ event.Event.Action != "" &&
+ !IsBeaconOnlyAction(event.Event.Action)
+}
diff --git a/pkg/asymptoteobserve/workspacespool_test.go b/pkg/asymptoteobserve/workspacespool_test.go
new file mode 100644
index 00000000..b7705ee5
--- /dev/null
+++ b/pkg/asymptoteobserve/workspacespool_test.go
@@ -0,0 +1,111 @@
+package asymptoteobserve
+
+import (
+ "encoding/json"
+ "path/filepath"
+ "testing"
+)
+
+func TestValidSpoolName(t *testing.T) {
+ cases := []struct {
+ name string
+ want bool
+ }{
+ {"60fdb1c1-0000-5000-8000-000000000000", true},
+ {"session-abc_123.v2", true},
+ {"claude_code", true},
+ {"", false},
+ {".", false},
+ {"..", false},
+ {".hidden", false},
+ {"a/b", false},
+ {"a\\b", false},
+ {"../escape", false},
+ {"has space", false},
+ {"line\nbreak", false},
+ {string(make([]byte, 129)), false},
+ }
+ for _, tc := range cases {
+ if got := ValidSpoolName(tc.name); got != tc.want {
+ t.Errorf("ValidSpoolName(%q) = %v, want %v", tc.name, got, tc.want)
+ }
+ }
+}
+
+// The writer and every drainer must derive the same directory from the same inputs, and an unsafe
+// name must yield none on every side rather than one side's sanitized guess.
+func TestWorkspaceSpoolDirAgreesOnSafeAndUnsafeNames(t *testing.T) {
+ workspace := t.TempDir()
+ dir, ok := WorkspaceSpoolDir(workspace, "opencode", "sess-1")
+ if !ok {
+ t.Fatal("safe names produced no directory")
+ }
+ if want := filepath.Join(workspace, ".beacon", "spool", "opencode", "sess-1"); dir != want {
+ t.Errorf("WorkspaceSpoolDir = %q, want %q", dir, want)
+ }
+ for _, tc := range []struct{ workspace, harness, session string }{
+ {workspace, "opencode", "../evil"},
+ {workspace, "../evil", "sess-1"},
+ {workspace, "", "sess-1"},
+ {" ", "opencode", "sess-1"},
+ } {
+ if _, ok := WorkspaceSpoolDir(tc.workspace, tc.harness, tc.session); ok {
+ t.Errorf("WorkspaceSpoolDir(%q, %q, %q) produced a directory", tc.workspace, tc.harness, tc.session)
+ }
+ }
+ if dir, ok := LegacyDSHSpoolDir(workspace, "sess-1"); !ok || dir != filepath.Join(workspace, ".beacon", "dsh-spool", "sess-1") {
+ t.Errorf("LegacyDSHSpoolDir = %q, %v", dir, ok)
+ }
+ if _, ok := LegacyDSHSpoolDir(workspace, "../evil"); ok {
+ t.Error("LegacyDSHSpoolDir produced a directory for an unsafe id")
+ }
+}
+
+// A workspace spool is writable by whatever can write the workspace, so a drain admits only what a
+// Beacon hook or plugin of that very session stages.
+func TestAdmitStagedLine(t *testing.T) {
+ line := func(mutate func(map[string]interface{})) []byte {
+ event := map[string]interface{}{
+ "vendor": Vendor,
+ "product": Product,
+ "harness": map[string]interface{}{"name": "opencode", "collection_method": CollectionMethodPlugin},
+ "session": map[string]interface{}{"id": "sess-1"},
+ "event": map[string]interface{}{"action": "prompt.submitted"},
+ }
+ if mutate != nil {
+ mutate(event)
+ }
+ data, err := json.Marshal(event)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return data
+ }
+ if !AdmitStagedLine(line(nil), "opencode", "sess-1") {
+ t.Fatal("a plugin event of the session was refused")
+ }
+ if !AdmitStagedLine(line(func(e map[string]interface{}) {
+ e["harness"] = map[string]interface{}{"name": "opencode", "collection_method": CollectionMethodHook}
+ }), "opencode", "sess-1") {
+ t.Fatal("a hook event of the session was refused")
+ }
+ for name, tc := range map[string]struct {
+ line []byte
+ harness, session string
+ }{
+ "another session": {line(nil), "opencode", "sess-2"},
+ "another harness": {line(nil), "claude_code", "sess-1"},
+ "no session": {line(func(e map[string]interface{}) { delete(e, "session") }), "opencode", "sess-1"},
+ "poll event": {line(func(e map[string]interface{}) {
+ e["harness"].(map[string]interface{})["collection_method"] = CollectionMethodPoll
+ }), "opencode", "sess-1"},
+ "Beacon-only action": {line(func(e map[string]interface{}) { e["event"] = map[string]interface{}{"action": ActionShareRequested} }), "opencode", "sess-1"},
+ "no action": {line(func(e map[string]interface{}) { e["event"] = map[string]interface{}{} }), "opencode", "sess-1"},
+ "another vendor": {line(func(e map[string]interface{}) { e["vendor"] = "someone-else" }), "opencode", "sess-1"},
+ "torn line": {line(nil)[:20], "opencode", "sess-1"},
+ } {
+ if AdmitStagedLine(tc.line, tc.harness, tc.session) {
+ t.Errorf("%s: admitted", name)
+ }
+ }
+}