package thintest import ( "encoding/json" "errors" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/equipo/housekeeping" "amadan.net/oficina/equipo/internal/wire" ) // Housekeeping slice 1 through the person API (spec // 2026-11-08-equipo-housekeeping.md §7): the duplicate detectors acting // under the loop's ledger, Undo, Pause, quiet hours, the digest and // auto-disable. The store-level gates are in internal/equipo/chat. // pair records two tasks one person filed that read very much alike, as // before Equipo looked (the coordinator's "separate" judgement dropped): // the next pass combines the second into the first. func (r *toolRig) pair(key, title string) (keep, fold string) { r.t.Helper() keep = taskID(r.t, r.call(key+"k", wire.ToolRecordTask, map[string]any{"repo": "oficina/sample", "title": title, "brief": "Seen on the phone."})) fold = taskID(r.t, r.call(key+"f", wire.ToolRecordTask, map[string]any{"repo": "oficina/sample", "title": title + " again", "brief": "Seen again.", "separate": true})) r.forgetPair(keep, fold) return keep, fold } func (r *toolRig) housekeeping() wire.Housekeeping { r.t.Helper() h, err := r.client.Housekeeping(r.ctx) if err != nil { r.t.Fatal(err) } return h } // action finds the person's action on a subject. func (r *toolRig) action(subject string) wire.HousekeepingAction { r.t.Helper() for _, a := range r.housekeeping().Actions { if a.Subject.ID == subject { return a } } r.t.Fatalf("no action on %s", subject) return wire.HousekeepingAction{} } // clock sets the loop's clock for the instance's current process. func (r *toolRig) clock(at time.Time) { r.inst.Store.Chat().SetHousekeepingClock(func() time.Time { return at }) } func (r *toolRig) tick() { r.t.Helper() if err := r.inst.Store.Chat().HousekeepingTick(r.ctx); err != nil { r.t.Fatal(err) } } // taskJSON is a task as the API serves it, less its revision and update // time, which an Undo moves on. func (r *toolRig) taskJSON(id string) string { r.t.Helper() k, err := r.client.Task(r.ctx, id) if err != nil { r.t.Fatal(err) } k.Revision, k.UpdatedAt = 0, time.Time{} raw, _ := json.Marshal(k) return string(raw) } // TestContractHousekeepingCombine is H1: two tasks one person filed are // combined by the loop on the next recorded task, with a receipt that // names its action; the action, the view and the summary match the // shared fixtures; a teammate sees none of it and cannot undo it. func TestContractHousekeepingCombine(t *testing.T) { r := newToolRig(t) keep, fold := r.pair("h1", "Swipe back from the edge doesn't work") if h := r.housekeeping(); len(h.Actions) != 0 { t.Fatalf("acted before the pass: %+v", h.Actions) } // The next task the coordinator records runs the detectors on its // project. taskID(t, r.call("h1x", wire.ToolRecordTask, map[string]any{"repo": "oficina/sample", "title": "Crash on launch after the update", "brief": "Every time."})) folded, _ := r.client.Task(r.ctx, fold) if folded.Folded == nil || folded.Folded.Into.ID != keep { t.Fatalf("not combined on record_task: %+v", folded.Folded) } h := r.housekeeping() shape(t, "api/housekeeping.json", h) a := r.action(fold) if a.State != wire.ActionDone || a.Detector != housekeeping.DuplicateSameCreatorID || a.Class != housekeeping.ClassAct || !a.Undoable || a.UndoUntil == nil || len(a.Evidence.Tasks) != 2 || a.Evidence.Tasks[1].ID != keep || a.Evidence.Shared < 3 { t.Fatalf("action: %+v", a) } if d := a.UndoUntil.Sub(a.At); d < housekeeping.UndoWindow-time.Second || d > housekeeping.UndoWindow { t.Fatalf("undo window %s", d) } shape(t, "api/action-combined.json", a) var card wire.Card r.wait("receipt with its action", func(c *Conversation) bool { for _, k := range c.Cards { if k.Kind == wire.CardCombined && k.TaskID == fold && k.ActionID == a.ID { card = k return true } } return false }) if card.VisibleAt != nil { t.Fatalf("receipt held outside quiet hours: %v", card.VisibleAt) } page, err := r.client.HousekeepingActions(r.ctx, "", 1) if err != nil || len(page.Items) != 1 { t.Fatalf("actions page: %+v %v", page, err) } snap, err := r.client.Snapshot(r.ctx) if err != nil || snap.HousekeepingSummary.Paused || len(snap.HousekeepingSummary.Disabled) != 0 { t.Fatalf("summary: %+v %v", snap.HousekeepingSummary, err) } // The view beside the Notebook, scriptless: the action, its evidence // and Undo; the conversation's header leads there. view := r.inst.Get(t, "/housekeeping") for _, want := range []string{`data-action="` + a.ID + `"`, "data-hk-undo", "Combined “Swipe back from the edge", "words in common", "data-hk-settings-link", `data-detector="duplicate_same_creator"`} { if !strings.Contains(view, want) { t.Fatalf("view lacks %q", want) } } if !strings.Contains(r.inst.Get(t, "/conversation"), "data-housekeeping-link") { t.Fatal("no way from the conversation to the view") } // Settings' Housekeeping section: Pause, quiet hours, the activity view. settings := r.inst.Get(t, "/conversation/settings/housekeeping") for _, want := range []string{`id="housekeeping"`, "data-hk-pause", "data-hk-quiet-on", ``, ``, `href="/housekeeping" data-hk-activity`} { if !strings.Contains(settings, want) { t.Fatalf("Settings lacks %q", want) } } if strings.Contains(settings, "data-placeholder") || strings.Contains(r.inst.Get(t, "/settings"), "data-hk-settings") { t.Fatal("the placeholder or the old /settings section is still there") } // A teammate sees none of it, and cannot undo it. member := personToolRig(t, r, "member@example.com", equipo.RoleMember) if mh, err := member.client.Housekeeping(r.ctx); err != nil || len(mh.Actions) != 0 { t.Fatalf("member's view: %+v %v", mh.Actions, err) } if _, err := member.client.UndoAction(r.ctx, a.ID); Status(err) != 404 { t.Fatalf("member undo: %v", err) } if _, err := member.client.Answer(r.ctx, card.ID, wire.ChoiceUndo, card.Revision); Status(err) != 404 { t.Fatalf("member undo on the receipt: %v", err) } if k, _ := r.client.Task(r.ctx, fold); k.Folded == nil { t.Fatal("a teammate undid it") } // Undo is offered for seven days, then 409 with the action. r.clock(a.At.Add(housekeeping.UndoWindow + time.Minute)) if late := r.action(fold); late.Undoable { t.Fatal("still undoable after seven days") } if _, err := r.client.UndoAction(r.ctx, a.ID); Status(err) != 409 { t.Fatalf("Undo after seven days: %v", err) } if _, err := r.client.Uncombine(r.ctx, fold); Status(err) != 409 { t.Fatalf("task page Undo after seven days: %v", err) } r.inst.Store.Chat().SetHousekeepingClock(daytime()) if _, err := r.client.UndoAction(r.ctx, a.ID); err != nil { t.Fatalf("Undo within the week: %v", err) } } // TestContractHousekeepingUndoRoundTrips: combine then Undo leaves both // tasks and their threads as they were, the destination included; the // key becomes a retained veto, so the same finding never acts again; a // second Undo is 409 with the action. Undo from the view and from the // receipt racing: exactly one commits. func TestContractHousekeepingUndoRoundTrips(t *testing.T) { r := newToolRig(t) keep, fold := r.pair("u1", "Timeline jumps when images load") // A finding moves the one that keeps the work along; the folded one // carries a thread. r.call("u1n", wire.ToolAddFinding, map[string]any{"task": keep, "text": "The image cell resizes.", "repo": "oficina/sample", "path": "timeline/cell.go", "line": 12}) if _, err := r.client.PostThread(r.ctx, fold, "Only on slow networks.", "u1t"); err != nil { t.Fatal(err) } beforeFold, beforeKeep := r.taskJSON(fold), r.taskJSON(keep) if n := r.tidy(); n != 1 { t.Fatalf("combined %d", n) } if r.taskJSON(keep) == beforeKeep { t.Fatal("the destination did not take the fold") } a := r.action(fold) undone, err := r.client.UndoAction(r.ctx, a.ID) if err != nil { t.Fatal(err) } if undone.State != wire.ActionUndone || undone.Undoable || undone.UndoneAt == nil { t.Fatalf("undone: %+v", undone) } shape(t, "api/action-undone.json", undone) if got := r.taskJSON(fold); got != beforeFold { t.Fatalf("folded task after Undo:\n got %s\nwant %s", got, beforeFold) } if got := r.taskJSON(keep); got != beforeKeep { t.Fatalf("destination after Undo:\n got %s\nwant %s", got, beforeKeep) } _, err = r.client.UndoAction(r.ctx, a.ID) var conflict wire.ActionConflict if Status(err) != 409 || json.Unmarshal(statusBody(err), &conflict) != nil || conflict.Action.State != wire.ActionUndone { t.Fatalf("second undo: %v", err) } shape(t, "api/action-conflict.json", conflict) // The veto holds even with the pair no longer kept apart. r.forgetPair(keep, fold) if n := r.tidy(); n != 0 { t.Fatal("the undone finding acted again") } // The race: Undo from the view and from the receipt at once. keep2, fold2 := r.pair("u2", "Compose sheet keyboard covers the send button") if n := r.tidy(); n != 1 { t.Fatalf("second pair combined %d", n) } a2 := r.action(fold2) var card wire.Card r.wait("second receipt", func(c *Conversation) bool { for _, k := range c.Cards { if k.ActionID == a2.ID { card = k return true } } return false }) var wg sync.WaitGroup errs := make([]error, 2) wg.Add(2) go func() { defer wg.Done(); _, errs[0] = r.client.UndoAction(r.ctx, a2.ID) }() go func() { defer wg.Done(); _, errs[1] = r.client.Answer(r.ctx, card.ID, wire.ChoiceUndo, card.Revision) }() wg.Wait() ok := 0 for _, err := range errs { switch { case err == nil: ok++ case Status(err) != 409: t.Fatalf("race loser: %v", err) } } if ok != 1 { t.Fatalf("race: %v", errs) } if k, _ := r.client.Task(r.ctx, fold2); k.Folded != nil || k.Stage == wire.StageCancelled { t.Fatalf("after the race: %+v", k.Folded) } if k, _ := r.client.Task(r.ctx, keep2); len(k.Combined) != 0 { t.Fatal("the destination kept the fold") } } func statusBody(err error) []byte { var s *ErrStatus if errors.As(err, &s) { return s.Body } return nil } // TestContractHousekeepingPause: one switch. Paused, no detector runs and // nothing is posted; a stale revision is refused; Resume and the next // pass acts. func TestContractHousekeepingPause(t *testing.T) { r := newToolRig(t) h := r.housekeeping() if h.Paused || h.Revision != 0 { t.Fatalf("defaults: %+v", h) } paused, err := r.client.SetHousekeeping(r.ctx, true, h.Revision) if err != nil || !paused.Paused { t.Fatalf("pause: %+v %v", paused, err) } shape(t, "api/housekeeping-paused.json", paused) if _, err := r.client.SetHousekeeping(r.ctx, false, h.Revision); Status(err) != 409 { t.Fatalf("stale revision: %v", err) } snap, _ := r.client.Snapshot(r.ctx) if !snap.HousekeepingSummary.Paused { t.Fatal("summary not paused") } _, fold := r.pair("p1", "Swipe back from the edge doesn't work") if n := r.tidy(); n != 0 { t.Fatal("combined while paused") } if k, _ := r.client.Task(r.ctx, fold); k.Folded != nil { t.Fatal("folded while paused") } if h := r.housekeeping(); len(h.Actions)+len(h.Refusals) != 0 { t.Fatalf("rows while paused: %+v", h.Actions) } // Nothing is posted: no digest while paused. r.clock(time.Now().UTC().Add(24 * time.Hour).Truncate(24 * time.Hour).Add(9 * time.Hour)) r.tick() for _, c := range r.snapshotCards() { if c.Kind == wire.CardHousekeeping { t.Fatal("a digest while paused") } } r.inst.Store.Chat().SetHousekeepingClock(daytime()) if _, err := r.client.SetHousekeeping(r.ctx, false, paused.Revision); err != nil { t.Fatal(err) } if n := r.tidy(); n != 1 { t.Fatalf("after Resume combined %d", n) } } func (r *toolRig) snapshotCards() []wire.Card { r.t.Helper() snap, err := r.client.Snapshot(r.ctx) if err != nil { r.t.Fatal(err) } return snap.Cards } // TestContractHousekeepingAutoDisable: two Undos within the week switch // the detector off for the person, it says so once in the digest, the // next pair is left alone, and only the person switches it back on. func TestContractHousekeepingAutoDisable(t *testing.T) { r := newToolRig(t) for i, title := range []string{"Swipe back from the edge doesn't work", "Timeline jumps when images load"} { _, fold := r.pair("a"+itoa(i), title) if n := r.tidy(); n != 1 { t.Fatalf("pair %d combined %d", i, n) } if _, err := r.client.UndoAction(r.ctx, r.action(fold).ID); err != nil { t.Fatal(err) } } h := r.housekeeping() var det wire.HousekeepingDetector for _, d := range h.Detectors { if d.ID == housekeeping.DuplicateSameCreatorID { det = d } } if det.Enabled || det.DisabledReason != wire.ReasonDetectorFailures || det.DisabledAt == nil { t.Fatalf("detector after two Undos: %+v", det) } snap, _ := r.client.Snapshot(r.ctx) if len(snap.HousekeepingSummary.Disabled) != 1 || snap.HousekeepingSummary.Disabled[0] != housekeeping.DuplicateSameCreatorID { t.Fatalf("summary: %+v", snap.HousekeepingSummary) } _, fold3 := r.pair("a3", "Compose sheet keyboard covers the send button") if n := r.tidy(); n != 0 { t.Fatal("a disabled detector combined") } // The digest says so once, from 08:00 the next day. next := time.Now().UTC().Add(24 * time.Hour).Truncate(24 * time.Hour).Add(8*time.Hour + 30*time.Minute) r.clock(next) r.tick() r.tick() var digests []wire.Card for _, c := range r.snapshotCards() { if c.Kind == wire.CardHousekeeping { digests = append(digests, c) } } if len(digests) != 1 || !strings.Contains(digests[0].Question, "Tidied 2 things.") || !strings.Contains(digests[0].Question, "Stopped combining duplicate tasks") { t.Fatalf("digest: %+v", digests) } shape(t, "api/card-digest.json", digests[0]) if !strings.Contains(r.inst.Get(t, "/conversation"), `data-digest-link`) { t.Fatal("the digest line is not on the conversation page") } r.clock(next.Add(24 * time.Hour)) r.tick() n := 0 for _, c := range r.snapshotCards() { if c.Kind == wire.CardHousekeeping && strings.Contains(c.Question, "Stopped") { n++ } } if n != 1 { t.Fatalf("said %d times", n) } r.inst.Store.Chat().SetHousekeepingClock(daytime()) // Only the person switches it back on. h = r.housekeeping() if _, err := r.client.SetDetector(r.ctx, housekeeping.DuplicateSameCreatorID, true, h.Revision); err != nil { t.Fatal(err) } if n := r.tidy(); n != 1 { t.Fatalf("after re-enabling combined %d", n) } if k, _ := r.client.Task(r.ctx, fold3); k.Folded == nil { t.Fatal("third pair not combined") } } // TestContractHousekeepingQuietHours: an action at 02:00 shows on the // view at once and in the conversation at 08:00; at 23:00 one waits until // the person's first message. func TestContractHousekeepingQuietHours(t *testing.T) { r := newToolRig(t) // In Madrid (an hour ahead of UTC, two in summer), on the local clock, // so it holds on any date (review S5). l := zoneClock(t, r.client, r.ctx, "Europe/Madrid") r.clock(l.at(0, 2, 0)) _, fold := r.pair("q1", "Swipe back from the edge doesn't work") if n := r.tidy(); n != 1 { t.Fatalf("combined %d", n) } a := r.action(fold) if a.VisibleAt == nil || !a.VisibleAt.Equal(l.at(0, 8, 0)) { t.Fatalf("visible at %v", a.VisibleAt) } receipt := func() *wire.Card { for _, c := range r.snapshotCards() { if c.ActionID == a.ID { return &c } } return nil } if receipt() != nil { t.Fatal("the receipt showed during quiet hours") } r.clock(l.at(0, 7, 59)) r.tick() if receipt() != nil { t.Fatal("the receipt showed before 08:00") } r.clock(l.at(0, 8, 0)) r.tick() c := receipt() if c == nil { t.Fatal("the receipt did not show at 08:00") } shape(t, "api/card-housekeeping.json", *c) r.wait("receipt event", func(cv *Conversation) bool { return cv.Cards[c.ID].ID != "" }) // At 23:00: the person's first message shows it. r.clock(l.at(0, 23, 0)) _, fold2 := r.pair("q2", "Timeline jumps when images load") if n := r.tidy(); n != 1 { t.Fatalf("second combined %d", n) } a2 := r.action(fold2) if a2.VisibleAt == nil || !a2.VisibleAt.Equal(l.at(1, 8, 0)) { t.Fatalf("second visible at %v", a2.VisibleAt) } for _, c := range r.snapshotCards() { if c.ActionID == a2.ID { t.Fatal("shown before the message") } } if _, err := r.client.Send(r.ctx, "Morning", "q2-msg"); err != nil { t.Fatal(err) } found := false for _, c := range r.snapshotCards() { found = found || c.ActionID == a2.ID } if !found { t.Fatal("the person's message did not show the receipt") } // The person's own window: 12:00 to 14:00. An action at 13:00 waits // until 14:00; one at 02:00 shows at once. h := r.housekeeping() h, err := r.client.SetQuiet(r.ctx, false, 12, 14, h.Revision) if err != nil || h.Quiet != (wire.QuietHours{From: 12, Until: 14}) { t.Fatalf("quiet hours: %+v %v", h.Quiet, err) } if _, err := r.client.SetQuiet(r.ctx, false, 24, 3, h.Revision); Status(err) != 422 { t.Fatalf("an hour past 23: %v", err) } r.clock(l.at(1, 13, 0)) _, fold3 := r.pair("q3", "Compose sheet keyboard covers the send button") r.tidy() if a3 := r.action(fold3); a3.VisibleAt == nil || !a3.VisibleAt.Equal(l.at(1, 14, 0)) { t.Fatalf("own window: %v", a3.VisibleAt) } // None: From equal to Until. if _, err := r.client.SetQuiet(r.ctx, false, 0, 0, r.housekeeping().Revision); err != nil { t.Fatal(err) } r.clock(l.at(2, 2, 0)) _, fold4 := r.pair("q4", "Crash on launch after the update") r.tidy() if a4 := r.action(fold4); a4.VisibleAt != nil { t.Fatalf("no quiet hours, still held: %v", a4.VisibleAt) } } // TestContractHousekeepingRestartWhileClaimed: a claim a crash left // behind is revalidated at start-up: unchanged and never dispatched, it // goes back to held; its subject moved, it expires and its reservation // is released; dispatched, it waits for the runner. func TestContractHousekeepingRestartWhileClaimed(t *testing.T) { r := newToolRig(t) id := taskID(t, r.call("c1", wire.ToolRecordTask, map[string]any{"repo": "oficina/sample", "title": "Crash on launch", "brief": "Every time."})) k, _ := r.client.Task(r.ctx, id) now := time.Now().UTC().Format(time.RFC3339Nano) for _, row := range []struct { id, key, attempt string rev int64 }{{"hk_same", "judge:same", "", k.Revision}, {"hk_moved", "judge:moved", "", k.Revision - 1}, {"hk_sent", "judge:sent", "t_1:1", k.Revision}} { if _, err := r.inst.DB.Writer().Exec(`INSERT INTO chat_housekeeping (id, team, person, detector, subject_kind, subject_id, subject_revision, finding_key, class, state, reason, claimed_at, attempt, reserved_turns, reserved_tokens, reserved_retries, charged_turns, charged_tokens, charged_retries, charged_complete, releasing, evidence, result, recurrences, at, revision) VALUES (?, ?, ?, 'judge', 'task', ?, ?, ?, 'propose', 'claimed', '', ?, ?, 1, 40000, 0, 0, 0, 0, 0, 0, '', '', 0, ?, 1)`, row.id, r.inst.TeamID, Owner, id, row.rev, row.key, now, row.attempt, now); err != nil { t.Fatal(err) } } r.inst.Restart(t) state := func(id string) (string, string, bool) { var s, reason string var releasing bool if err := r.inst.DB.Writer().QueryRow("SELECT state, reason, releasing FROM chat_housekeeping WHERE id = ?", id).Scan(&s, &reason, &releasing); err != nil { t.Fatal(err) } return s, reason, releasing } if s, _, _ := state("hk_same"); s != wire.ActionHeld { t.Fatalf("unchanged claim: %s", s) } if s, reason, releasing := state("hk_moved"); s != wire.ActionExpired || reason != wire.ReasonSubjectMoved || releasing { t.Fatalf("moved claim: %s %s %v", s, reason, releasing) } if s, _, _ := state("hk_sent"); s != wire.ActionClaimed { t.Fatalf("dispatched claim: %s", s) } } // digests are the digest lines in the person's conversation. func (r *toolRig) digests() []wire.Card { r.t.Helper() var out []wire.Card for _, c := range r.snapshotCards() { if c.Kind == wire.CardHousekeeping { out = append(out, c) } } return out } // TestContractHousekeepingPauseHoldsReceipts (Astra round 1, finding 5): // a receipt held through quiet hours stays held while its person is // paused, at 08:00 and when they write; Resume lets it show. func TestContractHousekeepingPauseHoldsReceipts(t *testing.T) { r := newToolRig(t) day := time.Now().UTC().Truncate(24 * time.Hour) r.clock(day.Add(2 * time.Hour)) _, fold := r.pair("ph", "Swipe back from the edge doesn't work") if n := r.tidy(); n != 1 { t.Fatalf("combined %d", n) } a := r.action(fold) shown := func() bool { for _, c := range r.snapshotCards() { if c.ActionID == a.ID { return true } } return false } r.clock(day.Add(3 * time.Hour)) h, err := r.client.SetHousekeeping(r.ctx, true, r.housekeeping().Revision) if err != nil { t.Fatal(err) } r.clock(day.Add(8 * time.Hour)) r.tick() if shown() { t.Fatal("published at 08:00 while paused") } if _, err := r.client.Send(r.ctx, "Morning", "ph-msg"); err != nil { t.Fatal(err) } if shown() { t.Fatal("published by the person's message while paused") } if _, err := r.client.SetHousekeeping(r.ctx, false, h.Revision); err != nil { t.Fatal(err) } r.tick() if !shown() { t.Fatal("not shown after Resume") } } // TestContractHousekeepingDigestSchedule (Astra round 1, findings 6 and // 7): an empty morning does not use up the day's digest, so a later // action still gets one that day; a digest due in quiet hours waits for // them to end, as receipts do, and is posted once. func TestContractHousekeepingDigestSchedule(t *testing.T) { r := newToolRig(t) // In Madrid, on the local clock (review S5). l := zoneClock(t, r.client, r.ctx, "Europe/Madrid") r.clock(l.at(0, 8, 30)) r.tick() if d := r.digests(); len(d) != 0 { t.Fatalf("a digest with nothing to say: %+v", d) } r.clock(l.at(0, 9, 0)) r.pair("d1", "Swipe back from the edge doesn't work") r.tidy() r.clock(l.at(0, 9, 30)) r.tick() if d := r.digests(); len(d) != 1 || !strings.Contains(d[0].Question, "Tidied 1 thing.") { t.Fatalf("the empty morning used up the day: %+v", d) } // The next day, nothing ticks until 23:00, after an action at 22:30: // the digest waits for 08:00. r.clock(l.at(1, 22, 30)) r.pair("d2", "Timeline jumps when images load") r.tidy() r.clock(l.at(1, 23, 0)) r.tick() if d := r.digests(); len(d) != 1 { t.Fatalf("a digest in quiet hours: %+v", d) } r.clock(l.at(2, 8, 0)) r.tick() r.tick() d := r.digests() if len(d) != 2 || d[1].VisibleAt == nil || !d[1].VisibleAt.Equal(l.at(2, 8, 0)) { t.Fatalf("the held digest at 08:00: %+v", d) } }