Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(extract): keep quarantined pages out of derived-data scans and extraction-health denominators (#5556)

time-attackc7415d34d0ad
diff --git a/scripts/check-engine-sql-dynamic.ts b/scripts/check-engine-sql-dynamic.ts
index 8763328f1d..115b47f7d3 100644
--- a/scripts/check-engine-sql-dynamic.ts
+++ b/scripts/check-engine-sql-dynamic.ts
@@ -54,6 +54,7 @@ const VETTED_BUILDERS: Record<string, string> = {
pageReadFilter: 'src/core/search/read-policy-sql.ts: binds scope values as params, splices only the caller alias',
buildRecencyComponentSql: 'src/core/search/sql-ranking.ts: inlines LIKE literals + numeric coefficients from the decay map, as master (planner behavior)',
privatePagesFilterFragment: 'src/core/search/private-visibility.ts: constant visibility predicate over a caller alias',
+ quarantineFilterFragment: 'src/core/quarantine.ts: constant quarantine predicate over a caller alias',
currentCodeEdgeFilter: 'src/core/code-intel/read-scope.ts: constant current-edge predicate over a caller alias',
buildCJKKeywordSql: 'src/core/search/cjk-keyword-sql.ts: binds the query as params; shared by both engines',
currentTextProjectionFilter: 'src/core/search/safe-chunks.ts: constant projection predicate over a caller alias',
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index fdd3fc99fc..06e4cb770a 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -8,7 +8,7 @@ src/commands/autopilot.ts 1642 ratchet refactor wave 1 split target (W4 autopilo
src/commands/doctor.ts 667 ratchet +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts
src/commands/embed.ts 2227 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts)
src/commands/extract-conversation-facts.ts 2188 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch); +2 fix wave 10 (#6037, issue #6033): explicit-slug page failures are contained per page through one bounded failure logger (recordPageFailure) shared with the pooled path; +4 fix wave 10 (#5120): facts.default_visibility resolved once per run (resolveDefaultVisibility) and applied to extracted rows only
-src/commands/extract.ts 2541 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured)
+src/commands/extract.ts 2547 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured); +6 fix wave 10 lane L1 #5556: quarantined pages skipped by the file walks, slug lists and DB walks (slug lookup in quarantine.ts quarantinedSlugs)
src/commands/jobs.ts 666 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5); +2 spend authorization: jobs submit --yes/--max-usd and jobs list --group help lines; +4 fix wave 9: supervisor stop help documents the 45 s wait, --queue and the verified-drain exit codes
src/commands/serve-http.ts 926 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts)
src/core/ai/gateway.ts 4425 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts)
@@ -42,4 +42,4 @@ src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap a
src/core/ops/pages.ts 671 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose
src/core/search/mode.ts 1594 ratchet +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part)
src/commands/eval-longmemeval.ts 1518 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts)
-src/commands/doctor/checks/extraction-sync.ts 1510 ratchet new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs
+src/commands/doctor/checks/extraction-sync.ts 1511 ratchet new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import)
diff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.ts
index 8697cfe796..7063297b61 100644
--- a/src/commands/doctor/checks/extraction-sync.ts
+++ b/src/commands/doctor/checks/extraction-sync.ts
@@ -26,6 +26,7 @@ import { slugifyPath, slugifyCodePath, isCodeFilePath } from '../../../core/sync
import { resolveSourceLocalFilePath } from '../../../core/markdown.ts';
import { scannerSlugRootMode } from '../../../core/write-through.ts';
import { unverifiedExtractionFragment } from '../../../core/extraction-review.ts';
+import { quarantineFilterFragment } from '../../../core/quarantine.ts';
import { managedPersistenceEnabled } from '../../../core/persistence/ownership.ts';
import { upstreamFreshness } from '../../../core/sync-upstream.ts';
import type { Check } from '../../doctor.ts';
@@ -109,8 +110,8 @@ export async function checkLinksExtractionLag(
try {
const totalRows = await engine.executeRaw<{ count: number }>(
sourceId
- ? `SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL AND source_id = $1`
- : `SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL`,
+ ? `SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL AND ${quarantineFilterFragment('pages')} AND source_id = $1`
+ : `SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL AND ${quarantineFilterFragment('pages')}`,
sourceId ? [sourceId] : [],
);
const total = Number(totalRows[0]?.count ?? 0);
diff --git a/src/commands/extract-timeline-db.ts b/src/commands/extract-timeline-db.ts
index 50c3cccaa3..064b1b67c9 100644
--- a/src/commands/extract-timeline-db.ts
+++ b/src/commands/extract-timeline-db.ts
@@ -35,6 +35,7 @@ import { createProgress } from '../core/progress.ts';
import { importAnalyzeEveryPages, maybeRefreshPlannerStats } from '../core/planner-stats.ts';
import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';
import { filterRefsSince } from './extract.ts';
+import { isQuarantined } from '../core/quarantine.ts';
const BATCH_SIZE = 100;
export const TIMELINE_EXTRACT_INTENT = 'managed_maintenance_timeline_extract';
@@ -159,7 +160,7 @@ export async function extractTimelineFromDB(engine: BrainEngine, opts: TimelineD
}
const page = await engine.getPage(slug, { sourceId: source_id });
- if (!page) continue;
+ if (!page || isQuarantined(page.frontmatter)) continue;
if (opts.typeFilter && page.type !== opts.typeFilter) continue;
const fullContent = page.compiled_truth + '\n' + page.timeline;
if (!opts.dryRun) await retractRemovedTimelineEntries(engine, slug, source_id, fullContent);
@@ -245,7 +246,7 @@ async function writePageTimeline(tx: BrainEngine, page: Page, slug: string, sour
async function publishPageTimeline(engine: BrainEngine, authority: MaintenanceAuthority, slug: string, sourceId: string,
opts: TimelineDbOptions): Promise<number | null | 'skipped' | 'pending'> {
const snapshot = await engine.readPageSnapshot(slug, { sourceId });
- if (!snapshot || (opts.typeFilter && snapshot.page.type !== opts.typeFilter)) return null;
+ if (!snapshot || isQuarantined(snapshot.page.frontmatter) || (opts.typeFilter && snapshot.page.type !== opts.typeFilter)) return null;
const plan = await plannedTimeline(engine, snapshot.page, slug, sourceId, opts.inferDates === true);
if (!plan.removed && !plan.entries.length) return 0;
for (let attempt = 0; ; attempt++) {
diff --git a/src/commands/extract.ts b/src/commands/extract.ts
index 0bb3f58892..fdea7ee510 100644
--- a/src/commands/extract.ts
+++ b/src/commands/extract.ts
@@ -86,6 +86,7 @@ import { formatMentionSummary, linkPhaseDeadline, mentionJsonFields, previewMent
import {
loadOpCheckpoint, recordCompleted, clearOpCheckpoint, mentionsFingerprint,
} from '../core/op-checkpoint.ts';
+import { isQuarantined, quarantinedSlugs } from '../core/quarantine.ts';
// v0.41.15.0 (T7, D9): --workers N for the fs-walk inner loops via the
// shared sliding-pool helper + PGLite-clamp wrapper.
import { runSlidingPool } from '../core/worker-pool.ts';
@@ -1308,6 +1309,7 @@ async function extractForSlugs(
// every non-slug filename as a deleted file and skip it without a word.
const slugToPath = buildSlugPathIndex(allFiles);
const allSlugs = new Set(slugToPath.keys());
+ const quarantined = await quarantinedSlugs(engine, sourceId ?? 'default');
const doLinks = mode === 'links' || mode === 'all';
const doTimeline = mode === 'timeline' || mode === 'all';
@@ -1391,7 +1393,7 @@ async function extractForSlugs(
onItem: async (slug) => {
// #1972: bail before doing any work for this slug on abort. The trailing
// flushTimeline still commits accumulated rows — no torn write.
- if (isAborted(signal)) return;
+ if (isAborted(signal) || quarantined.has(slug)) return;
const relPath = resolveSlugRelPath(slugToPath, brainDir, slug);
if (relPath === undefined) return; // deleted file — sync already handled removal
const fullPath = join(brainDir, relPath);
@@ -1472,6 +1474,7 @@ async function extractLinksFromDir(
const stdoutQuiet = jsonMode || quiet;
const files = walkMarkdownFiles(brainDir);
const allSlugs = new Set(files.map(f => pathToSlug(f.relPath)));
+ const quarantined = await quarantinedSlugs(engine, sourceId ?? 'default');
// Issue #972: read once before the walk so the per-file calls don't
// re-query the DB. globalBasename = true emits one edge per basename
@@ -1502,7 +1505,7 @@ async function extractLinksFromDir(
failureLabel: (f) => f.relPath,
onItem: async (file) => {
// #1972: bail before this file on abort; each page's links are replaced in its own transaction.
- if (isAborted(signal)) return;
+ if (isAborted(signal) || quarantined.has(pathToSlug(file.relPath))) return;
try {
const slug = pathToSlug(file.relPath);
const snapshot = ownership && (ownership.metadata.get(`${sourceId ?? 'default'}\0${slug}`)?.type === 'meeting' || ownership.origins.has(slug))
@@ -1554,6 +1557,7 @@ async function extractTimelineFromDir(
): Promise<{ created: number; pages: number }> {
const stdoutQuiet = jsonMode || quiet;
const files = walkMarkdownFiles(brainDir);
+ const quarantined = await quarantinedSlugs(engine, sourceId ?? 'default');
const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));
progress.start('extract.timeline_fs', files.length);
@@ -1586,7 +1590,7 @@ async function extractTimelineFromDir(
failureLabel: (f) => f.relPath,
onItem: async (file) => {
// #1972: bail before this file on abort; trailing flush() commits the batch.
- if (isAborted(signal)) return;
+ if (isAborted(signal) || quarantined.has(pathToSlug(file.relPath))) return;
try {
const content = readFileSync(file.path, 'utf-8');
const slug = pathToSlug(file.relPath);
@@ -1679,6 +1683,7 @@ export async function extractLinksForSlugs(
// frontmatter knob without per-caller threading — an unattended sync used to
// skip `related:` edges and then stamp the page fresh, defeating the knob.
const includeFrontmatter = opts?.includeFrontmatter ?? await resolveIncludeFrontmatter(engine);
+ const quarantined = await quarantinedSlugs(engine, sourceId);
let created = 0;
// Only a slug whose file was found AND read counts as processed. The
// caller stamps the watermark for these and no others, so a silent skip
@@ -1687,7 +1692,7 @@ export async function extractLinksForSlugs(
const errors: Array<{ slug: string; error: string }> = [];
const reads: Array<{ slug: string; relPath: string; content: string; links: LinkBatchInput[] }> = [];
for (const slug of slugs) {
- const relPath = resolveSlugRelPath(slugToPath, repoPath, slug);
+ const relPath = quarantined.has(slug) ? undefined : resolveSlugRelPath(slugToPath, repoPath, slug);
if (relPath === undefined) continue;
try {
// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- relPath comes from the slug→path index built by walkMarkdownFiles(repoPath) (repo-relative entries of that walk) or the validated-slug legacy fallback, never from a caller
@@ -1731,11 +1736,12 @@ export async function extractTimelineForSlugs(
// across every source containing the slug (the addTimelineEntry's
// INSERT...SELECT-from-pages fan-out was Data R1's HIGH 2).
const entryOpts = opts?.sourceId ? { sourceId: opts.sourceId } : undefined;
+ const quarantined = await quarantinedSlugs(engine, opts?.sourceId ?? 'default');
let created = 0;
const processed: string[] = [];
const errors: Array<{ slug: string; error: string }> = [];
for (const slug of slugs) {
- const relPath = resolveSlugRelPath(slugToPath, repoPath, slug);
+ const relPath = quarantined.has(slug) ? undefined : resolveSlugRelPath(slugToPath, repoPath, slug);
if (relPath === undefined) continue;
// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- relPath comes from the walkMarkdownFiles(repoPath) index or the validated-slug legacy fallback, never from a caller
const filePath = join(repoPath, relPath);
@@ -1873,7 +1879,7 @@ async function extractLinksFromDB(
for (const { slug, source_id } of walkRefs) {
const snapshot = await engine.readPageSnapshot(slug, { sourceId: source_id });
- if (!snapshot) continue;
+ if (!snapshot || isQuarantined(snapshot.page.frontmatter)) continue;
const page = snapshot.page;
if (typeFilter && page.type !== typeFilter) continue;
await loadSourceLinkPacks(engine, [source_id], packs);
@@ -2400,7 +2406,7 @@ async function extractMentionsFromDb(
// itself a completed decision. (#4304: the --since filter moved to the
// ref level above — out-of-window pages never reach this loop.)
const key = `${source_id}::${slug}`;
- if (!page || (typeFilter && page.type !== typeFilter)) {
+ if (!page || isQuarantined(page.frontmatter) || (typeFilter && page.type !== typeFilter)) {
pendingForFlush.push(key);
unpersistedCount++;
continue;
diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.ts
index f498962efb..db5ccf1931 100644
--- a/src/core/engine-sql/pages.ts
+++ b/src/core/engine-sql/pages.ts
@@ -22,6 +22,7 @@ import { moveSlugBindings, recordRenameAlias } from '../page-state/rename-alias.
import { sanitizeText } from '../batch-rows.ts';
import { SAFE_FENCE_CHUNKER_VERSION, bodyWriteChunkVersion } from '../search/safe-chunks.ts';
import { privatePagesFilterFragment, privateSnapshotFilterFragment } from '../search/private-visibility.ts';
+import { quarantineFilterFragment } from '../quarantine.ts';
import { validateSlug, contentHash, isBlankBody, rowToPage, rowToStalePage, isUndefinedTableError, warnOncePerProcess } from '../utils.ts';
import { DELETE_BATCH_SIZE } from '../engine-constants.ts';
import { jsonbParam, type SqlExecutor } from './executor.ts';
@@ -664,7 +665,8 @@ function stalePagesWhere(opts?: { sourceId?: string; versionTs?: string; attenda
const attendance = opts?.attendance === 'exclude'
? sqlFragment` AND links_attendance_blocked_revision IS DISTINCT FROM knowledge_revision`
: opts?.attendance === 'blocked' ? sqlFragment` AND links_attendance_blocked_revision = knowledge_revision` : sqlFragment``;
- return sqlFragment`deleted_at IS NULL AND ${version}${source}${attendance}`;
+ // A quarantined page is hidden from search; it is neither re-extracted nor counted as stale.
+ return sqlFragment`deleted_at IS NULL AND ${trustedSql(quarantineFilterFragment('pages'))} AND ${version}${source}${attendance}`;
}
export async function countStalePagesForExtraction(exec: ScopedRead, opts?: { sourceId?: string; versionTs?: string; attendance?: 'exclude' | 'blocked' }): Promise<number> {
diff --git a/src/core/extract-ner.ts b/src/core/extract-ner.ts
index ef19cf7147..b366c24912 100644
--- a/src/core/extract-ner.ts
+++ b/src/core/extract-ner.ts
@@ -21,6 +21,7 @@ import { buildGazetteer, findMentionedEntities, type Gazetteer } from './by-ment
import { isCrossSourceLinksEnabled } from './link-extraction.ts';
import { inferLinkTypeFromPack } from './schema-pack/link-inference.ts';
import { loadActivePackForLocalEngine, packSupportsNerInference } from './schema-pack/best-effort.ts';
+import { isQuarantined } from './quarantine.ts';
export interface ExtractNerOpts {
/** When true: enumerate but don't write. */
@@ -157,7 +158,7 @@ export async function extractNerLinks(
for (const { slug, source_id } of allRefs) {
const page = await engine.getPage(slug, { sourceId: source_id });
- if (!page) continue;
+ if (!page || isQuarantined(page.frontmatter)) continue;
if (opts.typeFilter && page.type !== opts.typeFilter) continue;
if (sinceMs !== null) {
const updatedMs = new Date(page.updated_at).getTime();
diff --git a/src/core/extract-timeline-from-meetings.ts b/src/core/extract-timeline-from-meetings.ts
index 425390c86e..db6b460926 100644
--- a/src/core/extract-timeline-from-meetings.ts
+++ b/src/core/extract-timeline-from-meetings.ts
@@ -16,6 +16,7 @@ import { isCrossSourceLinksEnabled } from './link-extraction.ts';
import { computeEffectiveDate } from './effective-date.ts';
import { parseFrontmatter } from './backfill-effective-date.ts';
import { isPrivatePage } from './search/private-visibility.ts';
+import { quarantineFilterFragment } from './quarantine.ts';
export interface ExtractTimelineFromMeetingsOpts {
dryRun?: boolean;
@@ -87,6 +88,7 @@ export async function extractTimelineFromMeetings(
FROM pages
WHERE ${MEETING_PAGE_PREDICATE}
AND deleted_at IS NULL
+ AND ${quarantineFilterFragment('pages')}
${sourceFilter}
ORDER BY effective_date DESC NULLS LAST, slug`,
meetingParams,
diff --git a/src/core/persistence/links-maintenance.ts b/src/core/persistence/links-maintenance.ts
index bbd83b7d06..5d7edafc38 100644
--- a/src/core/persistence/links-maintenance.ts
+++ b/src/core/persistence/links-maintenance.ts
@@ -1,5 +1,6 @@
import type { BrainEngine } from '../engine.ts';
import { LINK_EXTRACTOR_VERSION_TS } from '../link-extraction.ts';
+import { isQuarantined } from '../quarantine.ts';
import { prepareAutomaticLinks } from './links-preparation.ts';
import { withCoordinatedWrite } from './context.ts';
import { maintenanceAttribution } from './attribution.ts';
@@ -74,7 +75,7 @@ export async function extractManagedStaleLinks(engine: BrainEngine,
opts.signal?.throwIfAborted();
done.add(`${sourceId}\0${slug}`);
const snapshot = await engine.readPageSnapshot(slug, { sourceId });
- if (!snapshot) return;
+ if (!snapshot || isQuarantined(snapshot.page.frontmatter)) return;
const prepared = await prepareAutomaticLinks(engine, slug, snapshot.page, sourceId);
const outcome = await engine.transaction(async tx => withCoordinatedWrite(tx, [sourceId], async () => {
await tx.lockPageKeys(prepared.pageKeys);
diff --git a/src/core/quarantine.ts b/src/core/quarantine.ts
index 9c7bbb0429..0d5a4f8b35 100644
--- a/src/core/quarantine.ts
+++ b/src/core/quarantine.ts
@@ -31,6 +31,8 @@
* site (this module).
*/
+import type { BrainEngine } from './engine.ts';
+
// ---------------------------------------------------------------------------
// quarantine marker (HIDES)
// ---------------------------------------------------------------------------
@@ -95,6 +97,14 @@ export function filterOutQuarantined<T extends { frontmatter?: Record<string, un
return pages.filter((p) => !isQuarantined(p.frontmatter ?? null));
}
+/** Slugs of a source's live quarantined pages (the SQL marker test), for
+ * file walks that never read the page row before deriving links/timeline. */
+export async function quarantinedSlugs(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<Set<string>> {
+ const rows = await engine.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages WHERE source_id = $1 AND deleted_at IS NULL AND NOT ${quarantineFilterFragment('pages')}`, [sourceId]);
+ return new Set(rows.map((row) => row.slug));
+}
+
// ---------------------------------------------------------------------------
// content_flag marker (WARNS, does NOT hide)
// ---------------------------------------------------------------------------
diff --git a/test/fixtures/goldens/sql-text/pages.json b/test/fixtures/goldens/sql-text/pages.json
index 7bab5bc9f4..65a77c244e 100644
--- a/test/fixtures/goldens/sql-text/pages.json
+++ b/test/fixtures/goldens/sql-text/pages.json
@@ -10,8 +10,8 @@
"string",
"string"
],
- "sql": "SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL AND (links_extracted_at IS NULL OR links_extracted_at < $1::timestamptz OR updated_at > links_extracted_at) AND source_id = $2 AND links_attendance_blocked_revision = knowledge_revision",
- "textSha256": "be4f84c6281e3977a29eab4c2d35b5cab52a54f87936fb84eed35ac55b5a3bf3"
+ "sql": "SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL AND NOT (COALESCE(pages.frontmatter, '{}'::jsonb) ? 'quarantine') AND (links_extracted_at IS NULL OR links_extracted_at < $1::timestamptz OR updated_at > links_extracted_at) AND source_id = $2 AND links_attendance_blocked_revision = knowledge_revision",
+ "textSha256": "8dee8759d1d3fa1291deaa8744fbb18f2f0f3b2c97680df152ddac71046aa077"
}
],
"attendance-exclude": [
@@ -20,16 +20,16 @@
"params": [
"string"
],
- "sql": "SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL AND (links_extracted_at IS NULL OR links_extracted_at < $1::timestamptz OR updated_at > links_extracted_at) AND links_attendance_blocked_revision IS DISTINCT FROM knowledge_revision",
- "textSha256": "ac18ba62c816b3be4564d5a24bdc69304c45d24022c7ade0de8a81d0b36e3123"
+ "sql": "SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL AND NOT (COALESCE(pages.frontmatter, '{}'::jsonb) ? 'quarantine') AND (links_extracted_at IS NULL OR links_extracted_at < $1::timestamptz OR updated_at > links_extracted_at) AND links_attendance_blocked_revision IS DISTINCT FROM knowledge_revision",
+ "textSha256": "54f7d9f57c21651a059808468d5c235760e080580b4ce3ed3355811769e86a7b"
}
],
"default": [
{
"lane": "pool",
"params": [],
- "sql": "SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL AND (links_extracted_at IS NULL OR updated_at > links_extracted_at)",
- "textSha256": "3f9c86c575246f3a4f112b931aa51361c5e7b4c165330c026843dcb614072c94"
+ "sql": "SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL AND NOT (COALESCE(pages.frontmatter, '{}'::jsonb) ? 'quarantine') AND (links_extracted_at IS NULL OR updated_at > links_extracted_at)",
+ "textSha256": "8d9eac67843892ab0e9ccfcd25a1d5f5c3c2afd51b72dcedce29e718dc58b6c8"
}
],
"versionTs+sourceId": [
@@ -39,8 +39,8 @@
"string",
"string"
],
- "sql": "SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL AND (links_extracted_at IS NULL OR links_extracted_at < $1::timestamptz OR updated_at > links_extracted_at) AND source_id = $2",
- "textSha256": "fb4400e83c4a8ed0cf977fad5a1bd11c8336d3be942ba26f6e15486c2561dc3a"
+ "sql": "SELECT count(*)::int AS count FROM pages WHERE deleted_at IS NULL AND NOT (COALESCE(pages.frontmatter, '{}'::jsonb) ? 'quarantine') AND (links_extracted_at IS NULL OR links_extracted_at < $1::timestamptz OR updated_at > links_extracted_at) AND source_id = $2",
+ "textSha256": "247383a2d6f313bcad17403d6f4b6a403f284ea652647ebf1ceb7c56cc64d4e5"
}
]
},
@@ -638,8 +638,8 @@
"number",
"number"
],
- "sql": "SELECT id, slug, source_id, type, title, compiled_truth, timeline, frontmatter, updated_at, to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS updated_at_iso FROM pages WHERE deleted_at IS NULL AND (links_extracted_at IS NULL OR links_extracted_at < $1::timestamptz OR updated_at > links_extracted_at) AND source_id = $2 AND id > $3 ORDER BY id LIMIT $4",
- "textSha256": "02f69476257e0b3f3c2b8526ef5d8c92b84039ab79fe2a86c69cc9670b4603a8"
+ "sql": "SELECT id, slug, source_id, type, title, compiled_truth, timeline, frontmatter, updated_at, to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS updated_at_iso FROM pages WHERE deleted_at IS NULL AND NOT (COALESCE(pages.frontmatter, '{}'::jsonb) ? 'quarantine') AND (links_extracted_at IS NULL OR links_extracted_at < $1::timestamptz OR updated_at > links_extracted_at) AND source_id = $2 AND id > $3 ORDER BY id LIMIT $4",
+ "textSha256": "98da3d9f516c23cc4815949dd95ea5641349ff9b2951ccb366d031397eb0a149"
}
],
"default": [
@@ -648,8 +648,8 @@
"params": [
"number"
],
- "sql": "SELECT id, slug, source_id, type, title, compiled_truth, timeline, frontmatter, updated_at, to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS updated_at_iso FROM pages WHERE deleted_at IS NULL AND (links_extracted_at IS NULL OR updated_at > links_extracted_at) ORDER BY id LIMIT $1",
- "textSha256": "5caf4d2f7968dbdcb18b553c3d4c7e05bb474dbb338ed171071ccaadce8b0188"
+ "sql": "SELECT id, slug, source_id, type, title, compiled_truth, timeline, frontmatter, updated_at, to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS updated_at_iso FROM pages WHERE deleted_at IS NULL AND NOT (COALESCE(pages.frontmatter, '{}'::jsonb) ? 'quarantine') AND (links_extracted_at IS NULL OR updated_at > links_extracted_at) ORDER BY id LIMIT $1",
+ "textSha256": "d63c641db0d71de13ec2d3e5b67cd2301e8317048dc447fa18c9f9c62dd44a40"
}
]
},
diff --git a/test/quarantine-extraction.test.ts b/test/quarantine-extraction.test.ts
new file mode 100644
index 0000000000..f6539cddff
--- /dev/null
+++ b/test/quarantine-extraction.test.ts
@@ -0,0 +1,204 @@
+/**
+ * #5556 (quarantine core): a quarantined page is hidden from search, so no
+ * derived-data scan may process it and no extraction-health denominator may
+ * count it.
+ *
+ * Protects: each entry point that turns page text into links, timeline rows
+ * or a health ratio — the stale listing (count + batch, both engines via
+ * engine-sql), the doctor links_extraction_lag denominator, NER, the meeting
+ * timeline projection, the file-walk slug lists (sync/cycle incremental), the
+ * DB walks (`extract --source db`, mentions) and the managed link derivation.
+ * Fails when: an entry point ignores the marker, so junk becomes typed edges or
+ * timeline rows, or the doctor ratio lies about a source's lag.
+ * Why new: these entry points never consulted the marker; existing tests seed
+ * only unquarantined pages. Negative controls: an unquarantined sibling is
+ * still processed, and clearing the marker restores eligibility.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { buildQuarantineMarker, QUARANTINE_KEY } from '../src/core/quarantine.ts';
+import { LINK_EXTRACTOR_VERSION_TS } from '../src/core/link-extraction.ts';
+import { checkLinksExtractionLag } from '../src/commands/doctor/checks/extraction-sync.ts';
+import { extractNerLinks } from '../src/core/extract-ner.ts';
+import { extractTimelineFromMeetings } from '../src/core/extract-timeline-from-meetings.ts';
+import { extractLinksForSlugs, extractTimelineForSlugs, runExtractCore } from '../src/commands/extract.ts';
+import { extractTimelineFromDB } from '../src/commands/extract-timeline-db.ts';
+import { runExtract } from '../src/commands/extract.ts';
+import { extractManagedStaleLinks } from '../src/core/persistence/links-maintenance.ts';
+import type { Gazetteer } from '../src/core/by-mention.ts';
+
+let engine: PGLiteEngine;
+let repo: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ repo = mkdtempSync(join(tmpdir(), 'gbrain-quarantine-extract-'));
+}, 240_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+ rmSync(repo, { recursive: true, force: true });
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+});
+
+const marker = () => ({ [QUARANTINE_KEY]: buildQuarantineMarker('junk_pattern', 'cloudflare_ray_id') });
+
+async function page(slug: string, type: string, title: string, body: string, opts: { quarantined?: boolean; timeline?: string; frontmatter?: Record<string, unknown> } = {}): Promise<void> {
+ await engine.putPage(slug, {
+ type: type as never, title, compiled_truth: body, timeline: opts.timeline ?? '',
+ frontmatter: { ...(opts.frontmatter ?? {}), ...(opts.quarantined ? marker() : {}) },
+ effective_date: new Date('2026-04-20T00:00:00.000Z'),
+ });
+}
+
+function file(slug: string, content: string): void {
+ const path = join(repo, `${slug}.md`);
+ mkdirSync(join(path, '..'), { recursive: true });
+ writeFileSync(path, content);
+}
+
+async function quietly<T>(fn: () => Promise<T>): Promise<T> {
+ const log = console.log, err = console.error;
+ console.log = () => {}; console.error = () => {};
+ try { return await fn(); } finally { console.log = log; console.error = err; }
+}
+
+async function linksFrom(slug: string): Promise<string[]> {
+ const rows = await engine.executeRaw<{ to_slug: string }>(
+ `SELECT t.slug AS to_slug FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id WHERE f.slug = $1 ORDER BY t.slug`, [slug]);
+ return rows.map((r) => r.to_slug);
+}
+
+async function timelineCount(slug: string): Promise<number> {
+ const rows = await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM timeline_entries te JOIN pages p ON p.id = te.page_id WHERE p.slug = $1`, [slug]);
+ return Number(rows[0]?.n ?? 0);
+}
+
+describe('stale listing (engine-sql, both engines)', () => {
+ test('a quarantined page is neither counted nor listed as stale; clearing the marker restores it', async () => {
+ await page('notes/clean', 'note', 'Clean', 'A clean note.');
+ await page('notes/junk', 'note', 'Junk', 'Just a moment... checking your browser.', { quarantined: true });
+ const opts = { sourceId: 'default', versionTs: LINK_EXTRACTOR_VERSION_TS };
+ expect(await engine.countStalePagesForExtraction(opts)).toBe(1);
+ expect((await engine.listStalePagesForExtraction({ ...opts, batchSize: 10 })).map((r) => r.slug)).toEqual(['notes/clean']);
+ await page('notes/junk', 'note', 'Junk', 'Now a real note.');
+ expect(await engine.countStalePagesForExtraction(opts)).toBe(2);
+ });
+});
+
+describe('doctor links_extraction_lag denominator', () => {
+ test('quarantined pages are not in the denominator', async () => {
+ await page('notes/clean', 'note', 'Clean', 'A clean note.');
+ for (let i = 0; i < 3; i++) await page(`notes/junk-${i}`, 'note', `Junk ${i}`, 'Attention required.', { quarantined: true });
+ const check = await checkLinksExtractionLag(engine, { sourceId: 'default' });
+ expect(check.details).toMatchObject({ total: 1, stale: 1, pct: 100 });
+ });
+});
+
+describe('NER', () => {
+ test('a quarantined page yields no typed NER edge; an unquarantined sibling does', async () => {
+ await page('companies/acme-example', 'company', 'Acme Example', 'Acme Example builds widgets.');
+ await page('people/dana-example', 'person', 'Dana Example', 'Dana Example works at Acme Example.');
+ await page('people/junk-example', 'person', 'Junk Example', 'Junk Example works at Acme Example.', { quarantined: true });
+ const result = await extractNerLinks(engine);
+ expect(result.pack_unavailable).toBe(false);
+ expect(await linksFrom('people/dana-example')).toEqual(['companies/acme-example']);
+ expect(await linksFrom('people/junk-example')).toEqual([]);
+ });
+});
+
+describe('meeting timeline projection', () => {
+ test('a quarantined meeting is not scanned and projects no timeline rows', async () => {
+ await page('people/alice-example', 'person', 'Alice Example', 'Alice Example profile');
+ await page('meetings/real-sync', 'meeting', 'Real Sync', 'Meeting discussion notes.');
+ await page('meetings/junk-sync', 'meeting', 'Junk Sync', 'Meeting discussion notes.', { quarantined: true });
+ for (const meeting of ['meetings/real-sync', 'meetings/junk-sync']) {
+ await engine.addLinksBatch([{ from_slug: meeting, to_slug: 'people/alice-example', link_type: 'attended', link_source: 'manual' }]);
+ }
+ const result = await extractTimelineFromMeetings(engine, { gazetteer: new Map() as Gazetteer });
+ expect(result.meetings_scanned).toBe(1);
+ const timeline = await engine.getTimeline('people/alice-example', { sourceId: 'default' });
+ expect(timeline.map((t) => t.source)).toEqual(['extract-timeline-from-meetings:meetings/real-sync']);
+ });
+});
+
+describe('file-walk slug lists (sync / cycle incremental)', () => {
+ test('links and timeline skip a quarantined slug and leave it unprocessed', async () => {
+ await page('people/alice-example', 'person', 'Alice Example', 'Alice Example profile');
+ await page('notes/clean', 'note', 'Clean', 'See [[people/alice-example]].');
+ await page('notes/junk', 'note', 'Junk', 'See [[people/alice-example]].', { quarantined: true });
+ const body = '---\ntype: note\n---\nSee [[people/alice-example]].\n\n## Timeline\n\n- **2026-04-03** | Met Alice Example\n';
+ file('people/alice-example', '---\ntype: person\n---\nAlice Example profile\n');
+ file('notes/clean', body);
+ file('notes/junk', body);
+ const links = await extractLinksForSlugs(engine, repo, ['notes/clean', 'notes/junk'], { sourceId: 'default' });
+ expect(links.processed).toEqual(['notes/clean']);
+ expect(await linksFrom('notes/clean')).toEqual(['people/alice-example']);
+ expect(await linksFrom('notes/junk')).toEqual([]);
+ const timeline = await extractTimelineForSlugs(engine, repo, ['notes/clean', 'notes/junk'], { sourceId: 'default' });
+ expect(timeline.processed).toEqual(['notes/clean']);
+ expect(await timelineCount('notes/clean')).toBe(1);
+ expect(await timelineCount('notes/junk')).toBe(0);
+ });
+
+ test('the full file walk skips a quarantined page', async () => {
+ await page('people/alice-example', 'person', 'Alice Example', 'Alice Example profile');
+ await page('notes/clean', 'note', 'Clean', 'See [[people/alice-example]].');
+ await page('notes/junk', 'note', 'Junk', 'See [[people/alice-example]].', { quarantined: true });
+ file('people/alice-example', '---\ntype: person\n---\nAlice Example profile\n');
+ file('notes/clean', '---\ntype: note\n---\nSee [[people/alice-example]].\n');
+ file('notes/junk', '---\ntype: note\n---\nSee [[people/alice-example]].\n');
+ await runExtractCore(engine, { mode: 'links', dir: repo, quiet: true, sourceId: 'default' });
+ expect(await linksFrom('notes/clean')).toEqual(['people/alice-example']);
+ expect(await linksFrom('notes/junk')).toEqual([]);
+ });
+});
+
+describe('DB walks', () => {
+ test('extract links --source db skips a quarantined page', async () => {
+ await page('people/alice-example', 'person', 'Alice Example', 'Alice Example profile');
+ await page('notes/clean', 'note', 'Clean', 'See [[people/alice-example]].');
+ await page('notes/junk', 'note', 'Junk', 'See [[people/alice-example]].', { quarantined: true });
+ await quietly(() => runExtract(engine, ['links', '--source', 'db']));
+ expect(await linksFrom('notes/clean')).toEqual(['people/alice-example']);
+ expect(await linksFrom('notes/junk')).toEqual([]);
+ });
+
+ test('extract links --by-mention skips a quarantined page', async () => {
+ await page('companies/acme-example', 'company', 'Acme Example', 'Acme Example builds widgets.');
+ await page('notes/clean', 'note', 'Clean', 'We talked with Acme Example today.');
+ await page('notes/junk', 'note', 'Junk', 'We talked with Acme Example today.', { quarantined: true });
+ await quietly(() => runExtract(engine, ['links', '--by-mention', '--source', 'db']));
+ expect(await linksFrom('notes/clean')).toEqual(['companies/acme-example']);
+ expect(await linksFrom('notes/junk')).toEqual([]);
+ });
+
+ test('the shared link derivation skips a quarantined slug a sync names explicitly', async () => {
+ await page('people/alice-example', 'person', 'Alice Example', 'Alice Example profile');
+ await page('notes/clean', 'note', 'Clean', 'See [[people/alice-example]].');
+ await page('notes/junk', 'note', 'Junk', 'See [[people/alice-example]].', { quarantined: true });
+ const r = await extractManagedStaleLinks(engine, { sourceId: 'default', slugs: ['notes/junk', 'notes/clean'], mentions: false });
+ expect(r.remaining).toBe(0);
+ expect(await linksFrom('notes/clean')).toEqual(['people/alice-example']);
+ expect(await linksFrom('notes/junk')).toEqual([]);
+ });
+
+ test('extract timeline --source db skips a quarantined page', async () => {
+ const timeline = '- **2026-04-03** | Met Alice Example';
+ await page('notes/clean', 'note', 'Clean', 'A clean note.', { timeline });
+ await page('notes/junk', 'note', 'Junk', 'A junk note.', { timeline, quarantined: true });
+ await extractTimelineFromDB(engine, { dryRun: false, jsonMode: false, quiet: true });
+ expect(await timelineCount('notes/clean')).toBe(1);
+ expect(await timelineCount('notes/junk')).toBe(0);
+ });
+});