Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/frontmatter-block-once.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions api-report/common.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions api-report/ui-sdk.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1269,6 +1269,7 @@ export "./internal" (./src/internal.ts)
workerSandboxWarnings

export "./internal/client" (./src/internal-client.ts)
type FrontmatterBlock
type LinkEdit
type ShareTargetError
askUserFormPayload
Expand All @@ -1281,6 +1282,7 @@ export "./internal/client" (./src/internal-client.ts)
defaultAsrClientRegistry
defaultToolRendererRegistry
describeRetry
frontmatterBlock
handleShareTargetRequest
isShareTargetRequest
pruneStoredShares
Expand Down
43 changes: 42 additions & 1 deletion docs/decisions/frontmatter-parsing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
22 changes: 11 additions & 11 deletions docs/decisions/hygiene-review.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`).
Expand Down Expand Up @@ -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 |
| --- | --- | --- | --- |
Expand All @@ -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 |
Expand All @@ -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.
Expand All @@ -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.

Expand All @@ -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.

Expand Down Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions docs/decisions/mechanical-hygiene.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/decisions/module-instruction-ownership.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion docs/decisions/voice-permission.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
6 changes: 3 additions & 3 deletions docs/investigations/audit-capability-investigation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading