The two lines that do not work
build/ !build/keep.txt
Here is what git check-ignore -v (git 2.43) says about three files in that folder:
.gitignore:1:build/ build/keep.txt .gitignore:1:build/ build/assets/logo.svg .gitignore:1:build/ build/app.js
Every file is decided by line 1, build/, including the one the negation names. Git walks the tree one folder at a time. When it reaches build, the rule build/ matches the folder, so git skips it. The files inside are never listed, and a rule about build/keep.txt has nothing to match. The git documentation says it in one line: it is not possible to re-include a file if a parent directory of that file is excluded.
The rule that works
Ignore what is in the folder rather than the folder itself:
/build/* !build/keep.txt !build/assets/
Now the folder build is not ignored, so git looks inside. /build/* ignores each thing in it, and the two negations take back the file and the subfolder. After the change, the same command says:
.gitignore:2:!build/keep.txt build/keep.txt :: build/assets/logo.svg .gitignore:1:/build/* build/app.js
keep.txt is decided by the negation and kept, logo.svg is matched by nothing once its folder is open, and app.js stays ignored. The leading / is optional, but it makes a change visible: any pattern with a slash in the middle only matches next to its .gitignore file, so build/* and /build/* mean the same thing, while plain build/ matched a folder called build at any depth. If you had several build folders, write **/build/*.
Finding these in your own repository
The .gitignore Explainer takes your ignore files and a path list, flags every negation that a parent folder blocks, and writes the extra lines. Before offering them it re-runs the rules with the lines added, and tells you how many paths come back and which other paths, if any, change. Its rule engine is checked against git check-ignore on thousands of random repositories, and the fixes it suggests are re-checked in git the same way.
Questions
Why does build/ followed by !build/keep.txt not keep the file?
Because git decides about the folder build before it ever looks at the file. The rule build/ ignores the folder, and git never lists what is inside an ignored folder, so the rule !build/keep.txt is never compared with anything. Ignore the folder's contents with build/* instead, then the negation works.
What about files two folders deep?
Each folder on the way down has to be open. With build/* the folder build/assets is itself ignored, so a rule for build/assets/logo.svg cannot see the file either. Add !build/assets/ to re-open that folder and build/assets/* if you still want the rest of its contents ignored.
Does this also apply to a .gitignore inside the ignored folder?
Yes. Git does not read a .gitignore file inside a folder it has already ignored, so negations written there have no effect either. Put the rules in a .gitignore above the ignored folder.