Skip to content
quarry Artifact [df9ae48bc8]
Login

Artifact [df9ae48bc8]

Artifact df9ae48bc87058c010869423e52485d63a3b6da7bf02cd028bca5a19e751696e:


package api

import (
	"context"
	"fmt"
	"path/filepath"
	"strings"
	"sync"
	"testing"
	"time"

	"craftdesign.group/quarry/internal/artifact"
	"craftdesign.group/quarry/internal/index"
	"craftdesign.group/quarry/internal/ops"
)

type armedStub struct {
	AutoStore
	armed map[string]bool
}

func (a armedStub) AutoAcceptOf(repo, landing string) (string, bool) {
	return "alex", a.armed[repo+"/"+landing]
}

func ticketIndex(t *testing.T, tid, status string) *index.Index {
	t.Helper()
	ix, err := index.Open(filepath.Join(t.TempDir(), "t.db"))
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { ix.Close() })
	if err := ix.FoldNow([]index.Parsed{{Hash: "t1", Art: &artifact.Artifact{Type: artifact.Ticket, TicketID: tid,
		Date: "2026-08-15T09:00:00", User: "dan",
		Fields: []artifact.Field{{Name: "status", Value: status}, {Name: "title", Value: "x"}}}}}); err != nil {
		t.Fatal(err)
	}
	return ix
}

// settledFixture serves one account's inbox over repositories whose
// subjects are in every state the rules name.
func settledFixture(t *testing.T) (*ops.Registry, context.Context, *fakeAttention, map[string]string) {
	t.Helper()
	open := openLandingIndex(t, "feature", "f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1")
	done := landingIndex(t, "ada", "feature", "trunk", "rejected")
	openTicket, closedTicket := strings.Repeat("ab", 20), strings.Repeat("cd", 20)
	fa := newFakeAttention()
	d := Deps{
		Attention: fa, AttnRead: newMemAttnRead(),
		Repos: NewRepos(map[string]*Repo{
			"live":   {Chat: "live", Index: open},
			"done":   {Chat: "done", Index: done},
			"tickop": {Chat: "tickop", Index: ticketIndex(t, openTicket, "Open")},
			"tickcl": {Chat: "tickcl", Index: ticketIndex(t, closedTicket, "Closed")},
		}),
		Auto: armedStub{armed: map[string]bool{"live/" + landingHash: false}},
		SignOffs: fxSignOffs{rows: []SignOffRequest{
			{ID: "rq-open", Owner: "alice", State: "pending"},
			{ID: "rq-done", Owner: "alice", State: "approved"},
		}},
	}
	ids := map[string]string{}
	add := func(name, kind, repo, link, txn string) {
		seq, err := fa.Attend("alice", AttentionEvent{Kind: kind, Repo: repo, Summary: name, Link: link, At: "2026-08-01T00:00:01Z", TxnID: txn})
		if err != nil {
			t.Fatal(err)
		}
		ids[name] = localID(seq)
	}
	add("proposed-open", "landing", "live", "/r/live/landing/"+landingHash, "p1")
	add("proposed-settled", "landing", "done", "/r/done/landing/"+landingHash, "p2")
	add("disarm-live", kindDisarmed, "live", "https://forge.example/r/own/live/landing/"+landingHash, "d1")
	add("disarm-settled", kindDisarmed, "done", "/r/done/landing/"+landingHash, "d2")
	add("request-open", "signoff", "live", "/me/requests/rq-open", "s1")
	add("request-decided", "signoff", "live", "/me/requests/rq-done", "s2")
	add("ticket-open", "mention", "tickop", "/r/tickop/ticket/"+openTicket, "m1")
	add("ticket-closed", "mention", "tickcl", "/r/tickcl/ticket/"+closedTicket, "m2")
	add("reply-closed", "reply", "tickcl", "/r/tickcl/ticket/"+closedTicket, "m3")
	add("chat", "chat", "done", "/r/done/chat", "c1")
	add("reply-on-settled-landing", "reply", "done", "/r/done/landing/"+landingHash, "c2")
	add("comment-on-settled-landing", "landing.commented", "done", "/r/done/landing/"+landingHash, "c3")
	r := inboxRegistry(t, d)
	return r, ops.WithUser(context.Background(), "alice"), fa, ids
}

func TestInboxSettledFollowsEachRule(t *testing.T) {
	r, ctx, _, _ := settledFixture(t)
	out, err := r.Invoke(ctx, "inbox.list", inboxListIn{Limit: 50})
	if err != nil {
		t.Fatal(err)
	}
	got := map[string]bool{}
	for _, row := range out.(inboxListOut).Rows {
		got[row.Summary] = row.Settled
	}
	want := map[string]bool{
		"proposed-open": false, "proposed-settled": true,
		"disarm-live": false, "disarm-settled": true,
		"request-open": false, "request-decided": true,
		"ticket-open": false, "ticket-closed": true,
		"reply-closed": false, "chat": false, "reply-on-settled-landing": false, "comment-on-settled-landing": false,
	}
	for k, w := range want {
		if g, ok := got[k]; !ok || g != w {
			t.Errorf("FAIL: %s: settled %v (present %v), want %v", k, g, ok, w)
		}
	}
}

func TestInboxSettledADisarmIsSettledOnceArmedAgain(t *testing.T) {
	open := openLandingIndex(t, "feature", "f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1f1")
	fa := newFakeAttention()
	fa.Attend("alice", AttentionEvent{Kind: kindDisarmed, Repo: "live", Summary: "d", At: "2026-08-01T00:00:01Z",
		Link: "/r/live/landing/" + landingHash, TxnID: "d"})
	for _, armed := range []bool{false, true} {
		d := Deps{Attention: fa, AttnRead: newMemAttnRead(),
			Repos: NewRepos(map[string]*Repo{"live": {Chat: "live", Index: open}}),
			Auto:  armedStub{armed: map[string]bool{"live/" + landingHash: armed}}}
		out, err := inboxRegistry(t, d).Invoke(ops.WithUser(context.Background(), "alice"), "inbox.list", inboxListIn{})
		if err != nil {
			t.Fatal(err)
		}
		if got := out.(inboxListOut).Rows[0].Settled; got != armed {
			t.Errorf("FAIL: armed=%v: settled %v", armed, got)
		}
	}
}

// Rows over one repository read its landings once, and a settled read
// marks nothing read.
func TestInboxSettledIsBatchedAndNeverMarksRead(t *testing.T) {
	r, ctx, fa, _ := settledFixture(t)
	before := fa.sent["alice"]
	out, err := r.Invoke(ctx, "inbox.list", inboxListIn{Limit: 50})
	if err != nil {
		t.Fatal(err)
	}
	for _, row := range out.(inboxListOut).Rows {
		if row.Read {
			t.Errorf("FAIL: %s was marked read", row.Summary)
		}
	}
	if len(fa.sent["alice"]) != len(before) {
		t.Errorf("FAIL: the list wrote events")
	}
	// The batch: the landing reads for many rows are one per repository.
	rows := make([]inboxRow, 40)
	for i := range rows {
		rows[i] = inboxRow{Repo: "done", Link: "/r/done/landing/" + landingHash}
	}
	d := Deps{Repos: NewRepos(map[string]*Repo{"done": {Chat: "done", Index: landingIndex(t, "ada", "feature", "trunk", "rejected")}})}
	d.settleRows(context.Background(), "alice", rows)
	for i, row := range rows {
		if !row.Settled {
			t.Fatalf("FAIL: row %d unsettled", i)
		}
	}
}

func TestInboxCountLeavesOutSettledUnread(t *testing.T) {
	r, ctx, _, _ := settledFixture(t)
	out, err := r.Invoke(ctx, "inbox.count", inboxCountIn{})
	if err != nil {
		t.Fatal(err)
	}
	list, _ := r.Invoke(ctx, "inbox.list", inboxListIn{Limit: 50})
	unsettled := 0
	for _, row := range list.(inboxListOut).Rows {
		if !row.Read && !row.Settled {
			unsettled++
		}
	}
	if got := out.(inboxCountOut).Unread; got != unsettled || got == 0 {
		t.Errorf("FAIL: count %d, unsettled unread %d", got, unsettled)
	}
}

func TestInboxRowWireKeyIsSettled(t *testing.T) {
	r, ctx, _, _ := settledFixture(t)
	out, _ := r.Invoke(ctx, "inbox.list", inboxListIn{Limit: 5})
	if b := verdictJSON(t, out); b["rows"] == nil {
		t.Fatal("no rows")
	} else if row := b["rows"].([]any)[0].(map[string]any); row["settled"] == nil {
		t.Errorf("FAIL: row has no settled key: %v", row)
	}
}

// A burst of badge redraws makes one settle pass; no linked unread row
// makes none.
func TestInboxSettledABurstMakesOnePass(t *testing.T) {
	r, ctx, _, _ := settledFixture(t)
	before := settlePasses.Load()
	for i := 0; i < 25; i++ {
		if _, err := r.Invoke(ctx, "inbox.count", inboxCountIn{}); err != nil {
			t.Fatal(err)
		}
		if _, err := r.Invoke(ctx, "inbox.list", inboxListIn{Limit: 50}); err != nil {
			t.Fatal(err)
		}
	}
	if got := settlePasses.Load() - before; got != 1 {
		t.Errorf("FAIL: %d settle passes for a burst, want 1", got)
	}
}

func TestInboxSettledSkipsThePassWithNoLinkedUnreadRow(t *testing.T) {
	fa := newFakeAttention()
	fa.Attend("alice", AttentionEvent{Kind: "mention", Summary: "hi", At: "2026-08-01T00:00:01Z", Link: "/r/x/chat", TxnID: "a"})
	fa.Attend("alice", AttentionEvent{Kind: "reply", Repo: "done", Summary: "r", At: "2026-08-01T00:00:02Z", Link: "/r/done/landing/" + landingHash, TxnID: "b"})
	d := Deps{Attention: fa, AttnRead: newMemAttnRead(), Repos: NewRepos(nil)}
	before := settlePasses.Load()
	if _, err := inboxRegistry(t, d).Invoke(ops.WithUser(context.Background(), "alice"), "inbox.list", inboxListIn{}); err != nil {
		t.Fatal(err)
	}
	if got := settlePasses.Load() - before; got != 0 {
		t.Errorf("FAIL: %d passes with nothing to settle", got)
	}
}

// A reader who lost access to the repository learns nothing from it.
func TestInboxSettledIsFalseWhereTheReaderCannotRead(t *testing.T) {
	done := landingIndex(t, "ada", "feature", "trunk", "rejected")
	fa := newFakeAttention()
	fa.Attend("alice", AttentionEvent{Kind: "landing", Repo: "done", Summary: "p", At: "2026-08-01T00:00:01Z", Link: "/r/done/landing/" + landingHash, TxnID: "p"})
	for _, may := range []bool{true, false} {
		d := Deps{Attention: fa, AttnRead: newMemAttnRead(), Repos: NewRepos(map[string]*Repo{"done": {Chat: "done", Index: done}}),
			CanRead: func(context.Context, string) bool { return may }}
		out, err := inboxRegistry(t, d).Invoke(ops.WithUser(context.Background(), "alice"), "inbox.list", inboxListIn{})
		if err != nil {
			t.Fatal(err)
		}
		rows := out.(inboxListOut).Rows
		if may && (len(rows) != 1 || !rows[0].Settled) {
			t.Errorf("FAIL: a reader with access: %+v", rows)
		}
		if !may {
			for _, row := range rows {
				if row.Settled {
					t.Errorf("FAIL: a reader without access sees settled")
				}
			}
		}
	}
}

// An operations alert is settled a day after it was raised, and a memory
// alert as soon as no memory condition the reader was told of is open.
func TestInboxSettledOpsAlertsClearOrAgeOut(t *testing.T) {
	now := time.Date(2026, 11, 21, 12, 0, 0, 0, time.UTC)
	oldNow := settleNow
	settleNow = func() time.Time { return now }
	t.Cleanup(func() { settleNow = oldNow })
	fa := newFakeAttention()
	prefs := &memPrefs{}
	d := Deps{Attention: fa, AttnRead: newMemAttnRead(), Repos: NewRepos(map[string]*Repo{}), Prefs: prefs}
	at := func(ago time.Duration) string { return now.Add(-ago).Format(time.RFC3339) }
	add := func(name, kind, link, when string) {
		if _, err := fa.Attend("alice", AttentionEvent{Kind: kind, Summary: name, Link: link, At: when, TxnID: name}); err != nil {
			t.Fatal(err)
		}
	}
	add("slow-old", "slow", "https://forge.example/fleet/ops/route?path=GET+%2F", at(25*time.Hour))
	add("slow-new", "slow", "https://forge.example/fleet/ops/route?path=GET+%2F", at(time.Hour))
	add("error-old", "error", "https://forge.example/fleet", at(48*time.Hour))
	add("memory-new", "ops", "https://forge.example/fleet/ops#memory", at(time.Hour))
	add("mention-old", "mention", "https://forge.example/r/x/chat", at(48*time.Hour))
	r := inboxRegistry(t, d)
	ctx := ops.WithUser(context.Background(), "alice")
	settled := func() map[string]bool {
		settleCaches = sync.Map{}
		out, err := r.Invoke(ctx, "inbox.list", inboxListIn{Limit: 50})
		if err != nil {
			t.Fatal(err)
		}
		got := map[string]bool{}
		for _, row := range out.(inboxListOut).Rows {
			got[row.Summary] = row.Settled
		}
		return got
	}
	prefs.SetAccountPref("alice", openKey("host-low"), "1")
	got := settled()
	want := map[string]bool{"slow-old": true, "slow-new": false, "error-old": true, "memory-new": false, "mention-old": false}
	for k, w := range want {
		if got[k] != w {
			t.Errorf("FAIL: %s settled %v, want %v", k, got[k], w)
		}
	}
	// The clear takes the open mark away: the memory alert is settled.
	prefs.SetAccountPref("alice", openKey("host-low"), "")
	if got := settled(); !got["memory-new"] || got["slow-new"] {
		t.Errorf("FAIL: after the clear %v", got)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// inbox.count leaves out settled rows however deep they are, not only on
// the newest page.
func TestInboxCountLeavesOutSettledRowsPastTheFirstPage(t *testing.T) {
	now := time.Date(2026, 11, 21, 12, 0, 0, 0, time.UTC)
	oldNow := settleNow
	settleNow = func() time.Time { return now }
	t.Cleanup(func() { settleNow = oldNow; unsettledCache = sync.Map{} })
	unsettledCache = sync.Map{}
	fa := newFakeAttention()
	d := Deps{Attention: fa, AttnRead: newMemAttnRead(), Repos: NewRepos(map[string]*Repo{})}
	for i := 0; i < 300; i++ {
		fa.Attend("alice", AttentionEvent{Kind: "slow", Summary: "old", Link: "https://forge.example/fleet", At: now.Add(-72 * time.Hour).Format(time.RFC3339), TxnID: fmt.Sprintf("o%d", i)})
	}
	for i := 0; i < 3; i++ {
		fa.Attend("alice", AttentionEvent{Kind: "mention", Summary: "new", Link: "https://forge.example/r/x/chat", At: now.Format(time.RFC3339), TxnID: fmt.Sprintf("n%d", i)})
	}
	r := inboxRegistry(t, d)
	out, err := r.Invoke(ops.WithUser(context.Background(), "alice"), "inbox.count", inboxCountIn{})
	if err != nil {
		t.Fatal(err)
	}
	if got := out.(inboxCountOut).Unread; got != 3 {
		t.Errorf("FAIL: count %d, want the 3 unsettled", got)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// The badge is the list's unsettled unread rows. The companion's own
// unread total is counted by another half and can be lower than the
// unread rows the list shows; subtracting settled rows from it took a
// real badge to zero.
func TestInboxCountIsTheListsUnsettledRowsWhenTheRawTotalIsLow(t *testing.T) {
	now := time.Date(2026, 11, 22, 12, 0, 0, 0, time.UTC)
	oldNow := settleNow
	settleNow = func() time.Time { return now }
	t.Cleanup(func() { settleNow = oldNow; unsettledCache = sync.Map{} })
	unsettledCache = sync.Map{}
	var msgs []InboxMessage
	for i := 0; i < 250; i++ {
		msgs = append(msgs, InboxMessage{ID: fmt.Sprintf("old%d", i), Workflow: "quarry-slow", Subject: "slow render",
			Link: "https://forge.example/fleet/ops/route", At: now.Add(-72 * time.Hour).Format(time.RFC3339)})
	}
	for i := 0; i < 4; i++ {
		msgs = append([]InboxMessage{{ID: fmt.Sprintf("new%d", i), Workflow: "quarry-mention", Subject: "mention",
			Link: "https://forge.example/r/x/chat", At: now.Format(time.RFC3339)}}, msgs...)
	}
	// The companion says 120 unread while listing 254.
	inbox := &fixedPageInbox{msgs: msgs, unread: 120, pageSize: 200, honourLimit: true}
	d := Deps{Inbox: inbox, Repos: NewRepos(map[string]*Repo{})}
	r := inboxRegistry(t, d)
	out, err := r.Invoke(ops.WithUser(context.Background(), "alice"), "inbox.count", inboxCountIn{})
	if err != nil {
		t.Fatal(err)
	}
	if got := out.(inboxCountOut).Unread; got != 4 {
		t.Errorf("FAIL: count %d, want the 4 unsettled rows", got)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}