Skip to content

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

dsh_hook_capture: warn on unreadable evidence, scan every retained archive

Clauded2a399f28a64
diff --git a/cli/beacon/cmd/endpoint_dsh_doctor.go b/cli/beacon/cmd/endpoint_dsh_doctor.go
index a8be1929..8d1e12ad 100644
--- a/cli/beacon/cmd/endpoint_dsh_doctor.go
+++ b/cli/beacon/cmd/endpoint_dsh_doctor.go
@@ -9,6 +9,7 @@ import (
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/diagnostics"
endpointhooks "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/hooks"
endpointintegrations "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/integrations"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
)
@@ -62,43 +63,62 @@ func dshHookCaptureCheckAt(logPath, hooksPath, dshHome string) diagnostics.Check
Severity: diagnostics.SeverityInfo,
}
+ // Evidence that cannot be read is a warning, not a pass. Doctor's text output prints only
+ // failures and warnings, so an ok here would tell the operator hook capture had been checked
+ // when it had not been.
+ unreadable := func(evidence, what string, err error) diagnostics.Check {
+ check.Status = diagnostics.StatusWarn
+ check.Severity = diagnostics.SeverityLow
+ check.Evidence = evidence
+ check.Message = "could not verify DeepSeek Harness hook capture: " + what + " could not be read: " + err.Error()
+ check.Action = "check that this user can read " + what + ", then run beacon endpoint doctor again"
+ return check
+ }
+
// The hooks file is rewritten wholesale by every install and repair, so its modification time
// is when the current hook commands took effect. Sessions before it were never going to be
// captured live and are not evidence of anything.
hooksInfo, err := os.Stat(hooksPath)
if err != nil {
- check.Message = "DeepSeek Harness hooks file could not be read: " + err.Error()
- check.Evidence = "dsh_hooks_unreadable"
- return check
+ return unreadable("dsh_hooks_unreadable", "the hooks file "+hooksPath, err)
}
installedAt := hooksInfo.ModTime()
store, err := dshsession.NewStore(dshHome)
if err != nil {
- check.Message = "DeepSeek Harness session store could not be resolved: " + err.Error()
- check.Evidence = "dsh_sessions_unreadable"
- return check
+ return unreadable("dsh_sessions_unreadable", "the DeepSeek Harness session store", err)
}
refs, err := store.List()
if err != nil {
- check.Message = "DeepSeek Harness session store could not be read: " + err.Error()
- check.Evidence = "dsh_sessions_unreadable"
- return check
+ return unreadable("dsh_sessions_unreadable", "the DeepSeek Harness session store "+store.SessionsDir, err)
}
- // The newest archive is read as well as the live log: a busy machine rotates at 10 MiB, and
- // hook events that moved to runtime.jsonl.1 would otherwise make captured sessions read as
- // missed.
+ // Every retained archive is read, newest first, stopping at the first that holds a hook event:
+ // archives are strictly older than the file before them, so that event is the latest one. Poll
+ // backfill writes into the same log, so on a busy machine the last hook event can sit several
+ // rotations back while capture is working fine.
+ //
var lastHook time.Time
hookSeen := false
- for _, path := range []string{logPath, logPath + ".1"} {
+ paths := writer.RetainedLogPaths(logPath)
+ for _, path := range paths {
if ts, ok := endpointintegrations.LastHarnessEventByCollectionMethod(path, dshsession.Harness, asymptoteobserve.CollectionMethodHook); ok {
hookSeen = true
- if ts.After(lastHook) {
- lastHook = ts
- }
+ lastHook = ts
+ break
}
}
+ // Once the oldest archive slot is occupied, rotation has started discarding history, and a
+ // session last written before the oldest retained event has no evidence either way: its hook
+ // events, if it had any, are gone. Such sessions are not counted. Before that slot fills,
+ // nothing has been discarded and every session since install is fair evidence.
+ var oldestRetained time.Time
+ if len(paths) > 0 {
+ if first, ok := endpointintegrations.FirstEventTime(paths[len(paths)-1]); ok {
+ oldestRetained = first
+ }
+ }
+
// A session is missed when it was written after the hooks took effect and after the last live
// hook event, by more than the commit gap. Taking the later of the two lets a machine that
// captured fine and later moved to a sandboxed mode be flagged too, not only a fresh install.
@@ -111,7 +131,7 @@ func dshHookCaptureCheckAt(logPath, hooksPath, dshHome string) diagnostics.Check
var newest time.Time
for _, ref := range refs {
modified := time.UnixMilli(ref.ModTimeUnixMS)
- if modified.Before(installedAt) {
+ if modified.Before(installedAt) || modified.Before(oldestRetained) {
continue
}
sinceInstall++
diff --git a/cli/beacon/cmd/endpoint_dsh_doctor_test.go b/cli/beacon/cmd/endpoint_dsh_doctor_test.go
index 371914dd..b8d33ef4 100644
--- a/cli/beacon/cmd/endpoint_dsh_doctor_test.go
+++ b/cli/beacon/cmd/endpoint_dsh_doctor_test.go
@@ -1,6 +1,7 @@
package cmd
import (
+ "fmt"
"os"
"path/filepath"
"strings"
@@ -12,6 +13,7 @@ import (
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/diagnostics"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/harness"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
)
// DeepSeek Harness runs hook commands sandboxed to the session workspace unless the sandbox mode is
@@ -275,3 +277,76 @@ func TestDshHookCaptureReadsTheRotatedArchive(t *testing.T) {
t.Fatalf("status = %s, want ok when the hook event is in the rotated archive (%s)", got.Status, got.Message)
}
}
+
+// Evidence doctor cannot read is a warning, not a pass: doctor's text output prints only failures
+// and warnings, so an ok would report hook capture as checked when it was not.
+func TestDshHookCaptureWarnsWhenEvidenceIsUnreadable(t *testing.T) {
+ f := newDshDoctorFixture(t)
+ if err := os.Remove(f.hooksPath); err != nil {
+ t.Fatal(err)
+ }
+
+ got := f.check()
+ if got.Status != diagnostics.StatusWarn || got.Evidence != "dsh_hooks_unreadable" {
+ t.Fatalf("status/evidence = %s/%s, want warn/dsh_hooks_unreadable (%s)", got.Status, got.Evidence, got.Message)
+ }
+ if !strings.Contains(got.Message, f.hooksPath) || got.Action == "" {
+ t.Fatalf("the warning does not name what could not be read, or has no action: %+v", got)
+ }
+}
+
+// writeArchive writes one rotated archive of the runtime log holding the given lines.
+func (f dshDoctorFixture) writeArchive(t *testing.T, index int, lines ...string) {
+ t.Helper()
+ body := ""
+ for _, l := range lines {
+ body += l + "\n"
+ }
+ if err := os.WriteFile(fmt.Sprintf("%s.%d", f.logPath, index), []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func dshLogLine(method string, ts time.Time) string {
+ return `{"timestamp":"` + ts.UTC().Format(time.RFC3339Nano) + `","harness":{"name":"deepseek_harness","collection_method":"` + method + `"}}`
+}
+
+// Poll backfill writes into the same log, so on a busy machine the last hook event can sit several
+// rotations back. Every retained archive is read, not only the newest one.
+func TestDshHookCaptureReadsEveryRetainedArchive(t *testing.T) {
+ f := newDshDoctorFixture(t)
+ hookAt := f.installedAt.Add(time.Hour)
+ // The oldest retained slot holds the hook event; every newer file holds only poll events.
+ oldest := writer.DefaultRotateArchives
+ f.writeArchive(t, oldest, dshLogLine("hook", hookAt))
+ for i := oldest - 1; i >= 1; i-- {
+ f.writeArchive(t, i, dshLogLine("poll", hookAt.Add(time.Duration(oldest-i)*time.Second)))
+ }
+ f.event(t, "poll", hookAt.Add(time.Minute))
+ f.session(t, "sess-a", hookAt.Add(time.Minute))
+
+ if got := f.check(); got.Status != diagnostics.StatusOK || got.Evidence != "dsh_hook_events_observed" {
+ t.Fatalf("status/evidence = %s/%s, want ok when the last hook event is in archive .%d (%s)", got.Status, got.Evidence, oldest, got.Message)
+ }
+}
+
+// Once every archive slot is in use, rotation has started discarding history. A session older than
+// the oldest retained event may have had hook events that are gone, so it is not reported as missed.
+func TestDshHookCaptureIgnoresSessionsOlderThanRetainedHistory(t *testing.T) {
+ f := newDshDoctorFixture(t)
+ historyStart := f.installedAt.Add(10 * time.Hour)
+ for i := writer.DefaultRotateArchives; i >= 1; i-- {
+ f.writeArchive(t, i, dshLogLine("poll", historyStart.Add(time.Duration(writer.DefaultRotateArchives-i)*time.Minute)))
+ }
+ f.session(t, "before-history", f.installedAt.Add(time.Hour))
+
+ if got := f.check(); got.Status != diagnostics.StatusOK {
+ t.Fatalf("status = %s, want ok for a session older than the retained log history (%s)", got.Status, got.Message)
+ }
+
+ // A session inside the retained history with no hook event is still flagged.
+ f.session(t, "inside-history", historyStart.Add(time.Hour))
+ if got := f.check(); got.Status != diagnostics.StatusWarn || !strings.Contains(got.Message, "1 DeepSeek Harness session(s)") {
+ t.Fatalf("status = %s, want warn counting only the session inside the history (%s)", got.Status, got.Message)
+ }
+}
diff --git a/cli/beacon/internal/endpoint/integrations/logscan.go b/cli/beacon/internal/endpoint/integrations/logscan.go
index a3b59076..828262d5 100644
--- a/cli/beacon/internal/endpoint/integrations/logscan.go
+++ b/cli/beacon/internal/endpoint/integrations/logscan.go
@@ -91,6 +91,34 @@ func LastHarnessEventByCollectionMethod(logPath, harnessName, method string) (ti
return lastHarnessEvent(logPath, harnessName, method)
}
+// FirstEventTime returns the timestamp of the first event in logPath that carries a parseable one.
+// For a rotated archive that is the start of the history the file holds. Only the head of the file
+// is read.
+func FirstEventTime(logPath string) (time.Time, bool) {
+ if logPath == "" {
+ return time.Time{}, false
+ }
+ file, err := os.Open(logPath)
+ if err != nil {
+ return time.Time{}, false
+ }
+ defer file.Close()
+ scanner := bufio.NewScanner(file)
+ scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
+ for lines := 0; lines < 100 && scanner.Scan(); lines++ {
+ var event struct {
+ Timestamp string `json:"timestamp"`
+ }
+ if err := json.Unmarshal(scanner.Bytes(), &event); err != nil {
+ continue
+ }
+ if parsed, err := time.Parse(time.RFC3339Nano, event.Timestamp); err == nil {
+ return parsed, true
+ }
+ }
+ return time.Time{}, false
+}
+
func lastHarnessEvent(logPath, harnessName, method string) (time.Time, bool) {
if logPath == "" || strings.TrimSpace(harnessName) == "" {
return time.Time{}, false
diff --git a/cli/beacon/internal/endpoint/writer/writer.go b/cli/beacon/internal/endpoint/writer/writer.go
index 5b8f6cf8..f688e8a0 100644
--- a/cli/beacon/internal/endpoint/writer/writer.go
+++ b/cli/beacon/internal/endpoint/writer/writer.go
@@ -233,6 +233,23 @@ func openRuntimeFile(path string, flag int) (*os.File, error) {
return f, nil
}
+// RetainedLogPaths returns the runtime log at path followed by every archive the rotation contract
+// keeps for it, newest first: path, path.1, ..., path.N for N = DefaultRotateArchives. Readers that
+// need history older than the live file -- the last event of some kind, say -- walk this list
+// rather than guessing how many archives exist. The hook adapter and the beaconjson exporter rotate
+// with the same count, so the list covers whichever process wrote the log.
+func RetainedLogPaths(path string) []string {
+ if path == "" {
+ return nil
+ }
+ paths := make([]string, 0, DefaultRotateArchives+1)
+ paths = append(paths, path)
+ for i := 1; i <= DefaultRotateArchives; i++ {
+ paths = append(paths, path+fmt.Sprintf(".%d", i))
+ }
+ return paths
+}
+
func rotateIfNeeded(path string, maxSize int64, archives int, nextWriteBytes int64) error {
if maxSize <= 0 {
return nil
diff --git a/cli/beacon/internal/endpoint/writer/writer_test.go b/cli/beacon/internal/endpoint/writer/writer_test.go
index fda0c4fe..7349c14a 100644
--- a/cli/beacon/internal/endpoint/writer/writer_test.go
+++ b/cli/beacon/internal/endpoint/writer/writer_test.go
@@ -402,3 +402,49 @@ func TestAppendEventCollapsesTheHookAndCollectorReportsOfOneCall(t *testing.T) {
t.Fatalf("one Bash call was recorded %d times: %s", len(lines), string(data))
}
}
+
+// RetainedLogPaths must name exactly the files rotation keeps: a reader walking it for history
+// older than the live file (doctor's dsh_hook_capture looks for the last hook event) would
+// otherwise miss an archive, or look for one that can never exist.
+func TestRetainedLogPathsMatchesWhatRotationKeeps(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "runtime.jsonl")
+ for i := 0; i < DefaultRotateArchives*2+3; i++ {
+ event := schema.NewEvent(schema.NewEventOptions{
+ Action: "agent.detected",
+ Harness: schema.HarnessInfo{Name: "test"},
+ Message: "event " + strconv.Itoa(i),
+ })
+ if _, err := AppendEvent(event, Options{Path: path, RotateSize: 1}); err != nil {
+ t.Fatalf("AppendEvent %d: %v", i, err)
+ }
+ }
+
+ retained := RetainedLogPaths(path)
+ if len(retained) != DefaultRotateArchives+1 || retained[0] != path {
+ t.Fatalf("RetainedLogPaths = %v, want the live log then %d archives", retained, DefaultRotateArchives)
+ }
+ want := map[string]bool{}
+ for _, p := range retained {
+ want[p] = true
+ if _, err := os.Stat(p); err != nil {
+ t.Fatalf("%s is listed as retained but rotation did not keep it: %v", p, err)
+ }
+ }
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, entry := range entries {
+ name := filepath.Join(dir, entry.Name())
+ if strings.HasSuffix(name, ".lock") {
+ continue
+ }
+ if !want[name] {
+ t.Fatalf("rotation kept %s, which RetainedLogPaths does not list", name)
+ }
+ }
+ if got := RetainedLogPaths(""); got != nil {
+ t.Fatalf("RetainedLogPaths(\"\") = %v, want nil", got)
+ }
+}
diff --git a/docs/cli/endpoint-doctor.mdx b/docs/cli/endpoint-doctor.mdx
index 6e343ba9..d380d4f3 100644
--- a/docs/cli/endpoint-doctor.mdx
+++ b/docs/cli/endpoint-doctor.mdx
@@ -58,7 +58,7 @@ dsh_hook_capture: warn target=deepseek_harness (2 DeepSeek Harness session(s) ra
action="run `beacon endpoint dsh sync` to backfill those sessions from DeepSeek's session store; ..."
```
-Doctor cannot reproduce the sandbox, because running the hook command from doctor runs it outside `dsh`, where it succeeds. So the check compares evidence instead. It counts native sessions that DeepSeek wrote after the hooks were installed and more than a few minutes after the last event with `harness.collection_method=hook`. Each of those is a session the live hooks did not capture. The other cause is a `dsh` process that was already running when the hooks were installed and has not been restarted.
+Doctor cannot reproduce the sandbox, because running the hook command from doctor runs it outside `dsh`, where it succeeds. So the check compares evidence instead. It counts native sessions that DeepSeek wrote after the hooks were installed and more than a few minutes after the last event with `harness.collection_method=hook`. The live log and every rotated archive are searched for that event. Each of those sessions is one the live hooks did not capture. Once rotation has started discarding history, sessions older than the oldest retained event are not counted, because their hook events may have rotated out. Evidence doctor cannot read, such as a missing hooks file, is reported as a warning rather than a pass. The other cause is a `dsh` process that was already running when the hooks were installed and has not been restarted.
This is a warning, not a failure. The sandbox mode is the operator's choice in `dsh`, and Beacon does not change it. `--fix` lists the check as a manual skip. See [Live hooks and the DeepSeek Harness sandbox](/runtimes/deepseek-harness#live-hooks-and-the-deepseek-harness-sandbox).