Skip to content

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

Merge handoff 2/5 into handoff 3/5 and hand the runtime absolute paths

Claudeca04e35133e7
diff --cc cli/beacon/cmd/handoff.go
index 0c38aa66,6984393b..88f32379
--- a/cli/beacon/cmd/handoff.go
+++ b/cli/beacon/cmd/handoff.go
@@@ -71,70 -70,69 +70,92 @@@ 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)
- var notFound *handoff.NotFoundError
- switch {
- case 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
- case !errors.As(findErr, &notFound):
- return handoff.Brief{}, findErr
+ session, findErr := handoff.Find(handoffSources(handoffOpts.dirs), harness, id)
+ if findErr == nil {
+ return handoffSubject{session: session}, nil
}
- if !errors.Is(findErr, handoff.ErrNotFound) {
- logSession, events, err := loadHandoffLogSession(id, harness, notFound)
- if err != nil {
- return handoff.Brief{}, err
++ var notFound *handoff.NotFoundError
++ if !errors.As(findErr, &notFound) {
+ return handoffSubject{}, findErr
}
- return resolveHandoffLogSession(id, harness)
- return handoff.BuildBrief(logSession, events, handoff.FromRuntimeLog, handoffNow()), nil
++ return resolveHandoffLogSession(id, harness, notFound)
}
- func resolveHandoffLogSession(id, harness string) (handoffSubject, error) {
-// loadHandoffLogSession finds id in the runtime log. It refuses a session whose own store could not
-// be read: that session may well still be there, and a brief from the log would keep less of it
++// resolveHandoffLogSession finds id in the runtime log. It refuses a session whose own store could
++// not be read: that session may well still be there, and a brief from the log would keep less of it
+ // than the store does.
-func loadHandoffLogSession(id, harness string, notFound *handoff.NotFoundError) (handoff.Session, []schema.Event, error) {
++func resolveHandoffLogSession(id, harness string, notFound *handoff.NotFoundError) (handoffSubject, error) {
logPath := handoffRuntimeLogPath()
session, events, found, err := handoff.LogSession(logPath, id)
if err != nil {
- return handoff.Session{}, nil, fmt.Errorf("read runtime log %s: %w", logPath, err)
+ return handoffSubject{}, fmt.Errorf("read runtime log %s: %w", logPath, err)
}
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)
+ if notFound == nil {
+ notFound = &handoff.NotFoundError{ID: id}
+ }
- return handoff.Session{}, nil, fmt.Errorf("%w; not in the runtime log %s either (`beacon handoff list` shows what is available)", notFound, logPath)
++ return handoffSubject{}, fmt.Errorf("%w; not in the runtime log %s either (`beacon handoff list` shows what is available)", notFound, logPath)
+ }
+ if notFound != nil {
+ if storeErr := notFound.UnreadableStore(session.Harness); storeErr != nil {
- return handoff.Session{}, nil, fmt.Errorf("the %s session store could not be read (%v); fix that rather than build the brief from the runtime log, which keeps less", session.Harness, storeErr.Err)
++ return handoffSubject{}, fmt.Errorf("the %s session store could not be read (%v); fix that rather than build the brief from the runtime log, which keeps less", session.Harness, storeErr.Err)
+ }
}
- return session, events, nil
+ 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)
++ logSubject, logErr := resolveHandoffLogSession(session.ID, session.Harness, nil)
+ 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 subject.brief()
}
+ // handoffLogReason says why a session was read from the runtime log.
+ func handoffLogReason(session handoff.Session) string {
+ for _, harness := range handoff.Harnesses {
+ if harness == session.Harness {
+ return fmt.Sprintf("%s session %s is no longer in its runtime's store", session.Harness, session.ID)
+ }
+ }
+ return fmt.Sprintf("beacon handoff does not read %s session stores", session.Harness)
+ }
+
func handoffRuntimeLogPath() string {
return lifecycle.ResolveRuntimeLog(true, handoffOpts.logPath).EffectiveLogPath
}
diff --cc cli/beacon/cmd/handoff_resume.go
index 3653e2b8,00000000..7627d965
mode 100644,000000..100644
--- a/cli/beacon/cmd/handoff_resume.go
+++ b/cli/beacon/cmd/handoff_resume.go
@@@ -1,170 -1,0 +1,182 @@@
+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()
++ // The runtime starts in the session's directory, not Beacon's, so every path handed to it is
++ // absolute.
++ briefDir, err := filepath.Abs(handoffBriefDir())
++ if err != nil {
++ return fmt.Errorf("resolve brief directory: %w", err)
++ }
++ cwd := strings.TrimSpace(opts.cwd)
++ if cwd != "" {
++ if cwd, err = filepath.Abs(cwd); err != nil {
++ return fmt.Errorf("resolve --cwd: %w", err)
++ }
++ }
+ plan, err := handoff.PlanResume(session, handoff.PlanOptions{
+ Target: target,
+ ForceNew: opts.newOnly,
- Dir: opts.cwd,
++ Dir: cwd,
+ FromRuntimeLog: subject.fromLog,
- BriefPath: filepath.Join(handoffBriefDir(), handoff.BriefFileName(session, now)),
++ BriefPath: filepath.Join(briefDir, 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 --cc cli/beacon/cmd/handoff_resume_test.go
index de3bfce7,00000000..049de73a
mode 100644,000000..100644
--- a/cli/beacon/cmd/handoff_resume_test.go
+++ b/cli/beacon/cmd/handoff_resume_test.go
@@@ -1,331 -1,0 +1,359 @@@
+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
+}
++
++// The runtime starts in the session's directory, so a relative --output-dir or --cwd must reach it
++// as the absolute path Beacon meant.
++func TestHandoffResumeMakesRelativePathsAbsolute(t *testing.T) {
++ f := newResumeFixture(t)
++ work := t.TempDir()
++ t.Chdir(work)
++ if err := os.Mkdir("start-here", 0o755); err != nil {
++ t.Fatal(err)
++ }
++ handoffResumeOpts = handoffResumeOptions{}
++ if _, _, err := runHandoff(t, "resume", "claude-1", "--new", "--output-dir", "briefs", "--cwd", "start-here", "--yes"); err != nil {
++ t.Fatalf("resume: %v", err)
++ }
++ plan := f.launched[0]
++ if !filepath.IsAbs(plan.BriefPath) || !filepath.IsAbs(plan.Dir) {
++ t.Fatalf("brief %q and dir %q must be absolute", plan.BriefPath, plan.Dir)
++ }
++ if !strings.Contains(plan.Args[0], plan.BriefPath) {
++ t.Fatalf("the prompt must carry the absolute brief path: %q", plan.Args[0])
++ }
++ if _, err := os.Stat(plan.BriefPath); err != nil {
++ t.Fatalf("the brief is not where the prompt says: %v", err)
++ }
++ if filepath.Base(plan.Dir) != "start-here" || filepath.Base(filepath.Dir(plan.BriefPath)) != "briefs" {
++ t.Fatalf("dir %q, brief %q", plan.Dir, plan.BriefPath)
++ }
++}
diff --cc cli/beacon/internal/handoff/resume.go
index 4c7f4fdf,00000000..8b406e7a
mode 100644,000000..100644
--- a/cli/beacon/internal/handoff/resume.go
+++ b/cli/beacon/internal/handoff/resume.go
@@@ -1,220 -1,0 +1,225 @@@
+package handoff
+
+import (
+ "errors"
+ "fmt"
+ "os"
++ "path/filepath"
+ "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")
+ }
++ // The runtime reads the brief from its own directory, so a relative path would name another file.
++ if !filepath.IsAbs(opts.BriefPath) {
++ return Plan{}, fmt.Errorf("brief path %s is not absolute", opts.BriefPath)
++ }
+ 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 --cc cli/beacon/internal/handoff/resume_test.go
index e4aaff7f,00000000..b7e35ed5
mode 100644,000000..100644
--- a/cli/beacon/internal/handoff/resume_test.go
+++ b/cli/beacon/internal/handoff/resume_test.go
@@@ -1,259 -1,0 +1,262 @@@
+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"
++ brief := filepath.Join(t.TempDir(), "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"
++ brief := filepath.Join(t.TempDir(), "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})
++ plan, err := PlanResume(session, PlanOptions{BriefPath: filepath.Join(t.TempDir(), "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) {
++ if _, err := PlanResume(session, PlanOptions{Target: HarnessCodex, BriefPath: filepath.Join(t.TempDir(), "b.md"), 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)
+ }
++ if _, err := PlanResume(session, PlanOptions{ForceNew: true, BriefPath: filepath.Join("handoffs", "b.md"), LookPath: allRuntimes}); err == nil || !strings.Contains(err.Error(), "not absolute") {
++ t.Fatalf("a relative brief path names another file from the runtime's directory; 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)
+ }
+}