Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(quarantine): put_page and put_pages say when the gate quarantined the page (#6259)
time-attack4ec4699fc7b2
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex 3c80b423a1..a2b6799d06 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -47,7 +47,7 @@ boundary and add its link here rather than raising the cap.| [Core Persistence (engine graduation)](key-files/core-persistence-graduation.md) | `engine-graduation*.ts`, `graduation-*.ts`, `src/commands/migrate-graduation.ts`, the graduation doctor finding || [Managed sync and persistence stalls (key files cluster)](key-files/persistence-stalls.md) | `claim-phase.ts`, `pre-activation-release.ts`, `sync-concurrent-write.ts`, `worktree-manifest.ts`, `src/core/hardened-git.ts` || [Core Search (1/2)](key-files/core-search-1.md) | `src/core/search/` through `src/core/search/rerank.ts` |-| [Core Search (2/2)](key-files/core-search-2.md) | `src/core/search/return-policy.ts` through `src/core/search/vector-pool.ts`, plus the relational arm and multi-hop chain modules (`relational-recall.ts`, `relational-rerank-pin.ts`, `relational-chain.ts`, `relational-plan.ts`, `hub-dampening.ts`) |+| [Core Search (2/2)](key-files/core-search-2.md) | `src/core/search/return-policy.ts` through `src/core/search/vector-pool.ts`, the relational arm and multi-hop chain modules, `hub-dampening.ts` || [Core Services (1/3)](key-files/core-services-1.md) | `src/core/advisor/{types,run,render,recommended-set,history,apply,collect-*}.ts` through `src/core/connectors/` || [Core Services (1/3, continued)](key-files/core-services-1-continued.md) | `src/core/context/` through `src/core/context/ipc-path.ts` || [Core Services (2/3)](key-files/core-services-2.md) | `src/core/conversation-parser/` through `src/core/progressive-batch/`, except `src/core/persistence/` |@@ -80,6 +80,7 @@ boundary and add its link here rather than raising the cap.| [Always-loaded core memory (key files cluster)](key-files/core-memory.md) | Core tier, write-path guard and lock order, delivery lanes, pressure notice || [Workspace push and backup coverage (key files cluster)](key-files/workspace-push-and-backup.md) | Workspace push, hook push backstops, backup verdicts || [Ambient capture consent gate (key files cluster)](key-files/ambient-capture.md) | `memory.auto_writeback` capture lanes |+| [Quarantine (cluster)](key-files/quarantine.md) | Gate-marker strip; quarantined pages in facts, reads, writes |## BrainBench — in a sibling repodiff --git a/docs/architecture/key-files/commands-4-continued.md b/docs/architecture/key-files/commands-4-continued.mdindex 009ed8d8fa..211ae366a6 100644--- a/docs/architecture/key-files/commands-4-continued.md+++ b/docs/architecture/key-files/commands-4-continued.md@@ -9,7 +9,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/publish.ts` — Deterministic brain page publisher (code+skill pair, zero LLM calls)-- `src/core/quarantine-override.ts` — #6259 (fix wave 12): the `quarantine_override` frontmatter key `gbrain quarantine clear --force` records: `{ binding, cleared_at }`, where `binding` is a sha256 over the classifier's inputs (title, type, body) as the gate canonicalizes them (`quarantineOverrideFor`). `assessImportSanity` (`import-screen.ts`) wraps its verdict in `withQuarantineOverride`, which removes the junk-pattern, literal and markup-flag outcomes while the binding is current (size outcomes stay). `importFromContent` calls `stripGateOwnedMarkers` (`import-screen.ts`, `GATE_OWNED_FRONTMATTER_KEYS`): every writer loses `quarantine`, `content_flag`, `embed_skip`, `atoms_scan_hash` and `quarantine_override` unless an owner-tier path passes `preserveGateMarkers: true` (`importFromFile`, managed sync and file import, reindex, file repair, reconcile, the cycle derivers and their `managed_maintenance_page` intents, `quarantine clear/scan` and the owner-internal `managed_quarantine_clear` put_page kind); local put_page, connectors and ingest lanes do not. A preserving path keeps its own override only while current, and a current override drops classifier markers the content still carries. `opts.remote` keeps only its fence-merge/hidden-row meaning. Tests: `test/gate-marker-strip.test.ts`. For a stripped write the classifier would hide or markup-flag, `carryStoredQuarantineOverride` reads the stored override and keeps it when it still binds (so a remote tag edit does not re-hide the page); a clean remote write reads nothing extra (#6007 statement budget). Company-brain inspection refuses files carrying it (`hidden_input`). Doctor's quarantine row names `clear <slug> --force` and `content_sanity.disabled_patterns`.- `src/commands/quarantine.ts` — `gbrain quarantine <list|clear|scan>` operator surface for the content-quality gate. `list [--json] [--include-flagged]` paginates `listPages` and reports quarantined (HIDDEN) pages, optionally also `content_flag` (FLAGGED, searchable) pages. `clear <slug> [--force] [--no-embed] [--json]` drops both markers and re-imports through the normal pipeline so the page re-chunks + re-embeds and becomes searchable; the gate re-runs on import so genuinely-junk pages re-quarantine (exit 1) unless `--force` sets `GBRAIN_NO_SANITY=1` for that one import. `scan [--limit N] [--apply] [--no-embed] [--json]` re-assesses already-ingested pages so junk predating the gate gets marked (unchanged content short-circuits normal sync, so it never re-assesses otherwise); dry-run uses the SAME effective `content_sanity` config thresholds `--apply` will use, idempotent (skips already-marked pages), `--apply` re-imports with `forceRechunk` to set markers + (for quarantine) drop chunks. Dispatched in `cli.ts`. Pinned by `test/quarantine-cli.test.ts`. #6259: `clear` reads one snapshot (page, tags, revision) and, on a managed brain, publishes through `submitPageMutation` with that `expected_revision` (a concurrent edit is a `revision_conflict`, a pending receipt is reported as pending); `--force` writes a `quarantine_override` (see `src/core/quarantine-override.ts`) instead of disabling the gate, never mutation `force`. `scan --apply` refuses `writer_coordinator_required` on a managed brain. It is a router (`QUARANTINE_SUBCOMMANDS`, `printUsage`). Tests: `test/quarantine-override.serial.test.ts`, `test/quarantine-cli.test.ts`.- `src/commands/recall.ts` — the `gbrain recall` CLI (facts-first by default; local engine or thin-client). A malformed `--limit` (not a positive safe integer, or missing) throws `invalid_params` from `parseFlags`, so the CLI exits 2 through `renderCliError`: the v1 envelope under `--json` with `why` and a `fix` that reruns the same argv with `--limit 50`, and the Error/Fix/Why lines otherwise (`test/recall-limit-envelope.test.ts`). Optional `--budget-policy facts_first|query_first` routes a one-shot read through the shared operation, forwarding fact filters and using remote recall on thin clients. Enum validation uses the shared operation definition; option order does not affect budget parsing. Only query-first with a nonblank query preserves numeric fractions until server packing; omitted/explicit facts-first keeps legacy integer parsing. The new option rejects watch/cursor/rollup/as-context combinations rather than silently ignoring them. Opt-in selector failures use stamped v1 errors; JSON mode emits structured local and remote errors on stdout with a nonzero exit, preserving remote read-error details without requiring a mutation receipt. Omitted-policy validation and fallback remain unchanged. Entity→text fallback: a bare positional without verb options is entity-first, but when the entity arm matches ZERO facts (and no `--grep`/`--supersessions`/`--session-id` narrows the read), the query retries as SQL-level fact-text grep with a stderr note. One predicate and note formatter are shared by the local path and thin-client mirror; explicit grep callers keep exact semantics. `--since` composes with entity and session in one query before LIMIT, on event time unless `--since-last-run`. Local `--grep` is passed to every engine arm (ILIKE with escaped metacharacters, before LIMIT); only `--supersessions` keeps the client-side filter. Pinned by `test/recall-grep-local-cli.test.ts`. Pinned by `test/facts-recall-since-composition.test.ts`, `test/recall-budget-policy-transports.test.ts`, `test/recall-budget-policy-thin-cli.test.ts`, and `test/recall-budget-policy-thin.serial.test.ts`.diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.mdindex b538e0ce31..3341924bff 100644--- a/docs/architecture/key-files/files-and-sync-1.md+++ b/docs/architecture/key-files/files-and-sync-1.md@@ -27,7 +27,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/import-checkpoint.ts` — `loadCheckpoint(path, currentDir)`, `saveCheckpoint(path, cp)`, `resumeFilter(allFiles, dir, completed)`, `clearCheckpoint(path)`, `resolveImportTargetDir(dir)`, and the `ImportCheckpoint` type. Payload: `{schema_version: 1, owner: 'gbrain', kind: 'import', dir, completedPaths, timestamp}`; `dir` is the absolute realpath of the import target, never the caller's CWD. Paths record successful/unchanged progress, not content identity; ordinary `runImport` revalidates all current files via `importFile`'s existing content-hash comparison rather than using `resumeFilter`. Company-brain ingestion uses separate protected database checkpoints for an immutable approved manifest. The exported pure filter returns a path array and skips completed paths for company-brain manifest resume; by itself it is not proof that mutable file content is unchanged. `loadCheckpoint` returns `null` for missing/malformed payloads, target mismatch, invalid path/timestamp fields, or incompatible producer metadata; absent producer fields in legacy path-set checkpoints remain accepted. Old positional checkpoints log a stderr diagnostic before discard. `saveCheckpoint` sorts paths and atomically writes via `.tmp` + `rename()`; save/clear failures are non-fatal and silent. The caller supplies the checkpoint path via `gbrainPath()`, preserving `GBRAIN_HOME` isolation. Pinned by `test/import-checkpoint.test.ts`, `test/import-resume.test.ts`, and `test/import-json-stdout.test.ts`.-- `src/core/import-screen.ts` — `screenImportContent`: the one content screen (published exemption, size, frontmatter hold, slug conflict, Tier 1: a fixable fence is admitted normalized, a residual refuses typed (`coordinated`) or warns (`lenient`); optional sanity reject) shared by `importFromContent`, managed import and managed sync publication. `contentRefusalError` keeps each site's wire `error`; `isContentRefusal(code, message)` matches new codes and exact pre-upgrade strings, never capacity or transient refusals; `contentRefusalFromReceipt` restores code, reason, key and line on receipt replies. Tests: `test/import-screen.test.ts`, `test/sync-frontmatter-recovery.test.ts`, `test/put-page-recoverable-frontmatter.test.ts`.+- `src/core/import-screen.ts` — `screenImportContent`: the one content screen (published exemption, size, frontmatter hold, slug conflict, Tier 1: a fixable fence is admitted normalized, a residual refuses typed (`coordinated`) or warns (`lenient`); optional sanity reject) shared by `importFromContent`, managed import and managed sync publication. `contentRefusalError` keeps each site's wire `error`; `isContentRefusal(code, message)` matches new codes and exact pre-upgrade strings, never capacity or transient refusals; `contentRefusalFromReceipt` restores code, reason, key and line on receipt replies. Tests: `test/import-screen.test.ts`, `test/sync-frontmatter-recovery.test.ts`, `test/put-page-recoverable-frontmatter.test.ts`. #6259 marker strip: [quarantine cluster](quarantine.md).- `src/core/import-file.ts` — importFromFile + importFromContent (chunk + embed + tags). Every markdown import resolves and stamps `contextual_retrieval_mode` and `corpus_generation` with the canonical write, `--no-embed` included (#5621), so later embed passes reproduce the page's wrapping; a failed source-policy read fails the import unless the row or table is missing (`SourceRowNotFoundError`, `isUndefinedTableError`). Unchanged markdown or code content whose page is below the safe-chunk fence is re-sealed projection-only (direct imports install it; coordinated `prepare` imports stay no-ops and queue a `safe_chunk_reseal` projection job), with no page write or admission. Freshly embedded chunks carry `embedding_input_hash` for the tier they were built under. The `beforeCommit` hook runs inside the guarded canonical transaction so a rejected file write rolls back its projections; optional legacy source-path repair uses a savepoint. Deferred importer embedding callbacks capture the committed text projection and indexing context, then install with an UPDATE-only revision/chunk/hash check. Tests: `test/import-publication-guards.test.ts`. Coordinated `prepare` imports resolve and atomically stamp the page/source/global contextual wrapping mode even with `noEmbed:true`; the durable outbox later embeds that revision. The existing paid-synopsis title fallback and mount trust gate remain in force, while embedding signatures only certify completed vectors. `test/persistence-contextual-embedding.test.ts` covers both engines, policy precedence, deferred provider execution, and a competing title replacement. `importFromContent` and `importCodeFile` stamp `pages.embedding_signature` via `setPageEmbeddingSignature(slug, {sourceId, signature: currentEmbeddingSignature()})` when the import actually embedded (not `--no-embed`) so a model/dims swap is detectable as stale; `importCodeFile` only stamps when every chunk was freshly embedded this call (`needsEmbedIndexes.length === chunks.length`), mixed reuse-by-hash pages stay unstamped (`reindex --code --force` / `embed --stale` handle those). `importFromContent` reconciles tags by provenance (`tags.tag_source`, migration v175): frontmatter tags go through `addTag(..., { tagSource: 'frontmatter' })`, and a row still marked 'frontmatter' whose tag left the frontmatter is deleted in the import transaction. Every other `addTag` stamps 'added' (add_tag, enrichment, the code importer) and is never import-deleted, so `gbrain reindex --markdown` keeps enrichment tags; legacy NULL rows are adopted only while the frontmatter still lists them; prepared (managed) imports keep add-only tags, matching the union their canonical file renders. Pinned by `test/reindex-preserve-tags.test.ts`, `test/import-frontmatter-tag-removal.test.ts` + `test/import-file.test.ts`. identity decisions live in `src/core/import-identity.ts` (`decideImportIdentity`, `collidingSlugOwner`; pure reads, the importer applies them). The dedup pre-check calls `engine.findDuplicatePage?.(sourceId, {hash, frontmatterId, excludeSlug})` (optional `?` so test doubles compile; the caller's own slug never matches, and a `frontmatter.id` match ranks ahead of a bare hash match). Posture: MOVE when the `frontmatter.id` matches and the other page's OWN origin proves it moved (#5675): that origin is the `file://` path `importFromFile` records in `pages.source_uri` (never replacing non-file provenance), else the source's configured root (`local_path`, or the default source's legacy `sync.repo_path`). An origin that still exists moves only when it is this very file under another relative path (overlapping roots converge); a gone origin needs this file under that same root, and differing content also needs the same file name or title, so a missing path under another root, or a new note reusing a deleted note's template id, never renames a live page. `updateSlug` carries the row (page id, links, facts incl. `entity_slug`/`source_markdown_slug`, `page_aliases`, timeline, plus a rename alias) and the new content imports onto it, so a full sync's delete-reconcile has nothing live to remove; SKIP only when the id AND the content (`content_hash`, or title and body for a row written outside the importer) both match while the recorded file still exists (overlapping ingest roots); IMPORT with a warning when the id matches but content differs (templates, copy-paste; an edit is never frozen by the other page); WARN-ALWAYS on a bare content_hash collision; FAIL CLOSED on lookup error; bypass via `--force-rechunk`. Content-only callers (`put_page`, transcripts) never move a page. Soft-deleted pages excluded at the engine layer so tombstones don't block legitimate re-imports under new slugs. Slug collisions: when another live file (`existing.source_path`, realpath-distinct) already owns the slug, the incoming file is skipped with `skip_reason: 'slug_collision'` and a stderr warning, unless the incoming file is named exactly `<slug>.md` (the file the link extractor reads for that slug), so two spellings never overwrite each other. An embedding failure never blocks the text write: chunks commit with NULL vectors, no embedding signature is stamped, the result carries `embedding_deferred: true`, and the stale sweep embeds them later (a code file whose embed failed is not stamped either). An inline markdown re-import embeds only chunks whose embedding input changed: `planEmbeddingReuse` (keyed on chunk source + exact text) reuses a stored vector when the old index is sealed (`requireSafeChunks`), the page's `embedding_signature`, contextual mode, `corpus_generation` and (under the title wrapper) sanitized title are unchanged, and neither the old nor the new body holds protected fences; prepared, `--no-embed`, `--force-rechunk` and post-commit-embedding imports reuse nothing (`test/import-markdown-embedding-reuse.test.ts`). Offset-less frontmatter datetimes are read in the brain's `brain.timezone` (IANA, validated by `gbrain config set`; unset or invalid = UTC; the YAML parser tags naive timestamps with `NAIVE_DATETIME` so the wall-clock reading survives), while date-only values stay UTC calendar dates (`test/effective-date-brain-timezone.test.ts`). `effective_date` for an undated page falls back to `fallbackCreatedAt` (stored fallback date, else the earliest of the file's birth/modification time and — when `sync.git_first_commit_dates` is on — its git first-commit date via `fileTimes`, else now; `src/core/git-first-commit.ts` maps paths in one `git log --diff-filter=A` pass per `runImport`, skipping shallow clones; `test/effective-date-git-first-commit.test.ts`), never the latest write. Pinned by `test/import-dedup-frontmatter-id.test.ts`, `test/import-identity-move.test.ts`, `test/import-slug-collision.test.ts`, `test/import-embed-outage.test.ts` and `test/effective-date-calendar.test.ts`. `importFromContent` is the narrow waist every ingest path passes through (`gbrain import`, `gbrain sync`, `put_page` MCP, `/ingest` webhook). It runs a three-tier content-quality disposition via `assessContentSanity` from `src/core/content-sanity.ts` BEFORE chunking: (1) high-confidence junk (built-in Cloudflare/CAPTCHA interstitial patterns + operator literals) → QUARANTINE (stamps the `quarantine` frontmatter marker, writes ZERO chunks, hides the page from search) OR REJECT (throw → sync-failure) when `content_sanity.junk_disposition` is `reject`; (2) fuzzy markup-heavy (prose-vs-markup ratio above `content_sanity.max_markup_ratio`, warn-tier byte window, code pages exempt) → `content_flag:markup_heavy` marker (page stays fully searchable, marker rides search results + get_page to warn the agent); (3) oversize → `embed_skip` soft-block via `buildEmbedSkipMarker()` PLUS a `content_flag:oversized` marker, AND deletes any pre-existing chunks in the same transaction so search can't surface stale chunks. Gate-owned markers (`quarantine`, `content_flag`) are STRIPPED from untrusted (remote MCP, `ctx.remote !== false`) frontmatter so a write-scoped client can't hide pages or forge the warning channel; markers are excluded from `content_hash` so a flagged page doesn't re-embed every sync, but an `embed_skip` transition (present vs absent) defeats both unchanged fast paths so a threshold change rebuilds or removes chunks without `--force`. A trusted import whose content the gate no longer blocks drops an incoming `embed_skip` (and a `content_flag`) whose reason is `oversized`; other skip reasons, quarantined pages and the sanity bypass keep them. `gbrain import` honors `errors > 0` for non-zero exit. `classifyErrorCode` in `src/core/sync.ts` recognizes the `PAGE_JUNK_PATTERN` code so sync-failures.jsonl grouping bins these. `extractEntityRefs` (canonical; matches both `[Name](../people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks), `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled` config helper. Link candidates match any dir-shaped path (existence-checked at persist). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. Pinned by `test/import-file-content-sanity.test.ts`. `importImageFile` records `source_path` on every image page and skips an unchanged image only when its index is complete for the run: a visual vector when embedding is on, and OCR (`ocr_status: 'done'` in frontmatter, or legacy stored OCR text) when OCR is enabled, so an image first imported under `--no-embed` or an OCR skip is rebuilt on its next import (`test/import-image-retry.test.ts`). `importCodeFile` writes `source_path: relativePath` on every code page (the same repo-relative path markdown imports record) so the full-sync reconcile — which only considers `source_path IS NOT NULL` rows — can retire a deleted code file's page; `putPage` COALESCEs the column, so rows imported before this keep NULL until the file changes, `sync --force`, or `gbrain reindex-code --force`. A frontmatter `slug:` that would become the page identity and ends in `.md`/`.mdx` is held as `frontmatter_slug_conflict` unless that exact (source_id, slug) page is live (`persistence/suffixed-slug.ts`).@@ -35,7 +35,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/markdown.ts` — Frontmatter parsing + body splitter. `coerceFrontmatterString(v)` coerces a non-string `title`/`slug`/`type` to a deterministic string at parse time so a YAML-typed value never reaches `.toLowerCase()` and throws (`title: 2024-06-01` parses as a `Date`, `title: 1458` as a number, and a throw would block the sync bookmark from advancing); a `Date` becomes its UTC ISO date (`2024-06-01`, machine-independent and matching the on-disk token, unlike `String(date)`), `null`/`undefined` become `''`, everything else uses `String()`. `splitBody` requires an explicit timeline sentinel (`<!-- timeline -->`, `--- timeline ---`, or `---` immediately before `## Timeline`/`## History`). Plain `---` in body text is a markdown horizontal rule, not a separator. `inferType` auto-types `/wiki/analysis/` → analysis, `/wiki/guides/` → guide, `/wiki/hardware/` → hardware, `/wiki/architecture/` → architecture, `/writing/` → writing (plus existing people/companies/deals/etc heuristics). `resolveSourceLocalFilePath` maps Git-root-relative `pages.source_path` values into a source whose `local_path` scopes a repo subdirectory; it finds the Git root with filesystem checks only, strips the exact root-relative scope, rejects unsafe/non-markdown paths, and when given a slug it tolerates historical basename-relative `source_path` rows by checking the slug directory only after the direct path is absent. It leaves write containment to the caller. After its pre-quote pass, a block the strict parse refuses goes to `recoverFrontmatter`; only `quote` recoveries are applied. Under `validate`, YAML_PARSE stays in `errors` (location-only message, `recoverable` plus a content-free `recovery` record), advisories go to `warnings` (`FRONTMATTER_RECOVERED`, `FRONTMATTER_COMMENT_VALUE`), and `recovery` carries interpretive, protected-key and identity-key findings. `HOLD_CODES` and `classifyImportHold(parsed, ctx)` define the ingestion hold set once; `isFrontmatterHoldMessage` recognizes its exact messages. Tests: `test/frontmatter-recovery.test.ts`.-- `src/core/quarantine.ts` — the two frontmatter markers the content-quality gate writes, sibling of `src/core/embed-skip.ts` (same marker-as-JSONB-object pattern, same JSONB `?` existence check that works on Postgres AND PGLite; no schema migration — both are frontmatter JSONB keys). `quarantine` (key `QUARANTINE_KEY`) HIDES: set ONLY for high-confidence junk, writes zero chunks, excluded from search via `quarantineFilterFragment(pageAlias)` / `QUARANTINE_FILTER_FRAGMENT` (the `p`-aliased constant), the single source of truth `buildVisibilityClause` calls so the search filter and marker key can't drift. `content_flag` (key `CONTENT_FLAG_KEY`) WARNS, does NOT hide: set for fuzzy markup-heavy / oversize, page stays searchable, marker is READ INTO search/get_page output — deliberately NO SQL filter fragment. Three distinct markers, three reasons (never overloaded): `embed_skip` = oversized-but-clean, `quarantine` = junk hidden, `content_flag` = odd-examine-still-here; a page can carry more than one (oversize → embed_skip + content_flag:oversized) and each clears independently. Exports `buildQuarantineMarker` / `isQuarantined` / `filterOutQuarantined`, `buildContentFlagMarker` / `getContentFlag` / `hasContentFlag`, plus the two key constants. Pinned by `test/quarantine.test.ts`. A quarantined page is skipped by every derived-data scan (stale listing via the engine-sql stale predicate, NER, meeting timeline projection, file walks via `quarantinedSlugs`, DB walks, the managed link derivation) and is not in the `links_extraction_lag` denominator. Pinned by `test/quarantine-extraction.test.ts`.+- `src/core/quarantine.ts` — the two frontmatter markers the content-quality gate writes, sibling of `src/core/embed-skip.ts` (same JSONB-object marker and `?` existence check on both engines; no migration). `quarantine` (key `QUARANTINE_KEY`) HIDES: set ONLY for high-confidence junk, writes zero chunks, excluded from search via `quarantineFilterFragment(pageAlias)` / `QUARANTINE_FILTER_FRAGMENT` (the `p`-aliased constant), the single source of truth `buildVisibilityClause` calls so the search filter and marker key can't drift. `content_flag` (key `CONTENT_FLAG_KEY`) WARNS, does NOT hide: set for fuzzy markup-heavy / oversize, page stays searchable, marker is READ INTO search/get_page output — deliberately NO SQL filter fragment. Three markers, three reasons: `embed_skip` = oversized-but-clean, `quarantine` = junk hidden, `content_flag` = odd-examine-still-here; a page can carry more than one (oversize → embed_skip + content_flag:oversized) and each clears independently. Exports `buildQuarantineMarker` / `isQuarantined` / `filterOutQuarantined`, `buildContentFlagMarker` / `getContentFlag` / `hasContentFlag`, plus the two key constants. Pinned by `test/quarantine.test.ts`. #6259: [quarantine cluster](quarantine.md). A quarantined page is skipped by every derived-data scan (stale listing via the engine-sql stale predicate, NER, meeting timeline projection, file walks via `quarantinedSlugs`, DB walks, the managed link derivation) and is not in the `links_extraction_lag` denominator. Pinned by `test/quarantine-extraction.test.ts`.- `src/core/repo-root.ts` — Shared `findRepoRoot(startDir?)`: walks up from `startDir` (default `process.cwd()`) looking for `skills/RESOLVER.md`. Zero-dependency, imported by `doctor.ts` and `check-resolvable.ts`; parameterized `startDir` makes tests hermetic. Read-path / write-path split: `autoDetectSkillsDir` (shared, read+write-safe) has tier-0 `$GBRAIN_SKILLS_DIR` operator override ahead of the 4-tier chain. `autoDetectSkillsDirReadOnly` wraps it with a tier-5 install-path fallback that walks up from `fileURLToPath(import.meta.url)` and gates on `isGbrainRepoRoot` so unrelated repos can't false-positive. Read-path callers (`doctor`, `check-resolvable`, `routing-eval`) use the read-only variant; write-path callers (`skillpack install`, `skillify scaffold`, `post-install-advisory`) stay on the shared function so install-from-`~` can't retarget the bundled gbrain `skills/` instead of the user's workspace. `SkillsDirSource` variants `'env_explicit'`, `'install_path'`; `AUTO_DETECT_HINT_READ_ONLY` documents the extra tier. The `--fix` safety gate in `doctor.ts` + `check-resolvable.ts` refuses auto-repair when `detected.source === 'install_path'`.diff --git a/docs/architecture/key-files/quarantine.md b/docs/architecture/key-files/quarantine.mdnew file mode 100644index 0000000000..26ba8a3983--- /dev/null+++ b/docs/architecture/key-files/quarantine.md@@ -0,0 +1,39 @@+# Content-quality quarantine (key files cluster)++[Subsystem index](../KEY_FILES.md).++What a page the content-quality gate hid as junk may do and what readers and+writers are told (#1699, #6259). The markers themselves are in+`src/core/quarantine.ts` ([files and sync](files-and-sync-1.md)); the operator+surface is `src/commands/quarantine.ts` ([commands](commands-4-continued.md)).++**Trust boundary.** `stripGateOwnedMarkers` (`src/core/import-screen.ts`,+called once by `importFromContent`) removes `GATE_OWNED_FRONTMATTER_KEYS`+(`quarantine`, `content_flag`, `embed_skip`, `atoms_scan_hash`,+`quarantine_override`) from every write unless an owner-tier path passes+`preserveGateMarkers: true`: `importFromFile`, managed sync+(`persistence/sync-prepare.ts`) and file import (`import-prepare.ts`), reindex,+file repair, reconcile, the cycle derivers and their `managed_maintenance_page`+intents (`persistence/page-prepare.ts`), `quarantine clear/scan`, and the+owner-internal put_page kind `managed_quarantine_clear`+(`persistence/page-mutations.ts` `OWNER_FILE_INTENTS`). Local put_page,+connectors and ingest lanes are not owner-tier. `opts.remote` keeps only its+fence-merge and hidden-row meaning. Test: `test/gate-marker-strip.test.ts`.++**Derived data.** `isFactsBackstopEligible` returns `quarantined`; the+canonical projection and the unmanaged fence reconcilers (`cycle/extract-facts.ts`,+`cycle/extract-takes.ts`) project no facts or takes for a quarantined page and+leave rows projected before it as they are. Tests: `test/facts-eligibility.test.ts`,+`test/quarantine-fence-projection.test.ts`.++**What callers see.** A put_page the gate quarantined reports+`quarantined: { reason, detail }` (`quarantineOutcome`, set in+`persistence/page-prepare.ts`) and one `page_quarantined` safety notice+(`pageQuarantinedNotice`, emitted by `emitFenceNotice` in `page-mutations.ts`;+put_pages marks each page and emits one notice in `page-batch.ts`). get_page+(`ops/pages.ts`) carries `quarantined` and the notice; an untrusted reader gets+no body unless it holds `admin` and passes `include_quarantined: true`.+Test: `test/quarantine-read-write-surface.test.ts`.++- `src/core/quarantine-override.ts` — #6259 (fix wave 12): the `quarantine_override` frontmatter key `gbrain quarantine clear --force` records: `{ binding, cleared_at }`, where `binding` is a sha256 over the classifier's inputs (title, type, body) as the gate canonicalizes them (`quarantineOverrideFor`). `assessImportSanity` (`import-screen.ts`) wraps its verdict in `withQuarantineOverride`, which removes the junk-pattern, literal and markup-flag outcomes while the binding is current (size outcomes stay). `importFromContent` calls `stripGateOwnedMarkers` (`import-screen.ts`, `GATE_OWNED_FRONTMATTER_KEYS`): every writer loses `quarantine`, `content_flag`, `embed_skip`, `atoms_scan_hash` and `quarantine_override` unless an owner-tier path passes `preserveGateMarkers: true` (`importFromFile`, managed sync and file import, reindex, file repair, reconcile, the cycle derivers and their `managed_maintenance_page` intents, `quarantine clear/scan` and the owner-internal `managed_quarantine_clear` put_page kind); local put_page, connectors and ingest lanes do not. A preserving path keeps its own override only while current, and a current override drops classifier markers the content still carries. `opts.remote` keeps only its fence-merge/hidden-row meaning. Tests: `test/gate-marker-strip.test.ts`. For a stripped write the classifier would hide or markup-flag, `carryStoredQuarantineOverride` reads the stored override and keeps it when it still binds (so a remote tag edit does not re-hide the page); a clean remote write reads nothing extra (#6007 statement budget). Company-brain inspection refuses files carrying it (`hidden_input`). Doctor's quarantine row names `clear <slug> --force` and `content_sanity.disabled_patterns`.+- `src/core/ops/get-page-projection.ts` — `projectGetPage` shapes the get_page response from the reader-visible body (#2225 `content`, content_only round-trip fields, `timeline_entries`, `file_held`). #6259: `quarantinedView` decides whether a quarantined page's body is withheld (`body_omitted` for an untrusted reader without `admin` + `include_quarantined`); a withheld body empties compiled_truth and timeline and drops `content`.diff --git a/src/core/persistence/page-batch.ts b/src/core/persistence/page-batch.tsindex 89a3b27773..2c81d6a580 100644--- a/src/core/persistence/page-batch.ts+++ b/src/core/persistence/page-batch.ts@@ -10,6 +10,7 @@* `put_pages` with only `request_id` reads the batch status without resending* any content.*/+import { pageQuarantinedNotice } from '../quarantine.ts';import type { OperationContext } from '../ops/contract.ts';import { fenceNormalizedNotice, mergeFencesNormalized, type FencesNormalized } from '../fence-repair/report.ts';import { OperationError, opError } from '../ops/contract.ts';@@ -96,6 +97,7 @@ function pageEntry(result: PageResult): Record<string, unknown> {status: outcome.status, ...(typeof outcome.slug === 'string' && outcome.slug !== result.slug ? { duplicate_of: outcome.slug } : {}),...(outcome.embedding_state !== undefined ? { embedding_state: outcome.embedding_state } : {}), ...warning,...(outcome.fences_normalized ? { fences_normalized: outcome.fences_normalized } : {}),+ ...(outcome.quarantined ? { quarantined: outcome.quarantined } : {}),...(outcome.timeline_rows_removed ? { timeline_rows_removed: outcome.timeline_rows_removed } : {}) };} catch (error) {if (!(error instanceof OperationError)) throw error;@@ -138,6 +140,10 @@ function batchReceipt(ctx: OperationContext, batchId: string, sourceId: string,// #6188 (D12, D21): one `fences_normalized` and one coaching notice for every page whose fence Tier 1 rewrote.const fences = mergeFencesNormalized(pages.flatMap(page => page.fences_normalized ? [page.fences_normalized as FencesNormalized] : []));if (fences) ctx.emitNotice?.(fenceNormalizedNotice(fences));+ // #6259: one safety notice for the pages the content-quality gate quarantined (each page carries `quarantined`).+ const hidden = pages.filter(page => page.quarantined);+ if (hidden.length) ctx.emitNotice?.(pageQuarantinedNotice(hidden.length === 1 ? String(hidden[0]!.slug) : `${hidden.length} pages (${hidden.slice(0, 3).map(page => page.slug).join(', ')}${hidden.length > 3 ? ', ...' : ''})`,+ hidden[0]!.quarantined as { reason: string; detail: string }, 'write'));return { batch_request_id: batchId, source_id: sourceId, state, terminal: pending === 0, counts: { total: pages.length, committed, pending, failed },...(retryAfterMs !== null ? { retry_after_ms: retryAfterMs } : {}), next, links, pages, ...(fences ? { fences_normalized: fences } : {}) };}diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex 830f9051a2..ec5bd0eaa6 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -1,4 +1,5 @@import { randomUUID } from 'node:crypto';+import { pageQuarantinedNotice } from '../quarantine.ts';import { fenceNormalizedNotice, type FencesNormalized } from '../fence-repair/report.ts';import { parseFenceRepairReceipt } from '../fence-repair/receipt.ts';import { realpathSync } from 'node:fs';@@ -162,6 +163,9 @@ function pendingAwareResponse(ctx: OperationContext, row: WriteRequest): Record<export function emitFenceNotice(ctx: Pick<OperationContext, 'emitNotice'>, response: Record<string, unknown>, slug?: string): void {const report = response.fences_normalized as FencesNormalized | undefined;if (report) ctx.emitNotice?.(fenceNormalizedNotice(report, slug));+ // #6259: a write the content-quality gate quarantined says so (`quarantined` plus one safety notice).+ const quarantined = response.quarantined as { reason: string; detail: string } | undefined;+ if (quarantined && slug) ctx.emitNotice?.(pageQuarantinedNotice(slug, quarantined, 'write'));}/** Owner-internal `put_page` kinds the trusted local file writers (import, frontmatter repair, quarantine clear) submit; every other caller is refused them. */diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 04a2df78e9..54f67dfbaa 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -1,5 +1,5 @@import { isEmbedSkipped } from '../embed-skip.ts';-import { isQuarantined } from '../quarantine.ts';+import { isQuarantined, quarantineOutcome } from '../quarantine.ts';import { existsSync, readFileSync } from 'node:fs';import { join, relative, sep } from 'node:path';import type { BrainEngine } from '../engine.ts';@@ -483,6 +483,8 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequestslug: row.slug, source_id: row.source_id, chunks: ready.result.chunks, noop,...(ready.result.chunks === 0 ? {chunk_skip_reason: noop ? 'write_skipped': isEmbedSkipped(ready.parsedPage.frontmatter) || isQuarantined(ready.parsedPage.frontmatter) ? 'embed_skip' : 'empty_body'} : {}),+ // #6259: say the gate hid the page, not only why it has no chunks.+ ...(!noop && quarantineOutcome(ready.parsedPage.frontmatter) ? { quarantined: quarantineOutcome(ready.parsedPage.frontmatter) } : {}),...(row.operation === 'capture' ? { channel: 'capture', content_hash: p.capture_hash } : {}),...(edited ? editDiff(row.slug, edited.before, edited.after) : {}), ...fencesNormalized, ...fenceRepairOutcome };} };diff --git a/test/quarantine-read-write-surface.test.ts b/test/quarantine-read-write-surface.test.tsnew file mode 100644index 0000000000..dbc7f82004--- /dev/null+++ b/test/quarantine-read-write-surface.test.ts@@ -0,0 +1,99 @@+/**+ * #6259 follow-up (quarantine leaks, items 4 and 6): what readers and writers+ * are told about a page the content-quality gate quarantined.+ * - get_page: a trusted local read keeps the body and carries `quarantined`+ * plus a `page_quarantined` safety notice; an untrusted read gets no body+ * (compiled_truth, timeline and `content` withheld) unless an admin-scoped+ * caller passes include_quarantined: true.+ * - put_page / put_pages: the result says `quarantined: { reason, detail }`+ * and carries one `page_quarantined` notice, not only chunk_skip_reason.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import type { Notice } from '../src/core/agent-output.ts';+import { operations } from '../src/core/operations.ts';+import { withEnv } from './helpers/with-env.ts';++const JUNK = (title: string) => `---\ntitle: ${title}\ntype: note\n---\n\nScraper notes: the page said "Cloudflare Ray ID: 8f2a" before any article.\n`;+const CLEAN = (title: string) => `---\ntitle: ${title}\ntype: note\n---\n\nOrdinary prose about the project and its plans.\n`;+let engine: PGLiteEngine;+const home = mkdtempSync(join(tmpdir(), 'gbrain-q-surface-'));+const env = { GBRAIN_HOME: home, GBRAIN_AUDIT_DIR: home };+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); });+afterAll(async () => { await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });++const op = (name: string) => operations.find(o => o.name === name)!;+function ctx(o: { remote?: boolean; scopes?: string[]; notices?: Notice[] } = {}): OperationContext {+ return { engine, config: { engine: 'pglite' }, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: o.remote ?? false,+ sourceId: 'default', deferEmbeds: true, ...(o.scopes ? { auth: { scopes: o.scopes, sourceId: 'default' } } : {}),+ ...(o.notices ? { emitNotice: (n: Notice) => o.notices!.push(n) } : {}) } as unknown as OperationContext;+}++describe('put_page and put_pages say the gate hid the page (#6259 item 6)', () => {+ test('put_page reports quarantined and one safety notice; a clean page reports neither', () => withEnv(env, async () => {+ const notices: Notice[] = [];+ const junk = await op('put_page').handler(ctx({ notices }), { slug: 'notes/junk-write', content: JUNK('Junk write') }) as Record<string, unknown>;+ expect(junk.quarantined).toEqual({ reason: 'junk_pattern', detail: 'cloudflare_ray_id' });+ expect(junk.chunk_skip_reason).toBe('embed_skip');+ expect(notices.map(n => [n.code, n.kind])).toEqual([['page_quarantined', 'safety']]);+ expect(notices[0]!.why).toContain('gbrain quarantine clear notes/junk-write --force');+ const clean: Notice[] = [];+ const ok = await op('put_page').handler(ctx({ notices: clean }), { slug: 'notes/clean-write', content: CLEAN('Clean write') }) as Record<string, unknown>;+ expect(ok.quarantined).toBeUndefined();+ expect(clean).toEqual([]);+ }));++ test('put_pages marks each quarantined page and emits one notice for the batch', () => withEnv(env, async () => {+ const notices: Notice[] = [];+ const batch = await op('put_pages').handler(ctx({ notices }), { request_id: randomUUID(), pages: [+ { slug: 'notes/batch-junk', content: JUNK('Batch junk') }, { slug: 'notes/batch-clean', content: CLEAN('Batch clean') }] }) as { pages: Array<Record<string, unknown>> };+ expect(batch.pages.map(p => [p.slug, p.quarantined ?? null])).toEqual([+ ['notes/batch-junk', { reason: 'junk_pattern', detail: 'cloudflare_ray_id' }], ['notes/batch-clean', null]]);+ expect(notices.filter(n => n.code === 'page_quarantined')).toHaveLength(1);+ }));+});++describe('get_page of a quarantined page (#6259 item 4)', () => {+ const read = (c: OperationContext, extra: Record<string, unknown> = {}) =>+ op('get_page').handler(c, { slug: 'notes/junk-write', include_content: true, ...extra }) as Promise<Record<string, unknown>>;++ test('a trusted local read keeps the body, with quarantined and a notice', () => withEnv(env, async () => {+ const notices: Notice[] = [];+ const page = await read(ctx({ notices }));+ expect(String(page.compiled_truth)).toContain('Cloudflare Ray ID');+ expect(String(page.content)).toContain('Cloudflare Ray ID');+ expect(page.quarantined).toMatchObject({ reason: 'junk_pattern', detail: 'cloudflare_ray_id', body_omitted: false });+ expect(notices.map(n => n.code)).toEqual(['page_quarantined']);+ }));++ test('an untrusted read gets no body (content_only included), and the notice says it was withheld', () => withEnv(env, async () => {+ for (const extra of [{}, { content_only: true }, { include_quarantined: true }]) {+ const notices: Notice[] = [];+ const page = await read(ctx({ remote: true, scopes: ['read'], notices }), extra);+ expect(page.quarantined).toMatchObject({ reason: 'junk_pattern', body_omitted: true });+ expect(page.content).toBeUndefined();+ expect(page.compiled_truth ?? '').toBe('');+ expect(page.timeline ?? '').toBe('');+ expect(JSON.stringify(page)).not.toContain('Cloudflare Ray ID: 8f2a');+ expect(notices[0]!.why).toContain('include_quarantined: true');+ }+ }));++ test('an admin-scoped untrusted caller sees the body only when it asks', () => withEnv(env, async () => {+ expect((await read(ctx({ remote: true, scopes: ['admin'] }))).quarantined).toMatchObject({ body_omitted: true });+ const page = await read(ctx({ remote: true, scopes: ['admin'] }), { include_quarantined: true });+ expect(page.quarantined).toMatchObject({ body_omitted: false });+ expect(String(page.content)).toContain('Cloudflare Ray ID');+ }));++ test('a clean page reads as before', () => withEnv(env, async () => {+ const page = await op('get_page').handler(ctx({ remote: true, scopes: ['read'] }), { slug: 'notes/clean-write' }) as Record<string, unknown>;+ expect(page.quarantined).toBeUndefined();+ expect(String(page.compiled_truth)).toContain('Ordinary prose');+ }));+});