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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
|
# lectio Go Rewrite Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Reimplement the Python `daily-reading` tool as a self-contained Go project with two binaries — `lectio` (subcommand CLI) and `lectio-ui` (colored Bubble Tea TUI) — that fetches the daily Catholic readings and shows them across five versions with correct psalm versification, works offline from a harvested sigla file, and needs no external tools.
**Architecture:** Thin front-ends (`cmd/lectio`, `cmd/lectio-ui`) over shared `internal/` packages: `bible` (embedded corpora + lookup + citation conversion), `psalter` (versification), `liturgy` (fetch/parse/cache/harvest/offline), `config`, `render` (text output), `cli`, `tui`. Modelled on `~/git/projects/bread-calc`.
**Tech Stack:** Go 1.24, `github.com/charmbracelet/bubbletea` + `lipgloss` (TUI), `github.com/pelletier/go-toml/v2` (config). Stdlib `flag`, `net/http`, `embed`, `encoding/json` elsewhere.
**Spec:** `docs/superpowers/specs/2026-07-23-lectio-go-rewrite-design.md` (read it before starting).
## Global Constraints
- Module path: `github.com/lukaszkasprzak/lectio`. Go directive: `go 1.24.0`.
- No external runtime tools (no `vul`/`grb`/`wuj`/`drb`); all four corpora are embedded.
- No CLI framework dependency (cobra etc.) — dispatch hand-rolled with stdlib `flag`.
- Five version codes: `pl, wuj, vul, grb, drb`. Labels: `pl="Polski (niedziela.pl)"`, `wuj="Wujek (pol.)"`, `vul="Wulgata (lac.)"`, `grb="Grecki"`, `drb="Douay-Rheims (ang.)"`.
- Psalm systems: `vul/grb/wuj` → `"vulgate"`, `drb` → `"drb"`. `pl` is not a bible-lookup version.
- Cache dir: `${XDG_CACHE_HOME:-~/.cache}/lectio/`. Data dir (sigla): `${XDG_DATA_HOME:-~/.local/share}/lectio/sigla.tsv`. Config: `${XDG_CONFIG_HOME:-~/.config}/lectio/config.toml`.
- Source URL: `https://niezbednik.niedziela.pl/liturgia/{date}/Ewangelia`. Dates are `YYYY-MM-DD`.
- User-Agent: `Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36`.
- Offline: `pl` is dropped and `wuj` takes the Polish role.
- Exit codes: 0 ok, 1 runtime error, 2 usage error.
- `gofmt`-formatted; `go vet ./...` clean. Commit after every task.
---
## File Structure
```
go.mod go.sum Makefile .gitignore README.md LICENSE
cmd/lectio/main.go -> cli.Run(os.Args[1:], stdin, stdout, stderr)
cmd/lectio-ui/main.go -> load config, tui.New(...), tea program
internal/psalter/psalter.go DRB_TITLE_FOLD, DrbVerse, HebrewToVulgateChapter
internal/bible/corpora/*.tsv embedded wuj.tsv vul.tsv grb.tsv drb.tsv
internal/bible/bible.go Corpus, Load, Lookup, Verse
internal/bible/books.go canonical books, alias table, ResolveBook
internal/bible/ref.go ParseRef, SplitRef (reference grammar)
internal/bible/convert.go ToEnglishRef, psalmRef (Polish citation -> English)
internal/liturgy/section.go Section type, version constants/labels
internal/liturgy/parse.go Parse(html) []Section
internal/liturgy/fetch.go Fetch, cache (HTML+JSON), Load
internal/liturgy/store.go Harvest (update), sigla TSV, offline Load
internal/liturgy/testdata/*.html fixtures
internal/config/config.go Config, Load, seed
internal/render/render.go GatherVersion, Compare, RenderSection, dedup
internal/cli/cli.go Run + subcommand dispatch
internal/tui/styles.go color role styles
internal/tui/tui.go Model, Init, Update, View
```
---
## Task 1: Project scaffold + vendored corpora
**Files:**
- Create: `go.mod`, `Makefile`, `.gitignore`, `LICENSE`, `cmd/lectio/main.go`, `cmd/lectio-ui/main.go`
- Create: `internal/bible/corpora/wuj.tsv`, `vul.tsv`, `grb.tsv`, `drb.tsv`
**Interfaces:**
- Produces: buildable module; `internal/cli.Run` and `internal/tui` referenced by mains (stubbed this task).
- [ ] **Step 1: Init module and vendor corpora**
```bash
cd ~/git/projects/lectio
cat > go.mod <<'EOF'
module github.com/lukaszkasprzak/lectio
go 1.24.0
require (
github.com/charmbracelet/bubbletea v1.3.10
github.com/charmbracelet/lipgloss v1.1.0
github.com/pelletier/go-toml/v2 v2.4.2
)
EOF
mkdir -p internal/bible/corpora cmd/lectio cmd/lectio-ui
cp ~/git/projects/offline_readings/corpus/wuj.tsv internal/bible/corpora/wuj.tsv
cp ~/git/projects/offline_readings/drb/drb.tsv internal/bible/corpora/drb.tsv
sed '1,/^#EOF$/d' "$(command -v vul)" | tar xzf - -O vul.tsv > internal/bible/corpora/vul.tsv
sed '1,/^#EOF$/d' "$(command -v grb)" | tar xzf - -O grb.tsv > internal/bible/corpora/grb.tsv
# grb.tsv has a UTF-8 BOM on line 1; strip it
sed -i '1s/^\xEF\xBB\xBF//' internal/bible/corpora/grb.tsv
wc -l internal/bible/corpora/*.tsv
```
Expected: four files, ~31k–35k lines each.
- [ ] **Step 2: Stub the two mains so the tree builds**
`cmd/lectio/main.go`:
```go
package main
import (
"os"
"github.com/lukaszkasprzak/lectio/internal/cli"
)
func main() {
os.Exit(cli.Run(os.Args[1:], os.Stdin, os.Stdout, os.Stderr))
}
```
`internal/cli/cli.go` (temporary stub, replaced in Task 12):
```go
package cli
import (
"fmt"
"io"
)
// Run is the CLI entry point; returns a process exit code.
func Run(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
fmt.Fprintln(stdout, "lectio: not yet implemented")
return 0
}
```
`cmd/lectio-ui/main.go` (temporary stub, replaced in Task 15):
```go
package main
import "fmt"
func main() { fmt.Println("lectio-ui: not yet implemented") }
```
- [ ] **Step 3: Makefile, .gitignore, LICENSE**
`Makefile` (adapt bread-calc's):
```make
LECTIO := lectio
LECTIO_UI := lectio-ui
PREFIX ?= $(HOME)/.local
BINDIR := $(PREFIX)/bin
.PHONY: help build install uninstall test vet fmt clean cross
help: ## show this help
@grep -hE '^[a-z-]+:.*##' $(MAKEFILE_LIST) | sed -E 's/:.*## /\t/' | sort
build: ## build ./lectio and ./lectio-ui
go build -o $(LECTIO) ./cmd/lectio
go build -o $(LECTIO_UI) ./cmd/lectio-ui
install: ## build and install both to $(BINDIR)
@mkdir -p $(BINDIR)
go build -o $(BINDIR)/$(LECTIO) ./cmd/lectio
go build -o $(BINDIR)/$(LECTIO_UI) ./cmd/lectio-ui
@echo "installed $(BINDIR)/$(LECTIO) and $(BINDIR)/$(LECTIO_UI)"
uninstall: ## remove installed binaries
rm -f $(BINDIR)/$(LECTIO) $(BINDIR)/$(LECTIO_UI)
test: ## run tests
go test ./...
vet: ## go vet
go vet ./...
fmt: ## gofmt the tree
gofmt -w .
clean: ## remove build artifacts
rm -f $(LECTIO) $(LECTIO_UI); rm -rf dist
cross: ## cross-compile into dist/
@mkdir -p dist
@for t in linux/amd64 linux/arm64 darwin/arm64 darwin/amd64 windows/amd64; do \
os=$${t%/*}; arch=$${t#*/}; ext=; [ $$os = windows ] && ext=.exe; \
echo " $$os/$$arch"; \
GOOS=$$os GOARCH=$$arch go build -o dist/$(LECTIO)-$$os-$$arch$$ext ./cmd/lectio; \
GOOS=$$os GOARCH=$$arch go build -o dist/$(LECTIO_UI)-$$os-$$arch$$ext ./cmd/lectio-ui; \
done
```
`.gitignore`:
```
/lectio
/lectio-ui
dist/
*.test
*.out
coverage.*
```
`LICENSE`: copy `~/git/projects/bread-calc/LICENSE` verbatim.
- [ ] **Step 4: Fetch deps and build**
Run:
```bash
go mod tidy
go build ./cmd/lectio ./cmd/lectio-ui && ./lectio
```
Expected: `go.sum` written; build succeeds; prints `lectio: not yet implemented`.
- [ ] **Step 5: Commit**
```bash
git add -A && git commit -m "scaffold: module, mains, Makefile, embedded corpora"
```
---
## Task 2: internal/psalter (versification port)
**Files:**
- Create: `internal/psalter/psalter.go`, `internal/psalter/psalter_test.go`
- Source: port `~/git/projects/daily-reading/psalm_versify.py` verbatim.
**Interfaces:**
- Produces: `psalter.DrbVerse(hebrewPsalm, lectionaryVerse int) int`; `psalter.HebrewToVulgateChapter(h int) int`; `psalter.DRBTitleFold map[int]int`.
- [ ] **Step 1: Write the failing test**
`internal/psalter/psalter_test.go`:
```go
package psalter
import "testing"
func TestDrbVerse(t *testing.T) {
cases := []struct{ psalm, v, want int }{
{34, 2, 1}, // Ps 34: k=1, title folded
{34, 3, 2},
{51, 3, 1}, // Ps 51: k=2 (two-line title)
{63, 2, 1}, // Ps 63: k=1
{1, 5, 5}, // untitled: identity
{34, 1, 1}, // clamp: never below 1
}
for _, c := range cases {
if got := DrbVerse(c.psalm, c.v); got != c.want {
t.Errorf("DrbVerse(%d,%d)=%d want %d", c.psalm, c.v, got, c.want)
}
}
}
func TestHebrewToVulgateChapter(t *testing.T) {
cases := []struct{ h, want int }{{8, 8}, {34, 33}, {9, 9}, {10, 9}, {116, 114}, {147, 146}, {150, 150}}
for _, c := range cases {
if got := HebrewToVulgateChapter(c.h); got != c.want {
t.Errorf("HebrewToVulgateChapter(%d)=%d want %d", c.h, got, c.want)
}
}
}
```
- [ ] **Step 2: Run test, verify it fails**
Run: `go test ./internal/psalter/` — Expected: FAIL (undefined: DrbVerse).
- [ ] **Step 3: Implement psalter.go**
Port the data and functions from `psalm_versify.py`. `DRBTitleFold` is the exact `DRB_TITLE_FOLD` dict (63 entries) rendered as a Go map literal; `DrbVerse` and `HebrewToVulgateChapter` mirror the Python functions.
`internal/psalter/psalter.go`:
```go
// Package psalter bridges psalm versification between the Vulgate-family
// versions and the Douay-Rheims source. See the Go port of psalm_versify.py.
package psalter
// DRBTitleFold maps a Hebrew psalm number to the number of title verses the DRB
// source folds into verse 1 (1, or 2 for a historical superscription). Untitled
// psalms are absent (k = 0). Copy every entry from psalm_versify.py DRB_TITLE_FOLD.
var DRBTitleFold = map[int]int{
3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 11: 1, 12: 1, 14: 1, 18: 1, 19: 1,
20: 1, 21: 1, 22: 1, 30: 1, 31: 1, 34: 1, 36: 1, 38: 1, 39: 1, 40: 1,
41: 1, 42: 1, 44: 1, 45: 1, 46: 1, 47: 1, 48: 1, 49: 1, 51: 2, 52: 2,
53: 1, 54: 2, 55: 1, 56: 1, 57: 1, 58: 1, 59: 1, 60: 2, 61: 1, 62: 1,
63: 1, 64: 1, 65: 1, 67: 1, 68: 1, 69: 1, 70: 1, 75: 1, 76: 1, 77: 1,
80: 1, 81: 1, 83: 1, 84: 1, 85: 1, 88: 1, 89: 1, 92: 1, 102: 1, 108: 1,
140: 1, 142: 1,
}
// DrbVerse returns the DRB-source verse number for a lectionary (BT) psalm verse.
func DrbVerse(hebrewPsalm, lectionaryVerse int) int {
v := lectionaryVerse - DRBTitleFold[hebrewPsalm]
if v < 1 {
return 1
}
return v
}
// HebrewToVulgateChapter maps a Masoretic psalm number to its Vulgate chapter.
func HebrewToVulgateChapter(h int) int {
switch {
case h <= 8 || h >= 148:
return h
case h >= 9 && h <= 10:
return 9
case h >= 11 && h <= 113:
return h - 1
case h >= 114 && h <= 115:
return 113
case h == 116:
return 114
case h >= 117 && h <= 146:
return h - 1
case h == 147:
return 146
}
return h
}
```
- [ ] **Step 4: Run tests, verify pass**
Run: `go test ./internal/psalter/` — Expected: PASS.
- [ ] **Step 5: Commit**
```bash
git add internal/psalter && git commit -m "psalter: port psalm versification"
```
---
## Task 3: internal/bible — canonical books + alias resolution
**Files:**
- Create: `internal/bible/books.go`, `internal/bible/books_test.go`
- Source: port book names/abbrevs from the four corpora and the alias table from `~/git/projects/offline_readings/corpus/book_aliases.py` + `~/git/projects/daily-reading/ewangelia.py` `POLISH_TO_EN`.
**Interfaces:**
- Produces: `bible.ResolveBook(query string) (canonical string, ok bool)` — resolves an English name, English prefix, or Polish alias to a canonical English book name (as used in the corpora, e.g. `"John"`, `"1 Corinthians"`, `"The Acts"`, `"Song of Solomon"`, `"Wisdom"`).
- [ ] **Step 1: Write the failing test**
`internal/bible/books_test.go`:
```go
package bible
import "testing"
func TestResolveBook(t *testing.T) {
cases := []struct{ in, want string }{
{"John", "John"},
{"Joh", "John"}, // English prefix
{"J", "John"}, // Polish abbrev — NOT Joshua
{"Łk", "Luke"},
{"1 Kor", "1 Corinthians"},
{"Jana", "John"},
{"Rodzaju", "Genesis"},
{"Mdr", "Wisdom"},
{"Pnp", "Song of Solomon"},
{"Dz", "The Acts"},
}
for _, c := range cases {
if got, ok := ResolveBook(c.in); !ok || got != c.want {
t.Errorf("ResolveBook(%q)=%q,%v want %q", c.in, got, ok, c.want)
}
}
if _, ok := ResolveBook("Nonsense"); ok {
t.Error("ResolveBook(Nonsense) should fail")
}
}
```
- [ ] **Step 2: Run test, verify it fails**
Run: `go test ./internal/bible/ -run TestResolveBook` — Expected: FAIL (undefined: ResolveBook).
- [ ] **Step 3: Implement books.go**
Build an alias→canonical map. Resolution order (deterministic, fixes `J`→John): (1) exact alias match (longest alias wins for multi-word), (2) exact canonical name, (3) canonical-name prefix (len ≥ 2). Port the alias sets verbatim from `book_aliases.py` `BOOKS` (73 books incl. deuterocanonicals; each entry's aliases plus the canonical name). Generate case variants (original, lower, upper) at init as `book_aliases.py` does.
`internal/bible/books.go` (structure — fill `aliasSeed` from `book_aliases.py`):
```go
package bible
import "strings"
// canonical English book names, in corpus form.
// aliasSeed maps a canonical name to its accepted aliases (Polish abbrev, Polish
// full name, English abbrev). COPY every entry from offline_readings book_aliases.py.
var aliasSeed = map[string][]string{
"Genesis": {"Rdz", "Rodzaju", "Gen"},
"Exodus": {"Wj", "Wyjścia", "Ex", "Exod"},
// ... all 73 books, verbatim from book_aliases.py ...
"John": {"J", "Jan", "Jana"},
"1 Corinthians": {"1 Kor", "1 Koryntian"},
"Song of Solomon": {"Pnp", "Pieśń nad Pieśniami"},
"The Acts": {"Dz", "Dzieje", "Dzieje Apostolskie", "Acts"},
"Wisdom": {"Mdr", "Mądrości", "Księga Mądrości"},
"Revelation": {"Ap", "Apokalipsa", "Objawienie"},
}
var aliasMap map[string]string // lowercased alias -> canonical
var canonical []string // canonical names for prefix matching
func init() {
aliasMap = map[string]string{}
seen := map[string]bool{}
for name, aliases := range aliasSeed {
canonical = append(canonical, name)
for _, a := range append([]string{name}, aliases...) {
k := strings.ToLower(a)
if !seen[k] {
seen[k] = true
aliasMap[k] = name
}
}
}
}
// ResolveBook maps an English name/prefix or a Polish alias to a canonical book.
func ResolveBook(query string) (string, bool) {
q := strings.ToLower(strings.TrimSpace(query))
if c, ok := aliasMap[q]; ok { // exact alias/name
return c, true
}
for _, name := range canonical { // canonical prefix, len>=2
if len(q) >= 2 && strings.HasPrefix(strings.ToLower(name), q) {
return name, true
}
}
return "", false
}
```
Note: the alias map's exact match runs before prefix, so `"j"` resolves via alias to `John` and never prefix-matches `Joshua`.
- [ ] **Step 4: Run tests, verify pass**
Run: `go test ./internal/bible/ -run TestResolveBook` — Expected: PASS. If `J`→Joshua, the alias for John is missing; verify `aliasSeed["John"]` contains `"J"`.
- [ ] **Step 5: Commit**
```bash
git add internal/bible/books.go internal/bible/books_test.go
git commit -m "bible: canonical books + alias resolution"
```
---
## Task 4: internal/bible — embedded corpora + Lookup
**Files:**
- Create: `internal/bible/bible.go`, `internal/bible/bible_test.go`
**Interfaces:**
- Consumes: `ResolveBook` (Task 3).
- Produces: `bible.Verse{Chapter, Verse int; Text string}`; `bible.Lookup(version, book string, groups []VerseGroup) ([]Verse, []string)` where `VerseGroup` is defined in Task 5. **This task provides the corpus store + a simpler `lookupBook(version, book string) (map[[2]int]string, []int, bool)` helper**; the group-aware `Lookup` is completed in Task 5. Split accordingly: here, deliver corpus loading + a `Verses(version, book, chap int) []Verse` accessor.
- [ ] **Step 1: Write the failing test**
`internal/bible/bible_test.go`:
```go
package bible
import "testing"
func TestVerses(t *testing.T) {
cases := []struct {
version, book string
chap, verse int
wantPrefix string
}{
{"wuj", "Genesis", 1, 1, "Na początku stworzył Bóg"},
{"vul", "Genesis", 1, 1, "In principio creavit Deus"},
{"drb", "John", 20, 1, "AND on the first day of the week"},
{"wuj", "Wisdom", 3, 1, "A dusze sprawiedliwych"}, // deuterocanonical
}
for _, c := range cases {
vs := Verses(c.version, c.book, c.chap)
var got string
for _, v := range vs {
if v.Verse == c.verse {
got = v.Text
}
}
if !hasPrefix(got, c.wantPrefix) {
t.Errorf("%s %s %d:%d = %q want prefix %q", c.version, c.book, c.chap, c.verse, got, c.wantPrefix)
}
}
}
func hasPrefix(s, p string) bool { return len(s) >= len(p) && s[:len(p)] == p }
```
- [ ] **Step 2: Run test, verify it fails**
Run: `go test ./internal/bible/ -run TestVerses` — Expected: FAIL (undefined: Verses).
- [ ] **Step 3: Implement bible.go**
Embed the four TSVs; parse each once (lazy, `sync.Once`) into `map[book]map[chap][]Verse`.
```go
package bible
import (
"embed"
"strconv"
"strings"
"sync"
)
//go:embed corpora/wuj.tsv corpora/vul.tsv corpora/grb.tsv corpora/drb.tsv
var corporaFS embed.FS
// Verse is a single verse.
type Verse struct {
Chapter, Verse int
Text string
}
type corpus struct {
books map[string]map[int][]Verse // book -> chapter -> verses (verse-ordered)
}
var (
corpora = map[string]*corpus{}
corporaMu sync.Mutex
)
func load(version string) *corpus {
corporaMu.Lock()
defer corporaMu.Unlock()
if c, ok := corpora[version]; ok {
return c
}
data, err := corporaFS.ReadFile("corpora/" + version + ".tsv")
if err != nil {
corpora[version] = &corpus{books: map[string]map[int][]Verse{}}
return corpora[version]
}
c := &corpus{books: map[string]map[int][]Verse{}}
for _, line := range strings.Split(string(data), "\n") {
f := strings.Split(line, "\t")
if len(f) != 6 {
continue
}
chap, _ := strconv.Atoi(f[3])
vn, _ := strconv.Atoi(f[4])
book := f[0]
if c.books[book] == nil {
c.books[book] = map[int][]Verse{}
}
c.books[book][chap] = append(c.books[book][chap], Verse{chap, vn, f[5]})
}
corpora[version] = c
return c
}
// Verses returns all verses of one chapter of a book in a version (may be empty).
func Verses(version, book string, chap int) []Verse {
return load(version).books[book][chap]
}
```
- [ ] **Step 4: Run tests, verify pass**
Run: `go test ./internal/bible/ -run TestVerses` — Expected: PASS.
- [ ] **Step 5: Commit**
```bash
git add internal/bible/bible.go internal/bible/bible_test.go
git commit -m "bible: embed corpora + chapter lookup"
```
---
## Task 5: internal/bible — reference grammar (ParseRef, SplitRef, Lookup)
**Files:**
- Create: `internal/bible/ref.go`, `internal/bible/ref_test.go`
**Interfaces:**
- Consumes: `ResolveBook`, `Verses`.
- Produces:
- `type VerseGroup struct{ Chapter, From, To int }` (To==From for a single verse; a whole-verse-list "20:1,2,3" is multiple groups).
- `SplitRef(ref string) []string` — split a kjv-style ref with a mixed comma/range list into single-group refs (port of Python `split_ref`).
- `Lookup(version, ref string) (verses []Verse, missing []string)` — resolve a full English-style ref (`"John 20:1,11-18"`), returning matched verses in order and the sub-refs the corpus lacked.
- [ ] **Step 1: Write the failing test**
`internal/bible/ref_test.go`:
```go
package bible
import "testing"
func TestSplitRef(t *testing.T) {
got := SplitRef("John 20:1,11-18")
want := []string{"John 20:1", "John 20:11-18"}
if len(got) != 2 || got[0] != want[0] || got[1] != want[1] {
t.Fatalf("SplitRef mixed = %v want %v", got, want)
}
if g := SplitRef("Mat 7:1-5"); len(g) != 1 || g[0] != "Mat 7:1-5" {
t.Errorf("SplitRef contiguous = %v", g)
}
}
func TestLookup(t *testing.T) {
vs, missing := Lookup("wuj", "John 20:1,11-18")
if len(missing) != 0 {
t.Fatalf("missing = %v", missing)
}
if len(vs) == 0 || vs[0].Verse != 1 {
t.Fatalf("first verse = %+v", vs)
}
last := vs[len(vs)-1]
if last.Verse != 18 {
t.Errorf("last verse = %d want 18", last.Verse)
}
if _, m := Lookup("vul", "Wisdom 3:1"); len(m) == 0 {
t.Error("vul lacks Wisdom; expected a missing entry")
}
}
```
- [ ] **Step 2: Run test, verify it fails**
Run: `go test ./internal/bible/ -run 'TestSplitRef|TestLookup'` — Expected: FAIL.
- [ ] **Step 3: Implement ref.go**
Port `split_ref` and the reference-parsing logic. A ref is `<book> <chap>:<verses>` where `<verses>` is a comma list of items, each a single verse or a `from-to` range. `SplitRef` groups a mixed list (single verses + ranges) into separate refs, mirroring Python. `Lookup` resolves the book, then for each `SplitRef` part parses the chapter/range, pulls from `Verses`, and records misses.
```go
package bible
import (
"regexp"
"strconv"
"strings"
)
var refRe = regexp.MustCompile(`^(.*?)\s+(\d+):(.+)$`)
// SplitRef splits a ref whose verse list mixes single verses and ranges into
// one ref per group (the kjv tools reject a mixed list in a single query).
func SplitRef(ref string) []string {
m := refRe.FindStringSubmatch(ref)
if m == nil {
return []string{ref}
}
book, chap, verses := m[1], m[2], m[3]
if !strings.Contains(verses, ",") {
return []string{ref}
}
var out []string
for _, g := range strings.Split(verses, ",") {
g = strings.TrimSpace(g)
if g == "" {
continue
}
if strings.Contains(g, ":") {
out = append(out, book+" "+g)
} else {
out = append(out, book+" "+chap+":"+g)
}
}
return out
}
// Lookup resolves an English-style reference against a version, returning the
// matched verses (in order) and the sub-refs the corpus had no entry for.
func Lookup(version, ref string) ([]Verse, []string) {
var verses []Verse
var missing []string
for _, part := range SplitRef(ref) {
m := refRe.FindStringSubmatch(part)
if m == nil {
missing = append(missing, part)
continue
}
book, ok := ResolveBook(m[1])
if !ok {
missing = append(missing, part)
continue
}
chap, _ := strconv.Atoi(m[2])
from, to := verseRange(m[3])
found := false
for _, v := range Verses(version, book, chap) {
if v.Verse >= from && v.Verse <= to {
verses = append(verses, v)
found = true
}
}
if !found {
missing = append(missing, part)
}
}
return verses, missing
}
func verseRange(s string) (int, int) {
s = strings.TrimSpace(s)
if i := strings.IndexAny(s, "-–—"); i >= 0 {
from, _ := strconv.Atoi(strings.TrimSpace(s[:i]))
to, _ := strconv.Atoi(strings.TrimSpace(s[i+1:]))
return from, to
}
n, _ := strconv.Atoi(s)
return n, n
}
```
- [ ] **Step 4: Run tests, verify pass**
Run: `go test ./internal/bible/ -run 'TestSplitRef|TestLookup'` — Expected: PASS.
- [ ] **Step 5: Commit**
```bash
git add internal/bible/ref.go internal/bible/ref_test.go
git commit -m "bible: reference grammar + Lookup"
```
---
## Task 6: internal/bible — Polish citation → English ref conversion
**Files:**
- Create: `internal/bible/convert.go`, `internal/bible/convert_test.go`
- Source: port `to_english_ref` / `_psalm_ref` and `POLISH_TO_EN` from `~/git/projects/daily-reading/ewangelia.py`.
**Interfaces:**
- Consumes: `psalter.DrbVerse`.
- Produces: `bible.ToEnglishRef(plCitation, system string) (string, error)` where `system` ∈ `"vulgate"`, `"drb"`. Converts a Polish citation (`"Mt 7, 1-5"`, `"por. J 20, 11"`, `"Ps 63 (62), 2. 3-4 (R.: por. 2ab)"`) to a kjv-style ref.
- [ ] **Step 1: Write the failing test**
`internal/bible/convert_test.go`:
```go
package bible
import "testing"
func TestToEnglishRef(t *testing.T) {
cases := []struct{ in, system, want string }{
{"Mt 7, 1-5", "vulgate", "Mat 7:1-5"},
{"J 20, 1. 11-18", "vulgate", "John 20:1,11-18"},
{"por. J 20, 11", "vulgate", "John 20:11"},
{"Ps 63 (62), 2. 3-4. 5-6. 8-9 (R.: por. 2ab)", "vulgate", "Psalms 62:2,3-4,5-6,8-9"},
{"Ps 63 (62), 2. 3-4. 5-6. 8-9 (R.: por. 2ab)", "drb", "Psalms 63:1,2-3,4-5,7-8"},
}
for _, c := range cases {
got, err := ToEnglishRef(c.in, c.system)
if err != nil || got != c.want {
t.Errorf("ToEnglishRef(%q,%q)=%q,%v want %q", c.in, c.system, got, err, c.want)
}
}
}
```
- [ ] **Step 2: Run test, verify it fails**
Run: `go test ./internal/bible/ -run TestToEnglishRef` — Expected: FAIL.
- [ ] **Step 3: Implement convert.go**
Port `POLISH_TO_EN` (the full dict from `ewangelia.py`, ~66 entries — note it maps to short gospel forms `Mt→Mat` etc.), `to_english_ref`, and `_psalm_ref`. Steps mirror the Python exactly: strip leading `por.`, strip trailing `(R.: ...)`, collapse whitespace, match the longest Polish book key, for Psalms route through `psalmRef` (dual-numbering pick + drb verse fold via `psalter.DrbVerse`), then the punctuation transforms (`, `→`:`, `. `→`,`, ` i `→`,`, ranges, drop verse-part letters, remove spaces).
Provide the full function bodies (translated line-for-line from the Python). Key psalm helper:
```go
// psalmRef maps the psalm citation body ("63 (62), 2. 3-4. ...") to the target Psalter.
func psalmRef(rest, system string) string {
m := regexp.MustCompile(`(\d+)(?:\s*\((\d+)\))?(.*)$`).FindStringSubmatch(rest)
if m == nil {
return rest
}
heb, _ := strconv.Atoi(m[1])
tail := m[3]
if system == "vulgate" {
ch := m[1]
if m[2] != "" {
ch = m[2]
}
return ch + tail
}
if system == "drb" {
tail = regexp.MustCompile(`\d+`).ReplaceAllStringFunc(tail, func(s string) string {
n, _ := strconv.Atoi(s)
return strconv.Itoa(psalter.DrbVerse(heb, n))
})
}
return strconv.Itoa(heb) + tail
}
```
`ToEnglishRef` returns an `error` when no Polish book matches (mirrors the Python `ValueError`).
- [ ] **Step 4: Run tests, verify pass**
Run: `go test ./internal/bible/` — Expected: PASS (all bible tests).
- [ ] **Step 5: Commit**
```bash
git add internal/bible/convert.go internal/bible/convert_test.go
git commit -m "bible: Polish citation -> English ref (with psalm versification)"
```
---
## Task 7: internal/liturgy — Section type + Parse
**Files:**
- Create: `internal/liturgy/section.go`, `internal/liturgy/parse.go`, `internal/liturgy/parse_test.go`
- Create fixtures: `internal/liturgy/testdata/2026-07-22.html` (split feast), `2026-06-22.html` (normal day). Copy from `~/.cache/daily-reading/`.
**Interfaces:**
- Produces: `liturgy.Section{Heading, Subtitle, Citation string; Paragraphs [][]string}`; `liturgy.Parse(html string) ([]Section, error)`; `liturgy.ExtractCitation(heading string) (string, error)`.
- [ ] **Step 1: Copy fixtures + write the failing test**
```bash
mkdir -p internal/liturgy/testdata
cp ~/.cache/daily-reading/2026-07-22.html internal/liturgy/testdata/
cp ~/.cache/daily-reading/2026-06-22.html internal/liturgy/testdata/
```
`internal/liturgy/parse_test.go`:
```go
package liturgy
import (
"os"
"strings"
"testing"
)
func TestParse(t *testing.T) {
html, _ := os.ReadFile("testdata/2026-07-22.html")
secs, err := Parse(string(html))
if err != nil {
t.Fatal(err)
}
var gospel *Section
for i := range secs {
if strings.HasPrefix(secs[i].Heading, "Ewangelia") {
gospel = &secs[i]
}
}
if gospel == nil {
t.Fatal("no gospel section")
}
if gospel.Citation != "J 20, 1. 11-18" {
t.Errorf("gospel citation = %q", gospel.Citation)
}
if len(gospel.Paragraphs) == 0 {
t.Error("gospel has no paragraphs")
}
}
func TestParseLayoutChange(t *testing.T) {
if _, err := Parse("<html><body>redesigned</body></html>"); err == nil {
t.Error("expected error on missing reading tab")
}
}
```
- [ ] **Step 2: Run test, verify it fails**
Run: `go test ./internal/liturgy/ -run TestParse` — Expected: FAIL (undefined: Parse).
- [ ] **Step 3: Implement section.go + parse.go**
Port `parse_sections`, `html_to_lines`, `extract_reference` from `ewangelia.py`. Prefer the `tabnowy0all` tab; fall back to `tabstary0all`; error if neither, or if found-but-empty. Use `regexp` and `html.UnescapeString`. `ExtractCitation` pulls the parenthetical from a heading.
Provide full Go translations. Key regexes: pane `<div class="tab-pane[^"]*"\s+id="%s">`, headings `<h2>(.*?)</h2>` (with `(?s)`), subtitle `<h4>(.*?)</h4>`, paragraphs `<p>(.*?)</p>`, `<br\s*/?>` → newline, strip `<[^>]+>`.
- [ ] **Step 4: Run tests, verify pass**
Run: `go test ./internal/liturgy/ -run TestParse` — Expected: PASS.
- [ ] **Step 5: Commit**
```bash
git add internal/liturgy/section.go internal/liturgy/parse.go internal/liturgy/parse_test.go internal/liturgy/testdata
git commit -m "liturgy: Section type + HTML parse (fixtures)"
```
---
## Task 8: internal/liturgy — Fetch + cache + Load
**Files:**
- Create: `internal/liturgy/fetch.go`, `internal/liturgy/fetch_test.go`
**Interfaces:**
- Consumes: `Parse`.
- Produces:
- `type Options struct{ Date string; Refresh, Offline bool }`
- `liturgy.Load(opts Options) ([]Section, error)` — JSON cache → HTML cache(+parse, write JSON) → fetch(+cache both). (Offline path added in Task 9.)
- `liturgy.cacheDir() string`, using `XDG_CACHE_HOME`.
- [ ] **Step 1: Write the failing test (cache round-trip via a local server)**
`internal/liturgy/fetch_test.go`:
```go
package liturgy
import (
"net/http"
"net/http/httptest"
"os"
"testing"
)
func TestLoadCaches(t *testing.T) {
html, _ := os.ReadFile("testdata/2026-06-22.html")
hits := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits++
w.Write(html)
}))
defer srv.Close()
t.Setenv("XDG_CACHE_HOME", t.TempDir())
baseURL = srv.URL + "/liturgia/%s/Ewangelia" // test hook
secs1, err := Load(Options{Date: "2026-06-22"})
if err != nil || len(secs1) == 0 {
t.Fatalf("load1: %v", err)
}
secs2, _ := Load(Options{Date: "2026-06-22"}) // should hit JSON cache
if hits != 1 {
t.Errorf("server hit %d times, want 1 (cache miss on repeat)", hits)
}
if len(secs2) != len(secs1) {
t.Error("cache returned different section count")
}
}
```
- [ ] **Step 2: Run test, verify it fails**
Run: `go test ./internal/liturgy/ -run TestLoadCaches` — Expected: FAIL.
- [ ] **Step 3: Implement fetch.go**
`baseURL` is a package var (default the real URL, overridable in tests). `Load`: compute cache paths; if not `Refresh`, try `{date}.json` (unmarshal `[]Section`); else try `{date}.html` (parse, write JSON); else GET `baseURL` with the User-Agent, and — only if the page is fully published (`id="\w*0all"` present) — write `{date}.html` and `{date}.json`. Publish detection and the "Przykro nam"/unpublished handling mirror `ewangelia.py`.
- [ ] **Step 4: Run tests, verify pass**
Run: `go test ./internal/liturgy/ -run TestLoadCaches` — Expected: PASS (`hits == 1`).
- [ ] **Step 5: Commit**
```bash
git add internal/liturgy/fetch.go internal/liturgy/fetch_test.go
git commit -m "liturgy: fetch + HTML/JSON cache"
```
---
## Task 9: internal/liturgy — sigla harvest + offline Load
**Files:**
- Create: `internal/liturgy/store.go`, `internal/liturgy/store_test.go`
- Modify: `internal/liturgy/fetch.go` (Load consults offline path when `opts.Offline`)
**Interfaces:**
- Produces:
- `liturgy.Harvest(fromDate string, maxDays int) (added int, furthest string, err error)` — walks dates, extracts citations, writes/merges the sigla TSV. Stops at the unpublished horizon.
- `liturgy.LoadOffline(date string) ([]Section, error)` — build sections from the sigla TSV (Citation set, Paragraphs empty).
- `liturgy.siglaPath() string` (`XDG_DATA_HOME`).
- Modify `Load`: when `opts.Offline`, return `LoadOffline(opts.Date)`.
- [ ] **Step 1: Write the failing test**
`internal/liturgy/store_test.go`:
```go
package liturgy
import (
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
)
func TestHarvestAndOffline(t *testing.T) {
html, _ := os.ReadFile("testdata/2026-07-22.html")
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "2026-07-22") {
w.Write(html)
} else {
w.Write([]byte("<html>Przykro nam</html>")) // horizon
}
}))
defer srv.Close()
t.Setenv("XDG_CACHE_HOME", t.TempDir())
t.Setenv("XDG_DATA_HOME", t.TempDir())
baseURL = srv.URL + "/liturgia/%s/Ewangelia"
added, _, err := Harvest("2026-07-22", 3)
if err != nil || added < 1 {
t.Fatalf("harvest: added=%d err=%v", added, err)
}
secs, err := LoadOffline("2026-07-22")
if err != nil {
t.Fatal(err)
}
var haveGospel bool
for _, s := range secs {
if s.Citation == "J 20, 1. 11-18" {
haveGospel = true
}
}
if !haveGospel {
t.Error("offline gospel citation missing")
}
}
```
- [ ] **Step 2: Run test, verify it fails**
Run: `go test ./internal/liturgy/ -run TestHarvestAndOffline` — Expected: FAIL.
- [ ] **Step 3: Implement store.go + modify Load**
`Harvest`: from `fromDate`, for up to `maxDays` (0 = until horizon), fetch+parse each date; on "no reading published"/parse error, stop (horizon). For each section, `ExtractCitation` → append rows `date\tlabel\tcitation`. Merge with existing TSV (replace a date's rows on re-harvest). `LoadOffline`: read the TSV, gather rows for the date, build `[]Section{Heading:label, Citation:citation}`. Date iteration uses `time.Parse("2006-01-02", ...)` + `AddDate(0,0,1)`. In `Load`: add `if opts.Offline { return LoadOffline(opts.Date) }` at the top; and wrap the network branch so that on a fetch error it falls back to `LoadOffline(opts.Date)` when the date is harvested, returning the original fetch error only if the offline load also fails (auto-fallback per the spec).
- [ ] **Step 4: Run tests, verify pass**
Run: `go test ./internal/liturgy/` — Expected: PASS (all liturgy tests).
- [ ] **Step 5: Commit**
```bash
git add internal/liturgy/store.go internal/liturgy/store_test.go internal/liturgy/fetch.go
git commit -m "liturgy: sigla harvest + offline load"
```
---
## Task 10: internal/config
**Files:**
- Create: `internal/config/config.go`, `internal/config/config.toml` (embedded seed), `internal/config/config_test.go`
**Interfaces:**
- Produces: `config.Config{Versions []string; DefaultVersion string; Width int; All, Offline bool}`; `config.Load() (Config, error)` (env → `~/.config/lectio/config.toml` seed → defaults); `config.Default() Config`.
- [ ] **Step 1: Write the failing test**
`internal/config/config_test.go`:
```go
package config
import (
"os"
"path/filepath"
"testing"
)
func TestLoadSeeds(t *testing.T) {
dir := t.TempDir()
t.Setenv("XDG_CONFIG_HOME", dir)
cfg, err := Load()
if err != nil {
t.Fatal(err)
}
if cfg.DefaultVersion != "pl" || cfg.Offline {
t.Errorf("defaults wrong: %+v", cfg)
}
if _, err := os.Stat(filepath.Join(dir, "lectio", "config.toml")); err != nil {
t.Error("config not seeded")
}
}
func TestLoadOverride(t *testing.T) {
dir := t.TempDir()
t.Setenv("XDG_CONFIG_HOME", dir)
os.MkdirAll(filepath.Join(dir, "lectio"), 0o755)
os.WriteFile(filepath.Join(dir, "lectio", "config.toml"),
[]byte("offline = true\ndefault_version = \"wuj\"\n"), 0o644)
cfg, _ := Load()
if !cfg.Offline || cfg.DefaultVersion != "wuj" {
t.Errorf("override not applied: %+v", cfg)
}
}
```
- [ ] **Step 2: Run test, verify it fails**
Run: `go test ./internal/config/` — Expected: FAIL.
- [ ] **Step 3: Implement config.go + seed**
`internal/config/config.toml` = the seed from the spec (with `schema_version`, `versions`, `default_version`, `width`, `all`, `offline = false`), `//go:embed`ed. `Default()` returns the same values. `Load`: `LECTIO_CONFIG` env → `os.UserConfigDir()/lectio/config.toml` (seed the embedded default if absent) → parse with `toml.Unmarshal`. Validate each version in `Versions`/`DefaultVersion` against the five codes; error on unknown. Struct tags match the TOML keys.
- [ ] **Step 4: Run tests, verify pass**
Run: `go test ./internal/config/` — Expected: PASS.
- [ ] **Step 5: Commit**
```bash
git add internal/config && git commit -m "config: TOML load + seed"
```
---
## Task 11: internal/render
**Files:**
- Create: `internal/render/render.go`, `internal/render/render_test.go`
**Interfaces:**
- Consumes: `liturgy.Section`, `bible.ToEnglishRef`, `bible.Lookup`, version labels/systems.
- Produces:
- `render.GatherVersion(version string, sec liturgy.Section) (label string, blocks []string)` — `pl` returns deduped paragraphs (drop "Słowa Ewangelii" incipit + repeated refrains); a bible version returns verse lines `"C:V text"` plus a "brak" note for missing groups.
- `render.Compare(secs []liturgy.Section, versions []string, width int) string` — the side-by-side column layout (port `render_compare`).
- `render.OfflineVersions(versions []string) []string` — drop `pl`, ensure `wuj`.
- [ ] **Step 1: Write the failing test**
`internal/render/render_test.go`:
```go
package render
import (
"strings"
"testing"
"github.com/lukaszkasprzak/lectio/internal/liturgy"
)
func TestGatherPLDedup(t *testing.T) {
sec := liturgy.Section{
Heading: "Psalm (Ps 1)",
Paragraphs: [][]string{{"stanza one"}, {"refrain"}, {"stanza two"}, {"refrain"}},
}
_, blocks := GatherVersion("pl", sec)
n := 0
for _, b := range blocks {
if b == "refrain" {
n++
}
}
if n != 1 {
t.Errorf("refrain appears %d times, want 1 (deduped)", n)
}
}
func TestGatherBible(t *testing.T) {
sec := liturgy.Section{Heading: "Ewangelia (J 20, 1. 11-18)"}
label, blocks := GatherVersion("wuj", sec)
if !strings.Contains(label, "Wujek") {
t.Errorf("label = %q", label)
}
if len(blocks) == 0 || !strings.HasPrefix(blocks[0], "20:1") {
t.Errorf("first block = %q", blocks)
}
}
func TestOfflineVersions(t *testing.T) {
got := OfflineVersions([]string{"pl", "wuj", "vul"})
for _, v := range got {
if v == "pl" {
t.Error("pl not dropped offline")
}
}
}
```
- [ ] **Step 2: Run test, verify it fails**
Run: `go test ./internal/render/` — Expected: FAIL.
- [ ] **Step 3: Implement render.go**
Port `gather_version` (pl branch with incipit-drop + dedup; bible branch via `bible.ToEnglishRef(citation, system(version))` then `bible.Lookup`), the version labels/systems maps, `render_compare` (column widths, gap, label+dash header, row assembly), and `OfflineVersions`. `GatherVersion` derives the citation from `sec.Citation` (fallback `ExtractCitation(sec.Heading)`).
- [ ] **Step 4: Run tests, verify pass**
Run: `go test ./internal/render/` — Expected: PASS.
- [ ] **Step 5: Commit**
```bash
git add internal/render && git commit -m "render: gather versions + compare + dedup"
```
---
## Task 12: internal/cli — subcommand dispatch
**Files:**
- Replace: `internal/cli/cli.go` (the Task 1 stub); Create: `internal/cli/cli_test.go`
**Interfaces:**
- Consumes: `config.Load`, `liturgy.Load/Harvest`, `render.*`.
- Produces: full `Run(args, stdin, stdout, stderr) int` handling `today`, `date D`, `compare LIST`, `show VERSION`, `update`, `--version`, `help`; global `--offline`; per-command `--all --raw --width --refresh --date`.
- [ ] **Step 1: Write the failing test**
`internal/cli/cli_test.go`:
```go
package cli
import (
"bytes"
"strings"
"testing"
)
func TestHelp(t *testing.T) {
var out, errb bytes.Buffer
code := Run([]string{"help"}, nil, &out, &errb)
if code != 0 || !strings.Contains(out.String(), "lectio") {
t.Errorf("help code=%d out=%q", code, out.String())
}
}
func TestUnknownCommand(t *testing.T) {
var out, errb bytes.Buffer
if code := Run([]string{"bogus"}, nil, &out, &errb); code != 2 {
t.Errorf("unknown cmd code=%d want 2", code)
}
}
func TestVersion(t *testing.T) {
var out, errb bytes.Buffer
if code := Run([]string{"--version"}, nil, &out, &errb); code != 0 {
t.Errorf("version code=%d", code)
}
}
```
- [ ] **Step 2: Run test, verify it fails**
Run: `go test ./internal/cli/` — Expected: FAIL.
- [ ] **Step 3: Implement cli.go**
Hand-rolled dispatch (like bread-calc): first non-flag arg is the subcommand (default `today`). Each subcommand builds a `flag.FlagSet`, resolves `config.Load()` (flags override), calls `liturgy.Load`/`Harvest`, renders via `render`, writes to `stdout`. `--offline`/config sets `Options.Offline` and swaps versions via `render.OfflineVersions`. `help`/`-h` prints usage; unknown command → usage error (2); runtime errors → 1. Include a `helpText` const listing every subcommand (mirror the spec's CLI section).
- [ ] **Step 4: Run tests, verify pass**
Run: `go test ./internal/cli/` — Expected: PASS.
- [ ] **Step 5: Build + manual smoke + commit**
```bash
go build ./cmd/lectio && ./lectio today && ./lectio compare pl,wuj,vul,drb
git add internal/cli && git commit -m "cli: subcommand dispatch"
```
Expected: today's gospel prints; compare shows four columns (network required).
---
## Task 13: internal/tui — styles + model
**Files:**
- Create: `internal/tui/styles.go`, `internal/tui/tui.go`, `internal/tui/tui_test.go`
- Replace: `cmd/lectio-ui/main.go`
**Interfaces:**
- Consumes: `config.Config`, `liturgy.Load`, `render.GatherVersion`, `render.OfflineVersions`.
- Produces: `tui.New(cfg config.Config) tui.Model` implementing `tea.Model`.
- [ ] **Step 1: Write the failing test (pure model logic)**
`internal/tui/tui_test.go`:
```go
package tui
import (
"testing"
"github.com/lukaszkasprzak/lectio/internal/config"
)
func TestVersionCycle(t *testing.T) {
m := New(config.Config{Versions: []string{"pl", "wuj", "vul"}, DefaultVersion: "pl"})
if m.version() != "pl" {
t.Fatalf("start = %q", m.version())
}
m = m.cycleVersion(+1)
if m.version() != "wuj" {
t.Errorf("after tab = %q", m.version())
}
m = m.cycleVersion(-1)
if m.version() != "pl" {
t.Errorf("after shift-tab = %q", m.version())
}
}
func TestOfflineDropsPL(t *testing.T) {
m := New(config.Config{Versions: []string{"pl", "wuj", "vul"}, DefaultVersion: "pl", Offline: true})
for _, v := range m.versions {
if v == "pl" {
t.Error("offline model kept pl")
}
}
}
```
- [ ] **Step 2: Run test, verify it fails**
Run: `go test ./internal/tui/` — Expected: FAIL.
- [ ] **Step 3: Implement styles.go + tui.go**
`styles.go`: named `lipgloss.Style` per color role (heading bold accent, citation dim, verse number muted, verse text default, refrain italic, header, footer) using `lipgloss.AdaptiveColor`; honor `NO_COLOR`. `tui.go`: `Model{cfg, versions, verIdx, date, sections, scroll, width, loading, err}`; `New` applies `OfflineVersions` when `cfg.Offline` and sets `verIdx` to `default_version`; `version()`, `cycleVersion(d int)`, helpers are pure and unit-tested. `Init` issues the first load `tea.Cmd`; `Update` handles `tea.KeyMsg` (tab/arrows/j/k/g/G/r/q), `readingsMsg`, `errMsg`, `tea.WindowSizeMsg`; `View` renders header + styled reading (via `render.GatherVersion` for the active version, styled per role) + footer keybar. Fetching runs in a `tea.Cmd` returning `readingsMsg`/`errMsg`.
- [ ] **Step 4: Replace cmd/lectio-ui/main.go**
```go
package main
import (
"fmt"
"os"
tea "github.com/charmbracelet/bubbletea"
"github.com/lukaszkasprzak/lectio/internal/config"
"github.com/lukaszkasprzak/lectio/internal/tui"
)
func main() {
cfg, err := config.Load()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if _, err := tea.NewProgram(tui.New(cfg), tea.WithAltScreen()).Run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
```
- [ ] **Step 5: Run tests + build + commit**
```bash
go test ./internal/tui/ && go build ./cmd/lectio-ui
git add internal/tui cmd/lectio-ui && git commit -m "tui: colored reader + version switch"
```
Expected: tests pass; builds. (Interactive run verified manually: `./lectio-ui`.)
---
## Task 14: README, vet, cross-build, finalize
**Files:**
- Create: `README.md`
**Interfaces:** none.
- [ ] **Step 1: Write README**
Cover: what it is, install (`make install`), the subcommands, config file + keys, the TUI keys and colors, the `update`/offline workflow, and that it's self-contained (no external tools). Note the Python `daily-reading` is the predecessor.
- [ ] **Step 2: vet + fmt + full test**
Run: `gofmt -w . && go vet ./... && go test ./...`
Expected: no vet diagnostics; all tests pass.
- [ ] **Step 3: Cross-build sanity**
Run: `make cross && ls dist/`
Expected: ten binaries.
- [ ] **Step 4: Install + smoke both binaries**
Run: `make install && lectio today && echo '---' && lectio update --days 5`
Expected: gospel prints; update reports harvested days. (`lectio-ui` verified interactively.)
- [ ] **Step 5: Commit**
```bash
git add -A && git commit -m "docs: README; finalize build"
```
---
## Addendum A: Traditional lectionary (missalemeum)
Adds `lectionary = new|traditional`. Traditional propers come from the
missalemeum API. Integrates via the shared `[]Section` type. Do these after the
base plan (or interleave: A1–A2 before Task 11).
### Amendment to Task 7 (Section type)
Add a `PartID string` field to `Section`:
```go
type Section struct {
Heading, Subtitle, Citation, PartID string
Paragraphs [][]string
}
```
In modern `Parse`, set `PartID` from the heading: map `1. czytanie`→`pierwsze_czytanie`
(or `drugie_czytanie` for a second `1. czytanie` occurrence), `Psalm`→`psalm`,
`Aklamacja`→`aklamacja`, `Ewangelia`→`ewangelia`.
### Amendment to Task 10 (config)
Add fields and `PartShown`; extend the embedded seed with the commented
`lectionary`, `traditional_lang`, and `[parts.*]` blocks from the spec.
```go
type Config struct {
SchemaVersion int `toml:"schema_version"`
Lectionary string `toml:"lectionary"`
TraditionalLang string `toml:"traditional_lang"`
Versions []string `toml:"versions"`
DefaultVersion string `toml:"default_version"`
Width int `toml:"width"`
All bool `toml:"all"`
Offline bool `toml:"offline"`
Parts map[string]map[string]bool `toml:"parts"`
}
// PartShown reports whether a part renders: true unless explicitly set false.
func (c Config) PartShown(lectionary, partID string) bool {
if m, ok := c.Parts[lectionary]; ok {
if v, ok := m[partID]; ok {
return v
}
}
return true
}
```
Defaults: `Lectionary="new"`, `TraditionalLang="pl"`. Validate `Lectionary` ∈
{new,traditional}, `TraditionalLang` ∈ {pl,en}. Add a `TestPartShown` (empty →
all true; `{new:{psalm:false}}` → psalm false, ewangelia true).
### Amendment to Tasks 8–9 (Load router)
`Load(cfg config.Config, opts Options) ([]Section, error)`: if
`cfg.Lectionary=="traditional"`, delegate to `tradlit.Load(opts.Date,
cfg.TraditionalLang)` (offline: `tradlit.LoadOffline`); else the modern path.
Then filter: `sections = keep(s for s where cfg.PartShown(cfg.Lectionary, s.PartID))`,
unless `opts.GospelOnly`, which keeps only `ewangelia`/`evangelium`. Traditional
cache lives under `traditional/{date}.json`; harvest writes `sigla-traditional.tsv`.
### Task A1: internal/tradlit — fetch + parse missalemeum propers
**Files:** Create `internal/tradlit/tradlit.go`, `internal/tradlit/parse_test.go`,
`internal/tradlit/testdata/2026-07-22.json` (save `curl -s https://www.missalemeum.com/en/api/v5/proper/2026-07-22`).
**Interfaces:**
- Consumes: `liturgy.Section`.
- Produces: `tradlit.Parse(jsonBody []byte) ([]liturgy.Section, error)`;
`tradlit.Load(date, lang string) ([]liturgy.Section, error)`.
- [ ] **Step 1: Save fixture + write the failing test**
```bash
mkdir -p internal/tradlit/testdata
curl -s -A 'Mozilla/5.0' https://www.missalemeum.com/en/api/v5/proper/2026-07-22 \
> internal/tradlit/testdata/2026-07-22.json
```
`internal/tradlit/parse_test.go`:
```go
package tradlit
import (
"os"
"testing"
)
func TestParse(t *testing.T) {
body, _ := os.ReadFile("testdata/2026-07-22.json")
secs, err := Parse(body)
if err != nil {
t.Fatal(err)
}
var gospel, epistle bool
for _, s := range secs {
if s.PartID == "evangelium" {
gospel = true
if s.Citation != "Luke 7:36-50" {
t.Errorf("gospel citation = %q", s.Citation)
}
if len(s.Paragraphs) == 0 {
t.Error("gospel has no vernacular text")
}
}
if s.PartID == "lectio" {
epistle = true
}
}
if !gospel || !epistle {
t.Errorf("missing parts: gospel=%v epistle=%v", gospel, epistle)
}
}
```
- [ ] **Step 2: Run test, verify it fails**
Run: `go test ./internal/tradlit/` — Expected: FAIL.
- [ ] **Step 3: Implement tradlit.go**
Unmarshal `[]struct{ Info struct{Title string} `json:"info"`; Sections []struct{ ID, Label string; Body [][]string } }`. For each section: `PartID = strings.ToLower(ID)`, `Heading = Label`, join `Body[0]` into `Paragraphs`, and extract the citation from the first `*...*` marker in the body text (`regexp.MustCompile(`\*([^*\n]+)\*`)`). Skip empty/administrative sections. `Load` fetches `https://www.missalemeum.com/{lang}/api/v5/proper/{date}` with the User-Agent and calls `Parse`; a 404 means "no propers for this date". The citation is already kjv-style (e.g. `Luke 7:36-50`, `Ps 44:2`), so `bible.Lookup` consumes it directly; psalm citations are Vulgate-numbered (1962 Missal) — feed the version lookup as-is for `vul/grb/wuj`; `drb` psalms may sit a verse off (same known limitation as the modern mode, no extra handling).
- [ ] **Step 4: Run tests, verify pass**
Run: `go test ./internal/tradlit/` — Expected: PASS.
- [ ] **Step 5: Commit**
```bash
git add internal/tradlit && git commit -m "tradlit: missalemeum 1962 propers -> sections"
```
### Amendment to Task 11 (render) and Task 12 (cli)
`render.GatherVersion`: for a traditional section, the vernacular source column is
`sec.Paragraphs` (used for the `pl` role / when a part has no citation); the four
bible versions use `sec.Citation` when present. A prayer part (no citation)
renders vernacular only, with a one-line note that Latin is unavailable. `cli`:
add global `--lectionary`/`--lang` flags overriding config; everything else is
unchanged because both sources yield `[]Section`.
## Addendum B: lectio-web (HTMX web UI with selectable themes)
A third binary `lectio-web` — an hledger-web-style local server. Build after the
base plan + Addendum A. Consumes `readings.Load` + `render.GatherVersion`; imports
the domain packages, never the reverse.
### Amendment to Task 10 (config) — web fields
Add to `Config`: `WebTheme string \`toml:"web_theme"\``, `WebPort int \`toml:"web_port"\``.
Defaults: `WebTheme "light"`, `WebPort 0`. Validate `WebTheme` ∈
`{light,dark,sepia,parchment,nord}`. Add the two lines to the embedded seed
(after `offline`): `web_theme = "light"` and `web_port = 0` with the spec's
comments. (Do this as a small follow-up commit to internal/config.)
### Task B1: internal/web — HTML render + embedded themes
**Files:** Create `internal/web/render.go`, `internal/web/render_test.go`,
`internal/web/templates/*.html`, `internal/web/static/themes/{light,dark,sepia,parchment,nord}.css`,
`internal/web/static/htmx.min.js` (download the pinned release).
**Interfaces:**
- Consumes `liturgy.Section`, `render.GatherVersion`, `render.OfflineVersions`.
- Produces: `web.RenderReadings(secs []liturgy.Section, versions []string, lectionary string) template.HTML`
(the reading pane: per section, a heading + one column per version built from
`render.GatherVersion(v, sec, lectionary)`; verse-number / heading / citation /
refrain wrapped in CSS-class spans so themes restyle them), and
`web.Themes() []string` (the five theme names). Embed templates + CSS + htmx via `go:embed`.
- [ ] **Step 1: Write the failing test**
```go
func TestRenderReadings(t *testing.T) {
secs := []liturgy.Section{{Heading: "Ewangelia (J 20, 1. 11-18)", PartID: "ewangelia"}}
html := string(RenderReadings(secs, []string{"wuj"}, "new"))
if !strings.Contains(html, "Ewangelia") || !strings.Contains(html, "class=") {
t.Errorf("reading pane missing heading/classes: %q", html[:min(200, len(html))])
}
}
func TestThemesEmbedded(t *testing.T) {
for _, name := range Themes() {
if b, err := themeCSS(name); err != nil || len(b) == 0 {
t.Errorf("theme %s not embedded", name)
}
}
}
```
- [ ] **Step 2:** `go test ./internal/web/` → FAIL.
- [ ] **Step 3:** Implement render.go: `//go:embed templates static` FS; parse templates once; `RenderReadings` builds the pane by calling `render.GatherVersion` per (section, version) and feeding a `templates/readings.html` fragment; wrap heading/citation/verse-number/refrain in `<span class="...">`. `Themes()` returns the five names; `themeCSS(name)` reads `static/themes/<name>.css` from the embed FS (error on unknown). Write five real theme CSS files (each defines the colour-role classes + page background/foreground; light/dark/sepia/parchment/nord distinct). Download the pinned `htmx.min.js` into `static/`.
- [ ] **Step 4:** `go test ./internal/web/` → PASS.
- [ ] **Step 5:** Commit `web: HTML render + embedded themes`.
### Task B2: internal/web — server + handlers + cmd/lectio-web
**Files:** Create `internal/web/server.go`, `internal/web/server_test.go`, `cmd/lectio-web/main.go`.
**Interfaces:**
- Consumes `config.Config`, `readings.Load`, `bible.Lookup`, B1's render.
- Produces: `web.NewServer(cfg config.Config) http.Handler`; `web.Run(cfg) error`
(pick port = cfg.WebPort or a free one, start, open the browser).
- [ ] **Step 1: Write the failing test** (httptest against the handler, no real browser)
```go
func TestIndexAndPartial(t *testing.T) {
liturgy.SetBaseURL(fixtureServerURL(t) + "/liturgia/%s/Ewangelia") // reuse the T8 hook
srv := NewServer(config.Default())
// GET /?date=2026-07-22&v=wuj -> 200, contains a reading + the theme <link> + htmx script
rec := httptest.NewRecorder()
srv.ServeHTTP(rec, httptest.NewRequest("GET", "/?date=2026-07-22&v=wuj", nil))
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "htmx") { t.Fatalf("index: %d", rec.Code) }
// GET /readings (HTMX partial) -> 200, fragment only (no <html>)
rec2 := httptest.NewRecorder()
srv.ServeHTTP(rec2, httptest.NewRequest("GET", "/readings?date=2026-07-22&v=wuj", nil))
if rec2.Code != 200 || strings.Contains(rec2.Body.String(), "<html") { t.Fatalf("partial not a fragment") }
// GET /lookup?ref=J+20:1&v=wuj -> contains the verse
rec3 := httptest.NewRecorder()
srv.ServeHTTP(rec3, httptest.NewRequest("GET", "/lookup?ref=J+20:1&v=wuj", nil))
if !strings.Contains(rec3.Body.String(), "20:1") { t.Fatalf("lookup missing verse") }
// GET /theme.css?name=sepia -> text/css
rec4 := httptest.NewRecorder()
srv.ServeHTTP(rec4, httptest.NewRequest("GET", "/theme.css?name=sepia", nil))
if rec4.Code != 200 || !strings.Contains(rec4.Header().Get("Content-Type"), "css") { t.Fatalf("theme.css") }
}
```
- [ ] **Step 2:** `go test ./internal/web/` → FAIL.
- [ ] **Step 3:** Implement server.go: routes — `/` full page (date/lectionary/version/all/theme controls with `hx-get="/readings"` targeting the pane; the passage-lookup form `hx-get="/lookup"`; theme `<link id=theme href="/theme.css?name=…">` + a theme `<select>` that swaps it; embedded `/static/htmx.min.js`), `/readings` HTMX partial (calls `readings.Load` with query params, offline→OfflineVersions, returns `RenderReadings`), `/lookup` (bible.Lookup for the typed ref across the picked versions → HTML fragment), `/theme.css?name=` (serves `themeCSS`, `Content-Type: text/css`), `/static/` (embedded). `Run(cfg)` listens on cfg.WebPort or `:0`, prints the URL, best-effort opens the browser (`xdg-open`/`open`/`start`), serves. `cmd/lectio-web/main.go`: `config.Load()` → `web.Run(cfg)`.
- [ ] **Step 4:** `go test ./internal/web/` → PASS; `go build ./cmd/lectio-web`; manual: run it, open the browser, click date/version/theme, try the lookup box.
- [ ] **Step 5:** Commit `web: HTMX server + lectio-web binary`.
### Amendment to Task 1/14 (Makefile, .gitignore, README)
Add `lectio-web` to the Makefile `build`/`install`/`cross` targets and `.gitignore`;
document `lectio-web`, its keys/controls, and the themes in the README.
## Self-Review Notes
- Spec coverage: two binaries (T1,12,13,15-via-14), embedded corpora (T1,4), lookup (T4,5), aliases incl. `J`→John (T3), citation conversion + psalm systems (T2,6), fetch/parse (T7,8), cache HTML+JSON (T8), sigla harvest + offline (T9), config incl. `offline` (T10), render + dedup + pl→wuj (T11), subcommands (T12), colored reader TUI (T13), Makefile/cross/README (T1,14). All spec sections map to a task.
- Bulk data (73-book aliases, `POLISH_TO_EN`, `DRB_TITLE_FOLD`) is ported verbatim from named source files — concrete, not placeholder.
- Type consistency: `Verse`, `Section`, `Options`, `Config`, `GatherVersion`, `Lookup`, `ToEnglishRef`, `DrbVerse` names are used identically across tasks.
|