Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(quarantine): clear works on managed brains, and --force records a content-bound override the gate keeps honoring (#6259)

time-attacka339ddc1114c
diff --git a/docs/architecture/key-files/commands-4-continued.md b/docs/architecture/key-files/commands-4-continued.md
index 443fe5575f..d97e2c0a4f 100644
--- a/docs/architecture/key-files/commands-4-continued.md
+++ b/docs/architecture/key-files/commands-4-continued.md
@@ -9,7 +9,8 @@ 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/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`.
+- `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 `settleQuarantineOverride` at its gate-owned strip: remote input loses any override and keeps the stored one only while the binding still holds (so a remote tag edit does not re-hide the page); trusted input keeps its own only while current; a current override also drops classifier markers the content still carries. 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/entrypoints-and-docs.md b/docs/architecture/key-files/entrypoints-and-docs.md
index 7520b7c6a9..b5cefa5497 100644
--- a/docs/architecture/key-files/entrypoints-and-docs.md
+++ b/docs/architecture/key-files/entrypoints-and-docs.md
@@ -121,7 +121,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers `handleCliOnly`'s explicit ordered pipeline (`@cliPipelineStage` functions: thin-client guard, deferred-persistence routing, subcommand and help routes, read-only timeout path, sync watchdog and delegation, connectEngine terminator with degraded-serve recovery, teardown), thin-client routing and refusal, help and self-help text, strict flag parsing and process-exit teardown. Per-command dispatch (pre- and post-connect) lives in the command table (entry below), not in `src/cli.ts`.
- `src/cli/remember-format.ts` — the `remember` human formatter (`formatRememberResult`: status, entity with `(inferred from mention)`, expiry, degraded dedup, `warnings` + `hint`), kept out of `src/cli.ts`; `--json` prints the raw envelope. Pinned by `test/remember-entity-inference.test.ts`.
-- `src/cli/subcommands.ts` + `src/cli/router-help.ts` + `src/cli/strict-args.ts` — help never acts (#6114). `subcommands.ts` holds each router command's inventory (`ROUTERS`: pages, cache, integrity, hook, search, edge-proposals, schema, config; each router re-exports its list as `SUBCOMMANDS` and types its dispatch over it, so an unlisted subcommand fails typecheck) and the help grammar: `--help`/`-h` anywhere before `--` (a flag-value slot included) and a bare `help` only as the first token after a router command or one of its subcommands (`search help` stays a query). `cli.ts` decides `cliHelpRequested` once, before the update marker, backup nag and key warnings; on help it calls `printRouterHelp`, which loads only the router's `printUsage`, before any subcommand, thin-client route or engine. `strict-args.ts` is the per-subcommand table for destructive subcommands (pages purge-deleted, cache clear/prune, schema use/downgrade/init/remove-*, integrity auto/reset-progress, search modes --reset): an argument the handler would ignore refuses with `invalid_params` (exit 2) after help and before dispatch, with a read-only fix that itself parses under the table (`ask_user` for integrity reset-progress). The flag-registry generator skips `strict-args.ts` (its literals belong to the commands it lists). Pinned by `test/cli-help-grammar.test.ts` and the four-part subprocess gate `test/cli-help-no-side-effects*.serial.test.ts` (harness `test/helpers/cli-help-gate.ts`, child probe `test/helpers/cli-side-effect-probe.ts`): every self-help command's `--help`/`-h` and every router subcommand's `--help`/`-h`/`help` on a copy of a seeded PGLite brain, asserting exit 0 with usage, unchanged table rows and HOME/cwd files, and no fetch or spawn.
+- `src/cli/subcommands.ts` + `src/cli/router-help.ts` + `src/cli/strict-args.ts` — help never acts (#6114). `subcommands.ts` holds each router command's inventory (`ROUTERS`: pages, cache, integrity, hook, search, edge-proposals, schema, config; each router re-exports its list as `SUBCOMMANDS` and types its dispatch over it, so an unlisted subcommand fails typecheck) and the help grammar: `--help`/`-h` anywhere before `--` (a flag-value slot included) and a bare `help` only as the first token after a router command or one of its subcommands (`search help` stays a query). `cli.ts` decides `cliHelpRequested` once, before the update marker, backup nag and key warnings; on help it calls `printRouterHelp`, which loads only the router's `printUsage`, before any subcommand, thin-client route or engine. `strict-args.ts` is the per-subcommand table for destructive subcommands (pages purge-deleted, cache clear/prune, schema use/downgrade/init/remove-*, integrity auto/reset-progress, search modes --reset): an argument the handler would ignore refuses with `invalid_params` (exit 2) after help and before dispatch, with a read-only fix that itself parses under the table (`ask_user` for integrity reset-progress). The flag-registry generator skips `strict-args.ts` (its literals belong to the commands it lists). Pinned by `test/cli-help-grammar.test.ts` and the four-part subprocess gate `test/cli-help-no-side-effects*.serial.test.ts` (harness `test/helpers/cli-help-gate.ts`, child probe `test/helpers/cli-side-effect-probe.ts`): every self-help command's `--help`/`-h` and every router subcommand's `--help`/`-h`/`help` on a copy of a seeded PGLite brain, asserting exit 0 with usage, unchanged table rows and HOME/cwd files, and no fetch or spawn. `quarantine` (list, clear, scan) is a router since #6259.
- `src/cli/command-table.ts` + `src/cli/commands/<name>.ts` — one record per CLI-only command (`name`, `phase`, `thinClient`, `selfHelp`, `skipStartupHooks`, `load: () => import('<literal>')`, and the agent-contract fields `json`, `read_only`, `startup`, `end_of_options`, `help: () => import('./help/<name>.ts')` — see `src/cli/help/` in [agent contract](agent-contract.md)). A `selfHelp` record whose handler needs an engine answers `--help` brainless through `SELF_HELP_WITHOUT_ENGINE` in `src/cli.ts` (an explicit loader, or `true` to run the record's own module with a null engine). The records derive `CLI_ONLY`, `CLI_ONLY_SELF_HELP`, `THIN_CLIENT_REFUSED_COMMANDS` and `STARTUP_HOOK_SKIP_COMMANDS` (re-exported from `src/cli.ts`); `cliAliases`' collision check runs over the derived `CLI_ONLY`. Each module holds the body its switch case or plain branch had, moved verbatim, and receives dispatcher-owned pieces through `CliDispatchContext`. Master's membership inconsistencies are preserved (the dead second `auth` branch, the unreachable `capture --help` branch, the `connectors` and `recall` refuse hints that only `connectEngine`'s thin-client backstop reaches (the static extractor reports them as never reached), `watch` refused without a hint, `eval whoknows` shadowed by the refusal) and pinned by `test/fixtures/goldens/cli/membership-sets.json`. Contract: `test/cli-command-table.test.ts`; engine lifecycle per path: `test/cli-dispatch-lifecycle.serial.test.ts`. `json` / `jsonSubcommands` declare the D2 `--json` contract (record-wide / per subcommand).
- `scripts/lib/cli-pipeline.ts` — flattens `handleCliOnly` (inlining `@cliPipelineStage` functions) and reads the command table by AST, for the W0 dispatch-shape extractor (`test/helpers/cli-dispatch-extract.ts`) and `scripts/generate-flag-registry.ts`.
diff --git a/src/cli/command-table.ts b/src/cli/command-table.ts
index c2c2fa9fea..54af2c3937 100644
--- a/src/cli/command-table.ts
+++ b/src/cli/command-table.ts
@@ -382,7 +382,8 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp
// `code-def`/`code-refs`/`code-callers`/`code-callees` have NO MCP ops in operations.ts:2630-2671;
// cannot be "fixed by routing" yet
{ name: 'pages', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/pages.ts') },
- { name: 'quarantine', phase: 'post-connect', thinClient: 'route-then-refuse', load: () => import('./commands/quarantine.ts') },
+ // selfHelp: #6259 router (list, clear, scan); its usage prints before any engine is opened.
+ { name: 'quarantine', phase: 'post-connect', thinClient: 'route-then-refuse', selfHelp: true, load: () => import('./commands/quarantine.ts') },
// selfHelp: v0.43 (#2095): watch ships WATCH_HELP (flags + the stdin-turn protocol).
// thin client: v0.43 (#2095): watch streams against a LOCAL engine; thin clients get the
// volunteer_context MCP op instead.
diff --git a/src/cli/router-help.ts b/src/cli/router-help.ts
index fd97c87041..12348382c2 100644
--- a/src/cli/router-help.ts
+++ b/src/cli/router-help.ts
@@ -20,6 +20,7 @@ export const ROUTER_MODULES: Readonly<Record<string, () => Promise<RouterModule>
'edge-proposals': () => import('../commands/edge-proposals.ts'),
schema: () => import('../commands/schema.ts'),
config: () => import('../commands/config.ts'),
+ quarantine: () => import('../commands/quarantine.ts'),
};
/**
diff --git a/src/cli/subcommands.ts b/src/cli/subcommands.ts
index 0936a5f0be..c999fd748f 100644
--- a/src/cli/subcommands.ts
+++ b/src/cli/subcommands.ts
@@ -24,6 +24,7 @@ export const HOOK_SUBCOMMANDS = ['session-start', 'user-prompt', 'stop', 'sessio
export const SEARCH_SUBCOMMANDS = ['modes', 'stats', 'tune', 'diagnose'] as const;
export const EDGE_PROPOSALS_SUBCOMMANDS = ['list', 'show', 'accept', 'reject', 'undo', 'date'] as const;
export const CONFIG_SUBCOMMANDS = ['show', 'get', 'set', 'unset'] as const;
+export const QUARANTINE_SUBCOMMANDS = ['list', 'clear', 'scan'] as const;
export const SCHEMA_SUBCOMMANDS = [
'active', 'list', 'show', 'validate', 'use', 'detect', 'suggest', 'review-candidates', 'init', 'fork', 'edit',
'diff', 'graph', 'lint', 'explain', 'review-orphans', 'downgrade', 'usage', 'stats', 'cardinality-preview',
@@ -50,6 +51,7 @@ export const ROUTERS: Readonly<Record<string, RouterInventory>> = {
'edge-proposals': { subcommands: EDGE_PROPOSALS_SUBCOMMANDS, bareHelpFirst: true },
schema: { subcommands: SCHEMA_SUBCOMMANDS, bareHelpFirst: true },
config: { subcommands: CONFIG_SUBCOMMANDS, bareHelpFirst: true },
+ quarantine: { subcommands: QUARANTINE_SUBCOMMANDS, bareHelpFirst: true },
};
/** `--help` / `-h` before any `--` terminator. */
diff --git a/src/commands/doctor/checks/content-quality.ts b/src/commands/doctor/checks/content-quality.ts
index a5bddb4d68..bcb856bf17 100644
--- a/src/commands/doctor/checks/content-quality.ts
+++ b/src/commands/doctor/checks/content-quality.ts
@@ -248,7 +248,7 @@ async function runQuarantine(ctx: DoctorContext): Promise<Check[]> {
name: 'quarantined_pages',
status: n > 0 ? 'warn' : 'ok',
message: n > 0
- ? `${n} page(s) quarantined as junk (hidden from search). Review with 'gbrain quarantine list'; clear a false positive with 'gbrain quarantine clear <slug>'.`
+ ? `${n} page(s) quarantined as junk (hidden from search). Review with 'gbrain quarantine list'; clear a false positive with 'gbrain quarantine clear <slug> --force' (it stays cleared until the page changes; a pattern that misfires brain-wide is turned off with content_sanity.disabled_patterns).`
: 'No quarantined pages',
});
} catch (err) {
diff --git a/src/commands/quarantine.ts b/src/commands/quarantine.ts
index 43a92aa603..339139d1ff 100644
--- a/src/commands/quarantine.ts
+++ b/src/commands/quarantine.ts
@@ -13,6 +13,15 @@ import type { BrainEngine } from '../core/engine.ts';
import { isQuarantined, getContentFlag, QUARANTINE_KEY, CONTENT_FLAG_KEY } from '../core/quarantine.ts';
import { serializePageToMarkdown, serializeMarkdown } from '../core/markdown.ts';
import { importFromContent } from '../core/import-file.ts';
+import { randomUUID } from 'node:crypto';
+import { loadConfig } from '../core/config.ts';
+import { opError, type OperationContext } from '../core/ops/contract.ts';
+import { readFix } from '../core/ops/op-fix.ts';
+import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';
+import { submitPageMutation } from '../core/persistence/page-mutations.ts';
+import { resolveCliWriteWaitMs } from '../core/persistence/write-wait.ts';
+import { QUARANTINE_OVERRIDE_KEY, quarantineOverrideFor } from '../core/quarantine-override.ts';
+import { reportPersistenceCliError } from './persistence-delegate.ts';
import type { PageType } from '../core/types.ts';
export interface QuarantineRow {
@@ -194,64 +203,81 @@ async function runClear(engine: BrainEngine, args: string[]): Promise<void> {
}
// sourceId is resolved above whenever ANY row exists; zero candidates means
// the page doesn't exist in any source, so the 'default' fallback read
- // returns null and we error below either way.
- const page = await engine.getPage(slug, { sourceId: sourceId ?? 'default' });
- if (!page) {
+ // returns null and we error below either way. One snapshot gives the page,
+ // its tags and the revision a managed write is conditioned on (#6259).
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: sourceId ?? 'default' });
+ if (!snapshot) {
console.error(`No page found for slug "${slug}"${sourceIdFlag ? ` in source "${sourceIdFlag}"` : ''}.`);
process.exit(2);
}
+ const page = snapshot.page;
const fm = { ...((page.frontmatter ?? {}) as Record<string, unknown>) };
if (!isQuarantined(fm) && !getContentFlag(fm)) {
console.log(`Page "${slug}" carries no quarantine or content_flag marker — nothing to clear.`);
return;
}
- // Drop both markers, then re-import through the normal pipeline so the page
+ // Drop both markers, then write the page through the normal pipeline so it
// re-chunks + re-embeds and becomes searchable again. The gate re-runs on
- // import: if the page is STILL detected as junk it re-quarantines (reported
- // below) unless --force bypasses the gate for this one import.
+ // that write: if the page is STILL detected as junk it re-quarantines
+ // (reported below). --force records a `quarantine_override` bound to the
+ // page's title, type and body, so this write and every later one keep the
+ // classifier's verdict off until that content changes. It never bypasses
+ // size gates or the write's revision check.
delete fm[QUARANTINE_KEY];
delete fm[CONTENT_FLAG_KEY];
- const tags = await engine.getTags(slug, { sourceId: page.source_id });
+ delete fm[QUARANTINE_OVERRIDE_KEY];
// Serialize from the CLEANED frontmatter directly (NOT serializePageToMarkdown,
// which re-spreads page.frontmatter as the base and would re-introduce the
// markers we just deleted).
- const markdown = serializeMarkdown(fm, page.compiled_truth ?? '', page.timeline ?? '', {
+ const serialize = (frontmatter: Record<string, unknown>) => serializeMarkdown(frontmatter, page.compiled_truth ?? '', page.timeline ?? '', {
type: (page.type as PageType) ?? 'note',
title: page.title ?? '',
- tags,
+ tags: snapshot.tags,
});
+ let markdown = serialize(fm);
+ if (force) markdown = serialize({ ...fm, [QUARANTINE_OVERRIDE_KEY]: quarantineOverrideFor(markdown, `${slug}.md`) });
- const prevNoSanity = process.env.GBRAIN_NO_SANITY;
- if (force) process.env.GBRAIN_NO_SANITY = '1';
- let result;
- try {
- result = await importFromContent(engine, slug, markdown, {
- sourceId: page.source_id,
- noEmbed,
- forceRechunk: true,
- });
- } finally {
- if (force) {
- if (prevNoSanity === undefined) delete process.env.GBRAIN_NO_SANITY;
- else process.env.GBRAIN_NO_SANITY = prevNoSanity;
+ let reQuarantined: boolean;
+ let flagged: boolean;
+ let flagReason: string | undefined;
+ if (await managedPersistenceEnabled(engine)) {
+ // A managed brain publishes through the canonical owner, like put and capture.
+ const ctx = { engine, config: loadConfig() ?? { engine: engine.kind }, remote: false, dryRun: false, sourceId: page.source_id,
+ writeWaitMs: resolveCliWriteWaitMs({ config: loadConfig() }),
+ logger: { info: () => {}, warn: (m: string) => console.error(m), error: (m: string) => console.error(m) } } as unknown as OperationContext;
+ try {
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug, source_id: page.source_id, content: markdown,
+ expected_revision: snapshot.revision, request_id: randomUUID() } });
+ } catch (error) {
+ if (await reportPersistenceCliError(error, json)) return;
+ throw error;
}
+ const after = (await engine.getPage(slug, { sourceId: page.source_id }))?.frontmatter as Record<string, unknown> | undefined;
+ reQuarantined = isQuarantined(after);
+ flagReason = getContentFlag(after)?.reason;
+ flagged = !!flagReason;
+ } else {
+ const result = await importFromContent(engine, slug, markdown, { sourceId: page.source_id, noEmbed, forceRechunk: true });
+ reQuarantined = result.quarantined === true;
+ flagged = result.flagged ?? false;
+ flagReason = result.flag_reason;
}
- const reQuarantined = result.quarantined === true;
if (json) {
- console.log(JSON.stringify({ slug, cleared: !reQuarantined, re_quarantined: reQuarantined, flagged: result.flagged ?? false, forced: force }, null, 2));
+ console.log(JSON.stringify({ slug, cleared: !reQuarantined, re_quarantined: reQuarantined, flagged, forced: force }, null, 2));
return;
}
if (reQuarantined) {
console.error(
`Page "${slug}" is STILL detected as junk — it remained quarantined. ` +
- `Edit the source file to fix it, or re-run with --force to clear it anyway.`,
+ `Edit the page so it no longer matches, or re-run with --force to record that it is not junk.`,
);
process.exit(1);
}
console.log(
`Cleared "${slug}".` +
- (result.flagged ? ` (now flagged: ${result.flag_reason} — searchable, agent warned.)` : '') +
+ (force ? ' It stays cleared until its title, type or body changes.' : '') +
+ (flagged ? ` (now flagged: ${flagReason} — searchable, agent warned.)` : '') +
(noEmbed ? ' Embedding skipped (--no-embed); run `gbrain embed --stale` to make it searchable.' : ''),
);
}
@@ -281,6 +307,15 @@ async function runScan(engine: BrainEngine, args: string[]): Promise<void> {
} catch { /* fall back to defaults if DB-config lift fails */ }
const scanLiterals = effCs.junk_patterns_enabled !== false ? loadOperatorLiterals() : [];
+ // #6259: --apply re-imports every page through the legacy path; a managed
+ // brain publishes only through its canonical owner, so refuse up front.
+ if (apply && await managedPersistenceEnabled(engine)) {
+ const error = opError('writer_coordinator_required', 'quarantine scan --apply cannot rewrite pages on a managed brain.',
+ 'It re-imports every page outside the canonical owner, so nothing was changed. Preview with gbrain quarantine scan (no --apply); new imports already pass the gate. Review hidden pages with gbrain quarantine list and clear a false positive with gbrain quarantine clear <slug> --force.',
+ { fix: readFix('Previews what the gate would mark, read-only.', { argv: ['gbrain', 'quarantine', 'scan', '--json'] }) });
+ if (!await reportPersistenceCliError(error, json)) throw error;
+ return;
+ }
const refs = await engine.listAllPageRefs();
let scanned = 0;
let quarantined = 0;
@@ -348,6 +383,27 @@ async function runScan(engine: BrainEngine, args: string[]): Promise<void> {
}
}
+export const QUARANTINE_HELP = `Usage: gbrain quarantine <list|clear|scan> [options]
+
+ list [--json] [--include-flagged]
+ Pages the content-quality gate hid as junk (quarantine), and with
+ --include-flagged the searchable pages it flagged (content_flag).
+ clear <slug> [--source-id <id>] [--force] [--no-embed] [--json]
+ Remove the markers and write the page again; the gate re-checks it.
+ --force records that the page is not junk (quarantine_override, bound
+ to its title, type and body): it stays cleared until those change.
+ On a managed brain the write goes through the canonical owner.
+ scan [--limit N] [--apply] [--no-embed] [--json]
+ Re-check existing pages against the gate (preview by default).
+ --apply re-imports them and is refused on a managed brain.
+
+One junk pattern that misfires brain-wide can be turned off with
+content_sanity.disabled_patterns.`;
+
+export { QUARANTINE_SUBCOMMANDS as SUBCOMMANDS } from '../cli/subcommands.ts';
+/** #6259: `gbrain quarantine --help` (router help, printed before any engine is opened). */
+export function printUsage(): void { console.log(QUARANTINE_HELP); }
+
export async function runQuarantine(engine: BrainEngine, args: string[]): Promise<void> {
const sub = args[0];
const rest = args.slice(1);
@@ -359,10 +415,7 @@ export async function runQuarantine(engine: BrainEngine, args: string[]): Promis
case 'scan':
return runScan(engine, rest);
default:
- console.error('Usage: gbrain quarantine <list|clear|scan> [...]');
- console.error(' list [--json] [--include-flagged]');
- console.error(' clear <slug> [--force] [--no-embed] [--json]');
- console.error(' scan [--limit N] [--apply] [--no-embed] [--json]');
+ console.error(QUARANTINE_HELP);
process.exit(2);
}
}
diff --git a/src/core/company-brain/inspection.ts b/src/core/company-brain/inspection.ts
index e9c77018f4..379e60fdbc 100644
--- a/src/core/company-brain/inspection.ts
+++ b/src/core/company-brain/inspection.ts
@@ -8,6 +8,7 @@ import { buildSourceLocalReferenceIndex, frontmatterReferenceHints } from '../so
import { slugifyPath } from '../sync.ts';
import { opError, OperationError } from '../ops/contract.ts';
import { QUARANTINE_KEY } from '../quarantine.ts';
+import { QUARANTINE_OVERRIDE_KEY } from '../quarantine-override.ts';
import { EMBED_SKIP_KEY } from '../embed-skip.ts';
import { loadResolvedPackByName } from '../schema-pack/load-active.ts';
import { invalidatePackCache, type ResolvedPack } from '../schema-pack/registry.ts';
@@ -109,7 +110,7 @@ function readPage(content: string, entry: InspectionEntry, plan: CompanyBrainPla
const path = entry.path;
const raw = parseDataFrontmatter(content).data;
canonical(raw, Math.min(plan.limits.maxMetadataBytes, 256 * 1024));
- if (Object.hasOwn(raw, QUARANTINE_KEY) || Object.hasOwn(raw, EMBED_SKIP_KEY)) {
+ if (Object.hasOwn(raw, QUARANTINE_KEY) || Object.hasOwn(raw, EMBED_SKIP_KEY) || Object.hasOwn(raw, QUARANTINE_OVERRIDE_KEY)) {
entry.disposition = 'unsupported';
entry.reason = 'hidden_input';
finding(plan, 'error', 'hidden_input', 'A reserved search-hiding marker is present. Review it or exclude this file before connecting; markers are never cleared automatically.', path);
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index 188f502a09..ff62d2ddd1 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -3,6 +3,7 @@ import { suffixedFrontmatterSlugHold } from './persistence/suffixed-slug.ts';
import { maintenanceTransaction } from './persistence/attribution.ts';
import { assertImportBase, sameCanonicalImport, sameContentAnyKeyOrder } from './page-state/import-guard.ts';
import { stabilizeSafetyAssessments } from './persistence/reconcile-safety.ts';
+import { settleQuarantineOverride } from './quarantine-override.ts';
import { decideImportIdentity, collidingSlugOwner, fileOriginUri } from './import-identity.ts';
import { readSourceFileSync } from './minions/source-filesystem.ts';
import { readFileSync, statSync, lstatSync } from 'fs';
@@ -360,6 +361,7 @@ export async function importFromContent(
// trusted "this looks odd" channel) on clean content. Only the content-
// sanity gate (below) and trusted local CLIs may set these. Fail-closed:
// strip whenever opts.remote === true.
+ await settleQuarantineOverride(engine, parsed, slug, sourceId, opts.remote === true);
if (opts.remote === true && parsed.frontmatter) {
delete parsed.frontmatter[QUARANTINE_KEY];
delete parsed.frontmatter[CONTENT_FLAG_KEY];
diff --git a/src/core/import-screen.ts b/src/core/import-screen.ts
index 280abcb00d..0dcd5ec7fe 100644
--- a/src/core/import-screen.ts
+++ b/src/core/import-screen.ts
@@ -11,6 +11,7 @@
import type { BrainEngine } from './engine.ts';
import { loadConfig, loadConfigWithEngine } from './config.ts';
import { assessContentSanity, type ContentSanityResult } from './content-sanity.ts';
+import { withQuarantineOverride } from './quarantine-override.ts';
import { loadOperatorLiterals } from './content-sanity-literals.ts';
import { classifyImportHold, contentSizeHold, parseMarkdown, type ContentHold, type ParseOpts, type ParsedMarkdown } from './markdown.ts';
import { isCodeFilePath } from './sync.ts';
@@ -56,8 +57,9 @@ export async function loadImportSanityConfig(engine: BrainEngine): Promise<Impor
};
}
-export function assessImportSanity(page: Pick<ParsedMarkdown, 'compiled_truth' | 'timeline' | 'title' | 'type'>, cfg: ImportSanityConfig): ContentSanityResult {
- return assessContentSanity({
+/** #6259: a page carrying a current `quarantine_override` keeps the classifier's verdict off (see quarantine-override.ts). */
+export function assessImportSanity(page: Pick<ParsedMarkdown, 'compiled_truth' | 'timeline' | 'title' | 'type'> & { frontmatter?: Record<string, unknown> }, cfg: ImportSanityConfig): ContentSanityResult {
+ return withQuarantineOverride(assessContentSanity({
compiled_truth: page.compiled_truth,
timeline: page.timeline ?? '',
title: page.title,
@@ -69,7 +71,7 @@ export function assessImportSanity(page: Pick<ParsedMarkdown, 'compiled_truth' |
extra_literals: cfg.extraLiterals,
// #4702: the file plane is hand-edited JSON.
disabled_patterns: Array.isArray(cfg.cs.disabled_patterns) ? cfg.cs.disabled_patterns : undefined,
- });
+ }), page);
}
/**
diff --git a/src/core/quarantine-override.ts b/src/core/quarantine-override.ts
new file mode 100644
index 0000000000..a3756dd7c6
--- /dev/null
+++ b/src/core/quarantine-override.ts
@@ -0,0 +1,90 @@
+/**
+ * #6259 (fix wave 12, W1.2): an operator's decision that a quarantined page is
+ * not junk, recorded as the `quarantine_override` frontmatter key.
+ *
+ * The content-quality gate re-derives `quarantine` and `content_flag` on every
+ * import, so deleting the marker never sticks: the next sync (or the owner's
+ * publication) re-stamps it. `gbrain quarantine clear <slug> --force` writes
+ * this key instead. It is bound to the page's title, type and body: while
+ * they are unchanged the gate keeps its classifier verdict (junk patterns,
+ * operator literals, markup ratio) off the page; any change to them expires
+ * the override and the gate decides again. Size gates (oversize `embed_skip`)
+ * are not overridden.
+ *
+ * Trust: only trusted local callers set it. Every untrusted ingress strips it
+ * (the gate-owned strip in `import-file.ts`, which remote put_page,
+ * put_pages, HTTP and ingest-capture all reach through `remote: true`); a
+ * remote edit that leaves title, type and body unchanged carries the stored
+ * override forward, so an unrelated tag edit does not re-hide the page.
+ * Company-brain inspection refuses files that carry it.
+ */
+import type { BrainEngine } from './engine.ts';
+import type { ContentSanityResult } from './content-sanity.ts';
+import { parseMarkdown, type ParsedMarkdown } from './markdown.ts';
+import { sanitizeText } from './batch-rows.ts';
+import { sha256 } from './persistence/digest.ts';
+import { CONTENT_FLAG_KEY, QUARANTINE_KEY } from './quarantine.ts';
+
+export const QUARANTINE_OVERRIDE_KEY = 'quarantine_override';
+
+export interface QuarantineOverride { binding: string; cleared_at: string }
+
+type Bound = Pick<ParsedMarkdown, 'title' | 'type' | 'compiled_truth' | 'timeline'>;
+
+/** What the override is bound to: the classifier's inputs (title, type, body). */
+export function quarantineOverrideBinding(page: Bound): string {
+ return sha256(JSON.stringify(['quarantine_override/v1', page.title ?? '', page.type ?? '', page.compiled_truth ?? '', page.timeline ?? '']));
+}
+
+/** The override for `markdown` exactly as the import gate will parse and canonicalize it. */
+export function quarantineOverrideFor(markdown: string, path: string, now = new Date()): QuarantineOverride {
+ const parsed = parseMarkdown(markdown, path, { validate: true });
+ return { binding: quarantineOverrideBinding({ title: sanitizeText(parsed.title), type: parsed.type,
+ compiled_truth: sanitizeText(parsed.compiled_truth), timeline: sanitizeText(parsed.timeline) }), cleared_at: now.toISOString() };
+}
+
+function overrideOf(value: unknown): QuarantineOverride | null {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
+ const { binding, cleared_at } = value as Record<string, unknown>;
+ return typeof binding === 'string' && /^[0-9a-f]{64}$/.test(binding) && typeof cleared_at === 'string' ? { binding, cleared_at } : null;
+}
+
+/** Whether `page` carries an override bound to its current title, type and body. */
+export function hasCurrentQuarantineOverride(page: Bound & { frontmatter?: Record<string, unknown> | null }): boolean {
+ const override = overrideOf(page.frontmatter?.[QUARANTINE_OVERRIDE_KEY]);
+ return !!override && override.binding === quarantineOverrideBinding(page);
+}
+
+/**
+ * Called by the import gate before it assesses `parsed` (already canonicalized).
+ * Remote input loses any override it carries, then keeps the stored one only
+ * when it still binds this content; trusted input keeps its own override only
+ * while it binds. A stale or malformed override is dropped.
+ */
+export async function settleQuarantineOverride(engine: Pick<BrainEngine, 'executeRaw'>, parsed: ParsedMarkdown,
+ slug: string, sourceId: string | undefined, remote: boolean): Promise<void> {
+ if (remote) {
+ delete parsed.frontmatter[QUARANTINE_OVERRIDE_KEY];
+ const [stored] = await engine.executeRaw<{ override: unknown }>(
+ `SELECT frontmatter->'${QUARANTINE_OVERRIDE_KEY}' AS override FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL`, [sourceId ?? 'default', slug]);
+ const carried = overrideOf(stored?.override);
+ if (carried && carried.binding === quarantineOverrideBinding(parsed)) parsed.frontmatter[QUARANTINE_OVERRIDE_KEY] = carried;
+ } else if (Object.hasOwn(parsed.frontmatter, QUARANTINE_OVERRIDE_KEY) && !hasCurrentQuarantineOverride(parsed)) {
+ delete parsed.frontmatter[QUARANTINE_OVERRIDE_KEY];
+ }
+ // A classifier marker the content still carries (a file written before the clear) goes with a current override.
+ if (!hasCurrentQuarantineOverride(parsed)) return;
+ delete parsed.frontmatter[QUARANTINE_KEY];
+ if ((parsed.frontmatter[CONTENT_FLAG_KEY] as { reason?: unknown } | undefined)?.reason !== 'oversized') delete parsed.frontmatter[CONTENT_FLAG_KEY];
+}
+
+/** The gate verdict with the classifier's hide and markup-flag outcomes removed for an overridden page; size outcomes stay. */
+export function withQuarantineOverride(result: ContentSanityResult, page: Bound & { frontmatter?: Record<string, unknown> | null }): ContentSanityResult {
+ if (!hasCurrentQuarantineOverride(page)) return result;
+ const classifier = new Set(['junk_pattern', 'literal_substring', 'high_markup']);
+ const kept = result.reasons.map((reason, i) => [reason, result.reason_messages[i]] as const).filter(([reason]) => !classifier.has(reason));
+ return { ...result, junk_pattern_matches: [], literal_substring_matches: [],
+ reasons: kept.map(([reason]) => reason), reason_messages: kept.map(([, message]) => message!).filter(Boolean),
+ shouldQuarantine: false, shouldHardBlock: false, shouldSkipEmbed: result.oversize, shouldFlag: result.oversize,
+ flag_reason: result.oversize ? 'oversized' : null };
+}
diff --git a/test/company-brain-inspect.test.ts b/test/company-brain-inspect.test.ts
index 4863c6a134..113c623568 100644
--- a/test/company-brain-inspect.test.ts
+++ b/test/company-brain-inspect.test.ts
@@ -83,7 +83,7 @@ describe('company-brain committed inspection', () => {
expect(codes(plan)).toContain('restricted_audience');
});
- test.each(['quarantine', 'embed_skip'])('blocks a search-hiding marker: %s', async marker => {
+ test.each(['quarantine', 'embed_skip', 'quarantine_override'])('blocks a search-hiding marker: %s', async marker => {
const root = await repo({ 'notes/hidden.md': page('note', `${marker}: null\n`) });
const before = snapshot(root);
const plan = await inspect(root);
diff --git a/test/quarantine-override.serial.test.ts b/test/quarantine-override.serial.test.ts
new file mode 100644
index 0000000000..dfb9d2787c
--- /dev/null
+++ b/test/quarantine-override.serial.test.ts
@@ -0,0 +1,222 @@
+/**
+ * #6259 (fix wave 12, W1.2): `gbrain quarantine clear` on a managed brain and
+ * the `quarantine_override` an operator's --force records.
+ *
+ * Protects: a managed clear publishes through the canonical owner with the
+ * snapshot's expected revision (it used to refuse writer_coordinator_required);
+ * --force keeps the page cleared across later writes of the same title, type
+ * and body, and any change to them re-arms the gate; a concurrent edit makes
+ * the clear a revision conflict, never an overwrite; a pending receipt is not
+ * reported as cleared; untrusted writers (remote put_page / put_pages) can
+ * neither plant nor renew an override, while a remote edit that leaves the
+ * classifier's inputs unchanged keeps it.
+ *
+ * Named `.serial.test.ts`: it captures console output and sets process env.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { operations } from '../src/core/operations.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { runQuarantine, QUARANTINE_HELP } from '../src/commands/quarantine.ts';
+import { getContentFlag, isQuarantined } from '../src/core/quarantine.ts';
+import { QUARANTINE_OVERRIDE_KEY } from '../src/core/quarantine-override.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { activateSharedSkillPersistence } from '../src/core/persistence/skill-activation.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { localHostId } from '../src/core/persistence/identity.ts';
+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
+import { PENDING_WRITE_EXIT_CODE } from '../src/core/exit-codes.ts';
+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+
+const JUNK_BODY = 'Our scraper analysis: the headless browser stopped at a page that said "Cloudflare Ray ID: 8f2a" before any article text.';
+const junkPage = (title = 'Scraper notes', body = JUNK_BODY, extra = '') => `---\ntitle: ${title}\ntype: note\n${extra}---\n\n${body}\n`;
+const SLUG = 'notes/scraper-notes';
+
+let engine: BrainEngine;
+let close: () => Promise<void>;
+let home: string;
+let root: string;
+
+class Exited extends Error { constructor(readonly code: number | undefined) { super(`process.exit(${code})`); } }
+/** Captures console output; a process.exit becomes `exit` instead of ending the test runner. */
+async function capture(fn: () => Promise<void>): Promise<{ out: string; err: string; exit?: number }> {
+ const [log, error, exit] = [console.log, console.error, process.exit];
+ const out: string[] = [], err: string[] = [];
+ let code: number | undefined;
+ console.log = (...a: unknown[]) => { out.push(a.map(String).join(' ')); };
+ console.error = (...a: unknown[]) => { err.push(a.map(String).join(' ')); };
+ process.exit = ((c?: number) => { throw new Exited(c); }) as typeof process.exit;
+ try { await fn(); } catch (e) { if (!(e instanceof Exited)) throw e; code = e.code; }
+ finally { console.log = log; console.error = error; process.exit = exit; }
+ return { out: out.join('\n'), err: err.join('\n'), ...(code === undefined ? {} : { exit: code }) };
+}
+const ctx = (remote = false) => ({ engine, config: { engine: engine.kind, embedding_disabled: true }, sourceId: 'default', remote, dryRun: false,
+ deferEmbeds: true, logger: { info() {}, warn() {}, error() {} } }) as unknown as OperationContext;
+const frontmatter = async () => (await engine.getPage(SLUG, { sourceId: 'default' }))?.frontmatter as Record<string, unknown>;
+const managedPut = async (content: string) => {
+ const snapshot = await engine.readPageSnapshot(SLUG, { sourceId: 'default' });
+ return submitPageMutation(ctx(), { operation: 'put_page', params: { slug: SLUG, content, request_id: randomUUID(), ...(snapshot ? { expected_revision: snapshot.revision } : {}) } });
+};
+
+beforeAll(async () => {
+ home = realpathSync.native(mkdtempSync(join(tmpdir(), 'gbrain-quarantine-6259-')));
+ ({ engine, close } = await isolatedSharedSkillsEngine());
+}, 120_000);
+afterAll(async () => {
+ await withEnv({ GBRAIN_HOME: home }, async () => { await disposePersistenceConsumer(engine); });
+ await close(); rmSync(home, { recursive: true, force: true });
+});
+beforeEach(() => { _resetCliExitVerdictForTests(); });
+
+describe('quarantine clear on a managed brain (#6259)', () => {
+ const run = (fn: () => Promise<void>) => withEnv({ GBRAIN_HOME: home, GBRAIN_AUDIT_DIR: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, fn);
+
+ test('setup: a managed source whose page the gate quarantined', () => run(async () => {
+ root = join(home, 'content'); mkdirSync(root);
+ await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [root]);
+ await claimWorktree(engine, 'default', root, localHostId());
+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });
+ await managedPut(junkPage());
+ expect(isQuarantined(await frontmatter())).toBe(true);
+ }), 120_000);
+
+ test('without --force the gate re-checks the page and it stays quarantined', () => run(async () => {
+ const { err, exit } = await capture(() => runQuarantine(engine, ['clear', SLUG]));
+ expect(err).not.toContain('writer_coordinator_required');
+ expect(isQuarantined(await frontmatter())).toBe(true);
+ expect(err).toContain('STILL detected as junk');
+ expect(exit).toBe(1);
+ }), 120_000);
+
+ test('--force publishes through the owner with a binding override and the page is searchable again', () => run(async () => {
+ const { out } = await capture(() => runQuarantine(engine, ['clear', SLUG, '--force']));
+ expect(out).toContain(`Cleared "${SLUG}"`);
+ const fm = await frontmatter();
+ expect(isQuarantined(fm)).toBe(false);
+ expect(fm[QUARANTINE_OVERRIDE_KEY]).toMatchObject({ binding: expect.stringMatching(/^[0-9a-f]{64}$/) });
+ // The canonical file the owner published carries the override, so a later sync of it keeps the page cleared.
+ expect(readFileSync(join(root, `${SLUG}.md`), 'utf8')).toContain(`${QUARANTINE_OVERRIDE_KEY}:`);
+ }), 120_000);
+
+ test('writing the same title, type and body again keeps it cleared (the canonical file, re-submitted)', () => run(async () => {
+ await managedPut(readFileSync(join(root, `${SLUG}.md`), 'utf8'));
+ expect(isQuarantined(await frontmatter())).toBe(false);
+ }), 120_000);
+
+ test('a changed title or body expires the override and the gate decides again', () => run(async () => {
+ const file = readFileSync(join(root, `${SLUG}.md`), 'utf8');
+ await managedPut(file.replace('title: Scraper notes', 'title: Scraper notes, revised'));
+ let fm = await frontmatter();
+ expect(isQuarantined(fm)).toBe(true);
+ expect(fm[QUARANTINE_OVERRIDE_KEY]).toBeUndefined();
+ await capture(() => runQuarantine(engine, ['clear', SLUG, '--force']));
+ expect(isQuarantined(await frontmatter())).toBe(false);
+ await managedPut(readFileSync(join(root, `${SLUG}.md`), 'utf8').replace(JUNK_BODY, `${JUNK_BODY} Another line.`));
+ fm = await frontmatter();
+ expect(isQuarantined(fm)).toBe(true);
+ expect(fm[QUARANTINE_OVERRIDE_KEY]).toBeUndefined();
+ }), 120_000);
+
+ test('an edit landing after the clear read the page is a revision conflict, not an overwrite', () => run(async () => {
+ const original = engine.readPageSnapshot.bind(engine);
+ let raced = false, inside = false;
+ // Transaction engines inherit from `engine`, so the original's own nested call lands here too: pass it through.
+ engine.readPageSnapshot = (async (...args: Parameters<BrainEngine['readPageSnapshot']>) => {
+ if (inside) return original(...args);
+ inside = true;
+ let snapshot: Awaited<ReturnType<BrainEngine['readPageSnapshot']>>;
+ try { snapshot = await original(...args); } finally { inside = false; }
+ if (!raced && args[0] === SLUG) {
+ raced = true;
+ delete (engine as { readPageSnapshot?: unknown }).readPageSnapshot;
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => {
+ const page = (await tx.getPage(SLUG, { sourceId: 'default' }))!;
+ await tx.putPage(SLUG, { type: page.type, title: page.title, compiled_truth: `${JUNK_BODY} A concurrent edit.`, frontmatter: page.frontmatter }, { sourceId: 'default' });
+ }, TEST_WRITE_ATTRIBUTION));
+ }
+ return snapshot;
+ }) as BrainEngine['readPageSnapshot'];
+ try {
+ const { err } = await capture(() => runQuarantine(engine, ['clear', SLUG, '--force']));
+ expect(err).toContain('revision_conflict');
+ } finally { delete (engine as { readPageSnapshot?: unknown }).readPageSnapshot; }
+ expect(raced).toBe(true);
+ expect((await engine.getPage(SLUG, { sourceId: 'default' }))!.compiled_truth).toContain('A concurrent edit.');
+ expect(isQuarantined(await frontmatter())).toBe(true);
+ expect(currentExitCode()).toBe(1);
+ }), 120_000);
+
+ test('a pending receipt is reported as pending, never as cleared', () => run(async () => {
+ await disposePersistenceConsumer(engine);
+ const { out, err } = await withEnv({ GBRAIN_WRITE_WAIT_MS: '0' }, () => capture(() => runQuarantine(engine, ['clear', SLUG, '--force'])));
+ expect(out).not.toContain('Cleared');
+ expect(err).toContain('write_pending');
+ expect(err).toContain('Poll: gbrain write-request');
+ expect(currentExitCode()).toBe(PENDING_WRITE_EXIT_CODE);
+ }), 120_000);
+
+ test('scan --apply refuses on a managed brain and changes nothing', () => run(async () => {
+ const before = await engine.executeRaw('SELECT slug,knowledge_revision FROM pages ORDER BY id');
+ const { err } = await capture(() => runQuarantine(engine, ['scan', '--apply']));
+ expect(err).toContain('writer_coordinator_required');
+ expect(err).toContain('gbrain quarantine clear <slug> --force');
+ expect(currentExitCode()).toBe(1);
+ expect(await engine.executeRaw('SELECT slug,knowledge_revision FROM pages ORDER BY id')).toEqual(before);
+ }), 120_000);
+
+ test('help lists the subcommands and flags', () => {
+ for (const text of ['list', 'clear <slug>', '--source-id', '--force', '--no-embed', 'scan', '--apply', 'content_sanity.disabled_patterns']) expect(QUARANTINE_HELP).toContain(text);
+ });
+});
+
+describe('untrusted writers and quarantine_override (#6259)', () => {
+ const run = (fn: () => Promise<void>) => withEnv({ GBRAIN_HOME: home, GBRAIN_AUDIT_DIR: home }, async () => {
+ const { engine: plain, close: closePlain } = await isolatedSharedSkillsEngine();
+ const saved = engine;
+ engine = plain;
+ try { await fn(); } finally { engine = saved; await closePlain(); }
+ });
+ const put = async (content: string, remote: boolean) => {
+ const snapshot = await engine.readPageSnapshot(SLUG, { sourceId: 'default' });
+ return operations.find(o => o.name === 'put_page')!.handler(ctx(remote), { slug: SLUG, content, ...(snapshot ? { expected_revision: snapshot.revision } : {}) });
+ };
+ const forged = `${QUARANTINE_OVERRIDE_KEY}:\n binding: ${'a'.repeat(64)}\n cleared_at: 2026-10-07T00:00:00.000Z\n`;
+
+ test('remote put_page and put_pages cannot plant an override', () => run(async () => {
+ await put(junkPage(undefined, undefined, forged), true);
+ let fm = await frontmatter();
+ expect(isQuarantined(fm)).toBe(true);
+ expect(fm[QUARANTINE_OVERRIDE_KEY]).toBeUndefined();
+ await operations.find(o => o.name === 'put_pages')!.handler(ctx(true), { request_id: randomUUID(), pages: [
+ { slug: 'notes/batch-junk', content: junkPage('Batch notes', JUNK_BODY, forged) }] });
+ fm = (await engine.getPage('notes/batch-junk', { sourceId: 'default' }))!.frontmatter as Record<string, unknown>;
+ expect(isQuarantined(fm)).toBe(true);
+ expect(fm[QUARANTINE_OVERRIDE_KEY]).toBeUndefined();
+ }), 120_000);
+
+ test('a remote edit keeps a current override only while title, type and body are unchanged', () => run(async () => {
+ await importFromContent(engine, SLUG, junkPage(), { noEmbed: true });
+ await capture(() => runQuarantine(engine, ['clear', SLUG, '--force', '--no-embed']));
+ const cleared = await frontmatter();
+ expect(isQuarantined(cleared)).toBe(false);
+ // A tag edit leaves the classifier's inputs unchanged: the stored override carries forward.
+ await put(junkPage(undefined, undefined, 'tags: [scraping]\n'), true);
+ expect(isQuarantined(await frontmatter())).toBe(false);
+ expect((await frontmatter())[QUARANTINE_OVERRIDE_KEY]).toEqual(cleared[QUARANTINE_OVERRIDE_KEY]);
+ // A remote body edit cannot renew it.
+ await put(junkPage(undefined, `${JUNK_BODY} Remote addition.`, forged), true);
+ const fm = await frontmatter();
+ expect(isQuarantined(fm)).toBe(true);
+ expect(fm[QUARANTINE_OVERRIDE_KEY]).toBeUndefined();
+ expect(getContentFlag(fm)).toBeNull();
+ }), 120_000);
+});