Skip to content

refactor(utils): locate frontmatter in one place under a named policy - #457

Merged
runkids merged 4 commits into
mainfrom
runkids/arch-449-frontmatter
Oct 6, 2026
Merged

runkids merged 4 commits into
mainfrom
runkids/arch-449-frontmatter

Conversation

@runkids

@runkids runkids commented Oct 6, 2026 •

Copy link
Copy Markdown
Owner

Type

  • Bug fix
  • Small improvement (docs, typo, minor refactor)
  • Feature proposal (proposals/ only — see CONTRIBUTING.md)

Linked Issue

Closes #449

This is the low-risk subset of the issue: one locator, every reader in internal/utils built 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:

Piece Role
frontmatterPolicy The delimiter rule as four fields: skipBOM, dashGuard, firstLine, delim.
strictBlock, lenientBlock, bodyBlock, rewriteBlock The four rules that exist today, each naming the entry points that use it.
blockWalk The per-line rule: classifies each line as before, opening, inside or closing the block (or no block). The only place that decides this.
locateFrontmatter(content, policy) The locator for content in memory, built on blockWalk. Walks lines up to the closing delimiter and returns sub-slices of the content. No allocation.
scanLenientBlock(path, fn) The streaming path for the readers that take a path, built on blockWalk: feeds the lenient block's lines from a bufio.Scanner to fn until the block ends or fn stops.
readLenientBlock(path) Collects those lines for the list and fields readers.
scanLines(data) The Scanner view of pre-read content, for ReadSkillBody.
Entry point Policy
ParseFrontmatterMap strictBlock
ParseSkillName, ParseFrontmatterField, ParseFrontmatterFields, ParseFrontmatterList, ParseFrontmatterListFromBytes lenientBlock
ReadSkillBody bodyBlock
splitFrontmatterAndBody (RewriteFrontmatterList, SetFrontmatterList) rewriteBlock

Removed: extractFrontmatterRaw, extractFrontmatterRawFromBytes, the duplicated body of ParseFrontmatterList (both list readers now share stringList and decodeFrontmatter), and five hand-written delimiter scans. Exported names and signatures are unchanged; no file outside internal/utils changed.

Intentional behaviour changes

None in results. Every exported entry point returns what it returned on main, including the bufio.Scanner quirks of the path readers (a line of 64 KiB or more ends the content without an error, one \r is dropped per line) and the strict reader's guarantees from 64898e1, 78857ad, 69f7dfa and 76a49ad.

Resource use is the same as on main or lower:

  • ParseSkillName and ParseFrontmatterField still stream and return at their key (pinned by TestFrontmatterEntryPoints_KeyReadersStopAtTheKey, added for the Codex finding below).
  • ParseFrontmatterList and ParseFrontmatterFields still collect only the block, and never the body (pinned by TestFrontmatterEntryPoints_PathReadersKeepOnlyTheBlock).
  • ParseFrontmatterMap, ParseFrontmatterListFromBytes and RewriteFrontmatterList copy 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.go and were produced by the code on main. "Lenient" is ParseSkillName, ParseFrontmatterField, ParseFrontmatterFields, ParseFrontmatterList, ParseFrontmatterListFromBytes (sync, target naming, list/restore TUIs, resources, hub, install). ParseFrontmatterMap is mcp serve. The base file is --- / name: a / targets: [t] / --- / body.

Input Lenient ParseFrontmatterMap ReadSkillBody RewriteFrontmatterList
Opening --- indented name a error: no frontmatter at the start body sees no block: prepends a second block
Closing --- indented name a error: unclosed body sees no block: prepends a second block
Blank line before --- name a error: no frontmatter at the start body rewrites; the blank line is dropped
# Title before --- name a error: no frontmatter at the start whole file sees no block: prepends
First line --- title, real block after name a error: no frontmatter at the start body rewrites; the --- title line is dropped
Unclosed block name a (reads to end of file) error: unclosed empty sees no block: prepends
Trailing space/tab after --- name a error: no frontmatter at the start body rewrites
CRLF name a name a body (LF) sees no block: prepends a second block
BOM no name, no list name a whole file, BOM included sees no block: prepends before the BOM
Empty or blank block nothing error: no frontmatter body rewrites
Indented --- inside a block scalar name a, but the block ends there, so targets after it is lost name a, full block targets: [t] + --- + body rewrites correctly
Line of 64 KiB or more in the block, before name path readers: nothing after that line; ParseFrontmatterListFromBytes: t name a empty rewrites
Line of 64 KiB or more in the body name a name a body cut before that line rewrites
Block scalar on the last line ParseFrontmatterFields: text text\n — —
\r\r\n line endings ParseFrontmatterList gives t\nu\n, …FromBytes gives \nt\n\nu\n for the same block-scalar item — — —

2. RewriteFrontmatterList writes a second frontmatter block on CRLF and BOM files. rewriteBlock does not accept ---\r as 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 on main; 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.Scanner error, kept as it is. ReadSkillBody cuts 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 where RewriteFrontmatterList prepends a second one.
  • Other packages locate --- by hand and do not use internal/utils: internal/hub/index.go, internal/search/search.go, internal/version/skill.go, internal/audit/analyzer_metadata.go, internal/sync/context.go.
  • ParseSkillName and ParseFrontmatterField still read name: / <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: the MemStats allocation tests follow the existing TestParseFrontmatterMap_MemoryDoesNotGrowWithBodyLines; keeping the Scanner quirks and the separate rules is the point of this PR; ToggleFrontmatterFlag and other packages are listed as follow-ups.
  • /simplify (local): RewriteFrontmatterList no 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.
  • Codex round 1 (P2, frontmatter_locate.go): ParseSkillName / ParseFrontmatterField buffered 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:

Command Result
New tests on the code from main (first commit) pass
go vet ./internal/utils/, go test ./internal/utils/ -count=1 pass
make check (ai-context.py check, fmt-check, go vet ./..., scripts/test.sh) exit 0, 34 packages ok, 0 failures
Old-vs-new comparison, not committed: the main versions of frontmatter.go / frontmatter_write.go in 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 points no difference

Not run: UI tests and build, website build, E2E runbooks, Windows verification. No UI, website or CLI surface changed.

Checklist

  • I've read CONTRIBUTING.md
  • Tests included and passing (make check) — for code changes
  • No unrelated changes in the diff
  • Scope is focused — one concern per PR

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
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-06T16:37:42.103536Z 279be8a Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread internal/utils/frontmatter_locate.go Outdated
Comment on lines +118 to +121
if head.Len() > 0 {
head.WriteByte('\n')
}
head.Write(scanner.Bytes())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
@runkids

runkids commented Oct 6, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 279be8aba6

ℹ️ 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".

@runkids runkids added the architecture Deepening opportunity: restructure modules for locality and testability label Oct 6, 2026
@runkids
runkids merged commit 275131f into main Oct 6, 2026
8 checks passed
@runkids
runkids deleted the runkids/arch-449-frontmatter branch October 6, 2026 16:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

architecture Deepening opportunity: restructure modules for locality and testability

Projects

None yet

Development

Successfully merging this pull request may close these issues.

frontmatter: readers in internal/utils locate the delimiters under five different rules

1 participant