The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
Add beacon handoff resume: reopen a session or continue it elsewhere
Claude5da4127c791a
diff --git a/cli/beacon/cmd/handoff.go b/cli/beacon/cmd/handoff.goindex 8a5bd852..0c38aa66 100644--- a/cli/beacon/cmd/handoff.go+++ b/cli/beacon/cmd/handoff.go@@ -15,6 +15,7 @@ import (endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config""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/handoff")@@ -70,36 +71,68 @@ var (handoffNow = time.Now)-// loadHandoffBrief builds the brief for id from the runtime's session store, or from the runtime log-// when the store no longer has the session.-func loadHandoffBrief(id string) (handoff.Brief, error) {+// handoffSubject is the session a handoff command acts on, found in its runtime's store or, when+// the store no longer has it, in Beacon's runtime log.+type handoffSubject struct {+ session handoff.Session+ fromLog bool+ logEvents []schema.Event+}++func resolveHandoffSession(id string) (handoffSubject, error) {harness, err := handoff.ParseHarness(handoffOpts.harness)if err != nil {- return handoff.Brief{}, err+ return handoffSubject{}, err}- sources := handoffSources(handoffOpts.dirs)- session, findErr := handoff.Find(sources, harness, id)+ session, findErr := handoff.Find(handoffSources(handoffOpts.dirs), harness, id)if findErr == nil {- events, err := handoff.Events(sources, session)- if err == nil {- return handoff.BuildBrief(session, events, handoff.FromSessionStore, handoffNow()), nil- }- if !errors.Is(err, handoff.ErrNotFound) {- return handoff.Brief{}, fmt.Errorf("read %s session %s: %w", session.Harness, session.ID, err)- }- id = session.ID- } else if !errors.Is(findErr, handoff.ErrNotFound) {- return handoff.Brief{}, findErr+ return handoffSubject{session: session}, nil}+ if !errors.Is(findErr, handoff.ErrNotFound) {+ return handoffSubject{}, findErr+ }+ return resolveHandoffLogSession(id, harness)+}++func resolveHandoffLogSession(id, harness string) (handoffSubject, error) {logPath := handoffRuntimeLogPath()- logSession, events, found, err := handoff.LogSession(logPath, id)+ session, events, found, err := handoff.LogSession(logPath, id)if err != nil {- return handoff.Brief{}, fmt.Errorf("read runtime log %s: %w", logPath, err)+ return handoffSubject{}, fmt.Errorf("read runtime log %s: %w", logPath, err)}- if !found || (harness != "" && logSession.Harness != harness) {- return handoff.Brief{}, fmt.Errorf("%w: %s (not in any runtime session store or in %s; `beacon handoff list` shows what is available)", handoff.ErrNotFound, id, logPath)+ if !found || (harness != "" && session.Harness != harness) {+ return handoffSubject{}, fmt.Errorf("%w: %s (not in any runtime session store or in %s; `beacon handoff list` shows what is available)", handoff.ErrNotFound, id, logPath)+ }+ return handoffSubject{session: session, fromLog: true, logEvents: events}, nil+}++// brief builds the subject's brief. A session its store loses between lookup and read falls back to+// the runtime log.+func (subject handoffSubject) brief() (handoff.Brief, error) {+ if subject.fromLog {+ return handoff.BuildBrief(subject.session, subject.logEvents, handoff.FromRuntimeLog, handoffNow()), nil+ }+ session := subject.session+ events, err := handoff.Events(handoffSources(handoffOpts.dirs), session)+ if err == nil {+ return handoff.BuildBrief(session, events, handoff.FromSessionStore, handoffNow()), nil+ }+ if !errors.Is(err, handoff.ErrNotFound) {+ return handoff.Brief{}, fmt.Errorf("read %s session %s: %w", session.Harness, session.ID, err)+ }+ logSubject, logErr := resolveHandoffLogSession(session.ID, session.Harness)+ if logErr != nil {+ return handoff.Brief{}, logErr+ }+ return logSubject.brief()+}++func loadHandoffBrief(id string) (handoff.Brief, error) {+ subject, err := resolveHandoffSession(id)+ if err != nil {+ return handoff.Brief{}, err}- return handoff.BuildBrief(logSession, events, handoff.FromRuntimeLog, handoffNow()), nil+ return subject.brief()}func handoffRuntimeLogPath() string {diff --git a/cli/beacon/cmd/handoff_resume.go b/cli/beacon/cmd/handoff_resume.gonew file mode 100644index 00000000..3653e2b8--- /dev/null+++ b/cli/beacon/cmd/handoff_resume.go@@ -0,0 +1,170 @@+package cmd++import (+ "bufio"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "os"+ "os/exec"+ "path/filepath"+ "strings"++ "github.com/spf13/cobra"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/handoff"+)++type handoffResumeOptions struct {+ agent string+ newOnly bool+ cwd string+ print bool+ yes bool+ jsonPlan bool+}++var handoffResumeOpts handoffResumeOptions++var handoffResumeCmd = &cobra.Command{+ Use: "resume <session-id>",+ Short: "Pick a session up again, in its own runtime or another one",+ Long: `Pick a session up again, in its own runtime or another one.++When the session's own runtime can reopen it, it is reopened with its full context:+ claude --resume <id>, codex resume <id>, opencode --session <id>, cline --tui --id <id>++Otherwise, or with --agent naming another runtime or --new, Beacon writes a handoff brief of the+session and starts a new session whose first message points at it. The brief is passed by path,+never inlined into the command line.++The runtime runs in the session's directory, in this terminal. Beacon asks before launching unless+--yes is given; --print shows what would run without writing or launching anything. Cline is always+started with --auto-approve false.`,+ Args: cobra.ExactArgs(1),+ SilenceUsage: true,+ RunE: runHandoffResume,+}++// Swapped by tests.+var (+ handoffLookPath = exec.LookPath+ handoffLaunch = handoff.Launch+ handoffIsTerminal = func() bool { return isTerminal(os.Stdin) && isTerminal(os.Stdout) }+ handoffStdin io.Reader = os.Stdin+ handoffExit = os.Exit+)++func runHandoffResume(cmd *cobra.Command, args []string) error {+ opts := handoffResumeOpts+ if opts.jsonPlan && !opts.print {+ return errors.New("--json describes the plan and needs --print")+ }+ target, err := handoff.ParseHarness(opts.agent)+ if err != nil {+ return fmt.Errorf("--agent: %w", err)+ }+ subject, err := resolveHandoffSession(args[0])+ if err != nil {+ return err+ }+ session := subject.session+ now := handoffNow()+ plan, err := handoff.PlanResume(session, handoff.PlanOptions{+ Target: target,+ ForceNew: opts.newOnly,+ Dir: opts.cwd,+ FromRuntimeLog: subject.fromLog,+ BriefPath: filepath.Join(handoffBriefDir(), handoff.BriefFileName(session, now)),+ LookPath: handoffLookPath,+ })+ if err != nil {+ return err+ }++ out, errOut := cmd.OutOrStdout(), cmd.ErrOrStderr()+ if opts.print {+ if opts.jsonPlan {+ encoder := json.NewEncoder(out)+ encoder.SetIndent("", " ")+ return encoder.Encode(plan)+ }+ describeHandoffPlan(out, plan)+ return nil+ }+ describeHandoffPlan(errOut, plan)+ if !opts.yes {+ if !handoffIsTerminal() {+ return errors.New("not running in a terminal; pass --yes to launch, or --print to see the command")+ }+ if !confirmHandoff(handoffStdin, errOut) {+ fmt.Fprintln(errOut, "Cancelled.")+ return nil+ }+ }+ if plan.Mode == handoff.ModeNewSession {+ brief, err := subject.brief()+ if err != nil {+ return err+ }+ brief.GeneratedAt = now.UTC()+ if err := handoff.WriteBriefAt(plan.BriefPath, brief); err != nil {+ return err+ }+ }+ code, err := handoffLaunch(plan, handoffStdin, out, errOut)+ if err != nil {+ return fmt.Errorf("start %s: %w", plan.Executable, err)+ }+ if code != 0 {+ // The runtime has already reported whatever went wrong; Beacon passes its status through.+ if code < 0 {+ code = 1+ }+ handoffExit(code)+ }+ return nil+}++func describeHandoffPlan(w io.Writer, plan handoff.Plan) {+ source := plan.Source+ switch plan.Mode {+ case handoff.ModeNative:+ fmt.Fprintf(w, "Reopening %s session %s in %s\n", handoff.RuntimeLabel(source.Harness), source.ID, plan.Dir)+ default:+ fmt.Fprintf(w, "Starting a new %s session from %s session %s (%s)\n",+ handoff.RuntimeLabel(plan.Target), handoff.RuntimeLabel(source.Harness), source.ID, handoff.ReasonText(plan.Reason))+ fmt.Fprintf(w, " brief: %s\n", plan.BriefPath)+ fmt.Fprintf(w, " directory: %s\n", plan.Dir)+ }+ fmt.Fprintf(w, " command: %s\n", shellCommand(append([]string{plan.Executable}, plan.Args...)...))+}++func confirmHandoff(in io.Reader, w io.Writer) bool {+ fmt.Fprint(w, "Continue? [Y/n] ")+ line, err := bufio.NewReader(in).ReadString('\n')+ if err != nil && line == "" {+ fmt.Fprintln(w)+ return false+ }+ switch strings.ToLower(strings.TrimSpace(line)) {+ case "", "y", "yes":+ return true+ }+ return false+}++func init() {+ handoffCmd.AddCommand(handoffResumeCmd)+ addHandoffStoreFlags(handoffResumeCmd)+ f := handoffResumeCmd.Flags()+ f.StringVar(&handoffResumeOpts.agent, "agent", "", "Runtime to continue in: claude, codex, opencode or cline (default the session's own)")+ f.BoolVar(&handoffResumeOpts.newOnly, "new", false, "Start a new session from a brief even when the session could be reopened")+ f.StringVar(&handoffResumeOpts.cwd, "cwd", "", "Directory to start the runtime in (default the session's directory)")+ f.BoolVar(&handoffResumeOpts.print, "print", false, "Show what would run without writing a brief or launching anything")+ f.BoolVar(&handoffResumeOpts.yes, "yes", false, "Launch without asking")+ f.BoolVar(&handoffResumeOpts.jsonPlan, "json", false, "With --print, describe the plan as JSON")+ f.StringVar(&handoffOpts.outputDir, "output-dir", "", "Directory to write the brief into (default ~/.beacon/endpoint/handoffs)")+ f.StringVar(&handoffOpts.logPath, "log-path", "", "Runtime JSONL log to fall back to (default the local runtime log)")+}diff --git a/cli/beacon/cmd/handoff_resume_test.go b/cli/beacon/cmd/handoff_resume_test.gonew file mode 100644index 00000000..de3bfce7--- /dev/null+++ b/cli/beacon/cmd/handoff_resume_test.go@@ -0,0 +1,331 @@+package cmd++import (+ "encoding/json"+ "errors"+ "io"+ "os"+ "os/exec"+ "path/filepath"+ "regexp"+ "strings"+ "testing"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/handoff"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"+)++// resumeFixture is a Claude session whose directory and transcript exist, served by a stub store.+type resumeFixture struct {+ session handoff.Session+ briefDir string+ launched []handoff.Plan+ exitCode int+ exitCalled int+}++func newResumeFixture(t *testing.T) *resumeFixture {+ t.Helper()+ stubHandoffClock(t)+ f := &resumeFixture{briefDir: filepath.Join(t.TempDir(), "handoffs")}+ transcript := filepath.Join(t.TempDir(), "claude-1.jsonl")+ if err := os.WriteFile(transcript, []byte("{}\n"), 0o600); err != nil {+ t.Fatal(err)+ }+ f.session = handoff.Session{Harness: handoff.HarnessClaude, ID: "claude-1", Directory: t.TempDir(), SourcePath: transcript}+ stubHandoffSources(t, stubHandoffSource{+ harness: handoff.HarnessClaude,+ sessions: []handoff.Session{f.session},+ events: []schema.Event{{+ Timestamp: "2026-09-25T10:00:00Z",+ Event: schema.EventInfo{Action: "prompt.submitted"},+ Prompt: &schema.PromptInfo{Text: "add a health endpoint"},+ }},+ })++ prevLook, prevLaunch, prevTerm, prevStdin, prevExit := handoffLookPath, handoffLaunch, handoffIsTerminal, handoffStdin, handoffExit+ handoffLookPath = func(name string) (string, error) {+ if name == "claude" || name == "codex" {+ return "/bin/" + name, nil+ }+ return "", exec.ErrNotFound+ }+ handoffLaunch = func(plan handoff.Plan, _ io.Reader, _, _ io.Writer) (int, error) {+ f.launched = append(f.launched, plan)+ return f.exitCode, nil+ }+ handoffIsTerminal = func() bool { return true }+ handoffStdin = strings.NewReader("\n")+ handoffExit = func(code int) { f.exitCalled = code }+ t.Cleanup(func() {+ handoffLookPath, handoffLaunch, handoffIsTerminal, handoffStdin, handoffExit = prevLook, prevLaunch, prevTerm, prevStdin, prevExit+ })+ return f+}++func runResume(t *testing.T, f *resumeFixture, args ...string) (string, string, error) {+ t.Helper()+ handoffResumeOpts = handoffResumeOptions{}+ return runHandoff(t, append([]string{"resume", "--output-dir", f.briefDir}, args...)...)+}++func TestHandoffResumeCommandRegistered(t *testing.T) {+ cmd, _, err := rootCmd.Find([]string{"handoff", "resume"})+ if err != nil || cmd == nil || cmd.Name() != "resume" {+ t.Fatalf("handoff resume not registered: %v", err)+ }+ for _, flag := range []string{"agent", "new", "cwd", "print", "yes", "json", "output-dir", "log-path", "harness", "claude-projects-dir", "codex-dir", "opencode-dir", "cline-dir"} {+ if cmd.Flags().Lookup(flag) == nil {+ t.Fatalf("handoff resume missing --%s", flag)+ }+ }+}++func TestHandoffResumeReopensNativelyAfterConfirmation(t *testing.T) {+ f := newResumeFixture(t)+ _, stderr, err := runResume(t, f, "claude-1")+ if err != nil {+ t.Fatalf("resume: %v", err)+ }+ if len(f.launched) != 1 {+ t.Fatalf("launched %d times", len(f.launched))+ }+ plan := f.launched[0]+ if plan.Mode != handoff.ModeNative || plan.Executable != "/bin/claude" || strings.Join(plan.Args, " ") != "--resume claude-1" || plan.Dir != f.session.Directory {+ t.Fatalf("plan = %+v", plan)+ }+ if !strings.Contains(stderr, "Reopening Claude Code session claude-1") || !strings.Contains(stderr, "command: /bin/claude --resume claude-1") || !strings.Contains(stderr, "Continue? [Y/n]") {+ t.Fatalf("stderr = %q", stderr)+ }+ if entries, _ := os.ReadDir(f.briefDir); len(entries) != 0 {+ t.Fatalf("a native resume must not write a brief, found %d files", len(entries))+ }+ if f.exitCalled != 0 {+ t.Fatalf("a clean exit must not call exit, got %d", f.exitCalled)+ }+}++func TestHandoffResumeInAnotherRuntimeWritesTheBriefFirst(t *testing.T) {+ f := newResumeFixture(t)+ var briefAtLaunch string+ handoffLaunch = func(plan handoff.Plan, _ io.Reader, _, _ io.Writer) (int, error) {+ data, err := os.ReadFile(plan.BriefPath)+ if err != nil {+ t.Fatalf("the brief must exist before the runtime starts: %v", err)+ }+ briefAtLaunch = string(data)+ f.launched = append(f.launched, plan)+ return 0, nil+ }+ _, stderr, err := runResume(t, f, "claude-1", "--agent", "codex", "--yes")+ if err != nil {+ t.Fatalf("resume: %v", err)+ }+ plan := f.launched[0]+ if plan.Mode != handoff.ModeNewSession || plan.Target != handoff.HarnessCodex || plan.Executable != "/bin/codex" {+ t.Fatalf("plan = %+v", plan)+ }+ if filepath.Dir(plan.BriefPath) != f.briefDir || !strings.Contains(plan.Args[0], plan.BriefPath) {+ t.Fatalf("the prompt should name the brief in the output dir: %q / %q", plan.BriefPath, plan.Args)+ }+ if strings.Contains(plan.Args[0], "add a health endpoint") {+ t.Fatal("the brief must be passed by path, never inlined on the command line")+ }+ if !strings.Contains(briefAtLaunch, "add a health endpoint") || !strings.Contains(briefAtLaunch, "Brief written: 2026-09-25T12:00:00Z") {+ t.Fatalf("brief at launch:\n%s", briefAtLaunch)+ }+ if strings.Contains(stderr, "Continue?") {+ t.Fatal("--yes must not ask")+ }+ if !strings.Contains(stderr, "Starting a new Codex CLI session from Claude Code session claude-1 (it continues in a different runtime)") {+ t.Fatalf("stderr = %q", stderr)+ }+}++func TestHandoffResumePrintWritesAndLaunchesNothing(t *testing.T) {+ f := newResumeFixture(t)+ out, _, err := runResume(t, f, "claude-1", "--new", "--print")+ if err != nil {+ t.Fatalf("resume --print: %v", err)+ }+ if len(f.launched) != 0 {+ t.Fatal("--print launched the runtime")+ }+ if _, err := os.Stat(f.briefDir); !os.IsNotExist(err) {+ t.Fatalf("--print must not write a brief or create its directory: %v", err)+ }+ if !strings.Contains(out, "(a new session was requested)") || !regexp.MustCompile(`command: /bin/claude 'Continue the work from an earlier Claude Code session\. Beacon wrote a handoff brief of it at `).MatchString(out) {+ t.Fatalf("--print output:\n%s", out)+ }++ jsonOut, _, err := runResume(t, f, "claude-1", "--print", "--json")+ if err != nil {+ t.Fatalf("resume --print --json: %v", err)+ }+ var plan handoff.Plan+ if err := json.Unmarshal([]byte(jsonOut), &plan); err != nil || plan.Mode != handoff.ModeNative || plan.Source.ID != "claude-1" {+ t.Fatalf("plan json = %+v, %v\n%s", plan, err, jsonOut)+ }+ if _, _, err := runResume(t, f, "claude-1", "--json"); err == nil || !strings.Contains(err.Error(), "needs --print") {+ t.Fatalf("--json without --print err = %v", err)+ }+}++func TestHandoffResumeAsksAndCanBeDeclined(t *testing.T) {+ f := newResumeFixture(t)+ for _, answer := range []string{"n\n", "no\n", "later\n", ""} {+ handoffStdin = strings.NewReader(answer)+ _, stderr, err := runResume(t, f, "claude-1", "--new")+ if err != nil {+ t.Fatalf("declined resume returned an error: %v", err)+ }+ if !strings.Contains(stderr, "Cancelled.") {+ t.Fatalf("answer %q: stderr = %q", answer, stderr)+ }+ }+ if len(f.launched) != 0 {+ t.Fatal("a declined resume launched the runtime")+ }+ if _, err := os.Stat(f.briefDir); !os.IsNotExist(err) {+ t.Fatal("a declined resume must not write a brief")+ }+ for _, answer := range []string{"y\n", "YES\n", "\n"} {+ handoffStdin = strings.NewReader(answer)+ if _, _, err := runResume(t, f, "claude-1"); err != nil {+ t.Fatal(err)+ }+ }+ if len(f.launched) != 3 {+ t.Fatalf("accepted resumes launched %d times, want 3", len(f.launched))+ }+}++func TestHandoffResumeRefusesToLaunchWithoutATerminal(t *testing.T) {+ f := newResumeFixture(t)+ handoffIsTerminal = func() bool { return false }+ if _, _, err := runResume(t, f, "claude-1"); err == nil || !strings.Contains(err.Error(), "pass --yes") {+ t.Fatalf("err = %v", err)+ }+ if len(f.launched) != 0 {+ t.Fatal("launched without a terminal or --yes")+ }+ if _, _, err := runResume(t, f, "claude-1", "--yes"); err != nil || len(f.launched) != 1 {+ t.Fatalf("--yes launches without a terminal: %v", err)+ }+}++func TestHandoffResumePassesTheRuntimeExitCodeThrough(t *testing.T) {+ f := newResumeFixture(t)+ f.exitCode = 3+ if _, _, err := runResume(t, f, "claude-1", "--yes"); err != nil {+ t.Fatal(err)+ }+ if f.exitCalled != 3 {+ t.Fatalf("exit = %d, want the runtime's 3", f.exitCalled)+ }+ f.exitCode = -1+ if _, _, err := runResume(t, f, "claude-1", "--yes"); err != nil {+ t.Fatal(err)+ }+ if f.exitCalled != 1 {+ t.Fatalf("a runtime killed by a signal should exit 1, got %d", f.exitCalled)+ }+}++func TestHandoffResumeErrors(t *testing.T) {+ f := newResumeFixture(t)+ if _, _, err := runResume(t, f, "claude-1", "--agent", "opencode", "--yes"); !errors.Is(err, handoff.ErrRuntimeNotInstalled) {+ t.Fatalf("uninstalled target err = %v", err)+ }+ if _, _, err := runResume(t, f, "claude-1", "--agent", "cursor"); err == nil || !strings.Contains(err.Error(), "--agent") {+ t.Fatalf("unsupported --agent err = %v", err)+ }+ handoffLaunch = func(handoff.Plan, io.Reader, io.Writer, io.Writer) (int, error) {+ return -1, errors.New("exec format error")+ }+ if _, _, err := runResume(t, f, "claude-1", "--yes"); err == nil || !strings.Contains(err.Error(), "start /bin/claude: exec format error") {+ t.Fatalf("launch failure err = %v", err)+ }+ if _, _, err := runResume(t, f, "nope-123", "--log-path", filepath.Join(t.TempDir(), "none.jsonl")); !errors.Is(err, handoff.ErrNotFound) {+ t.Fatalf("unknown session err = %v", err)+ }+}++func TestHandoffResumeFromTheRuntimeLogStartsANewSession(t *testing.T) {+ f := newResumeFixture(t)+ logPath := handoffLog(t, "cursor", "cursor-conv-1", "rename the module")+ dir := t.TempDir()+ _, _, err := runResume(t, f, "cursor-conv-1", "--log-path", logPath, "--agent", "claude", "--cwd", dir, "--yes")+ if err != nil {+ t.Fatalf("resume: %v", err)+ }+ plan := f.launched[0]+ if plan.Mode != handoff.ModeNewSession || plan.Reason != handoff.ReasonOtherRuntime || plan.Dir != dir {+ t.Fatalf("plan = %+v", plan)+ }+ data, err := os.ReadFile(plan.BriefPath)+ if err != nil || !strings.Contains(string(data), "rename the module") || !strings.Contains(string(data), "runtime log") {+ t.Fatalf("log brief: %v\n%s", err, data)+ }+}++// Runs the real launcher against fake runtime executables on PATH, the way a person would run it.+func TestHandoffResumeEndToEndWithFakeRuntimes(t *testing.T) {+ testenv.RequirePOSIXExecutableFixtures(t)+ f := newResumeFixture(t)+ handoffLookPath, handoffLaunch = exec.LookPath, handoff.Launch+ bin := t.TempDir()+ record := filepath.Join(t.TempDir(), "record")+ for _, name := range []string{"claude", "codex"} {+ script := "#!/bin/sh\n{ echo \"exe=" + name + "\"; echo \"cwd=$(pwd)\"; for a in \"$@\"; do echo \"arg=$a\"; done; } > " + record + "\nexit 0\n"+ if err := os.WriteFile(filepath.Join(bin, name), []byte(script), 0o755); err != nil {+ t.Fatal(err)+ }+ }+ t.Setenv("PATH", bin)++ if _, _, err := runResume(t, f, "claude-1", "--yes"); err != nil {+ t.Fatalf("native resume: %v", err)+ }+ got := readRecord(t, record)+ realDir, _ := filepath.EvalSymlinks(f.session.Directory)+ if got["exe"][0] != "claude" || strings.Join(got["arg"], " ") != "--resume claude-1" || (got["cwd"][0] != f.session.Directory && got["cwd"][0] != realDir) {+ t.Fatalf("native run = %v", got)+ }++ if _, _, err := runResume(t, f, "claude-1", "--agent", "codex", "--yes"); err != nil {+ t.Fatalf("new session: %v", err)+ }+ got = readRecord(t, record)+ if got["exe"][0] != "codex" || len(got["arg"]) != 1 {+ t.Fatalf("new session run = %v", got)+ }+ path := regexp.MustCompile(`at (\S+\.md)\.`).FindStringSubmatch(got["arg"][0])+ if path == nil {+ t.Fatalf("prompt names no brief: %q", got["arg"][0])+ }+ data, err := os.ReadFile(path[1])+ if err != nil || !strings.Contains(string(data), "add a health endpoint") {+ t.Fatalf("the brief the runtime was pointed at: %v\n%s", err, data)+ }+ if testenv.HasPOSIXFileModes() {+ if info, _ := os.Stat(path[1]); info.Mode().Perm() != 0o600 {+ t.Fatalf("brief mode = %o", info.Mode().Perm())+ }+ }+}++func readRecord(t *testing.T, path string) map[string][]string {+ t.Helper()+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ out := map[string][]string{}+ for _, line := range strings.Split(strings.TrimSpace(string(data)), "\n") {+ key, value, _ := strings.Cut(line, "=")+ out[key] = append(out[key], value)+ }+ return out+}diff --git a/cli/beacon/cmd/handoff_test.go b/cli/beacon/cmd/handoff_test.goindex 778059dd..eadafa76 100644--- a/cli/beacon/cmd/handoff_test.go+++ b/cli/beacon/cmd/handoff_test.go@@ -47,6 +47,7 @@ func stubHandoffSources(t *testing.T, sources ...handoff.Source) *handoff.StoreDfunc runHandoff(t *testing.T, args ...string) (string, string, error) {t.Helper()handoffOpts = handoffOptions{}+ handoffResumeOpts = handoffResumeOptions{}for _, cmd := range handoffCmd.Commands() {cmd.Flags().VisitAll(func(f *pflag.Flag) {_ = f.Value.Set(f.DefValue)diff --git a/cli/beacon/internal/handoff/launch.go b/cli/beacon/internal/handoff/launch.gonew file mode 100644index 00000000..eebb1cdc--- /dev/null+++ b/cli/beacon/internal/handoff/launch.go@@ -0,0 +1,33 @@+package handoff++import (+ "errors"+ "io"+ "os"+ "os/exec"+ "os/signal"+)++// Launch runs the plan's runtime in the current terminal and waits for it, returning its exit+// code. The runtime owns the terminal while it runs: an interrupt reaches it through the terminal's+// process group, so Beacon ignores the interrupt itself instead of exiting underneath it.+func Launch(plan Plan, stdin io.Reader, stdout, stderr io.Writer) (int, error) {+ cmd := exec.Command(plan.Executable, plan.Args...)+ cmd.Dir = plan.Dir+ cmd.Stdin, cmd.Stdout, cmd.Stderr = stdin, stdout, stderr+ cmd.Env = os.Environ()++ interrupts := make(chan os.Signal, 1)+ signal.Notify(interrupts, os.Interrupt)+ defer signal.Stop(interrupts)++ err := cmd.Run()+ var exitErr *exec.ExitError+ if errors.As(err, &exitErr) {+ return exitErr.ExitCode(), nil+ }+ if err != nil {+ return -1, err+ }+ return 0, nil+}diff --git a/cli/beacon/internal/handoff/resume.go b/cli/beacon/internal/handoff/resume.gonew file mode 100644index 00000000..4c7f4fdf--- /dev/null+++ b/cli/beacon/internal/handoff/resume.go@@ -0,0 +1,220 @@+package handoff++import (+ "errors"+ "fmt"+ "os"+ "strings"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/clinesession"+)++// Resume modes.+const (+ // ModeNative reopens the session itself in its own runtime, with its full context.+ ModeNative = "native"+ // ModeNewSession starts a fresh session that is pointed at a brief of the old one.+ ModeNewSession = "new_session"+)++// Why a resume starts a new session instead of reopening the old one.+const (+ ReasonRequested = "requested"+ ReasonOtherRuntime = "other_runtime"+ ReasonNotResumable = "not_resumable"+ ReasonSessionGone = "session_file_missing"+ ReasonFromRuntimeLog = "runtime_log_only"+)++// runtimeCommand is how Beacon starts one runtime's CLI. Every argument vector was checked against+// that CLI's own --help.+type runtimeCommand struct {+ Executable string+ // Resume returns the arguments that reopen session, or ok=false when this runtime's CLI cannot+ // reopen it.+ Resume func(session Session) (args []string, ok bool)+ // NewSession returns the arguments that start an interactive session with prompt as its first+ // message.+ NewSession func(prompt string) []string+}++var runtimeCommands = map[string]runtimeCommand{+ HarnessClaude: {+ Executable: "claude",+ Resume: func(s Session) ([]string, bool) {+ // A subagent transcript is a sidechain of its parent; `claude --resume` reopens+ // top-level sessions only.+ if s.Subagent {+ return nil, false+ }+ return []string{"--resume", s.ID}, true+ },+ NewSession: func(prompt string) []string { return []string{prompt} },+ },+ HarnessCodex: {+ Executable: "codex",+ Resume: func(s Session) ([]string, bool) { return []string{"resume", s.ID}, true },+ NewSession: func(prompt string) []string { return []string{prompt} },+ },+ HarnessOpenCode: {+ Executable: "opencode",+ Resume: func(s Session) ([]string, bool) { return []string{"--session", s.ID}, true },+ NewSession: func(prompt string) []string { return []string{"--prompt", prompt} },+ },+ HarnessCline: {+ // Cline approves every tool call unless told otherwise. A session Beacon starts never+ // gains that on Beacon's say-so; the user can still turn it on inside the TUI.+ Executable: "cline",+ Resume: func(s Session) ([]string, bool) {+ // `cline --id` reopens CLI sessions; the older task history and subagent threads are+ // not sessions it can load.+ if s.Store != clinesession.SourceMessages || s.Subagent {+ return nil, false+ }+ return []string{"--tui", "--auto-approve", "false", "--id", s.ID}, true+ },+ NewSession: func(prompt string) []string {+ return []string{"--tui", "--auto-approve", "false", prompt}+ },+ },+}++// Plan is a resolved resume: what will run, where, and why.+type Plan struct {+ Mode string `json:"mode"`+ Reason string `json:"reason,omitempty"`+ Source Session `json:"source"`+ Target string `json:"target"`+ Executable string `json:"executable"`+ Args []string `json:"args"`+ Dir string `json:"dir"`+ // BriefPath is where the brief for a new session is written. It is empty for a native resume.+ BriefPath string `json:"brief_path,omitempty"`+}++// PlanOptions steer how a session is picked up.+type PlanOptions struct {+ // Target is the runtime to continue in. Empty means the session's own runtime.+ Target string+ // ForceNew starts a new session even when the session could be reopened.+ ForceNew bool+ // Dir overrides the directory the runtime starts in.+ Dir string+ // FromRuntimeLog marks a session known only from Beacon's runtime log, which no runtime can+ // reopen.+ FromRuntimeLog bool+ // BriefPath is where a new session's brief will be written.+ BriefPath string+ // LookPath resolves an executable on PATH; exec.LookPath outside tests.+ LookPath func(string) (string, error)+}++// ErrRuntimeNotInstalled reports that the runtime to continue in is not on PATH.+var ErrRuntimeNotInstalled = errors.New("runtime is not installed")++// PlanResume decides how to pick session up. It reopens the session natively when it can: same+// runtime, a runtime CLI that can load it, and its session file still present. Otherwise it starts+// a new session in the target runtime, pointed at a brief. The target runtime must be on PATH.+func PlanResume(session Session, opts PlanOptions) (Plan, error) {+ target := session.Harness+ if opts.Target != "" {+ target = opts.Target+ }+ targetCommand, ok := runtimeCommands[target]+ if !ok {+ return Plan{}, fmt.Errorf("%s sessions cannot be started by beacon handoff (supported: claude, codex, opencode, cline)", target)+ }+ dir, err := resumeDir(session, opts.Dir)+ if err != nil {+ return Plan{}, err+ }+ plan := Plan{Source: session, Target: target, Dir: dir}++ executable, err := opts.LookPath(targetCommand.Executable)+ if err != nil {+ return Plan{}, fmt.Errorf("%w: %s (%s was not found on PATH)", ErrRuntimeNotInstalled, RuntimeLabel(target), targetCommand.Executable)+ }+ plan.Executable = executable+ reason := nativeBlocker(session, target, opts)+ if reason == "" {+ plan.Mode, plan.Args = ModeNative, nativeArgs(targetCommand, session)+ return plan, nil+ }+ if opts.BriefPath == "" {+ return Plan{}, errors.New("a new session needs a brief path")+ }+ plan.Mode, plan.Reason = ModeNewSession, reason+ plan.BriefPath = opts.BriefPath+ plan.Args = targetCommand.NewSession(NewSessionPrompt(session, opts.BriefPath))+ return plan, nil+}++func nativeArgs(command runtimeCommand, session Session) []string {+ args, _ := command.Resume(session)+ return args+}++// nativeBlocker returns why session cannot be reopened in target, or "" when it can be.+func nativeBlocker(session Session, target string, opts PlanOptions) string {+ switch {+ case opts.ForceNew:+ return ReasonRequested+ case target != session.Harness:+ return ReasonOtherRuntime+ case opts.FromRuntimeLog:+ return ReasonFromRuntimeLog+ }+ if _, ok := runtimeCommands[target].Resume(session); !ok {+ return ReasonNotResumable+ }+ if session.SourcePath == "" {+ return ReasonSessionGone+ }+ if _, err := os.Stat(session.SourcePath); err != nil {+ return ReasonSessionGone+ }+ return ""+}++// resumeDir is the directory the runtime starts in. A runtime reopens and scopes a session by its+// directory, so a session whose directory is gone does not start anywhere else by accident.+func resumeDir(session Session, override string) (string, error) {+ dir := strings.TrimSpace(override)+ if dir == "" {+ dir = session.Directory+ }+ if dir == "" {+ return "", fmt.Errorf("%s session %s has no recorded directory; pass --cwd", session.Harness, session.ID)+ }+ info, err := os.Stat(dir)+ if err != nil || !info.IsDir() {+ return "", fmt.Errorf("directory %s does not exist on this machine; pass --cwd to start somewhere else", dir)+ }+ return dir, nil+}++// NewSessionPrompt is the first message of a session started from a brief. It names the brief by+// path rather than inlining it: the brief carries prompt text and command output, and a command+// line is visible to every local user through the process table.+func NewSessionPrompt(session Session, briefPath string) string {+ return fmt.Sprintf("Continue the work from an earlier %s session. Beacon wrote a handoff brief of it at %s. "++ "Read that file first, then tell me what you understand the task to be and wait for me to confirm before changing anything.",+ RuntimeLabel(session.Harness), briefPath)+}++// ReasonText explains a new-session reason to a person.+func ReasonText(reason string) string {+ switch reason {+ case ReasonRequested:+ return "a new session was requested"+ case ReasonOtherRuntime:+ return "it continues in a different runtime"+ case ReasonNotResumable:+ return "this runtime's CLI cannot reopen this kind of session"+ case ReasonSessionGone:+ return "the session file is no longer on this machine"+ case ReasonFromRuntimeLog:+ return "the session is known only from Beacon's runtime log"+ }+ return reason+}diff --git a/cli/beacon/internal/handoff/resume_test.go b/cli/beacon/internal/handoff/resume_test.gonew file mode 100644index 00000000..e4aaff7f--- /dev/null+++ b/cli/beacon/internal/handoff/resume_test.go@@ -0,0 +1,259 @@+package handoff++import (+ "errors"+ "os"+ "path/filepath"+ "reflect"+ "strings"+ "testing"++ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"+)++// installed resolves the named executables to /bin/<name>, as if they were on PATH.+func installed(names ...string) func(string) (string, error) {+ return func(name string) (string, error) {+ for _, n := range names {+ if n == name {+ return "/bin/" + name, nil+ }+ }+ return "", errors.New("executable file not found in $PATH")+ }+}++var allRuntimes = installed("claude", "codex", "opencode", "cline")++// resumableSession is a session whose directory and session file both exist.+func resumableSession(t *testing.T, harness, id string) Session {+ t.Helper()+ dir := t.TempDir()+ file := filepath.Join(t.TempDir(), id+".jsonl")+ writeFixture(t, file, "{}\n")+ s := Session{Harness: harness, ID: id, Directory: dir, SourcePath: file}+ if harness == HarnessCline {+ s.Store = "messages"+ }+ return s+}++func TestPlanResumeReopensEachRuntimeNatively(t *testing.T) {+ for _, tc := range []struct {+ harness, exe string+ args []string+ }{+ {HarnessClaude, "claude", []string{"--resume", "s-1"}},+ {HarnessCodex, "codex", []string{"resume", "s-1"}},+ {HarnessOpenCode, "opencode", []string{"--session", "s-1"}},+ {HarnessCline, "cline", []string{"--tui", "--auto-approve", "false", "--id", "s-1"}},+ } {+ t.Run(tc.harness, func(t *testing.T) {+ session := resumableSession(t, tc.harness, "s-1")+ plan, err := PlanResume(session, PlanOptions{LookPath: allRuntimes})+ if err != nil {+ t.Fatalf("PlanResume: %v", err)+ }+ if plan.Mode != ModeNative || plan.Reason != "" || plan.BriefPath != "" {+ t.Fatalf("plan = %+v, want a native resume with no brief", plan)+ }+ if plan.Executable != "/bin/"+tc.exe || !reflect.DeepEqual(plan.Args, tc.args) {+ t.Fatalf("command = %s %q, want /bin/%s %q", plan.Executable, plan.Args, tc.exe, tc.args)+ }+ if plan.Dir != session.Directory || plan.Target != tc.harness {+ t.Fatalf("dir/target = %q/%q", plan.Dir, plan.Target)+ }+ })+ }+}++func TestPlanResumeStartsANewSessionInEachRuntime(t *testing.T) {+ brief := "/home/me/.beacon/endpoint/handoffs/brief.md"+ for _, tc := range []struct {+ target, exe string+ prefix []string+ }{+ {HarnessClaude, "claude", nil},+ {HarnessCodex, "codex", nil},+ {HarnessOpenCode, "opencode", []string{"--prompt"}},+ {HarnessCline, "cline", []string{"--tui", "--auto-approve", "false"}},+ } {+ t.Run(tc.target, func(t *testing.T) {+ source := HarnessCodex+ if tc.target == HarnessCodex {+ source = HarnessClaude+ }+ session := resumableSession(t, source, "s-1")+ plan, err := PlanResume(session, PlanOptions{Target: tc.target, BriefPath: brief, LookPath: allRuntimes})+ if err != nil {+ t.Fatalf("PlanResume: %v", err)+ }+ if plan.Mode != ModeNewSession || plan.Reason != ReasonOtherRuntime || plan.BriefPath != brief {+ t.Fatalf("plan = %+v", plan)+ }+ want := append(append([]string{}, tc.prefix...), NewSessionPrompt(session, brief))+ if plan.Executable != "/bin/"+tc.exe || !reflect.DeepEqual(plan.Args, want) {+ t.Fatalf("command = %s %q\nwant /bin/%s %q", plan.Executable, plan.Args, tc.exe, want)+ }+ })+ }+}++func TestNewSessionPromptPointsAtTheBriefWithoutInliningIt(t *testing.T) {+ prompt := NewSessionPrompt(Session{Harness: HarnessClaude}, "/tmp/b.md")+ for _, want := range []string{"earlier Claude Code session", "/tmp/b.md", "Read that file first", "wait for me to confirm"} {+ if !strings.Contains(prompt, want) {+ t.Fatalf("prompt %q is missing %q", prompt, want)+ }+ }+}++func TestPlanResumeFallsBackToANewSession(t *testing.T) {+ brief := "/tmp/brief.md"+ cases := []struct {+ name string+ edit func(*Session, *PlanOptions)+ reason string+ }{+ {"requested", func(s *Session, o *PlanOptions) { o.ForceNew = true }, ReasonRequested},+ {"session file deleted", func(s *Session, o *PlanOptions) { os.Remove(s.SourcePath) }, ReasonSessionGone},+ {"no session file recorded", func(s *Session, o *PlanOptions) { s.SourcePath = "" }, ReasonSessionGone},+ {"known only from the runtime log", func(s *Session, o *PlanOptions) { o.FromRuntimeLog = true }, ReasonFromRuntimeLog},+ {"claude subagent", func(s *Session, o *PlanOptions) { s.Subagent = true }, ReasonNotResumable},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ session := resumableSession(t, HarnessClaude, "s-1")+ opts := PlanOptions{BriefPath: brief, LookPath: allRuntimes}+ tc.edit(&session, &opts)+ plan, err := PlanResume(session, opts)+ if err != nil {+ t.Fatalf("PlanResume: %v", err)+ }+ if plan.Mode != ModeNewSession || plan.Reason != tc.reason || plan.Target != HarnessClaude {+ t.Fatalf("plan = %+v, want a new claude session because %s", plan, tc.reason)+ }+ if ReasonText(plan.Reason) == plan.Reason {+ t.Fatalf("reason %q has no human text", plan.Reason)+ }+ })+ }+}++func TestPlanResumeClineOnlyReopensCLISessions(t *testing.T) {+ for _, tc := range []struct {+ name string+ edit func(*Session)+ }{+ {"task history", func(s *Session) { s.Store = "history" }},+ {"subagent thread", func(s *Session) { s.Subagent = true }},+ } {+ t.Run(tc.name, func(t *testing.T) {+ session := resumableSession(t, HarnessCline, "c-1")+ tc.edit(&session)+ plan, err := PlanResume(session, PlanOptions{BriefPath: "/tmp/b.md", LookPath: allRuntimes})+ if err != nil {+ t.Fatal(err)+ }+ if plan.Mode != ModeNewSession || plan.Reason != ReasonNotResumable {+ t.Fatalf("plan = %+v", plan)+ }+ if !reflect.DeepEqual(plan.Args[:3], []string{"--tui", "--auto-approve", "false"}) {+ t.Fatalf("a new Cline session must also turn auto-approve off: %q", plan.Args)+ }+ })+ }+}++// Every command Beacon builds for Cline must turn auto-approve off, because Cline defaults to+// approving every tool call.+func TestEveryClineCommandTurnsAutoApproveOff(t *testing.T) {+ command := runtimeCommands[HarnessCline]+ resume, _ := command.Resume(Session{ID: "x", Store: "messages"})+ for _, args := range [][]string{resume, command.NewSession("p")} {+ joined := strings.Join(args, " ")+ if !strings.Contains(joined, "--auto-approve false") {+ t.Fatalf("cline args %q do not turn auto-approve off", args)+ }+ }+}++func TestPlanResumeErrors(t *testing.T) {+ session := resumableSession(t, HarnessClaude, "s-1")++ if _, err := PlanResume(session, PlanOptions{LookPath: installed("codex")}); !errors.Is(err, ErrRuntimeNotInstalled) || !strings.Contains(err.Error(), "claude was not found") {+ t.Fatalf("missing runtime err = %v", err)+ }+ if _, err := PlanResume(session, PlanOptions{Target: HarnessCodex, BriefPath: "/b", LookPath: installed("claude")}); !errors.Is(err, ErrRuntimeNotInstalled) {+ t.Fatalf("missing target runtime err = %v", err)+ }+ if _, err := PlanResume(session, PlanOptions{Target: "cursor", LookPath: allRuntimes}); err == nil || !strings.Contains(err.Error(), "cannot be started") {+ t.Fatalf("unsupported target err = %v", err)+ }+ if _, err := PlanResume(Session{Harness: "cursor", ID: "x", Directory: t.TempDir()}, PlanOptions{LookPath: allRuntimes}); err == nil {+ t.Fatal("a session from an unsupported runtime needs --agent")+ }+ if _, err := PlanResume(session, PlanOptions{ForceNew: true, LookPath: allRuntimes}); err == nil || !strings.Contains(err.Error(), "brief path") {+ t.Fatalf("a new session without a brief path err = %v", err)+ }+}++func TestPlanResumeDirectory(t *testing.T) {+ session := resumableSession(t, HarnessCodex, "s-1")++ other := t.TempDir()+ plan, err := PlanResume(session, PlanOptions{Dir: other, LookPath: allRuntimes})+ if err != nil || plan.Dir != other {+ t.Fatalf("--cwd override = %q, %v", plan.Dir, err)+ }++ gone := session+ gone.Directory = filepath.Join(t.TempDir(), "deleted")+ if _, err := PlanResume(gone, PlanOptions{LookPath: allRuntimes}); err == nil || !strings.Contains(err.Error(), "--cwd") {+ t.Fatalf("a missing directory must not silently start elsewhere: %v", err)+ }+ unknown := session+ unknown.Directory = ""+ if _, err := PlanResume(unknown, PlanOptions{LookPath: allRuntimes}); err == nil || !strings.Contains(err.Error(), "no recorded directory") {+ t.Fatalf("no directory err = %v", err)+ }+ file := filepath.Join(t.TempDir(), "file")+ writeFixture(t, file, "x")+ if _, err := PlanResume(session, PlanOptions{Dir: file, LookPath: allRuntimes}); err == nil {+ t.Fatal("a file is not a directory to start in")+ }+}++func TestLaunchRunsInTheSessionDirectoryAndReturnsTheExitCode(t *testing.T) {+ testenv.RequirePOSIXExecutableFixtures(t)+ bin := t.TempDir()+ script := filepath.Join(bin, "fake-agent")+ writeFixture(t, script, "#!/bin/sh\npwd\nprintf '%s|' \"$@\"\necho\nread line\necho \"got $line\"\necho oops >&2\nexit 7\n")+ if err := os.Chmod(script, 0o755); err != nil {+ t.Fatal(err)+ }+ dir := t.TempDir()+ var stdout, stderr strings.Builder+ code, err := Launch(Plan{Executable: script, Args: []string{"--resume", "a b"}, Dir: dir}, strings.NewReader("hello\n"), &stdout, &stderr)+ if err != nil {+ t.Fatalf("Launch: %v", err)+ }+ if code != 7 {+ t.Fatalf("exit code = %d, want the runtime's own", code)+ }+ realDir, _ := filepath.EvalSymlinks(dir)+ lines := strings.Split(strings.TrimSpace(stdout.String()), "\n")+ if len(lines) != 3 || (lines[0] != dir && lines[0] != realDir) || lines[1] != "--resume|a b|" || lines[2] != "got hello" {+ t.Fatalf("stdout = %q; the runtime runs in the plan directory with its arguments intact and the terminal's stdin", stdout.String())+ }+ if strings.TrimSpace(stderr.String()) != "oops" {+ t.Fatalf("stderr = %q", stderr.String())+ }+}++func TestLaunchReportsAMissingExecutable(t *testing.T) {+ code, err := Launch(Plan{Executable: filepath.Join(t.TempDir(), "missing"), Dir: t.TempDir()}, nil, nil, nil)+ if err == nil || code != -1 {+ t.Fatalf("Launch = %d, %v", code, err)+ }+}diff --git a/cli/beacon/internal/handoff/write.go b/cli/beacon/internal/handoff/write.goindex ba0ff770..ceb98d5c 100644--- a/cli/beacon/internal/handoff/write.go+++ b/cli/beacon/internal/handoff/write.go@@ -8,33 +8,39 @@ import ("time")-// WriteBrief stores a rendered brief under dir and returns its path. The directory is private to-// the user (0700) and the file is 0600, because a brief carries prompt text and command output.-// An existing file is never overwritten.+// WriteBrief stores a rendered brief under dir and returns its path. See WriteBriefAt.func WriteBrief(dir string, brief Brief) (string, error) {+ path := filepath.Join(dir, BriefFileName(brief.Session, brief.GeneratedAt))+ return path, WriteBriefAt(path, brief)+}++// WriteBriefAt stores a rendered brief at path. Its directory is private to the user (0700) and the+// file is 0600, because a brief carries prompt text and command output. An existing file is never+// overwritten.+func WriteBriefAt(path string, brief Brief) error {+ dir := filepath.Dir(path)if err := os.MkdirAll(dir, 0o700); err != nil {- return "", fmt.Errorf("create handoff directory: %w", err)+ return fmt.Errorf("create handoff directory: %w", err)}// MkdirAll leaves an existing directory's mode alone; a brief directory someone widened is// narrowed again before anything is written into it.if err := os.Chmod(dir, 0o700); err != nil {- return "", fmt.Errorf("restrict handoff directory: %w", err)+ return fmt.Errorf("restrict handoff directory: %w", err)}- path := filepath.Join(dir, BriefFileName(brief.Session, brief.GeneratedAt))f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)if err != nil {- return "", fmt.Errorf("create handoff brief: %w", err)+ return fmt.Errorf("create handoff brief: %w", err)}if _, err := f.WriteString(brief.Render()); err != nil {f.Close()os.Remove(path)- return "", fmt.Errorf("write handoff brief: %w", err)+ return fmt.Errorf("write handoff brief: %w", err)}if err := f.Close(); err != nil {os.Remove(path)- return "", fmt.Errorf("write handoff brief: %w", err)+ return fmt.Errorf("write handoff brief: %w", err)}- return path, nil+ return nil}// BriefFileName names a brief after its runtime, session and the moment it was written. Session idsdiff --git a/docs/cli/handoff.mdx b/docs/cli/handoff.mdxindex c751a408..dd1e1851 100644--- a/docs/cli/handoff.mdx+++ b/docs/cli/handoff.mdx@@ -10,6 +10,7 @@ description: "Pick up a local agent session again, in the same runtime or anothe```bash title="Command syntax"beacon handoff list [flags]beacon handoff export <session-id> [flags]+beacon handoff resume <session-id> [flags]```Sessions come from each runtime's own local session store, not from Beacon's runtime log. That store is what the runtime resumes from, and it keeps content the runtime log truncates. Every read is local and read-only: nothing is uploaded, and no runtime file is changed.@@ -80,3 +81,52 @@ Briefs are written to `~/.beacon/endpoint/handoffs`. The directory is `0700` and| `--log-path` | Runtime log to fall back to. Defaults to the local runtime log. || `--json` | Print `{"path", "from", "session"}`. `from` is `session_store` or `runtime_log`. || `--harness` and the `--*-dir` flags | As for `list`. |++## `beacon handoff resume`++Picks a session up again, in its own runtime or another one.++```bash+beacon handoff resume 7f3c2a91 # reopen it where it ran+beacon handoff resume 7f3c2a91 --agent codex # continue a Claude Code session in Codex+beacon handoff resume 7f3c2a91 --new # a fresh session in the same runtime, from a brief+beacon handoff resume 7f3c2a91 --print # show what would run; writes and launches nothing+```++There are two ways to resume:++- **Reopen natively.** Beacon reopens the session with its full context when all of these hold: it continues in the same runtime, that runtime's CLI can load this kind of session, and the session file is still on this machine.++ | Runtime | Command |+ |---------|---------|+ | Claude Code | `claude --resume <id>` |+ | Codex CLI | `codex resume <id>` |+ | OpenCode | `opencode --session <id>` |+ | Cline | `cline --tui --auto-approve false --id <id>` |++- **Start a new session from a brief.** Otherwise, or with `--agent` naming another runtime or with `--new`, Beacon writes a brief (see `export`) and starts a new session. The first message of that session points at the brief:++ | Runtime | Command |+ |---------|---------|+ | Claude Code | `claude "<prompt>"` |+ | Codex CLI | `codex "<prompt>"` |+ | OpenCode | `opencode --prompt "<prompt>"` |+ | Cline | `cline --tui --auto-approve false "<prompt>"` |++ The prompt names the brief by its path and asks the agent to read it, then confirm the task before changing anything. The brief is never inlined into the command line, because a command line is visible to every local user through the process table.++Claude Code and Cline subagent sessions, and Cline's older task history, can't be reopened by their CLIs, so they always continue from a brief. A session known only from Beacon's runtime log also continues from a brief, and it needs `--agent` if its own runtime isn't one of the four above.++Cline approves every tool call by default. Beacon always passes `--auto-approve false`, so a session Beacon starts never gets auto-approval on Beacon's say-so. You can still turn it on inside the Cline TUI.++The runtime runs in this terminal, in the session's recorded directory. If that directory no longer exists, Beacon stops rather than starting somewhere else; pass `--cwd` to choose a directory. Beacon prints the plan and asks `Continue? [Y/n]` before launching. Without a terminal, it launches only with `--yes`. `beacon handoff resume` exits with the runtime's own exit code.++| Flag | Description |+|------|-------------|+| `--agent` | Runtime to continue in: `claude`, `codex`, `opencode`, or `cline`. Defaults to the session's own runtime. |+| `--new` | Start a new session from a brief even when the session could be reopened. |+| `--cwd` | Directory to start the runtime in. |+| `--print` | Show the plan and command without writing a brief or launching anything. |+| `--json` | With `--print`, describe the plan as JSON (`mode`, `reason`, `target`, `executable`, `args`, `dir`, `brief_path`). |+| `--yes` | Launch without asking. |+| `--output-dir`, `--log-path`, `--harness`, and the `--*-dir` flags | As for `export`. |