The code uses a counter, which is increased every time a header/footer cell is generated. If the counter is 1 (or <= the number of columns in my adaptation), then it’s the first occurrence of the header; otherwise a repetition. Same for footer, just checking whether the counter is big enough yet. That’s the basic idea.
Have a look at Tips on debugging Typst code, including the dark magic and debugging in general for some advice there. Tl;dr: the equivalent of printing debug outputs is hovering over a variable/expression. For the variables inside the header code in particular, you will see multiple values, since there are multiple header cells, each displayed multiple times.
I’m about to go to bed, but I want to leave you with some reading in case you’re interested in some background. There is a fundamental difference between how Typst and TeX do things in this regard, you can read a bit about it here: TeX and Typst: Layout Models | Laurenz's Blog. One thing that Typst makes possible is breakable grid rows; other things may be more complex in its model and without re-reading the article in detail, repeated headers may be among them.
Another thing is that advanced table features are just in general not really there yet, we can admit that. Ideally, we could write something like show table.header.where(repeated: true) or something like that, but table.header does not support show rules at all yet. I can’t tell if this would be particularly hard to implement, or if it’s just a matter of doing it, but that would be the kind of ergonomics Typst would want to offer.
That’s all I can just write about. I’ll see if I can have a look at actually solving the rest of your problems tomorrow or at least next week.