Repository navigation
refactor(utils): locate frontmatter in one place under a named policy - #457
Conversation
The readers in internal/utils locate the --- delimiters under different rules, so the same SKILL.md can give different answers depending on the entry point. Before they are rebuilt on one locator, these cases record each entry point's current result on the inputs where the rules differ (indented or late delimiters, unclosed and empty blocks, trailing spaces, CRLF, BOM, delimiters in the body) and on a line longer than the bufio.Scanner cap that the path readers silently stop at. Refs #449
Each reader in internal/utils found the --- delimiters with its own loop, under four different rules that were only visible by reading all of them, and the list reader existed twice with a path copy and a bytes copy that had drifted apart. A fix to one reader, like the mcp serve fixes to the strict one, did not reach the others, and nobody could say which rule an entry point followed without tracing it. locateFrontmatter now does the locating for every reader, and the rule is a frontmatterPolicy value: strictBlock, lenientBlock, bodyBlock and rewriteBlock name the rules that exist and the entry points that use them. The rules themselves are not unified; every entry point returns what it returned before, including the bufio.Scanner quirks of the readers that take a path (a line of 64 KiB or more ends the content, one \r is dropped per line), which now live in scannable. The strict reader still walks only to the closing delimiter and copies nothing. Two more cases found by comparing old and new code on random input are pinned: a block scalar on the last frontmatter line, and \r\r\n endings. Refs #449
Rebuilding the path readers on the shared locator made them read the whole SKILL.md into memory, where they used to scan line by line and stop at the closing delimiter. They run once per skill or agent during sync and listing, so a large body, or a large file with no frontmatter at all, now cost its full size on every call. readHead goes back to a bufio.Scanner and keeps the lines from the opening delimiter to the closing one, nothing before and nothing after. Reading through the real Scanner also replaces the code that imitated its quirks (64 KiB line cap, one \r dropped per line); ReadSkillBody, which needs the body, takes them from scanLines. An unclosed block is still kept to the end of the file, as the list and fields readers always did. Review follow-ups in the same files: RewriteFrontmatterList no longer copies the content to a string and back, ParseFrontmatterField's two loops no longer share an index, and the tests share one file helper. Results are unchanged for every entry point. Refs #449
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 90f161fef0
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if head.Len() > 0 { | ||
| head.WriteByte('\n') | ||
| } | ||
| head.Write(scanner.Bytes()) |
There was a problem hiding this comment.
Avoid buffering complete blocks for streaming readers
When a SKILL.md has a large but closed frontmatter block made of individually scanner-safe lines, this accumulates the entire block before ParseSkillName or ParseFrontmatterField can inspect it. Those entry points previously streamed the file and could return as soon as the requested key was encountered, so discovery and listing can now allocate memory proportional to the complete frontmatter size—even when name or description is the first field—and a sufficiently large skill can exhaust the process. Preserve a streaming path for these readers or impose a total block-size bound.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 279be8a. On main, ParseSkillName and ParseFrontmatterField scanned line by line and returned at their key; after the refactor they collected the whole block first, so a large closed block (or an unclosed one, to end of file) cost its full size even when name came first.
They now read through scanLenientBlock, which streams the lenient block through a bufio.Scanner and stops when the reader has its key. The per-line rule moved into blockWalk, shared by locateFrontmatter and the streaming path, so the two cannot drift. ParseFrontmatterList and ParseFrontmatterFields still collect the block, as they did on main (they decode it as YAML).
Covering test: TestFrontmatterEntryPoints_KeyReadersStopAtTheKey (name first, then 2.5 MiB of frontmatter, closed and unclosed; failed at ~27 MB allocated before the fix, now under 1 MiB). All characterization tests are unchanged, and an old-vs-new comparison against main on 60,000 random files showed no difference. make check passes.
On main these two readers scanned SKILL.md line by line and returned at the line they were looking for, keeping nothing. After the refactor they first collected the whole frontmatter block, so a large block cost its full size on every call even when name came first, and an unclosed one cost the rest of the file. Sync, target naming and listing call them once per skill or agent. Reported by Codex review on #457. The per-line rule (which line opens and which closes the block) moves into blockWalk, which locateFrontmatter and the new scanLenientBlock both use, so the streaming path and the byte locator cannot drift. ParseSkillName and ParseFrontmatterField stop at their key again; the list and fields readers collect the block as they always did. Results are unchanged for every entry point. Refs #449
|
@codex review |
|
Codex Review: Didn't find any major issues. Another round soon, please! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Type
proposals/only — see CONTRIBUTING.md)Linked Issue
Closes #449
This is the low-risk subset of the issue: one locator, every reader in
internal/utilsbuilt on it, and the rules named. No rule is unified; that decision is left open below.What moved where
New file
internal/utils/frontmatter_locate.go:frontmatterPolicyskipBOM,dashGuard,firstLine,delim.strictBlock,lenientBlock,bodyBlock,rewriteBlockblockWalklocateFrontmatter(content, policy)blockWalk. Walks lines up to the closing delimiter and returns sub-slices of the content. No allocation.scanLenientBlock(path, fn)blockWalk: feeds the lenient block's lines from abufio.Scannertofnuntil the block ends orfnstops.readLenientBlock(path)scanLines(data)ReadSkillBody.ParseFrontmatterMapstrictBlockParseSkillName,ParseFrontmatterField,ParseFrontmatterFields,ParseFrontmatterList,ParseFrontmatterListFromByteslenientBlockReadSkillBodybodyBlocksplitFrontmatterAndBody(RewriteFrontmatterList,SetFrontmatterList)rewriteBlockRemoved:
extractFrontmatterRaw,extractFrontmatterRawFromBytes, the duplicated body ofParseFrontmatterList(both list readers now sharestringListanddecodeFrontmatter), and five hand-written delimiter scans. Exported names and signatures are unchanged; no file outsideinternal/utilschanged.Intentional behaviour changes
None in results. Every exported entry point returns what it returned on
main, including thebufio.Scannerquirks of the path readers (a line of 64 KiB or more ends the content without an error, one\ris dropped per line) and the strict reader's guarantees from 64898e1, 78857ad, 69f7dfa and 76a49ad.Resource use is the same as on
mainor lower:ParseSkillNameandParseFrontmatterFieldstill stream and return at their key (pinned byTestFrontmatterEntryPoints_KeyReadersStopAtTheKey, added for the Codex finding below).ParseFrontmatterListandParseFrontmatterFieldsstill collect only the block, and never the body (pinned byTestFrontmatterEntryPoints_PathReadersKeepOnlyTheBlock).ParseFrontmatterMap,ParseFrontmatterListFromBytesandRewriteFrontmatterListcopy less: the block is decoded from the content in place.Open questions for the maintainer
1. Should any of these rules be unified? The entry points disagree on the inputs below. All rows are pinned in
frontmatter_entrypoints_test.goand were produced by the code onmain. "Lenient" isParseSkillName,ParseFrontmatterField,ParseFrontmatterFields,ParseFrontmatterList,ParseFrontmatterListFromBytes(sync, target naming, list/restore TUIs, resources, hub, install).ParseFrontmatterMapismcp serve. The base file is---/name: a/targets: [t]/---/body.ParseFrontmatterMapReadSkillBodyRewriteFrontmatterList---indentedabody---indentedabody---abody# Titlebefore---a--- title, real block afterabody--- titleline is droppeda(reads to end of file)---abodyaabody(LF)abody---inside a block scalara, but the block ends there, sotargetsafter it is losta, full blocktargets: [t]+---+bodynameParseFrontmatterListFromBytes:taaaParseFrontmatterFields:texttext\n\r\r\nline endingsParseFrontmatterListgivest\nu\n,…FromBytesgives\nt\n\nu\nfor the same block-scalar item2.
RewriteFrontmatterListwrites a second frontmatter block on CRLF and BOM files.rewriteBlockdoes not accept---\ras a delimiter and does not skip a BOM, so the dashboard's batch-targets write (internal/server/handler_skills_batch.go) finds no block and prepends a new one, leaving the old block in the body. Same for an indented delimiter and an unclosed block. This is the behaviour onmain; it is pinned, not fixed, because fixing it is a rule change.3. The 64 KiB line cap of the path readers is an unchecked
bufio.Scannererror, kept as it is.ReadSkillBodycuts a body at such a line without saying so.Follow-ups, not in this PR
ToggleFrontmatterFlag(frontmatter_write.go) still has its own delimiter scan, a fifth rule:TrimRight " \t\r", with only blank lines allowed before the opening delimiter. On a CRLF file it edits the existing block whereRewriteFrontmatterListprepends a second one.---by hand and do not useinternal/utils:internal/hub/index.go,internal/search/search.go,internal/version/skill.go,internal/audit/analyzer_metadata.go,internal/sync/context.go.ParseSkillNameandParseFrontmatterFieldstill readname:/<field>:by hand inside the located block, so a nested, indented key matches.Review
/code-review(local): one finding fixed, that the path readers buffered a whole file without frontmatter. The rest were left as they are: theMemStatsallocation tests follow the existingTestParseFrontmatterMap_MemoryDoesNotGrowWithBodyLines; keeping the Scanner quirks and the separate rules is the point of this PR;ToggleFrontmatterFlagand other packages are listed as follow-ups./simplify(local):RewriteFrontmatterListno longer copies the content to a string and back,ParseFrontmatterField's loops no longer share an index, the tests share one file helper, smaller test files. No pinned result changed.frontmatter_locate.go):ParseSkillName/ParseFrontmatterFieldbuffered the whole block instead of streaming to their key. Confirmed with a failing test (~27 MB allocated) and fixed in 279be8a. Round 2 on 279be8a: no major issues.Checks
Run in a task-owned container from the devcontainer image, with this branch mounted at
/workspace, on 279be8a:main(first commit)go vet ./internal/utils/,go test ./internal/utils/ -count=1make check(ai-context.py check,fmt-check,go vet ./...,scripts/test.sh)mainversions offrontmatter.go/frontmatter_write.goin a scratch package against this branch, 60,000 random files (delimiter variants, CR / CRLF /\r\r\n, BOM, block scalars, invalid YAML, 65535- and 65536-byte lines), all eight entry pointsNot run: UI tests and build, website build, E2E runbooks, Windows verification. No UI, website or CLI surface changed.
Checklist
make check) — for code changes