diff --git a/.changeset/frontmatter-block-once.md b/.changeset/frontmatter-block-once.md new file mode 100644 index 0000000000..453c062ef6 --- /dev/null +++ b/.changeset/frontmatter-block-once.md @@ -0,0 +1,8 @@ +--- +"@schlessera/brain-common": patch +"@schlessera/brain": patch +"@schlessera/brain-ui-sdk": patch +"@schlessera/brain-ui-react": patch +--- + +Where a document's frontmatter block starts and ends now has one implementation, `frontmatterBlock` in the new internal entry `@schlessera/brain-common/internal/frontmatter-block` (#2507). It follows the rule `parseFrontmatter` reads by. `frontmatterLength` moved there too, and core re-exports it. Five fixes follow. `brain validate` accepts a document whose frontmatter follows a byte order mark, and reports a `----` first line as missing frontmatter. `brain import --stamp` skips a file whose frontmatter follows a byte order mark instead of stamping a second block over it. The OKF bundle check sees frontmatter after a byte order mark. `brain hygiene` reads and keeps such a log file's frontmatter instead of rewriting it as body. `brain tags --apply` and the frontmatter key editor share one bounds and scalar reader. One rule is stricter than before: hygiene now refuses a log file whose closing fence has text after the dashes (`----`, `---x`). The public `splitFrontmatter` from `@schlessera/brain-ui-react` now reads a block that follows a byte order mark, has trailing whitespace after its opening fence, or is closed by a fence at the end of the file. It still returns an unclosed block as body. `bun run lint` refuses a frontmatter fence detected by hand in package source. The new entry, and its re-export from the ui-sdk's `internal/client`, are internal and carry no compatibility promise. diff --git a/api-report/common.txt b/api-report/common.txt index 9bb9440cc0..cb47c3621a 100644 --- a/api-report/common.txt +++ b/api-report/common.txt @@ -34,6 +34,11 @@ export "./internal/frontmatter" (./src/frontmatter-parse.ts) type ParsedFrontmatter parseFrontmatter +export "./internal/frontmatter-block" (./src/frontmatter-block.ts) + type FrontmatterBlock + frontmatterBlock + frontmatterLength + export "./internal/governance-policy" (./src/governance-policy.ts) type AnchoredGovernancePolicy BUILTIN_GOVERNANCE_POLICY diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index 170ac517a5..01e19f5414 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -1269,6 +1269,7 @@ export "./internal" (./src/internal.ts) workerSandboxWarnings export "./internal/client" (./src/internal-client.ts) + type FrontmatterBlock type LinkEdit type ShareTargetError askUserFormPayload @@ -1281,6 +1282,7 @@ export "./internal/client" (./src/internal-client.ts) defaultAsrClientRegistry defaultToolRendererRegistry describeRetry + frontmatterBlock handleShareTargetRequest isShareTargetRequest pruneStoredShares diff --git a/docs/decisions/frontmatter-parsing.md b/docs/decisions/frontmatter-parsing.md index 410cd3cf75..db2380ab91 100644 --- a/docs/decisions/frontmatter-parsing.md +++ b/docs/decisions/frontmatter-parsing.md @@ -54,7 +54,7 @@ maintainer chose option B on #142 on 2026-09-28. - Rule 1: gray-matter may be loaded (`import`, `import type`, `export … from`, `import x = require()`, `require()`, `import()`, subpaths) only by the files in its `ALLOWED` list (`ALLOWED`, - `scripts/check-frontmatter-parse.ts:40-62`). + `scripts/check-frontmatter-parse.ts:50-72`). - Rule 2: inside those files, the default binding may only be called with an object literal where gray-matter takes its options, or named in a type. Aliases, re-exports, `matter.read`, `matter.cache` and variable options @@ -105,6 +105,44 @@ This repairs the documented data-only input guarantee. It changes no supported YAML meaning, envelope, approval authority, descriptor read, size limit or last-valid fallback. See the [file-layer contract](../integration-contract/frontmatter.md#file-layer-contracts). +## Where the block starts and ends (#2507, 2026-11-03) + +Finding the fences without parsing the YAML has one answer too: +`frontmatterBlock` (`frontmatterBlock`, +`packages/common/src/frontmatter-block.ts:42-55`), reached through +`@schlessera/brain-common/internal/frontmatter-block`. It returns the offsets +of the opening fence, the inner YAML lines and the end of the block, plus +whether a closing fence was found, by gray-matter's rule: an optional byte +order mark, `---` not followed by a fourth `-`, the first `\n---` after it, and +one line ending after that. It imports nothing, so ui-react reaches it through +ui-sdk's browser-safe `internal/client` entry. `frontmatterLength` moved with +it; core re-exports it. A table-driven test holds it to `parseFrontmatter` on a +byte order mark, CRLF, trailing whitespace after either fence, a closing fence +at the end of the file, `----`, a leading blank line, an unclosed block, an +empty block and a `...` line. + +Nine places had their own rule. Each now asks `frontmatterBlock`, and each +default is the parser's answer, except where a stricter answer protects a +write: + +| Site | Disagreed on | Rule now | +| --- | --- | --- | +| `brain validate` | BOM (reported `frontmatter-missing`); `----` counted as a fence | the parser's | +| `brain import --stamp` | BOM (stamped a second block over the first, which became body) | the parser's | +| OKF bundle check | BOM (rejected explicitly: a marked concept "missing frontmatter", a marked `index.md` block let through) | the parser's | +| generated regions | none in effect; its search ignored the BOM offset | the parser's, still refusing an unclosed block | +| `brain tags --apply` and the key editor | two `frontmatterBounds`/`readScalar` pairs; the tags copy searched back from the block's end and took the closing fence into the block when a `---` rule followed it | one pair, in `frontmatter-edit.ts`; an unclosed block has no bounds | +| hygiene log files | BOM (frontmatter read as body and rewritten) | the parser's opening; **stricter closing**: a block not closed by a `---` line with only whitespace after it is refused, including `----`, `---x` and `...` closers the parser would end at or run past, because hygiene rewrites the body | +| ui-react `splitFrontmatter` | BOM; a closing fence at the end of the file | the parser's, except that an unclosed block is shown as body rather than swallowed, so the viewer never hides text | +| ui-server policy review `split` | accepts a `...` closer | unchanged for now; open on #2507 | + +Rule 3 of the gate (`scanFences`, `scripts/check-frontmatter-parse.ts:222-252`) +refuses a hand-written detector in package source: a non-multiline regex +anchored at a leading `---` (a BOM before it included), `startsWith("---…")` +and `indexOf`/`lastIndexOf("\n---…")`. Files that emit or post-process a fence +they wrote, and the pending policy splitter, are listed in `FENCE_ALLOWED` +with a reason each. + ## Rejected alternatives - **Pass `{}` at every call site (O1).** This was already half-done, and the @@ -158,6 +196,9 @@ file is parsed once per run. - An edit to the helper is made once, in `packages/common`. - A new entry in `ALLOWED` needs a reason that says why the file cannot reach the cache. "It only parses once" is not one: the cache is process-wide. +- A new entry in `FENCE_ALLOWED` needs a reason that says why the file is not + reading an arbitrary document's fences: it emits them, or it post-processes + text it emitted. ## Superseded: a copy per parsing package diff --git a/docs/decisions/hygiene-review.md b/docs/decisions/hygiene-review.md index 9bbb297a99..366642bde0 100644 --- a/docs/decisions/hygiene-review.md +++ b/docs/decisions/hygiene-review.md @@ -43,8 +43,8 @@ or a snooze reset by an unrelated edit, makes the owner's decision temporary. Reuse the existing markdown log and deterministic CLI operations. A candidate already carries category, path and stable evidence (`HygieneCandidate`, -`packages/core/src/lib/hygiene.ts:68-84`), and its ID derives from those fields -(`hygieneId`, `packages/core/src/lib/hygiene.ts:181-184`). Those primitives do not +`packages/core/src/lib/hygiene.ts:69-85`), and its ID derives from those fields +(`hygieneId`, `packages/core/src/lib/hygiene.ts:182-185`). Those primitives do not by themselves supply validation-to-hygiene equivalence, priority selection or review dispositions. The CLI exposes reconciliation, listing and deterministic selection (`hygieneCommand`, `packages/core/src/cli/commands/hygiene.ts:221-223`). @@ -135,11 +135,11 @@ shapes are in [the integration contract](../integration-contract/package-api.md# **Equivalence map.** Each `brain validate` rule becomes a candidate with a category and ID evidence (`VALIDATION_JOIN`, -`packages/core/src/lib/hygiene.ts:199-212`). Validation gives the join a +`packages/core/src/lib/hygiene.ts:200-213`). Validation gives the join a structured detail, so the message is never read (`export interface ValidationDetail`, -`packages/core/src/lib/validate.ts:43-51`). Candidates are one finding exactly +`packages/core/src/lib/validate.ts:44-52`). Candidates are one finding exactly when category, path and evidence agree, and the join does not depend on their -order (`canonicalFindings`, `packages/core/src/lib/hygiene.ts:283-333`). +order (`canonicalFindings`, `packages/core/src/lib/hygiene.ts:284-334`). | Validation rule | Category | ID evidence | Joins | | --- | --- | --- | --- | @@ -161,7 +161,7 @@ a source states it; otherwise it stays unknown. **Evidence fingerprints.** A fingerprint is 12 hex digits of SHA-1 over the category and a hash of each field below (`FINGERPRINT_FIELDS`, -`packages/core/src/lib/hygiene.ts:246-259`). Line numbers, messages, other +`packages/core/src/lib/hygiene.ts:247-260`). Line numbers, messages, other document content and age are never in it. | Category | Fingerprint fields | @@ -180,7 +180,7 @@ an invalidation can name the fields that changed. entries in `context/hygiene/dismissed.md`, snoozed ones in `snoozed.md`. Each records its time and the fingerprint it applied to. `until:` takes an ISO date-time or a date; a date is due at the start of that UTC day, as before -(`function dueAt`, `packages/core/src/lib/hygiene.ts:863-873`). A recorded +(`function dueAt`, `packages/core/src/lib/hygiene.ts:872-882`). A recorded fingerprint that no longer matches reopens the finding at once, with an `invalidated:` receipt naming the changed fields and the disposition's date. A snooze that comes due reopens it with no receipt. @@ -190,7 +190,7 @@ identity), the new finding carries the receipt only when the pairing is unambiguous. In one run, exactly one disposition in force with that category and path stops being detected, and exactly one new finding with them appears (`if (prior.length === 1 && siblings.length === 1)`, -`packages/core/src/lib/hygiene.ts:1513`). Otherwise the new finding opens +`packages/core/src/lib/hygiene.ts:1522`). Otherwise the new finding opens without one. Either way the old disposition does not suppress it. Entries moved by hand carry no fingerprint, so they keep their earlier behaviour. @@ -209,11 +209,11 @@ made (K1 A). It lives in `context/hygiene/kept.md`, which is never created empty. It holds only while the original's fingerprint is unchanged and its copy is a contained regular file outside `.brain/` and `workspaces/` that `media.track` keeps. Otherwise the original reopens with an `invalidated:` -receipt (`keptInvalidity`, `packages/core/src/lib/hygiene.ts:998-1008`). +receipt (`keptInvalidity`, `packages/core/src/lib/hygiene.ts:1007-1017`). Sync's count and review use one read-only function that applies these predicates to the log as it stands rather than trusting the file an entry sits -in (K2 B; `mediaReviewCounts`, `packages/core/src/lib/hygiene.ts:1753-1768`). +in (K2 B; `mediaReviewCounts`, `packages/core/src/lib/hygiene.ts:1762-1777`). Leave pending is a per-pass deferral in review state, never a log state: it skips the finding while its fingerprint holds, and the finding still counts. @@ -241,7 +241,7 @@ permission, premise revalidation and a real post-apply check before success. Do not implement dismissal by marking a still-detected finding resolved: existing reconciliation reopens such an entry (`const prev = field(entry, "resolved-by")`, -`packages/core/src/lib/hygiene.ts:1487-1490`). Keep review disposition distinct from +`packages/core/src/lib/hygiene.ts:1496-1499`). Keep review disposition distinct from actual check success and from notification acknowledgement. Markdown remains authoritative for findings, dispositions and confirmed content diff --git a/docs/decisions/mechanical-hygiene.md b/docs/decisions/mechanical-hygiene.md index 980bb9807d..57a88d2af7 100644 --- a/docs/decisions/mechanical-hygiene.md +++ b/docs/decisions/mechanical-hygiene.md @@ -36,10 +36,10 @@ scratch state are excluded from source-byte scoring; an input hygiene file remains protected. The prototype reuses table detection (`indexTableLag`, -`packages/core/src/lib/hygiene.ts:541-583`), scalar table rendering +`packages/core/src/lib/hygiene.ts:542-584`), scalar table rendering (`renderRegistry`, `packages/core/src/lib/index-registry.ts:117-185`) and the surgical frontmatter editor (`editFrontmatter`, -`packages/core/src/lib/frontmatter-edit.ts:216-224`). It intentionally refuses +`packages/core/src/lib/frontmatter-edit.ts:232-240`). It intentionally refuses wiki links and an entire index containing an unsafe row. ## Held-out quality and reliability @@ -134,7 +134,7 @@ one explicit providerless CLI planner/apply operation for this supported grammar, with `--json` and dry-run output, followed by the existing reconciliation. Re-read every consulted input and use the existing unchanged-source writer (`replaceIfUnchanged`, -`packages/core/src/lib/hygiene.ts:1236-1246`) before application. Keep registry +`packages/core/src/lib/hygiene.ts:1245-1255`) before application. Keep registry ownership, inbox/archive exclusions and all unhandled cases visible as log-only. The skill delegates these two mechanical operations; canonical judgment remains with it. That follow-up needs the additive contract documentation and normal diff --git a/docs/decisions/module-instruction-ownership.md b/docs/decisions/module-instruction-ownership.md index fd8e77c703..0848854686 100644 --- a/docs/decisions/module-instruction-ownership.md +++ b/docs/decisions/module-instruction-ownership.md @@ -30,7 +30,7 @@ The existing module mechanism builds contributions from validated config (`ModuleContribution`, `packages/core/src/lib/module-types.ts:136-164`). The generated-region helper replaces a whole named block and preserves bytes outside it (`replaceGeneratedRegion`, -`packages/core/src/lib/generated-regions.ts:99-120`). Neither a shared block +`packages/core/src/lib/generated-regions.ts:100-121`). Neither a shared block nor its heading establishes which module owns each paragraph. The CLI needs an authoritative source and explicit ownership to remove, regenerate and measure module instructions deterministically. diff --git a/docs/decisions/voice-permission.md b/docs/decisions/voice-permission.md index 98f58d7964..012ab4c409 100644 --- a/docs/decisions/voice-permission.md +++ b/docs/decisions/voice-permission.md @@ -255,7 +255,7 @@ as its allowlist and declares both `enforceAllowedTools` and `noGrantSurface`. | `mcp__brain__brain_graph` | Read-only. | | `mcp__brain__jobs_review` | Read-only query over the owner's local jobs queue, returning at most 50 summaries. No egress: it does not scrape, fetch listing URLs, change review decisions or create a missing database. Admitted 2026-10-01 (#605). | | `mcp__brain-ui__brain_add` | Creates a new document. The single most valuable eyes-free action there is — capture. A create destroys nothing: the worst case is a document the user did not want, which appears in Files and is removable. | -| `mcp__brain-ui__brain_update` | Edits an existing document. "Add this to my note about X" is the second most valuable eyes-free action, and the handler's shape is why it is safe enough to allow: it **never rewrites the body**, it only appends to it (`const appendTo`, `packages/core/src/lib/frontmatter-edit.ts:303-308`), so no prose can be lost. The exact bound on what it *can* destroy: the six frontmatter params are independent optionals on one call (`summary: z.string()`, `packages/core/src/mcp-server.ts:428-433`), applied independently (`input.summary !== undefined`, `packages/core/src/lib/ops/write.ts:88-100`), so **a single call can overwrite all six** — and `tags` replaces the whole tag list rather than merging into it (the terminal MCP accepts a comma-separated string, while the hosted route accepts a string array; `input.tags !== undefined`, `packages/core/src/lib/ops/write.ts:91`), while `deadline` and `next_review` take `""` as *delete the field* (`input.deadline !== undefined`, `packages/core/src/lib/ops/write.ts:92-99`). `updated` is bumped unconditionally (`updates.updated = updated`, `packages/core/src/lib/ops/write.ts:115`). None of it is checkpointed, so git recovers a prior value only if the document was committed. The claim this row rests on is therefore "loses no prose, and at most the six declared frontmatter fields, recoverable only if committed" — not "recoverable". `status` is the field that matters and it is handled separately below. | +| `mcp__brain-ui__brain_update` | Edits an existing document. "Add this to my note about X" is the second most valuable eyes-free action, and the handler's shape is why it is safe enough to allow: it **never rewrites the body**, it only appends to it (`const appendTo`, `packages/core/src/lib/frontmatter-edit.ts:319-324`), so no prose can be lost. The exact bound on what it *can* destroy: the six frontmatter params are independent optionals on one call (`summary: z.string()`, `packages/core/src/mcp-server.ts:428-433`), applied independently (`input.summary !== undefined`, `packages/core/src/lib/ops/write.ts:88-100`), so **a single call can overwrite all six** — and `tags` replaces the whole tag list rather than merging into it (the terminal MCP accepts a comma-separated string, while the hosted route accepts a string array; `input.tags !== undefined`, `packages/core/src/lib/ops/write.ts:91`), while `deadline` and `next_review` take `""` as *delete the field* (`input.deadline !== undefined`, `packages/core/src/lib/ops/write.ts:92-99`). `updated` is bumped unconditionally (`updates.updated = updated`, `packages/core/src/lib/ops/write.ts:115`). None of it is checkpointed, so git recovers a prior value only if the document was committed. The claim this row rests on is therefore "loses no prose, and at most the six declared frontmatter fields, recoverable only if committed" — not "recoverable". `status` is the field that matters and it is handled separately below. | | `Read`, `Glob`, `Grep` | Read-only over the brain repo, for the questions the brain tools do not cover. No mutation, no egress. | | `WebSearch`, `WebFetch` | Read-only egress. Kept, with the exposure stated below. | | the bridge tools, minus the mask editor | `ask_user`, `get_current_location`, `query_activity`, `show_block`, `turn_temp` are auto-allowed today and none of them is a permission decision (the same `allowed.push` block, from `const allowed`, `sdk-options.ts:194-219`). `request_image_mask` needs the user to paint a region, so it needs eyes; it is out. | diff --git a/docs/investigations/audit-capability-investigation.md b/docs/investigations/audit-capability-investigation.md index 76b61f09dc..84758d461a 100644 --- a/docs/investigations/audit-capability-investigation.md +++ b/docs/investigations/audit-capability-investigation.md @@ -74,7 +74,7 @@ Planning parses complete child metadata (`planRegistry`, `packages/core/src/lib/index-registry.ts:210-262`). Tag migration is real code (`applyTagChanges`, -`packages/core/src/lib/tags-apply.ts:435-497`): configured alias chains and +`packages/core/src/lib/tags-apply.ts:381-443`): configured alias chains and eligible variant groups determine the plan; raw tag entries are changed while other bytes, including `updated`, remain. The CLI opens its index before writes, then reindexes and accepts only the exact rewritten bytes. Literal configured @@ -150,8 +150,8 @@ Unsupported, missing, invalid and no-op cases stay manual/unavailable. Reindex after authoritative Markdown changes, then rerun the finding's actual check; partial repair or a failed check never becomes success. -Reuse (`candidateFromAudit`, `packages/core/src/lib/hygiene.ts:351-391`) and -(`hygieneId`, `packages/core/src/lib/hygiene.ts:181-184`) without inventing another +Reuse (`candidateFromAudit`, `packages/core/src/lib/hygiene.ts:352-392`) and +(`hygieneId`, `packages/core/src/lib/hygiene.ts:182-185`) without inventing another identity or disposition store. The [hygiene-review policy](../decisions/hygiene-review.md) binds #597's canonical equivalence, severity/known-urgency ordering and relevant evidence invalidation. This investigation chooses no mappings, review controls diff --git a/packages/common/README.md b/packages/common/README.md index ad1ec100f9..3e6d19da57 100644 --- a/packages/common/README.md +++ b/packages/common/README.md @@ -11,6 +11,7 @@ one; it arrives as their dependency. | --- | --- | | `@schlessera/brain-common/internal/env` | The environment descriptor contract (`EnvVarSpec`, `DynamicEnvReadSpec`), `readEnvVar`, and the boolean parsers `envFlag` and `envPresent`. Each package keeps its own `src/config/env.ts` chokepoint on top of it. | | `@schlessera/brain-common/internal/frontmatter` | `parseFrontmatter`, the only door to gray-matter's parser. It always passes an options object, so gray-matter's process-wide cache is never read or written ([decision](../../docs/decisions/frontmatter-parsing.md)). | +| `@schlessera/brain-common/internal/frontmatter-block` | `frontmatterBlock` and `frontmatterLength`: where a frontmatter block starts and ends, by the rule `parseFrontmatter` reads by, without parsing it. It imports nothing, so browser code can use it; every package that needs only the fences asks it (#2507). | | `@schlessera/brain-common/internal/worker-areas` | The hosted worker's write-area names and the rules stated about them: turn temp is never linked, the link rule, and the read-only-brain rule. The ui-sdk's sandbox note and core's `brain` CLI refusal both render them, so the refusal repeats the note word for word (#1654, admitted by #1693). | | `@schlessera/brain-common/internal/protected-paths` | The protected worker path tiers shared by core policy validation and the sandbox. | | `@schlessera/brain-common/internal/governance-policy` | Data-only policy schema, defaults, parsing and anchored reads shared by the core CLI and hosted server (#1744). The server can read policy without installing its optional core peer. Its policy writer reads and re-checks the file through the same descriptor-anchored reader (#2508). | diff --git a/packages/common/package.json b/packages/common/package.json index 314678be3e..50b30e59d8 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -36,6 +36,11 @@ "types": "./dist/frontmatter-parse.d.ts", "default": "./dist/frontmatter-parse.js" }, + "./internal/frontmatter-block": { + "bun": "./src/frontmatter-block.ts", + "types": "./dist/frontmatter-block.d.ts", + "default": "./dist/frontmatter-block.js" + }, "./internal/worker-areas": { "bun": "./src/worker-areas.ts", "types": "./dist/worker-areas.d.ts", diff --git a/packages/common/src/frontmatter-block.ts b/packages/common/src/frontmatter-block.ts new file mode 100644 index 0000000000..13f15f5212 --- /dev/null +++ b/packages/common/src/frontmatter-block.ts @@ -0,0 +1,63 @@ +// Internal to brain-kit: reached through +// `@schlessera/brain-common/internal/frontmatter-block`, with no compatibility +// promise. Where a document's frontmatter block starts and ends, by the rule +// `parseFrontmatter` (gray-matter 4.0.3) reads it. It imports nothing, so a +// browser bundle can use it (ui-react reaches it through ui-sdk's +// `internal/client`). Every site that needs the fences, but not the YAML, +// asks this instead of writing its own regex (#2507); +// scripts/check-frontmatter-parse.ts refuses a hand-written one. + +/** + * Offsets of a frontmatter block in the original text: + * + * - `start`: where the opening `---` is (1 after a byte order mark, else 0). + * - `innerStart`: after the opening fence's line ending (the end of the text + * when that line has none). + * - `innerEnd`: up to the closing fence, its preceding line ending included, + * so `text.slice(innerStart, innerEnd)` is the block's YAML lines; the end + * of the text when the block is not closed. + * - `end`: after the closing fence and one line ending following it, which is + * where `parseFrontmatter`'s `content` starts; the end of the text when the + * block is not closed. + * - `closed`: whether a closing fence was found. gray-matter reads an + * unclosed block to the end of the file; a writer should refuse one. + */ +export interface FrontmatterBlock { + start: number; + innerStart: number; + innerEnd: number; + end: number; + closed: boolean; +} + +/** + * The frontmatter block, or null when the text has none. gray-matter's rule: + * after a byte order mark, which it strips, the text opens with `---` not + * followed by a fourth `-` (anything else on that line is a language name); + * the block runs to the first `\n---` after it, wherever on its line that + * `---` is followed by more text, and one `\r` and one `\n` after the fence + * belong to it. A leading blank line means no frontmatter; a `...` line does + * not close it. + */ +export function frontmatterBlock(text: string): FrontmatterBlock | null { + const start = text.charCodeAt(0) === 0xfeff ? 1 : 0; + if (!text.startsWith("---", start) || text.charAt(start + 3) === "-") return null; + const newline = text.indexOf("\n", start); + const close = text.indexOf("\n---", start + 3); + if (close === -1) { + return { start, innerStart: newline === -1 ? text.length : newline + 1, innerEnd: text.length, end: text.length, closed: false }; + } + let end = close + 4; + if (text[end] === "\r") end++; + if (text[end] === "\n") end++; + return { start, innerStart: newline + 1, innerEnd: close + 1, end, closed: true }; +} + +/** + * Length of the frontmatter block, `frontmatterBlock(text).end`, or 0 when + * there is none. The length counts a byte order mark, so it is an offset into + * the original text. + */ +export function frontmatterLength(text: string): number { + return frontmatterBlock(text)?.end ?? 0; +} diff --git a/packages/common/tests/frontmatter-block.test.ts b/packages/common/tests/frontmatter-block.test.ts new file mode 100644 index 0000000000..ee92820e7b --- /dev/null +++ b/packages/common/tests/frontmatter-block.test.ts @@ -0,0 +1,52 @@ +/** + * `frontmatterBlock` finds the fences `parseFrontmatter` reads by (#2507). + * Every row is checked against the parser itself, so a change to either side + * that makes them disagree fails here. + */ + +import { describe, expect, test } from "bun:test"; + +import { frontmatterBlock, frontmatterLength } from "../src/frontmatter-block"; +import { parseFrontmatter } from "../src/frontmatter-parse"; + +const BOM = "\uFEFF"; + +const rows: Array<{ name: string; text: string; block: ReturnType; data?: Record }> = [ + { name: "plain LF", text: "---\ntitle: a\n---\nbody\n", block: { start: 0, innerStart: 4, innerEnd: 13, end: 17, closed: true }, data: { title: "a" } }, + { name: "byte order mark", text: `${BOM}---\ntitle: a\n---\nbody\n`, block: { start: 1, innerStart: 5, innerEnd: 14, end: 18, closed: true }, data: { title: "a" } }, + { name: "CRLF", text: "---\r\ntitle: a\r\n---\r\nbody\r\n", block: { start: 0, innerStart: 5, innerEnd: 15, end: 20, closed: true }, data: { title: "a" } }, + { name: "trailing whitespace after the opening fence", text: "--- \ntitle: a\n---\nbody\n", block: { start: 0, innerStart: 5, innerEnd: 14, end: 18, closed: true }, data: { title: "a" } }, + // gray-matter ends the block at the dashes; the whitespace starts the content. + { name: "trailing whitespace after the closing fence", text: "---\ntitle: a\n--- \nbody\n", block: { start: 0, innerStart: 4, innerEnd: 13, end: 16, closed: true }, data: { title: "a" } }, + { name: "closing fence at the end of the file", text: "---\ntitle: a\n---", block: { start: 0, innerStart: 4, innerEnd: 13, end: 16, closed: true }, data: { title: "a" } }, + { name: "four dashes are not a fence", text: "----\ntitle: a\n----\nbody\n", block: null }, + { name: "a leading blank line means no frontmatter", text: "\n---\ntitle: a\n---\nbody\n", block: null }, + { name: "no frontmatter", text: "# Title\n", block: null }, + { name: "unclosed block runs to the end", text: "---\ntitle: a\n", block: { start: 0, innerStart: 4, innerEnd: 13, end: 13, closed: false }, data: { title: "a" } }, + { name: "empty block", text: "---\n---\nbody\n", block: { start: 0, innerStart: 4, innerEnd: 4, end: 8, closed: true }, data: {} }, + // The first `\n---` closes; the next `---` line is a rule in the body. + { name: "a rule right after the closing fence", text: "---\ntitle: a\n---\n---\nbody\n", block: { start: 0, innerStart: 4, innerEnd: 13, end: 17, closed: true }, data: { title: "a" } }, + // A `...` line does not close a block: everything to the end is frontmatter. + { name: "a ... line is not a closer", text: "---\ntitle: a\n...\n", block: { start: 0, innerStart: 4, innerEnd: 17, end: 17, closed: false }, data: { title: "a" } }, +]; + +describe("frontmatterBlock agrees with parseFrontmatter", () => { + for (const row of rows) { + test(row.name, () => { + const block = frontmatterBlock(row.text); + expect(block).toEqual(row.block); + expect(frontmatterLength(row.text)).toBe(block?.end ?? 0); + const parsed = parseFrontmatter(row.text, { dataOnly: true }); + if (!block) { + expect(parsed.matter).toBe(""); + expect(parsed.data).toEqual({}); + return; + } + // What the parser treats as body is exactly what follows the block. + expect(parsed.content).toBe(row.text.slice(block.end)); + // What it treats as YAML is exactly the block's inner lines. + expect(parsed.matter.trim()).toBe(row.text.slice(block.innerStart, block.innerEnd).trim()); + expect(parsed.data).toEqual(row.data!); + }); + } +}); diff --git a/packages/core/src/cli/commands/import.ts b/packages/core/src/cli/commands/import.ts index 4c88a47772..a6f8bf8f55 100644 --- a/packages/core/src/cli/commands/import.ts +++ b/packages/core/src/cli/commands/import.ts @@ -2,6 +2,8 @@ import { readFileSync, statSync } from "fs"; import { resolve } from "path"; import { Glob } from "bun"; +import { frontmatterBlock } from "@schlessera/brain-common/internal/frontmatter-block"; + import { stringifyDocument } from "../../lib/frontmatter.js"; import { safeResolve, writeFileSafely } from "../../lib/safe-path.js"; import type { CoreCommand } from "../types.js"; @@ -48,7 +50,9 @@ export const importCommand: CoreCommand = { const full = resolve(base, rel); try { const raw = readFileSync(full, "utf-8"); - if (raw.startsWith("---")) { + // Frontmatter as the indexer finds it (#2507): a byte order mark + // before the fence still counts, so that block is never stamped over. + if (frontmatterBlock(raw)) { skipped.push(rel); continue; } diff --git a/packages/core/src/lib/document-parts.ts b/packages/core/src/lib/document-parts.ts index c5c96ec409..e9b1624913 100644 --- a/packages/core/src/lib/document-parts.ts +++ b/packages/core/src/lib/document-parts.ts @@ -3,6 +3,8 @@ import remarkGfm from "remark-gfm"; import remarkParse from "remark-parse"; import { unified } from "unified"; +import { frontmatterLength } from "@schlessera/brain-common/internal/frontmatter-block"; + import { caseFold } from "./case-fold.js"; import { estimateTokens } from "./chunker.js"; @@ -65,22 +67,10 @@ const parser = unified().use(remarkParse).use(remarkGfm); /** * Length of the frontmatter block, by the rule gray-matter applies when core - * reads a document: after a byte order mark, which gray-matter strips, the - * file opens with `---` not followed by a fourth `-`, and the block runs to - * the first `\n---` (to the end of the file if there is none), plus one line - * ending after it. The length counts the mark, so it is an offset into the - * original text. + * reads a document. It lives with `frontmatterBlock` next to `parseFrontmatter` + * in brain-common, so every site that finds the fences agrees (#2507). */ -export function frontmatterLength(text: string): number { - const bom = text.charCodeAt(0) === 0xfeff ? 1 : 0; - if (!text.startsWith("---", bom) || text.charAt(bom + 3) === "-") return 0; - const close = text.indexOf("\n---", bom + 3); - if (close === -1) return text.length; - let end = close + 4; - if (text[end] === "\r") end++; - if (text[end] === "\n") end++; - return end; -} +export { frontmatterLength } from "@schlessera/brain-common/internal/frontmatter-block"; interface LocatedHeading { level: number; diff --git a/packages/core/src/lib/frontmatter-edit.ts b/packages/core/src/lib/frontmatter-edit.ts index 94b370b2e4..f0e07cdfd9 100644 --- a/packages/core/src/lib/frontmatter-edit.ts +++ b/packages/core/src/lib/frontmatter-edit.ts @@ -14,48 +14,64 @@ */ import { parseFrontmatter } from "@schlessera/brain-common/internal/frontmatter"; +import { frontmatterBlock, frontmatterLength } from "@schlessera/brain-common/internal/frontmatter-block"; -import { frontmatterLength } from "./document-parts.js"; import { stringifyDocument } from "./frontmatter.js"; /** A new value: a string, a list of strings (written in flow style), or null to remove the key. */ export type FrontmatterValue = string | string[] | null; -interface Token { +/** A scalar's offsets in the block, quotes included, its quote, and its value with quotes and escapes read. */ +export interface ScalarToken { start: number; end: number; quote: '"' | "'" | null; + value: string; } -/** The frontmatter's inner text: after the opening `---` line, up to the closing `---` line. */ -function frontmatterBounds(text: string): { start: number; end: number } | null { - const length = frontmatterLength(text); - if (length === 0) return null; - // The first `\n---` after the opening fence, as frontmatterLength finds it: - // a later `---` or `----` line is a horizontal rule in the body. - const bom = text.charCodeAt(0) === 0xfeff ? 1 : 0; - const close = text.indexOf("\n---", bom + 3); - const start = text.indexOf("\n") + 1; - return close !== -1 && start > 0 && start <= close + 1 ? { start, end: close + 1 } : null; +type Token = Omit; + +/** + * The frontmatter's inner text: after the opening `---` line, up to the + * closing `---` line, by the fences `parseFrontmatter` reads (#2507). Null + * when there is no block, or when it is never closed: an edit cannot know + * where the body starts. `brain tags --apply` uses the same bounds. + */ +export function frontmatterBounds(text: string): { start: number; end: number } | null { + const block = frontmatterBlock(text); + return block?.closed ? { start: block.innerStart, end: block.innerEnd } : null; } -/** One scalar at `i`: quoted to its closing quote, or plain up to the line end or ` #`. */ -function readScalar(block: string, i: number): Token | null { - const quote = block[i]; +/** + * One scalar at `i`: quoted to its closing quote on the same line, or plain up + * to the line end, a character in `stops`, or ` #`. Null when there is none. + * Shared with `brain tags --apply`, which stops a flow entry at `,` and `]`. + */ +export function readScalar(text: string, i: number, stops = ""): ScalarToken | null { + const quote = text[i]; if (quote === '"' || quote === "'") { - for (let j = i + 1; j < block.length; j++) { - const c = block[j]; + let value = ""; + for (let j = i + 1; j < text.length; j++) { + const c = text[j]; if (c === "\n" || c === "\r") return null; - if (quote === '"' && c === "\\") j++; - else if (quote === "'" && c === "'" && block[j + 1] === "'") j++; - else if (c === quote) return { start: i, end: j + 1, quote }; + if (quote === '"' && c === "\\") { + const next = text[++j]; + value += next === "n" ? "\n" : next === "t" ? "\t" : next ?? ""; + } else if (quote === "'" && c === "'" && text[j + 1] === "'") { + value += "'"; + j++; + } else if (c === quote) { + return { start: i, end: j + 1, quote, value }; + } else { + value += c; + } } return null; } let j = i; - while (j < block.length && block[j] !== "\n" && block[j] !== "\r" && !/^[ \t]#/.test(block.slice(j, j + 2))) j++; - const raw = block.slice(i, j).replace(/[ \t]+$/, ""); - return raw ? { start: i, end: i + raw.length, quote: null } : null; + while (j < text.length && !stops.includes(text[j]!) && text[j] !== "\n" && text[j] !== "\r" && !/^[ \t]#/.test(text.slice(j, j + 2))) j++; + const raw = text.slice(i, j).replace(/[ \t]+$/, ""); + return raw ? { start: i, end: i + raw.length, quote: null, value: raw } : null; } /** A one-line flow sequence at `i`: up to its `]`, quoted entries skipped whole. */ diff --git a/packages/core/src/lib/generated-regions.ts b/packages/core/src/lib/generated-regions.ts index ae90c39ea0..75531dfee4 100644 --- a/packages/core/src/lib/generated-regions.ts +++ b/packages/core/src/lib/generated-regions.ts @@ -15,7 +15,8 @@ * and dashboard tables. */ -import { frontmatterLength } from "./document-parts.js"; +import { frontmatterBlock } from "@schlessera/brain-common/internal/frontmatter-block"; + import { codeRanges } from "./markdown-code.js"; /** A region name: lowercase letters, digits and dashes. */ @@ -124,14 +125,17 @@ export function replaceGeneratedRegion(body: string, name: string, content: stri * Split a file into its frontmatter block, kept verbatim (`---` fences * included), and its body. Frontmatter is never re-serialized: hand-written * YAML keeps its layout. Where the block starts follows the rule core reads - * documents by (`frontmatterLength`); a block that opens and never closes - * throws, since which part is the body cannot be known. + * documents by (`frontmatterBlock`, #2507); a block that opens and never + * closes throws, since which part is the body cannot be known. The + * frontmatter ends with the closing fence's three dashes; its line ending + * starts the body. */ export function splitFrontmatterBlock(raw: string): { frontmatter: string; body: string } { - if (frontmatterLength(raw) === 0) return { frontmatter: "", body: raw }; - const close = raw.indexOf("\n---", 3); - if (close === -1) throw new Error("frontmatter has no closing --- line"); - return { frontmatter: raw.slice(0, close + 4), body: raw.slice(close + 4) }; + const block = frontmatterBlock(raw); + if (!block) return { frontmatter: "", body: raw }; + if (!block.closed) throw new Error("frontmatter has no closing --- line"); + const fenceEnd = block.innerEnd + 3; + return { frontmatter: raw.slice(0, fenceEnd), body: raw.slice(fenceEnd) }; } /** diff --git a/packages/core/src/lib/hygiene.ts b/packages/core/src/lib/hygiene.ts index c0c97daaef..ddcd9581b6 100644 --- a/packages/core/src/lib/hygiene.ts +++ b/packages/core/src/lib/hygiene.ts @@ -17,6 +17,7 @@ import type { Database } from "bun:sqlite"; import { createHash } from "crypto"; import { closeSync, constants, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, realpathSync } from "fs"; +import { frontmatterBlock } from "@schlessera/brain-common/internal/frontmatter-block"; import { parseFrontmatter } from "@schlessera/brain-common/internal/frontmatter"; import { join, posix, resolve } from "path"; import remarkGfm from "remark-gfm"; @@ -712,7 +713,6 @@ export class HygieneLogError extends Error {} /** An entry heading: `### ` and one token ending in the ID's `-hash4`. */ const ENTRY_HEADING = /^### +(\S+-[0-9a-f]{4})[ \t]*\r?$/; -const FRONTMATTER = /^---[ \t]*\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/; /** A `## ` section of a log file, or (heading null) the text before the first one. */ interface Segment { @@ -735,14 +735,23 @@ interface LogFile { } /** - * The frontmatter and body of a log file. A file that opens a frontmatter - * block it does not close, or whose block is not a YAML mapping, is refused: - * rewriting it would mean guessing where the frontmatter ends. + * The frontmatter and body of a log file, by the fences the indexer reads + * (`frontmatterBlock`, #2507): a byte order mark before the opening fence + * still opens a block. A file that opens a block it does not close with a + * `---` line, or whose block is not a YAML mapping, is refused: rewriting it + * would mean guessing where the frontmatter ends. That is stricter than the + * indexer on purpose, because this rewrites the body. A closing fence with + * more than whitespace after its dashes (`----`, `---x`) is refused too: the + * indexer ends the block there, an author probably did not. The frontmatter + * keeps the closing line's trailing whitespace and line ending. */ function splitFrontmatter(text: string, rel: string): { frontmatter: string; body: string } { - if (!/^---[ \t]*\r?\n/.test(text)) return { frontmatter: "", body: text }; - const frontmatter = FRONTMATTER.exec(text)?.[0]; - if (!frontmatter) throw new HygieneLogError(`${rel}: the frontmatter is never closed with ---; fix it by hand, brain hygiene will not rewrite it`); + const block = frontmatterBlock(text); + if (!block) return { frontmatter: "", body: text }; + // After the closing dashes: optional whitespace, then a line ending or the end of the file. + const rest = block.closed ? /^[ \t]*(?:\r?\n|$)/.exec(text.slice(block.innerEnd + 3)) : null; + if (!rest) throw new HygieneLogError(`${rel}: the frontmatter is never closed with a --- line; fix it by hand, brain hygiene will not rewrite it`); + const frontmatter = text.slice(0, block.innerEnd + 3 + rest[0].length); let data: unknown; try { data = parseFrontmatter(frontmatter, { dataOnly: true }).data; diff --git a/packages/core/src/lib/okf-exporter.ts b/packages/core/src/lib/okf-exporter.ts index a3f4128191..46b5cc8330 100644 --- a/packages/core/src/lib/okf-exporter.ts +++ b/packages/core/src/lib/okf-exporter.ts @@ -1,4 +1,5 @@ import { Glob } from "bun"; +import { frontmatterBlock } from "@schlessera/brain-common/internal/frontmatter-block"; import { parseFrontmatter, type ParsedFrontmatter } from "@schlessera/brain-common/internal/frontmatter"; import { existsSync, @@ -488,8 +489,9 @@ export async function exportOkfBundle(options: OkfExportOptions): Promise 0 && start <= close + 1 ? { start, end: close + 1 } : null; -} - -interface Token { - /** Offsets of the scalar in the block text, quotes included. */ - start: number; - end: number; - value: string; -} - -/** Read one scalar at `i`: quoted, or plain up to a stop character or ` #`. */ -function readScalar(text: string, i: number, stops: string): Token | null { - const quote = text[i]; - if (quote === '"' || quote === "'") { - let j = i + 1; - let value = ""; - while (j < text.length) { - const c = text[j]; - if (quote === "'" && c === "'" && text[j + 1] === "'") { - value += "'"; - j += 2; - } else if (quote === '"' && c === "\\") { - const next = text[j + 1]; - value += next === "n" ? "\n" : next === "t" ? "\t" : next; - j += 2; - } else if (c === quote) { - return { start: i, end: j + 1, value }; - } else if (c === "\n" || c === "\r") { - return null; - } else { - value += c; - j++; - } - } - return null; - } - let j = i; - while (j < text.length && !stops.includes(text[j]) && !"\r\n".includes(text[j]) && !/^[ \t]#/.test(text.slice(j, j + 2))) { - j++; - } - const raw = text.slice(i, j).replace(/[ \t]+$/, ""); - return raw ? { start: i, end: i + raw.length, value: raw } : null; -} - /** A tag as YAML: plain when that reads back as the same string, else double-quoted. */ function yamlScalar(tag: string): string { const plain = diff --git a/packages/core/src/lib/validate.ts b/packages/core/src/lib/validate.ts index 9c531ae46e..e3504670ed 100644 --- a/packages/core/src/lib/validate.ts +++ b/packages/core/src/lib/validate.ts @@ -14,6 +14,7 @@ * the taxonomy so validation and the indexer's link graph agree exactly. */ +import { frontmatterBlock } from "@schlessera/brain-common/internal/frontmatter-block"; import { parseFrontmatter } from "@schlessera/brain-common/internal/frontmatter"; import { readFileSync, existsSync } from "fs"; import { resolve } from "path"; @@ -148,8 +149,9 @@ export function validateDetailed(root: string, taxonomy: Taxonomy): DetailedVali const fullPath = resolve(root, filePath); const raw = readFileSync(fullPath, "utf-8"); - // Check for frontmatter - if (!raw.startsWith("---")) { + // Check for frontmatter, by the fences the indexer reads (#2507): a + // byte order mark before them is fine, a `----` line is not a fence. + if (!frontmatterBlock(raw)) { issues.push({ file: filePath, level: "error", diff --git a/packages/core/tests/cli-onboarding.test.ts b/packages/core/tests/cli-onboarding.test.ts index 48f315ed4b..8f729ba0cc 100644 --- a/packages/core/tests/cli-onboarding.test.ts +++ b/packages/core/tests/cli-onboarding.test.ts @@ -110,6 +110,22 @@ test("import --stamp adds frontmatter to bare markdown", async () => { expect(stamped).toContain("status: draft"); }); +test("import --stamp skips frontmatter after a byte order mark instead of stamping over it (#2507)", async () => { + const root = tempBrain(); + const importDir = join(root, "import", "vault"); + mkdirSync(importDir, { recursive: true }); + const marked = "\uFEFF---\ntype: note\ntitle: Already\n---\nbody\n"; + writeFileSync(join(importDir, "marked.md"), marked); + writeFileSync(join(importDir, "rule.md"), "----\n\nA rule, not a fence.\n"); + + const { stdout, code } = await runCli(root, ["import", "--stamp", "import/vault", "--json"]); + expect(code).toBe(0); + const out = JSON.parse(stdout); + expect(out.skipped).toEqual(["marked.md"]); + expect(out.stamped).toEqual(["rule.md"]); + expect(readFileSync(join(importDir, "marked.md"), "utf-8")).toBe(marked); +}); + test("skills lint fails on a broken fixture skill", async () => { const root = tempBrain(); const skillDir = join(root, ".agents", "skills", "broken-skill"); diff --git a/packages/core/tests/frontmatter-fences.test.ts b/packages/core/tests/frontmatter-fences.test.ts new file mode 100644 index 0000000000..5637c4a060 --- /dev/null +++ b/packages/core/tests/frontmatter-fences.test.ts @@ -0,0 +1,85 @@ +/** + * Core's raw frontmatter editors find the block through `frontmatterBlock`, + * the rule `parseFrontmatter` reads by (#2507): the generated-region splitter, + * the key editor and `brain tags --apply` (which share one `frontmatterBounds` + * and one `readScalar`). + */ + +import { describe, expect, test } from "bun:test"; + +import { editFrontmatter, frontmatterBounds, readScalar, type ScalarToken } from "../src/lib/frontmatter-edit"; +import { splitFrontmatterBlock } from "../src/lib/generated-regions"; +import { rewriteTags } from "../src/lib/tags-apply"; + +const BOM = "\uFEFF"; + +describe("splitFrontmatterBlock", () => { + test.each([ + ["LF", "---\ntitle: a\n---\nbody\n", "---\ntitle: a\n---", "\nbody\n"], + ["a byte order mark", `${BOM}---\ntitle: a\n---\nbody\n`, `${BOM}---\ntitle: a\n---`, "\nbody\n"], + ["CRLF", "---\r\ntitle: a\r\n---\r\nbody\r\n", "---\r\ntitle: a\r\n---", "\r\nbody\r\n"], + ["a closing fence at the end of the file", "---\ntitle: a\n---", "---\ntitle: a\n---", ""], + ["a rule right after the closing fence", "---\ntitle: a\n---\n---\nbody\n", "---\ntitle: a\n---", "\n---\nbody\n"], + ["a leading blank line", "\n---\ntitle: a\n---\n", "", "\n---\ntitle: a\n---\n"], + ["a four-dash first line", "----\ntitle: a\n", "", "----\ntitle: a\n"], + ])("%s", (_, raw, frontmatter, body) => { + expect(splitFrontmatterBlock(raw)).toEqual({ frontmatter, body }); + }); + + test("a block that is never closed is refused", () => { + expect(() => splitFrontmatterBlock("---\ntitle: a\nbody\n")).toThrow("no closing --- line"); + expect(() => splitFrontmatterBlock(`${BOM}---\ntitle: a\n`)).toThrow("no closing --- line"); + }); +}); + +describe("frontmatterBounds, shared by the key editor and brain tags --apply", () => { + test.each([ + ["LF", "---\ntitle: a\n---\nbody\n", "title: a\n"], + ["a byte order mark", `${BOM}---\ntitle: a\n---\nbody\n`, "title: a\n"], + ["CRLF", "---\r\ntitle: a\r\n---\r\nbody\r\n", "title: a\r\n"], + ["a closing fence at the end of the file", "---\ntitle: a\n---", "title: a\n"], + // The copy in tags-apply searched back from the block's end, so this one + // took the closing fence into the block. + ["a rule right after the closing fence", "---\ntitle: a\n---\n---\nbody\n", "title: a\n"], + ["an empty block", "---\n---\nbody\n", ""], + ])("%s", (_, text, inner) => { + const bounds = frontmatterBounds(text); + expect(bounds && text.slice(bounds.start, bounds.end)).toBe(inner); + }); + + test("no block, or one never closed, has no bounds", () => { + for (const text of ["\n---\ntitle: a\n---\n", "----\ntitle: a\n----\n", "---\ntitle: a\n", "---\ntitle: a\n...\n"]) { + expect(frontmatterBounds(text)).toBeNull(); + } + }); + + test("the key editor keeps a byte order mark and an end-of-file fence", () => { + expect(editFrontmatter(`${BOM}---\ntitle: a\n---\nbody\n`, { title: "b" })).toBe(`${BOM}---\ntitle: b\n---\nbody\n`); + expect(editFrontmatter("---\ntitle: a\n---", { title: "b" })).toBe("---\ntitle: b\n---"); + }); + + test("brain tags --apply rewrites the tags after a byte order mark and before a rule", () => { + expect(rewriteTags(`${BOM}---\ntitle: T\ntags: [old]\n---\nbody\n`, () => ["new"])).toEqual({ + text: `${BOM}---\ntitle: T\ntags: [new]\n---\nbody\n`, from: ["old"], to: ["new"], + }); + expect(rewriteTags("---\ntitle: T\ntags:\n - old\n---\n---\nbody\n", () => ["new"])).toEqual({ + text: "---\ntitle: T\ntags:\n - new\n---\n---\nbody\n", from: ["old"], to: ["new"], + }); + }); +}); + +describe("readScalar, the one scalar reader both editors use", () => { + test.each<[string, string, string, ScalarToken]>([ + ["a plain scalar up to a comment", "abc # note", "", { start: 0, end: 3, quote: null, value: "abc" }], + ["a plain scalar up to a stop", "abc, def", ",]", { start: 0, end: 3, quote: null, value: "abc" }], + ["a double-quoted scalar with escapes", '"a\\"b\\n"', "", { start: 0, end: 8, quote: '"', value: 'a"b\n' }], + ["a single-quoted scalar with a doubled quote", "'it''s'", "", { start: 0, end: 7, quote: "'", value: "it's" }], + ])("%s", (_, text, stops, token) => { + expect(readScalar(text, 0, stops)).toEqual(token); + }); + + test("a quote not closed on its line, or nothing to read, is null", () => { + expect(readScalar('"open\n"', 0)).toBeNull(); + expect(readScalar(" # only a comment", 0)).toBeNull(); + }); +}); diff --git a/packages/core/tests/hygiene.test.ts b/packages/core/tests/hygiene.test.ts index 8bef8de11d..485363cb91 100644 --- a/packages/core/tests/hygiene.test.ts +++ b/packages/core/tests/hygiene.test.ts @@ -651,9 +651,27 @@ describe("writing the log", () => { expect(read(root, "resolved.md")).toContain(`### ${idOf(goes)}\n${seen}\n\nAsked about this on Monday.\n- resolved-by: auto-disappeared`); }); + test("a log file whose frontmatter follows a byte order mark keeps it as frontmatter (#2507)", () => { + const root = tempRoot(); + const seen = "- **First seen**: 2026-06-01 · **Last seen**: 2026-06-01"; + const frontmatter = '\uFEFF---\ntype: context\ntitle: "Open"\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n'; + mkdirSync(join(root, "context/hygiene"), { recursive: true }); + writeFileSync(log(root, "open.md"), `${frontmatter}\n## TODO markers\n\n${entry(idOf(goes), seen)}\n`); + expect(reconcile(root, [], docs, { now: NOW })).toMatchObject({ resolved: 1 }); + // The block is read where the indexer reads it: kept, mark included, with only `updated` set. + expect(read(root, "open.md")).toStartWith(frontmatter.replace("updated: 2026-01-01", `updated: ${TODAY}`)); + expect(read(root, "open.md")).not.toContain(`### ${idOf(goes)}`); + expect(read(root, "resolved.md")).toContain(`### ${idOf(goes)}`); + }); + test.each([ ["frontmatter that is not valid YAML", '---\ntitle: "unclosed\nupdated: 2026-01-01\n---\n\n## Resolved\n', "not valid YAML"], ["frontmatter that is never closed", "---\ntitle: Resolved\n\n## Resolved\n", "never closed"], + // The indexer ends these blocks at the dashes; an author probably did not (#2507). + ["a closing fence with text after its dashes", "---\ntitle: Resolved\n---x\n\n## Resolved\n---\n", "never closed"], + ["a four-dash closing line", "---\ntitle: Resolved\n----\n\n## Resolved\n---\n", "never closed"], + ["a ... closing line", "---\ntitle: Resolved\n...\n\n## Resolved\n", "never closed"], + ["a byte order mark before a block that is never closed", "\uFEFF---\ntitle: Resolved\n\n## Resolved\n", "never closed"], ["frontmatter that is a list, not a mapping", "---\n- one\n- two\n---\n\n## Resolved\n", "not a YAML mapping"], ["a section holding entries and other text", "## Parked\n\nA note.\n\n### todo-notes-goes-abcd\n- resolved-by: manual\n", 'section "## Parked"'], ])("a log file with %s is refused, and nothing is written", (_, text, message) => { diff --git a/packages/core/tests/okf-exporter.test.ts b/packages/core/tests/okf-exporter.test.ts index a476460af1..ee0c1e81d2 100644 --- a/packages/core/tests/okf-exporter.test.ts +++ b/packages/core/tests/okf-exporter.test.ts @@ -348,4 +348,14 @@ describe("OKF checker", () => { expect(errorReport.ok).toBe(false); expect(errorReport.errors).toBeGreaterThanOrEqual(4); }); + + test("finds frontmatter after a byte order mark, as the parser reads it (#2507)", () => { + const root = makeBrain({ + "index.md": "\uFEFF---\ntitle: Not allowed\n---\n# Bundle\n\n* [Concept](concept.md)\n", + "concept.md": `\uFEFF${document("Concept", "Body.")}`, + }); + const messages = checkOkfBundle(root).issues.map((issue) => `${issue.path}: ${issue.message}`); + expect(messages).toContain("index.md: index.md must not have frontmatter (except root okf_version only)"); + expect(messages).not.toContain("concept.md: concept document is missing YAML frontmatter"); + }); }); diff --git a/packages/core/tests/validate.test.ts b/packages/core/tests/validate.test.ts index c5c8a73538..c5a785be05 100644 --- a/packages/core/tests/validate.test.ts +++ b/packages/core/tests/validate.test.ts @@ -62,6 +62,17 @@ describe("validate", () => { }); }); + test("accepts frontmatter after a byte order mark, as the indexer reads it (#2507)", () => { + const fields = { type: "identity", title: "Identity", created: '"2026-01-01"', updated: '"2026-01-02"', tags: "[me]" }; + const root = makeCorpus({ "me/identity.md": `\uFEFF${doc(fields)}` }); + expect(validate(root, taxonomy).filter((i) => i.level === "error")).toEqual([]); + }); + + test("a four-dash first line is not frontmatter (#2507)", () => { + const root = makeCorpus({ "notes/raw.md": "----\ntitle: x\n----\nbody\n" }); + expect(validate(root, taxonomy)).toContainEqual({ file: "notes/raw.md", level: "error", message: "Missing YAML frontmatter" }); + }); + test("reports an invalid type and lists the taxonomy's valid types", () => { const root = makeCorpus({ "notes/x.md": doc({ type: "bogus", title: "X", tags: "[a]" }), diff --git a/packages/ui-react/src/lib/frontmatter.ts b/packages/ui-react/src/lib/frontmatter.ts index 452fc8f845..be305ac97a 100644 --- a/packages/ui-react/src/lib/frontmatter.ts +++ b/packages/ui-react/src/lib/frontmatter.ts @@ -5,8 +5,17 @@ * array (`tags: [a, b, c]`) and quoted string. We don't need a full YAML * parser — a small focused split keeps the bundle tiny and the behaviour * predictable. + * + * Where the block starts and ends is not decided here: `frontmatterBlock` + * (brain-common, through the ui-sdk) finds the fences by the rule the indexer + * reads documents by, so a byte order mark, CRLF and a closing fence at the + * end of the file read as they do everywhere else (#2507). One deliberate + * difference: a block that is never closed is shown as body, not swallowed as + * frontmatter, so a viewer never hides text it cannot delimit. */ +import { frontmatterBlock } from "@schlessera/brain-ui-sdk/internal/client"; + export interface FrontmatterField { key: string; /** Raw value as it appears in the file (quotes stripped). */ @@ -20,18 +29,11 @@ export interface FrontmatterSplit { body: string; } -const OPEN = /^---\r?\n/; - export function splitFrontmatter(md: string): FrontmatterSplit { - if (!OPEN.test(md)) return { fields: [], body: md }; - // Find closing `---` on its own line after the opener. - const afterOpen = md.replace(OPEN, ""); - const closeMatch = afterOpen.match(/\r?\n---\r?\n/); - if (!closeMatch || closeMatch.index === undefined) { - return { fields: [], body: md }; - } - const rawFrontmatter = afterOpen.slice(0, closeMatch.index); - const body = afterOpen.slice(closeMatch.index + closeMatch[0].length); + const block = frontmatterBlock(md); + if (!block?.closed) return { fields: [], body: md }; + const rawFrontmatter = md.slice(block.innerStart, block.innerEnd); + const body = md.slice(block.end); const fields: FrontmatterField[] = []; for (const line of rawFrontmatter.split(/\r?\n/)) { diff --git a/packages/ui-react/tests/frontmatter.test.ts b/packages/ui-react/tests/frontmatter.test.ts index 52c6a619a6..c51e78c573 100644 --- a/packages/ui-react/tests/frontmatter.test.ts +++ b/packages/ui-react/tests/frontmatter.test.ts @@ -90,4 +90,40 @@ describe("splitFrontmatter", () => { const r = splitFrontmatter(md); expect(r.body).toBe("\n\nbody line\n"); }); + + // The fences are found by frontmatterBlock, the rule the indexer reads by (#2507). + test("a closing fence at the end of the file closes the block", () => { + const r = splitFrontmatter("---\ntitle: a\n---"); + expect(r.fields).toEqual([{ key: "title", value: "a" }]); + expect(r.body).toBe(""); + }); + + test("frontmatter after a byte order mark is read", () => { + const r = splitFrontmatter("\uFEFF---\ntitle: a\n---\nbody\n"); + expect(r.fields).toEqual([{ key: "title", value: "a" }]); + expect(r.body).toBe("body\n"); + }); + + test("CRLF fences are read and the body keeps its line endings", () => { + const r = splitFrontmatter("---\r\ntitle: a\r\n---\r\nbody\r\n"); + expect(r.fields).toEqual([{ key: "title", value: "a" }]); + expect(r.body).toBe("body\r\n"); + }); + + test("trailing whitespace after the opening fence still opens a block", () => { + const r = splitFrontmatter("--- \ntitle: a\n---\nbody\n"); + expect(r.fields).toEqual([{ key: "title", value: "a" }]); + expect(r.body).toBe("body\n"); + }); + + test("a block that is never closed is shown as body, not hidden", () => { + const md = "---\ntitle: a\nbody\n"; + expect(splitFrontmatter(md)).toEqual({ fields: [], body: md }); + }); + + test("a leading blank line or a four-dash line is not frontmatter", () => { + for (const md of ["\n---\ntitle: a\n---\nbody\n", "----\ntitle: a\n----\nbody\n"]) { + expect(splitFrontmatter(md)).toEqual({ fields: [], body: md }); + } + }); }); diff --git a/packages/ui-sdk/src/internal-client.ts b/packages/ui-sdk/src/internal-client.ts index 522a2da0a5..6f5d5e720c 100644 --- a/packages/ui-sdk/src/internal-client.ts +++ b/packages/ui-sdk/src/internal-client.ts @@ -10,4 +10,5 @@ export { canonicalModelId, describeRetry, resolveThinkingLevel } from "./protoco export { pruneStoredShares, bindStoredShare, boundStoredShares, clearBoundStoredShares } from "./client/share-store.js"; export { handleShareTargetRequest, isShareTargetRequest, type ShareTargetError } from "./client/share-target-handler.js"; export { askUserFormPayload, askUserFormSpec, resolveAskUserFormLimits } from "./tool-contracts/form.js"; +export { frontmatterBlock, type FrontmatterBlock } from "@schlessera/brain-common/internal/frontmatter-block"; export { rewriteLinkDestinations, rewriteLinkDestinationsWithEdits, rebaseMessageBlocks, type LinkEdit } from "./markdown-links.js"; diff --git a/scripts/check-frontmatter-parse.ts b/scripts/check-frontmatter-parse.ts index a5b727264c..5ff903014c 100644 --- a/scripts/check-frontmatter-parse.ts +++ b/scripts/check-frontmatter-parse.ts @@ -27,6 +27,16 @@ // refused too. A `cache-probe` file is the exception: it is the test that // proves the helper ignores the cache, and must seed and read it. // +// 3. Where a frontmatter block starts and ends is answered by +// `frontmatterBlock` (`@schlessera/brain-common/internal/frontmatter-block`, +// #2507), the rule `parseFrontmatter` reads by. Package source may not +// detect a fence by hand: no regex anchored at the start of the text +// that opens with `---` (a BOM group before it included), no +// `startsWith("---…")` and no `indexOf`/`lastIndexOf("\n---…")`. Writers +// that emit or post-process a fence they produced are in FENCE_ALLOWED, +// each with its reason. A multiline (`m`) regex matches lines, not the +// start of a document, and is not a fence detector. +// // Detection is AST-based (the TypeScript compiler API), so comments and string // literals mentioning gray-matter do not trip it. @@ -61,6 +71,28 @@ export const ALLOWED: ReadonlyArray<{ pattern: RegExp; role: Role; reason: strin }, ]; +/** + * Package source that may spell a `---` fence by hand, and why. Everything + * else asks `frontmatterBlock`. + */ +export const FENCE_ALLOWED: ReadonlyArray<{ pattern: RegExp; reason: string }> = [ + { + pattern: /^packages\/common\/src\/frontmatter-block\.ts$/, + reason: "the shared fence rule itself", + }, + { + pattern: /^packages\/core\/src\/lib\/frontmatter\.ts$/, + reason: "stringifyDocument post-processes the LF-only block gray-matter's stringify just emitted", + }, + { + pattern: /^packages\/ui-server\/src\/brain\/policy-proposal\.ts$/, + reason: "pending: its review splitter still accepts a `...` closer; moving it onto frontmatterBlock is open work on #2507", + }, +]; + +/** Package source, where rule 3 applies. */ +const FENCE_SCOPE = /^packages\/[^/]+\/src\//; + const SCANNED = [ "packages/*/src/**/*.{ts,tsx,js,mjs,cjs}", "packages/*/tests/**/*.{ts,tsx,js,mjs,cjs}", @@ -74,7 +106,7 @@ export interface Finding { file: string; line: number; column: number; - rule: 1 | 2; + rule: 1 | 2 | 3; message: string; } @@ -109,7 +141,7 @@ export function scanSource(file: string, text: string): Finding[] { file.endsWith(".tsx") ? ts.ScriptKind.TSX : /\.[mc]?js$/.test(file) ? ts.ScriptKind.JS : ts.ScriptKind.TS); const allowed = ALLOWED.find((entry) => entry.pattern.test(file)); const findings: Finding[] = []; - const record = (node: ts.Node, rule: 1 | 2, message: string) => { + const record = (node: ts.Node, rule: 1 | 2 | 3, message: string) => { const { line, character } = source.getLineAndCharacterOfPosition(node.getStart(source)); findings.push({ file, line: line + 1, column: character + 1, rule, message }); }; @@ -137,6 +169,7 @@ export function scanSource(file: string, text: string): Finding[] { ts.forEachChild(node, visitLoads); }; visitLoads(source); + if (FENCE_SCOPE.test(file) && !FENCE_ALLOWED.some((entry) => entry.pattern.test(file))) scanFences(source, record); if (!allowed || ["cache-probe", "engine-probe"].includes(allowed.role) || bindings.size === 0) return findings; // Rule 2: every reference to the binding is a literal-options call or a type. @@ -182,6 +215,42 @@ export function scanSource(file: string, text: string): Finding[] { return findings; } +/** A regex source that anchors `---` at the start of the text, optionally after a BOM. */ +const FENCE_SOURCE = /^\^(?:\(\?:)?(?:\\uFEFF|\\ufeff|\uFEFF)?(?:\)\??|\?)?-{3}/; + +/** Rule 3: a frontmatter fence detected by hand instead of through `frontmatterBlock`. */ +function scanFences(source: ts.SourceFile, record: (node: ts.Node, rule: 3, message: string) => void): void { + const literal = (node: ts.Expression | undefined) => + node && ts.isStringLiteralLike(unwrap(node)) ? (unwrap(node) as ts.StringLiteralLike).text : undefined; + const refuse = (node: ts.Node, what: string) => + record(node, 3, `${what} detects a frontmatter fence by hand — use frontmatterBlock from ` + + "@schlessera/brain-common/internal/frontmatter-block, which reads the fences as parseFrontmatter does (#2507)"); + const visit = (node: ts.Node) => { + if (ts.isRegularExpressionLiteral(node)) { + const slash = node.text.lastIndexOf("/"); + const body = node.text.slice(1, slash), flags = node.text.slice(slash + 1); + if (!flags.includes("m") && FENCE_SOURCE.test(body)) refuse(node, "a regex anchored at a leading ---"); + } else if ((ts.isNewExpression(node) || ts.isCallExpression(node)) && ts.isIdentifier(node.expression) && + node.expression.text === "RegExp") { + const body = literal(node.arguments?.[0]); + const flags = literal(node.arguments?.[1]) ?? ""; + if (body !== undefined && !flags.includes("m") && FENCE_SOURCE.test(body)) refuse(node, "a RegExp anchored at a leading ---"); + } else if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) { + const method = node.expression.name.text; + const arg = literal(node.arguments[0]); + if (arg === undefined) { + // not a literal search string + } else if (method === "startsWith" && arg.startsWith("---")) { + refuse(node, `startsWith(${JSON.stringify(arg)})`); + } else if ((method === "indexOf" || method === "lastIndexOf") && /^\r?\n---/.test(arg)) { + refuse(node, `${method}(${JSON.stringify(arg)})`); + } + } + ts.forEachChild(node, visit); + }; + visit(source); +} + export function scanTree(root: string): Finding[] { const files = new Set(); for (const pattern of SCANNED) { @@ -200,16 +269,17 @@ if (import.meta.main) { const root = resolve(process.argv[2] ?? process.cwd()); const findings = scanTree(root); if (findings.length === 0) { - console.log("All frontmatter parsing goes through parseFrontmatter; gray-matter is loaded only by its designated files."); + console.log("All frontmatter parsing goes through parseFrontmatter; gray-matter is loaded only by its designated files; no package source finds a fence by hand."); process.exit(0); } - console.error("Frontmatter parsing that can reach gray-matter's global cache:"); + console.error("Frontmatter parsing that can reach gray-matter's global cache, or a fence found by hand:"); for (const f of findings) { console.error(` ${relative(root, resolve(root, f.file))}:${f.line}:${f.column}: [rule ${f.rule}] ${f.message}`); } console.error( `\n${findings.length} finding(s). Parse with parseFrontmatter ` + - "(@schlessera/brain-common/internal/frontmatter); see docs/decisions/frontmatter-parsing.md." + "(@schlessera/brain-common/internal/frontmatter) and find fences with frontmatterBlock " + + "(@schlessera/brain-common/internal/frontmatter-block); see docs/decisions/frontmatter-parsing.md." ); process.exit(1); } diff --git a/tests/frontmatter-parse-gate.test.ts b/tests/frontmatter-parse-gate.test.ts index c0f1293d26..086b3445df 100644 --- a/tests/frontmatter-parse-gate.test.ts +++ b/tests/frontmatter-parse-gate.test.ts @@ -8,7 +8,7 @@ import { describe, expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "fs"; import { tmpdir } from "os"; import { dirname, join, resolve } from "path"; -import { scanSource, scanTree } from "../scripts/check-frontmatter-parse"; +import { FENCE_ALLOWED, scanSource, scanTree } from "../scripts/check-frontmatter-parse"; const ROOT = resolve(import.meta.dir, ".."); const OTHER = "packages/core/src/lib/indexer/parse.ts"; @@ -115,6 +115,74 @@ describe("rule 2: inside a designated file, only literal-options calls", () => { }); }); +describe("rule 3: fences are found by frontmatterBlock (#2507)", () => { + const CORE = "packages/core/src/lib/x.ts"; + + test("a hand-written fence detector in package source is refused", () => { + for (const code of [ + "const OPEN = /^---\\n/;", + "const OPEN = /^---[ \\t]*\\r?\\n/;", + "const FM = /^(?:\\uFEFF)?---[ \\t]*\\r?\\n/;", + "const FM = /^\\uFEFF?---/;", + 'const FM = new RegExp("^---\\\\r?\\\\n");', + 'if (raw.startsWith("---")) skip();', + "if (raw.startsWith(`---\\n`)) skip();", + 'const close = raw.indexOf("\\n---", 3);', + 'const close = raw.lastIndexOf("\\n---", end);', + 'const close = raw.indexOf("\\r\\n---");', + ]) { + for (const file of [CORE, "packages/ui-react/src/lib/a.tsx", "packages/ui-server/src/a.js"]) { + expect({ code, file, rules: rules(file, code) }).toEqual({ code, file, rules: [3] }); + } + } + }); + + test("lines, emitted fences, other dashes and non-source files are not detectors", () => { + for (const code of [ + "s.replace(/^---+$/gm, '');", // a horizontal rule, line by line + "const fence = `---\\n${yaml}\\n---\\n`;", // emitting a fence + 'if (line === "---") end();', + 'const cell = "---";', + 'if (raw.startsWith("--")) x();', + 'if (raw.startsWith(prefix)) x();', + "const re = /a^---/;", + '// raw.startsWith("---")', + ]) { + expect({ code, rules: rules(CORE, code) }).toEqual({ code, rules: [] }); + } + for (const file of ["packages/core/tests/a.test.ts", "scripts/a.ts", "tests/a.test.ts"]) { + expect(rules(file, "const OPEN = /^---\\n/;")).toEqual([]); + } + }); + + test("only the shared rule and the listed writers may spell a fence", () => { + const planted = "const OPEN = /^---\\n/;"; + expect(rules("packages/common/src/frontmatter-block.ts", planted)).toEqual([]); + expect(rules(SERIALIZER, planted)).toEqual([]); + for (const file of ["packages/common/src/other.ts", "packages/core/src/lib/frontmatter-block.ts", "packages/common/src/lib/frontmatter-block.ts"]) { + expect({ file, rules: rules(file, planted) }).toEqual({ file, rules: [3] }); + } + for (const entry of FENCE_ALLOWED) expect(entry.reason.length).toBeGreaterThan(20); + }); + + test("the tree passes, and the CLI fails on a planted detector", () => { + expect(scanTree(ROOT).filter((f) => f.rule === 3)).toEqual([]); + const root = mkdtempSync(join(tmpdir(), "frontmatter-gate-")); + try { + mkdirSync(join(root, "packages/core/src/lib"), { recursive: true }); + writeFileSync(join(root, "packages/core/src/lib/planted.ts"), 'export const x = 1;\nconst OPEN = /^---\\n/;\n'); + const child = Bun.spawnSync({ + cmd: [process.execPath, resolve(import.meta.dir, "../scripts/check-frontmatter-parse.ts"), root], + stdout: "pipe", stderr: "pipe", + }); + expect(child.exitCode).toBe(1); + expect(child.stderr.toString()).toContain("packages/core/src/lib/planted.ts:2:14: [rule 3]"); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); +}); + describe("the tree", () => { test("discovers violations across source roots and excludes generated and unrelated files", () => { const root = mkdtempSync(join(tmpdir(), "frontmatter-gate-"));