Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(extract): stop silently dropping links from non-whitelisted directories (#2576) (#3560)

Garry Tanf08a51d9ded3
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index 6766a21f26..4afd268cb5 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -201,7 +201,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/core/conversation-parser/` — 17-pattern built-in chat-format registry + opt-in LLM polish/fallback. Modules: `types.ts` (PatternEntry + ParseResult + DateContext + CaptureMap + TimezonePolicy), `builtins.ts` (17 hand-vetted patterns sourced from public format docs — iMessage/Slack, Telegram bracket + text-export, bold-paren-time, bold-time-dash, bold-name-no-time, Discord classic + export, WhatsApp ISO + US, Signal, Matrix/Element, IRC classic + weechat, Teams export; module-load validation runs every `test_positive[]` + `test_negative[]` sample at startup so a typo in any built-in regex makes gbrain refuse to start; `DEFAULT_SPEAKER_CLEAN` exported as a module-level default), `parse.ts` (orchestrator with pattern-priority scoring across the first 10 lines + date derivation chain `explicit > frontmatter.date > effective_date > '1970-01-01'` + multi-line continuation + timezone warning), `llm-base.ts` (shared `runLlmCall<T>` with content-hash cache in-process + DB-persistent via migration v97 + 4-strategy JSON repair + Anthropic-key probe; polish and fallback are thin wrappers), `llm-polish.ts` (opt-IN; headroom guard skips when tracker within $0.10 of cap; pure `applyPolish` for merge/drop/edit ops), `llm-fallback.ts` (opt-IN; NO regex inference + NO persistence), `eval.ts` (`scoreFixture` + `aggregateScores` + `parseFixtureJsonl` for the fixture-corpus CI gate), `nightly-probe.ts` (DI-stubbed; mode-gated default tokenmax=ON, conservative/balanced opt-in; adversarial false-positive detection). Pattern `bold-name-no-time` (regex `/^\*\*(?!\[)(.+?):\*\*\s*(.*)$/`, ordered after the time-bearing bold patterns) parses `**Speaker:** text` with NO per-line timestamp (Circleback/Granola/Zoom), anchoring every message at `T00:00:00Z` of the frontmatter date (line order preserves sequence, same no-time convention as `irc-classic`); the `(?!\[)` lookahead rejects telegram-bracket `**[18:37] Name:**`; non-shadow is the colon-INSIDE-bold regex (NOT declaration order — `parse.ts` scores every candidate independently, order is only the tie-break). Because `**Label:** text` is a common prose idiom, the pattern sets optional `PatternEntry.score_full_body: true` so `parse.ts` recomputes the winner's acceptance score over the FULL body before the `SCORING_MIN_ACCEPTANCE` floor, keeping a bold-label notes page at `no_match`. Pattern `bold-paren-time` parses `**Speaker** (HH:MM): text` and `(HH:MM:SS)` (date_source: frontmatter). Fallback gates: `SCORING_HEAD_TRIGGER_THRESHOLD = 0.3` triggers a full-body re-score when the head pass scores below that; `SCORING_MIN_ACCEPTANCE = 0.05` blocks essay false-positives. Exported `scorePatternFull(body, entry)`; private `getNonBlankLines(body, headCap?)` + `scoreFromLines(lines, entry)` DRY the quick_reject+regex loop. CLI surfaces at `src/commands/eval-conversation-parser.ts` (`gbrain eval conversation-parser <fixture.jsonl>` exit 0/1/2, wired into `bun run verify` via `check:conversation-parser`) and `src/commands/conversation-parser.ts` (`scan <slug>` debug, `list-builtins`, `validate <file>`). Doctor checks: `conversation_format_coverage`, `progressive_batch_audit_health`, `conversation_parser_probe_health`. Pinned by `test/conversation-parser/{parse,llm-base,llm-fallback,llm-polish,nightly-probe}.test.ts` + the 27-case baseline at `test/extract-conversation-facts.test.ts` (back-compat invariant). Migration v97 (`conversation_parser_llm_cache_table`). Fixtures at `test/fixtures/conversation-formats/{imessage,imessage-time-only-12h,telegram-bracket,whatsapp-iso,whatsapp-us,signal-export,irc-classic,irc-weechat,matrix-element,teams-export,all,adversarial,bold-name-no-time,bold-time-dash}.jsonl` with `scripts/check-fixture-privacy.sh` banning real-name leaks. Maintainer guidance: [conversation parser patterns](conversation-parser-patterns.md).
- `src/core/progressive-batch/` — shared ramp-up + cost-cap + verification primitive (trial 10 → ramp 100 → ramp 500 → full, with verification at each stage), with verifier+policy injection (callers describe HOW TO MEASURE SUCCESS, not WHEN TO WAIT FOR CTRL-C). Modules: `types.ts` (Stage, StageVerdict, AbortReason, discriminated `Verifier` union `OutputCountVerifier | IdempotentMutationVerifier | NoopVerifier`, Policy, StageReport), `orchestrator.ts` (`runProgressiveBatch(items, verifier, policy, runner)` — reads `getCurrentBudgetTracker()` ahead of `Policy.maxCostUsd` fail-closed; null both ways triggers `abort_cost_cap reason='no_budget_safety_net'`), `audit.ts` (ISO-week JSONL at `~/.gbrain/audit/progressive-batch-YYYY-Www.jsonl` via the shared `audit-writer` primitive), `stage-report.ts` (ASCII formatter for the default `Policy.onStageReport`). Env knobs: `GBRAIN_PROGRESSIVE_BATCH_DISABLED=1`, `GBRAIN_PROGRESSIVE_BATCH_AUTO=1` (skip Ctrl-C grace), `GBRAIN_PROGRESSIVE_BATCH_STAGES=10,100,500`. Sites that "jump straight to full" stay that way by default; ramp is opt-in per-site via `Policy.interactiveAbortMs > 0`. Pinned by `test/progressive-batch/orchestrator.test.ts` (35 cases, every verdict path).
- `src/commands/extract-conversation-facts.ts` + `src/core/cycle/conversation-facts-backfill.ts` — bulk fact extraction for long-form conversation pages. Walks conversation/meeting/slack/email/imessage/imessage-daily pages, splits them into time-windowed segments (30-min gap or 30-msg cap), prepends a topical/temporal header, and uses the strict `extractFactsFromTurnWithOutcome()` path so provider and output failures remain retryable instead of becoming successful empty pages. Invariants: **strict per-source core** (`runExtractConversationFactsCore({sourceId, ...})` always takes one sourceId; CLI + cycle phase each do their own multi-source iteration because `PHASE_SCOPE='source'` is taxonomy-only); **bounded two-phase enumeration** (paginated `listPages({type, sourceId, limit:10})`; per-page body cap `MAX_PAGE_BODY_BYTES=25MB`); **page-global `row_num` accumulator** (the facts unique index is `(source_id, source_markdown_slug, row_num)`); **versioned snapshot-bound outcomes** (`cli:extract-conversation-facts:terminal:v2` for complete pages and a separate `non-extractable:v2` source for recognized pages with no eligible segment); **operation checkpoints are scheduling hints only** and never suppress a replay without a matching v2 outcome; **optional `opts.budgetTracker?`** is used as-is, while an absent tracker is created with `maxCostUsd`; **body reads cover compiled truth, timeline, and configured raw-transcript sidecars**; **`facts.extraction_enabled` kill-switch** with `--override-disabled`; **`--types LIST` allowlist** (`conversation,meeting,slack,email,imessage,imessage-daily`); and **`--background` via `maybeBackground`**. The companion `conversation_facts_backfill` cycle phase is default-off, iterates every source, and enforces per-source plus brain-wide cost and wall-time caps. Migration v94 provides the partial facts index used by outcome lookups. `computeConversationFactsBacklogCheck` reports fresh completed, scanned-not-extractable, and unfinished counts separately, warning when more than 10 eligible pages lack a fresh v2 outcome. `sources audit` exposes `facts_backfill_estimate: {pages, est_segments, est_cost_usd, types}`. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`.
-- `src/core/link-extraction.ts` — shared library for the graph layer. `extractEntityRefs` (canonical) matches `[Name](people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks; `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled`. `DIR_PATTERN` covers `people`, `companies`, `deals`, `topics`, `concepts`, `projects`, `entities`, `tech`, `finance`, `personal`, `openclaw`. Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. **Opt-in global-basename wikilink resolution** (issue #972, default off): `WIKILINK_GENERIC_RE` catches bare `[[name]]` wikilinks outside `DIR_PATTERN` (third pass `2c` in `extractEntityRefs`); `EntityRef.needsResolution: true` tags refs from this pass (the ref's `slug` is the wikilink TARGET, `name` the optional display alias). `SlugResolver` gains optional `resolveBasenameMatches(name): Promise<string[]>` (multi-match by design — emits one edge per matching page). The single shared basename matcher is `buildBasenameIndex(slugs)` + `queryBasenameIndex(index, name)` + `normalizeBasename` (keys raw/lower/slugified tail, stable-sorted shorter-first then lexical), used by `makeResolver`, the FS `resolveBasenameMatchesFromSlugs`, AND the doctor check so they cannot drift. `makeResolver(engine, {mode, sourceId})` builds the index lazily via `engine.getAllSlugs({sourceId})` — source-scoped so a bare `[[name]]` never resolves to a same-tail page in a different source. `extractPageLinks` gains `opts.globalBasename` (routes `needsResolution` refs through `resolveBasenameMatches` keyed on `ref.slug`, emits candidates tagged `linkType: 'wikilink_basename'` + `linkSource: 'wikilink-resolved'`, skips self-loops) and `opts.skipFrontmatter` (replaces the old `nullResolver` ternary). All three surfaces (FS extract, DB extract, `put_page` auto-link) tag provenance with `link_source='wikilink-resolved'`; `put_page` includes it in its reconcilable-edge set so stale basename edges are removed when the wikilink or the flag goes away. Exports `WIKILINK_BASENAME_LINK_TYPE` + `isGlobalBasenameEnabled(engine)` (resolution order: env `GBRAIN_LINK_RESOLUTION_GLOBAL_BASENAME` → DB config `link_resolution.global_basename` → default false). `gbrain doctor`'s `link_resolution_opportunity` check surfaces a paste-ready enable hint when ≥5 bare wikilinks would resolve AND ≥20% match. Migration v113 widens `links_link_source_check` to admit `'wikilink-resolved'`; v114 (#1941) then opens it to any kebab-case provenance (`^[a-z][a-z0-9]*(-[a-z0-9]+)*$`, ≤64 chars) so external derivers register their own tag (e.g. `citation-graph`) without a migration. `LINK_EXTRACTOR_VERSION_TS` also lives here (bump like `CHUNKER_VERSION` to invalidate prior extract-stale stamps). Pinned by `test/link-extraction.test.ts`, `test/extract-fs.test.ts`, `test/doctor.test.ts`, `test/e2e/global-basename-pglite.test.ts`.
+- `src/core/link-extraction.ts` — shared library for the graph layer. `extractEntityRefs` (canonical) matches `[Name](people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks; `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled`. #2576: markdown links, bare-slug prose refs, and slash-shaped wikilinks match ANY dir-shaped path (`ANY_DIR_SEGMENT`), not a directory whitelist — nonexistent targets are dropped by the persist paths' page-existence checks (`resolveCandidateSources`, put_page's allSlugs filter, `addLinksBatch` INNER JOINs) and counted as `skippedMissingTarget` in the extract summaries; the `DIR_PATTERN` whitelist survives only as the typed fast-path for pass-2b wikilinks (non-whitelisted `[[dir/...]]` get an equivalent direct typed candidate in pass 2c, plus the flag-gated suffix rescue for non-exact matches). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. **Opt-in global-basename wikilink resolution** (issue #972, default off): `WIKILINK_GENERIC_RE` catches bare `[[name]]` wikilinks outside `DIR_PATTERN` (third pass `2c` in `extractEntityRefs`); `EntityRef.needsResolution: true` tags refs from this pass (the ref's `slug` is the wikilink TARGET, `name` the optional display alias). `SlugResolver` gains optional `resolveBasenameMatches(name): Promise<string[]>` (multi-match by design — emits one edge per matching page). The single shared basename matcher is `buildBasenameIndex(slugs)` + `queryBasenameIndex(index, name)` + `normalizeBasename` (keys raw/lower/slugified tail, stable-sorted shorter-first then lexical), used by `makeResolver`, the FS `resolveBasenameMatchesFromSlugs`, AND the doctor check so they cannot drift. `makeResolver(engine, {mode, sourceId})` builds the index lazily via `engine.getAllSlugs({sourceId})` — source-scoped so a bare `[[name]]` never resolves to a same-tail page in a different source. `extractPageLinks` gains `opts.globalBasename` (routes `needsResolution` refs through `resolveBasenameMatches` keyed on `ref.slug`, emits candidates tagged `linkType: 'wikilink_basename'` + `linkSource: 'wikilink-resolved'`, skips self-loops) and `opts.skipFrontmatter` (replaces the old `nullResolver` ternary). All three surfaces (FS extract, DB extract, `put_page` auto-link) tag provenance with `link_source='wikilink-resolved'`; `put_page` includes it in its reconcilable-edge set so stale basename edges are removed when the wikilink or the flag goes away. Exports `WIKILINK_BASENAME_LINK_TYPE` + `isGlobalBasenameEnabled(engine)` (resolution order: env `GBRAIN_LINK_RESOLUTION_GLOBAL_BASENAME` → DB config `link_resolution.global_basename` → default false). `gbrain doctor`'s `link_resolution_opportunity` check surfaces a paste-ready enable hint when ≥5 bare wikilinks would resolve AND ≥20% match. Migration v113 widens `links_link_source_check` to admit `'wikilink-resolved'`; v114 (#1941) then opens it to any kebab-case provenance (`^[a-z][a-z0-9]*(-[a-z0-9]+)*$`, ≤64 chars) so external derivers register their own tag (e.g. `citation-graph`) without a migration. `LINK_EXTRACTOR_VERSION_TS` also lives here (bump like `CHUNKER_VERSION` to invalidate prior extract-stale stamps). Pinned by `test/link-extraction.test.ts`, `test/extract-fs.test.ts`, `test/doctor.test.ts`, `test/e2e/global-basename-pglite.test.ts`.
- `src/commands/extract.ts` — `gbrain extract links|timeline|all [--source fs|db] [--source-id <id>]`: batch link/timeline extraction. fs walks markdown files, db walks pages from the engine (mutation-immune snapshot iteration; use for live brains with no local checkout). No in-memory dedup pre-load — candidates buffered 100 at a time and flushed via `addLinksBatch` / `addTimelineEntriesBatch`; `ON CONFLICT DO NOTHING` enforces uniqueness at the DB layer, `created` counter returns real rows inserted. `ExtractOpts.slugs?: string[]` enables incremental extract via `extractForSlugs()` (single combined links+timeline pass); the cycle path threads sync's `pagesAffected` through. `walkMarkdownFiles(brainDir)` still runs to build `allSlugs` for link resolution. `--source-id <id>` scopes extraction to one source on federated brains (resolved via `resolveSourceWithTier()` before any SQL; failures hint `gbrain sources list`). `gbrain extract --stale [--source-id <id>] [--catch-up] [--dry-run] [--json]` branch (`extractStaleFromDB`) — incremental DB-source link+timeline sweep over pages whose `pages.links_extracted_at` watermark is stale. Stale predicate (shared by both engines + the doctor check): `links_extracted_at IS NULL OR links_extracted_at < LINK_EXTRACTOR_VERSION_TS::timestamptz OR updated_at > links_extracted_at` (the `updated_at` arm catches MCP `put_page` / `sync --no-extract` edited-since-extract). Three new `BrainEngine` methods (parity in postgres-engine.ts + pglite-engine.ts + bootstrap probes): `countStalePagesForExtraction(opts?)`, `listStalePagesForExtraction({batchSize, afterPageId?, sourceId?, versionTs?})` (returns page CONTENT to avoid N+1 `getPage`; `rowToStalePage` in utils.ts maps the row, `StalePageRow` in types.ts), `markPagesExtractedBatch(refs, defaultExtractedAt)` (3-array unnest `slug[],source_id[],ts[]`; each ref may carry its own `extractedAt`). `STALE_BATCH_SIZE` default 25 (`GBRAIN_EXTRACT_STALE_BATCH`; small because page bodies are unbounded — the LIMIT is the only fetch-time memory bound); `STALE_TIME_BUDGET_MS` 30min wall-clock (`--catch-up` removes the cap). Non-swallowing flush: link/timeline flush throws propagate and abort the batch; stamp LAST so a crash leaves pages unstamped and they re-extract idempotently (`addLinksBatch` ON CONFLICT DO NOTHING + timeline dedup). Race fix: `extractStaleFromDB` stamps with each row's READ `updated_at` (not `now()`), so a concurrent edit during the sweep keeps the page stale and it re-extracts next run rather than marked fresh-with-old-content. Source-correct stamping at DB-extract sites via `stampExtracted` (best-effort, never throws); `extractLinksFromDB` only stamps the combined watermark when `subcommand === 'all'` (a links-only run must not hide timeline staleness). `LINK_EXTRACTOR_VERSION_TS` lives in `src/core/link-extraction.ts` (bump like `CHUNKER_VERSION` to invalidate all prior stamps). Migration v112 (`pages_links_extracted_at`) adds nullable `TIMESTAMPTZ` + composite `(source_id, links_extracted_at)` index (CONCURRENTLY + invalid-remnant pre-drop on Postgres, plain on PGLite), NO backfill so the real backlog surfaces on first `gbrain doctor`. Schema parity in schema.sql + pglite-schema.ts + schema-embedded.ts + `REQUIRED_BOOTSTRAP_COVERAGE`. `src/commands/doctor.ts:checkLinksExtractionLag` (the `links_extraction_lag` check, also in `doctorReportRemote`) warn-only by default (>`GBRAIN_EXTRACTION_LAG_WARN_PCT`, default 20%; shared `EXTRACTION_LAG_WARN_PCT_DEFAULT` + `EXTRACTION_LAG_MIN_PAGES=100` + exported `_resolveEnvNumber`), hard-fails only when `GBRAIN_EXTRACTION_LAG_FAIL_PCT` is set; vacuous-skips <100 pages (no `--source`); pre-v112 brains graceful-skip via `isUndefinedColumnError`; strictly a SQL COUNT (safe on remote/thin-client). `src/commands/sync.ts` gains `--no-extract` (threaded through single-source + `--all` + `syncOneSource`), stamps `links_extracted_at` for `pagesAffected` at the inline-extract call site, and `maybeExtractionNudge` prints a one-line stderr nudge after a `synced | first_sync | up_to_date` sync that leaves a backlog (`shouldNudgeAfterSync` pure predicate; `GBRAIN_SYNC_NO_EXTRACT_NUDGE` suppresses). `src/core/retry.ts` adds `'extract.stale'` to `BATCH_AUDIT_SITES`; `src/core/doctor-categories.ts` adds `links_extraction_lag` to `BRAIN_CHECK_NAMES`. Pinned by `test/extract-stale.test.ts` (incl. edited-after-stamp regression + crash-contract), `test/sync-inline-extract-stamps.serial.test.ts`, `test/sync-nudge-status-gate.test.ts`, `test/doctor-links-extraction-lag.test.ts`, engine-parity (Postgres↔PGLite) for the 3 methods + v112 round-trip. The stale SELECT in both engines projects a deterministic full-µs UTC string `to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_iso` (carried on `StalePageRow.updated_at_iso`, populated by `rowToStalePage` in utils.ts with an ISO-only fallback — never `String(Date)`, which `::timestamptz` misparses); `extractStaleFromDB` stamps that exact-precision value, not a JS `Date` (which truncates to milliseconds), so on Postgres `links_extracted_at` equals the row's `updated_at` to the microsecond and `links_extraction_lag` clears — a ms-truncated stamp stays strictly below the µs `updated_at` and leaves every page perpetually stale, which `extract --stale` could never satisfy. `to_char` (not raw `::text`, which is `DateStyle`-fragile) keeps the projection deterministic. The `markPagesExtractedBatch` SQL is unchanged, so callers passing an explicit (e.g. backdated) `extractedAt` still control the stamp and the edited-since arm is exact. A deterministic PGLite regression in `test/extract-stale.test.ts` injects a µs `updated_at`, runs `--stale`, and asserts the lag is 0 and stays 0.
- `src/core/extract/receipt-writer.ts` + `src/core/extract/rollup-writer.ts` + `src/commands/extract-status.ts` + `src/commands/extract-explain.ts` + `src/commands/extract-benchmark.ts` + `src/core/schema-pack/scaffold-extractable.ts` — unified extract operator surface. Every shipped extractor (deterministic `facts.conversation` in `src/commands/extract-conversation-facts.ts` + three LLM-backed cycle phases at `src/core/cycle/{extract-atoms,synthesize-concepts,propose-takes,extract-facts}.ts`) writes ONE receipt page per run (`writeReceipt`) + UPSERTs a row to `extract_rollup_7d` (`upsertExtractRollup`). Receipt slug `extracts/{date}/{kind}/{source_id}/{run_id_short}/round-{N}.md`; frontmatter stamps BOTH `type: extract_receipt` AND `dream_generated: true` (belt+suspenders against extraction-loop guard drift). `extract_receipt` joins `ALL_PAGE_TYPES` in `src/core/types.ts`; `extracts/` prefix gets a 0.3x source-boost demote in `src/core/search/source-boost.ts`. Migration v104 adds `extract_rollup_7d (kind, source_id, day, cost_usd, halt_count, eval_pass_count, eval_fail_count, round_completed_count, rollup_write_failures, updated_at)` with PK `(kind, source_id, day)` + `idx_extract_rollup_7d_day`. Rollup writes best-effort with process-scoped error-dedup so transient DB failures bump `rollup_write_failures` instead of crashing the cycle. `extract_health` doctor check reads last 7 days, warns at halt-rate > 10% AND when rollup_write_failures > 0; pre-v104 brains report `ok`. CLI: `gbrain extract status [--source-id ID] [--kind X] [--verbose] [--json]` (7-day rollup, sorted halt_rate desc + cost desc, top-5 + "more rows" hint, stable `schema_version: 1`); `gbrain extract --explain <kind>` (resolution chain pack-declared vs built-in cycle phase, prompt_template + fixture_corpus paths with `✓`/`(missing)`, last 7d rollup); `gbrain extract benchmark --pack X --kind Y` (loads pack fixture corpus through strict path validation — rejects absolute paths, `..` traversal, null bytes, AND symlinks resolving outside pack root; ships as a stub-reporter). `src/core/schema-pack/manifest-v1.ts` widens `extractable` from `z.boolean()` to `z.union([z.boolean(), ExtractableSpecSchema])` (carries `prompt_template`, `fixture_corpus`, `eval_dimensions`, `benchmark_min_recall`, plus reserved `verifier_path` — parses but refuses at runtime); `extractableSpecsFromPack` + `getExtractableSpec` + `refuseVerifierPathInV042` in `src/core/schema-pack/extractable.ts`; `gbrain schema scaffold-extractable <type> --pack <pack>` declares the type extractable, generates 5 placeholder fixtures + a prompt template stub under `packs/<pack>/{fixtures,prompts}/extract/`, refuses to overwrite without `--force`. Pinned by `test/extractable-spec-widening.test.ts` (22), `test/extract/receipt-writer.test.ts` (12, canonical PGLite block R3+R4), `test/extract/benchmark.test.ts` (17), `test/extract/status.test.ts` (15), `test/schema-pack/scaffold-extractable.test.ts` (15, privacy guards), `test/doctor-extract-health.test.ts` (8).
- `src/commands/import.ts` — `gbrain import <path> [--source-id <id>]`: page import with the path-set checkpoint. `--source-id <id>` routes pages to the named source (resolved via `resolveSourceWithTier()` at the boundary; consistent across `import`, `extract`, `graph-query`, `sources current`). Pinned by `test/import-source-id.test.ts`.
@@ -231,7 +231,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this
- `src/commands/doctor.ts` extension — three checks wired into `runDoctor()` and the JSON envelope: `oversized_pages` (warns on pages exceeding `content_sanity.bytes_warn`), `scraper_junk_pages` (warns on live DB pages matching any junk pattern that escaped ingest), and `content_sanity_audit_recent` (reads the last 7 days of audit events, aggregates by pattern+source). Default scans the 1000 most-recent pages; `--content-audit` opts into a full scan. All three warn-only with paste-ready fix hints (junk → `gbrain sources audit <id>` + `git rm` source-of-truth, oversize → split or accept).
- `src/commands/lint.ts` extension — lint rules `huge-page` (flags pages exceeding `content_sanity.bytes_warn`) and `scraper-junk` (flags pages matching any junk pattern). Both reuse `assessContent()` from `src/core/content-sanity.ts` so lint, doctor, and ingest share one assessor. `lint.ts` lifts DB config when `~/.gbrain/` is reachable; falls back to file/env on CI. Pinned by `test/lint-content-sanity.test.ts`.
- `src/commands/embed.ts` extension — applies the `embed-skip` filter at all 5 stale-chunk sites: `runEmbedCore --stale`, `runEmbedCore --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks` via `EMBED_SKIP_SQL_FRAGMENT`. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper from `src/core/embed-skip.ts` is the regression guard — no per-site ad-hoc filter allowed. Pinned by `test/embed-skip.test.ts`.
-- `src/core/import-file.ts` extension — `importFromContent` is the narrow waist every ingest path passes through (`gbrain import`, `gbrain sync`, `put_page` MCP, `/ingest` webhook). It runs a three-tier content-quality disposition via `assessContentSanity` from `src/core/content-sanity.ts` BEFORE chunking: (1) high-confidence junk (built-in Cloudflare/CAPTCHA interstitial patterns + operator literals) → QUARANTINE (stamps the `quarantine` frontmatter marker, writes ZERO chunks, hides the page from search) OR REJECT (throw → sync-failure) when `content_sanity.junk_disposition` is `reject`; (2) fuzzy markup-heavy (prose-vs-markup ratio above `content_sanity.max_markup_ratio`, warn-tier byte window, code pages exempt) → `content_flag:markup_heavy` marker (page stays fully searchable, marker rides search results + get_page to warn the agent); (3) oversize → `embed_skip` soft-block via `buildEmbedSkipMarker()` PLUS a `content_flag:oversized` marker, AND deletes any pre-existing chunks in the same transaction so search can't surface stale chunks. Gate-owned markers (`quarantine`, `content_flag`) are STRIPPED from untrusted (remote MCP, `ctx.remote !== false`) frontmatter so a write-scoped client can't hide pages or forge the warning channel; markers are excluded from `content_hash` so a flagged page doesn't re-embed every sync. `gbrain import` honors `errors > 0` for non-zero exit. `classifyErrorCode` in `src/core/sync.ts` recognizes the `PAGE_JUNK_PATTERN` code so sync-failures.jsonl grouping bins these. `extractEntityRefs` (canonical; matches both `[Name](people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks), `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled` config helper. `DIR_PATTERN` covers `people`, `companies`, `deals`, `topics`, `concepts`, `projects`, `entities`, `tech`, `finance`, `personal`, `openclaw`. Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. Pinned by `test/import-file-content-sanity.test.ts`.
+- `src/core/import-file.ts` extension — `importFromContent` is the narrow waist every ingest path passes through (`gbrain import`, `gbrain sync`, `put_page` MCP, `/ingest` webhook). It runs a three-tier content-quality disposition via `assessContentSanity` from `src/core/content-sanity.ts` BEFORE chunking: (1) high-confidence junk (built-in Cloudflare/CAPTCHA interstitial patterns + operator literals) → QUARANTINE (stamps the `quarantine` frontmatter marker, writes ZERO chunks, hides the page from search) OR REJECT (throw → sync-failure) when `content_sanity.junk_disposition` is `reject`; (2) fuzzy markup-heavy (prose-vs-markup ratio above `content_sanity.max_markup_ratio`, warn-tier byte window, code pages exempt) → `content_flag:markup_heavy` marker (page stays fully searchable, marker rides search results + get_page to warn the agent); (3) oversize → `embed_skip` soft-block via `buildEmbedSkipMarker()` PLUS a `content_flag:oversized` marker, AND deletes any pre-existing chunks in the same transaction so search can't surface stale chunks. Gate-owned markers (`quarantine`, `content_flag`) are STRIPPED from untrusted (remote MCP, `ctx.remote !== false`) frontmatter so a write-scoped client can't hide pages or forge the warning channel; markers are excluded from `content_hash` so a flagged page doesn't re-embed every sync. `gbrain import` honors `errors > 0` for non-zero exit. `classifyErrorCode` in `src/core/sync.ts` recognizes the `PAGE_JUNK_PATTERN` code so sync-failures.jsonl grouping bins these. `extractEntityRefs` (canonical; matches both `[Name](people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks), `extractPageLinks`, `inferLinkType` heuristics (attended/works_at/invested_in/founded/advises/source/mentions), `parseTimelineEntries`, `isAutoLinkEnabled` config helper. Link candidates match any dir-shaped path (#2576; existence-checked at persist). Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts. Pinned by `test/import-file-content-sanity.test.ts`.
- `src/core/quarantine.ts` — the two frontmatter markers the content-quality gate writes, sibling of `src/core/embed-skip.ts` (same marker-as-JSONB-object pattern, same JSONB `?` existence check that works on Postgres AND PGLite; no schema migration — both are frontmatter JSONB keys). `quarantine` (key `QUARANTINE_KEY`) HIDES: set ONLY for high-confidence junk, writes zero chunks, excluded from search via `quarantineFilterFragment(pageAlias)` / `QUARANTINE_FILTER_FRAGMENT` (the `p`-aliased constant), the single source of truth `buildVisibilityClause` calls so the search filter and marker key can't drift. `content_flag` (key `CONTENT_FLAG_KEY`) WARNS, does NOT hide: set for fuzzy markup-heavy / oversize, page stays searchable, marker is READ INTO search/get_page output — deliberately NO SQL filter fragment. Three distinct markers, three reasons (never overloaded): `embed_skip` = oversized-but-clean, `quarantine` = junk hidden, `content_flag` = odd-examine-still-here; a page can carry more than one (oversize → embed_skip + content_flag:oversized) and each clears independently. Exports `buildQuarantineMarker` / `isQuarantined` / `filterOutQuarantined`, `buildContentFlagMarker` / `getContentFlag` / `hasContentFlag`, plus the two key constants. Pinned by `test/quarantine.test.ts`.
- `src/core/content-sanity.ts` extension — new `assessContentSanity(opts): SanityAssessment` returns the three-tier disposition (`shouldQuarantine` / `shouldFlag` + reason/detail) consumed by `importFromContent` and `gbrain quarantine scan`. Adds the fuzzy prose-vs-markup ratio pass (markup chars / total chars above `max_markup_ratio`, default 0.85; code pages exempt; gated by `prose_check_enabled`, default true) on top of the byte + junk-pattern passes. Three config knobs: `content_sanity.junk_disposition` (`quarantine` default | `reject`; no env override), `content_sanity.max_markup_ratio` (0.85, env `GBRAIN_MAX_MARKUP_RATIO`, clamped `(0,1]`), `content_sanity.prose_check_enabled` (true). Same env > file > DB > defaults resolution chain. Pinned by `test/content-sanity.test.ts`.
- `src/commands/quarantine.ts` — `gbrain quarantine <list|clear|scan>` operator surface for the content-quality gate. `list [--json] [--include-flagged]` paginates `listPages` and reports quarantined (HIDDEN) pages, optionally also `content_flag` (FLAGGED, searchable) pages. `clear <slug> [--force] [--no-embed] [--json]` drops both markers and re-imports through the normal pipeline so the page re-chunks + re-embeds and becomes searchable; the gate re-runs on import so genuinely-junk pages re-quarantine (exit 1) unless `--force` sets `GBRAIN_NO_SANITY=1` for that one import. `scan [--limit N] [--apply] [--no-embed] [--json]` re-assesses already-ingested pages so junk predating the gate gets marked (unchanged content short-circuits normal sync, so it never re-assesses otherwise); dry-run uses the SAME effective `content_sanity` config thresholds `--apply` will use, idempotent (skips already-marked pages), `--apply` re-imports with `forceRechunk` to set markers + (for quarantine) drop chunks. Dispatched in `cli.ts`. Pinned by `test/quarantine-cli.test.ts`.
diff --git a/docs/designs/COMMUNITY_IDEAS.md b/docs/designs/COMMUNITY_IDEAS.md
index d881b028f2..d8375f4aa9 100644
--- a/docs/designs/COMMUNITY_IDEAS.md
+++ b/docs/designs/COMMUNITY_IDEAS.md
@@ -154,10 +154,11 @@ these are the densest source of real bugs in the whole backlog.
`aliases:`), first-H1-title, and basename fallback resolution (path-equality-only gives
~5.5% edge recall on real vaults). Master shipped global-basename (#1388); the alias/
title fallbacks are the still-novel part.
-- **Schema-pack-aware link extraction** (#1547, @billy-armstrong) — **OPEN, high.** The
- link extractor's `DIR_PATTERN` is a frozen 16-prefix const that ignores pack-declared
- `path_prefixes`, so default-pack installs silently lose wikilinks to `person/`,
- `writing/`, `wiki/*`. Resolve prefixes from the active pack.
+- **Schema-pack-aware link extraction** (#1547, @billy-armstrong) — **RESOLVED via #2576.**
+ The extractor no longer gates on the frozen `DIR_PATTERN` whitelist: any dir-shaped
+ path produces a candidate and the persist paths' page-existence checks decide, so
+ pack-declared directories (`person/`, `writing/`, `wiki/*`, `ops/`) link without a
+ prefix registry.
- **DB-source extraction** (#1539, @afshaker) — **OPEN, high.** The cycle's extract phase
only walks the filesystem, so DB-resident pages (imported transcripts, remote-DB brains)
never get links/timeline and `brain_score` is capped. Thread `source:'db'`.
diff --git a/src/commands/extract.ts b/src/commands/extract.ts
index a67449e34a..f9f00ef481 100644
--- a/src/commands/extract.ts
+++ b/src/commands/extract.ts
@@ -1458,6 +1458,8 @@ async function extractLinksFromDB(
slugToSources.set(ref.slug, list);
}
let processed = 0, created = 0;
+ // #2576: skipped-candidate counter — see extractStaleFromDB's twin.
+ let skippedMissingTarget = 0;
// v0.42.7 (#1696): pages whose links we extracted this run — stamped after
// the loop so a manual `gbrain extract links|all --source db` clears the
// links_extraction_lag doctor signal. Non-dry-run only.
@@ -1514,7 +1516,7 @@ async function extractLinksFromDB(
// endpoint-validation + from/to source-id picking (null = skip: missing
// endpoint OR target only in a non-origin/non-default source).
const resolved = resolveCandidateSources(c, slug, source_id, allSlugs, slugToSources);
- if (!resolved) continue;
+ if (!resolved) { skippedMissingTarget++; continue; }
const { fromSlug, fromSourceId, toSourceId } = resolved;
if (dryRunSeen) {
@@ -1571,6 +1573,9 @@ async function extractLinksFromDB(
if (!jsonMode) {
const label = dryRun ? '(dry run) would create' : 'created';
console.log(`Links: ${label} ${created} from ${processed} pages (db source)`);
+ if (skippedMissingTarget > 0) {
+ console.log(`Skipped ${skippedMissingTarget} candidate(s) whose target page doesn't exist (references to non-pages are never persisted).`);
+ }
if (includeFrontmatter && unresolved.length > 0) {
// Top-20 preview of unresolvable frontmatter names so the user can
// see where the graph has holes (codex tension 6.4).
@@ -1716,7 +1721,7 @@ export async function extractStaleFromDB(
sourceIdFilter?: string;
catchUp: boolean;
},
-): Promise<{ linksCreated: number; timelineCreated: number; pagesProcessed: number; staleRemaining: number }> {
+): Promise<{ linksCreated: number; timelineCreated: number; pagesProcessed: number; staleRemaining: number; skippedMissingTarget?: number }> {
const { dryRun, jsonMode, includeFrontmatter, sourceIdFilter, catchUp } = opts;
const versionTs = LINK_EXTRACTOR_VERSION_TS;
@@ -1768,6 +1773,10 @@ export async function extractStaleFromDB(
let afterPageId = 0;
let linksCreated = 0, timelineCreated = 0, pagesProcessed = 0;
let budgetHit = false;
+ // #2576: candidates whose endpoint pages don't exist are skipped, not
+ // persisted. Counted so a dropped reference is observable in the summary
+ // instead of vanishing silently (the failure mode that hid bug 2).
+ let skippedMissingTarget = 0;
for (;;) {
const rows = await engine.listStalePagesForExtraction({
@@ -1787,7 +1796,7 @@ export async function extractStaleFromDB(
);
for (const c of extracted.candidates) {
const r = resolveCandidateSources(c, page.slug, page.source_id, allSlugs, slugToSources);
- if (!r) continue;
+ if (!r) { skippedMissingTarget++; continue; }
linkRows.push({
from_slug: r.fromSlug, to_slug: c.targetSlug, link_type: c.linkType,
context: c.context, link_source: c.linkSource, origin_slug: c.originSlug,
@@ -1848,6 +1857,9 @@ export async function extractStaleFromDB(
if (!jsonMode) {
console.log(`Extract --stale: ${linksCreated} link(s) + ${timelineCreated} timeline entr(ies) from ${pagesProcessed} page(s).`);
+ if (skippedMissingTarget > 0) {
+ console.log(`Skipped ${skippedMissingTarget} candidate(s) whose target page doesn't exist (references to non-pages are never persisted).`);
+ }
if (budgetHit && staleRemaining > 0) {
console.log(`Time budget reached — ${staleRemaining} page(s) still stale. Re-run 'gbrain extract --stale' (or pass --catch-up) to continue.`);
}
@@ -1855,9 +1867,10 @@ export async function extractStaleFromDB(
process.stdout.write(JSON.stringify({
action: 'extract_stale_done', links_created: linksCreated, timeline_created: timelineCreated,
pages_processed: pagesProcessed, stale_remaining: staleRemaining, budget_hit: budgetHit,
+ skipped_missing_target: skippedMissingTarget,
}) + '\n');
}
- return { linksCreated, timelineCreated, pagesProcessed, staleRemaining };
+ return { linksCreated, timelineCreated, pagesProcessed, staleRemaining, skippedMissingTarget };
}
/**
diff --git a/src/core/link-extraction.ts b/src/core/link-extraction.ts
index 9e87f3da60..a1f6377fbd 100644
--- a/src/core/link-extraction.ts
+++ b/src/core/link-extraction.ts
@@ -28,11 +28,13 @@ import { ensureWellFormed } from './text-safe.ts';
* OR updated_at > links_extracted_at`. It is an ISO-8601 string (NOT a number) —
* the column is TIMESTAMPTZ and the predicate binds it as `::timestamptz`.
*/
-// 2026-07-30: bumped for the #3466 inferTypeByDir fix — unevidenced
-// people/ -> companies/ adjacency now infers 'mentions' instead of
-// 'works_at'; the bump re-flags stamped pages so the next --stale sweep
-// re-extracts them under the corrected inference.
-export const LINK_EXTRACTOR_VERSION_TS = '2026-07-30T00:00:00Z';
+// 2026-08-01: bumped for the fix-wave-i extraction batch — the #3466
+// inferTypeByDir fix (unevidenced people/ -> companies/ adjacency now infers
+// 'mentions' instead of 'works_at') AND the #2576 bug-2 fix (the DIR_PATTERN
+// whitelist no longer drops markdown links / bare-slug refs / slash-shaped
+// wikilinks in non-whitelisted directories). Pages stamped by earlier sweeps
+// are re-flagged so the next --stale sweep re-extracts under both fixes.
+export const LINK_EXTRACTOR_VERSION_TS = '2026-08-01T00:00:00Z';
// ─── Entity references ──────────────────────────────────────────
@@ -81,16 +83,30 @@ export const WIKILINK_BASENAME_LINK_TYPE = 'wikilink_basename';
export type LinkResolutionType = 'qualified' | 'unqualified';
/**
- * Directory prefix whitelist. These are the top-level slug dirs the extractor
- * recognizes as entity references. Upstream canonical + our extensions:
- * - Gbrain canonical: people, companies, meetings, concepts, deal, civic, project, source, media, yc, projects, reference
- * - Our domain extensions: tech, finance, personal, openclaw (domain-organized wikis)
- * - Our entity prefix: entities (we kept some legacy entities/projects/ pages)
+ * Directory prefix whitelist. These are the canonical top-level slug dirs
+ * (gbrain-base pack dirs + historical extensions). #2576 (bug 2): this list
+ * is NO LONGER a drop-gate for markdown links, bare-slug prose refs, or
+ * slash-shaped wikilinks — those now match ANY_DIR_SEGMENT and rely on the
+ * downstream page-existence checks that every persist path already runs
+ * (resolveCandidateSources in extract.ts, the allSlugs filter in put_page
+ * auto-link, and addLinksBatch's INNER JOINs as the final backstop). The
+ * whitelist survives only as the typed fast-path for pass-2b wikilinks;
+ * non-whitelisted `[[dir/...]]` get equivalent treatment in pass 2c.
*/
const DIR_PATTERN = '(?:people|companies|meetings|concepts|deal|civic|project|projects|source|media|yc|tech|finance|personal|openclaw|entities|reference)';
/**
- * Match `[Name](path)` markdown links pointing to entity directories.
+ * #2576 (bug 2): a plausible top-level slug directory — lowercase alnum
+ * with dashes/underscores, digit-leading allowed (`90-people`). Used where
+ * the hardcoded DIR_PATTERN whitelist used to silently drop every
+ * user-invented directory (`ops/`, `notes/`, custom schema-pack dirs).
+ * Candidates matched through this are validated for page existence
+ * downstream, so a wider net creates no dead edges — only candidates.
+ */
+const ANY_DIR_SEGMENT = '[a-z0-9][a-z0-9_-]*';
+
+/**
+ * Match `[Name](path)` markdown links pointing at page-shaped paths.
* Accepts both filesystem-relative format (`[Name](../people/slug.md)`)
* AND engine-slug format (`[Name](people/slug)`).
*
@@ -98,9 +114,14 @@ const DIR_PATTERN = '(?:people|companies|meetings|concepts|deal|civic|project|pr
*
* The regex permits an optional `../` prefix (any number) and an optional
* `.md` suffix so the same function works for both filesystem and DB content.
+ *
+ * #2576 (bug 2): the first segment is ANY_DIR_SEGMENT, not the DIR_PATTERN
+ * whitelist — `[Pointer](../ops/services/pointer-agent.md)` must produce a
+ * candidate for a brain that has an `ops/` directory. Nonexistent targets
+ * are dropped by the callers' existence checks, exactly as before.
*/
const ENTITY_REF_RE = new RegExp(
- `\\[([^\\]]+)\\]\\((?:\\.\\.\\/)*(${DIR_PATTERN}\\/[^)\\s]+?)(?:\\.md)?\\)`,
+ `\\[([^\\]]+)\\]\\((?:\\.\\.\\/)*(${ANY_DIR_SEGMENT}\\/[^)\\s]+?)(?:\\.md)?\\)`,
'g',
);
@@ -486,6 +507,26 @@ export async function extractPageLinks(
// pre-v0.40.8.2 behavior of dropping bare wikilinks outside
// DIR_PATTERN.
if (ref.needsResolution) {
+ const slashIdx = ref.slug.lastIndexOf('/');
+ // #2576 (bug 2): a slash-shaped wikilink outside DIR_PATTERN
+ // (`[[ops/services/pointer-agent]]`) gets the SAME treatment a
+ // whitelisted dir gets from pass 2b — a direct, verb-typed candidate
+ // for the literal path, emitted regardless of the global_basename
+ // flag. Downstream existence checks (resolveCandidateSources /
+ // put_page's allSlugs filter / addLinksBatch's INNER JOINs) drop it
+ // when no such page exists, exactly as they do for 2b candidates.
+ // Pre-fix these refs were silently dropped (flag off) or demoted to
+ // untyped wikilink_basename edges (flag on).
+ if (slashIdx !== -1 && ref.slug !== slug) {
+ const litIdx = content.indexOf(ref.slug);
+ const litContext = litIdx >= 0 ? excerpt(content, litIdx, 240) : ref.name;
+ candidates.push({
+ targetSlug: ref.slug,
+ linkType: inferLinkType(pageType, litContext, content, ref.slug),
+ context: litContext,
+ linkSource: 'markdown',
+ });
+ }
if (!opts.globalBasename || typeof resolver.resolveBasenameMatches !== 'function') {
continue;
}
@@ -503,11 +544,12 @@ export async function extractPageLinks(
// (the analogue of the FS ancestor walk honoring the written path):
// a match must end with the literal, so `[[notes/struktura]]` can
// resolve to `vault/notes/struktura` but never to `wiki/struktura`.
- const slashIdx = ref.slug.lastIndexOf('/');
+ // The EXACT literal is excluded here — the direct typed candidate
+ // above already covers it (#2576), so keeping it would double-emit.
const basename = slashIdx === -1 ? ref.slug : ref.slug.slice(slashIdx + 1);
let matches = await resolver.resolveBasenameMatches(basename);
if (slashIdx !== -1) {
- matches = matches.filter(m => m === ref.slug || m.endsWith(`/${ref.slug}`));
+ matches = matches.filter(m => m !== ref.slug && m.endsWith(`/${ref.slug}`));
}
if (matches.length === 0) continue;
const idx = content.indexOf(ref.slug);
@@ -540,11 +582,14 @@ export async function extractPageLinks(
}
// 2. Bare slug references (e.g. "see people/alice-chen for context").
- // Limited to the same entity directories ENTITY_REF_RE covers.
+ // #2576 (bug 2): any dir-shaped path, not just the DIR_PATTERN whitelist —
+ // `see ops/services/pointer-agent` must produce a candidate. Prose noise
+ // that happens to look like a path (`on/off`, `com/foo/bar` inside a URL)
+ // is dropped by the callers' page-existence checks, never persisted.
// Code blocks are stripped first — slugs in code samples are not real refs.
const strippedContent = stripCodeBlocks(content);
const bareRe = new RegExp(
- `\\b(${DIR_PATTERN}\\/[a-z0-9][a-z0-9/-]*[a-z0-9])\\b`,
+ `\\b(${ANY_DIR_SEGMENT}\\/[a-z0-9][a-z0-9/-]*[a-z0-9])\\b`,
'g',
);
let m: RegExpExecArray | null;
@@ -552,6 +597,8 @@ export async function extractPageLinks(
// Skip matches that are part of a markdown link (already handled above).
const charBefore = m.index > 0 ? strippedContent[m.index - 1] : '';
if (charBefore === '/' || charBefore === '(') continue;
+ // #2576: never emit a self-loop for a page mentioning its own slug.
+ if (m[1] === slug) continue;
const context = excerpt(strippedContent, m.index, 240);
candidates.push({
targetSlug: m[1],
diff --git a/test/e2e/global-basename-pglite.test.ts b/test/e2e/global-basename-pglite.test.ts
index 3c5af045b1..1fa62f04e4 100644
--- a/test/e2e/global-basename-pglite.test.ts
+++ b/test/e2e/global-basename-pglite.test.ts
@@ -194,8 +194,11 @@ describe('issue #972 — DB-source (gbrain extract links --source db)', () => {
const outLinks = await engine.getLinks('concepts/knowledge-graph');
const strk = outLinks.find(l => l.to_slug === 'notes/struktura');
expect(strk).toBeDefined();
- expect(strk!.link_type).toBe('wikilink_basename');
- expect(strk!.link_source).toBe('wikilink-resolved');
+ // #2576: an exact-path wikilink to an existing page now produces the
+ // direct verb-typed edge (parity with whitelisted dirs), no longer a
+ // wikilink_basename demotion.
+ expect(strk!.link_type).toBe('mentions');
+ expect(strk!.link_source).toBe('markdown');
});
test('path-qualified wikilink never attaches to a basename-only sibling', async () => {
@@ -219,10 +222,11 @@ describe('issue #972 — DB-source (gbrain extract links --source db)', () => {
await runExtract(engine, ['links', '--source', 'db']);
const outLinks = await engine.getLinks('concepts/x');
- const basenameLinks = outLinks
- .filter(l => l.link_type === 'wikilink_basename')
- .map(l => l.to_slug);
- expect(basenameLinks).toEqual(['notes/struktura']);
+ // #2576: the exact-path edge is now direct + verb-typed. The invariant
+ // under test is unchanged: the written path binds to notes/struktura and
+ // NEVER to the basename-only sibling wiki/struktura.
+ expect(outLinks.map(l => l.to_slug)).toContain('notes/struktura');
+ expect(outLinks.map(l => l.to_slug)).not.toContain('wiki/struktura');
});
test('flag OFF → no basename edges via DB path (back-compat)', async () => {
diff --git a/test/link-extraction-dir-whitelist-2576.test.ts b/test/link-extraction-dir-whitelist-2576.test.ts
new file mode 100644
index 0000000000..37567a1d89
--- /dev/null
+++ b/test/link-extraction-dir-whitelist-2576.test.ts
@@ -0,0 +1,139 @@
+/**
+ * #2576 (bug 2) — link extraction must not silently drop edges for
+ * non-whitelisted directories.
+ *
+ * The hardcoded DIR_PATTERN whitelist gated three reference shapes on the
+ * DB-source path (extractPageLinks): markdown links, bare-slug prose refs,
+ * and (via the pass-2c flag gate) slash-shaped wikilinks. A brain with an
+ * `ops/` directory (or any user-invented dir a custom schema pack declares)
+ * had 5 of 6 reference shapes DROPPED with no counter — while identical
+ * `people/` references resolved in all 6.
+ *
+ * Post-fix, extraction emits candidates for ANY dir-shaped path and relies
+ * on the page-existence checks every persist path already runs
+ * (resolveCandidateSources in extract.ts, put_page's allSlugs filter,
+ * addLinksBatch's INNER JOINs). These tests exercise the pure extraction
+ * core the DB paths (`extract --stale`, `extract links --source db`,
+ * put_page auto-link) all share — every "ops" case below FAILS on master.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import {
+ extractPageLinks,
+ extractEntityRefs,
+ LINK_EXTRACTOR_VERSION_TS,
+ type SlugResolver,
+} from '../src/core/link-extraction.ts';
+
+const nullResolver: SlugResolver = { resolve: async () => null };
+
+/** Resolver backed by a fixed slug set, tail-keyed like makeResolver's index. */
+function setResolver(slugs: string[]): SlugResolver {
+ return {
+ resolve: async () => null,
+ resolveBasenameMatches: async (name: string) =>
+ slugs.filter(s => s.slice(s.lastIndexOf('/') + 1) === name),
+ };
+}
+
+describe('#2576 bug 2 — non-whitelisted dirs produce candidates (ops/ = people/ parity)', () => {
+ test('markdown link into ops/ produces a typed candidate (was: dropped)', async () => {
+ const { candidates } = await extractPageLinks(
+ 'notes/index', '[Pointer](../ops/services/pointer-agent.md) runs the fleet.',
+ {}, 'concept', nullResolver, { skipFrontmatter: true },
+ );
+ const c = candidates.find(x => x.targetSlug === 'ops/services/pointer-agent');
+ expect(c).toBeDefined();
+ expect(c!.linkSource).toBe('markdown');
+ expect(c!.linkType).toBe('mentions');
+ });
+
+ test('bare-slug prose ref into ops/ produces a candidate (was: dropped)', async () => {
+ const { candidates } = await extractPageLinks(
+ 'notes/index', 'see ops/services/pointer-agent for details.',
+ {}, 'concept', nullResolver, { skipFrontmatter: true },
+ );
+ expect(candidates.map(c => c.targetSlug)).toContain('ops/services/pointer-agent');
+ });
+
+ test('[[ops/...]] wikilink with global_basename OFF produces a typed candidate (was: dropped)', async () => {
+ const { candidates } = await extractPageLinks(
+ 'notes/index', '[[ops/services/pointer-agent]] runs the fleet.',
+ {}, 'concept', nullResolver, { skipFrontmatter: true },
+ );
+ const c = candidates.find(x => x.targetSlug === 'ops/services/pointer-agent');
+ expect(c).toBeDefined();
+ expect(c!.linkSource).toBe('markdown');
+ });
+
+ test('[[ops/...]] with global_basename ON yields ONE typed candidate, not a wikilink_basename demotion', async () => {
+ const resolver = setResolver(['ops/services/pointer-agent']);
+ const { candidates } = await extractPageLinks(
+ 'notes/index', '[[ops/services/pointer-agent]] runs the fleet.',
+ {}, 'concept', resolver, { skipFrontmatter: true, globalBasename: true },
+ );
+ const hits = candidates.filter(c => c.targetSlug === 'ops/services/pointer-agent');
+ expect(hits).toHaveLength(1);
+ expect(hits[0].linkType).toBe('mentions'); // typed, like people/
+ expect(hits[0].linkSource).toBe('markdown'); // NOT 'wikilink-resolved'
+ });
+
+ test('verb inference works for non-whitelisted dirs (typed edge, not just mentions)', async () => {
+ const { candidates } = await extractPageLinks(
+ 'people/carol', 'Carol founded [Widget Co](../startups/widget-co.md) in 2024.',
+ {}, 'person', nullResolver, { skipFrontmatter: true },
+ );
+ const c = candidates.find(x => x.targetSlug === 'startups/widget-co');
+ expect(c).toBeDefined();
+ expect(c!.linkType).toBe('founded');
+ });
+
+ test('extractEntityRefs surfaces non-whitelisted markdown refs', () => {
+ const refs = extractEntityRefs('[Pointer](ops/services/pointer-agent)');
+ expect(refs.map(r => r.slug)).toContain('ops/services/pointer-agent');
+ });
+
+ // ── regression pins: what must NOT change ─────────────────────────────
+
+ test('suffix rescue is preserved: [[notes/struktura]] still finds vault/notes/struktura (flag ON)', async () => {
+ const resolver = setResolver(['vault/notes/struktura', 'wiki/struktura']);
+ const { candidates } = await extractPageLinks(
+ 'concepts/x', 'See [[notes/struktura]].',
+ {}, 'concept', resolver, { skipFrontmatter: true, globalBasename: true },
+ );
+ const rescue = candidates.find(c => c.targetSlug === 'vault/notes/struktura');
+ expect(rescue).toBeDefined();
+ expect(rescue!.linkType).toBe('wikilink_basename');
+ // wiki/struktura does not end with the written path — still excluded.
+ expect(candidates.map(c => c.targetSlug)).not.toContain('wiki/struktura');
+ });
+
+ test('slash-shaped self-link is never emitted', async () => {
+ const { candidates } = await extractPageLinks(
+ 'ops/runbook', 'See [[ops/runbook]] for the checklist.',
+ {}, 'concept', nullResolver, { skipFrontmatter: true },
+ );
+ expect(candidates).toEqual([]);
+ });
+
+ test('bare [[name]] wikilinks (no slash) keep the flag-gated behavior', async () => {
+ const resolver = setResolver(['projects/struktura']);
+ const off = await extractPageLinks(
+ 'concepts/x', 'This relates to [[struktura]].',
+ {}, 'concept', resolver, { skipFrontmatter: true },
+ );
+ expect(off.candidates).toEqual([]);
+ const on = await extractPageLinks(
+ 'concepts/x', 'This relates to [[struktura]].',
+ {}, 'concept', resolver, { skipFrontmatter: true, globalBasename: true },
+ );
+ expect(on.candidates.map(c => c.targetSlug)).toEqual(['projects/struktura']);
+ expect(on.candidates[0].linkType).toBe('wikilink_basename');
+ });
+
+ test('LINK_EXTRACTOR_VERSION_TS was bumped so stamped pages re-extract', () => {
+ // Pages stamped by pre-fix sweeps had their non-whitelisted-dir edges
+ // silently dropped; the watermark bump re-flags them as stale.
+ expect(LINK_EXTRACTOR_VERSION_TS > '2026-07-10T00:00:00Z').toBe(true);
+ });
+});
diff --git a/test/link-extraction.test.ts b/test/link-extraction.test.ts
index 30e1a2bf3e..e3b3d1db70 100644
--- a/test/link-extraction.test.ts
+++ b/test/link-extraction.test.ts
@@ -100,10 +100,14 @@ describe('extractEntityRefs', () => {
expect(extractEntityRefs('[Alice(people/alice)')).toEqual([]);
});
- test('skips non-entity dirs (notes/, ideas/ stay if added later but are accepted now)', () => {
- // Current regex targets entity dirs explicitly. Notes/ shouldn't match.
+ test('#2576: non-whitelisted dirs (notes/, ops/) ARE extracted as candidates', () => {
+ // Pre-#2576 the DIR_PATTERN whitelist silently dropped these. Now any
+ // dir-shaped path is a candidate; page-existence checks downstream
+ // (resolveCandidateSources / put_page allSlugs / addLinksBatch JOIN)
+ // decide whether an edge is persisted.
const refs = extractEntityRefs('See [random](notes/random).');
- expect(refs).toEqual([]);
+ expect(refs.map(r => r.slug)).toEqual(['notes/random']);
+ expect(refs[0].dir).toBe('notes');
});
test('extracts meeting refs', () => {
@@ -484,8 +488,10 @@ describe('extractPageLinks', () => {
expect(seen).toContain('struktura');
expect(seen).not.toContain('notes/struktura');
expect(candidates.map(c => c.targetSlug)).toEqual(['notes/struktura']);
- expect(candidates[0].linkType).toBe('wikilink_basename');
- expect(candidates[0].linkSource).toBe('wikilink-resolved');
+ // #2576: the literal path now yields the direct verb-typed candidate
+ // (parity with whitelisted dirs), not a wikilink_basename demotion.
+ expect(candidates[0].linkType).toBe('mentions');
+ expect(candidates[0].linkSource).toBe('markdown');
});
test('path-qualified wikilink keeps only matches ending with the written path', async () => {
@@ -516,7 +522,13 @@ describe('extractPageLinks', () => {
'concepts/x', 'See [[notes/struktura]].',
{}, 'concept', resolver, { globalBasename: true },
);
- expect(candidates.map(c => c.targetSlug)).toEqual(['vault/notes/struktura']);
+ // #2576: the literal path is ALSO emitted as a direct candidate (typed,
+ // linkSource 'markdown') — downstream existence checks drop it when no
+ // `notes/struktura` page exists, so only the suffix match persists.
+ expect(candidates.map(c => c.targetSlug)).toEqual(['notes/struktura', 'vault/notes/struktura']);
+ const suffixMatch = candidates.find(c => c.targetSlug === 'vault/notes/struktura')!;
+ expect(suffixMatch.linkType).toBe('wikilink_basename');
+ expect(suffixMatch.linkSource).toBe('wikilink-resolved');
});
test('path-qualified self-link is dropped like the bare form', async () => {