src/core/content — the content model¶
Twelve files that know what a content file is: how to read its front matter, how to write it back without disturbing anything the user did not change, what a field means, where a page lives, what its SEO metrics are, and — since WP2.3 — what is wrong with it and which of those a script may honestly repair. Pure Node — see ../README.md for the layering rule.
| File | Exports | Owner |
|---|---|---|
frontmatter.ts |
FmValue, FrontMatter, FmFormat, FmBlock, detectFormat, splitFrontMatter, parseFrontMatterBlock, readYaml, parseYaml, parseTomlFlat, parseYamlKeyLine, isYamlSequenceItem, scanFrontMatterWarnings, ownValue, setOwn, asString, asList, asBool |
WP03, WP2.3 |
serialize.ts |
SerializeOptions, DEFAULT_SERIALIZE_OPTIONS, serializeOptions, KeyChange, applyChanges, applyCommaSeparatedFields, updateFrontMatterKeys, serializeFrontMatter, quoteScalar, stitch |
WP03 |
article.ts |
Article, parseArticle, readArticle, writeArticle, setFieldValue, stampModified, isSupported, CONVENTIONAL_MODIFIED_KEYS |
WP03 |
fields.ts |
inlineFieldCollections, evaluateWhen, visibleFields, emptyValueFor, isEmpty, validateFields, FieldViolation, violationToIssue, labelOf, limitFor, findField |
WP04, WP2.3 |
contentType.ts |
DEFAULT_CONTENT_TYPE, DEFAULT_CONTENT_TYPE_NAME, CONTENT_TYPE_FIELD, getContentTypes, contentTypeByName, resolveContentType, processFields, CreateContentRequest, CreateContentResult, createContent, renderContentFile, sanitizeFileName, generateContentTypeFrom, missingFields |
WP04 |
folders.ts |
resolveFolders, folderForFile, filePrefixFor |
WP04, WP2.1 |
placeholders.ts |
processPlaceholders, hasPlaceholder, PlaceholderContext, FAULTY_PLACEHOLDER, PLACEHOLDER_SCRIPT_TIMEOUT_MS, setPlaceholderTrust, placeholderTrust, and the synchronous token processors (processTimePlaceholders, processDatePlaceholders, processFmPlaceholders, processArticlePlaceholders, processPathPlaceholders, processFilePrefixIndex, processCustomPlaceholders) |
WP04, WP1.3 |
slug.ts |
createSlug, decorateSlug, alignedFilePath |
WP04, WP2.1 |
pageIndex.ts |
IndexCache, buildIndex, pageToRecord, PageSummary, slimPage, searchPages, emptyIndexCache, asIndexCache |
WP05 |
seo.ts |
ArticleDetails, getArticleDetails, emptyArticleDetails, stripShortcodes, SeoRow, seoInsights, KeywordCheck, KeywordInfo, keywordAnalysis, keywordDensity, keywordsOf, isHealthyDensity, KEYWORD_CHECK_NAMES, KEYWORD_CHECK_TOTAL, DENSITY_MIN, DENSITY_MAX, WORDS_PER_MINUTE |
WP05 |
audit.ts |
AuditRuleSpec, AUDIT_RULE_SPECS, auditPage, auditSite, fixFor, dryRunFix, pageFrontMatter, datePartOf, filenameDateOf, lineOfKey |
WP2.3 |
schema.ts |
SCHEMA_PATHS, SCHEMA_SOURCE_RANK, DEFAULT_DESCRIPTION_MAX, emptySiteSchema, schemaFromFrontmatterSchemaYml, schemaFromCmsConfig, schemaFromProjectConfig, schemaFromProfile, mergeSchemas, readSiteSchema, collectionSchemaFor, requiredKeysFor, toFrontMatterValue |
WP2.3 |
The front-matter engine, in one paragraph¶
splitFrontMatter decides by the file's leading characters — ---, +++, { — which dialect a block is written in, and returns an FmBlock (raw text, character offsets, parsed data) plus the body. updateFrontMatterKeys edits a block by line surgery: it finds the line range each changed key occupies and rewrites only those lines. serializeFrontMatter is the full-emit fallback for the cases surgery declines. stitch puts the fences back. article.ts is the only module that writes user markdown.
Contracts worth knowing before you change anything¶
The platform is a parameter, and its default is Jekyll (decision D12). buildIndex, pageToRecord, resolveFolders, filePrefixFor, resolveContentType, createContent and alignedFilePath each take profile: PlatformProfile = JEKYLL_PROFILE as their last argument. What a date in a filename means, which key holds the publication date, which keys carry the card image, which stems are structural, which basenames are page bundles, and which directories are build output all come from the profile now — and JEKYLL_PROFILE carries the exact literals these modules used to declare, so a call site that has not resolved a platform behaves as it always did. The byte-identity golden at src/test/fixtures/golden/platform/ is what makes "as it always did" a fact rather than an intention. resolveContentType gains one step from the profile: step 1b reads the platform's own type key (fmContentType on a zer0-mistakes site) after the conventional type, and JEKYLL_PROFILE names no extra key, so a bare Jekyll site never reaches it.
Dates stay strings. Nothing in frontmatter.ts or serialize.ts constructs a Date. Round-tripping 2026-07-31 through a JS Date is how a CMS quietly rewrites every date in a repository to a timezone-shifted timestamp, and it is the single most common way a front-matter library corrupts a site. stampModified formats a Date into a string and never reads one back out.
The dialect belongs to the file, not to the configuration. zer0.json's frontMatter.format decides what new blocks look like. (There is no VS Code setting for it — the project schema lives in zer0.json alone; see src/config.ts.) An existing TOML file stays TOML. serializeOptions(cfg, format) takes the detected format explicitly for exactly this reason; passing only cfg means "I am creating this block".
Line surgery is the default write path (decision D7). updateFrontMatterKeys rewrites only the lines of the keys named in its KeyChange[]. Comments, blank lines, key order, quoting style and indentation quirks of every other key survive because they are never re-emitted. Flipping status: pending to status: approved is a one-line diff, always — the property BASH-CMS's markStatus had for one key, generalised to every field edit. A key's range stops before the blank lines and comments that separate it from the next key, which is what makes "untouched lines are byte-identical" literally true.
null is the fallback signal, and for a YAML block it is a refusal. updateFrontMatterKeys returns null for a TOML/JSON block (those re-serialise wholesale, which is the documented trade for those dialects) and for a nested path whose parent holds a scalar or a sequence. A nested path whose parent is simply absent is no longer a null: surgery grows the missing nesting under the deepest ancestor it can find, because handing the block to a full re-emit for the sake of one new key deleted every comment, anchor and wrapped scalar in it. writeArticle therefore never re-emits an existing YAML block — it throws instead, since the re-emit would rebuild the block out of what the parser understood while applyChanges refuses the same change anyway. Never "guess" a location; appending a duplicate key is a worse failure than a formatting change.
__proto__ is data, not a prototype. Every mapping the parser builds is populated through setOwn and read through ownValue. node['__proto__'] on a plain object is Object.prototype and passes every "is this a nested mapping?" test, so the TOML table walk and applyChanges's path walk could both be steered into writing a key onto the prototype every object in the extension host shares — including the {} that resolveConfig reads governance off, which is how a content file could turn publishAllow on. A key really spelled __proto__ is kept as an ordinary own key: nothing is dropped and nothing escapes the object it was written to.
A malformed file has no front matter. Every parser here is written not to throw, and parseFrontMatterBlock catches anything that slips through and returns {}. The panel re-parses on every keystroke of a file somebody is mid-edit, so "unreadable" has to be a value, not an exception. Nothing is written as a result: a construct we cannot read is a construct we cannot corrupt.
And it says so out loud. FmBlock.warnings is one line per problem the reader met in this block: each error and warning the yaml package reports (an unclosed quote, an unknown tag, a tab used as indentation …), each alias that names no anchor (its value is then null, and a merge of it merges nothing — never the reason the rest of the block is lost), and in TOML [[array-of-tables]] and '''. Every line starts line <n>:, 1-based within the block body, and that prefix is a contract audit.ts reads. A YAML block is parsed once for its data and its warnings (readYaml).
The reason the channel exists is two floors up: an audit over a file whose <<: *defaults names no anchor would otherwise emit a confident missing-key for every key that merge was meant to supply, and a fix-it would stand ready to rewrite a file nothing had read. An empty warnings array is the only state under which data is a complete account of the block.
Nested changes are dotted keys. setFieldValue(data, ['seo','title'], v) yields { key: 'seo.title', value: v }, which the surgery resolves to the exact leaf line. A key that literally contains a dot (image.alt) wins over the path reading, decided against the block's own top-level keys. Path segments address mappings only — there is no index syntax for reaching into a sequence, and a segment that itself contains a dot falls back to rewriting the whole top-level container.
Reading YAML¶
YAML is read by the yaml package (ADR 0006 decision 9, amending D3: a maintained library bundled at build time, not a hand-rolled subset). Anchors, aliases, merge keys, tags, block and folded scalars, multi-line plain, quoted and flow values and every escape mean what YAML says they mean. The YAML 1.2 core schema decides the scalars, with three kinds kept as the text that was written, because front matter means them as text: a zero-padded integer (007), an integer past Number.MAX_SAFE_INTEGER, and the octal, hex, .inf and .nan spellings. So true/false → boolean, null/~/empty → null, decimal integers and floats → number, and yes/no/on/off and anything date-shaped stay strings — the core schema has no timestamp type, so dates stay strings end to end (D7). TOML keeps its own small reader (parseTomlFlat).
On the way back out, serializeFrontMatter quotes a string when a reader would coerce it — including the YAML 1.1 words Jekyll's Ruby parser treats as booleans, which our own parser does not. Keys are quoted only when they would not parse back as themselves.
commaSeparatedFields has two halves¶
Write side: serializeFrontMatter joins a listed key's array with ', ' onto one line. Read side: applyCommaSeparatedFields(data, keys) splits it back. The parser does not do the split — it has no configuration and never will; this is a field-level concern applied by whoever built the Zer0Config.
The content model, in five more paragraphs¶
Creation computes; it does not write. createContent resolves the content type, the filename prefix, the path and the starting front matter, refuses a path that already exists, and returns a CreateContentResult. renderContentFile(result, cfg) turns that into the exact bytes; the mkdir and the writeFile belong to the caller. That keeps article.ts's "only writer of user markdown" property intact and lets the MCP server and the tests exercise creation without producing files.
A content type is resolved in five steps, in order: the file's own type key → a content folder that binds exactly one type → the sole registered type → the type named default → the synthesized DEFAULT_CONTENT_TYPE. Step 1 is type, not FM's branded fmContentType. A folder that lists two content types binds nothing: guessing between them would apply the wrong schema silently.
Placeholders run in one documented order — article ({{title}}, {{slug}}) → front matter ({{fm.x}}) → path ({{pathToken.n}}) → file index ({{filePrefix.index}}) → custom ({{id}}) → time ({{now}}, {{year}}, …)
→ {{date|pattern}}. FM used two different orders for field defaults and file
prefixes and documented neither. A token whose source is missing is left in the text: a visible {{fm.author}} in a filename is a bug somebody fixes, an empty string is one nobody notices. A custom placeholder whose script fails yields FAULTY_PLACEHOLDER (<failed to process>), which isEmpty reads as empty — scripts run through execFile with an argv array and no shell.
A placeholder script is one of the five execution vectors, and it is the one that arrives entirely from zer0.json. Cloning a repository is enough to name a command in placeholders[] — there is no settings twin for that key — so the spawn passes evaluateExecGate before execFile (decision D13). An untrusted workspace refuses, and so does a script that resolves outside the workspace root, in a trusted workspace too. A refusal lands on the same path a failure already did: FAULTY_PLACEHOLDER, which isEmpty reads as empty, with the reason in the LogSink. Nothing new leaks into somebody's front matter.
Trust reaches this pure module as a callback, and the default refuses. src/core cannot import vscode, so the answer arrives two ways, in this order: PlaceholderContext.trusted when the caller knows it, else the provider installed with setPlaceholderTrust() — the same shape as setActiveFolderResolver in src/config.ts. registerContentCommands installs the real one at activation, which is why it is not optional: a graph nobody wired up answers false and runs nothing. That is deliberate for the MCP process and for a plain node test, both of which should spawn nothing from a token.
folderForFile matches on path boundaries, longest prefix first. FM asked filePath.includes(folder.path), which lets /site/pages claim /tmp/copy-of/site/pages/x.md. A folder registered with a wildcard is matched against its pattern, so the answer does not depend on resolveFolders having run first.
The when clause hides, it never invents. All 10 operators are implemented; the four FM declares but never implements are absent from WhenOperator entirely. A comparison whose operands are not comparable (startsWith against a number) returns "visible" rather than guessing, and a field whose parent is hidden is hidden too. caseSensitive defaults to true.
The index and the metrics¶
A file with no front matter is not a page. buildIndex walks the registered folders (honouring excludeSubdir and excludePaths, deepest folder winning when two overlap), and skips anything whose front-matter block does not parse. Nothing it meets can throw: an unreadable file, a missing folder and a malformed block are all just absent from the result, with a line in the LogSink.
The cache is keyed by mtime and invalidated by configuration. A refresh over an unchanged tree re-reads nothing and returns the same PageEntry objects, by identity — that is both the fast path and how the tests prove zero re-parses. IndexCache.skipped remembers the files that had no front matter, without which every refresh would re-read every README.md in the repository forever, and IndexCache.fingerprint covers the other staleness: a settings change that alters the projection (a different title field, a different draft field) while every mtime stays put. The cache is rebuilt, never mutated, so a deleted file cannot linger in it. The shell owns where it is stored (INDEX_CACHE_KEY in workspaceState); asIndexCache is the guard for what comes back out.
changed is the permission to write the cache. buildIndex returns it alongside pages and cache: false means every candidate was reused and the candidate set is identical, so the rebuilt cache says nothing the one that was passed in did not. It is derived from the run's own counters plus a size comparison of the two maps — when nothing was parsed, every entry and every skip came out of the old cache by reuse, so equal sizes mean equal sets, and a shrunken map is a file that was deleted, renamed or excluded. The shell uses it to skip a workspaceState write that costs half a megabyte to a megabyte and a half per root on a real site, on every rebuild, most of which change nothing.
The cold path reads eight files at a time; the warm path still costs one stat and no read. Each candidate is resolved by a worker pool over a shared cursor (SCAN_CONCURRENCY = 8) into a ScanResult, and the results are folded back by candidate index in a second, sequential pass. That is what makes the concurrency invisible: pages[] stays sorted by path rather than by whichever file the disk answered first, a cache hit still returns the very same PageEntry object, and the log lines still come out in candidate order because the fold — not the worker — writes them. Measured over lifehacker.dev's 382 files: a cold scan went from ~45 ms to ~26 ms, a warm one from ~7.3 ms to ~5.6 ms.
slimPage is what crosses the wire. PageEntry.data is the whole front-matter block, which is right for the panel (it edits arbitrary fields) and wrong for every surface that only draws a row — a search reply over a real site carries about 1.2 MB of front matter nothing on the other side reads. PageSummary is the eight fields a row needs (relPath, absolute path, title, slug, date, draft, collection, modified), dates still strings. It carries no Zer0Config, so collection is reached by matching the longest suffix of the page's absolute folder against its workspace-relative path — the same answer pageToRecord computes with relPath(). PageSummary is declared in pageIndex.ts only until it moves to shared/types.ts with the rest of the cross-cutting types.
pageToRecord says "unknown" out loud. It is decision D9: .cms/ absence is a normal state, so a PageEntry is projected into the same ContentRecord the contract uses, with health: -1, freshness: 'unknown', and wordCount / headingCount at UNKNOWN_COUNT (-1) — the scan reads front matter and never bodies, and 0 there is not "we did not look" but "this article is empty", which the content tree and the MCP zer0_get_content answer both used to state as a fact about a two-thousand-word page. Render those two through countLabel, never raw. Under those two values isDistributable degrades to not a draft and has a title — the strongest claim a front-matter scan can support. A choice draft field whose value is neither a draft word nor a published word yields draft: null rather than a guess, because guessing is how a governed queue publishes something it should not have.
Article metrics are a line scan, not a syntax tree. getArticleDetails strips {{…}} shortcodes with FM's own regex, then walks the body once: fenced code is skipped whole, inline code and image alt text are dropped (mdast calls them inlineCode and a node property, so FM never counted them either), link text is kept, and each list item is its own paragraph. wordCount keeps FM's split(' ') over-count bug-for-bug — the 1,760-word target was tuned against it, and "fixing" it would move the goal for every article in a repository at once. Links split internal/external on the http prefix plus the site's own base URL.
SEO thresholds are FM's, including the two rules people trip over. A threshold of <= 0 switches its row off entirely (that is how a workspace disables a check), and article length is never validated — it carries no isValid, so it renders as an em dash. keywordAnalysis is exactly six checks; heading matching is a substring test for a multi-word keyword and an exact-word test for a single word; density uses FM's regex, with the keyword escaped so a ( in a keyword no longer throws out of the panel's render, and is null rather than NaN when there is nothing to divide by.
The audit, and the fix-it that never writes¶
audit.ts answers "what is wrong with this site's front matter", and schema.ts answers "according to whom". Decision D-D.
The thirteen rule ids belong to lifehacker.dev. AUDIT_RULE_IDS is lifted from that site's scripts/ci/lint_frontmatter.rb, spelled the way it spells them — missing-key:<k>, invalid-date, future-date, filename-date-mismatch, tags-not-array, no-front-matter, description-too-long, plus the six this console adds (unknown-choice, title-too-long, unknown-key, duplicate-slug, duplicate-permalink, unreadable-frontmatter). That site files a GitHub issue per finding and so does this console's triage lane; a vocabulary that differed by one character would file the same problem twice and close it once. A rule id is a contract with another repository. AUDIT_RULE_SPECS carries each one's severity and lane as data, and src/test/audit.test.ts asserts the id strings as literals rather than deriving them from the constant — a test built from the constant would only prove the constant agrees with itself.
Severity follows lifehacker; the lane follows the fix. A missing required key, an unparseable or future date, a filename that disagrees with its own front matter and a non-list tags block that site's merge gate, so they are errors. Its style nits are warnings. unknown-key is info. The lane is the .cms/ split (../contract/README.md): mechanical when fixFor can derive the value from the file itself — the date in its own name, the slug of its own title, a default its own content type declares — and substantive otherwise. Populating title, description or author is substantive however easy it looks, because writing title: '' is the same violation in quieter clothes rather than a repair. fields.ts's violationToIssue speaks the same vocabulary, so the panel's own required-field validation and the site audit dedupe against each other too.
auditPage says nothing about what it did not read (D9). block is the raw block when the caller opened the file and undefined when it only has the index's projection, and the two are different claims. no-front-matter needs an absent block and no projected keys — an absent block with keys means we were handed a projection, and accusing a file nobody opened would be inventing a fact. A block whose warnings are non-empty reports exactly those and suppresses every other check on that file, for the reason the channel exists. unknown-key fires only where a site declared a closed optional vocabulary; title-too-long and description-too-long fire only against a cap the site itself declared, because the SEO panel's defaults are a budget and turning a budget into a finding on every page is noise wearing a rule's clothes. Nothing here computes a health score: SiteAudit has no such field, and pageToRecord still answers -1 beside these issues.
Dates stay strings, in the audit too. No front-matter date is parsed into a Date and written back. datePartOf matches one of two shapes — a bare YYYY-MM-DD, or a date with a time and an optional zone — then checks the calendar arithmetically (leap years included) and returns a slice of the string that was already there. future-date compares two YYYY-MM-DD prefixes lexicographically, which is what an ISO date is for. The only Date in the module is the now the caller passed.
duplicate-slug is grouped by the page's own directory, and skips structural stems. Grouping by the registered content folder reported ten collisions on lifehacker.dev that its build does not have: one recursive folder holds several of a generator's routes, and /hacks/:slug/ and /tools/:slug/ are two namespaces. index and README are skipped outright — index is a position in a directory, not a slug. duplicate-permalink is site-wide, because a permalink is, and a trailing slash is not a difference. Both live in auditSite; neither can be produced by looking at one file.
dryRunFix renders the bytes and writes none of them. It goes through the ordinary updateFrontMatterKeys → stitch path with writeArticle's own BOM/prefix handling, so the preview is what a write would produce rather than an approximation, and a caller shows the two strings in a diff and asks a person. It refuses in exactly the cases line surgery already declines — TOML and JSON, and a nested path whose parent holds a scalar — plus one more: a block with parser warnings is refused outright, because rewriting a file we did not understand is how an anchor becomes a literal string in somebody's repository. fixFor refuses the same file one step earlier, so "is there a fix?" and "show me the fix" never disagree.
Whose schema is it¶
schema.ts ingests the file each site already keeps rather than re-typing it here, because a fourth answer would drift from all three:
| Site | File | Gates CI? |
|---|---|---|
| zer0-mistakes | .github/config/frontmatter_schema.yml |
yes — scripts/lint-pages reads it |
| it-journey | .cms/config.yml + .cms/schema/content-schema.json |
no — its own header says it is stricter than the gate and never fails a build |
| this project | zer0.json content types with required: true |
no |
Precedence: the source that gates CI wins (frontmatter_schema.yml 3 → cms-config 2 → zer0.json 1 → profile-default 0 → none -1). Not "the most specific declaration" but "the declaration a contributor's pull request will actually be judged by": an audit exists to predict the red X on somebody's PR, and a schema that let a local file lower the bar CI enforces would report green on work about to fail. zer0.json still owns field types, defaults and choices — that is ContentType, which auditPage reads directly — it just does not get to overrule the gate.
Precedence resolves per collection. A site can gate posts in CI and describe quests only in .cms/; dropping the second would report less than we know, and silence about a collection is not a claim that it has no rules. Within one collection the winner is taken whole, with no union of required keys, because a union is exactly how the editor invents a requirement CI does not have. global.required comes from the winner alone — an empty list said "none", and a cap is borrowable where a bar is not. Constraints fill in per field, since a cap nobody stated is genuinely unstated.
One gap is deliberate and named rather than guessed at: global.canonical_fields (zer0-mistakes' updated → lastmod) is a rename map and SiteSchema has no slot for one. Both spellings go into every collection's optional list so unknown-key does not fire on a renamed key, and the mapping itself is dropped. Adding global.canonicalFields to SiteSchema in shared/types.ts would close it.
Tests¶
src/test/core.test.ts covers the parser (nested maps, block scalars, flow collections, coercion, every documented non-goal, and one warnings case per unsupported construct), updateFrontMatterKeys (comment preservation counted line by line, key add/delete, the null fallback signal), serializeFrontMatter in both directions of each option, and the readArticle → writeArticle byte-identical no-op on all three dialects.
src/test/audit.test.ts runs auditSite once over src/test/fixtures/audit/ — a miniature site with one page per rule id and a control page that must keep producing zero findings — and checks each rule against the file named for it. It also runs the audit over src/test/fixtures/workspace/, which yields zero errors and has to keep doing so: a rule that fires on a well-formed site is a rule that would fire on hundreds of good files somewhere real. The schema readers are tested against verbatim copies of the two sister sites' own files (src/test/fixtures/audit/schemas/, provenance in FIXTURE-SOURCES.md), because a reader tested against a schema we wrote ourselves proves only that we can read our own handwriting. And the whole fixture tree is hashed before and after every fix-it the suite runs, so "dryRunFix never writes" is a comparison rather than a promise.