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.
7 changes: 7 additions & 0 deletions .changeset/governance-policy-read-once.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@schlessera/brain-common": patch
"@schlessera/brain-ui-server": patch
"@schlessera/brain": patch
---

The governance policy file is read through one descriptor-anchored reader (#2508). `brain policy`, the indexer, `brain stats`, the hosted server's policy reader and its policy writer now share `openGovernancePolicyAnchored` and `verifyGovernancePolicyAnchored` in `@schlessera/brain-common/internal/governance-policy`, so a hardening fix reaches all of them. Each keeps the stricter rule of the two former copies. The writer no longer loads a file that grows past the 1 MiB bound after its size check, and it refuses a short read as a change. `checkGovernancePolicy` now refuses an ancestor directory replaced during the read on Linux as well, and reports an ancestor removed during the read as invalid rather than missing. The writer's review states and messages are unchanged.
8 changes: 8 additions & 0 deletions .changeset/safe-path-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-server": patch
---

Symlink-safe path containment now has one implementation, in the new internal entry `@schlessera/brain-common/internal/safe-path` (#2506). It holds `isWithin`, the containment primitive whose equality, separator, trailing-separator and normalisation answers are explicit parameters, and one canonicalisation algorithm with a synchronous and an asynchronous variant. core's `safeResolve`, the SDK's `resolveInRepo` and the server's `safeResolve` are thin wrappers over it, and the scratch-directory copies read the shared `BRAIN_SCRATCH_DIR`. Each caller keeps its own answers, with two exceptions: the server's `safeResolve` now refuses a path through a symlink cycle, as core and the SDK already did, instead of answering a path that resolves nowhere; and the server's check that core's query entry lies inside its package no longer refuses a directory whose name starts with `..`. `safeResolve` and `SCRATCH_DIR` stay exported from `@schlessera/brain/module` with their signatures and answers unchanged. The new entry is internal and carries no compatibility promise.
26 changes: 26 additions & 0 deletions .changeset/strict-containment-answers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
"@schlessera/brain": minor
"@schlessera/brain-ui-sdk": patch
"@schlessera/brain-ui-server": patch
"@schlessera/brain-module-diagrams": patch
"@schlessera/brain-module-travel": patch
"@schlessera/brain-module-images": patch
---

**Breaking: `safeResolve` and `resolveWritable` from `@schlessera/brain/module` now give the strictest containment answer in every row (#3422).** They return `null` for:

- an absolute path, even one inside the brain root;
- any `..` segment, even when the result stays inside;
- `:` or `\` in a segment;
- a dangling symlink, even one whose target is inside;
- a path that leaves the root through one symlink and comes back through another, since every existing component must now stay inside, not only the final path.

A root whose realpath fails was already refused, and still is. The answer is still the canonical path.

The CLI still accepts an absolute path argument inside the brain. Before resolving one, it converts it to a brain-relative path with the new `brainRelativeArgument(root, arg)`, which `@schlessera/brain/module` also exports for module commands. This covers `--out`, document paths and the other CLI path flags. An absolute path outside the brain is still refused, and so is one that reaches the outside through a symlink inside the brain or has a `..` segment.

Migration for module authors: pass paths relative to the brain root. A module command that takes a path argument from the user passes it through `brainRelativeArgument(ctx.root, arg)` first, as the first-party commands do. To re-check an absolute path you already hold, such as an earlier answer from `safeResolve`, pass it relative to the root's realpath (`relative(safeResolve(root, ".")!, path)`). Normalise a link target before resolving it (`join(dirname(path), target)`) instead of sending its `..`. Do not rely on a dangling link to name a file you are about to create.

The ui-sdk's `resolveInRepo` and the server's file `safeResolve` give the same answers. The SDK newly refuses `..`, `:` and `\`, dangling links and out-and-back links. The server newly refuses a missing brain root instead of falling back to the lexical path.

The deny-direction containment checks now treat `/` as holding every absolute path. Before, a `/` source passed the worker launcher's refusal of "the brain or its ancestors" for a transport bind, a managed worktree generation and a reference source view, and the server's sync transport mounted a local remote of `/`. A host credential state directory of `/` was also accepted. All of these are now refused.
20 changes: 20 additions & 0 deletions api-report/common.txt
Original file line number Diff line number Diff line change
Expand Up @@ -159,23 +159,34 @@ 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)
APIFY_LIMIT_BOUNDS
APIFY_MAX_ACTOR_GRANTS
APIFY_MAX_RUN_USD
type AnchoredGovernancePolicy
type ApifyLimits
BUILTIN_GOVERNANCE_POLICY
type EffectiveGovernancePolicy
GOVERNANCE_POLICY_MAX_BYTES
GOVERNANCE_POLICY_PATH
type GovernanceCommandRuleIndices
type GovernancePolicyCheck
type GovernancePolicyDirectory
type GovernancePolicyInput
GovernancePolicyReadError
type GovernancePolicyReadRefusal
GovernancePolicySchema
checkGovernancePolicy
openGovernancePolicyAnchored
parseGovernancePolicy
providerAllows
resolveGovernancePolicy
verifyGovernancePolicyAnchored

export "./internal/index-location" (./src/index-location.ts)
EMBEDDING_LOCK_FAMILY
Expand Down Expand Up @@ -215,6 +226,15 @@ export "./internal/provider-unavailable" (./src/provider-unavailable.ts)
providerUnavailableNotice
withheldKeys

export "./internal/safe-path" (./src/safe-path.ts)
type ContainedPath
type ContainmentPolicy
type ContainmentRefusal
type WithinRule
isWithin
resolveContained
resolveContainedSync

export "./internal/worker-areas" (./src/worker-areas.ts)
BRAIN_SCRATCH_DIR
BRAIN_WORKSPACES_DIR
Expand Down
5 changes: 4 additions & 1 deletion api-report/core.txt
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ export "./module" (./src/module.ts)
type WriteFileSafelyOptions
WriteRefusedError
assertScratchWritable
brainRelativeArgument
buildTaxonomy
configurationRoot
geminiCompletions
Expand Down Expand Up @@ -1449,6 +1450,8 @@ signatures (every public export and the types it is made of)
}, z.core.$strict>>>;
}, z.core.$strict>>;
}, z.core.$strict>;
brainRelativeArgument (packages/core/src/lib/safe-path.ts)
export function brainRelativeArgument(root: string, arg: string): string;
buildPathMatcher (packages/core/src/lib/reranker.ts)
export function buildPathMatcher(patterns: readonly string[] | undefined): ((path: string) => boolean) | undefined;
buildTaxonomy (packages/core/src/lib/taxonomy.ts)
Expand Down Expand Up @@ -1606,7 +1609,7 @@ signatures (every public export and the types it is made of)
resolveReranker (packages/core/src/lib/registry.ts)
export function resolveReranker(config?: RerankerSettings): Reranker | undefined;
resolveWritable (packages/core/src/lib/safe-path.ts)
export function resolveWritable(root: string, relOrAbs: string): string | null;
export function resolveWritable(root: string, relPath: string): string | null;
restoreStorageAttachment (packages/core/src/lib/storage-attachments.ts)
export function restoreStorageAttachment(root: string, path: string, expected: StorageAttachmentVersion, copy: (fd: number) => void, assertCurrent?: () => void): void;
rewriteGeneratedRegion (packages/core/src/lib/generated-regions.ts)
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 @@ -1333,6 +1333,7 @@ export "./internal" (./src/internal.ts)
workerSandboxWarnings

export "./internal/client" (./src/internal-client.ts)
type FrontmatterBlock
type LinkEdit
type ShareTargetError
askUserFormPayload
Expand All @@ -1345,6 +1346,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
14 changes: 7 additions & 7 deletions docs/decisions/governed-writable-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -505,11 +505,11 @@ before application-lock admission, acquires its own complete native checkpoint
asynchronously and runs a credential-free, read-only Git query. It releases
that input after the worker drains, without creating or publishing a writable
stage (`createScratchIgnoreQuery`,
`packages/ui-server/src/brain/scratch-mask-query.ts:7-43`). Exit 1 means the
`packages/ui-server/src/brain/scratch-mask-query.ts:8-44`). Exit 1 means the
directory is not ignored. Launch failure, another exit or timeout means the
rule could not be verified; the mask remains refused without forwarding worker
stderr or claiming that the ignore file needs repair (`assertScratchMaskAsync`,
`packages/ui-sdk/src/server/bridge-tools/mask.ts:224-235`).
`packages/ui-sdk/src/server/bridge-tools/mask.ts:228-239`).

**Credentials never reach a process that evaluates repository inputs.** A
read-only host does not stop sandboxed code from stealing a credential it was
Expand Down Expand Up @@ -1074,14 +1074,14 @@ is gone as well, and never enters another mount, so runtime state below
against its own budget, and a turn that cannot reserve it is refused as
`worker_state_busy` (docs/hosting/agent-workers.md). The `turn_temp` tool
reports usage and purges paths through the same descriptor
(`export function purgeTurnTemp`, `packages/ui-sdk/src/server/worker-turn-temp.ts:450-458`).
(`export function purgeTurnTemp`, `packages/ui-sdk/src/server/worker-turn-temp.ts:451-459`).
The restricted envelope gets the same sized `/tmp` and promotes nothing.
After the worker exits, the backend
rewrites the answer text the turn appended to its saved transcript, and only
that text. It looks at Markdown link and image destinations and reference
definitions outside code. A file is promoted once per turn however often it
is linked, up to 128 MiB per file, 256 MiB and 64 files per turn
(`export function createTurnTempPromoter`, `packages/ui-sdk/src/server/worker-turn-temp.ts:124-135`).
(`export function createTurnTempPromoter`, `packages/ui-sdk/src/server/worker-turn-temp.ts:125-136`).
The copy goes to `.brain/scratch/turns/<turnId>/` under a name the reader's
file links accept, so the rewritten link is brain-relative and is pinned like
any other scratch link. Each result reaches the server as a `promotion` or
Expand All @@ -1104,10 +1104,10 @@ Live blocks still use streamed-text offsets; the client and server share
the span rebasing function and discard ambiguous overlaps as plain Markdown.

**Pinning.** A link into `.brain/scratch/` pins the target. Prune skips pinned
files (`export function pruneScratch`, `packages/core/src/lib/scratch.ts:641`).
files (`export function pruneScratch`, `packages/core/src/lib/scratch.ts:645`).
A pin is released when every conversation that links the file is deleted or
falls out of retention. If the scratch area still exceeds its size limit
(`SCRATCH_MAX_BYTES`, `scratch.ts:58`) after unpinned files are pruned, the
(`SCRATCH_MAX_BYTES`, `scratch.ts:62`) after unpinned files are pruned, the
overage is reported. Pinned files are never deleted. A writer that prunes
after writing into scratch also passes the paths it just produced, protected
for that one call (`pinnedPaths`), so retained pins over the cap cannot make it
Expand Down Expand Up @@ -1409,7 +1409,7 @@ external editor throughout a native tool's execution.
The parent observes the worker's resolved mount sources, including strict
startup copies and writable area aliases; it does not substitute newer
canonical bytes for a frozen view (`createWorkerFileObserver`,
`packages/ui-sdk/src/server/worker-file-observer.ts:13`). A failed or changing
`packages/ui-sdk/src/server/worker-file-observer.ts:15`). A failed or changing
read cannot establish a new version. Claude's native `file_unchanged` response
also preserves the previous observation: it supplied no new bytes
(`const finishNativeFile`,
Expand Down
12 changes: 6 additions & 6 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:250-252`).
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 Down
Loading
Loading