oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package thin
2
3import (
4 "context"
5 "encoding/hex"
6 "encoding/json"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "strings"
11 "sync"
12 "testing"
13 "time"
14
15 "amadan.net/oficina/equipo/internal/wire"
16)
17
18// Kept sessions go when the instance says the task ended, and after the
19// retention period unused; a repeated forget frame does nothing more.
20func TestKeptSessionsForgetAndExpire(t *testing.T) {
21 ctx := context.Background()
22 s, err := OpenState(ctx, t.TempDir())
23 if err != nil {
24 t.Fatal(err)
25 }
26 defer s.Close()
27 keep := func(task, step, dir string) {
28 r := stepRow{DispatchCommand: dispatchFor(task, step, 1)}
29 if err := s.keepSession(ctx, r, wire.SpecialistEngineering, "claude-a", "", "", "00000000-0000-4000-8000-000000000001", dir, "", 10); err != nil {
30 t.Fatal(err)
31 }
32 }
33 keep("tk1", "s1", "/root/a/steps/1")
34 keep("tk1", "s2", "/root/a/steps/2")
35 keep("tk2", "s3", "/root/a/steps/3")
36 if k, ok, err := s.keptSessionFor(ctx, "s1"); err != nil || !ok || k.TaskID != "tk1" || k.Dir != "/root/a/steps/1" {
37 t.Fatalf("kept %+v %v %v", k, ok, err)
38 }
39 // Another person's forget touches nothing.
40 if dirs, err := s.ForgetTask(ctx, "f0", wire.ForgetTaskCommand{Person: "other@example.com", TaskID: "tk1"}); err != nil || len(dirs) != 0 {
41 t.Fatalf("other person forgot %v %v", dirs, err)
42 }
43 dirs, err := s.ForgetTask(ctx, "f1", wire.ForgetTaskCommand{Person: "owner@example.com", TaskID: "tk1"})
44 if err != nil || len(dirs) != 2 {
45 t.Fatalf("forget %v %v", dirs, err)
46 }
47 if _, ok, _ := s.keptSessionFor(ctx, "s1"); ok {
48 t.Fatal("forgotten session still kept")
49 }
50 if dirs, _ := s.ForgetTask(ctx, "f1", wire.ForgetTaskCommand{Person: "owner@example.com", TaskID: "tk2"}); len(dirs) != 0 {
51 t.Fatal("a repeated frame acted")
52 }
53 dirs, kept, bytes, err := s.expiredKept(ctx, time.Now().Add(-time.Hour))
54 if err != nil || len(dirs) != 0 || kept != 1 || bytes != 10 {
55 t.Fatalf("fresh sessions expired: %v %d %d %v", dirs, kept, bytes, err)
56 }
57 dirs, kept, _, err = s.expiredKept(ctx, time.Now().Add(time.Hour))
58 if err != nil || len(dirs) != 1 || dirs[0] != "/root/a/steps/3" || kept != 0 {
59 t.Fatalf("expired %v %d %v", dirs, kept, err)
60 }
61}
62
63// The sweep removes only kept-session directories under the session
64// root: past retention, or no longer recorded.
65func TestSweepKeptStaysUnderTheSessionRoot(t *testing.T) {
66 ctx := context.Background()
67 root := t.TempDir()
68 s, err := OpenState(ctx, t.TempDir())
69 if err != nil {
70 t.Fatal(err)
71 }
72 defer s.Close()
73 e := &Engineer{O: ClaudeOptions{SessionRoot: filepath.Join(root, "sessions"), State: s}}
74 mk := func(p string) string {
75 if err := os.MkdirAll(p, 0700); err != nil {
76 t.Fatal(err)
77 }
78 return p
79 }
80 live := mk(filepath.Join(root, "sessions", "p1", "steps", "live"))
81 orphan := mk(filepath.Join(root, "sessions", "p1", "steps", "orphan"))
82 desk := mk(filepath.Join(root, "sessions", "p1", "desk"))
83 outside := mk(filepath.Join(root, "outside"))
84 if err := s.keepSession(ctx, stepRow{DispatchCommand: dispatchFor("tk1", "s1", 1)}, wire.SpecialistEngineering, "claude-a", "", "", "x", live, "", 1); err != nil {
85 t.Fatal(err)
86 }
87 e.sweepKept(ctx, s)
88 for p, want := range map[string]bool{live: true, orphan: false, desk: true, outside: true} {
89 if _, err := os.Stat(p); (err == nil) != want {
90 t.Fatalf("%s exists=%v, want %v", p, err == nil, want)
91 }
92 }
93 if e.removeKept(outside) == nil || e.removeKept(filepath.Join(root, "sessions", "p1")) == nil || e.removeKept(filepath.Join(root, "sessions", "..", "outside", "steps", "x")) == nil {
94 t.Fatal("removed outside the steps directories")
95 }
96 e.Retention = time.Nanosecond
97 time.Sleep(time.Millisecond)
98 e.sweepKept(ctx, s)
99 if _, err := os.Stat(live); err == nil {
100 t.Fatal("kept past retention")
101 }
102}
103
104// The answering session's git tools only read this change: its log, its
105// patch (optionally one path) and its own commits; never another ref,
106// a path outside the repository or an option.
107func TestAnswerGitIsReadOnly(t *testing.T) {
108 ctx := context.Background()
109 dir := t.TempDir()
110 git := func(args ...string) string {
111 t.Helper()
112 cmd := exec.Command("git", args...)
113 cmd.Dir = dir
114 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")
115 out, err := cmd.CombinedOutput()
116 if err != nil {
117 t.Fatalf("git %v: %v %s", args, err, out)
118 }
119 return strings.TrimSpace(string(out))
120 }
121 git("init", "-q", "-b", "main")
122 os.WriteFile(filepath.Join(dir, "README.md"), []byte("teh panes\n"), 0644)
123 os.WriteFile(filepath.Join(dir, "other.txt"), []byte("one\n"), 0644)
124 git("add", ".")
125 git("commit", "-qm", "base")
126 base := git("rev-parse", "HEAD")
127 os.WriteFile(filepath.Join(dir, "README.md"), []byte("the panes\n"), 0644)
128 os.WriteFile(filepath.Join(dir, "other.txt"), []byte("two\n"), 0644)
129 git("commit", "-qam", "Fix the typo")
130 cand := git("rev-parse", "HEAD")
131 git("checkout", "-qb", "elsewhere", base)
132 os.WriteFile(filepath.Join(dir, "secret.txt"), []byte("not this change\n"), 0644)
133 git("add", ".")
134 git("commit", "-qm", "unrelated")
135 other := git("rev-parse", "HEAD")
136 gd := filepath.Join(dir, ".git")
137 call := func(name, args string) (string, bool) {
138 return answerGit(ctx, "git", gd, base, cand, name, json.RawMessage(args))
139 }
140 if out, bad := call("git_log", `{}`); bad || !strings.Contains(out, "Fix the typo") || strings.Contains(out, "base") {
141 t.Fatalf("log %q", out)
142 }
143 if out, bad := call("git_diff", `{"path":"README.md"}`); bad || !strings.Contains(out, "+the panes") || strings.Contains(out, "other.txt") {
144 t.Fatalf("diff %q", out)
145 }
146 if out, bad := call("git_diff", `{}`); bad || !strings.Contains(out, "+two") {
147 t.Fatalf("whole diff %q", out)
148 }
149 if out, bad := call("git_show", `{"commit":"`+cand[:9]+`"}`); bad || !strings.Contains(out, "Fix the typo") {
150 t.Fatalf("show %q", out)
151 }
152 for _, c := range []struct{ name, args string }{
153 {"git_show", `{"commit":"` + other + `"}`},
154 {"git_show", `{"commit":"HEAD"}`},
155 {"git_show", `{"commit":"--output=/tmp/x"}`},
156 {"git_diff", `{"path":"../outside"}`},
157 {"git_diff", `{"path":"--output=x"}`},
158 {"git_diff", `{"path":"a","extra":1}`},
159 {"git_log", `{"n":1}`},
160 {"git_push", `{}`},
161 } {
162 if out, bad := call(c.name, c.args); !bad || strings.Contains(out, "not this change") {
163 t.Fatalf("%s %s answered %q", c.name, c.args, out)
164 }
165 }
166 // Nothing in the repository changed.
167 if got := git("rev-parse", "main"); got != cand {
168 t.Fatalf("main moved to %s", got)
169 }
170}
171
172// Steps and questions share one queue: a question that arrives while a
173// step runs waits for it and never runs beside it; a cancel that comes
174// first holds the question, which never runs.
175func TestAskQueuesWithSteps(t *testing.T) {
176 ctx := context.Background()
177 s, err := OpenState(ctx, t.TempDir())
178 if err != nil {
179 t.Fatal(err)
180 }
181 defer s.Close()
182 var mu sync.Mutex
183 var order []string
184 stepping := false
185 started, release := make(chan struct{}), make(chan struct{})
186 e := &StepEngine{State: s, Notify: func() {}, Exec: func(context.Context, stepRow, func(wire.StepReport)) wire.StepReport {
187 mu.Lock()
188 stepping = true
189 order = append(order, "step")
190 mu.Unlock()
191 close(started)
192 <-release
193 mu.Lock()
194 stepping = false
195 mu.Unlock()
196 return wire.StepReport{State: wire.StepDone, Termination: true}
197 }, Ask: func(_ context.Context, a askRow, _ func(wire.AnswerReport)) askResult {
198 mu.Lock()
199 defer mu.Unlock()
200 if stepping {
201 t.Error("a question ran beside a step")
202 }
203 order = append(order, a.QuestionID)
204 return askResult{Report: wire.AnswerReport{TaskID: a.TaskID, QuestionID: a.QuestionID, Attempt: a.Attempt, State: wire.QuestionAnswered, Text: "ok"}, Terminated: true}
205 }}
206 cctx, cancel := context.WithCancel(ctx)
207 defer cancel()
208 if err := e.Start(cctx); err != nil {
209 t.Fatal(err)
210 }
211 if err := s.AcceptDispatch(ctx, "c1", dispatchFor("tk1", "s1", 1)); err != nil {
212 t.Fatal(err)
213 }
214 e.Wake()
215 <-started
216 if err := s.AcceptAsk(ctx, "c2", wire.AskCommand{Person: "owner@example.com", TaskID: "tk1", StepID: "s0", QuestionID: "q_1", Attempt: 1}); err != nil {
217 t.Fatal(err)
218 }
219 if err := s.RequestAskCancel(ctx, "c3", wire.CancelAskCommand{Person: "owner@example.com", TaskID: "tk1", QuestionID: "q_2", Attempt: 1}); err != nil {
220 t.Fatal(err)
221 }
222 if err := s.AcceptAsk(ctx, "c4", wire.AskCommand{Person: "owner@example.com", TaskID: "tk1", QuestionID: "q_2", Attempt: 1}); err != nil {
223 t.Fatal(err)
224 }
225 e.Wake()
226 time.Sleep(200 * time.Millisecond)
227 mu.Lock()
228 if len(order) != 1 {
229 t.Fatalf("ran %v while the step was running", order)
230 }
231 mu.Unlock()
232 close(release)
233 deadline := time.Now().Add(5 * time.Second)
234 for {
235 runs, _ := s.syncAsks(ctx)
236 if len(runs) == 2 && runs[0].State == runReported && runs[1].State == runReported {
237 break
238 }
239 if time.Now().After(deadline) {
240 t.Fatalf("questions not reported: %+v", runs)
241 }
242 time.Sleep(10 * time.Millisecond)
243 }
244 cancel()
245 e.Wait()
246 if strings.Join(order, ",") != "step,q_1" {
247 t.Fatalf("ran %v, want the step, then q_1 (q_2 was cancelled first)", order)
248 }
249 frames, _, _ := s.Unacked(ctx, 0)
250 states := map[string]string{}
251 for _, f := range frames {
252 if f.Type == wire.FrameAnswer {
253 var r wire.AnswerReport
254 json.Unmarshal(f.Data, &r)
255 states[r.QuestionID] = r.State
256 }
257 }
258 if states["q_1"] != wire.QuestionAnswered || states["q_2"] != wire.QuestionCancelled {
259 t.Fatalf("reports %v", states)
260 }
261}
262
263// A question a previous runner process left running ends at start
264// (runner_restarted); it is never run twice.
265func TestRecoverAsks(t *testing.T) {
266 ctx := context.Background()
267 s, err := OpenState(ctx, t.TempDir())
268 if err != nil {
269 t.Fatal(err)
270 }
271 defer s.Close()
272 if err := s.AcceptAsk(ctx, "c1", wire.AskCommand{Person: "owner@example.com", TaskID: "tk1", QuestionID: "q_1", Attempt: 1}); err != nil {
273 t.Fatal(err)
274 }
275 if err := s.RecoverAsks(ctx, nil); err != nil {
276 t.Fatal(err)
277 }
278 if _, ok, _ := s.nextAsk(ctx); ok {
279 t.Fatal("a recovered question would run again")
280 }
281 frames, _, _ := s.Unacked(ctx, 0)
282 if len(frames) != 1 || !strings.Contains(string(frames[0].Data), `"reason":"runner_restarted"`) {
283 t.Fatalf("frames %+v", frames)
284 }
285 if err := s.Acked(ctx, frames[0].ID); err != nil {
286 t.Fatal(err)
287 }
288 if runs, _ := s.syncAsks(ctx); len(runs) != 0 {
289 t.Fatalf("acked question still held: %+v", runs)
290 }
291}
292
293// Paul, 2026-11-08: a merged task's sessions stay for questions until
294// keep_until, then the sweep removes them; a cancelled task's go now.
295func TestForgetTaskKeepsMergedSessions(t *testing.T) {
296 ctx := context.Background()
297 s, err := OpenState(ctx, t.TempDir())
298 if err != nil {
299 t.Fatal(err)
300 }
301 defer s.Close()
302 r := stepRow{DispatchCommand: dispatchFor("tk1", "s1", 1)}
303 if err := s.keepSession(ctx, r, wire.SpecialistEngineering, "claude-a", "", "", "00000000-0000-4000-8000-000000000001", "/root/a/steps/1", "", 10); err != nil {
304 t.Fatal(err)
305 }
306 until := time.Now().Add(2 * time.Second)
307 if dirs, err := s.ForgetTask(ctx, "f1", wire.ForgetTaskCommand{Person: "owner@example.com", TaskID: "tk1", KeepUntil: &until}); err != nil || len(dirs) != 0 {
308 t.Fatalf("a merged task's sessions went at once: %v %v", dirs, err)
309 }
310 if _, ok, _ := s.keptSessionFor(ctx, "s1"); !ok {
311 t.Fatal("not kept")
312 }
313 // Used recently, but past keep_until: removed.
314 if dirs, kept, _, _ := s.expiredKept(ctx, time.Now().Add(-time.Hour)); len(dirs) != 0 || kept != 1 {
315 t.Fatalf("removed before keep_until: %v", dirs)
316 }
317 time.Sleep(2100 * time.Millisecond)
318 if dirs, kept, _, _ := s.expiredKept(ctx, time.Now().Add(-time.Hour)); len(dirs) != 1 || kept != 0 {
319 t.Fatalf("kept past keep_until: %v %d", dirs, kept)
320 }
321 // A keep_until already past forgets now.
322 if err := s.keepSession(ctx, r, wire.SpecialistEngineering, "claude-a", "", "", "00000000-0000-4000-8000-000000000001", "/root/a/steps/1", "", 10); err != nil {
323 t.Fatal(err)
324 }
325 past := time.Now().Add(-time.Second)
326 if dirs, _ := s.ForgetTask(ctx, "f2", wire.ForgetTaskCommand{Person: "owner@example.com", TaskID: "tk1", KeepUntil: &past}); len(dirs) != 1 {
327 t.Fatalf("past keep_until kept %v", dirs)
328 }
329}
330
331// Astra 4c round 2: a session kept at the merge lasts the full 14 days
332// from the merge, even if it was last used ten days before it: an
333// explicit merge expiry overrides the idle expiry.
334func TestMergedSessionOutlivesIdleExpiry(t *testing.T) {
335 ctx := context.Background()
336 s, err := OpenState(ctx, t.TempDir())
337 if err != nil {
338 t.Fatal(err)
339 }
340 defer s.Close()
341 r := stepRow{DispatchCommand: dispatchFor("tk1", "s1", 1)}
342 if err := s.keepSession(ctx, r, wire.SpecialistEngineering, "claude-a", "", "", "00000000-0000-4000-8000-000000000001", "/root/a/steps/1", "", 10); err != nil {
343 t.Fatal(err)
344 }
345 day := 24 * time.Hour
346 if _, err := s.db.Exec("UPDATE kept_sessions SET used_at=?", time.Now().Add(-10*day).UTC().Format(time.RFC3339Nano)); err != nil {
347 t.Fatal(err)
348 }
349 until := time.Now().Add(wire.KeepMergedSessions)
350 if _, err := s.ForgetTask(ctx, "f1", wire.ForgetTaskCommand{Person: "owner@example.com", TaskID: "tk1", KeepUntil: &until}); err != nil {
351 t.Fatal(err)
352 }
353 // Five days after the merge (idle 15 days, past the idle retention).
354 if dirs, kept, _, _ := s.expiredKept(ctx, time.Now().Add(5*day-KeptSessionRetention)); len(dirs) != 0 || kept != 1 {
355 t.Fatalf("a merged session went %v before its 14 days", dirs)
356 }
357}
358
359// A question pinned to an Engineering attempt (protocol 37) is bound to
360// that attempt's kept session, never the step's newest; one whose account
361// or session differs from what that attempt kept is a mismatch. One that
362// pins nothing (Review, an older instance) has the step's newest.
363func TestKeptForAskBindsTheAttempt(t *testing.T) {
364 ctx := context.Background()
365 s, err := OpenState(ctx, t.TempDir())
366 if err != nil {
367 t.Fatal(err)
368 }
369 defer s.Close()
370 for i, session := range []string{"00000000-0000-4000-8000-000000000001", "00000000-0000-4000-8000-000000000002"} {
371 r := stepRow{DispatchCommand: dispatchFor("tk1", "s1", int64(i+1))}
372 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 {
373 t.Fatal(err)
374 }
375 }
376 ask := wire.AskCommand{StepID: "s1", EngAttempt: 1, EngAccount: "claude-1", EngSession: "00000000-0000-4000-8000-000000000001"}
377 if k, found, mismatch, err := s.keptForAsk(ctx, ask); err != nil || !found || mismatch || k.Attempt != 1 || k.Dir != "/root/a/steps/1" {
378 t.Fatalf("pinned to attempt 1: %+v %v %v %v", k, found, mismatch, err)
379 }
380 for name, edit := range map[string]func(*wire.AskCommand){
381 "account": func(a *wire.AskCommand) { a.EngAccount = "claude-2" },
382 "session": func(a *wire.AskCommand) { a.EngSession = "00000000-0000-4000-8000-000000000002" },
383 } {
384 a := ask
385 edit(&a)
386 if _, found, mismatch, _ := s.keptForAsk(ctx, a); !found || !mismatch {
387 t.Errorf("another %s is not a mismatch", name)
388 }
389 }
390 if _, found, _, _ := s.keptForAsk(ctx, wire.AskCommand{StepID: "s1", EngAttempt: 3}); found {
391 t.Fatal("an attempt that kept nothing found a session")
392 }
393 if k, found, _, _ := s.keptForAsk(ctx, wire.AskCommand{StepID: "s1"}); !found || k.Attempt != 2 {
394 t.Fatalf("unpinned: %+v", k)
395 }
396}
397
398// However a streamed answer is cut into chunks, what a reader assembles
399// is at every moment a prefix of the whole answer redacted, and at the end
400// all of it: a known secret (any form) split across chunks never leaves.
401func TestRedactedStreamAcrossChunks(t *testing.T) {
402 secret := "sk-ant-oat01-fake-0123456789abcdefghij"
403 forms := secretForms([]string{secret})
404 full := "I read " + secret + " in the file, hex " + hex.EncodeToString([]byte(secret)) + ", and moved on."
405 want := redactText(full, forms)
406 if strings.Contains(want, secret) {
407 t.Fatal("the redaction leaves the secret")
408 }
409 for i := 1; i < len(full); i++ {
410 for j := i; j < len(full); j += 7 {
411 var draft strings.Builder
412 s := newRedactedStream(forms, func(offset int64, text string) {
413 if int(offset) != draft.Len() {
414 t.Fatalf("cut %d,%d: offset %d after %d bytes", i, j, offset, draft.Len())
415 }
416 draft.WriteString(text)
417 if !strings.HasPrefix(want, draft.String()) {
418 t.Fatalf("cut %d,%d: %q is not a prefix of %q", i, j, draft.String(), want)
419 }
420 })
421 s.add(full[:i])
422 s.add(full[i:j])
423 s.add(full[j:])
424 s.flush()
425 if draft.String() != want {
426 t.Fatalf("cut %d,%d: %q", i, j, draft.String())
427 }
428 }
429 }
430}
431