Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(graph): wanted pages — unresolved authored links are recorded and heal into edges when their target appears
garrytan17e44cbd2f60
diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.mdindex 25ff219388..faad69504e 100644--- a/docs/TOOL_CATALOG.md+++ b/docs/TOOL_CATALOG.md@@ -4,7 +4,7 @@<!-- Regenerate: bun run scripts/generate-tool-catalog.ts --><!-- Freshness-guarded by scripts/check-tool-catalog-fresh.sh (bun run verify). -->-Every non-localOnly operation on the MCP surface: 137 tools across 23 areas. **Starter** marks membership in the ~39-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.+Every non-localOnly operation on the MCP surface: 138 tools across 24 areas. **Starter** marks membership in the ~39-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.## admin@@ -155,6 +155,12 @@ Every non-localOnly operation on the MCP surface: 137 tools across 23 areas. **S| `ontology_get` | Life Chronicle: the current resolved per-entity ontology (dimension → value) at `asof` (default now), with provenance + confidence + validity. | read | | || `ontology_propose` | Life Chronicle: record one ontology observation (entity has dimension=value), sourced + confidence-weighted + bi-temporal. | write | | |+## other++| Tool | Description | Scope | Starter | Gate |+|---|---|---|---|---|+| `wanted_pages` | Link targets that have no page yet, most-referenced first: each was written as a link but its page does not exist, so no edge exists. | read | | |+## pages| Tool | Description | Scope | Starter | Gate |diff --git a/scripts/build-schema.ts b/scripts/build-schema.tsindex c5011158c1..217a3f6d83 100644--- a/scripts/build-schema.ts+++ b/scripts/build-schema.ts@@ -420,7 +420,7 @@ export const PGLITE_RULES: readonly Rule[] = [/** DO blocks outside fragment regions are opaque, so each is classified by content hash. */export const PGLITE_DO_BLOCKS: Readonly<Record<string, { keep: boolean; reason: string }>> = {- d4724194ea02: { keep: false, reason: 'schema.sql RLS enablement block: PGLite has no role system (the shared-skills fragment keeps its own block)' },+ '28b8b384fc62': { keep: false, reason: 'schema.sql RLS enablement block: PGLite has no role system (the shared-skills fragment keeps its own block)' },};interface Addition {diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex c8d143f471..911fcc92e3 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 autopilosrc/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.tssrc/commands/embed.ts 2219 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)src/commands/extract-conversation-facts.ts 2182 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)-src/commands/extract.ts 2528 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)+src/commands/extract.ts 2540 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); +12 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's linkssrc/commands/jobs.ts 660 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)src/commands/serve-http.ts 919 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)src/core/ai/gateway.ts 4393 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)@@ -31,12 +31,12 @@ src/core/minions/handlers/subagent.ts 1918 ratchet merged: master v131 settle resrc/commands/bootstrap.ts 2142 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags)src/core/minions/worker.ts 1764 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retrysrc/commands/sources.ts 2031 ratchet +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured)-src/core/link-extraction.ts 2158 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note+src/core/link-extraction.ts 2180 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidatessrc/core/embedding-migration.ts 1569 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verifysrc/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshsrc/commands/hook.ts 1903 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail readsrc/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)-src/core/config.ts 1838 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured)+src/core/config.ts 1842 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +4 P5: wanted_pages.enabled key rowsrc/core/bootstrap/harness.ts 2711 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook envsrc/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl optionsrc/core/ops/pages.ts 663 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)diff --git a/src/commands/extract.ts b/src/commands/extract.tsindex d5c1a55cb5..6d0ee99773 100644--- a/src/commands/extract.ts+++ b/src/commands/extract.ts@@ -47,6 +47,7 @@ import { isUndefinedTableError } from '../core/utils.ts';import type { PageType } from '../core/types.ts';import { parseMarkdown } from '../core/markdown.ts';import { resolveCandidateSources, resolveLinkFallbackDefault, loadLinkPageMetadata, capturedLinkEndpoints, fileLinkOwnership, replaceFileLinks, replacePageFileLinks, type LinkPageMetadata } from '../core/link-reconciliation.ts';+import { collectWantedLinks, isWantedPagesEnabled } from '../core/wanted-links.ts';export { reconcileSourceLinks, type SourceLinkReconciliationResult } from '../core/link-reconciliation.ts';export { extractMarkdownLinks } from '../core/link-extraction.ts';import {@@ -1931,8 +1932,13 @@ async function extractLinksFromDB(}if (!dryRun) {try {+ const wanted = await isWantedPagesEnabled(engine) ? collectWantedLinks({ candidates: extracted.candidates,+ frontmatterUnresolved: includeFrontmatter ? extracted.unresolved : [], originSourceId: source_id,+ crossSourceAllowed: federatedSourceIds.has(source_id) || crossSource, resolve: c => resolveCandidateSources(c, slug, source_id,+ allSlugs, slugToSources, federatedSourceIds.has(source_id), { crossSource, defaultSourceId: linkDefaultSourceId }) }) : [];const written = await engine.replaceDerivedLinks({ slug, sourceId: source_id, expectedRevision: snapshot.revision,sourceIncarnation: snapshot.sourceIncarnation }, batch, { includeFrontmatter,+ wanted: { producers: includeFrontmatter ? ['body', 'frontmatter'] : ['body'], rows: wanted },expectedEndpoints: capturedLinkEndpoints(batch, targetMetadata) });created += written.created;} catch (error) {@@ -2110,6 +2116,7 @@ export async function extractStaleFromDB(// from a genuinely missing target.let skippedCrossSource = 0;+ const wantedEnabled = await isWantedPagesEnabled(engine);for (;;) {const rows = await engine.listStalePagesForExtraction({batchSize: STALE_BATCH_SIZE, afterPageId, sourceId: sourceIdFilter, versionTs,@@ -2161,7 +2168,12 @@ export async function extractStaleFromDB(linkRows.push(resolvedLinkCandidate(c, page.slug, page.source_id, r));}const origin = { slug: page.slug, sourceId: page.source_id, expectedRevision: snapshot.revision, sourceIncarnation: snapshot.sourceIncarnation };- const linkOpts = { includeFrontmatter, expectedEndpoints: capturedLinkEndpoints(linkRows, targetMetadata) };+ const wanted = wantedEnabled ? collectWantedLinks({ candidates: extracted.candidates,+ frontmatterUnresolved: includeFrontmatter ? extracted.unresolved : [], originSourceId: page.source_id,+ crossSourceAllowed: federatedSourceIds.has(page.source_id) || crossSource, resolve: c => resolveCandidateSources(c, page.slug,+ page.source_id, allSlugs, slugToSources, federatedSourceIds.has(page.source_id), { crossSource, defaultSourceId: linkDefaultSourceId }) }) : [];+ const linkOpts = { includeFrontmatter, expectedEndpoints: capturedLinkEndpoints(linkRows, targetMetadata),+ wanted: { producers: includeFrontmatter ? ['body', 'frontmatter'] as const : ['body'] as const, rows: wanted } };const stampIso = page.updated_at.getTime() >= Date.parse(versionTs) ? page.updated_at_iso : versionTs;const written = await engine.replaceDerivedLinks(origin, linkRows, linkOpts);linksCreated += written.created;diff --git a/src/core/config.ts b/src/core/config.tsindex 60c1fb60d9..81f12965c6 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1569,6 +1569,10 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [// isAutoTimelineEnabled); registered so `gbrain config set auto_timeline off`// works without --force, as the compiled-truth guide documents.'auto_timeline',+ // Wanted pages: record unresolved authored links and wake their origins+ // when the target appears (src/core/wanted-links.ts). On by default; the+ // off switch is `gbrain config set wanted_pages.enabled false`.+ 'wanted_pages.enabled',// #5584: skillopt optimizer output cap (default 32000 thinking / 4096 otherwise).'skillopt.reflect_max_tokens',// #5585: skillopt strict model provenance (true|1|yes|on; other values count as on).diff --git a/src/core/derived-links.ts b/src/core/derived-links.tsindex f74a019762..e02b0776ce 100644--- a/src/core/derived-links.ts+++ b/src/core/derived-links.ts@@ -2,6 +2,7 @@ import type { BrainEngine, LinkBatchInput } from './engine.ts';import { assertPageRevision } from './page-state/types.ts';import { executeRawJsonb } from './sql-query.ts';import { sanitizeForJsonb } from './batch-rows.ts';+import { replaceWantedLinks, type WantedLinksReplacement } from './wanted-links-store.ts';export interface DerivedLinkOrigin {slug: string;@@ -15,6 +16,8 @@ export interface DerivedLinkReplacementOptions {preserveExisting?: boolean;includeLegacyNullProducer?: boolean;expectedEndpoints?: Array<{ slug: string; sourceId: string; revision: string }>;+ /** The origin's unresolved authored references, replaced in the same transaction (wanted pages). */+ wanted?: WantedLinksReplacement;}export class DerivedLinkRepairRequiredError extends Error {@@ -87,6 +90,7 @@ export async function replaceDerivedLinks(throw new Error('Derived link origin changed or was deleted');}const id = snapshot.page.id;+ if (opts.wanted) await replaceWantedLinks(tx, { pageId: id, sourceId: origin.sourceId }, opts.wanted);if (opts.includeFrontmatter !== false && !opts.preserveExisting) {const ambiguous = await tx.executeRaw(`SELECT 1 FROM links WHERE link_source='frontmatter'AND origin_page_id IS NULL AND (from_page_id=$1 OR to_page_id=$1) LIMIT 1`, [id]);diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.tsindex c68767a24f..26f8f80252 100644--- a/src/core/engine-sql/pages.ts+++ b/src/core/engine-sql/pages.ts@@ -240,7 +240,7 @@ export async function restorePage(exec: SqlExecutor, slug: string, opts?: { sourconst sourceId = opts?.sourceId;const sourceCondition = sourceId ? sqlFragment`AND source_id = ${sourceId}` : sqlFragment``;const { rows } = await exec.run(sqlFragment`- UPDATE pages SET deleted_at = NULL+ UPDATE pages SET deleted_at = NULL, updated_at = now()WHERE slug = ${slug} AND deleted_at IS NOT NULL ${sourceCondition}RETURNING slug`);@@ -615,6 +615,19 @@ export async function resolveSlugs(// ── v0.42.7 (#1696): link/timeline extraction freshness watermark ──+/**+ * Origins of wanted links whose target now exists: a live page with the wanted+ * slug (or, for a bare-name reference, the wanted basename) updated after the+ * origin last resolved it. Their next extraction creates the edge+ * (src/core/wanted-links.ts).+ */+const WANTED_ORIGIN_IS_STALE = sqlFragment`id IN (SELECT w.origin_page_id FROM wanted_links w+ JOIN pages t ON t.source_id = w.target_source_id AND t.slug = w.target_ref AND t.deleted_at IS NULL+ WHERE t.updated_at > w.checked_at+ UNION SELECT w.origin_page_id FROM wanted_links w+ JOIN pages t ON t.source_id = w.target_source_id AND regexp_replace(t.slug, '^.*/', '') = w.target_ref AND t.deleted_at IS NULL+ WHERE w.ref_kind = 'name' AND t.updated_at > w.checked_at)`;+/*** Shared stale-for-extraction predicate. `attendance` narrows it by the #5761* marker: a page is attendance-blocked while its marker equals its current@@ -623,8 +636,8 @@ export async function resolveSlugs(*/function stalePagesWhere(opts?: { sourceId?: string; versionTs?: string; attendance?: 'exclude' | 'blocked' }) {const version = opts?.versionTs- ? sqlFragment`(links_extracted_at IS NULL OR links_extracted_at < ${opts.versionTs}::timestamptz OR updated_at > links_extracted_at)`- : sqlFragment`(links_extracted_at IS NULL OR updated_at > links_extracted_at)`;+ ? sqlFragment`(links_extracted_at IS NULL OR links_extracted_at < ${opts.versionTs}::timestamptz OR updated_at > links_extracted_at OR ${WANTED_ORIGIN_IS_STALE})`+ : sqlFragment`(links_extracted_at IS NULL OR updated_at > links_extracted_at OR ${WANTED_ORIGIN_IS_STALE})`;const source = opts?.sourceId ? sqlFragment` AND source_id = ${opts.sourceId}` : sqlFragment``;const attendance = opts?.attendance === 'exclude'? sqlFragment` AND links_attendance_blocked_revision IS DISTINCT FROM knowledge_revision`diff --git a/src/core/link-extraction.ts b/src/core/link-extraction.tsindex efa57fcd18..2915f1dee1 100644--- a/src/core/link-extraction.ts+++ b/src/core/link-extraction.ts@@ -608,6 +608,21 @@ export interface LinkCandidate {originSlug?: string;/** Frontmatter field name (e.g. 'key_people'), for debug + unresolved report. */originField?: string;+ /**+ * The authored reference this candidate came from (a markdown link or a+ * wikilink in the body). Candidates sharing a `key` are alternative+ * resolutions of one reference; the reference is wanted when none of them+ * resolves (src/core/wanted-links.ts). Bare prose paths carry none.+ */+ authoredRef?: AuthoredRef;+}++/** One authored body reference, as recorded in `wanted_links` when it does not resolve. */+export interface AuthoredRef {+ key: string;+ kind: 'slug' | 'name';+ target: string;+ targetSourceId?: string;}/**@@ -730,6 +745,7 @@ export async function extractPageLinks(...typeFor(context, target, idx),context,linkSource: 'markdown',+ authoredRef: { key: `ref:${idx}`, kind: 'slug', target },});}continue;@@ -760,6 +776,7 @@ export async function extractPageLinks(...typeFor(litContext, ref.slug, litIdx),context: litContext,linkSource: 'markdown',+ authoredRef: { key: `ref:${litIdx}`, kind: 'slug', target: ref.slug },});}// #4062: a bare `[[name]]` (no slash) gets a direct verb-typed@@ -818,11 +835,14 @@ export async function extractPageLinks(const uniquePerson = personTargets.length === 1;if (pageType === 'meeting' && opts.targetType && !uniquePerson&& targets.filter(target => opts.targetType!(target) !== undefined).length > 1) attendanceAmbiguous.add(idx);+ const authoredRef: AuthoredRef | undefined = slashIdx === -1+ ? (normalizeBasename(ref.slug) ? { key: `ref:${idx}`, kind: 'name', target: normalizeBasename(ref.slug) } : undefined)+ : { key: `ref:${idx}`, kind: 'slug', target: ref.slug };for (const target of bareDirect) {const inferred = typeFor(context, target, idx);candidates.push({ targetSlug: target,...(inferred.canonicalAttendance && !uniquePerson ? { linkType: 'mentions' } : inferred),- context, linkSource: 'markdown' });+ context, linkSource: 'markdown', ...(authoredRef ? { authoredRef } : {}) });}for (const matched of matches) {const inferred = typeFor(context, matched, idx);@@ -831,6 +851,7 @@ export async function extractPageLinks(...(inferred.canonicalAttendance && uniquePerson ? inferred : { linkType: WIKILINK_BASENAME_LINK_TYPE }),context,linkSource: 'wikilink-resolved',+ ...(authoredRef ? { authoredRef } : {}),});}continue;@@ -857,6 +878,7 @@ export async function extractPageLinks(...typeFor(context, targetSlug, idx, ref.sourceId ?? undefined),context,linkSource: 'markdown',+ authoredRef: { key: `ref:${idx}`, kind: 'slug', target: targetSlug, ...(ref.sourceId ? { targetSourceId: ref.sourceId } : {}) },});}diff --git a/src/core/link-reconciliation.ts b/src/core/link-reconciliation.tsindex 4f67278ec2..23dc665d80 100644--- a/src/core/link-reconciliation.ts+++ b/src/core/link-reconciliation.ts@@ -5,6 +5,7 @@ import { fetchSource, isSourceFederated } from './sources-load.ts';import { parseMarkdown } from './markdown.ts';import { isValidSourceId } from './source-id.ts';import { buildSourceLocalReferenceIndex } from './source-local-reference-index.ts';+import { collectWantedLinks, isWantedPagesEnabled } from './wanted-links.ts';export interface LinkPageMetadata {slug: string;@@ -72,6 +73,7 @@ export async function reconcileSourceLinks(const pages = await loadLinkPageMetadata(engine, sourceId);const index = new Map(pages.map(page => [page.slug, page]));const resolver = makeIndexedLinkResolver(pages, sourceId);+ const wantedEnabled = await isWantedPagesEnabled(engine);const remaining = pages.filter(page => !opts.afterSlug || page.slug > opts.afterSlug).sort((a, b) => a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0);for (const metadata of remaining.slice(0, limit)) {@@ -110,8 +112,12 @@ export async function reconcileSourceLinks(rows.push(resolvedLinkCandidate(candidate, page.slug, sourceId,{ fromSlug: from, fromSourceId: sourceId, toSourceId: sourceId }));}+ const wanted = wantedEnabled ? collectWantedLinks({ candidates: extracted.candidates, frontmatterUnresolved: extracted.unresolved,+ originSourceId: sourceId, crossSourceAllowed: false, resolve: candidate =>+ candidate.targetSourceId && candidate.targetSourceId !== sourceId ? { ok: false, reason: 'cross_source' }+ : !index.has(candidate.targetSlug) ? { ok: false, reason: 'missing_target' } : { ok: true } }) : [];const written = await engine.replaceDerivedLinks({ slug: page.slug, sourceId,- expectedRevision: snapshot.revision, sourceIncarnation }, rows, { expectedEndpoints:+ expectedRevision: snapshot.revision, sourceIncarnation }, rows, { wanted: { producers: ['body', 'frontmatter'], rows: wanted }, expectedEndpoints:[...new Set(rows.flatMap(row => [row.from_slug, row.to_slug]))].map(slug => ({ slug, sourceId,revision: index.get(slug)!.knowledge_revision })) });result.pagesProcessed++;diff --git a/src/core/ops/links.ts b/src/core/ops/links.tsindex 7643344824..bca1228c67 100644--- a/src/core/ops/links.ts+++ b/src/core/ops/links.ts@@ -9,7 +9,7 @@ import { coordinatedManualLinkWrite } from '../persistence/manual-links.ts';*/import { opError, type Operation } from './contract.ts';-import { paramUse } from './op-fix.ts';+import { invalidParam, paramUse } from './op-fix.ts';import {assertExplicitSourceLive,enforceClientSlugFence,@@ -20,7 +20,10 @@ import {reclassifyMutationTimePageMiss,requireWritablePage,sourceScopeOpts,+ assertSourceInCallerScope,} from './context.ts';+import { listWantedPages } from '../wanted-links-store.ts';+import { privatePagesFilterFragment } from '../search/private-visibility.ts';import type { OperationContext } from './contract.ts';import type { Link, PageReadPolicy } from '../types.ts';import { ALL_SOURCES } from '../source-id.ts';@@ -443,8 +446,52 @@ const traverse_graph: Operation = {cliHints: { name: 'graph', positional: ['slug'] },};+const WANTED_DEFAULT_LIMIT = 50;+const WANTED_MAX_LIMIT = 100;++const wanted_pages: Operation = {+ name: 'wanted_pages',+ mutating: false,+ idempotent: true,+ outputRedaction: 'retrieval',+ description: 'Link targets that have no page yet, most-referenced first: each was written as a link but its page does not exist, so no edge exists. Use to find entities worth a page (enrichment) or typo links to fix. The edge appears on its own once the page is created.',+ params: {+ source_id: { type: 'string', description: 'Only targets referenced from this source (must be inside your source grant).' },+ limit: { type: 'number', description: `Rows per page (default ${WANTED_DEFAULT_LIMIT}, max ${WANTED_MAX_LIMIT}).` },+ offset: { type: 'number', description: 'Skip the first N targets.' },+ count_only: { type: 'boolean', description: 'Return the total with no rows.' },+ },+ scope: 'read',+ handler: async (ctx, p) => {+ const named = p.source_id === undefined ? undefined : String(p.source_id);+ if (named !== undefined) assertSourceInCallerScope(ctx, named);+ const policy = named !== undefined ? await readPolicyOpts(ctx, { sourceId: named }) : await readPolicyOpts(ctx);+ const limit = p.limit === undefined ? WANTED_DEFAULT_LIMIT : Number(p.limit);+ const offset = p.offset === undefined ? 0 : Number(p.offset);+ const limitOk = Number.isInteger(limit) && limit >= 1 && limit <= WANTED_MAX_LIMIT;+ if (!limitOk || !Number.isInteger(offset) || offset < 0) {+ throw invalidParam(ctx, 'wanted_pages', limitOk ? 'offset' : 'limit',+ `wanted_pages: limit must be 1-${WANTED_MAX_LIMIT} and offset a non-negative integer`,+ limitOk ? { def: wanted_pages.params.offset, example: 0 } : { def: wanted_pages.params.limit, example: WANTED_DEFAULT_LIMIT });+ }+ const { total, rows } = await listWantedPages(ctx.engine, { sourceId: policy.sourceId, sourceIds: policy.sourceIds,+ excludePrivate: policy.excludePrivate, privateFilter: privatePagesFilterFragment,+ limit: p.count_only === true ? 1 : limit, offset });+ const next = offset + limit < total ? offset + limit : null;+ return {+ total, limit, offset, next_offset: p.count_only === true ? null : next,+ targets: p.count_only === true ? [] : rows.map(row => ({ ...row,+ next: row.existing_matches.length+ ? `A page with this name exists (${row.existing_matches[0].slug}); link it by its full slug, e.g. [[${row.existing_matches[0].slug}]].`+ : `Create ${row.target} if it is a real entity (the ${row.referenced_by} linking page(s) gain the edge on the next extraction), or fix the link if it is a typo.` })),+ ...(total === 0 ? { note: 'Every authored link resolves to an existing page.' } : {}),+ };+ },+ cliHints: { name: 'wanted' },+};+// Ops in EXACTLY the canonical `operations` array order.export const linksOperations: Operation[] = [- add_link, remove_link, get_links, get_backlinks, list_link_sources, traverse_graph,+ add_link, remove_link, get_links, get_backlinks, list_link_sources, traverse_graph, wanted_pages,];diff --git a/src/core/persistence/links-preparation.ts b/src/core/persistence/links-preparation.tsindex 674dffd11c..46b9aafa88 100644--- a/src/core/persistence/links-preparation.ts+++ b/src/core/persistence/links-preparation.ts@@ -5,6 +5,8 @@ import { extractPageLinks, isGlobalBasenameEnabled, makeResolver, resolvedLinkCaimport { loadActivePackForLocalEngine } from '../schema-pack/best-effort.ts';import { DerivedLinkEndpointChangedError } from '../derived-links.ts';import { capturedLinkEndpoints, indexLinkSources, loadLinkSourcePolicy, resolveCandidateSources } from '../link-reconciliation.ts';+import { collectWantedLinks, isWantedPagesEnabled } from '../wanted-links.ts';+import { readFix } from '../ops/op-fix.ts';async function liveSlugAliases(engine: BrainEngine, sourceId: string, targets: string[]): Promise<Map<string, string>> {if (!targets.length) return new Map();@@ -51,6 +53,10 @@ export async function prepareAutomaticLinks(engine: BrainEngine, slug: string,return resolved.ok ? (targetSlug === slug && resolved.toSourceId === sourceId ? page.type: metadata.get(`${resolved.toSourceId}\0${targetSlug}`)?.type) : undefined;} });+ const wanted = { producers: ['body', 'frontmatter'] as const, rows: await isWantedPagesEnabled(engine)+ ? collectWantedLinks({ candidates: candidates.map(retarget), frontmatterUnresolved: unresolved, originSourceId: sourceId,+ crossSourceAllowed: policy.allowCrossSource || policy.crossSource, resolve })+ : [] };const rows = candidates.map(retarget).flatMap(candidate => {const resolved = resolve(candidate);if (!resolved.ok) return [];@@ -65,11 +71,15 @@ export async function prepareAutomaticLinks(engine: BrainEngine, slug: string,if (!snapshot) throw new Error('Automatic link origin disappeared');try {const result = await tx.replaceDerivedLinks({ slug, sourceId, expectedRevision: snapshot.revision,- sourceIncarnation: snapshot.sourceIncarnation }, rows, { preserveExisting: true,+ sourceIncarnation: snapshot.sourceIncarnation }, rows, { preserveExisting: true, wanted: { ...wanted, producers: [...wanted.producers] },expectedEndpoints: capturedLinkEndpoints(rows, new Map([...metadata,[`${sourceId}\0${slug}`, { slug, source_id: sourceId, type: page.type, knowledge_revision: snapshot.revision }]])).filter(endpoint => endpoint.slug !== slug || endpoint.sourceId !== sourceId) });- return { ...result, errors: 0, unresolved_count: unresolved.length };+ return { ...result, errors: 0, unresolved_count: unresolved.length, wanted_count: wanted.rows.length,+ ...(wanted.rows.length ? { wanted: wanted.rows.slice(0, 10).map(row => ({ slug: row.target_ref, source_id: row.target_source_id })),+ wanted_message: 'These link targets have no page yet; each edge is created when its page is. Create the page if it is real, or fix the link if it is a typo.',+ fix: readFix(`Lists every link target in source ${sourceId} that has no page yet, with the pages that link to it, read-only.`,+ { argv: ['gbrain', 'wanted', '--source-id', sourceId], mcp: { tool: 'wanted_pages', arguments: { source_id: sourceId } } }) } : {}) };} catch (error) {if (!(error instanceof DerivedLinkEndpointChangedError)) throw error;return { created: 0, removed: 0, errors: 1, unresolved_count: Math.max(1, unresolved.length) };diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex f9af4910a2..bc7ede6aa4 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -129,6 +129,7 @@ CREATE TRIGGER bump_page_generation_clock_trgCREATE INDEX IF NOT EXISTS idx_pages_type ON pages(type);CREATE INDEX IF NOT EXISTS idx_pages_frontmatter ON pages USING GIN(frontmatter);CREATE INDEX IF NOT EXISTS idx_pages_trgm ON pages USING GIN(title gin_trgm_ops);+CREATE INDEX IF NOT EXISTS idx_pages_slug_basename ON pages (source_id, (regexp_replace(slug, '^.*/', '')));CREATE INDEX IF NOT EXISTS idx_pages_source_id ON pages(source_id);CREATE INDEX IF NOT EXISTS pages_deleted_at_purge_idxON pages (deleted_at) WHERE deleted_at IS NOT NULL;@@ -197,6 +198,24 @@ CREATE OR REPLACE VIEW page_links ASSELECT id, from_page_id, to_page_id FROM links;+CREATE TABLE IF NOT EXISTS wanted_links (+ id BIGSERIAL PRIMARY KEY,+ origin_page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ producer TEXT NOT NULL CHECK (producer IN ('body','frontmatter')),+ ref_kind TEXT NOT NULL CHECK (ref_kind IN ('slug','name')),+ target_source_id TEXT NOT NULL,+ target_ref TEXT NOT NULL,+ link_type TEXT NOT NULL DEFAULT '',+ context TEXT NOT NULL DEFAULT '',+ checked_at TIMESTAMPTZ NOT NULL,+ first_seen_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ CONSTRAINT wanted_links_reference_unique+ UNIQUE (origin_page_id, producer, ref_kind, target_source_id, target_ref)+);+CREATE INDEX IF NOT EXISTS wanted_links_target_idx ON wanted_links (target_source_id, target_ref);+CREATE INDEX IF NOT EXISTS wanted_links_source_idx ON wanted_links (source_id);+CREATE TABLE IF NOT EXISTS tags (id SERIAL PRIMARY KEY,page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex 01044b0e99..80138b3fad 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -269,6 +269,7 @@ CREATE TRIGGER bump_page_generation_clock_trgCREATE INDEX IF NOT EXISTS idx_pages_type ON pages(type);CREATE INDEX IF NOT EXISTS idx_pages_frontmatter ON pages USING GIN(frontmatter);CREATE INDEX IF NOT EXISTS idx_pages_trgm ON pages USING GIN(title gin_trgm_ops);+CREATE INDEX IF NOT EXISTS idx_pages_slug_basename ON pages (source_id, (regexp_replace(slug, '^.*/', '')));-- v0.13.1 #170: avoids 14.6s seqscan on large brains when listing pages newest-first.CREATE INDEX IF NOT EXISTS idx_pages_updated_at_desc ON pages (updated_at DESC);-- v0.18.0: source-scoped scans (per /plan-eng-review Section 4).@@ -517,6 +518,27 @@ CREATE INDEX IF NOT EXISTS idx_links_to ON links(to_page_id);CREATE INDEX IF NOT EXISTS idx_links_source ON links(link_source);CREATE INDEX IF NOT EXISTS idx_links_origin ON links(origin_page_id);+-- Wanted pages (migration wanted_links): authored links whose target page does+-- not exist. A live target updated after checked_at makes the origin stale for+-- link extraction (src/core/wanted-links.ts).+CREATE TABLE IF NOT EXISTS wanted_links (+ id BIGSERIAL PRIMARY KEY,+ origin_page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ producer TEXT NOT NULL CHECK (producer IN ('body','frontmatter')),+ ref_kind TEXT NOT NULL CHECK (ref_kind IN ('slug','name')),+ target_source_id TEXT NOT NULL,+ target_ref TEXT NOT NULL,+ link_type TEXT NOT NULL DEFAULT '',+ context TEXT NOT NULL DEFAULT '',+ checked_at TIMESTAMPTZ NOT NULL,+ first_seen_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ CONSTRAINT wanted_links_reference_unique+ UNIQUE (origin_page_id, producer, ref_kind, target_source_id, target_ref)+);+CREATE INDEX IF NOT EXISTS wanted_links_target_idx ON wanted_links (target_source_id, target_ref);+CREATE INDEX IF NOT EXISTS wanted_links_source_idx ON wanted_links (source_id);+-- ============================================================-- tags-- ============================================================@@ -1658,6 +1680,7 @@ BEGINALTER TABLE pages ENABLE ROW LEVEL SECURITY;ALTER TABLE content_chunks ENABLE ROW LEVEL SECURITY;ALTER TABLE links ENABLE ROW LEVEL SECURITY;+ ALTER TABLE wanted_links ENABLE ROW LEVEL SECURITY;ALTER TABLE tags ENABLE ROW LEVEL SECURITY;ALTER TABLE raw_data ENABLE ROW LEVEL SECURITY;ALTER TABLE timeline_entries ENABLE ROW LEVEL SECURITY;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 16ef4d9ecc..8706ae62cf 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -201,6 +201,7 @@ import { v197 } from './v197-managed-guard-null-source-fallback.ts';import { v198 } from './v198-publication-failure-detail.ts';import { v199 } from './v199-chronicle-page-state.ts';import { v200 } from './v200-sync-hold-page-index.ts';+import { v201 } from './v201-wanted-links.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -400,4 +401,5 @@ export const MIGRATIONS: Migration[] = [v198,v199,v200,+ v201,];diff --git a/src/core/schema-migrations/v201-wanted-links.ts b/src/core/schema-migrations/v201-wanted-links.tsnew file mode 100644index 0000000000..44cb3c418f--- /dev/null+++ b/src/core/schema-migrations/v201-wanted-links.ts@@ -0,0 +1,44 @@+import type { Migration } from './types.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// Wanted pages: an authored link (wikilink, markdown link or frontmatter link+// field) whose target page does not exist is recorded here instead of being+// dropped. `checked_at` is when the origin's resolution was read; a live target+// page updated after it makes the origin stale for link extraction, so the edge+// appears once the target does (src/core/wanted-links.ts). Rows are derived+// state, replaced with the origin's links in the same transaction.+// The basename expression index serves `ref_kind = 'name'` targets and the+// put_page similar-pages advisory.+export const v201: Migration = {+ version: 201,+ name: 'wanted_links',+ idempotent: true,+ sql: `+ CREATE TABLE IF NOT EXISTS wanted_links (+ id BIGSERIAL PRIMARY KEY,+ origin_page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ producer TEXT NOT NULL CHECK (producer IN ('body','frontmatter')),+ ref_kind TEXT NOT NULL CHECK (ref_kind IN ('slug','name')),+ target_source_id TEXT NOT NULL,+ target_ref TEXT NOT NULL,+ link_type TEXT NOT NULL DEFAULT '',+ context TEXT NOT NULL DEFAULT '',+ checked_at TIMESTAMPTZ NOT NULL,+ first_seen_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ CONSTRAINT wanted_links_reference_unique+ UNIQUE (origin_page_id, producer, ref_kind, target_source_id, target_ref)+ );+ CREATE INDEX IF NOT EXISTS wanted_links_target_idx ON wanted_links (target_source_id, target_ref);+ CREATE INDEX IF NOT EXISTS wanted_links_source_idx ON wanted_links (source_id);+ CREATE INDEX IF NOT EXISTS idx_pages_slug_basename+ ON pages (source_id, (regexp_replace(slug, '^.*/', '')));+ DO $rls$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles pr WHERE pg_has_role(current_user, pr.oid, 'USAGE') AND (pr.rolbypassrls OR pr.rolsuper)) THEN+ ALTER TABLE wanted_links ENABLE ROW LEVEL SECURITY;+ END IF;+ END $rls$;+ `,+};diff --git a/src/core/sweep.ts b/src/core/sweep.tsindex 01ebe4fee8..522ea23968 100644--- a/src/core/sweep.ts+++ b/src/core/sweep.ts@@ -1,4 +1,5 @@import { lookupRefsForSlugs } from './link-reconciliation.ts';+import { collectWantedLinks, isWantedPagesEnabled, type WantedLinkInput } from './wanted-links.ts';/*** Serve-resident maintenance sweep [CX-P0.1, CX-P0.3, CX2-4].*@@ -409,6 +410,8 @@ async function runLinksTimelinePass(const linkBatch: LinkBatchInput[] = [];const endpointMetadata = new Map<string, { slug: string; source_id: string; type: string; knowledge_revision: string }>();const incomplete = new Set<string>();+ const wantedBySlug = new Map<string, WantedLinkInput[]>();+ const wantedEnabled = await isWantedPagesEnabled(engine);if (pageCandidates.length > 0) {const needed = new Set<string>();for (const { slug, candidates } of pageCandidates) {@@ -449,6 +452,11 @@ async function runLinksTimelinePass(skip('attendance_resolution_incomplete');continue;}+ if (wantedEnabled) {+ wantedBySlug.set(slug, collectWantedLinks({ candidates, originSourceId: sourceId,+ crossSourceAllowed: allowCrossSource || crossSource, resolve: c => resolveCandidateSources(c, slug, sourceId,+ allSlugs, slugToSources, allowCrossSource, { crossSource, defaultSourceId: linkDefaultSourceId }) }));+ }for (const c of candidates) {// #2589: a cross_source drop here means the target exists only in// other sources and cross-source links are off — counted in the@@ -501,7 +509,8 @@ async function runLinksTimelinePass(const snapshot = snapshots.get(ref.slug)!;const result = await engine.replaceDerivedLinks({ slug: ref.slug, sourceId,expectedRevision: snapshot.revision, sourceIncarnation: snapshot.sourceIncarnation }, desired,- { includeFrontmatter: false, preserveExisting: true, expectedEndpoints: [...new Set(desired.flatMap(row =>+ { includeFrontmatter: false, preserveExisting: true,+ wanted: { producers: ['body'], rows: wantedBySlug.get(ref.slug) ?? [] }, expectedEndpoints: [...new Set(desired.flatMap(row =>[`${row.from_source_id}\0${row.from_slug}`, `${row.to_source_id}\0${row.to_slug}`]))].map(key => {const endpoint = endpointMetadata.get(key)!;return { slug: endpoint.slug, sourceId: endpoint.source_id, revision: endpoint.knowledge_revision };diff --git a/src/core/wanted-links-store.ts b/src/core/wanted-links-store.tsnew file mode 100644index 0000000000..0fc9cf9167--- /dev/null+++ b/src/core/wanted-links-store.ts@@ -0,0 +1,134 @@+/**+ * Storage for wanted pages (see src/core/wanted-links.ts). Kept free of the+ * link-extraction import graph because derived-links.ts, which every engine+ * imports, calls it inside the derived-link replacement transaction.+ */+import type { BrainEngine } from './engine.ts';+import { executeRawJsonb } from './sql-query.ts';+import { sanitizeForJsonb } from './batch-rows.ts';++export type WantedProducer = 'body' | 'frontmatter';++export interface WantedLinkInput {+ producer: WantedProducer;+ ref_kind: 'slug' | 'name';+ target_source_id: string;+ target_ref: string;+ link_type: string;+ context: string;+}++export interface WantedLinksReplacement {+ rows: WantedLinkInput[];+ /** Producers whose rows this replacement owns; others stay untouched. */+ producers: readonly WantedProducer[];+}++/**+ * Replace one origin's wanted rows inside the caller's transaction (the same+ * one that replaces its derived links). Slug targets are locked first, so a+ * concurrent writer creating the target either committed before this check+ * (and the row is stamped `-infinity`, leaving the origin stale) or commits+ * after it with an `updated_at` past `checked_at`. Only an exact slug counts+ * here: a bare-name reference matching some page's basename may legitimately+ * stay unresolved (basename resolution is opt-in), and stamping it+ * `-infinity` would re-list its origin forever.+ */+export async function replaceWantedLinks(+ tx: Pick<BrainEngine, 'executeRaw' | 'lockPageKeys'>,+ origin: { pageId: number; sourceId: string },+ replacement: WantedLinksReplacement,+): Promise<number> {+ if (!replacement.producers.length) return 0;+ const rows = replacement.rows.filter(row => replacement.producers.includes(row.producer))+ .map(row => ({ ...row, context: sanitizeForJsonb(row.context) }));+ const slugTargets = rows.filter(row => row.ref_kind === 'slug')+ .map(row => ({ sourceId: row.target_source_id, slug: row.target_ref }));+ if (slugTargets.length) await tx.lockPageKeys(slugTargets);+ await executeRawJsonb(tx, `DELETE FROM wanted_links w+ WHERE w.origin_page_id = $1+ AND w.producer IN (SELECT jsonb_array_elements_text(($2::jsonb)->'producers'))+ AND NOT EXISTS (SELECT 1 FROM jsonb_to_recordset(($2::jsonb)->'rows')+ AS v(producer text, ref_kind text, target_source_id text, target_ref text)+ WHERE v.producer = w.producer AND v.ref_kind = w.ref_kind+ AND v.target_source_id = w.target_source_id AND v.target_ref = w.target_ref)`,+ [origin.pageId], [{ rows, producers: replacement.producers }]);+ if (!rows.length) return 0;+ const written = await executeRawJsonb<{ id: number }>(tx, `INSERT INTO wanted_links+ (origin_page_id, source_id, producer, ref_kind, target_source_id, target_ref, link_type, context, checked_at)+ SELECT $1, $2, v.producer, v.ref_kind, v.target_source_id, v.target_ref, v.link_type, v.context,+ CASE WHEN EXISTS (SELECT 1 FROM pages t WHERE t.source_id = v.target_source_id AND t.deleted_at IS NULL+ AND t.slug = v.target_ref)+ THEN '-infinity'::timestamptz ELSE now() END+ FROM jsonb_to_recordset(($3::jsonb)->'rows')+ AS v(producer text, ref_kind text, target_source_id text, target_ref text, link_type text, context text)+ ON CONFLICT ON CONSTRAINT wanted_links_reference_unique DO UPDATE+ SET link_type = EXCLUDED.link_type, context = EXCLUDED.context, checked_at = EXCLUDED.checked_at+ RETURNING id`, [origin.pageId, origin.sourceId], [{ rows }]);+ return written.length;+}++export interface WantedPageRow {+ target: string;+ target_source_id: string;+ ref_kind: 'slug' | 'name';+ referenced_by: number;+ sample_origins: Array<{ slug: string; source_id: string }>;+ link_types: string[];+ /** Live pages whose basename equals a bare-name target (link them by slug). */+ existing_matches: Array<{ slug: string; source_id: string }>;+ first_seen: string;+ last_checked: string;+}++/**+ * Missing link targets, most-referenced first. Scope applies to the origin+ * pages (the caller's readable sources) and, when `excludePrivate`, private+ * origins are removed BEFORE aggregation so a private page never reveals a+ * target name or contributes to a count. Soft-deleted origins never count.+ */+export async function listWantedPages(engine: Pick<BrainEngine, 'executeRaw'>, opts: {+ sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean; privateFilter?: (alias: string) => string;+ limit: number; offset: number;+}): Promise<{ total: number; rows: WantedPageRow[] }> {+ const params: unknown[] = [];+ const scope = opts.sourceIds?.length+ ? (params.push(opts.sourceIds), ` AND o.source_id = ANY($${params.length}::text[])`)+ : opts.sourceId ? (params.push(opts.sourceId), ` AND o.source_id = $${params.length}`) : '';+ const originPrivacy = opts.excludePrivate && opts.privateFilter ? ` AND ${opts.privateFilter('o')}` : '';+ const matchPrivacy = opts.excludePrivate && opts.privateFilter ? ` AND ${opts.privateFilter('m')}` : '';+ const base = `WITH wanted AS (+ SELECT w.target_source_id, w.target_ref, w.ref_kind, w.link_type, w.first_seen_at, w.checked_at,+ o.slug AS origin_slug, o.source_id AS origin_source_id+ FROM wanted_links w JOIN pages o ON o.id = w.origin_page_id AND o.deleted_at IS NULL+ WHERE NOT EXISTS (SELECT 1 FROM pages t WHERE t.source_id = w.target_source_id AND t.slug = w.target_ref AND t.deleted_at IS NULL)+ ${scope}${originPrivacy}+ ), grouped AS (+ SELECT target_source_id, target_ref, min(ref_kind) AS ref_kind,+ count(DISTINCT (origin_source_id, origin_slug))::int AS referenced_by,+ jsonb_agg(jsonb_build_object('slug', origin_slug, 'source_id', origin_source_id) ORDER BY origin_slug) AS origins,+ coalesce(jsonb_agg(DISTINCT link_type) FILTER (WHERE link_type <> ''), '[]'::jsonb) AS link_types,+ min(first_seen_at) AS first_seen, max(checked_at) AS last_checked+ FROM wanted GROUP BY target_source_id, target_ref+ )`;+ const [{ total }] = await engine.executeRaw<{ total: number }>(`${base} SELECT count(*)::int AS total FROM grouped`, params);+ params.push(opts.limit, opts.offset);+ const rows = await engine.executeRaw<{ target_source_id: string; target_ref: string; ref_kind: 'slug' | 'name'; referenced_by: number;+ origins: Array<{ slug: string; source_id: string }>; link_types: string[]; matches: Array<{ slug: string; source_id: string }> | null;+ first_seen: Date | string; last_checked: Date | string }>(`${base}+ SELECT g.*, (SELECT jsonb_agg(jsonb_build_object('slug', m.slug, 'source_id', m.source_id))+ FROM (SELECT m.slug, m.source_id FROM pages m WHERE g.ref_kind = 'name' AND m.source_id = g.target_source_id+ AND regexp_replace(m.slug, '^.*/', '') = g.target_ref AND m.deleted_at IS NULL${matchPrivacy}+ ORDER BY m.slug LIMIT 3) m) AS matches+ FROM grouped g ORDER BY g.referenced_by DESC, g.target_source_id, g.target_ref+ LIMIT $${params.length - 1} OFFSET $${params.length}`, params);+ const iso = (value: Date | string) => (value instanceof Date ? value : new Date(value)).toISOString();+ return { total: Number(total ?? 0), rows: rows.map(row => {+ const seen = new Set<string>();+ const origins = (row.origins ?? []).filter(o => !seen.has(`${o.source_id}\0${o.slug}`) && seen.add(`${o.source_id}\0${o.slug}`));+ return { target: row.target_ref, target_source_id: row.target_source_id, ref_kind: row.ref_kind,+ referenced_by: Number(row.referenced_by), sample_origins: origins.slice(0, 3), link_types: row.link_types ?? [],+ existing_matches: row.matches ?? [], first_seen: iso(row.first_seen),+ last_checked: Number.isFinite(new Date(row.last_checked).getTime()) ? iso(row.last_checked) : 'pending' };+ }) };+}diff --git a/src/core/wanted-links.ts b/src/core/wanted-links.tsnew file mode 100644index 0000000000..25d1691f61--- /dev/null+++ b/src/core/wanted-links.ts@@ -0,0 +1,87 @@+/**+ * Wanted pages: authored links whose target page does not exist yet.+ *+ * Link extraction used to drop such a candidate, so a page that linked to a+ * person before that person's page existed never gained the edge: nothing+ * re-extracted the linking page when the target appeared. Each unresolved+ * authored reference (a body markdown link or wikilink, or a frontmatter link+ * field) is recorded in `wanted_links`, replaced together with the origin's+ * derived links. A live page matching a wanted target and updated after the+ * row's `checked_at` makes the origin stale for extraction+ * (`WANTED_ORIGIN_IS_STALE` in engine-sql/pages.ts), so the next sweep creates the+ * edge and the row disappears. Rows are derived state: the page text is the+ * source of truth.+ */+import type { BrainEngine } from './engine.ts';+import type { LinkCandidate, UnresolvedFrontmatterRef } from './link-extraction.ts';+import { normalizeBasename, unwrapWikilink } from './link-extraction.ts';+import { isValidSourceId } from './source-id.ts';+import type { WantedLinkInput } from './wanted-links-store.ts';++export type { WantedLinkInput, WantedLinksReplacement, WantedProducer } from './wanted-links-store.ts';+export { replaceWantedLinks } from './wanted-links-store.ts';++type Resolution = { ok: true } | { ok: false; reason: string };++/**+ * Wanted rows for one origin page. A body reference is wanted only when every+ * alternative resolution of it failed because the target does not exist in the+ * reference's permitted domain: its qualified source, or the origin's own+ * source for an unqualified reference (a page with that slug in another source+ * does not satisfy it). A qualified reference into a source the origin may not+ * link to is forbidden, never wanted.+ */+export function collectWantedLinks(input: {+ candidates: readonly LinkCandidate[];+ frontmatterUnresolved?: readonly UnresolvedFrontmatterRef[];+ originSourceId: string;+ crossSourceAllowed: boolean;+ resolve: (candidate: LinkCandidate) => Resolution;+}): WantedLinkInput[] {+ const groups = new Map<string, { first: LinkCandidate; resolved: boolean; missing: boolean }>();+ for (const candidate of input.candidates) {+ const ref = candidate.authoredRef;+ if (!ref) continue;+ const result = input.resolve(candidate);+ const group = groups.get(ref.key) ?? { first: candidate, resolved: false, missing: true };+ if (result.ok) group.resolved = true;+ else if (result.reason !== 'missing_target' && result.reason !== 'cross_source') group.missing = false;+ groups.set(ref.key, group);+ }+ const rows = new Map<string, WantedLinkInput>();+ const add = (row: WantedLinkInput) => {+ const key = [row.producer, row.ref_kind, row.target_source_id, row.target_ref].join('\0');+ if (!rows.has(key)) rows.set(key, row);+ };+ for (const { first, resolved, missing } of groups.values()) {+ if (resolved || !missing) continue;+ const ref = first.authoredRef!;+ const targetSourceId = ref.targetSourceId ?? input.originSourceId;+ if (targetSourceId !== input.originSourceId && !input.crossSourceAllowed) continue;+ add({ producer: 'body', ref_kind: ref.kind, target_source_id: targetSourceId, target_ref: ref.target,+ link_type: first.linkType, context: first.context.slice(0, 240) });+ }+ for (const unresolved of input.frontmatterUnresolved ?? []) {+ if (unresolved.reason) continue;+ let target = unwrapWikilink(unresolved.name);+ let targetSourceId = input.originSourceId;+ const colon = target.indexOf(':');+ if (colon > 0 && isValidSourceId(target.slice(0, colon))) {+ targetSourceId = target.slice(0, colon);+ target = target.slice(colon + 1);+ if (targetSourceId !== input.originSourceId && !input.crossSourceAllowed) continue;+ }+ const slugShaped = /^[a-z0-9][a-z0-9_-]*(\/[a-z0-9][a-z0-9._-]*)+$/.test(target);+ const ref = slugShaped ? target : normalizeBasename(target);+ if (!ref) continue;+ add({ producer: 'frontmatter', ref_kind: slugShaped ? 'slug' : 'name', target_source_id: targetSourceId, target_ref: ref,+ link_type: '', context: `${unresolved.field}: ${unresolved.name}`.slice(0, 240) });+ }+ return [...rows.values()];+}++/** `wanted_pages.enabled` (default on). Off clears an origin's rows on its next extraction. */+export async function isWantedPagesEnabled(engine: Pick<BrainEngine, 'getConfig'>): Promise<boolean> {+ const value = await engine.getConfig('wanted_pages.enabled').catch(() => null);+ return value == null || !['false', '0', 'no', 'off'].includes(value.trim().toLowerCase());+}diff --git a/src/schema.sql b/src/schema.sqlindex 43fed65c5e..ff3959c470 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -265,6 +265,7 @@ CREATE TRIGGER bump_page_generation_clock_trgCREATE INDEX IF NOT EXISTS idx_pages_type ON pages(type);CREATE INDEX IF NOT EXISTS idx_pages_frontmatter ON pages USING GIN(frontmatter);CREATE INDEX IF NOT EXISTS idx_pages_trgm ON pages USING GIN(title gin_trgm_ops);+CREATE INDEX IF NOT EXISTS idx_pages_slug_basename ON pages (source_id, (regexp_replace(slug, '^.*/', '')));-- v0.13.1 #170: avoids 14.6s seqscan on large brains when listing pages newest-first.CREATE INDEX IF NOT EXISTS idx_pages_updated_at_desc ON pages (updated_at DESC);-- v0.18.0: source-scoped scans (per /plan-eng-review Section 4).@@ -513,6 +514,27 @@ CREATE INDEX IF NOT EXISTS idx_links_to ON links(to_page_id);CREATE INDEX IF NOT EXISTS idx_links_source ON links(link_source);CREATE INDEX IF NOT EXISTS idx_links_origin ON links(origin_page_id);+-- Wanted pages (migration wanted_links): authored links whose target page does+-- not exist. A live target updated after checked_at makes the origin stale for+-- link extraction (src/core/wanted-links.ts).+CREATE TABLE IF NOT EXISTS wanted_links (+ id BIGSERIAL PRIMARY KEY,+ origin_page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ producer TEXT NOT NULL CHECK (producer IN ('body','frontmatter')),+ ref_kind TEXT NOT NULL CHECK (ref_kind IN ('slug','name')),+ target_source_id TEXT NOT NULL,+ target_ref TEXT NOT NULL,+ link_type TEXT NOT NULL DEFAULT '',+ context TEXT NOT NULL DEFAULT '',+ checked_at TIMESTAMPTZ NOT NULL,+ first_seen_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ CONSTRAINT wanted_links_reference_unique+ UNIQUE (origin_page_id, producer, ref_kind, target_source_id, target_ref)+);+CREATE INDEX IF NOT EXISTS wanted_links_target_idx ON wanted_links (target_source_id, target_ref);+CREATE INDEX IF NOT EXISTS wanted_links_source_idx ON wanted_links (source_id);+-- ============================================================-- tags-- ============================================================@@ -1654,6 +1676,7 @@ BEGINALTER TABLE pages ENABLE ROW LEVEL SECURITY;ALTER TABLE content_chunks ENABLE ROW LEVEL SECURITY;ALTER TABLE links ENABLE ROW LEVEL SECURITY;+ ALTER TABLE wanted_links ENABLE ROW LEVEL SECURITY;ALTER TABLE tags ENABLE ROW LEVEL SECURITY;ALTER TABLE raw_data ENABLE ROW LEVEL SECURITY;ALTER TABLE timeline_entries ENABLE ROW LEVEL SECURITY;diff --git a/test/e2e/wanted-links-postgres.test.ts b/test/e2e/wanted-links-postgres.test.tsnew file mode 100644index 0000000000..9b7c609aa5--- /dev/null+++ b/test/e2e/wanted-links-postgres.test.ts@@ -0,0 +1,16 @@+/**+ * Postgres arms of the wanted-pages scenarios (test/wanted-links.test.ts runs+ * the same bodies on PGLite).+ */+import { describe, test } from 'bun:test';+import { bareNameReferenceSettles, disabledClearsRows, forwardReferenceHeals, onlyUnresolvedAuthoredReferences,+ privateOriginsStayPrivate } from '../helpers/wanted-links-scenarios.ts';++const url = process.env.DATABASE_URL;+describe.skipIf(!url)('Postgres wanted pages', () => {+ test('a forward reference heals once its target exists', () => forwardReferenceHeals(url), 180_000);+ test('only unresolved authored references are wanted', () => onlyUnresolvedAuthoredReferences(url), 180_000);+ test('a bare-name reference settles', () => bareNameReferenceSettles(url), 180_000);+ test('private origins stay private', () => privateOriginsStayPrivate(url), 180_000);+ test('disabling clears rows', () => disabledClearsRows(url), 180_000);+});diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex 99a6d7000e..d217e7f2ac 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -293,7 +293,13 @@"think_ab_results.think_ab_results_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","timeline_entries.timeline_entries_event_page_id_fkey": "f FOREIGN KEY (event_page_id) REFERENCES pages(id) ON DELETE CASCADE","timeline_entries.timeline_entries_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",- "timeline_entries.timeline_entries_pkey": "p PRIMARY KEY (id)"+ "timeline_entries.timeline_entries_pkey": "p PRIMARY KEY (id)",+ "wanted_links.wanted_links_origin_page_id_fkey": "f FOREIGN KEY (origin_page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "wanted_links.wanted_links_pkey": "p PRIMARY KEY (id)",+ "wanted_links.wanted_links_producer_check": "c CHECK ((producer = ANY (ARRAY['body'::text, 'frontmatter'::text])))",+ "wanted_links.wanted_links_ref_kind_check": "c CHECK ((ref_kind = ANY (ARRAY['slug'::text, 'name'::text])))",+ "wanted_links.wanted_links_reference_unique": "u UNIQUE (origin_page_id, producer, ref_kind, target_source_id, target_ref)",+ "wanted_links.wanted_links_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE"},"extensions": ["pg_trgm",@@ -641,6 +647,9 @@],"timeline_entries": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],+ "wanted_links": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"]},"indexes": {@@ -796,6 +805,7 @@"idx_pages_frontmatter": "CREATE INDEX idx_pages_frontmatter ON public.pages USING gin (frontmatter)","idx_pages_projection_pending": "CREATE INDEX idx_pages_projection_pending ON public.pages USING btree (source_id, page_kind, slug) WHERE ((deleted_at IS NULL) AND (text_projection_revision IS DISTINCT FROM knowledge_revision))","idx_pages_search": "CREATE INDEX idx_pages_search ON public.pages USING gin (search_vector)",+ "idx_pages_slug_basename": "CREATE INDEX idx_pages_slug_basename ON public.pages USING btree (source_id, regexp_replace(slug, '^.*/'::text, ''::text))","idx_pages_source_id": "CREATE INDEX idx_pages_source_id ON public.pages USING btree (source_id)","idx_pages_trgm": "CREATE INDEX idx_pages_trgm ON public.pages USING gin (title gin_trgm_ops)","idx_pages_type": "CREATE INDEX idx_pages_type ON public.pages USING btree (type)",@@ -977,7 +987,11 @@"timeline_entries_pkey": "CREATE UNIQUE INDEX timeline_entries_pkey ON public.timeline_entries USING btree (id)","uniq_minion_attachments_job_filename": "CREATE UNIQUE INDEX uniq_minion_attachments_job_filename ON public.minion_attachments USING btree (job_id, filename)","uniq_minion_jobs_idempotency": "CREATE UNIQUE INDEX uniq_minion_jobs_idempotency ON public.minion_jobs USING btree (idempotency_key) WHERE (idempotency_key IS NOT NULL)",- "uniq_subagent_messages_idx": "CREATE UNIQUE INDEX uniq_subagent_messages_idx ON public.subagent_messages USING btree (job_id, message_idx)"+ "uniq_subagent_messages_idx": "CREATE UNIQUE INDEX uniq_subagent_messages_idx ON public.subagent_messages USING btree (job_id, message_idx)",+ "wanted_links_pkey": "CREATE UNIQUE INDEX wanted_links_pkey ON public.wanted_links USING btree (id)",+ "wanted_links_reference_unique": "CREATE UNIQUE INDEX wanted_links_reference_unique ON public.wanted_links USING btree (origin_page_id, producer, ref_kind, target_source_id, target_ref)",+ "wanted_links_source_idx": "CREATE INDEX wanted_links_source_idx ON public.wanted_links USING btree (source_id)",+ "wanted_links_target_idx": "CREATE INDEX wanted_links_target_idx ON public.wanted_links USING btree (target_source_id, target_ref)"},"policies": {},"sequences": {@@ -1030,7 +1044,8 @@"take_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=take_proposals.id","takes_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=takes.id","think_ab_results_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=think_ab_results.id",- "timeline_entries_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=timeline_entries.id"+ "timeline_entries_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=timeline_entries.id",+ "wanted_links_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=wanted_links.id"},"tables": {"access_tokens": {@@ -2744,6 +2759,22 @@"15 last_written_at timestamp with time zone/timestamptz NULL"],"flags": "relkind=r rls=false force_rls=false"+ },+ "wanted_links": {+ "columns": [+ "1 id bigint/int8 NOT NULL DEFAULT nextval('wanted_links_id_seq'::regclass)",+ "2 origin_page_id integer/int4 NOT NULL",+ "3 source_id text/text NOT NULL",+ "4 producer text/text NOT NULL",+ "5 ref_kind text/text NOT NULL",+ "6 target_source_id text/text NOT NULL",+ "7 target_ref text/text NOT NULL",+ "8 link_type text/text NOT NULL DEFAULT ''::text",+ "9 context text/text NOT NULL DEFAULT ''::text",+ "10 checked_at timestamp with time zone/timestamptz NOT NULL",+ "11 first_seen_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=true force_rls=false"}},"triggers": {diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex db8a7c1b35..2302800257 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -293,7 +293,13 @@"think_ab_results.think_ab_results_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","timeline_entries.timeline_entries_event_page_id_fkey": "f FOREIGN KEY (event_page_id) REFERENCES pages(id) ON DELETE CASCADE","timeline_entries.timeline_entries_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",- "timeline_entries.timeline_entries_pkey": "p PRIMARY KEY (id)"+ "timeline_entries.timeline_entries_pkey": "p PRIMARY KEY (id)",+ "wanted_links.wanted_links_origin_page_id_fkey": "f FOREIGN KEY (origin_page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "wanted_links.wanted_links_pkey": "p PRIMARY KEY (id)",+ "wanted_links.wanted_links_producer_check": "c CHECK ((producer = ANY (ARRAY['body'::text, 'frontmatter'::text])))",+ "wanted_links.wanted_links_ref_kind_check": "c CHECK ((ref_kind = ANY (ARRAY['slug'::text, 'name'::text])))",+ "wanted_links.wanted_links_reference_unique": "u UNIQUE (origin_page_id, producer, ref_kind, target_source_id, target_ref)",+ "wanted_links.wanted_links_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE"},"extensions": ["pg_trgm",@@ -641,6 +647,9 @@],"timeline_entries": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],+ "wanted_links": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"]},"indexes": {@@ -796,6 +805,7 @@"idx_pages_frontmatter": "CREATE INDEX idx_pages_frontmatter ON public.pages USING gin (frontmatter)","idx_pages_projection_pending": "CREATE INDEX idx_pages_projection_pending ON public.pages USING btree (source_id, page_kind, slug) WHERE ((deleted_at IS NULL) AND (text_projection_revision IS DISTINCT FROM knowledge_revision))","idx_pages_search": "CREATE INDEX idx_pages_search ON public.pages USING gin (search_vector)",+ "idx_pages_slug_basename": "CREATE INDEX idx_pages_slug_basename ON public.pages USING btree (source_id, regexp_replace(slug, '^.*/'::text, ''::text))","idx_pages_source_id": "CREATE INDEX idx_pages_source_id ON public.pages USING btree (source_id)","idx_pages_trgm": "CREATE INDEX idx_pages_trgm ON public.pages USING gin (title gin_trgm_ops)","idx_pages_type": "CREATE INDEX idx_pages_type ON public.pages USING btree (type)",@@ -977,7 +987,11 @@"timeline_entries_pkey": "CREATE UNIQUE INDEX timeline_entries_pkey ON public.timeline_entries USING btree (id)","uniq_minion_attachments_job_filename": "CREATE UNIQUE INDEX uniq_minion_attachments_job_filename ON public.minion_attachments USING btree (job_id, filename)","uniq_minion_jobs_idempotency": "CREATE UNIQUE INDEX uniq_minion_jobs_idempotency ON public.minion_jobs USING btree (idempotency_key) WHERE (idempotency_key IS NOT NULL)",- "uniq_subagent_messages_idx": "CREATE UNIQUE INDEX uniq_subagent_messages_idx ON public.subagent_messages USING btree (job_id, message_idx)"+ "uniq_subagent_messages_idx": "CREATE UNIQUE INDEX uniq_subagent_messages_idx ON public.subagent_messages USING btree (job_id, message_idx)",+ "wanted_links_pkey": "CREATE UNIQUE INDEX wanted_links_pkey ON public.wanted_links USING btree (id)",+ "wanted_links_reference_unique": "CREATE UNIQUE INDEX wanted_links_reference_unique ON public.wanted_links USING btree (origin_page_id, producer, ref_kind, target_source_id, target_ref)",+ "wanted_links_source_idx": "CREATE INDEX wanted_links_source_idx ON public.wanted_links USING btree (source_id)",+ "wanted_links_target_idx": "CREATE INDEX wanted_links_target_idx ON public.wanted_links USING btree (target_source_id, target_ref)"},"policies": {},"sequences": {@@ -1030,7 +1044,8 @@"take_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=take_proposals.id","takes_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=takes.id","think_ab_results_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=think_ab_results.id",- "timeline_entries_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=timeline_entries.id"+ "timeline_entries_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=timeline_entries.id",+ "wanted_links_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=wanted_links.id"},"tables": {"access_tokens": {@@ -2744,6 +2759,22 @@"15 last_written_at timestamp with time zone/timestamptz NULL"],"flags": "relkind=r rls=false force_rls=false"+ },+ "wanted_links": {+ "columns": [+ "1 id bigint/int8 NOT NULL DEFAULT nextval('wanted_links_id_seq'::regclass)",+ "2 origin_page_id integer/int4 NOT NULL",+ "3 source_id text/text NOT NULL",+ "4 producer text/text NOT NULL",+ "5 ref_kind text/text NOT NULL",+ "6 target_source_id text/text NOT NULL",+ "7 target_ref text/text NOT NULL",+ "8 link_type text/text NOT NULL DEFAULT ''::text",+ "9 context text/text NOT NULL DEFAULT ''::text",+ "10 checked_at timestamp with time zone/timestamptz NOT NULL",+ "11 first_seen_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=true force_rls=false"}},"triggers": {diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex 796685335b..aab2d2404d 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -293,7 +293,13 @@"think_ab_results.think_ab_results_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","timeline_entries.timeline_entries_event_page_id_fkey": "f FOREIGN KEY (event_page_id) REFERENCES pages(id) ON DELETE CASCADE","timeline_entries.timeline_entries_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",- "timeline_entries.timeline_entries_pkey": "p PRIMARY KEY (id)"+ "timeline_entries.timeline_entries_pkey": "p PRIMARY KEY (id)",+ "wanted_links.wanted_links_origin_page_id_fkey": "f FOREIGN KEY (origin_page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "wanted_links.wanted_links_pkey": "p PRIMARY KEY (id)",+ "wanted_links.wanted_links_producer_check": "c CHECK ((producer = ANY (ARRAY['body'::text, 'frontmatter'::text])))",+ "wanted_links.wanted_links_ref_kind_check": "c CHECK ((ref_kind = ANY (ARRAY['slug'::text, 'name'::text])))",+ "wanted_links.wanted_links_reference_unique": "u UNIQUE (origin_page_id, producer, ref_kind, target_source_id, target_ref)",+ "wanted_links.wanted_links_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE"},"extensions": ["pg_trgm",@@ -641,6 +647,9 @@],"timeline_entries": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],+ "wanted_links": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"]},"indexes": {@@ -794,6 +803,7 @@"idx_pages_frontmatter": "CREATE INDEX idx_pages_frontmatter ON public.pages USING gin (frontmatter)","idx_pages_projection_pending": "CREATE INDEX idx_pages_projection_pending ON public.pages USING btree (source_id, page_kind, slug) WHERE ((deleted_at IS NULL) AND (text_projection_revision IS DISTINCT FROM knowledge_revision))","idx_pages_search": "CREATE INDEX idx_pages_search ON public.pages USING gin (search_vector)",+ "idx_pages_slug_basename": "CREATE INDEX idx_pages_slug_basename ON public.pages USING btree (source_id, regexp_replace(slug, '^.*/'::text, ''::text))","idx_pages_source_id": "CREATE INDEX idx_pages_source_id ON public.pages USING btree (source_id)","idx_pages_trgm": "CREATE INDEX idx_pages_trgm ON public.pages USING gin (title gin_trgm_ops)","idx_pages_type": "CREATE INDEX idx_pages_type ON public.pages USING btree (type)",@@ -973,7 +983,11 @@"timeline_entries_pkey": "CREATE UNIQUE INDEX timeline_entries_pkey ON public.timeline_entries USING btree (id)","uniq_minion_attachments_job_filename": "CREATE UNIQUE INDEX uniq_minion_attachments_job_filename ON public.minion_attachments USING btree (job_id, filename)","uniq_minion_jobs_idempotency": "CREATE UNIQUE INDEX uniq_minion_jobs_idempotency ON public.minion_jobs USING btree (idempotency_key) WHERE (idempotency_key IS NOT NULL)",- "uniq_subagent_messages_idx": "CREATE UNIQUE INDEX uniq_subagent_messages_idx ON public.subagent_messages USING btree (job_id, message_idx)"+ "uniq_subagent_messages_idx": "CREATE UNIQUE INDEX uniq_subagent_messages_idx ON public.subagent_messages USING btree (job_id, message_idx)",+ "wanted_links_pkey": "CREATE UNIQUE INDEX wanted_links_pkey ON public.wanted_links USING btree (id)",+ "wanted_links_reference_unique": "CREATE UNIQUE INDEX wanted_links_reference_unique ON public.wanted_links USING btree (origin_page_id, producer, ref_kind, target_source_id, target_ref)",+ "wanted_links_source_idx": "CREATE INDEX wanted_links_source_idx ON public.wanted_links USING btree (source_id)",+ "wanted_links_target_idx": "CREATE INDEX wanted_links_target_idx ON public.wanted_links USING btree (target_source_id, target_ref)"},"policies": {},"sequences": {@@ -1026,7 +1040,8 @@"take_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=take_proposals.id","takes_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=takes.id","think_ab_results_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=think_ab_results.id",- "timeline_entries_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=timeline_entries.id"+ "timeline_entries_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=timeline_entries.id",+ "wanted_links_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=wanted_links.id"},"tables": {"access_tokens": {@@ -2740,6 +2755,22 @@"15 last_written_at timestamp with time zone/timestamptz NULL"],"flags": "relkind=r rls=false force_rls=false"+ },+ "wanted_links": {+ "columns": [+ "1 id bigint/int8 NOT NULL DEFAULT nextval('wanted_links_id_seq'::regclass)",+ "2 origin_page_id integer/int4 NOT NULL",+ "3 source_id text/text NOT NULL",+ "4 producer text/text NOT NULL",+ "5 ref_kind text/text NOT NULL",+ "6 target_source_id text/text NOT NULL",+ "7 target_ref text/text NOT NULL",+ "8 link_type text/text NOT NULL DEFAULT ''::text",+ "9 context text/text NOT NULL DEFAULT ''::text",+ "10 checked_at timestamp with time zone/timestamptz NOT NULL",+ "11 first_seen_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=true force_rls=false"}},"triggers": {diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.jsonindex 3a33f51e94..6ff6f2b516 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json@@ -230,7 +230,13 @@"think_ab_results.think_ab_results_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","timeline_entries.timeline_entries_event_page_id_fkey": "f FOREIGN KEY (event_page_id) REFERENCES pages(id) ON DELETE CASCADE","timeline_entries.timeline_entries_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",- "timeline_entries.timeline_entries_pkey": "p PRIMARY KEY (id)"+ "timeline_entries.timeline_entries_pkey": "p PRIMARY KEY (id)",+ "wanted_links.wanted_links_origin_page_id_fkey": "f FOREIGN KEY (origin_page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "wanted_links.wanted_links_pkey": "p PRIMARY KEY (id)",+ "wanted_links.wanted_links_producer_check": "c CHECK ((producer = ANY (ARRAY['body'::text, 'frontmatter'::text])))",+ "wanted_links.wanted_links_ref_kind_check": "c CHECK ((ref_kind = ANY (ARRAY['slug'::text, 'name'::text])))",+ "wanted_links.wanted_links_reference_unique": "u UNIQUE (origin_page_id, producer, ref_kind, target_source_id, target_ref)",+ "wanted_links.wanted_links_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE"},"extensions": ["pg_trgm",@@ -499,6 +505,9 @@],"timeline_entries": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],+ "wanted_links": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"]},"indexes": {@@ -597,6 +606,7 @@"idx_oauth_tokens_expiry": "CREATE INDEX idx_oauth_tokens_expiry ON public.oauth_tokens USING btree (expires_at)","idx_pages_frontmatter": "CREATE INDEX idx_pages_frontmatter ON public.pages USING gin (frontmatter)","idx_pages_search": "CREATE INDEX idx_pages_search ON public.pages USING gin (search_vector)",+ "idx_pages_slug_basename": "CREATE INDEX idx_pages_slug_basename ON public.pages USING btree (source_id, regexp_replace(slug, '^.*/'::text, ''::text))","idx_pages_source_id": "CREATE INDEX idx_pages_source_id ON public.pages USING btree (source_id)","idx_pages_trgm": "CREATE INDEX idx_pages_trgm ON public.pages USING gin (title gin_trgm_ops)","idx_pages_type": "CREATE INDEX idx_pages_type ON public.pages USING btree (type)",@@ -733,7 +743,11 @@"timeline_entries_pkey": "CREATE UNIQUE INDEX timeline_entries_pkey ON public.timeline_entries USING btree (id)","uniq_minion_attachments_job_filename": "CREATE UNIQUE INDEX uniq_minion_attachments_job_filename ON public.minion_attachments USING btree (job_id, filename)","uniq_minion_jobs_idempotency": "CREATE UNIQUE INDEX uniq_minion_jobs_idempotency ON public.minion_jobs USING btree (idempotency_key) WHERE (idempotency_key IS NOT NULL)",- "uniq_subagent_messages_idx": "CREATE UNIQUE INDEX uniq_subagent_messages_idx ON public.subagent_messages USING btree (job_id, message_idx)"+ "uniq_subagent_messages_idx": "CREATE UNIQUE INDEX uniq_subagent_messages_idx ON public.subagent_messages USING btree (job_id, message_idx)",+ "wanted_links_pkey": "CREATE UNIQUE INDEX wanted_links_pkey ON public.wanted_links USING btree (id)",+ "wanted_links_reference_unique": "CREATE UNIQUE INDEX wanted_links_reference_unique ON public.wanted_links USING btree (origin_page_id, producer, ref_kind, target_source_id, target_ref)",+ "wanted_links_source_idx": "CREATE INDEX wanted_links_source_idx ON public.wanted_links USING btree (source_id)",+ "wanted_links_target_idx": "CREATE INDEX wanted_links_target_idx ON public.wanted_links USING btree (target_source_id, target_ref)"},"policies": {},"sequences": {@@ -774,7 +788,8 @@"take_nudge_log_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=take_nudge_log.id","take_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=take_proposals.id","think_ab_results_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=think_ab_results.id",- "timeline_entries_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=timeline_entries.id"+ "timeline_entries_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=timeline_entries.id",+ "wanted_links_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=wanted_links.id"},"tables": {"access_tokens": {@@ -2053,6 +2068,22 @@"8 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"],"flags": "relkind=r rls=false force_rls=false"+ },+ "wanted_links": {+ "columns": [+ "1 id bigint/int8 NOT NULL DEFAULT nextval('wanted_links_id_seq'::regclass)",+ "2 origin_page_id integer/int4 NOT NULL",+ "3 source_id text/text NOT NULL",+ "4 producer text/text NOT NULL",+ "5 ref_kind text/text NOT NULL",+ "6 target_source_id text/text NOT NULL",+ "7 target_ref text/text NOT NULL",+ "8 link_type text/text NOT NULL DEFAULT ''::text",+ "9 context text/text NOT NULL DEFAULT ''::text",+ "10 checked_at timestamp with time zone/timestamptz NOT NULL",+ "11 first_seen_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=false force_rls=false"}},"triggers": {diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.jsonindex 358ba68154..64bc4d9162 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json@@ -230,7 +230,13 @@"think_ab_results.think_ab_results_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","timeline_entries.timeline_entries_event_page_id_fkey": "f FOREIGN KEY (event_page_id) REFERENCES pages(id) ON DELETE CASCADE","timeline_entries.timeline_entries_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",- "timeline_entries.timeline_entries_pkey": "p PRIMARY KEY (id)"+ "timeline_entries.timeline_entries_pkey": "p PRIMARY KEY (id)",+ "wanted_links.wanted_links_origin_page_id_fkey": "f FOREIGN KEY (origin_page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "wanted_links.wanted_links_pkey": "p PRIMARY KEY (id)",+ "wanted_links.wanted_links_producer_check": "c CHECK ((producer = ANY (ARRAY['body'::text, 'frontmatter'::text])))",+ "wanted_links.wanted_links_ref_kind_check": "c CHECK ((ref_kind = ANY (ARRAY['slug'::text, 'name'::text])))",+ "wanted_links.wanted_links_reference_unique": "u UNIQUE (origin_page_id, producer, ref_kind, target_source_id, target_ref)",+ "wanted_links.wanted_links_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE"},"extensions": ["pg_trgm",@@ -499,6 +505,9 @@],"timeline_entries": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],+ "wanted_links": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"]},"indexes": {@@ -597,6 +606,7 @@"idx_oauth_tokens_expiry": "CREATE INDEX idx_oauth_tokens_expiry ON public.oauth_tokens USING btree (expires_at)","idx_pages_frontmatter": "CREATE INDEX idx_pages_frontmatter ON public.pages USING gin (frontmatter)","idx_pages_search": "CREATE INDEX idx_pages_search ON public.pages USING gin (search_vector)",+ "idx_pages_slug_basename": "CREATE INDEX idx_pages_slug_basename ON public.pages USING btree (source_id, regexp_replace(slug, '^.*/'::text, ''::text))","idx_pages_source_id": "CREATE INDEX idx_pages_source_id ON public.pages USING btree (source_id)","idx_pages_trgm": "CREATE INDEX idx_pages_trgm ON public.pages USING gin (title gin_trgm_ops)","idx_pages_type": "CREATE INDEX idx_pages_type ON public.pages USING btree (type)",@@ -733,7 +743,11 @@"timeline_entries_pkey": "CREATE UNIQUE INDEX timeline_entries_pkey ON public.timeline_entries USING btree (id)","uniq_minion_attachments_job_filename": "CREATE UNIQUE INDEX uniq_minion_attachments_job_filename ON public.minion_attachments USING btree (job_id, filename)","uniq_minion_jobs_idempotency": "CREATE UNIQUE INDEX uniq_minion_jobs_idempotency ON public.minion_jobs USING btree (idempotency_key) WHERE (idempotency_key IS NOT NULL)",- "uniq_subagent_messages_idx": "CREATE UNIQUE INDEX uniq_subagent_messages_idx ON public.subagent_messages USING btree (job_id, message_idx)"+ "uniq_subagent_messages_idx": "CREATE UNIQUE INDEX uniq_subagent_messages_idx ON public.subagent_messages USING btree (job_id, message_idx)",+ "wanted_links_pkey": "CREATE UNIQUE INDEX wanted_links_pkey ON public.wanted_links USING btree (id)",+ "wanted_links_reference_unique": "CREATE UNIQUE INDEX wanted_links_reference_unique ON public.wanted_links USING btree (origin_page_id, producer, ref_kind, target_source_id, target_ref)",+ "wanted_links_source_idx": "CREATE INDEX wanted_links_source_idx ON public.wanted_links USING btree (source_id)",+ "wanted_links_target_idx": "CREATE INDEX wanted_links_target_idx ON public.wanted_links USING btree (target_source_id, target_ref)"},"policies": {},"sequences": {@@ -774,7 +788,8 @@"take_nudge_log_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=take_nudge_log.id","take_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=take_proposals.id","think_ab_results_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=think_ab_results.id",- "timeline_entries_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=timeline_entries.id"+ "timeline_entries_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=timeline_entries.id",+ "wanted_links_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=wanted_links.id"},"tables": {"access_tokens": {@@ -2053,6 +2068,22 @@"8 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"],"flags": "relkind=r rls=false force_rls=false"+ },+ "wanted_links": {+ "columns": [+ "1 id bigint/int8 NOT NULL DEFAULT nextval('wanted_links_id_seq'::regclass)",+ "2 origin_page_id integer/int4 NOT NULL",+ "3 source_id text/text NOT NULL",+ "4 producer text/text NOT NULL",+ "5 ref_kind text/text NOT NULL",+ "6 target_source_id text/text NOT NULL",+ "7 target_ref text/text NOT NULL",+ "8 link_type text/text NOT NULL DEFAULT ''::text",+ "9 context text/text NOT NULL DEFAULT ''::text",+ "10 checked_at timestamp with time zone/timestamptz NOT NULL",+ "11 first_seen_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=false force_rls=false"}},"triggers": {diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.jsonindex c53886296f..ea3c33919f 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json@@ -230,7 +230,13 @@"think_ab_results.think_ab_results_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","timeline_entries.timeline_entries_event_page_id_fkey": "f FOREIGN KEY (event_page_id) REFERENCES pages(id) ON DELETE CASCADE","timeline_entries.timeline_entries_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",- "timeline_entries.timeline_entries_pkey": "p PRIMARY KEY (id)"+ "timeline_entries.timeline_entries_pkey": "p PRIMARY KEY (id)",+ "wanted_links.wanted_links_origin_page_id_fkey": "f FOREIGN KEY (origin_page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "wanted_links.wanted_links_pkey": "p PRIMARY KEY (id)",+ "wanted_links.wanted_links_producer_check": "c CHECK ((producer = ANY (ARRAY['body'::text, 'frontmatter'::text])))",+ "wanted_links.wanted_links_ref_kind_check": "c CHECK ((ref_kind = ANY (ARRAY['slug'::text, 'name'::text])))",+ "wanted_links.wanted_links_reference_unique": "u UNIQUE (origin_page_id, producer, ref_kind, target_source_id, target_ref)",+ "wanted_links.wanted_links_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE"},"extensions": ["pg_trgm",@@ -499,6 +505,9 @@],"timeline_entries": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],+ "wanted_links": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"]},"indexes": {@@ -596,6 +605,7 @@"idx_oauth_tokens_expiry": "CREATE INDEX idx_oauth_tokens_expiry ON public.oauth_tokens USING btree (expires_at)","idx_pages_frontmatter": "CREATE INDEX idx_pages_frontmatter ON public.pages USING gin (frontmatter)","idx_pages_search": "CREATE INDEX idx_pages_search ON public.pages USING gin (search_vector)",+ "idx_pages_slug_basename": "CREATE INDEX idx_pages_slug_basename ON public.pages USING btree (source_id, regexp_replace(slug, '^.*/'::text, ''::text))","idx_pages_source_id": "CREATE INDEX idx_pages_source_id ON public.pages USING btree (source_id)","idx_pages_trgm": "CREATE INDEX idx_pages_trgm ON public.pages USING gin (title gin_trgm_ops)","idx_pages_type": "CREATE INDEX idx_pages_type ON public.pages USING btree (type)",@@ -732,7 +742,11 @@"timeline_entries_pkey": "CREATE UNIQUE INDEX timeline_entries_pkey ON public.timeline_entries USING btree (id)","uniq_minion_attachments_job_filename": "CREATE UNIQUE INDEX uniq_minion_attachments_job_filename ON public.minion_attachments USING btree (job_id, filename)","uniq_minion_jobs_idempotency": "CREATE UNIQUE INDEX uniq_minion_jobs_idempotency ON public.minion_jobs USING btree (idempotency_key) WHERE (idempotency_key IS NOT NULL)",- "uniq_subagent_messages_idx": "CREATE UNIQUE INDEX uniq_subagent_messages_idx ON public.subagent_messages USING btree (job_id, message_idx)"+ "uniq_subagent_messages_idx": "CREATE UNIQUE INDEX uniq_subagent_messages_idx ON public.subagent_messages USING btree (job_id, message_idx)",+ "wanted_links_pkey": "CREATE UNIQUE INDEX wanted_links_pkey ON public.wanted_links USING btree (id)",+ "wanted_links_reference_unique": "CREATE UNIQUE INDEX wanted_links_reference_unique ON public.wanted_links USING btree (origin_page_id, producer, ref_kind, target_source_id, target_ref)",+ "wanted_links_source_idx": "CREATE INDEX wanted_links_source_idx ON public.wanted_links USING btree (source_id)",+ "wanted_links_target_idx": "CREATE INDEX wanted_links_target_idx ON public.wanted_links USING btree (target_source_id, target_ref)"},"policies": {},"sequences": {@@ -773,7 +787,8 @@"take_nudge_log_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=take_nudge_log.id","take_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=take_proposals.id","think_ab_results_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=think_ab_results.id",- "timeline_entries_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=timeline_entries.id"+ "timeline_entries_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=timeline_entries.id",+ "wanted_links_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=wanted_links.id"},"tables": {"access_tokens": {@@ -2052,6 +2067,22 @@"8 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"],"flags": "relkind=r rls=false force_rls=false"+ },+ "wanted_links": {+ "columns": [+ "1 id bigint/int8 NOT NULL DEFAULT nextval('wanted_links_id_seq'::regclass)",+ "2 origin_page_id integer/int4 NOT NULL",+ "3 source_id text/text NOT NULL",+ "4 producer text/text NOT NULL",+ "5 ref_kind text/text NOT NULL",+ "6 target_source_id text/text NOT NULL",+ "7 target_ref text/text NOT NULL",+ "8 link_type text/text NOT NULL DEFAULT ''::text",+ "9 context text/text NOT NULL DEFAULT ''::text",+ "10 checked_at timestamp with time zone/timestamptz NOT NULL",+ "11 first_seen_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=false force_rls=false"}},"triggers": {diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 8c613f7b27..7c50b65a68 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 196835,- "stdoutSha256": "7c6a8f58d1ecf9152a0bef45fe6b85d84ea6bc81c4610fc65b2a65eeec68370a",+ "stdoutBytes": 198031,+ "stdoutSha256": "1286e4a2fec89a92a17091deee6dee28d49823f587d066629978b452e7037f9e","toolNames": ["remember","entity",@@ -38,6 +38,7 @@"get_backlinks","list_link_sources","traverse_graph",+ "wanted_pages","add_timeline_entry","get_timeline","get_stats",@@ -1690,6 +1691,43 @@},"scope": "read"},+ {+ "description": "Link targets that have no page yet, most-referenced first: each was written as a link but its page does not exist, so no edge exists. Use to find entities worth a page (enrichment) or typo links to fix. The edge appears on its own once the page is created.",+ "idempotent": true,+ "local_only": false,+ "mutating": false,+ "name": "wanted_pages",+ "parameters": {+ "count_only": "boolean?",+ "limit": "number?",+ "offset": "number?",+ "source_id": "string?"+ },+ "required_scopes": [],+ "schema": {+ "properties": {+ "count_only": {+ "description": "Return the total with no rows.",+ "type": "boolean"+ },+ "limit": {+ "description": "Rows per page (default 50, max 100).",+ "type": "number"+ },+ "offset": {+ "description": "Skip the first N targets.",+ "type": "number"+ },+ "source_id": {+ "description": "Only targets referenced from this source (must be inside your source grant).",+ "type": "string"+ }+ },+ "required": [],+ "type": "object"+ },+ "scope": "read"+ },{"description": "Append a dated entry to a page timeline. Replaying the same entry changes nothing.","idempotent": true,diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 190c942fa0..7e722f3fe4 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 195,+ "count": 196,"gaps": [17,18,@@ -28,7 +28,7 @@"slugifyPath": "401dbca23580865d8b168dd8d84db4a6c708c6610d7cb61abafc7d0ee9809063","verifyProjectionStatistics": "59d9ccfea1c53384d8607874a51209a9c2dfd51b2b85a2cb6269fa4120faf1f3"},- "latest": 200,+ "latest": 201,"records": [{"handler": {@@ -2968,6 +2968,19 @@"transaction": "absent","verify": "absent","version": 200+ },+ {+ "handler": "absent",+ "idempotent": true,+ "name": "wanted_links",+ "sql": {+ "length": 1422,+ "sha256": "9f86606532990d1946206c23c7dcb0134bfbde881c5a63653b442d355d6042d8"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",+ "version": 201}],"versions": [@@ -3165,7 +3178,8 @@197,198,199,- 200+ 200,+ 201]},"normalizer": "migrations-record-v1"diff --git a/test/helpers/wanted-links-scenarios.ts b/test/helpers/wanted-links-scenarios.tsnew file mode 100644index 0000000000..309afd7a82--- /dev/null+++ b/test/helpers/wanted-links-scenarios.ts@@ -0,0 +1,113 @@+/**+ * Engine-parametrized wanted-pages scenarios. PGLite runs them from+ * test/wanted-links.test.ts; test/e2e/wanted-links-postgres.test.ts runs the+ * same bodies on Postgres.+ */+import { expect } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { OperationContext } from '../../src/core/ops/contract.ts';+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';+import { extractStaleFromDB } from '../../src/commands/extract.ts';+import { LINK_EXTRACTOR_VERSION_TS } from '../../src/core/link-extraction.ts';+import { operationsByName } from '../../src/core/operations.ts';+import { managedBrain } from './managed-brain.ts';++const put = (ctx: OperationContext, slug: string, body: string, type = 'note', frontmatter = '', expectedRevision?: string) =>+ submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(),+ ...(expectedRevision ? { expected_revision: expectedRevision } : {}),+ content: `---\ntype: ${type}\ntitle: ${slug}\n${frontmatter}---\n\n${body}\n` } }) as Promise<Record<string, any>>;+const stale = (engine: BrainEngine) => engine.countStalePagesForExtraction({ versionTs: LINK_EXTRACTOR_VERSION_TS });+const extractStale = (engine: BrainEngine) => extractStaleFromDB(engine, { dryRun: false, jsonMode: true, quiet: true, catchUp: true });+const wantedRows = (engine: BrainEngine) => engine.executeRaw<{ target_ref: string; ref_kind: string; producer: string }>(+ 'SELECT target_ref, ref_kind, producer FROM wanted_links ORDER BY target_ref');+const backlinks = (engine: BrainEngine, slug: string) => engine.executeRaw<{ slug: string }>(`SELECT f.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 t.slug=$1 ORDER BY f.slug`, [slug]);+const wantedOp = (ctx: OperationContext, params: Record<string, unknown> = {}) =>+ operationsByName.wanted_pages!.handler(ctx, params) as Promise<{ total: number; targets: Array<Record<string, any>> }>;++/** A link written before its target page exists becomes an edge once the target is created, after the next sweep. */+export async function forwardReferenceHeals(databaseUrl?: string) {+ await managedBrain(async ({ engine, ctx }) => {+ const written = await put(ctx, 'notes/lunch', 'Lunch with [[people/carol-example]] about [[companies/acme-example]].');+ const autoLinks = (written.outcome ?? written).auto_links;+ expect(autoLinks.wanted_count).toBe(2);+ expect(autoLinks.wanted).toHaveLength(2);+ expect(autoLinks.wanted).toEqual(expect.arrayContaining([{ slug: 'people/carol-example', source_id: 'default' },+ { slug: 'companies/acme-example', source_id: 'default' }]));+ expect(autoLinks.fix).toMatchObject({ argv: ['gbrain', 'wanted', '--source-id', 'default'], mcp: { tool: 'wanted_pages' } });+ await extractStale(engine);+ expect(await stale(engine)).toBe(0);+ expect((await wantedRows(engine)).map(row => row.target_ref)).toEqual(['companies/acme-example', 'people/carol-example']);++ await put(ctx, 'people/carol-example', 'Carol.', 'person');+ // The origin was stamped before Carol existed; the wanted row makes it stale again.+ expect(await stale(engine)).toBeGreaterThanOrEqual(1);+ await extractStale(engine);+ expect(await backlinks(engine, 'people/carol-example')).toEqual([{ slug: 'notes/lunch' }]);+ expect((await wantedRows(engine)).map(row => row.target_ref)).toEqual(['companies/acme-example']);+ expect(await stale(engine)).toBe(0);+ const listed = await wantedOp(ctx);+ expect(listed.total).toBe(1);+ expect(listed.targets[0]).toMatchObject({ target: 'companies/acme-example', referenced_by: 1,+ sample_origins: [{ slug: 'notes/lunch', source_id: 'default' }] });+ }, { databaseUrl });+}++/** Resolved references, bare prose paths and code spans never become wanted rows. */+export async function onlyUnresolvedAuthoredReferences(databaseUrl?: string) {+ await managedBrain(async ({ engine, ctx }) => {+ await put(ctx, 'people/alice-example', 'Alice.', 'person');+ await put(ctx, 'notes/mixed', [+ 'Met [[people/alice-example]].',+ 'See src/core/engine.ts and and/or docs/guides/missing for context.',+ 'Code: `[[people/in-code]]`.',+ ].join('\n'));+ await extractStale(engine);+ expect(await wantedRows(engine)).toEqual([]);+ }, { databaseUrl });+}++/** A bare-name reference that matches a page only by basename wakes its origin once, then settles (no re-listing loop). */+export async function bareNameReferenceSettles(databaseUrl?: string) {+ await managedBrain(async ({ engine, ctx }) => {+ await put(ctx, 'notes/call', 'Call with [[Dave Example]].');+ await extractStale(engine);+ expect(await wantedRows(engine)).toEqual([{ target_ref: 'dave-example', ref_kind: 'name', producer: 'body' }]);+ await put(ctx, 'people/dave-example', 'Dave.', 'person');+ expect(await stale(engine)).toBeGreaterThanOrEqual(1);+ await extractStale(engine);+ expect(await stale(engine)).toBe(0);+ const listed = await wantedOp(ctx);+ expect(listed.targets[0]).toMatchObject({ target: 'dave-example', ref_kind: 'name',+ existing_matches: [{ slug: 'people/dave-example', source_id: 'default' }] });+ expect(listed.targets[0].next).toContain('[[people/dave-example]]');+ }, { databaseUrl });+}++/** A remote caller never sees targets referenced only from private pages, nor counts that include them. */+export async function privateOriginsStayPrivate(databaseUrl?: string) {+ await managedBrain(async ({ engine, ctx }) => {+ await put(ctx, 'notes/open', 'Ask [[people/shared-target]].');+ await put(ctx, 'notes/secret', 'Ask [[people/shared-target]] and [[people/secret-target]].', 'note', 'visibility: private\n');+ await extractStale(engine);+ const local = await wantedOp(ctx);+ expect(local.targets.map(t => [t.target, t.referenced_by])).toEqual([['people/shared-target', 2], ['people/secret-target', 1]]);+ const remote = await wantedOp({ ...ctx, remote: true });+ expect(remote.total).toBe(1);+ expect(remote.targets.map(t => [t.target, t.referenced_by])).toEqual([['people/shared-target', 1]]);+ expect(JSON.stringify(remote)).not.toContain('secret');+ }, { databaseUrl });+}++/** Turning the feature off clears an origin's rows on its next extraction. */+export async function disabledClearsRows(databaseUrl?: string) {+ await managedBrain(async ({ engine, ctx }) => {+ const first = await put(ctx, 'notes/lunch', 'Lunch with [[people/carol-example]].');+ await extractStale(engine);+ expect(await wantedRows(engine)).toHaveLength(1);+ await engine.setConfig('wanted_pages.enabled', 'false');+ await put(ctx, 'notes/lunch', 'Lunch with [[people/carol-example]] again.', 'note', '', (first.outcome ?? first).revision);+ expect(await wantedRows(engine)).toEqual([]);+ }, { databaseUrl });+}diff --git a/test/operations-coverage-ledger.test.ts b/test/operations-coverage-ledger.test.tsindex 4d5cea1f05..90296ceda7 100644--- a/test/operations-coverage-ledger.test.ts+++ b/test/operations-coverage-ledger.test.ts@@ -109,6 +109,7 @@ const LEDGER: Record<string, string> = {get_agent_job: 'test/get-agent-job.test.ts',get_job_stats: 'test/get-job-stats-op.test.ts',find_orphans: 'test/orphans-source-scope.test.ts',+ wanted_pages: 'test/wanted-links.test.ts',get_calibration_profile: 'test/calibration-cli.test.ts',takes_list: 'test/takes-mcp-allowlist.serial.test.ts',takes_search: 'test/takes-mcp-allowlist.serial.test.ts',diff --git a/test/operations-source-isolation-matrix.test.ts b/test/operations-source-isolation-matrix.test.tsindex 0ff74a2645..7803312333 100644--- a/test/operations-source-isolation-matrix.test.ts+++ b/test/operations-source-isolation-matrix.test.ts@@ -163,6 +163,7 @@ const MATRIX: Row[] = [{ name: 'get_chunks', mode: 'isolated', args: { slug: 'notes/beta-note' } },{ name: 'get_ingest_log', mode: 'isolated', args: { limit: 50 } },{ name: 'find_orphans', mode: 'isolated', args: {} },+ { name: 'wanted_pages', mode: 'isolated', args: {} },{ name: 'takes_list', mode: 'isolated', args: { limit: 50 } },{ name: 'takes_search', mode: 'isolated', args: { query: 'BETAMARKER', limit: 20 } },{ name: 'get_recent_salience', mode: 'isolated', args: { limit: 50 } },@@ -251,6 +252,10 @@ beforeAll(async () => {await engine.addTag(`notes/${name}-note`, `${name}-topic`, { sourceId: src });await engine.addTag(`people/${name}-person`, `${name}-topic`, { sourceId: src });await engine.addLink(`notes/${name}-note`, `people/${name}-person`, `${MARK} ctx`, 'mentions', 'markdown', undefined, undefined, { fromSourceId: src, toSourceId: src });+ // Wanted page: an unresolved link from the note to a missing marker-named target.+ await engine.executeRaw(`INSERT INTO wanted_links (origin_page_id, source_id, producer, ref_kind, target_source_id, target_ref, checked_at)+ SELECT id, $1, 'body', 'slug', $1, $2, now() FROM pages WHERE slug = $3 AND source_id = $1`,+ [src, `people/${name}-missing-${MARK.toLowerCase()}`, `notes/${name}-note`]);await engine.createVersion(`notes/${name}-note`, { sourceId: src });await engine.putRawData(`notes/${name}-note`, 'crm', { owner: MARK }, { sourceId: src });await engine.logIngest({diff --git a/test/remote-privacy-sweep.test.ts b/test/remote-privacy-sweep.test.tsindex cbc1562cc2..5896bac5af 100644--- a/test/remote-privacy-sweep.test.ts+++ b/test/remote-privacy-sweep.test.ts@@ -263,6 +263,7 @@ const EXPECTED_OUTCOME: Record<string, Outcome> = {sources_list: 'ok',sources_status: 'ok',find_orphans: 'ok',+ wanted_pages: 'ok',find_contradictions: 'ok',find_experts: 'ok',find_trajectory: 'ok',diff --git a/test/retrieval-op-redaction.test.ts b/test/retrieval-op-redaction.test.tsindex 3bf5a9027a..06ae056549 100644--- a/test/retrieval-op-redaction.test.ts+++ b/test/retrieval-op-redaction.test.ts@@ -145,6 +145,8 @@ const SWEEP: Record<string, Row> = {advisor: { skip: 'aggregate advisory over the installed skill stack; advisor suites own it' },get_ingest_log: { args: { limit: 50 } },find_orphans: { args: {} },+ // Targets and origin slugs only; the fixture has no unresolved links (behavior: test/wanted-links.test.ts).+ wanted_pages: { args: {}, content: false },get_calibration_profile: { args: {}, content: false },takes_list: { args: { limit: 50 } },takes_search: { args: { query: 'PLANTMARK', limit: 20 } },diff --git a/test/wanted-links.test.ts b/test/wanted-links.test.tsnew file mode 100644index 0000000000..3a84d9c6fe--- /dev/null+++ b/test/wanted-links.test.ts@@ -0,0 +1,83 @@+/**+ * Wanted pages on PGLite: unresolved authored links are recorded, heal into+ * edges when their target appears, stay private, and never loop the stale+ * sweep. Postgres arm: test/e2e/wanted-links-postgres.test.ts.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { extractStaleFromDB } from '../src/commands/extract.ts';+import { collectWantedLinks } from '../src/core/wanted-links.ts';+import type { LinkCandidate } from '../src/core/link-extraction.ts';+import { bareNameReferenceSettles, disabledClearsRows, forwardReferenceHeals, onlyUnresolvedAuthoredReferences,+ privateOriginsStayPrivate } from './helpers/wanted-links-scenarios.ts';++test('a link written before its target exists becomes an edge after the target is created', () => forwardReferenceHeals(), 120_000);+test('resolved references, prose paths and code spans are never wanted', () => onlyUnresolvedAuthoredReferences(), 120_000);+test('a bare-name reference matched only by basename settles after one re-extraction', () => bareNameReferenceSettles(), 120_000);+test('remote callers never see targets or counts from private origins', () => privateOriginsStayPrivate(), 120_000);+test('wanted_pages.enabled=false clears an origin\'s rows on its next extraction', () => disabledClearsRows(), 120_000);++describe('collectWantedLinks', () => {+ const candidate = (targetSlug: string, key: string, extra: Partial<LinkCandidate> = {}): LinkCandidate => ({+ targetSlug, linkType: 'mentions', context: `ctx ${targetSlug}`, linkSource: 'markdown',+ authoredRef: { key, kind: 'slug', target: targetSlug }, ...extra });+ const run = (candidates: LinkCandidate[], outcome: Record<string, string>, crossSourceAllowed = false) =>+ collectWantedLinks({ candidates, originSourceId: 'src-a', crossSourceAllowed,+ resolve: c => outcome[c.targetSlug] === 'ok' ? { ok: true } : { ok: false, reason: outcome[c.targetSlug] ?? 'missing_target' } });++ test('a reference is wanted only when every alternative fails', () => {+ const bare = { key: 'ref:1', kind: 'name' as const, target: 'acme' };+ expect(run([candidate('acme', 'ref:1', { authoredRef: bare }), candidate('companies/acme', 'ref:1', { authoredRef: bare })],+ { acme: 'missing_target', 'companies/acme': 'ok' })).toEqual([]);+ expect(run([candidate('acme', 'ref:1', { authoredRef: bare })], {})).toEqual([{ producer: 'body', ref_kind: 'name',+ target_source_id: 'src-a', target_ref: 'acme', link_type: 'mentions', context: 'ctx acme' }]);+ });++ test('an unqualified target that exists only in another source is wanted in the origin source', () => {+ expect(run([candidate('people/x', 'ref:1')], { 'people/x': 'cross_source' })).toMatchObject([{ target_source_id: 'src-a', target_ref: 'people/x' }]);+ });++ test('a qualified reference into a forbidden source is never wanted; an allowed one keeps its source', () => {+ const qualified = candidate('people/x', 'ref:1', { targetSourceId: 'src-b',+ authoredRef: { key: 'ref:1', kind: 'slug', target: 'people/x', targetSourceId: 'src-b' } });+ expect(run([qualified], {})).toEqual([]);+ expect(run([qualified], {}, true)).toMatchObject([{ target_source_id: 'src-b', target_ref: 'people/x' }]);+ });++ test('candidates without an authored reference (prose paths) and non-missing failures are ignored', () => {+ expect(run([{ targetSlug: 'and/or', linkType: 'mentions', context: '', linkSource: 'markdown' }], {})).toEqual([]);+ expect(run([candidate('people/x', 'ref:1')], { 'people/x': 'missing_from' })).toEqual([]);+ });++ test('unresolved frontmatter names become name refs; qualified slugs keep their source', () => {+ expect(collectWantedLinks({ candidates: [], originSourceId: 'src-a', crossSourceAllowed: false, resolve: () => ({ ok: true }),+ frontmatterUnresolved: [{ field: 'company', name: 'Acme Example' }, { field: 'key_people', name: '[[people/bob-example]]' },+ { field: 'investors', name: 'src-b:companies/fund-a' }, { field: 'company', name: 'Typed', reason: 'target_type_mismatch' }] }))+ .toEqual([+ { producer: 'frontmatter', ref_kind: 'name', target_source_id: 'src-a', target_ref: 'acme-example', link_type: '', context: 'company: Acme Example' },+ { producer: 'frontmatter', ref_kind: 'slug', target_source_id: 'src-a', target_ref: 'people/bob-example', link_type: '', context: 'key_people: [[people/bob-example]]' },+ ]);+ });+});++describe('unmanaged brain', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ }, 60_000);+ afterAll(async () => { await engine.disconnect(); }, 60_000);++ test('the unmanaged stale sweep records and heals wanted links too', async () => {+ const sweep = () => extractStaleFromDB(engine, { dryRun: false, jsonMode: true, quiet: true, catchUp: true });+ await engine.putPage('notes/lunch', { type: 'note', title: 'Lunch', compiled_truth: 'Lunch with [[people/carol-example]].', timeline: '' });+ await sweep();+ expect(await engine.executeRaw('SELECT target_ref FROM wanted_links')).toEqual([{ target_ref: 'people/carol-example' }]);+ await engine.putPage('people/carol-example', { type: 'person', title: 'Carol', compiled_truth: 'Carol.', timeline: '' });+ await sweep();+ expect(await engine.executeRaw(`SELECT f.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 t.slug='people/carol-example'`)).toEqual([{ slug: 'notes/lunch' }]);+ expect(await engine.executeRaw('SELECT target_ref FROM wanted_links')).toEqual([]);+ }, 120_000);+});