package thin import ( "context" "encoding/hex" "encoding/json" "os" "os/exec" "path/filepath" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/wire" ) // Kept sessions go when the instance says the task ended, and after the // retention period unused; a repeated forget frame does nothing more. func TestKeptSessionsForgetAndExpire(t *testing.T) { ctx := context.Background() s, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } defer s.Close() keep := func(task, step, dir string) { r := stepRow{DispatchCommand: dispatchFor(task, step, 1)} if err := s.keepSession(ctx, r, wire.SpecialistEngineering, "claude-a", "", "", "00000000-0000-4000-8000-000000000001", dir, "", 10); err != nil { t.Fatal(err) } } keep("tk1", "s1", "/root/a/steps/1") keep("tk1", "s2", "/root/a/steps/2") keep("tk2", "s3", "/root/a/steps/3") if k, ok, err := s.keptSessionFor(ctx, "s1"); err != nil || !ok || k.TaskID != "tk1" || k.Dir != "/root/a/steps/1" { t.Fatalf("kept %+v %v %v", k, ok, err) } // Another person's forget touches nothing. if dirs, err := s.ForgetTask(ctx, "f0", wire.ForgetTaskCommand{Person: "other@example.com", TaskID: "tk1"}); err != nil || len(dirs) != 0 { t.Fatalf("other person forgot %v %v", dirs, err) } dirs, err := s.ForgetTask(ctx, "f1", wire.ForgetTaskCommand{Person: "owner@example.com", TaskID: "tk1"}) if err != nil || len(dirs) != 2 { t.Fatalf("forget %v %v", dirs, err) } if _, ok, _ := s.keptSessionFor(ctx, "s1"); ok { t.Fatal("forgotten session still kept") } if dirs, _ := s.ForgetTask(ctx, "f1", wire.ForgetTaskCommand{Person: "owner@example.com", TaskID: "tk2"}); len(dirs) != 0 { t.Fatal("a repeated frame acted") } dirs, kept, bytes, err := s.expiredKept(ctx, time.Now().Add(-time.Hour)) if err != nil || len(dirs) != 0 || kept != 1 || bytes != 10 { t.Fatalf("fresh sessions expired: %v %d %d %v", dirs, kept, bytes, err) } dirs, kept, _, err = s.expiredKept(ctx, time.Now().Add(time.Hour)) if err != nil || len(dirs) != 1 || dirs[0] != "/root/a/steps/3" || kept != 0 { t.Fatalf("expired %v %d %v", dirs, kept, err) } } // The sweep removes only kept-session directories under the session // root: past retention, or no longer recorded. func TestSweepKeptStaysUnderTheSessionRoot(t *testing.T) { ctx := context.Background() root := t.TempDir() s, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } defer s.Close() e := &Engineer{O: ClaudeOptions{SessionRoot: filepath.Join(root, "sessions"), State: s}} mk := func(p string) string { if err := os.MkdirAll(p, 0700); err != nil { t.Fatal(err) } return p } live := mk(filepath.Join(root, "sessions", "p1", "steps", "live")) orphan := mk(filepath.Join(root, "sessions", "p1", "steps", "orphan")) desk := mk(filepath.Join(root, "sessions", "p1", "desk")) outside := mk(filepath.Join(root, "outside")) if err := s.keepSession(ctx, stepRow{DispatchCommand: dispatchFor("tk1", "s1", 1)}, wire.SpecialistEngineering, "claude-a", "", "", "x", live, "", 1); err != nil { t.Fatal(err) } e.sweepKept(ctx, s) for p, want := range map[string]bool{live: true, orphan: false, desk: true, outside: true} { if _, err := os.Stat(p); (err == nil) != want { t.Fatalf("%s exists=%v, want %v", p, err == nil, want) } } if e.removeKept(outside) == nil || e.removeKept(filepath.Join(root, "sessions", "p1")) == nil || e.removeKept(filepath.Join(root, "sessions", "..", "outside", "steps", "x")) == nil { t.Fatal("removed outside the steps directories") } e.Retention = time.Nanosecond time.Sleep(time.Millisecond) e.sweepKept(ctx, s) if _, err := os.Stat(live); err == nil { t.Fatal("kept past retention") } } // The answering session's git tools only read this change: its log, its // patch (optionally one path) and its own commits; never another ref, // a path outside the repository or an option. func TestAnswerGitIsReadOnly(t *testing.T) { ctx := context.Background() dir := t.TempDir() git := func(args ...string) string { t.Helper() cmd := exec.Command("git", args...) cmd.Dir = dir cmd.Env = append(os.Environ(), "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@example.com", "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@example.com", "GIT_CONFIG_GLOBAL=/dev/null") out, err := cmd.CombinedOutput() if err != nil { t.Fatalf("git %v: %v %s", args, err, out) } return strings.TrimSpace(string(out)) } git("init", "-q", "-b", "main") os.WriteFile(filepath.Join(dir, "README.md"), []byte("teh panes\n"), 0644) os.WriteFile(filepath.Join(dir, "other.txt"), []byte("one\n"), 0644) git("add", ".") git("commit", "-qm", "base") base := git("rev-parse", "HEAD") os.WriteFile(filepath.Join(dir, "README.md"), []byte("the panes\n"), 0644) os.WriteFile(filepath.Join(dir, "other.txt"), []byte("two\n"), 0644) git("commit", "-qam", "Fix the typo") cand := git("rev-parse", "HEAD") git("checkout", "-qb", "elsewhere", base) os.WriteFile(filepath.Join(dir, "secret.txt"), []byte("not this change\n"), 0644) git("add", ".") git("commit", "-qm", "unrelated") other := git("rev-parse", "HEAD") gd := filepath.Join(dir, ".git") call := func(name, args string) (string, bool) { return answerGit(ctx, "git", gd, base, cand, name, json.RawMessage(args)) } if out, bad := call("git_log", `{}`); bad || !strings.Contains(out, "Fix the typo") || strings.Contains(out, "base") { t.Fatalf("log %q", out) } if out, bad := call("git_diff", `{"path":"README.md"}`); bad || !strings.Contains(out, "+the panes") || strings.Contains(out, "other.txt") { t.Fatalf("diff %q", out) } if out, bad := call("git_diff", `{}`); bad || !strings.Contains(out, "+two") { t.Fatalf("whole diff %q", out) } if out, bad := call("git_show", `{"commit":"`+cand[:9]+`"}`); bad || !strings.Contains(out, "Fix the typo") { t.Fatalf("show %q", out) } for _, c := range []struct{ name, args string }{ {"git_show", `{"commit":"` + other + `"}`}, {"git_show", `{"commit":"HEAD"}`}, {"git_show", `{"commit":"--output=/tmp/x"}`}, {"git_diff", `{"path":"../outside"}`}, {"git_diff", `{"path":"--output=x"}`}, {"git_diff", `{"path":"a","extra":1}`}, {"git_log", `{"n":1}`}, {"git_push", `{}`}, } { if out, bad := call(c.name, c.args); !bad || strings.Contains(out, "not this change") { t.Fatalf("%s %s answered %q", c.name, c.args, out) } } // Nothing in the repository changed. if got := git("rev-parse", "main"); got != cand { t.Fatalf("main moved to %s", got) } } // Steps and questions share one queue: a question that arrives while a // step runs waits for it and never runs beside it; a cancel that comes // first holds the question, which never runs. func TestAskQueuesWithSteps(t *testing.T) { ctx := context.Background() s, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } defer s.Close() var mu sync.Mutex var order []string stepping := false started, release := make(chan struct{}), make(chan struct{}) e := &StepEngine{State: s, Notify: func() {}, Exec: func(context.Context, stepRow, func(wire.StepReport)) wire.StepReport { mu.Lock() stepping = true order = append(order, "step") mu.Unlock() close(started) <-release mu.Lock() stepping = false mu.Unlock() return wire.StepReport{State: wire.StepDone, Termination: true} }, Ask: func(_ context.Context, a askRow, _ func(wire.AnswerReport)) askResult { mu.Lock() defer mu.Unlock() if stepping { t.Error("a question ran beside a step") } order = append(order, a.QuestionID) return askResult{Report: wire.AnswerReport{TaskID: a.TaskID, QuestionID: a.QuestionID, Attempt: a.Attempt, State: wire.QuestionAnswered, Text: "ok"}, Terminated: true} }} cctx, cancel := context.WithCancel(ctx) defer cancel() if err := e.Start(cctx); err != nil { t.Fatal(err) } if err := s.AcceptDispatch(ctx, "c1", dispatchFor("tk1", "s1", 1)); err != nil { t.Fatal(err) } e.Wake() <-started if err := s.AcceptAsk(ctx, "c2", wire.AskCommand{Person: "owner@example.com", TaskID: "tk1", StepID: "s0", QuestionID: "q_1", Attempt: 1}); err != nil { t.Fatal(err) } if err := s.RequestAskCancel(ctx, "c3", wire.CancelAskCommand{Person: "owner@example.com", TaskID: "tk1", QuestionID: "q_2", Attempt: 1}); err != nil { t.Fatal(err) } if err := s.AcceptAsk(ctx, "c4", wire.AskCommand{Person: "owner@example.com", TaskID: "tk1", QuestionID: "q_2", Attempt: 1}); err != nil { t.Fatal(err) } e.Wake() time.Sleep(200 * time.Millisecond) mu.Lock() if len(order) != 1 { t.Fatalf("ran %v while the step was running", order) } mu.Unlock() close(release) deadline := time.Now().Add(5 * time.Second) for { runs, _ := s.syncAsks(ctx) if len(runs) == 2 && runs[0].State == runReported && runs[1].State == runReported { break } if time.Now().After(deadline) { t.Fatalf("questions not reported: %+v", runs) } time.Sleep(10 * time.Millisecond) } cancel() e.Wait() if strings.Join(order, ",") != "step,q_1" { t.Fatalf("ran %v, want the step, then q_1 (q_2 was cancelled first)", order) } frames, _, _ := s.Unacked(ctx, 0) states := map[string]string{} for _, f := range frames { if f.Type == wire.FrameAnswer { var r wire.AnswerReport json.Unmarshal(f.Data, &r) states[r.QuestionID] = r.State } } if states["q_1"] != wire.QuestionAnswered || states["q_2"] != wire.QuestionCancelled { t.Fatalf("reports %v", states) } } // A question a previous runner process left running ends at start // (runner_restarted); it is never run twice. func TestRecoverAsks(t *testing.T) { ctx := context.Background() s, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } defer s.Close() if err := s.AcceptAsk(ctx, "c1", wire.AskCommand{Person: "owner@example.com", TaskID: "tk1", QuestionID: "q_1", Attempt: 1}); err != nil { t.Fatal(err) } if err := s.RecoverAsks(ctx, nil); err != nil { t.Fatal(err) } if _, ok, _ := s.nextAsk(ctx); ok { t.Fatal("a recovered question would run again") } frames, _, _ := s.Unacked(ctx, 0) if len(frames) != 1 || !strings.Contains(string(frames[0].Data), `"reason":"runner_restarted"`) { t.Fatalf("frames %+v", frames) } if err := s.Acked(ctx, frames[0].ID); err != nil { t.Fatal(err) } if runs, _ := s.syncAsks(ctx); len(runs) != 0 { t.Fatalf("acked question still held: %+v", runs) } } // Paul, 2026-11-08: a merged task's sessions stay for questions until // keep_until, then the sweep removes them; a cancelled task's go now. func TestForgetTaskKeepsMergedSessions(t *testing.T) { ctx := context.Background() s, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } defer s.Close() r := stepRow{DispatchCommand: dispatchFor("tk1", "s1", 1)} if err := s.keepSession(ctx, r, wire.SpecialistEngineering, "claude-a", "", "", "00000000-0000-4000-8000-000000000001", "/root/a/steps/1", "", 10); err != nil { t.Fatal(err) } until := time.Now().Add(2 * time.Second) if dirs, err := s.ForgetTask(ctx, "f1", wire.ForgetTaskCommand{Person: "owner@example.com", TaskID: "tk1", KeepUntil: &until}); err != nil || len(dirs) != 0 { t.Fatalf("a merged task's sessions went at once: %v %v", dirs, err) } if _, ok, _ := s.keptSessionFor(ctx, "s1"); !ok { t.Fatal("not kept") } // Used recently, but past keep_until: removed. if dirs, kept, _, _ := s.expiredKept(ctx, time.Now().Add(-time.Hour)); len(dirs) != 0 || kept != 1 { t.Fatalf("removed before keep_until: %v", dirs) } time.Sleep(2100 * time.Millisecond) if dirs, kept, _, _ := s.expiredKept(ctx, time.Now().Add(-time.Hour)); len(dirs) != 1 || kept != 0 { t.Fatalf("kept past keep_until: %v %d", dirs, kept) } // A keep_until already past forgets now. if err := s.keepSession(ctx, r, wire.SpecialistEngineering, "claude-a", "", "", "00000000-0000-4000-8000-000000000001", "/root/a/steps/1", "", 10); err != nil { t.Fatal(err) } past := time.Now().Add(-time.Second) if dirs, _ := s.ForgetTask(ctx, "f2", wire.ForgetTaskCommand{Person: "owner@example.com", TaskID: "tk1", KeepUntil: &past}); len(dirs) != 1 { t.Fatalf("past keep_until kept %v", dirs) } } // Astra 4c round 2: a session kept at the merge lasts the full 14 days // from the merge, even if it was last used ten days before it: an // explicit merge expiry overrides the idle expiry. func TestMergedSessionOutlivesIdleExpiry(t *testing.T) { ctx := context.Background() s, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } defer s.Close() r := stepRow{DispatchCommand: dispatchFor("tk1", "s1", 1)} if err := s.keepSession(ctx, r, wire.SpecialistEngineering, "claude-a", "", "", "00000000-0000-4000-8000-000000000001", "/root/a/steps/1", "", 10); err != nil { t.Fatal(err) } day := 24 * time.Hour if _, err := s.db.Exec("UPDATE kept_sessions SET used_at=?", time.Now().Add(-10*day).UTC().Format(time.RFC3339Nano)); err != nil { t.Fatal(err) } until := time.Now().Add(wire.KeepMergedSessions) if _, err := s.ForgetTask(ctx, "f1", wire.ForgetTaskCommand{Person: "owner@example.com", TaskID: "tk1", KeepUntil: &until}); err != nil { t.Fatal(err) } // Five days after the merge (idle 15 days, past the idle retention). if dirs, kept, _, _ := s.expiredKept(ctx, time.Now().Add(5*day-KeptSessionRetention)); len(dirs) != 0 || kept != 1 { t.Fatalf("a merged session went %v before its 14 days", dirs) } } // A question pinned to an Engineering attempt (protocol 37) is bound to // that attempt's kept session, never the step's newest; one whose account // or session differs from what that attempt kept is a mismatch. One that // pins nothing (Review, an older instance) has the step's newest. func TestKeptForAskBindsTheAttempt(t *testing.T) { ctx := context.Background() s, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } defer s.Close() for i, session := range []string{"00000000-0000-4000-8000-000000000001", "00000000-0000-4000-8000-000000000002"} { r := stepRow{DispatchCommand: dispatchFor("tk1", "s1", int64(i+1))} if err := s.keepSession(ctx, r, wire.SpecialistEngineering, "claude-"+itoa(int64(i+1)), "", "", session, "/root/a/steps/"+itoa(int64(i+1)), strings.Repeat("c", 40), 10); err != nil { t.Fatal(err) } } ask := wire.AskCommand{StepID: "s1", EngAttempt: 1, EngAccount: "claude-1", EngSession: "00000000-0000-4000-8000-000000000001"} if k, found, mismatch, err := s.keptForAsk(ctx, ask); err != nil || !found || mismatch || k.Attempt != 1 || k.Dir != "/root/a/steps/1" { t.Fatalf("pinned to attempt 1: %+v %v %v %v", k, found, mismatch, err) } for name, edit := range map[string]func(*wire.AskCommand){ "account": func(a *wire.AskCommand) { a.EngAccount = "claude-2" }, "session": func(a *wire.AskCommand) { a.EngSession = "00000000-0000-4000-8000-000000000002" }, } { a := ask edit(&a) if _, found, mismatch, _ := s.keptForAsk(ctx, a); !found || !mismatch { t.Errorf("another %s is not a mismatch", name) } } if _, found, _, _ := s.keptForAsk(ctx, wire.AskCommand{StepID: "s1", EngAttempt: 3}); found { t.Fatal("an attempt that kept nothing found a session") } if k, found, _, _ := s.keptForAsk(ctx, wire.AskCommand{StepID: "s1"}); !found || k.Attempt != 2 { t.Fatalf("unpinned: %+v", k) } } // However a streamed answer is cut into chunks, what a reader assembles // is at every moment a prefix of the whole answer redacted, and at the end // all of it: a known secret (any form) split across chunks never leaves. func TestRedactedStreamAcrossChunks(t *testing.T) { secret := "sk-ant-oat01-fake-0123456789abcdefghij" forms := secretForms([]string{secret}) full := "I read " + secret + " in the file, hex " + hex.EncodeToString([]byte(secret)) + ", and moved on." want := redactText(full, forms) if strings.Contains(want, secret) { t.Fatal("the redaction leaves the secret") } for i := 1; i < len(full); i++ { for j := i; j < len(full); j += 7 { var draft strings.Builder s := newRedactedStream(forms, func(offset int64, text string) { if int(offset) != draft.Len() { t.Fatalf("cut %d,%d: offset %d after %d bytes", i, j, offset, draft.Len()) } draft.WriteString(text) if !strings.HasPrefix(want, draft.String()) { t.Fatalf("cut %d,%d: %q is not a prefix of %q", i, j, draft.String(), want) } }) s.add(full[:i]) s.add(full[i:j]) s.add(full[j:]) s.flush() if draft.String() != want { t.Fatalf("cut %d,%d: %q", i, j, draft.String()) } } } }