package thintest import ( "amadan.net/oficina/equipo/internal/wire" "encoding/json" "fmt" "net/http" "net/url" "strings" "testing" ) func (r *toolRig) movePlacement(id, repo string, revision int64) error { return r.client.do(r.ctx, http.MethodPost, "/api/v1/tasks/"+id+"/move", wire.MoveTask{Repo: repo, Revision: revision}, nil) } func TestPlacementRestartContract(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) id := r.shopTask("placement") if got := r.call("placement-finding", wire.ToolAddFinding, map[string]any{"task": id, "text": "Keep this source context", "headline": "Original finding", "repo": "oficina/sample", "path": "README.md", "line": 1}); got.IsError { t.Fatal(got) } r.begin("placement-start", id) old := r.nextDispatch() before := r.task(id) if len(before.Findings) != 1 { t.Fatal("fixture finding missing", before.Findings) } if err := r.movePlacement(id, "oficina/equipo", before.Revision); err != nil { t.Fatal(err) } if task := r.task(id); !task.Moving || task.Repo != before.Repo { t.Fatalf("moved before termination: %+v", task) } // A cancellation acknowledgement, wrong attempt and terminal state do not prove termination. _, body := r.expect(wire.FrameCancelStep) cancel := body.(*wire.CancelStepCommand) if cancel.StepID != old.StepID || cancel.Attempt != old.Attempt { t.Fatal(cancel) } r.step("placement-unproven", wire.StepReport{TaskID: id, StepID: old.StepID, Attempt: old.Attempt, State: wire.StepCancelled}) if task := r.task(id); !task.Moving || task.Repo != before.Repo { t.Fatal("terminal without proof moved", task) } r.step("placement-wrong-attempt", wire.StepReport{TaskID: id, StepID: old.StepID, Attempt: old.Attempt + 1, State: wire.StepCancelled, Termination: true}) if task := r.task(id); !task.Moving { t.Fatal("wrong attempt moved", task) } r.step("placement-proven", wire.StepReport{TaskID: id, StepID: old.StepID, Attempt: old.Attempt, State: wire.StepCancelled, Termination: true}) fresh := r.nextDispatch() if fresh.Repo != "amadan.net/oficina/equipo" || fresh.Branch == old.Branch || fresh.StepID == old.StepID || fresh.BaseSHA != "" || fresh.Round != 0 || fresh.Republish { t.Fatalf("not a fresh destination: %+v", fresh) } after := r.task(id) if after.Moving || after.ID != before.ID || after.Brief != before.Brief || len(after.Findings) != len(before.Findings) || after.CandidateSHA != "" || after.Checks != "" || after.Verdict != "" || len(after.EarlierSteps) != 1 { t.Fatalf("move lost context or kept evidence: %+v", after) } // No command produced by the move may dispatch, publish or merge the old branch. var rows []struct{ Kind, Body string } if err := r.inst.DB.G.Table("runner_commands").Where("kind IN ?", []string{wire.FrameDispatch, wire.FramePublish}).Order("seq").Scan(&rows).Error; err != nil { t.Fatal(err) } count := 0 for _, row := range rows { var d struct { Branch string `json:"branch"` } json.Unmarshal([]byte(row.Body), &d) if d.Branch == old.Branch { count++ } } if count != 1 { t.Fatalf("old branch received new work: %+v", rows) } r.step("placement-late", wire.StepReport{TaskID: id, StepID: old.StepID, Attempt: old.Attempt, State: wire.StepDone, Termination: true, Pushed: true, BaseSHA: baseX, CandidateSHA: candX}) if task := r.task(id); task.CandidateSHA != "" || task.Branch != fresh.Branch { t.Fatal("late report revived old branch", task) } notes, err := r.client.Notebook(r.ctx) if err != nil { t.Fatal(err) } found := false for _, n := range notes.Entries { found = found || strings.Contains(n.Text, "oficina/equipo") && strings.Contains(n.Text, "oficina/sample") } if !found { t.Fatal("missing correction", notes) } } func TestPlacementAfterPushReviewAndReady(t *testing.T) { for _, stage := range []string{wire.StageInProgress, wire.StageInReview, wire.StageReadyToMerge} { t.Run(stage, func(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) id := r.shopTask("stage") now := r.inst.Store.Chat().Now() _, err := r.inst.DB.Writer().Exec("INSERT INTO chat_steps(id,task_id,idx,specialist,person,state,attempt,pushed,terminated,candidate_sha,base_sha,revision,created_at,updated_at) VALUES('s_old',?,1,'engineering',?,'done',1,1,1,?,?,1,?,?)", id, Owner, candX, baseX, now, now) if err != nil { t.Fatal(err) } if _, err := r.inst.DB.Writer().Exec("UPDATE chat_tasks SET stage=?,base_sha=?,ready_sha=?,merge_eligible=? WHERE id=?", stage, baseX, candX, candX, id); err != nil { t.Fatal(err) } before := r.task(id) if err := r.movePlacement(id, "oficina/equipo", before.Revision); err != nil { t.Fatal(err) } d := r.nextDispatch() if d.Branch == before.Branch || d.Repo == before.Repo || d.BaseSHA != "" { t.Fatal("old branch reused", d) } after := r.task(id) if after.CandidateSHA != "" || after.Verdict != "" || after.MergeOffered || after.Merged != nil { t.Fatal("old evidence carried over", after) } if len(after.Thread) == 0 || !strings.Contains(after.Thread[len(after.Thread)-1].Text, before.Branch) { t.Fatal("no old branch note", after.Thread) } }) } } func TestPlacementConsentContract(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) if res := r.call("create-unasked", wire.ToolCreateProject, map[string]string{"repo": "amadan.net/oficina/fresh"}); !res.IsError || res.Code != "placement_required" { t.Fatal(res) } if res := r.call("choose", wire.ToolAskPerson, map[string]any{"question": "Create whatever you want?", "options": []string{"Create a new project for it"}, "placement": wire.Placement{Repos: []string{"oficina/sample", "oficina/equipo"}, NewRepo: "oficina/fresh"}}); res.Code != "asked" { t.Fatal(res) } if res := r.call("record-premature", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Premature", "brief": "Don't start yet"}); !res.IsError || res.Code != "placement_pending" { t.Fatal(res) } snap, _ := r.client.Snapshot(r.ctx) var card wire.Card for _, c := range snap.Cards { if c.Kind == wire.CardQuestion { card = c } } if len(card.Options) != 3 || card.Options[0] != "Add to oficina/sample" || card.Options[2] != "New project: oficina/fresh" { t.Fatal(card) } if status, _ := r.post(r.inst.Cookie(), "/conversation/cards/"+card.ID+"/visibility", url.Values{"revision": {itoa(int(card.Revision))}, "aside": {"true"}}); status != http.StatusSeeOther { t.Fatal(status) } if res := r.call("create-aside", wire.ToolCreateProject, map[string]string{"repo": "amadan.net/oficina/fresh"}); !res.IsError { t.Fatal("aside authorised", res) } } func TestPlacementNewProjectAction(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) id := r.shopTask("new-placement") if err := r.runner.Send(r.ctx, "finish-old", wire.FrameReply, wire.Reply{TurnID: r.turn, Attempt: 1, Text: "Recorded."}); err != nil { t.Fatal(err) } r.wait("old turn ends", func(c *Conversation) bool { return c.Turns[r.turn].State == wire.TurnReplied }) before := r.task(id) status, where := r.post(r.inst.Cookie(), "/tasks/"+id+"/move", url.Values{"new": {"1"}, "repo": {"oficina/new-project"}, "revision": {itoa(int(before.Revision))}}) if status != http.StatusSeeOther || where != "/tasks/"+id { t.Fatalf("new project action %d %s", status, where) } if after := r.task(id); !after.Moving || !after.PreparingProject || after.Repo != before.Repo { t.Fatal("new project did not hold task", after) } _, body := r.expect(wire.FrameMessage) msg := body.(*wire.MessageCommand) if !strings.Contains(msg.Text, id) || !strings.Contains(msg.Text, "Do not record another task") { t.Fatal("missing correction context", msg) } r.turn = msg.TurnID if got := r.call("make-new", wire.ToolCreateProject, map[string]string{"repo": "amadan.net/oficina/new-project"}); got.Code != "create" { t.Fatal("own explicit tap not authorised", got) } if got := r.call("make-new/created", wire.ToolProjectCreated, map[string]string{"repo": "amadan.net/oficina/new-project"}); got.Code != "created" { t.Fatal(got) } // Creation precedes the runner's refreshed repository inventory. It is // durable pending state, and even a task with no steps resumes on hello. hello := primaryAt(toolHello(r.runner.Welcome.Generation), wire.ProtocolCurrent) hello.Repos = append(hello.Repos, "amadan.net/oficina/new-project") if err := r.runner.Send(r.ctx, "new-project-hello", wire.FrameHello, hello); err != nil { t.Fatal(err) } r.wait("new project move finishes", func(c *Conversation) bool { return c.Tasks[id].Repo == "amadan.net/oficina/new-project" && !c.Tasks[id].Moving }) after := r.task(id) if after.ID != before.ID || after.Brief != before.Brief || after.Stage != wire.StageNoted || len(after.Steps) > 0 { t.Fatal("new project started unstarted work", after) } } func TestPlacementAnswerAuthorizesOnlySelectedRepo(t *testing.T) { r := newToolRigSaying(t, wire.ProtocolCurrent, "Make a calendar") if res := r.call("placement-q", wire.ToolAskPerson, map[string]any{"question": "Where?", "placement": wire.Placement{Repos: []string{"oficina/sample"}, NewRepo: "oficina/calendar"}}); res.Code != "asked" { t.Fatal(res) } if err := r.runner.Send(r.ctx, "finish-ask", wire.FrameReply, wire.Reply{TurnID: r.turn, Attempt: 1, Text: "Where should it go?"}); err != nil { t.Fatal(err) } r.wait("ask turn ends", func(c *Conversation) bool { return c.Turns[r.turn].State == wire.TurnReplied }) snap, _ := r.client.Snapshot(r.ctx) var card wire.Card for _, c := range snap.Cards { if c.Kind == wire.CardQuestion { card = c } } if _, err := r.client.Answer(r.ctx, card.ID, "Made up choice", card.Revision); err == nil { t.Fatal("forged choice accepted") } if _, err := r.client.Answer(r.ctx, card.ID, "New project: oficina/calendar", card.Revision+1); err == nil { t.Fatal("stale choice accepted") } if _, err := r.client.Answer(r.ctx, card.ID, "New project: oficina/calendar", card.Revision); err != nil { t.Fatal(err) } _, body := r.expect(wire.FrameMessage) msg := body.(*wire.MessageCommand) r.turn = msg.TurnID if !strings.Contains(msg.Text, "Make a calendar") { t.Fatal("lost original request", msg.Text) } if got := r.call("wrong-create", wire.ToolCreateProject, map[string]string{"repo": "amadan.net/oficina/other"}); !got.IsError { t.Fatal("wrong repository consent", got) } if got := r.call("wrong-placement-record", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Misfiled calendar", "brief": "Make the calendar"}); !got.IsError { t.Fatal("recorded outside the chosen project", got) } if got := r.call("right-create", wire.ToolCreateProject, map[string]string{"repo": "amadan.net/oficina/calendar"}); got.Code != "create" { t.Fatal(got) } if _, err := r.client.Answer(r.ctx, card.ID, "New project: oficina/calendar", card.Revision); err == nil { t.Fatal("repeated answer accepted") } } func TestPlacementPreservesResearchAndThreads(t *testing.T) { r := newToolRigSaying(t, wire.ProtocolCurrent, personWords) r.researchOn() r.inventoryOn() research := r.runningResearch("move-research") r.step("move-research-done", wire.StepReport{TaskID: research.TaskID, StepID: research.StepID, Attempt: research.Attempt, State: wire.StepDone, Termination: true, Summary: "Read the source pages.", Research: &wire.ResearchResult{Findings: findingsJSON(t, goodFindings()), Fetches: fetchLog()}}) eng := r.nextDispatch() id := eng.TaskID now := r.inst.Store.Chat().Now() if _, err := r.inst.DB.Writer().Exec("INSERT INTO chat_questions(id,task_id,step_id,asker,idempotency_key,specialist,text,state,answer,attempt,revision,created_at,updated_at) VALUES('q_saved',?,?,?,'saved','engineering','Why this colour?','answered','From the original brand.',1,1,?,?)", id, eng.StepID, Owner, now, now); err != nil { t.Fatal(err) } if _, err := r.inst.DB.Writer().Exec("INSERT INTO chat_card_threads(id,card_id,person,text,created_at) SELECT 'ct_saved',id,?,'Keep the brand.',? FROM chat_cards WHERE task_id=? LIMIT 1", Owner, now, id); err != nil { t.Fatal(err) } before := r.task(id) if err := r.movePlacement(id, "oficina/equipo", before.Revision); err != nil { t.Fatal(err) } r.expect(wire.FrameCancelStep) r.step("move-research-proof", wire.StepReport{TaskID: id, StepID: eng.StepID, Attempt: eng.Attempt, State: wire.StepCancelled, Termination: true}) r.nextDispatch() after := r.task(id) found := false for _, s := range after.Steps { if s.ID == research.StepID && s.Research != nil && s.Summary == "Read the source pages." { found = true } } if !found || len(after.Questions) != 1 || after.Questions[0].Answer != "From the original brand." { t.Fatal("lost research or specialist thread", after) } var count int if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_card_threads WHERE id='ct_saved'").Scan(&count); err != nil || count != 1 { t.Fatal("lost sub-chat", count, err) } } func TestPlacementPendingKeepsUsageAndFinishingResearch(t *testing.T) { r := newToolRigSaying(t, wire.ProtocolCurrent, personWords) r.researchOn() r.inventoryOn() research := r.runningResearch("pending-research") before := r.task(research.TaskID) if err := r.movePlacement(before.ID, "oficina/equipo", before.Revision); err != nil { t.Fatal(err) } r.expect(wire.FrameCancelStep) tokens := int64(123) usage := []wire.Usage{{Provider: "codex", Connection: "codex", Model: "test", Attempt: research.Attempt, Outcome: wire.OutcomeReplied, Complete: true, InputTokens: &tokens}} r.step("research-await-proof", wire.StepReport{TaskID: before.ID, StepID: research.StepID, Attempt: research.Attempt, State: wire.StepDone, Usage: usage}) var got int64 if err := r.inst.DB.Writer().QueryRow("SELECT coalesce(sum(input_tokens),0) FROM chat_usage WHERE step_id=?", research.StepID).Scan(&got); err != nil { t.Fatal(err) } if got != tokens { t.Fatalf("lost pending usage: %d", got) } r.step("research-proof-and-findings", wire.StepReport{TaskID: before.ID, StepID: research.StepID, Attempt: research.Attempt, State: wire.StepDone, Termination: true, Summary: "Finished the source pages.", Research: &wire.ResearchResult{Findings: findingsJSON(t, goodFindings()), Fetches: fetchLog()}}) d := r.nextDispatch() if d.Repo != "amadan.net/oficina/equipo" { t.Fatal(d) } after := r.task(before.ID) found := false for _, s := range after.Steps { if s.ID == research.StepID && s.Research != nil && len(s.Research.Fetches) > 0 && s.Summary == "Finished the source pages." { found = true } } if !found { t.Fatal("lost Research that finished during cancellation", after.Steps) } } func TestPlacementWaitsForPendingPublication(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) id := r.shopTask("pending-publish") now := r.inst.Store.Chat().Now() if _, err := r.inst.DB.Writer().Exec("INSERT INTO chat_steps(id,task_id,idx,specialist,person,state,attempt,terminated,publication,candidate_sha,revision,created_at,updated_at) VALUES('s_publish',?,1,'engineering',?,'done',1,1,'pending',?,1,?,?)", id, Owner, candX, now, now); err != nil { t.Fatal(err) } before := r.task(id) if err := r.movePlacement(id, "oficina/equipo", before.Revision); err != nil { t.Fatal(err) } if task := r.task(id); !task.Moving || task.Repo != before.Repo { t.Fatal("moved while old publication was unsettled", task) } } func TestPlacementMergeDuringStopRefusesMove(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) id := r.shopTask("merge-during-stop") now := r.inst.Store.Chat().Now() if _, err := r.inst.DB.Writer().Exec("INSERT INTO chat_steps(id,task_id,idx,specialist,person,state,attempt,terminated,pushed,candidate_sha,revision,created_at,updated_at) VALUES('s_eng',?,1,'engineering',?,'done',1,1,1,?,1,?,?)", id, Owner, candX, now, now); err != nil { t.Fatal(err) } if _, err := r.inst.DB.Writer().Exec("INSERT INTO chat_steps(id,task_id,idx,specialist,person,state,attempt,terminated,runner_id,candidate_sha,revision,created_at,updated_at) VALUES('s_review',?,2,'review',?,'running',1,0,?,?,1,?,?)", id, Owner, r.runner.Welcome.RunnerID, candX, now, now); err != nil { t.Fatal(err) } if _, err := r.inst.DB.Writer().Exec("UPDATE chat_tasks SET stage='in_review' WHERE id=?", id); err != nil { t.Fatal(err) } before := r.task(id) if err := r.movePlacement(id, "oficina/equipo", before.Revision); err != nil { t.Fatal(err) } r.expect(wire.FrameCancelStep) if err := r.runner.Send(r.ctx, "merged-while-stopping", wire.FrameMerged, wire.MergedReport{TaskID: id, CandidateSHA: candX}); err != nil { t.Fatal(err) } r.wait("merge recorded", func(c *Conversation) bool { return c.Tasks[id].Stage == wire.StageDone }) r.step("review-stopped-after-merge", wire.StepReport{TaskID: id, StepID: "s_review", Attempt: 1, State: wire.StepCancelled, Termination: true}) after := r.task(id) if after.Repo != before.Repo || after.Stage != wire.StageDone || after.Moving { t.Fatal("move restarted a merged task", after) } } func TestPlacementReconnectProofRestarts(t *testing.T) { for _, failed := range []bool{false, true} { t.Run(fmt.Sprintf("failed-%v", failed), func(t *testing.T) { r := newToolRigAt(t, wire.ProtocolCurrent) id := r.shopTask("sync-move") r.begin("sync-start", id) old := r.nextDispatch() if failed { r.step("failed-unproven", wire.StepReport{TaskID: id, StepID: old.StepID, Attempt: old.Attempt, State: wire.StepFailed, Reason: "interrupted"}) } before := r.task(id) if err := r.movePlacement(id, "oficina/equipo", before.Revision); err != nil { t.Fatal(err) } r.expect(wire.FrameCancelStep) if err := r.runner.Send(r.ctx, "sync-placement-proof", wire.FrameSync, wire.Sync{Runs: []wire.Run{{TurnID: r.turn, Attempt: 1, State: "running"}}, Steps: []wire.StepRun{}}); err != nil { t.Fatal(err) } // Sync is not acknowledged. The next tool result is a barrier // on this ordered connection, so the sync has committed by then. if result := r.call("sync-barrier", wire.ToolStatus, map[string]any{}); result.IsError { t.Fatal(result) } after := r.task(id) if after.Moving || after.Repo != "amadan.net/oficina/equipo" || after.Stage != wire.StageInProgress { t.Fatal("reconnect proof lost pending restart", after.Stage, after.Repo, after.Moving) } }) } }