Skip to content
quarry Artifact [560f6b7615]
Login

Artifact [560f6b7615]

Artifact 560f6b761521bc5b8d21403bfe02001c94208ad9fcd9c28cf87f1738530a261c:


package api

import (
	"context"
	"path/filepath"
	"strings"
	"testing"

	"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")
				}
			}
		}
	}
}