~bigbes/sr-ht-dolt

ref: e04928c9954cfe97811816cdbe87ab8a36db0a06 sr-ht-dolt/web/beads_test.go -rw-r--r-- 26.7 KiB
e04928c9 — Eugene Blikh login: take the unified-login cookie decode from ecore 9 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
package web

import (
	"context"
	"net/http"
	"net/url"
	"sort"
	"strings"
	"testing"

	"sourcecraft.dev/bigbes/sr-ht-dolt/browse"
	"sourcecraft.dev/bigbes/sr-ht-dolt/core"
)

// --- fixtures ----------------------------------------------------------------

// beadsTables is a schema fingerprint that Applies should accept: issues (with
// id + status) + dependencies both present.
func beadsTables() []browse.TableInfo {
	return []browse.TableInfo{
		{Name: "issues", Columns: []browse.ColumnInfo{
			{Name: "id", PrimaryKey: true}, {Name: "status"},
		}},
		{Name: "dependencies", Columns: []browse.ColumnInfo{{Name: "id", PrimaryKey: true}}},
		{Name: "labels"},
	}
}

// beadsFixture wires a fakeSession whose per-table Rows model a small parade:
//   - i-open   : open, ready         → Lined Up
//   - i-prog   : in_progress         → Rolling
//   - i-done   : closed              → Past Stand
//   - i-blocked: open, blocked by i-open (a "blocks" dep to a non-closed target)
//     and also carries is_blocked=1  → Stalled
//
// The issues page deliberately orders its columns id,title,status,priority,...
// with is_blocked LAST so column-name mapping (not positional) is exercised.
func beadsFixture() *fakeSession {
	issues := &browse.RowPage{
		// Column order chosen so nothing is at a "natural" index; is_blocked is last
		// and close_reason sits mid-row so name (not positional) mapping is exercised.
		Columns: []string{"id", "title", "status", "priority", "issue_type", "assignee", "created_at", "closed_at", "close_reason", "is_blocked"},
		Rows: [][]string{
			{"i-open", "Ready to roll", "open", "1", "feature", "alice", "2024-01-01", "NULL", "NULL", "0"},
			{"i-prog", "Under way", "in_progress", "0", "bug", "bob", "2024-01-02", "NULL", "NULL", "0"},
			{"i-done", "Finished", "closed", "2", "chore", "carol", "2024-01-03", "2024-01-04", "Fixed in commit abc123", "0"},
			{"i-blocked", "Waiting", "open", "1", "feature", "dave", "2024-01-04", "NULL", "NULL", "1"},
		},
		Total: 4,
	}
	// i-blocked depends on i-open (blocks, target open → keeps it Stalled).
	// i-open is depended on by i-blocked → i-open.Blocks == 1.
	deps := &browse.RowPage{
		Columns: []string{"id", "issue_id", "depends_on_issue_id", "type"},
		Rows: [][]string{
			{"d1", "i-blocked", "i-open", "blocks"},
		},
		Total: 1,
	}
	labels := &browse.RowPage{
		Columns: []string{"issue_id", "label"},
		Rows: [][]string{
			{"i-open", "backend"},
			{"i-open", "urgent"},
		},
		Total: 2,
	}
	statuses := &browse.RowPage{
		Columns: []string{"name", "category"},
		Rows: [][]string{
			{"open", "open"},
			{"in_progress", "in_progress"},
			{"closed", "closed"},
		},
		Total: 3,
	}
	comments := &browse.RowPage{
		Columns: []string{"issue_id", "author", "text", "created_at"},
		Rows: [][]string{
			{"i-open", "alice", "first!", "2024-01-05"},
			{"i-prog", "bob", "not this one", "2024-01-06"},
		},
		Total: 2,
	}
	// i-done's closure is recorded as a `closed` audit event carrying the reason
	// (the only place the reason now surfaces — there is no standalone block).
	events := &browse.RowPage{
		Columns: []string{"id", "issue_id", "event_type", "actor", "old_value", "new_value", "comment", "created_at"},
		Rows: [][]string{
			{"e1", "i-done", "closed", "carol", "NULL", "Fixed in commit abc123", "NULL", "2024-01-03 12:00:00"},
		},
		Total: 1,
	}
	return &fakeSession{
		branches: []browse.Branch{{Name: "main", Head: "abcdef1234567890"}},
		tables:   beadsTables(),
		rowsByTable: map[string]*browse.RowPage{
			"issues":          issues,
			"dependencies":    deps,
			"labels":          labels,
			"custom_statuses": statuses,
			"comments":        comments,
			"events":          events,
		},
	}
}

// laneBySlug finds a lane in a built board by its slug.
func laneBySlug(d *BeadsData, slug string) *BeadsLane {
	for i := range d.Lanes {
		if d.Lanes[i].Slug == slug {
			return &d.Lanes[i]
		}
	}
	return nil
}

// cardIDs lists the ids of a lane's cards.
func cardIDs(l *BeadsLane) []string {
	if l == nil {
		return nil
	}
	out := make([]string, len(l.Issues))
	for i, c := range l.Issues {
		out[i] = c.ID
	}
	return out
}

// --- Applies -----------------------------------------------------------------

func TestBeadsApplies(t *testing.T) {
	v := &beadsView{}
	if !v.Applies(beadsTables()) {
		t.Fatalf("Applies should be true when issues+dependencies (with id+status) present")
	}
	// Missing dependencies → not a beads DB.
	if v.Applies([]browse.TableInfo{
		{Name: "issues", Columns: []browse.ColumnInfo{{Name: "id"}, {Name: "status"}}},
	}) {
		t.Fatalf("Applies should be false without a dependencies table")
	}
	// issues present but lacking status column → guard rejects.
	if v.Applies([]browse.TableInfo{
		{Name: "issues", Columns: []browse.ColumnInfo{{Name: "id"}}},
		{Name: "dependencies"},
	}) {
		t.Fatalf("Applies should be false when issues lacks a status column")
	}
	// Unrelated schema.
	if v.Applies([]browse.TableInfo{{Name: "widgets"}}) {
		t.Fatalf("Applies should be false for an unrelated schema")
	}
}

// --- board mode --------------------------------------------------------------

func TestBeadsBuildBoardLanes(t *testing.T) {
	v := &beadsView{}
	got, err := v.Build(context.Background(), beadsFixture(), &core.Repo{OwnerName: "alice", Name: "db"}, "main", url.Values{})
	if err != nil {
		t.Fatalf("Build: %v", err)
	}
	d, ok := got.(*BeadsData)
	if !ok {
		t.Fatalf("Build returned %T, want *BeadsData", got)
	}
	if d.Mode != "board" {
		t.Fatalf("Mode = %q, want board", d.Mode)
	}

	checks := map[string][]string{
		"rolling":    {"i-prog"},
		"lined-up":   {"i-open"},
		"stalled":    {"i-blocked"},
		"past-stand": {"i-done"},
	}
	for slug, want := range checks {
		got := cardIDs(laneBySlug(d, slug))
		if strings.Join(got, ",") != strings.Join(want, ",") {
			t.Errorf("lane %s = %v, want %v", slug, got, want)
		}
	}

	if d.Counts.Rolling != 1 || d.Counts.LinedUp != 1 || d.Counts.Stalled != 1 || d.Counts.PastStand != 1 {
		t.Errorf("counts = %+v, want 1 each", d.Counts)
	}
	if d.Counts.Total != 4 || d.Total != 4 {
		t.Errorf("total = %d/%d, want 4", d.Counts.Total, d.Total)
	}
}

func TestBeadsBuildBoardCounts(t *testing.T) {
	v := &beadsView{}
	got, _ := v.Build(context.Background(), beadsFixture(), &core.Repo{OwnerName: "a", Name: "b"}, "main", url.Values{})
	d := got.(*BeadsData)

	// i-blocked depends on i-open → i-blocked.BlockedBy==1, i-open.Blocks==1.
	blocked := laneBySlug(d, "stalled").Issues[0]
	if blocked.ID != "i-blocked" || blocked.BlockedBy != 1 || blocked.Blocks != 0 {
		t.Errorf("i-blocked = %+v, want BlockedBy=1 Blocks=0", blocked)
	}
	open := laneBySlug(d, "lined-up").Issues[0]
	if open.ID != "i-open" || open.Blocks != 1 || open.BlockedBy != 0 {
		t.Errorf("i-open = %+v, want Blocks=1 BlockedBy=0", open)
	}
	// Labels attach by issue_id.
	if strings.Join(open.Labels, ",") != "backend,urgent" {
		t.Errorf("i-open labels = %v, want [backend urgent]", open.Labels)
	}
}

// boardIDs returns every card id on the board, across all lanes.
func boardIDs(d *BeadsData) []string {
	var out []string
	for i := range d.Lanes {
		out = append(out, cardIDs(&d.Lanes[i])...)
	}
	sort.Strings(out)
	return out
}

func TestBeadsBoardFilters(t *testing.T) {
	repo := &core.Repo{OwnerName: "a", Name: "b"}
	cases := []struct {
		name  string
		query url.Values
		want  []string // sorted ids expected on the board
	}{
		{"type", url.Values{"type": {"feature"}}, []string{"i-blocked", "i-open"}},
		{"priority", url.Values{"priority": {"1"}}, []string{"i-blocked", "i-open"}},
		{"assignee", url.Values{"assignee": {"bob"}}, []string{"i-prog"}},
		{"label", url.Values{"label": {"urgent"}}, []string{"i-open"}},
		{"query-title", url.Values{"q": {"ready"}}, []string{"i-open"}},
		{"query-id", url.Values{"q": {"i-done"}}, []string{"i-done"}},
		{"combined-empty", url.Values{"type": {"feature"}, "assignee": {"bob"}}, nil},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			got, err := (&beadsView{}).Build(context.Background(), beadsFixture(), repo, "main", tc.query)
			if err != nil {
				t.Fatalf("Build: %v", err)
			}
			d := got.(*BeadsData)
			ids := boardIDs(d)
			if strings.Join(ids, ",") != strings.Join(tc.want, ",") {
				t.Errorf("board ids = %v, want %v", ids, tc.want)
			}
			if d.Total != len(tc.want) || d.Counts.Total != len(tc.want) {
				t.Errorf("total = %d/%d, want %d", d.Total, d.Counts.Total, len(tc.want))
			}
			if !d.Filter.Active() {
				t.Errorf("Filter.Active() = false, want true")
			}
		})
	}
}

func TestBeadsBoardFilterOptions(t *testing.T) {
	got, _ := (&beadsView{}).Build(context.Background(), beadsFixture(), &core.Repo{OwnerName: "a", Name: "b"}, "main", url.Values{})
	d := got.(*BeadsData)
	o := d.FilterOpts
	if strings.Join(o.Types, ",") != "bug,chore,feature" {
		t.Errorf("types = %v", o.Types)
	}
	if strings.Join(o.Priorities, ",") != "0,1,2" {
		t.Errorf("priorities = %v", o.Priorities)
	}
	if strings.Join(o.Assignees, ",") != "alice,bob,carol,dave" {
		t.Errorf("assignees = %v", o.Assignees)
	}
	if strings.Join(o.Labels, ",") != "backend,urgent" {
		t.Errorf("labels = %v", o.Labels)
	}
	if d.Filter.Active() {
		t.Errorf("no query set, Filter.Active() should be false")
	}
}

func TestBeadsReady(t *testing.T) {
	repo := &core.Repo{OwnerName: "a", Name: "b"}
	got, _ := (&beadsView{}).Build(context.Background(), beadsFixture(), repo, "main", url.Values{})
	d := got.(*BeadsData)

	ready := map[string]bool{}
	for i := range d.Lanes {
		for _, c := range d.Lanes[i].Issues {
			ready[c.ID] = c.Ready
		}
	}
	// Only i-open is actionable: open + unblocked. i-prog is in-progress, i-done
	// closed, i-blocked blocked.
	if !ready["i-open"] {
		t.Errorf("i-open should be ready")
	}
	for _, id := range []string{"i-prog", "i-done", "i-blocked"} {
		if ready[id] {
			t.Errorf("%s should not be ready", id)
		}
	}
	// The ready filter narrows the board to the actionable set.
	f, _ := (&beadsView{}).Build(context.Background(), beadsFixture(), repo, "main", url.Values{"ready": {"1"}})
	if ids := boardIDs(f.(*BeadsData)); strings.Join(ids, ",") != "i-open" {
		t.Errorf("ready filter board = %v, want [i-open]", ids)
	}
}

func TestBeadsDepTree(t *testing.T) {
	repo := &core.Repo{OwnerName: "a", Name: "b"}
	// Chain: a --blocks--> b --blocks--> c (c closed). a depends on b depends on c.
	sess := &fakeSession{
		tables: beadsTables(),
		rowsByTable: map[string]*browse.RowPage{
			"issues": {
				Columns: []string{"id", "title", "status"},
				Rows:    [][]string{{"a", "Aye", "open"}, {"b", "Bee", "open"}, {"c", "Cee", "closed"}},
				Total:   3,
			},
			"dependencies": {
				Columns: []string{"id", "issue_id", "depends_on_issue_id", "type"},
				Rows:    [][]string{{"d1", "a", "b", "blocks"}, {"d2", "b", "c", "blocks"}},
				Total:   2,
			},
		},
	}
	// From a: transitive prerequisites b(0) → c(1); c is closed.
	got, _ := (&beadsView{}).Build(context.Background(), sess, repo, "main", url.Values{"issue": {"a"}})
	d := got.(*BeadsData)
	if len(d.DependsTree) != 2 {
		t.Fatalf("DependsTree = %+v, want [b(0) c(1)]", d.DependsTree)
	}
	if d.DependsTree[0].ID != "b" || d.DependsTree[0].Depth != 0 {
		t.Errorf("node0 = %+v, want b depth 0", d.DependsTree[0])
	}
	if d.DependsTree[1].ID != "c" || d.DependsTree[1].Depth != 1 || !d.DependsTree[1].Closed {
		t.Errorf("node1 = %+v, want c depth 1 closed", d.DependsTree[1])
	}

	// From the leaf c: transitive dependents b(0) → a(1); no prerequisites.
	gotC, _ := (&beadsView{}).Build(context.Background(), sess, repo, "main", url.Values{"issue": {"c"}})
	dc := gotC.(*BeadsData)
	if len(dc.DependentTree) != 2 || dc.DependentTree[0].ID != "b" || dc.DependentTree[1].ID != "a" {
		t.Fatalf("DependentTree = %+v, want [b(0) a(1)]", dc.DependentTree)
	}
	if len(dc.DependsTree) != 0 {
		t.Errorf("c has no prerequisites; DependsTree = %+v", dc.DependsTree)
	}
}

// TestBeadsBlockedByDepOnly proves the dependency-derived block signal works
// even when is_blocked is not set: an issue with a "blocks" dep to a non-closed
// target lands in Stalled; the same dep to a CLOSED target does not.
func TestBeadsBlockedByDepOnly(t *testing.T) {
	sess := &fakeSession{
		tables: beadsTables(),
		rowsByTable: map[string]*browse.RowPage{
			"issues": {
				Columns: []string{"id", "status", "is_blocked"},
				Rows: [][]string{
					{"a", "open", "0"},   // blocked by open b → Stalled
					{"b", "open", "0"},   // ready → Lined Up
					{"c", "open", "0"},   // "blocked" by closed d → NOT stalled → Lined Up
					{"d", "closed", "0"}, // Past Stand
				},
				Total: 4,
			},
			"dependencies": {
				Columns: []string{"issue_id", "depends_on_issue_id", "type"},
				Rows: [][]string{
					{"a", "b", "blocks"},
					{"c", "d", "blocks"},
				},
				Total: 2,
			},
		},
	}
	v := &beadsView{}
	got, err := v.Build(context.Background(), sess, &core.Repo{OwnerName: "a", Name: "b"}, "main", url.Values{})
	if err != nil {
		t.Fatalf("Build: %v", err)
	}
	d := got.(*BeadsData)
	if ids := cardIDs(laneBySlug(d, "stalled")); strings.Join(ids, ",") != "a" {
		t.Errorf("stalled = %v, want [a] (blocked by open dep only)", ids)
	}
	if ids := cardIDs(laneBySlug(d, "lined-up")); strings.Join(ids, ",") != "b,c" {
		t.Errorf("lined-up = %v, want [b c] (c's blocker is closed)", ids)
	}
}

// --- detail mode -------------------------------------------------------------

func TestBeadsBuildDetail(t *testing.T) {
	v := &beadsView{}
	q := url.Values{}
	q.Set("issue", "i-open")
	got, err := v.Build(context.Background(), beadsFixture(), &core.Repo{OwnerName: "a", Name: "b"}, "main", q)
	if err != nil {
		t.Fatalf("Build: %v", err)
	}
	d := got.(*BeadsData)
	if d.Mode != "detail" {
		t.Fatalf("Mode = %q, want detail", d.Mode)
	}
	if d.Issue == nil || d.Issue.ID != "i-open" || d.Issue.Title != "Ready to roll" {
		t.Fatalf("Issue = %+v, want i-open/Ready to roll", d.Issue)
	}
	if strings.Join(d.Issue.Labels, ",") != "backend,urgent" {
		t.Errorf("labels = %v", d.Issue.Labels)
	}
	// i-open is depended on by i-blocked (incoming), and depends on nothing.
	if len(d.DependsOn) != 0 {
		t.Errorf("DependsOn = %v, want none", d.DependsOn)
	}
	if len(d.DependedOnBy) != 1 || d.DependedOnBy[0].IssueID != "i-blocked" {
		t.Errorf("DependedOnBy = %+v, want [i-blocked]", d.DependedOnBy)
	}
	// Only i-open's comment shows in its thread.
	if len(d.Comments) != 1 || d.Comments[0].Author != "alice" || d.Comments[0].Text != "first!" {
		t.Errorf("Comments = %+v, want single alice comment", d.Comments)
	}
}

func TestBeadsBuildDetailOutgoingEdge(t *testing.T) {
	v := &beadsView{}
	q := url.Values{}
	q.Set("issue", "i-blocked")
	got, _ := v.Build(context.Background(), beadsFixture(), &core.Repo{OwnerName: "a", Name: "b"}, "main", q)
	d := got.(*BeadsData)
	if len(d.DependsOn) != 1 || d.DependsOn[0].IssueID != "i-open" || d.DependsOn[0].Title != "Ready to roll" {
		t.Fatalf("DependsOn = %+v, want [i-open/Ready to roll]", d.DependsOn)
	}
	if d.DependsOn[0].Type != "blocks" || d.DependsOn[0].Closed {
		t.Errorf("edge = %+v, want type=blocks not-closed", d.DependsOn[0])
	}
}

// --- end to end --------------------------------------------------------------

func TestBeadsHandleViewBoard(t *testing.T) {
	h := newHarness(t)
	h.store.add(&core.Repo{Name: "db", OwnerID: 1, OwnerName: "alice", Path: "/d", Visibility: core.VisibilityPublic})
	h.browse.sess = beadsFixture()
	setViews(t, h, &beadsView{})

	rec := h.do("GET", "/~alice/db/view/beads", nil, nil)
	if rec.Code != http.StatusOK {
		t.Fatalf("board: got %d, want 200; body=%s", rec.Code, rec.Body.String())
	}
	body := rec.Body.String()
	for _, want := range []string{"Rolling", "Lined Up", "Stalled", "Past Stand", "Ready to roll", "beads-summary"} {
		if !strings.Contains(body, want) {
			t.Errorf("board body missing %q", want)
		}
	}
	// The Tables tab must remain reachable from the view.
	if !strings.Contains(body, "/~alice/db/tree/") {
		t.Errorf("board missing Tables tab link; body=%s", body)
	}
	// The filter bar renders with option lists drawn from the data, plus the
	// Ready-only toggle; i-open is ready, so a ready dot renders on the board.
	for _, want := range []string{`class="beads-filter"`, "All types", ">feature<", "All priorities", "Ready only", "ready-dot"} {
		if !strings.Contains(body, want) {
			t.Errorf("board missing control %q", want)
		}
	}
}

func TestBeadsDepTreeRender(t *testing.T) {
	h := newHarness(t)
	h.store.add(&core.Repo{Name: "db", OwnerID: 1, OwnerName: "alice", Path: "/d", Visibility: core.VisibilityPublic})
	h.browse.sess = &fakeSession{
		branches: []browse.Branch{{Name: "main", Head: "abcdef1234567890"}},
		tables:   beadsTables(),
		rowsByTable: map[string]*browse.RowPage{
			"issues": {Columns: []string{"id", "title", "status"},
				Rows: [][]string{{"a", "Aye", "open"}, {"b", "Bee", "open"}, {"c", "Cee", "open"}}, Total: 3},
			"dependencies": {Columns: []string{"id", "issue_id", "depends_on_issue_id", "type"},
				Rows: [][]string{{"d1", "a", "b", "blocks"}, {"d2", "b", "c", "blocks"}}, Total: 2},
		},
	}
	setViews(t, h, &beadsView{})

	rec := h.do("GET", "/~alice/db/view/beads?issue=a", nil, nil)
	if rec.Code != http.StatusOK {
		t.Fatalf("detail: got %d; body=%s", rec.Code, rec.Body.String())
	}
	body := rec.Body.String()
	// The transitive chain section appears with the depth-1 node c and an indent.
	for _, want := range []string{"Prerequisite chain", "dep-tree", "--depth: 1", ">c<"} {
		if !strings.Contains(body, want) {
			t.Errorf("dep-tree render missing %q; body=%s", want, body)
		}
	}
}

func TestBeadsBoardFilterRender(t *testing.T) {
	h := newHarness(t)
	h.store.add(&core.Repo{Name: "db", OwnerID: 1, OwnerName: "alice", Path: "/d", Visibility: core.VisibilityPublic})
	h.browse.sess = beadsFixture()
	setViews(t, h, &beadsView{})

	rec := h.do("GET", "/~alice/db/view/beads?type=feature", nil, nil)
	if rec.Code != http.StatusOK {
		t.Fatalf("filtered board: got %d; body=%s", rec.Code, rec.Body.String())
	}
	body := rec.Body.String()
	// The active type is preselected and a Clear link appears.
	if !strings.Contains(body, `value="feature" selected`) {
		t.Errorf("type filter not preselected; body=%s", body)
	}
	if !strings.Contains(body, "beads-filter-clear") {
		t.Errorf("Clear link missing when a filter is active")
	}
	// Only feature issues on the board; the bug (i-prog) is filtered out.
	if !strings.Contains(body, "i-open") || strings.Contains(body, "i-prog") {
		t.Errorf("filtered board should show features only; body=%s", body)
	}
}

func TestBeadsHandleViewDetail(t *testing.T) {
	h := newHarness(t)
	h.store.add(&core.Repo{Name: "db", OwnerID: 1, OwnerName: "alice", Path: "/d", Visibility: core.VisibilityPublic})
	h.browse.sess = beadsFixture()
	setViews(t, h, &beadsView{})

	rec := h.do("GET", "/~alice/db/view/beads?issue=i-blocked", nil, nil)
	if rec.Code != http.StatusOK {
		t.Fatalf("detail: got %d, want 200; body=%s", rec.Code, rec.Body.String())
	}
	body := rec.Body.String()
	if !strings.Contains(body, "Waiting") {
		t.Errorf("detail missing issue title; body=%s", body)
	}
	if !strings.Contains(body, "Depends on") || !strings.Contains(body, "i-open") {
		t.Errorf("detail missing dependency edge; body=%s", body)
	}
	if !strings.Contains(body, "Back to the parade") {
		t.Errorf("detail missing back link; body=%s", body)
	}
}

// A closed issue's detail pane must surface its close reason (and the closed
// timestamp), so the resolution recorded by `bd close -r` is not lost.
// TestBeadsDetailShowsCloseReason: the reason appears twice by design — once in
// the Comments tab (which has no closed event) as a Close reason block, and once
// in the History tab as the humanized `closed` event.
func TestBeadsDetailShowsCloseReason(t *testing.T) {
	h := newHarness(t)
	h.store.add(&core.Repo{Name: "db", OwnerID: 1, OwnerName: "alice", Path: "/d", Visibility: core.VisibilityPublic})
	h.browse.sess = beadsFixture()
	setViews(t, h, &beadsView{})

	rec := h.do("GET", "/~alice/db/view/beads?issue=i-done", nil, nil)
	if rec.Code != http.StatusOK {
		t.Fatalf("detail: got %d, want 200; body=%s", rec.Code, rec.Body.String())
	}
	body := rec.Body.String()
	// Comments-tab block.
	if !strings.Contains(body, "<h4>Close reason</h4>") {
		t.Errorf("Comments tab should show a Close reason block; body=%s", body)
	}
	// History-tab closed event.
	if !strings.Contains(body, "closed the issue") {
		t.Errorf("History should carry the closed event; body=%s", body)
	}
	// The reason text itself is present (both places).
	if !strings.Contains(body, "Fixed in commit abc123") {
		t.Errorf("close reason text missing; body=%s", body)
	}
}

// --- epic mode + history -----------------------------------------------------

// beadsEpicFixture models an epic (i-epic) with three parent-child children —
// one closed, one open, one in-progress — plus a comment and three audit events
// on the epic, so both the subtask rollup and the merged history are exercised.
func beadsEpicFixture() *fakeSession {
	issues := &browse.RowPage{
		Columns: []string{"id", "title", "status", "priority", "issue_type", "assignee", "created_at", "is_blocked"},
		Rows: [][]string{
			{"i-epic", "Big Epic", "open", "1", "epic", "", "2024-01-01", "0"},
			{"i-c1", "Child one", "open", "2", "task", "alice", "2024-01-02", "0"},
			{"i-c2", "Child two", "closed", "1", "task", "bob", "2024-01-03", "0"},
			{"i-c3", "Child three", "in_progress", "0", "bug", "carol", "2024-01-04", "0"},
		},
		Total: 4,
	}
	// Each child is the "from" side of a parent-child edge pointing at the epic;
	// created_at/created_by let the view synthesize "added subtask" history.
	deps := &browse.RowPage{
		Columns: []string{"id", "issue_id", "depends_on_issue_id", "type", "created_at", "created_by"},
		Rows: [][]string{
			{"d1", "i-c1", "i-epic", "parent-child", "2024-01-01 09:00:00", "Eugene"},
			{"d2", "i-c2", "i-epic", "parent-child", "2024-01-01 09:05:00", "Eugene"},
			{"d3", "i-c3", "i-epic", "parent-child", "2024-01-01 09:10:00", "Eugene"},
		},
		Total: 3,
	}
	statuses := &browse.RowPage{
		Columns: []string{"name", "category"},
		Rows: [][]string{
			{"open", "open"}, {"in_progress", "in_progress"}, {"closed", "closed"},
		},
		Total: 3,
	}
	comments := &browse.RowPage{
		Columns: []string{"issue_id", "author", "text", "created_at"},
		Rows: [][]string{
			{"i-epic", "alice", "kickoff", "2024-01-05 09:00:00"},
			{"i-c1", "bob", "unrelated", "2024-01-06 09:00:00"},
		},
		Total: 2,
	}
	events := &browse.RowPage{
		Columns: []string{"id", "issue_id", "event_type", "actor", "old_value", "new_value", "comment", "created_at"},
		Rows: [][]string{
			{"e1", "i-epic", "created", "Eugene", "NULL", "NULL", "NULL", "2024-01-01 08:00:00"},
			{"e2", "i-epic", "status_changed", "Eugene", `{"status":"open"}`, `{"status":"in_progress"}`, "NULL", "2024-01-02 10:00:00"},
			{"e3", "i-epic", "updated", "Eugene", "NULL", `{"priority":0}`, "NULL", "2024-01-03 11:00:00"},
			{"e4", "i-epic", "label_added", "Eugene", "NULL", "NULL", "Added label: milestone:m3", "2024-01-04 09:00:00"},
			{"e9", "i-c1", "created", "Eugene", "NULL", "NULL", "NULL", "2024-01-02 08:00:00"},
		},
		Total: 5,
	}
	return &fakeSession{
		branches: []browse.Branch{{Name: "main", Head: "abcdef1234567890"}},
		tables:   beadsTables(),
		rowsByTable: map[string]*browse.RowPage{
			"issues":          issues,
			"dependencies":    deps,
			"custom_statuses": statuses,
			"comments":        comments,
			"events":          events,
		},
	}
}

func TestBeadsEpicMode(t *testing.T) {
	v := &beadsView{}
	raw, err := v.Build(context.Background(), beadsEpicFixture(), nil, "main", url.Values{"issue": {"i-epic"}})
	if err != nil {
		t.Fatalf("build: %v", err)
	}
	d := raw.(*BeadsData)
	if d.Mode != "epic" {
		t.Fatalf("Mode = %q, want epic", d.Mode)
	}
	if d.SubtaskTotal != 3 || d.SubtaskDone != 1 {
		t.Errorf("rollup = %d/%d, want 1/3", d.SubtaskDone, d.SubtaskTotal)
	}
	if d.SubtaskPct() != 33 {
		t.Errorf("pct = %d, want 33", d.SubtaskPct())
	}
	// Sorted open-work-first (in_progress p0, then open p2), closed sinks last.
	gotIDs := []string{d.Subtasks[0].ID, d.Subtasks[1].ID, d.Subtasks[2].ID}
	wantIDs := []string{"i-c3", "i-c1", "i-c2"}
	for i := range wantIDs {
		if gotIDs[i] != wantIDs[i] {
			t.Errorf("subtask order = %v, want %v", gotIDs, wantIDs)
			break
		}
	}
	if d.Subtasks[2].Category != "closed" {
		t.Errorf("last subtask category = %q, want closed", d.Subtasks[2].Category)
	}
}

func TestBeadsHistoryMerge(t *testing.T) {
	v := &beadsView{}
	raw, err := v.Build(context.Background(), beadsEpicFixture(), nil, "main", url.Values{"issue": {"i-epic"}})
	if err != nil {
		t.Fatalf("build: %v", err)
	}
	d := raw.(*BeadsData)

	// Only the epic's own comment shows in the Comments tab (not i-c1's).
	if len(d.Comments) != 1 || d.Comments[0].Text != "kickoff" {
		t.Fatalf("comments = %+v, want just the epic's kickoff", d.Comments)
	}
	// History merges the epic's 1 comment + 4 events + 3 synthesized subtask-add
	// entries (i-c1's own event is excluded), time-sorted.
	if len(d.History) != 8 {
		t.Fatalf("history len = %d, want 8: %+v", len(d.History), d.History)
	}
	for i := 1; i < len(d.History); i++ {
		if d.History[i-1].CreatedAt > d.History[i].CreatedAt {
			t.Errorf("history not time-sorted at %d: %q > %q", i, d.History[i-1].CreatedAt, d.History[i].CreatedAt)
		}
	}
	if d.History[0].Kind != "event" || d.History[0].Summary != "created the issue" {
		t.Errorf("first history = %+v, want created event", d.History[0])
	}
	last := d.History[len(d.History)-1]
	if last.Kind != "comment" || last.Text != "kickoff" {
		t.Errorf("last history = %+v, want the kickoff comment", last)
	}
	// Humanized change lines, and a label event collapsed to one line with no
	// redundant "Added label:" body.
	var sawStatus, sawUpdate, sawLabel, sawSubtask bool
	for _, a := range d.History {
		switch a.Summary {
		case "changed status to in_progress":
			sawStatus = true
		case "updated priority to 0":
			sawUpdate = true
		case "added label milestone:m3":
			sawLabel = true
			if a.Text != "" {
				t.Errorf("label event should have no body, got %q", a.Text)
			}
		case "added subtask i-c1":
			sawSubtask = true
			if a.Kind != "dep" || a.Actor != "Eugene" {
				t.Errorf("subtask-add entry = %+v, want kind=dep actor=Eugene", a)
			}
		}
		if strings.Contains(a.Text, "Added label:") {
			t.Errorf("label note leaked into a history body: %+v", a)
		}
	}
	if !sawStatus || !sawUpdate || !sawLabel || !sawSubtask {
		t.Errorf("history missing lines; status=%v update=%v label=%v subtask=%v",
			sawStatus, sawUpdate, sawLabel, sawSubtask)
	}
}

func TestBeadsEpicViewRender(t *testing.T) {
	h := newHarness(t)
	h.store.add(&core.Repo{Name: "db", OwnerID: 1, OwnerName: "alice", Path: "/d", Visibility: core.VisibilityPublic})
	h.browse.sess = beadsEpicFixture()
	setViews(t, h, &beadsView{})

	rec := h.do("GET", "/~alice/db/view/beads?issue=i-epic", nil, nil)
	if rec.Code != http.StatusOK {
		t.Fatalf("epic view: got %d, want 200; body=%s", rec.Code, rec.Body.String())
	}
	body := rec.Body.String()
	for _, want := range []string{"Subtasks", "1 of 3 done", "epic-progress", "Child three", "History", "changed status to in_progress"} {
		if !strings.Contains(body, want) {
			t.Errorf("epic render missing %q", want)
		}
	}
}