Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts): a quarantined page is never offered to the facts backstop (#6259)
time-attack349feebb7807
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex 4be9a0d1b5..9a905c5bf5 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -6,7 +6,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/conversation-parser/` — 19-pattern built-in chat-format registry + opt-in LLM fallback. Modules: `types.ts` (PatternEntry + ParseResult + DateContext + CaptureMap + TimezonePolicy), `builtins.ts` (19 hand-vetted patterns sourced from public format docs — iMessage/Slack, Telegram bracket + text-export, bold-paren-time, bold-time-dash, bold-name-no-time, chatgpt-export-you-chatgpt, Discord classic + export, WhatsApp ISO + US, Signal, Matrix/Element, IRC classic + weechat, Teams export, markdown-heading-turn; module-load validation runs every `test_positive[]` + `test_negative[]` sample at startup so a typo in any built-in regex makes gbrain refuse to start; `DEFAULT_SPEAKER_CLEAN` exported as a module-level default), `parse.ts` (orchestrator with pattern-priority scoring across the first 10 lines + date derivation chain `explicit > frontmatter.date > effective_date > '1970-01-01'` + multi-line continuation + timezone warning; also populates `ParseResult.unrecognized_headings` — when the WINNING pattern is heading-anchored, heading-shaped lines whose label is outside the pattern's speaker set FOLD into the previous turn's body (or drop before the first anchor) while the parse still returns `regex_match`, silently crediting one speaker with another's words; detection is diagnostic-only and unconditional (not behind `opts.diagnostic` — the extractor's decline gate depends on it), fence-aware (a fence closes only on ITS OWN marker; an unclosed fence suppresses detection below it), labels deduped/capped at 10 entries ≤48 chars, undefined when empty so healthy-page JSON stays byte-identical; `gbrain conversation-parser scan` surfaces the field in both human and JSON output; `applyPattern` never DROPS a matched anchor whose date it cannot reconstruct (a localized month name, malformed digits) — dropping it would fold that speaker's body into the previous turn on a multi_line pattern, so the message opens anyway, inheriting the previous anchor's timestamp (page fallback date at midnight for the first), and the count surfaces as `ParseResult.date_fallback_count`, undefined when zero), `llm-base.ts` (shared `runLlmCall<T>` with content-hash cache in-process + DB-persistent via migration v97 + 4-strategy JSON repair + Anthropic-key probe; fallback is a thin wrapper), `llm-fallback.ts` (opt-IN; NO regex inference + NO persistence), `eval.ts` (`scoreFixture` + `aggregateScores` + `parseFixtureJsonl` for the fixture-corpus CI gate), `nightly-probe.ts` (DI-stubbed; mode-gated default tokenmax=ON, conservative/balanced opt-in; adversarial false-positive detection; an unreadable fixture returns `skipped` with `fixture_unavailable`, which the autopilot wiring audits, and the wiring reads the embedded fixtures from `cycle/nightly-probe-fixtures.ts`). Pattern `bold-name-no-time` (regex `/^\*\*(?!\[)(.+?):\*\*\s*(.*)$/`, ordered after the time-bearing bold patterns) parses `**Speaker:** text` with NO per-line timestamp (Circleback/Granola/Zoom), anchoring every message at `T00:00:00Z` of the frontmatter date (line order preserves sequence, same no-time convention as `irc-classic`); the `(?!\[)` lookahead rejects telegram-bracket `**[18:37] Name:**`; non-shadow is the colon-INSIDE-bold regex (NOT declaration order — `parse.ts` scores every candidate independently, order is only the tie-break). Because `**Label:** text` is a common prose idiom, the pattern sets optional `PatternEntry.score_full_body: true` so `parse.ts` recomputes the winner's acceptance score over the FULL body before the `SCORING_MIN_ACCEPTANCE` floor, keeping a bold-label notes page at `no_match`. Pattern `chatgpt-export-you-chatgpt` (regex `/^\*\*(You|ChatGPT):\*\*\s*(.*)$/`, declared just before `bold-name-no-time` so it wins the score tie on the two literal ChatGPT-export labels) parses ChatGPT's web-export → Markdown shape, where each turn's `**You:**` / `**ChatGPT:**` anchor is followed by a blank line and a multi-paragraph reply; `bold-name-no-time` alone cannot absorb that shape (`multi_line: false` scores a long reply's density near zero and falls below `SCORING_MIN_ACCEPTANCE`), so this pattern sets `multi_line: true` + `score_continuations_as_body: true` (excludes non-`**`-prefixed reply lines from the density denominator) + `score_full_body: true`. The speaker capture is a closed two-value enumeration (`You` or `ChatGPT` exactly, never an arbitrary `(.+?)` label), so it cannot reopen `bold-name-no-time`'s BROAD-REGEX GUARD against notes pages. Because a bare `**You:**`/`**ChatGPT:**` heading is plausible in prose ABOUT ChatGPT, the pattern also sets the optional `PatternEntry.score_continuations_min_distinct_speakers: 2`: `scoreFromLines` only grants the continuation-density-exclusion score when the anchor lines that fully match `regex` collectively capture at least that many DISTINCT `speaker_group` values, so a page with only one role falls back to the ordinary flat-density score. It ALSO sets `PatternEntry.score_continuations_max_preamble_lines: 5`, because one genuine pair embedded deep in an unrelated long document would otherwise pass: `scoreFromLines` tracks the index of the FIRST fully-matching anchor line and only grants the immunity when that index is at or before the bound (a short title preamble is tolerated). Pattern `bold-paren-time` parses `**Speaker** (HH:MM): text` and `(HH:MM:SS)` (date_source: frontmatter). Fallback gates: `SCORING_HEAD_TRIGGER_THRESHOLD = 0.3` triggers a full-body re-score when the head pass scores below that; `SCORING_MIN_ACCEPTANCE = 0.05` blocks essay false-positives. Exported `scorePatternFull(body, entry)`; private `getNonBlankLines(body, headCap?)` + `scoreFromLines(lines, entry)` DRY the quick_reject+regex loop. CLI surfaces at `src/commands/eval-conversation-parser.ts` (`gbrain eval conversation-parser <fixture.jsonl>` exit 0/1/2, wired into `bun run verify` via `check:conversation-parser`) and `src/commands/conversation-parser.ts` (`scan <slug>` debug, `list-builtins`, `validate <file>`). Doctor checks: `conversation_format_coverage`, `progressive_batch_audit_health`, `conversation_parser_probe_health`. Pinned by `test/conversation-parser/{parse,llm-base,llm-fallback,nightly-probe}.test.ts` + the 27-case baseline at `test/extract-conversation-facts.test.ts` (back-compat invariant). Migration v97 (`conversation_parser_llm_cache_table`). Fixtures at `test/fixtures/conversation-formats/{imessage,imessage-time-only-12h,telegram-bracket,whatsapp-iso,whatsapp-us,signal-export,irc-classic,irc-weechat,matrix-element,teams-export,all,adversarial,bold-name-no-time,bold-time-dash,chatgpt-export-you-chatgpt}.jsonl` with `scripts/check-fixture-privacy.sh` banning real-name leaks. Maintainer guidance: [conversation parser patterns](../conversation-parser-patterns.md).- `src/core/facts/conversation-types.ts` — single-source conversation-type allowlist (`ALLOWED_TYPES`: conversation, meeting, slack, email, imessage, imessage-daily + `AllowedType`). It also owns the granular collector aliases (`ALLOWED_TYPE_ALIASES`, `pageTypesForAllowed`) and the one eligibility rule (#5330): `isConversationFactsEligiblePage` and its SQL twin `conversationFactsEligibleSql` admit an allowed concrete type unless frontmatter says `conversation_parseable: false`; with `cycle.conversation_facts_backfill.require_parseable_flag` on, only `type: conversation` or `conversation_parseable: true`. The extractor (slug, batch and enumeration paths), the doctor backlog SQL and its in-process verifier, and the format-coverage sample all use it, so the backlog can drain. Every consumer derives from this frozen leaf module — `extract-conversation-facts.ts` (which re-exports both names verbatim for its existing importers), the cycle backfill phase, `doctor.ts` + `doctor/checks/search-eval.ts`, `sources.ts`, `jobs.ts` — so no hand-copied list can drift. It lives under `src/core/facts/` (not `src/commands/`) because `scripts/generate-flag-registry.ts` scans option-shaped literals one relative-import level deep — importing the constant straight from `extract-conversation-facts.ts` would transitively attribute that command's whole option surface to doctor/jobs/sources in the generated CLI_ONLY registry. Drift-guarded by `test/conversation-facts-type-allowlist-drift.test.ts`. `isFrontmatterFlagOff` (the same off spellings) is shared with `facts/eligibility.ts`.-- `src/core/facts/eligibility.ts` — `isFactsBackstopEligible`, the one automatic facts-extraction predicate (page-write outbox, its `body_unchanged` check, sync's post-import hook, the facts-absorb job's re-check). Skips `wiki/agents/`, `dream_generated: true`, `facts_backstop` set off (`opted_out`, #6232: a writer's opt-out for a page whose facts another page carries, such as a meeting's raw transcript; removing it re-offers the page even with an unchanged body), bodies under 80 characters, and types outside `ELIGIBLE_TYPES` unless the slug is under a rescue prefix. Receipt reasons are documented under `facts_backstop_skipped` in the error registry. Pinned by `test/facts-eligibility.test.ts`, `test/persistence-facts-backstop.test.ts`.+- `src/core/facts/eligibility.ts` — `isFactsBackstopEligible`, the one automatic facts-extraction predicate (page-write outbox, its `body_unchanged` check, sync's post-import hook, the facts-absorb job's re-check). Skips `wiki/agents/`, `dream_generated: true`, `facts_backstop` set off (`opted_out`, #6232: a writer's opt-out for a page whose facts another page carries, such as a meeting's raw transcript; removing it re-offers the page even with an unchanged body), bodies under 80 characters, and types outside `ELIGIBLE_TYPES` unless the slug is under a rescue prefix. Receipt reasons are documented under `facts_backstop_skipped` in the error registry. Pinned by `test/facts-eligibility.test.ts`, `test/persistence-facts-backstop.test.ts`. #6259: a quarantined page (the gate's `quarantine` marker) is ineligible with reason `quarantined`, which the page-write receipt reports as `facts_backstop.skipped` (registered in `facts_backstop_skipped`).- `src/core/facts/extract.ts` — the LLM facts extractor (`extractFactsFromTurnWithOutcome` and friends; the output cap, truncation retry, and salvage behavior are described under the trajectory entry). Deterministic junk gate: `isJunkFact(text, kind?)` tests `JUNK_FACT_PATTERNS` — assistant plan/offer narration, meta-narration about the conversation itself, provider billing/rate-limit strings captured verbatim — and is kind-aware: a candidate the extractor classified `commitment` is exempt from the plan-narration arm ONLY ("I'll send the deck by Friday" is a genuine commitment); meta-narration and provider-error strings are junk for every kind. `isJunkFilterEnabled(engine)` is the config kill switch (fail-open on a config read error); `getFactsExtractionPromptAppendix` supplies the config-driven prompt appendix. Entity gate at the candidate loop (the ONE seam where LLM-emitted entity tokens become `entity_slug`): `isUnknownSpeakerLabel` (anonymous diarizer labels — `Speaker A`, `SPEAKER_00`, `spk_0`, `other|unknown|guest`) and `isNullLikeEntity` (placeholder STRINGS `"null"`/`"None"`/`"n/a"` where the prompt asked for JSON null; shared with `write-single.ts`) both null the attribution and KEEP the fact, so no consumer can mint `entity_slug='null'` through the resolver's fallback slugify. The provider-error arm is start-anchored (`^\W*`, optional error/status token or a `<step> stopped|failed because …` prefix, then `(spend|rate) (limit|cap) … (hit|exceeded|reached)`), so a genuine fact that merely mentions a spend limit or rate limit mid-sentence survives; the verbatim provider strings still match. Two config keys: `facts.extraction_prompt_appendix` (non-empty text is appended to the extraction prompt) and `facts.extraction_junk_filter` (`false` disables the deterministic junk gate; default on), plus the opt-in `facts.extraction_missing_confidence` (stored when confidence is missing, null or non-numeric; unset keeps 1.0). A numeric-string confidence (`"0.3"`) is read as the stated value; unknown kinds are still stored as `fact` but counted in a stderr warning. Every extractor `chat()` call (first attempt, the #2113 truncation retry, the malformed-output retry) carries `responseSchema: FACTS_EXTRACTION_SCHEMA` (mirrors `RawExtracted`: `facts[]` of `{fact, kind ∈ ALL_EXTRACT_KINDS}` plus `entity/confidence/notability/metric/value/unit/period` — EVERY property in `required`, the optional ones nullable via type unions, `additionalProperties: false` at both levels, so the schema is OpenAI-strict-safe for proxies that honor the SDK's default `strict: true`); the gateway honors it only on openai-compatible recipes that declare structured outputs (Ollama's server-side grammar), so small local models cannot emit malformed JSON, while `parseExtractorJsonDetailed` still validates the reply text on every lane. Pinned by `test/facts-extract-structured-output.test.ts`.diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 2d4b3a8598..add9eb2fba 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -154,7 +154,7 @@ export const CODES = {fact_already_expired: { class: 'caller', summary: "The fact had already expired before this write." },fact_not_found: { class: 'caller', summary: "Fact not found." },facts_absorb_write_refused: { class: 'caller', summary: "Facts absorb refused the write." },- facts_backstop_skipped: { class: 'unavailable', summary: "A page write queued no automatic fact extraction; the receipt's `facts_backstop.skipped` reason says why (a `kind:<type>` reason names a page type that is not extracted).", reasons: ['opted_out', 'body_unchanged', 'extraction_disabled', 'dream_generated', 'subagent_namespace', 'too_short', 'no_parsed_page', 'slug_bound_client', 'operation_bound_client', 'not_imported', 'backstop_error'], docs: 'docs/guides/concurrent-writes.md#facts-backstop', suggestion: 'Nothing failed. `opted_out` means the page frontmatter sets `facts_backstop: false`; remove that line and save the page to extract it.', fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], consent: [], actor: 'agent', why: 'Shows the page frontmatter that decided the skip.', requires_exclusive: false } },+ facts_backstop_skipped: { class: 'unavailable', summary: "A page write queued no automatic fact extraction; the receipt's `facts_backstop.skipped` reason says why (a `kind:<type>` reason names a page type that is not extracted).", reasons: ['opted_out', 'quarantined', 'body_unchanged', 'extraction_disabled', 'dream_generated', 'subagent_namespace', 'too_short', 'no_parsed_page', 'slug_bound_client', 'operation_bound_client', 'not_imported', 'backstop_error'], docs: 'docs/guides/concurrent-writes.md#facts-backstop', suggestion: 'Nothing failed. `opted_out` means the page frontmatter sets `facts_backstop: false`; remove that line and save the page to extract it.', fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], consent: [], actor: 'agent', why: 'Shows the page frontmatter that decided the skip.', requires_exclusive: false } },facts_drain_deferred: { class: 'unavailable', summary: "The automatic facts drain left queued facts-absorb jobs waiting; `reason` says why and `fix`, when present, is the next step. Nothing is dropped: the jobs run on a later drain.", reasons: ['no_key', 'extraction_unavailable', 'budget_exhausted', 'daily_budget_exhausted', 'job_over_budget', 'no_pricing', 'provider_halted', 'drain_error'], docs: 'docs/guides/facts-drain.md#deferrals', suggestion: 'Read doctor `facts_drain`: its message names the cause and its fix the next step (raising a spend cap is paid; ask the user first).', fix: { argv: ['gbrain', 'doctor', '--only', 'facts_drain', '--json'], consent: [], actor: 'agent', why: 'Shows the drain status, the backlog and the last error with its fix.', requires_exclusive: false } },facts_drain_job_failed: { class: 'server', summary: "A facts-absorb job failed inside the automatic facts drain; it retries with backoff until its attempts run out.", docs: 'docs/guides/facts-drain.md#deferrals', suggestion: 'Read doctor `facts_drain`: its message names the cause and its fix the next step (raising a spend cap is paid; ask the user first).', fix: { argv: ['gbrain', 'doctor', '--only', 'facts_drain', '--json'], consent: [], actor: 'agent', why: 'Shows the drain status, the backlog and the last error with its fix.', requires_exclusive: false } },facts_payload_expired: { class: 'server', summary: "The accepted fact extraction failed and its retained payload has expired." },diff --git a/src/core/facts/eligibility.ts b/src/core/facts/eligibility.tsindex 9fa30adb1b..8d611f27f3 100644--- a/src/core/facts/eligibility.ts+++ b/src/core/facts/eligibility.ts@@ -37,6 +37,7 @@* groups by reason).*/+import { isQuarantined } from '../quarantine.ts';import type { PageType } from '../types.ts';import { isFrontmatterFlagOff } from './conversation-types.ts';@@ -91,6 +92,8 @@ export function isFactsBackstopEligible(): EligibilityResult {if (!parsed) return { ok: false, reason: 'no_parsed_page' };if (slug.startsWith('wiki/agents/')) return { ok: false, reason: 'subagent_namespace' };+ // #6259: the content-quality gate hid this page as junk; its text must not become facts.+ if (isQuarantined(parsed.frontmatter)) return { ok: false, reason: 'quarantined' };if (parsed.frontmatter && parsed.frontmatter.dream_generated === true) {return { ok: false, reason: 'dream_generated' };}diff --git a/test/facts-eligibility.test.ts b/test/facts-eligibility.test.tsindex 8e4ddafe09..e7952dacbd 100644--- a/test/facts-eligibility.test.ts+++ b/test/facts-eligibility.test.ts@@ -154,3 +154,15 @@ describe('#6232 facts_backstop opt-out', () => {expect(isFactsBackstopEligible('meetings/2026-05-09-kickoff', meeting)).toEqual({ ok: false, reason: 'opted_out' });});});++// #6259 (quarantine leaks, item 2): a page the content-quality gate hid as junk is never offered to the backstop.+describe('isFactsBackstopEligible — quarantined pages', () => {+ test('a quarantine marker makes an otherwise eligible page ineligible with reason quarantined', () => {+ const { slug, parsed } = fixture({ frontmatter: { quarantine: { reason: 'junk_pattern', detail: 'cloudflare_ray_id', assessed_at: '2026-10-07T00:00:00.000Z' } } });+ expect(isFactsBackstopEligible(slug, parsed)).toEqual({ ok: false, reason: 'quarantined' });+ });+ test('a content_flag (searchable, warned) leaves the page eligible', () => {+ const { slug, parsed } = fixture({ frontmatter: { content_flag: { reason: 'markup_heavy', detail: 'x', assessed_at: '2026-10-07T00:00:00.000Z' } } });+ expect(isFactsBackstopEligible(slug, parsed)).toEqual({ ok: true });+ });+});diff --git a/test/quarantine-override.serial.test.ts b/test/quarantine-override.serial.test.tsindex 19a78bca07..ad55af1fab 100644--- a/test/quarantine-override.serial.test.ts+++ b/test/quarantine-override.serial.test.ts@@ -126,6 +126,12 @@ describe('quarantine clear on a managed brain (#6259)', () => {expect(fm[QUARANTINE_OVERRIDE_KEY]).toBeUndefined();}), 120_000);+ test('a managed write the gate quarantines records facts_backstop.skipped quarantined in its receipt', () => run(async () => {+ const body = `${JUNK_BODY} ${'The rest of the note is ordinary prose that would otherwise be long enough to extract. '.repeat(2)}`;+ const response = await submitPageMutation(ctx(), { operation: 'put_page', params: { slug: 'notes/junk-facts', content: junkPage('Junk facts', body), request_id: randomUUID() } }) as Record<string, unknown>;+ expect(response.facts_backstop).toEqual({ skipped: 'quarantined' });+ }), 120_000);+test('a local managed put_page cannot plant gate-owned markers (only the clear\'s owner kind keeps its override)', () => run(async () => {const clean = '---\ntitle: Clean notes\ntype: note\nquarantine:\n reason: junk_pattern\n detail: planted\natoms_scan_hash: deadbeefdeadbeef\n---\n\nOrdinary prose with nothing junk-like in it.\n';const slug = 'notes/planted-managed';